TITLE: Demonstration of DocOnce support for LaTeX code block environments
AUTHOR: Hans Petter Langtangen at Center for Biomedical Computing, Simula Research Laboratory & Department of Informatics, University of Oslo
DATE: today

__Summary.__
This note demonstrates the DocOnce capabilities for generating LaTeX
code for verbatim blocks of computer code. These new capabilities
replaces the need for both the stand-alone program `ptex2tex` and
the simplified `doconce ptex2tex` utility. In fact, the
new capabilities are more flexible than `ptex2tex` and results in
much cleaner LaTeX code (especially for verbatim blocks with
background color).

======= Blocks of computer code in LaTeX =======

===== History =====
label{latexcode:history}

Originally, DocOnce relied on generating code for `ptex2tex` rather than
plain LaTeX, the reason being that `ptex2tex` offered about 40 different
styles for typesetting verbatim blocks of code. The `ptex2tex` utility
relies on a comprehensive configure file for setting the style of every
code environment (`pycod`, `fpro`, `sys`, etc.). A simpler and quicker
alternative, `doconce ptex2tex` was developed later such that DocOnce
was not dependent on the comprehensive `ptex2tex` set up.

In 2015, a new implementation in DocOnce replaced `ptex2tex` and
`doconce ptex2tex`, and can in fact generate LaTeX code directly.
Rather than offering a range of packages for typesetting computer
code, as the `ptex2tex` tool does, the implementation made use of only
three choices: `fancyvrb`, `minted`, or `listing`, but these choices
with all their parameters actually span a much richer way of
typesetting code than what `ptex2tex` offers.

# #ifdef THINK_THIS_IS_OUTDATED
, though not
all[^ptex2tex] popular `ptex2tex` environments are supported in the
new implementation.

[^ptex2tex]: The `ptex2tex` program is not yet made completely
redundant by the new implemention. In fact, there is no exact support for
colored backgrounds with a *thin vertical bar* on the left, to
indicate a complete program, and as specified by, e.g., the `BlueBar`
environment in the `ptex2tex` configuration file.  Two styles in the
new implementation come close: 1) the `blue1` style for `lst` gives
a darker-color rectangular *frame*, and 2) the `vrb-blue1` (or
`pyg-blue1` or `lst-blue1`) style has a darker-color vertical bar,
but for `vrb` and `pyg`
the colored background is then significantly larger than the code.
If `!bbox` is not used in the document, the size of the background is
reduced, but it is not as tight as when a colored `lst` background
(or `BlueBar` in `.ptex2tex.cfg`) is specified.
# #endif

===== Quick overview of the functionality =====
label{latexcode:overview}

When running `doconce format latex mydoc` or `doconce format pdflatex mydoc`,
the command-line argument `--latex_code_style=...` specifies the typesetting
of blocks of computer code. The result of the `doconce format` command
is then a LaTeX file `mydoc.tex`, which can be processed by `latex`,
`pdflatex`, or `xelatex`.

We use the term *code environment* for the DocOnce environments in which
blocks of code are typset. For example, the `pycod` environment is
surrounded by the `!bc pycod` and `!ec` directives. DocOnce supports
a lot of such environments: `pycod` for code snippets in Python, `pypro`
for complete executable Python programs, `fcod` and `fpro` for
snippets and complete programs in Fortran, `cppcod` and `cpppro` for
the C++ counterparts, `mcod` and `mpro` for Matlab, to mention some.

The user can choose between three well-known packages for typesetting
computer code in LaTeX:

 * `vrb`: `fancyvrb` and the `Verbatim` LaTeX environment
 * `pyg`: `minted`, i.e., the Pygments tool, and the `minted` LaTeX environment
 * `lst`: `listingsutf8` and the `lstlisting` LaTeX environment
 * `any`: any environment named `any` from any package

The terms `vrb`, `pyg`, `lst`, and `any` are the terms for these
packages/environments on the command line when running `doconce format`.

In addition, the user can specify a possibly colored background for
the blocks of computer code and also set the parameters in the
various environments. This information can be specified for each
DocOnce code environment (`pycod`, `sys`, etc.) independently, including a
common default choice for the code environments that are not specified.

===== The simplest choice: a single LaTeX environment for all blocks =====
label{latexcode:uniform}

The following command speficies the `Verbatim` (`vrb`)
environment for all code blocks:

!bc sys
Terminal> doconce format pdflatex mydoc --latex_code_style=vrb
!ec
A "DocOnce demo document": "doc.do.txt.html" has been made to illustrate
how the various typesettings look like. The document contains
a data file with the code environment `dat`, a complete executable
Python program in the code environment `pypro`, and a terminal session
in the code environment `sys`. The result of
`--latex_code_style=vrb` gives the most plain and standard way of
typesetting verbatim code blocks in LaTeX, see "the result": "doc_vrb.pdf".
Or more precisely, DocOnce generates a `Verbatim` environment with
several parameters set:

!bc latexcod
\begin{Verbatim}[numbers=none,fontsize=\\fontsize{9pt}{9pt},%
                 baselinestretch=0.95,xleftmargin=2mm]
...
\end{Verbatim}
!ec
This results in slightly smaller font and slightly squeezed lines in
the code block. It matches well running text in 10pt font.

The `xleftmargin=2mm` parameter can be explicitly set to something
else on the command line: `--latex_code_leftmargin=7` (e.g.). The number
is measured in mm. (Using square brackets, as shown below, it can also
be set individually for different code environments.)

===== Using the `minted` (Pygments) tool =====
label{latexcode:pyg}

Replacing `vrb` by `pyg` switches the LaTeX environments to `minted`:

!bc sys
Terminal> doconce format pdflatex mydoc --latex_code_style=pyg
!ec
Now, "the resulting PDF file": "doc_pyg.pdf"
has typesetting of computer code that depends
on the programming language. For example, the Python program leads to

!bc latexcod
\begin{minted}[%
   fontsize=\\fontsize{9pt}{9pt},linenos=false,%
   baselinestretch=1.0,fontfamily=tt,xleftmargin=2mm]{python}
...
\end{minted}
!ec

!bwarning Remember `-shell-escape` when compiling `minted` (Pygments) code!
The `minted` LaTeX environment requires `latex` or `pdflatex` to be
run with the `-shell-escape` option:

!bc sys
Terminal> pdflatex -shell-escape mydoc
!ec
!ewarning

The `minted` style to be used can be
specified by the `--minted_latex_style=` option, e.g.,

!bc sys
Terminal> doconce format pdflatex mydoc --latex_code_style=vrb --minted_latex_style=perldoc
!ec
The `perldoc` choice "changes the colors": "doc_pyg_perldoc.pdf" from
the default (Pygments `default`) "choice": "doc_pyg.pdf" generated previously.

===== Using the `lstlisting` tool =====
label{latexcode:lst}

The third package for typesetting of verbatim blocks of code is
`listingsutf8` and the `lstlisting` LaTeX environment, which in
the following most plain form gives a "look": "doc_lst.pdf" not
much different from the `Verbatim` environment:

!bc sys
Terminal> doconce format pdflatex mydoc --latex_code_style=lst
!ec
The resulting LaTeX code is:

!bc latexcod
\begin{lstlisting}[language=Python,style=simple,xleftmargin=2mm]
...
\end{listlisting}
!ec
However, all possible `lstlisting` options can be set, as will
be shown later.

===== Specifying other packages =====
label{latexcode:any}

Say you have a LaTeX package `compcode` with the environment `ultimate`
that you want to use. This can be specified by

!bc sys
Terminal> doconce format pdflatex mydoc \
          --latex_code_style=ultimate --latex_packages=compcode
!ec
The resulting LaTeX code becomes

!bc latexcod
\begin{ultimate}
...
\end{ultimate}
!ec


===== Adding a colored background =====
label{latexcode:background}

In the previous example, we can add one of the predefined backgrounds
in DocOnce:

!bc sys
doconce format pdflatex doc --latex_code_style=lst-yellow2
!ec
The `yellow2` background is "light yellow": "doc_lst_yellow2.pdf".
For colored backgrounds, one should notice that the `pro` code environments
(as in `pypro`)
for complete executable programs get a 1mm slightly darker bar at the left
side of the code block. This almost invisible color change indicates for
the reader that the code can be copied and run as it stands.
(The `cod` code environments are used for snippets that will not
normally run unless some additional statements is supplied.)

The general specification of a background is `pkg-bg`, where
`pkg` is the package specification (`vrb`, `pyg`, or `lst`) and `bg`
is the DocOnce name of a background:

 * `gray`: light gray
 * `yellowgray`: light yellow, somewhat gray-ish
 * `yellow1`: yellow
 * `yellow2`: light yellow
 * `blue1`: light blue
 * `red1`: light red, somewhat apricot-ish
 * `white`: no background

If you want to tailor the background color, say change the `yellow1`
color to have RGB values (0.95, 0.95, 0.8) rather than (0.98, 0.98, 0.8),
autoedit the `.tex` file with a regular expression:

!bc sys
Terminal> doconce subst 'yellow1\}\{rgb.+' \
          'yellow1{rgb}{0.95, 0.95, 0.8} mydoc.tex
!ec
or just replace the exact text:

!bc sys
Terminal> doconce replace \
          'cbg_yellow1}{rgb}{.98, .98, 0.8}' \
          'cbg_yellow1}{rgb}{.95, .95, 0.8}' mydoc.tex
!ec

# #ifdef TOO_MUCH
## We repeat this several times...
=== Blue backgrounds with a darker bar for complete programs ===

Typical blueish code environments mimicing those in the author's latest
books (e.g., *A Primer on Scientific Programming with Python*) can
be produced by 1) blue background combined with plain verbatim text
(see "PDF": "doc_vrb_style_primer.pdf"),

!bc
"--latex_code_style=default:vrb-blue1@sys:vrb[frame=lines,
label=\\fbox{{\tiny Terminal}},framesep=2.5mm,framerule=0.7pt,
fontsize=\fontsize{9pt}{9pt}]"
!ec
(without the linebreaks!)
or 2) blue background combined with the listings package,

!bc
"--latex_code_style=default:lst[style=blue1]@
pypro:lst[style=blue1bar]@dat:lst[style=gray]@
sys:vrb[frame=lines,label=\\fbox{{\tiny Terminal}},
framesep=2.5mm,framerule=0.7pt,fontsize=\fontsize{9pt}{9pt}]"
!ec
(without the linebreaks!).

For the `vrb/pyg/list-backgroundcolor` styles,
more vertical space before and after the code can be added to the
background with the `--latex_code_bg_vpad` option, as
in this "vrb-blue1 demo": "doc_vrb_style_primer_vpad.pdf"
or this "pyg-blue1 demo": "doc_pyg_style_primer_vpad.pdf". The latter
used

!bc
"--latex_code_style=default:pyg-blue1@dat:lst[style=gray]@
sys:vrb[frame=lines,label=\\fbox{{\tiny Terminal}},
framesep=2.5mm,framerule=0.7pt,fontsize=\fontsize{9pt}{9pt}]"
!ec
(without the linebreaks!).

Notice that the complete program, which can be run as is, applies
a darker blue bar to the left (`vrb`, `pyg`) while `lst` has a
darker frame. This graphical element is used to help readers distinguish
between a complete program (`!bc pypro`) and a program snippet
(`!bc pycod`).
# #endif


===== Setting LaTeX environment parameters =====
label{latexcode:latex:prms}

It is easy to specify parameters to the `lstlisting` or the two
other LaTeX environments:

!bc sys
Terminal> doconce format pdflatex doc \
"--latex_code_style=lst-yellow2[numbers=left,
numberstyle=\\tiny,numbersep=15pt,breaklines=true]"
!ec
(but no linebreaks in the `--latex_code_style` command!).
These parameters specify "line numbers in the code blocks": "doc_lst_yellow2_linenos.pdf" as well as wrapping of too long lines (`breaklines=true`).
*Note that any backslash in LaTeX command must be a
double backslash* on the command line!

Here is an example where we use the fictitious code enviroment `ultimate`
from the package `compcode` with a yellow backgrund and with some
environment parameters `arg1` and `arg2`:

!bc sys
Terminal> doconce format pdflatex mydoc --latex_packages=compcode \
         '--latex_code_style=ultimate-yellow2[arg1=val1,arg2=val2]'
!ec
The resulting LaTeX code becomes

!bc latexcod
\begin{cod}{cbg_yellow2}\begin{ultimate}[arg1=val1,arg2=val2]
...
\end{ultimate}\end{cod}
!ec
In this way, you can use any environment in any package for typesetting
code.

===== Specifying individual code environments =====
label{latexcode:nonuniform}

The colored background might be appropriate for computer code in the
previous example, but maybe not so appropriate for the terminal
session. Let us typeset the terminal session using the `Verbatim`
environment, but rely on `lst` without line numbers as above for the
other code environments:

!bc sys
Terminal> doconce format pdflatex doc \
          "--latex_code_style=default:lst-yellow2@sys:vrb"
!ec
That is, we specify  the default choice (`default`) and the `sys`
environment. The specifications are separated by `@`. One can
add parameters to the LaTeX environments, e.g.,

!bc sys
Terminal> doconce format pdflatex doc \
  "--latex_code_style=default:lst-yellow2[numbers=left]@sys:vrb"
!ec
Here is a more fancy typesetting of `sys` environments with lines
above and below and a title `Terminal` inside a box:

!bc sys
Terminal> doconce format pdflatex doc \
"--latex_code_style=default:lst-yellow2@
sys:vrb[frame=lines,label=\\fbox{{\\tiny Terminal}},framesep=2.5mm,
framerule=0.7pt,fontsize=\fontsize{9pt}{9pt}]"
!ec
(with no linebreaks though!).
"Here is the result": "doc_lst_sys.pdf".

===== Specifying the `lst` style =====
label{latexcode:lst:style}

DocOnce comes with some predefined styles for the `lstlisting` LaTeX
environment:

 * `simple` for no coloring of code (plain verbatim style)
 * `redblue` for coloring of code dominated by red and blue
 * `greenblue` for coloring of code dominated by green and blue
 * `gray` for a framed gray background and no code coloring
 * `graycolor` for a framed gray background and green comments, pink keywords,
   red strings, and orange variables
 * `blue1` for a light blue/cyan background with no code coloring
 * `blue1bar` for a light blue/cyan background with a darker think frame
   and with no code coloring
 * `blue1_bluegreen` colored code with blue background (combination of
   `blue1` background and `bluegreen` syntax coloring)
 * `blue1bar_bluegreen` colored code with blue background and darker
    frame (combination of
   `blue1bar` background and `bluegreen` syntax coloring)
 * `yellow2_fb` for a framed yellow (`yellow2`) background and
   green comments, blue keywords, red strings, and orange variables
   (the style from the FEniCS book)
   of code *and* a background color equal to `yellow2`

The styles with a colored background (`yellow2_fb`, `gray`, `graycolor`,
`blue1`)
should of course not be combined with another colored background
(skip `backgroundcolor` specification or set it to `white`).

The user can also define any number of additional styles and put them
in a file, say `.mylststyles`, and give them to `doconce format` through
the command-line option `--latex_code_lststyles=.mylststyles`.
Just include `\lstdefinestyle{name}{...}` commands in the file.

Here is an example of specifying the `yellow2_fb` style with yellow
background, coloring of code, and a frame around all code blocks
(as made famous in the "FEniCS book": "http://goo.gl/myz5yp"):

!bc sys
Terminal> doconce format pdflatex doc \
  "--latex_code_style=default:lst[style=yellow2_fb]"
!ec
You may check out the "corresponding result": "doc_lst_style_fenicsbook.pdf".

Blue background and plain verbatim non-colored code (as made
famous in the "Python Primer on Scientific Programming book":
"http://goo.gl/OKDAzs") results from

!bc sys
Terminal> doconce format pdflatex doc \
"--latex_code_style=default:lst[style=blue1]@
pypro:lst[style=blue1bar]@dat:lst[style=gray]@
sys:vrb[frame=lines,label=\\fbox{{\tiny Terminal}},
framesep=2.5mm,framerule=0.7pt,fontsize=\fontsize{9pt}{9pt}]"
!ec
(but no linebreaks as here).
Note that this style does not offer the thin vertical darker-colored bar
for `pypro` enviroments (indicating complete programs) as
`ptex2tex` offers through the `BlueBar` environment. Instead, there is a
"darker-colored top+bottom frame":
"doc_lst_styleprimer.pdf" around `pypro` code specifications.
(The old vertical bar is enabled by a `pypro:vrb-blue1` specification, but then
with a colored background that is significantly larger than the computer code
block.)

The 5th edition of the mention ``Primer book'' features syntax highlighting,
offered by the `blue1_bluegreen` and `blue1bar_bluegreen` styles:

!bc sys
Terminal> doconce format pdflatex doc \
"--latex_code_style=default:lst[style=blue1_bluegreen]@
pypro:lst[style=blue1bar_bluegreen]@dat:lst[style=gray]@
sys:vrb[frame=lines,label=\\fbox{{\tiny Terminal}},
framesep=2.5mm,framerule=0.7pt,fontsize=\fontsize{9pt}{9pt}]"
!ec
(but no linebreaks as here). Look at "the result": "doc_lst_style_primer5.pdf".

===== General syntax for `--latex_code_style=` =====
label{latexcode:syntax}

The `--latex_code_style=` option can take a set of code environment
specifications separated by `@`. Each specification is of the form
`envir:pgk-bg[prms]`,
where `envir` is the code environment name (`pypro`, `sys`, etc., or `default`),
`pkg` is the package name (`vrb`, `pyg`, `lst`), `bg` is
the DocOnce name of a potential background (can be omitted), and
`prms` is a list of parameters for the LaTeX environment.

As an example, we may specify a default typesetting with `lst` and the `blue1`
background, using the `greenblue` style and numbering of lines;
then we let the `dat` environment be typeset with the `Verbatim`
environment with a light gray background; and finally we let `sys` also use
`Verbatim`, but with many parameters for more fancy layout. The
value of `--latex_code_style=` is then (split over several lines for
increased readability - it must be one line as a terminal command!):

!bc
"--latex_code_style=default:lst-blue1[style=greenblue,
numbers=left,numberstyle=\\tiny,stepnumber=3,
numbersep=15pt,xleftmargin=1mm]@dat:vrb-gray@
sys:vrb[frame=lines,label=\\fbox{{\\tiny Terminal}},
framesep=2.5mm,framerule=0.7pt,fontsize=\fontsize{9pt}{9pt}]"
!ec
Here is the "result": "doc_lots.pdf" of this detailed specification.

!bnotice Size of colored background
The default colored background, as specified by (e.g.) `vrb-blue`,
is significantly larger than the
verbatim text. The surrounding space can be reduced by setting
`\fboxsep` to a negative value,
see the line right before the definition of the `cod`
environment in the `.tex` file. However, if a `!bbox` is used in
the document, `\fboxsep` cannot be set to a negative value without
destroying those boxes. If one really wants the colored background
to be about as large as the text, there is at present two options:

 o use `lst` with a style (`gray`, `yellow2_fb`, `blue1`)
 o use `ptex2tex` with the `Blue` and similar environments in the
   `.ptex2tex.cfg` file.

The results are very similar so there is no demand for `ptex2tex`.
!enotice

===== Using different code styles inside admonitions =====

Sometimes the use of colored background for code does not look right
inside admonitions -- you may want something less eye catching.
DocOnce has support for providing an alternative
environment, say `pycod2` for `pycod`, inside admons.
See the DocOnce manual and the section called
*Typesetting of solutions to exercises* for a detailed case
how this can be done.

===== Wrapping code environments with user-customized environments =====
label{latexcode:userdef}

Suppose you want to typeset your code with an environment that is not
supported by DocOnce. For example, we want in LaTeX to have headline
before each code snippet with a section-based counter, the filename
and some title for the code. Then we want double lines before and
after the code snippet:

FIGURE: [fig/userdef_code_envir, width=500 frac=0.7]

This is fairly easy: we define a *user-defined environment* in
DocOnce, here called `code` and provide a Python module that translates
this environment into proper format-specific code.
Details are provided in the DocOnce manual, see the section
"User-Defined Environments": "http://hplgit.github.io/doconce/doc/pub/manual/html/manual.html#user-defined-environments". In the present case,
the syntax in a DocOnce file is to wrap every `@@@CODE` line or
`!bc` environment in a `!bu-code` and `!eu-code` environment. The
code in the figure above is produced by

!bc do
|bu-code file=process.f Return `a` multiplied by `c`
|bc fcod
       subroutine process(a, n, c, r)
C      Return array r = c*a
       integer n
       real*8 a(n), c, r(n)
       integer i
       do i = 1,n
          r(i) = c*a(i)
       end do
       return
       end
|ec
|eu-code
!ec

The LaTX code we want is

!bc latexcod
\begin{pycode}

\Verb!process.f!:
Return a multiplied by \Verb!c!

\hrule
\vspace{1mm}
\hrule

\begin{lstlisting}[language=Fortran,style=simple,xleftmargin=2mm]
       subroutine process(a, n, c, r)
C      Return array r = c*a
       integer n
       real*8 a(n), c, r(n)
       integer i
       do i = 1,n
          r(i) = c*a(i)
       end do
       return
       end
\end{lstlisting}

\hrule
\vspace{1mm}
\hrule
\end{pycode}
!ec
We have created a special LaTeX environment
(``theorem'') called
`pycode` that LaTeX will give a section-based
number (just like theorems, examples, etc).

To this end, we must write a file `userdef_environments.py`
where we define the `code` environment for LaTeX and
other formats (usually some tailored LaTeX code and just some reasonable
common DocOnce code for other formats). The `userdef_environments.py`
file looks like this in the current example:

@@@CODE userdef_environments.py
We grab information on
the `!bu-code` line for a potential filename, label, and header for
the code snippet.

When compiling to `pdflatex`, we simply use `--latex_code_style=lst`,
but we could use more fancy styles if desired.
You can inspect the "PDF file": "doc_udef.pdf" for this example with
a tailored, user-defined code environment.
