2

I want a macro that takes an optional argument.

  • If nothing is passed, it produces G.
  • If i is passed, it produces G_{p_i}.

The following code however is facing some error "Can't use '\spacefactor' in math mode".

\documentclass{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amsthm}
\newcommand{\cabGo}[1][\@empty]{
    \ifx\@empty#1{{\sf G}}
    \else{{\sf G}_{p_{#1}}}
    \fi
}
\begin{document}
$\cabGo$
$\cabGo[3]$
\end{document}
2

1 Answer 1

7

The main problem is missing \makeatletter.

On the other hand, the code is not really well written:

\newcommand{\cabGo}[1][]{%
  \mathsf{G}%
  \if\relax\detokenize{#1}\relax
  \else
    _{p_{#1}}%
  \fi
}

The test for emptiness of the argument is more robust; also \sf has been deprecated for more than 20 years.

If you load xparse, the code is even simpler:

\usepackage{xparse}

\NewDocumentCommand{\cabGo}{o}{%
  \mathsf{G}\IfValueT{#1}{_{p_{#1}}}%
}

The change requested in comments (any number of options can be given)

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\cabGo}{o}
 {
  \mathsf{G}
  \IfValueT{#1}
   {
    \sb{\clist_map_inline:nn { #1 } { p\sb{##1} }}
   }
 }

\ExplSyntaxOff

\begin{document}

$\cabGo$ (no option)

$\cabGo[1]$ (single option)

$\cabGo[1,2]$ (double option)

$\cabGo[1,2,3]$ (triple option)

\end{document}

enter image description here

3
  • Isn't there an \else missing? Jul 10, 2018 at 8:04
  • @RaoulKessels Indeed!
    – egreg
    Jul 10, 2018 at 8:18
  • Hi @egreg, can you please make it more robust as suggested following? \cabGo outputs G \cabGo[1] outputs G_{p_1} \cabGo[2,3] outputs G_{p_2p_3} etc. Thanks a lot in advance.
    – mxant
    Jul 11, 2018 at 17:35

You must log in to answer this question.

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