md2html


md2html


MD2Html ("MarkDown to HTML") is a utility that transforms Markdown files to HTML, after expanding all Rexx fenced code blocks.

Md2html operates in two modes: when the argument is a file, it converts that single file to HTML; when the argument is a directory, it converts all .md files in it (and its subdirectories) to HTML.

Usage

[rexx] md2html [options] filename [destination]
[rexx] md2html [options] source [destination]

In single-file mode, filename is a file containing Markdown. If the file is not found and does not already have an extension, .md is appended automatically. The output HTML file is placed in the destination directory, which defaults to the current directory.

In batch mode, source and destination should be existing directories. Destination defaults to the current directory.

When called without arguments, display help information and exit.

Options


-h, --help Display help and exit
-c cssbase, --css cssbase   Where to locate the CSS files
--continue Continue when a fenced code block is in error and, in batch mode, when a file fails
--default "attributes" Default attributes for all code blocks
-it, --itrace Print internal traceback on error
-j jsbase, --js jsbase Where to locate the JavaScript files
-p path, --path path First path to search for default.md2html and md2html.custom.rex
--plain The document alone, with its styles: no page around it
--style name|file D efault highlighting style


With --plain, the HTML file is the document alone: its text, the Markdown style sheet and the highlighting styles it uses, and nothing else. There is no page around it (no Bootstrap layout, header, sidebar or footer), no style chooser, and default.md2html and md2html.custom.rex are not used for the page. This is the way to look at a README, or any Markdown file, in a browser.

When cssbase is not specified, it defaults to the filesystem location of a first-level css subdirectory of the destination directory, if one exists; the same is true, respectively, of jsbase and the js subdirectory.

Prerequisites

A working installation of Pandoc is required.

YAML front matter

Md2html reads RexxPub options from the YAML front matter block of each Markdown file. Options are placed under the rexxpub: key, separate from Pandoc's standard metadata:

---
bibliography: references.bib
lang: en
rexxpub:
  section-numbers: 3
  number-figures: true
  style: light
---

The supported options under rexxpub: include style, section-numbers, and number-figures (which accepts 0, 1, true, or false, case-insensitive), as well as listings: and figures: sub-tables for caption and frame customization. The Pandoc top-level metadata fields lang (HTML language) and highlight-style are also recognized. With a bibliography: (or references:) in the front matter, the citations are processed by Pandoc's citeproc, in the rexxpub style (csl/rexxpub.csl) unless csl: names another.

The highlighting style can also be given on the command line, with --style name, as in md2pdf and md2epub. The command line wins over the YAML style value, which wins over the default (dark). The style set this way is the style of the whole page: code blocks, Rexx mentions in the prose, and the option pre-selected in the page's style chooser. A name that is not one of the shipped styles is an error. In the YAML, an unknown style is ignored with a warning, and the default applies. style: (and --style) can also be a stylesheet of the author's own, a file: see the YAML front matter documentation.

This is not the same as --default "style=name". --default writes its attributes into every code block, as if the author had typed them on each fence, so style= there pins every block to that style: the style chooser leaves those blocks alone, and the Rexx mentions in the prose still follow the document style. To set the style of the document, use --style.

All other options are set exclusively in the YAML front matter.

See the YAML front matter documentation for the full specification.

Tables

A table is balanced: its columns are as wide as what they hold, as the browser lays them out, and not as the dashes under its header said (|---|---|---| was a third each, whatever the columns held). It has a line above, a line below and a line under its head, as in the PDF.

On the ::: that holds it, a table takes cols=1:4 (the proportions of its columns, as in md2slides and md2latex), .grid (a line around every cell), .stripes (every second row of the body on a light grey) and stripes=#E8F0FF (on that colour):

::: {.table .grid stripes=#E8F0FF}
| Precedence | Operators | Description |
|---|---|---|
| 1 | `~ ~~` | Message, cascading message |
| 2 | `+ - \` | Prefix plus, prefix minus, prefix not |
:::

For the whole document, in the YAML: rexxpub: tables: grid: yes and stripes: yes (or a colour); .nogrid and .nostripes undo them for one table. The same holds in the CGI, md2pdf and md2epub; the look is in css/tables.css.

scale=0.85 on any ::: (a table's too) or [span], as in md2slides and md2latex, sets its text and its code that much smaller (or bigger, above 1); scales multiply when they nest.

blanks=all (or blanks=data, or {.blanks}) on program output or on code that is not Rexx, a block or `in the text`, draws every blank as an open box, as the highlighter does for Rexx; the blanks are still there to be copied. Such a block loses the highlighting of its language. The same holds in the CGI, md2pdf and md2epub.

source=FILE on such a block (a program's output, say) puts the lines of FILE, relative to the document, in the block, as for Rexx; without the file, the block keeps its own text.

spot= on a listing, on program output or on any other block marks lines and texts as md2slides does, all at once (there are no steps on a page): ```{.output spot="err:3 msg:[NOVALUE] ink"} turns line 3 and the word NOVALUE to the colour of a pen; wash (the default), box, ring, bold and pen= are the other words (see the fenced code documentation). A block that is not Rexx loses the highlighting of its language when it has marks.

background=, border=solid|dashed|dotted|none, border-width= and border-color= on any fence, Rexx's too, give the block a ground and a frame; rexxpub: blocks: in the YAML does it for every block, or for the blocks of code or of output, or (since v366) of one language (see the YAML front matter). The look is in css/tables.css (div.rx-dress, .rx-spot). The same holds in the CGI, md2pdf and md2epub.

[USE]{.kw} is a keyword mention, `USE`{.rexx keyword}, and rexxpub: mentions: background: none in the YAML sets the mentions in the colours of the style, on no ground (span.rx-bare). The colours of pen=, background= and border-color= are #RRGGBB, #RGB or one of the 148 names of CSS.

Program operation

In both modes, the processing of each Markdown file follows the same pipeline. The utility first expands all the Rexx fenced code blocks, using the Rexx Highlighter, then runs Pandoc against the result to convert it to HTML, and finally calls a set of routines found in md2html.custom.rex, which provide the constant or almost constant parts of an HTML page, like headers, footers, menus or sidebars.

In single-file mode, md2html changes to the directory containing the file before processing, so that Pandoc can resolve relative paths for resources such as bibliographies.

In batch mode, md2html uses SysFileTree to recursively list all the Markdown (.md) files found in the source directory and processes them in turn. The first file that fails stops the run; with --continue, the remaining files are processed as well. At the end, a summary reports the number of files processed and the number of failures, and md2html returns 1 if any file failed.

                               md2html workflow
                               ────────────────

                        ╔═════════════════════════════╗
                        ║                             ║
                        ║ (1) Markdown source file    ║
                        ║                             ║
                        ╚═════════════════════════════╝
                                       │
                                       │ ◀──── The Rexx Highlighter (FencedCode.cls)
                                       │
                                       ▼
                        ╔═════════════════════════════╗
                        ║                             ║
                        ║ (2) Markdown +              ║
                        ║     Rexx code expanded      ║
                        ║                             ║
                        ╚═════════════════════════════╝
                                       │
                                       │ ◀──── pandoc
                                       │
                                       ▼
                        ╔═════════════════════════════╗
                        ║                             ║
                        ║ (3) HTML code (inner part   ║
                        ║     of the page)            ║
                        ║                             ║
                        ╚═════════════════════════════╝
                                       │
                                       │ ◀──── default.md2html + md2html.custom.rex
                                       │
                                       ▼
                        ╔═════════════════════════════╗
                        ║                             ║
                        ║ (4) Final HTML + CSS code   ║
                        ║                             ║
                        ╚═════════════════════════════╝

A sample md2html.custom.rex is distributed with the Rexx Parser. To allow for maximum customization, the md2html utility looks for md2html.custom.rex first in the path specified by the -p or --path options, if present, then in the current directory, then in the destination directory, then (in batch mode) in the source directory, and finally using the standard Rexx search order for external files.

Pandoc is used to convert the source Markdown content into the inner part of the HTML file. The structure of the whole HTML page is defined in a separate template file called default.md2html, which is searched in the same order as md2html.custom.rex. Md2html looks for this file and reads a line at a time. Lines starting with "--" (in the first column) are considered to be comments and are completely ignored. Other lines will be copied to the target file as-is, and some special markers will be expanded by md2html. A sample default.md2html is distributed with the Rexx Parser; it can be found in the bin subdirectory.

Complete list of markers accepted in default.md2html

The following markers are recognized in the template file (they should appear alone on a line, in lowercase):

%title%
Replaced by the contents of the first <h1> header found in the file.
%header%
Calls the Md2html.Header routine.
%contentheader%
Calls the Md2html.ContentHeader routine.
%contents%
Replaced by the HTML output generated by Pandoc.
%footer%
Calls the Md2html.Footer routine.
%sidebar%
Calls the Md2html.Sidebar routine.
%printstyle%
If a print style CSS file exists for the current file (see below), inserts a link to it.
%filenamespecificstyle%
If a filename-specific style has been defined (see below), inserts a link to it.
%usedStyles%
Replaced by <link> elements for every Rexx highlighting CSS style used in the fenced code blocks of the file.
%cssbase% and %jsbase%
Replaced early during template loading with the values of the corresponding options.
%SectionNumbers%
Replaced by the CSS class for section numbering (e.g. section-numbers-3). The default depth depends on the filename: 3 for article (and others), 2 for book, 0 for slides. Can be overridden in the YAML front matter.
%NumberFigures%
Replaced by number-figures when figure/listing numbering is active (the default), or by an empty string when disabled in the YAML front matter.
%printFigures%
Inserts a <script> tag loading numberFigures.js from the JavaScript base directory. This script processes data-caption attributes on code blocks and numbers figures and listings.

Structure of the md2html.custom.rex file

The md2html.custom.rex routine is called just before the moment when the individual Markdown files are processed. The custom file may contain a series of public routines called md2html.name. The conceptual page model is as follows (all parts except the page contents are optional):

--      +-------------------------------------------------------------+
--      |              page header, including the title               |
--      +-------------------------------------------------------------+
--      |                content header               |   side bar    |
--      +---------------------------------------------+               |
--      |                                             |               |
--      |                  contents                   |               |
--      |                                             |               |
--      +-------------------------------------------------------------+
--      |                          page footer                        |
--      +-------------------------------------------------------------+

The md2html processor attempts a call to each of these routines in the following contexts:

Md2html.Exception
Called every time a file is processed. Arg(1) is the filename (including the extension). Should return 1 when a file should not be processed, and 0 otherwise.
Md2html.Extension
Returns the extension for the HTML files generated by md2html (default is "html"). In the default implementation, returns the value of the package-local .Extension environment variable.
Md2html.Header
Called whenever a %header% marker is found in the default.md2html file.
Md2html.ContentHeader
Called whenever a %contentheader% marker is found in the default.md2html file.
Md2html.Footer
Called whenever a %footer% marker is found in the default.md2html file.
Md2html.SideBar
Called whenever a %sidebar% marker is found in the default.md2html file.
Md2html.TranslatedName
Called every time a file is processed. Arg(1) is the filename (including the extension). Returns the translated filename, or .Nil when no translation is necessary. In the default implementation, returns the value returned by the package-local .TranslateFilename[Arg(1)].
Md2html.FilenameSpecificStyle
Called every time a file is processed. Arg(1) is the filename (including the extension). Returns the name of a filename-specific CSS style (without the .css extension), or .Nil when no specific style is needed.

CSS and JavaScript

Most HTML pages use a combination of CSS and JavaScript. You can specify their location by using the -c, --css, -j and --js options. If the destination directory contains first-level css or js directories and these options have not been specified, md2html will use these directories, using the file:/// scheme, which can be useful for debugging purposes and on local installations.

Special print styles, like running headers and running footers, can be specified by storing in the same directory a file with the same filename as the Markdown file and with an additional .css extension. For example, a print style for readme.md should be stored in readme.md.css.

A sample run (on Windows)

Open a command window, locate the Rexx Parser directory, and run setenv. Now create a test directory in another drive, say C:\Test. Change to the C: drive, and cd \Test. Create a css directory under C:\Test, and copy the following files from the css subdirectory of the Rexx Parser distribution: markdown.css, rexx-dark.css and rexx-light.css. Now, run

md2html directory

where directory is the Rexx Parser installation directory.

After a few seconds, you will have a complete, working, translation of the whole Markdown tree under C:\Test.

Please note that, since this is a sample demo run, header, footer, and sidebar links point to https://rexx.epbcn.com/.