1

I want to define a new macro that gets an optional argument X and a citation key Y. If only Y is present it prints

\cite{Y}

If, however, also X is present it prints

X, \cite{Y}

This should in principle be done with the simple syntax of \newcommand which allows one optional argument with a default value which could be empty. But how do I get rid of the straying comma? Or maybe there is a way to do this with the citation command?

I've seen more general answers for the question of how to define a new command which behaves differently with and without an optional argument, but these answers seem to be quite more sophisticated than what I need here.

4
  • I should emphasize that I'm looking for a simpler solution than the general "if-branch" approach.
    – Ariel
    Jul 13, 2015 at 11:05
  • 2
    I don't understand why you want a version without if statement but I added a possible solution to my answer
    – cgnieder
    Jul 13, 2015 at 17:10
  • It is just that my macro is already quite complicated (I just gave a minimal example to explain my need), and I don't want to clutter it even further with an extra \if construction. Your second solution is exactly what I was looking for.
    – Ariel
    Jul 14, 2015 at 7:47
  • Note that if you are really looking into this in the context of biblatex's citation commands, the pre-note does something quite similar: \cite[Cf.][]{sigfridsson}.
    – moewe
    Apr 5, 2019 at 7:11

2 Answers 2

5

You can test if the optional argument is empty. How to check if a macro value is empty or will not create text with plain TeX conditionals? gives several possible ways how to do that. I picked one here:

\documentclass{article}

% traditional solution:
\newcommand*\mycommand[2][]{%
  \if\relax\detokenize{#1}\relax
  \else
    #1,\nobreakspace
  \fi
  \cite{#2}%
}

% without if statement:
\newcommand*\gobbletwo[2]{}
\newcommand*\myothercommand[2][\gobbletwo]{%
  #1,\nobreakspace\cite{#2}%
}

\begin{document}

+\mycommand{foo}+

+\mycommand[bla]{foo}+

+\myothercommand{foo}+

+\myothercommand[bla]{foo}+

\end{document}
4

It's really easy with xparse:

\usepackage{xparse}

\NewDocumentCommand{\ocite}{om}{%
  \IfNoValueTF{#1}
    {% no optional argument in the input
     \cite{#2}%
    }
    {% optional argument has been given
     #1,~\cite{#2}% note the tie
    }%
}

The list of arguments, instead of being a number, says

o for an optional argument without a default value
m for a mandatory argument

The call \ocite{abc} will follow the “true” branch of \IfNoValueTF{#1}; conversely \ocite[X]{abc} will follow the “false” branch.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .