Changes

Jump to navigation Jump to search
no edit summary
< [[Inside ConTeXt]] | [[Commands with KeyVal arguments]] >
In LaTeX you define a new command with an optional argument with "newcommand": <texcode>\newcommand{\MyCommand}[2][World]{{#2Hello #1!}}\MyCommand{\bfseries}\MyCommand[Hans]{\scshape}</texcode> <context>{\bf Hello World!}{\sc Hello Hans!}</context> In ConTeXt, the optional argument processing is handled as a two-step process. First, we write the command for the end-user as a wrapper command, which calls <{{cmd>|dodoubleempty</cmd> }} (from [http://source.contextgarden.net/tex/context/base/{{src|syst-genaux.tex systmkiv}} or {{src|sys-gen.tex]mkii}}) to handle the arguments properly -- including the optional ones -- and then calls a "private" command that contains the internals of the macro. Note that this function call does not explicitly refer to the arguments at all.
<texcode>
</texcode>
We then create the "private" macro (<tt>\doMacroName</tt> is the traditional ConTeXt name for these), with all the arguments defined as nonoptional. Default values for the arguments need to be handled somewhat more explicitly than with LaTeX; macros such as <{{cmd>|ifsecondargument</cmd> }} are used to determine whether the given argument was specified, as follows:
<texcode>
</context>
If you ''don't'' want any optional arguments, but still want your arguments enclosed in <tt>[]</tt> with appropriate handling for spaces (or line breaks) between the square brackets, use <{{cmd>|dodoubleargument</cmd> }} instead of <{{cmd>|dodoubleempty</cmd>}}. There are of course versions for other numbers of arguments, found by replacing <tt>double</tt> with <tt>single</tt> through <tt>seventuple</tt>; see [http://source.contextgarden.net/tex/context/base/syst-gen.mkii {{src|syst-genaux.tex] mkiv}} for the exact names.
=== Examples ===
\def\doMycommand[#1][#2]#3{whatever}
</texcode>
 
 
 
To define <code>\mycommand[optional]{text}</code>, do the following
 
<texcode>
 
\def\mynewcommand{\dosingleempty\doMyNewCommand}
\def\doMyNewCommand[#1]#2{%
\stoptext
</context>
 
 
On a final note, for comparative purposes: in LaTeX, a new command with an optional argument is defined with <code>\newcommand</code>.
 
<texcode>
\newcommand{\MyCommand}[2][World]{{#2Hello #1!}}
\MyCommand{\bfseries}
\MyCommand[Hans]{\scshape}
</texcode>
Reference:

Navigation menu