19

I'm writing a document where I have many code blocks like so:

\begin{align}
d = \sqrt{ (x'-x)^2 } 
\end{align}

\begin{minted}{latex}
d = \sqrt{ (x'-x)^2 }
\end{minted}

So the first line renders the latex code, and the second shows the source. Is there any way of wrapping this whole thing in its own environment? For example, it would look like:

\begin{eqnexample}
d = \sqrt{ (x'-x)^2 }
\end{eqnexample}

Thoughts?

yo'
  • 51,322
picadora
  • 393

2 Answers2

12

The simplest thing is to write out the contents of your "example" environment and read it back twice:

\documentclass{article}

\usepackage{amsmath}
\usepackage{minted} % loads fancyvrb

\newenvironment{eqnexample}
 {\VerbatimOut{\jobname.tmp}}
 {\endVerbatimOut
  \inputminted{latex}{\jobname.tmp}
  \input{\jobname.tmp}}

\begin{document}

\begin{eqnexample}
\begin{align}
  d &= \sqrt{ (x'-x)^2 }
  \\
  e &= 0
\end{align}
\end{eqnexample}

\begin{eqnexample}
\begin{multline}
  d = \sqrt{ (x'-x)^2 }
  \\
  = f(x,x')
\end{multline}
\end{eqnexample}

\end{document}

enter image description here

David Carlisle
  • 757,742
egreg
  • 1,121,712
  • 1
    Thanks egreg. It leaves a "clunky" feeling in my stomach, but knowing that I can write all kinds of things to temp files and use them later is actually very powerful. Thanks! – picadora Jan 16 '13 at 14:18
7

Here's a simple way to do it with fancyvrb. This approach saves the environment content to an external file and then brings it back twice. There may be ways to do this without using a temporary external file, but if you are using minted you are already using lots of temporary files.

By the way, you might want to use the upquote package to make the prime on the x be a straight quote rather than a curly quote in the minted environment.

enter image description here

\documentclass{minimal}

\usepackage{amsmath}
\usepackage{minted}
%\usepackage{fancyvrb} %Already loaded by minted

\newenvironment{eqnexample}%
  {\VerbatimEnvironment
    \begin{VerbatimOut}{eqnexample.tmp}}%
  {\end{VerbatimOut}%
    \begin{align}%
    \input{eqnexample.tmp}%
    \end{align}%
    \inputminted{latex}{eqnexample.tmp}}


\begin{document}

\begin{eqnexample}
d = \sqrt{ (x'-x)^2 }
\end{eqnexample}

\end{document}
G. Poore
  • 12,417