套件 hyperref 與節標題內的計數器衝突

套件 hyperref 與節標題內的計數器衝突

以下最小文件

\documentclass{article}

\usepackage{hyperref}

\newcounter{projno}
\newcommand{\proj}{%
\stepcounter{projno}%
\theprojno}


\begin{document}

\section{Project \protect\proj }

\end{document}

產生錯誤

! Missing \endcsname inserted.
<to be read again> 
                   \csname\endcsname
l.14 \section{Project \protect\proj }

當我註解掉時,錯誤消失了\usepackage{hyper ref}。有人找到擺脫這種困境的方法嗎?

答案1

該巨集\proj會導致書籤出現問題。大多數 TeX 的胃部機器在這裡不起作用。可擴展命令在書籤中工作正常,但分配(計數器增量,...)則不然。包hyperref提供\texorpdfstring\pdfstringdefDisableCommands處理應在書籤內重新定義或過濾掉的命令:

\section{Project\texorpdfstring{\protect\proj}{\theprojno}}

或可通過的書籤代碼\proj得知:hyperref

...
\usepackage{hyperref}
\pdfstringdefDisableCommands{\let\proj\theprojno}
...
\begin{document}
...
\section{Project\protect\proj}

提示:

  • 如果使用 定義\proj,則在使用 時不需要\DeclareRobustCommand明確:\protectproj

    \newcommand*{\proj}{}% check, whether \proj is undefined
    \DeclareRobustCommand*{\proj}{\stepcounter{projno}}
    
  • 來自egreg的重要提示他的評論\stepcounter應該更好用 \section。否則,計數器也會隨著目錄和標題行中的條目而增加(取決於頁面樣式)。

相關內容