Rexx Fenced code blocks: the RexxPub attributes


Rexx Fenced code blocks: the RexxPub attributes


The FencedCode routine, which highlights the Rexx fenced code blocks of a Markdown or HTML file, and the fencedcode utility, which runs it on a file, are part of the parser, and come with ooRexx. The format of a fenced code block and the attributes that the highlighter understands (style, .numberLines, startFrom, patch, source, the variants of Rexx...) are described in the chapter Utilities and Samples of the book.

This page describes the attributes that only RexxPub uses: background and border, caption, program and spot. FencedCode writes them into the HTML (as data- attributes); RexxPub (the md2* programs and the CGI) turns them into what you see. Two features of FencedCode use parts of RexxPub, and are available only when RexxPub is installed: the code in the cells of grid tables (GridTables.cls; without it, a grid table is left as it is), and the beats drawn at once in the page (STATICSPOTS, Spots.cls; without it, asking for them is an error).

Optional attributes

Attributes are blank-separated booleans, which are usually preceded by a dot, or name=value pairs. When a value contains blanks, it has to be enclosed in single or double quotes.

A Rexx fence is caseless, as Rexx is: ~~~REXX is ~~~rexx, a boolean may be written in any case (.numberlines, .NUMBERLINES and .numberLines are the same, and so are blanks and BLANKS), and so may the name in a name=value pair. A dash is as good as a capital: start-from=97 is startFrom=97, as .number-lines is .numberLines. A name=value pair that FencedCode does not know stops the build, and the message says the line of the block and the file it is in.

Only a Rexx fence is caseless: it is read by the Rexx Parser. Everything else between braces (other fences, ::: blocks, headings, spans, links, pictures) is read by Pandoc, by the style sheets and by the browser, and keeps their rules: names are case-sensitive there. When a class or a name is one of ours but for its case or its dashes ({.output .numberlines} on an output block), every md2* program says so, with its line, and what it probably meant (.numberLines).

~~~rexx {.boolean1 name1=value1 .boolean2 name2="long value" ...}

The attributes of RexxPub are:

background=colour, border=line, border-width=length, border-color=colour

Give the block a ground and a frame of its own (md2html, the CGI, md2pdf, md2epub, md2latex and, since v359, md2slides):

~~~rexx {background=#F2F6FA border=dashed border-color=#5070A0}
  ...
~~~

background= is a colour, or none; border= is solid, dashed, dotted or none; border-width= is a length (0.5pt, 1px, 0.2mm; 1px by default) and border-color= a colour (gray by default). A colour is #RRGGBB, #RGB or one of the 148 names of CSS (gray, navy, teal, maroon...). A border-width= or a border-color= alone means a solid frame. The frame goes round the whole block, line numbers included.

The same attributes work on any other fence (```{.output}, ```python...), and rexxpub: blocks: in the YAML front matter gives every block, or every block of code, or of output, or of one language, its ground and its frame (see the YAML front matter); what a fence says wins. They are not read here: they travel to the HTML as data-rx-background, data-rx-border... on the block's wrapper, and each pipeline draws them.

caption="text"

Add a caption to the code block. The caption text is emitted as a data-caption attribute on the outer <div>, and numberFigures.js converts it to a visible <figcaption> at render time. When figure numbering is active (the default in all pipelines), the caption is prefixed with "Listing N." following the LaTeX convention. Listing captions are placed above the code block, and figure captions (for Pandoc images) below the image.

~~~rexx {caption="A sample listing"}
Say "Hello, world!"
~~~

produces:

Say "Hello, world!"

program=name

Marks this fence as one fragment of a larger logical program. Every Rexx fence that carries the same name — wherever it sits in the document — is treated as a single listing: the fragments are fused, highlighted together as one unit, and then rendered back in their original places. Because the whole program is parsed as a unit, stateful highlighting (a block comment, a ::RESOURCE, a line continuation) is resolved correctly across the gaps between fragments, and line numbering flows continuously from one fragment to the next.

This lets you split a single program across, say, two side-by-side slide columns, several pages, or code interleaved with prose in a paged article, while the highlighter still sees — and colours — one coherent program.

Fragments are grouped by a normalised form of the name: any run of blanks and/or dashes collapses to a single dash and the result is upper-cased, so program="The Towers of Hanoi", program=the-towers-of-hanoi and program="The Towers of Hanoi" all refer to the same program, THE-TOWERS-OF-HANOI. Note that normalisation collapses runs of blanks and dashes and changes case, but it does not add or remove words: program="Towers of Hanoi" normalises to TOWERS-OF-HANOI, which is a different program. As with any attribute, a value that contains blanks must be quoted.

The first fence's attributes are the program's. Its spot= marks the whole program, its lines numbered as the program's (line 12 is the twelfth line of the program, whichever fragment it is in): each fragment shows the marks that fall on its own lines. A spot= on a later fence is added to the first one's for that fragment only, with the same names for the same beats.

spot="beats"

Marks lines of this listing with the spotlight: a highlighter pen that strikes across whole lines, the way one marks a printed listing before talking about it.

The value names the beats this listing takes part in, and which of its lines light up in each one:

~~~rexx {.numberLines spot="init:2 salary:5-7,9"}
  ...
~~~

A beat is a named group of things that happen together; its name ignores case, as a Rexx symbol does. Terms are separated by blanks or by semicolons, as you prefer — spot="init:2 salary:5" and spot="init:2; salary:5" are the same thing. Lines may be given singly (2), as an inclusive range (5-7), or as a comma-separated list of both (2,5-7,9). Line numbers are the ones the reader sees: under startFrom=97, spot="x:97" means the first line of the block. The block need not show its numbers: without .numberLines the lines count from 1, the first line of the block, so a listing can be marked the way it is shown.

A few words can be marked instead of a line, by writing them between square brackets: spot="trap:[NOVALUE NAME ANY],[ANY:]" marks those texts wherever they appear in the block, and trap:5[ANY:] only on line 5. The match is by whole words, as written, and stays within one line; to match in any case, add the word caseless to the attribute, spot="trap:[say] caseless", and to match inside words too, part (spot="esc:[%20] part" marks the %20 of Rony%20G.; v360). Brackets inside the text pair up ([a[1]]). A text needs no line numbers, so it works on an unnumbered block too. The marks are drawn by the slide runtime; see the md2slides documentation.

The point is the correspondence. Two listings that share a beat light up together, in the same colour, with no further ceremony:

~~~rexx   {.numberLines spot="init:2"}
  ...
~~~

~~~output {.numberLines spot="init:1"}
  ...
~~~

That says "this line of the program produces this line of the output" — and says it in a way that survives the reader looking away. The two blocks need not come from the same highlighter: an output, python or plain-text fence carries spot= with exactly the same spelling, and shares the colour.

The colours belong to the chosen style, which declares four pens beside its own token palette, so a beat reads correctly on a light ground and on a dark one. Beats are given a pen in the order they appear.

In a paged or static rendering — an HTML page, a PDF, an EPUB — every beat is simply struck: there is no "advance", so the marks collapse into one finished picture. In a slide deck, where there is an advance, each beat fires on its own keypress and the marks accumulate; and a prose fragment may join a beat, so the sentence and the marks arrive together:

::: {.fragment spot=init}
This line builds the object...
:::

Because a beat waits for the last of its participants to appear, where you write that fragment decides when the pen strikes.

Words that are not beats. Besides the beats, spot= takes a few words that say how this listing's marks look, written next to the beats, as caseless is:

~~~rexx {spot="old:[DEFINE]; new:3-5; box pen=2"}
  ...
~~~
Word What it does
wash The highlighter's wash. This is the default.
ink The text itself in the pen's colour, on no wash.
box A frame round the marked text, or round a run of marked lines.
ring The same frame, rounded.
hatch Diagonal strokes in the pen's colour, instead of a wash.
bold The text in bold. Alone, nothing else; with another look (bold ink), both.
pen=n One of the style's four pens, 1 to 4, instead of the one the beat's place gives it.
pen=colour Any CSS colour (red, #c00, rgb(0 128 0)); on a page and in md2latex, a hex colour or a name (see below). The wash is that colour, lighter.
caseless A [text] matches in any case (see above).
part A [text] matches inside words too, not only as a whole word (v360).
indent Each run of marked lines is a band that starts where the text of its first line starts, not at the margin. Nested blocks give nested bands, and where two bands overlap the overlap is darker.
clear When this beat lights, every beat before it goes out.

clear is about steps, and so is hide, which goes on a cue or a fragment rather than on a listing: when its step comes, the beats it names go out, and a later cue lights them again. Both make sense in a slide deck. A hide written on a listing is reported by the deck's diagnose mode.

None of these words is a beat, so a beat cannot be called wash, ink, box, ring, hatch, pen=, caseless, indent, clear, hide or hull (hull is for trees on a slide). The words are read where the marks are drawn, not here: this attribute travels to the HTML as it is, so that an output or plain-text block, which does not pass through this highlighter, spells it the same way. On a slide, spot= goes on more than listings (prose, tables, trees, pictures), and a cue can give a whole beat its look; see How a Mark Looks in the md2slides documentation.

On a page. md2html, the CGI, md2pdf, md2epub and md2latex draw every beat at once, as a slide looks when all its steps are done: whole lines, texts, wash, ink, box, ring (and hatch, as a wash), bold and pen=. A beat that names no pen takes the next one: the first beat of the page pen 1, the second pen 2, and so on, in every block, Rexx or not, so that a beat that comes back in another block keeps its colour, as on a slide. (A block inside a cell of a grid table is not counted: a new beat there takes the pen of its place in its block.) The pens are those of the listing's style; on a block that is not Rexx, those of the document's style in md2latex, and the light style's on a page. Here pen= takes 1 to 4, #RRGGBB, #RGB or one of the 148 names of CSS (red, navy, cornflowerblue..., as in JDOR), which md2latex turns into numbers. The words about steps (clear, hide) and about slides (indent, hull) are left alone. One look holds for the whole block. A block that is not Rexx is written by the pipeline when it has marks, and so loses the highlighting of its language, as with blanks=.

An example: the YAMLFrontMatter program source

The program listing below is produced by inserting the two following lines in the HTML source.

~~~rexx {source=../../../bin/rexxpub/YAMLFrontMatter.cls}
~~~

Here is the program output:

/******************************************************************************/
/*                                                                            */
/* YAMLFrontMatter.cls -- Parse YAML front matter from a Markdown source      */
/* ====================================================================       */
/*                                                                            */
/* This file is part of the Rexx Parser package                               */
/* [See https://rexx.epbcn.com/rexx-parser/]                                  */
/*                                                                            */
/* Copyright (c) 2024-2026 Josep Maria Blasco <josep.maria.blasco@epbcn.com>  */
/*                                                                            */
/* License: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0)  */
/*                                                                            */
/* Version history:                                                           */
/*                                                                            */
/* Date     Version Details                                                   */
/* -------- ------- --------------------------------------------------------- */
/* 20260311    0.5   First public release                                     */
/* 20260925    0.5a  Comments at the end of a line ("total: 45  # minutes")   */
/* 20260926    0.6   Full YAML 1.2: the parsing is done by yaml.cls, which    */
/*                   comes with ooRexx (5.2.0 and later). This file is now    */
/*                   an adapter: it gives RexxPub the tree it expects.        */
/* 20260927          A UTF-8 BOM before the opening "---" is removed          */
/* 20261115         Use CATCH instead of SIGNAL ON (RFE #31; needs ooRexx     */
/*                  r13514 or later)                                          */
/* 20261121         Moved from bin/parser/ to bin/rexxpub/: it is RexxPub's,  */
/*                  not part of the parser (RFE #878)                         */
/* 20261126         Invalid YAML is a Rexx.Parser.DocumentError               */
/*                  (parser/DocumentError.cls), thrown as USER                */
/*                  REXX.PARSER.DOCUMENTERROR, and no longer a SYNTAX 98.900; */
/*                  the message is the same                                   */
/*                                                                            */
/******************************************************************************/

/******************************************************************************/
/*                                                                            */
/* YAMLFrontMatter(source) parses the YAML front matter of a Markdown         */
/* document.                                                                  */
/*                                                                            */
/* 'source' is an array of source lines. The front matter starts at line 1    */
/* with "---" and ends at the next "---" or "...". Returns .nil when there    */
/* is no front matter (no "---" at line 1, or no closing line).               */
/*                                                                            */
/* The YAML itself is read by yaml.cls, the YAML 1.2 class that comes with    */
/* ooRexx: block and flow mappings and sequences, quoted and block scalars,   */
/* escapes, anchors and aliases, comments. What comes back is normalized to   */
/* the tree the RexxPub pipelines expect:                                     */
/*                                                                            */
/*   mapping   a StringTable (also the front matter as a whole; one that is   */
/*             not a mapping, or is empty, gives an empty StringTable)        */
/*   sequence  an Array, its items normalized in the same way                 */
/*   boolean   the string "true" or "false" (YAML 1.2 core schema, plus the   */
/*             YAML 1.1 words yaml.cls also takes: yes/no, on/off)            */
/*   null      a key whose value is null ("key:", "key: ~", "key: null") is   */
/*             left out, as if it had not been written: "not specified".      */
/*             In a sequence a null item is ""                                */
/*   others    the string yaml.cls gives (numbers are canonical: 012 is 12)   */
/*                                                                            */
/* Invalid YAML throws a Rexx.Parser.DocumentError (USER                      */
/* REXX.PARSER.DOCUMENTERROR) whose description is "line N: invalid YAML      */
/* front matter: <what>", with N a line of 'source' (or no "line N: " when    */
/* the line is not known). Pandoc would reject the                            */
/* same front matter; this says so first, and more clearly.                   */
/* CheckedYAMLFrontMatter(source, file) is the same, but on invalid YAML it   */
/* reports "file:N: ..." on .Error and returns "", so that the caller stops   */
/* the way it stops for its other errors: the command-line tools use it.      */
/*                                                                            */
/******************************************************************************/

::Requires "yaml.cls"
::Requires "parser/DocumentError.cls"

::Routine YAMLFrontMatter Public
  Use Strict Arg source

  If source~items == 0          Then Return .Nil

  -- A UTF-8 byte order mark (EF BB BF), which Windows editors like to put at
  -- the start of a file, is not part of the text. Left in, line 1 reads as
  -- BOM || "---", not "---", and the front matter was silently not read at
  -- all (Rony, 27-sep: skin fields, footer, everything). It is removed from
  -- 'source' itself, so that the caller goes on with the text without it.
  If source[1]~startsWith("EFBBBF"x) Then source[1] = source[1]~substr(4)

  -- The YAML front matter must start at line 1 with "---"
  If Strip(source[1]) \== "---" Then Return .Nil

  -- Collect YAML lines (between opening "---" and closing "---" or "...")
  Loop i = 2 To source~items
    s = Strip(source[i])
    If s \== "---", s \== "..." Then Iterate
    yamlLines = source~section(2,i-2)
    Signal YAMLFrontMatterFound
  End

  -- If we ran off the end without finding a closing delimiter, no valid YAML
  Return .nil

YAMLFrontMatterFound:

  If yamlLines~items == 0 Then Return .StringTable~new

  Do
    tree = .Yaml~new~parseArray(yamlLines)
  Catch co = Syntax
    additional = co["ADDITIONAL"]
    what = ""
    If additional~isA(.Array), additional~items > 0 Then what = additional[1]
    If \what~isA(.String) Then Raise Propagate
    If \what~startsWith("YamlError: ") Then Raise Propagate

    -- "YamlError: <message> (line N)", and maybe a line with the context
    Parse Var what "YamlError: " what "0a"x
    line = ""
    If what~endsWith(")") Then Do
      at = what~lastPos(" (line ")
      If at > 0 Then Do
        n = what~substr(at + 7)~strip("T", ")")
        If n~dataType("W") Then Do
          what = Left(what, at - 1)
          -- n counts the lines of the front matter from 1; 'source' has the
          -- opening "---" before them. But yaml.cls up to ooRexx 5.3.0 gives
          -- one more than the line in error (fixed in later versions): ask
          -- the yaml.cls at hand how it counts.
          line = n + 1 - YamlLineBias()
        End
      End
    End
    -- A tab in the indentation comes without a line: find it.
    If line == "", what~startsWith("Tab character in indentation") Then
      Loop j = 1 To yamlLines~items
        lead = yamlLines[j]~verify(" "||"09"x)
        If lead == 0 Then lead = Length(yamlLines[j]) + 1
        If Pos("09"x, Left(yamlLines[j], lead - 1)) == 0 Then Iterate
        line = j + 1
        Leave
      End

    .Rexx.Parser.DocumentError~new( "invalid YAML front matter:" what, -
      line )~throw
  End

  If \tree~isA(.Table) Then Return .StringTable~new
  Return Normalized(tree)

/******************************************************************************/
/* YamlLineBias -- 1 if yaml.cls reports errors one line too far, else 0      */
/*                                                                            */
/* The yaml.cls of ooRexx 5.2.0 and 5.3.0 reports, for most errors, the line  */
/* AFTER the one in error; later versions report the right one. An error on   */
/* line 1 tells which: it comes back as line 2 or as line 1.                  */
/******************************************************************************/

::Routine YamlLineBias
  Do
    probe = .Yaml~new~parseArray(.Array~of("a: b: c"))
    Return 0                                  -- no error at all: no bias known
  Catch co = Syntax
    text = co["ADDITIONAL"]
    If text~isA(.Array) Then text = text[1]
    If \text~isA(.String) Then Return 0
    If text~pos("(line 2)") > 0 Then Return 1
    Return 0
  End

/******************************************************************************/
/* CheckedYAMLFrontMatter -- YAMLFrontMatter, for a command-line tool         */
/*                                                                            */
/* Invalid YAML is reported on .Error ("file:N: invalid YAML front matter:    */
/* ...") and gives "", which YAMLFrontMatter never returns: the caller then   */
/* stops. (An EXIT here would only end this routine, not the program.)        */
/******************************************************************************/

::Routine CheckedYAMLFrontMatter Public
  Use Strict Arg source, file

  Do
    Return YAMLFrontMatter(source)
  Catch co = User Rexx.Parser.DocumentError
    Do line Over co~additional~in(file)~report
      .Error~Say(line)
    End
    Return ""
  End

/******************************************************************************/
/* Normalized -- the tree yaml.cls gives, as RexxPub expects it               */
/******************************************************************************/

::Routine Normalized
  Use Strict Arg node

  Select
    When node~isA(.YamlBoolean) Then
      If node~value Then Return "true"
      Else               Return "false"
    When node~isA(.Table) Then Do
      map = .StringTable~new
      Do key Over node~allIndexes
        value = node[key]
        If value == .Nil Then Iterate              -- "key:" is "not given"
        name = key~request("String")
        If name == .Nil Then Iterate               -- a complex key
        map[name] = Normalized(value)
      End
      Return map
    End
    When node~isA(.Array) Then Do
      list = .Array~new
      -- Not "Do item Over": it skips the slots that hold .nil (a null item).
      Do i = 1 To node~items
        item = node[i]
        If item == .Nil Then list~append("")
        Else                 list~append(Normalized(item))
      End
      Return list
    End
    Otherwise Return node
  End