我有一个自定义宏:
\NewDocumentCommand\includefigure{mo}{
...
\caption{#2}
\label{fig:#2}
}
可选参数用于标题和标签。问题是,当我格式化此参数的某些部分时,会\includefigure{pic}[Hi \textit{there}!]
出现错误,例如“缺少 \endcsname 插入”。因为\label
不允许参数中包含命令。
是否存在类似的元命令\plaintext
,我可以在我的命令中使用\label{\plaintext{fig:#2}}
,然后\includefigure{pic}[Hi \textit{there}!]
会导致\label{fig:Hi there!}
?
或者也许有标签的替代品。
答案1
\label
通过转换成十六进制代码,可以将标题文本转换为系统安全的字符串,例如:
\documentclass{article}
\usepackage{pdfescape}
\makeatletter
\newcommand*{\make@hex@label}[1]{%
\def\hex@label{#1}%
\@onelevel@sanitize\hex@label
\EdefEscapeHex\hex@label{\hex@label}%
}
\newcommand*{\hexlabel}[1]{%
\@bsphack
\make@hex@label{#1}%
\label{\hex@label}%
\@esphack
}
\newcommand*{\hexref}[1]{%
\make@hex@label{#1}%
\ref{\hex@label}%
}
\newcommand*{\hexpageref}[1]{%
\make@hex@label{#1}%
\pageref{\hex@label}%
}
\makeatother
\newcommand*{\figurecaption}[1]{%
\caption{#1}%
\hexlabel{#1}%
}
\begin{document}
\begin{figure}
\figurecaption{Hi \textit{there}!}
\end{figure}
See figure \hexref{Hi \textit{there}!}.
\end{document}
坏处:警告显示十六进制字符串,例如:
LaTeX Warning: Reference `4869205C746578746974207B74686572657D21' on page 1 undefined on input line 35.