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:
Marc WäckerlinandClaude Opus 5.5 committed 2026-11-14 12:14:55 +01:00
1 parent adc58e19d7
commit d7aac52ac7
28 files changed
+3918 -137

No files matched your search

+910
View File
@@ -7,7 +7,9 @@ the page is a property of the page, so it is measured there.
"""
import os
import re
import shutil
import sys
import zlib
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import support
@@ -34,6 +36,10 @@ OWN_VALUE = re.compile(r"^\s*(\\definecolor|\\colorlet|\\setmainfont"
# document is then built without what it does. Measured in a sister package on
# 2026-09-21, where the head height was measured by code that never ran.
ENDINPUT = re.compile(r"^\\endinput\s*$", re.MULTILINE)
# An option that stores its value in a macro of the template: the declaration,
# the option and at least one line that reads it are three mentions.
OPTION = re.compile(r"\\DeclareOptionX\{([a-z]+)\}\{\\(?:renewcommand\{|def)"
r"(\\business@[a-z]+)")
DOCUMENT = r"""\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
@@ -263,6 +269,18 @@ def source_checks(check):
used -= {"identity", "suite", "brief", "beamer"}
missing = sorted(used - declared)
check.that(not missing, f"roles read but never declared: {missing}")
# Every option of a template stores a value that a line of the template
# reads. An option that only stores takes what a company writes, raises no
# error and changes nothing: `titlelogoheight` did that from the day the
# logo left the title block until 2026-10-05.
for name in TEMPLATES:
with open(os.path.join(support.SUITE, name), encoding="utf-8") as handle:
text = handle.read()
for option, macro in OPTION.findall(text):
uses = len(re.findall(re.escape(macro) + r"(?![@a-zA-Z])", text))
check.that(uses > 2,
f"{name}: the option `{option}` stores `{macro}` and no "
"line of the template reads it")
def page_checks(check):
@@ -512,15 +530,907 @@ def tagline_colour(check):
"a colour named for the tagline changed the colour of the name")
BODY_DOCUMENT = r"""\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
%s
\begin{document}
Consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt.
\end{document}
"""
BODY_ROLE = BODY_DOCUMENT % r"\businesscolours{text=black!55}"
BODY_DEFAULT = BODY_DOCUMENT % ""
def body_colour(check):
"""The body text is set in the text role of the company.
LaTeX writes in its own pure black until it is told otherwise, and a brand
whose dark is not that black then carries a colour nobody chose on every
page of running text. Measured at the darkest pixel of each word, which is
the core of a stem and therefore the colour the type is set in: a company
that sets its text role to a 55 percent grey gets that grey, and one that
leaves it at black gets black, which is the control that proves the
measurement sees the colour at all.
"""
tone = {}
for name, fixture in (("role", BODY_ROLE), ("default", BODY_DEFAULT)):
source = support.write("bodycolour%s.tex" % name, fixture)
pdf, _ = build(source, EXAMPLES)
page = Page(pdf, 1)
found = {word[0]: word for word in support.words(pdf, 1)}
check.that("Consetetur" in found and "invidunt." in found,
f"the body text of the {name} fixture is not on the page")
if "Consetetur" not in found or "invidunt." not in found:
return
tone[name] = max(darkest(page, found["Consetetur"]),
darkest(page, found["invidunt."]))
check.that(tone["default"] < 40,
f"black body text comes out at {tone['default']}, so the "
"measurement does not see the colour of the type")
check.that(tone["role"] > 80,
f"a text role of 55 percent grey comes out at {tone['role']}: "
"the body text is not set in the text role of the company")
SVG_COMPANY = r"""\ProvidesPackage{svgcompany}[2026/10/05 A company with an SVG logo]
\RequirePackage{business-identity}
\setmainfont{Latin Modern Roman}
\businessfonts{default = rm, smallcaps = false}
\businessidentity{name = Svgcompany, lockup = banner, logo = svgmark}
\DeclareOption*{\PassOptionsToPackage{\CurrentOption}{business-suite}}
\ProcessOptions\relax
\RequirePackage{business-suite}
\endinput
"""
SVG_DOCUMENT = r"""\documentclass[a4paper,10pt]{article}
\usepackage[nologo]{svgcompany}
\begin{document}
\pagestyle{empty}
\noindent\logo[height=2cm]
\end{document}
"""
SVG_MARK = ('<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20">'
'<rect width="40" height="20" fill="#202020"/></svg>\n')
LOGO = os.path.join(support.ROOT, "bin", "logo.py")
def logo_from_svg(check):
"""A logo that exists as an SVG is a logo the company does not convert by hand.
No TeX engine reads an SVG, so `bin/logo.py` puts a PDF of the same name
beside it, and the identity keeps naming the logo without a format. A logo
the company has as an SVG alone stops the build with the command that
converts it: graphicx says «File not found» about a file the company can see
in its directory. Until 2026-10-05 the identity named `bin/logo.py` in a
comment, and the file did not exist.
"""
folder = os.path.join(support.BUILD, "svglogo")
shutil.rmtree(folder, ignore_errors=True)
os.makedirs(folder)
for name, text in (("svgcompany.sty", SVG_COMPANY),
("svgmark.svg", SVG_MARK),
("svglogo.tex", SVG_DOCUMENT)):
with open(os.path.join(folder, name), "w", encoding="utf-8") as handle:
handle.write(text)
check.that(support.run(["python3", LOGO, "--check", folder]).returncode == 1,
"logo.py --check calls an SVG without its PDF current")
# The build has to stop here, and `build` reports a stop as an exception;
# what it said stands in the log of the run either way.
try:
build(os.path.join(folder, "svglogo.tex"), folder)
except AssertionError:
pass
said = ""
log = os.path.join(support.BUILD, "svglogo", "svglogo.log")
if os.path.exists(log):
with open(log, encoding="utf-8", errors="replace") as handle:
said = handle.read()
check.that("exists as an SVG only" in said,
"a logo that exists as an SVG alone does not say how to convert "
"it")
converted = support.run(["python3", LOGO, folder])
check.that(converted.returncode == 0
and os.path.exists(os.path.join(folder, "svgmark.pdf")),
f"logo.py did not convert the SVG:\n{converted.stdout[-800:]}")
check.that(support.run(["python3", LOGO, "--check", folder]).returncode == 0,
"logo.py --check calls a freshly converted PDF out of date")
try:
pdf, _ = build(os.path.join(folder, "svglogo.tex"), folder)
except AssertionError:
pdf = ""
check.that(os.path.exists(pdf) and Page(pdf, 1).ink_rows(),
"the converted logo did not reach the page")
# Five addresses of the lengths a company really writes, each at three heights,
# one lockup to a page so that nothing else carries ink there.
ADDRESSES = ("https://nordwind.example",
"Nordwind AG, Hafenstrasse 4, 8000 Zurich",
"nordwind.ch",
"post@nordwind.example",
"Nordwind AG -- Lorem ipsum dolor sit amet consetetur sadipscing")
HEIGHTS = ("1cm", "2cm", "4cm")
ADDRESS_DOCUMENT = r"""\documentclass[a4paper,10pt]{article}
\usepackage[nologo]{nordwind}
\begin{document}
\pagestyle{empty}
""" + "\n\\newpage\n".join(
"\\businessidentity{address={%s}}\\noindent\\logo[address, nolink, "
"height=%s]" % (address, height)
for address in ADDRESSES for height in HEIGHTS) + r"""
\end{document}
"""
def address_on_logo(check):
"""The address line is as wide as the logo above it, at every height and for
every address, and the whole block scales with the height it is asked for.
The size of the line is derived from the two widths, never a factor of the
height: a factor fits one address and leaves the next one short of the logo
or over its edge. Five addresses, from one letter to a sentence, each at
1cm, 2cm and 4cm. The left edge of the logo is the ink of the icon, which
fills its own box, and the right edge is the box of the name.
And the block at twice the height is twice as large: its height from the top
of the icon to the foot of the address line, the width of the logo and the
width of the address line. A length read as a number drops its unit, and
that shows at one height and not at another. These are two of the measurements the package the suite
came out of carries and the suite did not, named as the condition for moving
that package onto the suite.
"""
source = support.write("addresses.tex", ADDRESS_DOCUMENT)
pdf, _ = build(source, EXAMPLES)
measured = {}
for index, (address, height) in enumerate(
(address, height) for address in ADDRESSES for height in HEIGHTS):
number = index + 1
found = support.words(pdf, number)
names = [word for word in found if word[0] == "Nordwind"]
check.that(names, f"page {number}: the lockup did not reach the page")
if not names:
continue
name = min(names, key=lambda word: word[2])
line = [word for word in found if word[2] > name[4] - 0.5]
check.that(line, f"page {number}: the address line is missing")
if not line:
continue
page = Page(pdf, number)
block = page.box()
# The left edge of the LOGO is read above the address line: the ink of
# the whole page begins with the address wherever the address reaches
# past the icon, and the comparison would then measure the address
# against itself. Measured on 2026-10-05, when a space in front of every
# icon put the address a word space left of it and this check stayed
# green.
top = min(word[2] for word in line)
logo_left = page.box(0, int(top * page.dpi / 72.0))[0]
logo_right = name[3]
left = min(word[1] for word in line)
right = max(word[3] for word in line)
check.that(abs(left - logo_left) < 1.5 and abs(right - logo_right) < 1.5,
f"«{address}» at {height}: the address runs from {left:.1f} to "
f"{right:.1f} and the logo from {logo_left:.1f} to "
f"{logo_right:.1f}")
measured[(address, height)] = (block[3] - block[1],
logo_right - logo_left, right - left)
for address in ADDRESSES:
for small, large in (("1cm", "2cm"), ("2cm", "4cm")):
one, two = measured.get((address, small)), measured.get((address,
large))
if not one or not two:
continue
for what, a, b in zip(("block", "logo", "address line"), one, two):
ratio = b / a if a else 0
check.that(1.94 < ratio < 2.06,
f"«{address}»: the {what} at {large} is {ratio:.3f} "
f"times the one at {small}, not twice")
MARKS_DOCUMENT = r"""\documentclass[a4paper,10pt]{article}
\usepackage[nologo]{nordwind}
\begin{document}
\pagestyle{empty}
\noindent{\fontsize{60}{72}\selectfont\success}
\newpage
\noindent{\fontsize{60}{72}\selectfont\fail}
\end{document}
"""
def marks_fill(check):
"""Each of the two marks is a white sign that fills a share of its box.
The page shows the box in any case; what it shows inside is the question. A
sign the symbol face does not carry leaves the box empty, a sign of another
face fills it in another share, and neither says a word in the log. The share
of white inside the box of each mark is read at 60 points: measured on
2026-10-05 at 0.12 for the check and 0.21 for the cross with DejaVu Sans, so
a window of 0.08 to 0.30 holds both and catches an empty box, which is no
white at all, and a box that lost its colour, which is nearly all white.
This is the last of the measurements the package the suite came out of
carried and the suite did not.
"""
source = support.write("marksfill.tex", MARKS_DOCUMENT)
pdf, _ = build(source, EXAMPLES)
for number, name in ((1, "success"), (2, "fail")):
page = Page(pdf, number)
box = page.box()
check.that(box, f"the {name} mark did not reach the page")
if not box:
continue
scale = page.dpi / 72.0
left, top = int(box[0] * scale), int(box[1] * scale)
right, bottom = int(box[2] * scale), int(box[3] * scale)
inside = [page.pixels[y * page.width + x]
for y in range(top, bottom + 1)
for x in range(left, right + 1)]
white = sum(1 for value in inside if value > 230) / max(1, len(inside))
check.that(0.08 < white < 0.30,
f"the white sign fills {white:.2f} of the box of the {name} "
"mark")
DECK = r"""\documentclass{beamer}
\usetheme{nordwind}
%s
\begin{document}
\begin{frame}{Lorem Ipsum}Consetetur sadipscing elitr.\end{frame}
\begin{frame}{Dolor Sit}At vero eos et accusam.\end{frame}
\end{document}
"""
DECK_PLAIN = DECK % ""
DECK_GROUND = DECK % (r"\businesscolours{canvas-top=red, canvas-bottom=blue,"
r" sidebar-top=green, sidebar-bottom=yellow}")
def deck_pixels(pdf, page):
"""The colour of one rendered slide, as a function of x and y in points."""
stem = os.path.join(support.BUILD, "deck")
result = support.run(["pdftoppm", "-r", "36", "-f", str(page), "-l",
str(page), "-singlefile", pdf, stem])
with open(stem + ".ppm", "rb") as handle:
data = handle.read()
fields, offset = [], 0
while len(fields) < 4:
end = data.index(b"\n", offset)
line = data[offset:end]
offset = end + 1
if not line.startswith(b"#"):
fields += line.split()
width = int(fields[1])
pixels = data[offset:]
def at(x, y):
index = 3 * (int(y / 2) * width + int(x / 2))
return tuple(pixels[index:index + 3])
return at, result.stdout
def deck_ground(check):
"""The ground of a slide and its sidebar take the roles of the company.
A company that names no colour for them keeps the deck of the family: white
ground, the sidebar in the brand colour. One that names two colours gets a
ground from the first at the top to the second at the bottom. The ground is
drawn as bands and not as a shading of beamer: xdvipdfmx writes such a
shading into the first page alone, and a reader of the PDF reported «XObject
'Fm2' is unknown» on every later slide. So the reader is asked as well.
"""
for name, fixture in (("plain", DECK_PLAIN), ("ground", DECK_GROUND)):
source = support.write("deck%s.tex" % name, fixture)
pdf, _ = build(source, EXAMPLES)
at, said = deck_pixels(pdf, 2)
check.that("Error" not in said,
f"the {name} deck makes the PDF reader report: {said[:200]}")
# A point of the ground at the right edge, top and bottom, away from
# the text; and a point of the sidebar at the left edge.
top, bottom = at(350, 60), at(350, 255)
if name == "plain":
check.that(min(top) > 240 and min(bottom) > 240,
f"a company without a ground of its own got {top} at "
f"the top and {bottom} at the bottom instead of white")
else:
# The two points lie a fifth of the way in from either end, so each
# carries some of the other colour; what they have to show is which
# of the two dominates.
check.that(top[0] > 150 and top[0] > 3 * top[2],
f"the top of the ground is {top}, not mostly the red "
"named for it")
check.that(bottom[2] > 150 and bottom[2] > 3 * bottom[0],
f"the bottom of the ground is {bottom}, not mostly the "
"blue named for it")
side_top, side_bottom = at(10, 60), at(10, 255)
check.that(side_top[1] > 100 and side_top[1] > 2 * side_top[0],
f"the top of the sidebar is {side_top}, not mostly the "
"green named for it")
check.that(side_bottom[0] > 150 and side_bottom[1] > 150
and side_bottom[2] < 100,
f"the bottom of the sidebar is {side_bottom}, not mostly "
"the yellow named for it")
NAMED_DOCUMENT = r"""\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
\begin{document}
\section{Lorem Ipsum}\label{lorem-ipsum}
Consetetur sadipscing elitr.
\end{document}
"""
def destinations(pdf):
"""The names of the places of a PDF that a link from outside can reach.
The names stand in the destination tree, partly in compressed object
streams, so the file is decompressed before it is read.
"""
with open(pdf, "rb") as handle:
data = handle.read()
chunks = [data]
for match in re.finditer(rb"stream\r?\n(.*?)endstream", data, re.S):
try:
chunks.append(zlib.decompress(match.group(1)))
except zlib.error:
continue
found = set()
for chunk in chunks:
for hit in re.finditer(rb"\(([A-Za-z0-9._-]+)\)\s*(?:\[|<<|\d+ \d+ R)",
chunk):
found.add(hit.group(1).decode("latin-1"))
return found
def named_destinations(check):
"""A section is reachable from another document by the name of its label.
A link from one document into a section of another carries the name of the
label there, and hyperref numbers its places unless it loads with
`destlabel`. The template passed that option AFTER the identity had loaded
hyperref, so it reached no company: measured on 2026-10-05, when a section
of a converted report carried no named place and a link into it opened the
report on page one.
"""
source = support.write("named.tex", NAMED_DOCUMENT)
pdf, _ = build(source, EXAMPLES)
places = destinations(pdf)
check.that("lorem-ipsum" in places,
"the section is not reachable by the name of its label; the "
"places are: " + ", ".join(sorted(places)[:12]))
RULE_DOCUMENT = r"""\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
%s
\begin{document}
\begin{tabular}{ll}
\toprule
Consetetur & sadipscing \\
\midrule
Elitr & sed \\ \businessrowrule
Diam & nonumy \\
\bottomrule
\end{tabular}
\end{document}
"""
RULE_ROLE = RULE_DOCUMENT % r"\businesscolours{text=black!55}"
RULE_DEFAULT = RULE_DOCUMENT % ""
def rule_tone(page):
"""The darkest pixel of the rules of a table, 0 to 255.
A rule is the one thing on the page that is dark over a long unbroken run of
a pixel row: a line of type has white between its letters. The darkest pixel
of those rows is the core of the heaviest rule, and that is its colour.
"""
darkest_found = 255
for y in range(page.height):
row = page.pixels[y * page.width:(y + 1) * page.width]
run = longest = 0
for value in row:
run = run + 1 if value < 200 else 0
longest = max(longest, run)
if longest > 100:
darkest_found = min(darkest_found, min(row))
return darkest_found
def rule_colour(check):
"""The rules of a table are drawn in the text role of the company.
colortbl draws in its own pure black until it is told otherwise, and the row
rule of this package reset the rules to exactly that black after every row:
a company whose text is a dark of its own then carried pure black in every
table. Measured on 2026-10-05 in a company whose palette ink is a black of
its own. A text role of 55 percent grey has to reach the rules, and black has
to stay black, which is the control that proves the measurement sees them.
"""
tone = {}
for name, fixture in (("role", RULE_ROLE), ("default", RULE_DEFAULT)):
source = support.write("rulecolour%s.tex" % name, fixture)
pdf, _ = build(source, EXAMPLES)
tone[name] = rule_tone(Page(pdf, 1))
check.that(tone["default"] < 40,
f"black rules come out at {tone['default']}, so the measurement "
"does not see the rules of the table")
check.that(tone["role"] > 80,
f"under a text role of 55 percent grey the rules come out at "
f"{tone['role']}: they are not drawn in the text role")
# A page of the furniture and nothing else: the title block, the running head,
# both heading levels, the two marks, a table with its rules, the foot. No
# picture, because a photograph carries the colours of whatever it shows and
# says nothing about the template that places it.
PALETTE_DOCUMENT = r"""\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
\title{Lorem Ipsum}
\author{Erika Muster}
\date{21 September 2026}
\begin{document}
\maketitle
\section{Consetetur}
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore. Done: \success{} Open: \fail{}
\subsection{Dolor Sit}
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
\begin{tabular}{lr}
\toprule
\businesstablehead{Lorem} & \businesstablehead{Ipsum} \\
\midrule
Consetetur sadipscing & 41 \\ \businessrowrule
Sed diam nonumy & 17 \\
\bottomrule
\end{tabular}
\end{document}
"""
def role_names():
"""Every colour role the package declares, read off the package."""
with open(os.path.join(support.SUITE, "business-identity.sty"),
encoding="utf-8") as handle:
text = handle.read()
return re.findall(r"^\\business@role\{([^}]+)\}", text, re.MULTILINE)
def role_inks(check, names):
"""What each role really comes out as, asked of xcolor in a probe.
The company assigns a role to a palette entry or to a mixture of two, and
only xcolor knows what that mixture is. A list of values written here would
be the palette of one company, which is the one thing this suite may not
carry.
"""
lines = "".join(
"\\convertcolorspec{named}{business-%s}{RGB}\\business@ink"
"\\typeout{ROLE %s \\business@ink}\n" % (name, name) for name in names)
source = support.write("paletteprobe.tex",
"\\documentclass[a4paper,10pt]{article}\n"
"\\usepackage{nordwind}\n\\makeatletter\n"
"\\AtBeginDocument{%%\n%s}\n\\makeatother\n"
"\\begin{document}Lorem.\\end{document}\n" % lines)
_, log = build(source, EXAMPLES)
with open(log, encoding="utf-8") as handle:
found = re.findall(r"^ROLE (\S+) ([\d.]+),([\d.]+),([\d.]+)\s*$",
handle.read(), re.MULTILINE)
inks = {name: tuple(round(float(value)) for value in triple)
for name, *triple in found}
check.that(len(inks) == len(names),
f"the probe reported {len(inks)} of the {len(names)} roles the "
"package declares")
return inks
def between(colour, first, second):
"""How far a pixel lies from the line between two colours of the palette.
A renderer draws the edge of a letter in the colours between the ink and
what lies under it, so every pixel of a page sits on the line between two
colours the page uses. The distance to that line says whether the pixel
belongs there, and a colour past both ends — a black darker than the one the
company declared — lies off it and is found.
"""
along = sum((one - other) * (one - other)
for one, other in zip(second, first))
if not along:
return max(abs(one - other) for one, other in zip(colour, first))
share = sum((end - start) * (pixel - start)
for end, start, pixel in zip(second, first, colour)) / along
share = min(1.0, max(0.0, share))
return max(abs(start + share * (end - start) - pixel)
for end, start, pixel in zip(second, first, colour))
# The same page twice: a company that says what its links look like, and one
# that says nothing. The word of the link stands alone in its paragraph, so its
# pixels are easy to find, and the fixture asks xcolor what the role really is,
# because a value written here would be the palette of one company.
LINKSTYLE = r"""\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
%s\makeatletter
\AtBeginDocument{\convertcolorspec{named}{business-link}{RGB}\business@ink
\typeout{ROLE link \business@ink}}
\makeatother
\begin{document}
\pagestyle{empty}
\noindent\href{https://nordwind.example}{Verweis}
\end{document}
"""
LINKSTYLE_SET = LINKSTYLE % ("\\businesscolours{link = nordwind-deep}\n"
"\\businesslinks{colour = link, "
"underline = true}\n")
LINKSTYLE_PLAIN = LINKSTYLE % ""
# The same setting with a table of contents: every entry of it is an internal
# link, so it takes the colour of the role, and a line under each of them would
# turn the contents page into a grid.
LINKSTYLE_CONTENTS = r"""\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
\businesscolours{link = nordwind-deep}
\businesslinks{colour = link, underline = true}
\begin{document}
\tableofcontents
\newpage
\section{Erster Abschnitt}
\noindent\href{https://nordwind.example}{Verweis}
\end{document}
"""
def painted(pdf, word=None):
"""Colours around one word, or on the page, with the rows they cover."""
stem = os.path.join(support.BUILD, "linkpage")
support.run(["pdftoppm", "-r", "150", "-f", "1", "-l", "1", "-singlefile",
pdf, stem])
with open(stem + ".ppm", "rb") as handle:
data = handle.read()
fields, offset = [], 0
while len(fields) < 4:
end = data.index(b"\n", offset)
line = data[offset:end]
offset = end + 1
if not line.startswith(b"#"):
fields += line.split()
width = int(fields[1])
pixels = data[offset:]
top, bottom = 0, len(pixels) // 3 // width
if word:
found = [item for item in support.words(pdf, 1) if item[0] == word]
if found:
scale = 150 / 72.0
top = max(0, int(found[0][2] * scale) - 3)
bottom = int(found[0][4] * scale) + 4
rows = {}
for index in range(0, len(pixels) - 2, 3):
row = index // 3 // width
if row < top or row > bottom:
continue
colour = tuple(pixels[index:index + 3])
if colour == (255, 255, 255):
continue
rows.setdefault(colour, set()).add(row)
return rows
def asked_role(log, name):
"""What the build reported for a role, out of its own log."""
with open(log, encoding="utf-8", errors="replace") as handle:
found = re.search(r"^ROLE %s ([\d.]+),([\d.]+),([\d.]+)\s*$" % name,
handle.read(), re.MULTILINE)
return tuple(round(float(value)) for value in found.groups()) if found \
else None
def link_style(check):
"""A link looks the way the company says, and nothing says it by default.
A reader of a PDF and a reader of the website of the same company see one
design, so the colour of a link is a role of the palette and the line under
it is a setting, both taken from the stylesheet of that company. Measured on
the rendered page: the word of the link stands in the colour of the role,
and the line under it in the same colour. What a PDF cannot carry is the
state of a link — there is no hover and no visited link on paper.
Without the setting a link keeps the colour of the text and carries no
line, which is what this package did before and what a printed page wants.
"""
styled, log = build(support.write("linkstyle.tex", LINKSTYLE_SET), EXAMPLES)
wanted = asked_role(log, "link")
check.that(wanted, "the build reported no colour for the role link")
if not wanted:
return
rows = painted(styled, "Verweis")
near = {colour: places for colour, places in rows.items()
if max(abs(colour[band] - wanted[band]) for band in range(3)) < 20}
check.that(near,
f"no pixel of the page stands in the link colour {wanted}")
if not near:
return
lines = set()
for places in near.values():
lines |= places
# The word and the line under it: the word covers a band of rows and the
# line adds its own under it, at the distance of the underline.
check.that(max(lines) - min(lines) > 12,
"the link carries no line under it: its colour covers "
f"{max(lines) - min(lines)} rows of the page")
plain, plain_log = build(support.write("linkplain.tex", LINKSTYLE_PLAIN),
EXAMPLES)
quiet = painted(plain, "Verweis")
coloured = [colour for colour in quiet
if max(abs(colour[band] - wanted[band])
for band in range(3)) < 20]
check.that(not coloured,
"a document that sets nothing carries the link colour all the "
f"same: {sorted(coloured)[:3]}")
contents_without_lines(check, wanted)
heading_link(check)
def heading_link(check):
"""A link inside a section title builds, and keeps its destination.
A title is written out three times over: into the contents file, into the
running head and into the bookmark of the PDF. A replacement of `\\hyperref`
that is not robust is expanded in those places while its argument is still
unread, and the title then ends in the middle of itself. Reported from the
PLIM documents on 2026-10-23, where exactly one of nineteen documents
carried such a title and stopped building.
"""
pdf, _ = build(support.write("linkheading.tex", LINKSTYLE_HEADING),
EXAMPLES)
names = support.run(["pdfinfo", "-dests", pdf]).stdout
check.that("marke" in names,
"the destination of the link in the title is missing from the "
"built document")
# A link inside a section title, written the way pandoc writes a Markdown
# heading that carries one: the title travels into the contents, the running
# head and the bookmark, and a replacement of `\hyperref` that is not robust
# tears the title apart on the way.
LINKSTYLE_HEADING = r"""\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
\businesscolours{link = nordwind-deep}
\businesslinks{colour = link, underline = true}
\begin{document}
\tableofcontents
\newpage
\section{\texorpdfstring{Der \hyperref[marke]{Verweis} im Titel}%
{Der Verweis im Titel}}
\label{marke}
\noindent Rumpf.
\end{document}
"""
def ruled_rows(pdf, page, wanted, word):
"""Rows under a word that are a long run of one colour: a drawn line.
Only the band of the word is read. A page of this suite carries lines of its
own — the rule under the head stands in a colour of the same palette, 194
pixels long, and a measurement over the whole page reports it as an
underline.
"""
stem = os.path.join(support.BUILD, "linkcontents")
support.run(["pdftoppm", "-r", "150", "-f", str(page), "-l", str(page),
"-singlefile", pdf, stem])
with open(stem + ".ppm", "rb") as handle:
data = handle.read()
fields, offset = [], 0
while len(fields) < 4:
end = data.index(b"\n", offset)
line = data[offset:end]
offset = end + 1
if not line.startswith(b"#"):
fields += line.split()
width, height = int(fields[1]), int(fields[2])
pixels = data[offset:]
found = [item for item in support.words(pdf, page) if item[0] == word]
if not found:
return [("the word %s stands on no page %d" % (word, page), 0)], width
scale = 150 / 72.0
top = max(0, int(found[0][2] * scale) - 3)
height = min(height, int(found[0][4] * scale) + 7)
ruled = []
for row in range(top, height):
run = longest = 0
for column in range(width):
index = (row * width + column) * 3
colour = tuple(pixels[index:index + 3])
if max(abs(colour[band] - wanted[band]) for band in range(3)) < 40:
run += 1
longest = max(longest, run)
else:
run = 0
# A drawn line runs without a gap under the whole word, 40 pixels at
# 150 dpi for a word of seven letters at ten points. A row of glyphs
# never does: the horizontal stroke of a letter is a few pixels wide,
# and the leaders of a contents entry are dots with white between them.
if longest > 40:
ruled.append((row, longest))
return ruled, width
def contents_without_lines(check, wanted):
"""The line under a link belongs to a link in the text, not to a contents page.
Every entry of a table of contents is an internal link, so it takes the
colour of the role like any other. A line under each of them would draw a
grid over the page, and nobody reads a contents page that way: the line is
drawn around `\\href` and `\\hyperref`, the two commands a text writes, and
`\\contentsline` builds its entries with neither.
"""
pdf, _ = build(support.write("linkcontents.tex", LINKSTYLE_CONTENTS),
EXAMPLES)
contents, _ = ruled_rows(pdf, 1, wanted, "Erster")
check.that(not contents,
"the contents page carries a drawn line in the link colour, "
f"row and length: {contents}")
text, width = ruled_rows(pdf, 2, wanted, "Verweis")
check.that(text,
"the link in the text carries no line under it on its page")
def palette(check):
"""No ink on the page outside the colours the company declared.
LaTeX writes in its own pure black until it is told otherwise, and a company
whose text is a warm black never sees the difference by eye. The check reads
the RENDERED page and not the content stream: a stream sets a colour for
what follows, and the writer of a PDF sets pure black at the head of every
page whether anything is painted in it or not. What a reader sees is the
pixel.
Taken over from the design of a company of this family on 2026-10-06, where
it stood with that company's four colours written into the test. Here the
roles are read off the package and their values out of xcolor, so it holds
for every company and grows with every role the family adds.
"""
names = role_names()
check.that(len(names) > 10,
f"the package declares {len(names)} colour roles, which is fewer "
"than this family has")
inks = role_inks(check, names)
if not inks:
return
# The paper is no role and belongs to every page; every letter of every page
# is drawn on it, so every edge lies on a line that ends there.
colours = list(inks.values()) + [(255, 255, 255)]
source = support.write("palettedoc.tex", PALETTE_DOCUMENT)
pdf, _ = build(source, EXAMPLES)
stem = os.path.join(support.BUILD, "palettepage")
support.run(["pdftoppm", "-r", "100", "-f", "1", "-l", "1", "-singlefile",
pdf, stem])
with open(stem + ".ppm", "rb") as handle:
data = handle.read()
fields, offset = [], 0
while len(fields) < 4:
end = data.index(b"\n", offset)
line = data[offset:end]
offset = end + 1
if not line.startswith(b"#"):
fields += line.split()
pixels = data[offset:]
strange = {}
for index in range(0, len(pixels) - 2, 3):
colour = tuple(pixels[index:index + 3])
if colour in strange:
strange[colour] += 1
continue
# Eight steps of 255: a blend of two colours sits on its line by
# construction, and the window covers the rounding of the renderer and
# the corner where three colours meet in one pixel.
if min(between(colour, first, second)
for number, first in enumerate(colours)
for second in colours[number:]) > 8:
strange[colour] = 1
worst = sorted(strange.items(), key=lambda pair: -pair[1])[:3]
check.that(not strange,
"the page carries ink the company never declared: "
+ ", ".join("#%02X%02X%02X (%d pixels)" % (colour + (count,))
for colour, count in worst))
# A company that builds on another: it loads that identity and names a mark of
# its own. `nordwind` DRAWS its icon, so the drawing has to give way to the file.
DAUGHTER = r"""\documentclass[a4paper,10pt]{article}
\usepackage[nologo]{nordwind}
\businessidentity{icon = example-image}
\begin{document}
\pagestyle{empty}
\noindent\logo[height=2cm]
\end{document}
"""
def daughter_mark(check):
"""A mark named after another identity was loaded replaces the one it drew.
A file and a drawing answer the same question, and the package preferred the
drawing wherever one stood. A company that loads the identity of another and
names its own `icon` therefore carried the mark of that other company, on
every page, with nothing in any log to say so. The measurement is the shape
on the page: the drawn mark of the example company is a disc and as wide as
it is high, the test image of TeX Live is half again as wide as it is high.
"""
source = support.write("daughter.tex", DAUGHTER)
pdf, _ = build(source, EXAMPLES)
page = Page(pdf, 1)
rows = page.ink_rows()
check.that(rows, "the mark of the daughter did not reach the page")
if not rows:
return
columns = page.ink_columns(rows[0], rows[-1] + 1)
factor = 72.0 / page.dpi
high = (rows[-1] - rows[0] + 1) * factor
wide = (columns[-1] - columns[0] + 1) * factor
check.that(wide > 1.2 * high,
f"the mark is {wide:.1f} points wide and {high:.1f} high, so the "
"drawing of the identity that was loaded first is still there")
# A document that brings the PDF management of the kernel with it: it writes
# the XMP stream itself, and a package that would write a second one is turned
# away. The two curricula vitae of the family are built this way, for PDF/UA.
MANAGED = r"""\DocumentMetadata{}
\documentclass[a4paper,10pt]{article}
\usepackage{nordwind}
\title{Gemessen}
\author{Erika Musterfrau}
\begin{document}
\maketitle
Dolor sit amet.
\end{document}
"""
def managed(check):
"""Where the kernel manages the PDF, the suite asks for nothing beside it.
`hyperxmp` writes the stream a reader and an archive look at, and the
template loads it. Where a document declares `\\DocumentMetadata`, the
kernel writes that stream itself and turns the package away with a warning —
and a warning is an error in the projects that build such documents, so the
template must not ask for it there. Measured in the build log, and the
title still has to reach the file.
"""
source = support.write("managed.tex", MANAGED)
pdf, log = build(source, EXAMPLES)
with open(log, encoding="utf-8", errors="replace") as handle:
text = handle.read()
turned = [line for line in text.splitlines()
if "hyperxmp" in line and ("disabled" in line
or "Warning" in line)]
check.that(not turned,
"the template asks for hyperxmp where the kernel manages the "
"PDF: " + "; ".join(turned[:2]))
properties = support.run(["pdfinfo", pdf]).stdout
check.that("Gemessen" in properties,
"the title of a managed document did not reach its properties")
def main():
check = Check("identity")
source_checks(check)
plain(check)
page_checks(check)
logo_from_file(check)
logo_from_svg(check)
tagline(check)
tagline_colour(check)
body_colour(check)
rule_colour(check)
named_destinations(check)
deck_ground(check)
address_on_logo(check)
marks_fill(check)
lockup_sizes(check)
palette(check)
daughter_mark(check)
managed(check)
link_style(check)
return check.done()