Using listings with output
The best way to show the output along with the LaTeX code is to use the showexpl
package:
Notes:
- To adjust the position of the output you can use the
pos=
option:t
op,b
ottom,r
ight,l
eft,o
uter, andi
nner.
Code:
%\RequirePackage{filecontents}% Comment out so that "example.tex" is not overwritten
\begin{filecontents*}{example.tex}
Here is some \LaTeX code in an
\emph{external} file.
The input file is not altered in
terms of line breaks, but the
output is properly typeset.
\end{filecontents*}
\documentclass{article}
\usepackage{showexpl}
\usepackage{xcolor}
\lstset{ % General setup for the package
language={[LaTeX]TeX},
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
tabsize=4,
columns=fixed,
showstringspaces=false,
showtabs=false,
keepspaces,
commentstyle=\color{red},
keywordstyle=\color{blue}
}
\begin{document}
Use the environment \verb|LTXexample| to show the code and its output:
\medskip
\begin{LTXexample}[width=0.60\linewidth]
\begin{document}
Welcome to \LaTeX.
\end{document}
\end{LTXexample}
\bigskip
To include code from an external file, use \verb|\LTXinputExample|,
and also applied \verb|pos=r| to have output on right:
\medskip
\LTXinputExample[width=0.5\linewidth,pos=r]{example.tex}
\end{document}
The tcolorbox
provides means for nice typesetting and direct output of listings
LaTeX
code. There are many conceptual and visual configuration possibilities, see the documentation of tcolorbox, e.g. in chapter 9 of the current version 3.12.
However, a \begin{document}....\end{document}
cannot be catched easily. Just relaxing \begin{document}
etc. is no option. The document
environment has to be redefined within a group, such that it's capsuled and does not influence the real outer document
environment. However, this will drop some content defined within a potential \AtBeginDocument
or \AtEndDocument
.
In principle any command allowed only in Preamble will break this example.
\documentclass{article}
\usepackage{listings}
\usepackage{tcolorbox}
\tcbuselibrary{listings}%
\usepackage{xcolor}
\lstset{ % General setup for the package
language={[LaTeX]TeX},
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
tabsize=4,
columns=fixed,
showstringspaces=false,
showtabs=false,
keepspaces,
commentstyle=\color{red},
keywordstyle=\color{blue}
}%
\tcbset{listing engine={listings}}
\begin{document}
% Redefine the document environment within a group
\begingroup
\renewenvironment{document}{%
}{%
}%
\begin{tcblisting}{}
\begin{document}
Welcome to \LaTeX.
\end{document}
\end{tcblisting}
\endgroup
\end{document}