GeneralBuilding command name from strings and expanding it

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
migf
Posts: 20
Joined: Mon Feb 18, 2013 2:33 pm

Building command name from strings and expanding it

Post by migf »

I am trying to define a command that from a division name like section and a string S will, among other things, expand a command like \section*{S}.

I have two failed attempts on this after a couple of hours searching the web. The first uses \@nameuse like this

Code: Select all

\makeatletter
\newcommand{\mydiv}[2]{%
\@nameuse{\expandafter\csname #1*\endcsname {#2}}%
%...
}
\makeatother
and fails with a Missing \endcsname inserted..

The other tries to define a temporary command and use it:

Code: Select all

\newcommand{\mydiv}[2]{%
\edef\temp{\csname #1*\endcsname}%
\temp{#2}%
%...
}
but just expands to the second argument.

Thanks in advance for any help.
Last edited by cgnieder on Mon Oct 31, 2016 9:49 pm, edited 1 time in total.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

rais
Posts: 419
Joined: Sun Nov 16, 2014 8:51 pm

Building command name from strings and expanding it

Post by rais »

Hi,
your first snippet reads a little like

Code: Select all

\@nameuse{\section*{S}}
i.e., trying to get a command out of the result of `\section*{S}'
(that's not the whole truth yet, `\section*' doesn't exist as a command, s.b.)
Your second snippet doesn't work, because you're trying to call `section*', but the * is not part of the command name. But \csname/\endcsname doesn't complain, if the constructed command isn't defined, that's why you just get the second argument (as it was given) in the output. Try

Code: Select all

\documentclass{article}
\newcommand{\mydiv}[2]{%
  \csname#1\endcsname*{#2}%
}
\begin{document}
\mydiv{section}{S}
\section*{S}% for comparison
\end{document}
(note the placement of the * character outside the macro name)

KR
Rainer
migf
Posts: 20
Joined: Mon Feb 18, 2013 2:33 pm

Re: Building command name from strings and expanding it

Post by migf »

Hi,

Many thanks! Your suggestion works fine.

Best regards,
Miguel
Post Reply