# How reuse latex code for later expansion?

I would like to make a command to help me writing lines like:

The \LaTeX~code is: \verb@e^{i\pi} - 1 = 0@, and the result is: $e^{i\pi} - 1 = 0$.


I thought of using a newcommand as:

\newcommand{\eqn}[1]{The \LaTeX~code is: \verb@#1@, and the result is: $#1$.}


to use as:

\eqn{e^{i\pi} - 1 = 0}


which doesn't work.

Trying to pull out the verbatim out as:

\newcommand{\eqn1}[1]{The \LaTeX~code is: #1, and the result is: $#1$.}


to use as:

\eqn1{\verb@e^{i\pi} - 1 = 0@}


also doesn't work.

My question is, is there a way to achieve this in latex?

Thank you. PS: unfortunately the thread bellow seems to indicate that it's not possible :( Wrapping code (listings, verbatim, or other method) inside a newcommand

• Regarding the second definition, there are two things which would cause errors: LaTeX commands cannot contain numbers (so \eqn1 generates a Missing \begin{document} error); and your eqn1 command takes math and pastes it into the document inside textmode, so you'll get a bunch of errors from that (e.g. ^ is not allowed in textmode). – Arun Debray Dec 18 '15 at 5:17
• – Werner Dec 18 '15 at 5:47

Absorb the argument verbatim and rescan it when you need the real output:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\eqn}{v}
{
The~\LaTeX{}~code~is:~\texttt{#1},~and~the~
result~is:~\tl_rescan:nn { } { $#1$ }.
}
\ExplSyntaxOff

\begin{document}

\eqn{e^{i\pi} - 1 = 0}

\end{document}


• Nice! I really need to look more into expl3 programming. – Håkon Marthinsen Dec 18 '15 at 18:49

With inspiration from this answer by Ulrich Schwarz, we can solve this using \meaning:

\documentclass{article}

\makeatletter
\newcommand\meaningbody[1]{%
{\ttfamily
\expandafter\strip@prefix\meaning#1}%
}
\newcommand\eqn[1]{%
{\def\@foo{$#1$}The \LaTeX~code is \meaningbody\@foo, and the result is: $#1$.}%
}
\makeatother

\begin{document}

\eqn{e^{i\pi} - 1 = 0}

\end{document}


The result is:

One potential problem is that the output from \meaning is not exactly the same as the input code. There is an extra space after \pi in this example.