Difference between revisions of "Commands with KeyVal arguments"

From Wiki
Jump to navigation Jump to search
(Add hint for parsing keyval arguments with TeX interface.)
(Merge sections)
 
Line 1: Line 1:
 
< [[Inside ConTeXt]]
 
< [[Inside ConTeXt]]
  
== Using ConTeXt ==
+
== Using Lua ==
 +
 
 +
There is a lovely set of functions in the <tt>utilities.parsers</tt> table that turns strings into nice Lua-accessible tables of various kinds. An example is given below; the functions are documented on the [[String_manipulation#util-prs.lua|string manipulation]] page.
 +
 
 +
<texcode>
 +
\startluacode
 +
userdata = userdata or { }
 +
 
 +
function userdata.mycommand(keywords, keyvals)
 +
    keyword_options = utilities.parsers.settings_to_array(keywords)
 +
    named_values = utilities.parsers.settings_to_hash(keyvals)
 +
   
 +
    -- do stuff based on that array and that hashtable.
 +
end
 +
\stopluacode
 +
 
 +
\def\mycommand[#1][#2]{\ctxlua{
 +
    userdata.mycommand('#1', '#2')}   
 +
 
 +
\mycommand[top, inmargin, now][color=green, roof=gabled]
 +
</texcode>
 +
 
 +
== Using ConTeXt/TeX ==
 +
 
 +
This section is based on a post on the mailing list by Taco Hoekwater from [[http://www.mail-archive.com/ntg-context@ntg.nl/msg03235.html 2004-06-28]] and Hans Hagen from [[https://www.mail-archive.com/ntg-context@ntg.nl/msg100795.html 2021-12-14]].
 +
 
 +
=== Example 1 ===
  
 
To parse your own optional keyval argument from a command. You may want to adapt the logic according to your needs. Note that in the example below, <tt>[#1]</tt> is not optional.  
 
To parse your own optional keyval argument from a command. You may want to adapt the logic according to your needs. Note that in the example below, <tt>[#1]</tt> is not optional.  
Line 25: Line 51:
 
Of course, one can pass on <tt>#1</tt> as argument to other commands. If <tt>MyOwnKeyOne</tt> is not matched by its argument list, it's ignored.
 
Of course, one can pass on <tt>#1</tt> as argument to other commands. If <tt>MyOwnKeyOne</tt> is not matched by its argument list, it's ignored.
  
See also https://www.mail-archive.com/ntg-context@ntg.nl/msg100795.html.
+
See also https://www.mail-archive.com/ntg-context@ntg.nl/msg100795.html for more complex cases and other variants.
 
 
== Using Lua ==
 
 
 
There is a lovely set of functions in the <tt>utilities.parsers</tt> table that turns strings into nice Lua-accessible tables of various kinds. An example is given below; the functions are documented on the [[String_manipulation#util-prs.lua|string manipulation]] page.
 
 
 
<texcode>
 
\startluacode
 
userdata = userdata or { }
 
 
 
function userdata.mycommand(keywords, keyvals)
 
    keyword_options = utilities.parsers.settings_to_array(keywords)
 
    named_values = utilities.parsers.settings_to_hash(keyvals)
 
   
 
    -- do stuff based on that array and that hashtable.
 
end
 
\stopluacode
 
 
 
\def\mycommand[#1][#2]{\ctxlua{
 
    userdata.mycommand('#1', '#2')}   
 
 
 
\mycommand[top, inmargin, now][color=green, roof=gabled]
 
</texcode>
 
 
 
== Using TeX ==
 
 
 
This section is based on a post on the mailing list by Taco Hoekwater from [[http://www.mail-archive.com/ntg-context@ntg.nl/msg03235.html 2004-06-28]].  
 
  
=== Example code ===
+
=== Example 2 ===
  
 
<texcode>
 
<texcode>
Line 96: Line 96:
 
</texcode>
 
</texcode>
  
=== The same example, with commentary ===
+
=== Example 2 with commentary ===
  
 
The 'key' to the keyval functionality in ConTeXt are two macros called
 
The 'key' to the keyval functionality in ConTeXt are two macros called

Latest revision as of 17:44, 18 December 2021

< Inside ConTeXt

Using Lua

There is a lovely set of functions in the utilities.parsers table that turns strings into nice Lua-accessible tables of various kinds. An example is given below; the functions are documented on the string manipulation page.

\startluacode
userdata = userdata or { }

function userdata.mycommand(keywords, keyvals) 
    keyword_options = utilities.parsers.settings_to_array(keywords)
    named_values = utilities.parsers.settings_to_hash(keyvals)
    
    -- do stuff based on that array and that hashtable.
end
\stopluacode

\def\mycommand[#1][#2]{\ctxlua{
    userdata.mycommand('#1', '#2')}    

\mycommand[top, inmargin, now][color=green, roof=gabled]

Using ConTeXt/TeX

This section is based on a post on the mailing list by Taco Hoekwater from [2004-06-28] and Hans Hagen from [2021-12-14].

Example 1

To parse your own optional keyval argument from a command. You may want to adapt the logic according to your needs. Note that in the example below, [#1] is not optional.

\tolerant\protected\def\MyCommand[#1]#2
  {\ifempty{#1}%
     I only got \quote{#2}.
   \orelse\ifhastok={#1}%
     \getdummyparameters[MyOwnKeyOne={},MyOwnKeyTwo={B},#1]
     % this is to define default values; overwritten when mentioned as part of ",#1"
     \ifcstok{\dummyparameter{MyOwnKeyOne}}\emptytoks
     \else
       % if this one is not empty, we do ...
       Here is #1! 
     \fi
     And I also got \quote{#2}.
   \else
     #1 and #2  % whatever
   \fi}

Of course, one can pass on #1 as argument to other commands. If MyOwnKeyOne is not matched by its argument list, it's ignored.

See also https://www.mail-archive.com/ntg-context@ntg.nl/msg100795.html for more complex cases and other variants.

Example 2

\unprotect % enable exclamations in macro names

% Helper function: if the user specifies nothing, throw an error
\def\errorDir{%
   \def\Dir{0}% error recovery
   \message{Please supply "Dir" argument}%
}

% Helper function: process Dir=... other than Up/Down/Left/Right
% Accept numbers, else throw an error
\def\checkDir#1{%
  \doifnumberelse {#1}
                  {\def\Dir{#1}}
                  {\message{Invalid "Dir" argument! (#1)}}
}

% Defining our command that accepts key=val
\def\MyZigzag#1[#2]{%
  % the #1 makes sure we allow a space before the bracket

  % create commands \ZZDir, \ZZLinewidth (default 1pt), etc.
  \getparameters[ZZ][Dir=,Linewidth=1pt,Color=Red,Width=3em,#2]

  % define an alias
  \edef\mywidth{\ZZWidth}%

  % accept keywords for Dir= (and map those keywords to numbers)
  %\expandafter\processaction\expandafter[\ZZDir] % mkii
  \processaction[\ZZDir]                          % mkiv
	[      Down=>\def\Dir{270},
	       Left=>\def\Dir{180},
   	         Up=>\def\Dir{90},
 	      Right=>\def\Dir{0},
	 \s!default=>\errorDir, 
	 \s!unknown=>\checkDir{\ZZDir}]
} % this brace belongs to \def!

\protect % end of definitions

Example 2 with commentary

The 'key' to the keyval functionality in ConTeXt are two macros called \getparameters and \processaction.

\unprotect % enable exclamations in macro names

\def\MyZigzag#1[#2]{% % This brace is closed below, after the \expandafter block
  % the #1 makes sure we allow a space before the bracket

  \getparameters[ZZ][Dir=,Linewidth=1pt,Color=Red,Width=3em,#2]

Now you have a set of new macros that all start with ZZ. At least there are \ZZDir,\ZZLinewidth, \ZZColor and \ZZWidth (these have default values) but possibly others as well, depending on user input. In the next lines you make use of these variables, for example as follows:

 \edef\mywidth{\ZZWidth}%

If you want some of the variables to accept keyword values, then you also need to use \processaction on the ZZ variable in question to map the keywords onto actual values.

Say you want "Dir" to be mandatory and that it accepts 4 directional keywords, as well as a direct angle specification. I've used all mixed case keywords, because otherwise you might run into conflicts with the multilingual interface:

  %\expandafter\processaction\expandafter[\ZZDir] % mkii
  \processaction[\ZZDir]                          % mkiv
	[      Down=>\def\Dir{270},
	       Left=>\def\Dir{180},
   	         Up=>\def\Dir{90},
 	      Right=>\def\Dir{0},
	 \s!default=>\errorDir, 
	 \s!unknown=>\checkDir{\ZZDir}]
} % this brace belongs to \def!

\s!default may be triggered because \ZZDir's expansion is empty unless the user supplied something.

In MkII, the first argument to \processaction has to be expanded, so you need the \expandafters. In MkIV, \processaction does this automatically.

For completeness, here is an example definition of \checkDir and \errorDir:

\def\errorDir{%
   \def\Dir{0}% error recovery
   \message{Please supply "Dir" argument}%
}

\def\checkDir#1{%
  \doifnumberelse {#1}
                  {\def\Dir{#1}}
                  {\message{Invalid "Dir" argument! (#1)}}
}

\protect % end of definitions