## Missing: FIGURE, MOVIE, Exercise, environments

TITLE: DocOnce Tutorial: Document Once, Include Anywhere
AUTHOR: Hans Petter Langtangen {copyright} at Center for Biomedical Computing, Simula Research Laboratory & Department of Informatics, University of Oslo
DATE: today

# #ifdef EXTRA
 * When writing a note, report, manual, etc., do you find it difficult
   to choose the typesetting format? That is, to choose between plain
   (email-like) text, wiki, Word/OpenOffice, LaTeX, HTML,
   reStructuredText, Sphinx, XML, etc.  Would it be convenient to
   start with some very simple text-like format that easily converts
   to the formats listed above, and then at some later stage
   eventually go with a particular format?
 * Do you need to write documents in varying formats but find it
   difficult to remember all the typesetting details of various
   formats like "LaTeX":"http://refcards.com/docs/silvermanj/amslatex/LaTeXRefCard.v2.0.pdf", "HTML":"http://www.htmlcodetutorial.com/", "reStructuredText":"http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html", "Sphinx":"http://sphinx.pocoo.org/contents.html", and "wiki":"http://code.google.com/p/support/wiki/WikiSyntax"? Would it be convenient
   to generate the typesetting details of a particular format from a
   very simple text-like format with minimal tagging?
 * Do you have the same information scattered around in different
   documents in different typesetting formats? Would it be a good idea
   to write things once, in one format, stored in one place, and
   include it anywhere?

If any of these questions are of interest, you should keep on reading.
# #endif

======= Some DocOnce Features =======

 * Strong support for texts with much math and code.
 * Same source can produce a variety of output formats:
   * "traditional LaTeX B/W documents for printing": "http://hplgit.github.com/teamods/writing_reports/_static/report_4printing.pdf"
   * "color LaTeX PDF documents": "http://hplgit.github.com/teamods/writing_reports/_static/report.pdf"
   * "color LaTeX PDF documents for viewing on small phones": "http://hplgit.github.com/teamods/writing_reports/_static/report_4phone.pdf"
   * "Sphinx HTML documents with 20+ different designs": "http://hplgit.github.com/teamods/writing_reports/_static/sphinx-fenics_minimal1/report.html"
   * "Plain HTML": "http://hplgit.github.com/teamods/writing_reports/_static/report.html", "Boostrap HTML": "http://hplgit.github.com/teamods/writing_reports/_static/report_bootstrap_bluegray.html", or with a "template": "http://hplgit.github.com/teamods/writing_reports/_static/report_vagrant.html", or with "another template": "http://hplgit.github.com/teamods/writing_reports/_static/report_github_minimal.html", or "solarized HTML": "http://hplgit.github.com/teamods/writing_reports/_static/report_solarized3_light.html"
   * HTML for "Google": "http://doconce-report-demo.blogspot.no/" or "Wordpress": "http://doconcereportdemo.wordpress.com/" blog posts
   * "MediaWiki": "http://doconcedemo.shoutwiki.com/wiki/DocOnce_demo_page" (Wikipedia, Wikibooks, etc)
   * Markdown for further processing by Pandoc to a lot of formats
   * "IPython notebook": "http://nbviewer.ipython.org/url/hplgit.github.com/teamods/writing_reports/_static/report.ipynb"
   * Other formats include plain untagged text (for email),
     Creole wiki (for Bitbucket wikis), Google wiki (for Googlecode),
     and reStructuredText.
 * There is an exercise environment with many advanced features
   such as subexercises and solutions. The document can be compiled
   with or without solutions.
 * With a preprocessor, Preprocess or Mako, one can include other
   documents (files), large portions of text can be defined in or out
   of the text. Mako enables use of variables, functions, if-tests,
   and loops to parameterize the text and generate various versions of
   the text for different purposes.
 * Computer code can be copied directly from parts of source code files.
 * Figures and movies with captions, simple tables,
   URLs with links, index list, labels and references are supported.
   YouTube and Vimeo videos are automatically embedded in web documents.
 * Running text can quickly be edited to slide formats (reveal.js and deck.js,
   based on HTML5+CSS3).
 * Special exercise environments with support for hints, answers,
   subexercises, etc.
 * Automatic inline embedding of YouTube and Vimeo movies.
 * Good support for admonitions in various LaTeX and HTML styles
   for warnings, questions, hints, remarks, summaries, etc.


======= What Does DocOnce Look Like? =======

DocOnce text looks like ordinary text (much like Markdown[^markdown-input]),
but there
are some almost invisible text constructions that allow you to control
the formating. Here are some examples.

  * Bullet lists automatically arise from lines starting with `*`,
    or `o` if the list is to be enumerated.
  * *Emphasized words* are surrounded by `*`. _Words in boldface_
    are surrounded by underscores.
  * Words from computer code are enclosed in backticks and
    then typeset `verbatim (in a monospace font)`.
  * Section headings are recognized by special
    decorating characters `=` before and after the heading, e.g.,
    `===== Here is a subsection heading =====`.
  * The abstract of a document starts with *Abstract* as paragraph
    heading, and all text up to the next heading makes up the abstract,
  * Blocks of computer code are surrounded by
    `!bc` (begin code) and `!ec` (end code) tags on separate lines.
    Blocks of computer code can also be imported from source files.
  * Blocks of LaTeX mathematics are surrounded by
    `!bt` (begin TeX) and `!et` (end TeX) tags on separate lines.
    Inline mathematics is surrounded by dollar signs: `$a=b$`.
  * Comment lines start with `#` and are not visible in the output document.
  * Comments to authors can be inserted throughout the text with a
    syntax like `[name: comment...]` and made visible or invisible as desired.
  * Title, author, date, figures, and movies are written on one line,
    starting with a keyword: `TITLE:`, `AUTHOR:`, `DATE:`, `FIGURE:`,
    and `MOVIE:`.

[^markdown-input]: In fact, DocOnce allows basic
"GitHub-extended Markdown syntax": "https://guides.github.com/features/mastering-markdown/" as input. This is attractive for newcomers from Markdown or
writers who also write Markdown documents (or uses Markdown frequently at
GitHub).

!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.
!ewarning

===== What Can DocOnce Be Used For? =====

LaTeX is ideal for articles, thesis, and books, but the PDF files does
not look fresh and modern on tablets and phones or big computer
screens. For the latter type of media you need HTML-based documents
with strong support for nice layouts. Tools like Sphinx, Markdown, or
plain HTML with Bootstrap are then more appropriate than LaTeX, but
involves a very different syntax.  DocOnce lets you write one text in
one place and then generate the most appropriate language for the
media you want to target.  DocOnce also has many extra features for
supporting large documents with much code and mathematics, not found
in any of other publishing tool.

# #include "../manual/guidelines.do.txt"

===== Basic Syntax =====

Here is an example of some simple text written in the DocOnce format:

!bc
======= First a Section Heading =======

===== Then a Subsection Heading =====

=== Finally a Subsubection Heading ===

You can also have paragraphs with a paragraph heading surrounded
by double underscores are the beginning of a line.

__This is a paragraph heading.__
And here comes the text.

===== A Subsection with Sample Text =====
label{my:first:sec}

Ordinary text looks like ordinary text, but must always start at the
beginning of lines. Tags used for _boldface_ words, *emphasized*
words, and `computer` words look natural in plain text.  Quotations
appear inside double backticks and double single quotes, as in ``this
example''.

Below the section title we have a *label*, which can be used to
refer to Section ref{my:first:sec}.
References to equations, such as XXX1, work in the same
LaTeX-inspired way.

Lists are typeset as you would do in email,

  * item 1
  * item 2,
    perhaps with a 2nd line
  * item 3

Note the consistent use of indentation (as in Python programming!).
Lists can also have automatically numbered items instead of bullets,

  o item 1
  o item 2
  o item 3,
    but be careful with the indentation of the next lines!

__Hyperlinks.__
URLs with a link word are possible, as in "hpl": "http://folk.uio.no/hpl".
If the word is just URL, the URL itself becomes the link name,
as in URL: "tutorial.do.txt". DocOnce distinguishes between paper
and screen output. In traditional paper output, in PDF generated from LaTeX
generated from DocOnce, the URLs of links appear as footnotes.
With screen output, all links are clickable hyperlinks, except in
the plain text format which does not support hyperlinks.

__Inline comments.__
DocOnce also allows inline comments of the form [name: comment] (with
a space after `name:`), e.g., such as [hpl: here I will make some
remarks to the text]. Inline comments can be removed from the output
by a command-line argument (see Section ref{doconce2formats} for an
example). Inline comments can also be used for detailed editing of
text, much like track changes in word, to illustrate how a text
is revised. (However, for seeing how others have revised the text, I
strongly recommend using Git for version control and running `git diff`
on the appropriate versions, or you can click on differences at
GitHub if the files are hosted there.)

__Footnotes.__ Adding a footnote[^footnote] is also possible.

[^footnote]: The syntax for footnotes is borrowed from Extended Markdown.

__Tables.__
Tables are also written in the plain text way, e.g.,

  |--c--------c-----------c--------|
  |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    |
  |--------------------------------|

The characters `c`, `r`, and `l` can be inserted, as illustrated above,
for aligning the headings and the columns (center, right, left).
One can also use `X` for potentially very long text in a column (will be
left-adjusted).

# Lines beginning with # are comment lines.
!ec

The DocOnce text above results in the following little document:


======= First a Section Heading =======

===== Then a Subsection Heading =====

=== Finally a Subsubection Heading ===

You can also have paragraphs with a paragraph heading surrounded
by double underscores are the beginning of a line.

__This is a paragraph heading.__
And here comes the text.

===== A Subsection with Sample Text =====
label{my:first:sec}

Ordinary text looks like ordinary text, but must always start at the
beginning of lines. Tags used for _boldface_ words, *emphasized*
words, and `computer` words look natural in plain text.  Quotations
appear inside double backticks and double single quotes, as in ``this
example''.

Below the section title we have a *label*, which can be used to
refer to Section ref{my:first:sec}.
References to equations, such as '(ref{myeq1})', work in the same
LaTeX-inspired way.

Lists are typeset as you would do in email,

  * item 1
  * item 2,
    perhaps with a 2nd line
  * item 3

Note the consistent use of indentation (as in Python programming!).
Lists can also have automatically numbered items instead of bullets,

  o item 1
  o item 2
  o item 3,
    but be careful with the indentation of the next lines!

__Hyperlinks.__
URLs with a link word are possible, as in "hpl": "http://folk.uio.no/hpl".
If the word is just URL, the URL itself becomes the link name,
as in URL: "tutorial.do.txt". DocOnce distinguishes between paper
and screen output. In traditional paper output, in PDF generated from LaTeX
generated from DocOnce, the URLs of links appear as footnotes.
With screen output, all links are clickable hyperlinks, except in
the plain text format which does not support hyperlinks.

__Inline comments.__
DocOnce also allows inline comments of the form [name: comment] (with
a space after `name:`), e.g., such as [hpl: here I will make some
remarks to the text]. Inline comments can be removed from the output
by a command-line argument (see Section ref{doconce2formats} for an
example). Inline comments can also be used for detailed editing of
text, much like track changes in word, to illustrate how a text
is revised. (However, for seeing how others have revised the text, I
strongly recommend using Git for version control and running `git diff`
on the appropriate versions, or you can click on differences at
GitHub if the files are hosted there.)

__Footnotes.__ Adding a footnote[^footnote] is also possible.

[^footnote]: The syntax for footnotes is borrowed from Extended Markdown.

__Tables.__
Tables are also written in the plain text way, e.g.,

  |--c--------c-----------c--------|
  |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    |
  |--------------------------------|

The characters `c`, `r`, and `l` can be inserted, as illustrated above,
for aligning the headings and the columns (center, right, left).

# Lines beginning with # are comment lines.


===== Mathematics =====

Inline mathematics, such as $\nu = \sin(x)$ is written exactly as in LaTeX:

!bc
$\nu = \sin(x)$
!ec

Blocks of mathematics are typeset with raw LaTeX, inside
`!bt` and `!et` (begin TeX, end TeX) directives:

!bc
|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
\end{align}
|et
!ec
## Note: |bt and |et (and |bc and |ec below) are used to illustrate
## tex and code blocks in inside verbatim blocks and are replaced
## by !bt, !et, !bc, and !ec after all other formatting is finished.
## (Comment lines starting with ## are not copied to the output
## format and hence much used to explain the DocOnce syntax
## used in special constructions.)
The result looks like this:

!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
\end{align}
!et
Of course, such blocks only looks nice in formats with support
for LaTeX mathematics
(this includes `latex`, `pdflatex`, `html`, `sphinx`, `ipynb`, `pandoc`,
and `mwiki`). Simpler
formats have to just list the raw
LaTeX syntax.

!bwarning Remark
Although DocOnce allows user-defined styles in the preamble of LaTeX output,
HTML-based output cannot make use of such styles. If-else constructs for
the preprocessor can be used to allow special LaTeX environments for
LaTeX output and alternative typesetting for other formats, but it is
recommended to stay away from special environments in the text and
write in a simpler fashion. For example, DocOnce has no special construction
for algorithms, so these must be simulated by lists or verbatim blocks.
Other constructions that should be avoided include margin notes, special
tables, and
`subfigure` (combine image files to one file instead, via `doconce combine_images`).
!ewarning

===== Computer Code =====

You can have blocks of computer code, starting and ending with
`!bc` and `!ec` instructions, respectively.

!bc
|bc pycod
from math import sin, pi
def myfunc(x):
    return sin(pi*x)

import integrate
I = integrate.trapezoidal(myfunc, 0, pi, 100)
|ec
!ec
Such blocks are formatted as

!bc pycod
from math import sin, pi
def myfunc(x):
    return sin(pi*x)

import integrate
I = integrate.trapezoidal(myfunc, 0, pi, 100)
!ec
A code block must come after some plain sentence (at least for successful
output to `sphinx`, `rst`, and formats close to plain text),
not directly after a section/paragraph heading or a table.

Blocks of computer code has *named environments*, such as *pycod*. The *py*
stands for Python and *cod* indicates a code snippet that cannot be run
without more code. Another example is *fpro*, *f* for Fortran and *pro* for
a complete program that will run as it stands. There is support for
code in C, C++, Fortran, Java, Python, Perl, Ruby, JavaScript, HTML, and LaTeX,

# Note: the @@@CODE command starts in column 2 below such that we fool
# DocOnce to drop copying the file...

One can also copy computer code directly from files, either the
complete file or specified parts, e.g,

!bc
 @@@CODE src/myprog.py fromto: def regression\(@import mymod
!ec
The copying is based on regular expressions and not on line numbers, which
makes the specifications much more robust during software and document
developing. With the `@@@CODE` command,
computer code is never
duplicated in the documentation (important for the principle of
avoiding copying information!) and once the software is updated, the
next compilation of the document is up-to-date.

__Inclusion of files.__ Another DocOnce document or any file can be
included by writing `# #include "mynote.do.txt"` at the beginning of a
line.  DocOnce documents have extension `do.txt`. The `do` part stands
for `doconce`, while the trailing `.txt` denotes a text document so
that editors gives you plain text editing capabilities.


===== Macros (Newcommands), Cross-References, Index, and Bibliography =====
label{newcommands}

DocOnce supports a type of macros via a LaTeX-style *newcommand*
construction.  The newcommands are defined in files with names
`newcommands*.tex`, using standard LaTeX syntax. Only newcommands
for use inside LaTeX math environments are supported. (But you can
define any type of macros through Mako functions!)

Labels, corss-references, citations, and support of an index and
bibliography are much inspired by LaTeX syntax, but DocOnce features
no backslashes. Use labels for sections and equations only, and
preceed the reference by ``Section'' or ``Chapter'', or in case of
an equation, surround the reference by parenthesis.

Here is an example:

!bc
===== My Section =====
label{sec:mysec}

idx{key equation} idx{$\u$ conservation}

We refer to Section ref{sec:yoursec} for background material on
the *key equation*. Here we focus on the extension

# \Ddt, \u and \mycommand are defined in newcommands_keep.tex

|bt
\begin{equation}
\Ddt{\u} = \mycommand{v},
label{mysec:eq:Dudt}
\end{equation}
|et
where $\Ddt{\u}$ is the material derivative of $\u$.
Equation (ref{mysec:eq:Dudt}) is important in a number
of contexts, see cite{Larsen_et_al_2002,Johnson_Friedman_2010a}.
Also, cite{Miller_2000} supports such a view.

As see in Figure ref{mysec:fig:myfig}, the key equation
features large, smooth regions *and* abrupt changes.

FIGURE: [fig/myfile, width=600 frac=0.9] My figure. label{mysec:fig:myfig}

===== References =====

BIBFILE: papers.pub
!ec

DocOnce applies "Publish":
"https://bitbucket.org/logg/publish" for specifying bibliographies because
this tool has more functionality than BibTeX, but any BibTeX database can
be automatically converted to the simple Publish format.

For further details on functionality and
syntax we refer to the "DocOnce manual": "http://hplgit.github.io/doconce/doc/pub/manual/html/".


======= From DocOnce to Other Formats =======
label{doconce2formats}

We refer to the manual for detailed information on how to compile a DocOnce
document to various formats. Here we just give a glimpse of the
possibilities.

===== Example: Make an HTML File =====

Suppose you have some DocOnce text in `mydoc.do.txt`. Here is how you
compile that document to an HTML file `mydoc.html`, which can be viewed
in a web browser:

!bc sys
Terminal> doconce format html mydoc --html_style=bootswatch_journal
!ec
There are lots of styles for HTML files, and `bootswatch_journal` is
a fancy one. There are also lots of other command-line options for
tailoring the compilation. Run `doconce format --help` to see a list
of all options. Those that start with `--html_` are specific for the
HTML output format.

===== Preprocessors =====

A DocOnce compilation has three stages:

 o The preprocessor Preprocess is applied to `mydoc.do.txt`, resulting in `tmp_preprocess__mydoc.do.txt`.
 o The preprocessor Mako is applied to `tmp_preprocess__mydoc.do.txt`, resulting in `tmp_mako__mydoc.do.txt`.
 o The text in `tmp_mako__mydoc.do.txt` is translated to the chosen output format.

The preprocessor stages are only run if you have applied preprocessor
syntax. The Preprocess program allows you to include other files
(usually other DocOnce files) in your document (nested includes are
possible). You can also have if-else branching based on variables set
on the command line. The Mako preprocessor is (much) more advanced
and features if-else tests, loops, variables, and function calls.
You can, e.g., write Python functions in Mako to make quite intelligent
output (e.g., copy computer code from a certain directory based on a
variable that tells which computer language the document is to apply).
The preprocessors are definitely one of the strongest features of
DocOnce.

===== Output Formats =====

DocOnce can be translated to many formats. For documents with much
mathematics and/or computer code the following formats are suitable:

 * `latex`, `pdflatex`
 * `html`
 * `sphinx`
 * `ipynb` (IPython/Jupyter notebooks)
 * `matlabnb` (Matlab notebooks)

Other formats are

 * Wikis: `gwiki` (Googlecode), `cwiki` (Creole), `mwiki` (MediaWiki)
 * `plain` (pure ascii)
 * `pandoc` (various Markdown formats)

===== Slides =====

DocOnce has strong support for writing slides, see the
"slides demo": "http://hplgit.github.io/doconce/doc/pub/slides/demo/index.html"
for examples. Each slide starts with
a subsection heading (5 `=`), preceded by `!split` to indicate a
new slide. Section headings are used to mark parts of the presentation.
The slides are compiled as any other DocOnce file, but there is usually
a second step where the text is modified to become a proper slide text
in the chosen output format. We refer to the manual for details
and the "DocOnce slide demo": "http://hplgit.github.io/doconce/doc/pub/slides/demo/index.html".

Several popular slide formats are supported:

 * LaTeX Beamer
 * HTML5: reveal.js, deck.js, CSSS
 * Markdown: Remark
 * Plain HTML


======= Demos =======

Our "short scientific report":
"http://hplgit.github.io/teamods/writing_reports/index.html" is a good
starting point for seeing how DocOnce documents are written and get a
demonstration of the vast choice of output formats and settings that
are available.

There is also a demo of different "slide formats":
"http://hplgit.github.io/doconce/doc/pub/slides/demo/index.html".

DocOnce has support for *responsive* HTML documents with design and
functionality based on Bootstrap styles.  A "Bootstrap demo":
"http://hplgit.github.io/doconce/doc/pub/bootstrap/index.html"
illustrates the many possibilities for colors and layouts.

DocOnce also has support for exercises in "quiz format":
"http://hplgit.github.io/doconce/doc/pub/quiz/quiz.html". Pure quiz
files can be *automatically uploaded* to "Kahoot!":
"https://getkahoot.com" online quiz games operated through smart
phones (with the aid of "quiztools":
"https://github.com/hplgit/quiztools" for DocOnce to Kahoot!
translation).

The current text is generated from a DocOnce format stored in the file

!bc
doc/tutorial/tutorial.do.txt
!ec
The file `make.sh` in the `tutorial` directory of the
DocOnce source code contains a demo of how to produce a variety of
formats.
