0

Last time I asked: How to check if command is used more than once?

This time I want LaTeX to throw an error message if two or more commands have the same definiton.

This is allowed

\documentclass{article}

\newcommand{\one}{Definition 1}
\newcommand{\two}{Definition 2}
\newcommand{\three}{Definition 3}

\begin{document}

\one

\two

\three

\end{document}

This is should throw an error message

\documentclass{article}

\newcommand{\one}{Definition 1}
\newcommand{\two}{Definition 1} % Definition already exists!
\newcommand{\three}{Definition 3}

\begin{document}

\one

\two

\three

\end{document}

EDIT

  • I'd like to have the error at point of definition.
  • It's an error if the definition already exists in another command.

1 Answers1

1

Use \newuniquecommand instead of \newcommand.

\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand \newuniquecommand { m O{0} o +m }
 {
  \bool_set_false:N \l_schneider_alreadydefined_bool
  \prop_map_inline:Nn \g_schneider_commands_prop
   {
    \str_if_eq:nnT { ##2 } { #4 }
     {
      \bool_set_true:N \l_schneider_alreadydefined_bool
      \prop_map_break:
     }
   }
  \bool_if:NTF \l_schneider_alreadydefined_bool
   { <ERROR! add what you want to output in case of error> }
   {
    \prop_gput:Nnn \g_schneider_commands_prop { #1 } { #4 }
    \IfValueTF {#3}
     { \newcommand #1 [#2] [#3] {#4} }
     { \newcommand #1 [#2]      {#4} }
   }
 }
\bool_new:N \l_schneider_alreadydefined_bool
\prop_new:N \g_schneider_commands_prop

\ExplSyntaxOff
Manuel
  • 27,118