检测通过 \csdef 定义的重复 csnames

检测通过 \csdef 定义的重复 csnames

我有一个重复使用的大型列表\csdef。在一个单独的 tex 文件中,我尝试检测任何重复项,但在尝试打印出初始定义和重复项试图设置的值时遇到问题。

MWE 中的两个问题行已被注释掉,MWE 的期望输出为

macro 1: Macro 1 Value
         Macro 3 Value

Number of Duplicates = 1

我得到的错误是

LaTeX 错误:缺少 \begin{document}。

请参阅 LaTeX 手册或 LaTeX Companion 了解解释。输入 H 可立即获得帮助。...

l.29 \csdef{宏 1}{宏 3 值}

相关问题:

代码:

\documentclass{article}

\usepackage{etoolbox}
\usepackage{xparse}
\usepackage{letltxmacro}

\newcounter{NumberOfDuplicates}

\LetLtxMacro{\OldCsdef}{\csdef}
\RenewDocumentCommand{\csdef}{%
    m%    #1 = control sequence name
    O{0}% #2 = number of parameters (UNUSED HERE)
    m%    #3 = value
}{%
    \ifcsdef{#1}{%
        \typeout{ERROR: '#1' defined multiple times.}%
%        #1: \csuse{#1}%       <-- Show Old Definition
%       \par\hphantom{#1: }#3% <-- Show new definition
        \stepcounter{NumberOfDuplicates}%
    }{%
        \OldCsdef{#1}{#3}%
    }%
}%

% ------------------------------ Want to check that there are no duplicate csnames here
\csdef{macro 1}{Macro 1 Value}
\csdef{macro 2}{Macro 2 Value}
\csdef{macro 1}{Macro 3 Value}
%
\begin{document}
\medskip\par
Number of Duplicates = \arabic{NumberOfDuplicates}.
\end{document}

答案1

当然,您会得到“缺失\begin{document}”错误:您正尝试在序言中排版某些内容。

\documentclass{article}

\usepackage{etoolbox}
\usepackage{xparse}
\usepackage{letltxmacro}

\newcounter{NumberOfDuplicates}

\LetLtxMacro{\OldCsdef}{\csdef}
\RenewDocumentCommand{\csdef}{%
  m%    #1 = control sequence name
  O{0}% #2 = number of parameters (UNUSED HERE)
  m%    #3 = value
}{%
  \ifcsdef{#1}{%
    \typeout{ERROR: '#1' defined multiple times.}%
    \xappto\duplicateslist{
      #1: \expandafter\meaning\csname #1\endcsname % <-- Old
      \noexpand\par\noexpand\leavevmode
      \noexpand\hphantom{#1: }\unexpanded{#3}% <-- New
      \noexpand\par
    }%
        \stepcounter{NumberOfDuplicates}%
    }{%
        \OldCsdef{#1}{#3}%
    }%
}%

\AtBeginDocument{{\ttfamily\duplicateslist}}

% ------------------------------ Want to check that there are no duplicate csnames here

\csdef{macro 1}{Macro 1 Value}
\csdef{macro 2}{Macro 2 Value}
\csdef{macro 1}{Macro 3 Value}
%
\begin{document}

\medskip\par
Number of Duplicates = \arabic{NumberOfDuplicates}.
\end{document}

在此处输入图片描述

相关内容