将文本内容写为标签并使用 \nameref* 引用它们

将文本内容写为标签并使用 \nameref* 引用它们

今天早上,当我试图改进我对某个问题给出的(可能的)解决方案答案时,我遇到了困难。

我尝试将自动生成的标签(使用带有前缀等的唯一命名方案)与文本(甚至数学内容等)一起写入文件,然后通过from.aux使用标签名称引用它。\nameref*nameref

下面的 MWE 简化为基本问题,我创建了一个\WriteMyLabel完成该工作的小命令。

但是我不能写类似的东西

\WriteMyLabel{\textbf{some bold text}}

LaTeX 提供了非常有趣的错误信息

\text@command #1->\def \reserved@a { #1}\ifx \reserved@a \@empty \let \check@...

我该如何解决这个问题?有可能吗?

\documentclass[12pt]{article}
\usepackage{blindtext}%
\usepackage{xcolor}
\usepackage{etoolbox}
\usepackage{hyperref}

\newcounter{TotalLabelCounter}

%%%% A command to make the references clearer, just for debugging, not in 
%%%% end production code
\newrobustcmd{\refcommand}[1]{\fbox{\textbf{\textcolor{blue}{\nameref*{#1}}}}}

\makeatletter
\newrobustcmd{\WriteMyLabel}[1]{%
\refstepcounter{TotalLabelCounter}%
\immediate\write\@auxout{%
\string\newlabel{MyLabel::\number\value{TotalLabelCounter}}{{\thesection}{\thepage}{#1}{}}
}% End of writing to AUX file
}%
\makeatother

\begin{document}

\section{First}

\WriteMyLabel{The Three Witches}

\WriteMyLabel{$E = mc^2$}

\blindtext[1]

\newpage
\section{Another section}
\blindtext[1]

\WriteMyLabel{\textbf{some bold text}}

\refcommand{MyLabel::1} from the play 'Macbeth' have a very important part, however, there are no nice formulas such as \refcommand{MyLabel::2} and 
it would be better, if \refcommand{MyLabel::3} would work.

\end{document}

在此处输入图片描述

答案1

哦,这太简单了,想了想:代码必须是\unexpanded;-)

\documentclass[12pt]{scrartcl}
\usepackage{blindtext}%
\usepackage{xcolor}
\usepackage{etoolbox}
\usepackage{hyperref}

\newcounter{TotalLabelCounter}

%%%% A command to make the references clearer, just for debugging, not in 
%%%% end production code
\newrobustcmd{\refcommand}[1]{\fbox{\textbf{\textcolor{blue}{\nameref*{#1}}}}}

\makeatletter
\newrobustcmd{\WriteMyLabel}[1]{%
\refstepcounter{TotalLabelCounter}%
\immediate\write\@auxout{%
\string\newlabel{MyLabel::\number\value{TotalLabelCounter}}{{\thesection}{\thepage}{\unexpanded{#1}}{}}
}% End of writing to AUX file
}%
\makeatother

\begin{document}

\section{First}

\WriteMyLabel{The Three Witches}

\WriteMyLabel{$E = mc^2$}

\blindtext[1]

\newpage
\section{Another section}
\blindtext[1]

\WriteMyLabel{\textbf{bold text}}

\refcommand{MyLabel::1} from the play 'Macbeth' have a very important part, however, there are no nice formulas such as \refcommand{MyLabel::2} and 
it would be better, if \refcommand{MyLabel::3} would work.

\end{document}

在此处输入图片描述

相关内容