![如何在節標題中使用 \newrobustcmd 和 \NewDocumentCommand 以及 hyperref](https://rvso.com/image/353010/%E5%A6%82%E4%BD%95%E5%9C%A8%E7%AF%80%E6%A8%99%E9%A1%8C%E4%B8%AD%E4%BD%BF%E7%94%A8%20%5Cnewrobustcmd%20%E5%92%8C%20%5CNewDocumentCommand%20%E4%BB%A5%E5%8F%8A%20hyperref.png)
如何在啟用的部分標題中使用\newrobustcmd
和?下面的 MWE 顯示,雖然渲染的 PDF 看起來正確,但書籤不顯示巨集內容。NewDocumentCommand
hyperref
\documentclass[11pt]{article}
\usepackage{hyperref}
\usepackage{xparse}
\usepackage{etoolbox}
\newcommand{\testA}[0]{world}
\newrobustcmd{\testB}[0]{world}
\NewDocumentCommand{\testC}{}{world}
\begin{document}
\section{Hello \testA}
\section{Hello \testB}
\section{Hello \testC}
\end{document}
該MWE.out
文件如下所示。
\BOOKMARK [1][-]{section.1}{Hello world}{}% 1
\BOOKMARK [1][-]{section.2}{Hello }{}% 2
\BOOKMARK [1][-]{section.3}{Hello }{}% 3
答案1
使用\newcommand
定義可擴充巨集 ( \def
),同時\newrobustcmd
定義\NewDocumentCommand
受引擎保護的巨集 ( \protected\def
)。在建立書籤字串時,書籤的內容會擴展,但受保護的巨集無法擴展,因此標記\testB
和\testC
MWE 中的內容最終會像書籤中一樣。hyperref
不知道如何處理它們,因此丟棄它們。
Package hyperref Warning: Token not allowed in a PDF string (PDFDocEncoding):
(hyperref) removing `\testB' on input line 13.
Package hyperref Warning: Token not allowed in a PDF string (PDFDocEncoding):
(hyperref) removing `\testC' on input line 14.
因此,如果您確實需要受保護的宏,您有兩個選項:
\section{Hello \texorpdfstring{\testB}{world}}
在文件中使用或加載後在序言中添加更簡單的可擴展定義
hyperref
,這些定義將在書籤中使用\pdfstringdefDisableCommands{% \def\testB{world}% \def\testC{world}% }