Popular ways to define a macro with optional arguments is using TeX's \def
with the aid of \@ifnextchar[
and/or LaTeX's \newcommand
. In both cases, macro's definition usually contains its optional arguments.
Now, I want to use optional arguments just as a sort of junction which decides how macro expands. The option itself is not used in macro's definition explicitly.
For a simple instance, let me define \conjTrans
, which denotes a conjugate transpose of a matrix in three notations. The specification of \conjTrans
is as follows:
\documentclass{standalone}
\usepackage{conjTrans} % \conjTrans is defined here
\begin{document}
$\conjTrans{A}$,
$\conjTrans[asterisk]{B}$,
$\conjTrans[Hermite]{C}$, and
$\conjTrans[dagger]{D}$
\end{document}
will produce
and if invalid option (e.g. dager
) is given, an error like the option is incorrect
occurs.
I first tried to utilize \ifx
or other conditional branches, but it didn't go well with my competence because options are more than one token and I don't know the solution to it.
I implemented \conjTrans
with the following code.
% conjTrans.sty
\ProvidesPackage{conjTrans}[2016/01/05 my first question on TeX.SX]
\RequirePackage{amsmath}
\def\conjTrans{\@ifnextchar[\nkt@conjTrans{\nkt@conjTrans[asterisk]}}
\def\nkt@conjTrans[#1]#2{%
\expandafter\ifx\csname nkt@conjTrans@#1\endcsname\relax
\PackageError{conjTrans}{The option #1 is unknown to \string\conjTrans}{Optional argument for \string\conjTrans\space must be either ast, H, or dagger.}%
\else
\csname nkt@conjTrans@#1\endcsname#2%
\fi
}
\def\nkt@conjTrans@asterisk#1{\boldsymbol#1^{\ast}}
\def\nkt@conjTrans@Hermite#1{\boldsymbol#1^{\text{H}}}
\def\nkt@conjTrans@dagger#1{\boldsymbol#1^{\dagger}}
This \conjTrans
seems to work quite well, but I wonder if there is a method which is more sophisticated, safer, or better in certain sense than mine. Are there any standard “idioms” to use optional arguments in this way?