I am trying to define a macro with variable number of arguments. For example I want to define a macro with two arguments that can work with one argument as well. So the same macro works in two ways.
\textcolor{red}{sample text}
This would limit the red color to the sample text and whereas just calling \textcolor{red}
would turn on the red color until the end of the document. So the second way of using the macro would be
\textcolor{red}
I was trying to implement the macro using \@ifnextchar
. I am not having much success. Could you please give me some hints?
Based on @Joseph's suggestion below I modified my toy code and it works. I still have problem understanding the actual execution flow in the code. Here is my code.
\documentclass[12pt]{article}
\makeatletter
\def\oneortwoargs#1{%
\@ifnextchar\bgroup%
{\twoargs@aux{#1}}
{\onearg@only{#1}}
}
\def\onearg@only#1{%
Only argument provided: #1 %
}
\def\twoargs@aux#1#2{%
Two arguments are provided. \\%
First argument: #1 \\ %
Second argument: #2%
}
\makeatother
\begin{document}
\oneortwoargs{gg}{fff}
\oneortwoargs{qq}
\end{document}
As @Joseph explained below one token is left in the input stream. What is confusing me is that \onearg@only
and \twoargs@aux
are invoked the same way with only one argument.