[Tex/LaTex] Print small TeX code verbatim and render it

macrosverbatim

To write some documentation, I would like the ability to define a command such as

\showcase{x^{y}\in\Omega}

which expands to something roughly equivalent to

\verb|x^{y}\in\Omega| & $x^{y}\in\Omega$ \\

so that I can show what the latex code looks like and how does it show on the document.

Now I now that it isn't really possible to use \verb for this because it's really fragile and you can't pass arguments from a macro to it. But, assuming that I'm not trying to write anything crazy in the argument to \showcase (e.g. braces are always balanced, I don't care much if spaces are collapsed, no %'s inside), is there a way to define such a command?

Update

\detokenize does (almost) exactly what I want. Take the following example

\newcommand\showcase[1]{{\ttfamily\detokenize{#1}} & $#1$}
\begin{tabular}{cc|cc}
\showcase{x^{y}}      & \showcase{\hat{x}, \bar{x}} \\
\showcase{x_{y}}      & \showcase{f\colon X \to Y} \\
\showcase{x'}         & \showcase{\sqrt{x+2}} \\
\showcase{x''_{2}}    & \showcase{2 < x \leq 4} \\
\showcase{A^{1}_{2}}  & \showcase{\frac{a+b}{c+d}} \\
\showcase{3\pi/4}     & \showcase{\int_{0}^{1} x^{2} \,dx} \\
\showcase{x\in\Omega} & \showcase{A \cup B \subseteq C \cap D}
\end{tabular}

Which produces the output:

enter image description here

My minor quibbles are that:

  • The double '' seems to have been collapsed into a "
  • I find mildly annoying the spaces after control sequences. I know why they are there, but could there be a way to remove the space if it is not followed by a letter or number? (Or, conversely, if followed by { or _)

Best Answer

For math mode this should work.

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\showcase}{v}
 {
  \texttt{#1} & \tl_rescan:nn { } { $#1$ }
 }
\ExplSyntaxOff

\begin{document}
\begin{tabular}{cc|cc}
\showcase{x^{y}}      & \showcase{\hat{x}, \bar{x}} \\
\showcase{x_{y}}      & \showcase{f\colon X \to Y} \\
\showcase{x'}         & \showcase{\sqrt{x+2}} \\
\showcase{x''_{2}}    & \showcase{2 < x \leq 4} \\
\showcase{A^{1}_{2}}  & \showcase{\frac{a+b}{c+d}} \\
\showcase{3\pi/4}     & \showcase{\int_{0}^{1} x^{2} \,dx} \\
\showcase{x\in\Omega} & \showcase{A \cup B \subseteq C \cap D}
\end{tabular}
\end{document}

enter image description here

Should you want to swap the columns, so the result appears before the code, just change the definition of \showcase inverting the cells:

\NewDocumentCommand{\showcase}{v}
 {
  \tl_rescan:nn { } { $#1$ } &  \texttt{#1}
 }

enter image description here