[NTG-context] Defining command with optional and mandatory arguments

Christoph Reller christoph.reller at gmail.com
Thu May 24 11:21:43 CEST 2018


On Wed, 23 May 2018 16:01:05 +0200, Hans Hagen <j.hagen at xs4all.nl> wrote:
>
> On 5/23/2018 3:39 PM, Christoph Reller wrote:
>> Hi,
>>
>> What is the right way to define a command with both mandatory and
>> optional arguments, e.g:
>>
>> \MyCommand[optional][mandatory]
>>
>> Consider the following MWE:
>>
>> \unexpanded\def\MyCommand[#1]{
>>    \dosingleempty{\doMyCommand[#1]}}
>> \def\doMyCommand[#1][#2]{
>>    \doifsomething{#1}{number 1: #1\par}
>>    \doifsomething{#2}{number 2: #2}\blank[big]}
>> \starttext
>> \MyCommand[A][B]
>> \MyCommand[A]
>> \stoptext
>>
>> In last year's versions of ConTeXt the output was
>>
>> number 1: A
>> number 2: B
>> number 1: A
>>
>> In the latest version of ConTeXt the output is
>>
>> number 1: A
>> number 2: B
>> number 2: A
>>
>> Is this behavior intended? How can I make a definition whose behavior
>> does not change in new versions of ConTeXt?
> i'm not sure wht happens at your end but this is the best way:
>
> \unexpanded\def\MyCommand
>    {\dodoubleempty\doMyCommand}
>
> \def\doMyCommand[#1][#2]%
>    {\iffirstargument
>       number 1: #1%
>       \par
>     \fi
>     \ifsecondargument
>       number 2: #2%
>     \fi
>     \blank[big]}
>
> \starttext
>      \MyCommand[A][B]
>      \MyCommand[A]
> \stoptext

Thank you Hans for this information. My question is rather about error
handling. I want:

\MyCommand[A][B] % <- succeeds with #1->A, #2->B
\MyCommand[A] % <- succeeds with #1->A
\MyCommand % <- fails with "! Use of \MyCommand doesn't match its definition"

I just wanted to ask whether there is a standard way to achieve this
with \do<whatever>empty. If not, then this is also okay.

Cheers,
Christoph


More information about the ntg-context mailing list