[Tex/LaTex] Define a new environment to combine tikzpicture and lstlisting

listingstikz-pgf

I would like to define a new environment to combine the tikzpicture environment from package pgf/tikz and the lstlisting environment from package listings. The result would be to first produce the picture, then, include verbatim code afterwards. It would be similar to the examples in the PGF manual. Till Tantau uses an environment codeexample, but it is too complicated for me to comprehend, and I don't need other functionalities such as extracting keywords etc.

Best Answer

Use the showexpl package. It uses listings "under the hood", but also compiles your code example for you.

\documentclass{article}
\usepackage{showexpl}
\usepackage{tikz}

% showexpl uses the listings package, so you need to check
% its documentation for that.
% Set up the basic parameters for showing the code
\lstset{%
    basicstyle=\ttfamily\scriptsize,
    commentstyle=\itshape\ttfamily\small,
    showspaces=false,
    showstringspaces=false,
    breaklines=true,
    breakautoindent=true,
    captionpos=t
}
% set up the parameters for the examples themselves
\lstset{explpreset={rframe={},xleftmargin=1em,columns=flexible,language={}}}

\begin{document}
\begin{LTXexample}[pos=b]

\begin{tikzpicture}
\shade[left color=white, right color=red]
      (0,0) rectangle +(3,2);
\end{tikzpicture}

\end{LTXexample}
\end{document}

Output of this document:

Sample code and tikz image

Related Question