
我需要編寫一個包含“&”的標籤。這是一個奇怪的需求,但它是在巨集中使用的\keyword
,它還會向 aux 檔案添加一個字串,我稍後可以解析該字串(例如,使用外部程式)。英文名稱顯然可以包含 &,如 S&P~500。
\documentclass{article}
\NewDocumentCommand{\keyword}{ m }{%
\label{KW:\thesection:\thepage:#1}%
\textbf{#1}
}
\begin{document}
\keyword{abc}
\keyword{def}
\label{i\&j}
\keyword{s\&p500}
\end{document}
錯誤當然是
! Missing \endcsname inserted.
<to be read again>
\&
l.4 \newlabel{i\&j}{{}{1}}
我如何要求乳膠只考慮 aux 檔案字串中的 & 一個可行的字元?
感謝建議。
答案1
您\label
只是在濫用向文件寫入內容.aux
:無法\label
在 a 中使用此類創建的內容\ref
,因為您不知道它最終將在哪裡排版。
我不會\newlabel
在.aux
文件中使用,而是使用不同的標記。
\documentclass{article}
\ExplSyntaxOn
\NewDocumentCommand{\fakelabel}{m}{} % for the .aux file
\NewDocumentCommand{\keyword}{ m }
{
\group_begin:
\cs_set:Npx \& { \token_to_str:N \& }
\iow_shipout:cx { @auxout }
{
\token_to_str:N \fakelabel { KW : \thesection : \thepage : #1 }
}
\group_end:
\textbf{#1}
}
\ExplSyntaxOff
\begin{document}
\keyword{abc}
\keyword{def}
\keyword{s\&p500}
\end{document}
關於\label{i\&j}
,只需避免它或使用\label{i&j}
有效的即可。
aux 檔案的內容將是
\relax
\fakelabel{KW:0:1:abc}
\fakelabel{KW:0:1:def}
\fakelabel{KW:0:1:s\&p500}
\gdef \@abspage@last{1}
您的外部程式將能夠尋找\fakelabel
並使用提供的資料。