I've detailed some of how I approach this in my blog. I use the listings
package along with some code adapted from the listings
documentation:
%\lst@RequireAspects{writefile}
%\newsavebox{\LaTeXdemo@box}
%\lstnewenvironment{LaTeXdemo}[1][code and example]{^^A
% \global\let\lst@intname\@empty
% \expandafter\let\expandafter\LaTeXdemo@end
% \csname LaTeXdemo@#1@end\endcsname
% \@nameuse{LaTeXdemo@#1}^^A
%}{^^A
% \LaTeXdemo@end
%}
%\newcommand*\LaTeXdemo@new[3]{^^A
% \expandafter\newcommand\expandafter*\expandafter
% {\csname LaTeXdemo@#1\endcsname}{#2}^^A
% \expandafter\newcommand\expandafter*\expandafter
% {\csname LaTeXdemo@#1@end\endcsname}{#3}^^A
%}
%\newcommand*\LaTeXdemo@common{^^A
% \setkeys{lst}{
% basicstyle = \small\ttfamily,
% basewidth = 0.51em,
% gobble = 3,
% keywordstyle = \color{blue},
% language = [LaTeX]{TeX},
% moretexcs = {
% examplemacro,
% ^^A Add you command names here!
% }
% }^^A
%}
%\newcommand*\LaTeXdemo@input{^^A
% \MakePercentComment
% \catcode`\^^M=10\relax
% \small
% \begingroup
% \setkeys{lst}{
% SelectCharTable=\lst@ReplaceInput{\^\^I}{\lst@ProcessTabulator}
% }^^A
% \leavevmode
% \input{\jobname.tmp}^^A
% \endgroup
% \MakePercentIgnore
%}
%\LaTeXdemo@new{code and example}{^^A
% \setbox\LaTeXdemo@box=\hbox\bgroup
% \lst@BeginAlsoWriteFile{\jobname.tmp}^^A
% \LaTeXdemo@common
%}{^^A
% \lst@EndWriteFile
% \egroup
% \begin{center}
% \ifdim\wd\LaTeXdemo@box>0.48\linewidth\relax
% \hbox to\linewidth{\box\LaTeXdemo@box\hss}^^A
% \begin{minipage}{\linewidth}
% \LaTeXdemo@input
% \end{minipage}
% \else
% \begin{minipage}{0.48\linewidth}
% \LaTeXdemo@input
% \end{minipage}
% \hfill
% \begin{minipage}{0.48\linewidth}
% \hbox to\linewidth{\box\LaTeXdemo@box\hss}^^A
% \end{minipage}
% \fi
% \end{center}
%}
%\LaTeXdemo@new{code only}{^^A
% \LaTeXdemo@common
%}{^^A
%}
(This is taken directly from a .dtx
, hence the apparent comment-out characters!) This can then be used as
%\begin{LaTeXdemo}
% Some clever demo here
%\end{LaTeXdemo}
and will typeset the code and the result of the code side-by-side.
I use a three character 'gobble' as the way I tend to lay out my code is to indent by two spaces for each environment, and there is also the %
to gobble. I also have an optional argument to my demo environment, so I can do things like
%\begin{LaTeXdemo}[code only]
% \usepackage{foo}
%\end{LaTeXdemo}
to explain preamble-only stuff and similar 'show code but don't actually execute' material.
If you have stuff which needs to float, you need a different demo, which I set up using the additional lines
%\LaTeXdemo@new{code and float}{^^A
% \lst@BeginAlsoWriteFile{\jobname.tmp}^^A
% \LaTeXdemo@common
%}{^^A
% \lst@EndWriteFile
% \LaTeXdemo@input
%}
This again is set up to work with an optional argument to the environment, and avoids placing the float inside a box (which will fail).
ydoc
bundle for this kind of listings. Unfortunately, it is still in the alpha stage and not recommended to be used for other users packages.