\pdfstringdefDisableCommands 包含星號和不帶星號的指令

\pdfstringdefDisableCommands 包含星號和不帶星號的指令

以下MCE:

\documentclass{article}
\usepackage{hyperref}
\ExplSyntaxOn
\NewDocumentCommand { \foo } { s m } {
  \IfBooleanTF {#1}{
    Foo~ #2
  }{
    #2
  }
}
\pdfstringdefDisableCommands{
  \def\foo*#1{Foo~ #1}
  % \def\foo#1{#1}
}
\ExplSyntaxOff
\begin{document}
\section{\foo*{bar}}
% \section{\foo{bar}}
\end{document}

編譯就像一個魅力,除非\section{\foo{bar}}未註釋,錯誤訊息在這種情況下:

! Use of \foo doesn't match its definition.
<argument> ...rline {\csname thesection\endcsname }\fi \foo {
                                                  bar}

有沒有辦法\pdfstringdefDisableCommands同時使用有星號和沒有星號的指令?

答案1

您必須使用與原始命令相同的簽名來重新定義命令。由於s m是可擴展命令的有效簽名,因此您可以使用以下命令重新定義\RenewExpandableDocumentCommand

\documentclass{article}
\usepackage{hyperref}
\ExplSyntaxOn
\NewDocumentCommand { \foo } { s m } {
  \IfBooleanTF {#1}{
    Foo~ #2
  }{
    #2
  }
}
\pdfstringdefDisableCommands{
  \RenewExpandableDocumentCommand \foo { s m }
    { Foo~ #2 }
}
\ExplSyntaxOff
\begin{document}
\section{\foo*{bar}}
\section{\foo{bar}}
\end{document}

請注意,在您的範例中,該命令\foo僅包含可擴展宏,因此它可以在僅擴展上下文中工作,因此如果您\NewExpandableDocumentCommand直接使用定義它,則無需重新定義 for hyperref

\documentclass{article}
\usepackage{hyperref}
\ExplSyntaxOn
\NewExpandableDocumentCommand { \foo } { s m } {
  \IfBooleanTF {#1}{
    Foo~ #2
  }{
    #2
  }
}
\ExplSyntaxOff
\begin{document}
\section{\foo*{bar}}
\section{\foo{bar}}
\end{document}

相關內容