39

When documenting a style file, it would be nice to be able to easily put side by side different examples of code, side-by-side with the output they produce.

What recommendations to people have to do this efficiently, and æsthetically?

5
  • I think it has been asked by others. See this solution: tex.stackexchange.com/questions/4095/… May 28, 2011 at 16:50
  • 2
    @xport: that's a question about just showing the source-code. Mine is somewhat more precise in that it requires side-by-side displaying of LaTeX code, and Seamus' answer happens to suggest the same tool as the answer you've linked to. May 28, 2011 at 17:01
  • @xport: That question is not a duplicate, but I see that your answer is relevant here. However, DTX files must be handled different here because of there special handling of %. These must first be removed from the start of the code lines, but remaining ones must be handled as comments again when processing the output... May 28, 2011 at 17:05
  • Also related: Any way to show LaTeX example code and execute it? Apr 23, 2013 at 20:17
  • See CTAN topic macro-demo for a list of all alternatives offering that functionality.
    – koppor
    May 9, 2020 at 11:21

6 Answers 6

22

There's showexpl which has the LTXexample environment for exactly this purpose. It's based on listings

11
  • I was going to answer recommending the same package; while I was designing a little example you beat me! May 28, 2011 at 16:29
  • 1
    I tried to use showexpl quite a while ago for my DTX files and it had issues with the special handling of % in these files. I can't remember the exact details now, but I gave up on it and coded something by myself as part of my ydoc class (which is still an unstable alpha version). May 28, 2011 at 16:55
  • @Martin I've only ever used it in normal .tex files, not in .dtx files, and I've not encountered any (serious) problems. If you could add an answer about ydoc I'm sure people would be interested in it.
    – Seamus
    May 28, 2011 at 17:01
  • 2
    @Gonzalo For these "low-hanging fruit" questions you need to be quick on the draw... Heh. You beat me to the sections/chapter headings one, so I guess we're even...
    – Seamus
    May 28, 2011 at 17:02
  • @Seamus: The issue is that ydoc is not really finished yet and has almost no documentation. I didn't do much on that part of the code for over a year and have issues recalling its current state. ;-) May 28, 2011 at 17:03
39

My package tcolorbox provides another possible answer for the question. It allows to place the source code before or after the output. With version 2.20, source and output can be set side-by-side. The output can be placed inside a colored box or outside, before the source or after the source.

\documentclass{article}

\usepackage[skins,listings]{tcolorbox}

\newtcblisting{exampleA}[2][]{%
  colframe=red!50!yellow!50!black,
  colback=red!50!yellow!5!white,
  coltitle=red!50!yellow!3!white,
  bicolor,colbacklower=white,
  fonttitle=\sffamily\bfseries,
  sidebyside,
  title=#2,#1}

\newtcblisting{exampleB}[2][]{%
  colframe=red!50!yellow!50!black,
  colback=white,
  coltitle=red!50!yellow!3!white,
  bicolor,colbacklower=red!50!yellow!5!white,
  fonttitle=\sffamily\bfseries,
  sidebyside,text and listing,
  title=#2,#1}

\begin{document}

\begin{exampleA}[righthand width=3.5cm,center lower]{Side-by-side (inside box)}
\begin{tikzpicture}
\path[fill=yellow!50!white] (0,0) circle (11mm);
\path[fill=white] (0,0) circle (9mm);
\foreach \w/\c in {90/red,210/green,330/blue}
{\path[shading=ball,ball color=\c] (\w:1cm) circle (7mm);}
\end{tikzpicture}
\end{exampleA}

\begin{exampleA}[righthand width=3.5cm,listing outside text]{Side-by-side (outside box)}
\begin{tikzpicture}
\path[fill=yellow!50!white] (0,0) circle (11mm);
\path[fill=white] (0,0) circle (9mm);
\foreach \w/\c in {90/red,210/green,330/blue}
{\path[shading=ball,ball color=\c] (\w:1cm) circle (7mm);}
\end{tikzpicture}
\end{exampleA}

\begin{exampleB}[lefthand width=3.5cm]{}
\begin{tikzpicture}
\path[fill=yellow!50!white] (0,0) circle (11mm);
\path[fill=white] (0,0) circle (9mm);
\foreach \w/\c in {90/red,210/green,330/blue}
{\path[shading=ball,ball color=\c] (\w:1cm) circle (7mm);}
\end{tikzpicture}
\end{exampleB}

\begin{exampleB}[lefthand width=3.5cm,text outside listing,
  colback=red!50!yellow!5!white,top=0mm,bottom=0mm,left=0mm,right=0mm,
  arc=0mm,boxrule=1pt,watermark text=Source,
  watermark color=yellow!75!red!30!white]{}
\begin{tikzpicture}
\path[fill=yellow!50!white] (0,0) circle (11mm);
\path[fill=white] (0,0) circle (9mm);
\foreach \w/\c in {90/red,210/green,330/blue}
{\path[shading=ball,ball color=\c] (\w:1cm) circle (7mm);}
\end{tikzpicture}
\end{exampleB}

\end{document}

enter image description here

3
  • I just tried this approach. It is magnificent! Whereas some of the other methods choke on my code (probably because I do internal catcode changes), yours sails right through. And I like how it auto-wraps as well. Wish I could upvote more than once! Jul 25, 2019 at 17:16
  • @Thomas F. Sturm: what does title=#2,#1 stand for?. If I want to use only one style, how the command \newtcblisting{exampleA}[2][] needs to be modified?
    – user149418
    Aug 8, 2019 at 18:17
  • @user149418 title=#2,#1 stands for setting the title to the mandatory parameter #2 and adding further options from the optional parameter #1. If no title and no further options are needed, use \newtcblisting{exampleA}{colframe=... Sep 10, 2019 at 11:16
28

I made a package tkzexample that I use for all my documentation. I upload yesterday on ctan a new version (you need to wait several days before see it) but without documentation actually ( I have a little work to do to finish the doc. The main macro is based on the \codeexampleof T. Tantau. Till gave me permission to use and modify the macro. \codeexample don't work with accents and utf8 but tkzexample accepts accents and utf8. I add the possibility to num the lines and I created an option to save the example on an extern file with \usepackage[saved]{tkzexample}.

\documentclass[]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}   
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{tikz}
\usepackage{amsmath,amssymb,booktabs}
\usepackage[frenchb]{babel}
\usepackage{tkzexample} 
% possible \usepackage[saved]{tkzexample} permet de sauvegarder l'exemple
\usepackage[protrusion = true,
            expansion, final,
            verbose = false, babel   = true]{microtype}
\DisableLigatures{encoding = T1, family = tt*}  

\parindent=0pt

\begin{document}

\colorlet{graphicbackground}{blue!10!white}%
\colorlet{codebackground}{red!10}%  
1) How to use

 \begin{tkzltxexample}[]
\documentclass{scrartcl}
\usepackage{tkzexample}
\begin{document}     
\begin{tkzexample}[]
\begin{tikzpicture}
    \path coordinate (A) at (0,0)
          coordinate (B) at (-60:12cm)
          coordinate (C) at (240:12cm);
\foreach \density in {20,30,...,160}{%
    \draw[fill=MidnightBlue!\density] (A)--(B)--(C)--cycle;
    \path (A) coordinate (X) -- (B) coordinate[pos=.15](A)
          -- (C) coordinate[pos=.15](B) -- (X) coordinate[pos=.15](C);}
\end{tikzpicture}  
\end{tkzexample}
\end{document}  
\end{tkzltxexample} 

2) Usage classique

\begin{tkzexample}[latex=6cm]
\begin{tikzpicture}[scale=.5]
    \path coordinate (A) at (0,0)
          coordinate (B) at (-60:12cm)
          coordinate (C) at (240:12cm);
    \foreach \density in {20,30,...,160}{%
        \draw[fill=MidnightBlue!\density] 
             (A)--(B)--(C)--cycle;
        \path (A) coordinate (X)
           -- (B) coordinate[pos=.15](A)
           -- (C) coordinate[pos=.15](B)
           -- (X) coordinate[pos=.15](C);
    }
\end{tikzpicture}  
\end{tkzexample}
3) Un tableau
\begin{tkzexample}[width=6cm,frame tex=Maroon,frame code=Maroon,num ]
\begin{tabular}{ll}
\toprule  
Essai avec un tabeau  &\\
\midrule
Un premier &   texte\\
Un second & texte\\
\bottomrule
\end{tabular}
\end{tkzexample} 

4) Les accents en français
\begin{tkzexample}[small,num]
\begin{tikzpicture}
    \node[draw] {éè§çà};
\end{tikzpicture}
\end{tkzexample} 
\end{document} 

enter image description here

3
  • I shall have to check it out. Nice eye-candy! Jun 5, 2011 at 15:41
  • Thanks!. I will put on my site the new version this week and a beta version of the documentation. The version on ctan will arrive in several days because I uploaded a lot of stuff. Jun 5, 2011 at 17:22
  • @Niel The announcement is not done yet but the new version in on CTAN. The collection tkz is also on CTAN and on TeXLive 2011. TL 2010 is now frozen so you need to install the package by hand Otherwise you'll wait for the TL2011 ( the beginning of July) Jun 7, 2011 at 15:20
12

For normal documents the showexpl package would be the way to go, as Seamus already stated in his answer. However, special care must be taken for DTX files because of the special handling of % in them.

I wrote some own code for the my ydoc bundle. The ydoc-expl package of this bundle provides an example float where the actual code is wrapped into examplecode. You can add a caption and also display a list of examples. It uses listings and float for this. You can use \lstset{...} to modify its display. Its sets the compiled output on the left or top and the code on the right or bottom depending on the amount of horizontal space both require.

Note that ydoc is still an alpha version and under development. Things might change in future revisions and there a still a few bugs in it.

You can use the ydoc class instead of ltxdoc or just load the ydoc-expl package.

% \iffalse meta-comment
%
% Copyright (C) 2009 by Martin Scharrer <[email protected]>
% -----------------------------------------------------------------
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3c
% of this license or (at your option) any later version.
% The latest version of this license is in
%
%   http://www.latex-project.org/lppl.txt
%
% and version 1.3c or later is part of all distributions of LaTeX
% version 2008/05/04 or later.
%
% This work has the LPPL maintenance status `maintained'.
%
% The Current Maintainer of this work is Martin Scharrer.
%
% This work consists of the files j.dtx, j.ins
% and the derived file j.sty.
%
% \fi
%
% \iffalse
%<*driver>
\documentclass{ltxdoc}
\usepackage{ydoc-expl}
%\documentclass{ydoc}

\usepackage{tikz}

\EnableCrossrefs
%\CodelineIndex
\RecordChanges
%\OnlyDescription
\begin{document}
  \DocInput{\jobname.dtx}
  \PrintChanges
  %\newpage\PrintIndex
\end{document}
%</driver>
% \fi
%
% {Titlepage ..}
% \listof{example}{List of Examples}
%
% \section{Usage}
% \begin{example}
%    \begin{examplecode}
%       \begin{tikzpicture}
%           \draw (2.5,2.5) circle (2cm);
%           \draw (0,0) -- (5,5);
%       \end{tikzpicture}
%    \end{examplecode}
%    \caption{Some example}
% \end{example}
%
% \StopEventually{}
% \iffalse
%<*package>
% \fi
%
% \section{Implementation}
% \subsection{Package Header}
%
% \begin{macro}{\mymacro}
%    \begin{macrocode}
\def\mymacro{%
}
%    \end{macrocode}
% \end{macro}
%
% \Finale
%</package>

Result

11

There are several packages for this purpose:

  • fvrb-ex, based on fancyvrb, contributed with fancyvrb together.
  • lstdoc, part of listings package, used by document of listings itself.
  • examplep, based on listings.
  • showexpl, based on listings.
  • sverb, provides demo environment.

And Martin may explain ydoc himself.

4
  • 2
    Nice list, but again: DTX files are more tricky then normal documents and these packages might not handle them correctly. May 28, 2011 at 17:07
  • In my own document, I also wrote some macros using verbatim package for myself. (I didn't know these packages that time.) It seems the function is implemented time and time again.
    – Leo Liu
    May 28, 2011 at 17:13
  • 1
    @Martin: At least lstdoc.sty works fine in DTX files. It is used in listings.dtx. However, it is not well documented.
    – Leo Liu
    May 28, 2011 at 17:18
  • It seems OK to use fvrb-ex (used in fvrb-ex.dtx) and sverb (used in sverb.dtx) in DTX files too.
    – Leo Liu
    May 28, 2011 at 17:38
4

For documenting my own packages I wrote a custom class cnltx-doc which comes bundled with a package called cnltx-example:

\usepackage{cnltx-example}

or

\usepackage[example]{cnltx}

It provides an environment {example} which can display code and output side by side (for which there's also the {sidebyside} environment)) or above each other or only the code (for which there's also the {sourcecode} environment).

It allows for compiling the example as separate document if needed (with the engine of choice) – this needs shell-escape enabled at least for the first compilation, of course.

The package comes with predefined styles for LaTeX, BibTeX and makeindex listings. Output (colors, frames…) can be customized.

Behind the scenes the listings package is used.

\documentclass{article}

\usepackage{cnltx-example}
\setcnltx{
  add-cmds = {foo}
}

\begin{document}

\begin{example}
  This is a \LaTeX\ example.

  \newcommand*\foo{foo}

  Some inline math $x^2$ and some display math:
  \begin{equation}
    x^2 + y^2 = z^2
  \end{equation}
\end{example}

\begin{example}[side-by-side]
  This is a \LaTeX\ example.

  \newcommand*\foo{foo}

  Some inline math $x^2$ and some display math:
  \begin{equation}
    x^2 + y^2 = z^2
  \end{equation}
\end{example}

\begin{example}[side-by-side,code-left=false]
  This is a \LaTeX\ example.

  \newcommand*\foo{foo}

  Some inline math $x^2$ and some display math:
  \begin{equation}
    x^2 + y^2 = z^2
  \end{equation}
\end{example}

\newpage

\begin{example}[compile,graphics={trim={2cm 22cm 2cm 2cm},clip}]
  \documentclass{article}
  \begin{document}

  This is a \LaTeX\ example.

  \newcommand*\foo{foo}

  Some inline math $x^2$ and some display math:
  \begin{equation}
    x^2 + y^2 = z^2
  \end{equation}

  \end{document}
\end{example}

\end{document}

enter image description here

enter image description here

3
  • 1
    See also tex.stackexchange.com/a/209600/5049 (which I had forgotten about)
    – cgnieder
    Feb 7, 2017 at 14:11
  • In the second example, if we want to comment the option for a while, the first line of the code is removed. Try \begin{example}%[side-by-side].
    – Sigur
    Nov 12, 2018 at 23:45
  • @Sigur yes, commenting on the first line is not allowed IIRC
    – cgnieder
    Nov 13, 2018 at 9:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .