[Tex/LaTex] Detect no argument in \newcommand

argumentsmacrosoptional arguments

I wonder if there is a way to create a command which can discriminate when there is an argument or not. I don't mean empty argument, I mean no argument at all.

Here an example

\newcommand{\mycommand}[1]{
\if \totallyempty
0
\elseif \empty 
1
\else 
%whatever
2
\fi
}

Testing

\mycommand

0

\mycommand[]

1

\mycommand[2]

2

UPDATE

Apologies, the command argument does not need to be in braces {}, as many pointed, the optional arguments should be []. My main concern was about the possibility of not especify the argument, e.g. \mycommand,\mycommand[],\mycommand[2].

Apologies for not explaining correctly. I changed in the main text. Regards.

SOLUTION

Thanks very much to all the solution submitted, they are all very creative and useful.

I had to select @egreg solution (https://tex.stackexchange.com/a/409770/105956) for the very easy to implement and clear code. Mention to @Phelype Oleinik and @David Carlisle for not use any package.

Thanks very much. Kind regards.

Best Answer

You can, but you shouldn't. Optional arguments should be delimited by [].

I hope that the command names are clear enough to tell what's my opinion on the matter.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\cs_new_eq:NN \IfBlankTF \tl_if_blank:nTF
\cs_new_eq:NN \IfEmptyTF \tl_if_empty:nTF
\ExplSyntaxOff


\NewDocumentCommand{\mybadcommand}{g}{%
  \IfNoValueTF{#1}
   {0}
   {%
    \IfEmptyTF{#1}% if you allow { } to represent case 1, use \IfBlankTF instead
      {1}
      {2}%
   }%
}

\NewDocumentCommand{\mygoodcommand}{o}{%
  \IfNoValueTF{#1}
   {0}
   {%
    \IfEmptyTF{#1}% if you allow [ ] to represent case 1, use \IfBlankTF instead
      {1}
      {2}%
   }%
}

\begin{document}

\mybadcommand

\mybadcommand{}

\mybadcommand{x}

\mygoodcommand

\mygoodcommand[]

\mygoodcommand[x]

\end{document}

enter image description here

Related Question