This usage is very uncommon with LaTeX (it's not the way \author
etc. works), but it is possible to make the macro look ahead with \@ifnextchar
to see if the next character is a brace (which needs to be written as \bgroup
because you need a matching pair of braces in the macro).
\newcommand*\tutor{%
\@ifnextchar\bgroup
{\gdef\@tutor}%
{\@tutor}%
}
This will expand to \gdef\@tutor
if there is an argument (which will then be taken by it) or to \@tutor
if not.
There is also the xparse
package which allows to define macros with optional brace arguments and a way to test if the argument was there or not. See the package manual for the details. For this case it is IMHO a little overkill.
You could also define \tutor
in the form you have in your post and redefine it at the begin of the document to be equal to \@tutor
.
\newcommand*{\tutor}[1]{\gdef\@tutor{#1}}
% or
% \newcommand*{\tutor}{\gdef\@tutor}
\AtBeginDocument{\let\tutor\@tutor}
Then you can use \tutor{<argument>}
only in the preamble and \tutor
only in the document body.
Macros with an @
in the name need to be wrapped in \makeatletter
... \makeatother
, except in package or class files, which do this automatically.
Let's assume you don't want to type in (x,y)
or (x,y\mid a)
for some reasons. And there are good reasons not to: for instance, you might want or be required to change notation. A hardwired input would make the task very difficult.
The idea is to type in
\dependSet{x,y}
\dependSet{x,y|a}
but without impacting on the final output. The input is quite natural and avoids the complications of too many braces.
How do we do it? We can use \NewDocumentCommand
and its \SplitArgument
feature.
\documentclass{article}
%\usepackage{xparse} % uncomment for older versions of LaTeX
\NewDocumentCommand{\dependSet}{>{\SplitArgument{1}{|}}m}{%
\dependSetAux#1%
}
\NewDocumentCommand{\dependSetAux}{mm}{%
\IfNoValueTF{#2}{% no | found
(#1)%
}{% found |
(#1\mid #2)%
}%
}
\begin{document}
$\dependSet{x}+\dependSet{x,y}+\dependSet{x,y|a}$
\end{document}
Comments.
The command \dependSet
passes its argument to \dependSetAux
as two braced groups. If there is no |
in the initial argument, the second braced group will be {-NoValue-}
that can be tested as shown.
If you want to change the final formatting, act on \dependSetAux
.
A possibly more efficient code, but less straightforward, would be
\NewDocumentCommand{\dependSetAux}{mm}{%
(#1\IfValueT{#2}{\mid #2})%
}
Best Answer
As pointed out by Steven B. Segletes in a comment,
works and saves the optional argument. If the optional argument is not required, then
is the solution.