我想在某些章节名称中使用计数器,这对于目录和章节名称本身来说都很有效,但对章节名称的引用似乎使用引用时的计数器,而不是章节时的计数器。
下面是一个 MWE 来展示该问题:
\documentclass{book}
\usepackage{hyperref}
\newcounter{NoteIdx}
\newcommand{\notechapter}[1]{%
\stepcounter{NoteIdx}%
\chapter{Note \arabic{NoteIdx}: #1}%
}
\begin{document}
\tableofcontents
\chapter{Things}
Refer to the \nameref{bees} chapter.
Refer to the \nameref{hat} chapter.
\notechapter{Don't eat bees}
\label{bees}
Some text here
\chapter{Stuff}
Refer to the \nameref{bees} chapter.
Refer to the \nameref{hat} chapter.
\notechapter{Always wear a hat}
\label{hat}
Some text here
\end{document}
第 1 章的内容如下:
请参阅注意事项 0:不要吃蜜蜂章节。请参阅注意事项 0:务必戴帽子章节。
第 3 章正文如下:
请参阅注意事项 1:不要吃蜜蜂章节。请参阅注意事项 1:务必戴帽子章节。
有没有办法定义章节名称,以便将计数器生成的数字转换为文本,而不是\nameref
在计数器为错误值时发送要处理的命令?
答案1
我会尝试nameref
的驾驶室。具体来说,nameref
用途/需要\@currentlabelname
识别名称,因此请在您的内部定义它,以便\notechapter
按照您想要的方式进行查看:
\documentclass{book}
\usepackage{hyperref}
\newcounter{NoteIdx}
\makeatletter
\newcommand{\notechapter}[1]{%
\stepcounter{NoteIdx}%
\chapter{Note \theNoteIdx: #1}%
\protected@edef\@currentlabelname{Note \theNoteIdx: #1}% To make nameref happy
}
\makeatother
\begin{document}
\tableofcontents
\chapter{Things}
Refer to the \nameref{bees} chapter.
Refer to the \nameref{hat} chapter.
\notechapter{Don't eat bees}\label{bees}
Some text here
\chapter{Stuff}
Refer to the \nameref{bees} chapter.
Refer to the \nameref{hat} chapter.
\notechapter{Always wear a hat}\label{hat}
Some text here
\end{document}
答案2
格式错误,但你可以这样做:
\documentclass{book}
\usepackage{hyperref}
\newcounter{NoteIdx}
\newcommand{\notechapter}[2]{%
\refstepcounter{NoteIdx}\label{note:#1}%
\chapter{Note \ref*{note:#1}: #2}\label{#1}%
}
\begin{document}
\tableofcontents
\chapter{Things}
Refer to the \nameref{bees} chapter.
Refer to the \nameref{hat} chapter.
\notechapter{bees}{Don't eat bees}
Some text here
\chapter{Stuff}
Refer to the \nameref{bees} chapter.
Refer to the \nameref{hat} chapter.
\notechapter{hat}{Always wear a hat}
Some text here
\end{document}
编辑感谢 Werner,格式已得到纠正。
答案3
您需要传递\theNoteIdx
扩展,而不是篡改内部内容。
\documentclass{book}
\usepackage{xparse}
\usepackage{hyperref}
\newcounter{NoteIdx}
\ExplSyntaxOn
\NewDocumentCommand{\notechapter}{m}
{
\stepcounter{NoteIdx}%
\jhabbott_notechapter:fn { \theNoteIdx } { #1 }
}
\cs_new_protected:Nn \jhabbott_notechapter:nn
{
\chapter{Note~#1:~#2}
}
\cs_generate_variant:Nn \jhabbott_notechapter:nn { f }
\ExplSyntaxOff
\begin{document}
\tableofcontents
\chapter{Things}
Refer to the \nameref{bees} chapter.
Refer to the \nameref{hat} chapter.
\notechapter{Don't eat bees}\label{bees}
Some text here
\chapter{Stuff}
Refer to the \nameref{bees} chapter.
Refer to the \nameref{hat} chapter.
\notechapter{Always wear a hat}\label{hat}
Some text here
\end{document}
还有其他方法,不需要expl3
,但这是简洁的代码:f
-variant 提供了正确的完全扩展位。