-------------------------------------------------------------------------------- -- -- -- rexxpub.lua - Pandoc Lua filter: RexxPub Markdown conventions to LaTeX -- -- ====================================================================== -- -- -- -- 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) -- -- -- -- Version history: -- -- -- -- Date Version Details -- -- -------- ------- --------------------------------------------------------- -- -- 20261010 0.7 First version (md2latex) -- -- 20261011 Books: parts, matters, lists, index, captioned divs, -- -- cross-references, code that is not Rexx -- -- 20261011 acmart (ACM): authors, keywords; ::: city and ::: country -- -- 20261011 as small print (not an acronym);
 blocks     --
-- 20261012         
 without the HTML reader (Pandoc 3.11)               --
--                                                                            --
-- 20261021         Tables: balanced by default; .grid, .stripes (% rxtable)  --
-- 20261025         Marks (spot=, every beat at once) on output and code that --
--                  is not Rexx; the ground and frame of every block          --
--                  (rxdress, rxframe; cgi/spots.lua); {.newpage} on any :::  --
-- 20261026         A cell that holds a listing or a block of code is as wide --
--                  as its longest line asks (cell_len; the Rosetta Stone)    --
-- 20261026         Books: code in a language Pandoc knows, highlighted; code --
--                  and output with .numberLines, numbered (Rony)             --
-- 20261102         Books: the title as md2pdf writes it too ("# [T]{.book-   --
--                  title}"; the book stayed in \frontmatter); .toc-exclude   --
--                  keeps a heading out of the contents                       --
-- 20261102         caption= on code that is not Rexx; a span's style= is     --
--                  said, not dropped in silence                              --
-- 20261102         A table's ::: is read in any class (cols=, rules=, .grid, --
--                  .stripes: only a book's ::: {.table} was); an article's   --
--                  ::: {#id .table} numbers its caption and labels it        --
-- 20261102         Books: .ref-chapter is the number of the chapter the      --
--                  target is in (it was .ref-num again)                      --
-- 20261102         Code in the text shows its blanks (.blanks, blanks=all,   --
--                  blanks=data; `x`{.out .blanks} too), as on a page         --
--------------------------------------------------------------------------------
--                                                                            --
-- Used by md2latex.rex. A RexxPub article is written for the HTML pipelines: --
-- its title page is a set of fenced divs, it uses a few inline HTML tags     --
-- (, ...), and some divs carry a meaning that the CSS gives      --
-- them (epigraph, quotation, noindent). Pandoc's LaTeX writer drops raw      --
-- HTML and ignores the classes, so this filter gives each of them its LaTeX  --
-- form. Anything HTML it does not know is reported, never dropped silently.  --
--                                                                            --
-- The title page goes to the metadata (title, subtitle, date, author), in    --
-- the shape the document class wants: "rexxpub-class" in the metadata says   --
-- which one (md2latex sets it). The authors are written as raw LaTeX.        --
--                                                                            --
--------------------------------------------------------------------------------

local class = "article"
local twocolumn_meta = false            -- md2latex says: two columns
local header_file = nil
local warned = {}

local function warn(msg)
  if not warned[msg] then
    warned[msg] = true
    io.stderr:write("md2latex: " .. msg .. "\n")
  end
end

-- Blanks, and what is not a blank, in ASCII. Lua's %s, %a, %w and %l follow
-- the C locale, and Pandoc on Windows runs under the system's code page: in
-- 1252, byte A0 is a blank, so "%S+" split a no-break space (C2 A0) or an
-- "à" (C3 A0) in two, and utf8.len failed on the halves (Rony, 21-Oct: a
-- table of his book stopped md2latex). The same with "%s+$" at the end of
-- an "à" ate half of it.
local WS, NONWS = "[ \t\n\r\f\v]", "[^ \t\n\r\f\v]"

-- Marks (spot=) and the ground and frame of the blocks: the rules are those
-- of the HTML outputs, in cgi/spots.lua
local spots = dofile(pandoc.path.join({ pandoc.path.directory(PANDOC_SCRIPT_FILE),
  "..", "..", "cgi", "spots.lua" }))
local doc_blocks = nil                  -- rexxpub: blocks: (spots.defaults)
local pens = {                          -- md2latex says: the style's (rexxpub-pens)
  { bar = "E8833C", bg = "FFC496", a = "55" }, { bar = "34A96B", bg = "96E6BE", a = "55" },
  { bar = "2E86DE", bg = "A0CDF5", a = "55" }, { bar = "D8447F", bg = "FAAFCD", a = "55" },
}

local function latex(s) return pandoc.RawInline("latex", s) end
local function latexb(s) return pandoc.RawBlock("latex", s) end

-- Inlines rendered as LaTeX (for the parts of the title we write by hand).
local function tex(inlines)
  local doc = pandoc.Pandoc({ pandoc.Plain(inlines) })
  local out = pandoc.write(doc, "latex")
  return (out:gsub(WS .. "+$", ""))
end

local function blockstex(blocks)
  local out = pandoc.write(pandoc.Pandoc(blocks), "latex")
  return (out:gsub(WS .. "+$", ""))
end

--------------------------------------------------------------------------------
-- Inline HTML tags: X and friends become Spans, then LaTeX.   --
--------------------------------------------------------------------------------

local pairs_known = {
  small = { "\\rxsmall{", "}" },
  sup   = { "\\textsuperscript{", "}" },
  sub   = { "\\textsubscript{", "}" },
  b     = { "\\textbf{", "}" },
  strong= { "\\textbf{", "}" },
  i     = { "\\textit{", "}" },
  em    = { "\\emph{", "}" },
  u     = { "\\underline{", "}" },
  kbd   = { "\\rxkbd{", "}" },
  code  = { "\\texttt{", "}" },
  s     = { "\\rxstrike{", "}" },
  del   = { "\\rxstrike{", "}" },
  abbr  = { "", "" },
  cite  = { "\\textit{", "}" },
  q     = { "\\enquote{", "}" },
  span  = { "", "" },
}

local function tagof(raw)
  local close, name = raw:match("^<" .. WS .. "*(/?)" .. WS .. "*([A-Za-z][A-Za-z0-9]*)")
  if not name then return nil end
  return name:lower(), close == "/"
end

--  has two uses in RexxPub: an acronym (HTML), which
-- becomes small capitals, and small print (a sentence, a caption, perhaps
-- with links and footnotes), which becomes \small. An acronym is a single
-- word with no lowercase letters; anything else is small print.
local function small_is_acronym(inls, i)
  local depth, text = 0, ""
  for j = i + 1, #inls do
    local el = inls[j]
    if el.t == "RawInline" and el.format == "html" then
      local name, closing = tagof(el.text)
      if name == "small" then
        if closing then
          if depth == 0 then
            return text ~= "" and not text:find("[a-z]")
          end
          depth = depth - 1
        else
          depth = depth + 1
        end
      end
      if name ~= "small" then return false end
    elseif el.t == "Str" then
      text = text .. el.text
    else
      return false                       -- a space, a note, a link...
    end
  end
  return false
end

local function fix_inlines(inls)
  local out = pandoc.List()
  local stack = {}
  for i, el in ipairs(inls) do
    local handled = false
    if el.t == "RawInline" and el.format == "html" then
      local name, closing = tagof(el.text)
      if name == "small" and not closing
        and not small_is_acronym(inls, i) then
        out:insert(latex("\\rxsmallprint{")); handled = true
      elseif name == "br" then
        out:insert(pandoc.LineBreak()); handled = true
      elseif name == "wbr" then
        out:insert(latex("\\allowbreak{}")); handled = true
      elseif name and pairs_known[name] then
        local p = pairs_known[name]
        out:insert(latex(closing and p[2] or p[1])); handled = true
      elseif el.text:match("^: before is the title, inside the subtitle.
local function split_title(inls)
  local title, sub = pandoc.List(), pandoc.List()
  local into = title
  for _, el in ipairs(inls) do
    if el.t == "RawInline" and el.format == "html" then
      local name, closing = tagof(el.text)
      if name == "small" then
        into = closing and title or sub
        goto continue
      end
    end
    into:insert(el)
    ::continue::
  end
  while #title > 0 and (title[#title].t == "Space" or title[#title].t == "SoftBreak") do
    title:remove(#title)
  end
  return title, sub
end

local function div_text(div)
  -- The inlines of a one-paragraph div; several paragraphs are joined by \\.
  local parts = {}
  for _, b in ipairs(div.content) do
    if b.t == "Para" or b.t == "Plain" then
      table.insert(parts, tex(fix_inlines(b.content)))
    end
  end
  return table.concat(parts, "\\\\ ")
end

-- The authors, as the document class wants them. Each author is a table
-- with name, affiliation, address, email and phone (all LaTeX already).
local function authors_article(list)
  local out = pandoc.List()
  for _, a in ipairs(list) do
    local lines = { a.name }
    if a.affiliation then table.insert(lines, a.affiliation) end
    if a.address then table.insert(lines, a.address) end
    if a.email then table.insert(lines, "\\texttt{" .. a.email .. "}") end
    if a.phone then table.insert(lines, a.phone) end
    out:insert(table.concat(lines, " \\\\ "))
  end
  return out, nil
end

-- llncs: \author{A\inst{1} \and B\inst{2}} and \institute{...\and...}.
-- Authors of the same institution (same affiliation and address) share it.
local function authors_llncs(list)
  local out, inst, index = pandoc.List(), {}, {}
  for _, a in ipairs(list) do
    local lines = {}
    if a.affiliation then table.insert(lines, a.affiliation) end
    if a.address then table.insert(lines, a.address) end
    local key = table.concat(lines, " \\\\ ")
    local n = index[key]
    if not n then
      table.insert(inst, { text = key, emails = {} })
      n = #inst
      index[key] = n
    end
    if a.email then table.insert(inst[n].emails, a.email) end
    out:insert(a.name .. (#list > 1 and ("\\inst{" .. n .. "}") or ""))
  end
  local parts = {}
  for _, i in ipairs(inst) do
    local t = i.text
    if #i.emails > 0 then
      t = t .. (t ~= "" and " \\\\ " or "") .. "\\email{" .. table.concat(i.emails, ", ") .. "}"
    end
    table.insert(parts, t)
  end
  return out, "\\institute{" .. table.concat(parts, " \\and ") .. "}"
end

-- IEEEtran: \IEEEauthorblockN{name}\IEEEauthorblockA{affiliation...}
local function authors_ieee(list)
  local out = pandoc.List()
  for _, a in ipairs(list) do
    local lines = {}
    if a.affiliation then table.insert(lines, a.affiliation) end
    if a.address then table.insert(lines, a.address) end
    if a.email then table.insert(lines, a.email) end
    if a.phone then table.insert(lines, a.phone) end
    out:insert("\\IEEEauthorblockN{" .. a.name .. "}" ..
      (#lines > 0 and ("\\IEEEauthorblockA{" .. table.concat(lines, " \\\\ ") .. "}") or ""))
  end
  return out, nil
end

-- acmart: each author complete, \author{name}\affiliation{...}\email{...}.
-- The affiliation is \institution, \city and \country (ACM prints no more):
-- ::: affiliation, ::: city (or, without it, ::: address) and ::: country.
local function oneline(s) return (s:gsub(" \\\\ ", ", ")) end
local function authors_acm(list)
  local out = pandoc.List()
  for _, a in ipairs(list) do
    local s = "\\author{" .. a.name .. "}"
    local city = a.city or a.address
    if a.city and a.address then
      warn("acmart: the address is left out (ACM prints the city and the country)")
    end
    if a.affiliation or city or a.country then
      local aff = {}
      if a.affiliation then
        table.insert(aff, "\\institution{" .. oneline(a.affiliation) .. "}")
      else
        warn("acmart: an author has no ::: affiliation (\\institution)")
      end
      if city then
        table.insert(aff, "\\city{" .. oneline(city) .. "}")
      else
        warn("acmart: an affiliation has no ::: city (ACM wants one)")
      end
      if a.country then
        table.insert(aff, "\\country{" .. oneline(a.country) .. "}")
      else
        warn("acmart: an affiliation has no ::: country (acmart stops with an error)")
      end
      s = s .. "\n\\affiliation{" .. table.concat(aff) .. "}"
    end
    if a.email then
      for e in (a.email .. " \\\\ "):gmatch("(.-) \\\\ ") do
        s = s .. "\n\\email{" .. e .. "}"
      end
    end
    if a.phone then warn("acmart: the phone is left out (ACM does not print it)") end
    out:insert(s)
  end
  return out, nil
end

-- The city and the country are lines of the address, but for acmart
local function with_city_country(a)
  local b = {}
  for k, v in pairs(a) do b[k] = v end
  for _, k in ipairs({ "city", "country" }) do
    if a[k] then b.address = b.address and (b.address .. " \\\\ " .. a[k]) or a[k] end
    b[k] = nil
  end
  return b
end

local function authors(list)
  if class == "acmart" then return authors_acm(list) end
  local l = {}
  for _, a in ipairs(list) do table.insert(l, with_city_country(a)) end
  if class == "llncs" then return authors_llncs(l) end
  if class == "IEEEtran" then return authors_ieee(l) end
  return authors_article(l)
end

-- The keywords, at the end of the abstract
local function keywords_tex(k)
  if class == "llncs" then return "\\keywords{" .. k .. "}" end
  if class == "IEEEtran" then
    return "\\begin{IEEEkeywords}\n" .. k .. "\n\\end{IEEEkeywords}"
  end
  return "\\par\\medskip\\noindent\\textit{Keywords:} " .. k
end

local title_meta = nil
local abstract, keywords = nil, nil

-- Add raw LaTeX to the header-includes, after what is there (the author's)
local function add_header(meta, text)
  local h = meta["header-includes"]
  local hl = pandoc.List()
  if h then
    if pandoc.utils.type(h) == "List" then hl:extend(h) else hl:insert(h) end
  end
  hl:insert(pandoc.MetaBlocks({ latexb(text) }))
  meta["header-includes"] = pandoc.MetaList(hl)
end

-- How deep the lists go: numbered, bulleted, and all together (a quote and
-- a definition list are lists to LaTeX too). LaTeX stops at 4 numbered, 4
-- bulleted and 6 in all ("Too deeply nested"): Rony's class hierarchy, 22-Oct,
-- is a numbered list five levels deep ("please allow deeper lists!").
local function list_depths(blocks, o, b, t, acc)
  for _, bl in ipairs(blocks) do
    local tag = bl.t
    if tag == "OrderedList" or tag == "BulletList" then
      local o2 = o + (tag == "OrderedList" and 1 or 0)
      local b2 = b + (tag == "BulletList" and 1 or 0)
      acc.o = math.max(acc.o, o2); acc.b = math.max(acc.b, b2)
      acc.t = math.max(acc.t, t + 1)
      for _, item in ipairs(bl.content) do list_depths(item, o2, b2, t + 1, acc) end
    elseif tag == "DefinitionList" then
      acc.t = math.max(acc.t, t + 1)
      for _, item in ipairs(bl.content) do
        for _, def in ipairs(item[2]) do list_depths(def, o, b, t + 1, acc) end
      end
    elseif tag == "BlockQuote" then
      acc.t = math.max(acc.t, t + 1)
      list_depths(bl.content, o, b, t + 1, acc)
    elseif tag == "Div" then
      list_depths(bl.content, o, b, t, acc)
    end
  end
  return acc
end

-- Deeper lists, only when a document has them: enumitem, nine levels, and
-- labels: numbers for levels 5 to 9 (Pandoc defines \labelenumN in each
-- list), and the class's bullets for levels 1 to 4, and again for 5 to 9
-- (enumitem's \renewlist leaves itemize without any: "Undefined label")
local function deep_lists(blocks)
  local d = list_depths(blocks, 0, 0, 0, { o = 0, b = 0, t = 0 })
  if d.o <= 4 and d.b <= 4 and d.t <= 6 then return nil end
  local h = { "\\usepackage{enumitem}", "\\setlistdepth{9}",
    "\\renewlist{enumerate}{enumerate}{9}", "\\renewlist{itemize}{itemize}{9}" }
  -- copies: label=\labelitemi would make \labelitemi out of itself (a loop)
  local bullets = {}
  for i, r in ipairs({ "i", "ii", "iii", "iv" }) do
    table.insert(h, 2, "\\let\\rxlabelitem" .. r .. "\\labelitem" .. r)
    bullets[i] = "\\rxlabelitem" .. r
  end
  for level = 1, 9 do
    table.insert(h, "\\setlist[itemize," .. level .. "]{label=" .. bullets[(level - 1) % 4 + 1] .. "}")
    if level >= 5 then
      table.insert(h, "\\setlist[enumerate," .. level .. "]{label=\\arabic*.}")
      -- as far in as level 4 (enumitem gives the new levels a narrow margin)
      table.insert(h, "\\setlist[" .. level .. "]{leftmargin=\\leftmarginiv}")
    end
  end
  return table.concat(h, "\n")
end

-- ::: abstract (its own heading, if any, is the class's to write)
local function abstract_div(div)
  local blocks = pandoc.List(div.content)
  if #blocks > 0 and blocks[1].t == "Header" then blocks:remove(1) end
  abstract = blocks
  return {}
end

-- ::: keywords: one paragraph, the keywords separated by commas
local function keywords_div(div)
  keywords = div_text(div)
  return {}
end

local function title_page(div)
  local t = { authors = {} }
  for _, b in ipairs(div.content) do
    if b.t == "Header" then
      t.title, t.subtitle = split_title(b.content)
      t.title, t.subtitle = fix_inlines(t.title), fix_inlines(t.subtitle)
    elseif b.t == "Div" then
      local c = b.classes[1]
      local text = div_text(b)
      if c == "author" then
        table.insert(t.authors, { name = text })
      elseif c == "date" then
        t.date = text
      elseif c == "affiliation" or c == "address" or c == "email" or c == "phone"
          or c == "city" or c == "country" then
        if #t.authors == 0 then table.insert(t.authors, { name = "" }) end
        local a = t.authors[#t.authors]
        a[c] = a[c] and (a[c] .. " \\\\ " .. text) or text
      else
        warn("title page: div '" .. tostring(c) .. "' not known, left out")
      end
    end
  end
  title_meta = t
  return {}
end

--------------------------------------------------------------------------------
-- Divs with a meaning                                                        --
--------------------------------------------------------------------------------

local function noindent(div)
  return div.content:walk({
    Para = function(p)
      local c = pandoc.List({ latex("\\noindent{}") })
      c:extend(p.content)
      return pandoc.Para(c)
    end
  })
end

local function epigraph(div)
  local cite, attribution = nil, nil
  for _, b in ipairs(div.content) do
    if b.t == "Div" and b.classes[1] == "cite" then cite = b.content
    elseif b.t == "Div" and b.classes[1] == "attribution" then attribution = b.content
    end
  end
  local out = pandoc.List({ latexb("\\begin{rxepigraph}") })
  if cite then out:extend(cite) end
  if attribution then
    out:insert(latexb("\\rxattribution{" .. blockstex(attribution) .. "}"))
  end
  out:insert(latexb("\\end{rxepigraph}"))
  return out
end

--------------------------------------------------------------------------------
-- Tables in two columns: longtable cannot be used there, so a table is a    --
-- float with a tabular (booktabs rules, as Pandoc's).                       --
--------------------------------------------------------------------------------

local twocolumn = { IEEEtran = true }

local aligns = { AlignLeft = "l", AlignRight = "r", AlignCenter = "c", AlignDefault = "l" }

local function cell_tex(cell)
  local t = blockstex(cell.contents)
  return (t:gsub("\n" .. WS .. "*\n", " \\newline "):gsub("\n", " "))
end

local function row_tex(row)
  local cells = {}
  for _, c in ipairs(row.cells) do table.insert(cells, cell_tex(c)) end
  return table.concat(cells, " & ") .. " \\\\"
end

local function float_table(tbl)
  local spec = {}
  for _, cs in ipairs(tbl.colspecs) do table.insert(spec, aligns[cs[1]] or "l") end
  local out = { "\\begin{table}[htbp]", "\\centering" }
  local cap = tbl.caption and tbl.caption.long and #tbl.caption.long > 0
  if cap then
    -- with its id, a \label (20261102: an article's ::: {#id .table})
    local label = tbl.identifier ~= "" and ("\\label{" .. tbl.identifier .. "}") or ""
    table.insert(out, "\\caption{" .. blockstex(tbl.caption.long) .. "}" .. label)
  end
  table.insert(out, "\\begin{tabular}{" .. table.concat(spec) .. "}")
  table.insert(out, "\\toprule")
  for _, r in ipairs(tbl.head.rows) do table.insert(out, row_tex(r)) end
  if #tbl.head.rows > 0 then table.insert(out, "\\midrule") end
  for _, body in ipairs(tbl.bodies) do
    for _, r in ipairs(body.body) do table.insert(out, row_tex(r)) end
  end
  table.insert(out, "\\bottomrule")
  table.insert(out, "\\end{tabular}")
  table.insert(out, "\\end{table}")
  return latexb(table.concat(out, "\n"))
end

local function environment(name, div)
  local out = pandoc.List({ latexb("\\begin{" .. name .. "}") })
  out:extend(div.content)
  out:insert(latexb("\\end{" .. name .. "}"))
  return out
end

--------------------------------------------------------------------------------
-- Books (docclass: book)                                                     --
--                                                                            --
-- Parts are "# Title {.part}"; unnumbered chapters before the first part or  --
-- numbered chapter are the front matter, a heading with .back starts the     --
-- back matter. Divs #toc, #list-of-figures, #list-of-tables and              --
-- #list-of-listings are where those lists go (their heading is the list's    --
-- title), and #index-body where the index goes (the heading before it, its   --
-- title). Captioned things are divs whose last paragraph is the caption:     --
--   ::: {#id .listing}  code  caption :::   (numbered, in the list of        --
--   ::: {#id .figure}   picture or output  caption :::        listings...)   --
--   ::: {#id .table}    table  caption :::                                   --
-- An index entry is []{ix="Level 1!Level 2!Level 3"} (.main: main entry).   --
-- A cross-reference is a link whose class says what to write:                --
--   .ref (Code 1.1-1, Table 3, 2.3.6), .ref-num (the number), .ref-chapter  --
--   (the number of the chapter it is in: 2 for 2.3.6), .ref-page (the       --
--   page), .ref-dir (above or below), .ref-text                             --
--   (the heading's title; other targets keep their text).                    --
-- The link's text is what an HTML reader sees, and the fallback here.       --
--------------------------------------------------------------------------------

local book = {
  dir = ".", listing_label = "Listing", numbering = nil, toc_depth = nil,
  ids = {},            -- id -> "header", "listing", "figure", "table", "anchor"
  chapter_of = {},     -- id -> the id of the numbered chapter it is in
  index_title = nil, index_used = false,
  matter = nil,        -- nil, "front", "main", "back"
  lol_title = nil,
}

local function texescape(s)
  return (s:gsub("[\\{}$&#%%_^~]", {
    ["\\"] = "\\textbackslash{}", ["{"] = "\\{", ["}"] = "\\}", ["$"] = "\\$",
    ["&"] = "\\&", ["#"] = "\\#", ["%"] = "\\%", ["_"] = "\\_",
    ["^"] = "\\textasciicircum{}", ["~"] = "\\textasciitilde{}" }))
end

-- Code in the text with its blanks shown (20261102): .blanks, blanks=all or
-- blanks=data, as on a page (cgi/tables.lua: every blank, the open box ␣,
-- which header.tex draws); Rexx is the highlighter's. It was not done here,
-- not even for `x`{.out .blanks}, which MARKUP.md (Rony's book) has.
local function wants_blanks(c)
  if c.classes:includes("rexx") then return false end
  local b = c.attributes.blanks
  return c.classes:includes("blanks") or b == "all" or b == "data"
end

local function code_text(c)
  local t = texescape(c.text)
  if wants_blanks(c) then t = t:gsub(" ", "\u{2423}") end
  return t
end

-- A line of code, for \rxL: specials escaped, each blank \rxs{}, tabs of 8
local function codeline(s)
  s = s:gsub("\t", "        ")
  local out = {}
  for _, c in utf8.codes(s) do
    local ch = utf8.char(c)
    if ch == " " then table.insert(out, "\\rxs{}")
    else table.insert(out, texescape(ch)) end
  end
  return table.concat(out)
end

local function codewidth(text)
  local w = 0
  for line in (text .. "\n"):gmatch("(.-)\n") do
    w = math.max(w, utf8.len((line:gsub("\t", "        "))) or #line)
  end
  return w
end

-- A makeindex entry: levels split at "!", each level "sort@shown" when the
-- shown form needs TeX escapes; makeindex's own specials are quoted with ".
-- hyperref looks for the first "|" of an entry, quoted or not: a "|" is
-- written \textbar{}, and sorted as a broken bar.
local function ixentry(spec, main)
  local levels = {}
  for part in (spec .. "!"):gmatch("(.-)!") do
    local q = part:gsub("|", "¦"):gsub('["@!]', '"%0')
    local shown = texescape(part):gsub("|", "\\textbar{}")
    if shown ~= part then
      table.insert(levels, q:gsub("[\\{}]", '"%0') .. "@" .. shown:gsub('["@|!]', '"%0'))
    else
      table.insert(levels, q)
    end
  end
  return "\\index{" .. table.concat(levels, "!") .. (main and "|textbf" or "") .. "}"
end

local function is_ix(el)
  return el.t == "Span" and el.attributes and el.attributes.ix ~= nil
end

local function ix_raw(el)
  book.index_used = true
  return latex(ixentry(el.attributes.ix, el.classes:includes("main")))
end

-- Take the index entries out of some inlines (titles, captions: moving
-- arguments): returns the inlines without them, and the entries as LaTeX.
local function take_ix(inls)
  local entries = {}
  -- (the Spans may already be raw \index: inlines are filtered before blocks)
  local rest = pandoc.Inlines(inls):walk({
    Span = function(s)
      if is_ix(s) then
        book.index_used = true
        table.insert(entries, ixentry(s.attributes.ix, s.classes:includes("main")))
        return {}
      end
    end,
    RawInline = function(r)
      if r.format == "latex" and r.text:match("^\\index{") then
        table.insert(entries, r.text)
        return {}
      end
    end })
  return rest, table.concat(entries)
end

local function para_of(blocks)            -- the last paragraph: the caption
  local last = blocks[#blocks]
  if last and (last.t == "Para" or last.t == "Plain") then
    local b = pandoc.List(blocks)
    b:remove(#b)
    return b, last.content
  end
  return blocks, nil
end

local function wrap(before, inls, after)
  local l = pandoc.List({ latex(before) })
  l:extend(inls)
  l:insert(latex(after))
  return pandoc.Plain(l)
end

-- The ground and the frame of a block (cgi/spots.lua): the LaTeX before and
-- after its box. get(name) reads what the block says; kind is "code" or
-- "output", lang its language (v366: blocks: has a key per language). A highlighter's box (rxhlisting, rxblock, rxoutput) goes in
-- rxdress, which gives it the options; with frame = true, a box of its own
-- (rxframe), for the code that Pandoc writes.
local function dress_tex(get, kind, frame, lang)
  local d, warnings = spots.dress(get, doc_blocks, kind, lang)
  for _, w in ipairs(warnings) do warn(w) end
  if not d then return "", "" end
  -- The box's own frame is an area under its ground: with no ground, it
  -- would show. So it is never drawn, and the frame asked for is a line
  -- (borderline), which a box that breaks across pages draws part by part
  local bg, colour, opts = "", "", {}
  if d.bg == "none" then
    bg = "FFFFFF"; table.insert(opts, "opacityback=0,opacityframe=0")
  elseif d.bg then bg = d.bg end
  if d.border == "none" then table.insert(opts, "boxrule=0pt")
  elseif d.border then
    colour = d.color
    local w = spots.texlength(d.width)
    local line = ({ solid = "", dashed = ",dashed",
      dotted = ",line cap=round,dash pattern=on 0pt off 2.5\\pgflinewidth" })[d.border]
    table.insert(opts, "boxrule=0pt,borderline={" .. w .. "}{0pt}{rxd@frame" .. line .. "}")
  end
  if frame and d.border and d.border ~= "none" then
    table.insert(opts, "left=4pt,right=4pt,top=3pt,bottom=3pt")
  end
  local env = frame and "rxframe" or "rxdress"
  return "\\begin{" .. env .. "}{" .. bg .. "}{" .. colour .. "}{" .. table.concat(opts, ",") .. "}",
    "\\end{" .. env .. "}"
end

-- The pen of beat k: { bar, bg, a } (RRGGBB, RRGGBB, per cent)
local function pen_of(sp, k)
  local p = spots.pen(sp, k)
  if p.n then return pens[p.n] end
  return { bar = p.hex, bg = p.hex, a = "40" }
end

-- A line of a block with its marks: \rxL, or \rxhLW / \rxhLB for a line
-- marked whole; a text in \rxhMW or \rxhMB; ink and bold, \textcolor and
-- \textbf (the text has no colours of its own)
local function marked_line(text, m, sp, blanks)
  local wash = sp.look == "wash" or (sp.look == "" and not sp.bold)
  local box = sp.look == "box" or sp.look == "ring"
  local function looks(piece, c)
    if sp.bold then piece = "\\textbf{" .. piece .. "}" end
    if sp.look == "ink" then piece = "\\textcolor[HTML]{" .. c.bar .. "}{" .. piece .. "}" end
    return piece
  end
  local out = {}
  for _, p in ipairs(m.pieces) do
    local t = text:sub(p.s, p.e)
    if blanks then t = t:gsub(" ", "\u{2423}") end
    local piece = codeline(t)
    if p.k > 0 then
      local c = pen_of(sp, p.k)
      piece = looks(piece, c)
      if box then
        piece = "\\rxhMB{" .. c.bar .. "}{" .. (p.first and 1 or 0) .. "}{" ..
          (p.last and 1 or 0) .. "}{" .. piece .. "}"
      elseif wash then
        piece = "\\rxhMW{" .. c.bg .. "}{" .. c.a .. "}{" .. piece .. "}"
      end
    end
    table.insert(out, piece)
  end
  local line = table.concat(out)
  if m.beat == 0 then return "\\rxL{" .. line .. "}" end
  local c = pen_of(sp, m.beat)
  line = looks(line, c)
  if box then
    return "\\rxhLB{" .. c.bar .. "}{" .. (m.first and 1 or 0) .. "}{" ..
      (m.last and 1 or 0) .. "}{" .. line .. "}"
  elseif wash then
    return "\\rxhLW{" .. c.bg .. "}{" .. c.a .. "}{" .. c.bar .. "}{" .. line .. "}"
  end
  return "\\rxL{" .. line .. "}"
end

-- The spot= of a block, read, or nil when it marks nothing
local function spot_of(cb)
  if not cb.attributes.spot then return nil end
  local sp, warnings = spots.parse(cb.attributes.spot)
  for _, w in ipairs(warnings) do warn("spot=: " .. w) end
  if not spots.any(sp) then return nil end
  return sp
end

-- Code that is not Rexx, and program output: the file of source=, or the text,
-- in the highlighter's box, with its marks, its ground and its frame
-- Code in a language Pandoc knows (```vb, ```java...), highlighted as Pandoc
-- does it, in the box of the book (Rony, 26-Oct: the VB of his Rosetta Stone
-- came out plain). Pandoc writes the block as HTML, which is easy to read
-- token by token; each token becomes Pandoc's own LaTeX macro (\KeywordTok,
-- \StringTok...), defined in the preamble (tok_macros). nil when Pandoc does
-- not know the language.
local TOK = {
  al = "Alert", an = "Annotation", at = "Attribute", bn = "BaseN", bu = "BuiltIn",
  cf = "ControlFlow", ch = "Char", cn = "Constant", co = "Comment", cv = "CommentVar",
  ["do"] = "Documentation", dt = "DataType", dv = "DecVal", er = "Error", ex = "Extension",
  fl = "Float", fu = "Function", im = "Import", ["in"] = "Information", kw = "Keyword",
  op = "Operator", ot = "Other", pp = "Preprocessor", sc = "SpecialChar", ss = "SpecialString",
  st = "String", va = "Variable", vs = "VerbatimString", wa = "Warning",
}
local HTMLENT = { lt = "<", gt = ">", amp = "&", quot = '"' }
local function unhtml(t)
  t = t:gsub("&#(%d+);", function(d) return utf8.char(tonumber(d)) end)
  return (t:gsub("&([a-z]+);", function(n) return HTMLENT[n] or ("&" .. n .. ";") end))
end
local function highlighted_lines(lang, text)
  local ok, html = pcall(pandoc.write,
    pandoc.Pandoc({ pandoc.CodeBlock(text, { "", { lang }, {} }) }), "html",
    { highlight_style = PANDOC_WRITER_OPTIONS.highlight_style })
  if not ok then return nil end
  local body = html:match('(.*)')
  if not body then return nil end
  local lines = {}
  for l in (body .. "\n"):gmatch("(.-)\n") do
    l = l:gsub('^]*>', ""):gsub("$", "")
    local out, pos = {}, 1
    while true do
      local s, e, cls, inner = l:find('(.-)', pos)
      if not s then table.insert(out, codeline(unhtml(l:sub(pos)))) break end
      if s > pos then table.insert(out, codeline(unhtml(l:sub(pos, s - 1)))) end
      local t = codeline(unhtml(inner))
      table.insert(out, TOK[cls] and ("\\" .. TOK[cls] .. "Tok{" .. t .. "}") or t)
      pos = e + 1
    end
    table.insert(lines, table.concat(out))
  end
  return lines
end

-- Pandoc's \XxxTok macros for the highlight-style, as \providecommand: in a
-- book every block is ours, so Pandoc does not write them (unless some code
-- in the text is highlighted: then its own come first, and these give way)
local function tok_macros()
  local ok, m = pcall(pandoc.write,
    pandoc.Pandoc({ pandoc.CodeBlock("x = 1", { "", { "c" }, {} }) }), "latex",
    { template = pandoc.template.compile("$highlighting-macros$"),
      highlight_style = PANDOC_WRITER_OPTIONS.highlight_style })
  if not ok then return "" end
  local keep = {}
  for line in (m .. "\n"):gmatch("(.-)\n") do
    if line:find("^\\newcommand{\\[A-Za-z]+Tok}") then
      table.insert(keep, (line:gsub("^\\newcommand", "\\providecommand")))
    end
  end
  return table.concat(keep, "\n")
end

local function code_block(cb)
  local text = cb.text
  local src = cb.attributes.source
  local missing = false
  if src then
    local f = io.open(book.dir .. "/" .. src, "r")
    if not f then
      warn("source file not found: " .. src)
      text = "(" .. src .. " not found)"
      missing = true
    else
      text = f:read("a"):gsub("\n$", "")
      f:close()
    end
  end
  -- blanks= / {.blanks} (Rony, 25-Oct): every blank, the open box. Without a
  -- parser, "data" (the blanks a program sees) cannot be told from the rest
  local blanks = cb.attributes.blanks
  blanks = cb.classes:includes("blanks") or blanks == "all" or blanks == "data"
  local output = cb.classes:includes("output")
  local env = (output and class == "book") and "rxoutput" or "rxblock"
  local before, after = dress_tex(function(k) return cb.attributes[k] end,
    output and "output" or "code", false, spots.lang(cb.classes))
  local sp = spot_of(cb)
  local lines = {}
  for line in (text .. "\n"):gmatch("(.-)\n") do table.insert(lines, line) end
  -- .numberLines (or .number-lines), startFrom= (or start-from=), as on a
  -- Rexx listing: the numbers in a gutter, numberWidth= digits (3)
  local numbered = cb.classes:includes("numberLines") or cb.classes:includes("number-lines")
  local first = tonumber(cb.attributes.startFrom or cb.attributes["start-from"] or "") or 1
  local digits = tonumber(cb.attributes.numberWidth or "") or 3
  digits = math.max(digits, #tostring(first + #lines - 1))
  local marks = sp and spots.marks(sp, lines, numbered and first or 1)
  -- The language's own colours, unless the block has marks or shows its
  -- blanks (as in HTML: then it loses them)
  local lang = cb.classes[1]
  local hl = (not output and not marks and not blanks and not missing and lang and lang ~= "numberLines"
    and lang ~= "number-lines") and highlighted_lines(lang, text) or nil
  if hl and #hl ~= #lines then hl = nil end
  local out = {}
  if before ~= "" then table.insert(out, before) end
  table.insert(out, "\\begin{" .. env .. "}[" .. (codewidth(text) + (numbered and digits + 3 or 0)) ..
                "]" .. (env == "rxblock" and "{1}" or ""))
  for i, line in ipairs(lines) do
    local l
    if marks then l = marked_line(line, marks[i], sp, blanks)
    elseif hl then l = "\\rxL{" .. hl[i] .. "}"
    else
      if blanks then line = line:gsub(" ", "\u{2423}") end
      l = "\\rxL{" .. codeline(line) .. "}"
    end
    if numbered then
      local n = "{" .. digits .. "}{" .. (first + i - 1) .. "}"
      l = l:gsub("^\\rxL{", "\\rxLN" .. n .. "{", 1)
           :gsub("^\\rxhLW{", "\\rxhLNW" .. n .. "{", 1)
           :gsub("^\\rxhLB{", "\\rxhLNB" .. n .. "{", 1)
    end
    table.insert(out, l)
  end
  table.insert(out, "\\end{" .. env .. "}")
  if after ~= "" then table.insert(out, after) end
  return latexb(table.concat(out, "\n"))
end

-- 
...
, a raw HTML block (a terminal session, say): its text, with -- the entities decoded and the tags out. It is -- set in the box of the code, as program output in a book; the box makes the -- text smaller when a line is wider than the page. local entities = { lt = "<", gt = ">", amp = "&", quot = '"', apos = "'", nbsp = "\u{A0}" } local function pre_text(html) local t = html:gsub("^" .. WS .. "*<[Pp][Rr][Ee][^>]*>\n?", ""):gsub("" .. WS .. "*$", "") t = t:gsub("<[^>]*>", "") -- the tags out t = t:gsub("&#[xX](%x+);", function(h) return utf8.char(tonumber(h, 16)) end) t = t:gsub("&#(%d+);", function(d) return utf8.char(tonumber(d)) end) t = t:gsub("&([A-Za-z]+);", function(n) return entities[n] or ("&" .. n .. ";") end) return t end local function pre_block(html) -- the text by hand: Pandoc's HTML reader makes a
 a code block in
  -- 3.1, but lines with breaks in 3.11 when it holds a tag ()
  local text = pre_text(html):gsub("\n+$", "")
  local env = class == "book" and "rxoutput" or "rxblock"
  local before, after = dress_tex(function() return nil end, "output", false)
  local out = { "\\begin{" .. env .. "}[" .. codewidth(text) .. "]" ..
                (env == "rxblock" and "{1}" or "") }
  if before ~= "" then table.insert(out, 1, before) end
  for line in (text .. "\n"):gmatch("(.-)\n") do
    table.insert(out, "\\rxL{" .. codeline(line) .. "}")
  end
  table.insert(out, "\\end{" .. env .. "}")
  if after ~= "" then table.insert(out, after) end
  return { latexb(table.concat(out, "\n")) }
end

local function listing_div(div)
  local code, cap = para_of(div.content)
  local id = div.identifier
  local out = pandoc.List(code)
  if cap then
    local c, ix = take_ix(cap)
    out:insert(wrap(ix .. "\\rxlistingcaption{" .. id .. "}{", c, "}"))
  else
    out:insert(latexb("\\rxanchor{" .. id .. "}"))
  end
  return out
end

local function figure_div(div)
  local body, cap = para_of(div.content)
  local id = div.identifier
  local output = false
  for _, b in ipairs(body) do
    if b.t == "CodeBlock" or b.t == "RawBlock" then output = true end
  end
  local out = pandoc.List({ latexb("\\begin{figure}[" .. (output and "H" or "htbp") .. "]\n\\centering") })
  out:extend(body)
  local ix = ""
  if cap then
    local c
    c, ix = take_ix(cap)
    out:insert(wrap("\\caption{", c, "}\\label{" .. id .. "}\\rxanchor{" .. id .. "}"))
  end
  out:insert(latexb("\\end{figure}" .. ix))
  return out
end

-- cols= on the ::: of a table, as in md2slides: the proportions of its
-- columns ("1:5", "2,2,4", "1 5"). A column it does not name counts as 1;
-- shares beyond the table's columns are room the table does not take, so
-- cols=2:2:4 makes a two-column table half the width (Rony, 20-Oct: wide
-- tables came out with all their columns as wide).
local function table_cols(tbl, spec)
  local shares = {}
  for n in tostring(spec):gmatch("[%d%.]+") do table.insert(shares, tonumber(n)) end
  if #shares == 0 then
    warn("cols=" .. tostring(spec) .. ": not numbers; the table is left as it was")
    return
  end
  local n = #tbl.colspecs
  local total = 0
  for i = 1, math.max(n, #shares) do total = total + (shares[i] or 1) end
  for i = 1, n do
    local align = tbl.colspecs[i][1]
    tbl.colspecs[i] = { align, (shares[i] or 1) / total }
  end
end

-- Balanced columns, by default (Rony, 21-Oct). A pipe table with a long
-- line gets its widths from the dashes under its header, so |---|---|---|
-- was a third each. Unless the author gave cols= (or dashes of different
-- lengths), the widths come from what the columns hold, as a browser does:
-- a table whose lines fit in the line keeps the natural width of its
-- columns; otherwise each column that needs less than its share gets what
-- it needs, and the rest share what is left by how much they hold.
-- A listing or a block of code in a cell (Rony's Rosetta Stone, 26-Oct) is
-- not text that wraps: the cell needs its longest line, and a Rexx listing
-- says how long that is (\begin{rxhlisting}[N]; code that is not Rexx in a
-- book, \begin{rxblock}[N], output \begin{rxoutput}[N]); stringify did not.
local function cell_len(cell)
  local n, code = 0, 0
  local text = {}
  for _, b in ipairs(cell.contents) do
    if b.t == "CodeBlock" then
      code = math.max(code, codewidth(b.text))
    elseif b.t == "RawBlock" then
      local w = b.format == "latex" and b.text:match("\\begin{rx%a+}%[(%d+)%]")
      if w then code = math.max(code, tonumber(w)) end
    else
      table.insert(text, b)
    end
  end
  local t = pandoc.utils.stringify(text)
  for w in t:gmatch(NONWS .. "+") do n = n + (utf8.len(w) or #w) + 1 end
  -- (the box's own margins: one character; the cell's are counted by the caller)
  return math.max(n, code > 0 and code + 1 or 0)
end

local function table_balance(tbl)
  local n = #tbl.colspecs
  local first, same = nil, true
  for i = 1, n do
    local w = tbl.colspecs[i][2]
    if type(w) == "number" then
      first = first or w
      if math.abs(w - first) > 0.001 then same = false end
    end
  end
  if first and not same then return end      -- the author's dashes: kept
  local need = {}
  for i = 1, n do need[i] = 1 end
  -- A cell that spans columns (Rony, 23-Oct: a heading across the table)
  -- does not say how wide any of them is; the next cell is in the column
  -- after the last it spans
  local function rows(list)
    for _, row in ipairs(list) do
      local col = 1
      for _, cell in ipairs(row.cells) do
        local span = cell.col_span or 1
        if span == 1 and col <= n then need[col] = math.max(need[col], cell_len(cell)) end
        col = col + span
      end
    end
  end
  rows(tbl.head.rows)
  for _, b in ipairs(tbl.bodies) do rows(b.head); rows(b.body) end
  rows(tbl.foot.rows)
  local line, sum = 75, 0                     -- characters in a line, roughly
  for i = 1, n do sum = sum + need[i] + 2 end
  if sum <= line then                         -- it fits: natural widths
    for i = 1, n do tbl.colspecs[i] = { tbl.colspecs[i][1], pandoc.ColWidthDefault } end
    return
  end
  local width, left, open = {}, line, {}
  for i = 1, n do open[i] = true end
  local again = true
  while again do
    again = false
    local count = 0
    for i = 1, n do if open[i] then count = count + 1 end end
    if count == 0 then break end
    local share = left / count
    for i = 1, n do
      if open[i] and need[i] + 2 <= share then
        width[i], open[i], left, again = need[i] + 2, false, left - need[i] - 2, true
      end
    end
  end
  local rest = 0
  for i = 1, n do if open[i] then rest = rest + need[i] end end
  for i = 1, n do
    if open[i] then width[i] = left * need[i] / rest end
    tbl.colspecs[i] = { tbl.colspecs[i][1], width[i] / line }
  end
end

-- What a table asks for, on its ::: or for the whole document in the YAML
-- (md2latex passes rexxpub: tables: as rexxpub-tables-grid and -stripes):
--   rules=solid|dashed|dotted  a line under each row of the body;
--   .grid                      lines round every cell;
--   .stripes, stripes=#F2F2F2  every second row of the body on a ground.
-- Only a mark here, "% rxtable n=N rules=... grid stripes=...", before the
-- table: md2latex does it in the LaTeX Pandoc wrote, once every filter (the
-- document's own too) has done its work on the cells.
local doc_tables = { grid = false, stripes = nil }

local function stripes_value(s)
  if s == nil then return nil end
  local l = s:lower()
  if l == "no" or l == "false" or l == "0" then return nil end
  if l == "yes" or l == "true" or l == "1" or l == "" then return "F2F2F2" end
  local hex = s:match("^#?(%x%x%x%x%x%x)$")
  if hex then return hex:upper() end
  warn("stripes=" .. s .. ": a colour is six hexadecimal digits (#F2F2F2); the default is used")
  return "F2F2F2"
end

local function table_mark(tbl, attrs, classes)
  local rules = attrs and attrs.rules
  if rules and rules ~= "solid" and rules ~= "dashed" and rules ~= "dotted" then
    warn("rules=" .. rules .. ": it is solid, dashed or dotted; the table has no lines")
    rules = nil
  end
  local grid = doc_tables.grid
  if classes and classes:includes("grid") then grid = true end
  if classes and classes:includes("nogrid") then grid = false end
  local stripes = doc_tables.stripes
  if classes and classes:includes("stripes") then stripes = stripes or "F2F2F2" end
  if attrs and attrs.stripes then stripes = stripes_value(attrs.stripes) end
  if classes and classes:includes("nostripes") then stripes = nil end
  if not (rules or grid or stripes) then return nil end
  return latexb("% rxtable n=" .. #tbl.colspecs ..
    (rules and (" rules=" .. rules) or "") .. (grid and " grid" or "") ..
    (stripes and (" stripes=" .. stripes) or ""))
end

-- A table and what its ::: says: the widths, and the mark
-- A listing in a cell starts at the top of the cell, as the text next to it
-- does, and ends at its bottom: \rxincell takes the space a listing leaves
-- above and below itself in the text (header.tex). A cell is a group.
local function cells_snug(tbl)
  local function snug(cell)
    for _, b in ipairs(cell.contents) do
      if b.t == "RawBlock" and b.format == "latex" and b.text:find("\\begin{rx%a+}%[") then
        cell.contents:insert(1, latexb("\\rxincell"))
        return
      end
    end
  end
  local function rows(list)
    for _, row in ipairs(list) do
      for _, cell in ipairs(row.cells) do snug(cell) end
    end
  end
  rows(tbl.head.rows)
  for _, b in ipairs(tbl.bodies) do rows(b.head); rows(b.body) end
  rows(tbl.foot.rows)
end

local function table_dress(tbl, attrs, classes)
  if attrs and attrs.cols then table_cols(tbl, attrs.cols) else table_balance(tbl) end
  cells_snug(tbl)
  tbl.attr.attributes["rx-dressed"] = "1"
  return table_mark(tbl, attrs, classes)
end

local function table_div(div)
  local body, cap = para_of(div.content)
  local id = div.identifier
  local out = pandoc.List({ latexb("\\rxanchor{" .. id .. "}") })
  local ix = ""
  for _, b in ipairs(body) do
    if b.t == "Table" then
      if cap then
        local c
        c, ix = take_ix(cap)
        b.caption = { long = { pandoc.Plain(c) } }
      end
      b.identifier = id
      local mark = table_dress(b, div.attributes, div.classes)
      if mark then out:insert(mark) end
    end
    out:insert(b)
  end
  if ix ~= "" then out:insert(latexb(ix)) end
  return out
end

local function list_title(div)
  for _, b in ipairs(div.content) do
    if b.t == "Header" then return tex(b.content) end
  end
  return nil
end

local function into_toc(name)
  return "\\cleardoublepage\\phantomsection\\addcontentsline{toc}{chapter}{" .. name .. "}"
end

local function lists_div(div)
  local id, name = div.identifier, list_title(div)
  if id == "toc" then
    return latexb((name and ("\\renewcommand*\\contentsname{" .. name .. "}") or "") ..
      (book.toc_depth and ("\\setcounter{tocdepth}{" .. book.toc_depth .. "}") or "") ..
      -- The contents get a bookmark of their own, as the lists do (Rony,
      -- 20-Oct: the PDF's outline had the lists and not the contents)
      "\\cleardoublepage\\phantomsection\\pdfbookmark[0]{\\contentsname}{rxtoc}" ..
      "{\\hypersetup{linkcolor=black}\\tableofcontents}")
  elseif id == "list-of-figures" then
    return latexb((name and ("\\renewcommand*\\listfigurename{" .. name .. "}") or "") ..
      into_toc("\\listfigurename") .. "{\\hypersetup{linkcolor=black}\\listoffigures}")
  elseif id == "list-of-tables" then
    return latexb((name and ("\\renewcommand*\\listtablename{" .. name .. "}") or "") ..
      into_toc("\\listtablename") .. "{\\hypersetup{linkcolor=black}\\listoftables}")
  elseif id == "list-of-listings" then
    return latexb((name and ("\\renewcommand*\\rxlolname{" .. name .. "}") or "") ..
      into_toc("\\rxlolname") .. "{\\hypersetup{linkcolor=black}\\listoflistings}")
  elseif id == "index-body" then
    return latexb("{\\hypersetup{linkcolor=black}\\printindex}")
  end
  return nil
end

local function matter(which)
  if book.matter == which then return nil end
  book.matter = which
  -- The back matter's chapters are not the last part's (Rony, 21-Oct: the
  -- PDF's outline had the index and the links under part IV). The bookmark
  -- package, that Pandoc's template loads when it is there, starts them at
  -- the root; with hyperref alone, they stay where they were.
  if which == "back" then
    return latexb("\\backmatter\\ifdefined\\bookmarksetup\\bookmarksetup{startatroot}\\fi")
  end
  return latexb("\\" .. which .. "matter")
end

local sec_counter = { [1] = "chapter", [2] = "section", [3] = "subsection",
  [4] = "subsubsection", [5] = "paragraph", [6] = "subparagraph" }

-- The heading's role on the title page: its class, or the class of the one
-- span it holds ("# [The Book]{.book-title}", as md2pdf's books write it),
-- and its text without that span (20261102: the span form was a chapter,
-- that left the book in the front matter)
local function title_role(h)
  for _, k in ipairs({ "book-title", "book-subtitle" }) do
    if h.classes:includes(k) then return k, h.content end
  end
  local only
  for _, i in ipairs(h.content) do
    if i.t ~= "Space" and i.t ~= "SoftBreak" then
      if only then return nil end
      only = i
    end
  end
  if only and only.t == "Span" then
    for _, k in ipairs({ "book-title", "book-subtitle" }) do
      if only.classes:includes(k) then return k, only.content end
    end
  end
  return nil
end

-- .toc-exclude: the heading keeps its number, and stays out of the contents
-- (as in md2pdf; 20261102: it did nothing). \rxtocoff and \rxtocon
-- (header-book.tex) go into the .toc, around the heading's line.
local function toc_out(blocks)
  local out = pandoc.List({ latexb("\\addtocontents{toc}{\\protect\\rxtocoff}") })
  out:extend(blocks)
  out:insert(latexb("\\addtocontents{toc}{\\protect\\rxtocon}"))
  return out
end

local book_header_in

local function book_header(h)
  -- The headings of the title page and of the lists are not chapters
  if title_role(h) or h.classes:includes("rx-not-chapter") then return nil end
  local out = book_header_in(h)
  if h.classes:includes("toc-exclude") then return toc_out(out) end
  return out
end

function book_header_in(h)
  local id = h.identifier
  local inls, ix = take_ix(h.content)
  while #inls > 0 and (inls[#inls].t == "Space" or inls[#inls].t == "SoftBreak") do inls:remove(#inls) end
  h.content = inls
  local out = pandoc.List()
  local unnumbered = h.classes:includes("unnumbered")
  if h.level == 1 then
    if h.classes:includes("back") then
      out:insert(matter("back"))
    elseif not unnumbered then
      out:insert(matter("main"))
    end
  end
  if id == "index" and h.classes:includes("back") then
    book.index_title = tex(inls)
    out:insert(latexb(ix))
    return out
  end
  if h.level == 1 and h.classes:includes("part") then
    out:insert(wrap("\\part{", inls, "}\\label{" .. id .. "}\\rxanchor{" .. id .. "}" .. ix))
    return out
  end
  out:insert(h)
  local after = "\\rxanchor{" .. id .. "}"
  if not unnumbered and sec_counter[h.level] then
    after = after .. "\\rxsetsec{\\the" .. sec_counter[h.level] .. "}"
  end
  out:insert(latexb(after .. ix))
  return out
end

local function ref_link(link)
  local kind
  for _, c in ipairs(link.classes) do
    if c:match("^ref") then kind = c end
  end
  if not kind then return nil end
  local id = link.target:match("^#(.+)$")
  if not id then return nil end
  -- [12](#n12){.ref-note}: the number of the note labelled n12
  if kind == "ref-note" then
    if not book.ids["rxfn-" .. id] then
      warn("reference to a missing footnote: " .. id)
      return link.content
    end
    return latex(note_mark("rxfn-" .. id))
  end
  local what = book.ids[id]
  if not what then
    warn("cross-reference to a missing target: #" .. id)
    return link.content
  end
  local anchor = what == "anchor"
  if kind == "ref" then
    local name = ({ listing = "\\rxlistingname", table = "\\tablename",
                    figure = "\\figurename" })[what]
    if name then return latex("\\hyperref[" .. id .. "]{" .. name .. "~\\ref*{" .. id .. "}}") end
    if anchor then return latex("\\rxsecnum{" .. id .. "}") end
    return latex("\\ref{" .. id .. "}")
  elseif kind == "ref-chapter" then
    return chapter_ref(id, link.content)
  elseif kind == "ref-num" then
    if anchor then return latex("\\rxsecnum{" .. id .. "}") end
    return latex("\\ref{" .. id .. "}")
  elseif kind == "ref-page" then
    return latex("\\pageref{" .. id .. "}")
  elseif kind == "ref-dir" then
    return latex("\\rxdir{" .. id .. "}")
  elseif kind == "ref-text" then
    if what == "header" then return latex("\\nameref{" .. id .. "}") end
    return nil                              -- a caption: the link as written
  end
  return nil
end

-- A reference to a footnote (20-Oct, Rony's book): "[12]{.ref-num note=n12}",
-- "p. [73]{.ref-page note=n12}", "[above]{.ref-dir note=n12}", and the mark
-- again, "[12]{.ref-note note=n12}" (or [12](#n12){.ref-note}), where n12 is
-- the note's label ([^n12]). md2latex put an anchor, rxfn-n12, at the start
-- of the note's text: there a \label takes the note's number. The text in
-- the brackets is what an HTML reader sees, and the fallback here.
function note_ref(s)
  local kind
  for _, c in ipairs(s.classes) do
    if c:match("^ref") then kind = c end
  end
  if not kind then return nil end
  local id = "rxfn-" .. s.attributes.note
  if not book.ids[id] then
    warn("reference to a missing footnote: " .. s.attributes.note)
    return s.content
  end
  if kind == "ref-page" then return latex("\\pageref{" .. id .. "}") end
  if kind == "ref-dir" then return latex("\\rxdir{" .. id .. "}") end
  if kind == "ref-note" then return latex(note_mark(id)) end
  if kind == "ref-chapter" then return chapter_ref(id, s.content) end
  return latex("\\ref{" .. id .. "}")       -- ref-num, ref: the number, in the text
end

-- .ref-chapter (20261102): the number of the chapter the target is in, the
-- chapter's own if it is one ("see Chapter [2](#sec-2-3-6){.ref-chapter}");
-- outside a numbered chapter, the text as written, and a warning
function chapter_ref(id, fallback)
  local ch = book.chapter_of[id]
  if not ch then
    warn("ref-chapter: #" .. id:gsub("^rxfn%-", "") .. " is not in a numbered chapter")
    return fallback
  end
  return latex("\\ref{" .. ch .. "}")
end

-- .ref-note is the note's mark again, raised as a footnote mark is ("the
-- following output[20]{.ref-note note=n20}:", a second mark for note 20);
-- .ref-num is its number in the text ("Footnote [12]{.ref-num note=n12}").
function note_mark(id)
  return "\\textsuperscript{\\normalfont\\ref{" .. id .. "}}"
end

local function book_title_page(div)
  local t = { lines = {}, verso = {} }
  for _, b in ipairs(div.content) do
    if b.t == "Header" then
      local role, content = title_role(b)
      content = content or b.content
      if role == "book-subtitle" or (role == nil and b.level > 1) then t.subtitle = tex(fix_inlines(content))
      else t.title = tex(fix_inlines(content)) end
    elseif b.t == "Div" then
      local c = b.classes[1]
      local text = div_text(b)
      if c == "author" then t.author = text
      elseif c == "title-verso" then table.insert(t.verso, text)
      else table.insert(t.lines, text) end   -- date, edition, title-line...
    end
  end
  book.title_plain = t.title
  book.matter = "front"
  return pandoc.List({ latexb("\\frontmatter"), latexb("\\rxtitlepage{" .. (t.title or "") .. "}{" ..
    (t.subtitle or "") .. "}{" .. (t.author or "") .. "}{" .. table.concat(t.lines, "\\\\[0.6em] ") ..
    "}{" .. table.concat(t.verso, "\\\\[0.6em] ") .. "}") })
end

-- The numbered chapter each id is in, for .ref-chapter (20261102): the
-- blocks in their order; a level-1 heading that is a chapter (not a part,
-- not the title page's, not a list's) starts one, numbered unless it is
-- .unnumbered or in the back matter (from the first .back on)
function chapters_of(blocks)
  local current, back = nil, false
  local function note(id) if id ~= "" then book.chapter_of[id] = current end end
  local function ids_in(b)
    pandoc.walk_block(pandoc.Div({ b }), {
      Header = function(h) note(h.identifier) end,
      Div    = function(d) note(d.identifier) end,
      Span   = function(x) note(x.identifier) end,
    })
  end
  local function visit(list)
    for _, b in ipairs(list) do
      if b.t == "Header" and b.level == 1 and not b.classes:includes("part")
         and not title_role(b) and not b.classes:includes("rx-not-chapter") then
        if b.classes:includes("back") then back = true end
        if back or b.classes:includes("unnumbered") then current = nil
        else current = b.identifier ~= "" and b.identifier or nil end
        note(b.identifier)
      elseif b.t == "Header" and b.level == 1 and b.classes:includes("part") then
        current = nil
        note(b.identifier)
      elseif b.t == "Div" then
        note(b.identifier)
        visit(b.content)
      else
        ids_in(b)
      end
    end
  end
  visit(blocks)
end

local book_filters = {
  -- Everything a reference can point to
  {
    Pandoc = function(doc)
      local lists = { toc = true, ["list-of-figures"] = true, ["list-of-tables"] = true,
        ["list-of-listings"] = true, ["index-body"] = true }
      doc = doc:walk({
        Header = function(h) if h.identifier ~= "" then book.ids[h.identifier] = "header" end end,
        Div = function(d)
          -- The headings of the lists' divs are not chapters (their divs go
          -- whole; a heading there must not start the main matter)
          if lists[d.identifier] then
            d.content = d.content:walk({ Header = function(h)
              h.classes:insert("rx-not-chapter"); return h end })
          end
          if d.identifier == "" then return d end
          for _, k in ipairs({ "listing", "figure", "table" }) do
            if d.classes:includes(k) then book.ids[d.identifier] = k; return d end
          end
          book.ids[d.identifier] = "div"
          return d
        end,
        Span = function(s) if s.identifier ~= "" then book.ids[s.identifier] = "anchor" end end,
      })
      chapters_of(doc.blocks)
      book.matter = "front"
      return doc
    end,
  },
  {
    Div = function(div)
      if div.classes:includes("title-page") then return book_title_page(div) end
      local l = lists_div(div)
      if l then return l end
      if div.classes:includes("listing") then return listing_div(div) end
      if div.classes:includes("figure") then return figure_div(div) end
      if div.classes:includes("table") then return table_div(div) end
      if div.classes:includes("toc-exclude") then
        div.classes = div.classes:filter(function(c) return c ~= "toc-exclude" end)
        return toc_out({ div })
      end
    end,
    CodeBlock = function(cb)
      if cb.attributes.source or cb.classes:includes("output") or cb.classes[1] then
        return code_block(cb)
      end
    end,
    Header = book_header,
    Link = ref_link,
    Span = function(s)
      if is_ix(s) then return ix_raw(s) end
      if s.attributes.note then return note_ref(s) end
      if s.identifier ~= "" and #s.content == 0 then
        return latex("\\phantomsection\\label{" .. s.identifier .. "}\\rxanchor{" .. s.identifier .. "}")
      end
    end,
    Code = function(c)
      if c.classes:includes("out") then return latex("\\rxout{" .. code_text(c) .. "}") end
    end,
  },
  {
    Pandoc = function(doc)
      local h = {}
      table.insert(h, "\\renewcommand*{\\rxlistingname}{" .. book.listing_label .. "}")
      if book.numbering == "section" or book.numbering == "chapter" then
        table.insert(h, "\\rxlistingnumbering{" .. book.numbering .. "}")
      end
      if book.index_used then
        table.insert(h, "\\usepackage{imakeidx}")
        table.insert(h, "\\makeindex[intoc,columns=2" ..
          (book.index_title and (",title={" .. book.index_title .. "}") or "") .. "]")
      end
      -- The title page is ours: Pandoc's \maketitle would write another one
      local title = doc.meta.title and pandoc.utils.stringify(doc.meta.title)
      local author = doc.meta.author and pandoc.utils.stringify(doc.meta.author)
      doc.meta.title, doc.meta.subtitle, doc.meta.author, doc.meta.date = nil, nil, nil, nil
      table.insert(h, "\\AtBeginDocument{\\hypersetup{pdftitle={" .. texescape(title or "") ..
        "},pdfauthor={" .. texescape(author or "") .. "}}}")
      table.insert(h, tok_macros())
      add_header(doc.meta, table.concat(h, "\n"))
      return doc
    end,
  },
}

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

-- The book filters run only for books
local function only_books(filter)
  local f = {}
  for k, fn in pairs(filter) do
    f[k] = function(...) if class == "book" then return fn(...) end end
  end
  return f
end

-- scale= on a ::: block or a [span] (Rony, 23-Oct: "a block in a smaller
-- size, such that the code does not get broken up", as in md2slides): the
-- block goes in rxscale (header.tex), the span in a group; the block stays
-- as it was for what comes after (a table, a figure...)
local function scale_of(el)
  local v = el.attributes.scale
  if not v then return nil end
  el.attributes.scale = nil
  local x = tonumber(v)
  if not x or x <= 0 or x > 10 then
    warn("scale=" .. v .. ": not a scale (0.85, say); left out")
    return nil
  end
  return x
end

local filters = {
  {
    -- caption= on code that is not Rexx (FencedCode captions the Rexx), as
    -- on the pages: "Listing 1." and the text, above (20261102: it was lost)
    CodeBlock = function(cb)
      local c = cb.attributes.caption
      if not c then return nil end
      cb.attributes.caption = nil
      return { latexb("\\rxcaption{" .. texescape(c) .. "}"), cb }
    end,
    -- A style= on a span () has no LaTeX: said, not
    -- dropped in silence (20261102)
    Span = function(s)
      local st = s.attributes.style
      if st and st ~= "" then
        warn('style="' .. st .. '" on "' .. pandoc.utils.stringify(s.content) ..
          '" has no LaTeX: the text is kept, the style left out')
      end
    end,
  },
  {
    Div = function(div)
      local x = scale_of(div)
      if not x then return nil end
      return { latexb("\\begin{rxscale}{" .. x .. "}"), div, latexb("\\end{rxscale}") }
    end,
    -- blanks= / {.blanks} on code that is not Rexx (Rexx is the highlighter's):
    -- every blank, the open box, also where Pandoc writes the block (articles)
    CodeBlock = function(cb)
      local b = cb.attributes.blanks
      if cb.attributes.spot then return nil end     -- code_block: after the marks
      if cb.classes:includes("blanks") or b == "all" or b == "data" then
        cb.text = cb.text:gsub(" ", "\u{2423}")
        return cb
      end
    end,
    Span = function(span)
      local x = scale_of(span)
      if not x then return nil end
      return { latex("\\begingroup\\rxsetscale{" .. x .. "}"), span, latex("\\endgroup{}") }
    end,
  },
  {
    Meta = function(m)
      local function get(k) return m[k] and pandoc.utils.stringify(m[k]) end
      class = get("rexxpub-class") or class
      header_file = get("rexxpub-header")
      doc_tables.grid = (get("rexxpub-tables-grid") or "") == "true"
      doc_tables.stripes = stripes_value(get("rexxpub-tables-stripes"))
      twocolumn_meta = get("rexxpub-twocolumn") == "true"
      book.dir = get("rexxpub-dir") or book.dir
      book.listing_label = get("rexxpub-listing-label") or book.listing_label
      book.numbering = get("rexxpub-listing-numbering")
      book.toc_depth = get("rexxpub-toc-depth")
      -- The pens of the document's style ("BAR:BG:A BAR:BG:A ..."), for the
      -- marks of the blocks that are not Rexx; the ground and frame of blocks
      local p, n = get("rexxpub-pens"), 0
      for bar, bg, a in (p or ""):gmatch("(%x+):(%x+):(%d+)") do
        n = n + 1
        if n <= 4 then pens[n] = { bar = bar, bg = bg, a = a } end
      end
      doc_blocks = spots.defaults(m)
    end,
  },
  {
    -- The title page first: it still holds its raw . (A book's title
    -- page is written by the book filters.)
    Div = function(div)
      if class ~= "book" and div.classes:includes("title-page") then return title_page(div) end
    end,
  },
  {
    Inlines = fix_inlines,
  },
}
for _, f in ipairs(book_filters) do table.insert(filters, only_books(f)) end

-- Code in the text with its blanks (20261102), where the book filters have
-- not taken it (an article's, or a book's that is not .out)
table.insert(filters, {
  Code = function(c)
    if wants_blanks(c) then return latex("\\texttt{" .. code_text(c) .. "}") end
  end,
})

-- A table in a ::: (20261102): what the ::: says of its columns and its
-- lines (cols=, rules=, .grid, .stripes) is read in any class, as md2html
-- reads it (cgi/tables.lua); it was read only on a book's ::: {.table},
-- which the book filters have taken by now. In an article, a
-- ::: {#id .table} gives its last paragraph to the table as its caption,
-- which LaTeX numbers ("Table 1"), and its id to the table, as a \label
-- (a book does this in table_div). A pass of its own: in
-- one pass the table would be dressed, plainly, before its ::: is seen.
table.insert(filters, {
  Div = function(div)
    local n = 0
    for _, b in ipairs(div.content) do
      if b.t == "Table" and not b.attr.attributes["rx-dressed"] then n = n + 1 end
    end
    if n == 0 then return nil end
    local body, cap = div.content, nil
    if class ~= "book" and n == 1 and div.classes:includes("table") then
      body, cap = para_of(div.content)
    end
    local out = pandoc.List()
    for _, b in ipairs(body) do
      if b.t == "Table" and not b.attr.attributes["rx-dressed"] then
        if cap then
          b.caption = { long = { pandoc.Plain(cap) } }
          if div.identifier ~= "" then
            b.identifier = div.identifier
            div.identifier = ""                 -- one \label, the table's
          end
          cap = nil
        end
        local mark = table_dress(b, div.attributes, div.classes)
        if mark then out:insert(mark) end
      end
      out:insert(b)
    end
    div.content = out
    return div
  end,
})

-- What a div of the article means, by its class
local function rest_div(div)
  local c = div.classes
  if c:includes("abstract")  then return abstract_div(div) end
  if c:includes("keywords")  then return keywords_div(div) end
  if c:includes("noindent")  then return noindent(div) end
  if c:includes("epigraph")  then return epigraph(div) end
  if c:includes("quotation") then return environment("quotation", div) end
  if c:includes("quote")     then return environment("quote", div) end
  if c:includes("center")    then return environment("center", div) end
end

local rest = {
  {
    Div = function(div)
      local c = div.classes
      -- {.newpage} on any ::: (Rony, 25-Oct: each test of a document on a
      -- page of its own), as md2pdf does; on a heading, below. The div is
      -- still what its other classes say.
      if c:includes("newpage") then
        local i = 1
        while i <= #c do if c[i] == "newpage" then c:remove(i) else i = i + 1 end end
        local r = rest_div(div) or div
        local out = pandoc.List({ latexb("\\clearpage") })
        if pandoc.utils.type(r) == "Block" then out:insert(r) else out:extend(r) end
        return out
      end
      return rest_div(div)
    end,
    Table = function(tbl)
      local mark = nil
      if tbl.attr.attributes["rx-dressed"] then
        tbl.attr.attributes["rx-dressed"] = nil  -- its ::: did it already
      else
        mark = table_dress(tbl, nil, nil)       -- balanced, the document's way
      end
      local t = tbl
      if twocolumn[class] or twocolumn_meta then t = float_table(tbl) end
      if mark then return { mark, t } end
      return t
    end,
    Header = function(h)
      if h.classes:includes("newpage") then
        return { latexb("\\clearpage"), h }
      end
    end,
    -- Code that is still Pandoc's (an article's, or a fence with no class in
    -- a book): with marks, the highlighter's box, as in a book; with a ground
    -- or a frame, in rxframe
    CodeBlock = function(cb)
      if spot_of(cb) then return code_block(cb) end
      local before, after = dress_tex(function(k) return cb.attributes[k] end,
        cb.classes:includes("output") and "output" or "code", true, spots.lang(cb.classes))
      if before == "" then return nil end
      return { latexb(before), cb, latexb(after) }
    end,
    RawBlock = function(b)
      -- A Rexx listing (md2latex's BlockLatex): its ground and its frame
      if b.format == "latex" and b.text:find("\\rxdressbegin{", 1, true) then
        local t = b.text:gsub("\\rxdressbegin{(%a+)}{([^}]*)}", function(kind, attrs)
          local v, i = {}, 0
          for field in (attrs .. "|"):gmatch("([^|]*)|") do
            i = i + 1
            if field ~= "" then v[({ "background", "border", "border-width", "border-color" })[i]] = field end
          end
          local before, after = dress_tex(function(k) return v[k] end, kind, false, "rexx")
          return before ~= "" and before or "\\begin{rxdress}{}{}{}"
        end)
        t = t:gsub("\\rxdressend", function() return "\\end{rxdress}" end)
        return pandoc.RawBlock("latex", t)
      end
      if b.format == "html" then
        if b.text:match("^" .. WS .. "*...
(a terminal session, say): see pre_block. if b.text:match("^" .. WS .. "*<[Pp][Rr][Ee][ \t\n\r\f\v>]") then -- The red box of FencedCode: a Rexx block that does not parse. if b.text:match("^" .. WS .. "*
 0 then
          doc.meta.subtitle = pandoc.MetaInlines(t.subtitle)
        end
        if t.date then
          if class == "acmart" then
            warn("acmart: the date is left out (the class prints the conference's)")
          else
            doc.meta.date = pandoc.MetaInlines({ latex(t.date) })
          end
        end
        if #t.authors > 0 then
          local list, extra = authors(t.authors)
          local meta = pandoc.List()
          for _, a in ipairs(list) do meta:insert(pandoc.MetaInlines({ latex(a) })) end
          doc.meta.author = pandoc.MetaList(meta)
          if extra then add_header(doc.meta, extra) end
        end
      end
      -- acmart: authors from the YAML (author:) are \author{...} too
      if class == "acmart" and not (t and #t.authors > 0) and doc.meta.author then
        local a, meta = doc.meta.author, pandoc.List()
        if pandoc.utils.type(a) ~= "List" then a = { a } end
        for _, x in ipairs(a) do
          meta:insert(pandoc.MetaInlines({ latex("\\author{" .. tex(pandoc.Inlines(x)) .. "}") }))
        end
        doc.meta.author = pandoc.MetaList(meta)
      end
      local deep = deep_lists(doc.blocks)
      if deep then add_header(doc.meta, deep) end
      -- The language is md2latex's header's (babel with bidi): Pandoc's
      -- template would load babel again
      doc.meta.lang = nil
      if abstract then doc.meta.abstract = pandoc.MetaBlocks(abstract) end
      if not keywords and doc.meta.keywords then
        local k, ks = doc.meta.keywords, {}
        if pandoc.utils.type(k) == "List" then
          for _, x in ipairs(k) do table.insert(ks, pandoc.utils.stringify(x)) end
        else
          table.insert(ks, pandoc.utils.stringify(k))
        end
        keywords = tex(pandoc.Inlines(table.concat(ks, ", ")))
      end
      if keywords and class == "acmart" then  -- \keywords, before \maketitle
        doc.meta["rexxpub-keywords"] = pandoc.MetaInlines({ latex(keywords) })
      elseif keywords then
        local ab, m = pandoc.Blocks({}), doc.meta.abstract
        local ty = m and pandoc.utils.type(m)
        if ty == "Blocks" then ab:extend(m)
        elseif ty == "Inlines" then ab:insert(pandoc.Plain(m))
        elseif m then ab:insert(pandoc.Plain(pandoc.Inlines(pandoc.utils.stringify(m))))
        end
        ab:insert(latexb(keywords_tex(keywords)))
        doc.meta.abstract = pandoc.MetaBlocks(ab)
      end
      return doc
    end,
  },
}
for _, f in ipairs(rest) do table.insert(filters, f) end
return filters