write_tab_stops.py

Die Python-Datei des Beispiels „Tabulatoren und Tabstopps“. Dieselben tabulierten Zeilen unter jeder der drei Methoden, dann ein Inhaltsblock, dessen Punkte bis zu einem Stopp rechts laufen. Ein Tabulator kann von dort weitergehen, wo der Text aufhörte, auf dem regelmäßigen Raster einer Schreibmaschine landen oder auf einen eigenen Stopp zielen, an dem der folgende Text beginnt, sich zentriert oder an seinem Dezimalzeichen ausrichtet.

Python 796 Zeilen

Wofür dieses Beispiel da ist

Eine Zahlenspalte, die nicht bündig steht, ist schlimmer als gar keine Spalte: Der Leser hört auf, die Zahlen zu lesen, und betrachtet stattdessen die Kanten. Leerzeichen erledigen das nicht, weil ein Leerzeichen in den meisten Schriften nicht so breit ist wie eine Ziffer; also muss etwas anderes angeben, wo das nächste Textstück beginnt, wie lang das letzte auch ausgefallen ist.

Was dieses Beispiel zeigt

  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
"""Sets the same tabulated text under each of the three tab methods, then a
table of contents whose dots run out to a right-hand stop, twice — plain dots,
then spaced grey dots set on a grid — so what each method does to a column can
be read off the page.

A second page sets the relative method told so, at twice the default step; the ruler
lining its prices up on a decimal comma; and the table of contents three more times, its
leader laid from the far edge inwards, stretched from one end of the room to the other,
and set smaller and raised off the baseline.

The Python twin of the `write_tab_stops` example in Rust. A grey rule is drawn
at every stop the block was told to use, so the runs can be seen landing on
them. The relative method steps the pen on from wherever it stands, so its
columns never line up; the typewriter method steps to the next multiple of the
tab size, so they do; a ruler sends each tabulation to a stop of its own and
sets the run on it, centred over it, or lined up on its decimal point.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
set the page is labelled in. The step the typewriter panel works in is not one
of them: its label is set around the very number the panel is given, so no
language can announce a grid the page does not land on.

Usage: python examples/write_tab_stops.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_tab_stops.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Sequence

import _language
import _licence
import _out

import hqf_pdf

# The left edge every panel is set from.
X = 80.0

# The room every panel has to fill.
COLUMN = 430.0

# The distance from a panel's heading down to the block below it.
DROP = 20.0

# The reference, the quantity and the unit price of each row the first three panels set.
# What each row is a category of is a word, and stands in `Words` under the same order.
ROWS = (
    ("A-1180", "12", "18.50"),
    ("B-2050", "4", "7.05"),
    ("C-9004", "120", "1 250.00"),
)

# The page each entry of the table of contents is on.
PAGES = ("7", "18", "34", "61", "112")

# The step the typewriter panel works in, which is the grid its columns land on and the
# number its label spells out.
GRID = 96.0

# How much of a line one tabulation opens when a flow is told nothing, as the first
# panel's label spells it out.
SHARE = "7.5%"

# How much of a line one tabulation opens on the second page's relative panel.
WIDE_SHARE = 0.15

# `WIDE_SHARE` as the panel's label spells it out.
WIDE_SHARE_SAID = "15%"

# The stops the ruler panel sends its three tabulations to.
RULER = [130.0, 260.0, 380.0]


@dataclass(frozen=True)
class Words:
    """Every word the page is labelled in, in one language."""

    # The label over the relative panel, set around the share of a line one tabulation
    # opens under the default.
    relative: tuple[str, str]
    # The label over the typewriter panel, set around the step it works in.
    typewriter: tuple[str, str]
    # The label over the ruler panel.
    ruler: str
    # The label over the table of contents.
    listing: str
    # The label over the table of contents whose leader is set on a grid.
    grid_listing: str
    # The label over the second page's relative panel, set around the share of a line
    # one tabulation opens there.
    relative_told: tuple[str, str]
    # The label over the ruler panel whose prices line up on a comma.
    comma: str
    # The label over the table of contents whose leader is laid from the far edge.
    from_edge: str
    # The label over the table of contents whose leader is stretched.
    stretch: str
    # The label over the table of contents whose leader is set smaller and raised.
    from_text: str
    # What each of the four columns is called.
    columns: tuple[str, str, str, str]
    # What each row of `ROWS` is a category of.
    categories: tuple[str, str, str]
    # The entries of the table of contents, each set on the page `PAGES` gives it.
    contents: tuple[str, str, str, str, str]

    def relative_label(self) -> str:
        """The label over the relative panel, around the share it opens."""
        return f"{self.relative[0]}{SHARE}{self.relative[1]}"

    def typewriter_label(self) -> str:
        """The label over the typewriter panel, around the step it works in."""
        return f"{self.typewriter[0]}{GRID:g}{self.typewriter[1]}"

    def relative_told_label(self) -> str:
        """The label over the second page's relative panel, around the share it
        opens."""
        return f"{self.relative_told[0]}{WIDE_SHARE_SAID}{self.relative_told[1]}"

    def comma_rows(self) -> str:
        """The rows of `rows`, their prices written with a decimal comma."""
        return self.rows().replace(".", ",")

    def rows(self) -> str:
        """The four columns the first three panels set, a tabulation between each pair
        and a heading over them."""
        lines = ["\t".join(self.columns)]
        lines.extend(
            f"{row[0]}\t{category}\t{row[1]}\t{row[2]}"
            for row, category in zip(ROWS, self.categories)
        )
        return "\n".join(lines)

    def listed(self) -> str:
        """The table of contents, each entry with its page number behind a
        tabulation."""
        return "\n".join(
            f"{entry}\t{page}" for entry, page in zip(self.contents, PAGES)
        )


# The page in English.
ENGLISH = Words(
    relative=(
        "Relative, the default: each tabulation steps the pen on by ",
        " of the column from where it stands, so the rows do not line up.",
    ),
    typewriter=(
        "Typewriter: each tabulation lands on the next multiple of ",
        " points, so the rows line up on that grid.",
    ),
    ruler=(
        "Ruler: a stop of its own for each tabulation, the second centred on it and "
        "the third lined up on its decimal point, the heading, which carries none, "
        "ending on the stop."
    ),
    listing=(
        "A ruler stop at the far edge, the run ending on it and the leader filling the "
        "room the tabulation opened."
    ),
    grid_listing=(
        "The same stop, the leader a spaced dot in grey set on a grid, so its dots "
        "stand in the same columns on every line."
    ),
    relative_told=(
        "Relative, told so, each tabulation stepping the pen on by ",
        " of the column: steps twice as long, the rows still out of line.",
    ),
    comma=(
        "Ruler, its third stop lining the prices up on a decimal comma rather than on "
        "a full stop."
    ),
    from_edge=(
        "The leader laid from the far edge inwards: the room its repeats do not fill "
        "is left against the words."
    ),
    stretch=(
        "The leader stretched: as many whole dots as fit, spread from one end of the "
        "room to the other."
    ),
    from_text=(
        "The leader laid from the words outwards, a dash in a smaller size raised off "
        "the baseline."
    ),
    columns=(
        "Reference",
        "Category",
        "Quantity",
        "Unit price",
    ),
    categories=(
        "Binding",
        "Cover",
        "Paper",
    ),
    contents=(
        "Getting started",
        "The page model",
        "Fonts and the text engine",
        "Tables and their columns",
        "Digital signatures",
    ),
)

# The page in French.
FRENCH = Words(
    relative=(
        "Relative, par défaut : chaque tabulation avance le texte de ",
        (
            " de la colonne à partir de sa position, si bien que les lignes ne "
            "s’alignent pas."
        ),
    ),
    typewriter=(
        "Machine à écrire : chaque tabulation tombe sur le multiple suivant de ",
        " points, donc les lignes s’alignent sur cette grille.",
    ),
    ruler=(
        "Règle : un taquet par tabulation, le deuxième centré dessus et le troisième "
        "aligné sur son séparateur décimal ; l’en-tête, qui n’en a pas, se termine sur "
        "le taquet."
    ),
    listing=(
        "Un taquet de règle au bord droit, le texte s’y terminant et les points de "
        "conduite comblant l’espace ouvert par la tabulation."
    ),
    grid_listing=(
        "Le même taquet, les points de conduite espacés, en gris et posés sur une "
        "grille, donc alignés d’une ligne à l’autre."
    ),
    relative_told=(
        "Relative, demandée expressément, chaque tabulation avançant le texte de ",
        " de la colonne : des pas deux fois plus longs, les lignes toujours décalées.",
    ),
    comma=(
        "Règle, son troisième taquet alignant les prix sur une virgule décimale plutôt "
        "que sur un point."
    ),
    from_edge=(
        "Les points de conduite posés depuis le bord droit : l’espace qu’ils ne "
        "remplissent pas reste contre le texte."
    ),
    stretch=(
        "Les points de conduite étirés : autant de points entiers qu’il en tient, "
        "répartis d’un bout à l’autre de l’espace."
    ),
    from_text=(
        "Les points de conduite posés depuis le texte, un tiret plus petit et surélevé "
        "par rapport à la ligne de base."
    ),
    columns=(
        "Référence",
        "Catégorie",
        "Quantité",
        "Prix unitaire",
    ),
    categories=(
        "Reliure",
        "Couverture",
        "Papier",
    ),
    contents=(
        "Pour commencer",
        "Le modèle de page",
        "Les polices et le moteur de texte",
        "Les tableaux et leurs colonnes",
        "Les signatures numériques",
    ),
)

# The page in Dutch.
DUTCH = Words(
    relative=(
        "Relatief, de standaard: elke tab zet de pen",
        " van de kolom verder vanaf waar hij staat, dus de rijen lijnen niet uit.",
    ),
    typewriter=(
        "Schrijfmachine: elke tab komt op het volgende veelvoud van",
        " punten, dus de rijen lijnen uit op dat raster.",
    ),
    ruler=(
        "Liniaal: een eigen tabstop voor elke tab, de tweede erop gecentreerd en de "
        "derde uitgelijnd op het decimaalteken, en de kop, die er geen heeft, eindigt "
        "op de tabstop."
    ),
    listing=(
        "Een liniaaltabstop aan de verre rand, de tekst eindigt erop en de opvulling "
        "vult de ruimte die de tab opende."
    ),
    grid_listing=(
        "Dezelfde tabstop, de opvulling een gespatieerde grijze punt op een raster, "
        "dus de punten staan op elke regel in dezelfde kolommen."
    ),
    relative_told=(
        "Relatief, uitdrukkelijk opgegeven: elke tab zet de pen",
        " van de kolom verder: stappen twee keer zo lang, de rijen nog steeds niet uitgelijnd.",
    ),
    comma=(
        "Liniaal, de derde tabstop lijnt de prijzen uit op een decimale komma in "
        "plaats van een punt."
    ),
    from_edge=(
        "De opvulling gelegd van de verre rand naar binnen: de ruimte die de "
        "herhalingen niet vullen, blijft bij de woorden."
    ),
    stretch=(
        "De opvulling uitgerekt: zoveel hele punten als passen, verspreid van het ene "
        "eind van de ruimte naar het andere."
    ),
    from_text=(
        "De opvulling gelegd van de woorden naar buiten, een streepje in een kleinere "
        "grootte boven de basislijn."
    ),
    columns=(
        "Referentie",
        "Categorie",
        "Aantal",
        "Stukprijs",
    ),
    categories=(
        "Bindwerk",
        "Omslag",
        "Papier",
    ),
    contents=(
        "Aan de slag",
        "Het paginamodel",
        "Lettertypen en de tekstmotor",
        "Tabellen en hun kolommen",
        "Digitale handtekeningen",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    relative=(
        "Relativo, por omissão: cada tabulação avança a caneta",
        " da coluna a partir de onde está, por isso as linhas não se alinham.",
    ),
    typewriter=(
        "Máquina de escrever: cada tabulação cai no múltiplo seguinte de",
        " pontos, por isso as linhas alinham-se nessa grelha.",
    ),
    ruler=(
        "Régua: uma paragem própria para cada tabulação, a segunda centrada nela e a "
        "terceira alinhada pelo separador decimal, e o título, que não tem nenhum, a "
        "acabar na paragem."
    ),
    listing=(
        "Uma paragem de régua na margem, o texto a acabar nela e o enchimento a "
        "preencher o espaço que a tabulação abriu."
    ),
    grid_listing=(
        "A mesma paragem, o enchimento um ponto espaçado em cinzento numa grelha, por "
        "isso os seus pontos ficam nas mesmas colunas em cada linha."
    ),
    relative_told=(
        "Relativo, dito explicitamente, cada tabulação a avançar a caneta",
        " da coluna: passos duas vezes mais longos, as linhas ainda desalinhadas.",
    ),
    comma=(
        "Régua, a terceira paragem a alinhar os preços por uma vírgula decimal em vez "
        "de um ponto."
    ),
    from_edge=(
        "O enchimento posto da margem para dentro: o espaço que as suas repetições "
        "não enchem fica junto às palavras."
    ),
    stretch=(
        "O enchimento esticado: tantos pontos inteiros quantos cabem, espalhados de "
        "uma ponta à outra do espaço."
    ),
    from_text=(
        "O enchimento posto das palavras para fora, um traço num corpo menor "
        "levantado da linha de base."
    ),
    columns=(
        "Referência",
        "Categoria",
        "Quantidade",
        "Preço unitário",
    ),
    categories=(
        "Encadernação",
        "Capa",
        "Papel",
    ),
    contents=(
        "Primeiros passos",
        "O modelo de página",
        "Os tipos de letra e o motor de texto",
        "As tabelas e as suas colunas",
        "As assinaturas digitais",
    ),
)

# The page in Italian.
ITALIAN = Words(
    relative=(
        "Relativo, predefinito: ogni tabulazione fa avanzare la penna di",
        " della colonna da dove si trova, così le righe non si allineano.",
    ),
    typewriter=(
        "Macchina da scrivere: ogni tabulazione cade sul multiplo successivo di",
        " punti, così le righe si allineano su quella griglia.",
    ),
    ruler=(
        "Righello: un fermo proprio per ogni tabulazione, il secondo centrato su di "
        "esso e il terzo allineato sul separatore decimale, e il titolo, che non ne "
        "ha, finisce sul fermo."
    ),
    listing=(
        "Un fermo di righello sul bordo, il testo che finisce lì e il riempitivo che "
        "occupa lo spazio aperto dalla tabulazione."
    ),
    grid_listing=(
        "Lo stesso fermo, il riempitivo un punto spaziato in grigio su una griglia, "
        "così i suoi punti stanno nelle stesse colonne su ogni riga."
    ),
    relative_told=(
        "Relativo, detto esplicitamente, ogni tabulazione che fa avanzare la penna di",
        " della colonna: passi lunghi il doppio, le righe ancora disallineate.",
    ),
    comma=(
        "Righello, il terzo fermo che allinea i prezzi su una virgola decimale "
        "anziché su un punto."
    ),
    from_edge=(
        "Il riempitivo steso dal bordo verso l’interno: lo spazio che le sue "
        "ripetizioni non riempiono resta vicino alle parole."
    ),
    stretch=(
        "Il riempitivo allungato: quanti punti interi ci stanno, distribuiti da un "
        "capo all’altro dello spazio."
    ),
    from_text=(
        "Il riempitivo steso dalle parole verso l’esterno, un trattino in un corpo "
        "minore sollevato dalla linea di base."
    ),
    columns=(
        "Riferimento",
        "Categoria",
        "Quantità",
        "Prezzo unitario",
    ),
    categories=(
        "Rilegatura",
        "Copertina",
        "Carta",
    ),
    contents=(
        "Per iniziare",
        "Il modello di pagina",
        "I font e il motore del testo",
        "Le tabelle e le loro colonne",
        "Le firme digitali",
    ),
)

# The page in Spanish.
SPANISH = Words(
    relative=(
        "Relativo, por defecto: cada tabulación avanza la pluma",
        " de la columna desde donde está, así que las filas no se alinean.",
    ),
    typewriter=(
        "Máquina de escribir: cada tabulación cae en el siguiente múltiplo de",
        " puntos, así que las filas se alinean en esa rejilla.",
    ),
    ruler=(
        "Regla: un tope propio por tabulación, el segundo centrado en él y el tercero "
        "alineado en su separador decimal, y el título, que no lleva ninguno, "
        "acabando en el tope."
    ),
    listing=(
        "Un tope de regla en el borde, el texto acabando en él y el relleno ocupando "
        "el hueco que abrió la tabulación."
    ),
    grid_listing=(
        "El mismo tope, el relleno un punto espaciado en gris sobre una rejilla, así "
        "que sus puntos quedan en las mismas columnas en cada línea."
    ),
    relative_told=(
        "Relativo, dicho expresamente, cada tabulación avanzando la pluma",
        " de la columna: pasos el doble de largos, las filas aún desalineadas.",
    ),
    comma=(
        "Regla, su tercer tope alineando los precios en una coma decimal y no en un "
        "punto."
    ),
    from_edge=(
        "El relleno puesto desde el borde hacia dentro: el hueco que no llenan sus "
        "repeticiones queda junto a las palabras."
    ),
    stretch=(
        "El relleno estirado: tantos puntos enteros como caben, repartidos de un "
        "extremo al otro del hueco."
    ),
    from_text=(
        "El relleno puesto desde las palabras hacia fuera, un guion en un cuerpo "
        "menor elevado sobre la línea base."
    ),
    columns=(
        "Referencia",
        "Categoría",
        "Cantidad",
        "Precio unitario",
    ),
    categories=(
        "Encuadernación",
        "Cubierta",
        "Papel",
    ),
    contents=(
        "Primeros pasos",
        "El modelo de página",
        "Las fuentes y el motor de texto",
        "Las tablas y sus columnas",
        "Las firmas digitales",
    ),
)

# The page in German.
GERMAN = Words(
    relative=(
        "Relativ, die Voreinstellung: Jeder Tabulator rückt den Stift um ",
        " der Spalte von seiner Stelle aus weiter, also fluchten die Zeilen nicht.",
    ),
    typewriter=(
        "Schreibmaschine: Jeder Tabulator landet auf dem nächsten Vielfachen von ",
        " Punkt, also fluchten die Zeilen auf diesem Raster.",
    ),
    ruler=(
        "Lineal: ein eigener Stopp für jeden Tabulator, der zweite darauf zentriert "
        "und der dritte am Dezimalpunkt ausgerichtet; die Kopfzeile, die keinen hat, "
        "endet am Stopp."
    ),
    listing=(
        "Ein Linealstopp am äußeren Rand, der Text endet dort, und die Füllzeichen "
        "füllen den Raum, den der Tabulator öffnete."
    ),
    grid_listing=(
        "Derselbe Stopp, die Füllzeichen ein gesperrter grauer Punkt auf einem "
        "Raster, also stehen seine Punkte in jeder Zeile in denselben Spalten."
    ),
    relative_told=(
        "Relativ, ausdrücklich so eingestellt, jeder Tabulator rückt den Stift um ",
        " der Spalte weiter: doppelt so lange Schritte, die Zeilen fluchten noch immer nicht.",
    ),
    comma=(
        "Lineal, sein dritter Stopp richtet die Preise an einem Dezimalkomma statt an "
        "einem Punkt aus."
    ),
    from_edge=(
        "Füllzeichen vom äußeren Rand nach innen gelegt: Der Raum, den ihre "
        "Wiederholungen nicht füllen, bleibt an den Wörtern."
    ),
    stretch=(
        "Füllzeichen gestreckt: so viele ganze Punkte, wie passen, von einem Ende des "
        "Raums zum anderen verteilt."
    ),
    from_text=(
        "Füllzeichen von den Wörtern nach außen gelegt, ein kleinerer Strich über die "
        "Grundlinie gehoben."
    ),
    columns=(
        "Referenz",
        "Kategorie",
        "Menge",
        "Einzelpreis",
    ),
    categories=(
        "Bindung",
        "Umschlag",
        "Papier",
    ),
    contents=(
        "Erste Schritte",
        "Das Seitenmodell",
        "Schriften und die Text-Engine",
        "Tabellen und ihre Spalten",
        "Digitale Signaturen",
    ),
)

# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}


def panel(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    top: float,
    label: str,
    flow: hqf_pdf.TextFlow,
    text: str,
    stops: Sequence[float],
) -> None:
    """Draws one panel: its heading, the tabulated block below it, and a grey rule
    at every stop the block was told to use."""
    heading = hqf_pdf.TextFlow(handle, 8.0)
    heading_lines = heading.break_lines(label, COLUMN)
    heading.draw(content, heading_lines, X, top, COLUMN)

    text_top = top - DROP
    lines = flow.break_lines(text, COLUMN)
    height = flow.height(lines)

    # The stops first, so the text is read over them rather than under them.
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.78, 0.78, 0.82))
    content.set_line_width(0.5)
    for stop in stops:
        content.move_to(X + stop, text_top)
        content.line_to(X + stop, text_top - height)
        content.stroke()
    content.restore_state()

    flow.draw(content, lines, X, text_top, COLUMN)



def second_page(handle, words) -> hqf_pdf.Page:
    """The second page: the relative method told so at a wider step, the ruler on a
    decimal comma, and the table of contents under three more leaders."""
    content = hqf_pdf.Content()
    rows = words.rows()

    # The method a flow takes when told nothing, told so, at a step of its own.
    relative = hqf_pdf.TextFlow(
        handle,
        11.0,
        leading=16.0,
        tab_method=hqf_pdf.TabMethod.Relative,
        tab_size=hqf_pdf.TabSize.fraction(WIDE_SHARE),
    )
    panel(content, handle, 780.0, words.relative_told_label(), relative, rows, [])

    comma = hqf_pdf.TextFlow(
        handle,
        11.0,
        leading=16.0,
        tab_method=hqf_pdf.TabMethod.Ruler,
        tab_ruler=RULER,
        tab_alignments=[
            hqf_pdf.TabAlign.Left,
            hqf_pdf.TabAlign.Center,
            hqf_pdf.TabAlign.Decimal,
        ],
        tab_align_char=",",
    )
    panel(content, handle, 660.0, words.comma, comma, words.comma_rows(), RULER)

    listed = words.listed()
    leaders = (
        (
            540.0,
            words.from_edge,
            hqf_pdf.Leader(
                ". ",
                color=hqf_pdf.Rgb(0.55, 0.55, 0.55),
                fit=hqf_pdf.LeaderFit.FromEdge,
            ),
        ),
        (400.0, words.stretch, hqf_pdf.Leader(".", fit=hqf_pdf.LeaderFit.Stretch)),
        (
            260.0,
            words.from_text,
            hqf_pdf.Leader(
                "\u2013 ",
                font=handle,
                size=7.0,
                rise=2.0,
                fit=hqf_pdf.LeaderFit.FromText,
            ),
        ),
    )
    for top, label, leader in leaders:
        flow = hqf_pdf.TextFlow(
            handle,
            11.0,
            leading=16.0,
            tab_method=hqf_pdf.TabMethod.Ruler,
            tab_ruler=[COLUMN],
            tab_alignments=[hqf_pdf.TabAlign.Right],
            leader_with=leader,
        )
        panel(content, handle, top, label, flow, listed, [COLUMN])

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    return page


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("tab_stops.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    content = hqf_pdf.Content()
    rows = words.rows()

    # Relative, which is what a flow does when it is told nothing: every tabulation
    # steps the pen on by the tab size from wherever it stands, so a longer entry pushes
    # the whole row along with it.
    relative = hqf_pdf.TextFlow(handle, 11.0, leading=16.0)
    panel(content, handle, 780.0, words.relative_label(), relative, rows, [])

    # A typewriter's tab bar: every tabulation lands on the next multiple of the tab
    # size, so the rows line up on a grid however wide their entries are.
    typewriter = hqf_pdf.TextFlow(
        handle,
        11.0,
        leading=16.0,
        tab_method=hqf_pdf.TabMethod.Typewriter,
        tab_size=hqf_pdf.TabSize.points(GRID),
    )
    panel(
        content,
        handle,
        660.0,
        words.typewriter_label(),
        typewriter,
        rows,
        [GRID, GRID * 2.0, GRID * 3.0, GRID * 4.0],
    )

    # A ruler names its stops, and each one says how the run it opens sits about it: the
    # quantities are centred, the prices line up on their decimal point.
    ruler = hqf_pdf.TextFlow(
        handle,
        11.0,
        leading=16.0,
        tab_method=hqf_pdf.TabMethod.Ruler,
        tab_ruler=RULER,
        tab_alignments=[
            hqf_pdf.TabAlign.Left,
            hqf_pdf.TabAlign.Center,
            hqf_pdf.TabAlign.Decimal,
        ],
    )
    panel(content, handle, 540.0, words.ruler, ruler, rows, RULER)

    # The stop sits at the far edge and the run ends on it, so the numbers are flush
    # right whatever they are worth, and the leader fills the room the tabulation
    # opened.
    contents = hqf_pdf.TextFlow(
        handle,
        11.0,
        leading=16.0,
        tab_method=hqf_pdf.TabMethod.Ruler,
        tab_ruler=[COLUMN],
        tab_alignments=[hqf_pdf.TabAlign.Right],
        leader=".",
    )
    panel(content, handle, 420.0, words.listing, contents, words.listed(), [COLUMN])

    # The same listing, its leader a dot and a space in grey, laid on a grid of its own
    # width counted from the left edge of the box.
    gridded = hqf_pdf.TextFlow(
        handle,
        11.0,
        leading=16.0,
        tab_method=hqf_pdf.TabMethod.Ruler,
        tab_ruler=[COLUMN],
        tab_alignments=[hqf_pdf.TabAlign.Right],
        leader_with=hqf_pdf.Leader(
            ". ", color=hqf_pdf.Rgb(0.55, 0.55, 0.55), fit=hqf_pdf.LeaderFit.Grid
        ),
    )
    panel(
        content, handle, 280.0, words.grid_listing, gridded, words.listed(), [COLUMN]
    )

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)
    document.add_page(second_page(handle, words))

    written = document.write(out)
    print(f"wrote {out}: {written} bytes")


if __name__ == "__main__":
    main()