將 \detokenize 和底線與 \listoffigures 結合使用

將 \detokenize 和底線與 \listoffigures 結合使用

X我一直在使用類似的宏

\newcommand{\X}[1]{{\ttfamily{\detokenize{#1}}}}

格式化可能包含下劃線的某些單詞,而不必使用 轉義\_。這一直有效,直到我在\caption.這會導致 pdflatex 和 lualatex ( ) 都出現錯誤! Missing $ inserted.。考慮這個 MWE:

\documentclass{article}

\newcommand{\X}[1]{{\ttfamily{\detokenize{#1}}}}

\begin{document}    
\listoffigures
\begin{figure}
  \centering
  \caption{One \X{a_b} Two}
\end{figure}
\end{document}

我是否必須使用不同/更複雜的解決方案,X或者我應該通常轉義下劃線?我對最佳實踐更感興趣,而不是非常聰明的駭客。

答案1

您需要該命令是健壯的,否則.lof文件中的註釋將變成

\contentsline {figure}{\numberline {1}{\ignorespaces One \texttt {a_b} Two}}{1}%

(我將語法從 更改為{\ttfamily...}\texttt{...}這更好)。如您所見,\detokenize已應用並消失。

另一方面,如果你這樣做

\newcommand{\X}{}% for safety
\DeclareRobustCommand{\X}[1]{\texttt{\detokenize{#1}}}

註釋將是

\contentsline {figure}{\numberline {1}{\ignorespaces One \X {a_b} Two}}{1}%

且問題不會顯示出來。

或者,\protect\X在激烈的爭論中使用。

相關內容