2

This seems obvious but I can't seem to find what I need via a search (I can't figure out a good search term I guess).

So what I'm looking for is to have a command that takes in a string, and then calls a command whose name contains that string. For reference the command will be in a sty file.

MWE:

Sty file:

\newcommand{\foo@tempinput}
    {This works I hope!}
\newcommand{\DesiredMacro}[1]
    {\csname \foo@#1\endcsname}

Actual Document:

\documentclass{article}
\usepackage{Customstyfile}
\begin{document}
\DesiredMacro{tempinput}
\end{document}

And ideally that would output "This works I hope!"

I know the above doesn't work because the \csname isn't expanding the #1, but I'm unsure as to if \csname can be used as a way of executing a command, or if it's only used to define a command?

I want to do this so that I can have a host of commands, and the user can execute the one they need by typing in a name, which protecting the command itself from the user (and avoiding having the user need to know the more complicated command names. I want to be able to have the user input only be a part of the command name).

Thanks!

1

By using, as the OP did, \csname \foo@#1\endcsname, a macro is invoked with the name formed by substituting the definition of \foo followed by argument 1, #1. But what the OP's main code suggests isn't that the value of \foo is desired, but rather the letters "foo" themselves, so that the macro being invoked has the "name" of "foo#1", where #1's value is substituted.

Thus, eliminating the backslash prior to foo in the definition of \DesiredMacro takes care of the problem.

\documentclass{article}
%\usepackage{Customstyfile}
\makeatletter
\newcommand{\foo@tempinput}
    {This works I hope!}
\newcommand{\DesiredMacro}[1]
    {\csname foo@#1\endcsname}
\makeatother
\begin{document}
\DesiredMacro{tempinput}
\end{document}

enter image description here

  • Yep, I'm a moron, that slash was the problem. Figures... bang my head against a wall for an hour over a backslash. Story of my life heh, thanks Steven! – Jason Apr 29 '16 at 0:04
  • @Jason Glad to help. Yes, I do think the term "backslash" is aptly named, for all the injury it causes. – Steven B. Segletes Apr 29 '16 at 0:05

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.