% ---------------------------------------------------------------------------
% md2latex header (RexxPub). Included after Pandoc's own preamble.
% Needs LuaLaTeX: fonts, Unicode fallbacks and bidi are LuaTeX features.
% ---------------------------------------------------------------------------
\ifdefined\directlua\else
  \errmessage{This document needs LuaLaTeX (it was generated by md2latex)}
\fi

% A character that no font has is an error, not a blank: never lose text.
\tracinglostchars=3

% --- Fonts ------------------------------------------------------------------
% The main fonts, and the fonts that supply what they lack. A character is
% taken from the first font of the chain that has it. Only the fonts this
% machine has are in a chain (12-Oct: TeX Live on Windows has no NotoMusic
% nor NotoSansEthiopic, and a font of the chain that is not there was loaded
% at size 0 under the scaled code font: "invalid font identifier"). A
% character that only a missing font had is still an error, and said.
% (No hash, tilde or per cent in this Lua: they are TeX's here.)
\directlua{
  local function present(list)
    local find = fonts and fonts.names and fonts.names.lookup_font_name
    local out = {}
    for _, spec in ipairs(list) do
      local name = spec:match("^[^:]+")
      local keep = true
      if find then
        local ok, path = pcall(find, { name = name:lower(), specification = name, lookup = "name" })
        if ok and not path then keep = false end
      end
      if keep then table.insert(out, spec) end
    end
    return out
  end
  luaotfload.add_fallback("rxserif", present({
%RXSERIFCHAIN%
  }))
  luaotfload.add_fallback("rxsans", present({
%RXSANSCHAIN%
  }))
  luaotfload.add_fallback("rxmono", present({
%RXMONOCHAIN%
  }))
}
% A main font this machine does not have is a warning, not a fatal error:
% Latin Modern, which every TeX has, takes its place (20-Oct: MiKTeX on
% Windows had no TeX Gyre Termes nor Heros, and the run stopped there).
%RXSETFONTS%
% (Without unicode-math, as with acmart and its newtxmath, the class's math)
\ifdefined\setmathfont
  \IfFontExistsTF{%RXMATHFONT%}{\setmathfont{%RXMATHFONT%}}{}
\fi

% --- Visible blanks ------------------------------------------------------------
% U+2423 (the open box for a blank) is drawn, as RexxPub draws it in HTML:
% strokes .045em thick, as wide as a character of the font in use, a little
% under the baseline. The fonts that have the glyph draw it as heavy as the
% letters, or heavier (Rony, 20-Oct). Copying the PDF gives a blank.
\usepackage{newunicodechar}
\newlength{\rxblankw}
\newcommand{\rxblankglyph}{\leavevmode\begingroup
  \settowidth{\rxblankw}{x}%
  \lower.12em\hbox to\rxblankw{\hss
    \vrule width .045em height .3em depth 0pt
    \vrule width \dimexpr .75\rxblankw - .09em\relax height .045em depth 0pt
    \vrule width .045em height .3em depth 0pt\hss}%
  \endgroup}
\newunicodechar{␣}{\rxblankglyph}

% --- Languages and directions ------------------------------------------------
% Right-to-left text (Arabic, Hebrew...) is found by its characters and set in
% its direction and its font, whatever language the document is in.
\usepackage[bidi=basic]{babel}
\babelprovide[main,import]{%RXLANGUAGE%}
%RXOTHERLANGUAGES%
\usepackage{csquotes}

% --- Page -------------------------------------------------------------------
% (paper, margins, size and link colours are Pandoc variables: md2latex
% sets them; hyperref is loaded by Pandoc's template after this header)
\usepackage{xcolor}
\usepackage{booktabs}     % also for the float tables of two-column classes
\definecolor{rxlink}{HTML}{00529B}
% A line under each row of a table, dashed or dotted (rules= on its :::;
% solid is booktabs' \midrule): a row of its own across the table's #1
% columns, that is only as tall as the line.
\newcommand{\rxruledashed}[1]{\noalign{\vskip\aboverulesep}%
  \multispan{#1}\xleaders\hbox to .6em{\hss\vrule width .35em height .04em\hss}\hfill\\%
  \noalign{\vskip\belowrulesep}}
\newcommand{\rxruledotted}[1]{\noalign{\vskip\aboverulesep}%
  \multispan{#1}\xleaders\hbox to .3em{\hss\vrule width .06em height .06em\hss}\hfill\\%
  \noalign{\vskip\belowrulesep}}

% --- Inline -----------------------------------------------------------------
% <small>HTML</small>, an acronym, becomes small capitals; any other
% <small> (a sentence, perhaps with links and notes) is small print.
\providecommand{\rxsmall}[1]{\textsc{\MakeLowercase{#1}}}
\providecommand{\rxsmallprint}[1]{{\small #1}}
\providecommand{\rxkbd}[1]{\fbox{\footnotesize\ttfamily #1}}
\usepackage[soul]{lua-ul}     % same options as Pandoc's, for ~~strike~~
\providecommand{\rxstrike}[1]{\st{#1}}

% --- Epigraph ----------------------------------------------------------------
\newenvironment{rxepigraph}
  {\par\vspace{1.5em}\begin{list}{}{\leftmargin=6em\rightmargin=1em}%
   \item\relax\small\noindent\ignorespaces}
  {\end{list}\vspace{1em}\par}
\providecommand{\rxattribution}[1]{\par\vspace{0.3em}{\raggedleft #1\par}}

% --- Rexx code --------------------------------------------------------------
% The prolog of the Rexx Highlighter's LaTeX driver (rexxpub/Latex.Driver.cls,
% what highlight --latex --prolog writes): a listing is rxhlisting, a box with
% the background of its style that can break across pages, each line \rxhL
% (\rxhLN when numbered), each token \rxhT{flags/fg/bg}{text}, each blank \rxhs.
% A mention is \rxhI{fg}{bg}{tokens}. Plain TeX, not verbatim: listings work
% anywhere (lists, notes, quotes).
%RXPROLOG%
% For the code that is not Rexx (the Lua filter), the book's program output and
% the documents' own headers: the names md2latex used before, with the colours
% of the default style (the second argument of rxblock is kept, and not used).
\let\rxs\rxhs
\let\rxsp\rxhsp
\let\rxL\rxhL
\let\rxLN\rxhLN
\let\rxcw\rxhcw
\makeatletter\let\rxcode\rxh@code\let\rxfit\rxh@fit\makeatother
% A mention on no ground (rexxpub: mentions: background: none; Rony, 26-Oct:
% keywords in the text as in the code, without so many grounds): \rxhI
% without its box, in the colour of the style's text
\makeatletter
\protected\def\rxhB#1#2{{\rxh@code\color[HTML]{#1}#2}}
\makeatother
% scale= on a ::: block or a [span] (Rony, 23-Oct, as in md2slides): its
% text, and its code, that much bigger or smaller; scales multiply when they
% nest. Listings are \small times the scale they are in.
\makeatletter
\def\rx@scale{1}
\newcommand\rxsetscale[1]{\edef\rx@scale{\fpeval{\rx@scale*(#1)}}%
  \fontsize{\fpeval{\f@size*(#1)}}{\fpeval{\f@baselineskip*(#1)}}\selectfont}
\newenvironment{rxscale}[1]{\rxsetscale{#1}}{}
\newcommand\rxscaled{\ifdim\rx@scale pt=1pt\else
  \fontsize{\fpeval{\f@size*\rx@scale}}{\fpeval{\f@baselineskip*\rx@scale}}\selectfont\fi}
\renewcommand\rxhfont{\small\rxscaled}
\makeatother
\definecolor{rxfg@1}{HTML}{%RXFG%}
\definecolor{rxbg@1}{HTML}{%RXBG%}
\newenvironment{rxblock}[2][0]
  {\begin{rxhlisting}[#1]%RXBOX%}{\end{rxhlisting}}
% A listing's caption (caption= on the fence), numbered. The word is
% listings: label:, or "Listing" in the document's lang: (20261102: it was
% always "Listing")
\newcounter{rxlisting}
\providecommand{\rxlistingname}{%RXLISTINGNAME%}
\newcommand{\rxcaption}[1]{\par\refstepcounter{rxlisting}\vspace{0.6em}%
  \noindent{\small\textbf{\rxlistingname~\therxlisting.} #1}\par\nobreak\vspace{-0.4em}}

% --- The ground and the frame of a block -----------------------------------
% background=, border=, border-width=, border-color= on a fence, or rexxpub:
% blocks: in the YAML (Rony, 25-Oct). The Lua filter puts each block in
% rxdress: #1 its ground (RRGGBB, or empty: the style's), #2 the colour of
% its frame (or empty), #3 more options for the box (tcolorbox's: boxrule=,
% borderline=...). A Rexx listing, code that is not Rexx and program output
% are boxes of the highlighter (rxhlisting), which takes them; Pandoc's own
% code (an article's) goes in rxframe, a box of the same kind.
\makeatletter
\def\rxh@groundname{rxh@bg}
\newenvironment{rxdress}[3]
  {\ifx\relax#1\relax\else
     \definecolor{rxd@bg}{HTML}{#1}\def\rxh@groundname{rxd@bg}%
     \tcbset{rxh/.append style={colback=rxd@bg}}%
   \fi
   \ifx\relax#2\relax\else\definecolor{rxd@frame}{HTML}{#2}\fi
   \tcbset{rxh/.append style={#3}}}
  {}
\newenvironment{rxframe}[3]
  {\ifx\relax#1\relax\definecolor{rxd@bg}{HTML}{FFFFFF}\else
     \definecolor{rxd@bg}{HTML}{#1}\colorlet{shadecolor}{rxd@bg}\fi
   \ifx\relax#2\relax\else\definecolor{rxd@frame}{HTML}{#2}\fi
   \begin{tcolorbox}[breakable, enhanced jigsaw, boxrule=0pt, arc=0pt,
     left=0pt, right=0pt, top=0pt, bottom=0pt, before skip=0.6em,
     after skip=0.8em, colback=rxd@bg, #3]}
  {\end{tcolorbox}}

% A listing in the cell of a table (Rony's Rosetta Stone, 26-Oct): a box in
% the line, its top on the top of the cell, so that it starts where the text
% of the next cell does (a box that breaks hangs from its bottom, and pushed
% the other cells down). A cell does not break across pages, so neither does
% a listing in it. A cell is a group: only its listings.
\newcommand\rxincell{\tcbset{rxh/.append style={unbreakable, nobeforeafter, box align=top}}}

% --- Marks (spot=: every beat at once) --------------------------------------
% The highlighter marks a Rexx listing (Spots.cls), the Lua filter the rest
% (cgi/spots.lua). A text: \rxhMW{BG}{A}{text}, a wash of BG at A per cent
% over the ground; \rxhMB{BAR}{F}{L}{text}, a frame in the pen's colour,
% with its left side if F is 1 and its right side if L is 1 (a text that goes
% through several tokens is several pieces). A whole line: \rxhLW{BG}{A}{BAR}
% {line} (a wash, and the pen's bar on its left) and \rxhLB{BAR}{F}{L}{line}
% (a frame, its top on the first line of a run and its bottom on the last);
% \rxhLNW and \rxhLNB with the number of the line before (width, number).
% Ink and bold are the tokens' own colour and weight. Nothing moves: the
% frames and the bar are drawn over the text's room, or in the box's margin.
\newlength\rxh@mf \setlength\rxh@mf{.6pt}
\newcommand\rxh@wash[2]{\definecolor{rxh@pen}{HTML}{#1}%
  \colorlet{rxh@washc}{rxh@pen!#2!\rxh@groundname}}
\newcommand\rxhMW[3]{\begingroup\rxh@wash{#1}{#2}\setlength{\fboxsep}{0pt}%
  \colorbox{rxh@washc}{\strut#3}\endgroup}
\newcommand\rxhMB[4]{\begingroup\definecolor{rxh@pen}{HTML}{#1}%
  \sbox\z@{\strut#4}\leavevmode\rlap{\color{rxh@pen}%
    \rlap{\rule[-\dp\z@]{\wd\z@}{\rxh@mf}}%
    \rlap{\rule[\dimexpr\ht\z@-\rxh@mf\relax]{\wd\z@}{\rxh@mf}}%
    \ifnum#2=1 \rlap{\rule[-\dp\z@]{\rxh@mf}{\dimexpr\ht\z@+\dp\z@\relax}}\fi
    \ifnum#3=1 \rlap{\hbox to\wd\z@{\hss\rule[-\dp\z@]{\rxh@mf}{\dimexpr\ht\z@+\dp\z@\relax}}}\fi}%
  \usebox\z@\endgroup}
% A line as \rxhL sets it, in a box #1 wide (it goes on in the next line,
% indented, when it is too long)
\newcommand\rxh@linebox[2]{\parbox[t]{#1}{\raggedright\setlength{\parindent}{0pt}%
  \hyphenpenalty=10000\exhyphenpenalty=10000\relax
  \hangindent=3\rxhcw\hangafter=1\strut#2\strut}}
\newcommand\rxh@lwash[5]{% width, bg, alpha, bar, line
  \rxh@wash{#2}{#3}\definecolor{rxh@bar}{HTML}{#4}%
  \sbox\z@{\rxh@linebox{#1}{#5}}%
  \llap{\textcolor{rxh@bar}{\rule[-\dp\z@]{1.5pt}{\dimexpr\ht\z@+\dp\z@\relax}}}%
  {\setlength{\fboxsep}{0pt}\colorbox{rxh@washc}{\usebox\z@}}}
\newcommand\rxh@lbox[5]{% width, bar, first, last, line
  \definecolor{rxh@bar}{HTML}{#2}%
  \sbox\z@{\rxh@linebox{#1}{#5}}%
  \rlap{\color{rxh@bar}%
    \llap{\rule[-\dp\z@]{\rxh@mf}{\dimexpr\ht\z@+\dp\z@\relax}}%
    \rlap{\hbox to\wd\z@{\hss\rlap{\rule[-\dp\z@]{\rxh@mf}{\dimexpr\ht\z@+\dp\z@\relax}}}}%
    \ifnum#3=1 \rlap{\kern-\rxh@mf\rule[\dimexpr\ht\z@-\rxh@mf\relax]{\dimexpr\wd\z@+2\rxh@mf\relax}{\rxh@mf}}\fi
    \ifnum#4=1 \rlap{\kern-\rxh@mf\rule[-\dp\z@]{\dimexpr\wd\z@+2\rxh@mf\relax}{\rxh@mf}}\fi}%
  \usebox\z@}
% Each line a paragraph of one box: the boxes of a run touch
\newcommand\rxh@lpar[1]{\par\begingroup\lineskip=0pt\lineskiplimit=0pt
  \noindent#1\par\endgroup}
\newcommand\rxh@lnum[2]{\makebox[#1\rxhcw][r]{\textcolor{rxhgutter}{#2}}%
  \hspace{4pt}{\color{rxhgutter}\vrule}\hspace{4pt}}
\newcommand\rxh@lrest[1]{\dimexpr\linewidth-#1\rxhcw-8pt-0.4pt\relax}
\newcommand\rxhLW[4]{\rxh@lpar{\rxh@lwash{\linewidth}{#1}{#2}{#3}{#4}}}
\newcommand\rxhLB[4]{\rxh@lpar{\rxh@lbox{\linewidth}{#1}{#2}{#3}{#4}}}
\newcommand\rxhLNW[6]{\rxh@lpar{\rxh@lnum{#1}{#2}\rxh@lwash{\rxh@lrest{#1}}{#3}{#4}{#5}{#6}}}
\newcommand\rxhLNB[6]{\rxh@lpar{\rxh@lnum{#1}{#2}\rxh@lbox{\rxh@lrest{#1}}{#3}{#4}{#5}{#6}}}
\makeatother

% --- Code that is not Rexx ---------------------------------------------------
% Pandoc's: highlighted (its Highlighting environment, with highlight-style:)
% or not (a fence with no language: verbatim). Both are fancyvrb Verbatims
% here, through fvextra, and a line too long for the page goes on in the next
% one instead of out of the page. With latex: code: listings (--listings),
% Pandoc writes lstlisting, and listings breaks the lines.
\usepackage{fvextra}
\fvset{breaklines=true, breaksymbolleft={}, breakindent=1.5em}   % as the Rexx box
\RecustomVerbatimEnvironment{verbatim}{Verbatim}{}
\ifdefined\lstset
  \lstset{basicstyle=\ttfamily, breaklines=true, columns=fullflexible,
    keepspaces=true, showstringspaces=false, upquote=true}
\fi
% ---------------------------------------------------------------------------
