TITLE: DocOnce Description
AUTHOR: Hans Petter Langtangen {copyright} at Center for Biomedical Computing, Simula Research Laboratory & Department of Informatics, University of Oslo
AUTHOR: Kristian Gregorius Hustad {copyright} at Centre for Computing in Science Education, University of Oslo & Department of Informatics, University of Oslo
DATE: today


# lines beginning with # are doconce comment lines
# (documents can also have mako comment lines)

!bwarning
Some parts of this manual may be outdated. Please create an issue at URL: "https://github.com/hplgit/doconce" to report errors.
!ewarning

======= What Is DocOnce? =======
label{what:is:doconce}
idx{doconce}

# #include "../tutorial/_what_is.do.txt"

# #if FORMAT not in ("latex", "pdflatex")
## This figure does not work well with pdflatex

DocOnce has been used as writing platform for several books:

FIGURE: [fig/doconce_books, width=600 frac=0.8]

# #endif

!split
TOC: on

#
# Here are some comment lines that do not affect any formatting
# these lines are converted to comments in the output format.
# This may have some side effects, especially in rst and sphinx
# where lines following the comment may be taken as part of
# the comment if there are no blank lines after the comment.
#
# One can use ## and the mako preprocessor to remove comments
# *before* doconce sees the text. That can be useful when
# doconce comments interferes with formatting.
# The mako tool also supports <%doc> .. </%doc>
#

!split
===== Demos and Documentation =====

idx{demos}

!bwarning This guide is for the experienced DocOnce writer!
Do not read the detailed descriptions of DocOnce syntax that follows
(this is a manual!) before you have read the tutorial and played
a little around with a simple document.
!ewarning


The primary demo for what can be achieved as output from DocOnce documents
regards a little "scientific report": "http://hplgit.github.io/teamods/writing_reports/_static/report/do.txt.html" that is compiled to
a "range of various output documents": "http://hplgit.github.io/teamods/writing_reports/index.html". A version of that web page contains the specific
compilation commands to create each of the output demonstrations.

There is also a demo on the many different ways one can "create slides":
"http://hplgit.github.io/doconce/doc/pub/slides/demo/index.html".

!bwarning Write DocOnce documents in a text editor with monospace font!
Some DocOnce constructions are sensitive to whitespace (indentation in
lists is a primary example), so you *must* use a text editor with
monospace font (also known as verbatim text). Never use fonts like
Arial or Helvetica.
(Other popular markup languages such as Sphinx and Markdown are also
sensitive to whitespace and require a monospace font in the text editor.)
!ewarning

!bnotice Tip: Read the FAQ!
A lot of tips and problems have over the years been collected in the
Troubleshooting and FAQ document, available in
"Sphinx": "http://hplgit.github.io/doconce/doc/pub/trouble/html/index.html",
"HTML": "http://hplgit.github.io/doconce/doc/pub/trouble/trouble.html", and
"PDF": "http://hplgit.github.io/doconce/doc/pub/trouble/trouble.pdf".
The FAQ and this manual are the two key references for how to make use
of DocOnce.
!enotice

## setup4books-doconce, all the books?

The DocOnce tutorial (available in
"Sphinx": "http://hplgit.github.io/doconce/doc/pub/tutorial/html/index.html",
"HTML": "http://hplgit.github.io/doconce/doc/pub/tutorial/tutorial.html", and
"PDF": "http://hplgit.github.io/doconce/doc/pub/tutorial/tutorial.pdf" formats)
has its source code in the GitHub repository for
DocOnce, more precisely in the file

!bc
doc/src/tutorial/tutorial.do.txt
!ec
One can compare this source with the output in
"HTML": "http://hplgit.github.io/doconce/doc/pub/tutorial/tutorial.html",
"Sphinx": "http://hplgit.github.io/doconce/doc/pub/tutorial/html/index.html",
and
"PDF": "http://hplgit.github.io/doconce/doc/pub/tutorial/tutorial.pdf".
The `make.sh` script in the same directory
tells in detail how the various versions were compiled.

The DocOnce source of the current manual is also found at the GitHub repository
for DocOnce, in the file

!bc
doc/src/manual/manual.do.txt
!ec
You can compare this source with the available output in
"HTML": "http://hplgit.github.io/doconce/doc/pub/manual/manual.html",
"Sphinx": "http://hplgit.github.io/doconce/doc/pub/manual/html/index.html",
and
"PDF": "http://hplgit.github.io/doconce/doc/pub/manual/manual.pdf".



!split
======= Markup Based on Special Lines =======

The DocOnce markup language has a concept called *special lines*.
Such lines starts with a markup at the very beginning of the
line and are used to mark document title, authors, date,
sections, subsections, paragraphs, figures, movies, lists, etc.


===== Heading with title and author(s) =====

idx{`TITLE` keyword} idx{`AUTHOR` keyword} idx{`DATE` keyword}
idx{author!email}
idx{author!institution}

# Note: AUTHOR: must here be indented one space to avoid
# interpretation as author

Lines starting with `TITLE:`, `AUTHOR:`, and `DATE:` are optional and used
to identify a title of the document, the authors, and the date. The
title is treated as the rest of the line, so is the date, but the
author text consists of the name and associated institution(s) with
the syntax
!bc
 AUTHOR: name at institution1 & institution2 & institution3
!ec
The `at` with surrounding spaces
is essential for adding information about institution(s)
to the author name, and the `and` with surrounding spaces is
essential as delimiter between different institutions.
An email address can optionally be included, using the syntax
!bc
 AUTHOR: name Email: somename@site.net at institution1 & institution2
!ec
Multiple authors require multiple `AUTHOR:` lines. All information
associated with `TITLE:` and `AUTHOR:` keywords must appear on a single
line.  Here is an example:

!bc do
 TITLE: On an Ultimate Markup Language
 AUTHOR: H. P. Langtangen at Center for Biomedical Computing, Simula Research Laboratory & Dept. of Informatics, Univ. of Oslo
 AUTHOR: Kaare Dump Email: dump@cyb.space.com at Segfault, Cyberspace Inc.
 AUTHOR: A. Dummy Author
 DATE: November 9, 2016
!ec
Note how one can specify a single institution, multiple institutions
(with `&` as separator between institutions),
and no institution. In some formats (including `rst` and `sphinx`)
only the author names appear. Some formats have
``intelligence'' in listing authors and institutions, e.g., the plain text
format:

!bc
Hans Petter Langtangen [1, 2]
Kaare Dump  (dump@cyb.space.com) [3]
A. Dummy Author

[1] Center for Biomedical Computing, Simula Research Laboratory
[2] Department of Informatics, University of Oslo
[3] Segfault, Cyberspace Inc.
!ec
Similar typesetting is done for LaTeX and HTML formats.

The current date can be specified as `today`.

===== Copyright =====
label{copyright}

idx{copyright syntax}

A copyright notice can be given as part of the `AUTHOR:` command.
The syntax is

!bc
{copyright,year1-year2|license}
!ec
where `year1-year2` represents the year(s) and `license` represents
the type of license (e.g., Creative Commons license) if that apply.
The year and license parts can be left out. In that case, the current
year is used, and no license appears.
Note that *the year and the license must be identical in all copyright
specifications* for all authors who claim copyright!
(Otherwise, an error message is issued.)
The `{copyright...}` specification can appear after the author's name
(and email address) and/or after an organization's name (see examples below).

The syntax of the `year1-year` part goes as follows:

 * A single year: `2012`.
 * A range: `2006-2010`. Up to the current year is specified by `2005-present`. Any attempt to use an upper limit into the future will be replaced by `present`, e.g., `2001-2100` becomes `2001-present`.
 * A single year: `date`, which fetches the year from the `DATE:` field in the DocOnce document.

The syntax of the `license` part is flexible:

 * Any formulation can be given. For example, <linebreak>
   `{copyright|This work is released under an MIT license}`.
 * Standardized short forms for Creative Commons (CC) licenses are available.
   For example, `CC BY`, which means a CC Attribution license. `BY` can be replaced by `BY-NC` (Attribution-NonCommercial) and other abbreviations from URL: "https://creativecommons.org/licenses/". The command-line option `--CC_license=` is used to provide a template for embedding the spelled out name of the abbreviated CC license. By default this template reads `Released under a CC %s 4.0 license`, where `%s` is to be replaced by the license name. A common value is <linebreak>
   `--CC_license="This work is released under the Creative Commons %s 4.0 license"`.

How the copyright is typeset depends on the format:

 * LaTeX: The copyright appears as a footer on all pages (typeset with
   the `\fancyfoot[C]` command from the `fancyhdr` package).
   The command-line option `--latex_copyright=titlepages` leads to a copyright
   statement in the footer of the titlepage and (for books) the first page
   of each chapter.
 * Sphinx: The copyright is provided as the `copyright` variable in `conf.py`
   and appears in the footer according to the chosen theme.
 * HTML: The copyright appears at the bottom of all pages (right before the `</body> tag`).
 * Other formats: A copyright line is inserted after the date.

Here are some examples on specifying copyright.

!bc
 AUTHOR: Joe Doe Email:joe.doe@somemail.com {copyright}
 AUTHOR: Jane Doe {copyright}
!ec
Output becomes ``Copyright 2015, Joe Doe, Jane Doe'' (if the present year
is 2015).

!bc
 AUTHOR: Joe Doe {copyright,2001-present}
!ec
Output becomes ``Copyright 2001-2015, Joe Doe'' (if the present year
is 2015).

!bc
 AUTHOR: Joe Doe {copyright,2001-2010|CC BY}
 AUTHOR: Jane Doe Email:jd@kk.org {copyright,2001-2010|CC BY}
!ec
Output becomes ``Copyright 2001-2010, Joe Doe, Jane Doe. Released under CC Attribution 4.0 license''. One can provide the option `<linebreak>
--CC_license="This work is released under the Creative Commons %s 4.0 license."`, and the output
becomes ``Copyright 2001-2010, Joe Doe, Jane Doe. This work is released under the Creative Commons Attribution 4.0 license.''

!bc
 AUTHOR: Joe Doe {copyright} at Digital Company {copyright}
 AUTHOR: Jane Doe
!ec
In this case, an author and an institution (but not the second author) hold
the copyright. The output is typically ``Copyright 2015, Joe Doe, Digital Company''. Below, two institutions but no authors hold the copyright:

!bc
 AUTHOR: Joe Doe at Digital Company {copyright,2015|CC BY}
 AUTHOR: Jane Doe at Analog Company {copyright,2015|CC BY}
!ec
The output becomes ``Copyright 2015, Digital Company, Analog Company. Released under CC Attribution 4.0 license''.



===== Table of contents =====

idx{`TOC` keyword}
idx{table of contents}
idx{toc depth}

A table of contents can be generated by the line

!bc do
TOC: on
!ec
This line is usually placed after the `DATE:` line.
The value `off` turns off the table of contents.

The depth of the table of contents is dictated by the command-line
option `--toc_depth=`, which is 2 by default, meaning that sections and
subsections are included, but not subsubsections.
When making Sphinx documents, `toc_depth=` is a command-line option for
for the `doconce sphinx_dir` command (and not `doconce format`).

!split
===== Section headings =====
idx{headlines} idx{section headings} idx{headings}

Section headings are recognized by being surrounded by equal signs (=) or
underscores before and after the text of the headline. Different
section levels are recognized by the associated number of underscores
or equal signs (=):

   * 9 `=` characters for chapters
   * 7 for sections
   * 5 for subsections
   * 3 for subsubsections
   * 2 *underscores* (only! - it looks best) for paragraphs
     (paragraph heading will be inlined)

Headings can be surrounded by as many blanks as desired, but the
first `=` must start in column 1 and there must one blank
on each side of the heading, between the heading and the `=` signs.
Here are examples on headings:

!bc do
======= Example on a Section Heading =======

The running text goes here.


===== Example on a Subsection Heading =====

The running text goes here.

=== Example on a Subsubsection Heading ===

The running text goes here.

__A Paragraph.__ The running text goes here.
!ec

===== Abstract =====
idx{abstract}

DocOnce also supports abstracts. The syntax is like an ordinary
paragraph with heading *Abstract*, *Summary*, or *Preface*,
but the text *must* be followed by a

 * section or paragraph heading
 * table of contents (`TOC:`)
 * date (`DATE:`)

Everything up to the first heading, table of contents, or date is
taken as the abstract.  For articles, the abstract is placed after the
date, but before the table of contents or the first ordinary
heading. For books one may insert the abstract before the date to make
appear on the first page.

Here are examples on an abstract and some type of ending
text (section headings, table of contents, or date).

!bc do
__Abstract.__ This abstract
lasts up to the section heading.

======= Here Is the First Section Heading =======

# or

__Summary.__
This is
a summary.

Even with two paragraphs. It lasts
until the table of contents.

TOC: on

# In books we may place the summary before DATE

TITLE: Some Title
AUTHOR: Some Author

__Summary.__ Here is the backmatter
promotion text for this book, appearing
on the front page...

DATE: today
!ec

===== Appendix =====
idx{appendix}

Appendix is supported too: just let the heading start with ``Appendix: ''
This affects only `latex` output, where the appendix formatting
is used - all other formats just leave the heading as it is written.


!split
===== Figures =====

# Note: need extra blank after FIGURE and MOVIE in !bc environments
# because doconce treats !ec as part of the caption and moves the
# !ec up to the caption line

idx{`FIGURE` keyword}

=== Basic syntax ===

Figures are recognized by the special line syntax

!bc do
FIGURE:[filename, width=600 frac=0.8] caption

!ec
The filename can be without extension, and DocOnce will search for an
appropriate file with the right extension. If the extension is wrong,
say `.pdf` when requesting an HTML format, DocOnce tries to find another
file, and if not, the given file is converted to a proper format
(using ImageMagick's `convert` utility).

!bwarning
Note the comma
between the filename and the figure size specifications and
that there should be no space around the = sign. This syntax must
be strictly followed.

Note also that, like for `TITLE:` and `AUTHOR:` lines, all information
related to a figure line *must be written on the same line*. Introducing
newlines in a long caption will destroy the formatting (only the
part of the caption appearing on the same line as `FIGURE:` will be
included in the formatted caption).
!ewarning

The `height`, `width`, and `frac` keywords can be included
if desired and may have effect for some formats: the height and width
are used for output in the formats `html`, `rst`, `sphinx`, while
the frac specification is used for `latex` and `pdflatex` to specify
the width of the image as a fraction of the text width.

=== Figure Placement ===

In web formats (`html`, `sphinx`, `ipynb`, `matlabnb`, wikis), the `FIGURE:` command is replaced by
an `img` tag exactly where the `FIGURE:` appears in the document.
LaTeX, however, will normally place the figure at a different location.
The generated LaTeX code applies

!bc latexcod
\begin{figure}[!ht] % my:fig
!ec
i.e., we use the
``here'' option `[!ht]` to recommend a placement as near the `FIGURE:`
command as possible. One can autoedit the `.tex` file and modify the
`figure` environment options, e.g.,

!bc sys
Terminal> doconce replace '{figure}[!ht]' '{figure}[t]' mydoc.tex
!ec
The above command will change all `[!ht]` options to `[t]` (top).
A specific figure can also be edited, using the fact that the label
is printed at the same line as `\begin{figure}`:

!bc sys
Terminal> doconce subst '{figure}[!ht] .+my:fig' \
          '{figure}[!h] % my:fig' mydoc.tex
!ec
Of greater influence than options like `[ht]`, `[h]`, etc., is the
LaTeX code found in the preamble:

!bc latexcod
\setcounter{topnumber}{2}
\setcounter{bottomnumber}{2}
\setcounter{totalnumber}{4}
\renewcommand{\topfraction}{0.95}
\renewcommand{\bottomfraction}{0.95}
\renewcommand{\textfraction}{0}
\renewcommand{\floatpagefraction}{0.75}
% floatpagefraction must always be less than topfraction!
\usepackage[section]{placeins}  % flush all figs before next section
!ec
These values can be manipulated to fine-tune how LaTeX places figures.

=== Figure References ===

Suppose we have the DocOnce code

!bc do
The results are presented in Figure ref{myfig}.

FIGURE:[myfigfile, width=400 frac=0.8] Results for $a=2$. label{myfig}

!ec

Different formats will display the figure reference differently.
In LaTeX, DocOnce generates the code `... in Figure~\ref{myfig}`, which
reads ``... in Figure 5'' (article) or ``... in Figure 5.2'' (book).
Requesting the `varioref` package (with `--latex_packages=varioref`)
makes DocOnce emit `\vref` references and then the above reference
becomes `in Figure~\vref{myfig}`, which reads
``... in Figure 5 on page 67''. However, if Figure 5 appears on the
present page where the reference is done, the page reference is
left out, and one can read just ``in Figure 5''.

Sphinx applies the caption as name of the figure, so the reference
reads ``... in Figure Results for .'', and the caption/name is a link
to the figure. Note that Sphinx strips off the mathematics from
the caption. In HTML, figures are given numbers, so the reference
reads ``... in Figure 3'', with the figure number as a link to the
place in the document where the `FIGURE:` command was located.
The IPython notebook format makes a Markdown link: `... in [Figure](#myfig)`,
where `myfig` is an anchor such one can click on `Figure`.
The plain text format displays the reference as ``... in Figure ref{myfig}.''.
Wiki formats show ``... in Figure myfig.''. So to summarize, figure
references work best in LaTeX, HTML, and Sphinx. Other formats
should avoid figure references with labels.

=== Inline Figures ===

The figure caption is optional. If omitted, the figure appears ``inline''
in the text without any figure environment in LaTeX formats or HTML.
#The caption may contain a label for referencing the figure also in this case.
An inline figure is handy in LaTeX since it appears exactly where the
`FIGURE:` command appears (figures with captions are encapsulated in the
LaTeX `figure` environment and become floating objects whose placement
is up to LaTeX do decide).

!bnotice Tip: use linebreak to insert space around inline figures
Sometimes inline figures (`FIGURE` line without caption) get squeezed
into the text. You can add vertical space in LaTeX and HTML by
inserting several lines with `<linebreak>`.
!enotice


FIGURE:[fig/wave1D, width=400] A wave. label{fig:viz}

idx{`--fig_prefix=`}
idx{FIGPREFIX}

=== Choosing the Figure Format ===

For each output format, there is a preference for the type of graphics file
to use. That is, for HTML, for instance, we can accept many types
of graphics formats. If we specify the extension as part of the filename,
DocOnce will try to find that specific format. If not found, it will convert
whatever can be used to some format suitable for HTML. It is highly recommended
to prepare figures in different formats manually and not rely on automatic
conversion by DocOnce -- that gives the best quality. For example, plots should
always be prepared in both PDF and PNG formats.

If we just specify the filestem of the figure file, DocOonce will pick the
most appropriate version of the file for given output format. For HTML
there is a preference for `.svg`, thereafter comes `.html` (typically Bokeh
plots), then `.png`, then `gif`, then `.jpg`. Here is the preference list
for the various formats:

 * `latex`: `.eps`, `.ps`
 * `pdflatex`: `.pgf`, `.tikz`, `.pdf`, `.png`, `.jpg`, `.jpeg`
 * `html`: `.svg`, `.html`, `.png`, `.gif`, `.jpg`, `.jpeg`
 * `sphinx`: `.png`, `.gif`, `.jpg`, `.jpeg`
 * `pandoc`: `.png`, `.gif`, `.jpg`, `.jpeg`, `.tif`, `.tiff`, `.pdf`

Other formats, which can display graphics, will prefer `.png` files.


=== Handling Variable Figure Paths ===

Figure files are usually located in some directory. Sometimes one needs to
compile the DocOnce source file(s) from different directories, and
then the path to figure files changes. For example, think of a master
DocOnce file that includes different sections whose DocOnce source files
are located in different directories. If you want to compile a section
as stand-alone document, you have to do that from the subdirectory for
that section. The path to a common directory for figures may then be
like `../fig/myfig.png`, while for the master document in the parent
directory, the corresponding path is `fig/myfig.png`.

The simplest way out of this problem is to use the `--fig_prefix=`
command-line option to set a path prefix for the figure filename.
When compiling a section in a subdirectory one sets
`--fig_prefix=../fig` while in the parent directory one needs
`--fig_prefix=fig` to compile the master document.
In the DocOnce source file one has `FIGURE: [myfig, width=...]`.

A more manual method is to introduce a Mako variable `FIGPREFIX`
that is set on the command line as part of the `doconce format` command.
The `FIGPREFIX` variable holds a prefix for the path to the figure.
In our example one writes

!bc do
FIGURE: [${FIGPREFIX}/myfig, width=500 frac=0.8] caption label{my:fig}
!ec
and set `FIGPREFIX=../fig` after the `doconce format ...` command if
one compiles a section, while `FIGPREFIX=fig` is the appropriate
value of the path when compiling the master document.

idx{subfigures}

=== Figures with Subfigures ===

Combining several image files into one, in a table fashion, can be done by the
`montage` program from the ImageMagick suite:

!bc sys
montage -background white -geometry 100% -tile 2x \
        file1.png file2.png ... file4.png result.png
!ec
The option `-tile XxY` gives `X` figures in the horizontal direction and
`Y` in the vertical direction (`tile 2x` means two figures per row
and `-tile x2` means two rows).

The `montage` program is only appropriate for bitmap images (PNG, JPEG, GIF,
TIFF). Images in the PDF format should be mounted together
using `pdftk` (to combine images to one file),
`pdfnup` (to align them in tabular format), and `pdfcrop` (to
remove surrounding whitespace):

!bc sys
Terminal> pdftk file1.pdf file2.pdf ... file4.pdf output tmp.pdf
Terminal> pdfnup --nup 2x2 tmp.pdf        # output in tmp-nup.pdf
Terminal> pdfcrop tmp-nup.pdf result.png  # output in FE1.png
!ec

Instead of using `montage`, `pdftk`, etc., one can rely on the
convenient command `doconce combine_images`:

!bc sys
Terminal> doconce combine_images pdf -2 fig1 fig2 fig3 fig4 fig
!ec
This command will combine `fig1.pdf`, `fig2.pdf`, `fig3.pdf`, and
`fig4.pdf` with two images per row (`-2` option) and place the
result in `fig.pdf`. By just changing the `pdf` option to `png`,
the same will happen with
`fig1.png`, `fig2.png`, `fig3.png`, and
`fig4.png`, resulting in `fig.png`. The tool employs the technique
above for PNG and PDF files to produce ultimate quality of the combined
image.

One can also run `doconce combine_images` with filenames with extension,
e.g.,

!bc sys
Terminal> doconce combine_images myfig1.png myfig2.png fig2.png
!ec
Here, `myfig1,png` and `myfig2.png` are placed next to each other in
a new figure file `fig2.png`.

=== Sidecaption in LaTeX and HTML ===

The figure caption can be placed on the (right) side of figures by
using the `sidecap` feature as figure option, e.g.,
`FIGURE: [myfig, width=500 frac=0.5 sidecap=True]`. The generated
`latex` and `pdflatex` output then uses the `sidecap` package and
the `SCfigure` environment to typeset the figure. Remember to
use a quite low `frac` value for figures with sidecaption (0.5
for instance). A table is used for typesetting a figure with
sidecaption in HTML, and a low `width` value is recommended.
The `sidecap=True` figure option has no impact on other formats.

=== TikZ Figures ===

Many LaTeX writers are dependent upon TikZ figures, and these can be
used in DocOnce documents, see the "demo document":
"http://hplgit.github.io/doconce/doc/pub/pgf_tikz/pgf_tikz.html".

=== Plot Files in LaTeX ===

Users who applies Matplotlib to make figures get plots with fonts that
differ from the rest of a LaTeX document.
A "blog post": "http://bkanuka.com/articles/native-latex-plots/" describes
techniques for overcoming this problem. The plotfile is then a `.pgf`
file and one must use the `pgf` LaTeX package. DocOnce supports `.pgf`
plot files for the `pdflatex` output format
and will make use of such files if they exist. These
are included by a simple `\input{file.pgf}`. If no `.pgf` file is found,
the `pdflatex` output format will apply `.pdf`, `.png`, or `.jpg` file,
in that order of preference.

idx{Bokeh interactive plots}

=== Interactive Bokeh Plots for HTML ===

Fancy interactive plots for data exploration can be made with the
"Bokeh": "http://bokeh.pydata.org/en/latest/" library. Such plots
reside in an HTML file. DocOnce will for the HTML output format detect
files of this type and use the HTML code in the file to embed the
plot(s) in the generated output document.

Below is a complete example on creating a grid of interactive plots where
the horizontal axes are coupled to each other. Panning the graph in one
plot automatically moves all the other graphs. In this way, one can
scroll through a long time series simultaneously for many plots.
# #if FORMAT == 'html'
Grap one graph below, move
into the future with the mouse, and watch the other graphs follow!

FIGURE: [fig/bokeh_demo, width=800 frac=1]
# #else
Our demo looks as follows in a browser:

FIGURE: [fig/bokeh_gridplot1, width=800 frac=1]
# #endif

Such a figure is specified the normal way: if the HTML code for the figure
is in `myfig.html`, write

!bc do
FIGURE: [myfig] caption
!ec
Options like `width` are ignored for Bokeh plots, unless you have
other versions of the figure (`myfig.png`, for instance, see the box
below) where such options may be useful for some formats.

!bnotice Make alternatives to Bokeh plots
Note that Bokeh plots have only meaning when DocOnce translates the
document to HTML. For other formats, one needs to supply figure files
that those formats can accept (PNG, PDF, etc.).

Suppose you have made a Bokeh
plot in `myfig.html`. Either you have to embed the `FIGURE` command
inside a preprocessor test that the `FORMAT == 'html'` or you must
provide alternatives like `myfig.png`. A Bokeh plot will often have a
save button that can be used to save the plot to PNG format.
This can be used for Sphinx, wikis, and pdfLaTeX (although the latter would
appreciate real vector graphics in a PDF plot).

The plot example above is so advanced that there is no natural
counterpart in a static PNG or PDF plot.
!enotice

!bnotice Tip: reduce the size of Bokeh HTML files
When making Bokeh plots in Python programs, we recommend to use
the `mode='cdn'` option in the call `output_file`. This argument leads
to links to Bokeh tools in the resulting HTML file. Without the argument,
Bokeh embeds long HTML code for its tools into the file.
DocOnce issues a warning in this case and recommends the `mode` argument.

Note that with `mode='cdn'` the HTML code for the plot requires Internet
access.
!enotice

An interactive plot like the one shown above, stored in a file
"`tmp.html`":
"https://github.com/hplgit/doconce/tree/master/doc/src/manual/fig/bokeh_demo.html",
can be made by the code below ("download file":
"https://github.com/hplgit/doconce/tree/master/doc/src/manual/bokeh_demo.py"):

@@@CODE bokeh_demo.py

=== Converting Matplotlib Plots to Bokeh ===

Most Python users apply Matplotlib to create line drawings.
Bokeh has a conversion utility from Matplotlib to Bokeh that
works well for standard curve plots. The script below demonstrates
how to generate a plot in Matplotlib and convert it to a Bokeh `tmp.html`
file.

@@@CODE mpl2bokeh.py

# #if FORMAT == 'html'
FIGURE: [fig/mpl2bokeh] Example on Bokeh figure generated by Matplotlib.
# #endif

##In the resulting Bokeh plot, one can zoom, pan, resize, etc. However,

# Sphinx: plot must be .py file, use Bokeh Sphinx extensions for that
# https://raw.githubusercontent.com/bokeh/bokeh/master/sphinx/source/docs/quickstart.rst

!split
===== Movies =====

idx{`MOVIE` keyword}

Movies/videos are inserted using the `MOVIE:` keyword. This
feature works well for the `latex`, `html`, `rst`, and `sphinx` formats.
Other formats try to generate some HTML file and link to that file
for showing the movie. If such a link is not appropriate and one wants
a figure instead of the movie, use the preprocessor as explained
in the box *Recommendations* below.

=== The Basic Command ===

As with `FIGURE`, the `MOVIE` command expands just *one line* and is of
the form

!bc do
MOVIE: [filename, height=xxx width=yyy] possible caption
!ec

Note that there must be a blank line after every `MOVIE:` command.
The width and height parameters are not required, but leaving them out
may lead to movie sizes you do not want.

Here is a movie in the Ogg format:

MOVIE: [mov/wave.ogg, width=600] A movie in Ogg format.

realized by the command

!bc do
MOVIE: [mov/wave.igg, width=600] A movie in Ogg format.
!ec

A URL works too as movie address:

!bc do
MOVIE: [http://hplgit.github.io/animate/doc/pub/mov-animate/demo.ogg] Ogg movie in cyberspace.
!ec

MOVIE: [http://hplgit.github.io/animate/doc/pub/mov-animate/demo.ogg] Ogg movie in cyberspace.

!bwarning Important
Movies will not work properly in `sphinx` format unless they are located
in a directory (tree) with a name starting with `mov`. Make it a habit
to place figures in `fig-X` and movies in `mov-X` directories, where `X`
is a short logical name for the current document (or let the names of
the directories be just `fig` and `mov`).
!ewarning

=== MP4, WebM, and Ogg Movies in HTML ===

If a movie is in Ogg, MP4, or WebM format, and the output format is `html`,
DocOnce will check if the movie file is also in the other formats among
Ogg, MP4, and WebM, and include these as well such that the movie has
backup formats in case the browser does not support a particular format.
Providing a movie in Ogg, MP4, *and* WebM format is therefore the safest
way to ensure that the movie can be played in any browser on any device.

!bnotice
If you specify a movie in Ogg or WebM format and it also exists in
MP4 format, the MP4 format will be loaded first. To avoid having
alternative movie formats in HTML, use the `--no_mp4_webm_ogg_alternatives`
command-line option when running `doconce format`.
!enotice

=== Movie Handling in Various Formats ===

Movies are easiest shown in the HTML format.
The reST and Sphinx formats apply the same raw HTML code as the
HTML format and therefore have the same capabilities.
The LaTeX format supports different methods for embedding
movies via the option `-latex_movie=...`. Proper values are listed below.

 o `href`: the `\href{run:file}{link}` is used for all movies (default),
   typeset in a one-line `quote` environment with the movie caption
   (if present) and a movie counter.
 o `media9`:
   the `media9` package is used for Flash and MP4 movies, `movie15`
   for MPEG and AVI files, and a simple `\href{run:file}{link}` command
   for other formats. Only Acrobat Reader supports displaying these
   type of movies.
 o `multimedia`: the `\movie` command (known from LaTeX Beamer) is used
   for movies.
 o `movie15`: the old `movie15` package is used.

!bnotice Where to put the movie file for a PDF document?
A major concern when using the default (`href`) link to a movie
in a PDF document, is where to store the movie file. If your
document is in a repository at GitHub or Bitbucket, one can
use this address for the movie file. However, for the HTML and
Sphinx formats, we would like to use some short, local address
`mov/mymovie.ogg`. For LaTeX PDF we can then use the command-line
option `--prefix_movie=` to prefix the local address with the
proper address in the repository in the cloud. Suppose the `mov`
directory is found in

!bc
https://github.com/n/p/blob/master/doc/mov
!ec
We need, however, the raw movie file, which has the address

!bc
https://raw.githubusercontent.com/n/p/master/doc/mov/m.ogg
!ec
We can then use the line

!bc do
MOVIE: [mov/m.ogg]
!ec
in the document, but compile to LaTeX with the command-line option

!bc
--movie_prefix=https://raw.githubusercontent.com/n/p/master/doc/
!ec
All links to movies in the PDF file will then be links to the
repository file in the cloud while for HTML and Sphinx we link
to the local movie files that are stored together with the `.html`
files for the document.
!enotice

For all other formats, an HTML file that acts as a movie player is
generated and linked from the output document. This movie player
has essentially the same code as the HTML format would have, except
that the `video` tag is not used, only the `embed` tag. Some wiki
types do have support for videos, e.g., Wikipedia can work with
Ogg files, but DocOnce has not yet implemented robust schemes for
anything but LaTeX, HTML, and Sphinx output.


=== YouTube and Vimeo Movies ===

Many publish their scientific movies on YouTube or Vimeo, and DocOnce recognizes
YouTube and Vimeo URLs as movies. When the output from DocOnce
is an HTML file, the movie will
be embedded, otherwise a URL to the YouTube or Vimeo page is inserted.
You should equip the `MOVIE:` command with the right width and height
of *embedded* YouTube and Vimeo movies. The recipe goes as follows:

 o click on *Share* (and on YouTube then *Embed*)
 o note the height and width of the embedded movie

A typical `MOVIE` command with a YouTube movie is then

!bc do
MOVIE: [http://www.youtube.com/watch?v=sI2uCHH3qIM, width=420 height=315]

MOVIE: [http://vimeo.com/55562330, width=500 height=278] CFD.
!ec

=== Animation Based on Filename Generators ===

It is possible to define a movie from a set of files, usually plot files,
which can be shown in sequence to create an animation.
If the files are local on the computer, one can specify them by a
simple Unix wildcard notation, as in

!bc do
MOVIE: [../experiments/frame_*.png]
!ec
Output in the HTML, reST, and Sphinx formats will make use of inline
JavaScript code to show the frames in sequence.
LaTeX employs the `animate` package for the same purpose.
Other formats generates a file (`movie_playerX.py`, where `X` is a number)
containing the HTML code with JavaScript to show and control the animation.
The DocOnce document has a link to this movie viewer.

There is an alternative syntax to the Unix wildcard notation:

!bc do
MOVIE: [../experiments/frame_%04d.png:0->320]
!ec
The filename is specified via printf syntax (typically the same
syntax as used to generate the individual frame files). The postfix
`:0->320` specifies the lower and upper limit of the counter
that is used in the printf specification `%04d`.
This latter syntax must be used if the plot files reside on some
web server, e.g.,

!bc do
MOVIE: [http://some.where.net/experiments/frame_%04d.png:0->320]
!ec

Here is an example:

MOVIE: [http://hplgit.github.io/animate/doc/pub/mov-animate/frames/frame_%04d.png:0->320]

!bnotice Recommendations
It is challenging to write robust DocOnce code with movies.
The recommended formats in HTML are MP4, WebM, and Ogg. One should
preferably make all three. These also works in reST and Sphinx.

The filename generation works very well in LaTeX, while true movie formats
pose big challenges. On Linux systems, the `media9`
does not work well because a proper Flash player for embedding in
the PDF file is not always available. The `movie15` package also leads
to problems because Acrobat Reader depends on an external player to
show the files, and the correct plugins to launch players with support
for a given format are not trivial to install. Even the plain `href{run:file}`
command relies on an external player and not all formats will be
supported on a given computer.

To have really robust code, use filename generators and not movie files.

!bc do
MOVIE: [../experiments/frame_*.png]
!ec

One can write flexible DocOnce code and decide at run time
if HTML output should have movie files or filename generators.
A relevant snippet using Mako and a user-defined variable
`HTMLMOVIE` is

!bc do
% FORMAT in ("latex", "pdflatex") or HTMLMOVIE == "files":
MOVIE: [../experiments/frame_*.png]

% else:
MOVIE: [../experiments/movie.ogg]

% endif
!ec
With the `-DHTMLMOVIE=files` flag, animation of individual files will
be performed, while any other value than `files` leads to
use of the `movie.ogg` in all but LaTeX formats. In HTML one will try
to load `movie.mp4` (if it exists) and then `movie.webm` (if it exists)
and then finally `movie.ogg`.

There is no way to control the number of frames per second in
LaTeX animations based on filename generators such as `myframes*.png`.
However, with a little auto editing in a script one can control
the frame rates of the various movies. The rate is specified as `2`
in lines on the form

!bc do
\begin{animateinline}[controls,loop]{2} % frames: f000.png -> f098.png
!ec
Setting the rate to 12 instead for this particular movie based on the
`f%03.png` files, the following `doconce subst` command does the job
in a script:

!bc sys
doconce subst ',loop]{2}( .+: f000)' ',loop{12}\g<1>' mydoc.do.txt
!ec

Sometimes it is desired to use true movies in web formats and a figure
in LaTeX, e.g., a figure with four snapshots from the movie combined
into a single figure file with `doconce combine_images`. A preprocessor
test is appropriate for this:

!bc do
% if FORMAT in ("latex", "pdflatex"):

FIGURE: [myfig, frac=1] caption

% else:

MOVIE: [mymov] caption

% endif
!ec
If you encounter a large number of such if-else statements, it is
advantageous to write a Mako function in Python:

!bc do
<%
def figmov(figfile, movfile, caption):
    if FORMAT in ("latex", "pdflatex"):
        return "FIGURE: [%s, frac=1] %s" % (figfile, caption)
% else:
        return "MOVIE: [%s] %s" % (movfile, caption)
% endif
%>
!ec
The one can avoid if-else tests in the running code and instead write just

!bc do
${figmov('myfig', 'mymov', 'caption')}
!ec
to insert a movie or figure file, depending on the output format.
!enotice

!split
===== Copying Computer Code from Source Files =====

Another type of special lines starts with `@@@CODE` and enables copying
of computer code from a file directly into a verbatim environment, see
Section ref{sec:verbatim:blocks} below.

===== Inserting the Output from Operating System Commands =====

idx{running programs}
idx{output from programs}

When DocOnce is used to document computer program and results from
computer code it is important to ensure that the document contains
the latest version of the code and the corresponding output.
The former is handled by the `@@@CODE` directive, while the latter
has its own directive `@@@OSCMD`. The syntax reads

!bc do
@@@OSCMD cmd
!ec
where `cmd` is any text that can be run in the operating system.
The output is copied into the DocOnce source. For example,

!bc do
@@@OSCMD python -c 'print "Hello,\nWorld!"'
!ec
results in

!bc sys
Terminal> python -c 'print "Hello,\nWorld!"'
Hello,
World!
!ec

There is a command-line option `--os_prompt=` that can be used to
set the (terminal) prompt that prefixes the command:

 * `--os_prompt=None` results in no prompt, just the command.
 * `--os_prompt=nocmd` results in no prompt and no command, just the output.
 * `--os_prompt=Terminal>` is the default setting (as in the example above).

!split
===== Comments =====

idx{comment lines}

Comments intended to be (sometimes) visible in the output document and
read by readers are known as *inline comments* in DocOnce and
described in Section ref{inline:tagging}.

Here we address comments in the DocOnce source file that are not
intended to be visible in the output document. Basic comment
lines start with the hash `#`:

!bc do
#
# Here are some comment lines that do not affect any formatting.
# These lines are converted to comments in the output format.
#
!ec
Such comment lines may have some side effects in the `rst` and `sphinx`
formats because following lines are taken as part of the comment if
there is not a blank line after the comment.

The Mako preprocessor supports comments that are filtered out *before*
DocOnce starts translating the document. Such comments are very valuable
as they will never interfere with the output format and they are only
present in the DocOnce source. Mako has two types of comments:
lines starting with a double hash `##` and multiple lines enclosed by
the `<%doc>` (beginning) and `<%doc/>` (closing) tags.

If you need a lot of comments in the DocOnce file, consider using
Mako comments instead of the single hash, unless you want the
comments to be in the source code of the output document.

To comment out or remove large sections, consider using the Preprocess
preprocessor and an if-else block with a variable that is undefined
(typically something like a test `# #ifdef EXTRA` in Preprocess, or
the Mako equivalent `% if EXTRA:`).


!split
===== Tables =====

idx{tables}

=== Basic Syntax ===

A table like

|--------------------------------|
|time  | velocity | acceleration |
|--r--------r-----------r--------|
| 0.0  | 1.4186   | -5.01        |
| 2.0  | 1.376512 | 11.919       |
| 4.0  | 1.1E+1   | 14.717624    |
|--------------------------------|

is built up of pipe symbols and dashes:

!bc do

|--------------------------------|
|time  | velocity | acceleration |
|--r--------r-----------r--------|
| 0.0  | 1.4186   | -5.01        |
| 2.0  | 1.376512 | 11.919       |
| 4.0  | 1.1E+1   | 14.717624    |
|--------------------------------|

!ec

 * The pipes and column values do not need to be aligned (but why write
   the DocOnce source in an ugly way?).
 * In the line below the heading,
   one can insert the characters `c`, `r`, or `l` to specify the
   alignment of the columns (centered, right, or left, respectively).
   One can also use `X` for potentially very wide text that must be
   wrapped and left-adjusted (will only affect `latex` and `pdflatex` where the
   `tabularx` package is then used; `X` means `l` in all other formats).
 * Similar character can be inserted in the line above the header to
   align the headings.
 * There must be a blank line before and after the table.
 * Tables are *inlined* in the text, without numbers or labels for reference.
 * Some CSS files used by some HTML styles may overrule the alignment
   characters `c`, `r`, and `l` and, e.g., center all text.
 * For output in LaTeX one can control certain aspects of the typesetting
   of tables: the text size (`--latex_table_format=`), the color of every
   two rows (`--latex_colored_table_rows=`), and the space between
   rows (`--latex_table_row_sep=`).

Here is an example with centered headings (which is default anyway),
and the numbers are
left-adjusted in the first column and right-adjusted in the two others.

!bc do

|--c--------c-----------c--------|
|time  | velocity | acceleration |
|--l--------r-----------r--------|
| 0.0  | 1.4186   | -5.01        |
| 2.0  | 1.376512 | 11.919       |
| 4.0  | 1.1E+1   | 14.717624    |
|--------------------------------|

!ec

Typeset result:

|--c--------c-----------c--------|
|time  | velocity | acceleration |
|--l--------r-----------r--------|
| 0.0  | 1.4186   | -5.01        |
| 2.0  | 1.376512 | 11.919       |
| 4.0  | 1.1E+1   | 14.717624    |
|--------------------------------|

Pipes `|` can also be inserted to indicate
vertical rules in LaTeX tables (they are ignored for other formats):

!bc do

|--------------------------------|
|time  | velocity | acceleration |
|--l---|----r-----|-----r--------|
| 0.0  | 1.4186   | -5.01        |
| 2.0  | 1.376512 | 11.919       |
| 4.0  | 1.1E+1   | 14.717624    |
|--------------------------------|

!ec

!bnotice
 * Not all formats offer alignment of heading or entries
   in tables (`rst` and `sphinx` are examples).
 * DocOnce tables are very simple: neither entries nor
   headings can span several columns or rows. When that functionality
   is needed, one can make use of the preprocessor and if-tests on
   the format and insert format-specific code for tables.
!enotice

=== Quick way of creating tables ===

It takes some efforts to put the pipes and dashes correctly in the
table format. A quick way of generating a DocOnce table is to first
put the table entries in a file with comma between the entries.
This is essentially a file in the famous CSV format.
Data in CSV format can be transformed to DocOnce table format
by the `doconce csv2table` utility:

!bc sys
Terminal> doconce csv2table somefile.csv > table.do.txt
!ec
For example, we can write a text file `tmp.csv` with

!bc dat
time, velocity, acceleration
0.0, 1.4186, -5.01
2.0, 1.376512, 11.919
4.0, 1.1E+1, 14.717624
!ec
Running `doconce csv2table tmp.csv` creates the table

!bc do

|------c--------------c--------------c-------|
| time         | velocity     | acceleration |
|------c--------------c--------------c-------|
| 0.0          | 1.4186       | -5.01        |
| 2.0          | 1.376512     | 11.919       |
| 4.0          | 1.1E+1       | 14.717624    |
|--------------------------------------------|

!ec

If the output from `doconce csv2table` is redirected to a file:

!bc sys
Terminal> doconce csv2table data.csv > mytable.do.txt
!ec
one can easily include this file by `# #include "mytable.do.txt"` in the
DocOnce source file. This is an efficient method for generating
DocOnce tables directly from data.


=== Tables from DocOnce to CSV Data Files ===

The command-line option `--tables2csv` (to `doconce format`) makes
DocOnce dump each table to CSV format in a file `table_X.csv`, where
`X` is a generated table number. This feature makes it easy to load
tables from DocOnce documents into spreadsheet programs for further
analysis.

idx{`doconce` commands!`cvs2table`}


===== Lists =====

idx{lists}
idx{itemized lists}
idx{lists!unordered}
idx{lists!bullets}

An unordered bullet list makes use of the `*` as bullet sign
and is *consistently indented* by some chosen spaces as follows

!bc do
   * item 1
   * item 2
     * subitem 1, if there are more
       lines, each line must
       be exactly intended as shown here
       (i.e., start in the same column)
     * subitem 2,
       also spans two lines
   * item 3
!ec

This list gets typeset as

   * item 1
   * item 2
     * subitem 1, if there are more
       lines, each line must
       be exactly intended as shown here
       (i.e., start in the same column)
     * subitem 2,
       also spans two lines
   * item 3

# #if FORMAT == "gwiki"
(As seen, nested lists in (g)wiki format are not treated well by
DocOnce. Plain unnested lists work fine. And the (g)wiki format
automatically puts multiple lines of an item on a single line as
required :-)
# #endif

idx{enumerated lists}
idx{ordered lists}
idx{lists!ordered}
idx{lists!enumerated}

In an ordered list, each item starts with an `o` (as the first letter
in *ordered*):

!bc do
   o item 1
   o item 2
     * subitem 1
     * subitem 2
   o item 3
!ec

resulting in

   o item 1
   o item 2
     * subitem 1
     * subitem 2
   o item 3

# #if FORMAT == "gwiki"
(Again, there are problems with mixing nested lists and liststypes
for the (g)wiki format.)
# #endif

Ordered lists cannot have an ordered sublist, i.e., the ordering
applies to the outer list only.

idx{description lists}
idx{keyword lists}
idx{lists!descriptions}
idx{lists!keywords}

In a description list, each item is recognized by a dash followed
by a keyword followed by a colon:

!bc do
   - keyword1: explanation of keyword1

   - keyword2: explanation
     of keyword2 (remember to indent properly
     if there are multiple
     lines)
!ec

The result becomes

   - keyword1: explanation of keyword1

   - keyword2: explanation
     of keyword2 (remember to indent properly
     if there are multiple
     lines)



!bwarning No indentation - except in lists!
DocOnce syntax is sensitive to whitespace!
No lines should be indented, only lines belonging to lists.
Indented lines may give strange output in some formats.
Also note that extra whitespace after ``item'' indicators (`*`, `o`, or `-`)
in lists may give strange behavior.
!ewarning



!split
======= Inline Tagging =======
label{inline:tagging}

DocOnce supports tags for *emphasized phrases*, _boldface phrases_,
and `verbatim text` (also called type writer text, for inline code),
# #if FORMAT in ("latex", "pdflatex", "html")
color{blue}{colored words},
# #endif
plus LaTeX/TeX inline mathematics, such as $\nu = \sin(x)$|$v = sin(x)$.
Links are easy to define, either with a "text": "http://google.com" or
just a plain URL: "http://google.com".
Also a non-breaking space (to avoid linebreak), linebreak,<linebreak>
m-dash (as in m---dash), and horizontal rule can be specified (below).

-------

!bwarning Limitation of inline tagging
Since DocOnce applies regular expressions to recognize inline tagging,
there might be cases where the tags are not correctly interpreted
and translated. Fortunately, most such pitfalls are easily circumvented.
The "troubleshooting document": "http://hplgit.github.io/doconce/doc/pub/trouble/trouble/trouble.html#trouble:pitfalls" shows some
examples.
!ewarning

===== Emphasized Words =====

idx{inline tagging} idx{emphasized words} idx{boldface words}

Emphasized text is typeset inside a pair of asterisk, and there should
be no spaces between an asterisk and the emphasized text, as in

!bc do
*emphasized words*
!ec

Boldface font is recognized by an underscore instead of an asterisk:

!bc do
_several words in boldface_ followed by *emphasized text*.
!ec
The line above gets typeset as
_several words in boldface_ followed by *emphasized text*.
One should only have pure text (no mathematical formulas) between the boldface
or emphasize markers, and no leading or trailing blanks (with such blanks,
the text will not be recognized as boldface or emphasize).

Colored text is formatted as

!bc do
some text color{red}{more text in red}
!ec
# #if FORMAT not in ("latex", "pdflatex", "html")
The current output format does not support colors, however.
# #endif

===== Inline Verbatim Text =====

idx{inline verbatim text}
idx{verbatim text, inline}

Verbatim text, typically used for short inline code,
is typeset between backticks:

!bc do
`call myroutine(a, b)` looks like a Fortran call
while `void myfunc(double *a, double *b)` must be C.
!ec
The typesetting result looks like this:
`call myroutine(a, b)` looks like a Fortran call
while `void myfunc(double *a, double *b)` must be C.
Note that there must be no leading or trailing spaces inside the backticks.

It is recommended to have inline verbatim text on the same line in
the DocOnce file, because some formats (LaTeX in combination with
the `ptex2tex` program (but not `doconce pretex`))
will have problems with inline verbatim text that is split over two lines.

!bnotice
Watch out for mixing backticks and asterisk (i.e., verbatim and
emphasized code): the DocOnce interpreter is not very smart in
detecting such errors. A missing backtick will also quickly create
strange output. If you suspect inline code to be the
source of problems in the final format, examine the
DocOnce source and the output.
!enotice

===== Links to Web Addresses =====

idx{links}
idx{hyperlinks}

Web addresses with links are typeset as

!bc do
some URL like "Search Google": "http://google.com".
!ec
which appears as some URL like "Search Google": "http://google.com".
The space after colon is optional, but it is important to enclose the
link and the URL in double quotes.

To have the URL address itself as link text, put an "URL" or URL
before the address enclosed in double quotes:

!bc do
Click on this link: URL: "https://github.com/hplgit/doconce".
!ec
which gets rendered as
Click on this link: URL: "https://github.com/hplgit/doconce".

(There is also support for lazy writing of URLs: any http or https web address
with a leading space and a trailing space, comma, semi-colon, or question
mark (but not period!) becomes a link with the web address as link text.)

===== Links to Mail Addresses =====

Links that launches a mail to a specified address is written as
ordinary URLs, typically as

!bc do
Send "mail": "mailto:hpl@simula.no"
# Alternative:
to "`hpl@simula.no`": "mailto:hpl@simula.no".
!ec
which appears as Send "mail": "mailto:hpl@simula.no" to
"`hpl@simula.no`": "mailto:hpl@simula.no".

===== Links to Local Files =====

Links to files ending in `.txt`, `.html`, `.pdf`, `.py`, `.f`,
`.f77`, `.f90`, `.f95`, `.sh`, `.csh`, `.ksh`, `.zsh`,
`.c`, `.cpp`, `.cxx`, `.pl`, and `.java` follows the same
setup:

!bc do
see the "DocOnce Manual": "manual.do.txt".
!ec
which appears as see the "DocOnce Manual": "manual.do.txt".
However, linking to local files like this needs caution:

  * In the `html` format the links work well if the files are
    supplied with the `.html` with the same relative location.
  * In the `latex` and `pdflatex` formats, such links in PDF files
    will unless the `.tex` file has a full URL specified through
    a `\hyperbaseurl` command and the linked files are located correctly
    relative to this URL. Otherwise full URL must be used in links.
  * In the `sphinx` format, links to local files do not work unless the
    files reside in a `_static` directory (a warning is issued about this).

As a consequence, we strongly recommend that one copies the relevant
files to a `_static` or `_static-name` directory and makes links to
files in this directory only (`name` is the nickname of the DocOnce
document, usually the name of the parent directory or main document).
Other links to files should use the full URL. If DocOnce is used
for HTML output only, then plain links to local files work fine.

If you want a link to a local source code file and have it
viewed in the browser rather than being downloaded, we recommend
to transform the source code file to HTML format by running
`pygmentize`, e.g.,

!bc sys
Terminal> pygmentize -l bash -f html -O full,style=emacs \
          -o _static/make.sh.html subdir/make.sh
!ec
Then you can link to `_static/make.sh.html` instead of
`subdir/make.sh`. Here is an example where the reader
has the file available as `src/myprog.py` in her
software and the document links to `_static/myprog.py`:

!bc do
See the code URL:"src/myprog.py" ("view: "_static/myprog.py.html").
!ec

Links to files with other extensions are typeset with
*the filename as link text*. The syntax consists of
the keyword URL, followed by a colon, and then the filename enclosed
in double quotes:

!bc do
URL: "manual.html"
!ec
resulting in the link URL: "manual.html".

# This is now automatically carried out by the autogenerated
# script for sphinx:
#For such local links to
#work with the `sphinx` format, the `.rst` file needs a fix, carried
#out by
#!bc sys
#doconce sphinxfix_localURLs mydoc.rst
#!ec
#(The files, such as `manual.html`, are then copied to a subdirectory
#`_static`, which must be manually copied to the Sphinx directory's
#`_static` directory - links in the `.rst` files are automatically
#adjusted.)

idx{quotation syntax}

===== Quotes =====

idx{quotation}

Quotations employ either the emphasized font or double quotation marks.
In the latter case, one should not use the character `"` but rather
the (LaTeX-inspired) construction with double backticks and two single
quotes:

!bc do
This is a sentence with ``words to be quoted''.
!ec
To candidates for find double quotes that should be transferred to the above
type of quotation (which is a common mistake),
one can run a regular expression search like

!bc sys
Terminal> find . -name '*.do.txt' -exec grep -E \
          '[^("]"[A-Za-z0-9 ,]+" *[^:`)"]' {} \; -print
!ec
This search may give many false hits as double quotes are frequently
used in computer code and preprocessor instructions (URLs and hyperlinks
should not give hits in the above regular expressions).

idx{non-breaking space}

===== Non-Breaking Space =====

idx{non-breaking space} idx{nbsp}

The non-breaking space character is tilde:

!bc do
Here comes a long line with a specification of a number with unit at the end,
which is an example that requires a "non-breaking space character":
"http://en.wikipedia.org/wiki/Non-breaking_space": 7.4~km is traveled
in~$7.4/5.5\approx 1.345$~s. (Computer code, where the tilde has a
meaning, as in `y = ~x`, is not affected. The non-breaking character only
works between characters, numbers, and the math dollar sign.)
!ec
This is rendered as

!bquote
Here comes a long line with a specification of a number with unit at the end,
which is an example that requires a "non-breaking space character":
"http://en.wikipedia.org/wiki/Non-breaking_space": 7.4~km is traveled
in~$7.4/5.5\approx 1.345$~s. (Computer code, where the tilde has a
meaning, as in `y = ~x`, is not affected. The non-breaking character only
works between characters, numbers, and the math dollar sign.)
!equote


===== Horizontal rule =====

idx{horizontal rule}

A horizontal rule for separating content vertically, like this:

-----

is typeset as four or more hyphens on a single line:

!bc do
---------
!ec

===== Em-dash =====

idx{m-dash} idx{em-dash}

The `latex`, `pdflatex`, `sphinx`, `html`, `pandoc`, and
`ipynb` formats support em-dash,
indicated by three hyphens: `---`. Other formats print just the
three hyphens.
The em-dash has two applications:

 * as alternative to an ordinary single hyphen (with space around) in a sentence---except that there are no spaces around the em-dash (this is common, cf. "Wikipedia": "https://en.wikipedia.org/wiki/Dash"), and
 * origin of quotes (where there is no space between the end of the quote and the m-dash):

!bquote
*Premature optimization is the root of all evil.*---Donald Knuth.
!equote
The associated DocOnce source reads

!bc do
|bquote
*Premature optimization is the root of all evil.*---Donald Knuth.
|equote
!ec

===== En-dash =====

idx{n-dash} idx{em-dash}

The en-dash constists of two hyphens, as in `--`, and can be used instead
of a single hyphen to get a slightly longer hyphen (LaTeX writers are
especially used to this). Common applications are

 * hyphen in compound words as the Navier--Stokes equations (here written as `Navier--Stokes`)
 * hyphen in number ranges like 1--9
 * hyphen around a sentence in sentence: To be precise -- but not to detailed -- we should ... (here the hyphen is written as `--`), as an alternative to em-dash (see section above)

The `latex`, `pdflatex`, `sphinx`, `html`, `pandoc`, and
`ipynb` formats support en-dash (basically this means that HTML output
has `&ndash` and LaTeX output is not altered). Other formats just show
the raw double hyphen.

# The m- and n-dashes are processed in doconce.py

===== Ampersand =====

idx{ampersand}

An ampersand, as in Guns & Roses or Texas A & M, is written as a
plain `&` *with space(s) on both sides*. Single upper case letters on each
side of `&`, as in `Texas A & M`, remove the spaces and result in
Texas A & M, while words on both sides of `&`, as in `Guns & Roses`,
preserve the spaces: Guns & Roses. Failing to have spaces before and
after `&` will result in wrong typesetting of the ampersand in the `html`,
`latex`, and `pdflatex` formats. If special quoting of the ampersand
is undesired, e.g., when one has inserted native LaTeX code for tables,
the command-line option `--no_ampersand_quote` for `doconce format` turns
off the ampersand treatment for all formats.

===== Footnotes =====

idx{footnotes}

Typesetting of footnotes employs a common email or Extended Markdown syntax:

!bc do
Footnotes are typeset according to the output format[^typesetting].
The syntax is optional spaces, opening bracket, hat, a footnote name
without spaces[^remedy-for-name-with-spaces], and closing bracket. The
logical name of the footnote is not used in LaTeX, HTML,
reStructuredText, or Sphinx, because these languages employ numbered
footnotes. Other formats employ the logical name.

[^typesetting]: Typesetting of the footnote depends on the format.
Plain text does nothing, LaTeX removes the definition and inserts the
footnote as part of the LaTeX text.  reStructuredText and Sphinx
employ a similar type of typesetting as Extended Markdown and DocOnce,
and in HTML we keep the same syntax, just displayed properly in HTML.

Footnotes are preferably defined after the paragraph they are used.
The definition is the footnote syntax (some optional space, bracket,
hat, name, bracket) followed by colon and a text.
A new paragraph marks the end of a footnote.

[^remedy-for-name-with-spaces]: Just put in dashes or underscores in
case of spaces.
!ec
The text above looks as follows.

Footnotes are typeset according to the output format[^typesetting].
The syntax is optional spaces, opening bracket, hat, a footnote name
without spaces[^remedy-for-name-with-spaces], and closing bracket. The
logical name of the footnote is not used in LaTeX, HTML,
reStructuredText, or Sphinx, because these languages employ numbered
footnotes. Other formats employ the logical name.

  [^typesetting]: Typesetting of the footnote depends on the format.
Plain text does nothing, LaTeX removes the definition and inserts the
footnote as part of the LaTeX text.  reStructuredText and Sphinx
employ a similar type of typesetting as Extended Markdown and DocOnce,
and in HTML we keep the same syntax, just displayed properly in HTML.

Footnotes are preferably defined after the paragraph they are used.
The definition is the footnote syntax (some optional space, bracket,
hat, name, bracket) followed by colon and a text.
A new paragraph marks the end of a footnote.

[^remedy-for-name-with-spaces]: Just put in dashes or underscores in
case of spaces.

===== Inline Comments =====

idx{inline comments}
idx{comments, inline}

DocOnce also supports inline comments in the text:

!bc do
[name: comment]
!ec
where `name` is (e.g.) the name of the author of the comment, and `comment` is a
plain text text. Note that *there must be a space after the colon*,
otherwise the comment is not recognized. The name can contain upper and lower
case characters, digits, single quote, `+` and `-`, as well
as space. Next is an example.
[hpl's comment: Inline comments
can span
several lines,
if desired.]

The name and comment are visible in the output unless `doconce format`
is run with a command-line argument `--skip_inline_comments`
(see Section ref{doconce2formats} for an example). Inline comments
are helpful during development of a document since different authors
and readers can comment on formulations, missing points, etc.
All such comments can easily be removed from the `.do.txt` file
by `doconce remove_inline_comments` (see Section ref{doconce2formats}).

Inline comments are typeset in a simple way: boldface name, a
numbering of the comment, and then the comment, all in red and in
parenthesis. However, with the `--latex_todonotes` option, LaTeX will
apply the `todonotespackage` to typeset the comments in very visible
color boxes.

===== Inline Comments for Editing =====

idx{track changes}
idx{inline comments for editing}

!bnotice
The inline editing syntax in DocOnce was implemented before the invention
of "CriticMarkup": "https://github.com/CriticMarkup/CriticMarkup-toolkit".
Now it would make sense to use the CriticMarkup syntax and associated
tools. (DocOnce needs proper rendering of CriticMarkup
!enotice

Inline comments can also be used to markup editing of the text.
The following syntax is supported:

!bc do
[add: ,]
[add: .]
[add: ;]
[del: ,]
[del: ,]
[del: .]
[del: ;]
[add: some text]
[del: some text]
[edit: some text -> some replacement for text]
[name: some text -> some replacement for text]
!ec
That is, one can add, delete, and replace text, and adding or deleting
a comma, period, or semicolon leads to special typesetting where
such a small edit is highlighted. Below
is an example of a text with inline editing.

Originally, we have the text

!bc do
First consider a quantity $Q$. Without loss of generality, we assume
$Q>0$. There are three, fundamental, basic property of $Q$.
!ec
Then, some reader wants to change this text and explicitly demonstrate
what is deleted, added, and replaced (as when using track changes
in Microsoft Word). The use of the `add`, `del`, and replacement
construction with `->` may look as follows.

!bc do
First[add: ,] consider [edit: a quantity -> the flux]
[del: $Q$. Without loss of generality,
we assume] $Q>0$. There are three[del: ,] fundamental[del: , basic]
[edit: property -> properties] of $Q$. [add: These are not
important for the following discussion.]
!ec
The text gets rendered as

!bquote
First[add: ,] consider [edit: a quantity -> the flux]
[del: $Q$. Without loss of generality,
we assume] $Q>0$. There are three[del: ,] fundamental[del: , basic]
[edit: property -> properties] of $Q$. [add: These are not
important for the following discussion.]
!equote

Such inline comments with edits are only given special typesetting in
the output formats `latex`, `pdflatex`, `html`, and `sphinx`.
Otherwise, just the DocOnce syntax is shown (but that is also quite
readable as edit instructions.)

idx{`doconce` commands!`apply_edit_comments`}

The editing implied by the edit comments can be implemented in the DocOnce
file by the command

!bc sys
Terminal> doconce apply_edit_comments mydoc.do.txt
!ec

===== Forced Line Breaks =====

idx{linebreak}
idx{citations}
idx{`cite`}

By *ending* a line in the DocOnce file
with `<linebreak>` the output format has a forced
linebreak at this point. This can be used to typeset poems,
songs (if not in a verbatim block), or the origin of quotes.
Here is an example:

!bc do
|bquote
*Program writing is substantially more demanding than book
writing. Why is it so? I think the main reason is that a larger
attention span is needed when working on a large computer program
than when doing other intellectual tasks.* <linebreak>
Donald Knuth cite[p. 18]{Knuth85}, computer scientist, 1938-.
|equote
!ec
is rendered as

!bquote
*Program writing is substantially more demanding than book
writing. Why is it so? I think the main reason is that a larger
attention span is needed when working on a large computer program
than when doing other intellectual tasks.* <linebreak>
Donald Knuth cite[p. 18]{Knuth85}, computer scientist, 1938-.
!equote

The `<linebreak>` is a newline in LaTeX if it has preceding text,
otherwise it is a `\vspace{3mm}`. In HTML, `<linebreak>` is `<br>`.
Both constructions can be used to either force a linebreak or add
vertical space.

!bnotice Tip on using forced linebreaks
The `<linebreak>` tag is often useful in slides to avoid overfull
lines in bullet lists, portion such lines into separate lines,
or to insert vertical
space. It can be used in admonitions too to get more space between
the title and the text. Remember to have `<linebreak>` at the end of
the line.
!enotice

===== Inline Mathematics =====

idx{inline mathematics}
idx{formulas (math)}
idx{mathematical formulas}

Inline mathematics is written as in LaTeX, i.e., inside dollar signs.
Many formats leave this syntax as it is (including the two dollar signs),
hence nice math formatting is only obtained in LaTeX, HTML, MediaWiki,
and Sphinx (Epytext has some inline math support that is utilized).

The following text

!bc do
Let $a=\sin(x) + \cos(x)$. Then $a^2 = 2\sin(x)\cos(x)$
because $\sin^2x + \cos^2x = 1$.
!ec
is rendered as ``Let $a=\sin(x) + \cos(x)$. Then $a^2 = 2\sin(x)\cos(x)$
because $\sin^2x + \cos^2x = 1$.''

Mathematical expressions in LaTeX syntax often contains
special formatting commands, which may appear annoying in plain
text. DocOnce therefore supports an extended inline math syntax where
the writer can provide an alternative syntax suited for formats close
to plain ASCII:

!bc do
Here is an example on a linear system
${\bf A}{\bf x} = {\bf b}$|$Ax=b$,
where $\bf A$|$A$ is an $n\times n$|$nxn$ matrix, and
$\bf x$|$x$ and $\bf b$|$b$ are vectors of length $n$|$n$.
!ec
That is, we provide two alternative expressions, both enclosed in
dollar signs and separated by a pipe symbol, the expression to the
left is used in formats with LaTeX support (`latex`, `pdflatex`, `html`,
`sphinx`, `mwiki`), while the expression to the right is used for
all other formats.  The above text is typeset as "Here is an example
on a linear system ${\bf A}{\bf x} = {\bf b}$|$Ax=b$, where $\bf A$|$A$
is an $n\times n$|$nxn$ matrix, and $\bf x$|$x$ and $\bf b$|$b$
are vectors of length $n$|$n$."

!split
===== Cross-Referencing =====
idx{cross referencing} idx{labels} idx{references} idx{`ref` (label reference)}

References and labels are supported. The syntax is simple:

!bc do
label{section:verbatim}   # defines a label
For more information we refer to Section ref{section:verbatim}.
!ec
The DocOnce label syntax is close that that of labels and cross-references in
LaTeX, but note that *labels cannot contain whitespace and cannot have a backslash*.

When the label is placed after a section or subsection heading,
the `plain` text, `epytext`, and `st` formats will simply
replace the reference by the title of the (sub)section.  All labels
will become invisible, except those in math environments.  (In the
`rst` and `sphinx` formats, the end effect is the same, but
the `label` and `ref` commands are first translated to the proper
reST commands by `doconce format`.) In the `html`, `ipynb`, and wiki formats,
labels become anchors and references become links,
and with LaTeX `label` and `ref` are just equipped with backslashes so
these commands work as usual in LaTeX.

Since references to sections appear differently in different formats, we
provide an example.

!bc do
..., we refer to Section ref{sec:theory}.

======= Basic Theory =======
label{sec:theory}

A first discovery was that 1+1 is 2.
!ec
The reference appears as follows in various output formats:

 * `latex` and `pdflatex`: ``we refer to Section 2.3'' with
   LaTeX code <linebreak>
   `we refer to Section~\ref{sec:theory}`
 * `html`: ``we refer to the section Basic Theory'' with the HTML code <linebreak>
   `we refer to the section <a href="#sec:theory">Basic Theory</a>`
 * `rst`, `sphinx`: ``we refer to the section Basic Theory''
 * `plain`: ``we refer to the section "Basic Theory"''
 * `ipynb`: ``we refer to the section Basic Theory'' with Markdown code <linebreak>
   `we refer to the section [Basic Theory](#sec:theory)`
 * `mwiki`: ``we refer to the section Basic Theory'' with MediaWiki code <linebreak>
   `We refer to the section [#Basic_Theory]`


Labels and references should only be used for
(sub)sections, equations, figures, and movies (since DocOnce does not
support references to tables and algorithms, for instance).
By the way, here is an example on referencing Figure ref{fig:viz}.
Additional references to Sections ref{mathtext} and ref{newcommands} are
nice to demonstrate, as well as a reference to equations,
say (ref{myeq1})-(ref{myeq2}).

!bwarning References to equations must be in parentheses!
LaTeX writers who are used to `\eqref{}` should observe that
there is only one type of reference syntax in DocOnce, `ref`, without
backslash, and that references to an equation with label `my:special:eq`
must feature parentheses and look like

!bc
..., see (ref{my:special:eq}).
!ec
# Since any (ref{}) will be translated to \eqref{}, also inside
# verbatim blocks, we need a hack to write (ref{my:eq}) above:
# the make.sh script for manual.do.txt must translate \eqref{} back to (ref{})!

!ewarning



Hyperlinks to files or web addresses are handled as explained
in Section ref{inline:tagging}.

idx{`refaux` (label reference)}

References to equations and sections in other documents can be done
by the *generalized cross-referencing* syntax explained in the next
section. However, sometimes one wants in an HTML document or notebook
to make references to equations and sections in
a LaTeX textbook. This is not well handled by the generalized cross-referencing
technique, but DocOnce has a special option for this feature:
`--replace_ref_by_latex_auxno=../book.aux` will read the label and numbering
information from `../book.aux` and replace all references (`ref`) by the
corresponding number found in the `../book.aux` file. Sometimes one wants
to use this feature for selected references. In that case, use `refaux`
instead of `ref`. If there one or more `refaux` commands in the DocOnce
source, only `refaux` references will be replaced by numbers from the
`.aux` file. Otherwise, all `ref` commands corresponding to labels in
the `.aux` file will be replaced. In any case, the
`--replace_ref_by_latex_auxno=` option is needed to specify one
`.aux` file.

===== Generalized Cross-Referencing =====
label{manual:genrefs}

idx{citations}
idx{`cite`}
idx{citations, generalized}
idx{generalized citations}
idx{cross-document referencing}
idx{`ref` (generalized reference)}

Sometimes a series of individual documents may be assembled to one
large document, typically a book.
In the book one wants to make cross references between chapters
and sections, while these become references to external documents
when the chapters (or sections) are compiled as stand-alone
documents. For example, one can in a DocOnce file `file1.do.txt`
have text like

!bc do
...as shown in Section ref{sec:eqs}.
!ec
with the label `sec:eqs` defined in another file `file2.do.txt`.
If `file1.do.txt` and `file2.do.txt` are combined to a single
document, the reference is treated correctly, but if `file1.do.txt`
is compiled as a single document, the label `sec:eqs` becomes
undefined. Then one would instead write

!bc do
...as shown in the document "Mathematical Equations":
"http://some.net/doc/matheqs.html" cite{math_eqs_2020}.
!ec

LaTeX has functionality for referring to labels
in external documents. One must use the `xr` package
and list external documents with a command
`\externaldocument{name}` such that LaTeX can extract label
information from the `name.aux` file. We are then able to
write the above reference as

!bc do
\externaldocument{file2}
...
...as shown in Section ref{sec:eqs} in cite{math_eqs_2020}.
!ec
and get output like ``...as shown in Section 3.4 in [12].''
When the numbering of sections in `file2.tex` changes later,
the output from the shown line in `file1.tex` will automatically
be changed if `file2.aux` is recently compiled
(so `file2.aux` with the mapping from labels to section numbers is updated).

=== Generalized References ===

DocOnce mimics a generalization of the LaTeX functionality in the
`xr` package such that one can refer to external documents in
other formats than LaTeX (HTML, Sphinx, IPython notebooks, wikis, etc.).
This feature is called a *generalized reference* and involves
a reference with *three* values.
The syntax of generalized references reads

!bc do
ref[internal][cite][external]
!ec
If all references in the text `internal` are
to labels defined in the present DocOnce document, the
generalized reference becomes the text `internal`.
If one or more references in `internal` are not labels
present in the document and
`latex` or `pdflatex` is the output format,
the generalized reference becomes the
text `internal` followed by `cite`, while for all other formats the
text in `external` is used.

The example above can now be written as the generalized reference

!bc do
...as shown in ref[Section ref{sec:eqs}][ in cite{math_eqs_2020}][
the document "Mathematical Equations":
"http://some.net/doc/matheqs.html" cite{math_eqs_2020}].
!ec
(Note that there must be no spaces between closing and opening brackets: `][`.)
When the label `sec:eqs` is found in the current DocOnce document,
this generalized reference becomes

!bc do
Section ref{sec:eqs}
!ec
If not, and `latex` or `pdflatex` is the output format,
the reference becomes

!bc do
Section ref{sec:eqs}] in cite{math_eqs_2020}
!ec
while in all other cases the reference becomes

!bc do
the document "Mathematical Equations":
"http://some.net/doc/matheqs.html" cite{math_eqs_2020}
!ec

For the reference to a label in an external document
to work in the LaTeX case it is required to list this
document in the DocOnce file as

!bc do
# Externaldocuments: file2
!ec
Several external documents can be listed with comma as delimiter:

!bc do
# Externaldocuments: file2, file3, myfile
!ec
on *a single line*. The `Externaldocuments` comment leads to use
of the `xr` package and insertion of `\externaldocument{file2}`
in the `.tex` output file. It is a good habit to place
the `Externaldocument` comment after the title, author, and date.

!bwarning External documents must be recently compiled
When compiling DocOnce documents with generalized references
to `latex` or `pdflatex`,
all documents listed in
the `Externaldocuments` comment must have been recently compiled
such that their `.aux` files *are available and updated*.

Note that cleaning (`doconce clean`)
of the directory holding an external document will destroy the
`.aux` file, and `latex` or `pdflatex` may then complain that
a file listed as `\externaldocument{}` has no `.aux` file.
This is just a warning - the result is question marks in the
PDF document.
!ewarning

idx{`refch` (generalized chapter reference)}

=== Generalized References to Chapters ===

A reference to a chapter in a book becomes just
a reference to a complete stand-alone document
if chapters are compiled individually. Here is an example:

!bc do
...as shown in Chapter ref{ch:model}.
!ec
This reference works fine if the present document is a book and `ch:model`
is a label of a chapter in the book. However,
if the chapter with label `ch:model` is compiled separately, we would
rather write

!bc do
...as shown in cite{math_eqs_2020}.
!ec
where `math_eqs_2020` is the citation label for the external document
as listed in the Publish database. Or if the output format supports
hyperlinks, we would perhaps add such a link:

!bc do
the document "Mathematical Equations":
"http://some.net/doc/matheqs.html" cite{math_eqs_2020}.
!ec
Such references to
chapters or complete documents are very much like the previously
generalized references, but written with `refch` instead
of `ref`:

!bc do
refch[internal][cite][external]
!ec
The only difference between `refch` and `ref` is that the former,
for `latex` and `pdflatex` output, just use the `cite` text
and not `internal` if the labels in the `internal` text are not found in
the document. To be precise, the reference

!bc do
...as shown in refch[Chapter ref{ch:eqs}][cite{eqs_doc_2008}][
the document "Some Equations": "http://some.net/someeqs/"].
!ec
will be

!bc do
...as shown in Chapter ref{ch:eqs}.
!ec
if `ch:eqs` is a label defined in the present document. It becomes

!bc do
...as shown in Chapter cite{eqs_doc_2008}.
!ec
if `ch:eqs` is not found in the present document *and* the output
format is `latex` or `pdflatex`. In all other cases the result becomes

!bc do
...as shown in
the document "Some Equations": "http://some.net/someeqs/"].
!ec

=== Generalized References to LaTeX Documents ===

It is difficult in the `[external]` part of the generalized reference to
refer to equation numbers in an external document. If one wants to refer
to a LaTeX document, say a textbook, from some HTML or notebook, then
one can use the `refaux` reference and an `.aux` file as explained at the
end of the previous section on *Cross-Referencing*. Here is one example:

!bc do
From ref[(ref{eq1})][ in cite{Langtangen_2045}][
equation (refaux{eq1}) in cite{Langtangen_2045}], we realize that...
!ec
For LaTeX output, the reference to `eq1` will remain, but for other
formats

!bc
(refaux{eq1})
!ec
will be replaced by (say)
`(1.5)` if we provide the option `--replace_ref_by_latex_auxno=mybook.aux`
and `mybook.aux` defines label `eq1` to have number `1.5`.
Replacing `refaux` by `ref` above will lead to hardcoding of `ref{eq1}`
as `1.5` also in LaTeX output (which is okay, the `xr` package and
giving `Externaldocuments: mybook` results in the same).

The example above is particularly relevant if one writes exercises that
are to be filtered out as notebooks. The notebooks can then refer to
a LaTeX book, while in the LaTeX version of the document,
the exercises make references to the LaTeX book via the `xr` package the
usual way.

Sometimes one does not want to refer to a LaTeX document in the
`[external]` part of a generalized reference, but to a web document.
Then the text must be
written in a different way if one has equation or section references.
For example,

!bc do
From ref[(ref{eq1})][ in cite{Langtangen_2045}][
the differential equation for $u(t)$ in the section
"Setting up the model": "http://some.where.net/doc#model"
in cite{Langtangen_2045}], we realize that...
!ec


=== Tool for Generating Generalized References ===

The `doconce ref_external` command will read all the labels in the
external documents listed in the `Externaldocuments:` comment
and use the Publish database file of the current document
(specified by `BIBFILE:`) to automatically
generate substitution commands that translate ordinary LaTeX-style
internal references
to generalized references in DocOnce syntax.
For example, `doconce ref_external file1`
will find the reference

!bc do
......as shown in Section ref{sec:eqs}.
!ec
as a reference to a label `sec:eqs` defined in `file2`, grab
the title of `file2.do.txt`, find the bibliographic data in
the Publish file, and make a substitution command

!bc do
doconce subst "Section\s+ref{sec:eqs}" "..." $files
!ec
where `"..."` is the complete generalized reference for this particular
reference.
In other words, with `doconce ref_external` one can automatically
generate generalized references between, for example, chapters in
a book that exist as stand-alone documents.

# Need to artificially declare the labels referred to in the
# box below, otherwise split_html will complain that we have
# `ref{X}`, but not corresponding `label{X}`... Also, we
# need to typeset labels in verbatim to avoid them being
# translated into something different.

# `\label{eqs:g1}` and `\label{eqs:g4}`

!bwarning References to equations
Generalized references to equations work well in LaTeX, but
not in other formats as one cannot resolve the equation number
in the external document. It is then better to write different
text using the `FORMAT` variable in Mako:

!bc do
% if FORMAT in ("pdflatex", "latex"):
By combining ref[(ref{eqs:g1})-(ref{eqs:g4})][ in cite{some_doc}][
dummy] we can derive the expression ...
% else:
One can from cite{some_doc} derive the expression
% endif
!ec
The `doconce ref_external` tool generates an `external` text
in case of references to equations that says
``reference to specific _equations_ (label eqs:g1 and eqs:g4)
in external document "name": "link" is not recommended''.
One can then search for this text and make a Mako if-else rewrite
as shown above.
!ewarning

!bwarning Limited support
The `doconce ref_external` tool cannot correctly handle references
to a range of sections like

!bc do
Sections ref{mydoc:sec1}-ref{mydoc:sec2}
!ec
The automatically generated generalized references should always
be manually checked and edited!
!ewarning

=== A Worked Example ===

Here is an example on a specific working generalized reference where
the LaTeX output also has a hyperlink:

!bc do
As explained in
ref[Section ref{subsec:ex}][in "Langtangen, 2012":
"http://hplgit.github.io/doconce/test/demo_testdoc.html#subsec:ex"
cite{DocOnce:test}][a "section":
"http://hplgit.github.io/doconce/test/demo_testdoc.html#subsec:ex" in
the document "A Document for Testing DocOnce":
"http://hplgit.github.io/doconce/test/demo_testdoc.html"
cite{DocOnce:test}], DocOnce documents may include tables.
!ec
With `latex` or `pdflatex` as output, this translates to

!bc do
As explained in
Section ref{subsec:ex}, DocOnce documents may include tables.
!ec
if the label `{subsec:ex}` appears in the present DocOnce source, and
otherwise

!bc do
As explained in
Section ref{subsec:ex} in "Langtangen, 2012":
"http://hplgit.github.io/doconce/test/demo_testdoc.html#subsec:ex"
cite{DocOnce:test}, DocOnce documents may include tables.
!ec
The latter DocOnce code is translated to the following
LaTeX code:

!bc do
As explained in
Section~\ref{subsec:ex} in
\href{{http://hplgit.github.io/doconce/...}}{Langtangen, 2012}
\cite{DocOnce:test}, DocOnce documents may include tables.
!ec
In a format different from `latex` and `pdflatex`, the effective DocOnce
text becomes

!bc do
As explained in
a "section":
"http://hplgit.github.io/doconce/test/demo_testdoc.html#subsec:ex" in
the document "A Document for Testing DocOnce":
"http://hplgit.github.io/doconce/test/demo_testdoc.html"
cite{DocOnce:test}, DocOnce documents may include tables.
!ec
The rendered text in the current format becomes

!bquote
As explained in
ref[Section ref{subsec:ex}][in "Langtangen, 2012":
"http://hplgit.github.io/doconce/test/demo_testdoc.html#subsec:ex"
cite{DocOnce:test}][a "section":
"http://hplgit.github.io/doconce/test/demo_testdoc.html#subsec:ex" in
the document "A Document for Testing DocOnce":
"http://hplgit.github.io/doconce/test/demo_testdoc.html"
cite{DocOnce:test}], DocOnce documents may include tables.
!equote

A complete ``chapter'' reference may look like

!bc do
As explained in
refch[Chapter ref{ch:testdoc}]["Langtangen, 2012":
"http://hplgit.github.io/doconce/test/demo_testdoc.html"
cite{DocOnce:test}][the document
"A Document for Testing DocOnce":
"http://hplgit.github.io/doconce/test/demo_testdoc.html"
cite{DocOnce:test}], DocOnce documents may include tables.
!ec
The output now, if `ch:testdoc` is not a label in the document,
becomes in the `latex` and `pdflatex` case

!bc do
As explained in
"Langtangen, 2012":
"http://hplgit.github.io/doconce/test/demo_testdoc.html"
cite{DocOnce:test}, DocOnce documents may include tables.
!ec
That is, the internal reference `Chapter ...` is omitted since
it is not meaningful to refer to an external document as ``Chapter''.
The resulting rendered text in the current format becomes
!bquote
As explained in
refch[Chapter ref{ch:testdoc}]["Langtangen, 2012":
"http://hplgit.github.io/doconce/test/demo_testdoc.html"
cite{DocOnce:test}][the document
"A Document for Testing DocOnce":
"http://hplgit.github.io/doconce/test/demo_testdoc.html"
cite{DocOnce:test}], DocOnce documents may include tables.
!equote

Note that LaTeX cannot
have links to local files, so a complete URL on the form
`http://...` must be used.

!bnotice Tip
Use `doconce ref_external` to get an overview of the external
references in a file. Very often you want to rewrite the text
to reduce the amount of external referencing. Remember then
to compile your document before running `doconce ref_external`
again since the command applies the compiled files to get information
(`tmp_preprocess_*` or `tmp_mako_*`) if you use any of the Preprocess
or Mako preprocessors.
!enotice

!bnotice Splitting documents into smaller parts is easy!
The generalized references and the `doconce ref_external` are great
tools for splitting an existing document into smaller parts, say one
chapter into two or one book into two books. Such a split will normally
create a lot of difficulties with cross-document referencing (unless
you just write directly in LaTeX with the `xr` packcage).
!enotice

!split
===== Index =====
idx{index}

An index can be created for the `latex`, `rst`, and `sphinx` formats
by the `idx` keyword, following a LaTeX-inspired syntax:

!bc do
idx{some index entry}
idx{main entry!subentry}
idx{`verbatim_text` and more}
!ec
The exclamation mark divides a main entry and a subentry. Backquotes
surround verbatim text, which is correctly transformed in a LaTeX setting to

!bc do
\index{verbatim\_text@\texttt{\rm\smaller verbatim\_text and more}}
!ec
Everything related to the index simply becomes invisible in plain
text, Epytext, StructuredText, HTML, and wiki formats.  Note: `idx`
commands should be inserted outside paragraphs and admonitions,
not in between the
text as this may cause some strange behaviour of reST and
Sphinx formatting.  As a recommended rule, index items are naturally
placed right after section headings, before the text begins, while
index items related to a paragraph should be placed above the
paragraph one a separate line (and not in between the text or between
the paragraph heading and the text body, although this works fine if
LaTeX is the output format). For paragraphs with `===` heading,
the index keywords should be placed above the heading.

The keywords in the index are automatically placed in a meta
tag in `html` output such that search engines can make use of the them.

SIAM has developed a very useful document on "how to create an
effective index": "http://www.siam.org/books/authors/indexguidelines.pdf"
in a book.


===== Emojis =====
idx{emojis}
idx{smileys}

Emojis are specified by syntax like `:sweat_smile:`, followed by
whitespace (blank or newline) before and after.
The available emoji names are shown at URL: "http://www.emoji-cheat-sheet.com".
Here is an example: :sweat_smile:

DocOnce supports emojis for the `html`, `pdflatex`, and `pandoc` formats.
All other formats will just print the raw emoji name (like `:sweat_smile:`).
The command-line option `--no_emoji` removes all emojis from the output so
you can get serious in a second.




!split
======= Exercises, Problems, Projects, and Examples =======
label{manual:exercises}

idx{exercise environment}
idx{problem environment}
idx{project environment}
idx{example environment}

DocOnce has special support for four types of ``exercises'', named
*exercise*, *problem*, *project*, or *example*.
These are all typeset as special kind of
subsections. Such subsections start with a subsection
headline surrounded by 5 `=` characters, and last up to the
next headline or the end of the file. The headline itself must
consists of the word *Exercise*, *Problem*, *Project*, or *Example*, followed
by a colon and a title of the exercise, problem, or project.

===== Examples on Exercise Syntax =====

=== Elements in an Exercise ===

The next line(s) may contain a label and specification of the
name of the result file(s) (if the answer to the exercise is to be handed
in) and a solution file. The DocOnce code looks like this:

!bc do
===== Project: Determine the Distance to the Moon =====
label{proj:moondist}
file=earth2moon.pdf
solution=eart2moon_sol.do.txt

Here goes the running text of the project....

!ec
DocOnce will recognize the exercise, problem, project, or example *title*,
the optional *label*, the optional *name of the answer file* (`file=`), the
optional name of the *solution* file (`solution=`),
and the *running text*. In addition,
one can add subexercise environments, starting with `!bsubex` and ending
with `!esubex`, on the beginning of separate lines.
Within the main exercise or
a subexercise, three other environments are possible: (full) solution,
(short) *answer*, and *hints*. The environments have begin-end
directives `!bans`, `!eans`, `!bsol`, `!esol`, `!bhint`, `!ehint`, which
all must appear on the beginning of a separate line (just as
`!bc` and `!ec`).

The `file=` or `files=` command accepts a comma-separated list of filenames.
Sometimes it is appropriate to skip the file extension and just give
a filestem, as in `file=earth2moon`.


=== Solutions ===

The solution environment with `!bsol` and `!esol` allows inline
solution as an alternative to the `solution=...` directive mentioned
above (which requires that the solution is in a separate file). Comment
lines are inserted so that the beginning and end of answers and
solutions can be identified and removed if desired. It seems that
DocOnce authors prefer `!bsol` and `!esol` over a separate solution file.

!bwarning Avoid headings in solutions
Headings in solutions in exercises will
appear in table of contents, but if
solutions are left out of the document (using the
`--without_solutions` option), the table of contents will be wrong
and contain non-existing headings from the solution parts.
Therefore, *never use headings in solutions*, just use *paragraph
headings* (double underscores) if you feel the need for headings.
!ewarning

!bwarning Avoid numbered equations in solutions
Numbered equations in solutions will influence the global numbering of
equations in a document (unless exercises always come at the end of
chapters). If you compile versions of the document with and without
solutions, the equation numbering may differ between the versions and may
cause confusion among readers.
!ewarning

The command line options `--without_answers` and `--without_solutions`
turn off output of answers and solutions, respectively, except for
examples.


=== Example ===

A full exercise set-up can be sketched as follows:

!bc do
===== Exercise: Determine the Distance to the Moon =====
label{exer:moondist}
file=earth2moon.pdf

Here goes main body of text describing the exercise...

|bsubex
Subexercises are numbered a), b), etc.

|bans
Short answer to subexercise a).
|eans

|bhint
First hint to subexercise a).
|ehint

|bhint
Second hint to subexercise a).
|ehint
|esubex

|bsubex
Here goes the text for subexercise b).

|bhint
A hint for this subexercise.
|ehint

|bsol
Here goes the solution of this subexercise.
|esol
|esubex

|bremarks
At the very end of the exercise it may be appropriate to summarize
and give some perspectives. The text inside the |bremarks-|eremarks
directives is always typeset at the end of the exercise.
|eremarks

|bsol
Here goes a full solution of the entire exercise, if solutions to
subexercises are not appropraite.
|esol
|ec
!ec

=== Exercise versus Problem and Project ===

Recommended rules for using the different ``exercise'' types goes as follows:

  * Exercises are smaller problems directly related to the present chapter
    (e.g., with references to the text).
  * Problems are sufficiently independent of the chapter's text
    that they make sense on their own, separated from the rest of the document.
  * Projects are larger problems that also make sense on their own.
  * Examples are exercises, problems, or projects, but with full solutions
    not typeset with `!bsol` and `!esol` but as running text

Authors may use `Exercise` everywhere or make use of the convention
in the first three points.

=== Modified Heading ===

Sometimes one does not want the heading of an exercise, problem, project,
or example to contain the keyword `Exercise:`, `Problem:`, `Project:`,
or `Example:`. By enclosing the keyword in braces, as in

!bc do
===== {Problem}: Find a solution to a problem =====
!ec
the keyword is marked for being left out of the heading, resulting in
the heading ``Find a solution to a problem''. In this case, there is
no numbering of exercises, problems, projects, or examples, so
`--section_numbering=on` for numbering *all* sections in the document
may be a desired option.

=== Data Structure for all Exercises ===

The various elements of exercises are collected in a special data
structure (list of dictionaries) stored in a file `.mydoc.exerinfo`,
if `mydoc.do.txt` is the name of the DocOnce file.  The file contains
a list of dictionaries, where keys in the dictionary corresponds to
elements in the exercise: filename, solution file, answer, label, list
of hints, list of subexercises, closing remarks, and the main body of
text.

===== Typesetting of Exercises =====

Tailored formatting of exercises in special output formats can make
use of the elements in an exercise.  For example, one can imagine web
formats where the hints are displayed one by one when needed and where
the result file can be uploaded. One can also think of mechanisms for
downloading the solution file if the result file meets certain
criteria.  DocOnce does not yet generate such functionality in any
output format, but this is an intended future feature to be
implemented.

For now, exercises, problems, projects, examples are typeset as ordinary
DocOnce sections (this is the most general approach that will work for many
formats). One must therefore refer to an exercise, problem, project, or
example by its label, which normally will translate to the section number
(in LaTeX, for instance) or a link to the title of the section.
The *title* is typeset without any leading *Exercise:*, *Problem:*,
or *Project:* word, so that references like

!bc do
see Problem ref{...}
!ec
works well in all formats (i.e., no double `Problem Problem` appears).

=== Remark on Typesetting of Examples ===

Examples are *not* typeset similarly to exercises unless one adds the
command-line option `--examples_as_exercises`. That is, without this
option, any heading and starting with `Example:` makes DocOnce treat
the forthcoming text as ordinary text without any interpretation of
exercise-style instructions.  This is usually what you want.
With the command-line option
`--examples_as_exercises`, one can use the `!bsubex` and `!bsol`
commands to indicate a subproblem and a solution in an example.  In
this way, the typesetting of the example looks like an exercise
equipped with a solution.
As for exercises, the content of the example runs from the heading
until the next subsection.

!bwarning Examples and exercises share the same counter!
If you use the `--examples_as_exercises`, any subsection starting with
`Example:` will get a number for the example, and this number corresponds
to a counter that is shared with Exercise, Problem, and Project.
This may work well if you look at Example, Exercise, Problem, and Project
as much of the same thing, basically Example is then an Exercise with
solution. However, the same numbering of examples and exercises
may look quite odd too, so be careful with the
`--examples_as_exercises` option.
!ewarning

===== List of Exercises, Problems, and Projects =====

DocOnce also supports listing all exercises, problems, and projects
with corresponding page numbers.
By default, no such listing is enabled. When running
`doconce format pdflatex` (or `latex`)
there is a command-line option `--list_of_exercises`
that can be set to

 * `toc`: include exercises, problems, and projects as part of
   the table of contents
 * `loe`: make a separate list of exercises, problems, and projects,
   which appears after the table of contents

There is a special LaTeX environment for the exercises that one can
use to further tailor the appearance of exercises (given that one
edits the `.tex` file, preferably by a script after each `doconce format`
command).

idx{short title (in sections)}

There is also a command `doconce latex_exercise_toc` that makes a special
table of contents of the exercises. It truncates too long exercise headings,
but by inserting `# Short title: Shorter title` right after the heading,
the `Shorter title` will be used as title. Usually, this option is used
if the automatic truncation of the title of the exercise fails (truncation
in the middle of a formula, for instance).

!bc sys
Terminal> doconce latex_exercise_toc mydoc.do.txt "List of Exercises"
!ec
Try it out and compare with other methods for listing the exercises.

===== Numbering of Extra Equations in Solutions =====
label{manual:exercises:sol:no}

A potential problem arises if you produce two versions of your document,
one with solutions and one without solutions (`--without_solutions`),
and there are numbered equations in the solutions. Equations in the
text of the document *after* these exercises sections might then be
numbered differently in the different versions you produce of the text.
There are two ways out of this problem.

=== Book ===

In a book with chapters, collect all exercises at the end in a
separate section ``Exercises''.
Equations are numbered chapter-wise, and equations in solutions
will not influence the numbering of equations before this exercise
section. However, if some of the exercises contain numbered equations
in the exercise text, numbered equations in solutions to previous exercises
will influence the numbering of equations in forthcoming exercise texts.
In such cases, either avoid numbered equations in a solution or in
the exercise text.

=== Use the tag command ===

Equations can be given explicit numbers, completely governed by the writer.
The following equation is given the number `11.5.3` and a label `myeq`:

!bc
|bt
\[ 1 + 1 = 2 \tag{11.5.3}
label{myeq}
|et
!ec
Equations in solutions can then be given their own numbers (here, `11.5`
could be chapter 11, section 5). One can use a Mako variable to automatically
assign appropriate numbers in the `tag` command.

===== Typesetting of solutions to exercises =====
label{manual:exercises:solutions:typesetting}

There is an option `--exercise_solution=` option for controling the
typesetting of solutions. Three values are legal: `paragraph` means that
the solution just gets a paragraph heading, `admon` means that
the solution is typeset within a notice admonition environment (`!bnotice`),
while `quote` means typesetting within a quote environment.

__Suggestion for HTML Bootstrap.__
If your choice is `--exercise_solution=admon`, and you want the
Boostrap HTML output format, use `--html_admon=bootstrap_panel`.  It
makes the solutions stand out nicely in the text.

__Suggestion for LaTeX.__
Sometimes the standard admons are not so suitable for typesetting
solutions because they may have a background color, or they may be too
eye catching. Here is a trick for LaTeX output where we 1) change the
admon environment in solutions from notice to question type, 2) change
the parameters in the question admon so there is no catchy background
color and also a thinner frame, 3) typeset code inside solution
environment without any background color. These modifications can be
done by editing the `mydoc.tex` file in the compilation script (if
`mydoc` is the name of the document).

We can identify all begin and end of question admons in solutions
because both are tagged with the title (`Solution`). Looking at the
`mydoc.tex` file, we can therefore accomplish change number 1 by the
replacements

!bc shcod
doconce replace 'notice_mdfboxadmon}[Solution.]' \
    'question_mdfboxadmon}[Solution.]' mydoc.tex
doconce replace 'end{notice_mdfboxadmon} % title: Solution.' \
    'end{question_mdfboxadmon} % title: Solution.' mydoc.tex
!ec

Change number 2 is done with a regular expression edit that replaces
the complete definition of question admons:

!bc shcod
doconce subst -s '% "question" admon.+?question_mdfboxmdframed\}' \
    '% "question" admon
\colorlet{mdfbox_question_background}{gray!5}
\\newmdenv[        % edited for solution admons in exercises
  skipabove=15pt,
  skipbelow=15pt,
  outerlinewidth=0,
  backgroundcolor=white,
  linecolor=black,
  linewidth=1pt,       % frame thickness
  frametitlebackgroundcolor=blue!5,
  frametitlerule=true,
  frametitlefont=\\normalfont\\bfseries,
  shadow=false,        % frame shadow?
  shadowsize=11pt,
  leftmargin=0,
  rightmargin=0,
  roundcorner=5,
  needspace=0pt,
]{question_mdfboxmdframed}' mydoc.tex
!ec

Change number 3 involves mapping `pycod` and `pypro` environments inside
admons to `pycod2` and `pypro2` and define these environments by the
simpler listing style `greenblue`, which does not have any background
color. Mapping of an environment to another variant inside admons
is described in *LaTeX code Environments Inside Admonitions* in
Section ref{manual:admon}. For this purpose one employs the `--latex_admon_envir_map=` option.

Here is a possible command (that employs a blue background for
all boxes, except `pypro` that gets a frame to indicate ``program'' and
`sys` and `dat` that get a completely different typesetting):

!bc shcod
doconce format pdflatex mydoc \
  "--latex_code_style=default:lst[style=blue1_bluegreen]@
  pypro:lst[style=blue1bar_bluegreen]@
  pypro2:lst[style=greenblue]@
  pycod2:lst[style=greenblue]@
  dat:lst[style=gray]@
  sys:vrb[frame=lines,label=\\fbox{{\tiny Terminal}},
  framesep=2.5mm,framerule=0.7pt,fontsize=\fontsize{9pt}{9pt}]" \
  --exercise_solution=admon --latex_admon_envir_map=2
!ec
(Note that we had to split the `--latex_code_style=` option over
several lines -- everything should be on one line in the compilation script!)

The `--latex_admon_envir_map=2` option renames an environment like `pycod`
inside an admon to `pycod2`, and the `--latex_code_style=` option defines
the new `pycod2` environment to be bluegray syntax highlighting, but no
background color. Note that this applies to all question admons, but
usually there are few question admons, so very often this will be
a specific typesetting for solutions to exercises.

Note that when you use `--exercise_solution=admon` and
`--latex_admon=mdfbox` (default), you cannot have figures with
captions inside the admons, i.e., inside `!bsol` and `!esol` in
the present problem setting. Only *inline figures* will work.
Write these as `FIGURE:` the usual way, but drop the caption.

The current example shows how we can tailor DocOnce output to a level
far beyond what DocOnce itself can output!

# #ifdef EXTRA
===== Where to Put Exercises =====

Some prefer exercises scattered around, while others prefer them in
separate sections. DocOnce has its richest functionality if you
*collect exercises in a separate section* (usually called `Exercises`).
See the section above why exercises scattered around might cause problems.
# #endif

===== Extracting Selected Exercises in a Separate Document =====

idx{`doconce` commands!`extract_exercises`}

The command

!bc sys
Terminal> doconce extract_exercises tmp_mako__mydoc.do.txt --filter=key1;key2
!ec
extracts all exercises in `mydoc.do.txt` with keywords `key1` or `key2`
in a separate document `mydoc_exer.do.txt`. For example, this feature can
be used to extract all exercises suitable for being published as
IPython/Jupyter notebooks (and perhaps automatically graded by "`nbgrader`": "https://github.com/jupyter/nbgrader"). Just attach the keyword `ipynb` to all
exercises suitable for the IPython/Jupyter notebook and run the command
with `--filter=ipynb`. Without `--filter=`, the `extract_exercises` utility
extracts all exercises such that one can publish this document separately,
with or without solutions and/or short answers.
By ``exercise'' we here mean all exercises, problems,
and projects.

The numbering of the exercises in the new document follows the numbering
in the original document[^exer-numbering], but you must use the
`--exercise_numbering=chapter` option in addition if
you want a chapter-based numbering when extracting exercises from a book.

It is also possible to extract examples along with exercises: just add
`--examples_as_exercises` (to extract the examples only, equip them with
a unique keyword that you can use in the `--filter=` option).

[^exer-numbering]: If you want a new natural numbering of the extracted
exercises only, you must go into the DocOnce source file with the
extracted exercises and remove the comment line that contains the
`labels2numbers` dictionary.

__Note:__ Instead of having all filtered exercises in one document, you
may (especially for notebooks) want stand-alone documents for each
exercise, see the next section.

===== Extracting Exercises as Stand-Alone Documents =====
label{exercises:standalone}

It is sometimes convenient to publish exercises from a larger document
as *individual documents*.
With the `--exercises_in_zip` option, DocOnce will
generate a zip file `mydoc_exercises.zip` (for `mydoc.do.txt`) with
each exercise (problem, project, or example) in a separate `.do.txt` file.
The zip archive also contains a script `make.py` for translating the
`.do.txt` files to various formats. In university courses it may be
attractive to give the students `.tex` with the exercise text such that
the students can fill in the answers and extend the text to a report.
Or one may distribute the exercises as IPython/Jupyter Notebook files
and let the students fill in answers in the notebooks. This approach
can be combined with "`nbgrader`": "https://github.com/jupyter/nbgrader"
for automatic grading.

The zip archive also contains a file `index.do.txt` with a list of all
the exercise files that can be published on the Internet and used for
download of the exercises. The `index.do.txt` file contains a variable
`FILE_EXTENSIONS` for the type of formats the exercises are available
in. The user must edit `make.py` accordingly so the right set of
formats are compiled as desired.

__Note:__ Unzipping the archive packs out the files in a subdirectory
`standalone_exercises`. For figure and movie references to work one
needs the `--figure_prefix=../` and `--movie_prefix=../` options.
If the exercise files are distributed to students, make sure figure
files are also available (check by compiling the exercises!).

!bwarning References in stand-alone exercises may not work!
Exercises with references to sections in the running text of the
original document cause trouble when the exercises are compiled as
stand-alone documents. For LaTeX this may work if the original document
is compiled in the parent directory of `standalone_exercises` and
the corresponding `.aux` file is available (the exercise will in such
cases make use of the `# Externaldocuments:` command in the file and
use the `xr` package for cross-referencing between documents).
All other formats will face problems with references to the original
parent document. When missing references are encountered, a comment about
the issue is inserted in the exercise file.
!ewarning

__Naming of Exercise Files.__
The option `--exercises_in_zip_filename=X` can be used to determine the
name of the exercise files. With `X=logical`, the logical name specified by
the `file=` command in the exercise is used. With `X=number`, the
filename contains the exercise number, either an absolute number (integer)
like `132`
or a `chapter.local_number` like `5.2` or `B.4` (in case of an appendix),
depending on the option
`--exercise_numbering=X`, with `X=absolute` or `X=chapter`, respectively.

===== Example of an Exercise =====

The next section show the typesetting of the following exercise.
For output in HTML with various Bootstrap styles, hints and answers
appear as unfolded sections - one must click to open the text.

!bc do
===== Exercise: Compute integrals =====
label{doconce:manual:exercise:ex}
files=integrals.py, integrals.pdf
keywords=1+1; integrals; SymPy

Use the most appropriate tools to answer the various subexercises.

|bsubex
What is 1+1?

|bhint
Your brain is a perfectly appropriate tool for this task.
|ehint
|esubex

|bans
2
|eans

|bsubex
What is the integral of $e^{-ax}\sin(wx)$?

|bhint
Assume $a$ and $w$ real.
|ehint

|bsol
This is an easy task for SymPy:

|bc pyshell
>>> import sympy as sp
>>> x = sp.symbols('x')
>>> a, w = sp.symbols('a w', real=True,positive=True)
>>> F = sp.integrate(sp.exp(-a*x)*sp.sin(w*x), x)
>>> F
-a*sin(w*x)/(a**2*exp(a*x) + w**2*exp(a*x)) -
w*cos(w*x)/(a**2*exp(a*x) + w**2*exp(a*x))
>>> sp.simplify(F)
-(a*sin(w*x) + w*cos(w*x))*exp(-a*x)/(a**2 + w**2)
|ec
That is, $-\frac{e^{- a x}}{a^{2} + w^{2}}
\left(a \sin{\left (w x \right )}
+ w \cos{\left (w x \right )}\right)$.
|esol
|esubex

|bsubex
Compute $\int_{-\infty}^1 e^{-x^4}dx$.

|bsol
Continuing the last session,

|bc pyshell
>>> F = sp.integrate(sp.exp(-x**4), (x, -sp.oo, 0))
>>> F
gamma(1/4)/4
>>> F.evalf()
0.906402477055477
|ec
|esol
|esubex

|bsubex
|bquiz
Q: What is correct about the integral $\int e^{-t^2}dt$?

Cw: The integral is the error function.
E: Almost correct, but the error function has a slightly different
definition:

|bt
\[ \hbox{erf}(x) = \frac{2}{\sqrt{2}}\int_{0}^x e^{-t^2}dt.\]
|et

Cw: It cannot be computed.
E: That would be correct if computed means ``calculated as
a closed-form formula by hand'', but the integral
$\int_a^b e^{-t^2}dt$ can be easily computed numerical
methods.

Cr: It equals

|bt
\[ \frac{\Gamma{\left(\frac{1}{4} \right)}
\gamma\left(\frac{1}{4}, x^{4}\right)}{16
\Gamma{\left(\frac{5}{4} \right)}},\]
|et
where $\Gamma(x)$ is the (upper) incomplete gamma function
and $\gamma(x)$ is the lower incomplete gamma function
(see "Wikipedia":
"http://en.wikipedia.org/wiki/Incomplete_gamma_function"
for definition).
E: This is correct, as proved by SymPy:

|bc pyshell
>>> import sympy as sym
>>> F = sym.integrate(sym.exp(-x**4), x)
>>> F
gamma(1/4)*lowergamma(1/4, x**4)/(16*gamma(5/4))
|ec

Cw: It equals the cumulative normal density function.
E: The cumulative normal density function, with mean $\mu$ and
standard deviation $\sigma$, is defined as

|bt
\[ \Phi(x) = \int_{-\infty}^x \frac{1}{\sqrt{2\pi}\sigma}
e^{-\frac{(t-\mu)^2}{2\sigma}}dt.\]
|et
|equiz
|esubex

|bremarks
This exercise demonstrates subexercise, hint, solution, short answer,
multiple-choice question (quiz), and final remark - combined with
mathematics and computer code.
|eremarks
!ec


===== Exercise: Compute integrals =====
label{doconce:manual:exercise:ex}
files=integrals.py, integrals.pdf
keywords=1+1; integrals; SymPy

Use the most appropriate tools to answer the various subexercises.

!bsubex
What is 1+1?

!bhint
Your brain is a perfectly appropriate tool for this task.
!ehint

!bans
2
!eans
!esubex

!bsubex
What is the integral of $e^{-ax}\sin(wx)$?

!bhint
Assume $a$ and $w$ real.
!ehint

!bsol
This is an easy task for SymPy:

!bc pyshell
>>> import sympy as sp
>>> x = sp.symbols('x')
>>> a, w = sp.symbols('a w', real=True,positive=True)
>>> F = sp.integrate(sp.exp(-a*x)*sp.sin(w*x), x)
>>> F
-a*sin(w*x)/(a**2*exp(a*x) + w**2*exp(a*x)) -
w*cos(w*x)/(a**2*exp(a*x) + w**2*exp(a*x))
>>> sp.simplify(F)
-(a*sin(w*x) + w*cos(w*x))*exp(-a*x)/(a**2 + w**2)
!ec
That is, $-\frac{e^{- a x}}{a^{2} + w^{2}}
\left(a \sin{\left (w x \right )}
+ w \cos{\left (w x \right )}\right)$.
!esol
!esubex

!bsubex
Compute $\int_{-\infty}^1 e^{-x^4}dx$.

!bsol
Continuing the last session,

!bc pyshell
>>> F = sp.integrate(sp.exp(-x**4), (x, -sp.oo, 0))
>>> F
gamma(1/4)/4
>>> F.evalf()
0.906402477055477
!ec
!esol
!esubex

!bsubex
!bquiz
Q: What is correct about the integral $\int e^{-t^2}dt$?

Cw: The integral is the error function.
E: Almost correct, but the error function has a slightly different
definition:

!bt
\[ \hbox{erf}(x) = \frac{2}{\sqrt{2}}\int_{0}^x e^{-t^2}dt.\]
!et

Cw: It cannot be computed.
E: That would be correct if computed means ``calculated as
a closed-form formula by hand'', but the integral
$\int_a^b e^{-t^2}dt$? can be easily computed numerical
methods.

Cr: It equals

!bt
\[ \frac{\Gamma{\left(\frac{1}{4} \right)}
\gamma\left(\frac{1}{4}, x^{4}\right)}{16
\Gamma{\left(\frac{5}{4} \right)}},\]
!et
where $\Gamma(x)$ is the (upper) incomplete gamma function
and $\gamma(x)$ is the lower incomplete gamma function
(see "Wikipedia":
"http://en.wikipedia.org/wiki/Incomplete_gamma_function"
for definition).
E: This is correct, as proved by SymPy:

!bc pyshell
>>> F = sp.integrate(sp.exp(-x**4), x)
>>> F
gamma(1/4)*lowergamma(1/4, x**4)/(16*gamma(5/4))
!ec

Cw: It equals the cumulative normal density function.
E: The cumulative normal density function, with mean $\mu$ and
standard deviation $\sigma$, is defined as

!bt
\[ \Phi(x) = \int_{-\infty}^x \frac{1}{\sqrt{2\pi}\sigma}
e^{-\frac{(t-\mu)^2}{2\sigma}}dt.\]
!et
!equiz
!esubex

!bremarks
This exercise demonstrates subexercise, hint, solution, short answer,
multiple-choice question (quiz), and final remark - combined with
mathematics and computer code.
!eremarks

!split
======= Other Environments =======

===== Blocks of Verbatim Computer Code =====
label{sec:verbatim:blocks}

idx{verbatim text, code blocks}
idx{code blocks}
idx{syntax highlighting}
idx{computer code blocks}

Blocks of computer code, to be typeset verbatim, must appear inside a
``begin code'' `!bc` keyword and an ``end code'' `!ec` keyword. Both
keywords must be on a single line and *start at the beginning of the
line*.  Before such a code block there must be a plain sentence
(at least if successful transformation to reST and
ASCII-type formats is desired). For example, a code block cannot come
directly after a section/paragraph heading or a table.

Here is a plain code block:

!bc do
|bc dat
% Could be a comment line in some file
% And some data
1.003 1.025
2.204 1.730
3.001 1.198
|ec
!ec
which gets rendered as

!bc dat
% Could be a comment line in some file
% And some data
1.003 1.025
2.204 1.730
3.001 1.198
!ec

!bnotice Tip: let code lines be shorter than 67 characters
Most output formats from DocOnce will get nice-looking code
environments if you keep the length of lines in source code
below or equal to 67 characters.
!enotice

=== Typesetting Styles ===

There may be an argument after the `!bc` tag to specify a certain
environment (in LaTeX, HTML, or Sphinx) for
typesetting the verbatim code. For instance, `!bc dat` corresponds to
the data file environment and `!bc cod` is typically used for a code
snippet. There are some predefined environments explained below. If
there is no argument specifying the environment, one assumes some
plain verbatim typesetting (usually just the most plain verbatim
style in LaTeX or HTML, or `python` in Sphinx,
or if `ptex2tex` is used, the environment
corresponds to `ccq` which is defined in the config file `.ptex2tex.cfg`).

By default, `pro` is used for complete programs, `cod` is for a code
snippet. The syntax `Xcod` and `Xpro` imply a program or snippet in
computer language `X`, where `X` can be `f` for Fortran, `c` for C,
`cpp` for C++, `sh` for Unix shells, `pl` for Perl, `m` for Matlab,
`cy` for Cython, `r` for Ruby, `js` for JavaScript, `latex` for LaTeX,
`html` for HTML, and `py` for Python.  With no `X` prefix, `cod` and
`pro` implies Python code. The argument `sys` after `!bc` means a
verbatim environment suitable for operating system commands (and
output).  As mentioned, `dat` is for a data file or print out,
`pyshell` is for plain interactive Python shell sessions, `ipy`
for interactive IPython sessions, and `pysc` turns on interactive
Python code in executable HTML windows (using a SageMathCell server)
while being equivalent to `pycod` in other formats.

Notebooks and other executable code snippets in HTML may need some
initializing code before a snippet works, and if such code is
not intended for being shown in the text, one can use the `Xhid`
argument to `!bc`, where `hid` indicates a hidden snippet. It becomes
executable in live code environments but is otherwise not shown.

All these definitions of the arguments after `!bc` can be redefined
in command-line arguments for the `--latex_code_style=` option,
the `.ptex2tex.cfg` configuration file for `ptex2tex`, and in
the `sphinx code-blocks` comments for Sphinx, see below.

idx {`-t` code envir postfix}

=== Executable and Non-Executable Code ===

The `ipynb` and `matlabnb` formats create notebooks where computer
code can be executed. Sometimes one wants to show code that is *not*
to be executed, but just shown as a text block. Any code environment
with a postfix `-t` indicates that the code is not to be executed, only
displayed. For example, `!bc pycod-t` is a Python snippet not intended
for execution. All other formats than the notebook formats ignore the
`-t` postfix.

idx {`-h` code envir postfix}

=== Hiding code blocks in HTML ===

Code blocks in HTML can be visible or not by clicking on an associated
button _Show/hide code_. The behavior is triggered by a postfix `-h` to
the code environment, e.g., `!bc pycod-h` or `!bc pro-h`.
The `-h` postfix has no impact on other output formats.

idx{`sphinx code-blocks:`}

=== Customizing Code Environments Types for Sphinx ===

The argument after `!bc` can in case of Sphinx output be mapped onto
any valid Pygments language for typesetting of the verbatim block by
Pygments, if you do not want to rely on the defaults. This mapping
takes place in an optional comment to be inserted in the DocOnce
source file. Here is an example on such a comment line:

!bc do
# sphinx code-blocks: pycod=python cod=fortran cppcod=c++ sys=console
!ec
Three arguments are defined: `!bc pycod` maps on to the
Pygments style `python` for Python code,
`!bc cod` maps on to the Pygments style `fortran` for Fortran
code, `!bc cppcod`  maps on to the Pygments style `c++` for C++ code,
and `!bc sys` maps on to the Pygments `console` style for
terminal sessions. The same arguments would be defined
in `.ptex2tex.cfg` or on the command line for `doconce ptex2tex`
for how to typeset the blocks in LaTeX using
various verbatim styles (Pygments can also be used in a LaTeX
context).

# (Any sphinx code-block comment, whether inside verbatim code
# blocks or outside, yields a mapping between bc arguments
# and computer languages. In case of muliple definitions, the
# first one is used.)

=== Examples ===

Here is a verbatim code block with Python code (`pycod` style):

!bc do
|bc pycod
def f(x, y):
    return x + y

# Main program
from math import pi
print 'Testing f:', f(pi, 0)
|ec
!ec
The typeset result of this block becomes

!bc pycod
def f(x, y):
    return x + y

# Main program
from math import pi
print 'Testing f:', f(pi, 0)
!ec

!bwarning Tip
The enclosing `!ec` tag of verbatim computer code blocks must
be followed by a newline.  A common error in list environments is to
forget to indent the plain text surrounding the code blocks. In
general, we recommend to use paragraph headings instead of list items
in combination with code blocks (it usually looks better, and some
common errors are naturally avoided).
!ewarning

And here is a C++ code snippet (`cppcod` style):

!bc do
|bc cppcod
void myfunc(double* x, const double& myarr) {
    for (int i = 1; i < myarr.size(); i++) {
        myarr[i] = myarr[i] - x[i]*myarr[i-1]
    }
}
|ec
!ec
with the rendered result

!bc cppcod
void myfunc(double* x, const double& myarr) {
    for (int i = 1; i < myarr.size(); i++) {
        myarr[i] = myarr[i] - x[i]*myarr[i-1]
    }
}
!ec

# When showing @@@COPY from file in !bc envir, indent a character - otherwise
# ptex2tex is confused and starts copying. However, here we use
# doconce ptex2tex which does not have this problem.

=== Copying Code from Source Files ===

Computer code can be copied directly from a file, if desired. The syntax
is then

!bc do
@@@CODE myfile.f
@@@CODE myfile.f fromto: subroutine\s+test@^C\s{5}END1
!ec
The first line implies that all lines in the file `myfile.f` are
copied into a verbatim block, typset in a `!bc Xpro` environment, where
`X` is the extension of the filename, here `f` (i.e., the environment
becomes `!bc fpro` and will typically lead to some Fortran-style
formatting).  The
second line has a `fromto:` directive, which implies copying code
between two lines in the code, typset within a !`bc Xcod`
environment (again, `X` is the filename extension, implying the
type of file). Note that the `pro` and `cod` arguments are only used for LaTeX
and Sphinx output, all other formats will have the code typeset within
a plain `!bc` environment.) Two regular expressions, separated by the
`@` sign, define the ``from'' and ``to'' lines.  The ``from'' line is
included in the verbatim block, while the ``to'' line is not. In the
example above, we copy code from the line matching `subroutine test`
(with as many blanks as desired between the two words) and the line
matching `C END1` (C followed by 5 blanks and then the text END1). The
final line with the ``to'' text is not included in the verbatim block.


One can also specify the code environment explicitly rather than relying
on the file extension:

!bc do
@@@CODE somefile.py envir=X fromto: def myfunc@def yourfunc
!ec
This is the same as writing `!bc X` and copying parts of the `somefile.py`
text into the DocOnce source file, followed by `!ec`.
For example, if the lines between the `myfunc` and `yourfunc` functions
actually work as a complete Python program, one could specify `envir=pypro`
to indicate that it is a complete program that can be run as is.
By default, copying a part of a `.py` file will lead to
`!bc pycod`, which indicates a code snippet that normally needs
additional code to be run.

Using `envir=None` results in a pure include of the file, without any
surrounding code environment (i.e., no `!bc` or `!ec` directives around
the contents of the file). Section ref{manual:mako:nomenclature} shows
an example.

Let us demonstrate the result of copying a whole file, as
specified in the first line above:

@@@CODE __testcode.f

Let us then copy just a piece in the middle as indicated by the `fromto:`
directive above:

@@@CODE __testcode.f fromto:subroutine\s+test@^C\s{5}END1

=== The `fromto` and `from-to` directives ===

Note that the ``to'' line is never copied into the DocOnce file, but the
``from'' line is. Sometimes it is convenient to also neglect the
``from'' line, a feature that is allowed by replacing `fromto:` by
`from-to` (``from with minus''). This allows for copying very similar
code segments throughout a file, while still distinguishing between them.
Copying the second set of parameters from the text

!bc cod
# --- Start Example 1 ---
c = -1
A = 2
p0 = 4
simulate_and_plot(c, A, p0)
# --- End Example 1 ---

# --- Start Example 2 ---
c = -1
A = 1
p0 = 0
simulate_and_plot(c, A, p0)
# --- End Example 2 ---
!ec
is easy with

!bc do
from-to: Start Example 2@End Example 2
!ec
With only `fromto:` this would be impossible.

Remark for those familiar with `ptex2tex`: The from-to
syntax is slightly different from that used in `ptex2tex`. When
transforming DocOnce to LaTeX, one first transforms the document to a
`.p.tex` file to be treated by `ptex2tex` or `doconce ptex2tex`.
However, note that the `@@@CODE` line
is always interpreted by DocOnce first.

Remark for those familiar with the `listings` package in LaTeX: the
`listing` package can copy code from files, but snippets must be
specified through exact line numbers. The `@@@CODE` directive
above works with regular expressions which are much less sensitive
to edits of the source code file than the line numbers.
Moreover, copy of code from file works in DocOnce across formats
(HTML, Sphinx, Markdown, etc.).

The `--code_prefix=text` option adds a path `text` to the filename specified
in the `@@@CODE` command. For example

!bc
 @@@CODE src/myfile.py
!ec
and `--code_prefix=http://some.place.net`, the file

!bc
http://some.place.net/src/myfile.py
!ec
will be included. If source files have a header with author, email, etc.,
one can remove this header by the option `'--code_skip_until=# ---'`.
The lines up to and including (the first) `# ---` will then be excluded.

!bwarning The regular expressions in `CODE` commands are non-greedy!
The copying of code from file will search for the first occurrence of
the ``from'' regular expression and then continue up to the first
occurrence of the ``to'' expression. This means a non-greedy regular
expression. A to make the expression greedy is
to insert a comment statement as the ``to'' expression to make a
special end of the snippet to be copied. For example, you have the
code

!bc pycod
compute(x)
print x
x = new(x)
compute(x)
print x
x = new(x)
compute(x)
!ec
and you want to copy from the first `compute` and include the second,
but not the following `print x` statement, i.e.,

!bc pycod
compute(x)
print x
x = new(x)
compute(x)
!ec
`fromto: compute@compute` will not work. The way to do this is to insert
a comment statement after the desired ``to'' expression:

!bc pycod
compute(x)
print x
x = new(x)
compute(x)
# dummy comment
print x
x = new(x)
compute(x)
!ec
The regular expressions are then `fromto: compute@# dummy comment`
(``from'' and ``to'' are
actually plain text here -- no use of special regular expressions).
!ewarning

=== Removing indentation in copied code ===

In general, it is not recommended to have a code block where all lines
are indented, because in some output formats the indentation is respected
(e.g., LaTeX) while others ignore it (e.g., Sphinx). Therefore, at least
one line of the code should start in column 1.

Sometimes you want to copy a part of a function where all code is indented.
Then you also want to remove the indentation. This is enabled by
`@@@CODE-X`, where `X` is the number of blanks in the indentation to be
removed. For example, `@@@CODE-4` will copy the code and remove the first
4 characters from each line.

!split
===== LaTeX Blocks of Mathematical Text =====
label{mathtext}

idx{mathematical equations}
idx{equations}
idx{LaTeX blocks with math}

Blocks of mathematical text are like computer code blocks, but
the opening tag is `!bt` (begin TeX) and the closing tag is
`!et`. It is important that `!bt` and `!et` appear on the beginning of the
line and followed by a newline.

!bc do
|bt
\begin{align}
{\partial u\over\partial t} &= \nabla^2 u + f,
label{myeq1}\\
{\partial v\over\partial t} &= \nabla\cdot(q(u)\nabla v) + g.
label{myeq2}
\end{align}
|et
!ec
Here is the result:

!bt
\begin{align}
{\partial u\over\partial t} &= \nabla^2 u + f,
label{myeq1}\\
{\partial v\over\partial t} &= \nabla\cdot(q(u)\nabla v) + g.
label{myeq2}
\end{align}
!et


=== Support of LaTeX Math in Various Output Formats ===

The support of LaTeX mathematics varies among the formats:

 * Output in LaTeX (`latex` and `pdflatex` formats) has full
   support of all LaTeX mathematics, of course.
 * The `html` format supports single equations and multiple equations
   via the align environment, also with labels.
 * Markdown (`pandoc` format) allows single equations and inline mathematics,
   but does not allow references to equations (the generated DocOnce code
   simulates such references, however).
 * MediaWiki (`mwiki` format) does not enable labels in equations and hence
   equations cannot be referred to.

!bwarning Important!
The main conclusion is that for
output beyond LaTeX (`latex` and `pdflatex` formats), stick to
simple `\[` and `\]` or `equation` and `align` or `align*` environments,
and avoid referring to equations in MediaWikis.
!ewarning

idx{MS Word}
idx{Word (Microsoft)}

Going from DocOnce to MS Word is most easily done by outputting in the
`latex` format and then using the "Pandoc":
"http://johnmacfarlane.net/pandoc/" or "latex2rtf":
"http://latex2rtf.sourceforge.net/" programs to translate from LaTeX
to MS Word. Note that only a subset of LaTeX will be translated
correctly, and mathematics is notoriously difficult and unpredictable.

idx{epub}
idx{`epubmaker.py`}
idx{Calibre}

=== ePub and Mobi ===

Conversion to the ePub and Mobi formats, popular for reading on Kindle
devices, can go via HTML and the "Calibre":
"http://calibre-ebook.com/" tools. On Debian/GNU Linux, install
`sudo apt-get install calibre`, and run (e.g.)

!bc sys
Terminal> ebook-convert mydoc.html mydoc.epub
Terminal> ebook-convert mydoc.html mydoc.mobi
Terminal> ebook-convert mydoc.pdf  mydoc.epub
Terminal> calibre mydoc.epub  # view ebook
!ec
Unfortunately, it seems that HTML and PDF documents with
mathematics cannot be converted to ePub by Calibre (PDF
looks strange, MathJax is not used to render formulas in HTML).
For documents with mathematics, `ebook-convert` is a fine tool, but
blocks of computer code may need reformatting in terms of shorter lines.

Pandoc is another program that can generate ePub (not tested).  The
ePub3 format supports mathematics via MathML.  Some dicussions of this
topic appear in URL:
"http://tex.stackexchange.com/questions/1551/use-latex-to-produce-epub". The
"LaTeXML": "http://dlmf.nist.gov/LaTeXML/" program can convert LaTeX
to XML and XHTML and can be a good starting point for further
conversion to ePub, but the plain `latexml` fails miserably on LaTeX
documents generated from DocOnce (the present manual to be precise).

Sphinx is seemingly good support for compiling the document to
the ePub and MOBI formats, but this author has not yet tried it out.
One should definitely test Sphinx along with `ebookmaker.py` (see next
paragraph) if the ePub or MOBI is a requested format.

What has been successfully used to convert DocOnce documents with
mathematics and code to ePub is
the `ebookmaker.py` script (use this "fork": "https://github.com/hplgit/ebookmaker" by the author for a version of this script that actually works).
HTML, in particular with Bootstrap styles, translates well to ePub by
this script. The script requires a JSON file describing the content of
the book. A typical file for a DocOnce document `mydoc.do.txt` that
is translated to HTML and split into a series of files `._mydoc*.html`
goes as follows:

!bc
{
    "filename" : "mydoc",
    "title" : "Title of the document",
    "authors" : [
        {
            "name" : "Hans Petter Langtangen",
            "sort" : "Langtangen, Hans Petter"
        }
    ],
    "rights" : "Public Domain",
    "language" : "en",
    "publisher": "hpl",
    "subjects" : [ "Science" ],
    "contributors" : [
        {
            "name" : "Hans Petter Langtangen",
            "role" : "author"
        }
    ],
    "identifier" : {
        "scheme" : "URL",
        "value" : "http://somewhere.net"
    },
    "contents" : [
        {
            "type" : "text",
            "source" : "._mydoc*.html"
        }
    ],
    "toc" : {
        "depth" : 2,
        "parse" : [ "text" ],
        "generate" : {
            "title" : "Index"
        }
    }
}
!ec
Just edit this file, save it as `mydoc.json` and run
`python3 /some/path/to/epubmaker.py mydoc.json` to produce `mydoc.epub`.

idx{Kindle}

If you want to read your DocOnce document on Kindle, sending the PDF
file to the email address for the device seems to be a satisfactory option.


=== Apple iBook Format ===

A converter to iBooks would be nice. In theory, ePub documents can be
imported and converted to iBooks in the iBooks Author application, but
ePub files created by `ebookmaker.py` do not translate well.
The `.iba` files of iBooks documents can be unzipped and the
XML code for the book is available in `index.xml`. However, the XML
is undocumented and must be manipulated and filled with the contents
of a DocOnce document, e.g., by first translating DocOnce to HTML,
and then using BeautifulSoup to get an XHTML version of the HTML
that can act as a starting point for filling the XML file for an
iBook. See also other "ideas": "http://christian-fries.de/blog/files/2012-10-iBooks-Author-LaTeX.html".

=== Dealing with Mathematics in Formats without LaTeX Math Support ===

If the document targets formats with and without support of LaTeX
mathematics, one can use the preprocessor to typeset the mathematics
in two versions. After `#if FORMAT in ("latex", "pdflatex", "html",
"sphinx", "mwiki", "pandoc")` one places LaTeX mathematics, and after
`#else` one can write inline mathematics in a way that looks nice in
plain text and wiki formats without support for mathematical
typesetting. Such branching can be used with mako if-else statements
alternatively:

!bc do
% if FORMAT in ("latex", "pdflatex", "html", "sphinx", "mwiki", "pandoc"):
|bt
\[ \sin^2x + \cos^2x = 1,\]
|et
% else:
|bc
              sin^2(x) + cos^2(x) = 1,
|ec
% endif
!ec


=== Mathematics for PowerPoint/OpenOffice ===

If you have LaTeX mathematics written in DocOnce, it is fairly easy
to generate PNG images of all mathematical formulas and equations for
use with PowerPoint or OpenOffice presentations.

  o Make a Sphinx version of the DocOnce file.
  o Go to the Sphinx directory and load the `conf.py` file into
    a browser.
  o Search for ``math'' and comment out the
    `'sphinx.ext.mathjax'` (enabled by default) and
    `'matplotlib.sphinxext.mathmpl'` (disabled by default)
    lines, and uncomment the `'sphinx.ext.pngmath'` package.
    This is the package that generates small PNG pictures
    of the mathematics.
  o Uncomment the line with `pngmath_dvipng_args =` and
    set the PNG resolution to `-D 200` when the purpose is to
    generate mathematics pictures for slides.
  o Run `make html`.
  o Look at the HTML source file in the `_build/html`
    directory: all mathematics are in `img` tags with `src=`
    pointing to a PNG file and `alt=` pointing to the LaTeX
    source for the formula in question. This makes it very
    easy to find the PNG file that corresponding to a particular
    mathematical expression.

!split
===== Macros (Newcommands) =====
label{newcommands}

idx{LaTeX newcommands}
idx{newcommands (LaTeX)}
idx{macros (LaTeX)}

DocOnce supports a type of macros via a LaTeX-style *newcommand*
construction, but only inside mathematical expressions (inline
LaTeX math or LaTeX math blocks). Newcommands are not allowed
in the running text. Here is an example:

@@@CODE newcommands_replace.tex

!bnotice
If you desire a newcommand for the running text, using a Mako function
(written in plain Python) is much more flexible. See
Section ref{manual:mako}.
!enotice

The newcommands must be defined by the standard LaTeX command

!bc latexcod
\newcommand{name}{definition}
!ec
in a separate file with name
`newcommands*.tex`. Use of `\def` is ignored. Each newcommand
definition *must* appear on a single line.

Newcommands in a file with name
`newcommand_replace.tex` are expanded when DocOnce is translated to
other formats, except for LaTeX (since LaTeX performs the expansion
itself).  Newcommands in files with names `newcommands.tex` and
`newcommands_keep.tex` are kept unaltered when DocOnce text is
translated to other formats, except for the Sphinx format. (Since Sphinx
understands LaTeX math, but not newcommands if the Sphinx output is
HTML, it makes most sense to expand all newcommands.)  Normally, a user
will put all newcommands that appear in math blocks surrounded by
`!bt` and `!et` in `newcommands_keep.tex` to keep them unchanged, at
least if they contribute to make the raw LaTeX math text easier to
read in the formats that cannot render LaTeX.


# #ifdef EXTRA
__Example.__ Suppose we have the following commands in
`newcommand_replace.tex`:

@@@CODE newcommands_replace.tex

and these in `newcommands_keep.tex`:

@@@CODE newcommands_keep.tex

The LaTeX block

!bc do
\beqa
\x\cdot\normalvec &=& 0, label{my:eq1}\\
\Ddt{\uvec} &=& \Q \ep   label{my:eq2}
\eeqa
!ec
will then be rendered to

!bt
\beqa
\x\cdot\normalvec &=& 0, label{my:eq1}\\
\Ddt{\uvec} &=& \Q \ep   label{my:eq2}
\eeqa
!et
in the current format.
# #endif

# #include "guidelines.do.txt"


===== Typesetting of Algorithms =====

idx{algorithms}

DocOnce has no support for typesetting of algorithms, while LaTeX
has quite sophisticated support. LaTeX writes need some strategy with
dealing with algorithms in DocOnce: they should be sophisticated
when the output is in LaTeX and they should be readable when the
output is in other formats that have no native support for
algorithms.

The simplest solution is to use the preprocessor (Preprocess or Mako)
to allow different solutions for different formats.
There are basically three typesetting styles available: LaTeX
algorithm environments, pseudo code in a verbatim block, and
a nested list. A preprocessor variable, say `ALG` can be used
to select the typesetting. With Mako we can write

!bc do
% if ALG == 'latex':
# Write native LaTeX code for the algorithm
% elif ALG == 'code':
# Write pseudo code in (e.g.) a python-like style
|bc pycode
if feature in element:
...
|ec
% elif ALG == 'list':
# Use lists to express the algorithm
  o if this element has the feature:
    * ...
% endif
!ec


!split
===== Admonitions =====
label{manual:admon}

idx{admonitions}
idx{warning admon}
idx{notice admon}
idx{summary admon}
idx{question admon}
idx{block admon}

DocOnce offers strong support for admonition environments, such
as warning boxes, notification boxes, question boxes,
and summary boxes. The boxes normally have an icon, a heading,
and may also have a background color. A special box, the block,
has never any icon and can be used when an icon would be disturbing
or misleading. The variety of admonitions and their many typesetting
styles are available through a "demo": "http://hplgit.github.io/doconce/doc/pub/admon/index.html".

=== Examples on Admonition Types ===

The following admonition environments are available:
`block`, `warning`, `notice`, `question`, and `summary`.
The box is defined by begin and end tags such as `!bnotice` and `!enotice`.
The title of the box is fully customizable. This means that if you want
different types of boxes, e.g. a *detour* box and a *tip* box, you can just
open introduce the convention that detour applies the summary box and
starts with 'Detour:' in the title, while the notice box is used for
tip boxes and as a title starting with 'Tip:'.

Here are a few examples:

!bc do
|bwarning
Here is a warning!
|ewarning

|bnotice
This is a notice box with default title.
|enotice

|bnotice Hint
A *Hint* or *Tip* box can use the `notice` box.
|enotice

|bquestion
How many admonition types are there in DocOnce?
|equestion

|bblock This is a block.
A block never has any icon. A block has never any icon,
but may feature a title. It is often used in slides.
|eblock

|bnotice Going deeper
This is text meant to provide more details. The box has the
layout of the notice box, but a custom title, here *Going deeper*.
|enotice

Finally some summary:

|bsummary
The main message is to utilize the admonition styles for
marking different parts of the text
|esummary
!ec
The above DocOnce code is in the present format rendered as

!bwarning
Here is a warning!
!ewarning

!bnotice
This is a notice box with default title.
!enotice

!bnotice Hint
A *Hint* or *Tip* box can, e.g., use the `notice` box.
!enotice

!bquestion
How many admonition types are there in DocOnce?
!equestion

!bblock This is a block.
A block never has any icon. A block has never any icon,
but may feature a title. It is often used in slides.
!eblock

!bnotice Going deeper
This is text meant to provide more details. The box has the
layout of the notice box, but a custom title, here *Going deeper*.
!enotice

Finally some summary:

!bsummary
The main message is to utilize the admonition styles for
marking different parts of the text
!esummary


The layout of admonitions depend on the format.  In the `rst` and
`sphinx` formats one applies the native admonitions, but in `sphinx`
the `automake_sphinx.py` script manipulates the HTML file to set a
gray background for all admonitions.  In `html`, `latex` and
`pdflatex` there is quite some functionality to control the layout of
admonitions.

idx{admonition layout}
idx{HTML admonitions}

=== Layout of Admonitions in HTML ===

The command-line argument `--html_admon` sets the admonition style
for the `html` format (see "demo": "http://hplgit.github.io/doconce/doc/pub/admon/index.html"):

 * `--html_admon=gray` for
   icons with gray background and small font,
 * `--html_admon=yellow`
   and `--html_admon=apricot` are similar,
   but the icons and colors are different,
 * `--html_admon=colors` has quite bright colors
   as backgrounds for the different admonitions,
 * `--html_admon=lyx`
   gives a white background and small icons,
 * `--html_admon=bootstrap_alert` gives the common colored admonition
   boxes associated with the Bootstrap HTML styles (only effective
   if `--html_style=boots*`),
 * `--html_admon=bootstrap_panel` applies the panel construction
   in Bootstrap to make admonition boxes with (normally) white background
   but a colored background for the title (only effective
   if `--html_style=boots*`),
 * `--html_admon=paragraph` results in a simple paragraph with the
   admon title as heading. With `--html_admon=paragraph-X`, where `X`
   is `small` or `large` (or a number less than 100 or grater than 100,
   resp.). The admon text is then typeset with a small or large font.

The options `--html_admon_bg_color=...` and `--html_admon_bd_color=...`
can be used to override the default background and boundary frame colors
of the admon styles (respectively). These options have only effect
for the `apricot`, `yellow`, and `gray` styles.

Some recommended combinations for admonitions in HTML are

 * `--html_style=bloodish`, `--html_admon=gray`, `--pygments_html_style=none` or
   `--pygments_html_style=default`
 * `--html_style=blueish2`, `--html_admon=yellow`, `--pygments_html_style=none` or `--pygments_html_style=default`
 * `--html_style=boots*`, `--html_admon=bootstrap_alert` or `--html_admon=bootstrap_panel`

idx{LaTeX admonitions}

=== Layout of Admonitions in LaTeX ===

In `latex` and `pdflatex`, the type of admonition style is set by
the command-line option `--latex_admon=`.
Several values are available (see "demo": "http://hplgit.github.io/doconce/doc/pub/admon/index.html"):

 * `paragraph` is the simplest type of admonition and typeset
   as plain text with an optional paragraph heading. The variant
   `paragraph-X` typesets the paragraph with font size `X`, where
   `X` can be `large`, `small`, `footnotesize`, or `tiny`. With the `X`
   specification there is also some small space above and below the admon.
 * `colors1` (inspired by the original NumPy User Guide in LaTeX/PDF)
   applies different colors for
   the different admons with an embedded icon.
 * `colors2` is like `colors1` but the text is wrapped around the icon.
 * `mdfbox` is the default and gives rounded white boxes with a potential
   title and no icon (using the very flexible `mdframed` packaged in LaTeX).
 * `graybox2` has square corners, gray background, and is narrower
   than `mdfbox`. One special feature of `graybox2` is the summary
   admon, which has a different look with horizontal rules only,
   and for A4 format, the summary box is half of the text width and
   wrapped with running text around (if it does not contain verbatim text,
   in that case the standard `graybox2` style is used). This small
   summary box is effective in proposals to disperse small paragraphs
   of key points around.
 * `grayicon` has icons and a light gray background.
 * `yellowicon` has icons and a light yellow background.

There is also an option `--latex_admon_color=...` that can be used
to override the default color. Values are either saturated colors
like `gray!10` or an RGB tuple `0.95,0.91,0.97`. The chosen color
replaces all default colors for all admon styles except `paragraph`.
For example, an oval gray box is produced by `--latex_admon=mdfbox`
and `'--latex_admon_color=gray!10'` (note the quotes: they are necessary
to avoid a Bash error due to the exclamation mark in the color
specification).

The `mdfbox` admonition styles has boxes with many possibilities for
customization by editing the `.tex` file. For example, `linecolor`
sets the color of the frame border and `frametitlebackgroundcolor`
sets the background color of the title area. A dark blue frame and
a light blue background for the title is produced by this automatic
edit:

!bc shpro
doconce replace 'linecolor=black,' 'linecolor=darkblue,' mydoc.tex
doconce subst 'frametitlebackgroundcolor=.*?,' 'frametitlebackgroundcolor=blue!5 mydoc.tex
!ec

Admonition titles without a period, exclamation mark, or colon at the end
will by default get a period at the end. For some LaTeX admonitions
(e.g., `mdfbox`), it may be natural to view the title with a heading
*without* any period. The command-line option `--latex_admon_title_no_period`
avoids appending a period.

=== LaTeX code Environments Inside Admonitions ===

Sometimes one sets a special background color in the admonitions, and
colored code blocks, which look fine in the running text, may then
have inappropriate colors inside admonitions. The option
`--latex_admon_envir_map=...` is used to map an environment (usually
for code) to a new style inside admonitions. Specifying a number,
say 2, as in `--latex_admon_envir_map=2`, appends the number
to all environments inside admonitions, so `!bc pycod` becomes
effectively `!bc pycod2`.
One can then in `doconce ptex2tex` (or in the `ptex2tex` configuration
file) specify the typesetting
of the `pycod2` environment.
Otherwise the specification must be a mapping for each envir
that should be changed inside the admons:

!bc
--latex_admon_envir_map=pycod-pycod_yellow,fpro-fpro2
!ec
i.e., a from-to, from-to type of syntax. In this particular example,
the `!bc pycod` environment becomes `!bc pycod_yellow` and
`!bc fpro` becomes `!bc fpro2` inside admonitions.

idx{box environment}
idx{frame (box) environment}
idx{equation with frame}

=== The Box Environment ===

A plain box without any title or colored background,
just a rectangular frame, is also
available. The syntax goes like

!bc do
|bbox
|bt
\[ \nabla\cdot\bm{u} = 0  \quad\hbox{(mass balance)}\]
|et
|ebox
!ec
resulting in

!bbox
!bt
\[ \nabla\cdot\bm{u} = 0\quad\hbox{(mass balance)}\]
!et
!ebox

Admonitions are usually used to typeset something that should be distinct
from the running text: a warning, a remark, a notification, a question,
a summary, while a box is often used to highlight a key finding
in the running text: an equation, a hypothesis, a theorem, a
rule, or a conclusion.

===== User-Defined Environments =====
label{manual:userdef:envir}

LaTeX writers are often fond of their favorite environments and think
that formats like DocOnce, Markdown, and HTML are primitive without
these favorite environments. DocOnce, however, offers *user-defined* environments with begin and end tags, as typical in LaTeX. This section explains
how to define such user-defined environments.

__Remark.__
Special environments can always be implemented by Mako code as illustrated
in Section ref{manual:theorem:envir}, but the DocOnce user-defined
environments are easier to use.

For example, suppose you want to typeset examples using
a native *example* environment in LaTeX, while other formats can
simply typeset examples as subsections. You can
then introduce your own example
environment in DocOnce and write the environment like this:

!bc do
|bu-example Addition label=ex:math:1p1
We have

|bt
\[ 1 + 1 = 2 \]
|et
|!eu-example
!ec
The convention for this type of examples is to have a title,
and the title line
may feature `label=xxx`, where we can use `xxx` as a label for the
example.
The example environment above is in the present output format
typeset like this:

!bu-example Addition label=ex:math:1p1
We have

!bt
\[ 1 + 1 = 2 \]
!et
or in tabular form:

|-------------------|
| Problem | Result  |
|----c--------c-----|
| $1+1$   |  $2$    |
|-------------------|

!eu-example

The definition of the example environment must be done in a Python
module `userdef_environments`, located in the same directory as the
DocOnce source code or the parent directory.
In this file (`userdef_environments.py`),
we must provide a dictionary `envir2format` for translating an
environment into the right code for a specific format:

!bc pycod
envir2format = {
    'intro': {
        'latex': r"""
\usepackage{amsthm}
\theoremstyle{definition}
\newtheorem{example}{Example}[section]
""",},
    'example': {
        'latex': example,
        'do': do_example,
        },
}
!ec
The `intro` key contains initializing statements for the LaTeX and
HTML formats (the preamble and the `head` tag, respectively).
Here, we need the `amsthm` package and a definition of the `example`
environment in LaTeX. No initialization is needed for HTML.
The other keys are the names of the environments. For each environment,
we use a function to format the code for a specific output format.
The `do` key is a default DocOnce formatting, expressed in
DocOnce syntax and applied if the output format is not present among
the other keys. The LaTeX output is here defined by the function
`example`:

!bc pycod
def example(text, titleline, counter, format):
    """LaTeX typesetting of example environment."""
    label, titleline = get_label(titleline)
    s = r"""
\begin{example}
"""
    if label:
        s += 'label{%s}\n' % label  # no \ (is added by DocOnce)
    s += r"""
\noindent\emph{%s}.

%s
\end{example}
""" % (titleline, text)
    return s

def get_label(titleline):
    """
    Extract label from title line in begin environment.
    Return label and title (without label).
    """
    label = ''
    if 'label=' in titleline:
        pattern = r'label=([^\s]+)'
        m = re.search(pattern, titleline)
        if m:
            label = m.group(1)
            titleline = re.sub(pattern, '', titleline).strip()
    return label, titleline
!ec
The arguments are `text` for the body of the environment, `titleline`
for the title (everything that comes after `!bc-example` on the line),
an integer `counter` that counts the number of the current environment
(1, 2, and so on, which can be used for reference as an alternative to
the label), and the `format` string holding the user's output format.
In the present case,
we add the label inside the example environment if we have a  label
in the title, and we typeset the title in the emphasize font.
Otherwise, we rely on the standard `example` (or `newtheorem`)
LaTeX environment.

In HTML and other formats, we simply typeset the example as a subsection:

!bc pycod
def do_example(text, titleline, counter, format):
    """General typesetting of example environment via a section."""
    label, titleline = get_label(titleline)
    s = """

===== Example %d: %s =====
""" % (counter, titleline)
    if label:
        s += 'label{%s}\n' % label
    s += '\n%s\n\n' % text
    return s
!ec

We quickly encounter a problem when referring to a specific example.
In LaTeX, we want to write `Example ref{label}`, using the label
defined in the example heading. In other formats, this label is a
section number, or usually the section (example) heading. Different
wording is needed for different formats. This is easiest accomplished
by a little Mako function in the top of the DocOnce source:

!bc
<%
def refex(label, capital=False):
    if FORMAT in ('latex', 'pdflatex'):
        return 'Example ref{%s}' % label
    else:
        s = 'The ' if capital else 'the '
        s += 'example in Section ref{%s}' % label
        return s
%>
!ec
We can then write something like

!bc
${refex('ex:test:1p1', capital=True)} demonstrates how to do 1+1.
That is, the calculation 1+1 appears in ${refex('ex:test:1p1')}.
!ec
Note that we distinguish between `capital=True`, which means that the
example reference opens a sentence, and `capital=False`, which refers
to a reference later in the sentence. In HTML we see the difference:

!bc
The example in the section
<a href="#ex:test:1p1">Example 1: A test function</a>
demonstrates how to do 1+1.
That is, the calculation 1+1 appears in the example in the section
<a href="#ex:test:1p1">Example 1: A test function</a>.
!ec
while there is no difference in LaTeX since we refer to *Example* with
capital E anyway:

!bc
Example~\ref{ex:test:1p1} demonstrates how to do 1+1.
That is, the calculation 1+1 appears in Example~\ref{ex:test:1p1}.
!ec
To summarize, the *example* environment together with the `refex` Mako
function allows you to work with native LaTeX example environments, while
there is a neat alternative solution for all other formats.

!bnotice Enumerated environments
It is also possible to make enumerated environments such that their `ref`s use numbers
instead of section headings in HTML format (just like Figures do). This mimics LaTeX
behaviour on theorem-style environments. See the example in "DocOnce repository":
"https://github.com/hplgit/doconce/blob/master/doc/src/userdef_envirs/enumerated_envs".
!enotice

You may take a look at a complete "`userdef_environments.py`":
"https://github.com/hplgit/doconce/blob/master/doc/src/manual/userdef_environments.py"
file to see this example environment and another *highlight* environment
where we define blue boxes in LaTeX and HTML and rely on a standard
notice admon for all other formats. The highlight environment is
written like

!bc do
|bu-highlight Highlight box!
This environment is used to highlight something:

|bt
\[ E = mc^2 \]
|et
|eu-highlight
!ec
and typeset as

!bu-highlight Highlight box!
This environment is used to highlight something:

!bt
\[ E = mc^2 \]
!et
!eu-highlight

!bwarning Tip: Test `userdef_environments.py`!
Make sure you run the `userdef_environments.py` file to check
that all syntax is correct:

!bc sys
Terminal> python userdef_environments.py
!ec

A common error is to have the `envir2format` dictionary defined
before the functions it refers to.
!ewarning

A complete example showing how one can create tailored environments
for computer code, using `--latex_code_style`,
in particular the following one (with a caption),

FIGURE: [fig/userdef_code_envir.png, width=400 frac=0.5]

# #if FORMAT in ("latex", "pdflatex")
\noindent
# #endif
appears at the end of the document
"Demonstration of DocOnce support for LaTeX code block environments":
"http://hplgit.github.io/doconce/doc/pub/latexcode/demo.html".

Other examples are available in the "DocOnce repository":
"https://github.com/hplgit/doconce/blob/master/doc/src/userdef_envirs".

======= Bibliography (References) =======

idx{bibliography}
idx{reference list}
idx{Publish (for bibliography)}

DocOnce applies the software tool "Publish":
"https://bitbucket.org/logg/publish" to handle the bibliography in a
document. With Publish it is easy to import BibTeX data and maintain a
database in a clean, self-explanatory textual format. From the Publish
format it is easy to go BibTeX and reST or straightforward DocOnce
typesetting (and from there to HTML, plain text, wiki formats, and so
on).

Installing Publish is trivial: either do

!bc sys
Terminal> pip install -e \
   hg+https://bitbucket.org/logg/publish#egg=publish#egg=publish
!ec
or checkout the code on
"`bitbucket.org`": "https://bitbucket.org/logg/publish":

!bc sys
Terminal> hg clone https://bitbucket.org/logg/publish
Terminal> cd publish
Terminal> sudo python setup.py install
!ec

===== Importing your data to the Publish database =====

idx{BibTeX}
idx{bibliography, database}

Many scientists have their bibliographic data in the BibTex format. Here we
assume that you have two files, `refs1.bib` and `refs2.bib`. These can
be imported to a Publish database, residing in the file `papers.pub`,
by the commands

!bc sys
publish import refs1.bib
publish import refs2.bib
!ec
During import, Publish may ask you for accepting the name of new
institutions or journals. Publish already have a database of journals
and institutions/departments, but when you add new, you also get
a file `venues.list` (in the current working directory) which will be used
for future imports in this directory. Make sure you store `publish.pub`
and `venues.list` along with your DocOnce document files (they do not
need to reside in the same directory, but make sure you add them to
your version control system).

!bwarning Importing big BibTeX databases may imply a lot of work
If your BibTeX database does not confirm to the strict BibTeX syntax
required by Publish (entry names must be in lower case, their values
must be surrounded by curly braces), you will get error messages.
Publish will also check the names of all journals and detect duplicate
entries. For databases automatically created by some of the modern
web tools for references, the BibTeX file may need a lot of
edits before it can be accepted by Publish. Consider using a script
to automate many of the edits.
!ewarning

===== Requirements to input data =====

!bnotice
Note that Publish only accepts BibTeX files where the keys (author,
title, etc.) are in lower case and where the data are enclosed in
curly braces. You may need to edit your BibTeX files to meet this
demand.
!enotice

The utility `doconce fix_bibtex4publish file.bib` fixes several known
issues with BibTeX files such that Publish has a better chance of
accepting the entries. Run this utility first, then run Publish,
respond to any requirements that Publish spits out, remove `papers.pub`
if it exists, and run the import statements again.

Although references are visible as numbers only in the
output, it is recommended to have apply a nice, consistent
typesetting of your keys. It is suggested to use the following scheme:

!bc do
Langtangen_2003a          # single author
Langtangen_Pedersen_2002  # two authors
Langtangen_et_al_2002     # three or more authors
!ec
One can add a, b, c, and so forth if several keys feature the same
authors and year.

===== Adding new references to the database =====

When you get some new BibTeX references you simply put them in
a file, say `refs3.pub` and run the `publish import refs3.pub` command
to update the database. You may also consider editing the `papers.pub`
file directly when adding new references.

===== Exporting the database =====

Export of everything in the database to
BibTeX is done by

!bc sys
publish export mybibtexfile.bib
!ec
You can easily export subsets of the database, e.g., only papers associated
with a particular author (the Publish manual has details on how this is
done). DocOnce will automatically export the database to BibTeX if
the output format is `latex` or `pdflatex`.

===== Referring to publications =====

idx{citations}
idx{`cite`}

We use the command

!bc do
cite{key}
!ec
to refer to a publication with bibliographic key `key`.
Here is an example: cite{Langtangen_Pedersen_2002} discussed propagation of
large destructive water waves, cite{Langtangen_et_al_2002} gave
an overview of numerical methods for solving the Navier-Stokes equations,
while the use of Backward Kolmogorov equations for analyzing
random vibrations was investigated in cite{Langtangen_1994a}.
The book chapter cite{Mardal_et_al_2003a} contains information on
C++ software tools for programming multigrid methods. A real retro
reference is cite{Langtangen_1988d} about a big FORTRAN package.
Multiple references are also possible, e.g., see
cite{Langtangen_Pedersen_2002,Mardal_et_al_2003a}.

A LaTeX-style cite command with additional detailed reference is also possible,

!bc do
cite[details]{key}
!ec
for example as in cite[Section 2]{Langtangen_et_al_2002}
or cite[Equation (4.2)]{Langtangen_et_al_2002}.

In LaTeX, the `cite` command is directly translated to the
corresponding LaTeX version of the command with a backslash; in reST
and Sphinx the citations becomes links, with the citation keys as
names; in HTML the citations are numbered from 1, 2, and so forth
according to their appearance, and the numbers appear as links; while
in other formats the citations are simply the keys inside square
brackets and the corresponding references are listed in the order they
are cited.

===== Specifying the Publish database =====

The specification of the Publish database file in the DocOnce document
is done one a line containing `BIBFILE: papers.pub` (you may give
the database file another name and store it in another directory).
The references will be inserted at the place where this command appears.
Before the command you will often want to have a headline with
``References'', ``Bibliography'', or similar.
Here is an example:

!bc do

======= References =======

BIBFILE: papers.pub
!ec
In LaTeX and pdfLaTeX the `papers.pub` file is exported to BibTeX format
and included in the document, while in all other formats, suitable
text is produced from the database.

===== LaTeX Bibliography Style =====

idx{LaTeX bibliographic styles}

The bibliography style is ``plain'' in LaTeX output. To change this, just
edit the `.p.tex` file. For example,

!bc sys
doconce format latex mydoc
doconce replace 'bibliographystyle{plain}' 'bibliographystyle{abbrev}' mydoc.p.tex
!ec



!split
======= Preprocessing and Postprocessing =======

idx{split command}
idx{`!split`}

DocOnce allows preprocessor commands for, e.g., including files,
leaving out text, or inserting special text depending on the format.
These commands are run prior to translation of the document.
After translation, there are `doconce split_*` commands available
for splitting HTML and Sphinx documents into smaller pieces (web pages)
as a postprocess. Each split is performed where the document writer
has inserted a `!split` command (starting in the first column of a
line and being the only text on that line):

!bc do
# Split document here
!split
======= New section =======
!ec

===== The Preprocess and Mako Preprocessors =====

idx{preprocessing}
idx{`mako` preprocessor}
idx{`preprocess` preprocessor}

Two preprocessors are supported: preprocess
(URL:"https://github.com/doconce/preprocess") and mako
(URL:"http://www.makotemplates.org/"). The former allows include and if-else
statements much like the well-known preprocessor in C and C++ (but it
does not allow sophisticated macro substitutions). The latter
preprocessor is a very powerful template system.  With Mako you can
automatically generate various type of text and steer the generation
through Python code embedded in the DocOnce document. An arbitrary set
of `name=value` command-line arguments (at the end of the command line)
automatically define Mako variables that are substituted in the document.

DocOnce will detect if preprocess or Mako commands are used and run
the relevant preprocessor prior to translating the DocOnce source to a
specific format.

The preprocess and mako programs always have the variable `FORMAT`
defined as the desired output format of DocOnce (`html`, `latex`,
`plain`, `rst`, `sphinx`, `epydoc`, `st`).  It is then easy to test on
the value of `FORMAT` and take different actions for different
formats. Below is an example:

@@@CODE _format_specific1.do.txt envir=cc

A variable `DEVICE` is also defined. It equals `screen` by default,
but the command-line argument `--device=paper` can set `DEVICE` to
`paper` (or another value). Testing on `DEVICE` inside the document
makes it possible to test if the output is on paper media, a screen,
or a particular device.

Other user-defined variables for the preprocessor can be set at
the command line as explained in Section ref{doconce2formats}.

More advanced use of mako can include Python code that may automate
the writing of parts of the document.

!bnotice On the type of a Mako variable from the command line
You define Mako variables as in this example:

!bc sys
Terminal> doconce format html mydoc LANG=C NO=4 COMMENTS=False
!ec
The variable `LANG` gets the value `'C'` as a Python string
inside the document. All values are treated as strings, except
if the value is `True` or `False` or if it is an integer.
Therefore, `NO` becomes the integer `4` and you can test
like `% if NO > 4:`. The variable `COMMENTS` gets
the boolean value `False` and `% if not COMMENT:` is a positive
test. With Mako such variables set on the command-line
you can easily leave out portions
of the document or choose between different versions of the text
in a very flexible and fine-tuned way.
!enotice

!bnotice Advanced setting of Mako variables
Mako variables can also be run through `eval` before being
sent to Mako. For example,

!bc sys
Terminal> doconce format latex mydoc \
          SOMEVAR="eval(['problem', 'data', 'results'])"
!ec
Now, `SOMEVAR` will be defined by

!bc pycod
SOMEVAR = eval("['problem', 'data', 'results']")
!ec
and result in the list `['problem', 'data', 'results']`.
In a DocOnce document, we can write

!bc do
% for element in SOMEVAR:
 * "`${element}.pdf`": "http://some.net/pdf/${element}.pdf"
% endfor
!ec
and produce the following LaTeX code:

!bc latexcod
\begin{itemize}
 \item \href{{http://some.net/pdf/problem.pdf}}{\nolinkurl{problem.pdf}}

 \item \href{{http://some.net/pdf/data.pdf}}{\nolinkurl{data.pdf}}

 \item \href{{http://some.net/pdf/results.pdf}}{\nolinkurl{results.pdf}}
\end{itemize}
!ec
Instead of giving the `SOMEVAR` list on the command line, we can hardcode
it inside the document:

!bc do
<%
SOMEVAR = ['problem', 'data', 'results']
%>
!ec
The flexibility enabled by Mako variables and statements is one of the
major reasons to adopt DocOnce.
!enotice

!split
===== Splitting Documents into Smaller Pieces =====

idx{splitting documents}
idx{multi-page documents}

Long documents are conveniently split into smaller DocOnce files.
However, there must be a master document including all the pieces,
otherwise references to sections and the index will not work properly.
The master document is preferably a file just containing a set of
preprocessor include statements of the form `#include "file.do.txt"`.
The preprocessor will put together all the pieces so that DocOnce
sees a long file with the complete text.

# #ifdef DEPRECATED
For reST and Sphinx documents it is a point to have
separate `.rst` files and an index file listing the various `.rst`
that build up the document. To generate the various `.rst` files one
should not run DocOnce on the individual `.do.txt` files, because then
references and index entries are not treated correctly. Instead,
run DocOnce on the master file and invoke the script `doconce split_rst`
to split the long, complete `.rst` into pieces. This process requires
that each `#include "file.do.txt` line in the master file is preceded by a
``marker line'' having the syntax `#>>>>>> part: file >>>>>>`, where
`file` is the filename without extension. The number of greater than
signs is not important, but it has to be a comment line and it has
to contain the keyword `part:`.

Here is an example. Say the name of the master file is `master.do.txt`.
The following Bash script does the job:
We run

!bc cod
doconce format sphinx master
# Split master.rst into parts
# as defined by #>>>>> part: name >>>>> lines
files=`doconce split_rst master.rst`

dir=sphinxm-rootdir

if [ ! -d $dir ]; then
  doconce sphinx_dir dirname=$dir author='me and you' \
          version=1.0 theme=default $files
  sh automake_sphinx.sh
else
  for file in $files; do
    cp $file.rst $dir
  done
  cd $dir
  make html
  cd ..
fi
!ec
The autogenerated `automake_sphinx.sh` file (by `doconce sphinx_dir`)
is compatible with a master `.rst` file split into pieces as long as
the complete set of pieces in correct order is given to `doconce sphinx_dir`.
This set is the output of `doconce split_rst`, which we catch in a
variable `files` above.
# #endif

For web documents it is often desired to split long pages into shorter
ones. This is done by the DocOnce command `!split` placed at the
beginning of a line. The `!split` commands works with output in
`html`, `rst`, `sphinx`, `latex`, and `pdflatex`. The `!split` command
are normally placed before section headings. It is very actively used
when writing slides with DocOnce. The `doconce format` command does not
recognize `!split` instructions: one needs to run `doconce split_*`
as a postprocess, where the `*` means `html`, `rst`, or `beamer`.

idx{`doconce` commands!`split_html`}

__HTML.__
Splitting an HTML document is done by

!bc sys
Terminal> doconce format html mydoc
Terminal> doconce split_html mydoc
!ec
The `mydoc.html` document created by the first command is replaced
by a new HTML file, representing the first part of the document,
after the second command. The various files that constitute the
parts of the document are listed after the `split_html` command.
The files have names `mydoc.html`, `._mydoc000.html` (equal to
`mydoc.html`), `._mydoc001.html`, `._mydoc002.html`, and so
on. Recall that all the parts are needed if the HTML document is to be moved
to another location (you can always check `.mydoc_html_file_collection`
for a list of all the files that are needed to display this HTML
document).

MathJax cannot refer to equations defined in other HTML files, but
the `doconce split_html` fixes this problem. Note, however, that
running `doconce split_html` leads to another equation numbering
than in the original HTML document. In the latter, we use AMS
equation numbering, which means that the standard LaTeX conventions
are followed, while in the split document only the subset of
equations with labels are given numbers.

The HTML documents have by default very simple navigation buttons for
the previous and next document. These buttons are customizable:

!bc sys
Terminal> doconce split_html mydoc.html --nav_buttons=X
!ec
where `X` can be `text` (pure text ``Previous'' and ``Next'', no
buttons), `gray1`, `gray2`, `bigblue`, `blue`, or `green` as
shown here, respectively (from left to right):

FIGURE: [fig/nav_buttons.png, width=300 frac=0.6]

However, if `--html_theme=` is set any theme starting
with `bootstrap` or `bootswatch`, the navigation buttons are ignored,
and Bootstrap-style buttons are used.

idx{`doconce` commands!`split_rst`}
idx{`doconce` commands!`sphinx_dir`}
idx{`automake_sphinx.py`}

__reStructuredText and Sphinx.__
Here is a typical split of a large Sphinx document `mydoc.rst`
into smaller pieces:

!bc sys
Terminal> doconce format sphinx mydoc
Terminal> doconce split_rst mydoc
Terminal> doconce sphinx_dir author="Some Author" \
          title="Short title" theme=fenics dirname=mydir mydoc
Terminal> python automake_sphinx.py
!ec
The `doconce format sphinx mydoc` command is needed to produce `mydoc.rst`,
which is the starting point for the `doconce split_rst` command.
The various files that constitute the complete Sphinx document are
`mydoc.rst`, `._mydoc000.rst`, `._mydoc001.rst`, `._mydoc002.rst`,
and so on. The `automake_sphinx.py` script ensures that the Sphinx document
is compiled correctly. If all links to local files are in a `_static`
directory, the whole Sphinx document exists in a complete version
in the compiled directory (usually `sphinx-rootdir/_build/html`) and
can easily be moved around.


__Split and LaTeX.__
LaTeX Beamer slides generated from DocOnce source also apply `!split` to
indicate the start of individual slides. However, the split is
performed by the `doconce slides_beamer` command and does not result
in individual files like `split_rst` and `split_html` do.


!split
======= Writing Slides =======

idx{slides}
idx{HTML5 slides}
idx{LaTeX slides}
idx{Markdown slides}

It is a potentially fast procedure to make slides from large amounts
of DocOnce text, in particular for condensing material for
lectures or for providing the slide set as an overview or study
guide.  The slides can either be ordinary, separate slides - or just a
document with much briefer text and emphasis on bullet lists, figures,
mathematical formulas, admonitions, etc.

# NOTE: (*@\pause@*) cannot be written as verbatim text because the two
# * makes this look like emphasize...can only appear in code blocks but
# will then be replaced by nothing in all formats except latex... See
# list below for how to describe the command with pre- and postfix.

Points to consider (just sketches...):

 * Only some pygments styles are suited for a particular reveal.js/deck.js
   theme
 * Only some admon styles are appropriate
 * Admon styles are erased in reveal
 * Use `--keep_pygments_html_bg` to avoid big changes in background
   color for code
 * pause command for pop-up in Beamer slides (ignored in other formats).
 * Can use PowerPoint or Google Presenter to design a slide and then
   save as image (GP directly, PP via Save as Picture or
   Save As + choosing image type,
   and then all or present slide only), then import image in doconce.
   LaTeX formulas in image are easiest created as PNGs using
   URL: "http://www.codecogs.com/latex/eqneditor.php".
 * From doconce to PP or GP: use the latexslides script to convert
   to PDFs and odp format, convert odp to ppt interactively or with
   `unoconv`.
 * Sections (7 `=`) are used to indicate sections in slides (gives
   a toc in beamer slides), while subsections (5 `=`) are used for
   slide headings. Remember `!split` before each slide (subsection).
   A comment `# Short title: title` after a section is interpreted
   in `latex` and `pdflatex` output as a short title for the section.
   (Short titles for sections in ordinary text files are not supported.)

idx{short title (for slides)}

!split
===== Overview =====

=== Slide Types ===

DocOnce can generate two types of slides: HTML5+CSS3 type of
slides to be presented through a web browser, and classical
LaTeX Beamer slides. A "comprehensive demo": "http://hplgit.github.io/doconce/doc/pub/slides/demo/index.html" shows the range of possible
layouts.

The following specific types of output is supported:

 * LaTeX:
  * "Beamer slides": "http://en.wikibooks.org/wiki/LaTeX/Presentations"
 * HTML5:
  * "reveal.js": "http://lab.hakim.se/reveal-js/#/"
  * "deck.js": "http://imakewebthings.com/deck.js/"
  * "CSSS": "http://leaverou.github.io/CSSS/#intro"
  * "dzslides": "http://paulrouget.com/dzslides/"
 * Markdown:
  * "Remark": "http://remarkjs.com/#1"

=== Syntax ===

Basically, DocOnce slides are ordinary DocOnce text with `!split`
inserted before each slide. Nevertheless, contents of slide differ
considerably from ordinary running text. Some guidelines on
the elements within each slide are necessary to produce effective
slide sets:

 * Use a section heading (7 `=`) for dividing a presentation into parts.
   There can be text of figure(s) after the heading to illustrate
   the part.
 * Use a subsection heading as slide heading (5 `=`).
 * Limit the amount of running text (as always).
 * Limit the amount of material so it fits within a slide
   (inspect slides visually to move or delete content - just
   an extra `!split` and a new heading is enough to make a new
   slide).
 * Use the `pop` environment to pop up list items or blocks
   one by one.
 * You can use `\pause` prefixed by `(*@` and postfixed by `@*)`
   inside code or math blocks to pop up
   code lines or formulas in Beamer slides (the pause command is
   simply ignored in other formats).
 * Use the `slidecell` environment (see below) to create
   a grid of slide cells (makes it easy to move figures and
   bullet lists or text around).
 * Adjust the size of figures (`width` parameter for HTML,
   `frac` parameter for LaTeX Beamer) so they become effective
   on the slide.

===== Slide Elements =====

idx{slide syntax}

=== Title page ===

Here is a typical title page:

!bc do
TITLE: On Something Interesting
AUTHOR: O. Nordmann at Seg. Fault Ltd. & D. Bug Inc.
AUTHOR: John Doe Email: john.doe@mail.com at Progress Ltd.
AUTHOR: Chan Siu Ming at Progress Ltd & Moon University
DATE: today

FIGURE: [fig/logo, width=300 frac=0.3]
!ec

=== Parts Page ===

Parts of the presentation are divided by section headings. Here
we also add some keywords in a bullet list on the left and a
figure on the right. The `!bslidecell XY f` command starts the
definition of a cell in a grid of cells in the slide. The `XY`
part defines the coordinates of the cell, `00` is upper left,
`01` is upper right. The `f` parameter specifies the fraction
of the width occupied by this column of cells (can be left out,
which results in columns of equal widths).

idx{short title (in sections)}

!bc do
!split
======= Problem setting and methods =======
# Short title: Problem

|bslidecell 00 0.4

 * Scope
 * Focus
 * Approach

|eslidecell

|bslidecell 01 0.6
FIGURE: [fig/method, width=600 frac=0.7]
|eslidecell
!ec
The `# Short title: ...` line can be used to define a short
title for slide formats with navigation (where long titles are
inappropriate), e.g., Beamer PDF slides.


=== Standard bullet list page ===

Bullet lists are typeset as usual in DocOnce:

!bc do
!split
===== Methods =====

 * Slow:
   * Pick-and-choose
   * Foxtrot
 * Fast:
   * Quickstep
   * MMST
   * PQR
!ec

Some prefer the bullet list or other contents of the slide to
appear in a frame or Beamer block (potentially with shadows in
some Beamer styles). This design is enabled by putting the
contents inside the `block` environment:

!bc do
!split
===== Methods =====

|bblock Methods are slow or fast:
 * Slow:
   * Pick-and-choose
   * Foxtrot
 * Fast:
   * Quickstep
   * MMST
   * PQR
|eblock
!ec
The block title is optional.

One can easily pop up one item at a time using `!bpop` and `!epop`:

!bc do
!split
===== Methods =====

|bblock Methods are slow or fast:
|bpop
 * Slow:
   * Pick-and-choose
   * Foxtrot
 * Fast:
   * Quickstep
   * MMST
   * PQR
|epop
|eblock
!ec


=== Equations, movies, figures ===

Standard DocOnce elements and formatting work in slides too:

!bc do
!split
===== Key formulas =====

|bt
\[ a = b \]
|et

FIGURE: [fig/a_eq_b, width=500 frac=0.4]

MOVIE: [mov/animate_a_eq_b]
!ec

Here is another example on math and code:

!bc do
!split
===== Example =====

|bblock Problem:
Solve $ax+b=0$.
|eblock

|bblock Solution:
$x=-b/a$
|eblock

|bblock Implementation:
|bc pypro
import sys
a = float(sys.argv[1])
b = float(sys.argv[2])
x = -b/a
print x
|ec
|eblock
!ec

===== HTML5 Slides =====

idx{`doconce` commands!`slides_html`}

# doconce-adjusted styles: easy to switch between styles since
# font sizes are compatible

Not yet written...

Just a very preliminary sketch of commands:

!bc sys
Terminal> doconce format html myslides \
          --pygments_html_style=native --keep_pygments_html_bg
Terminal> doconce slides_html myslides reveal \
          --html_slide_theme=darkgray
!ec

=== Potential Problems ===

 * Some newer Firefox does not show rounded corners of the
   admonition boxes, e.g., notice and warning (tested on Ubuntu)
 * DocOnce performs some adjustments of the spacing around
   equations. More edits (automate with `doconce subst`) might be needed.

===== LaTeX Beamer Slides =====

=== Themes ===

Four themes come with DocOnce: `X_Y`, where `X` is `blue` or `red`
(the main color of the slides) and `Y` is "`plain`":
"http://hplgit.github.io/teamods/doconce/demo/demo_red_plain.pdf"
for simple layout and
"`shadow`": "http://hplgit.github.io/teamods/doconce/demo/demo_blue_shadow.pdf"
for shadowed boxes and more visual structure in the slides.

=== Pop of list items and blocks ===

The `!bpop` and `!epop` directives have the following effect in
Beamer slides:

 * If `!bpop` comes right before the beginning of a list, each list
   item is popped up, one at a time.
 * Otherwise, the rest of the slide, or the text until the next `!bpop`
   pops up all at once.

=== Compilation ===

The cycle is

 * `doconce format pdflatex mydoc` for producing `mydoc.p.tex`
 * `doconce ptex2tex` or `ptex2tex` for translating `mydoc.p.tex` to `mydoc.tex`
 * `doconce slides_beamer mydoc.tex` to produce a Beamer version `mydoc.tex`
 * standard pdfLaTeX compilation of `mydoc.tex`

!split
======= Support for non-English =======

DocOnce can handle documents in other languages than English. At the time
of this writing there is support for Basque, German and Norwegian. Please create an issue at URL: "https://github.com/hplgit/doconce/issues" to request support for additional languages.

A demo directory with files is "`locale`": "https://github.com/hplgit/doconce/tree/master/doc/src/locale". For example, `norsk.do.txt` contains a simple document
in Norwegian. To compile, one must supply the options
`--encoding=utf-8 --language=Norwegian`:

!bc sys
Terminal> doconce format html norsk \
          --html_style=bootstrap_FlatUI \
          --encoding=utf-8 --language=Norwegian
!ec

!split
======= Misc =======

===== Missing Features =====

DocOnce does not aim to support sophisticated typesetting, simply because
sophisticated typesetting usually depend quite strongly on the particular
output format chosen. When a particular feature needed is not supported
by DocOnce, it is recommended to hardcode that feature for a particular
format and use the if-else construction of the preprocessor. For example,
if a sophisticated table is desired in LaTeX output, do something like

@@@CODE _format_specific2.do.txt envir=ccq

Similarly, if certain adjustments are needed, like
pagebreaks in LaTeX, hardcode that in the DocOnce format (and recall
that this is really LaTeX dependent - pagebreaks are not
relevant HTML formats).

Instead of inserting special code in the DocOnce document, one can
alternatively script editing of the output from DocOnce. That is,
we develop a Python or Bash script that runs the translation of
a DocOnce document to a ready document in another format. Inside this
script, we may edit and fine-tune the output from DocOnce.


===== Git `.gitignore` File =====
label{gitignore}

For DocOnce repositories using the Git version control system, the
following `.gitignore` file is useful:

!bc
syntax: glob
# doconce files:
*.rst
*.ipynb
*.gwiki
*.cwiki
*.mwiki
*.pdf
*.tex
automake_sphinx.py
.*_html_file_collection
.*.exerinfo
.*.copyright
sphinx-rootdir
Trash
papers.bib
# compiled files:
*.o
*.so
*.a
# temporary files:
build
*.bak
*.swp
*~
.*~
*.old
tmp*
temp*
.#*
\#*
# tex files:
*.log
*.dvi
*.aux
*.blg
*.bbl
*.idx
*.ilg
*.ind
*.loe
*.nav
*.out
*.toc
*.snm
*.vrb
# eclipse files:
*.cproject
*.project
# misc:
.DS_Store
.idea
__pycache__
_minted-*
!ec


===== Emacs DocOnce Formatter =====
label{emacs:doconce}

idx{Emacs doconce support}
idx{doconce syntax highlighting}
idx{syntax highlighting for doconce}
idx{doconce editing (Emacs)}

## Note: check http://www.latex-community.org/viewtopic.php?f=28&t=208
## for highly configurable latex editors that perhaps can be adapted
## to doconce (Kile seems to be the choice because of extensibility)

The file ".doconce-mode.el": "https://github.com/hplgit/doconce/blob/master/misc/.doconce-mode.el" in the DocOnce source distribution
gives a "DocOnce Editing Mode" in Emacs.

Here is how to get the DocOnce Editing Mode in Emacs: Download ".doconce-mode.el": "https://raw.github.com/hplgit/doconce/master/misc/.doconce-mode.el" and save it in your home directory, then add these lines to `~/.emacs`:

!bc do
(load-file "~/.doconce-mode.el")
!ec
Emacs will now recognize files with extension `.do.txt` and enter
the DocOnce Editing Mode.

The major advantage with the DocOnce Editing Mode in Emacs is that
many keyboard shortcuts are defined:

|--------------------------------------------------------|
| Emacs key      | Action                                |
|----l-------------------------l-------------------------|
|  Ctrl+c f      | figure                                |
|  Ctrl+c v      | movie/video                           |
|  Ctrl+c h1     | heading level 1 (section/h1)          |
|  Ctrl+c h2     | heading level 2 (subsection/h2)       |
|  Ctrl+c h3     | heading level 2 (subsection/h3)       |
|  Ctrl+c hp     | heading for paragraph                 |
|  Ctrl+c me     | math environment: `!bt` equation `!et`|
|  Ctrl+c ma     | math environment: `!bt` align `!et`   |
|  Ctrl+c ce     | code environment: `!bc` code `!ec`    |
|  Ctrl+c cf     | code from file: `@@@CODE`             |
|  Ctrl+c table2 | table with 2 columns                  |
|  Ctrl+c table3 | table with 3 columns                  |
|  Ctrl+c table4 | table with 4 columns                  |
|  Ctrl+c exer   | exercise outline                      |
|  Ctrl+c slide  | slide outline                         |
|  Ctrl+c help   | print this table                      |
|--------------------------------------------------------|

Typing `Ctrl+c help` prints the above table in Emacs. Try out
the different shortcuts and see how handy they are in learning
DocOnce and saving much typing!


===== Atom Syntax Highlighting for DocOnce =====
label{atom}

There is a package for the "Atom editor" : "https://atom.io/" available at URL: "https://atom.io/packages/language-doconce" which provides syntax highlighting for DocOnce.


!split
======= Mako Programming =======
label{manual:mako}

idx{`mako` programming}

The "Mako": "http://docs.makotemplates.org/" templating engine is used
as preprocessor for DocOnce documents, but the "Preprocess": "http://code.google.com/p/preprocess" is run prior to Mako and is recommended for
including other files via `# #include "filename"`. Preprocess is also
sufficient for if-else tests to steer which parts of the text that
are to be compiled. For more demanding tasks, use Mako, which resembles
a real programming language.

!bwarning
Unfortunately, the combination of Mako and LaTeX mathematics may
lead to problems because Mako applies syntax like `${var}` to extract
variables or call functions, while LaTeX mathematics sometimes applies
the same syntax, e.g., `${\cal O}(\Delta x^2)$` which looks like a
Mako function call. This problem can give rise to strange error
messages from Mako, usually that a variable is not defined.
The solution is to avoid such Mako-style syntax when writing
LaTeX mathematics, e.g., by defining newcommands if it is otherwise
problematic.
!ewarning

===== The Basics of Mako =====

Just a preliminary sketch of some Mako code (next example is better!):

!bc do
# Define variables
<%
mycounter = 1
mydict = {}
%>

# Assume MYVAR is given on the command line as MYVAR=mytext (e.g.)
% if MYVAR is not UNDEFINED:
The value of MYVAR is ${MYVAR}.
% endif

<%
## Manipulation of variables
mycounter += 1
%>

% if MYVAR in (2,4,6):
MYVAR is even integer in [2,6].
% elif MYVAR > 1000000:
MYVAR is big.
% else:
MYVAR=${MYVAR}, mycounter=${mycounter}.
% endif

# Function
<%
# Define Python function: FORMAT and DEVICE
# are always defined

def link(filename):
    url = "https://github.com/some/path/to/' + filename + '"'
    if DEVICE == 'screen':
        # make link to url
        return '"filename":' + url
    elif DEVICE == 'paper':
        # write URL explicit on paper
        return 'URL:' + url
%>

<%doc>
This
is
a
block
comment in Mako.
<%doc/>
!ec

===== Debugging Python code in Mako =====
label{mako:py:debugging}

Although it is easy to put in Python code inside `<%` and `%>` directives,
it may quickly become a nightmare to debug the Python code. If Mako
reports a syntax error in the Python code, it is recommended to debug
the Python code outside of Mako. That is, copy all Python code to a
separate file and run it as standard Python code. This will give much
more precise (and familiar) error messages.

A setup that is easy for developing and maintaining the Python code
used in Mako goes as follows. Different pieces of Python code in Mako
is placed in separate files and included via the Preprocess preprocessor
in the DocOnce document. For instance,

@@@CODE _mako_python.do.txt
Here, we have separated the Python code in Mako into three files:
`variables.py`, `basic_functions.py`, and `more_functions.py`.
With the `# #include` statements, Mako sees the `.py` files inserted
as text inside the `<%` and `%>` directives (check the file
`tmp_preprocess__mydoc.do.txt` for the result of running Preprocess and
the complete DocOnce file that Mako sees).

To debug the `.py` files, collect all their text in one single `.py`
file and run it. The recommended way is to use Preprocess to copy
all the text in the `.py` files into a single file, named (say) `all_code.p.py`:

@@@CODE _all_code.p.py
Note that after including the `.py` files one can insert calls to functions,
print variables, etc., as desired to debug and experiment.

Run Preprocess on `all_code.p.py` to produce an ordinary Python file
`all_code.py` and run that code to test and debug. A little shell script
`all_code.sh` doing both these things is convenient:

!bc shpro
#!/bin/sh
preprocess all_code.p.py > all_code.py
python all_code.py
!ec
Especially when the Python code in Mako grows and becomes non-trivial,
this setup for having the code external to the DocOnce document is
very effective.

!bsummary Things to remember when programming Mako

 * Do not use continuation character (backslash) in Python code.
 * When a Mako error refers to a line in the text, invoke the
   file that Mako sees: `tmp_preprocess__mydoc.do.txt` if
   the DocOnce file has name `mydoc.do.txt`.
 * Use double `##` (Mako comment) to comment out Mako calls
   of the form `${name...}`.

And to be repeated: keep the Python code in separate files!
!esummary

One can use Mako to extend the DocOnce syntax. Four examples are given next.


!split
===== Example: Nomenclature functionality =====
label{manual:mako:nomenclature}

LaTeX has a package for nomenclatures (see "documentation": "http://cs.brown.edu/about/system/managed/latex/doc/nomencl.pdf") that allows a user
to issue a simple command

!bc latexcod
\nomenclature{symbol}{definition}
!ec
to add a symbol and its definition to a nomenclature. The
command `\printglossary` inserts the nomenclature table in the document.

We can easily create something similar in DocOnce with the aid of Mako.
Here are the basic ideas:

 * Collect the nomenclature definitions in a table in a file `.nomenclature.do.txt`.
 * Introduce a command `${insert_nomenclature()}` to make a fresh
   `.nomenclature.do.txt` file and return a `@@@CODE` command
   for inserting the nomenclature table.
 * Introduce a command `${nomenclature(symbol, definition)}`
   for adding a new line in the nomenclature table in the file.
 * Introduce a command `${end_nomenclature()}` to finish the nomenclature
   table, i.e., insert the last table line.

The Mako functions are defined by

!bc do
<%
# Nomenclature functionality

def insert_nomenclature():
    # Make new file
    with open('.nomenclature.do.txt', 'w') as f:
        f.write("""\
|---------------------------------|
| symbol | definition             |
|---l---------l-------------------|
""")
    # Use envir=None to make plain include
    return '@@@CODE .nomenclature.do.txt envir=None'

def nomenclature(symbol, definition):
    with open('.nomenclature.do.txt', 'a') as f:
        f.write('| ' + symbol + ' | ' + definition + ' |\n')
    return ''

def end_nomenclature():
    with open('.nomenclature.do.txt', 'a') as f:
        f.write('|---------------------------------|\n')
    return ''
%>
!ec

The typical application in a DocOnce document is

!bc do
TITLE: ...
AUTHOR: ...
DATE: today

!split
TOC: on

!split
${insert_nomenclature()}

# Here comes a lot of text...

The equation becomes

|bt
\[ \nabla\cdot\sigma = \varrho f,\]
|et
where $\sigma$ is the stress tensor, $\varrho$ is the density,
and $f$ is a body force.
${nomenclature(r'$\sigma$', 'stress tensor')}
${nomenclature(r'$\varrho$', 'density')}
${nomenclature(r'$f$', 'body force')}

## More text....

## At the end:
${end_nomenclature()}
!ec
Make it a habit to use raw strings `r"..."`
for the symbol in `${nomenclature(r"...", ....`
(sometimes backslashes enter the definition too and raw strings are
required).

Here is
the resulting DocOnce after mako is run (found in `tmp_mako__mydoc.do.txt` if
`mydoc.do.txt` is the file above):

!bc do
TITLE: Test
AUTHOR: HPL
DATE: today

!split
TOC: on

!split
@@@CODE .nomenclature.do.txt envir=None

# Here comes a lot of text...

The equation becomes

|bt
\[ \nabla\cdot\sigma = \varrho f,\]
|et
where $\sigma$ is the stress tensor, $\varrho$ is the density,
and $f$ is a body force.
!ec

The file `.nomenclature.do.txt` reads

!bc do

|---------------------------------|
| symbol | definition             |
|---l---------l-------------------|
| $\sigma$ | stress tensor |
| $\varrho$ | density |
| $f$ | body force |
|---------------------------------|

!ec

===== Example: Executing Python and using SymPy Objects in LaTeX =====

Here is an example where we want to illustrate how to calculate a
double integral. All mathematics is to be done in SymPy, and results
are supposed to be embedded in the document's text.
We can include Python code to be executed, anywhere in the document,
and a variable `var` in the Python code is reached by `${var}`.
Here, we run SymPy and use SymPy's LaTeX converter to make LaTeX
code out of computed SymPy expressions:

!bc do
# Execute Python code
<%
import sympy as sm
x, y, a = sm.symbols('x y a')
f = a*x + sm.sin(y)
step1 = sm.Integral(f, x, y)
step2 = sm.Integral(sm.Integralf, x).doit(), y)
step3 = step2.doit()
%>

# Make use of results in the above block when writing LaTeX math
|bt
\begin{align*}
${sm.latex(step1)} &= ${sm.latex(step2)}\\
&= ${sm.latex(step3)}
\end{align*}
|et
!ec

The result of the LaTeX block above, after Mako is run, becomes

!bc latexcod
\begin{align*}
\iint a x + y^{2} \sin{\left (y \right )}\, dx\, dy &=
\int \frac{a x^{2}}{2} + x y^{2} \sin{\left (y \right )}\, dy\\
&= \frac{a y}{2} x^{2} + x \left(- y^{2} \cos{\left (y \right )} +
2 y \sin{\left (y \right )} + 2 \cos{\left (y \right )}\right)
\end{align*}
!ec

Debugging Python code in Mako is less convenient than debugging Python
files directly, so one may prefer to just include the Python code
that Mako is supposed to run by

@@@CODE _mako_sympy_ex1.txt

## Must do a trick above: since we use preprocess syntax, #include
## will not work, and the code has to be in a separate file.

This is the recommended way to make use of SymPy
to automate the mathematical derivations: first develop and test
the SymPy code files, include the files in the document inside
Mako's Python code environment.

__Remark.__ Executing Python code inside the DocOnce document is
closely related to *literate programming*. Tools supporting
creating a document while running a Python programming cover
"Pweave": "http://mpastell.com/pweave/",
"Python literate": "https://github.com/stdbrouw/python-literate",
"PyWebTool": "http://pywebtool.sourceforge.net/",
"Antiweb": "http://pythonhosted.org/antiweb/index.html",
"Literate Programming in Python": "http://en.literateprograms.org/Literate_Programming_(Python)",
"Pyreport": "http://gael-varoquaux.info/computers/pyreport/",
and also IPython notebooks.


!split
===== Example: Extending Tables to Handle Figures =====
label{manual:tables:wfigs}

DocOnce tables cannot contain figures, since figures must appear on
a single line with the special syntax `FIGURE: [file, ...]`.
What if you want a table of thumbnail figures with hyperlinks?

=== Solution for LaTeX and HTML ===

We first restrict the attention to LaTeX and HTML. In those cases
we can create an ordinary table and insert a call to a Mako
function in cells in the table to return the proper LaTeX or
HTML code for displaying a figure.

The Mako call syntax in a cell is decided to be
`${tfig('080')}`, which insert the figure `mov/wave_frames/frame_0080.png`.
A 3x3 table of figures then look like

!bc do

|-------------------------------------------------|
|               |                |                |
|-------c---------------c----------------c--------|
|${tfig('080')} | ${tfig('085')} | ${tfig('090')} |
|${tfig('095')} | ${tfig('100')} | ${tfig('105')} |
|${tfig('110')} | ${tfig('115')} | ${tfig('120')} |
|-------------------------------------------------|

!ec
We do not want a heading, just a grid of figures, but a heading is
required in DocOnce figures, so the solution is to provide
empty column names in the heading. This solution
gives acceptable results in HTML and LaTeX.

The Mako function can be a plain Python function:

!bc pycod
<%
def tfig(fileno):
    p = 'mov/wave_frames/frame_0' + fileno + '.png'  # path
    if FORMAT in ("latex", "pdflatex"):
        text = r'\includegraphics[width=2cm]{%s}' % p
    elif FORMAT == "html":
        text = '<a href="%s"><img src="%s" width="300"></a>' % (p, p)
    else:
        text = '"`%s`": "%s"' % (fileno, p)  # plain link
    return text
%>
!ec
Note that for other formats than LaTeX and HTML we just return a link to
the figure.

!bnotice
A corresponding solution
for Sphinx will not work because inline figures in Sphinx has
a syntax with pipe symbols ('|') that interfere with the
column separator in tables in DocOnce. Returning the HTML
code in case of Sphinx will just display that HTML code
in the cells, not the rendered HTML code. A solution that
includes Sphinx is provided later.
!enotice

The resulting table is displayed below.

# @@@FIGTABLE 3x3 080 085 090 095 100 105 110 115 120

# Cannot just have the Mako code here and generate the table
# because this manual cannot be run with Mako (--no_mako
# is used in make.sh).
# The code below is generated by having the Mako function
# and table in a separate file _figtable.do.txt and then
# manually generating the various formats and inserting
# them here.

# #if FORMAT == "pdflatex"
# pdflatex, not that latex will not work with PNG images
\begin{quote}\begin{tabular}{ccc}
\hline
 \\
\hline
\includegraphics[width=2cm]{mov/wave_frames/frame_0080.png} & \includegraphics[width=2cm]{mov/wave_frames/frame_0085.png} & \includegraphics[width=2cm]{mov/wave_frames/frame_0090.png} \\
\includegraphics[width=2cm]{mov/wave_frames/frame_0095.png} & \includegraphics[width=2cm]{mov/wave_frames/frame_0100.png} & \includegraphics[width=2cm]{mov/wave_frames/frame_0105.png} \\
\includegraphics[width=2cm]{mov/wave_frames/frame_0110.png} & \includegraphics[width=2cm]{mov/wave_frames/frame_0115.png} & \includegraphics[width=2cm]{mov/wave_frames/frame_0120.png} \\
\hline
\end{tabular}\end{quote}
# #elif FORMAT == "html"
# html
<p>
<table border="1">
<tr></tr>
<tr><td align="center">   <a href="mov/wave_frames/frame_0080.png"><img src="mov/wave_frames/frame_0080.png" width="300"></a>    </td> <td align="center">   <a href="mov/wave_frames/frame_0085.png"><img src="mov/wave_frames/frame_0085.png" width="300"></a>    </td> <td align="center">   <a href="mov/wave_frames/frame_0090.png"><img src="mov/wave_frames/frame_0090.png" width="300"></a>    </td> </tr>
<tr><td align="center">   <a href="mov/wave_frames/frame_0095.png"><img src="mov/wave_frames/frame_0095.png" width="300"></a>    </td> <td align="center">   <a href="mov/wave_frames/frame_0100.png"><img src="mov/wave_frames/frame_0100.png" width="300"></a>    </td> <td align="center">   <a href="mov/wave_frames/frame_0105.png"><img src="mov/wave_frames/frame_0105.png" width="300"></a>    </td> </tr>
<tr><td align="center">   <a href="mov/wave_frames/frame_0110.png"><img src="mov/wave_frames/frame_0110.png" width="300"></a>    </td> <td align="center">   <a href="mov/wave_frames/frame_0115.png"><img src="mov/wave_frames/frame_0115.png" width="300"></a>    </td> <td align="center">   <a href="mov/wave_frames/frame_0120.png"><img src="mov/wave_frames/frame_0120.png" width="300"></a>    </td> </tr>
</table>
# #else
|-------------------------------------------------|
|               |                |                |
|-------c---------------c----------------c--------|
|"`080`": "mov/wave_frames/frame_0080.png" | "`085`": "mov/wave_frames/frame_0085.png" | "`090`": "mov/wave_frames/frame_0090.png" |
|"`095`": "mov/wave_frames/frame_0095.png" | "`100`": "mov/wave_frames/frame_0100.png" | "`105`": "mov/wave_frames/frame_0105.png" |
|"`110`": "mov/wave_frames/frame_0110.png" | "`115`": "mov/wave_frames/frame_0115.png" | "`120`": "mov/wave_frames/frame_0120.png" |
|-------------------------------------------------|
# #endif

=== Generating the Entire Table ===

The specific structure of this table also suggest using Mako
to generate the entire table:

!bc pycod
<%
def generate_table(start, end, step, no_of_columns):
    # Heading
    text = ''
    horizontal_rule = '|----|\n'
    text += horizontal_rule
    text += '|  '*no_of_columns + '|\n'
    text += horizontal_rule
    fig_counter = 0
    for counter in range(start, end+1, step):
        fig_counter += 1
        text += '| ' + tfig('%03d' % counter) + ' '
        if fig_counter % no_of_columns == 0:
            text += '|\n'
    text += horizontal_rule
    return text
%>

${generate_table(80, 120, 5, 3)}
!ec
The result is a table like the one above, except that the horizontal rules
and the heading are very short lines (but this is legal syntax -
it just does not look appealing in the DocOnce source).

=== Generating the Entire Table in a Native Format via Mako ===

To allow Sphinx and other formats, it is best to generate the entire
table. This can be done either by a Mako function or as a post
process after DocOnce has created the output file. We show the Mako
solution here.

!bnotice Tip
A pure Python function Mako is easiest to develop in a separate
Python program file because Python has better error messages
than Mako. Also, Python has debugging facilities that make the
development of the code much more efficient than writing in Mako.
When the Python function works, it can be inserted in the DocOnce
file inside the Mako directives `<%` and `%>`.
!enotice

The Mako function for generating the entire table in LaTeX, HTML,
and Sphinx format goes as follows.

!bc pycod
<%
def generate_native_table(start, end, step, no_of_columns):
    text = ''
    # Heading
    if FORMAT in ("latex", "pdflatex"):
        text += r"""\begin{quote}\begin{tabular}{%s}
\hline
 \\
\hline
""" % ('c'*no_of_columns)
    elif FORMAT in ("sphinx", "rst", "html"):
        text += '<p><table border="1">\n<tr>'
    fig_counter = 0
    latex_columns = []
    for counter in range(start, end+1, step):
        fig_counter += 1
        if FORMAT in ("latex", "pdflatex"):
            latex_columns.append(r'\includegraphics[width=2cm]'\
                    '{mov/wave_frames/frame_%04d.png}\n' % counter)
        elif FORMAT in ("sphinx", "rst", "html"):
            text += '<td align="center"> '\
            '<a href="mov/wave_frames/frame_%04d.png">'\
            '<img src="mov/wave_frames/frame_%04d.png" width="300">'\
            '</a> </td>\n' % (counter, counter)

        if fig_counter % no_of_columns == 0:  # new row
            if FORMAT in ("latex", "pdflatex"):
                text += '   ' + ' & '.join(latex_columns)
                if counter != end:
                    text += r'\\' + '\n'
                latex_columns = []
            elif FORMAT in ("sphinx", "rst", "html"):
                text += '</tr>\n'
                if counter != end:
                    text += '<tr>\n'  # begin new row
    # Footer
    if FORMAT in ("latex", "pdflatex"):
        text += r"""\hline
\end{tabular}\end{quote}
"""
    elif FORMAT in ("sphinx", "rst", "html"):
        text += '</table>\n'
    if FORMAT in ("sphinx", "rst"):
        # Wrap raw HTML code
        lines = text.splitlines()
        text = '\n.. raw:: html\n\n'
        for line in lines:
            text += '    ' + line + '\n'
        text += '\n'
    return text
%>

## Example on call in DocOnce source
${generate_native_table(80, 120, 5, 3)}
!ec
One can easily add support for various other formats, such as `pandoc`,
`gwiki`, `mwiki`, etc.
# #if FORMAT in ("latex", "pdflatex", "html")
The output in format the current format is as above.
# #elif FORMAT in ("rst", "sphinx")
The output in the current format is shown below.

.. begin sphinx-figtable-in-html

.. raw:: html

    <p><table border="1">
    <tr><td align="center"> <a href="mov/wave_frames/frame_0080.png"><img src="mov/wave_frames/frame_0080.png" width="300"></a> </td>
    <td align="center"> <a href="mov/wave_frames/frame_0085.png"><img src="mov/wave_frames/frame_0085.png" width="300"></a> </td>
    <td align="center"> <a href="mov/wave_frames/frame_0090.png"><img src="mov/wave_frames/frame_0090.png" width="300"></a> </td>
    </tr>
    <tr>
    <td align="center"> <a href="mov/wave_frames/frame_0095.png"><img src="mov/wave_frames/frame_0095.png" width="300"></a> </td>
    <td align="center"> <a href="mov/wave_frames/frame_0100.png"><img src="mov/wave_frames/frame_0100.png" width="300"></a> </td>
    <td align="center"> <a href="mov/wave_frames/frame_0105.png"><img src="mov/wave_frames/frame_0105.png" width="300"></a> </td>
    </tr>
    <tr>
    <td align="center"> <a href="mov/wave_frames/frame_0110.png"><img src="mov/wave_frames/frame_0110.png" width="300"></a> </td>
    <td align="center"> <a href="mov/wave_frames/frame_0115.png"><img src="mov/wave_frames/frame_0115.png" width="300"></a> </td>
    <td align="center"> <a href="mov/wave_frames/frame_0120.png"><img src="mov/wave_frames/frame_0120.png" width="300"></a> </td>
    </tr>
    </table>

.. end sphinx-figtable-in-html

# #endif

## Could have raw:: latex also above (?)

=== Generating the Entire Table in a Native Format as a Post Process ===

Instead of using Mako as shown above, we can invent our own syntax line
for the table with figures and apply a script to the DocOnce output file
to replace the special line with proper native code.
We use the same `generate_native_table` function as above, but this
time in a Python script. In the DocOnce source we place a line

!bc do
@@@FIGTABLE 80 120 5 3
!ec
which is meant to generate a table with figures where the numbers
correspond to arguments in the `generative_native_table` function.

Suppose we have run

!bc sys
Terminal> doconce format sphinx mydoc
!ec
In the resulting `mydoc.rst` file we have the magic line `@@@FIGTABLE ...`.
Such lines can now be processed in our Python script:

!bc pycod
# read mydoc.rst into the string filestr
pattern = r'@@@FIGTABLE (.+)'
def replacement(m):
    # m is a MatchObject
    args = m.group(1)
    # Convert args to a tuple of words with right type
    args = [eval(arg) for arg in args.split()]
    text = generate_native_table(*args)

filestr = re.sub(pattern, filestr, replacement)
# write filestr back to manual.rst
!ec
This code makes use of a function for creating the replacement string
for the `re.sub` command and demands a knowledge of regular expression
syntax and the workings or `re.sub`. A more plain Python version
goes like this:

!bc pycod
# read mydoc.rst into the string filestr
lines = filestr.splitsplines()
for i in range(len(lines)):
    if lines[i].startswith('@@@FIGTABLE'):
        args = lines[i][10:].strip()
        # Convert args to a tuple of words with right type
        args = [eval(arg) for arg in args.split()]
        text = generate_native_table(*args)
        lines[i] = text
filestr = '\n'.join(lines)  # make one string from all separate lines
# write filestr back to manual.rst
!ec

!bnotice Recommendation
This latter way of inserting specialized native text after DocOnce
has generated the output file is easier than using Mako and usually
also safer.
!enotice

!bsummary Lesson Learned
The above examples show different techniques for extending the
DocOnce capabilities. The ideas are not restricted to DocOnce: using
Mako as a preprocessing step or inserting ``magic'' lines that you
can later substitute by a script is possible in all types of
ASCII-based documents, e.g., LaTeX, Sphinx, and Markdown.
!esummary

!split
===== Example: Defining a Theorem Environment =====
label{manual:theorem:envir}

DocOnce supports only basic formatting elements (headings, paragraphs,
lists, etc.), while LaTeX users are used to fancy environments for, e.g.,
theorems. A flexible strategy is to typeset theorems
using paragraph headings, which will look satisfactorily in all
formats, but add comment lines that can be replaced by LaTeX environments
via `doconce replace`. Theorems can be numbered using a variable in Mako.
Here is an example on raw DocOnce code:

!bc do
<%
theorem_counter = 4
%>

# begin theorem
label{theorem:fundamental1}
<%
theorem_counter += 1
theorem_fundamental1 = theorem_counter
%>

__Theorem ${theorem_counter}.__
Let $a=1$ and $b=2$. Then $c=3$.
# end theorem

# begin proof
__Proof.__
Since $c=a+b$, the result follows from straightforward addition.
$\Diamond$|$END$
# end proof

As we see, the proof of Theorem ${theorem_counter} is a modest
achievement.
!ec
The `.p.tex` output file now reads

!bc do
% begin theorem
label{theorem:fundamental1}


\paragraph{Theorem 5.}
Let $a=1$ and $b=2$. Then $c=3$.
% end theorem

% begin proof
\paragraph{Proof.}
Since $c=a+b$, the result follows from straightforward addition.
$\Diamond$
% end proof

As we see, the proof of Theorem 5 is a modest
achievement.
!ec
Note that with Mako variables we can easily create our own counters,
and this works in any format. In LaTeX we can use both the generated
numbers from Mako variables or we can use the labels.

The next step is to replace the `% begin ...` and `% end ...` lines with
the proper LaTeX expressions in the `.p.tex` file. Moreover, we
need to remove the paragraphs with *Theorem*.
The following Bash script does the job:

!bc shpro
file=mydoc.p.tex
thpack='\\usepackage{theorem}\n\\newtheorem{theorem}{Theorem}[section]'
doconce subst '% insert custom LaTeX commands\.\.\.' $thpack $file
doconce subst '\\paragraph\{Theorem \d+\.\}' '' $file
doconce replace '% begin theorem' '\begin{theorem}' $file
doconce replace '% end theorem' '\end{theorem}' $file
!ec
More heavy editing is better done in a Python script that reads the
`mydoc.p.tex` file and performs string substitutions and regex
substitutions as needed.

The resulting `mydoc.tex` file now becomes

!bc do
\usepackage{theorem}
\newtheorem{theorem}{Theorem}[section]

...

\begin{theorem}
\label{theorem:fundamental1}



Let $a=1$ and $b=2$. Then $c=3$.
\end{theorem}

% begin proof
\paragraph{Proof.}
Since $c=a+b$, the result follows from straightforward addition.
$\Diamond$
% end proof

As we see, the proof of Theorem 5 is a modest
achievement.
!ec
Even better, HTML output looks nice as well.

Note that DocOnce supports fancy environments for verbatim code via
the `ptex2tex` program with all its flexibility for choosing environments.
Also `doconce ptex2tex` has quite some flexibility for typesetting
computer code.



!split
===== Tools for Writing DocOnce Documents =====

 * Emacs (with the modest DocOnce syntax highlighting), Vim, Gedit, etc.
 * "TeXMaker": "http://www.xm1math.net/texmaker/" and "Kile": "http://kile.sourceforge.net/" can in theory be adapted to handle DocOnce compilation and maybe even DocOnce constructs.



===== Debugging =====

Given a problem, extract a small portion of text surrounding the
problematic area and debug that small piece of text. DocOnce does a
series of transformations of the text. The effect of each of these
transformation steps are dumped to a logfile, named
`_doconce_debugging.log`, if the to `doconce format` after the filename
is `debug`. The logfile is intended for the developers of DocOnce, but
may still give some idea of what is wrong.  The section ``Basic Parsing
Ideas'' explains how the DocOnce text is transformed into a specific
format, and you need to know these steps to make use of the logfile.


# Example on including another DocOnce file:

!split
# #include "doconce2anything.do.txt"

!split
# #include "install.do.txt"



======= Basic Parsing Ideas =======

# avoid list here since we have code in between (never a good idea)

The (parts of) files with computer code to be directly included in
the document are first copied into verbatim blocks.

All verbatim and TeX blocks are removed and stored elsewhere
to ensure that no formatting rules are not applied to these blocks.

The text is examined line by line for typesetting of lists, as well as
handling of blank lines and comment lines.  List parsing needs some
awareness of the context.  Each line is interpreted by a regular
expression

!bc do
(?P<indent> *(?P<listtype>[*o-] )? *)(?P<keyword>[^:]+?:)?(?P<text>.*)\s?
!ec

That is, a possible indent (which we measure), an optional list
item identifier, optional space, optional words ended by colon,
and optional text. All lines are of this form. However, some
ordinary (non-list) lines may contain a colon, and then the keyword
and text group must be added to get the line contents. Otherwise,
the text group will be the line.

When lists are typeset, the text is examined for sections, paragraphs,
title, author, date, plus all the inline tags for emphasized, boldface,
and verbatim text. Plain substitutions based on regular expressions
are used for this purpose.

The final step is to insert the code and TeX blocks again (these should
be untouched and are therefore left out of the previous parsing).

It is important to keep the DocOnce format and parsing simple.  When a
new format is needed and this format is not obtained by a simple edit
of the definition of existing formats, it might be better to convert
the document to reST and then to XML, parse the XML and
write out in the new format.  When the DocOnce format is not
sufficient to getting the layout you want, it is suggested to filter
the document to another, more complex format, say reST or
LaTeX, and work further on the document in this format.


===== Typesetting of Function Arguments, Return Values, and Variables =====

!bnotice Note
This text is somewhat outdated.
Now DocOnce supports NumPy-style docstrings. DocOnce can also do
automatic references to Python documentation, say the :mod:`math`
module, but the link only works in case of Sphinx output.
Typical syntax is

!bc do
With :mod:`numpy` and the :func:`scipy.io.loadmat` function in
the :mod:`scipy.io` module, we can ...
!ec
In case of ambiguous names, say a local `math` module, one can
use `python`, `numpy`, `scipy`, and `mpl` (matplotlib) as prefix
(as defined in `conf.py`, generated by the `doconce sphinx_dir`):

!bc do
With :func:`python:math.sin` instead of :func:`math.sin` ...
!ec
(More info in the Sphinx API doc by the author - under development.)

A Mako function can provide greater flexibility such that
other formats than Sphinx can take advantage of such references
(full URL can be built into the function, depending on the format).
!enotice


!bquote
As part of comments (or doc strings) in computer code one often wishes
to explain what a function takes of arguments and what the return
values are. Similarly, it is desired to document class, instance, and
module variables.  Such arguments/variables can be typeset as
description lists of the form listed below and *placed at the end of
the doc string*. Note that `argument`, `keyword argument`, `return`,
`instance variable`, `class variable`, and `module variable` are the
only legal keywords (descriptions) for the description list in this
context.  If the output format is Epytext (Epydoc) or Sphinx, such lists of
arguments and variables are nicely formatted.

!bc
    - argument x: x value (float),
      which must be a positive number.
    - keyword argument tolerance: tolerance (float) for stopping
      the iterations.
    - return: the root of the equation (float), if found, otherwise None.
    - instance variable eta: surface elevation (array).
    - class variable items: the total number of MyClass objects (int).
    - module variable debug: True: debug mode is on; False: no debugging
      (bool variable).
!ec

The result depends on the output format: all formats except Epytext
and Sphinx just typeset the list as a list with keywords.

    - module variable x: x value (float),
      which must be a positive number.
    - module variable tolerance: tolerance (float) for stopping
      the iterations.
!equote

======= References =======

!bwarning Note
The references below are just for illustrating and testing citation
syntax and not references for explaining parts of the text.
!ewarning

BIBFILE: papers.pub
