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...).

  • 1
    If the goal is to avoid redefinitions in the preamble, you can likely define it initially (in the preamble) with \AtBeginDocument{\let\foo\relax\newcommand\foo[1]{\textcolor{red}{#1}}} – Steven B. Segletes Oct 31 '17 at 19:50
  • 2
    What about \providecommand\foo? – user31729 Oct 31 '17 at 19:52
  • 1
    @ChristianHupfer Unless I misunderstand your point, that would still throw an error with a subsequent blue \foo. – Steven B. Segletes Oct 31 '17 at 19:54
  • 1
    @StevenB.Segletes: I thought of \newcommand\foo and then \providecommand\foo (as second usage) – user31729 Oct 31 '17 at 20:00
  • 1
    @ChristianHupfer OK, changing the second \newcommand to providecommand was transparent, so it works fine for me, thank you! Feel free to write an answer, I will also wait a bit to see if there are other more general solutions that avoid touching to the second \newcommand. – anderstood Oct 31 '17 at 20:07
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

|improve this answer|||||

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