# Any way to show LaTeX example code *and* execute it? [duplicate]

In (La)TeX documentation and tutorials, it is common to show a snippet of code next to the output it generates. It might be two minipages side by side, or a code listing followed by boxed output, or whatever. For a trivial example, we might see

$sin \theta$ next to its output, sin θ

Whenever I've done this, I had to use two copies of the code, e.g., once inside verbatim and once inside a minipage or framed box). This just begs for inconsistencies and maintainability problems, since it's very easy to fix one copy and not the other. So, is there any way to display a bunch of code and to execute (a copy of) it, showing the results?

I'm pretty sure it's not straightforward: the code needs to have different catcodes for reading and displaying, but catcodes get assigned only once, when the text is encountered. But if there's no better way, it should be doable by reading the code verbatim and saving a copy in the .aux file, from where it'll get read and interpreted the next time around. But I've never seen such a thing. Has anyone else here?

## marked as duplicate by Count Zero, Speravir, zeroth, Werner, Martin SchröderApr 23 '13 at 21:08

• – Werner Apr 23 '13 at 19:33
• @Werner: tcolorbox is new ;-) – Marco Daniel Apr 23 '13 at 19:45
• @Werner, only the first of these questions is related. The second is about styling LaTeX in listings – alexis Apr 23 '13 at 19:49
• I had no luck bringing up these questions when I looked, how do you guys do it... but I think @Marco's answer is better than the ones in the linked question :-) – alexis Apr 23 '13 at 19:51

Both packages provide options to manipulated the output. The options demonstrate the default behaviour.

Option 1: Package showexpl

This method uses the the package listings. The manipulation is done with LaTeX commands.

\documentclass{article}
\usepackage{showexpl}
\begin{document}
\begin{LTXexample}
$1+1=2$
\end{LTXexample}
\end{document}


Option 2: Package tcolorbox

This package uses listings to format the code and TikZ to draw the frame. Based on this you have a lot of options.

\documentclass{article}
\usepackage{tcolorbox}
\tcbuselibrary{listings}
\begin{document}
\begin{tcblisting}{}
1+1=2
\end{tcblisting}
\end{document}


One way of doing it is:

\documentclass{article}

\usepackage{verbatim}

\begin{document}
\verbatiminput{items.tex}

\input{items.tex}
\end{document}


where items.tex has something like this:

\begin{itemize}
\item one
\item two
\item three
\end{itemize}

• Clever, thanks, but I'm afraid it's pretty impractical with lots of code snippets. Fortunately there are better solutions already :-) – alexis Apr 23 '13 at 19:44