2

I have defined a command for writing down 'requirements' in my document. It automatically styles and numbers it and creates a label to which I can refer to get the number - really nice. However, sometimes I want to repeat the full text of the requirement when referring to it, so the reader does not have to go back in the document. I of course do not want to rewrite it, because that would be prone to errors when I change it in one place. How can I repeat the text using a command?

The current form of my command definition is as follows:

\newcommand{\requirement}[2]{
    \vspace{10pt}
    \noindent
    \textbf{
        \refstepcounter{reqnum}
        \label{req:#2}
        R\thereqnum: #1
    }
}

I tried many variations of the following attempt, to no avail:

\newcommand{\requirement}[2]{
    \vspace{10pt}
    \noindent
    \textbf{
        \refstepcounter{reqnum}
        \label{req:#2}
        R\thereqnum: #1
    }
    \newcommand{\req{#2}}{#1}
}
Oebele
  • 153
  • For the last line \expandafter\def\csname req#2\endcsname {<definition>} should work. – MaestroGlanz Jun 08 '16 at 09:38
  • @MaestroGlanz Awesome, that works! Could you perhaps post it as an answer including an explanation of what it does precisely? Also thanks for the edit, looks much better. – Oebele Jun 08 '16 at 11:13

1 Answers1

2

There is the \csname <string>\endcsname, which makes a command \<string>. You can also use the macros from the etoolbox, which are very convenient to use.

If you replace \newcommand{\req{#2}}{#1} with \expandafter\def\csname req#2\endcsname {#1}, it should work.

\def\name defines a macro \name. It doesn't ask, contrary to \newcommand, if it exists already. So it overwrites \name, if \name exists already. This can be useful, but usually it's harmful.

If you write just \def\csname req#2\endcsname {<definition>}, it tries to redefine \csnameand throws an error, because there is lonesome \endcsname (and a missing \).

If you put \expandafter before \def,

\expandafter\def\csname req#2\endcsname {<definition>}

becomes

\def\req<argument2> {<definition>}

and tada, it is defined. \expandafter delays the expansion of the next token (can be a command sequence). Two expandafters delay for two cycles.

MaestroGlanz
  • 2,348