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


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.

  • 5
    Will \mycommand have to distinguish between different keys? For example, do you allow inputs like \mycommand[house=1], \mycommand[tree=2], \mycommand[house=4,tree=1]?
    – Werner
    May 31, 2012 at 22:57
  • 3
    I agree with Werner: the question is too generic for getting a sensible answer. If you need only one key, it's simpler not to use a key at all and use just an optional argument.
    – egreg
    May 31, 2012 at 23:05
  • @Werner No Werner.The key would have just to distinguish between two values of the single key. In particular I want a Syllabus to have an optional section called project. So if I type \coursecontent[project=yes] the command will put optional paragraph about project. If [project=no] the project section will be omitted. Jun 1, 2012 at 2:16
  • 4
    In that case, despite my accepted answer below you don't need key=value syntax at all, the latex style would be just to have \coursecontent[yes] or since there are only two values have no argument at all and just \coursecontent and \coursecontent* (which you can code easily by using \def\coursecontent{\@ifstar{code for * version}{code for other version}} Jun 1, 2012 at 8:15
  • @David Carlisle You are the best! Thank you so much. Jun 1, 2012 at 14:23

1 Answer 1


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




  \count@=0 % default
  \def\thiscolor{}% default
    \typeout{key=\the\count@: Odd!}%
    \typeout{key=\the\count@: Even!}%
   \typeout{the color is \thiscolor}}



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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .