1

Is it possible to define a command \foo such that further \newcommand\foo (I do not mean \renewcommand) are ignored and do not return errors?

For example:

\newcommand\foo[1]{\textcolor{red}{#1}}
\newcommand\foo[1]{\textcolor{blue}{#1}} % to be ignored!

\foo{This should print in red.}

The reason why I am asking for this is that I have a document doc.tex of the form

\newcommand\foo[1]{\textcolor{blue}{#1}}
\foo{Some text}

that I want to include in another document using \input{doc.tex}, and I'd like Some text to print in red (of course, in reality my problem is not about text color...).

anderstood
  • 2,196
  • 19
  • 35

1 Answers1

3

Change both \newcommand macros usages to \providecommand. The \providecommand will define a new macro only if there is no macro of the same name already, otherwise it will silently ignore the 2nd definition (or rather the trial to define it again) and do nothing at all.

Of course, it is still important which \providecommand\foo comes first. Depending on the real use case, loading as early as possible should be safe -- unless some really 'weird' usage such as interfering with the cross-reference/counter system or ToC - related issues is applied.

\documentclass{article}

\usepackage{xcolor}

\providecommand\foo[1]{\textcolor{red}{#1}}
\providecommand\foo[1]{\textcolor{blue}{#1}} % Will be ignored!


\begin{document}

\foo{This text should be printed in red -- and it is red}


\end{document}

enter image description here