2

Is there a way to define a LaTeX command in which an argument forms part of a command that is expanded inside the text defined by the command?

For example, here's a MNWE (Minimal Non-Working Example--it doesn't work, and that's the basis of the question):

\newcommand{\firstExclamation}{Yesiree!}
\newcommand{\secondExclamation}{No way!}

\newcommand{\firstExplanation}{You are our favorite customer.}
\newcommand{\secondExplanation}{We're all out of that product.}

\newcommand{\usesMyCommands}[1]{I said, ``\#1Exclamation \#1Explanation"}

Then \usesMyCommands{first} should expand into "Yesiree! You are our favorite customer.", while \usesMyCommands{second} should expand into "No way! We're all out of that product."

This question and its answer seem very relevant, as does this one, but after some experimentation, I have not figured out how to apply their lessons to my case. These questions are about how to define a command inside a command, and I want to use a command inside a command. Maybe I'm just not seeing it, though--maybe the answer is there in those answers, and I'm not realizing it.

I am sure that there is a way to do this is in raw TeX. I'm hoping not to have to descend into the TeX swamp. I respect those who routinely do so. I have also looked at this, this, and this, but hope that I do not have to understand them. :-)

5
\documentclass{article}

\usepackage{amsmath}

\begin{document}
\newcommand{\firstExclamation}{Yesiree!}
\newcommand{\secondExclamation}{No way!}

\newcommand{\firstExplanation}{You are our favorite customer.}
\newcommand{\secondExplanation}{We're all out of that product.}

\newcommand{\usesMyCommands}[1]{I said, ``\csname #1Exclamation\endcsname\ \csname#1Explanation\endcsname"}
\usesMyCommands{first}, \usesMyCommands{second}
\end{document}

enter image description here

  • Thanks--that's great! This is going to be extremely helpful. I had tried messing around with \csname and \endcsname, but I didn't know what I was doing. Among other things, I put a backslash in front of #1. (For anyone who comes to this page without knowing what \*csname do [I didn't], this answer gives a succinct statement of their use in Ulrike's answer here, and other answers to that question describe other uses.) – Mars May 25 '18 at 0:02

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.