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

idx{`doconce` commands!`format`}

Transformation of a DocOnce document `mydoc.do.txt` to various other
formats is done with the script `doconce format`:

!bc sys
Terminal> doconce format formatname mydoc.do.txt
!ec
or just drop the extension:

!bc sys
Terminal> doconce format formatname mydoc
!ec

===== Writing a Makefile =====
label{do2any:make_sh}

Producing HTML, Sphinx, and in particular LaTeX documents from
DocOnce sources requires a few commands. Often you want to
produce several different formats. The relevant commands should
then be placed in a script that acts as a ``makefile''.

We here show how to make a Bash script. Alternatively, scripts
can be coded in Python or Perl, for instance. Below is
the skeleton of a typical Bash script, called `make.sh` and run as
`bash make.sh` in a Terminal application on Mac or any of the many
terminal or console applications on Linux. On Windows you normally
cannot run Bash scripts, so you should go for Python instead (maybe
as the language in Windows Script Host).

!bc shpro
#!/bin/bash
set -x  # write out all commands prior to execution

function system {
# Run operating system command and if failure, report and abort

  "$@"
  if [ $? -ne 0 ]; then
    echo "make.sh: unsuccessful command $@"
    echo "abort!"
    exit 1
  fi
}

# Do a hard clean (remove all files that can be regenerated)
doconce clean
# Do a soft clean (keep compiled files)
#doconce lightclean

# Run spellcheck
system doconce spellcheck -d .dict4spell.txt *.do.txt

name=mydoc # name of DocOnce master document

# Compile to PDF
system doconce pdflatex $name --latex_code_style=pyg  # + more options
system pdflatex -shell-escape $name
system bibtex $name
system makeindex $name
pdflatex -shell-escape $name
pdflatex -shell-escape $name

# Compile to HTML (two different styles)
styles="bootstrap solarized3"
for style in $styles; do
system doconce format html $name --html_style=$style \
       --html_output=${name}-${style}
system doconce split_html ${name}-${style}  # split at !split commands
done

# Compile to Sphinx
system doconce format sphinx $name
system doconce sphinx_dir theme=alabaster $name
python automake_sphinx.py
!ec

In addition, you are strongly encouraged to make a clean script.
Here is a quick Bash version, called `clean.sh`:

!bc shpro
#!/bin/sh
doconce clean
rm -f *.html
rm -rf Trash
rm -f automake_sphinx.py
!ec

If you host your files in a Git repository, you should also have a
`.gitignore` file in the root directory of the repository:

!bc
*~
.*~
tmp*
temp*
.#*
\#*
# DocOnce files
.*_html_file_collection
*.p.tex
.*.exerinfo
.*.quiz
.*.quiz.html
automake_sphinx.py
Trash
# LaTeX files:
*.log
*.dvi
*.aux
*.blg
*.idx
*.nav
*.out
*.toc
*.snm
*.vrb
!ec

idx{`.nojekyll` file}

If you host your files on GitHub and use a gh-pages branch to publish
your documents, make sure you have an empty file called `.nojeykyll`
in the root directory or the repository and that this file is present
in the gh-pages branch. Without `.nojekyll`, GitHub will not display
files starting with an underscore or dot, with the result that
HTML and Sphinx documents are not rendered correctly.


===== Generating a Makefile =====
label{do2any:make}

The `doconce makefile` can be used to automatically generate
such a makefile, more precisely a Python script `make.py`, which
carries out the commands explained below. If our DocOnce source
is in `main_myproj.do.txt`, we run

!bc sys
doconce makefile main_myproj html pdflatex sphinx
!ec
to produce the necessary output for generating HTML, pdfLaTeX, and
Sphinx. Usually, you need to edit `make.py` to really fit your
needs. Some examples lines are inserted as comments to show
various options that can be added to the basic commands.
A handy feature of the generated `make.py` script is that it
inserts checks for successful runs of the many `doconce` commands,
and if something goes wrong, the script aborts.


===== Spell checking =====
label{do2any:spellcheck}

Despite not being a part of compiling DocOnce to some format, spell checking
is often the first task done in a `make.sh` or `make.py` file. DocOnce
comes with a convenient support for spell checking, `doconce spellcheck`, where
all code and mathematics are stripped from the document, as well as all inline
verbatim expressions, comments, etc. Then the program `ispell` is run on
the stripped document, and a list of misspellings is reported.

Any DocOnce document has its own set of ``legal words'' (approved by the
authors) in the file `.dict4spell.txt`. When `doconce spellcheck` reports
new misspellings, some are corrected and some are added to `.dict4spell.txt`.
The spell checker applies an American dictionary and the user's custom
dictionary in `.dict4spell.txt`.

The work flow is simple:

  o Run `doconce spellcheck -d .dict4spell.txt *.do.txt`
  o Examine `misspellings.txt~` for misspellings and make corrections in
    the source files.
  o Rerun `doconce spellcheck` and repeat the procedure.
  o When all words in `misspellings.txt~` are acceptable, add these to
    the current custom dictionary by `cp new_dictionary.txt~ .dict4spell.txt`.

Run `doconce spellcheck` without any arguments to get more description of
what kind of files that are produced. For example, the text in `mydoc.do.txt`,
stripped for math, code, and other special constructions, is available
in `tmp_stripped_mydoc.do.txt` and can be copied into (e.g.) Microsoft Word
for grammar check.

===== Preprocessing =====
label{do2any:pre}

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

The `preprocess` and `mako` programs are used to preprocess the
file. The DocOnce program detects whether `preprocess` and/or `mako`
statements are present and runs the corresponding programs, first
`preprocess` and then `mako`.

Variables to `preprocess` and/or `mako` can be added after the
filename with the syntax `-DMYVAR`, `-DMYVAR=val` or `MYVAR=val`.

 * The form `-DMYVAR` defines the variable `MYVAR` for `preprocess` (like the
   same syntax for the C preprocessor - `MYVAR` is defined, but has
   not specific value). When running `mako`, `-DMYVAR` means that
   `MYVAR` has the (Python) value `True`. You can test for
   `# #ifdef MYVAR` in Preprocess and `% if MYVAR:` in Mako.
 * The expressions `-DMYVAR=val` and `MYVAR=val` are
   equivalent. When running `preprocess`, `MYVAR` is defined and has
   the value `val` (`# #ifdef MYVAR` and `# #if MYVAR == "val"` are both
   true tests), while for `mako`, `MYVAR` exists as
   variable and has the value `val` (`% if MYVAR == "val"` is true).

Note that `MYVAR=False` defines `MYVAR` in `preprocess` and
any test `# #ifdef MYVAR` is always true, regardless of the value one has
set `MYVAR` to, so a better test is
`# #if MYVAR == True`. In general, it is recommended to go with
`preprocess` directives if the tests are very simple, as in
`# #ifdef MYVAR` or `# #if FORMAT == "latex"`, otherwise use
only `mako` syntax like `% if MYVAR or YOURVAR:` to incorporate
`if` tests in the preprocessor phases.

Two examples on defining preprocessor variables are

!bc sys
Terminal> doconce format sphinx mydoc -Dextra_sections -DVAR1=5
Terminal> doconce format sphinx mydoc extra_sections=True VAR1=5
!ec

The variable `FORMAT` is always defined as the current format when
running `preprocess` or `mako`. That is, in the above examples, `FORMAT` is
defined as `sphinx`. Inside the DocOnce document one can then perform
format specific actions through tests like `#if FORMAT == "sphinx"`
(for `preprocess`) or `% if FORMAT == "sphinx":` (for `mako`).

The result of running `preprocess` on a DocOnce file `mydoc.do.txt`
is available in a file `tmp_preprocess__mydoc.do.txt`. Similarly,
the result of running `mako` is available in
`tmp_mako__mydoc.do.txt`. By examining these files one can see exactly
what the preprocessors have done.

The command-line arguments `--no_preprocess` and `--no_mako` turn off
running `preprocess` and `mako`, respectively.


=== Variable Substition with Preprocessors ===

A variable `VAR=value` given on the command line (or `-DVar=value`) can
be used in Preprocess and Mako tests. With Mako, the variable can
also be used inside text, as `${VAR}`, and Mako will substitute the
variable by its value. Preprocess can also substitute a variable by
its value, but this is (on DocOnce's use of Preprocess) restricted
to filenames in `#include` statements. With the command-line option
`--preprocess_include_subst`, any `-DVAR=value` variable will lead
to a susbtitution of `VAR` by `value` in included filenames.
For example, `# #include "MYDIR/myfile.do.txt"` and `-DMYDIR=RN2`
will lead to inclusion of the file `RN2/myfile.do.txt`. Note that
for this Preprocess substitution, the variable in the filename
must be `MYDIR`, not `${MYDIR}` as with Mako.

===== Removal of Inline Comments =====
label{do2any:inlinecomments}

idx{inline comments}

Inline comments (inside square brackets)
in the text are removed from the output by

!bc sys
Terminal> doconce format latex mydoc --skip_inline_comments
!ec
One can also remove all such comments from the original DocOnce
file by running:
!bc
Terminal> doconce remove_inline_comments mydoc
!ec
This action is convenient when a DocOnce document reaches its final form
and comments by different authors should be removed.

===== Notes =====
label{do2any:notes}

idx{notes (visible/invisible)}

DocOnce does not have a tag for longer notes, because implementation
of a "notes feature" is so easy using the `preprocess` or `mako`
programs. Just introduce some variable, say `NOTES`, that you define
through `-DNOTES` (or not) when running `doconce format ...`. Inside
the document you place your notes between `# #ifdef NOTES` and
`# #endif` preprocess tags. Alternatively you use `% if NOTES:`
and `% endif` that `mako` will recognize. In the same way you may
encapsulate unfinished material, extra material to be removed
for readers but still nice to archive as part of the document for
future revisions.

===== Demo of Different Formats =====

idx{demos}

A simple scientific report is available in "a lot of different formats":
"http://hplgit.github.com/teamods/writing_reports/index_with_doconce_commands.html".
How to create the different formats is explained in more depth
in the coming sections.

===== Tweaking the DocOnce Output =====
label{do2any:tweaking}

idx{tweaking output}
idx{automatic editing}

Occasionally, one would like to tweak the output in a certain format
from DocOnce. One example is figure filenames when transforming
DocOnce to reStructuredText. Since DocOnce does not know if the
`.rst` file is going to be filtered to LaTeX or HTML, it cannot know
if `.eps` or `.png` is the most appropriate image filename.
The solution is to use a text substitution command or code with, e.g., sed,
perl, python, or scitools subst, to automatically edit the output file
from DocOnce. It is then wise to run DocOnce and the editing commands
from a script to automate all steps in going from DocOnce to the final
format(s). The `make.sh` files in `docs/manual` and `docs/tutorial`
constitute comprehensive examples on how such scripts can be made.


===== Useful Options for `doconce format` =====

The `doconce format` command used to translate a DocOnce document to
an output format performs some syntax check and to notify the user
about common problems. There are some useful options for turning on
additional checks:

 * `--labelcheck=on` (or `off`) to check that every `ref` reference
   has a corresponding `label` definition within the document (this check
   may lead to wrong diagnostics, e.g., when a label is defined in an
   external document and referred via generalized references, so the
   check must be used with care)
 * `--urlcheck` checks that all URLs referred to in the document are valid.

Other useful options are

 * `--os_prompt=PROMPT>` sets the prompt, here `PROMPT>`, as terminal
   prompt in output from running OS commands with the `@@@OSCMD` instruction.
   The value `None` gives no prompt.
 * `--code_prefix=X` prefixes all `@@@CODE` imports with some path `X`
   (if the source files are located in some other directory)
 * `--figure_prefix=X` and `--movie_prefix=X` prefix figure/movie file
   names with a path or URL
 * `--sections_down` and `--sections_up` move all sections down or up
   (e.g., sections become subsections or chapters).
 * `--tables2csv` translates each table to a CSV file.
 * `--short_title=X` sets a short title `X` for the document.
 * `--toc_depth=X`: controls the depth of the table of contents
   in documents. Default value of `X` is 3, meaning chapters,
   sections, and subsections. `X` as 0 gives the table of contents as a
   nested list in Bootstrap styles.

Many more options, depending on the output format, are listed in the
following sections. A list of all options is otbained by running
`doconce format --help` (or preferably
`doconce format --help | less` since the output is extensive).

======= HTML =======
label{do2any:html}

idx{HTML output}
idx{output format!HTML}

===== Basic HTML Output =====

Making an HTML version of a DocOnce file `mydoc.do.txt`
is performed by
!bc sys
Terminal> doconce format html mydoc
!ec
The resulting file `mydoc.html` can be loaded into any web browser for viewing.

idx{HTML syntax highlighting}

===== Typesetting of Code =====

If the Pygments package (including the `pygmentize` program)
is installed, code blocks are typeset with
aid of this package. The command-line argument `--no_pygments_html`
turns off the use of Pygments and makes code blocks appear with
plain (`pre`) HTML tags. The option `--pygments_html_linenos` turns
on line numbers in Pygments-formatted code blocks. A specific
Pygments style is set by `--pygments_html_style=style`, where `style`
can be `default`, `emacs`, `perldoc`, and other valid names for
Pygments styles.

idx{HTML movies}
idx{movies in HTML}

===== Handling of Movies =====

MP4, WebM, and Ogg movies are typeset with the HTML5 `video` tag
and the HTML code tries to load as many versions among MP4, WebM,
and Ogg as exist (and the files are loaded in the mentioned order).
If just the specified file is to be loaded, use the
`--no_mp4_webm_ogg_alternatives` command-line option.
Other movie formats, e.g., `.flv`, `.mpeg` and `.avi`, are embedded via
the older `embed` tag.

idx{HTML layouts}

===== HTML Styles =====

The HTML style can be defined either in the header of the HTML file,
using a named built-in style;
in an external CSS file; or in a template file.

An external CSS file `filename` used by setting the command-line
argument `--css=filename`. There available built-in styles are
specified as `--html_style=name`, where `name` can be

 * `solarized`: the famous "solarized": "http://ethanschoonover.com/solarized"
   style (yellowish),
 * `blueish`: a simple style with blue headings (default),
 * `blueish2`: a variant of *bluish*,
 * `bloodish`: as `bluish`, but dark read as color,
 * `bootstrap*` or `bootswatch*` in a lot of variants, see
   `doconce format --help` for a list of all styles.

There is a "comprehensive demonstration": "http://hplgit.github.io/teamods/writing_reports/index.html" of almost all available styles!

Using `--css=filename` where `filename` is a non-existing file makes
DocOnce write the built-in style to that file. Otherwise the HTML
links to the CSS stylesheet in `filename`. Several stylesheets can
be specified: `--ccs=file1.css,file2.css,file3.css`.

idx{HTML templates}

===== HTML templates =====

Templates are HTML files with ready-made headers, footers, and style
specifications where plain HTML text can be inserted in "slots" in the
template file. Typically, there is a slot `%(main)s` for the main body
of text, `%(title)s` for the title, and `%(date)s` for the date.
Templates are designed beforehand and `doconce format` puts
the translated HTML text into the template to form the complete HTML
document.

DocOnce comes with a few ready-made HTML templates. The usage of templates is
described in a "separate document": "http://hplgit.github.io/doconce/doc/pub/design/". That document describes how you your DocOnce-generated
HTML file can have any specified layout.

The HTML file can be embedded in a template with your own tailored
design, see a "tutorial": "http://hplgit.github.io/doconce/doc/pub/tech_wrapper.htl" on this topic. The template file must contain
valid HTML code and can have three "slots": `%(title)s` for a title,
`%(date)s` for a date, and `%(main)s` for the main body of text. The
latter is the
DocOnce document translated to HTML. The title becomes the first
heading in the DocOnce document, or the title (but a title is not
recommended when using templates). The date is extracted from the
`DATE:` line. With the template feature one can easily embed
the text in the look and feel of a website. DocOnce comes with
two templates in `bundled/html_styles`. Just copy the directory
containing the template and the CSS and JavaScript files to your
document directory, edit the template as needed (also check that
paths to the `css` and `js` subdirectories are correct - according
to how you store the template files), and run

!bc sys
Terminal> doconce format html mydoc --html_template=mytemplate.html
!ec
The template in `style_vagrant` also needs an extra option
`--html_style=bootstrap`.

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

===== Splitting HTML documents =====

The `!split` instruction (on separate lines) signifies a pagebreak.
A command `doconce split_html` is needed after `doconce format` to
actually perform the split. The `doconce split_html` command has
several options for setting the type of splitting, type of navigation
buttons, etc. Just type `doconce split_html` to see the options.
Here is an example with separate links for each page (pagination)
at the top and bottom of each page:

!bc sys
Terminal> doconce format html mydoc --html_style=bootswatch_journal
Terminal> doconce split_html mydoc --nav_buttontop+bottom --pagination
!ec

idx{HTML file collection}

=== The HTML File Collection ===

There are usually a range of files needed for an HTML document arising
from a DocOnce source. The needed files are listed in
`.basename_html_file_collection`, where `basename` is the filestem of
the DocOnce file (i.e., the DocOnce source is in `basename.do.txt`).

=== Filenames ===

An HTML version of a DocOnce document is often made in different styles,
calling for a need to rename the HTML output file. This is conveniently
done by the `--html_output=mydoc` option, where `mydoc` is the
filestem of the associated HTML files. The
`.mydoc_html_file_collection` file lists all the needed files
for the HTML document. Here is an example on making three versions of
the HTML document: `mydoc_bloodish.html`, `mydoc_solarized`, and
`mydoc_vagrant`.

!bc sys
Terminal> doconce format html mydoc --html_style=bloodish \
          --html_output=mydoc_bloodish
Terminal> doconce split_html mydoc_bloodish.html
Terminal> doconce format html mydoc --html_style=solarized \
          --html_output=mydoc_solarized \
          --pygments_html_style=perldoc --html_admon=apricot
Terminal> doconce format html mydoc --html_style=vagrant \
          --html_output=mydoc_vagrant --pygments_html_style=default \
          --html_template=templates/my_adapted_vagrant_template.html
Terminal> doconce split_html mydoc_vagrant.html
!ec

===== URL to files hosted on GitHub =====

The generated HTML code will have URLs to files in the DocOnce repo at GitHub.
The type of URL is set with the `--html_raw_github_url=...` option:

 * `--html_raw_github_url=safe` or `--html_raw_github_url=cdn.rawgit`:
   safe URL for high traffic production sites (default)
 * `--html_raw_github_url=test` or `--html_raw_github_url=rawgit`:
   recommended URL for low traffic development sites - use this when
   developing HTML pages and the DocOnce GitHub links in the HTML files
   are also developed and subject to changes
 * `--html_raw_github_url=github` or `--html_raw_github_url=raw.github`:
   URL directly to the raw GitHub file (`https://raw.github.com/hplgit/doconce/...`) that may fail to load properly in (e.g.) Internet explorer
 * `--html_raw_github_url=githubusercontent` or `--html_raw_github_url=raw.githubusercontent`: as the one above, but using `https://raw.githubusercontent.com` instead

===== Other HTML options =====

The Bootstrap family of styles have become very popular since they
provide responsive pages for phones and small tablets.
There are several specific options for Bootstrap styles:

 * `--html_code_style=on,off,inherit,transparent`: control the style of
   inline verbatim code `code` tags. With `off`, `inherit`, or `transparent`
   the verbatim text inherits foreground and background color from its
   surroundings, while `on` (default) means that the typesetting is
   css-specified. This option is most relevant for Bootstrap styles to
   avoid the redish typesetting of inline verbatim text.
 * `--html_pre_style=on,off,inherit,transparent`: control the style of
   code blocks in `pre` tags. With `off`, `inherit`, or `transparent`
   the code blocks inherit foreground and background color from their
   surroundings, while `on` (default) means that code block colors are
   css-specified. This option is most relevant for Bootstrap styles to
   avoid white background in code blocks inside colorful admons.
 * `--html_bootstrap_navbar=on,off`: turn the Bootstrap navigation
   bar on or off.
 * `--html_bootstrap_jumbotron=on,off,h2`: turn the jumbotron intro on or off,
   and govern the size of the document title. Default is `on`, while
   `h2` means a jumbotron with `h2` (section) size of the title
   (normally the jumbotron has huge heading fonts so some jumbotrons
   look better with `h2` typesetting of the document title).
 * `--html_quiz_button_text=X`: set a text on the answer button for
   Bootstrap-style quizzes. Without this option a small icon is used.

Other options:

 * `--html_share=http://...` makes sharing buttons at the end of the
   document: email, Facebook, Google+, LinkedIn, Twitter, and print by
   default. `--html_share=http://...,twitter,linkedin` will make just
   to sharing buttons for Twitter and LinkedIn. Sites are separated
   by comma and valid names are `email`, `facebook`, `google+`,
   `linkedin`, `twitter`, and `print`. The URL `http://...` must be
   the URL where the document is published.
 * `--html_toc_indent=X`: indent sections/subsections `X` spaces in the table
   of contents.
 * `--html_body_font=`: specify font for text body. The value `?` lists
   available fonts.
 * `--html_heading_font=`: specify font for headings. The value `?` lists
   available fonts.
 * `--html_video_autoplay=True,False`: let videos play automatically
   (`True`, default) or not (`False`) when the HTML page is loaded.
 * `--html_admon=X`: specify typesetting of admonitions. Values of `X`
   are `colors`, `gray`, `yellow`, `apricot`, `lyx`, `paragraph`.
   For Bootstrap styles only to other values are legal:
   `botstrap_panel` or `bootstrap_alert`. See demos for how these look
   like.
 * `--html_admon_bg_color=X`: set the background color in admonitions.
 * `--html_admon_bd_color=X`: set the boundary color in admonitions.
 * `--html_admon_shadow`: add a shadow effect in admonitions.
 * `--html_box_shadow`: add a shadow effect in box environments (`!bbox`).
 * `--html_exercise_icon=X`: specify an icon to more easily notify exercises.
   `X` can be any filename `question_*.png` in the `bundled/html_images`
   directory in the DocOnce repo. With `X` as `default`, a default icon
   choice is made, based on the current style.
 * `--html_exercise_icon_width=X`: set the width of the exercise icon
   image to `X` pixels.
 * `--exercise_numbering=absolute, chapter`
 * `--html_DOCTYPE`: insert `<!DOCTYPE HTML>` at the top of the HTML
   output file. This is normally recommended, but malformed CSS files
   will then not be loaded (so by default, the doctype is not specified).
   This option is necessary for correct rendering of Bootstrap styles
   in Internet Explorer.
 * `--html_links_in_new_window`: open all links as new tabs.
 * `--html_figure_hrule=X`: control the use of horizontal rules in
   figures. `X` is `top` by default; other values are `none` (no rules),
   `bottom` and `top+bottom`.
 * `--allow_refs_to_external_docs` (do not abort if there are references whose labels are not found)

idx{open links in new window}

===== Blog Posts =====
label{do2any:blog}

idx{blog posts}
idx{Wordpress blog}
idx{Google blogger}

DocOnce can be used for writing blog posts provided the blog site accepts
raw HTML code. Google's Blogger service (`blogger.com` or
`blogname.blogspot.com`) is particularly well suited since it also
allows extensive LaTeX mathematics via MathJax.

 o Write the text of the blog post as a DocOnce document without any
   title, author, and date.
 o Generate HTML as described above.
 o Copy the text and paste it into the
   text area in the blog post (just delete the HTML code that initially
   pops up in the text area). Make sure the input format is HTML.

See a "simple blog example": "http://doconce.blogspot.no" and
a "scientific report": "http://doconce-report-demo.blogspot.no/"
for demonstrations of blog posts at `blogspot.no`.

!bwarning
The comment field after the blog post does not recognize MathJax (LaTeX)
mathematics or code with indentation. However, using a MathJax
bookmarklet, e.g., at URL: "http://checkmyworking.com/misc/mathjax-bookmarklet/", one can get the mathematics properly rendered. The comment fields are
not suitable for computer code, though, as HTML tags are not allowed.
!ewarning

!bnotice
Figure files must be uploaded to some web site and the local filenames name must
be replaced by the relevant URL. This is usually done by using the
`--figure_prefix=http://project.github.io/...` option to give some URL
as prefix to all figure names (a similar `--movie_prefix=` option exists as
well).

Changing figure names in a blog post can also be done ``manually'' by
some editing code in the script that compiles the DocOnce document
to HTML format:

!bc shcod
cp mydoc.do.txt mydoc2.do.txt
url="https//raw.github.com/someuser/someuser.github.com"
dir="master/project/dir1/dir2"
for figname in fig1 fig2 fig3; do
  doconce replace "[$figname," "[$site/$dir/$figname.png," \
          mydoc2.do.txt
done
doconce format html mydoc2
# Paste mydoc2.html into a new blog post page
!ec
!enotice

# See here if MathJax stops working in HTML pages on blogger and elsewhere:
# http://weiqigao.blogspot.no/2013/03/enabling-mathjax-in-blogger.html

Blog posts at Google can also be published "automatically through email":
"http://support.google.com/blogger/bin/answer.py?hl=en&answer=41452".
A Python program can send the contents of the HTML file
to the blog site's email address using the packages  `smtplib` and `email`.

WordPress (`wordpress.com`) allows raw HTML code in blogs, but has
very limited LaTeX support, basically only formulas. The `--wordpress`
option to `doconce` modifies the HTML code such that all equations are
typeset in a way that is acceptable to WordPress.  Look at a "simple
doconce example": "http://doconce.wordpress.com" and a "scientific
report": "http://doconcereportdemo.wordpress.com/" to see blog posts
with mathematics and code on WordPress.

Speaking of WordPress, the related project URL:
"http://pressbooks.com" can take raw HTML code (from DocOnce, for
instance, but use the `--wordpress` option)
and produce very nice-looking books.  There is support for LaTeX
mathematics as in WordPress blog posts, meaning that one cannot refer
to equations.

# #ifdef SAVE_AS_COMMENT
===== How to view HTML file bundles on iPad =====

PDF files from LaTeX are very easy to transfer to an iPad via a cloud
service like Dropbox and apps like
GoodReader or GoodNotes. HTML files can be viewed through a browser,
but if you want a large HTML document to be viewed offline on
an iPad you can to that by the following steps.

 o Pack all files necessary for viewing the HTML document in a tarball.
   Usually, this will be a command like `tar cvzf tmp.tar.gz mydoc.html ._mydoc*.html fig mov` (where `fig` and `mov` are figure and movie directories needed by the `.html` files).
 o Use the iZip Pro app to download the `tmp.tar.gz` file from a service
   like Dropbox.
 o Click on *Files - Dropbox - tmp.tar.gz*, unpack files and follow
   links to the directory containing the file bundle. Click on the
   main file, `mydoc.html` and it opens locally in a browser-like app.
 o No, _LINKS DO NOT WORK!_

# #endif

[[[

======= Pandoc and Markdown =======
label{do2any:pandoc}

idx{output format!Markdown}
idx{output format!Pandoc}
idx{Markdown output}
idx{Pandoc output}

Output in Pandoc's extended Markdown format results from

!bc sys
Terminal> doconce format pandoc mydoc
!ec
or (equivalent)

!bc sys
Terminal> doconce format markdown mydoc
!ec

!bwarning Test on `FORMAT == 'pandoc'` for Markdown!
Note that even though it works to write `doconce format markdown`,
the `FORMAT` variable that is defined in all DocOnce documents has
the value `pandoc` for all the Markdown formats. A test like
`FORMAT == 'markdown'` will not work!
!ewarning

The name of the output file is `mydoc.md`. There are four supported
dialects of Markdown (see sections below for more information):

 * Pandoc-extended Markdown
 * GitHub-flavored Markdown
 * MultiMarkdown
 * Strict Markdown

From the Markdown format one can go to numerous other formats using
the `pandoc` program:

!bc sys
Terminal> pandoc -R -t mediawiki -o mydoc.mwk --toc mydoc.md
!ec
Pandoc supports `latex`, `html`, `odt` (OpenOffice), `docx` (Microsoft
Word), `rtf`, `texinfo`, to mention some. The `-R` option makes
Pandoc pass raw HTML or LaTeX to the output format instead of ignoring it,
while the `--toc` option generates a table of contents.
See the "Pandoc documentation": "http://johnmacfarlane.net/pandoc/README.html"
for the many features of the `pandoc` program.

===== Markdown to HTML conversion =====

The HTML output from
`pandoc` needs adjustments to provide full support for MathJax LaTeX
mathematics, and for this purpose one should use `doconce md2html`:

!bc sys
Terminal> doconce format pandoc mydoc
Terminal> doconce md2html mydoc
!ec
The result `mydoc.html` can be viewed in a browser.

idx{output format!strict Markdown}

===== Strict Markdown =====

The option `--strict_markdown_output` generates plain or strict
Markdown without the many extension that Pandoc accepts in Markdown
syntax.

idx{output format!GitHub-flavored Markdown}

===== GitHub-flavored Markdown =====

Adding the command-line option `github-md` turns on the
"GutHub-flavored Markdown dialect": "https://guides.github.com/features/mastering-markdown/", which is used for the issue tracker on "GitHub": "http://github.com". A special feature is the support of task lists:
unnumbered lists with `[x]` (task done) or `[ ]` (task not done).
(Tables get typeset directly as HTML and the syntax for code highlighting
is different from Pandoc extended Markdown.) Below is a typical
response in a GitHub issue tracker
where one first quotes the issue and then provides an answer:

!bc
|bquote
===== Problems with a function =====

There is a problem with the `f(x)` function

|bc pycod
def f(x):
    return 1 + x
|ec
This function should be quadratic.
|equote

OK, this is fixed:

|bc pycod
def f(x, a=1, b=1, c=1):
    return a*x**2 + b*x + c
|ec

===== Updated task list =====

   * [x] Offer an `f(x)` function
   * [ ] Extension to cubic functions
   * [x] Allowing general coefficient in the quadratic function

=== Remaining functionality ===

|---------------------------------------------------------------|
| function | purpose                        | state |
|----l-----------l------------------------------l---------------|
|  `g(x)`  | Compute the Gaussian function. | Formula ready. |
|  `h(x)`  | Heaviside function.            | Formula ready. |
|  `I(x)`  | Indicator function.            | Nothing done yet. |
|---------------------------------------------------------------|

!ec
Say this text is stored in a file `mycomments.do.txt`. Running

!bc sys
Terminal> doconce format pandoc mycomments --github_md
!ec
produces the Markdown file `mycomments.md`, which can be pasted into
the Write field of
the GitHub issue tracker. Turning on Preview shows the typesetting of
the quote, compute code, inline verbatim, headings, the task list, and
the table.

===== MultiMarkdown =====

The option `--multimarkdown_output` generates the MultiMarkdown
version of Markdown (as opposed to Pandoc-extended Markdown (default),
strict Markdown, or GitHub-flavored Markdown).

idx{output format!strapdown Markdown}

===== Strapdown rendering of Markdown text =====

"Strapdown": "http://strapdownjs.com" is a tool that can render Markdown
text nicely in a web browser by just inserting an HTML header and
footer in the Markdown file and load the file into a browser.
The option `--strapdown` outputs the relevant header and footer.
The output file must be renamed such that it gets the extension `.html`:

!bc sys
Terminal> doconce format pandoc mydoc --strict_markdown_output \
          --strapdown --bootstrap_bootwatch_theme=slate
Terminal> mv mydoc.md mydoc.html
!ec
The `--bootstrap_bootwatch_theme=theme` option is used to choose
a "Bootswatch": "http://bootswatch.com/" theme whose names are
found on the "Strapdown page": "http://strapdownjs.com".

===== Using Pandoc to go from LaTeX to MS Word or HTML =====

Pandoc is useful to go from LaTeX mathematics to, e.g., HTML or MS
Word.  There are two ways (experiment to find the best one for your
document): `doconce format pandoc` and then translating using `doconce
md2latex` (which runs `pandoc`), or `doconce format latex`, and then
going from LaTeX to the desired format using `pandoc`.
Here is an example on the latter strategy:

!bc sys
Terminal> doconce format latex mydoc
Terminal> doconce ptex2tex mydoc
Terminal> doconce replace '\Verb!' '\verb!' mydoc.tex
Terminal> pandoc -f latex -t docx -o mydoc.docx mydoc.tex
!ec
When we go through `pandoc`, only single equations, `align`, or `align*`
environments are well understood for output to HTML.

Note that DocOnce applies the `Verb` macro from the `fancyvrb` package
while `pandoc` only supports the standard `verb` construction for
inline verbatim text.  Moreover, quite some additional `doconce
replace` and `doconce subst` edits might be needed on the `.mkd` or
`.tex` files to successfully have mathematics that is well translated
to MS Word.  Also when going to reStructuredText using Pandoc, it can
be advantageous to go via LaTeX.

======= LaTeX =======
label{do2any:latex}

idx{LaTeX output}
idx{output format!LaTeX}

!bnotice
XeLaTeX and pdfLaTeX are used very much in the same way as standard
LaTeX. The minor differences are described in separate sections
of the documentation of the DocOnce to LaTeX translation.
!enotice

===== Overview =====

Making a LaTeX file `mydoc.tex` from `mydoc.do.txt` can be done in two
ways:

 o direct translation to a `.tex` file
 o translation to a `.p.tex` file

In the latter case, one must apply the `ptex2tex` program or the
simplified `doconce ptex2tex` program to translate the `.p.tex` file
to a plain `.tex` file. This step involves the specification of how
blocks of verbatim code should be typeset in LaTeX. Before 2015,
DocOnce always translated to the `.p.tex` syntax and required the
use of `ptex2tex` or `doconce ptex2tex`. Now, one can choose a direct
translation, which is simpler and actually more versatile than even
using the `ptex2tex` program.

Direct translation is specified by the `--latex_code_style=` command-line
option. A separate document, "Demonstration of DocOnce support for LaTeX code block environments": "http://hplgit.github.io/doconce/doc/pub/latexcode/demo.html", describes how this option is used and the demonstrates
many possibilities that are available. One popular choice is

!bc
default:lst[style=blue1_bluegreen]@dat:lst[style=gray]@sys:vrb
!ec
This value gives syntax-highlighted blue-green code on a blue
background and sets data files with gray background.

The `--latex_code_style=` option makes the use of `ptex2tex` or
`doconce ptex2tex` redundant.

===== The old `ptex2tex` step =====

Here, we describe the old translation via a `.p.tex` file.
New users should jump over this information and use
the `--latex_code_style=` option to specify verbatim code environments.

First we
compile the DocOnce source to the `ptex2tex` format, and then we compile
the `ptex2tex` format to standard LaTeX.
The "`ptex2tex`": "http://code.google.com/p/ptex2tex" format can be
viewed as an extended LaTeX. For DocOnce users, the `ptex2tex` format
essentially means that the file consists of

 o `if-else` statements for the `preprocess` processor such that
   LaTeX constructions can be activated or deactivated, and
 o all code environments can be typeset according to a `.ptex2tex.cfg`
   configuration file.

Point 2 is only of interest if you aim to use a special computer code
formatting that requires you to use a configuration file and
the `ptex2tex` program.

The reason for generating `ptex2tex` and not standard LaTeX directly
from DocOnce was that the `ptex2tex` format shows a range of possible
LaTeX constructions for controlling the layout. It can be instructive
for LaTeX users to look at this code before choosing specific parts
for some desired layout. Experts may also want to edit this code
(which should be automated by a script such that the edits can be
repeated when the DocOnce source is modified, see Step 2b below).
(Direct control of the LaTeX layout in the `doconce format` program
would not spit out alternative LaTeX constructs as is now done through
the `ptex2tex` step.)

Going from `ptex2tex` format to standard LaTeX format is enabled by
either the `ptex2tex` program or DocOnce's (simplified) version of it:
`doconce ptex2tex`.

!bnotice Inline verbatim tries to use `texttt` and not `Verb` if possible
Inline verbatim
code, typeset with backticks in DocOnce, is translated to

!bc
\Verb!text!
!ec
or similar constructions with other delimiters if the pipe is used in `text`.
Thereafter, if `text` does not contain illegal characters for the `\texttt`
command, the latter is used instead since then LaTeX can insert
linebreaks in the inline verbatim text and hence avoid overfull hboxes.
!enotice

# Note: putting code blocks inside a list is not successful in many
# formats - the text may be messed up. A better choice is a paragraph
# environment, as used here.

===== LaTeX-PDF: Generate LaTeX (Step 1) =====
label{do2any:latex:compile1}

idx{`ptex2tex` program}
idx{`ptex2tex` doconce version}

=== The translation command ===

Filter the doconce text directly to valid LaTeX using
the `--latex_code_style=` option:

!bc sys
Terminal> doconce format pdflatex mydoc --latex_code_style=vrb
!ec
Without `--latex_code_style=`, the output will be a `mydoc.p.tex` file
that has to be converted to a standard `mydoc.tex` LaTeX file via
the programs `ptex2tex` or `doconce ptex2tex`.

=== Newcommands ===

LaTeX-specific commands (``newcommands'') in math formulas and similar
can be placed in files `newcommands.tex`, `newcommands_keep.tex`, or
`newcommands_replace.tex` (see Section ref{newcommands}).
If these files are present, they are included in the LaTeX document
so that your commands are defined.

=== Output for paper vs screen ===

An option `--device=paper` makes some adjustments for documents
aimed at being printed. For example, links to web resources are
associated with a footnote listing the complete web address (URL).
(Very long URLs in footnotes can be shortened using services such
as URL: "http://goo.gl/", URL: "http://tinyurl.com/", and
URL: "https://bitly.com/".)
The default, `--device=screen`, creates a PDF file for reading
on a screen where links are just clickable.

idx{LaTeX style options}

=== Command-line options ===

There are many additional options (run `doconce format --help` and
look for options starting with `--latex` to get a more verbose description):

 * `--latex_code_style=lst,vrb,pyg,any`
 * `--latex_font=helvetica,palatino`
 * `--latex_papersize=a4,a6`
 * `--latex_bibstyle=plain` (name of BibTeX style)
 * `--latex_title_layout=titlepage, std, beamer, doconce_heading, Springer_collection`
 * `--latex_style=std, Springer_sv, Springer_lncse, Springer_llncs, Springer_lnup, Springer_T2, Springer_T4, siamltex, siamltexmm, elsevier`
 * `--latex_packages=package1,package2,package3` (list of extra packages to be included[^varioref])
 * `--draft` (turns on draft mode in documentclass, otherwise final mode)
 * `--latex_copyright=everypage,titlepages` (copyright on every page or on titlepage and chapter pages)
 * `--latex_list_of_exercises=loe,toc,none` (LaTeX list of exercises, integrated into the table of contents, or no list)
 * `--latex_fancy_header` (chapter/section headings at top of pages, style depends on value of `--latex_section_headings`)
 * `--latex_section_headings=std,blue,bookblue,strongblue,gray,gray-wide` (standard LaTeX, blue headings, blue headings for books, strong blue headings, white in gray box, white in gray box that fills the page width)
 * `--latex_table_format=quote, center, footnotesize, tiny` (environment around tables)
 * `--latex_colored_table_rows=blue, gray, no` (color of every two lines in tables)
 * `--latex_table_row_sep=1.5` (increase the separation between table (and matrix) rows by a factor 1.5)
 * `--latex_todonotes` (inline comments typeset as ``bubbles'')
 * `--latex_double_spacing` (to ease hand-writing between the lines)
 * `--latex_line_numbers` (to ease references to sentences)
 * `--latex_labels_in_margin` (name of section, equation, citation labels in the margin)
 * `--latex_preamble=filename` (user-specific preamble)
 * `--latex_admon=mdfbox, graybox2, grayicon, yellowicon, paragraph, colors1, colors2`
 * `--latex_admon_color=0.34,0.02,0.8` (background color in admons)
 * `--latex_admon_envir_map=2` (code environment names in admons)
 * `--exercise_numbering=absolute, chapter`
 * `--latex_movie=media9, href, multimedia, movie15` (control typesetting of movies)
 * `--latex_movie_controls=on`
 * `--latex_external_movie_viewer` (for `movie15` package)
 * `--xelatex` (prepare for XeLaTeX)

The overall LaTeX style is much governed by `--latex_title_layout` and
`--latex_style`.  For the former, `titlepage` gives a separate title
page; `std` is just standard LaTeX handling of title, author, and
date; `doconce_heading` is a more modern heading,
`Springer_collection` is used with `--latex_style=Springer_lncse` for
an edited book; `beamer` is needed if the DocOnce document is to be
translated to LaTeX Beamer slides. For `--latex_style`, `std` gives
standard LaTeX behavior; `Springer_lncse` is for Springer's LNCSE book
series style (to be used with
`--latex_title_layout=Springer_collection` if the book is an edited
book); `Springer_llncs` is for Springer's Lecture Notes in Computer
Science series (normally an edited book that also requres
`--latex_title_layout=Springer_collection`); `Springer_lnup` for
Springer's Lecture Notes for Undergraduate Physics books,
`Springer_T2` for Springer's T2 book layout, `siamltex`, for the LaTeX
style of papers in standard SIAM journals (also used far beyond SIAM
journals and requires the stylefiles `siamltex.cls` and `siam10.clo`),
`siamltexmm` for the new multimedia SIAM journal style (requires
`siamltex.cls` and `siam10.clo`), `elsevier` for the style of papers
to be submitted to Elsevier journals (`--latex_elsevier_journal=` can
be used to set the journal name, and the style requires
`elsarticle.cls` and `elsarticle-num.bst`).

[^varioref]: Listing `varioref` in as package
automatically leads to references with page numbers, if the element referred to
is not on the same page. This is often very helpful, e.g., ``see
Figure 5.3 on page 67''.

idx{LaTeX syntax highlighting}

=== Syntax highlighting ===

The style of verbatim blocks of computer code is specified by
`--latex_code_style=X`, where `X` can be set in a very flexible way.
There are three main values, corresponding to three LaTeX tools
for verbatim type setting:

 * `vrb` for plain `Verbatim` style (`fancyvrb` LaTeX package)
 * `pyg` for the Pygments style (`mintex` LaTeX package)
 * `lst` for the Listings styles (`listingsutf8` LaTeX package)
 * `any` for any environment named `any` from any package

A separate "demo":
"http://hplgit.github.io/doconce/doc/pub/latexcode/demo.html" explains
the many possible settings of `X`. Popular choices are minimalistic
plain verbatim,

!bc
--latex_code_style=vrb
!ec
maybe with an added light blue background color,

!bc
--latex_code_style=vrb-blue1
!ec
or the default Pygments style,

!bc
--latex_code_style=pyg
!ec
or the Listings-based style with yellow background color

!bc
--latex_code_style=lst-yellow2
!ec
It is easy to specify different styles for different code environments, say
blue background with plain verbatim style for code but a special terminal
window for the `sys` environment:

!bc
"--latex_code_style=default:vrb-blue1@
sys:vrb[frame=lines,label=\\fbox{{\tiny Terminal}},
framesep=2.5mm,framerule=0.7pt,fontsize=\fontsize{9pt}{9pt}]"
!ec
(but no linebreaks, as here, they are for formatting this document only).

=== Drafts ===

During development of a manuscript, may prefer line numbers, double line spacing, frequent use of inline comments, and label names printed in the margin.
This is enabled by the options `--latex_line_numbers --latex_double_spacing --latex_todonotes --latex_labels_in_margin`. One may also (automatically) edit the
`final` argument in the `documentclass` heading to `draft` as this will
mark overful lines (hboxes).

=== Potential problems with ampersand ===

Another useful option for LaTeX documents is `--no_ampersand_quote`, which
prevents ampersands from getting a backskash. This is necessary if one
inserts native latex code for tables
inside `% if FORMAT in ('latex', 'pdflatex'):` (or similar `preprocess` syntax)
tests.

=== Part 2 of Step 1 (outdated) ===

In case you *did not* specify the `--latex_code_style=` option,
you must run `ptex2tex` (if you have installed the
Python ptex2tex package) to make a standard LaTeX file,

!bc sys
Terminal> ptex2tex mydoc
!ec
If you do not have `ptex2tex`, or do not bother to make the required
configuration file for `ptex2tex` (you may of course rely on the default
file), a (simplified) version of `ptex2tex`
that comes with DocOnce can be run:

!bc sys
Terminal> doconce ptex2tex mydoc
!ec

The `ptex2tex` command can set two preprocessor variables:

 * `PREAMBLE` to turn the LaTeX preamble on or off (i.e., complete document
   or document to be included elsewhere - and note that
   the preamble is only included
   if the document has a title, author, and date)
 * `MINTED` for inclusion of the minted package for typesetting of
   code with the Pygments tool (which requires `latex`
   or `pdflatex` to be run with the `-shell-escape` option); not used
   for `doconce ptex2tex` only in the `ptex2tex` program

If you are not satisfied with the generated DocOnce preamble, you can provide
your own preamble by adding the command-line option `--latex_preamble=myfile`.
In case `myfile` contains a documentclass definition, DocOnce assumes
that the file contains the *complete* preamble you want (not that all
the packages listed in the default preamble are required and must be
present in `myfile`). Otherwise, `myfile` is assumed to contain
*additional* LaTeX code to be added to the DocOnce default preamble.

The `ptex2tex` tool makes it possible to easily switch between many
different fancy formattings of computer code in LaTeX documents. After
any `!bc` command in the DocOnce source you can insert verbatim block
styles as defined in your `.ptex2tex.cfg` file, e.g., `!bc sys` for a
terminal session, where `sys` is set to a certain environment in
`.ptex2tex.cfg` (e.g., `CodeTerminal`).  There are about 40 styles to
choose from, and you can easily add new ones.

The `doconce ptex2tex` allows specifications
of code environments as well. Here is an example:
!bc sys
Terminal> doconce ptex2tex mydoc \
          "sys=\begin{quote}\begin{verbatim}@\end{verbatim}\end{quote}" \
          fpro=minted fcod=minted shcod=Verbatim envir=ans:nt
!ec
Note that `@` must be used to separate the begin and end LaTeX
commands, unless only the environment name is given (such as `minted`
above, which implies `\begin{minted}{fortran}` and `\end{minted}` as
begin and end for blocks inside `!bc fpro` and `!ec`).  Specifying
`envir=ans:nt` means that all other environments are typeset with the
`anslistings.sty` package, e.g., `!bc cppcod` will then result in
`\begin{c++}`. A predefined shortcut as in `shcod=Verbatim-0.85`
results in denser
vertical spacing (baselinestretch 0.85 in LaTeX terminology), and
`shcod=Verbatim-indent` implies indentation of the verbatim text.
Alternatively, one can provide all desired parameters
`\begin{Verbatim}` instruction using the syntax illustrated for
the `sys` environments above.

If no environments like `sys`, `fpro`, or the common
`envir` are defined on the command line, the plain `\begin{Verbatim}`
and `\end{Verbatim}` instructions are used.

===== LaTeX-PDF: Edit the LaTeX File (Step 2, Optional) =====
label{do2any:latex:compile2}

You can *edit* the `mydoc.tex` file to your needs.
For example, you may want to substitute `section` by `section*` to
avoid numbering of sections, you may want to insert linebreaks
(and perhaps space) in the title, etc. This can be automatically
edited with the aid of the `doconce replace` and `doconce subst`
commands. The former works with substituting text directly, while the
latter performs substitutions using regular expressions.
You will use `doconce replace` to edit `section{` to `section*{`:

!bc sys
Terminal> doconce replace 'section{' 'section*{' mydoc.tex
!ec
For fixing the line break of a title, you may pick a word in the
title, say "Using", and insert a break after than word. With
`doconce subst` this is easy employing regular expressions with
a group before "Using" and a group after:

!bc sys
Terminal> doconce subst 'title\{(.+)Using (.+)\}' \
          'title{\g<1> \\\\ [1.5mm] Using \g<2>' mydoc.tex
!ec
A lot of tailored fixes to the LaTeX document can be done by
an appropriate set of text replacements and regular expression
substitutions. You are anyway encourged to make a script for
generating PDF from the LaTeX file so the `doconce subst` or
`doconce replace` commands can be put inside the script.

===== LaTeX-PDF: Generate PDF (Step 3) =====
label{do2any:latex:compile3}

Compile `mydoc.tex` and create the PDF file, using `pdflatex`:

!bc sys
Terminal> pdflatex mydoc
Terminal> pdflatex mydoc
Terminal> makeindex mydoc   # if index
Terminal> bibtex mydoc      # if bibliography
Terminal> pdflatex mydoc
!ec

One can also compile `mydoc` the ``old way'' with `latex` and `dvipdf`.
Use `doconce format latex` in that case and proceed with `latex mydoc`.

If the minted style is used, `latex`, `pdflatex`, or `xelatex`
*must* be run with the
`-shell-escape` option:

!bc sys
Terminal> pdflatex -shell-escape mydoc
Terminal> pdflatex -shell-escape mydoc
Terminal> makeindex mydoc   # if index
Terminal> bibtex mydoc      # if bibliography
Terminal> pdflatex -shell-escape mydoc
!ec


===== XeLaTeX =====
label{do2any:xelatex}

idx{output format!XeLaTeX}
idx{XeLaTeX output}

XeLaTeX is an alternative to pdfLaTeX and is run in almost the
same way, except for the `--xelatex` flag to `doconce format`:

!bc
Terminal> doconce format pdflatex mydoc --xelatex \
          --latex_code_style=lst
Terminal> xelatex mydoc
!ec

===== From PDF to e-book formats =====
label{do2any:epub}

idx{ePub output}
idx{output format!ePub}

PDF (as generated from LaTeX above) can be read on most devices today.
However, for Kindle and other devices specialized for e-books you
need to convert to ePub or MOBI. The "Calibre": "http://calibre-ebook.com/"
program can produce epub, mobi, and other e-book formats from PDF,
see a "description": "http://www.dedoimedo.com/computers/latex-lyx-e-books.html". Unfortunately, Calibre cannot deal satisfactory with LaTeX math so
the usefulness for DocOnce writers is limited.
See Section ref{mathtext} for more information on how to generate ePub.

===== Microsoft Word or LibreOffice =====
label{do2any:MS:ooffice}

idx{output format!MS Word}
idx{output format!LibreOffice}
idx{output format!OpenOffice}

Transforming DocOnce files to Word format is best done with the aid
of `pandoc`. A standard way is to first generate the Markdown format
(`doconce format pandoc`) and then use `pandoc` to generate a `.docx`
file:

!bc sys
Terminal> doconce format pandoc mydoc
Terminal> pandoc -t docx -o mydoc.docx mydoc.md
!ec
The transformation works well for simple text files, but LaTeX mathematics
does not work.

======= Jupyter (IPython) Notebooks =======
label{do2any:ipynb}

idx{output format!notebook}
idx{IPython notebook}
idx{Jupyter notebook}
idx{notebook}

DocOnce can generate json files for the Jupyter Notebook:

!bc sys
Terminal> doconce format ipynb mydoc  # results in mydoc.ipynb
!ec

===== Hidden code blocks =====

It is no guarantee that the notebook can be executed. For example,
having the code

!bc pycod
print sys.version
!ec
will not execute unless `sys` is imported. While a book may show such
code and skip (potentially tedious) initializing statements, they must
be present in the notebook. To this end, use the `!bc *hid` environment
for hidden code. In the present example, we use `!bc pyhid` to specify
Python code that needs to be executed, but that should normally be
hidden (other formats, with the exception of certain interactive Sphinx
documents, will hide such code).

!bc
|bc pyhid
import sys
|ec
!ec
The notebook will feature the `import sys` statement in a cell prior to the
`print sys.version` cell, and the latter will work.

Similarly, if you import from your own modules, say `from mymod import hello`,
the `mymod.py` must be accessible for the notebook. Suppose this file
is in `src-test/mymod.py`. Then you need to add `src-test` to `sys.path`
for the import statement to work:

!bc
|bc pyhid
sys.path.append('src-test')
|ec
!ec

===== Displaying code as plain text instead of executable cells =====

Some code blocks may just be there for explanation and are not
meant to be executed. These can be marked by `!bc pycod-t` (or
`!bc Xcod-t` for any supported programming language `X`):

!bc
|bc pycod-t
if isinstance(myvar, float):
    raise TypeError('myvar must be array, not %s' % type(myvar))
|ec
!ec
The code segment above will then be typeset as verbatim text and not
an executable cell, and there is no need to worry about a missing
definition of `myvar` (which would cause problems in an executable cell).

Interactive sessions with the `pyshell` or `ipy` environment will
by default be broken up into many cells such that each output command
ends a cell. By executing the cells, the input *and* output from the
session is recovered. This is usually the behavior that is wanted, but
there is an option `--ipynb_split_pyshell=off` that can be used to
typeset the entire session with all input but no output in one cell
(`print` statements will lead to output, but plain dumping of
a variable will not lead to output like it does in a Python shell).

To have an interactive session typeset with input and output in plain
text, use the `-t` extension to the environment: `pyshell-t` and `ipy-t`.

===== Figures =====

As with HTML files, you need to ensure that the notebook has access to
figures and source code as requested.

Figures in notebooks can be typeset in various ways, specified by
the `--ipynb_figure=` option, with the following values:

 * `md`: plain Markdown syntax for a figure, with no possibility to adjust
   the size (default)
 * `imgtag`: `<img ...>` tag in HTML taking the specified width into account
 * `Image`: Python notebook cell with `Image` object

===== Movies =====

Typesetting of movies is specified by `--ipynb_movie=`, and valid options
are

 * `md`: raw HTML code with `iframe` tag - not relevant for the notebook
 * `HTML`: raw HTML code with `iframe` tag
    embedded in the `HTML` object from the notebook (default)
 * `HTML-YouTube`: as `HTML` but use an `IPython.display.YouTubeVideo`
   object to display YouTube videos
 * `ipynb`: use `IPython.display.YouTubeVideo` object for YouTube videos,
   and use an `HTML` object with `video` tag for local movies

===== Admonitions =====

Typesetting of admonition is rather primitive in notebooks.
We offer these different choices, set by the
option `--ipynb_admon=`:

 * `quote`: typeset admon as Markdown quote (special font and gray vertical bar on
   the left)
 * `paragraph`: typeset admon as a plain paragraph with a heading if any (default)
 * `hrule`: use a horozontal rule to surround the heading and the text

Note that quotes in `!bc quote` environments
are always typeset as Markdown quotes.

===== References to an External Textbook =====

Sometimes one wants to refer to equations and sections in an external
LaTeX book where a `book.aux` file is available. The references in the
notebook to the LaTeX book can then be hardcoded from the `book.aux` file
with this construction:

!bc sys
Terminal> doconce format ipynb mydoc \
          --replace_ref_by_latex_auxno=book.aux
!ec

===== Conversion from Notebook Back to DocOnce =====

A notebook generated from DocOnce can be converted back to DocOnce format
again, even after being annotated in a web browser. Here is a trivial
example:

!bc do
Here is a code:

|bc pypro
a = 1
b = 2
print a + b
|ec
!ec
We translate this DocOnce document to a notebook:

!bc sys
Terminal> doconce format ipynb mydoc
!ec
We load `mydoc.ipynb` into the notebook application and add a code cell

!bc pycod
print "Hello, World!"
!ec
before the original code cell. After executing the cells we download
the new notebook as the file `mydoc2.ipynb`. We can then generate
the corresponding DocOnce document `mydoc2.do.txt`:

!bc sys
Terminal> ipynb2doconce mydoc2.ipynb
!ec

Title, author, and other information in DocOnce that does not have
a corresponding syntax in the notebook are stored as special comments
in the generated `.ipynb` file so that DocOnce can retrieve this information
when running the `doconce ipynb2doconce` conversion command.

======= Matlab Notebooks =======
label{do2any:matlabnb}

idx{output format!notebook}
idx{Matlab notebook}
idx{Matlab publish format (notebook)}
idx{notebook}

The Matlab *publish* format is aimed at notebooks, but the markup is
quite primitive, so only a small subset of DocOnce markup can translate
successfully to the Matlab publish format. However, if you write within
that subset, it is easy to create notebooks in DocOnce that can translate
both to Python and Matlab (use preprocessor directives or Mako functions
to include Matlab or Python code, depending on the output format).

The Matlab publish format is called `matlabnb`:

!bc sys
Terminal> doconce format matlabnb mydoc
!ec

The `--replace_ref_by_latex_auxno=` option for referring to equations
and sections in a textbook, as explained at the end of the section on
Jupyter/IPython notebooks, also works with Matlab notebooks (and for
any other output format):

!bc sys
Terminal> doconce format matlabnb mydoc \
          --replace_ref_by_latex_auxno=book.aux
!ec


======= Plain ASCII Text =======
label{do2any:ascii}

idx{output format!ASCII}
idx{output format!plain untagged text}
idx{ASCII output}
idx{plain untagged text output}

We can go from DocOnce "back to" plain untagged text suitable for viewing
in terminal windows, inclusion in email text, or for insertion in
computer source code:
!bc sys
Terminal> doconce format plain mydoc.do.txt  # results in mydoc.txt
!ec

======= reStructuredText =======
label{do2any:rst}

idx{output format!reStructuredText}
idx{reStructuredText output}

Going from DocOnce to reStructuredText gives a lot of possibilities to
go to other formats. First we filter the DocOnce text to a
reStructuredText file `mydoc.rst`:
!bc sys
Terminal> doconce format rst mydoc.do.txt
!ec
We may now produce various other formats:
!bc sys
Terminal> rst2html.py  mydoc.rst > mydoc.html # html
Terminal> rst2latex.py mydoc.rst > mydoc.tex  # latex
Terminal> rst2xml.py   mydoc.rst > mydoc.xml  # XML
Terminal> rst2odt.py   mydoc.rst > mydoc.odt  # OpenOffice
!ec

The OpenOffice file `mydoc.odt` can be loaded into OpenOffice and
saved in, among other things, the RTF format or the Microsoft Word format.
However, it is more convenient to use the program `unoconv`
to convert between the many formats OpenOffice supports *on the command line*.
Run
!bc sys
Terminal> unoconv --show
!ec
to see all the formats that are supported.
For example, the following commands take
`mydoc.odt` to Microsoft Office Open XML format,
classic MS Word format, and PDF:
!bc sys
Terminal> unoconv -f ooxml mydoc.odt
Terminal> unoconv -f doc mydoc.odt
Terminal> unoconv -f pdf mydoc.odt
!ec

__Remark about Mathematical Typesetting.__
At the time of this writing, there is no easy way to go from DocOnce
and LaTeX mathematics to reST and further to OpenOffice and the
"MS Word world". Mathematics is only fully supported by `latex` as
output and to a wide extent also supported by the `sphinx` output format.
Some links for going from LaTeX to Word are listed below.

 * URL:"http://ubuntuforums.org/showthread.php?t=1033441"
 * URL:"http://tug.org/utilities/texconv/textopc.html"
 * URL:"http://nileshbansal.blogspot.com/2007/12/latex-to-openofficeword.html"



======= Sphinx =======
label{do2any:sphinx}

idx{output format!Sphinx}
idx{Sphinx output}

===== The Basic Steps =====

Sphinx documents demand quite some steps in their creation. We have automated
most of the steps through the `doconce sphinx_dir` command:

!bc sys
Terminal> doconce sphinx_dir version=1.0 dirname=sphinxdir \
          theme=sometheme mydoc short_title="short title" mydoc
!ec
The author, title, and copyright information needed by Sphinx is
taken from the DocOnce file `mydoc.do.txt`.
By default, `version` is 1.0 and
`dirname` is `sphinx-rootdir`. The `theme`
keyword is used to set the theme for design of HTML output from
Sphinx (the default theme is `classic`).

There are more options for the `sphinx_dir` command: `--runestone`
for Runestone Interactive books, `toc_depth=` for setting the depth
of the table of contents, `intersphinx` for allowing the document to
link automatically to other Sphinx documents, `conf.py=` for specifying
a tailored `conf.py` file, `logo=` and `favicon=` for specifying logo
and favicon files.

One often just runs the simple command
!bc sys
Terminal> doconce sphinx_dir mydoc
!ec
which creates the Sphinx directory `sphinx-rootdir` with
relevant files.

The `doconce sphinx_dir` command generates a script
`automake_sphinx.py` for compiling the Sphinx document into an HTML
document.  Run

!bc sys
Terminal> python automake_sphinx.py
!ec
As the output also tells, you can see the Sphinx HTML version of the document
by running

!bc sys
Terminal> google-chrome sphinx-rootdir/_build/html/index.html
!ec
or loading the `index.html` file manually into your favorite web browser.

If you cycle through editing the DocOnce file and watching the
HTML output, you should observe that `automake_sphinx.py` does not
recompile the DocOnce file if the Sphinx `.rst` version already exists.
In each edit-and-watch cycle do

!bc sys
Terminal> rm mydoc.rst; python automake_sphinx.py
!ec

!bnotice Tip
If you are new
to Sphinx and end up producing quite some Sphinx documents, you are encouraged
to read the Sphinx documentation and study the `automake_sphinx.py`
file. Maybe you want to do things differently.
!enotice

The following paragraphs describes the many possibilities for steering
the Sphinx output.

===== Links =====

The `automake_sphinx.py` script copies directories named `fig*`
over to the Sphinx directory so that figures are accessible
in the Sphinx compilation.  It also examines `MOVIE:` and `FIGURE:`
commands in the DocOnce file to find other image files and copies
these too. I strongly recommend to put files
to which there are local links (not `http:` or `file:` URLs) in
a directory named `_static`. The `automake_sphinx.py` copies
`_static*` to the Sphinx directory, which guarantees that the links
to the local files will work in the Sphinx document.

There is a utility `doconce sphinxfix_localURLs` for checking links to
local files and moving the files to `_static` and changing the links
accordingly. For example, a link to `dir1/dir2/myfile.txt` is changed
to `_static/myfile.txt` and `myfile.txt` is copied to `_static`.
However, I recommend instead that you manually copy
files to `_static` when you want to link to them, or let your
script which compiles the DocOnce document do it automatically.

idx{open links in new window}

One can get all links to open in a new window by adding the
option `--html_links_in_new_window` to the `doconce format` command.


===== Themes =====

idx{Sphinx styles}
idx{Sphinx themes}

DocOnce comes with a rich collection of HTML themes for Sphinx documents,
much larger than what is found in the standard Sphinx distribution.
Additional themes include
`agni`,
`alabaster`,
`basic`,
`basicstrap`,
`bootstrap`,
`cloud`,
`epub`,
`fenics`,
`fenics_minimal`,
`flask`,
`haiku`,
`jal`,
`pylons`,
`pyramid`,
`redcloud`,
`scipy_lectures`,
`scrolls`,
`slim-agogo`,
`sphinx_rtd_theme`,
and
`vlinux-theme`.
Some of the themes come with basic Sphinx, while others must be installed
separately, see the `bundled/README_sphinx_themes.do.txt` file in
the DocOnce source code tree for installation instructions.


idx{`conf.py` (Sphinx configuration)}

The
`doconce sphinx_dir` insert lots of extra code in the `conf.py`
file to enable easy specification of information and,
in particular,customization of themes.
For example, modules are loaded for the additional themes that
come with DocOnce, code is inserted to allow customization of
the look and feel of themes, etc.

=== Using a Your Own Configuration File ===

The `conf.py` file is a good starting point for fine-tuning your
favorite theme, and your own `myconf.py` file can later be supplied
and used when running `doconce sphinx_dir`: simply add the
command-line option `conf.py=myconf.py`. If you leave the `project`
and `copyright` variables as empty strings in your own `myconf.py`
file, DocOnce will automatically edit a copy (`conf.py`) of
`myconf.py` in the sphinx root directory so that `project` becomes the
title of the DocOnce source file, and `copyright` is based on the
author or copyright information in the source file. Other variables in
`myconf.py` depending on title, author, and copyright information will
also be edited. In this way, you can have your tailored `conf.py`
file, and be sure that it is always compatible with title, author, and
copyright information in the underlying DocOnce source.

If a short title is desired, use the `short_title=` option as part
of the `doconce sphinx_dir` command. This will propagate the short
title to your tailored `conf.py` file regardless of what the short
title in that file is.

It is recommended to leave the variables `latex_documents`, `man_pages`,
and `texinfo_documents` as empty lists: `[]` in a tailored `conf.py` file.

!bnotice Tip: Error messages from `conf.py`
When you have edited a `conf.py` file and supplied it as part of
a `doconce sphinx_dir` command through the `conf.py=myconf.py` option, it is
a danger that `python automake_sphinx.py` will abort with an error
message because of a problem with your configuration file.
Note that the error message refers to a line in the `conf.py` in the Sphinx
root directory (`sphinx-rootdir` by default) and *not* the configuration
file `myconf.py` you created yourself (so make sure you
search in `sphinx-rootdir/conf.py` for the error). If the error comes
from some wrong manual editing, make sure you correct the error in
`myconf.py`.
!enotice

=== Compiling Multiple Themes ===

A script
`make-themes.sh` can make HTML documents with one or more themes.
For example,
to realize the themes `fenics`, `pyramid`, and `pylon` one writes

!bc sys
Terminal> ./make-themes.sh fenics pyramid pylon
!ec
The resulting directories with HTML documents are `_build/html_fenics`
and `_build/html_pyramid`, respectively. Without arguments,
`make-themes.sh` makes all available themes (!). With `make-themes.sh`
it is easy to check out various themes to find the one that is most
attractive for your document.

You may supply your own theme and avoid copying all the themes
that come with DocOnce into the Sphinx directory. Just specify
`theme_dir=path` on the command line, where `path` is the relative
path to the directory containing the Sphinx theme. You must also
specify a configure file by `conf.py=path`, where `path` is the
relative path to your `conf.py` file.

=== Example ===

Say you like the `scipy_lectures` theme, but you want
a table of contents to appear *to the right*, much in the same style
as in the `default` or `classic` themes
(where the table of contents is to the left).
You can then run `doconce sphinx_dir`, invoke a text editor with the
`conf.py` file, find the line `html_theme == 'scipy_lectures'`,
edit the following `nosidebar` to `false` and `rightsidebar` to `true`.
Alternatively, you may write a little script using `doconce replace`
to replace a portion of text in `conf.py` by a new one:

!bc shpro
doconce replace "elif html_theme == 'scipy_lectures':
    html_theme_options = {
        'nosidebar': 'true',
        'rightsidebar': 'false',
        'sidebarbgcolor': '#f2f2f2',
        'sidebartextcolor': '#20435c',
        'sidebarlinkcolor': '#20435c',
        'footerbgcolor': '#000000',
        'relbarbgcolor': '#000000',
    }" "elif html_theme == 'scipy_lectures':
    html_theme_options = {
        'nosidebar': 'false',
        'rightsidebar': 'true',
        'sidebarbgcolor': '#f2f2f2',
        'sidebartextcolor': '#20435c',
        'sidebarlinkcolor': '#20435c',
        'footerbgcolor': '#000000',
        'relbarbgcolor': '#000000',
    }" conf.py
!ec
Obviously, we could also have changed colors in the edit above.
The final alternative is to save the edited `conf.py` file somewhere
and reuse it the next time `doconce sphinx_dir` is run

!bc sys
doconce sphinx_dir theme=scipy_lectures \
                   conf.py=../some/path/conf.py mydoc
!ec

===== RunestoneInteractive books =====

The `doconce format sphinx` command accepts an option `--runestone`
for generating "RunestoneInteractive": "http://runestoneinteractive.org"
books (which build on Sphinx).
You must run the generated `automake_sphinx.py` also with a `--runestone`
option to generate these type of documents.

idx{Sphinx directory}

===== The manual Sphinx procedure =====

If it is not desirable to use the autogenerated scripts explained
above, here is the complete manual procedure of generating a
Sphinx document from a file `mydoc.do.txt`.

__Step 1.__ Translate DocOnce into the Sphinx format:
!bc sys
Terminal> doconce format sphinx mydoc
!ec

__Step 2.__ Create a Sphinx root directory
either manually or by using the interactive `sphinx-quickstart`
program. Here is a scripted version of the steps with the latter:
!bc sys
mkdir sphinx-rootdir
sphinx-quickstart <<EOF
sphinx-rootdir
n
_
Name of My Sphinx Document
Author
version
version
.rst
index
n
y
n
n
n
n
y
n
n
y
y
y
EOF
!ec
The autogenerated `conf.py` file
may need some edits if you want to specific layout (Sphinx themes)
of HTML pages. The `doconce sphinx_dir` generator makes an extended `conv.py`
file where, among other things, several useful Sphinx extensions
are included.


__Step 3.__ Copy the `mydoc.rst` file to the Sphinx root directory:
!bc sys
Terminal> cp mydoc.rst sphinx-rootdir
!ec
If you have figures in your document, the relative paths to those will
be invalid when you work with `mydoc.rst` in the `sphinx-rootdir`
directory. Either edit `mydoc.rst` so that figure file paths are correct,
or simply copy your figure directories to `sphinx-rootdir`.
Links to local files in `mydoc.rst` must be modified to links to
files in the `_static` directory, see comment above.

__Step 4.__ Edit the generated `index.rst` file so that `mydoc.rst`
is included, i.e., add `mydoc` to the `toctree` section so that it becomes
!bc
.. toctree::
   :maxdepth: 2

   mydoc
!ec
(The spaces before `mydoc` are important!)

__Step 5.__ Generate, for instance, an HTML version of the Sphinx source:
!bc sys
make clean   # remove old versions
make html
!ec

Sphinx can generate a range of different formats:
standalone HTML, HTML in separate directories with `index.html` files,
a large single HTML file, JSON files, various help files (the qthelp, HTML,
and Devhelp projects), epub, LaTeX, PDF (via LaTeX), pure text, man pages,
and Texinfo files.

__Step 6.__ View the result:
!bc sys
Terminal> firefox _build/html/index.html
!ec

Note that verbatim code blocks can be typeset in a variety of ways
depending the argument that follows `!bc`: `cod` gives Python
(`code-block:: python` in Sphinx syntax) and `cppcod` gives C++, but
all such arguments can be customized both for Sphinx and LaTeX output.


======= Wiki Formats =======
label{do2any:wiki}

idx{output format!MediaWiki}
idx{output format!Creole wiki}
idx{output format!Google wiki}
idx{MediaWiki output}
idx{Google wiki output}
idx{Creole wiki output}
idx{wiki output}

There are many different wiki formats, but DocOnce only supports three:
"Googlecode wiki": "http://code.google.com/p/support/wiki/WikiSyntax",
"MediaWiki": "http://www.mediawiki.org/wiki/Help:Formatting", and
"Creole Wiki": "http://www.wikicreole.org/wiki/Creole1.0".
These formats are called
`gwiki`, `mwiki`, and `cwiki`, respectively.
Transformation from DocOnce to these formats is done by
!bc sys
Terminal> doconce format gwiki mydoc.do.txt
Terminal> doconce format mwiki mydoc.do.txt
Terminal> doconce format cwiki mydoc.do.txt
!ec

The produced MediaWiki can be tested in the "sandbox of
wikibooks.org": "http://en.wikibooks.org/wiki/Sandbox". The format
works well with Wikipedia, Wikibooks, and
"ShoutWiki": "http://doconcedemo.shoutwiki.com/wiki/DocOnce_demo_page",
but not always well elsewhere
(see "this example":
"http://doconcedemo.jumpwiki.com/wiki/First_demo").

Large MediaWiki documents can be made with the
"Book creator":
"http://en.wikipedia.org/w/index.php?title=Special:Book&bookcmd=book_creator".
From the MediaWiki format one can go to other formats with aid
of "mwlib": "http://pediapress.com/code/". This means that one can
easily use DocOnce to write "Wikibooks": "http://en.wikibooks.org"
and publish these in PDF and MediaWiki format, while
at the same time, the book can also be published as a
standard LaTeX book, a Sphinx web document, or a collection of HTML files.



The Googlecode wiki document, `mydoc.gwiki`, is most conveniently stored
in a directory which is a clone of the wiki part of the Googlecode project.
This is far easier than copying and pasting the entire text into the
wiki editor in a web browser. Note that Google decided to close down its
Googlecode service in 2015.

When the DocOnce file contains figures, each figure filename must in
the `.gwiki` file be replaced by a URL where the figure is
available. There are instructions in the file for doing this. Usually,
one performs this substitution automatically (see next section).

======= Google Docs =======
label{do2any:google:docs}

idx{Google docs output}

Google Docs are normally made online in the interactive editor. However,
you may upload a DocOnce document to Google Docs. This requires transforming
the DocOnce document to one of the accepted formats for Google Docs:

 * OpenOffice: `doconce format rst` and then run
   `rst2odt` (or `rst2odt.py`). Upload the `.odt` file, click
   *Open...* in Google Drive and choose *Google Docs* as viewer.
 * MS Word: `doconce format pandoc` and then run `pandoc` to
   produce a `.docx` file that can be uploaded to Google Drive
   and opened in Google Docs.
 * RTF: `doconce format pandoc` and then run `pandoc` to produce
   a `.rtf` file that can be uploaded to Google Drive and opened.
   Another possibility is to run `doconce format latex` and
   then "latex2rtf": "http://sourceforge.net/projects/latex2rtf"
   (the support of mathematics has gotten worse).
 * Plain text: `doconce format plain`. Upload the `.txt` file
   to Google Drive and open in Google Docs.
 * HTML: `doconce format html`. Upload the `.html` file and
   open in Google Docs. Complicated HTML files can be misinterpreted
   by Google Docs.

This is not yet much tested. It remains to see how code becomes in
Google Docs. Support for mathematics is probably impossible until
Google Docs can import LaTeX files, but LaTeX mathematics can be embedded
in Google Docs and the "googledoc2latex": "http://code.google.com/p/googledoc2latex" script can convert a Google document to LaTeX.

======= Options for the `doconce` commands =======

===== `doconce format` command-line options =====

idx{`doconce format` options}
idx{command-line options!doconce format}

The transformation of a DocOnce source to various format is done with
the `doconce format` command, which has *a lot* of command-line options.
These are printed out by `doconce format --help`. The output is listed
here for convenience.

@@@OSCMD doconce format --help
