# Learning to use xparse

I'm learning to use xparse to build commands with optional arguments. But I'm having problems:

I want to make a command called \topcat with output:

\mathcal{O} if no argument is specified
\mathcal{O}^{#1} if we specify \topcat[op]


I tried to use something like:

\NewDocumentCommand{\topcatm}{o}{#1}{$\mathcal{O}$^{\IfValueTF{#1}}}


It'd be great if someone could give me some tips for xparse I tried to read about xparse in CTAN but I find it quite dense.

-

xparse can be a little bit confusing on the first glance, since it has a different syntax compared to \newcommand.

The syntax is

\NewDocumentCommand{\macroname}{argument specifiers}{%
expansion code
}


The argument specifiers are quite useful. If an optional argument is requested and there is no default value given, then o is most likely the right choice, otherwise use O{default} (replace default with the default value ;-))

Now, if o is used, the command \IfValueTF or \IfValueT or \IfValueF decides, whether the optional argument is given at all. (Which one is to be applied depends on the specific needs. If unsure, use \IfValueTF. )

(If none of the mentioned \IfValueTF macros is used, the replacement 'text' of the relevant argument is -NoValue- if the optional argument was specified to be of o type and was omitted in the macro call)

The usage is

\IfValueTF{#1}{true code}{false code}


Althought the trial code by the O.P. might work concerning the ^{\IfValueTF{#1}...} I don't recommend this syntax, just for clarity reasons.

Here's a working version, however, I removed the $...$ characters.

\documentclass{article}
\usepackage{mathtools}

\usepackage{xparse}

\NewDocumentCommand{\topcatm}{o}{%
\IfValueTF{#1}{%
\mathcal{O}^{#1}%
}{%
\mathcal{O}%
}%
}
\begin{document}

$\topcatm$

$\topcatm[foo]$
\end{document}


xparse provides the facility to use different delimiters such as <> or () for optional arguments, using the d or D specifiers instead of o or O

-
I restrict my explanations to the absolutely necessary case. The same explanations are true for \DeclareDocumentCommand and \RenewDocumentCommand etc. – Christian Hupfer Jan 14 at 15:49
Crystal clear explanation I needed something like this :) – Abellan Jan 14 at 15:52
@Abellan: You're welcome! Happy TeXing! – Christian Hupfer Jan 14 at 16:08
Nice answer, but the code can be reduced to \mathcal{O}\IfValueT{#1}{^{#1}}, which is quite interesting as well, because it explains the usage of \IfValue(TF). – egreg Jan 14 at 18:52
@egreg: I know, but I am not really a fan of such constructs actually. – Christian Hupfer Jan 14 at 18:57