LaTeX forum ⇒ GeneralBuilding command name from strings and expanding it Topic is solved

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

Building command name from strings and expanding it

Postby migf » Sun Oct 30, 2016 3:44 pm

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

  1. \makeatletter
  2. \newcommand{\mydiv}[2]{%
  3. \@nameuse{\expandafter\csname #1*\endcsname {#2}}%
  4. %...
  5. }
  6. \makeatother


and fails with a Missing \endcsname inserted..

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

  1. \newcommand{\mydiv}[2]{%
  2. \edef\temp{\csname #1*\endcsname}%
  3. \temp{#2}%
  4. %...
  5. }


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.
Reason: added inline code markup

Tags:

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

Postby rais » Sun Oct 30, 2016 6:48 pm

Hi,
your first snippet reads a little like
  1. \@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
  1. \documentclass{article}
  2. \newcommand{\mydiv}[2]{%
  3. \csname#1\endcsname*{#2}%
  4. }
  5. \begin{document}
  6. \mydiv{section}{S}
  7. \section*{S}% for comparison
  8. \end{document}

(note the placement of the * character outside the macro name)

KR
Rainer

migf
Posts: 11
Joined: Mon Feb 18, 2013 2:33 pm

Postby migf » Sun Oct 30, 2016 7:53 pm

Hi,

Many thanks! Your suggestion works fine.

Best regards,
Miguel


Return to “General”

Who is online

Users browsing this forum: No registered users and 5 guests