8

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

hackdev
  • 81

2 Answers2

6

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}

enter image description here

egreg
  • 1,121,712
2

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:

enter image description here

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.