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.
  • Do you want the error at point of definition or at point of use? – Manuel Jan 19 '18 at 8:25
  • 1
    you can easily test whether any two specified commands have the same definition but you can not check whether any other command has the same definition of the one have just defined. Please clarify your question to make it clear what you want to test. – David Carlisle Jan 19 '18 at 8:39
  • @Manuel: I updated my question. – Sr. Schneider Jan 19 '18 at 9:10
  • @Sr.Schneider That's what I give in my answer. – Manuel Jan 19 '18 at 9:38
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
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.