[Tex/LaTex] newcommand key value

conditionalskey-valuemacros

This is a completely noob question for LaTeX package writers. Could somebody share a piece of code or a MWE for the following situation. I would like to define a newcommand which will depend on the key. Something like

\newcommand{\mycommand}#if key_value=1 {test} else {test2}

which should do someting like follows

\mycommand[key=1]

should print test, otherwise the output should be test2.

I apologize to seasoned package writers for this and other noob questions. I am just overwhelmed with amount of simple material I am clueless about.

Best Answer

There are several packages for defining a key=value syntax. I'll show keyval as it's part pf the basic latex distribution, and I know something about it.

If you LaTeX the following:

\makeatletter % not needed in a .sty file

\RequirePackage{keyval}




\define@key{test}{key}{%
  \count@=#1\relax}

\define@key{test}{color}{%
  \def\thiscolor{#1}}


\newcommand{\mycommand}[1]{%
  \count@=0 % default
  \def\thiscolor{}% default
  \setkeys{test}{#1}%
  \ifodd\count@
    \typeout{key=\the\count@: Odd!}%
  \else
    \typeout{key=\the\count@: Even!}%
   \fi
   \typeout{the color is \thiscolor}}



\typeout{======}
\mycommand{key=1,color=red]}

\stop

You will see both keys have been processed and the following typeouts are made

======
key=1: Odd!
the color is red]
 )
No pages of output.

The way this works is the package handles the splitting up of the comma separated settings , but for each key "key" and "color" here you have to define a command that does something with the value. Here the key is a number to be saved in \count@ and the colour is treated as text stored in \thiscolor, then after processing the keys these values can be used as normal TeX code.

Related Question