62

I'm trying to compile a LaTeX code with an older version of some package. Thus, I'm having a few issues due to undefined commands.

How can I add conditional code so that I can define some work-around commands of this older package version?

% I want something like this:
if command \foobar is not defined
  \newcommand{\foobar}{FooBar}

% I don't need an "else" clause here, but it would be good
% to know how to add one, in case I need it in future

end if
lockstep
  • 250,273

4 Answers4

62

The LaTeX kernel command \providecommand{\foobar}{FooBar} does exactly what you want.

lockstep
  • 250,273
53

I think that \providecommand is what you want for this, as lockstep says, but it's worth mentioning the \@ifundefined LaTeX command which tests for whether or not a command is defined and executes some code if it is or isn't. It's more flexible than \providecommand in that it doesn't just deal with defining a particular command. Here's a simple example that I use when anglicising a few commands:

\makeatletter
\@ifundefined{centre}{%
\newenvironment{centre}{\center}{\endcenter}%
}{}
\makeatother

So if the command \centre is not defined then it defines the environment centre.

Andrew Stacey
  • 153,724
  • 43
  • 389
  • 751
  • 1
    This should be promoted. This is a nice way to define environments as well as commands conditionally which I was about to ask about separately. – Huck Bennett Oct 21 '15 at 21:45
25

The ifthen package provides some easy-to-use macros for this. For example:

\ifthenelse{\isundefined{\foobar}}{
  %% Do this if it is undefined
}{
  %% Do this if it is defined
}

You can also do it in plain TeX (which doesn't require any external packages):

\ifx\foobar\undefined
  %% Do this if it is undefined
\else
  %% Do this if it is defined
\fi
vanden
  • 30,891
  • 23
  • 67
  • 87
ESultanik
  • 4,410
17

The e-TeX primitives that LaTeX wraps (apparently) are \ifdefined and \ifcsname. Use like this:

\ifdefined \foobar \else
  \newcommand{\foobar}{FooBar}
\fi

Use \ifcsname if you need to construct the command name with macros:

\ifcsname foobar\endcsname \else
  \newcommand{\foobar}{FooBar}
\fi

The \ifdefined and \ifcsname control sequences do not exist in the original tex program, but they do in all latex/xetex/pdftex variants on my Ubuntu system.

Arun Debray
  • 7,126
  • 2
  • 30
  • 54
JanKanis
  • 2,307
  • 3
    These commands are no TeX primitives, but defined in e-tex. In newer tex distributions, latex usually links to pdftex, which includes the e-tex extensions already. If you run your code snippets through plain tex you'll see, that they won't work, running them through etex works. Good answer nonetheless. – Elmar Zander Nov 30 '11 at 13:18
  • There seems to be conflicting statements here. The first sentence says \ifdefined and \ifcsname are TeX primitives, and the last sentence says otherwise. – SimplyKnownAsG Mar 19 '14 at 18:21