程式碼在“iftoggle”內部時似乎沒有效果

程式碼在“iftoggle”內部時似乎沒有效果

答 我被建議修補hyperrefpdfauthor 的自動元資料處理機制,如下所示。目標是讓 PDF 元資料authblk與多個作者一起工作。

\documentclass{article}
\usepackage[pdfusetitle]{hyperref}
\usepackage{authblk}
\usepackage{xpatch}

\newtoggle{patchhref}
\toggletrue{patchhref}
%\iftoggle{patchhref}{
    \xpretocmd{\author}{\addhrauthor{#2}}{}{}
    \newif\iffirstauthor
    \firstauthortrue
    \newcommand{\addhrauthor}[1]{%
        \iffirstauthor%
            \newcommand{\hrauthor}{#1}\firstauthorfalse%
        \else%
            \xapptocmd{\hrauthor}{, #1}{}{}%
        \fi
    }
    \AtEndDocument{
        \hypersetup{pdfauthor={\hrauthor}}
    }
%}{
%}

\begin{document}
\title{The title}
\author{Firstname 1 Lastname 1}
\author{Second author}
\affil{First affiliation\\
   \href{mailto:firstname.fastname@affiliation}{firstname.fastname@affiliation}
}
\author{Name3}
\affil{Second affiliation}

\maketitle
Content.

\end{document}

我已經添加了這個iftoggle東西,它不在原始答案中。不使用時iftoggle,它可以工作。但是,當使用iftoggle(取消註解三個相關行來嘗試)時,當到達文件末尾時會失敗Undefined control sequence. <argument> \hrauthor。就好像定義的命令hrauthor沒有被執行一樣。但關於的部分\AtEndDocument確實被執行了。根據評論,替換iftoggle為遺留if構造作品。

我怎樣才能使這個補丁有條件地工作,iftoggle使用首選條件切換機制?

答案1

\iftoggle這與本身無關,而是與類別代碼(catcode)有關。當 TeX 第一次掃描一個標記時,它的類別代碼被“凍結”,即 TeX 會記住它第一次被讀取時的內容。就你而言,#罪魁禍首是。

\iftoggle{patchhref}展開為等價於\@firstoftwoor 的東西\@secondoftwo

\newcommand\@firstoftwo[2]{#1}
\newcommand\@secondoftwo[2]{#2}

這將掃描接下來的兩組並刪除第二組。第一組中的所有目錄代碼在此過程中都被凍結。#通常有類別代碼6,並且在使用 修補命令時需要小心#\xpretocmd嘗試解決這個問題,但如果#已經掃描過,則失敗。

您可以透過定義來解決這個問題

{\catcode`#=11\relax
    \gdef\fixauthor{\xpretocmd{\author}{\addhrauthor{#2}}{}{}}%
}

在您之前\iftoggle並將該\xpatchcmd行替換為\fixauthor.

答案2

您不需要\addrauthor在切換部分中定義:無論如何您都必須編寫程式碼。

在指令參數中進行修補的問題可以透過多種方式解決,最簡單的一種是使用標準條件。

\addhrauthor在這裡我建議使用一個更簡單的巨集版本expl3

\documentclass{article}

\usepackage{xpatch,xparse}
\usepackage[pdfusetitle]{hyperref}
\usepackage{authblk}

\ExplSyntaxOn
\seq_new:N \g_oc_hrauthor_seq
\NewDocumentCommand{\addhrauthor}{m}
 {
  \seq_gput_right:Nn \g_oc_hrauthor_seq { #1 }
 }
\NewExpandableDocumentCommand{\hrauthor}{}
 {
  \seq_use:Nn \g_oc_hrauthor_seq {,~}
 }
\ExplSyntaxOff

\newif\ifpatchhref
%\patchhreftrue

\ifpatchhref
  \xpretocmd{\author}{\addhrauthor{#2}}{}{}
  \AtEndDocument{\hypersetup{pdfauthor={\hrauthor}}}
\fi


\begin{document}
\title{The title}
\author{Firstname 1 Lastname 1}
\author{Second author}
\affil{First affiliation\\
   \href{mailto:firstname.fastname@affiliation}{firstname.fastname@affiliation}
}
\author{Name3}
\affil{Second affiliation}

\maketitle
Content.

\end{document}

相關內容