/******************************************************************************/ /* */ /* md2latex.rex - Markdown (a RexxPub article) to LaTeX for LuaLaTeX */ /* ================================================================== */ /* */ /* This program is part of the Rexx Parser package */ /* [See https://rexx.epbcn.com/rexx-parser/] */ /* */ /* Copyright (c) 2024-2026 Josep Maria Blasco */ /* */ /* License: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0) */ /* */ /* Date Version Details */ /* -------- ------- --------------------------------------------------------- */ /* 20261010 0.7 First version */ /* 20261011 docclass book (parts, front/back matter, lists, index, */ /* numbered listings, cross-references); --header, --filter */ /* and the latex: group of the YAML; wide listings scaled */ /* 20261011 acmart (ACM), with its own Pandoc template; class-options */ /* for every class; no parskip for the publishers' classes */ /* 20261011 The Rexx code is written with the macros of the LaTeX */ /* highlighter driver (HLDrivers/Latex.Driver.cls): the same */ /* LaTeX from highlight --latex and from md2latex */ /* 20261011 as small print;
 in the code box; the        */
/*                  scripts in the code font chain; Rexx that does not parse  */
/* 20261012         highlight-style:, --pandoc-highlighting-style; latex:     */
/*                  code: listings and --listings; long lines of code break   */
/* 20261012         Pandoc 3.8 and later: --syntax-highlighting               */
/* 20261012         The font chains: only the fonts there are (header.tex)    */
/* 20261018         The start of a numbered listing: --rx-start (and the old  */
/*                  counter-reset, for HTML written before)                   */
/* 20261020         Arabic and Hebrew only with their text; a missing font is */
/*                  a warning (Latin Modern for a main font); \rxfit again    */
/* 20261020         Books: references to footnotes (note=); a PDF that cannot */
/*                  be written (open in a viewer) is said before LuaLaTeX     */
/*                                                                            */
/* 20261021         Tables: balanced by default; .grid and .stripes, on the   */
/*                  ::: or in the YAML (tables:), dressed in the .tex         */
/* 20261022         style: (and --style) can be a file of the author's own    */
/* 20261024         Cells that span columns with .stripes and .grid; scale=   */
/*                  on a ::: or a [span]; deeper lists (enumitem, 23-Oct)     */
/* 20261025         Marks (spot=, every beat at once: wash, ink, box, ring,   */
/*                  bold), the ground and frame of the blocks (background=,   */
/*                  border=, border-width=, border-color=; rexxpub: blocks:), */
/*                  {.newpage} on any block (Rony, 25-Oct)                    */
/* 20261026         rexxpub: mentions: background: none (mentions on no       */
/*                  ground); latex: line-numbers: and --line-numbers (lineno) */
/* 20261026         Fences in the cells of a grid table (Rony's "Rosetta      */
/*                  Stone"): each cell made LaTeX on its own, and the table   */
/*                  drawn again (GridTables.cls, TablesLatex)                 */
/* 20261026         latex: list-gaps: no (no gap between the chapters in the  */
/*                  lists of figures and tables)                              */
/* 20261027         A class or a key that is ours but for its case is said    */
/*                  (NearMisses.cls; Rony: caseless names)                    */
/* 20261102         A listing's caption says "Listing" in the document's      */
/*                  lang:, or listings: label: (it was always "Listing")      */
/* 20261102         csl: in the front matter wins over --csl (as the docs     */
/*                  said; --csl, always given, used to win)                   */
/* 20261103         spot=: one colour per beat for the whole page, also in    */
/*                  the blocks that are not Rexx (REXXPUB_BEAT_PENS) (Rony)   */
/* 20261115         The per-file SYNTAX trap is a DO with a CATCH clause      */
/*                  (RFE #31; needs ooRexx r13514 or later)                   */
/* 20261119         A syntax error in a Rexx block is the condition USER      */
/*                  REXX.PARSER.ERROR (THROW, RFE #31; ooRexx r13546 or       */
/*                  later), reported by ReportParseError                      */
/* 20261122         rexxpub/SearchPath.cls first: the parser is the one of    */
/*                  the installed ooRexx, and finds rexxpub/ (Spots,          */
/*                  GridTables, the LaTeX driver) in REXX_PATH                */
/******************************************************************************/
/*                                                                            */
/* Conferences and journals want LaTeX. md2latex writes the LaTeX of a        */
/* RexxPub article, to be run with LuaLaTeX (the only engine that does        */
/* Unicode and OpenType properly, and the one with a future), and, with       */
/* --pdf, runs it.                                                            */
/*                                                                            */
/* The pieces:                                                                */
/*                                                                            */
/* - The Markdown is read and its Rexx code highlighted exactly as md2pdf     */
/*   does (FencedCode). The HTML that comes out for each listing and each     */
/*   inline mention is then rewritten here as LaTeX, with the macros of the   */
/*   LaTeX highlighter driver (rexxpub/Latex.Driver.cls): one per token,      */
/*   \rxhT{flags/fg/bg}{text}, its look taken from the same CSS that styles   */
/*   the HTML (GetHighlight). One source of truth for both outputs.           */
/* - Pandoc writes the LaTeX, with its own template, a header of ours         */
/*   (md2latex/header.tex: fonts, Unicode fallbacks, bidi, the code box)      */
/*   and a Lua filter (md2latex/rexxpub.lua) for the RexxPub conventions:     */
/*   the title page, , epigraphs, quotations, {.newpage}; for books,   */
/*   parts, the front and back matter, the lists of figures, tables and       */
/*   listings, the index and the cross-references.                            */
/* - A document can bring its own LaTeX header and Lua filter (--header,      */
/*   --filter, or latex: header/filter in the YAML), for its own conventions. */
/* - Unicode: every font has a chain of fallback fonts (luaotfload), right-   */
/*   to-left scripts are found by their characters (babel, bidi=basic), and   */
/*   a character that no font has is an ERROR (\tracinglostchars=3): with     */
/*   --pdf, md2latex lists those characters. Nothing is lost in silence.      */
/*                                                                            */
/******************************************************************************/

  Call Time "R"

  CLIhelper    = InitCLI()
  myName       = CLIhelper~name
  myHelp       = CLIhelper~help
  args         = CLIhelper~args
  rootDir      = .File~new(.context~package~name)~parentFile~parent
  rootDir      = ChangeStr("\",rootDir,"/")
  homeDir      = rootDir"/bin/md2latex"

  check = "✔"
  fail  = "❌"

  defaultTheme   = "light"           -- Paper: a light style by default
  cliStyle       = 0
  defaultOptions = ""
  csl            = "rexxpub"
  docClass       = "article"         -- The LaTeX class (and its title block)
  makePDF        = 0
  keep           = 0
  outFile        = ""
  executor       = 0
  experimental   = 0
  unicode        = 0
  itrace         = 0
  cliClass       = 0
  extraHeaders   = .Array~new         -- --header FILE (more LaTeX)
  extraFilters   = .Array~new         -- --filter FILE (more Lua)
  highlightStyle = "pygments"         -- Pandoc's, for code that is not Rexx
  cliHighlight   = 0
  listings       = 0                  -- --listings: that code with listings
  lineNumbers    = 0                  -- --line-numbers: every line of the text

  If args~size == 0 Then Signal Help

  Loop While args~size > 0, args[1][1] == "-"
    option = args[1]
    args~delete(1)
    Select Case Lower(option)
      When "-h", "--help"                 Then Signal Help
      When "-it", "--itrace"              Then itrace       = 1
      When "--check-deps"                 Then Do; Call CheckDeps; Exit 0; End
      When "--pdf"                        Then makePDF      = 1
      When "--keep"                       Then keep         = 1
      When "-xtr", "--executor"           Then executor     = 1
      When "-exp", "--experimental"       Then experimental = 1
      When "-u", "--tutor", "--unicode"   Then unicode      = 1
      When "-o", "--output"  Then outFile        = NextArg(option, "file name")
      When "--style"         Then Do
        defaultTheme = NextArg(option, "style name")
        cliStyle     = 1
      End
      When "--class"         Then Do
        docClass = NextArg(option, "class name")
        cliClass = 1
      End
      When "--header"        Then extraHeaders~append(NextArg(option, "file name"))
      When "--filter"        Then extraFilters~append(NextArg(option, "file name"))
      When "--csl"           Then csl            = NextArg(option, "CSL style")
      When "--listings"                   Then listings     = 1
      When "--line-numbers"               Then lineNumbers  = 1
      When "--pandoc-highlighting-style" Then Do
        hsName = NextArg(option, "style name")
        highlightStyle = PandocStyle(hsName)
        If highlightStyle == "" Then Call Error "Pandoc highlighting style '"hsName"' not found."
        cliHighlight = 1
      End
      When "--default"       Then defaultOptions = NextArg(option, "options")
      Otherwise Call Error "Invalid option '"option"'."
    End
  End

  If WordPos(docClass, "article llncs IEEEtran acmart book") == 0 Then
   .Error~Say("Warning: no title profile for class '"docClass"';" -
      "the title, authors and abstract are written as for article.")
  If args~size == 0 Then Call Error "Missing file name."
  If args~size  > 1 Then Call Error "Unexpected argument '"args[2]"'."
  file = args[1]
  If \SysFileExists(file) Then Call Error "'"file"' not found."

  -- --style: a shipped style, or a file of the author's (LocalStyle)
  local = LocalStyle(defaultTheme, Directory())
  Select
    When local == .Nil Then Do
      defaultTheme = Lower(defaultTheme)
      If \.File~new(rootDir"/css/rexx-"defaultTheme".css")~exists Then
        Call Error "Style '"defaultTheme"' not found."
    End
    When local~isA(.Array) Then defaultTheme = local[1]
    Otherwise Call Error "Style '"defaultTheme"':" local"."
  End

  If csl~pos("/") > 0 | csl~pos("\") > 0 | csl~caselessEndsWith(".csl")
    Then cslPath = csl
    Else cslPath = rootDir"/csl/"csl".csl"

  Exit ProcessFile(.File~new(file)~absolutePath)

--------------------------------------------------------------------------------

NextArg:
  If args~size == 0 Then Call Error "Missing" Arg(2) "after '"Arg(1)"' option."
  Parse Value args[1] With value
  args~delete(1)
  Return value

--------------------------------------------------------------------------------

ProcessFile: Procedure Expose rootDir homeDir check fail defaultTheme cliStyle -
  defaultOptions cslPath docClass makePDF keep outFile executor experimental  -
  unicode itrace cliClass extraHeaders extraFilters highlightStyle cliHighlight -
  listings lineNumbers

  Use Strict Arg file

  fileObj  = .File~new(file)
  fileDir  = fileObj~parent
  name     = FileSpec("Name", file)
  If name~caselessEndsWith(".md") Then name = Left(name, Length(name) - 3)

  If outFile == "" Then texFile = fileDir"/"name".tex"
  Else                  texFile = .File~new(outFile)~absolutePath
  texDir   = .File~new(texFile)~parent
  texName  = FileSpec("Name", texFile)
  If texName~caselessEndsWith(".tex") Then texName = Left(texName, Length(texName) - 4)

  source   = LoadProgramSource(file)

  yaml     = CheckedYAMLFrontMatter(source, file)
  If yaml == "" Then Return 1
  opts     = ParseRexxPubYAML(yaml)

  -- style: a shipped style, or a file of the author's, relative to the .md
  -- (Rony, 21-Oct: his own variant of vim-light-zellner, next to book.md)
  If \cliStyle, opts["style"] \== .Nil Then Do
    local = LocalStyle(opts["style"], fileDir)
    Select
      When local == .Nil Then Do
        yamlStyle = Lower(opts["style"])
        If .File~new(rootDir"/css/rexx-"yamlStyle".css")~exists Then
          defaultTheme = yamlStyle
        Else
         .Error~Say("Warning: YAML style '"opts["style"]"' not found, ignored.")
      End
      When local~isA(.Array) Then defaultTheme = local[1]
      Otherwise
       .Error~Say("Warning: YAML style '"opts["style"]"':" local"; ignored.")
    End
  End

  -- docclass: book in the YAML makes a book, unless --class says otherwise
  If \cliClass, opts["docclass"] == "book" Then docClass = "book"
  Else If opts["docclass"] \== .Nil, WordPos(opts["docclass"], "article book") == 0 Then
   .Error~Say("Warning: md2latex writes articles and books; docclass" -
      "'"opts["docclass"]"' treated as article.")
  book = docClass == "book"

  size = 12
  If opts["size"] \== .Nil Then size = opts["size"]
  If WordPos(size, "10 11 12") == 0 Then Do
   .Error~Say("Warning: size" size"pt is not a LaTeX size; 12pt used.")
    size = 12
  End

  If book Then sectionNumbers = DefaultSectionNumbers("book")
  Else         sectionNumbers = DefaultSectionNumbers("article")
  If opts["section-numbers"] \== .Nil Then sectionNumbers = opts["section-numbers"]

  language = "en"
  If opts["language"] \== .Nil Then language = opts["language"]

  -- Code that is not Rexx: Pandoc highlights it, with highlight-style: (at
  -- the top of the YAML, as for md2html and md2pdf), or listings sets it
  If \cliHighlight, opts["highlight-style"] \== .Nil Then Do
    hs = PandocStyle(opts["highlight-style"])
    If hs == "" Then
     .Error~Say("Warning: highlight-style '"opts["highlight-style"]"' not" -
        "found; pygments used.")
    Else highlightStyle = hs
  End

  ------------------------------------------------------------------------------
  -- The latex: group of the rexxpub: YAML (what only md2latex reads)         --
  ------------------------------------------------------------------------------

  latex.   = ""
  latex.paper    = "a4"
  latex.tocDepth = ""
  tables.grid    = 0                  -- rexxpub: tables: grid:
  tables.stripes = ""                 -- rexxpub: tables: stripes: (yes or a colour)
  mentionsBare   = 0                  -- rexxpub: mentions: background: none
  listGaps       = 1                  -- latex: list-gaps: no: no gap per chapter
  rp = .Nil
  If yaml~isA(.MapCollection) Then rp = yaml["rexxpub"]
  If rp~isA(.StringTable) Then Do
    lx = rp["latex"]
    If lx~isA(.StringTable) Then Do
      Do key Over .Array~of("header", "filter", "paper", "toc-depth", "class-options", "code", -
                            "line-numbers", "list-gaps")
        value = lx[key]
        If value == .Nil Then Iterate
        Select Case key
          When "header"        Then extraHeaders~append(fileDir"/"value)
          When "filter"        Then extraFilters~append(fileDir"/"value)
          When "paper"         Then latex.paper    = value
          When "toc-depth"     Then latex.tocDepth = value
          When "class-options" Then latex.classOptions = value
          When "line-numbers"  Then
            If WordPos(Lower(value), "1 yes true on") > 0 Then lineNumbers = 1
          When "list-gaps"     Then
            If WordPos(Lower(value), "0 no false off") > 0 Then listGaps = 0
          When "code"          Then Select Case Lower(value)
            When "listings"  Then listings = 1
            When "pandoc"    Then Nop
            Otherwise .Error~Say("Warning: latex: code: '"value"' is" -
              "neither pandoc nor listings; pandoc used.")
          End
        End
      End
    End
    -- tables: grid: and stripes: for every table (Rony, 21-Oct)
    tb = rp["tables"]
    If tb~isA(.StringTable) Then Do
      If tb["grid"] \== .Nil Then
        tables.grid = WordPos(Lower(tb["grid"]), "1 yes true on") > 0
      If tb["stripes"] \== .Nil Then Do
        v = tb["stripes"]
        Select
          When WordPos(Lower(v), "1 yes true on") > 0 Then tables.stripes = "yes"
          When WordPos(Lower(v), "0 no false off") > 0 Then tables.stripes = ""
          Otherwise tables.stripes = v
        End
      End
    End
    -- mentions: background: none -- a mention on no ground, in the colours
    -- of the style (Rony, 25-Oct: keywords in the text as in the code, and
    -- not so many grounds in the text)
    mn = rp["mentions"]
    If mn~isA(.StringTable), mn["background"] \== .Nil Then
      mentionsBare = WordPos(Lower(mn["background"]), "none no false off 0 transparent") > 0
    -- listings: label and numbering (numbering: section -> "1.1-1")
    lst = rp["listings"]
    If lst~isA(.StringTable) Then Do
      If lst["numbering"] \== .Nil Then latex.numbering = Lower(lst["numbering"])
    End
  End
  listingLabel = opts["listing-label"]
  -- (20261102) The word follows lang:, as in the pages (js/numberFigures.js)
  If listingLabel == "" Then listingLabel = ListingWord(language)
  Do list Over .Array~of(extraHeaders, extraFilters)
    Do f Over list
      If \SysFileExists(f) Then Do
       .Error~Say(fail "'"f"' not found.")
        Return 1
      End
    End
  End

  ------------------------------------------------------------------------------
  -- Rexx code: highlighted as for HTML, then turned into LaTeX               --
  ------------------------------------------------------------------------------

  combinedDefaults = defaultOptions
  If executor     | opts["executor"]     == "true" Then combinedDefaults = Strip(combinedDefaults "executor")
  If experimental | opts["experimental"] == "true" Then combinedDefaults = Strip(combinedDefaults "experimental")
  If unicode      | opts["unicode"]      == "true" Then combinedDefaults = Strip(combinedDefaults "unicode")

  options. = 0
  options.default = combinedDefaults
  -- One file, as md2pdf and md2html with one: a block that does not parse
  -- is shown as an error box, and the rest of the document goes on.
  options.["CONTINUE"] = 1
  -- spot=: every mark at once (Spots.cls marks the HTML; Tokens draws it)
  options.["STATICSPOTS"] = 1

  -- A class or a key that is ours but for its case (.numberlines): said,
  -- not mended. Outside a Rexx fence names are case-sensitive, as in Pandoc
  -- and CSS (Rony, 27/10/2026).
  Loop note Over NearMisses(source)
    .Error~Say( "Warning:" note )
  End

  Do
    -- The pens of the beats, by their place in the page: the Lua filters
    -- (cgi/spots.lua) mark the blocks that are not Rexx with the same ones
    Call Value "REXXPUB_BEAT_PENS", PageBeatPens( source ), "ENVIRONMENT"
    highlighted = FencedCode( file, source, defaultTheme, options. )
  Catch co = User Rexx.Parser.Error
    -- A syntax error in a Rexx block is reported, and this file fails
    Call ReportParseError co~additional, itrace
    Return 1
  Catch co = Syntax
    -- An error FencedCode found in the document is reported, and this file
    -- fails; anything else is an error of ours
    If \IsAParseError(co, itrace) Then Raise Propagate
    Return 1
  End

  -- A grid table first, cell by cell: the LaTeX of a listing is not as
  -- long as its HTML, and the table has to be drawn again
  highlighted = TablesLatex(highlighted, mentionsBare)
  markdown = HTML2Latex(highlighted~makeString("L", "0a"x), mentionsBare)
  -- In a book, a footnote can be referred to (its number, page, above or
  -- below): each note's text starts with an anchor of its own, rxfn-LABEL.
  If book Then markdown = NoteAnchors(markdown)

  ------------------------------------------------------------------------------
  -- The header                                                               --
  ------------------------------------------------------------------------------

  header = FileContents(homeDir"/header.tex")
  fonts. = FontDefaults(docClass)
  header = header                                         -
    ~changeStr("%RXSERIFCHAIN%",  fonts.serifChain)       -
    ~changeStr("%RXSANSCHAIN%",   fonts.sansChain)        -
    ~changeStr("%RXMONOCHAIN%",   fonts.monoChain)        -
    ~changeStr("%RXSETFONTS%",    SetFonts(fonts.))       -
    ~changeStr("%RXMATHFONT%",    fonts.math)             -
    ~changeStr("%RXLANGUAGE%",    BabelLanguage(language)) -
    ~changeStr("%RXLISTINGNAME%", listingLabel)            -
    ~changeStr("%RXOTHERLANGUAGES%", RTLLanguages(source)) -
    ~changeStr("%RXPROLOG%",      .LaTeX.Highlighter~prologText)   -
    ~changeStr("%RXBOX%",         DefaultBox(defaultTheme))        -
    ~changeStr("%RXFG%",          Word(.LaTeX.Highlighter~box(defaultTheme), 1)) -
    ~changeStr("%RXBG%",          Word(.LaTeX.Highlighter~box(defaultTheme), 2))
  If book Then header = header || FileContents(homeDir"/header-book.tex")
  -- Every line of the text numbered, the numbers starting again on each page,
  -- for the proofreaders (Rony, 26-Oct: "refer to the page and the exact
  -- line number on that page"). Code and output are boxes: not numbered. In
  -- a book (two sides), the numbers go in the outer margin.
  -- (fvextra loads lineno already, with no options: its commands say them)
  If lineNumbers Then Do
    lineOptions = "\pagewiselinenumbers"
    If book Then lineOptions ||= "\switchlinenumbers"
    header = header || "0a"x"% --- latex: line-numbers:"  || "0a"x || -
      "\usepackage{lineno}"lineOptions                      || "0a"x || -
      "\renewcommand\linenumberfont{\normalfont\tiny\sffamily\color{gray}}" || "0a"x || -
      "\linenumbers"                                        || "0a"x
  End
  -- The book class groups the entries of the List of Figures and the List of
  -- Tables by chapter: every \chapter writes \addvspace{10pt} into the .lof
  -- and the .lot. latex: list-gaps: no makes one list with no groups (Rony,
  -- 26-Oct: "sometimes there are empty lines"). The gap is dropped where the
  -- lists are read, not where the chapters write it: titlesec, or a class of
  -- the author's, may define \chapter in its own way.
  If \listGaps Then
    header = header || "0a"x"% --- latex: list-gaps: no"   || "0a"x || -
      "\makeatletter"                                       || "0a"x || -
      "\def\rx@nogap@lof{}\def\rx@nogap@lot{}"              || "0a"x || -
      "\let\rx@starttoc\@starttoc"                          || "0a"x || -
      "\def\@starttoc#1{\begingroup"                        || "0a"x || -
      "  \ifcsname rx@nogap@#1\endcsname\let\addvspace\@gobble\fi" || "0a"x || -
      "  \rx@starttoc{#1}\endgroup}"                        || "0a"x || -
      "\makeatother"                                        || "0a"x
  Do f Over extraHeaders
    header = header || "0a"x"% ---" f "0a"x || FileContents(f)
  End

  ------------------------------------------------------------------------------
  -- Pandoc                                                                   --
  ------------------------------------------------------------------------------

  tmpDir     = .File~temporaryPath~absolutePath
  mdFile     = SysTempFileName(tmpDir"/"name"?????.md")
  headerFile = SysTempFileName(tmpDir"/"name"?????.tex")
  Call WriteFile mdFile, markdown
  Call WriteFile headerFile, header

  -- csl: in the front matter wins over --csl (20261102): Pandoc's --csl is
  -- metadata given on the command line, which wins over the document's
  cslOption = '--csl="'cslPath'"'
  If yaml~isA(.MapCollection), yaml~hasIndex("csl") Then cslOption = ""

  pandoc = 'pandoc "'mdFile'"'                                -
    '-f markdown -t latex --standalone'                       -
    '--resource-path="'fileDir'"'                             -
    '--lua-filter="'homeDir'/rexxpub.lua"'                    -
    '-M rexxpub-header="'headerFile'"'                        -
    '-M rexxpub-class='docClass                               -
    '-M rexxpub-dir="'fileDir'"'                              -
    '-M rexxpub-listing-label="'listingLabel'"'               -
    '-M rexxpub-pens="'PenColours(defaultTheme)~makeString("L", " ")'"' -
    '-V documentclass='docClass                               -
    '-V colorlinks=true'                                      -
    '-V linkcolor=rxlink -V urlcolor=rxlink'                  -
    '-V citecolor=rxlink -V filecolor=rxlink'                 -
    '--citeproc' cslOption '-M link-citations=true'           -
    '-o "'texFile'"'
  Do f Over extraFilters
    pandoc = pandoc '--lua-filter="'f'"'
  End
  -- Code that is not Rexx (Rexx is LaTeX already, and Pandoc leaves it be).
  -- Pandoc 3.8 renamed the options (the old ones still work, with a warning)
  If PandocAtLeast(3, 8) Then Do
    If listings Then pandoc = pandoc '--syntax-highlighting=idiomatic'
    Else             pandoc = pandoc '--syntax-highlighting='highlightStyle
  End
  Else Do
    If listings Then pandoc = pandoc '--listings'
    Else             pandoc = pandoc '--highlight-style='highlightStyle
  End
  -- acmart: our own template (Pandoc's clashes with it: see acmart.latex)
  If docClass == "acmart" Then
    pandoc = pandoc '--template="'homeDir'/acmart.latex"'
  -- The publishers' classes indent their paragraphs: no parskip from Pandoc
  If WordPos(docClass, "llncs IEEEtran acmart") > 0 Then
    pandoc = pandoc '-V indent=true'
  If latex.numbering \== "" Then
    pandoc = pandoc '-M rexxpub-listing-numbering='latex.numbering
  If latex.tocDepth \== "" Then
    pandoc = pandoc '-M rexxpub-toc-depth='latex.tocDepth
  If tables.grid Then
    pandoc = pandoc '-M rexxpub-tables-grid=true'
  If tables.stripes \== "" Then
    pandoc = pandoc '-M rexxpub-tables-stripes="'tables.stripes'"'
  -- The page is RexxPub's only for article: a publisher's class has its own
  If docClass == "article" Then
    pandoc = pandoc '-V fontsize='size'pt -V papersize=a4 -V geometry=margin=3cm'
  -- A book: chapters at the top, facing pages, a wider inner margin
  If book Then Do
    pandoc = pandoc '--top-level-division=chapter'        -
      '-V fontsize='size'pt -V papersize='latex.paper     -
      '-V classoption=twoside -V classoption=openright'   -
      '-V geometry=inner=3cm -V geometry=outer=2.2cm'      -
      '-V geometry=top=2.5cm -V geometry=bottom=2.8cm'     -
      '-V geometry=headheight=14pt'
  End
  If docClass == "IEEEtran" Then          -- Conference papers
    pandoc = pandoc '-V classoption=conference'
  -- acmart: the format is a class option (sigconf, unless another is given)
  classOptions = Space(ChangeStr(",", latex.classOptions, " "))
  If docClass == "acmart" Then Do
    acmFormat = "sigconf"
    Do o Over classOptions~makeArray(" ")
      If WordPos(ChangeStr("format=", o, ""), "manuscript acmsmall acmlarge" -
        "acmtog sigconf siggraph sigplan sigchi sigchi-a acmengage acmcp") > 0 Then
        acmFormat = ""
    End
    If acmFormat \== "" Then classOptions = Strip(acmFormat classOptions)
  End
  Do o Over classOptions~makeArray(" ")   -- latex: class-options, any class
    pandoc = pandoc '-V classoption='o
  End
  -- Two columns: a table is a float (longtable cannot be used)
  twoColumn = docClass == "IEEEtran"
  If docClass == "acmart" Then Do o Over classOptions~makeArray(" ")
    If WordPos(ChangeStr("format=", o, ""), "sigconf siggraph sigplan acmtog") > 0 Then
      twoColumn = 1
  End
  If twoColumn Then pandoc = pandoc '-M rexxpub-twocolumn=true'
  -- secnumdepth counts from \section (1): in a book, level 1 is \chapter (0)
  If sectionNumbers > 0 Then Do
    If book Then pandoc = pandoc '--number-sections -V secnumdepth='sectionNumbers - 1
    Else         pandoc = pandoc '--number-sections -V secnumdepth='sectionNumbers
  End

  savedDir = Directory()
  Call Directory fileDir
 .Error~CharOut("Invoking Pandoc... ")
  Address COMMAND pandoc With Error Stem err.
  pandocRC = rc
  Call Directory savedDir
  If pandocRC \== 0 Then Do
   .Error~Say(fail "Pandoc failed with return code" pandocRC":")
    Do i = 1 To err.0; .Error~Say(err.i); End
    Return pandocRC
  End
 .Error~Say(check)
  Do i = 1 To err.0; .Error~Say(err.i); End     -- The filter's warnings

  -- rules=, .grid, .stripes on a table: done now that every filter has
  -- done its work on the cells
  tex = FileContents(texFile)
  If tex~pos("% rxtable ") > 0 Then Call WriteFile texFile, TableDress(tex)

  If \keep Then Do
    Call SysFileDelete mdFile
    Call SysFileDelete headerFile
  End
  Else .Error~Say("Kept:" mdFile headerFile)

 .Error~Say("Wrote" texFile)

  If \makePDF Then Return 0

  ------------------------------------------------------------------------------
  -- LuaLaTeX                                                                 --
  ------------------------------------------------------------------------------

  -- A PDF that is open in a viewer cannot be written over on Windows, and
  -- LuaLaTeX says so in words that do not say it (Rony, 20-Oct): ask first.
  pdfFile = texDir"/"texName".pdf"
  If SysFileExists(pdfFile) Then Do
    s = .Stream~new(pdfFile)
    If s~open("Write")~left(6) \== "READY:" Then Do
     .Error~Say(fail "'"pdfFile"' cannot be written: is it open in another" -
        "program? Close it and run md2latex again.")
      Return 1
    End
    s~close
  End

  Call Directory texDir
  lualatex = 'lualatex -interaction=nonstopmode' -
    '-file-line-error "'texName'.tex"'
  -- A book needs more passes: the lists and the index move the page numbers
  passes = 3
  If book Then passes = 5
  Do pass = 1 To passes
   .Error~CharOut("Running LuaLaTeX (pass" pass")... ")
    Address COMMAND lualatex With Output Stem out. Error Stem err.
    latexRC = rc
    logText = FileContents(texName".log")
    If latexRC \== 0 Then Leave
   .Error~Say(check)
    -- longtable says "Table widths have changed. Rerun LaTeX.": without
    -- that pass a table's head and body did not line up
    -- lineno numbers page by page from what the run before wrote, and says
    -- nothing: three runs at least
    If lineNumbers, pass < 3 Then Iterate
    If logText~pos("Rerun to get") == 0, logText~pos("Label(s) may have changed") == 0, -
       logText~pos("Rerun LaTeX") == 0 Then
      Leave
  End
  Call Directory savedDir

  missing = MissingCharacters(logText)
  If missing \== "" Then Do
   .Error~Say(fail "Characters that no font has (add a font that has them):")
   .Error~Say(missing)
    Return 1
  End
  If latexRC \== 0 Then Do
   .Error~Say(fail "LuaLaTeX failed (see" texDir"/"texName".log):")
    Do i = 1 To out.0
      If out.i~left(1) == "!" | out.i~pos(":") > 0 & out.i~pos(".tex:") > 0 Then
       .Error~Say("  " out.i)
    End
    Return latexRC
  End
 .Error~Say("Wrote" texDir"/"texName".pdf, took" Time("E")~format(,1) "seconds.")
  Return 0

--------------------------------------------------------------------------------
-- The characters LuaTeX reported as missing ("Missing character: There is  --
-- no X (U+NNNN) in font F!"), each once, with its code point.              --
--------------------------------------------------------------------------------

MissingCharacters: Procedure
  Use Strict Arg log
  seen = .Set~new
  list = ""
  Do While log~pos("Missing character: There is no ") > 0
    Parse Var log "Missing character: There is no " char " (U+" code ")" log
    If seen~hasIndex(code) Then Iterate
    seen~put(code)
    list ||= "    U+"code char || "0a"x
  End
  Return Strip(list, "T", "0a"x)

--------------------------------------------------------------------------------
-- Fonts. Times-like for the text, as RexxPub's article; DejaVu Sans Mono   --
-- for code (it has real bold and oblique). Each chain lists the fonts that --
-- supply what the main font lacks, in order: HarfBuzz mode, so that the    --
-- scripts that need shaping (Devanagari...) are shaped.                    --
--------------------------------------------------------------------------------

FontDefaults: Procedure
  Use Strict Arg class
  scripts = "NotoSansDevanagari NotoSansBengali NotoSansTamil" -
            "NotoSansThai NotoSansArmenian NotoSansGeorgian"   -
            "NotoSansEthiopic"
  common = "NotoSansMath NotoSansSymbols NotoSansSymbols2"   -
           "NotoSerifCJKsc" scripts "NotoMusic"              -
           "NotoColorEmoji DejaVuSans"
  f.main  = "TeX Gyre Termes"
  f.sans  = "TeX Gyre Heros"
  f.mono  = "DejaVu Sans Mono"
  f.math  = "TeX Gyre Termes Math"
  f.mainOptions = ""
  f.sansOptions = ""
  If class == "llncs" Then Do             -- Springer: Computer Modern
    f.main = "Latin Modern Roman"
    f.sans = "Latin Modern Sans"
    f.math = "Latin Modern Math"
  End
  If class == "acmart" Then Do            -- ACM: Libertine, as acmart loads
    f.main = "LinLibertine"               -- it (by file), and its math
    f.sans = "LinBiolinum"                -- (newtxmath, not unicode-math)
    f.mainOptions = "Extension=.otf,UprightFont=*_R,ItalicFont=*_RI," || -
      "BoldFont=*_RB,BoldItalicFont=*_RBI,Ligatures=TeX,"
    f.sansOptions = "Extension=.otf,UprightFont=*_R,ItalicFont=*_RI," || -
      "BoldFont=*_RB,BoldItalicFont=*_RBO,Ligatures=TeX,"
  End
  f.serifChain = Chain("NotoSerif" common)
  f.sansChain  = Chain("NotoSans"  common)
  -- The scripts go last, so that nothing the first fonts had changes font.
  f.monoChain  = Chain("NotoSansMono NotoSansMath NotoSansSymbols2" -
                       "NotoSansCJKsc DejaVuSans NotoColorEmoji"    -
                       scripts "NotoSansSymbols NotoMusic")
  Return f.

-- Is Pandoc (the one on the PATH) this version or a later one?
PandocAtLeast: Procedure
  Use Strict Arg major, minor
  Address COMMAND "pandoc --version" With Output Stem o. Error Stem e.
  If rc \== 0 | o.0 == 0 Then Return 0
  Parse Var o.1 . v .
  Parse Var v ma "." mi "."
  If \DataType(ma, "W") Then Return 0
  If \DataType(mi, "W") Then mi = 0
  Return ma > major | (ma = major & mi >= minor)

-- A Pandoc highlighting style, as Pandoc names it ("breezedark"), or "" when
-- there is no such style. The names are those of css/pandoc, for md2html.
PandocStyle: Procedure
  Use Strict Arg name
  Do s Over "pygments kate tango espresso zenburn monochrome breezedark haddock"~makeArray(" ")
    If Lower(name) == s Then Return s
  End
  Return ""

Chain: Procedure
  Use Strict Arg fonts
  out = ""
  Do f Over fonts~makeArray(" ")
    out ||= '    "'f':mode=harf;",' || "0a"x
  End
  Return Strip(out, "T", "0a"x)

--------------------------------------------------------------------------------
-- Languages: babel names for the codes RexxPub uses. Right-to-left         --
-- scripts are provided "onchar", so that they are recognised in any text.  --
--------------------------------------------------------------------------------

BabelLanguage: Procedure
  Use Strict Arg code
  Parse Lower Value code With code "-" .
  Select Case code
    When "en" Then Return "english"
    When "es" Then Return "spanish"
    When "ca" Then Return "catalan"
    When "de" Then Return "german"
    When "fr" Then Return "french"
    When "it" Then Return "italian"
    When "pt" Then Return "portuguese"
    When "nl" Then Return "dutch"
    Otherwise
     .Error~Say("Warning: language '"code"' not known to md2latex; English used.")
      Return "english"
  End

-- What a table asked for (Rony, 20 and 21-Oct): the filter left
-- "% rxtable n=N rules=KIND grid stripes=HEX" before it (N, its columns);
-- here, in the LaTeX Pandoc wrote, after every filter:
--   rules=   each row of the body but the last gets a line after its "\\":
--            \midrule, or \rxruledashed{N} or \rxruledotted{N} (header.tex);
--   grid     a bar between the columns and at both ends, booktabs' rules
--            become \hline (they leave gaps at the bars), and a \hline
--            under each row (unless rules= says another line);
--   stripes  every second row of the body starts with \rowcolor (colortbl,
--            loaded then, with the colour).
-- The mark goes. Line ends are kept as found.
TableDress: Procedure
  Use Strict Arg tex
  If tex~pos("0d0a"x) > 0 Then nl = "0d0a"x; Else nl = "0a"x
  out    = .MutableBuffer~new
  colors = .Array~new
  Loop
    p = tex~pos("% rxtable ")
    If p == 0 Then Leave
    Parse Value SubStr(tex, p) With "% rxtable " words (nl) .
    n = 0; rules = ""; grid = 0; stripes = ""
    Do w Over words~makeArray(" ")
      Parse Var w key "=" value
      Select Case key
        When "n"       Then n = value
        When "rules"   Then rules = value
        When "grid"    Then grid = 1
        When "stripes" Then stripes = value
        Otherwise Nop
      End
    End
    q = tex~pos(nl, p)
    If q == 0 Then q = tex~length + 1
    tex = Left(tex, p - 1) || SubStr(tex, q + Length(nl))
    b = tex~pos("\begin{longtable}", p)
    e = tex~pos("\end{longtable}", p)
    f = tex~pos("\endlastfoot", p)
    If b == 0 | e == 0 | f == 0 | f > e | b > f Then Iterate  -- not a longtable
    Select
      When rules == "solid" | (rules == "" & grid) Then line = "\midrule"
      When rules == "dashed" Then line = "\rxruledashed{"n"}"
      When rules == "dotted" Then line = "\rxruledotted{"n"}"
      Otherwise line = ""
    End
    If grid, line == "\midrule" Then line = "\hline"
    head = SubStr(tex, b, f - b)
    If grid Then head = GridHead(head, nl, n)
    Else If stripes \== "" Then head = NoEdges(head, nl, 0)
    bodyStart = f + Length("\endlastfoot" || nl)
    out~append(Left(tex, b - 1), head, SubStr(tex, f, bodyStart - f))
    body = SubStr(tex, bodyStart, e - bodyStart)
    lines = body~makeArray(nl)
    -- The rows end where a line ends in "\\" outside any environment and
    -- brace: in a cell of several lines (Pandoc's minipage) a "\\" is a
    -- line break, and a \rowcolor or a rule there is an error, or worse
    -- (Rony, 22-Oct: LuaLaTeX hung on a table with .stripes rules=dotted)
    ends = RowEnds(lines)
    last = 0
    Do i = 1 To lines~items
      If ends[i] Then last = i
    End
    row = 1; starts = 1
    If stripes \== "" Then Do
      color = "rxstripe"stripes
      If \colors~hasItem(stripes) Then colors~append(stripes)
    End
    Do i = 1 To lines~items
      l = lines[i]
      If grid | stripes \== "", l~pos("\multicolumn{") > 0 Then
        If grid Then l = MultiColumns(l, 1, n + 1)
        Else         l = MultiColumns(l, 0, 0)
      If starts, stripes \== "", row // 2 == 0, l~strip \== "" Then l = "\rowcolor{"color"}"l
      If l~strip \== "" Then starts = 0
      If ends[i] Then Do
        If i < last, line \== "" Then l = l line
        row += 1; starts = 1
      End
      out~append(l, nl)
    End
    tex = SubStr(tex, e)
  End
  out~append(tex)
  tex = out~string
  If colors~items > 0 Then Do
    pre = "\usepackage{colortbl}"nl
    Do c Over colors
      pre ||= "\definecolor{rxstripe"c"}{HTML}{"c"}"nl
    End
    tex = tex~changeStr("\begin{document}", pre"\begin{document}", 1)
  End
  Return tex

-- Which lines of a longtable's body end a row: "\\" at the end, outside any
-- environment (\begin{minipage}...) and any brace
RowEnds: Procedure
  Use Strict Arg lines
  ends = .Array~new
  envs = 0; braces = 0
  Do i = 1 To lines~items
    l = lines[i]
    envs += l~countStr("\begin{") - l~countStr("\end{")
    t = l~changeStr("\\", "")~changeStr("\{", "")~changeStr("\}", "")
    braces += t~countStr("{") - t~countStr("}")
    ends[i] = l~strip("T")~right(2) == "\\" & envs <= 0 & braces <= 0
  End
  Return ends

-- The head of a longtable (from \begin{longtable} to \endlastfoot), with a
-- grid: bars in the column spec, \hline for booktabs' rules
GridHead: Procedure
  Use Strict Arg head, nl, n
  head = NoEdges(head, nl, n + 1)
  open = "\begin{longtable}[]{"
  p = head~pos(open)
  If p == 0 Then Return head
  s = p + Length(open)
  e = ColspecEnd(head, s)
  If e == 0 Then Return head
  spec = SubStr(head, s, e - s)
  new = "|"
  If spec~pos(nl) > 0 Then                    -- one p{} column a line
    Do part Over spec~makeArray(nl)
      If part~strip == "" Then Iterate
      new ||= nl || part~strip("T") || "|"
    End
  Else Do i = 1 To spec~length                -- "lll": a letter a column
    new ||= spec[i] || "|"
  End
  head = Left(head, s - 1) || new || SubStr(head, e)
  head = head~changeStr("\toprule", "\hline")~changeStr("\midrule", "\hline") -
    ~changeStr("\bottomrule", "\hline")
  Return head

-- Pandoc's longtable has no room at its edges (@{} ... @{}), and its p{}
-- columns share the width that is left. A coloured row (colortbl) and a grid
-- want that room: the colour of a cell overhangs it by \tabcolsep, and so went
-- out of the table. The edges get their room back, and the columns give it
-- (and the width of the bars of a grid, if any): the table is still as wide
-- as the text.
NoEdges: Procedure
  Use Strict Arg head, nl, bars
  open = "\begin{longtable}[]{"
  p = head~pos(open)
  If p == 0 Then Return head
  s = p + Length(open)
  e = ColspecEnd(head, s)
  If e == 0 Then Return head
  spec = SubStr(head, s, e - s)
  If spec~left(3) == "@{}" Then spec = SubStr(spec, 4)
  If spec~right(3) == "@{}" Then spec = Left(spec, spec~length - 3)
  Return Left(head, s - 1) || RoomInWidths(spec, bars) || SubStr(head, e)

-- The widths of p{} columns, with the room of the edges (and of the bars, if
-- any) taken from them. "(\columnwidth - 4\tabcolsep)" (Pandoc 3.1),
-- "(\linewidth - 4\tabcolsep)" (later Pandocs): whatever the width, the
-- number before \tabcolsep
RoomInWidths: Procedure
  Use Strict Arg spec, bars
  out = ""
  Loop
    t = spec~pos("\tabcolsep)")
    If t == 0 Then Leave
    o = spec~lastPos("(", t)
    Parse Value SubStr(spec, o + 1, t - o - 1) With width "-" k
    width = width~strip; k = k~strip
    If o == 0 | width~left(1) \== "\" | \k~dataType("W") Then Do
      out ||= Left(spec, t + 10); spec = SubStr(spec, t + 11); Iterate
    End
    room = "("width" - "k + 2"\tabcolsep"
    If bars > 0 Then room ||= " -" bars"\arrayrulewidth"
    out ||= Left(spec, o - 1) || room")"
    spec = SubStr(spec, t + 11)
  End
  Return out || spec

-- A cell that spans columns (Rony, 23-Oct): "\multicolumn{N}{SPEC}{...}".
-- Pandoc writes SPEC without room at the edges of the table (@{}), and, in
-- later versions, as a p{} of the widths it spans. When the table gets its
-- edges back (.stripes, .grid), so does the cell, and its width the room it
-- gives; with .grid, its bars: the one on its right, and the left one too
-- when it starts the row.
MultiColumns: Procedure
  Use Strict Arg line, grid, bars
  out = ""
  Loop
    p = line~pos("\multicolumn{")
    If p == 0 Then Leave
    q = line~pos("}{", p)
    If q == 0 Then Leave
    s = q + 2
    e = ColspecEnd(line, s)
    If e == 0 Then Leave
    spec = SubStr(line, s, e - s)
    first = spec~left(3) == "@{}"
    If first Then spec = SubStr(spec, 4)
    If spec~right(3) == "@{}" Then spec = Left(spec, spec~length - 3)
    spec = RoomInWidths(spec, bars)
    If grid Then Do
      -- a p{} cell spans the bars between its columns too (later Pandocs
      -- write "+ 2\tabcolsep}", the room between them)
      Parse Value SubStr(line, p + Length("\multicolumn{")) With span "}"
      If span~dataType("W"), span > 1 Then
        spec = spec~changeStr("\tabcolsep}", "\tabcolsep +" span - 1"\arrayrulewidth}")
      spec = spec"|"
      If first Then spec = "|"spec
    End
    out ||= Left(line, s - 1) || spec
    line = SubStr(line, e)
  End
  Return out || line

-- Where the column spec that starts at s ends (its closing brace)
ColspecEnd: Procedure
  Use Strict Arg text, s
  depth = 1
  Do i = s To text~length
    c = text[i]
    If c == "{" Then depth += 1
    Else If c == "}" Then Do
      depth -= 1
      If depth == 0 Then Return i
    End
  End
  Return 0

-- "[^n12]: text" becomes "[^n12]: []{#rxfn-n12}text": an anchor inside the
-- note, where a \label takes the note's number. Pandoc keeps no name for a
-- note, so this is the only place to give it one. Code fences are skipped.
NoteAnchors: Procedure
  Use Strict Arg md
  out   = .MutableBuffer~new
  fence = ""
  Do line Over md~makeArray("0a"x)
    s = Strip(line, "L")
    If fence == "" Then Do
      If s~left(3) == "```" | s~left(3) == "~~~" Then fence = s~left(3)
      Else If s~left(2) == "[^" Then Do      -- in a list item it is indented
        indent = Left(line, line~length - s~length)
        Parse Var s "[^" label "]:" rest
        ok = XRange("a", "z") || XRange("A", "Z") || XRange("0", "9") || "-_."
        If label \== "" & label~verify(ok) == 0 & s~pos("]:") == label~length + 3 Then
          line = indent"[^"label"]: []{#rxfn-"label"}"Strip(rest, "L")
      End
    End
    Else If s~left(3) == fence Then fence = ""
    out~append(line, "0a"x)
  End
  Return out~string

-- Only a document with Arabic or Hebrew text gets them (20-Oct: babel loads
-- the fonts of a provided language at \begin{document}, and a machine
-- without Noto Naskh Arabic stopped there, on a book in English). Each font
-- is asked for only if it is there; if not, a warning names it, and a
-- character that no font has is still an error (\tracinglostchars=3).
RTLLanguages: Procedure
  Use Strict Arg source
  If source~isA(.Array) Then text = source~makeString("L", "0a"x)
  Else text = source
  fonts = .Directory~new
  fonts["arabic"] = .Array~of("rm", "Noto Naskh Arabic", "sf", "Noto Sans Arabic", -
                              "tt", "Noto Sans Arabic")
  fonts["hebrew"] = .Array~of("rm", "Noto Serif Hebrew", "sf", "Noto Sans Hebrew", -
                              "tt", "Noto Sans Hebrew")
  ranges = .Directory~new
  ranges["arabic"] = "0600-06FF 0750-077F 08A0-08FF FB50-FDFF FE70-FEFF"
  ranges["hebrew"] = "0590-05FF FB1D-FB4F"
  out = ""
  Do lang Over .Array~of("arabic", "hebrew")
    If \HasCodepoints(text, ranges[lang]) Then Iterate
    out ||= "\babelprovide[import,onchar=ids fonts]{"lang"}" || "0a"x
    f = fonts[lang]
    Do i = 1 To f~items By 2
      family = f[i]; name = f[i + 1]
      out ||= "\IfFontExistsTF{"name"}%" || "0a"x || -
        "  {\babelfont["lang"]{"family"}[Renderer=HarfBuzz,Scale=MatchLowercase]{"name"}}%" || "0a"x || -
        "  {\PackageWarningNoLine{md2latex}{Font '"name"' not found: the" lang "text needs it}}" || "0a"x
    End
  End
  Return Strip(out, "T", "0a"x)

-- Does the UTF-8 text have a character in one of these ranges ("0590-05FF
-- FB1D-FB4F")? Only two- and three-byte characters are looked at (all the
-- ranges are below U+10000), and the text is skipped up to each lead byte.
HasCodepoints: Procedure
  Use Strict Arg text, ranges
  ascii = XRange("00"x, "BF"x)            -- not a lead byte of U+0080-FFFF
  at = 1
  Loop Forever
    at = Verify(text, ascii, "N", at)
    If at == 0 Then Return 0
    b1 = C2D(SubStr(text, at, 1))
    Select
      When b1 >= 224 & b1 < 240 Then Do   -- three bytes
        cp = (b1 - 224) * 4096 + (C2D(SubStr(text, at + 1, 1)) - 128) * 64 -
             + C2D(SubStr(text, at + 2, 1)) - 128
        at += 3
      End
      When b1 >= 192 & b1 < 224 Then Do   -- two bytes
        cp = (b1 - 192) * 64 + C2D(SubStr(text, at + 1, 1)) - 128
        at += 2
      End
      Otherwise
        at += 1
        Iterate
    End
    Do r Over ranges~makeArray(" ")
      Parse Var r lo "-" hi
      If cp >= X2D(lo) & cp <= X2D(hi) Then Return 1
    End
  End

-- The main fonts, each only if this machine has it: a missing one is a
-- warning, and Latin Modern (every TeX has it) takes its place. A font that
-- is loaded by file (acmart's Libertine, with Extension=) is not looked up
-- by name: it is set as it is.
SetFonts: Procedure
  Use Strict Arg f.
  out = SetFont("main", f.main, f.mainOptions, "rxserif", "", "Latin Modern Roman") || "0a"x || -
        SetFont("sans", f.sans, f.sansOptions, "rxsans",  "", "Latin Modern Sans")  || "0a"x || -
        SetFont("mono", f.mono, "",            "rxmono",  ",Scale=MatchLowercase", "Latin Modern Mono")
  Return out

SetFont: Procedure
  Use Strict Arg which, name, options, chain, after, standby
  set = "\set"which"font{"name"}["options"RawFeature={fallback="chain"}"after"]"
  If options~pos("Extension=") > 0 Then Return set
  Return "\IfFontExistsTF{"name"}{"set"}{%" || "0a"x || -
    "  \PackageWarningNoLine{md2latex}{Font '"name"' not found: "standby" used}%" || "0a"x || -
    "  \set"which"font{"standby"}[RawFeature={fallback="chain"}"after"]}"

--------------------------------------------------------------------------------
-- The Rexx code FencedCode wrote as HTML, rewritten as LaTeX:              --
--                                                                          --
--   
...
...
-- --
-> a raw LaTeX block: rxhlisting, \rxhL, \rxhT -- -- `...`{=html}-- -- -> a raw LaTeX inline: \rxhI -- -------------------------------------------------------------------------------- HTML2Latex: Procedure Use Strict Arg md, bare = 0 out = .MutableBuffer~new -- Blocks Do Forever p = md~pos('
1, md[q - 1] == "`"; q -= 1; End fence = SubStr(md, q, p - q) If fence == "" Then Do out~append(Left(md, p)); md = SubStr(md, p + 1); Iterate End e = md~pos(fence"{=html}", p) If e == 0 Then Do out~append(Left(md, p)); md = SubStr(md, p + 1); Iterate End chunk = SubStr(md, p, e - p) out~append(Left(md, q - 1)) out~append(InlineLatex(chunk, bare)) md = SubStr(md, e + Length(fence"{=html}")) End out~append(md) Return out~string -------------------------------------------------------------------------------- -- The grid tables whose cells hold Rexx made HTML (a listing, a mention): -- -- each cell rewritten as LaTeX on its own, and the table drawn again as wide -- -- as its cells now are (GridTables.cls). Rewriting the whole text at once -- -- changes the length of the lines of a cell, and a grid table whose "|" are -- -- no longer under its "+" is no table for Pandoc (Rony's Rosetta Stone). -- -------------------------------------------------------------------------------- TablesLatex: Procedure Use Strict Arg lines, bare i = 0 Loop While i < lines~items i += 1 If Strip(lines[i], "Leading")~left(1) \== "+" Then Iterate If \.GridTable~isBorder(lines, i) Then Iterate table = .GridTable~at(lines, i) If table == .Nil Then Do -- No table: none inside it either i = .GridTable~runEnd(lines, i) Iterate End changed = 0 Do cell Over table~cells text = cell~bare~makeString("L", "0a"x) If text~pos('class="highlight-rexx-') == 0 Then Iterate cell~setBare( HTML2Latex(text, bare)~makeArray("0a"x) ) changed = 1 End If \changed Then Do i = table~last Iterate End new = table~lines res = lines~section(1, table~first - 1) res~appendAll(new) res~appendAll(lines~section(table~last + 1)) lines = res i = table~first + new~items - 1 End Return lines -- Position just after the
that closes the
", i) If c == 0 Then Return Length(s) + 1 If o > 0, o < c Then Do depth += 1; i = o + 4 End Else Do depth -= 1; i = c + 6 If depth == 0 Then Return i End End StyleOf: Procedure Use Strict Arg chunk Parse Var chunk 'class="highlight-rexx-' style '"' Parse Var style style . Return style -- A listing: the box, one \rxhL per line, one \rxhT per token. The box goes -- in \rxdressbegin{code}{...}/\rxdressend, with the ground and the frame the -- fence asked for (data-rx-NAME): the Lua filter writes rxdress there, with -- the defaults of the YAML (rexxpub: blocks:), as for every other block. -- A line marked whole (spot=, Spots.cls) is \rxhLW (a wash) or \rxhLB (a -- box); a text, \rxhMW or \rxhMB around its tokens; ink and bold are the -- tokens' own colour and weight. BlockLatex: Procedure Use Strict Arg chunk, indent style = StyleOf(chunk) Parse Value .LaTeX.Highlighter~box(style) With fg bg Parse Var chunk '' caption = "" If divAttrs~pos('data-caption="') > 0 Then Parse Var divAttrs 'data-caption="' caption '"' dress = "" Do name Over .Array~of("background", "border", "border-width", "border-color") value = "" If divAttrs~pos(' data-rx-'name'="') > 0 Then Parse Var divAttrs ' data-rx-'(name)'="' value '"' dress ||= "|"Entities(value)~changeStr("|", "")~changeStr("}", "")~changeStr("{", "") End dress = SubStr(dress, 2) pens = PenColours(style) Parse Var chunk "" numbered = preAttrs~pos("rx-numbered") > 0 If numbered Then Do -- .numberLines: width and start Parse Var preAttrs "rx-w" width +1 . If \DataType(width, "W") Then width = 3 Parse Var chunk "--rx-start: " start ";" If \DataType(start, "W") Then -- HTML from before 20261018 Parse Var chunk "counter-reset: rx-line " start ";" If \DataType(start, "W") Then start = 0 number = start End Parse Var chunk "" code "" nl = "0a"x -- The longest line, in characters: a listing too wide for the page is set -- smaller (rxhlisting's optional argument), never wrapped if it can be helped maxWidth = 0 Do line Over Entities(StripTags(code))~makeArray(nl) maxWidth = Max(maxWidth, CharLength(line~changeStr("09"x, " "))) End If numbered Then maxWidth += width + 3 res = nl || indent"```{=latex}"nl res ||= indent"\rxdressbegin{code}{"dress"}"nl If caption \== "" Then res ||= indent"\rxcaption{"EscapeTeX(Entities(caption))"}"nl res ||= indent"\begin{rxhlisting}["maxWidth"]{"fg"}{"bg"}"nl raws = code~makeArray(nl) texts = .Array~new Do raw Over raws texts~append(Tokens(raw, style, "block", pens)) End -- The last line, when it has no text, is the end of the If texts~items > 0, texts[texts~last] == "" Then Do texts~delete(texts~last) raws~delete(raws~last) End Do i = 1 To raws~items raw = raws[i] line = texts[i] -- The line's own span: marked whole? mark = .Nil If raw~left(5) == "" If tag~pos("rx-spot-line") > 0 Then mark = MarkOf(tag, pens) End look = "" If mark \== .Nil Then look = mark~look If numbered Then Do number += 1 Select Case look When "wash" Then res ||= indent"\rxhLNW{"width"}{"number"}{"mark~bg"}{"mark~alpha"}{"mark~bar"}{"line"}"nl When "box", "ring" Then res ||= indent"\rxhLNB{"width"}{"number"}{"mark~bar"}{"mark~first"}{"mark~last"}{"line"}"nl Otherwise res ||= indent"\rxhLN{"width"}{"number"}{"line"}"nl End End Else Select Case look When "wash" Then res ||= indent"\rxhLW{"mark~bg"}{"mark~alpha"}{"mark~bar"}{"line"}"nl When "box", "ring" Then res ||= indent"\rxhLB{"mark~bar"}{"mark~first"}{"mark~last"}{"line"}"nl Otherwise res ||= indent"\rxhL{"line"}"nl End End res ||= indent"\end{rxhlisting}"nl res ||= indent"\rxdressend"nl res ||= indent"```"nl Return res -- A mark (Spots.cls), from the attributes of its span: a Directory with -- where (line or text), look (wash, ink, box, ring, or "" for bold only), -- bold, bar (the pen's colour, RRGGBB), bg and alpha (its wash: a colour and -- how much of it over the ground, in per cent), first and last (1 or 0) MarkOf: Procedure Use Strict Arg tag, pens Parse Var tag 'class="' classes '"' m = .Directory~new m~where = "text" m~look = "" m~bold = 0 m~first = 0 m~last = 0 pen = 1 Do c Over classes~makeArray(" ") Select Case c When "rx-spot-line" Then m~where = "line" When "rx-spot-wash" Then m~look = "wash" When "rx-spot-ink" Then m~look = "ink" When "rx-spot-box" Then m~look = "box" When "rx-spot-ring" Then m~look = "ring" When "rx-spot-bold" Then m~bold = 1 When "rx-spot-first" Then m~first = 1 When "rx-spot-last" Then m~last = 1 When "rx-spot-pen1", "rx-spot-pen2", "rx-spot-pen3", "rx-spot-pen4" Then pen = Right(c, 1) When "rx-spot-penx" Then pen = "x" Otherwise Nop End End If pen == "x" Then Do Parse Var tag "--rx-spot-line: #" hex ";" m~bar = Upper(Left(hex, 6)) m~bg = m~bar m~alpha = 40 End Else Do Parse Value pens[pen] With bar ":" bgc ":" alpha m~bar = bar m~bg = bgc m~alpha = alpha End Return m -- The four pens of a style, an Array of "BAR:BG:ALPHA" (RRGGBB, RRGGBB, per -- cent): the --spot-pen-N-bar and --spot-pen-N-bg of its style sheet, as -- md2slides uses them. A pen the sheet does not have gets the colours of the -- light style. PenColours: Procedure Use Strict Arg style key = "MD2LATEX.PENS."style pens = .local[key] If pens \== .Nil Then Return pens defaults = .Array~of("E8833C:FFC496:55", "34A96B:96E6BE:55", - "2E86DE:A0CDF5:55", "D8447F:FAAFCD:55") file = LocalStyleFile(style) If file == .Nil Then file = .File~new(.context~package~name)~parentFile~parent"/css/rexx-"style".css" css = "" If SysFileExists(file) Then Do css = CharIn(file, 1, Chars(file)) Call Stream file, "C", "Close" End pens = .Array~new Do n = 1 To 4 Parse Value defaults[n] With bar ":" bgc ":" alpha p = css~pos("--spot-pen-"n"-bar:") If p > 0 Then Do Parse Value SubStr(css, p) With ":" value ";" value = Strip(value) If value~left(1) == "#" Then Do h = SpotHex(value) If h \== "" Then bar = h End End p = css~pos("--spot-pen-"n"-bg:") If p > 0 Then Do Parse Value SubStr(css, p) With ":" value ";" Parse Var value "rgba(" r "," g "," b "," a ")" If r~strip~dataType("W"), g~strip~dataType("W"), b~strip~dataType("W"), - a~strip~dataType("N") Then Do bgc = D2X(r~strip, 2) || D2X(g~strip, 2) || D2X(b~strip, 2) alpha = Format(a~strip * 100, , 0) End End pens~append(bar":"bgc":"alpha) End .local[key] = pens Return pens -- The length of a UTF-8 string, in characters CharLength: Procedure Use Strict Arg s Return Length(s) - CountStr("80"x, s~translate(Copies("80"x, 64), xrange("80"x, "BF"x))) -- An inline mention -- (bare: rexxpub: mentions: background: none -- \rxhB, no ground) InlineLatex: Procedure Use Strict Arg chunk, bare = 0 style = StyleOf(chunk) Parse Value .LaTeX.Highlighter~box(style) With fg bg Parse Var chunk "" code "" -- A mention of one element (`DO`{.rexx keyword}) has its classes on the -- itself ("rexx rx-kw"): they are the token's (they were lost) If codeAttrs~pos('class="') > 0 Then Do Parse Var codeAttrs 'class="' classes '"' classes = Space(ChangeStr(" rexx ", " "classes" ", " ")) If classes \== "" Then code = ''code'' End tex = Tokens(code, style, "inline") plain = EscapeTeX(Entities(StripTags(code))) If bare Then latex = "\texorpdfstring{\rxhB{"fg"}{"tex"}}{"plain"}" Else latex = "\texorpdfstring{\rxhI{"fg"}{"bg"}{"tex"}}{"plain"}" -- The raw inline's own fence: longer than any run of backticks in it fence = "`" Do While latex~pos(fence) > 0; fence ||= "`"; End Return fence || latex || fence"{=latex}" -- The tokens of a : text in nested s. A span of a -- mark (rx-spot, Spots.cls) is not a token: the innermost one says how the -- token looks (pens: the listing's, from PenColours). Tokens: Procedure Use Strict Arg code, style, where, pens = (PenColours(style)) res = .MutableBuffer~new stack = .Array~new -- the classes of the open spans tags = .Array~new -- and their tags Do While code \== "" If code[1] == "<" Then Do Parse Var code "<" tag ">" code Select When tag~left(1) == "/" Then Do If Lower(Left(tag, 5)) == "/span", stack~items > 0 Then Do stack~delete(stack~last) tags~delete(tags~last) End End When Lower(Word(tag, 1)) == "span" Then Do classes = "" If tag~pos('class="') > 0 Then Parse Var tag 'class="' classes '"' stack~append(classes) tags~append(tag) End Otherwise Nop -- ,
... no text End Iterate End p = code~pos("<") If p == 0 Then p = Length(code) + 1 text = Entities(Left(code, p - 1)) code = SubStr(code, p) -- The token's classes, without the marks'; the innermost mark classes = "" mark = 0 Do i = 1 To stack~items If stack[i]~pos("rx-spot") > 0 Then mark = i Else classes ||= " "stack[i] End classes = Space(classes) -- blanks= / {.blanks}: the highlighter wraps each blank it marks in a -- span of its own (rx-blank-mark), and here it is the open box, U+2423, -- that header.tex draws (Rony, 25-Oct: blanks=all did nothing in a PDF) If classes~pos("blank-mark") > 0 Then text = text~changeStr(" ", "E290A3"x) token = .LaTeX.Highlighter~token(style, classes, text, where) If mark > 0 Then Do m = MarkOf(tags[mark], pens) If m~look == "ink" | m~bold Then token = Restyled(token, m) If m~where == "text" Then Select Case m~look When "wash" Then token = "\rxhMW{"m~bg"}{"m~alpha"}{"token"}" When "box", "ring" Then token = "\rxhMB{"m~bar"}{"m~first"}{"m~last"}{"token"}" Otherwise Nop End End res~append(token) End Return res~string -- A token in the pen's colour (ink) or in bold: \rxhT{flags/fg/bg}{text} Restyled: Procedure Use Strict Arg token, m If token~startsWith("\rxhT{") Then Do Parse Var token "\rxhT{" flags "/" fg "/" bg "}{" . text = SubStr(token, token~pos("}{") + 2) text = Left(text, Length(text) - 1) End Else Do flags = ""; fg = ""; bg = "" text = token End If m~look == "ink" Then fg = m~bar If m~bold, flags~pos("B") == 0 Then flags ||= "B" Return "\rxhT{"flags"/"fg"/"bg"}{"text"}" StripTags: Procedure Use Strict Arg s Do While s~pos("<") > 0 Parse Var s before "<" . ">" after s = before || after End Return s Entities: Procedure Use Strict Arg s If s~pos("&") == 0 Then Return s out = "" Do While s~pos("&") > 0 Parse Var s before "&" entity ";" rest out ||= before Select When entity == "lt" Then out ||= "<" When entity == "gt" Then out ||= ">" When entity == "amp" Then out ||= "&" When entity == "quot" Then out ||= '"' When entity == "apos" Then out ||= "'" When entity == "nbsp" Then out ||= "C2A0"x When entity~left(2)~upper == "#X" Then out ||= UTF8(SubStr(entity, 3)~x2d) When entity~left(1) == "#", DataType(SubStr(entity, 2), "W") Then out ||= UTF8(SubStr(entity, 2)) Otherwise out ||= "&"entity";" End s = rest End Return out || s UTF8: Procedure -- A code point, as UTF-8 Use Strict Arg n Select When n < 128 Then Return d2c(n) When n < 2048 Then Return d2c(192 + n % 64) || d2c(128 + n // 64) When n < 65536 Then Return d2c(224 + n % 4096) || d2c(128 + n % 64 // 64) || d2c(128 + n // 64) Otherwise Return d2c(240 + n % 262144) || d2c(128 + n % 4096 // 64) || - d2c(128 + n % 64 // 64) || d2c(128 + n // 64) End -- Text for normal LaTeX (not Verbatim) EscapeTeX: Procedure Use Strict Arg s out = .MutableBuffer~new Do i = 1 To Length(s) c = s[i] Select Case c When "\" Then out~append("\textbackslash{}") When "{" Then out~append("\{") When "}" Then out~append("\}") When "$" Then out~append("\$") When "&" Then out~append("\&") When "#" Then out~append("\#") When "%" Then out~append("\%") When "_" Then out~append("\_") When "^" Then out~append("\textasciicircum{}") When "~" Then out~append("\textasciitilde{}") Otherwise out~append(c) End End Return out~string -------------------------------------------------------------------------------- WriteFile: Procedure Use Strict Arg name, contents Call SysFileDelete name s = .Stream~new(name) s~open("Write Replace") s~charOut(contents) s~close Return FileContents: Procedure Use Strict Arg file s = .Stream~new(file) s~open("Read") contents = s~charIn(1, s~chars) s~close Return contents CheckDeps: Call Dep "pandoc -v", "pandoc" Call Dep "lualatex --version", "LuaLaTeX (texlive-luatex)" Do f Over .Array~of("TeX Gyre Termes", "DejaVu Sans Mono", "Noto Serif", - "Noto Sans Math", "Noto Serif CJK SC", "Noto Naskh Arabic") Call FontDep f End Return -- luaotfload-tool --find returns 0 whether it finds the font or not FontDep: .Error~CharOut("Checking font '"Arg(1)"'... ") Address COMMAND 'luaotfload-tool --find="'Arg(1)'"' - With Output Stem o. Error Stem e. found = 0 Do i = 1 To o.0; If o.i~pos("Resolved file name") > 0 Then found = 1; End Do i = 1 To e.0; If e.i~pos("Resolved file name") > 0 Then found = 1; End If found Then .Error~Say(check) Else .Error~Say(fail) Return Dep: .Error~CharOut("Checking" Arg(2)"... ") Address COMMAND Arg(1) With Output Stem discard. Error Stem discard. If rc \== 0 Then .Error~Say(fail) Else .Error~Say(check) Return Error: .Error~Say(Arg(1)) Exit 1 Help: Say .Resources[Help]~makeString - ~caselessChangeStr("myName", myName) - ~caselessChangeStr("myHelp", myHelp) Exit 1 -------------------------------------------------------------------------------- -- The colours of the default style, for code that is not Rexx -- -------------------------------------------------------------------------------- ::Routine ListingWord -- (20261102) "Listing" in the language Use Strict Arg language words = .Directory~of( ("en", "Listing"), ("es", "Listado"), - ("fr", "Listing"), ("de", "Listing"), ("it", "Listato"), - ("pt", "Listagem"), ("nl", "Listing"), ("ca", "Llistat"), - ("gl", "Listaxe") ) word = words[Lower(Left(language, 2))] If word == .Nil Then Return "Listing" Return word ::Routine DefaultBox Use Strict Arg style Parse Value .LaTeX.Highlighter~box(style) With fg bg Return "{"fg"}{"bg"}" ::Resource Help End "::End" myname -- A RexxPub article or book (Markdown) to LaTeX, for LuaLaTeX Usage: [rexx] myname [OPTIONS] FILE.md Writes FILE.tex next to FILE.md (or the file given with -o). With --pdf, runs LuaLaTeX on it too: FILE.pdf. The LaTeX needs LuaLaTeX: Unicode text in any script is set with a chain of fallback fonts, right-to-left scripts in their direction, and a character that no font has is an error (with --pdf, myname lists them). Options: --check-deps Check that Pandoc, LuaLaTeX and the fonts are there --class NAME The LaTeX document class: article (default), llncs, IEEEtran, acmart or book (docclass: book in the YAML) --csl NAME|PATH The Citation Style Language style (default: rexxpub; csl: in the front matter wins) --default OPTIONS Default options for Rexx code blocks -exp, --experimental Enable Experimental features for all code blocks --filter FILE One more Lua filter, after md2latex's --header FILE More LaTeX for the preamble, after md2latex's -h, --help Display this help -it, --itrace Print internal traceback on error --keep Keep the intermediate files (Markdown, header) --line-numbers Number the lines of the text, page by page, for the proofreaders (latex: line-numbers: yes) --listings Code that is not Rexx with listings (latex: code:) -o, --output FILE The LaTeX file to write --pandoc-highlighting-style NAME Pandoc's style for code that is not Rexx (pygments) --pdf Run LuaLaTeX too --style NAME|FILE The visual theme for Rexx code (default: light) -u, --tutor, --unicode Enable TUTOR-flavoured Unicode for all code blocks -xtr, --executor Enable Executor support for all code blocks The 'myname' program is part of the Rexx Parser package, see https://rexx.epbcn.com/rexx-parser/. It is distributed under the Apache 2.0 License (https://www.apache.org/licenses/LICENSE-2.0). Copyright (c) 2024-2026 Josep Maria Blasco . See myhelp for details. ::End ::Requires "rexxpub/SearchPath.cls" -- First: bin/ in REXX_PATH (parser) ::Requires "parser/BaseClassesAndRoutines.cls" ::Requires "parser/ErrorHandler.cls" ::Requires "parser/CLISupport.cls" ::Requires "parser/FencedCode.cls" ::Requires "rexxpub/NearMisses.cls" ::Requires "rexxpub/YAMLFrontMatter.cls" ::Requires "rexxpub/RexxPubOptions.cls" ::Requires "parser/StyleSheet.cls" ::Requires "rexxpub/Spots.cls" ::Requires "rexxpub/GridTables.cls"