如何在節標題中使用 \newrobustcmd 和 \NewDocumentCommand 以及 hyperref

如何在節標題中使用 \newrobustcmd 和 \NewDocumentCommand 以及 hyperref

如何在啟用的部分標題中使用\newrobustcmd和?下面的 MWE 顯示,雖然渲染的 PDF 看起來正確,但書籤不顯示巨集內容。NewDocumentCommandhyperref

\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}

產生的pdf文件

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\testCMWE 中的內容最終會像書籤中一樣。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{wor‌​ld}%
    }
    

相關內容