9

I've been trying to read through some examples and text about how expansion works, but I seem to be unable to understand how it really works. The code I am trying to get to work, is the following:

\documentclass[11pt]{article}
\usepackage{lipsum, ifthen,color}

% I want to use a modified version of this command:
\newcommand{\version}[2]{\marginpar{\expandafter\colorbox{\csname \ifthenelse{\equal{#1}{1}}{green}{red}\endcsname}{\begin{minipage}{\marginparwidth}
        V.#1 #2
    \end{minipage}}}}

% Command made just for this example    
\newcommand{\versionB}[2]{\marginpar{\colorbox{red}{\begin{minipage}{\marginparwidth}
        V.#1 #2
    \end{minipage}}}}

\begin{document}
\section{incomplete sectinon}\versionB{0.9}{Need to add something, therefor this box is red.}
\lipsum[1]
\section{Complete sectinon}\versionB{1}{This section is complete, therefore this box \emph{should} be green.}
\lipsum[2]
\end{document}

A note in the margin is printed, to show if a section is completed. If it is highlighted, it should have a green background, if not, red. In the example above, I have used the command \versionB to just show the notes for the example only. Change it to simply \version to use the command which should make it change color depending on the given first argument.

This command currently expands wrong.

12
 \newcommand{\version}[2]{\marginpar{%
  \expandafter\colorbox{%
    \csname \ifthenelse{%
       \equal{#1}{1}}{green}{red}\endcsname}{%
         \begin{minipage}{\marginparwidth}

\expandafter works at the level of tokens. The token after \colorbox is { so \expandafter here does nothing as { is not expandable.

The tokens between \csname and \endcsname have to expand to a sequence of character tokens, which is then used as the command name. \ifthenelse does not work by expansion, internally it has groups and \def and \let assignments, so it can't be used here at all.

I think you want an expandable test choosing red or green depending on whether #1 is 1 so:

 \newcommand{\version}[2]{\marginpar{%
    \colorbox{\ifnum#1=1 green\else red\fi}{%
         \begin{minipage}{\marginparwidth}

Note that \colorbox uses the same \fboxsep padding as \fbox so unless you have set \fboxsep to 0pt somewhere your inner minipage is 2\fboxsep too wide.

  • Thank you, this more than solves my problem. Great explanation, I think I got it now:) And thanks for the extra info. Cheers. – Runar Nov 14 '15 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.