为什么$]$会破坏 \marginpar 的重新定义?

为什么$]$会破坏 \marginpar 的重新定义?

帮我理解为什么$]$a 中的a\marginpar被重新定义为这样

\documentclass{article}

\let\oldmarginpar\marginpar
\renewcommand{\marginpar}[2][]{% always add the optional parameter, make it empty by default
   \if\relax\detokenize{#1}\relax% optional parameter empty, in most usual document calls
      \oldmarginpar[\itshape #2]{\itshape #2}%
   \else%two parameters, if some other package needs to redefine the original marginpar
      \oldmarginpar[#1]{#2}%
   \fi%
}

\begin{document}
\section{A section}
A few words. \marginpar{And an ugly dangling $]$.}
\end{document}

破坏了一些东西,但当上面的重新定义包括

\oldmarginpar[{\itshape #2}]{{\itshape #2}}

反而。

有没有更好的方法来避免这种情况?

答案1

您需要对可选参数进行分组,以免被]认为是可选参数的结束。

\documentclass[twoside]{article}

\let\oldmarginpar\marginpar
\renewcommand{\marginpar}[2][]{% always add the optional parameter, make it empty by default
   \if\relax\detokenize{#1}\relax% optional parameter empty, in most usual document calls
      \oldmarginpar[{\itshape #2}]{\itshape #2}%
   \else%two parameters, if some other package needs to redefine the original marginpar
      \oldmarginpar[{#1}]{#2}%
   \fi%
}

\begin{document}
\section{A section}
A few words. \marginpar{And an ugly dangling $]$.}


A few words. \marginpar[not an ugly duckling]{And an ugly dangling $]$.}

\clearpage
A few words. \marginpar{And an ugly dangling $]$.}


A few words. \marginpar[not an ugly duckling]{And an ugly dangling $]$.}
\end{document}

在此处输入图片描述

在此处输入图片描述

相关内容