12

This question already has an answer here:

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öder Apr 23 '13 at 21:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

20

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}

enter image description here

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}

enter image description here


5

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}
  • 2
    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

Not the answer you're looking for? Browse other questions tagged or ask your own question.