1.0.2: converter searches no subfolders, safer filters, forms, links and watermark
A document at the root of a checkout of 68377 folders needed 56 minutes, because the converter named the suite, the document folder and the build folder with `//` in TEXINPUTS; it now names them without recursion and the same document converts in 11.5 seconds. A file below the document no longer replaces a package of TeX Live. The security review of the pending changes found four defects, each fixed with a test proven red against the old files and green against the new ones twice: an HTML table read in an empty sandbox, so an iframe opens no address; form labels written through the LaTeX writer, so they are set as text; the form pattern scans a line once instead of quadratically; a kept build folder no longer lays the links of an earlier drawing over a new one. The form tests remove the PDF of an earlier run before each conversion. Also carried: forms out of Markdown, link colours from the company, clickable links in prose, HTML tables and SVG drawings, the watermark, and the further changes of 1.0.1 and 1.0.2 in the CHANGELOG. npm test: 1232 of 1232 checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
adc58e19d7
commit
d7aac52ac7
28 files changed
+3918
-137
No files matched your search
+40
-8
@@ -13,20 +13,47 @@
|
||||
-- `CreditCardCustomerBasicInfoSerializer` reads a boundary anyway. No hyphen is
|
||||
-- inserted: a hyphen in a path would be read as part of the path.
|
||||
--
|
||||
-- Only a span from 16 characters up is treated. The shortest one that left the
|
||||
-- type area in that document was `plim/settings.py:25` at 19 characters, and a
|
||||
-- short span finds room on the next line by itself, where breaking it would
|
||||
-- only make it harder to read.
|
||||
-- Every span that carries such a boundary is treated, however short it is. The
|
||||
-- rule used to start at 16 characters, on the reasoning that a shorter span
|
||||
-- finds room on the next line by itself; a style guide that lists the names of
|
||||
-- its convention refuted it. `--color-dark` and `--size-medium`, twelve and
|
||||
-- thirteen characters, stood in a row with one space between them, and the two
|
||||
-- lines carrying them ran 3.5 and 7.9 points past the edge while
|
||||
-- `--color-fg-error` beside them broke after a hyphen — a break in one place
|
||||
-- and none in the other, in one sentence.
|
||||
--
|
||||
-- A break that is OFFERED costs nothing: TeX takes it where a line cannot be
|
||||
-- set otherwise and leaves the span whole everywhere else, so the short span is
|
||||
-- still read in one piece on every line that has room for it.
|
||||
|
||||
local THRESHOLD = 16
|
||||
-- Where the name really begins: a name may OPEN with the characters that
|
||||
-- structure it — `--size-medium`, `.btn-primary`, `_private` — and there they
|
||||
-- structure nothing. A break between the two hyphens of a custom property, or
|
||||
-- directly behind them, leaves a line ending in `--` and a reader who copies
|
||||
-- the name with two pieces, neither of which is the name. So the run at the
|
||||
-- front belongs to the first piece, and the first break stands behind the first
|
||||
-- piece of content.
|
||||
--
|
||||
-- And the first piece is set in a box, because the break this forbids is not
|
||||
-- one this filter offers: TeX breaks after a hyphen of its own accord, in the
|
||||
-- typewriter face as anywhere else. Measured on the rendered page after the
|
||||
-- break points alone had been corrected — a line still ended in `--` with
|
||||
-- `font-size-large` on the next one. A box has no break inside it and none
|
||||
-- behind it where no space follows, which is exactly the two places.
|
||||
local function opening(text)
|
||||
local run = text:match('^[/._:%-]+')
|
||||
return run and #run or 0
|
||||
end
|
||||
|
||||
local function pieces(text)
|
||||
local parts, current = {}, ''
|
||||
local front = opening(text)
|
||||
for index = 1, #text do
|
||||
local char = text:sub(index, index)
|
||||
local following = text:sub(index + 1, index + 1)
|
||||
current = current .. char
|
||||
local structural = char:match('[/._:%-]') and following ~= ''
|
||||
local structural = index > front
|
||||
and char:match('[/._:%-]') and following ~= ''
|
||||
local camel = char:match('%l') and following:match('%u')
|
||||
if structural or camel then
|
||||
parts[#parts + 1] = current
|
||||
@@ -41,12 +68,17 @@ end
|
||||
|
||||
function Code(code)
|
||||
if not FORMAT:match('latex') then return nil end
|
||||
if #code.text < THRESHOLD then return nil end
|
||||
local parts = pieces(code.text)
|
||||
if #parts < 2 then return nil end
|
||||
local result = {}
|
||||
for index, part in ipairs(parts) do
|
||||
result[#result + 1] = pandoc.Code(part)
|
||||
if index == 1 and opening(code.text) > 0 then
|
||||
result[#result + 1] = pandoc.RawInline('latex', '\\mbox{')
|
||||
result[#result + 1] = pandoc.Code(part)
|
||||
result[#result + 1] = pandoc.RawInline('latex', '}')
|
||||
else
|
||||
result[#result + 1] = pandoc.Code(part)
|
||||
end
|
||||
if index < #parts then
|
||||
result[#result + 1] = pandoc.RawInline('latex', '\\allowbreak{}')
|
||||
end
|
||||
|
||||
+18
-4
@@ -67,11 +67,25 @@ function Image(image)
|
||||
end
|
||||
end
|
||||
|
||||
-- A picture alone in its paragraph, and a raster picture is alone with the
|
||||
-- mark of its kind in front of it: pandoc runs the function above over every
|
||||
-- picture before it looks at a paragraph, so the paragraph of a photograph
|
||||
-- holds two things by then. Counted as one, it lost its caption until
|
||||
-- 2026-10-05.
|
||||
local function alone(content)
|
||||
if #content == 1 then return content[1], nil end
|
||||
if #content == 2 and content[1].t == 'RawInline'
|
||||
and content[1].text == '\\businessbitmap' then
|
||||
return content[2], content[1]
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
function Para(para)
|
||||
if #para.content ~= 1 then return nil end
|
||||
local image = para.content[1]
|
||||
if image.t ~= 'Image' or #image.caption == 0 then return nil end
|
||||
local image, mark = alone(para.content)
|
||||
if not image or image.t ~= 'Image' or #image.caption == 0 then return nil end
|
||||
local shown = mark and pandoc.Plain{ mark, image } or pandoc.Plain{ image }
|
||||
return pandoc.Figure(
|
||||
pandoc.Blocks{ pandoc.Plain{ image } },
|
||||
pandoc.Blocks{ shown },
|
||||
{ long = pandoc.Blocks{ pandoc.Plain(image.caption) } })
|
||||
end
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
-- Copyright (c) 2026 Marc Wäckerlin. SPDX-License-Identifier: MIT
|
||||
-- A chapter somebody ticks and writes into becomes a form of the PDF.
|
||||
--
|
||||
-- The two shapes a writer uses are the ones GitHub, GitLab and Gitea already
|
||||
-- render, so the Markdown stays readable where it is read:
|
||||
--
|
||||
-- - [ ] **S1 Title.** What is to be confirmed
|
||||
--
|
||||
-- Remarks: ____________
|
||||
--
|
||||
-- A task list item becomes a checkbox, named after the identifier in the bold
|
||||
-- lead-in of the item; where an item carries none, it is named after its place
|
||||
-- in the document, `q1`, `q2`. A paragraph that is a label, a colon and a run
|
||||
-- of underscores becomes a text field, named after the item it stands in,
|
||||
-- `S1-remarks`, and after its label where it stands by itself.
|
||||
--
|
||||
-- A run of underscores ALONE is a thematic break in all three platforms and in
|
||||
-- pandoc, so a field is only ever made where a label stands in front of it; a
|
||||
-- rule stays a rule.
|
||||
--
|
||||
-- How many lines a field takes follows from where it stands, which is what the
|
||||
-- writer has already said by writing it there: inside a list item it is the
|
||||
-- remark on that item and takes three lines; alone in its section it is the
|
||||
-- large field at the end of a form and takes six; anywhere else it is a line of
|
||||
-- a signature block and takes one. Every one of them scrolls, so no entry is
|
||||
-- ever cut off.
|
||||
-- How many characters a line of the body text holds, measured in the probe the
|
||||
-- converter builds with the identity of the company and handed over in the
|
||||
-- environment, as the filters for tables and announcing sentences read it.
|
||||
local LINE = (tonumber(os.getenv('MD2PDF_LINEWIDTH')) or 538)
|
||||
/ (tonumber(os.getenv('MD2PDF_CHARACTER')) or 5.3)
|
||||
|
||||
local NESTED_LINES = 3
|
||||
-- A field that stands alone between two headings is the large one at the end
|
||||
-- of a form, where somebody writes as much as he has to say. Fourteen lines is
|
||||
-- the free half of a page under a short section, measured on the sign-off
|
||||
-- chapter it was written for; the field scrolls, so what is written is never
|
||||
-- bounded by it.
|
||||
local SECTION_LINES = 14
|
||||
local SINGLE_LINES = 1
|
||||
|
||||
-- The character pandoc's gfm reader writes for a task list item, ticked and
|
||||
-- unticked. They are the first inline of the item's first block.
|
||||
local UNTICKED = '\u{2610}'
|
||||
local TICKED = '\u{2612}'
|
||||
|
||||
local counted = 0
|
||||
local seen = {}
|
||||
|
||||
local function unique(name)
|
||||
local candidate, number = name, 1
|
||||
while seen[candidate] do
|
||||
number = number + 1
|
||||
candidate = name .. '-' .. number
|
||||
end
|
||||
seen[candidate] = true
|
||||
return candidate
|
||||
end
|
||||
|
||||
-- The name of a field, out of the text the writer wrote: the identifier of the
|
||||
-- bold lead-in, or the label of the line. Everything that is not a letter, a
|
||||
-- digit or a dash becomes a dash, because a field name travels into the PDF and
|
||||
-- is read there by whoever evaluates the filled file.
|
||||
local function slug(text)
|
||||
local name = text:gsub('[^%w%-]+', '-'):gsub('^%-+', ''):gsub('%-+$', '')
|
||||
return name
|
||||
end
|
||||
|
||||
local function identifier(blocks)
|
||||
local first = blocks[1]
|
||||
if not first or not first.content then return nil end
|
||||
for _, inline in ipairs(first.content) do
|
||||
if inline.t == 'Strong' then
|
||||
local word = pandoc.utils.stringify(inline):match('^%s*([%w%._%-]+)')
|
||||
if word then return slug(word) end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- A paragraph that is a field: a label, a colon, and three or more underscores
|
||||
-- with nothing after them.
|
||||
local function field_of(block)
|
||||
if block.t ~= 'Para' and block.t ~= 'Plain' then return nil end
|
||||
local text = pandoc.utils.stringify(block)
|
||||
local label, rule = text:match('^%s*(.-)%s*:%s*(_+)%s*$')
|
||||
if not label or label == '' or #rule < 3 then return nil end
|
||||
return label
|
||||
end
|
||||
|
||||
local function task_of(block)
|
||||
if block.t ~= 'Para' and block.t ~= 'Plain' then return nil end
|
||||
local first = block.content and block.content[1]
|
||||
if not first or first.t ~= 'Str' then return nil end
|
||||
if first.text == UNTICKED or first.text == TICKED then
|
||||
return first.text == TICKED
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function latex(text)
|
||||
return pandoc.RawBlock('latex', text)
|
||||
end
|
||||
|
||||
-- What stands beside the box: the item without the character pandoc wrote for
|
||||
-- the box, and without the space behind it.
|
||||
local function beside(block)
|
||||
local kept = {}
|
||||
for index, inline in ipairs(block.content) do
|
||||
if index == 1 then
|
||||
-- the box character itself
|
||||
elseif index == 2 and inline.t == 'Space' then
|
||||
-- the space behind it
|
||||
else
|
||||
kept[#kept + 1] = inline
|
||||
end
|
||||
end
|
||||
return pandoc.Para(kept)
|
||||
end
|
||||
|
||||
local function render(inlines)
|
||||
local document = pandoc.Pandoc({pandoc.Plain(inlines)})
|
||||
return pandoc.write(document, 'latex')
|
||||
end
|
||||
|
||||
-- The label of a field as LaTeX text: a brace, a backslash, `%`, `&`, `#` or
|
||||
-- `_` in it is written as the character, never read as a command.
|
||||
local function text_of(label)
|
||||
return (render({pandoc.Str(label)}):gsub('%s+$', ''))
|
||||
end
|
||||
|
||||
-- One item of a task list: the box, the text beside it, and the fields the item
|
||||
-- carries under it.
|
||||
local function item(blocks, ticked)
|
||||
local name = identifier(blocks)
|
||||
if not name then
|
||||
counted = counted + 1
|
||||
name = 'q' .. counted
|
||||
end
|
||||
name = unique(name)
|
||||
-- The room the whole item needs, so that it moves to the next page as one
|
||||
-- thing: the lines its text takes, the label of every field under it, the
|
||||
-- height of those fields, and the space around them. A page that breaks
|
||||
-- inside an item lets the reader tick on one page and write on the next —
|
||||
-- reported from a sign-off chapter where item S7 stood at the foot of page 4
|
||||
-- and its frame began page 5.
|
||||
local text = pandoc.utils.stringify(blocks[1])
|
||||
local needed = math.max(1, math.ceil(#text / LINE)) + 1
|
||||
for index = 2, #blocks do
|
||||
if field_of(blocks[index]) then
|
||||
needed = needed + NESTED_LINES + 2
|
||||
end
|
||||
end
|
||||
local made = pandoc.Blocks{}
|
||||
made:insert(latex('\\businessneed{' .. needed .. '}'))
|
||||
local option = ticked and '[checked=true]' or ''
|
||||
made:insert(latex('\\businesscheckbox' .. option .. '{' .. name .. '}{'
|
||||
.. render(beside(blocks[1]).content) .. '}'))
|
||||
for index = 2, #blocks do
|
||||
local label = field_of(blocks[index])
|
||||
if label then
|
||||
-- The suffix is written small whatever the label looks like: the
|
||||
-- identifier of the item is the name of the thing, the suffix says which
|
||||
-- field of it, and whoever evaluates the filled file reads `S1-remarks`.
|
||||
made:insert(latex('\\businessremark{' .. name .. '-'
|
||||
.. slug(label):lower()
|
||||
.. '}{' .. text_of(label) .. '}{' .. NESTED_LINES .. '}'))
|
||||
else
|
||||
made:insert(blocks[index])
|
||||
end
|
||||
end
|
||||
return made
|
||||
end
|
||||
|
||||
-- The document is walked from the top, and a list is descended into here. A
|
||||
-- `Blocks` filter would run on the content of a list item as well, and the
|
||||
-- remark under an item would be read there, out of reach of the item it
|
||||
-- belongs to: it then became a line of a signature block named after its own
|
||||
-- label, and three items carried three fields called «Remarks».
|
||||
local function walk(blocks)
|
||||
local kept = pandoc.Blocks{}
|
||||
for index, block in ipairs(blocks) do
|
||||
local label = field_of(block)
|
||||
if label then
|
||||
-- Alone between two headings it is the large field of the form, beside
|
||||
-- other paragraphs it is a line of a signature block.
|
||||
local before = blocks[index - 1]
|
||||
local after = blocks[index + 1]
|
||||
local alone = (not before or before.t == 'Header')
|
||||
and (not after or after.t == 'Header')
|
||||
local lines = alone and SECTION_LINES or SINGLE_LINES
|
||||
local name = unique(slug(label))
|
||||
if alone then
|
||||
kept:insert(latex('\\businessremark{' .. name .. '}{' .. text_of(label)
|
||||
.. '}{' .. lines .. '}'))
|
||||
else
|
||||
-- Every label of a block of lines gets the width of the widest of
|
||||
-- them, so the frames begin on one edge: the labels of a signature
|
||||
-- block are of different lengths, and each pushed its own frame.
|
||||
local block_labels = {label}
|
||||
for ahead = index + 1, #blocks do
|
||||
local next_label = field_of(blocks[ahead])
|
||||
if not next_label then break end
|
||||
block_labels[#block_labels + 1] = next_label
|
||||
end
|
||||
for back = index - 1, 1, -1 do
|
||||
local earlier = field_of(blocks[back])
|
||||
if not earlier then break end
|
||||
table.insert(block_labels, 1, earlier)
|
||||
end
|
||||
-- Which of them is the widest is measured in the type, by the
|
||||
-- template; a label that carries a comma is left out, because the
|
||||
-- list is read as one.
|
||||
local listed = {}
|
||||
for _, one in ipairs(block_labels) do
|
||||
if not one:find(',') then listed[#listed + 1] = text_of(one) end
|
||||
end
|
||||
kept:insert(latex('\\businesslabelwidth{'
|
||||
.. table.concat(listed, ',') .. '}'))
|
||||
kept:insert(latex('\\businessline{' .. name .. '}{' .. text_of(label) .. '}'))
|
||||
end
|
||||
elseif block.t == 'BulletList' then
|
||||
local tasks = pandoc.Blocks{}
|
||||
local every = true
|
||||
for _, entry in ipairs(block.content) do
|
||||
local ticked = task_of(entry[1])
|
||||
if ticked == nil then
|
||||
every = false
|
||||
break
|
||||
end
|
||||
tasks:extend(item(entry, ticked))
|
||||
end
|
||||
if every then
|
||||
kept:extend(tasks)
|
||||
else
|
||||
kept:insert(block)
|
||||
end
|
||||
else
|
||||
kept:insert(block)
|
||||
end
|
||||
end
|
||||
return kept
|
||||
end
|
||||
|
||||
function Pandoc(document)
|
||||
if not FORMAT:match('latex') then return nil end
|
||||
return pandoc.Pandoc(walk(document.blocks), document.meta)
|
||||
end
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Copyright (c) 2026 Marc Wäckerlin. SPDX-License-Identifier: MIT
|
||||
-- HTML structures that GitHub renders and the LaTeX writer otherwise drops.
|
||||
|
||||
-- A raw HTML table remains one table in the Markdown source, including merged
|
||||
-- cells. Reading that block as HTML gives pandoc a native Table with row and
|
||||
-- column spans, which every output writer can then render.
|
||||
function RawBlock(block)
|
||||
if block.format ~= 'html' or not block.text:match('^%s*<table[%s>]') then
|
||||
return nil
|
||||
end
|
||||
-- The reader runs in an empty sandbox: an `<iframe>` or a picture in the
|
||||
-- table would otherwise make the build open its address and paste what came
|
||||
-- back into the PDF.
|
||||
return pandoc.read(block.text, 'html', nil, {}).blocks
|
||||
end
|
||||
|
||||
-- An empty anchor inside a Markdown table is a stable destination in the web
|
||||
-- rendering. In LaTeX raw HTML is omitted, so turn it into the equivalent
|
||||
-- native Span and let pandoc write the label.
|
||||
function RawInline(inline)
|
||||
if inline.format ~= 'html' then return nil end
|
||||
local id = inline.text:match('^%s*<a%s+id=["\']([^"\']+)["\']%s*>%s*$')
|
||||
if id then return pandoc.Span({}, pandoc.Attr(id)) end
|
||||
if inline.text:match('^%s*</a>%s*$') then return {} end
|
||||
return nil
|
||||
end
|
||||
Executable
+97
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright (c) 2026 Marc Wäckerlin. SPDX-License-Identifier: MIT
|
||||
"""Convert the SVG drawings of a company to the PDF form LaTeX includes.
|
||||
|
||||
No TeX engine reads an SVG, so a company that has its logo as an SVG gets a PDF
|
||||
of the same name beside it, and the identity names the logo without a format:
|
||||
`logo = company-logo` finds `company-logo.pdf`. The SVG stays the source.
|
||||
|
||||
logo.py <directory> [<directory> …] convert every drawing
|
||||
logo.py --check <directory> [<directory> …] name every PDF that is
|
||||
missing or older than its SVG
|
||||
|
||||
Only the directories named are read, not their folders: a company keeps its
|
||||
drawings beside its identity, and a tree further down is somebody else's.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
# A shell opened by a snap-packaged editor can point a system Inkscape at the
|
||||
# editor's GTK modules and settings schemas. The resulting process aborts before
|
||||
# reading the SVG. These paths belong to the parent application, not to the
|
||||
# converter subprocess.
|
||||
SNAP_LEAKS = ("GSETTINGS_SCHEMA_DIR", "GTK_PATH", "GIO_MODULE_DIR",
|
||||
"GTK_IM_MODULE_FILE", "XDG_DATA_DIRS")
|
||||
|
||||
|
||||
def inkscape_environment():
|
||||
"""The caller's environment without GTK paths owned by an editor snap."""
|
||||
environment = os.environ.copy()
|
||||
for name in SNAP_LEAKS:
|
||||
environment.pop(name, None)
|
||||
return environment
|
||||
|
||||
|
||||
def drawings(directory):
|
||||
"""Every SVG of one directory, as pairs of source and target."""
|
||||
return [(os.path.join(directory, name),
|
||||
os.path.join(directory, os.path.splitext(name)[0] + ".pdf"))
|
||||
for name in sorted(os.listdir(directory))
|
||||
if name.lower().endswith(".svg")]
|
||||
|
||||
|
||||
def stale(source, target):
|
||||
"""True where the PDF has to be made again."""
|
||||
return not os.path.exists(target) \
|
||||
or os.path.getmtime(target) < os.path.getmtime(source)
|
||||
|
||||
|
||||
def convert(source, target):
|
||||
"""inkscape, the converter the drawing filter of the suite uses as well."""
|
||||
result = subprocess.run(
|
||||
["inkscape", "--export-type=pdf", "--export-filename=" + target,
|
||||
source],
|
||||
env=inkscape_environment(),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
encoding="utf-8", errors="replace")
|
||||
if result.returncode != 0 or not os.path.exists(target):
|
||||
return f"{source}: inkscape could not convert the drawing:\n" \
|
||||
f"{result.stdout.strip()}"
|
||||
print(target)
|
||||
return None
|
||||
|
||||
|
||||
def main(arguments=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("directories", nargs="+", metavar="directory")
|
||||
parser.add_argument("--check", action="store_true")
|
||||
options = parser.parse_args(arguments)
|
||||
missing = [directory for directory in options.directories
|
||||
if not os.path.isdir(directory)]
|
||||
for directory in missing:
|
||||
print(f"{directory}: there is no such directory", file=sys.stderr)
|
||||
if missing:
|
||||
return 1
|
||||
pairs = [pair for directory in options.directories
|
||||
for pair in drawings(directory)]
|
||||
if options.check:
|
||||
outdated = [(source, target) for source, target in pairs
|
||||
if stale(source, target)]
|
||||
for source, target in outdated:
|
||||
print(f"{target} is missing or older than {source}",
|
||||
file=sys.stderr)
|
||||
return 1 if outdated else 0
|
||||
failures = [failure for failure in
|
||||
(convert(source, target) for source, target in pairs
|
||||
if stale(source, target))
|
||||
if failure]
|
||||
for failure in failures:
|
||||
print(failure, file=sys.stderr)
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+79
-9
@@ -52,12 +52,35 @@ import tempfile
|
||||
# suite is: the filters beside it would then be looked for in the directory of
|
||||
# the link, and the document would be built without them.
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
# The directory of the packages and classes of the suite, the one directory of
|
||||
# it LaTeX needs: the rest of the repository holds examples and test builds.
|
||||
PACKAGES = os.path.join(ROOT, "texmf", "tex", "latex", "business-suite")
|
||||
FILTERS = [os.path.join(ROOT, "bin", name) for name in
|
||||
("details.lua", "svg.lua", "links.lua",
|
||||
("html.lua", "details.lua", "svg.lua", "links.lua",
|
||||
# Before the table filter: that one wraps a table in a group of its
|
||||
# own, and the sentence above would then no longer stand directly in
|
||||
# front of a table.
|
||||
"leadin.lua", "tables.lua", "code.lua", "figures.lua")]
|
||||
"leadin.lua", "tables.lua", "code.lua", "figures.lua",
|
||||
# Last: a checkbox and a field are raw LaTeX, and a filter that
|
||||
# reads the text of a paragraph would no longer find them.
|
||||
"forms.lua")]
|
||||
|
||||
# A terminal opened by a snap-packaged editor can point a system Inkscape at
|
||||
# the editor's GTK modules and settings schemas. The SVG filter starts Inkscape
|
||||
# through pandoc, so remove paths that belong to the parent application from
|
||||
# every converter subprocess.
|
||||
SNAP_LEAKS = ("GSETTINGS_SCHEMA_DIR", "GTK_PATH", "GIO_MODULE_DIR",
|
||||
"GTK_IM_MODULE_FILE", "XDG_DATA_DIRS")
|
||||
|
||||
# What makes a document a form: a task list item, which every platform renders
|
||||
# as a checkbox, and a paragraph that is a label, a colon and a run of
|
||||
# underscores. A document that carries neither gets no form dictionary, so
|
||||
# nothing about it changes.
|
||||
# The label part is written so that a line is scanned once: `^.*\S.*:` tried
|
||||
# every split of a line between its two `.*`, and a line of 40000 characters took
|
||||
# a second.
|
||||
FORM = re.compile(r"^\s*(?:[-*+]\s+\[[ xX]\]\s)|^[^\S\n]*\S[^\n]*?:\s*_{3,}\s*$",
|
||||
re.MULTILINE)
|
||||
|
||||
# Which language a document is written in decides where LaTeX may break a word,
|
||||
# and the wrong patterns break it in the wrong places: German patterns put
|
||||
@@ -128,8 +151,11 @@ LENGTH = re.compile(r"^(\w+) ([0-9.]+)pt$", re.MULTILINE)
|
||||
|
||||
def run(command, cwd, environment=None):
|
||||
"""One external command; its output comes back as text."""
|
||||
inherited = os.environ.copy()
|
||||
for name in SNAP_LEAKS:
|
||||
inherited.pop(name, None)
|
||||
return subprocess.run(command, cwd=cwd,
|
||||
env=dict(os.environ, **(environment or {})),
|
||||
env=dict(inherited, **(environment or {})),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
encoding="utf-8", errors="replace")
|
||||
|
||||
@@ -154,8 +180,30 @@ def language(source, given):
|
||||
|
||||
|
||||
def searchpath(source_dir, build):
|
||||
"""Where LaTeX looks: the suite, the document, the build directory."""
|
||||
return os.pathsep.join([ROOT + "//", source_dir + "//", build + "//", ""])
|
||||
"""Where LaTeX looks: the package directory of the suite, what the caller
|
||||
searches, the document, the build directory, and the TeX tree.
|
||||
|
||||
What the caller searches comes BEFORE the document. A company whose identity
|
||||
lies outside the TeX tree names its directory in `TEXINPUTS`, and a file
|
||||
beside a document — a picture called `logo.pdf`, a package of the same name
|
||||
— must not stand in for the identity of the company. Until 2026-10-05 the
|
||||
converter replaced the search path of its caller, and such a company could
|
||||
not be built at all.
|
||||
|
||||
The converter's own entries name their directories without `//`, so no
|
||||
subfolder of them is searched. kpathsea expands `//` into every folder below
|
||||
the entry and tries each file name in all of them before it reaches the TeX
|
||||
tree, which comes last: for a document at the root of a checkout of 68377
|
||||
folders, one lookup of `fontspec.sty` took 257 seconds instead of 0.15, and
|
||||
the probe of one PDF ran for twelve and a half minutes, measured on
|
||||
2026-11-14. A file of the name of a TeX Live package anywhere below the
|
||||
document also replaced that package. A picture in a subfolder is named by
|
||||
its relative path from the document, which latexmk resolves in the directory
|
||||
of the document, so it needs no search.
|
||||
"""
|
||||
inherited = [entry for entry in
|
||||
os.environ.get("TEXINPUTS", "").split(os.pathsep) if entry]
|
||||
return os.pathsep.join([PACKAGES] + inherited + [source_dir, build, ""])
|
||||
|
||||
|
||||
def metrics(options, build, source_dir):
|
||||
@@ -171,8 +219,18 @@ def metrics(options, build, source_dir):
|
||||
"fontsize": options.fontsize,
|
||||
"identity": options.identity,
|
||||
"reference": REFERENCE})
|
||||
run(["xelatex", "-no-pdf", "-interaction=nonstopmode", "-halt-on-error",
|
||||
"metrics.tex"], cwd=build,
|
||||
# -no-shell-escape: the probe loads the identity from the search path, and
|
||||
# the directory of the document is on it, so a package lying there could
|
||||
# otherwise call the programs TeX Live allows in restricted mode.
|
||||
#
|
||||
# The probe is named by its full path. A bare file name is looked up through
|
||||
# the search path like a package, the suite and the directories of the
|
||||
# caller come before the build directory, and a `metrics.tex` an earlier
|
||||
# conversion left in the suite measured the example company for every
|
||||
# company: measured on 2026-10-05 in a Pacta document, whose head cells
|
||||
# stood past the right edge of the page.
|
||||
run(["xelatex", "-no-shell-escape", "-no-pdf", "-interaction=nonstopmode",
|
||||
"-halt-on-error", probe], cwd=build,
|
||||
environment={"TEXINPUTS": searchpath(source_dir, build)})
|
||||
written = os.path.join(build, "metrics.txt")
|
||||
if not os.path.exists(written):
|
||||
@@ -261,6 +319,11 @@ def to_latex(source, tex, build, options, measured):
|
||||
"-V", "header-includes=\\usepackage{" + options.identity + "}",
|
||||
"-V", "header-includes=\\usepackage{business-suite}",
|
||||
"-o", tex]
|
||||
with open(read, encoding="utf-8", errors="replace") as handle:
|
||||
if FORM.search(handle.read()):
|
||||
command[-2:-2] = ["-V", "header-includes=\\businessform"]
|
||||
print(f"{os.path.basename(source)}: a form, filled in and saved in "
|
||||
"the reader")
|
||||
if tag:
|
||||
command += ["-M", "lang=" + tag]
|
||||
print(f"{os.path.basename(source)}: {tag}")
|
||||
@@ -299,8 +362,15 @@ def row_rules(tex):
|
||||
|
||||
|
||||
def to_pdf(tex, build, source_dir):
|
||||
"""xelatex, through latexmk, with as many runs as the document needs."""
|
||||
return run(["latexmk", "-xelatex", "-interaction=nonstopmode",
|
||||
"""xelatex, through latexmk, with as many runs as the document needs.
|
||||
|
||||
-norc: latexmk would otherwise run the Perl code of a `latexmkrc` lying in
|
||||
the directory of the document, which is where it runs. -no-shell-escape:
|
||||
a package lying beside the document is found on the search path, and it
|
||||
could otherwise call the programs TeX Live allows in restricted mode.
|
||||
"""
|
||||
return run(["latexmk", "-norc", "-xelatex",
|
||||
"-latexoption=-no-shell-escape", "-interaction=nonstopmode",
|
||||
"-file-line-error", "-emulate-aux-dir",
|
||||
"-auxdir=" + build, "-outdir=" + build, tex],
|
||||
cwd=source_dir,
|
||||
|
||||
+86
-8
@@ -17,16 +17,94 @@ local function absolute(file)
|
||||
return file:sub(1, 1) == '/' and file or source .. '/' .. file
|
||||
end
|
||||
|
||||
-- Numbered, so that a/logo.svg and b/logo.svg do not share one PDF in the
|
||||
-- build directory, where the second overwrote the first. The output of a source
|
||||
-- path is remembered, so a drawing shown twice is converted once.
|
||||
local count = 0
|
||||
local converted_to = {}
|
||||
|
||||
local function number(value)
|
||||
return value and tonumber(value:match('[-+]?[%d.]+')) or nil
|
||||
end
|
||||
|
||||
local function attribute(tag, name)
|
||||
local escaped = name:gsub('(%W)', '%%%1')
|
||||
return tag:match(escaped .. '%s*=%s*"([^"]+)"')
|
||||
or tag:match(escaped .. "%s*=%s*'([^']+)'")
|
||||
end
|
||||
|
||||
local function linked_texts(svg, target)
|
||||
local view = svg:match('<svg[%s%S]-viewBox%s*=%s*"([^"]+)"')
|
||||
local min_x, min_y, width, height
|
||||
if view then
|
||||
min_x, min_y, width, height = view:match(
|
||||
'^%s*([-+%d.]+)%s+([-+%d.]+)%s+([-+%d.]+)%s+([-+%d.]+)')
|
||||
min_x, min_y, width, height = tonumber(min_x), tonumber(min_y),
|
||||
tonumber(width), tonumber(height)
|
||||
else
|
||||
local root = svg:match('<svg[%s%S]-%>') or ''
|
||||
min_x, min_y = 0, 0
|
||||
width, height = number(attribute(root, 'width')),
|
||||
number(attribute(root, 'height'))
|
||||
end
|
||||
if not width or not height or width == 0 or height == 0 then return end
|
||||
|
||||
local lines = {}
|
||||
for opening, body in svg:gmatch('(<a%s+[%s%S]-%>)([%s%S]-)</a>') do
|
||||
local href = attribute(opening, 'href')
|
||||
if href and href:match('^#[%w_.:-]+$') then
|
||||
for tag in body:gmatch('<text%s+[%s%S]-%>') do
|
||||
local x, y = number(attribute(tag, 'x')), number(attribute(tag, 'y'))
|
||||
local size = number(attribute(tag, 'font-size'))
|
||||
local length = number(attribute(tag, 'textLength'))
|
||||
if x and y and size and length then
|
||||
local left = (x - min_x) / width
|
||||
local bottom = 1 - (y + size * 0.25 - min_y) / height
|
||||
local link_width = length / width
|
||||
local link_height = size * 1.25 / height
|
||||
table.insert(lines, string.format(
|
||||
'\\businessimagelink{%s}{%.8f}{%.8f}{%.8f}{%.8f}',
|
||||
href:sub(2), left, bottom, link_width, link_height))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- A kept build folder still holds the links of the drawing that carried this
|
||||
-- number before; the template would lay them over this one.
|
||||
os.remove(target .. '.links.tex')
|
||||
if #lines == 0 then return end
|
||||
local sidecar, message = io.open(target .. '.links.tex', 'w')
|
||||
if not sidecar then
|
||||
error('the links of the drawing could not be written: ' .. tostring(message))
|
||||
end
|
||||
sidecar:write(table.concat(lines, '\n'), '\n')
|
||||
sidecar:close()
|
||||
end
|
||||
|
||||
function Image(image)
|
||||
if not image.src:lower():match('%.svg$') then return nil end
|
||||
local name = image.src:gsub('.*/', ''):gsub('%.[Ss][Vv][Gg]$', '') .. '.pdf'
|
||||
local target = build .. '/' .. name
|
||||
local converted, message = pcall(pandoc.pipe, 'inkscape',
|
||||
{'--export-type=pdf', '--export-filename=' .. target,
|
||||
absolute(image.src)}, '')
|
||||
if not converted then
|
||||
error('the drawing ' .. image.src .. ' could not be converted: '
|
||||
.. tostring(message))
|
||||
local source_path = absolute(image.src)
|
||||
local target = converted_to[source_path]
|
||||
if not target then
|
||||
count = count + 1
|
||||
local name = count .. '-'
|
||||
.. image.src:gsub('.*/', ''):gsub('%.[Ss][Vv][Gg]$', '') .. '.pdf'
|
||||
target = build .. '/' .. name
|
||||
local converted, message = pcall(pandoc.pipe, 'inkscape',
|
||||
{'--export-type=pdf', '--export-filename=' .. target, source_path}, '')
|
||||
if not converted then
|
||||
error('the drawing ' .. image.src .. ' could not be converted: '
|
||||
.. tostring(message))
|
||||
end
|
||||
local handle, read_message = io.open(source_path, 'r')
|
||||
if not handle then
|
||||
error('the drawing ' .. image.src .. ' could not be read: '
|
||||
.. tostring(read_message))
|
||||
end
|
||||
local svg = handle:read('*a')
|
||||
handle:close()
|
||||
linked_texts(svg, target)
|
||||
converted_to[source_path] = target
|
||||
end
|
||||
image.src = target
|
||||
return image
|
||||
|
||||
Reference in new issue
Block a user