-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
2541 lines (2322 loc) · 119 KB
/
Copy pathbuild.py
File metadata and controls
2541 lines (2322 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Symbulator documentation builder.
Reads the single source tree described in SPEC.md and emits, for each
version of the software:
build/tex/symbulator-v<N>.tex -> build/pdf/symbulator-v<N>.pdf
build/web/content/v<N>/*.html + toc.json (included by web/index.php)
Usage: python3 build.py [--web] [--pdf] [--versions 7,8,9]
"""
from __future__ import annotations
import argparse
import html
import json
import os
import re
import unicodedata
import shutil
import subprocess
import sys
from dataclasses import dataclass, field
import yaml
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools"))
from check_palette import check_palette # noqa: E402 (needs sys.path set first)
from stamp_assets import check_asset_stamps # noqa: E402
from check_control_chars import check_control_chars # noqa: E402
from check_index import check_index # noqa: E402 (#422: the back-of-book index)
from gen_timeline import check_timeline # noqa: E402 (the dates, in both books)
import app_links # noqa: E402 (#224: the app link on every worked problem)
ROOT = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(ROOT, "src")
BUILD = os.path.join(ROOT, "build")
ASSETS = os.path.join(ROOT, "assets")
# ---- figure sizes (#153) --------------------------------------------------
# tools/figure_sizes.json, written by tools/measure_figures.py, records the
# pixel size of every figure scan and the estimated height in pixels of the
# label text inside it. A figure is rendered at the width that puts that
# label text at target_mm -- the size of the body text -- capped at the
# line; the same proportion goes to the web as a percentage of the column.
# The scans' own pixel sizes are meaningless (most were resampled to a
# uniform 1100 px in 2023), which is why the old fixed 72%-of-the-line rule
# printed some labels at half the body size and others at triple.
FIGSIZES_PATH = os.path.join(ROOT, "tools", "figure_sizes.json")
try:
with open(FIGSIZES_PATH, encoding="utf-8") as _fh:
_FIGSIZES = json.load(_fh)
except FileNotFoundError:
_FIGSIZES = {"target_mm": 3.4, "line_mm": 156.0,
"overrides": {}, "measured": {}}
FIG_LINE_MM = float(_FIGSIZES.get("line_mm", 156.0))
#: The desktop reading column in CSS pixels: --measure is 34rem in
#: web/assets/style.css at the 16px root. A figure's measured width in mm
#: becomes a pixel width at this column's scale (#256), so the labels
#: inside it are the same height on every screen -- a phone included --
#: instead of shrinking with the column as a percentage did.
MEASURE_PX = 544.0
#: #171: the most a problem may demand before it starts -- the title and
#: three lines or so. Above that it stops protecting a title and starts
#: throwing away the foot of the page.
PROBLEM_NEED_MAX = 34.0
#: #172: where a circuit may go. "h" first so it stays where it was
#: written whenever it fits; "t" for the top of the page it lands on.
#: Never "b" or "p" -- a circuit that sank to the foot of the page, or
#: to a page of its own, would be reached before the words that set it
#: up. "!" tells LaTeX to ignore its own fullness quotas, which are
#: tuned for journal figures, not for a circuit per worked problem.
FIGURE_FLOAT = "!ht"
def figure_size_mm(ref: str):
"""(width_mm, height_mm) to render a figure at, or (None, None).
None means the manifest knows nothing about the file -- the renderers
fall back to the old 72%-of-the-line rule, and a fresh run of
tools/measure_figures.py is due.
"""
rel = ref[len("assets/"):] if ref.startswith("assets/") else ref
m = _FIGSIZES["measured"].get(rel)
ov = _FIGSIZES["overrides"].get(rel)
if ov is not None:
w_mm = min(float(ov), FIG_LINE_MM)
if m and m.get("w"):
return (w_mm, w_mm * m["h"] / m["w"])
return (w_mm, None)
if not m or not m.get("text_px"):
return (None, None)
w_mm = min(m["w"] * float(_FIGSIZES["target_mm"]) / m["text_px"],
FIG_LINE_MM)
return (w_mm, w_mm * m["h"] / m["w"])
# The shared banner lockup's one source, in the app repository -- a
# sibling tree of this one (see the top-level CLAUDE.md for the
# layout). It lives there rather than here because the app's build
# inlines a copy it cannot fetch, and moving the source into that repo
# pins the lockup and the check to the same commit (#75).
SHARED_BANNER = os.path.normpath(os.path.join(
ROOT, "..", "Application", "v9", "repos", "local", "banner.css"))
# Every URL this build writes into the site is root-absolute.
#
# learn.symbulator.com serves the same index.php at /?v=9&p=lesson-dc and at
# the pretty /9/lesson-dc. A relative "assets/style.css" resolves against the
# second as /9/assets/style.css and 404s -- which is how the site shipped
# with no stylesheet, no logo and no figures on every pretty URL while the
# query form looked perfect. Root-absolute paths resolve identically under
# both, so there is one right answer rather than one per URL shape.
#
# The site therefore only works at a document root. That is already true of
# symbulator.com's landing page, and is stated in the deploy notes.
def site_path(ref: str) -> str:
"""An in-site asset reference, made root-absolute. External URLs and
anything already absolute are returned untouched."""
if ref.startswith(("http://", "https://", "//", "/", "data:", "#")):
return ref
return "/" + ref
def page_url(v, p: str = "") -> str:
"""A link to a chapter: /9/lesson-dc. Mirrors url() in web/index.php,
including its fallback -- .htaccess only rewrites [789] and a
lowercase-alnum-hyphen slug, so anything else takes the query form
rather than 404ing."""
import re as _re
if not _re.fullmatch(r"[789]", str(v)) or (p and not _re.fullmatch(r"[a-z0-9-]+", p)):
return f"/?v={v}" + (f"&p={p}" if p else "")
return f"/{v}/" + p
# --------------------------------------------------------------------------
# AST
# --------------------------------------------------------------------------
@dataclass
class Node:
kind: str
text: str = ""
arg: str = ""
children: list = field(default_factory=list)
meta: dict = field(default_factory=dict)
def applink_args(blocks: list) -> list:
"""Every `::: applink` argument under `blocks`, in reading order (#297)."""
out = []
for b in blocks:
if b.kind == "applink":
out.append(b.arg)
out.extend(applink_args(b.children))
return out
def title_for(ch, v) -> str:
"""A chapter's title for version v (#270, 6 Sep 2026). The title is
front matter -- one string for all three versions -- but Lesson 2's
must say *expert mode* in 7 and 8 and *Expert Mode* in 9, so it may
carry the same version spans the body does: `{{v7,8|expert
mode}}{{v9|Expert Mode}}`, or `{{!v7|...}}`. Only version spans are
resolved; a title is printed raw everywhere (the h1, the sidebar's
toc.json, the search index, the PDF's \\lesson and running foot),
so no other markup belongs in one -- bold included."""
return resolve_vspans(ch.title, v)
def _unqualified(title: str) -> str:
"""A problem's title without a trailing (qualifier)."""
return re.sub(r"\s*\([^()]*\)\s*$", "", title).strip() or title
def resolve_vspans(text: str, v: int) -> str:
"""Version spans resolved inside a plain string.
Split out of title_for for #368: a worked problem's title may carry
the same spans a chapter title may, and a cross-reference to that
problem has to print the version the reader is on rather than the
raw markup."""
def pick(m):
neg, vers = m.group(1), [int(x) for x in m.group(2).split(",")]
hit = v in vers
return m.group(3) if hit != bool(neg) else ""
return re.sub(r"\{\{(!?)v([\d,]+)\|([^}]*)\}\}", pick, text)
def eyebrow_for(ch, number) -> str:
"""The small line above a chapter title.
"Lesson 3" for a lesson, "Tech Note A" for a technical note, and
nothing for the Introduction or the credits -- a chapter with no
label printed its title twice when this fell back to the title.
One function because three renderers ask: the HTML chapter head, the
TeX one, and `toc.json`, which the home page cards and the sidebar
are both built from.
"""
if ch.kind == "note":
return f"Tech Note {ch.note_letter}" if ch.note_letter else ""
if ch.kind == "manual":
return f"Part {ch.part_number}" if ch.part_number else ""
return f"Lesson {number}" if number else ""
@dataclass
class Chapter:
id: str
title: str
kind: str = "lesson"
versions: list = field(default_factory=lambda: [7, 8, 9])
absent_note: str = ""
updated: str = ""
summary: str = ""
blocks: list = field(default_factory=list)
note_letter: str = "" # set per version by `for_version`
part_number: int = 0 # the Manual's own sequence (#390)
books: list = field(default_factory=list) # example books (#383)
book: str = "course" # which book this chapter is in (#390)
class SourceError(Exception):
pass
# --------------------------------------------------------------------------
# Block parser
# --------------------------------------------------------------------------
DIRECTIVES = {"tip", "note", "warning", "danger", "figure", "problem",
"answer", "practice", "only", "not", "web", "pdf", "address",
"result", "applink", "photos"}
def photo_rows(text: str):
"""The `path | caption` lines of a ::: photos block, in order.
The first is the one the PDF prints: a printed book cannot flip
(Roberto, 16 Sep 2026), so the web gets the set and the books keep
the single photograph they have always had.
"""
rows = []
for line in text.splitlines():
line = line.strip()
if not line:
continue
src, _, cap = line.partition("|")
rows.append((src.strip(), cap.strip()))
return rows
#: The label a ::: result panel shows over an answer, from the name in
#: front of it (#276) -- the app's own words, from _ELEMENT_KEYS and
#: _TOOL_LABELS in repos/server/symbulator_ui.py. The directive's argument
#: overrides it: `::: result node voltage`.
#: With the element named (Roberto, 6 Sep 2026 -- a departure from the
#: app, whose card shows the element once as a heading the reader of a
#: single panel cannot see): "current through r3", "voltage drop in c",
#: "power consumed by r1", "resistance seen by e".
RESULT_LABELS = {"i": "current through {}", "v": "voltage drop in {}",
"p": "power consumed by {}", "r": "resistance seen by {}",
"z": "impedance seen by {}", "s": "complex power in {}"}
RESULT_SPECIAL = {"v_{th}": "Thévenin voltage", "i_{no}": "Norton current",
"R_{eq}": "equivalent resistance",
"Z_{eq}": "equivalent impedance",
"p_{max}": "maximum deliverable power"}
def result_label(text: str, arg: str) -> str:
"""The label for a result panel: the argument if given, else derived
from the name before the `=`; empty when there is no name."""
if arg.strip():
return arg.strip()
m = re.match(r"\s*([A-Za-z]_\{[^}]*\})\s*&?=", text)
if not m:
return ""
name = m.group(1)
if name in RESULT_SPECIAL:
return RESULT_SPECIAL[name]
elem = re.sub(r"[\\{}]", "", name[3:-1]) # the subscript, plain
return RESULT_LABELS.get(name[0], "").format(elem).strip()
#: The two output media. `::: web` / `::: pdf` blocks and `{{web|...}}` /
#: `{{pdf|...}}` spans show in one of them only; a pass that is not
#: rendering (labels, --check) sees both.
MEDIA = ("web", "pdf")
BS = chr(92) # a LaTeX escape, spelled out so no editor eats it
NL = chr(10) # a real newline in the emitted .tex
HEADING_RE = re.compile(r"^(#{2,3})\s+(.*?)(?:\s*\{#([\w-]+)\})?\s*$")
# ```field 9 Circuit description -- lang, versions, then a free-text
# name for the interface field the reader types into. Only `field` uses
# the third part; for the others a stray word is a parse error rather
# than silent text.
FENCE_RE = re.compile(r"^```(\w+)?\s*([\d,]*)\s*(.*?)\s*$")
DIRECTIVE_RE = re.compile(r"^:::\s*(\w+)?\s*(.*)$")
ULI_RE = re.compile(r"^[-*]\s+(.*)$")
#: A pipe table, GitHub style, and the `|---|---|` rule under its header.
#: A row is only a row if the rule is on the line below the first one, so a
#: paragraph that happens to start with a pipe is still a paragraph.
TABLE_ROW_RE = re.compile(r"^\s*\|.*\|\s*$")
TABLE_RULE_RE = re.compile(r"^\s*\|[\s:|-]+\|\s*$")
#: A quotation. `>` alone separates its paragraphs, as in Markdown.
QUOTE_RE = re.compile(r"^>\s?(.*)$")
#: An em dash or an en dash: how an attribution opens. Either is accepted,
#: because both are what people actually type.
QUOTE_DASHES = "\u2014\u2013"
OLI_RE = re.compile(r"^\d+[.)]\s+(.*)$")
def _ascii(s: str) -> str:
r"""Fold accents away: "Thevenin" from "Thévenin".
Python's \w is Unicode-aware, so the obvious slugify keeps "e-acute"
and the name reaches a filename. That survives fine over SFTP, but it
did not survive a ZIP unpacked by cPanel's extractor, which wrote the
UTF-8 bytes out through a legacy code page and left junk twins of six
figures on the live server. Slugs are ASCII from here on.
"""
return "".join(c for c in unicodedata.normalize("NFKD", s)
if not unicodedata.combining(c))
def slugify(s: str) -> str:
s = re.sub(r"\{\{[^}]*\}\}", "", s)
s = _ascii(s)
s = re.sub(r"[^\w\s-]", "", s, flags=re.ASCII).strip().lower()
return re.sub(r"[\s_]+", "-", s) or "section"
def parse_chapter(path: str) -> Chapter:
raw = open(path, encoding="utf-8").read()
if not raw.startswith("---"):
raise SourceError(f"{path}: missing YAML front matter")
_, fm, body = raw.split("---", 2)
meta = yaml.safe_load(fm) or {}
ch = Chapter(
id=meta.get("id") or os.path.splitext(os.path.basename(path))[0],
title=meta.get("title", "Untitled"),
kind=meta.get("kind", "lesson"),
books=[str(x) for x in (meta.get("books") or [])],
book=str(meta.get("book", "course")).strip() or "course",
versions=meta.get("versions", [7, 8, 9]),
absent_note=(meta.get("absent_note") or "").strip(),
updated=str(meta.get("updated", "")),
summary=(meta.get("summary") or "").strip(),
)
lines = body.split("\n")
ch.blocks = parse_blocks(lines, path)
return ch
def split_row(line: str) -> list:
"""One table row into its cells.
An escaped pipe is a literal pipe rather than a cell boundary, which
this book needs more than most: the calculator's "with" operator is a
pipe, and it is discussed in the text."""
body = line.strip().strip("|")
parts = re.split(r"(?<!\\)\|", body)
return [c.replace("\\|", "|").strip() for c in parts]
def parse_blocks(lines: list[str], path: str, depth: int = 0) -> list[Node]:
"""Consume `lines` (mutated) until exhausted or a closing ':::' at depth>0."""
out: list[Node] = []
i = 0
while i < len(lines):
line = lines[i]
if not line.strip():
i += 1
continue
# closing markers are consumed by collect_directive; any left is an error
if line.strip() == ":::":
raise SourceError(f"{path}: stray ':::' (unbalanced directive)")
# heading
m = HEADING_RE.match(line)
if m:
level = len(m.group(1))
title = m.group(2).strip()
anchor = m.group(3) or slugify(title)
out.append(Node("heading", text=title, meta={"level": level,
"anchor": anchor}))
i += 1
continue
# code fence
m = FENCE_RE.match(line)
if m and m.group(1) in ("sym", "out", "field", "text", None):
lang = m.group(1) or "text"
vers = [int(v) for v in m.group(2).split(",") if v] or None
name = m.group(3) or ""
if name and lang != "field":
raise SourceError(
f"{line!r}: only a ```field fence takes a name after the "
f"version. Did you mean ```field?")
j = i + 1
buf = []
while j < len(lines) and not lines[j].startswith("```"):
buf.append(lines[j])
j += 1
out.append(Node("code", text="\n".join(buf),
meta={"lang": lang, "versions": vers,
"field": name}))
i = j + 1
continue
# directive
m = DIRECTIVE_RE.match(line)
if m and m.group(1) in DIRECTIVES:
name, arg = m.group(1), m.group(2).strip()
inner, consumed = collect_directive(lines[i + 1:], path, depth + 1)
if name in ("result", "photos"): # #276, and one photo per line
node = Node(name, arg=arg, text="\n".join(l for l in inner if l.strip()))
else:
node = Node(name, arg=arg, children=parse_blocks(inner, path, depth + 1))
out.append(node)
i = i + 1 + consumed
continue
# table
if (TABLE_ROW_RE.match(line) and i + 1 < len(lines)
and TABLE_RULE_RE.match(lines[i + 1])):
head = split_row(line)
rows, j = [], i + 2
while j < len(lines) and TABLE_ROW_RE.match(lines[j]):
row = split_row(lines[j])
if len(row) != len(head):
raise SourceError(
f"{path}: this table row has {len(row)} cell(s) "
f"where the header has {len(head)}:\n "
f"{lines[j].strip()}\n"
f" A cell holding a pipe has to write it as \\|.")
rows.append(row)
j += 1
out.append(Node("table", meta={"head": head, "rows": rows}))
i = j
continue
# quotation
if QUOTE_RE.match(line):
buf, j = [], i
while j < len(lines) and QUOTE_RE.match(lines[j]):
buf.append(QUOTE_RE.match(lines[j]).group(1))
j += 1
out.append(Node("quote", children=parse_blocks(buf, path, depth)))
i = j
continue
# list
if ULI_RE.match(line) or OLI_RE.match(line):
ordered = bool(OLI_RE.match(line))
items, j = [], i
while j < len(lines):
mm = OLI_RE.match(lines[j]) if ordered else ULI_RE.match(lines[j])
if not mm:
if lines[j].startswith(" ") and items: # continuation
items[-1] += " " + lines[j].strip()
j += 1
continue
break
items.append(mm.group(1).strip())
j += 1
out.append(Node("list", meta={"ordered": ordered, "items": items}))
i = j
continue
# display maths
if line.strip() == "$$":
j = i + 1
buf = []
while j < len(lines) and lines[j].strip() != "$$":
buf.append(lines[j])
j += 1
out.append(Node("mathblock", text="\n".join(buf)))
i = j + 1
continue
# paragraph
buf = []
j = i
while j < len(lines) and lines[j].strip() and not (
HEADING_RE.match(lines[j]) or lines[j].startswith("```")
or lines[j].startswith(":::") or ULI_RE.match(lines[j])
or OLI_RE.match(lines[j]) or QUOTE_RE.match(lines[j])
or (TABLE_ROW_RE.match(lines[j]) and j + 1 < len(lines)
and TABLE_RULE_RE.match(lines[j + 1]))):
buf.append(lines[j].strip())
j += 1
out.append(Node("para", text=" ".join(buf)))
i = j
return out
def collect_directive(rest: list[str], path: str, depth: int):
"""Return (inner_lines, lines_consumed_including_closing_marker)."""
inner, level, k = [], 1, 0
while k < len(rest):
line = rest[k]
m = DIRECTIVE_RE.match(line)
if line.strip() == ":::":
level -= 1
if level == 0:
return inner, k + 1
inner.append(line)
elif m and m.group(1) in DIRECTIVES:
level += 1
inner.append(line)
else:
inner.append(line)
k += 1
raise SourceError(f"{path}: unclosed ':::' directive")
# --------------------------------------------------------------------------
# Inline parser
# --------------------------------------------------------------------------
# `\*` is a literal asterisk -- the multiplication sign in an answer the
# software gave back, as in **{.904\*vs,10952.}**. Until 2 Sep 2026 there
# was no escape at all: the interior `*` broke the `**...**` match, the
# stars then re-paired themselves across the rest of the paragraph, and
# the sentence rendered with scrambled italics and a stray `*` left over.
# Eleven lines across four lessons were doing this and nobody had looked.
#
# The escape set is deliberately just `*` and `\` -- NOT a general `\.`.
# A backslash is ordinary content here: the calculator's own namespace is
# written `s\dc`, `s\tr`, `s\rms`, and a general escape would eat those.
#
# Hence the atom `(?:\\[*\\]|[^*])`, in that order and not the other way
# round. The escape alternative goes first so `\*` is swallowed whole and
# its star cannot close the span; `[^*]` then still admits a *lone*
# backslash, which is what keeps **s\bode** bold. Writing the atom as
# `(?:[^*\\]|\\[*\\])` looks equivalent and is not -- it bans ordinary
# backslashes from emphasis entirely, and silently un-bolded every
# `**s\...**` in the book. Only a diff of the built pages showed it.
#
# One level of nesting each way (#263, 5 Sep 2026): an italic span may
# hold `**...**` runs -- *"**symb**olic sim**ulator**"* in the
# Introduction -- and a bold span may hold `*...*` runs -- `**Tick *real
# solutions only*.**` in Lesson 11. Each body admits a whole group of the
# other kind as one atom, so the inner stars cannot close the outer span;
# the body is then parsed again and the group becomes a node inside.
# The inner group is the plain form, so the nesting stops at one level.
# Strong is still tried first at any position, so a plain `**bold**`
# never reads as an italic that happens to start with a star. A side
# effect: `***x***`, which used to print a stray star and then bold, now
# reads as bold inside italic; no source writes it. Before this rule the
# Introduction's line rendered as five italic runs with no bold, and the
# Lesson 11 bullet as two stray stars and two fragments of italic -- the
# span closed at the first inner star and the stars re-paired down the
# rest of the paragraph.
INLINE_RE = re.compile(
r"(?P<esc>\\[*\\])"
r"|(?P<brace>\{\{(?:[^{}]|\{[^{}]*\})*\}\})"
r"|(?P<code>`[^`]+`)"
r"|(?P<math>\$[^$]+\$)"
r"|(?P<link>\[[^\]]+\]\([^)]+\))"
r"|(?P<strong>\*\*(?:\\[*\\]|\*(?:\\[*\\]|[^*])+\*|[^*])+\*\*)"
r"|(?P<em>\*(?:\\[*\\]|\*\*(?:\\[*\\]|[^*])+\*\*|[^*])+\*)"
)
def brace_end(text: str, start: int) -> int:
"""Index just past the `}}` closing the `{{` at `start`, or -1.
Depth-counted, so one brace command may contain another:
`{{v9|tick {{ui:Show equations}}}}` (#358). Until then INLINE_RE's
brace group stopped at the first `}}`, which truncated the outer span
and leaked the rest of it onto the page as literal markup -- a trap
documented in SPEC.md and policed by a check rather than fixed, and
the reason #357 had to leave 44 sites in plain bold.
"""
depth, i, n = 0, start, len(text)
while i < n - 1:
two = text[i:i + 2]
if two == "{{":
depth += 1
i += 2
elif two == "}}":
depth -= 1
i += 2
if depth == 0:
return i
else:
i += 1
return -1
def parse_inline(text: str) -> list[Node]:
out, pos, i, n = [], 0, 0, len(text)
while i < n:
# Braces first, and by depth rather than by regex: they are the one
# inline construct that nests. An unbalanced `{{` falls through to
# INLINE_RE, which still matches the flat form, so a damaged source
# degrades exactly as it used to instead of eating the paragraph.
if text.startswith("{{", i):
end = brace_end(text, i)
if end > 0:
if i > pos:
out.append(Node("text", text=text[pos:i]))
out.append(parse_brace(text[i + 2:end - 2]))
pos = i = end
continue
m = INLINE_RE.match(text, i)
if not m:
i += 1
continue
if i > pos:
out.append(Node("text", text=text[pos:i]))
kind = m.lastgroup
s = m.group()
if kind == "esc":
out.append(Node("text", text=s[1]))
elif kind == "brace":
out.append(parse_brace(s[2:-2]))
elif kind == "code":
out.append(Node("icode", text=s[1:-1]))
elif kind == "math":
out.append(Node("imath", text=s[1:-1]))
elif kind == "link":
label, url = re.match(r"\[([^\]]+)\]\(([^)]+)\)", s).groups()
out.append(Node("link", text=label, arg=url,
children=parse_inline(label)))
elif kind == "strong":
out.append(Node("strong", children=parse_inline(s[2:-2])))
elif kind == "em":
out.append(Node("em", children=parse_inline(s[1:-1])))
pos = i = m.end()
if pos < n:
out.append(Node("text", text=text[pos:]))
return out
_ANSWER_MATH_CACHE: dict = {}
def answer_math(text: str):
"""LaTeX for an `{{o:...}}` value that is a symbolic expression, or None.
An answer the software gave back is quoted verbatim in the source --
`i*exp(-t/(c*r))/c` -- and until 27 Aug 2026 rendered as that plain
text. When the value parses to a SymPy expression that actually
contains symbols, it is typeset as mathematics instead (KaTeX on the
web, math mode in the PDFs); a bare number, a braced pair like
{4.77,7.18}, or anything else that does not parse keeps the plain
`.ans` treatment it always had. The source text is untouched either
way, so `tools/check_against_originals.py` and the verify harness
keep reading the value exactly as printed."""
if text in _ANSWER_MATH_CACHE:
return _ANSWER_MATH_CACHE[text]
result = None
if re.search(r"[a-zA-Z]", text) and not re.search(r"[{}\\]", text):
try:
import sympy as sp
expr = sp.sympify(text)
if getattr(expr, "free_symbols", None):
result = sp.latex(expr)
except Exception: # noqa: BLE001
result = None
_ANSWER_MATH_CACHE[text] = result
return result
def parse_brace(inner: str) -> Node:
if inner.startswith("i:"):
return Node("index", text=inner[2:].strip())
if inner.startswith("t:"):
return Node("term", text=inner[2:].strip())
if inner.startswith("ref:"):
return Node("ref", text=inner[4:].strip())
if inner.startswith("o:"): # an answer the software gave back
return Node("answer_span", text=inner[2:].strip())
if inner.startswith("card:"): # a card in the app (#357)
return Node("uicard", text=inner[5:].strip())
if inner.startswith("tool:"): # a tool you run (#369)
return Node("uitool", text=inner[5:].strip())
if inner.startswith("btn:"): # a button you press (#361)
return Node("uibtn", text=inner[4:].strip())
if inner.startswith("ui:"): # a control inside a card (#357)
return Node("uictl", text=inner[3:].strip())
if inner.startswith("var:"): # a problem's own variable (#261)
return Node("var", text=inner[4:].strip())
if inner.startswith("sub:"):
return Node("sub", text=inner[4:].strip())
if inner.startswith("sup:"):
return Node("sup", text=inner[4:].strip())
m = re.match(r"^(web|pdf)\|(.*)$", inner, re.S)
if m: # {{web|...}} / {{pdf|...}}
return Node("mspan", arg=m.group(1), children=parse_inline(m.group(2)))
m = re.match(r"^(!?)v([\d,]+)\|(.*)$", inner, re.S)
if m:
neg, vers, body = m.groups()
return Node("vspan", arg=neg,
meta={"versions": [int(v) for v in vers.split(",")]},
children=parse_inline(body))
return Node("text", text="{{" + inner + "}}")
# --------------------------------------------------------------------------
# Version resolution / numbering
# --------------------------------------------------------------------------
class Book:
def __init__(self, meta: dict, chapters: list[Chapter]):
self.meta = meta
self.chapters = chapters
def for_version(self, v: int):
"""Chapters present in version v, with display numbers assigned."""
out, n, k, m = [], 0, 0, 0
for ch in self.chapters:
present = v in ch.versions
if not present and not ch.absent_note:
continue
number = None
if ch.kind == "lesson":
n += 1
number = n
# A technical note is lettered rather than numbered (#380):
# the notes have no reading order, and a number implies one.
# Assigned here, beside the lesson numbers, so the two
# sequences cannot drift and both are per-version.
ch.note_letter = ""
if ch.kind == "note":
k += 1
ch.note_letter = chr(ord("A") + k - 1) if k <= 26 else str(k)
# The Manual's parts are numbered in their own sequence (#390),
# assigned here beside the lesson numbers and the note letters
# so that all three are per-version and cannot drift apart.
ch.part_number = 0
if ch.kind == "manual":
m += 1
ch.part_number = m
out.append((ch, number, present))
return out
def labels(self, v: int) -> dict:
"""id -> (display name, chapter id, anchor) for cross-references."""
lab = {}
# #369: a problem reference reads as the prose does, so a
# trailing qualifier the chapter added comes off -- but only
# where two problems would not then read the same.
bare: dict = {}
for ch, _n, present in self.for_version(v):
if not present:
continue
for b in walk_deep(ch.blocks, v):
if b.kind == "problem":
full = resolve_vspans(b.arg, v)
bare.setdefault(_unqualified(full), set()).add(full)
for ch, number, present in self.for_version(v):
name = f"Lesson {number}" if number else title_for(ch, v)
lab[ch.id] = (name, ch.id, "")
if not present:
continue
sect = 0
# #368: the problem ids are worked out the same way the HTML
# renderer works them out -- slugify the source title, then
# a counter for a repeat -- over the same walk(blocks, v), so
# the two cannot disagree. check_problem_media() below bans
# the one thing that could make them: a problem inside a
# ::: web or ::: pdf block, which this walk keeps and the
# renderer's medium-filtered walk might drop.
seen: set = set()
for b in walk_deep(ch.blocks, v):
if b.kind == "heading" and b.meta["level"] == 2:
sect += 1
disp = (f"section {number}.{sect}" if number
else f"“{b.text}”")
lab[b.meta["anchor"]] = (disp, ch.id, b.meta["anchor"])
elif b.kind == "heading" and b.meta["level"] == 3:
lab[b.meta["anchor"]] = (f"“{b.text}”", ch.id,
b.meta["anchor"])
elif b.kind == "problem":
base = slugify(b.arg)
pid, i = f"prob-{base}", 2
while pid in seen:
pid, i = f"prob-{base}-{i}", i + 1
seen.add(pid)
full = resolve_vspans(b.arg, v)
short = _unqualified(full)
disp = full if len(bare.get(short, ())) > 1 else short
lab[pid] = (disp, ch.id, pid)
return lab
def walk_deep(blocks: list[Node], v: int):
"""walk(), and then into every block's children as well.
#368: walk() flattens the version and medium wrappers but hands
back every other block whole, so a worked problem -- which lives
inside a `::: practice` block, and often has an `::: answer`
inside it in turn -- is never reached by a flat walk. Depth-first
in document order, which is the order the renderer meets them in
and therefore the order its `prob-` counters follow."""
for b in walk(blocks, v):
yield b
if b.children:
yield from walk_deep(b.children, v)
def keep(node: Node, v: int) -> bool:
if node.kind == "only":
return v in [int(x) for x in node.arg.replace(" ", "").split(",") if x]
if node.kind == "not":
return v not in [int(x) for x in node.arg.replace(" ", "").split(",") if x]
if node.kind == "code":
vers = node.meta.get("versions")
return vers is None or v in vers
return True
def walk(blocks: list[Node], v: int, medium: str | None = None):
"""Yield blocks visible in version v, flattening only/not wrappers.
`medium` is "web" or "pdf" while rendering; a `::: web` or `::: pdf`
block is flattened when it matches and dropped when it does not. With
no medium (labels, --check) both are kept, so an anchor defined in
either is known everywhere."""
for b in blocks:
if b.kind in MEDIA:
if medium is None or medium == b.kind:
yield from walk(b.children, v, medium)
continue
if b.kind in ("only", "not"):
if keep(b, v):
yield from walk(b.children, v, medium)
continue
if not keep(b, v):
continue
yield b
# --------------------------------------------------------------------------
# Callout furniture
# --------------------------------------------------------------------------
# Each callout carries an icon *and* a word, so the four kinds stay
# distinguishable in greyscale, in print, and for a colour-blind reader.
# Drawn as inline SVG (stroked in currentColor, so the CSS accent applies).
CALLOUT_LABELS = {"tip": "Tip", "note": "Note", "warning": "Warning",
"danger": "Caution", "absent": "Not in this version"}
CALLOUT_ICONS = {
# lightbulb
"tip": '<circle cx="8" cy="6.4" r="3.9"/><path d="M6 12.4h4M6.7 14.4h2.6"/>',
# circled i
"note": '<circle cx="8" cy="8" r="6.2"/><path d="M8 7.2v4"/>'
'<circle cx="8" cy="4.6" r=".85" fill="currentColor" stroke="none"/>',
# triangle with a bang
"warning": '<path d="M8 1.9 15 13.9H1z"/><path d="M8 6.3v3.5"/>'
'<circle cx="8" cy="11.9" r=".85" fill="currentColor" stroke="none"/>',
# octagon with a bang
"danger": '<path d="M5.5 1.6h5L14.4 5.5v5l-3.9 3.9h-5L1.6 10.5v-5z"/>'
'<path d="M8 4.7v4.2"/>'
'<circle cx="8" cy="11.5" r=".85" fill="currentColor" stroke="none"/>',
# circle with a bar
"absent": '<circle cx="8" cy="8" r="6.2"/><path d="M4.8 8h6.4"/>',
}
def callout_head(kind: str) -> str:
"""The icon-plus-word strip that opens every callout."""
return (f'<p class="callout-kind">'
f'<svg class="callout-icon" viewBox="0 0 16 16" aria-hidden="true" '
f'fill="none" stroke="currentColor" stroke-width="1.3" '
f'stroke-linejoin="round" stroke-linecap="round">'
f'{CALLOUT_ICONS[kind]}</svg>'
f'<span>{CALLOUT_LABELS[kind]}</span></p>')
# --------------------------------------------------------------------------
# HTML emitter
# --------------------------------------------------------------------------
class HtmlRenderer:
def __init__(self, book: Book, version: int):
self.book, self.v = book, version
self.terms = book.meta.get("terms", {})
self.labels = book.labels(version)
self.index: dict[str, list[str]] = {}
self.chapter_id = ""
self.section_no = 0
self.chapter_no = None
# #224. Version 9 is the only one with an app to open a problem
# in, so the books are read only when they can be used -- a v7
# build does not reach into the app tree at all.
self.books = app_links.load_books() if version == 9 else {}
self.entries: list = [] # the entries of each problem, in order
self.problem_no = 0 # which problem the renderer is on
self.problem_ids: set = set()
self.medium = "web"
# -- inline ----------------------------------------------------------
def inline(self, text: str) -> str:
return "".join(self.inode(n) for n in parse_inline(text))
def inode(self, n: Node) -> str:
if n.kind == "text":
return html.escape(n.text)
if n.kind == "icode":
return f'<code>{html.escape(n.text)}</code>'
if n.kind == "imath":
return f'<span class="math">\\({html.escape(n.text)}\\)</span>'
if n.kind == "strong":
return "<strong>" + "".join(self.inode(c) for c in n.children) + "</strong>"
if n.kind == "em":
return "<em>" + "".join(self.inode(c) for c in n.children) + "</em>"
if n.kind == "link":
return (f'<a href="{html.escape(n.arg)}">'
+ "".join(self.inode(c) for c in n.children) + "</a>")
if n.kind == "term":
return html.escape(str(self.terms.get(n.text, {}).get(self.v, n.text)))
if n.kind == "index":
anchor = "ix-" + slugify(n.text) + f"-{len(self.index.get(n.text, []))}"
self.index.setdefault(n.text, []).append(f"{self.chapter_id}#{anchor}")
return f'<span class="ix" id="{anchor}"></span>'
if n.kind == "ref":
name, cid, anchor = self.labels.get(n.text, (n.text, "", ""))
href = page_url(self.v, cid) + (f"#{anchor}" if anchor else "")
return f'<a class="xref" href="{href}">{html.escape(name)}</a>'
if n.kind == "answer_span":
ltx = answer_math(n.text)
if ltx:
return f'<span class="ans ans-math">\\({ltx}\\)</span>'
return f'<span class="ans">{html.escape(n.text)}</span>'
if n.kind in ("uicard", "uictl", "uibtn", "uitool"):
# #357: the app's own vocabulary, in two tiers -- the card
# the reader is sent to, and the control inside it. Bold
# alone could not carry either: the book bolds node and
# element names too (#267, #302).
cls = {"uicard": "ui-card", "uictl": "ui-ctl",
"uibtn": "ui-btn", "uitool": "ui-tool"}[n.kind]
return f'<span class="{cls}">{html.escape(n.text)}</span>'
if n.kind == "var":
# #261: a variable the problem itself names -- I_s, v_o, R_L --
# as distinct from the name Symbulator files the answer under
# (`ir3`, in code). Bold italic, Roberto's choice of 5 Sep 2026;
# `_` starts a subscript, so {{var:I_s}} is I with s below.
base, _, sb = n.text.partition("_")
sb = f'<sub>{html.escape(sb)}</sub>' if sb else ""
# <em class="var">, weight 600 in style.css (#271): the site
# loads Plex Serif's italic 600 cut for it, so the browser no
# longer fakes a bold italic by slanting the semibold roman.
return f'<em class="var">{html.escape(base)}{sb}</em>'
if n.kind == "sub":
return f'<sub>{html.escape(n.text)}</sub>'
if n.kind == "sup":
return f'<sup>{html.escape(n.text)}</sup>'
if n.kind == "vspan":
hit = self.v in n.meta["versions"]
show = (not hit) if n.arg == "!" else hit
return "".join(self.inode(c) for c in n.children) if show else ""
if n.kind == "mspan":
return ("".join(self.inode(c) for c in n.children)
if n.arg == self.medium else "")
return ""
# -- blocks ----------------------------------------------------------
def blocks(self, blocks: list[Node]) -> str:
return "\n".join(self.block(b) for b in walk(blocks, self.v, self.medium))
def block(self, b: Node) -> str:
k = b.kind
if k == "para":
return f"<p>{self.inline(b.text)}</p>"
if k == "heading":
if b.meta["level"] == 2:
self.section_no += 1
num = (f'<span class="secno">{self.chapter_no}.{self.section_no}</span>'
if self.chapter_no else "")
return (f'<h2 id="{b.meta["anchor"]}">{num}'
f'{self.inline(b.text)}</h2>')
return f'<h3 id="{b.meta["anchor"]}">{self.inline(b.text)}</h3>'
if k == "list":
tag = "ol" if b.meta["ordered"] else "ul"
items = "".join(f"<li>{self.inline(i)}</li>" for i in b.meta["items"])
return f"<{tag}>{items}</{tag}>"
if k == "table":
# A blank header row means the table has no header -- see
# chapter 13's gain answers, which are a label against a value.
head = ("" if not any(c.strip() for c in b.meta["head"]) else
"<thead><tr>"
+ "".join(f"<th>{self.inline(c)}</th>"
for c in b.meta["head"])
+ "</tr></thead>")
body = "".join(
"<tr>" + "".join(f"<td>{self.inline(c)}</td>" for c in row)