[Tex/LaTex] Define a macro based on parameter

macros

I am trying to create a macro that creates two macros. The first sets a default value and the second creates a macro to redefine the first. I am trying to generalize a common pattern I am using quite a bit.

\newcommand{\mkMac}[1]{%
\newcommand{\the#1}{The macro ##1}
\newcommand{\#1}[1]{\renewcommand{\the#1}{##1}}
}

Usage:

\mkMac{affilation}
\affilation{University}
Welcome to \theaffilation

Best Answer

With \newcommand and \renewcommand you have to use \csname...\endcsname, with some \expandafter to build the control sequence before \newcommand or \renewcommand comes into action:

\newcommand{\mkMac}[1]{%
  \expandafter\newcommand\csname the#1\endcsname{%
    Call the macro \texttt{\expandafter\string\csname #1\endcsname}!%
  }%
  \expandafter\newcommand\csname #1\endcsname[1]{%
    \expandafter\renewcommand\csname the#1\endcsname{##1}%
  }%
}

\mkMac{affiliation}
\show\theaffiliation
\show\affiliation
\affiliation{University}
\show\theaffiliation

\stop

This is the output on the terminal when running the example (\stop is just to end the run):

This is pdfTeX, Version 3.1415926-2.5-1.40.14 (TeX Live 2013)
 restricted \write18 enabled.
entering extended mode
(./mkmak.tex
LaTeX2e <2011/06/27>
Babel <3.9f> and hyphenation patterns for 78 languages loaded.
> \theaffiliation=\long macro:
->Call the macro \texttt {\expandafter \string \csname affiliation\endcsname }!.
l.11 \show\theaffiliation

?
> \affiliation=\long macro:
#1->\expandafter \renewcommand \csname theaffiliation\endcsname {#1}.
l.12 \show\affiliation

?
> \theaffiliation=\long macro:
->University.
l.14 \show\theaffiliation

?
 )
No pages of output.
Transcript written on mkmak.log.

So \mkMak{affiliation} defines a temporary value for \theaffiliation and the macro \affiliation; the call \affiliation{University} redefines \theaffiliation to University.