コードは `iftoggle` 内では効果がないようです

コードは `iftoggle` 内では効果がないようです

これ回答 次のように、 の自動 pdfauthor メタデータ処理メカニズムにパッチを当てることが提案されましたhyperref。目標は、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(関連する3行のコメントを解除して試してみてください)、 でドキュメントの最後に到達すると失敗しますUndefined control sequence. <argument> \hrauthor。 を定義するコマンドが実行されなかったかのようにhrauthor。 しかし、 に関する部分\AtEndDocumentは実行されます。 によるとこれコメント、iftoggleレガシーif構造に置き換えると機能します。

このパッチを条件付きで動作させるにはどうすればいいでしょうかiftoggle好ましい条件付き切り替えのメカニズム?

答え1

これは、それ自体とは関係ありません\iftoggleが、カテゴリ コード (catcodes) と関係があります。 TeX がトークンを初めてスキャンすると、そのカテゴリ コードは「固定」されます。つまり、TeX はトークンが最初に読み込まれたときのコードを記憶します。 あなたの場合、 が#原因です。

\iftoggle{patchhref}\@firstoftwoまたはと同等のものに展開されます\@secondoftwo

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

これは次の 2 つのグループをスキャンし、2 番目のグループを削除します。最初のグループのすべての catcodes はプロセスで固定されます。には#通常カテゴリ コードがあり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}

関連情報