

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

• 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
• What about \providecommand\foo? – user31729 Oct 31 '17 at 19:52
• @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
• @StevenB.Segletes: I thought of \newcommand\foo and then \providecommand\foo (as second usage) – user31729 Oct 31 '17 at 20:00

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}