我想测试在加载 nameref 时附加到标签的“name”键是否为空。可以使用 refcount 以可扩展的方式检索该值,\getrefbykeydefault
并按如下方式进行测试。
\documentclass{article}
\usepackage{nameref}
\begin{document}
\section{bla} \label{mylab1}
\section{} \label{mylab2}
\ExplSyntaxOn
\tl_if_empty:eTF { \getrefbykeydefault{mylab1}{name}{} }
{ EMPTY }{ NOT~EMPTY }
\par
\tl_if_empty:eTF { \getrefbykeydefault{mylab2}{name}{} }
{ EMPTY }{ NOT~EMPTY }
\ExplSyntaxOff
\end{document}
但是,一旦“名称”包含不可扩展的标记,测试就会出错。
\documentclass{article}
\usepackage{nameref}
\begin{document}
\section{bla\textit{h}} \label{mylab}
\ExplSyntaxOn
\tl_if_empty:eTF { \getrefbykeydefault{mylab}{name}{} }
{ EMPTY }{ NOT~EMPTY }
\ExplSyntaxOff
\end{document}
产生错误
! Argument of \@sect has an extra }.
<inserted text>
\par
l.10 ...eTF { \getrefbykeydefault{mylab}{name}{} }
I've run across a `}' that doesn't seem to match anything.
For example, `\def\a#1{...}' and `\a}' would produce
this error. If you simply proceed now, the `\par' that
I've just inserted will cause me to report a runaway
argument that might be the root of the problem. But if
your `}' was spurious, just type `2' and it will go away.
Runaway argument?
{\normalfont \Large \bfseries }{\unexpanded {h}}\ifx \reserved@a \@empty \ETC.
! Paragraph ended before \@sect was complete.
<to be read again>
\par
l.10 ...eTF { \getrefbykeydefault{mylab}{name}{} }
I suspect you've forgotten a `}', causing me to apply this
control sequence to too much text. How can we recover?
My plan is to forget the whole thing and hope for the best.
我知道\textit
在章节标题中放置命令是不好的做法。假设我无法控制输入,我该如何检查标签上附加的“名称”是否为空?
如果我使用 ltproperties,我可以测试“title”键的内容(请注意,这与 refcount 的“name”键相当,而不是其“title”键)。
\documentclass{article}
\usepackage{nameref}
\begin{document}
\section{bla\textit{h}}
\label{reallabel1}
\RecordProperties{mylab1}{title}
\section{}
\label{reallabel2}
\RecordProperties{mylab2}{title}
\ExplSyntaxOn
\tl_if_empty:eTF { \RefProperty{mylab1}{title} }
{ EMPTY }{ NOT~EMPTY }
\par
\tl_if_empty:eTF { \RefProperty{mylab2}{title} }
{ EMPTY }{ NOT~EMPTY }
\ExplSyntaxOff
%\RefProperty{mylab1}{title} % this errors
\nameref{reallabel1} % but this works
\end{document}
与示例不同\getrefbykeydefault
,当节标题包含不可展开的标记时,这不会出错。但是这有两个问题。首先,如果取消注释\RefProperty{mylab1}{title}
,则会出错,因此它不能替代\nameref
。其次,我希望这些数据可以仅从标签数据中恢复,而不需要\RecordProperties
每个实例都这样做。
答案1
任何用户输入都不应放入\edef
或使用e
或x
类型进行扩展。为了安全扩展,LaTeX 提供了\protected@edef
处理强大命令的功能。
\documentclass{article}
\usepackage{nameref}
\begin{document}
\section{bla\textit{h}} \label{mylab}
\ExplSyntaxOn\makeatletter
\protected@edef\l_tmpa_tl{ \getrefbykeydefault{mylab}{name}{}}
\tl_if_empty:NTF \l_tmpa_tl
{ EMPTY }{ NOT~EMPTY }
\ExplSyntaxOff
\end{document}