Debian Codegraph @

texmf-dist/source/lualatex/lua-typo/lua-typo.dtx

raw
1 % \iffalse meta-comment
2 %
3 % This program can be distributed and/or modified under the terms
4 % of the LaTeX Project Public License either version 1.3c of this
5 % license or (at your option) any later version.
6 % The latest version of this license is in
7 % http://www.latex-project.org/lppl.txt
8 % and version 1.3c or later is part of all distributions of LaTeX
9 % version 2005/12/01 or later.
10 %
11 % This file has the LPPL maintenance status "maintained".
12 %
13 % Lua-Typo package for LaTeX version 2e
14 %
15 % Copyright © 2020-2026 by Daniel Flipo
16 %
17 % Please report errors to: daniel (dot) flipo (at) free (dot) fr
18 %
19 %<*batch>
20 %<*gobble>
21 \ifx\jobname\relax\let\documentclass\undefined\fi
22 \ifx\documentclass\undefined
23 \csname fi\endcsname
24 %</gobble>
25 \input docstrip.tex
26 \keepsilent
27 \let\MetaPrefix\relax
28 \preamble
29 \endpreamble
30 \postamble
31 \endpostamble
32 \let\MetaPrefix\DoubleperCent
33 \askforoverwritefalse
34 \generate{%
35 \file{lua-typo.sty}{\from{lua-typo.dtx}{sty}}%
36 \nopreamble
37 \file{lua-typo.cfg}{\from{lua-typo.dtx}{cfg}}%
38 \file{lua-typo-fr.ltx}{\from{lua-typo.dtx}{driver,docfr}}%
39 \file{lua-typo.ltx}{\from{lua-typo.dtx}{driver,doc}}%
40 }
41 \iffalse
42 \generate{%
43 \file{lua-typo.sty}{\from{lua-typo.dtx}{sty,dbg}}%
44 \file{scan-page.sty}{\from{lua-typo.dtx}{scan}}%
45 }
46 \fi
47 \endbatchfile
48 %</batch>
49 %<*gobble>
50 \fi
51 \expandafter\ifx\csname @currname\endcsname\empty
52 \csname fi\endcsname
53 %</gobble>
54 %<*driver>
55 %<+doc>\DocumentMetadata{pdfstandard={UA-2,A-4f}, lang=en-GB}
56 %<+doc>\documentclass[a4paper,british]{ltxdoc}
57 %<+docfr>\DocumentMetadata{pdfstandard={UA-2,A-4f}, lang=fr-FR}
58 %<+docfr>\documentclass[a4paper,french]{ltxdoc}
59 \usepackage{fontspec}
60 \setmainfont{erewhon}
61 \setsansfont{Cabin}[Scale=MatchLowercase]
62 \setmonofont{MonaspaceNeon}[%
63 Scale = MatchLowercase, FakeStretch = .81,
64 HyphenChar=None, Color=5D1D00,
65 Extension = .otf,
66 UprightFont = *-Regular,
67 ItalicFont = *-Italic,
68 BoldFont = *-ExtraBold,
69 BoldFontItalic = *-ExtraBoldItalic,
70 ]
71 \usepackage[expansion=true, protrusion=true]{microtype}
72 \usepackage{babel,varioref}
73 \usepackage[ShortPages, OverfullLines, UnderfullLines,
74 EOPHyphens, RepeatedHyphens, % Widows, Orphans,
75 ]{lua-typo}
76 %\renewcommand*\descriptionlabel[1]{%
77 % \hspace{\labelsep}\texttt{#1}}
78 \usepackage{array,url,verbatim}
79 \usepackage[numbered]{hypdoc}
80 \hypersetup{colorlinks,urlcolor=blue,unicode}
81 %
82 %<+docfr>\OnlyDescription
83 %<+docfr>\let\FrenchDoc\begingroup\let\endFrenchDoc\endgroup
84 %<+doc|docfr>\let\Debugging\comment\let\endDebugging\endcomment
85 %<*doc>
86 \let\FrenchDoc\comment\let\endFrenchDoc\endcomment
87 \RecordChanges
88 \AtEndDocument{%
89 \clearpage
90 \section{Change History}%
91 \GlossaryPrologue{}%
92 Changes are listed in reverse order (latest first)
93 from version~0.30.
94 \PrintChanges
95 }
96 %</doc>
97 \newcommand*\texdir[1]{\textsc{#1}}
98 \newcommand*\file[1]{\texttt{#1}}
99 \newcommand*\pkg[1]{\texttt{#1}}
100 \newcommand*\opt[1]{\texttt{#1}}
101 \renewcommand\meta[1]{\texttt{\textsl{<#1>}}}
102 \newcommand*\node[1]{\textsc{#1}}
103 %
104 \setlength{\parindent}{0pt}
105 \setlength{\parskip}{.3\baselineskip plus 0.3pt minus 0.3pt}
106 \begin{document}
107 \GetFileInfo{lua-typo.sty}
108 \DocInput{lua-typo.dtx}
109 \end{document}
110
111 %%% Local Variables:
112 %%% coding: utf-8
113 %%% TeX-engine: luatex
114 %%% End:
115 %</driver>
116 %<*gobble>
117 \fi
118 %</gobble>
119 % \fi
120 %
121 % \begin{FrenchDoc}
122 % \begin{center}
123 % \textbf{\Large Recherche d’imperfections typographiques\\[3pt]
124 % avec LuaLaTeX}
125 % \\[.5\baselineskip]^^A\]
126 % {\large Daniel Flipo}\\
127 % \texttt{[email protected]}
128 % \end{center}
129 %
130 % \section{De quoi s’agit-il ?}
131 %
132 % L’extension \pkg{lua-typo} décrite ci-dessous%
133 % \footnote{Version \fileversion, mise à jour le \filedate.}
134 % permet de mettre en lumière par un changement de couleur, les
135 % lignes potentiellement imparfaites d’un fichier PDF produit par
136 % LuaLaTeX ; comme son nom l’indique elle ne fonctionne qu’avec
137 % LuaLaTeX. Une liste des pages concernées est affichée à la fin
138 % du fichier \file{.log}, permettant un accès rapide aux pages
139 % incriminées. \pkg{lua-typo} crée également un fichier de suffixe
140 % \file{.typo} regroupant les informations (type, page, ligne) sur
141 % les imperfections relevées.
142 %
143 % Normalement, c’est-à-dire lorsque la justification n’est pas trop
144 % étroite, (Lua)TeX fait du bon travail, surtout si \pkg{microtype}
145 % est utilisé mais il peut rester des points à vérifier, notamment
146 % des lignes trop pleines ou lavées (\emph{Overfull, Underfull box}),
147 % des veuves et des orphelines, des mots coupés en fin de page ou
148 % d’alinéa ou sur plusieurs lignes consécutives, des dernières lignes
149 % d’alinéa trop courtes ou presque pleines, des pages quasi vides.
150 % La répétition d’un même mot ou partie de mot au début ou à la fin
151 % de deux lignes consécutives est aussi détectée.
152 % La présence en fin de ligne de certains mots très courts (une ou
153 % deux lettres, liste dépendant de la langue) peut également être
154 % recherchée.
155 %
156 % \textbf{Important :} a) les lignes totalement ou partiellement
157 % coloriées par \pkg{lua-typo} le sont uniquement pour
158 % \emph{attirer l’attention} du correcteur à qui il appartient
159 % de décider si ces lignes doivent être remaniées ou non.
160 % Certains « défauts » peuvent être acceptables dans certaines
161 % conditions (multicolonnage, documents techniques) et pas dans
162 % d’autres, œuvres litéraires par exemple.
163 % Seul un humain entrainé peut décider si une ligne légèrement lavée
164 % est acceptable ou non, ou si la suppression d’une coupure malvenue
165 % ne va pas provoquer d’autres désordres bien plus graves.\\
166 % b) Inversement, il n’est pas exclu que \pkg{lua-typo} comporte
167 % des bogues l’empêchant de détecter des lignes potentiellement
168 % imparfaites. Depuis la version~0.85, le fichier \file{.typo}
169 % fournit, s’il y a lieu, une liste de pages « suspectes », celles où
170 % aucune ligne de texte n’a été trouvée. L’avertissement peut être
171 % anodin (page contenant uniquement des illustrations par exemple) ou
172 % révéler un défaut de détection.\\
173 % c) Les vérifications de \pkg{lua-typo} sur les boîtes de type
174 % minipages ou parbox ou marginpar ne portent que sur les
175 % « Overfull/Underfull boxes ».
176 %
177 % \pkg{lua-typo} est largement configurable et devrait pouvoir
178 % s’adapter aux exigences variables des auteurs ou correcteurs :
179 % voir ci-dessous la liste des options et le fichier de configuration
180 % \file{lua-typo.cfg}.
181 %
182 % \pkg{lua-typo} ne corrigeant aucun des « défauts » relevés, quels
183 % sont les moyens à notre disposition pour le faire manuellement ?
184 % Reformuler une phrase est souvent efficace, un auteur peut se le
185 % permettre, un correcteur ne le peut pas. Il est possible de jouer
186 % sur l’espace inter-mots grâce à la commande TeX \cs{spaceskip},
187 % ou sur l’interlettrage grâce à la commande \cs{textls} de
188 % \pkg{microtype} mais dans les deux cas, le faire
189 % \emph{avec parcimonie}\footnote{%
190 % Le but ultime est de parvenir à un « gris typographique »,
191 % aussi parfait que possible ; l’argument optionnel de \cs{textls} ne
192 % devrait guère sortir de l’intervalle $[-5,+15]$ (unité
193 % 1/1000\up{e}\,\texttt{em}) et \cs{spaceskip} devrait rester très
194 % proche de l’espace-mot standard déterminée par les \cs{fontdimen}.}
195 % pour que le remède ne soit pas pire que le mal.
196 % Un \emph{léger} accroissement de l’espace inter-mots ou de
197 % l’interlettrage dans un groupe de mots peut rendre acceptable la
198 % dernière ligne initialement trop courte d’un paragraphe ou, si elle
199 % était presque pleine, ajouter une ligne, ce qui peut permettre
200 % de supprimer une orpheline.
201 % De même une légère contraction peut supprimer la dernière ligne
202 % (courte) d’un paragraphe et éviter une veuve en début de la page
203 % suivante.
204 %
205 % Je conseille de n’appliquer \pkg{lua-typo} que sur des textes
206 % « presque au point », d’améliorer ce qui peut l’être puis de
207 % \emph{supprimer} l’appel à \pkg{lua-typo} afin de ne pas risquer
208 % de mettre en lumière les imperfections que l’on aura renoncé
209 % à corriger. Pour appliquer toutes les vérifications proposées par
210 % \pkg{lua-typo}, il suffit d’ajouter dans le préambule la ligne %\\
211 % |\usepackage[All]{lua-typo}|
212 %
213 % La version courante (\fileversion) nécessite un noyau LaTeX récent,
214 % 2022/06/01 ou ultérieur. Ceux qui ne disposent que d’un noyau
215 % antérieur à 2021/06/01 reçoivent un message d’erreur
216 % «\texttt{Unable to register callback}» ; une version «rollback »
217 % est prévue à leur intention, elle se charge par la commande
218 % |\usepackage[All]{lua-typo}[=v0.4]|. Une autre version
219 % intermédiaire est présente, elle se charge avec l’option |[=v0.65]|.
220 %
221 % Les fichiers \file{demo.tex} et \file{demo.pdf} fournissent un
222 % exemple du traitement opéré par \pkg{lua-typo}.
223 %
224 % Un grand merci à Jacques André et Thomas Savary pour avoir accepté
225 % de tester les pré-versions et pour leurs retours riches et toujours
226 % pertinents ; leurs suggestions et leurs encouragements ont
227 % grandement contribué à améliorer la première version mise en ligne.
228 % Merci également à Michel Bovani pour ses remarques et suggestions
229 % qui ont conduit à la version~0.61.
230 %
231 % \section{Utilisation}
232 %
233 % Comme indiqué plus haut la vérification la plus complète s’obtient
234 % par :\\
235 % |\usepackage[All]{lua-typo}|
236 %
237 % Il est possible de choisir les tests à activer de deux
238 % manières, soit « tout sauf … » soit « seulement ceci et cela ».
239 % Pour tout activer sauf les options \meta{OptX} et \meta{OptY} :\\
240 % |\usepackage[All, |\meta{OptX}|=false, |\meta{OptY}|=false]{lua-typo}|\\
241 % ou pour se limiter aux tests \meta{OptX} et \meta{OptY} :\\
242 % |\usepackage[|\meta{OptX}|, |\meta{OptY}|]{lua-typo}|
243 %
244 % La liste des options et le type des vérifications proposées sont
245 % présentés dans le tableau \vpageref{options-fr}.
246 % Par exemple, pour limiter les vérifications aux lignes trop pleines
247 % ou creuses, il suffit de coder :\\
248 % |\usepackage[OverfullLines, UnderfullLines]{lua-typo}|\\
249 % Pour tout vérifier sauf les coupures répétées en fin de ligne on
250 % codera :\\
251 % |\usepackage[All, RepeatedHyphens=false]{lua-typo}|\\
252 % Notez que l’option that \opt{All} doit être la première de la
253 % liste, les suivantes étant rétirées de la liste complète définie
254 % par~\opt{All}.
255 %
256 % \begin{table}[ht]
257 % \centering\label{options-fr}
258 % \begin{tabular}{>{\ttfamily}ll}
259 % \multicolumn{1}{l}{Nom} & Imperfection à signaler\\ \hline
260 % All & Active toutes les options ci-dessous\\
261 % ShortLines & Dernière ligne d’alinéa trop courte ?\\
262 % BackParindent & Dernière ligne d’alinéa \emph{presque} pleine ?\\
263 % ShortPages & Page quasi vide (quelques lines) ?\\
264 % OverfullLines & Ligne trop pleine ?\\
265 % UnderfullLines & Ligne lavée ? \\
266 % Widows & Veuve (haut de page) ?\\
267 % Orphans & Orpheline (bas de page) ?\\
268 % EOPHyphens & Mot coupé en bas de page ?\\
269 % RepeatedHyphens & Coupures sur trop de lignes consécutives ?\\
270 % ParLastHyphen & Coupure à l’avant-dernière ligne d’un alinéa ?\\
271 % EOLShortWords & Mots courts (1 or 2 lettres) en fin de ligne ?\\
272 % FirstWordMatch & Même (partie de) mot en début de lignes
273 % consécutives ?\\
274 % LastWordMatch & Même (partie de) mot en fin de lignes
275 % consécutives ?\\
276 % FootnoteSplit & Fin de note de bas de page sur page suivante?\\
277 % ShortFinalWord & Mot de fin de phrase court en haut de page\\
278 % MarginparPos & Note marginale se terminant trop bas\\
279 % \hline
280 % \end{tabular}
281 % \end{table}
282 %
283 % Le nom des différentes options n’étant pas facile à mémoriser, il
284 % est possible de les retrouver sans devoir consulter la
285 % documentation ; l’option \opt{ShowOptions} affiche la liste
286 % complète dans le fichier \file{.log} :
287 % |\usepackage[ShowOptions]{lua-typo}|
288 %
289 % L’option \opt{None}, empêche toute vérification :
290 % |\usepackage[None]{lua-typo}|
291 % a pour effet de supprimer complètement tout ajout de code LuaTeX
292 % (aucune fonction n’est ajoutée aux \emph{callbacks} de LuaTeX).
293 % Cette option peut-être utile lors de la toute dernière compilation,
294 % elle n’est pas tout-à-fait équivalente à la mise en commentaire de la
295 % ligne car les variables utilisées par \pkg{luatypo} restent
296 % définies ; si certaines ont été modifiées dans le préambule aucun
297 % message d’erreur du type ``\emph{Undefined Control Sequence}’’ ne
298 % sera émis à leur sujet.
299 %
300 % Terminons par quelques précisions sur ces options.
301 % \begin{description}
302 % \item[\opt{FirstWordMatch :}] les répétitions en début de ligne dans les
303 % listes ne sont pas signalées. Ceci est voulu car elles résultent
304 % d’un choix délibéré de l’auteur.
305 % \item[\opt{ShortPages :}] lorsque le nombre de lignes d’une page est jugé
306 % insuffisant (voir ci-dessous), seule la dernière ligne de celle-ci
307 % est mise en couleur.
308 % \item[\opt{RepeatedHyphens :}] de même, lorsque le nombre de lignes
309 % consécutives affectées par des coupures dépasse le seuil fixé
310 % (voir ci-dessous), ne sont coloriées que les coupures en excès.
311 % \item[\opt{ShortFinalWord :}] lorsque le premier mot de la première ligne
312 % d’une page termine une phrase et qu’il est court (au plus
313 % |\luatypoMinLen=4| lettres), on le signale.
314 % \end{description}
315 %
316 % \section{Incompatibilités connues}
317 %
318 % La version actuelle de \pkg{lua-typo} est incompatible avec
319 % l’extension \pkg{reledmac}. Si celle-ci est chargée, aucune
320 % vérification n’est effectuée par \pkg{lua-typo}, l’utilisateur
321 % en est informé par un message dans le fichier \file{.log}.
322 %
323 % \section{Paramétrage personnalisé}
324 %
325 % Pour certaines vérifications faites par \pkg{lua-typo} un
326 % paramétrage est nécessaire : à partir de quelle limite une dernière
327 % ligne d’alinéa est-elle considérée comme trop courte ?
328 % Combien de coupures consécutives en bout de ligne sont-elles
329 % acceptables ? Ces réglages dépendent évidemment du contexte, un
330 % correcteur de romans aura des exigences plus strictes qu’un auteur
331 % de documentation technique par exemple…
332 %
333 % \pkg{lua-typo} permet de modifier le réglage des curseurs soit dans
334 % le fichier \file{lua-typo.cfg} soit dans le préambule après l’appel
335 % de \pkg{lua-typo} ; les réglages placés dans le préambule prévalent
336 % sur ceux du fichier \file{lua-typo.cfg} qui eux-mêmes prévalent sur
337 % les réglages internes de l’extension.
338 %
339 % Le fichier \file{lua-typo.cfg} fourni avec la distribution reprend
340 % exactement les réglages internes, il se trouve normalement dans le
341 % répertoire \texdir{texmfdist} des distributions TeXLive, MikTeX, etc.
342 % L’utilisateur a la possibilité de recopier ce fichier soit dans son
343 % répertoire de travail, soit dans son répertoire \texdir{texmfhome}
344 % ou \texdir{texmflocal} et de le personnaliser comme il l’entend.
345 %
346 % Voici la liste complète des paramètres personnalisables avec leur
347 % valeur par défaut, leurs noms sont systématiquement préfixés par
348 % |luatypo| afin d’éviter de possibles conflits avec d’autres
349 % extensions.
350 % \begin{description}
351 % \item[\opt{BackParindent :}] la dernière ligne d’un alinéa
352 % devrait, soit se terminer à plus de |\luatypoBackPI=1em|
353 % de la marge droite, soit être (approximativement) pleine
354 % (tolérance |\luatypoBackFuzz=2pt|)%
355 % \footnote{Certains auteurs n’acceptent pas les lignes pleines
356 % en fin de paragraphe, ceux-là pourront faire
357 % \cs{luatypoBackFuzz=0pt} pour qu’elles soient détectées comme
358 % fautives.}.
359 %
360 % \item[\opt{ShortLines :}] |\luatypoLLminWD=2\parindent|%
361 % \footnote{Ou \texttt{20pt} si \cs{parindent=0pt}.}
362 % fixe la longueur minimale acceptable pour la dernière ligne
363 % d’un alinéa.
364 %
365 % \item[\opt{ShortPages :}] |\luatypoPageMin=5| fixe le nombre
366 % minimal de lignes d’une page pour que celle-ci ne soit pas
367 % déclarée trop courte. En fait, la position de la dernière
368 % ligne est prise en compte afin que les pages de titre ou celles
369 % contenant une image ne soient pas signalées comme fautives.
370 %
371 % \item[\opt{RepeatedHyphens :}] |\luatypoHyphMax=2| fixe le nombre maximal
372 % acceptable de lignes consécutives terminées par un mot coupé.
373 %
374 % \item[\opt{UnderfullLines :}] |\luatypoStretchMax=200| fixe le
375 % pourcentage maximal acceptable pour l’étirement des
376 % espaces-mots, au-delà la ligne est déclarée lavée.
377 % La valeur donnée doit être un entier supérieur ou égal à~100,
378 % cette valeur 100 correspond à l’étirement maximal prévu par la
379 % fonte (|\fontdimen3|) ; avec ce réglage attendez-vous à trouver
380 % une kyrielle de lignes creuses ! En fait la valeur par défaut
381 % (200) correspond approximativement à ce que TeX, avec les
382 % réglages par défaut (|\tolerance=200|, |\hbadness=1000|),
383 % considère comme \emph{Underfull hbox}.
384 %
385 % \item[\opt{First/LastWordMatch :}] |\luatypoMinFull=3| et
386 % |\luatypoMinPart=4| désignent les nombres minimaux
387 % de lettres identiques (resp. pour un mot complet ou pour une
388 % partie de mot) au début ou à la fin de deux lignes consécutives
389 % déclenchant l’avertissement.
390 % Avec ce réglage (3 et 4), seront détectées deux lignes se
391 % terminant par « cible » et « irrésistible » ou
392 % « irrésistible-(ment) » (quatre lettres en commun), ainsi que la
393 % présence de « mon » en début ou fin de deux lignes consécutives
394 % (trois lettres en commun), mais « mon » et « mont » en début de
395 % ligne échappent à la détection.
396 %
397 % \item[\opt{EOLShortWords :}] cette option signale la présence en fin de
398 % ligne de mots très courts (une ou deux lettres)
399 % qui sont répertoriés dans une des listes
400 % suivantes (elles dépendent de la langue courante) :\\
401 % |\luatypoOneChar{|\meta{langue}|}{'|\meta{liste de mots}|'}|\\
402 % |\luatypoTwoChars{|\meta{langue}|}{'|\meta{liste de mots}|'}|
403 %
404 % Lorsque les listes correspondant à la langue du document sont
405 % vides, aucune vérification n’est effectuée. Pour l’instant,
406 % il y a deux lignes (non actives) prévues pour le français :\\
407 % |\luatypoOneChar{french}{'À Ô Y'}|\\
408 % |\luatypoTwoChars{french}{'Je Tu Il On Au De'}|
409 %
410 % Deux contraintes sont à respecter lorsqu’on veut
411 % personnaliser ces listes :\\
412 % a) le premier argument (langue) \emph{doit être connu de}
413 % \pkg{babel}, aussi les commandes |\luatypoOneChar| et
414 % |\luatypoTwoChars|, si elles sont utilisées, doivent l’être
415 % \emph{après} le chargement de \pkg{babel}, une bonne habitude
416 % à prendre est donc de toujours charger \pkg{lua-typo}
417 % \emph{après} \pkg{babel} ;
418 % b) le second argument \emph{doit être une chaîne de
419 % caractères}, donc entourée de simples ou doubles
420 % \emph{quotes} \textsc{ascii} et composées de mots séparés
421 % par des espaces comme dans les exemples ci-dessus.
422 %
423 % \item[\opt{MarginparPos :}] \cs{luatypoMarginparTol}est une
424 % \emph{dimension} qui vaut |\baselineskip| par défaut;
425 % les notes marginales qui se terminent à plus de
426 % |\luatypoMarginparTol| en dessous de la dernière ligne
427 % de la page sont déclarées fautives.
428 %
429 % \end{description}
430 %
431 % À chacune des vérifications faites par \pkg{lua-typo} peut être
432 % attachée une couleur spécifique pour mettre en évidence les
433 % imperfections détectées.
434 % Actuellement, seulement six couleurs sont utilisées par défaut,
435 % voici leur définition dans \file{lua-typo.cfg} :
436 % \begin{verbatim}
437 % \definecolor{LTgrey}{gray}{0.6}
438 % \definecolor{LTred}{rgb}{1,0.55,0}
439 % \definecolor{LTline}{rgb}{0.7,0,0.3}
440 % \luatypoSetColor1{red} % Coupure à l’avant-dernière ligne
441 % \luatypoSetColor2{red} % Coupure en bas de page
442 % \luatypoSetColor3{red} % Coupures consécutives
443 % \luatypoSetColor4{red} % Mot court en fin de ligne
444 % \luatypoSetColor5{cyan} % Veuve
445 % \luatypoSetColor6{cyan} % Orpheline
446 % \luatypoSetColor7{cyan} % Dernière ligne d’alinéa trop courte
447 % \luatypoSetColor8{blue} % Ligne trop pleine
448 % \luatypoSetColor9{blue} % Ligne creuse
449 % \luatypoSetColor{10}{red} % Page presque vide (qq. lignes)
450 % \luatypoSetColor{11}{LTred} % Répétitions en début de ligne
451 % \luatypoSetColor{12}{LTred} % Répétitions en fin de ligne
452 % \luatypoSetColor{13}{LTgrey}% Dernière ligne alinéa presque pleine
453 % \luatypoSetColor{14}{cyan} % Note de bas de page éclatée
454 % \luatypoSetColor{15}{red} % Mot de fin de phrase en haut de page
455 % \luatypoSetColor{16}{LTline}% Ligne présentant plusieurs "défauts"
456 % \luatypoSetColor{17}{red} % Note marginale se terminant trop bas
457 % \end{verbatim}
458 % \pkg{lua-typo} charge les extensions \pkg{luacolor} et donc
459 % \pkg{color}. Seules les couleurs portant un nom (\emph{named
460 % colors}) peuvent être utilisées dans la commande
461 % |\luatypoSetColor| ; pour en définir de nouvelles il faut donc,
462 % soit utiliser la commande |\definecolor| de l’extension
463 % \pkg{color} (comme ci-dessus pour |LTgrey| ou |LTred|), soit
464 % charger l’extension \pkg{xcolor} qui donne accès à une
465 % kyrielle de noms de couleurs.
466 % \end{FrenchDoc}
467 %
468 % \StopEventually{}
469 %
470 % \begin{center}
471 % \textbf{\Large Highlighting Typographical Flaws with LuaLaTeX}
472 % \\[.5\baselineskip]^^A\]
473 % {\large Daniel Flipo}\\
474 % \texttt{[email protected]}
475 % \end{center}
476 %
477 % \section{What is it about?}
478 %
479 % The file \file{\filename}\footnote{The file described in this
480 % section has version number \fileversion\ and was last revised on
481 % \filedate.}, is meant for careful writers and proofreaders who do
482 % not feel totally satisfied with LaTeX output, the most frequent
483 % issues being overfull or underfull lines, widows and orphans,
484 % hyphenated words split across two pages, two many consecutive lines
485 % ending with hyphens, paragraphs ending on too short or nearly full
486 % lines, homeoarchy, etc.
487 %
488 % This package, which works with LuaLaTeX only,
489 % \emph{does not try to correct anything} but just highlights
490 % potential issues (the offending lines or end of lines are printed
491 % in colour) and provides at the end of the \file{.log} file a summary
492 % of pages to be checked and manually improved if possible.
493 % \pkg{lua-typo} also creates a \file{<jobname>.typo} file which
494 % summarises the informations (type, page, line number) about the
495 % detected issues.
496 %
497 % \textbf{Important notice:} a) the highlighted lines are only meant
498 % to \emph{draw the proofreader’s attention} on possible issues, it
499 % is up to him/her to decide whether an improvement is desirable or
500 % not; they should \emph{not} be regarded as blamable! some issues
501 % may be acceptable in some conditions (multi-columns, technical
502 % papers) and unbearable in others (literary works f.i.).
503 % Moreover, correcting a potential issue somewhere may result in
504 % other much more serious flaws somewhere else …\\
505 % b) Conversely, possible bugs in \pkg{lua-typo} might hide issues
506 % that should normally be highlighted. Starting with version~0.85,
507 % the \file{<jobname>.typo} file lists, if any, the pages on which
508 % no text line could be found. The warning may be irrelevant (page
509 % only composed of figures) or point out a possible bug.\\
510 % c) Regarding boxed materials, i.e.\ lines of text included in
511 % minipages, parboxes or marginotes, \pkg{lua-typo} \emph{only checks}
512 % Overfull/Undefull boxes.
513 %
514 % \pkg{lua-typo} is highly configurable in order to meet the
515 % variable expectations of authors and correctors: see the options’
516 % list and the \file{lua-typo.cfg} configuration file below.
517 %
518 % When \pkg{lua-typo} shows possible flaws in the page layout,
519 % how can we fix them? The simpliest way is to rephrase some bits of
520 % text… this is an option for an author, not for a proofreader.
521 % When the text can not be altered, it is possible to \emph{slightly}
522 % adjust the inter-word spacing (via the TeX commands |\spaceskip| and
523 % |\xspaceskip|) and/or the letter spacing (via \pkg{microtype}’s
524 % |\textls| command): slightly enlarging either of them or both may
525 % be sufficient to make a paragraph’s last line acceptable when it
526 % was originally too short or add a line to a paragraph when its last
527 % line was nearly full, thus possibly removing an orphan.
528 % Conversely, slightly reducing them may remove a paragraph’s last line
529 % (when it was short) and get rid of a widow on top of next page.
530 %
531 % I suggest to add a call |\usepackage[All]{lua-typo}| to the
532 % preamble of a document which is ``nearly finished’’
533 % \emph{and to remove it} once all possible corrections have been
534 % made: if some flaws remain, getting them printed in colour in
535 % the final document would be a shame!
536 %
537 % Starting with version 0.50 a recent LaTeX kernel (dated 2021/06/01)
538 % is required. Users running an older kernel will get a warning
539 % and an error message ``\texttt{Unable to register callback}’’;
540 % for them, a ``rollback’’ version of \pkg{lua-typo} is provided,
541 % it can be loaded this way: |\usepackage[All]{lua-typo}[=v0.4]|.
542 %
543 % \enlargethispage*{\baselineskip}
544 % The current version (\fileversion) requires a LaTeX kernel dated
545 % 2022/06/01 or later. Another ``rollback’’ version |[=v0.65]| has
546 % been added for those who run an older kernel.
547 %
548 % See files \file{demo.tex} and \file{demo.pdf} for a short example
549 % (in French).
550 %
551 % I am very grateful to Jacques André and Thomas Savary, who kindly
552 % tested my beta versions, providing much valuable feedback and
553 % suggesting many improvements for the first released version.
554 % Special thanks to both of them and to Michel Bovani whose
555 % contributions led to version~0.61!
556 %
557 % \section{Usage}
558 %
559 % The easiest way to trigger all checks perfomed by \pkg{lua-typo}
560 % is:\\
561 % |\usepackage[All]{lua-typo}|
562 %
563 % It is possible to enable or disable some checks through boolean
564 % options passed to \pkg{lua-typo};
565 % you may want to perform all checks except a few, then
566 % \pkg{lua-typo} should be loaded this way:\\
567 % |\usepackage[All, |\meta{OptX}|=false, |\meta{OptY}|=false]{lua-typo}|\\
568 % or to enable just a few checks, then do it this way:\\
569 % |\usepackage[|\meta{OptX}|, |\meta{OptY}|, |\meta{OptZ}|]{lua-typo}|
570 %
571 % Here is the full list of possible checks (name and purpose):\\[12pt]
572 % \begin{tabular}{>{\ttfamily}ll}
573 % \multicolumn{1}{l}{Name} & Glitch to highlight\\ \hline
574 % All & Turns all options to \opt{true}\\
575 % BackParindent & paragraph’s last line \emph{nearly} full?\\
576 % ShortLines & paragraph’s last line too short?\\
577 % ShortPages & nearly empty page (just a few lines)?\\
578 % OverfullLines & overfull lines?\\
579 % UnderfullLines & underfull lines?\\
580 % Widows & widows (top of page)?\\
581 % Orphans & orphans (bottom of page)?\\
582 % EOPHyphens & hyphenated word split across two pages?\\
583 % RepeatedHyphens & too many consecutive hyphens?\\
584 % ParLastHyphen & paragraph’s last full line hyphenated?\\
585 % EOLShortWords & short words (1 or 2 chars) at end of line?\\
586 % FirstWordMatch & same (part of) word starting two consecutive lines?\\
587 % LastWordMatch & same (part of) word ending two consecutive lines?\\
588 % FootnoteSplit & footnotes spread over two pages or more?\\
589 % ShortFinalWord & Short word ending a sentence on the next page\\
590 % MarginparPos & Margin note ending too low on the page\\
591 % \hline
592 % \end{tabular}\\[12pt]
593 % For example, if you want \pkg{lua-typo} to only warn about overfull
594 % and underfull lines, you can load \pkg{lua-typo} like this:\\
595 % |\usepackage[OverfullLines, UnderfullLines]{lua-typo}|\\
596 % If you want everything to be checked except paragraphs ending on
597 % a short line try:\\
598 % |\usepackage[All, ShortLines=false]{lua-typo}|\\
599 % please note that \opt{All} has to be the first one, as options are
600 % taken into account as they are read \emph{i.e.} from left to right.
601 %
602 % \newpage
603 % The list of all available options is printed to the \file{.log}
604 % file when option \opt{ShowOptions} is passed to \pkg{lua-typo},
605 % this option provides an easy way to get their names without having
606 % to look into the documentation.
607 %
608 % With option \opt{None}, \pkg{lua-typo} \emph{does absolutely
609 % nothing}, all checks are disabled as the main function is not added
610 % to any LuaTeX callback. It not quite equivalent to commenting out
611 % the |\usepackage{lua-typo}| line though, as user defined commands
612 % related to \pkg{lua-typo} are still defined and will not print
613 % any error message.
614 %
615 % Please be aware of the following features:
616 % \begin{description}
617 % \item[\opt{FirstWordMatch:}] the first word of consecutive list items
618 % is not highlighted, as these repetitions result of the author’s
619 % choice.
620 % \item[\opt{ShortPages:}] if a page is considered too short, its last
621 % line only is highlighted, not the whole page.
622 % \item[\opt{RepeatedHyphens:}] ditto, when the number of consecutives
623 % hyphenated lines is too high, only the hyphenated words in
624 % excess (the last ones) are hightlighted.
625 % \item[\opt{ShortFinalWord :}] the first word on a page is highlighted
626 % if it ends a sentence and is short (up to |\luatypoMinLen=4|
627 % letters).
628 %
629 % \end{description}
630 %
631 % \section{Known issues}
632 %
633 % \pkg{lua-typo} is currently incompatible with the \pkg{reledmac}
634 % package. When the latter is loaded, no check is performed by
635 % \pkg{lua-typo}, a warning is issued in the \file{.log} file.
636 %
637 % \section{Customisation}
638 %
639 % Some of the checks mentionned above require tuning, for
640 % instance, when is a last paragraph’s length called too short?
641 % how many hyphens ending consecutive lines are acceptable?
642 % \pkg{lua-typo} provides user customisable parameters to set
643 % what is regarded as acceptable or not.
644 %
645 % A default configuration file \file{lua-typo.cfg} is provided
646 % with all parameters set to their defaults; it is located under
647 % the \texdir{texmfdist} directory. It is up to the users to copy
648 % this file into their working directory (or \texdir{texmfhome} or
649 % \texdir{texmflocal}) and tune the defaults according to their own
650 % taste.
651 %
652 % It is also possible to provide defaults directly in the
653 % document’s preamble (this overwrites the corresponding settings
654 % done in the configuration file found on TeX’s search path: current
655 % directory, then \texdir{texmfhome}, \texdir{texmflocal} and
656 % finally \texdir{texmfdist}.
657 %
658 % Here are the parameters names (all prefixed by |luatypo| in order
659 % to avoid conflicts with other packages) and their default values:
660 % \begin{description}
661 % \item[\opt{BackParindent:}] paragraphs’ last line should either
662 % end at at sufficient distance of the right margin
663 % (|\luatypoBackPI|, default |1em|) or (approximately) touch the
664 % right margin ---the tolerance is
665 % |\luatypoBackFuzz| (default |2pt|)%
666 % \footnote{Some authors do not accept full lines at end of
667 % paragraphs, they can just set \cs{luatypoBackFuzz=0pt}
668 % to make them pointed out as faulty.}.
669 %
670 % \item[\opt{ShortLines:}] |\luatypoLLminWD=2\parindent|%
671 % \footnote{Or \texttt{20pt} if \cs{parindent=0pt}.}
672 % sets the minimum acceptable length for paragraphs’ last lines.
673 %
674 % \item[\opt{ShortPages:}] |\luatypoPageMin=5| sets the minimum
675 % acceptable number of lines on a page (chapters’ last page
676 % for instance). Actually, the last line’s vertical position on
677 % the page is taken into account so that f.i.\ title pages or
678 % pages ending on a picture are not pointed out.
679 %
680 % \item[\opt{RepeatedHyphens:}] |\luatypoHyphMax=2| sets the maximum
681 % acceptable number of consecutive hyphenated lines.
682 %
683 % \item[\opt{UnderfullLines:}] |\luatypoStretchMax=200| sets the maximum
684 % acceptable percentage of stretch acceptable before a line is
685 % tagged by \pkg{lua-typo} as underfull; it must be an integer
686 % over 100, 100 means that the slightest stretch exceeding the
687 % font tolerance (|\fontdimen3|) will be warned about (be
688 % prepared for a lot of ``underfull lines’’ with this setting),
689 % the default value 200 is just below what triggers TeX’s
690 % ``Underfull hbox’’ message (when |\tolerance=200| and
691 % |\hbadness=1000|).
692 %
693 % \item[\opt{First/LastWordMatch:}] |\luatypoMinFull=3|,
694 % |\luatypoMinPart=4| set the minimum number of characters
695 % required for a match to be pointed out. With this setting (3
696 % and 4), two occurrences of the word `out’ at the beginning or
697 % end of two consecutive lines will be highlighted (three chars,
698 % `in’ wouldn’t match), whereas a line ending with ``full’’ or
699 % ``overfull’’ followed by one ending with ``underfull’’ will
700 % match (four chars): the second occurence of ``full’’ or
701 % ``erfull’’ will be highlighted.
702 %
703 % \item[\opt{EOLShortWords:}] this check deals with lines ending with
704 % very short words (one or two characters), not all of them but
705 % a user selected list depending on the current language.\\
706 % |\luatypoOneChar{|\meta{language}|}{'|\meta{list of words}|'}|\\
707 % |\luatypoTwoChars{|\meta{language}|}{'|\meta{list of words}|'}|
708 %
709 % Currently, defaults (commented out) are suggested for the French
710 % language only:\\
711 % |\luatypoOneChar{french}{'À Ô Y'}|\\
712 % |\luatypoTwoChars{french}{'Je Tu Il On Au De'}|
713 %
714 % Feel free to customise these lists for French or to add your
715 % own shorts words for other languages but remember that
716 % a) the first argument (language name) \emph{must be known by}
717 % \pkg{babel}, so if you add |\luatypoOneChar| or
718 % |\luatypoTwoChars| commands, please make sure that
719 % \pkg{lua-typo} is loaded \emph{after} \pkg{babel};
720 % b) the second argument \emph{must be a string}
721 % (\emph{i.e.} surrounded by single or double \textsc{ascii}
722 % quotes) made of your words separated by spaces.
723 %
724 % \item[\opt{MarginparPos:}] |\luatypoMarginparTol}| is
725 % a \emph{dimension} which defaults to |\baselineskip|;
726 % marginal notes trigger a flaw if they end lower than
727 % |\luatypoMarginparTol| under the page’s last line.
728 %
729 % \end{description}
730 %
731 % It is possible to define a specific colour for each
732 % typographic flaws that \pkg{lua-typo} deals with.
733 % Currently, only six colours are used in \file{lua-typo.cfg}:
734 % \begin{verbatim}
735 % \definecolor{LTgrey}{gray}{0.6}
736 % \definecolor{LTred}{rgb}{1,0.55,0}
737 % \definecolor{LTline}{rgb}{0.7,0,0.3}
738 % \luatypoSetColor1{red} % Paragraph last full line hyphenated
739 % \luatypoSetColor2{red} % Page last word hyphenated
740 % \luatypoSetColor3{red} % Hyphens on consecutive lines
741 % \luatypoSetColor4{red} % Short word at end of line
742 % \luatypoSetColor5{cyan} % Widow
743 % \luatypoSetColor6{cyan} % Orphan
744 % \luatypoSetColor7{cyan} % Paragraph ending on a short line
745 % \luatypoSetColor8{blue} % Overfull lines
746 % \luatypoSetColor9{blue} % Underfull lines
747 % \luatypoSetColor{10}{red} % Nearly empty page (a few lines)
748 % \luatypoSetColor{11}{LTred} % First word matches
749 % \luatypoSetColor{12}{LTred} % Last word matches
750 % \luatypoSetColor{13}{LTgrey}% Paragraph’s last line nearly full
751 % \luatypoSetColor{14}{cyan} % Footnotes spread over two pages
752 % \luatypoSetColor{15}{red} % Short final word on top of the page
753 % \luatypoSetColor{16}{LTline}% Line color for multiple flaws
754 % \luatypoSetColor{17}{red} % Margin note ending too low\end{verbatim}
755 % \pkg{lua-typo} loads the \pkg{luacolor} package which loads the
756 % \pkg{color} package from the LaTeX graphic bundle.
757 % |\luatypoSetColor| requires named colours, so you can either use
758 % the |\definecolor| from \pkg{color} package to define yours
759 % (as done in the config file for `LTgrey’ and `LTred’) or load the
760 % \pkg{xcolor} package which provides a bunch of named colours.
761 %
762 % \section{\TeX{}nical details}
763 %
764 % \iffalse
765 %<*sty|scan>
766 %% IMPORTANT NOTICE:
767 %% For the copyright see the source file `lua-typo.dtx’.
768 %%
769 \NeedsTeXFormat{LaTeX2e}[2021/06/01]
770 %</sty|scan>
771 %<+sty>\ProvidesPackage{lua-typo}
772 %<+scan>\ProvidesPackage{scan-page}
773 %<+dtx>\ProvidesFile{lua-typo.dtx}
774 %<*dtx|sty|scan>
775 [2026-01-07 v.0.88 Daniel Flipo]
776 %</dtx|sty|scan>
777 %<*sty>
778 % \fi
779 %
780 % \changes{v0.50}{2021/05/05}{Rollback mechanism used for recovering
781 % older versions.}
782 %
783 % Starting with version~0.50, this package uses the rollback
784 % mechanism to provide easier backward compatibility.
785 % Rollback version~0.40 is provided for users who would have
786 % a LaTeX kernel older than 2021/06/01.
787 % Rollback version~0.65 is provided for users who would have
788 % a LaTeX kernel older than 2022/06/01.
789 %
790 % \begin{macrocode}
791 \DeclareRelease{v0.4}{2021-01-01}{lua-typo-2021-04-18.sty}
792 \DeclareRelease{v0.65}{2023-03-08}{lua-typo-2023-03-08.sty}
793 \DeclareCurrentRelease{}{2023-09-13}
794 % \end{macrocode}
795 %
796 % This package only runs with LuaLaTeX and requires packages
797 % \pkg{luatexbase}, \pkg{luacode}, \pkg{luacolor} and
798 % \pkg{atveryend}.
799 %
800 % \begin{macrocode}
801 \ifdefined\directlua
802 \RequirePackage{luatexbase,luacode,luacolor,atveryend}
803 \else
804 \PackageError{This package is meant for LuaTeX only! Aborting}
805 {No more information available, sorry!}
806 \fi
807 % \end{macrocode}
808 %
809 % Let’s define the necessary internal counters, dimens, token
810 % registers and commands…
811 %
812 % \begin{macrocode}
813 \newdimen\luatypoLLminWD
814 \newdimen\luatypoBackPI
815 \newdimen\luatypoBackFuzz
816 \newdimen\luatypoMarginparTol
817 \newcount\luatypoStretchMax
818 \newcount\luatypoHyphMax
819 \newcount\luatypoPageMin
820 \newcount\luatypoMinFull
821 \newcount\luatypoMinPart
822 \newcount\luatypoMinLen
823 \newcount\luatypo@LANGno
824 \newcount\luatypo@options
825 \newtoks\luatypo@single
826 \newtoks\luatypo@double
827 % \end{macrocode}
828 % … and define a global table for this package.
829 % \begin{macrocode}
830 \begin{luacode}
831 luatypo = { }
832 \end{luacode}
833 % \end{macrocode}
834 %
835 % Set up \pkg{ltkeys} initializations.
836 % Option \opt{All} resets all booleans relative to specific
837 % typographic checks to \opt{true}.
838 %
839 % \changes{v0.70}{2023/04/08}{Package options no longer require
840 % `kvoptions’, they rely on LaTeX `ltkeys’ package.}
841 %
842 % \begin{macrocode}
843 \DeclareKeys[luatypo]
844 {
845 ShowOptions.if = LT@ShowOptions ,
846 None.if = LT@None ,
847 BackParindent.if = LT@BackParindent ,
848 ShortLines.if = LT@ShortLines ,
849 ShortPages.if = LT@ShortPages ,
850 OverfullLines.if = LT@OverfullLines ,
851 UnderfullLines.if = LT@UnderfullLines ,
852 Widows.if = LT@Widows ,
853 Orphans.if = LT@Orphans ,
854 EOPHyphens.if = LT@EOPHyphens ,
855 RepeatedHyphens.if = LT@RepeatedHyphens ,
856 ParLastHyphen.if = LT@ParLastHyphen ,
857 EOLShortWords.if = LT@EOLShortWords ,
858 FirstWordMatch.if = LT@FirstWordMatch ,
859 LastWordMatch.if = LT@LastWordMatch ,
860 FootnoteSplit.if = LT@FootnoteSplit ,
861 ShortFinalWord.if = LT@ShortFinalWord ,
862 MarginparPos.if = LT@MarginparPos ,
863 PageFirstLine.if = LT@PageFirstLine ,
864 All.if = LT@All ,
865 All.code = \LT@ShortLinestrue \LT@ShortPagestrue
866 \LT@OverfullLinestrue \LT@UnderfullLinestrue
867 \LT@Widowstrue \LT@Orphanstrue
868 \LT@EOPHyphenstrue \LT@RepeatedHyphenstrue
869 \LT@ParLastHyphentrue \LT@EOLShortWordstrue
870 \LT@FirstWordMatchtrue \LT@LastWordMatchtrue
871 \LT@BackParindenttrue \LT@FootnoteSplittrue
872 \LT@ShortFinalWordtrue \LT@MarginparPostrue
873 }
874 \ProcessKeyOptions[luatypo]
875 % \end{macrocode}
876 %
877 % Forward these options to the |luatypo| global table.
878 % Wait until the config file \file{lua-typo.cfg} has been read
879 % in order to give it a chance of overruling the boolean options.
880 % This enables the user to permanently change the defaults.
881 %
882 % \begin{macrocode}
883 \AtEndOfPackage{%
884 \ifLT@None
885 \directlua{ luatypo.None = true }%
886 \else
887 \directlua{ luatypo.None = false }%
888 \fi
889 \ifLT@BackParindent
890 \advance\luatypo@options by 1
891 \directlua{ luatypo.BackParindent = true }%
892 \else
893 \directlua{ luatypo.BackParindent = false }%
894 \fi
895 \ifLT@ShortLines
896 \advance\luatypo@options by 1
897 \directlua{ luatypo.ShortLines = true }%
898 \else
899 \directlua{ luatypo.ShortLines = false }%
900 \fi
901 \ifLT@ShortPages
902 \advance\luatypo@options by 1
903 \directlua{ luatypo.ShortPages = true }%
904 \else
905 \directlua{ luatypo.ShortPages = false }%
906 \fi
907 \ifLT@OverfullLines
908 \advance\luatypo@options by 1
909 \directlua{ luatypo.OverfullLines = true }%
910 \else
911 \directlua{ luatypo.OverfullLines = false }%
912 \fi
913 \ifLT@UnderfullLines
914 \advance\luatypo@options by 1
915 \directlua{ luatypo.UnderfullLines = true }%
916 \else
917 \directlua{ luatypo.UnderfullLines = false }%
918 \fi
919 \ifLT@Widows
920 \advance\luatypo@options by 1
921 \directlua{ luatypo.Widows = true }%
922 \else
923 \directlua{ luatypo.Widows = false }%
924 \fi
925 \ifLT@Orphans
926 \advance\luatypo@options by 1
927 \directlua{ luatypo.Orphans = true }%
928 \else
929 \directlua{ luatypo.Orphans = false }%
930 \fi
931 \ifLT@EOPHyphens
932 \advance\luatypo@options by 1
933 \directlua{ luatypo.EOPHyphens = true }%
934 \else
935 \directlua{ luatypo.EOPHyphens = false }%
936 \fi
937 \ifLT@RepeatedHyphens
938 \advance\luatypo@options by 1
939 \directlua{ luatypo.RepeatedHyphens = true }%
940 \else
941 \directlua{ luatypo.RepeatedHyphens = false }%
942 \fi
943 \ifLT@ParLastHyphen
944 \advance\luatypo@options by 1
945 \directlua{ luatypo.ParLastHyphen = true }%
946 \else
947 \directlua{ luatypo.ParLastHyphen = false }%
948 \fi
949 \ifLT@EOLShortWords
950 \advance\luatypo@options by 1
951 \directlua{ luatypo.EOLShortWords = true }%
952 \else
953 \directlua{ luatypo.EOLShortWords = false }%
954 \fi
955 \ifLT@FirstWordMatch
956 \advance\luatypo@options by 1
957 \directlua{ luatypo.FirstWordMatch = true }%
958 \else
959 \directlua{ luatypo.FirstWordMatch = false }%
960 \fi
961 \ifLT@LastWordMatch
962 \advance\luatypo@options by 1
963 \directlua{ luatypo.LastWordMatch = true }%
964 \else
965 \directlua{ luatypo.LastWordMatch = false }%
966 \fi
967 \ifLT@FootnoteSplit
968 \advance\luatypo@options by 1
969 \directlua{ luatypo.FootnoteSplit = true }%
970 \else
971 \directlua{ luatypo.FootnoteSplit = false }%
972 \fi
973 \ifLT@ShortFinalWord
974 \advance\luatypo@options by 1
975 \directlua{ luatypo.ShortFinalWord = true }%
976 \else
977 \directlua{ luatypo.ShortFinalWord = false }%
978 \fi
979 \ifLT@MarginparPos
980 \advance\luatypo@options by 1
981 \directlua{ luatypo.MarginparPos = true }%
982 \else
983 \directlua{ luatypo.MarginparPos = false }%
984 \fi
985 \ifLT@PageFirstLine
986 \advance\luatypo@options by 1
987 \directlua{ luatypo.PageFirstLine = true }%
988 \else
989 \directlua{ luatypo.PageFirstLine = false }%
990 \fi
991 }
992 % \end{macrocode}
993 %
994 % |ShowOptions| is specific:
995 %
996 % \begin{macrocode}
997 \ifLT@ShowOptions
998 \GenericWarning{* }{%
999 *** List of possible options for lua-typo ***\MessageBreak
1000 [Default values between brackets]%
1001 \MessageBreak
1002 ShowOptions [false]\MessageBreak
1003 None [false]\MessageBreak
1004 All [false]\MessageBreak
1005 BackParindent [false]\MessageBreak
1006 ShortLines [false]\MessageBreak
1007 ShortPages [false]\MessageBreak
1008 OverfullLines [false]\MessageBreak
1009 UnderfullLines [false]\MessageBreak
1010 Widows [false]\MessageBreak
1011 Orphans [false]\MessageBreak
1012 EOPHyphens [false]\MessageBreak
1013 RepeatedHyphens [false]\MessageBreak
1014 ParLastHyphen [false]\MessageBreak
1015 EOLShortWords [false]\MessageBreak
1016 FirstWordMatch [false]\MessageBreak
1017 LastWordMatch [false]\MessageBreak
1018 FootnoteSplit [false]\MessageBreak
1019 ShortFinalWord [false]\MessageBreak
1020 MarginparPos [false]\MessageBreak
1021 \MessageBreak
1022 *********************************************%
1023 \MessageBreak Lua-typo [ShowOptions]
1024 }%
1025 \fi
1026 % \end{macrocode}
1027 %
1028 % Some defaut values which can be customised in the preamble
1029 % are forwarded to Lua AtBeginDocument.
1030 %
1031 % \changes{v0.87}{2024/04/18}{Add warning: lua-typo incompatible
1032 % with the `reledmac’ package.}
1033 %
1034 % \begin{macrocode}
1035 \AtBeginDocument{%
1036 \@ifpackageloaded{reledmac}%
1037 {\PackageWarning{lua-typo}{%
1038 'lua-typo' is incompatible with\MessageBreak
1039 the 'reledmac' package.\MessageBreak
1040 'lua-typo' checking disabled.\MessageBreak
1041 Reported}%
1042 \LT@Nonetrue
1043 \directlua{ luatypo.None = true }%
1044 }{}%
1045 \directlua{
1046 luatypo.HYPHmax = tex.count.luatypoHyphMax
1047 luatypo.PAGEmin = tex.count.luatypoPageMin
1048 luatypo.Stretch = tex.count.luatypoStretchMax
1049 luatypo.MinFull = tex.count.luatypoMinFull
1050 luatypo.MinPart = tex.count.luatypoMinPart
1051 % \end{macrocode}
1052 % Ensure |MinFull|$\leq$|MinPart|.
1053 % \begin{macrocode}
1054 luatypo.MinFull = math.min(luatypo.MinPart,luatypo.MinFull)
1055 luatypo.MinLen = tex.count.luatypoMinLen
1056 luatypo.LLminWD = tex.dimen.luatypoLLminWD
1057 luatypo.BackPI = tex.dimen.luatypoBackPI
1058 luatypo.BackFuzz = tex.dimen.luatypoBackFuzz
1059 luatypo.MParTol = tex.dimen.luatypoMarginparTol
1060 % \end{macrocode}
1061 % \changes{v0.80}{2023/04/28}{New table `luatypo.map’ for colours.}
1062 %
1063 % Build a compact table holding all colours defined by
1064 % \file{lua-typo} (no duplicates).
1065 % \begin{macrocode}
1066 local tbl = luatypo.colortbl
1067 local map = { }
1068 for i,v in ipairs (luatypo.colortbl) do
1069 if i == 1 or v > tbl[i-1] then
1070 table.insert(map, v)
1071 end
1072 end
1073 luatypo.map = map
1074 }%
1075 }
1076 % \end{macrocode}
1077 %
1078 % Print the summary of offending pages ---if any--- at the
1079 % (very) end of document and write the report file on disc,
1080 % unless option |None| has been selected.
1081 %
1082 % On every page, at least one line of text should be found.
1083 % Otherwise, \pkg{lua-typo} presumes something went wrong and
1084 % writes the page number to a |failedlist| list.
1085 % In case |pagelist| is empty \emph{and} |failedlist| \emph{is not},
1086 % a warning is issued instead of the \texttt{No Typo Flaws found.}
1087 % message (new to version~0.85).
1088 %
1089 % \changes{v0.85}{2023/09/07}{Warn in case some pages failed to
1090 % be checked properly.}
1091 %
1092 % \begin{macrocode}
1093 \AtVeryEndDocument{%
1094 \ifnum\luatypo@options = 0 \LT@Nonetrue \fi
1095 \ifLT@None
1096 \directlua{
1097 texio.write_nl(' ')
1098 texio.write_nl('************************************')
1099 texio.write_nl('*** lua-typo running with NO option:')
1100 texio.write_nl('*** NO CHECK PERFORMED! ***')
1101 texio.write_nl('************************************')
1102 texio.write_nl(' ')
1103 }%
1104 \else
1105 \directlua{
1106 texio.write_nl(' ')
1107 texio.write_nl('*************************************')
1108 if luatypo.pagelist == " " then
1109 if luatypo.failedlist == " " then
1110 texio.write_nl('*** lua-typo: No Typo Flaws found.')
1111 else
1112 texio.write_nl('*** WARNING: ')
1113 texio.write('lua-typo failed to scan these pages:')
1114 texio.write_nl('***' .. luatypo.failedlist)
1115 texio.write_nl('*** Please report to the maintainer.')
1116 end
1117 else
1118 texio.write_nl('*** lua-typo: WARNING *************')
1119 texio.write_nl('The following pages need attention:')
1120 texio.write(luatypo.pagelist)
1121 end
1122 texio.write_nl('*************************************')
1123 texio.write_nl(' ')
1124 if luatypo.failedlist == " " then
1125 else
1126 local prt = "WARNING: lua-typo failed to scan pages " ..
1127 luatypo.failedlist .. "\string\n\string\n"
1128 luatypo.buffer = prt .. luatypo.buffer
1129 end
1130 local fileout= tex.jobname .. ".typo"
1131 local out=io.open(fileout,"w+")
1132 out:write(luatypo.buffer)
1133 io.close(out)
1134 }%
1135 \fi}
1136 % \end{macrocode}
1137 %
1138 % \begin{macro}{\luatypoOneChar}
1139 % \begin{macro}{\luatypoTwoChars}
1140 % These commands set which short words should be avoided at end of
1141 % lines. The first argument is a language name, say \opt{french},
1142 % which is turned into a command |\l@french| expanding to a number
1143 % known by luatex, otherwise an error message occurs.
1144 % The utf-8 string entered as second argument has to be
1145 % converted into the font internal coding.
1146 % \begin{macrocode}
1147 \newcommand*{\luatypoOneChar}[2]{%
1148 \def\luatypo@LANG{#1}\luatypo@single={#2}%
1149 \ifcsname l@\luatypo@LANG\endcsname
1150 \luatypo@LANGno=\the\csname l@\luatypo@LANG\endcsname \relax
1151 \directlua{
1152 local langno = \the\luatypo@LANGno
1153 local string = \the\luatypo@single
1154 luatypo.single[langno] = " "
1155 for p, c in utf8.codes(string) do
1156 local s = utf8.char(c)
1157 luatypo.single[langno] = luatypo.single[langno] .. s
1158 end
1159 %<dbg> texio.write_nl('SINGLE=' .. luatypo.single[langno])
1160 %<dbg> texio.write_nl(' ')
1161 }%
1162 \else
1163 \PackageWarning{luatypo}{Unknown language "\luatypo@LANG",
1164 \MessageBreak \protect\luatypoOneChar\space command ignored}%
1165 \fi}
1166 \newcommand*{\luatypoTwoChars}[2]{%
1167 \def\luatypo@LANG{#1}\luatypo@double={#2}%
1168 \ifcsname l@\luatypo@LANG\endcsname
1169 \luatypo@LANGno=\the\csname l@\luatypo@LANG\endcsname \relax
1170 \directlua{
1171 local langno = \the\luatypo@LANGno
1172 local string = \the\luatypo@double
1173 luatypo.double[langno] = " "
1174 for p, c in utf8.codes(string) do
1175 local s = utf8.char(c)
1176 luatypo.double[langno] = luatypo.double[langno] .. s
1177 end
1178 %<dbg> texio.write_nl('DOUBLE=' .. luatypo.double[langno])
1179 %<dbg> texio.write_nl(' ')
1180 }%
1181 \else
1182 \PackageWarning{luatypo}{Unknown language "\luatypo@LANG",
1183 \MessageBreak \protect\luatypoTwoChars\space command ignored}%
1184 \fi}
1185 % \end{macrocode}
1186 % \end{macro}
1187 % \end{macro}
1188 %
1189 % \vspace*{\baselineskip}
1190 % \begin{macro}{\luatypoSetColor}
1191 % This is a user-level command to customise the colours highlighting
1192 % the sixteen types of possible typographic flaws.
1193 % The first argument is a number (flaw type: 1-16), the second the
1194 % named colour associated to it.
1195 % The colour support is based on the \pkg{luacolor} package (colour
1196 % attributes).
1197 % \begin{macrocode}
1198 \newcommand*{\luatypoSetColor}[2]{%
1199 \begingroup
1200 \color{#2}%
1201 \directlua{luatypo.colortbl[#1]=\the\LuaCol@Attribute}%
1202 \endgroup
1203 }
1204 %\luatypoSetColor{0}{black}
1205 % \end{macrocode}
1206 % \end{macro}
1207 %
1208 % The Lua code now, initialisations.
1209 %
1210 % \begin{macrocode}
1211 \begin{luacode}
1212 luatypo.colortbl = { }
1213 luatypo.map = { }
1214 luatypo.single = { }
1215 luatypo.double = { }
1216 luatypo.pagelist = " "
1217 luatypo.failedlist = " "
1218 luatypo.buffer = "List of typographic flaws found for "
1219 .. tex.jobname .. ".pdf:\string\n\string\n"
1220
1221 local char_to_discard = { }
1222 char_to_discard[string.byte(",")] = true
1223 char_to_discard[string.byte(".")] = true
1224 char_to_discard[string.byte("!")] = true
1225 char_to_discard[string.byte("?")] = true
1226 char_to_discard[string.byte(":")] = true
1227 char_to_discard[string.byte(";")] = true
1228 char_to_discard[string.byte("-")] = true
1229
1230 local eow_char = { }
1231 eow_char[string.byte(".")] = true
1232 eow_char[string.byte("!")] = true
1233 eow_char[string.byte("?")] = true
1234 eow_char[utf8.codepoint("…")] = true
1235
1236 local DISC = node.id("disc")
1237 local GLYPH = node.id("glyph")
1238 local GLUE = node.id("glue")
1239 local KERN = node.id("kern")
1240 local RULE = node.id("rule")
1241 local HLIST = node.id("hlist")
1242 local VLIST = node.id("vlist")
1243 local LPAR = node.id("local_par")
1244 local MKERN = node.id("margin_kern")
1245 local PENALTY = node.id("penalty")
1246 local WHATSIT = node.id("whatsit")
1247 % \end{macrocode}
1248 % Glue subtypes:
1249 % \begin{macrocode}
1250 local USRSKIP = 0
1251 local PARSKIP = 3
1252 local LFTSKIP = 8
1253 local RGTSKIP = 9
1254 local TOPSKIP = 10
1255 local PARFILL = 15
1256 % \end{macrocode}
1257 % Hlist subtypes:
1258 % \begin{macrocode}
1259 local LINE = 1
1260 local BOX = 2
1261 local INDENT = 3
1262 local ALIGN = 4
1263 local EQN = 6
1264 % \end{macrocode}
1265 % Penalty subtypes:
1266 % \begin{macrocode}
1267 local USER = 0
1268 local HYPH = 0x2D
1269 % \end{macrocode}
1270 % Glyph subtypes:
1271 % \begin{macrocode}
1272 local LIGA = 0x102
1273 % \end{macrocode}
1274 % Counter |parline| (current paragraph) \emph{must not be reset}
1275 % on every new page!
1276 % \begin{macrocode}
1277 local parline = 0
1278 % \end{macrocode}
1279 % Local definitions for the `node’ library:
1280 % \begin{macrocode}
1281 local dimensions = node.dimensions
1282 local rangedimensions = node.rangedimensions
1283 local effective_glue = node.effective_glue
1284 local set_attribute = node.set_attribute
1285 local get_attribute = node.get_attribute
1286 local slide = node.slide
1287 local traverse = node.traverse
1288 local traverse_id = node.traverse_id
1289 local has_field = node.has_field
1290 local uses_font = node.uses_font
1291 local is_glyph = node.is_glyph
1292 local utf8_len = utf8.len
1293 % \end{macrocode}
1294 % Local definitions from the `unicode.utf8’ library: replacements are
1295 % needed for functions |string.gsub()|, |string.sub()|, |string.find()|
1296 % and |string.reverse()| which are meant for one-byte characters only.
1297 %
1298 % \changes{v0.65}{2023/03/02}{Three new functions for utf-8 strings’
1299 % manipulations.}
1300 %
1301 % |utf8_find| requires an utf-8 string and a `pattern’ (also utf-8),
1302 % it returns |nil| if pattern is not found, or the \emph{byte}
1303 % position of the first match otherwise [not an issue as we only
1304 % care for true/false].
1305 % \begin{macrocode}
1306 local utf8_find = unicode.utf8.find
1307 % \end{macrocode}
1308 % |utf8_gsub| mimics |string.gsub| for utf-8 strings.
1309 % \begin{macrocode}
1310 local utf8_gsub = unicode.utf8.gsub
1311 % \end{macrocode}
1312 % |utf8_reverse| returns the reversed string (utf-8 chars read from
1313 % end to beginning) [same as |string.reverse| but for utf-8 strings].
1314 % \begin{macrocode}
1315 local utf8_reverse = function (s)
1316 if utf8_len(s) > 1 then
1317 local so = ""
1318 for p, c in utf8.codes(s) do
1319 so = utf8.char(c) .. so
1320 end
1321 s = so
1322 end
1323 return s
1324 end
1325 % \end{macrocode}
1326 % |utf8_sub| returns the substring of s that starts at i and
1327 % continues until j (j-i-1 utf8 chars.). \emph{Warning: it requires
1328 % $i\ge1$ and $j\ge i$}.
1329 % \begin{macrocode}
1330 local utf8_sub = function (s,i,j)
1331 i=utf8.offset(s,i)
1332 j=utf8.offset(s,j+1)-1
1333 return string.sub(s,i,j)
1334 end
1335 % \end{macrocode}
1336 %
1337 %\changes{v0.32}{2021/03/14}{Better protection against unexpected
1338 % nil nodes.}
1339 %
1340 % The next function colours glyphs and discretionaries.
1341 % It requires two arguments: a node and a (named) colour.
1342 %
1343 % \begin{macrocode}
1344 local color_node = function (node, color)
1345 local attr = oberdiek.luacolor.getattribute()
1346 if node and node.id == DISC then
1347 local pre = node.pre
1348 local post = node.post
1349 local repl = node.replace
1350 if pre then
1351 set_attribute(pre,attr,color)
1352 end
1353 if post then
1354 set_attribute(post,attr,color)
1355 end
1356 if repl then
1357 set_attribute(repl,attr,color)
1358 end
1359 elseif node then
1360 set_attribute(node,attr,color)
1361 end
1362 end
1363 % \end{macrocode}
1364 %
1365 % The next function colours a whole line without overriding
1366 % previously set colours by f.i.\ homeoarchy, repeated hyphens etc.
1367 % It requires two arguments: a line’s node and a (named) colour.
1368 %
1369 % Digging into nested hlists and vlists is needed f.i.\ to colour
1370 % aligned equations.
1371 %
1372 % \changes{v0.50}{2021/05/05}{Go down deeper into hlists and vlists to
1373 % colour nodes.}
1374 %
1375 % \changes{v0.80}{2023/04/18}{`color\_line’ no longer overwrites colors
1376 % set previously.}
1377 %
1378 % \begin{macrocode}
1379 local color_line = function (head, color)
1380 local first = head.head
1381 local map = luatypo.map
1382 local color_node_if = function (node, color)
1383 local c = oberdiek.luacolor.getattribute()
1384 local att = get_attribute(node,c)
1385 local uncolored = true
1386 for i,v in ipairs (map) do
1387 if att == v then
1388 uncolored = false
1389 break
1390 end
1391 end
1392 if uncolored then
1393 color_node (node, color)
1394 end
1395 end
1396 for n in traverse(first) do
1397 if n.id == HLIST or n.id == VLIST then
1398 local ff = n.head
1399 for nn in traverse(ff) do
1400 if nn.id == HLIST or nn.id == VLIST then
1401 local f3 = nn.head
1402 for n3 in traverse(f3) do
1403 if n3.id == HLIST or n3.id == VLIST then
1404 local f4 = n3.head
1405 for n4 in traverse(f4) do
1406 if n4.id == HLIST or n4.id == VLIST then
1407 local f5 = n4.head
1408 for n5 in traverse(f5) do
1409 if n5.id == HLIST or n5.id == VLIST then
1410 local f6 = n5.head
1411 for n6 in traverse(f6) do
1412 color_node_if(n6, color)
1413 end
1414 else
1415 color_node_if(n5, color)
1416 end
1417 end
1418 else
1419 color_node_if(n4, color)
1420 end
1421 end
1422 else
1423 color_node_if(n3, color)
1424 end
1425 end
1426 else
1427 color_node_if(nn, color)
1428 end
1429 end
1430 else
1431 color_node_if(n, color)
1432 end
1433 end
1434 end
1435 % \end{macrocode}
1436 %
1437 % The next function takes four arguments: a string, two numbers
1438 % (which can be \node{nil}) and a flag. It appends a line to
1439 % a buffer which will be written to file `\cs{jobname.typo}’.
1440 %
1441 % \changes{v0.50}{2021/05/13}{Summary of flaws written to file
1442 % `\cs{jobname.typo}’.}
1443 %
1444 % \begin{macrocode}
1445 log_flaw= function (msg, line, colno, footnote)
1446 local pageno = tex.getcount("c@page")
1447 local prt ="p. " .. pageno
1448 if colno then
1449 prt = prt .. ", col." .. colno
1450 end
1451 if line then
1452 local l = string.format("%2d, ", line)
1453 if footnote then
1454 prt = prt .. ", (ftn.) line " .. l
1455 else
1456 prt = prt .. ", line " .. l
1457 end
1458 end
1459 prt = prt .. msg
1460 luatypo.buffer = luatypo.buffer .. prt .. "\string\n"
1461 end
1462 % \end{macrocode}
1463 %
1464 % The next three functions deal with ``homeoarchy’’, \emph{i.e.}
1465 % lines beginning or ending with the same (part of) word.
1466 % While comparing two words, the only significant nodes are glyphs
1467 % and ligatures, dicretionnaries other than ligatures, kerns
1468 % (letterspacing) should be discarded.
1469 % For each word to be compared we build a ``signature’’ made of
1470 % glyphs, split ligatures and underscores (representing glues).
1471 %
1472 % \changes{v0.65}{2023/03/02}{All ligatures are now split using the
1473 % node’s `components’ field rather than a table.}
1474 %
1475 % \changes{v0.86}{2024/01/10}{Typo corrected in the signature function.}
1476 %
1477 % The first function adds a (non-nil) node to a signature of type
1478 % string, nil nodes are ignored.
1479 % It returns the augmented string and its length
1480 % (underscores are omitted in the length computation).
1481 % The last argument is a boolean needed when building a signature
1482 % backwards (see |check_line_last_word|).
1483 % \begin{macrocode}
1484 local signature = function (node, string, swap)
1485 local n = node
1486 local str = string
1487 if n and n.id == GLYPH then
1488 local b = n.char
1489 % \end{macrocode}
1490 % Punctuation has to be discarded; other glyphs may be ligatures,
1491 % then they have a |components| field which holds the list of glyphs
1492 % which compose the ligature.
1493 % \begin{macrocode}
1494 if b and not char_to_discard[b] then
1495 if n.components then
1496 local c = ""
1497 for nn in traverse_id(GLYPH, n.components) do
1498 c = c .. utf8.char(nn.char)
1499 end
1500 if swap then
1501 str = str .. utf8_reverse(c)
1502 else
1503 str = str .. c
1504 end
1505 else
1506 str = str .. utf8.char(b)
1507 end
1508 end
1509 elseif n and n.id == DISC then
1510 % \end{macrocode}
1511 % Discretionaries are split into |pre| and |post| and both parts
1512 % are stored. They might be ligatures (\emph{ffl, ffi})…
1513 % \begin{macrocode}
1514 local pre = n.pre
1515 local post = n.post
1516 local c1 = ""
1517 local c2 = ""
1518 if pre and pre.char then
1519 if pre.components then
1520 for nn in traverse_id(GLYPH, pre.components) do
1521 c1 = c1 .. utf8.char(nn.char)
1522 end
1523 else
1524 c1 = utf8.char(pre.char)
1525 end
1526 c1 = utf8_gsub(c1, "-", "")
1527 end
1528 if post and post.char then
1529 if post.components then
1530 for nn in traverse_id(GLYPH, post.components) do
1531 c2 = c2 .. utf8.char(nn.char)
1532 end
1533 else
1534 c2 = utf8.char(post.char)
1535 end
1536 end
1537 if swap then
1538 str = str .. utf8_reverse(c2) .. c1
1539 else
1540 str = str .. c1 .. c2
1541 end
1542 elseif n and n.id == GLUE then
1543 str = str .. "_"
1544 end
1545 % \end{macrocode}
1546 % The returned length is the number of \emph{letters}.
1547 % \begin{macrocode}
1548 local s = utf8_gsub(str, "_", "")
1549 local len = utf8_len(s)
1550 return len, str
1551 end
1552 % \end{macrocode}
1553 %
1554 % The next function looks for consecutive lines ending with
1555 % the same letters.\par
1556 % It requires five arguments: a string (previous line’s signature),
1557 % a node (the last one on the current line), a line number, a column
1558 % number (possibly |nil|) and a boolean to cancel checking in some
1559 % cases (end of paragraphs).
1560 % It prints the matching part at end of linewith with the supplied
1561 % colour and returns the current line’s last word and a boolean (match).
1562 %
1563 % \changes{v0.32}{2021/03/14}{Functions `check\_line\_first\_word’ and
1564 % `check\_line\_last\_word’ rewritten.}
1565 %
1566 % \changes{v0.50}{2021/05/13}{Homeoarchy detection added for lines
1567 % starting or ending on \cs{mbox}.}
1568 %
1569 % \changes{v0.61}{2023/02/06}{`check\_line\_last\_word’ returns a flag
1570 % to set pageflag.}
1571 %
1572 % \changes{v0.70}{2023/04/08}{`check\_line\_first\_word’ and
1573 % `check\_line\_last\_word’: length of matches corrected.}
1574 %
1575 % \changes{v0.80}{2023/04/18}{`check\_line\_first\_word’ and
1576 % `check\_line\_last\_word’: argument footnote added.}
1577 %
1578 % \begin{macrocode}
1579 local check_line_last_word =
1580 function (old, node, line, colno, flag, footnote)
1581 local COLOR = luatypo.colortbl[12]
1582 local match = false
1583 local new = ""
1584 local maxlen = 0
1585 local MinFull = luatypo.MinFull
1586 local MinPart = luatypo.MinPart
1587 if node then
1588 local swap = true
1589 local box, go
1590 % \end{macrocode}
1591 % Step back to the last glyph or discretionary or hbox.
1592 % \begin{macrocode}
1593 local lastn = node
1594 while lastn and lastn.id ~= GLYPH and lastn.id ~= DISC and
1595 lastn.id ~= HLIST do
1596 lastn = lastn.prev
1597 end
1598 % \end{macrocode}
1599 % A signature is built from the last two (or more) words
1600 % on the current line.
1601 % \begin{macrocode}
1602 local n = lastn
1603 local words = 0
1604 while n and (words <= 2 or maxlen < MinPart) do
1605 % \end{macrocode}
1606 % Go down inside boxes, read their content from end to beginning,
1607 % then step out.
1608 % \begin{macrocode}
1609 if n and n.id == HLIST then
1610 box = n
1611 local first = n.head
1612 local lastn = slide(first)
1613 n = lastn
1614 while n do
1615 maxlen, new = signature (n, new, swap)
1616 n = n.prev
1617 end
1618 n = box.prev
1619 local w = utf8_gsub(new, "_", "")
1620 words = words + utf8_len(new) - utf8_len(w) + 1
1621 else
1622 repeat
1623 maxlen, new = signature (n, new, swap)
1624 n = n.prev
1625 until not n or n.id == GLUE or n.id == HLIST
1626 if n and n.id == GLUE then
1627 maxlen, new = signature (n, new, swap)
1628 words = words + 1
1629 n = n.prev
1630 end
1631 end
1632 end
1633 new = utf8_reverse(new)
1634 new = utf8_gsub(new, "_+$", "") -- $
1635 new = utf8_gsub(new, "^_+", "")
1636 maxlen = math.min(utf8_len(old), utf8_len(new))
1637 %<dbg> texio.write_nl('EOLsigold=' .. old)
1638 %<dbg> texio.write(' EOLsig=' .. new)
1639 % \end{macrocode}
1640 % When called with flag |false|, |check_line_last_word| doesn’t
1641 % compare it with the previous line’s, but just returns the
1642 % last word’s signature.
1643 % \begin{macrocode}
1644 if flag and old ~= "" then
1645 % \end{macrocode}
1646 % |oldlast| and |newlast| hold the last (full) words to be compared
1647 % later:
1648 % \begin{macrocode}
1649 local oldlast = utf8_gsub (old, ".*_", "")
1650 local newlast = utf8_gsub (new, ".*_", "")
1651 % \end{macrocode}
1652 % Let’s look for a partial match: build |oldsub| and |newsub|,
1653 % reading (backwards) the last |MinPart| \emph{non-space} characters
1654 % of both lines.
1655 % \begin{macrocode}
1656 local oldsub = ""
1657 local newsub = ""
1658 local dlo = utf8_reverse(old)
1659 local wen = utf8_reverse(new)
1660 for p, c in utf8.codes(dlo) do
1661 local s = utf8_gsub(oldsub, "_", "")
1662 if utf8_len(s) < MinPart then
1663 oldsub = utf8.char(c) .. oldsub
1664 end
1665 end
1666 for p, c in utf8.codes(wen) do
1667 local s = utf8_gsub(newsub, "_", "")
1668 if utf8_len(s) < MinPart then
1669 newsub = utf8.char(c) .. newsub
1670 end
1671 end
1672 if oldsub == newsub then
1673 %<dbg> texio.write_nl('EOLnewsub=' .. newsub)
1674 match = true
1675 end
1676 if oldlast == newlast and utf8_len(newlast) >= MinFull then
1677 %<dbg> texio.write_nl('EOLnewlast=' .. newlast)
1678 if utf8_len(newlast) > MinPart or not match then
1679 oldsub = oldlast
1680 newsub = newlast
1681 end
1682 match = true
1683 end
1684 if match then
1685 % \end{macrocode}
1686 % Minimal full or partial match |newsub| of length |k|;
1687 % any more glyphs matching?
1688 % \begin{macrocode}
1689 local k = utf8_len(newsub)
1690 local osub = utf8_reverse(oldsub)
1691 local nsub = utf8_reverse(newsub)
1692 while osub == nsub and k < maxlen do
1693 k = k + 1
1694 osub = utf8_sub(dlo,1,k)
1695 nsub = utf8_sub(wen,1,k)
1696 if osub == nsub then
1697 newsub = utf8_reverse(nsub)
1698 end
1699 end
1700 newsub = utf8_gsub(newsub, "^_+", "")
1701 %<dbg> texio.write_nl("EOLfullmatch=" .. newsub)
1702 local msg = "E.O.L. MATCH=" .. newsub
1703 log_flaw(msg, line, colno, footnote)
1704 % \end{macrocode}
1705 % Lest’s colour the matching string.
1706 % \begin{macrocode}
1707 local ns = utf8_gsub(newsub, "_", "")
1708 k = utf8_len(ns)
1709 oldsub = utf8_reverse(newsub)
1710 local newsub = ""
1711 local n = lastn
1712 local l = 0
1713 local lo = 0
1714 local li = 0
1715 while n and newsub ~= oldsub and l < k do
1716 if n and n.id == HLIST then
1717 local first = n.head
1718 for nn in traverse_id(GLYPH, first) do
1719 color_node(nn, COLOR)
1720 local c = nn.char
1721 if not char_to_discard[c] then l = l + 1 end
1722 end
1723 %<dbg> texio.write_nl('l (box)=' .. l)
1724 elseif n then
1725 color_node(n, COLOR)
1726 li, newsub = signature(n, newsub, swap)
1727 l = l + li - lo
1728 lo = li
1729 %<dbg> texio.write_nl('l=' .. l)
1730 end
1731 n = n.prev
1732 end
1733 end
1734 end
1735 end
1736 return new, match
1737 end
1738 % \end{macrocode}
1739 %
1740 % Same thing for beginning of lines: check the first two words
1741 % and compare their signature with the previous line’s.
1742 %
1743 % \changes{v0.61}{2023/02/06}{`check\_line\_first\_word’ returns a flag
1744 % to set pageflag.}
1745 %
1746 % \begin{macrocode}
1747 local check_line_first_word =
1748 function (old, node, line, colno, flag, footnote)
1749 local COLOR = luatypo.colortbl[11]
1750 local match = false
1751 local swap = false
1752 local new = ""
1753 local maxlen = 0
1754 local MinFull = luatypo.MinFull
1755 local MinPart = luatypo.MinPart
1756 local n = node
1757 local box, go
1758 while n and n.id ~= GLYPH and n.id ~= DISC and
1759 (n.id ~= HLIST or n.subtype == INDENT) do
1760 n = n.next
1761 end
1762 start = n
1763 local words = 0
1764 while n and (words <= 2 or maxlen < MinPart) do
1765 if n and n.id == HLIST then
1766 box = n
1767 n = n.head
1768 while n do
1769 maxlen, new = signature (n, new, swap)
1770 n = n.next
1771 end
1772 n = box.next
1773 local w = utf8_gsub(new, "_", "")
1774 words = words + utf8_len(new) - utf8_len(w) + 1
1775 else
1776 repeat
1777 maxlen, new = signature (n, new, swap)
1778 n = n.next
1779 until not n or n.id == GLUE or n.id == HLIST
1780 if n and n.id == GLUE then
1781 maxlen, new = signature (n, new, swap)
1782 words = words + 1
1783 n = n.next
1784 end
1785 end
1786 end
1787 new = utf8_gsub(new, "_+$", "") -- $
1788 new = utf8_gsub(new, "^_+", "")
1789 maxlen = math.min(utf8_len(old), utf8_len(new))
1790 %<dbg> texio.write_nl('BOLsigold=' .. old)
1791 %<dbg> texio.write(' BOLsig=' .. new)
1792 % \end{macrocode}
1793 % When called with flag |false|, |check_line_first_word| doesn’t
1794 % compare it with the previous line’s, but returns
1795 % the first word’s signature.
1796 % \begin{macrocode}
1797 if flag and old ~= "" then
1798 local oldfirst = utf8_gsub (old, "_.*", "")
1799 local newfirst = utf8_gsub (new, "_.*", "")
1800 local oldsub = ""
1801 local newsub = ""
1802 for p, c in utf8.codes(old) do
1803 local s = utf8_gsub(oldsub, "_", "")
1804 if utf8_len(s) < MinPart then
1805 oldsub = oldsub .. utf8.char(c)
1806 end
1807 end
1808 for p, c in utf8.codes(new) do
1809 local s = utf8_gsub(newsub, "_", "")
1810 if utf8_len(s) < MinPart then
1811 newsub = newsub .. utf8.char(c)
1812 end
1813 end
1814 if oldsub == newsub then
1815 %<dbg> texio.write_nl('BOLnewsub=' .. newsub)
1816 match = true
1817 end
1818 if oldfirst == newfirst and utf8_len(newfirst) >= MinFull then
1819 %<dbg> texio.write_nl('BOLnewfirst=' .. newfirst)
1820 if utf8_len(newfirst) > MinPart or not match then
1821 oldsub = oldfirst
1822 newsub = newfirst
1823 end
1824 match = true
1825 end
1826 if match then
1827 % \end{macrocode}
1828 % Minimal full or partial match |newsub| of length |k|;
1829 % any more glyphs matching?
1830 % \begin{macrocode}
1831 local k = utf8_len(newsub)
1832 local osub = oldsub
1833 local nsub = newsub
1834 while osub == nsub and k < maxlen do
1835 k = k + 1
1836 osub = utf8_sub(old,1,k)
1837 nsub = utf8_sub(new,1,k)
1838 if osub == nsub then
1839 newsub = nsub
1840 end
1841 end
1842 newsub = utf8_gsub(newsub, "_+$", "") --$
1843 %<dbg> texio.write_nl('BOLfullmatch=' .. newsub)
1844 local msg = "B.O.L. MATCH=" .. newsub
1845 log_flaw(msg, line, colno, footnote)
1846 % \end{macrocode}
1847 % Lest’s colour the matching string.
1848 % \begin{macrocode}
1849 local ns = utf8_gsub(newsub, "_", "")
1850 k = utf8_len(ns)
1851 oldsub = newsub
1852 local newsub = ""
1853 local n = start
1854 local l = 0
1855 local lo = 0
1856 local li = 0
1857 while n and newsub ~= oldsub and l < k do
1858 if n and n.id == HLIST then
1859 local nn = n.head
1860 for nnn in traverse(nn) do
1861 color_node(nnn, COLOR)
1862 local c = nn.char
1863 if not char_to_discard[c] then l = l + 1 end
1864 end
1865 elseif n then
1866 color_node(n, COLOR)
1867 li, newsub = signature(n, newsub, swap)
1868 l = l + li - lo
1869 lo = li
1870 end
1871 n = n.next
1872 end
1873 end
1874 end
1875 return new, match
1876 end
1877 % \end{macrocode}
1878 %
1879 % \changes{v0.65}{2023/03/02}{New `check\_page\_first\_word’ function.}
1880 %
1881 % The next function is meant to be called on the first line of a new
1882 % page. It checks the first word: if it ends a sentence and is short
1883 % (up to |\luatypoMinLen| characters), the function returns |true|
1884 % and colours the offending word. Otherwise it just returns |false|.
1885 % The function requires two arguments: the line’s first node and
1886 % a column number (possibly |nil|).
1887 %
1888 % \begin{macrocode}
1889 local check_page_first_word = function (node, colno, footnote)
1890 local COLOR = luatypo.colortbl[15]
1891 local match = false
1892 local swap = false
1893 local new = ""
1894 local minlen = luatypo.MinLen
1895 local len = 0
1896 local n = node
1897 local pn
1898 while n and n.id ~= GLYPH and n.id ~= DISC and
1899 (n.id ~= HLIST or n.subtype == INDENT) do
1900 n = n.next
1901 end
1902 local start = n
1903 if n and n.id == HLIST then
1904 start = n.head
1905 n = n.head
1906 end
1907 repeat
1908 len, new = signature (n, new, swap)
1909 n = n.next
1910 until len > minlen or (n and n.id == GLYPH and eow_char[n.char]) or
1911 (n and n.id == GLUE) or
1912 (n and n.id == KERN and n.subtype == 1)
1913 % \end{macrocode}
1914 % In French `?’ and `!’ are preceded by a glue (babel) or a kern
1915 % (polyglossia).
1916 % \begin{macrocode}
1917 if n and (n.id == GLUE or n.id == KERN) then
1918 pn = n
1919 n = n.next
1920 end
1921 if len <= minlen and n and n.id == GLYPH and eow_char[n.char] then
1922 % \end{macrocode}
1923 % If the line does not ends here, set |match| to |true| (otherwise
1924 % this line is just a short line):
1925 % \begin{macrocode}
1926 repeat
1927 n = n.next
1928 until not n or n.id == GLYPH or
1929 (n.id == GLUE and n.subtype == PARFILL)
1930 if n and n.id == GLYPH then
1931 match = true
1932 end
1933 end
1934 %<dbg> texio.write_nl('FinalWord=' .. new)
1935 if match then
1936 local msg = "ShortFinalWord=" .. new
1937 log_flaw(msg, 1, colno, footnote)
1938 % \end{macrocode}
1939 % Lest’s colour the final word and punctuation sign.
1940 % \begin{macrocode}
1941 local n = start
1942 repeat
1943 color_node(n, COLOR)
1944 n = n.next
1945 until eow_char[n.char]
1946 color_node(n, COLOR)
1947 end
1948 return match
1949 end
1950 % \end{macrocode}
1951 %
1952 % The next function looks for a short word (one or two
1953 % chars) at end of lines, compares it to a given list and colours it
1954 % if matches. The first argument must be a node of type |GLYPH|,
1955 % usually the last line’s node, the next two are the line and
1956 % column number.
1957 %
1958 % \changes{v0.61}{2023/02/06}{`check\_regexpr’ returns a flag
1959 % to set pageflag in `check\_vtop’.}
1960 %
1961 % \begin{macrocode}
1962 local check_regexpr = function (glyph, line, colno, footnote)
1963 local COLOR = luatypo.colortbl[4]
1964 local lang = glyph.lang
1965 local match = false
1966 local retflag = false
1967 local lchar, id = is_glyph(glyph)
1968 local previous = glyph.prev
1969 % \end{macrocode}
1970 % First look for single chars unless the list of words is empty.
1971 % \begin{macrocode}
1972 if lang and luatypo.single[lang] then
1973 % \end{macrocode}
1974 % For single char words, the previous node is a glue.
1975 % \begin{macrocode}
1976 if lchar and previous and previous.id == GLUE then
1977 match = utf8_find(luatypo.single[lang], utf8.char(lchar))
1978 if match then
1979 retflag = true
1980 local msg = "RGX MATCH=" .. utf8.char(lchar)
1981 log_flaw(msg, line, colno, footnote)
1982 color_node(glyph,COLOR)
1983 end
1984 end
1985 end
1986 % \end{macrocode}
1987 % Look for two chars words unless the list of words is empty.
1988 % \begin{macrocode}
1989 if lang and luatypo.double[lang] then
1990 if lchar and previous and previous.id == GLYPH then
1991 local pchar, id = is_glyph(previous)
1992 local pprev = previous.prev
1993 % \end{macrocode}
1994 % For two chars words, the previous node is a glue…
1995 % \begin{macrocode}
1996 if pchar and pprev and pprev.id == GLUE then
1997 local pattern = utf8.char(pchar) .. utf8.char(lchar)
1998 match = utf8_find(luatypo.double[lang], pattern)
1999 if match then
2000 retflag = true
2001 local msg = "RGX MATCH=" .. pattern
2002 log_flaw(msg, line, colno, footnote)
2003 color_node(previous,COLOR)
2004 color_node(glyph,COLOR)
2005 end
2006 end
2007 % \end{macrocode}
2008 % …unless a kern is found between the two chars.
2009 % \begin{macrocode}
2010 elseif lchar and previous and previous.id == KERN then
2011 local pprev = previous.prev
2012 if pprev and pprev.id == GLYPH then
2013 local pchar, id = is_glyph(pprev)
2014 local ppprev = pprev.prev
2015 if pchar and ppprev and ppprev.id == GLUE then
2016 local pattern = utf8.char(pchar) .. utf8.char(lchar)
2017 match = utf8_find(luatypo.double[lang], pattern)
2018 if match then
2019 retflag = true
2020 local msg = "REGEXP MATCH=" .. pattern
2021 log_flaw(msg, line, colno, footnote)
2022 color_node(pprev,COLOR)
2023 color_node(glyph,COLOR)
2024 end
2025 end
2026 end
2027 end
2028 end
2029 return retflag
2030 end
2031 % \end{macrocode}
2032 %
2033 % The next function prints the first part of an hyphenated
2034 % word up to the discretionary, with a supplied colour.
2035 % It requires two arguments: a \node{disc} node and a (named) colour.
2036 %
2037 % \begin{macrocode}
2038 local show_pre_disc = function (disc, color)
2039 local n = disc
2040 while n and n.id ~= GLUE do
2041 color_node(n, color)
2042 n = n.prev
2043 end
2044 return n
2045 end
2046 % \end{macrocode}
2047 %
2048 % \begin{macro}{footnoterule-ahead}
2049 % The next function scans the current \node{vlist} in search
2050 % of a |\footnoterule|; it returns |true| if found, false otherwise.
2051 % The \node{rule} node above footnotes is normaly surrounded by
2052 % two (vertical) \node{kern} nodes, the total height is either
2053 % 0 (standard and koma classes) or equals the rule’s height
2054 % (memoir class).
2055 %
2056 % \changes{v0.50}{2021/05/02}{New function `footnoterule\_ahead’.}
2057 %
2058 % \begin{macrocode}
2059 local footnoterule_ahead = function (head)
2060 local n = head
2061 local flag = false
2062 local totalht, ruleht, ht1, ht2, ht3
2063 if n and n.id == KERN and n.subtype == 1 then
2064 totalht = n.kern
2065 n = n.next
2066 %<dbg> ht1 = string.format("%.2fpt", totalht/65536)
2067 % \end{macrocode}
2068 % \changes{v0.51}{2023/01/17}{In some cases glue nodes might preceed
2069 % the footnote rule; next line added}
2070 % \begin{macrocode}
2071 while n and n.id == GLUE do n = n.next end
2072 if n and n.id == RULE and n.subtype == 0 then
2073 ruleht = n.height
2074 %<dbg> ht2 = string.format("%.2fpt", ruleht/65536)
2075 totalht = totalht + ruleht
2076 n = n.next
2077 if n and n.id == KERN and n.subtype == 1 then
2078 %<dbg> ht3 = string.format("%.2fpt", n.kern/65536)
2079 totalht = totalht + n.kern
2080 if totalht == 0 or totalht == ruleht then
2081 flag = true
2082 else
2083 %<dbg> texio.write_nl(' ')
2084 %<dbg> texio.write_nl('Not a footnoterule:')
2085 %<dbg> texio.write(' KERN height=' .. ht1)
2086 %<dbg> texio.write(' RULE height=' .. ht2)
2087 %<dbg> texio.write(' KERN height=' .. ht3)
2088 end
2089 end
2090 end
2091 end
2092 return flag
2093 end
2094 % \end{macrocode}
2095 % \end{macro}
2096 %
2097 % \begin{macro}{check-EOP}
2098 % This function looks ahead of |node| in search of a page end
2099 % or a footnote rule and returns the flags |page_bottom| and
2100 % |body_bottom| [used in text and display math lines].
2101 % \begin{macrocode}
2102 local check_EOP = function (node)
2103 local n = node
2104 local page_bot = false
2105 local body_bot = false
2106 while n and (n.id == GLUE or n.id == PENALTY or
2107 n.id == WHATSIT ) do
2108 n = n.next
2109 end
2110 if not n then
2111 page_bot = true
2112 body_bot = true
2113 elseif footnoterule_ahead(n) then
2114 body_bot = true
2115 %<dbg> texio.write_nl('=> FOOTNOTE RULE ahead')
2116 %<dbg> texio.write_nl('check_vtop: last line before footnotes')
2117 %<dbg> texio.write_nl(' ')
2118 end
2119 return page_bot, body_bot
2120 end
2121 % \end{macrocode}
2122 % \end{macro}
2123 %
2124 % \changes{v0.85}{2023/09/07}{New function `check\_marginnote’.}
2125 %
2126 % \begin{macro}{check-marginnote}
2127 % This function checks margin notes for overfull/underfull lines;
2128 % It also warns if a margin note ends too low under the last line
2129 % of text.
2130 % \begin{macrocode}
2131 local check_marginnote = function (head, line, colno, vpos, bpmn)
2132 local OverfullLines = luatypo.OverfullLines
2133 local UnderfullLines = luatypo.UnderfullLines
2134 local MarginparPos = luatypo.MarginparPos
2135 local margintol = luatypo.MParTol
2136 local marginpp = tex.getdimen("marginparpush")
2137 local textht = tex.getdimen("textheight")
2138 local mnflag = false
2139 local ofirst = true
2140 local ufirst = true
2141 local n = head.head
2142 local bottom = vpos
2143 if vpos <= bpmn then
2144 bottom = bpmn + marginpp
2145 end
2146 %<dbg> texio.write_nl('*** Margin note? ***')
2147 repeat
2148 if n and (n.id == GLUE or n.id == PENALTY) then
2149 %<dbg> texio.write_nl(' Found GLUE or PENALTY')
2150 n = n.next
2151 elseif n and n.id == VLIST then
2152 %<dbg> texio.write_nl(' Found VLIST')
2153 n = n.head
2154 end
2155 until not n or (n.id == HLIST and n.subtype == LINE)
2156 local head = n
2157 if head then
2158 %<dbg> texio.write_nl(' Found HLIST')
2159 else
2160 %<dbg> texio.write_nl(' No text line found.')
2161 end
2162 %<dbg> local l = 0
2163 local last = head
2164 while head do
2165 local next = head.next
2166 if head.id == HLIST and head.subtype == LINE then
2167 %<dbg> l = l + 1
2168 %<dbg> texio.write_nl(' Checking line ' .. l)
2169 bottom = bottom + head.height + head.depth
2170 local first = head.head
2171 local linewd = head.width
2172 local hmax = linewd + tex.hfuzz
2173 local w,h,d = dimensions(1,2,0, first)
2174 local Stretch = math.max(luatypo.Stretch/100,1)
2175 if w > hmax and OverfullLines then
2176 %<dbg> texio.write(': Overfull!')
2177 mnflag = true
2178 local COLOR = luatypo.colortbl[8]
2179 color_line (head, COLOR)
2180 if ofirst then
2181 local msg = "OVERFULL line(s) in margin note"
2182 log_flaw(msg, line, colno, false)
2183 ofirst = false
2184 end
2185 elseif head.glue_set > Stretch and head.glue_sign == 1 and
2186 head.glue_order == 0 and UnderfullLines then
2187 %<dbg> texio.write(': Underfull!')
2188 mnflag = true
2189 local COLOR = luatypo.colortbl[9]
2190 color_line (head, COLOR)
2191 if ufirst then
2192 local msg = "UNDERFULL line(s) in margin note"
2193 log_flaw(msg, line, colno, false)
2194 ufirst = false
2195 end
2196 end
2197 end
2198 last = head
2199 head = next
2200 end
2201 %<dbg> local tht = string.format("%.1fpt", textht/65536)
2202 %<dbg> local bott = string.format("%.1fpt", bottom/65536)
2203 %<dbg> texio.write_nl(' Bottom=' .. bott)
2204 %<dbg> texio.write(' TextBottom=' ..tht)
2205 if bottom > textht + margintol and MarginparPos then
2206 mnflag = true
2207 local COLOR = luatypo.colortbl[17]
2208 color_line (last, COLOR)
2209 local msg = "Margin note too low"
2210 log_flaw(msg, line, colno, false)
2211 end
2212 return bottom, mnflag
2213 end
2214 % \end{macrocode}
2215 % \end{macro}
2216 %
2217 % \changes{v0.88}{2026/01/06}{New function `check\_vbox’.}
2218 %
2219 % \begin{macro}{check-vbox}
2220 % This function checks vboxes for overfull/underfull lines.
2221 % \begin{macrocode}
2222 local check_vbox = function (head, line, colno, vpos, lmax)
2223 local OverfullLines = luatypo.OverfullLines
2224 local UnderfullLines = luatypo.UnderfullLines
2225 local vbflag = false
2226 local l = 0
2227 local ll = line
2228 local n = head.head
2229 %<dbg> texio.write_nl('*** vbox found ***')
2230 while n do
2231 if n.id == HLIST and n.subtype == LINE then
2232 l = l + 1
2233 if l > 1 then ll = ll + 1 end
2234 %<dbg> texio.write_nl('l = ' .. l)
2235 local first = n.head
2236 local linewd = n.width
2237 local hmax = linewd + tex.hfuzz
2238 local w,h,d = dimensions(1,2,0, first)
2239 local Stretch = math.max(luatypo.Stretch/100,1)
2240 if w > hmax and OverfullLines then
2241 %<dbg> texio.write(': Overfull!')
2242 vbflag = true
2243 local COLOR = luatypo.colortbl[8]
2244 color_line (n, COLOR)
2245 local wpt = string.format("%.2fpt", (w-n.width)/65536)
2246 local msg = "OVERFULL line in vbox, " .. wpt
2247 log_flaw(msg, ll, colno, false)
2248 elseif n.glue_set > Stretch and n.glue_sign == 1 and
2249 n.glue_order == 0 and UnderfullLines then
2250 %<dbg> texio.write(': Underfull!')
2251 vbflag = true
2252 local COLOR = luatypo.colortbl[9]
2253 color_line (n, COLOR)
2254 local s = string.format("%.0f%s", 100*n.glue_set, "%")
2255 local msg = "UNDERFULL line in vbox, stretch=" .. s
2256 log_flaw(msg, ll, colno, false)
2257 end
2258 end
2259 n = n.next
2260 end
2261 lmax = math.max(l, lmax)
2262 %<dbg> texio.write_nl('lmax = ' .. lmax)
2263 return lmax, vbflag
2264 end
2265 % \end{macro}
2266 %
2267 % \begin{macro}{get-pagebody}
2268 % The next function scans the \node{vlist}s on the current
2269 % page in search of the page body.
2270 % It returns the corresponding node or nil in case of failure.
2271 %
2272 % \changes{v0.50}{2021/05/02}{New function `get\_pagebody’ required for
2273 % callback `pre\_shipout\_filter’.}
2274 %
2275 % \changes{v0.86}{2024/01/10}{Package `stfloats’ adds 1sp to the
2276 % external \cs{vbox}. Be less picky regarding height test.}
2277 %
2278 % \changes{v0.87}{2024/04/18}{\cs{get\_pagebody} improved: it
2279 % failed for crop + hyperref.}
2280 %
2281 % \begin{macrocode}
2282 local get_pagebody = function (head)
2283 local textht = tex.getdimen("textheight")
2284 local fn = head.list
2285 local body
2286 repeat
2287 fn = fn.next
2288 until fn.id == VLIST and fn.height > 0
2289 %<dbg> texio.write_nl(' ')
2290 %<dbg> local ht = string.format("%.1fpt", fn.height/65536)
2291 %<dbg> local dp = string.format("%.1fpt", fn.depth/65536)
2292 %<dbg> texio.write_nl('get_pagebody: TOP VLIST')
2293 %<dbg> texio.write(' ht=' .. ht .. ' dp=' .. dp)
2294 % \end{macrocode}
2295 % Enter the first \node{vlist} found, recursively scan its
2296 % internal \node{vlist}s high enough to include the 'body'
2297 % the height of which is known ('textht')…
2298 % \begin{macrocode}
2299 first = fn.list
2300 repeat
2301 for n in traverse_id(VLIST,first) do
2302 % \end{macrocode}
2303 % Package `stfloats’ seems to add 1sp to the external \cs{vbox}
2304 % for each float found on the page.
2305 % Add $\pm8$sp tolerance when comparing |n.height| to
2306 % |\textheight|.
2307 % \begin{macrocode}
2308 if n.subtype == 0 and n.height >= textht-1 then
2309 if n.height <= textht+8 then
2310 %<dbg> local ht = string.format("%.1fpt", n.height/65536)
2311 %<dbg> texio.write_nl('BODY found: ht=' .. ht)
2312 %<dbg> texio.write('=' .. n.height .. 'sp')
2313 %<dbg> texio.write_nl(' ')
2314 body = n
2315 break
2316 else
2317 first = n.list
2318 end
2319 else
2320 %<dbg> texio.write_nl('Skip short VLIST:')
2321 %<dbg> local ht = string.format("%.1fpt", n.height/65536)
2322 %<dbg> local dp = string.format("%.1fpt", n.depth/65536)
2323 %<dbg> texio.write('ht=' .. ht .. '=' .. n.height .. 'sp')
2324 %<dbg> texio.write('; dp=' .. dp)
2325 end
2326 end
2327 until body or not first
2328 if not body then
2329 texio.write_nl('***lua-typo ERROR: PAGE BODY *NOT* FOUND!***')
2330 end
2331 return body
2332 end
2333 % \end{macrocode}
2334 % \end{macro}
2335 %
2336 % \begin{macro}{check-vtop}
2337 % The next function is called repeatedly by |check_page| (see below);
2338 % it scans the boxes found in the page body (f.i.\ columns)
2339 % in search of typographical flaws and logs.
2340 %
2341 % \changes{v0.40}{2021/04/18}{Title pages, pages with figures and/or
2342 % tables may not be empty pages: check `vpos’ last line’s position.}
2343 %
2344 % \changes{v0.60}{2023/01/28}{Loop redesigned.}
2345 %
2346 % \changes{v0.60}{2023/01/29}{Typographical flaws are recorded here
2347 % (formerly in check\_page).}
2348 %
2349 % \changes{v0.60}{2023/01/29}{Break `check\_vtop’ loop
2350 % if a two columns box starts.}
2351 %
2352 % \begin{macrocode}
2353 check_vtop = function (top, colno, vpos)
2354 local head = top.list
2355 local PAGEmin = luatypo.PAGEmin
2356 local HYPHmax = luatypo.HYPHmax
2357 local LLminWD = luatypo.LLminWD
2358 local BackPI = luatypo.BackPI
2359 local BackFuzz = luatypo.BackFuzz
2360 local BackParindent = luatypo.BackParindent
2361 local ShortLines = luatypo.ShortLines
2362 local ShortPages = luatypo.ShortPages
2363 local OverfullLines = luatypo.OverfullLines
2364 local UnderfullLines = luatypo.UnderfullLines
2365 local Widows = luatypo.Widows
2366 local Orphans = luatypo.Orphans
2367 local EOPHyphens = luatypo.EOPHyphens
2368 local RepeatedHyphens = luatypo.RepeatedHyphens
2369 local FirstWordMatch = luatypo.FirstWordMatch
2370 local ParLastHyphen = luatypo.ParLastHyphen
2371 local EOLShortWords = luatypo.EOLShortWords
2372 local LastWordMatch = luatypo.LastWordMatch
2373 local FootnoteSplit = luatypo.FootnoteSplit
2374 local ShortFinalWord = luatypo.ShortFinalWord
2375 local PageFirstLine = luatypo.PageFirstLine
2376 local Stretch = math.max(luatypo.Stretch/100,1)
2377 local blskip = tex.getglue("baselineskip")
2378 local vpos_min = PAGEmin * blskip
2379 vpos_min = vpos_min * 1.5
2380 local linewd = tex.getdimen("textwidth")
2381 local first_bot = true
2382 local done = false
2383 local footnote = false
2384 local ftnsplit = false
2385 local orphanflag = false
2386 local widowflag = false
2387 local pageshort = false
2388 local overfull = false
2389 local underfull = false
2390 local shortline = false
2391 local backpar = false
2392 local pflflag = false
2393 local firstwd = ""
2394 local lastwd = ""
2395 local hyphcount = 0
2396 local pageline = 0
2397 local ftnline = 0
2398 local line = 0
2399 local bpmn = 0
2400 local body_bottom = false
2401 local page_bottom = false
2402 local pageflag = false
2403 local pageno = tex.getcount("c@page")
2404 % \end{macrocode}
2405 % The main loop scans the content of the |\vtop| holding the page
2406 % (or column) body, footnotes included.
2407 % \begin{macrocode}
2408 while head do
2409 local nextnode = head.next
2410 % \end{macrocode}
2411 % Let’s scan the top nodes of this vbox: expected are \node{hlist}
2412 % (text lines or vboxes), \node{rule}, \node{kern}, \node{glue}…
2413 % \begin{macrocode}
2414 if head.id == HLIST and head.subtype == LINE and
2415 (head.height > 0 or head.depth > 0) then
2416 % \end{macrocode}
2417 % This is a text line, store its width, increment counters
2418 % |pageline| or |ftnline| and |line| (for |log_flaw|).
2419 % Let’s update |vpos| (vertical position in `sp’ units) and
2420 % set flag |done| to |true|.
2421 % \begin{macrocode}
2422 vpos = vpos + head.height + head.depth
2423 done = true
2424 local linewd = head.width
2425 local first = head.head
2426 local ListItem = false
2427 if footnote then
2428 ftnline = ftnline + 1
2429 line = ftnline
2430 else
2431 pageline = pageline + 1
2432 line = pageline
2433 pflflag = false
2434 end
2435 % \end{macrocode}
2436 % Is this line the last one on the page or before footnotes?
2437 % This has to be known early in order to set the flags |orphanflag|
2438 % and |ftnsplit|.
2439 % \begin{macrocode}
2440 page_bottom, body_bottom = check_EOP(nextnode)
2441 % \end{macrocode}
2442 % Is the current line overfull or underfull?
2443 % \changes{v0.50}{2021/05/13}{Detection of overfull boxes fixed: the
2444 % former code didn’t work for typewriter fonts.}
2445 % \changes{v0.80}{2023/04/18}{Colouring lines deferred until the full
2446 % line is scanned.}
2447 % \begin{macrocode}
2448 local hmax = linewd + tex.hfuzz
2449 local w,h,d = dimensions(1,2,0, first)
2450 if w > hmax and OverfullLines then
2451 pageflag = true
2452 overfull = true
2453 local wpt = string.format("%.2fpt", (w-head.width)/65536)
2454 local msg = "OVERFULL line " .. wpt
2455 log_flaw(msg, line, colno, footnote)
2456 elseif head.glue_set > Stretch and head.glue_sign == 1 and
2457 head.glue_order == 0 and UnderfullLines then
2458 pageflag = true
2459 underfull = true
2460 local s = string.format("%.0f%s", 100*head.glue_set, "%")
2461 local msg = "UNDERFULL line stretch=" .. s
2462 log_flaw(msg, line, colno, footnote)
2463 end
2464 % \end{macrocode}
2465 % In footnotes, set flag |ftnsplit| to |true| on page’s last line.
2466 % This flag will be reset to false if the current line ends a
2467 % paragraph.
2468 % \begin{macrocode}
2469 if footnote and page_bottom then
2470 ftnsplit = true
2471 end
2472 % \end{macrocode}
2473 % The current node being a line, |first| is its first node.
2474 % Skip margin kern and/or leftskip if any.
2475 %
2476 % \changes{v0.40}{2021/04/18}{Both MKERN and LFTSKIP may occur on
2477 % the same line.}
2478 %
2479 % \changes{v0.40}{2021/04/18}{All hlists of subtype LINE now
2480 % count as a pageline.}
2481 %
2482 % \begin{macrocode}
2483 while first.id == MKERN or
2484 (first.id == GLUE and first.subtype == LFTSKIP) do
2485 first = first.next
2486 end
2487 % \end{macrocode}
2488 % Now let’s analyse the beginning of the current line.
2489 % \begin{macrocode}
2490 if first.id == LPAR then
2491 % \end{macrocode}
2492 % It starts a paragraph… Reset |parline| except in footnotes
2493 % (|parline| and |pageline| counts are for ``body’’ \emph{only},
2494 % they are frozen in footnotes).
2495 % \begin{macrocode}
2496 hyphcount = 0
2497 firstwd = ""
2498 lastwd = ""
2499 if not footnote then
2500 parline = 1
2501 if pageline == 1 and PageFirstLine then
2502 % \end{macrocode}
2503 % This paragraph starts on top of this page or column, is it indented?
2504 % \begin{macrocode}
2505 local nn = first.next
2506 if nn.id == HLIST and nn.subtype == INDENT and
2507 nn.width > 0 then
2508 pageflag = true
2509 pflflag = true
2510 end
2511 end
2512 if body_bottom then
2513 % \end{macrocode}
2514 % We are at the page bottom (footnotes excluded), this ligne is
2515 % an orphan (unless it is the unique line of the paragraph, this
2516 % will be checked later when scanning the end of line).
2517 % \begin{macrocode}
2518 orphanflag = true
2519 end
2520 end
2521 % \end{macrocode}
2522 % List items begin with |LPAR| followed by an hbox.
2523 % \begin{macrocode}
2524 local nn = first.next
2525 if nn and nn.id == HLIST and nn.subtype == BOX then
2526 ListItem = true
2527 end
2528 elseif not footnote then
2529 parline = parline + 1
2530 end
2531 % \end{macrocode}
2532 % Does the first word and the one on the previous line match
2533 % (except lists)?
2534 % \begin{macrocode}
2535 if FirstWordMatch then
2536 local flag = not ListItem and (line > 1)
2537 firstwd, flag =
2538 check_line_first_word(firstwd, first, line, colno,
2539 flag, footnote)
2540 if flag then
2541 pageflag = true
2542 end
2543 end
2544 % \end{macrocode}
2545 % Check the page’s first word (end of sentence?).
2546 % \begin{macrocode}
2547 if ShortFinalWord and pageline == 1 and parline > 1 and
2548 check_page_first_word(first, colno, footnote) then
2549 pageflag = true
2550 end
2551 % \end{macrocode}
2552 % Check for possible vboxes (minipages, parboxes) inside this line.
2553 % \begin{macrocode}
2554 local cn = first
2555 local lmax = 1
2556 repeat
2557 if cn.id == VLIST and cn.subtype == 0 then
2558 lmax, vbflag = check_vbox (cn, line, colno, vpos, lmax)
2559 end
2560 cn = cn.next
2561 until not cn
2562 if not footnote then
2563 line = line + lmax - 1
2564 parline = parline + lmax - 1
2565 pageline = pageline + lmax - 1
2566 end
2567 % \end{macrocode}
2568 % Let’s now check the end of line: |ln| (usually a rightskip)
2569 % and |pn| are the last two nodes.
2570 % \begin{macrocode}
2571 local ln = slide(first)
2572 % \end{macrocode}
2573 % Skip a possible RULE pointing an overfull line.
2574 % \begin{macrocode}
2575 if ln.id == RULE and ln.subtype == 0 then
2576 ln = ln.prev
2577 end
2578 local pn = ln.prev
2579 if pn and pn.id == GLUE and pn.subtype == PARFILL then
2580 % \end{macrocode}
2581 % CASE 1: this line ends the paragraph, reset |ftnsplit| and |orphan|
2582 % flags to false…
2583 % \begin{macrocode}
2584 %<dbg> texio.write_nl('EOL CASE 1: end of paragraph')
2585 hyphcount = 0
2586 ftnsplit = false
2587 orphanflag = false
2588 % \end{macrocode}
2589 % it is a widow if it is the page’s first line and it does’nt
2590 % start a new paragraph. If so, we flag this line as `widow’;
2591 % colouring full lines will take place later.
2592 % \begin{macrocode}
2593 if pageline == 1 and parline > 1 then
2594 widowflag = true
2595 end
2596 % \end{macrocode}
2597 % |PFskip| is the rubber length (in sp) added to complete the line.
2598 % \begin{macrocode}
2599 local PFskip = effective_glue(pn,head)
2600 if ShortLines then
2601 local llwd = linewd - PFskip
2602 %<dbg> local PFskip_pt = string.format("%.1fpt", PFskip/65536)
2603 %<dbg> local llwd_pt = string.format("%.1fpt", llwd/65536)
2604 %<dbg> texio.write_nl('PFskip= ' .. PFskip_pt)
2605 %<dbg> texio.write(' llwd= ' .. llwd_pt)
2606 % \end{macrocode}
2607 % |llwd| is the line’s length. Is it too short?
2608 % \begin{macrocode}
2609 if llwd < LLminWD then
2610 pageflag = true
2611 shortline = true
2612 local msg = "SHORT LINE: length=" ..
2613 string.format("%.0fpt", llwd/65536)
2614 log_flaw(msg, line, colno, footnote)
2615 end
2616 end
2617 % \end{macrocode}
2618 % Does this (end of paragraph) line ends too close to the right
2619 % margin?
2620 % \begin{macrocode}
2621 if BackParindent and PFskip < BackPI and
2622 PFskip >= BackFuzz and parline > 1 then
2623 pageflag = true
2624 backpar = true
2625 local msg = "NEARLY FULL line: backskip=" ..
2626 string.format("%.1fpt", PFskip/65536)
2627 log_flaw(msg, line, colno, footnote)
2628 end
2629 % \end{macrocode}
2630 % Does the last word and the one on the previous line match?
2631 % \begin{macrocode}
2632 if LastWordMatch then
2633 local flag = true
2634 if PFskip > BackPI or line == 1 then
2635 flag = false
2636 end
2637 local pnp = pn.prev
2638 lastwd, flag =
2639 check_line_last_word(lastwd, pnp, line, colno,
2640 flag, footnote)
2641 if flag then
2642 pageflag = true
2643 end
2644 end
2645 elseif pn and pn.id == DISC then
2646 % \end{macrocode}
2647 % CASE 2: the current line ends with an hyphen.
2648 % \begin{macrocode}
2649 %<dbg> texio.write_nl('EOL CASE 2: hyphen')
2650 hyphcount = hyphcount + 1
2651 if hyphcount > HYPHmax and RepeatedHyphens then
2652 local COLOR = luatypo.colortbl[3]
2653 local pg = show_pre_disc (pn,COLOR)
2654 pageflag = true
2655 local msg = "REPEATED HYPHENS: more than " .. HYPHmax
2656 log_flaw(msg, line, colno, footnote)
2657 end
2658 if (page_bottom or body_bottom) and EOPHyphens then
2659 % \end{macrocode}
2660 % This hyphen occurs on the page’s last line (body or footnote),
2661 % colour (differently) the last word.
2662 % \begin{macrocode}
2663 pageflag = true
2664 local msg = "LAST WORD SPLIT"
2665 log_flaw(msg, line, colno, footnote)
2666 local COLOR = luatypo.colortbl[2]
2667 local pg = show_pre_disc (pn,COLOR)
2668 end
2669 % \end{macrocode}
2670 % Track matching words at end of line.
2671 % \begin{macrocode}
2672 if LastWordMatch then
2673 local flag = true
2674 lastwd, flag =
2675 check_line_last_word(lastwd, pn, line, colno,
2676 flag, footnote)
2677 if flag then
2678 pageflag = true
2679 end
2680 end
2681 if nextnode and ParLastHyphen then
2682 % \end{macrocode}
2683 % Does the next line end the current paragraph? If so, |nextnode| is
2684 % a `linebreak penalty’, the next one is a `baseline skip’ and the
2685 % node after is a \node{hlist-1} with |glue_order=2|.
2686 % \begin{macrocode}
2687 local nn = nextnode.next
2688 local nnn = nil
2689 if nn and nn.next then
2690 nnn = nn.next
2691 if nnn.id == HLIST and nnn.subtype == LINE and
2692 nnn.glue_order == 2 then
2693 pageflag = true
2694 local msg = "HYPHEN on next to last line"
2695 log_flaw(msg, line, colno, footnote)
2696 local COLOR = luatypo.colortbl[1]
2697 local pg = show_pre_disc (pn,COLOR)
2698 end
2699 end
2700 end
2701 % \end{macrocode}
2702 % CASE 3: the current line ends with anything else (\node{glyph},
2703 % \node{mkern}, \node{hlist}, etc.), then reset |hyphcount| and
2704 % check for `LastWordMatch’ and `EOLShortWords’.
2705 % \begin{macrocode}
2706 else
2707 %<dbg> texio.write_nl('EOL CASE 3')
2708 hyphcount = 0
2709 % \end{macrocode}
2710 % Track matching words at end of line and short words.
2711 % \begin{macrocode}
2712 if LastWordMatch and pn then
2713 local flag = true
2714 lastwd, flag =
2715 check_line_last_word(lastwd, pn, line, colno,
2716 flag, footnote)
2717 if flag then
2718 pageflag = true
2719 end
2720 end
2721 if EOLShortWords then
2722 while pn and pn.id ~= GLYPH and pn.id ~= HLIST do
2723 pn = pn.prev
2724 end
2725 if pn and pn.id == GLYPH then
2726 if check_regexpr(pn, line, colno, footnote) then
2727 pageflag = true
2728 end
2729 end
2730 end
2731 end
2732 % \end{macrocode}
2733 % End of scanning for the main type of node (text lines).
2734 % Let’s colour the whole line if necessary. If more than one kind
2735 % of flaw \emph{affecting the whole line} has been detected,
2736 % a special colour is used [homearchy, repeated hyphens, etc.
2737 % will still be coloured properly: |color_line| doesn’t override
2738 % previously set colours].
2739 % \begin{macrocode}
2740 if pflflag then
2741 local COLOR = luatypo.colortbl[5]
2742 color_line (head, COLOR)
2743 local msg = "INDENTED first line (paragraph start)."
2744 log_flaw(msg, line, colno, false)
2745 end
2746 if widowflag and Widows then
2747 pageflag = true
2748 local msg = "WIDOW"
2749 log_flaw(msg, line, colno, footnote)
2750 local COLOR = luatypo.colortbl[5]
2751 if backpar or shortline or overfull or underfull then
2752 COLOR = luatypo.colortbl[16]
2753 if backpar then backpar = false end
2754 if shortline then shortline = false end
2755 if overfull then overfull = false end
2756 if underfull then underfull = false end
2757 end
2758 color_line (head, COLOR)
2759 widowflag = false
2760 elseif orphanflag and Orphans then
2761 pageflag = true
2762 local msg = "ORPHAN"
2763 log_flaw(msg, line, colno, footnote)
2764 local COLOR = luatypo.colortbl[6]
2765 if overfull or underfull then
2766 COLOR = luatypo.colortbl[16]
2767 end
2768 color_line (head, COLOR)
2769 elseif ftnsplit and FootnoteSplit then
2770 pageflag = true
2771 local msg = "FOOTNOTE SPLIT"
2772 log_flaw(msg, line, colno, footnote)
2773 local COLOR = luatypo.colortbl[14]
2774 if overfull or underfull then
2775 COLOR = luatypo.colortbl[16]
2776 end
2777 color_line (head, COLOR)
2778 elseif shortline then
2779 local COLOR = luatypo.colortbl[7]
2780 color_line (head, COLOR)
2781 shortline = false
2782 elseif overfull then
2783 local COLOR = luatypo.colortbl[8]
2784 color_line (head, COLOR)
2785 overfull = false
2786 elseif underfull then
2787 local COLOR = luatypo.colortbl[9]
2788 color_line (head, COLOR)
2789 underfull = false
2790 elseif backpar then
2791 local COLOR = luatypo.colortbl[13]
2792 color_line (head, COLOR)
2793 backpar = false
2794 end
2795 elseif head and head.id == HLIST and head.subtype == BOX then
2796 if head.width > 0 then
2797 if head.height == 0 then
2798 % \end{macrocode}
2799 % This is a possible margin note.
2800 % \begin{macrocode}
2801 bpmn, mnflag = check_marginnote(head, line, colno, vpos, bpmn)
2802 if mnflag then pageflag = true end
2803 page_bottom, body_bottom = check_EOP(nextnode)
2804 else
2805 % \end{macrocode}
2806 % Leave |check_vtop| if a two columns box starts.
2807 % \begin{macrocode}
2808 local hf = head.list
2809 if hf and hf.id == VLIST and hf.subtype == 0 then
2810 %<dbg> texio.write_nl('check_vtop: BREAK => multicol')
2811 %<dbg> texio.write_nl(' ')
2812 break
2813 else
2814 line = line + 1
2815 pageline = pageline + 1
2816 end
2817 end
2818 end
2819 % \end{macrocode}
2820 % \changes{v0.80}{2023/04/18}{hlist-2: added detection of page bottom
2821 % and increment vpos.}
2822 % This is an |\hbox| (f.i.\ centred), let’s update |vpos| and
2823 % check for page bottom. Counter pageline is \emph{not} incremented.
2824 % \begin{macrocode}
2825 vpos = vpos + head.height + head.depth
2826 page_bottom, body_bottom = check_EOP (nextnode)
2827 elseif head.id == HLIST and
2828 (head.subtype == EQN or head.subtype == ALIGN) and
2829 (head.height > 0 or head.depth > 0) then
2830 % \end{macrocode}
2831 % This line is a displayed or aligned equation.
2832 % Let’s update |vpos| and the line number.
2833 %
2834 % \changes{v0.50}{2021/05/05}{Consider displayed and aligned equations
2835 % too for overfull boxes.}
2836 %
2837 % \begin{macrocode}
2838 vpos = vpos + head.height + head.depth
2839 if footnote then
2840 ftnline = ftnline + 1
2841 line = ftnline
2842 else
2843 pageline = pageline + 1
2844 line = pageline
2845 end
2846 % \end{macrocode}
2847 % Is this line the last one on the page or before footnotes?
2848 % (information needed to set the |pageshort| flag).
2849 % \begin{macrocode}
2850 page_bottom, body_bottom = check_EOP (nextnode)
2851 % \end{macrocode}
2852 % Let’s check for an `Overfull box’. For a displayed equation
2853 % it is straightforward. A set of aligned equations all have the
2854 % same (maximal) width; in order to avoid highlighting the whole
2855 % set, we have to look for glues at the end of embedded
2856 % \node{hlist}s.
2857 % \begin{macrocode}
2858 local fl = true
2859 local wd = 0
2860 local hmax = 0
2861 if head.subtype == EQN then
2862 local f = head.list
2863 wd = rangedimensions(head,f)
2864 hmax = head.width + tex.hfuzz
2865 else
2866 wd = head.width
2867 hmax = tex.getdimen("linewidth") + tex.hfuzz
2868 end
2869 if wd > hmax and OverfullLines then
2870 if head.subtype == ALIGN then
2871 local first = head.list
2872 for n in traverse_id(HLIST, first) do
2873 local last = slide(n.list)
2874 if last.id == GLUE and last.subtype == USER then
2875 wd = wd - effective_glue(last,n)
2876 if wd <= hmax then fl = false end
2877 end
2878 end
2879 end
2880 if fl then
2881 pageflag = true
2882 local w = wd - hmax + tex.hfuzz
2883 local wpt = string.format("%.2fpt", w/65536)
2884 local msg = "OVERFULL equation " .. wpt
2885 log_flaw(msg, line, colno, footnote)
2886 local COLOR = luatypo.colortbl[8]
2887 color_line (head, COLOR)
2888 end
2889 end
2890 elseif head and head.id == RULE and head.subtype == 0 then
2891 vpos = vpos + head.height + head.depth
2892 % \end{macrocode}
2893 % This is a \node{rule}, possibly a footnote rule. It has most likely
2894 % been detected on the previous line (then |body_bottom=true|) but
2895 % might have no text before (footnote-only page!).
2896 % \begin{macrocode}
2897 local prev = head.prev
2898 if body_bottom or footnoterule_ahead (prev) then
2899 % \end{macrocode}
2900 % If it is, set the |footnote| flag and reset some counters
2901 % and flags for the coming footnote lines.
2902 % \begin{macrocode}
2903 %<dbg> texio.write_nl('check_vtop: footnotes start')
2904 %<dbg> texio.write_nl(' ')
2905 footnote = true
2906 ftnline = 0
2907 body_bottom = false
2908 orphanflag = false
2909 hyphcount = 0
2910 firstwd = ""
2911 lastwd = ""
2912 end
2913 % \end{macrocode}
2914 % Track short pages: check the number of lines at end of page,
2915 % in case this number is low, \emph{and} |vpos| is less than
2916 % |vpos_min|, fetch the last line and colour it.
2917 % \begin{macrocode}
2918 elseif body_bottom and head.id == GLUE and head.subtype == 0 then
2919 if first_bot then
2920 %<dbg> local vpos_pt = string.format("%.1fpt", vpos/65536)
2921 %<dbg> local vmin_pt = string.format("%.1fpt", vpos_min/65536)
2922 %<dbg> texio.write_nl('pageline=' .. pageline)
2923 %<dbg> texio.write_nl('vpos=' .. vpos_pt)
2924 %<dbg> texio.write(' vpos_min=' .. vmin_pt)
2925 %<dbg> if page_bottom then
2926 %<dbg> local tht = tex.getdimen("textheight")
2927 %<dbg> local tht_pt = string.format("%.1fpt", tht/65536)
2928 %<dbg> texio.write(' textheight=' .. tht_pt)
2929 %<dbg> end
2930 %<dbg> texio.write_nl(' ')
2931 if pageline > 1 and pageline < PAGEmin
2932 and vpos < vpos_min and ShortPages then
2933 pageshort = true
2934 pageflag = true
2935 local msg = "SHORT PAGE: only " .. pageline .. " lines"
2936 log_flaw(msg, line, colno, footnote)
2937 local COLOR = luatypo.colortbl[10]
2938 local n = head
2939 repeat
2940 n = n.prev
2941 until n.id == HLIST and n.subtype == LINE
2942 color_line (n, COLOR)
2943 end
2944 first_bot = false
2945 end
2946 elseif head.id == GLUE then
2947 % \end{macrocode}
2948 % Increment |vpos| on other vertical glues.
2949 % \begin{macrocode}
2950 vpos = vpos + effective_glue(head,top)
2951 elseif head.id == KERN and head.subtype == 1 then
2952 % \end{macrocode}
2953 % This is a vertical kern, let’s update |vpos|.
2954 % \begin{macrocode}
2955 vpos = vpos + head.kern
2956 elseif head.id == VLIST then
2957 % \end{macrocode}
2958 % This is a |\vbox|, let’s update |vpos|.
2959 % \begin{macrocode}
2960 vpos = vpos + head.height + head.depth
2961 %<dbg> local tht = head.height + head.depth
2962 %<dbg> local tht_pt = string.format("%.1fpt", tht/65536)
2963 %<dbg> texio.write(' vbox: height=' .. tht_pt)
2964 end
2965 head = nextnode
2966 end
2967 %<dbg> if nextnode then
2968 %<dbg> texio.write('Exit check_vtop, next=')
2969 %<dbg> texio.write(tostring(node.type(nextnode.id)))
2970 %<dbg> texio.write('-'.. nextnode.subtype)
2971 %<dbg> else
2972 %<dbg> texio.write_nl('Exit check_vtop, next=nil')
2973 %<dbg> end
2974 %<dbg> texio.write_nl('')
2975 % \end{macrocode}
2976 % Update the list of flagged pages avoiding duplicates:
2977 % \begin{macrocode}
2978 if pageflag then
2979 local plist = luatypo.pagelist
2980 local lastp = tonumber(string.match(plist, "%s(%d+),%s$"))
2981 if not lastp or pageno > lastp then
2982 luatypo.pagelist = luatypo.pagelist .. tostring(pageno) .. ", "
2983 end
2984 end
2985 return head, done
2986 % \end{macrocode}
2987 % |head| is nil unless |check_vtop| exited on a two column start.
2988 % |done| is true unless |check_vtop| found no text line.
2989 % \begin{macrocode}
2990 end
2991 % \end{macrocode}
2992 % \end{macro}
2993 %
2994 % \begin{macro}{check-page}
2995 % This is the main function which will be added to the
2996 % |pre_shipout_filter| callback unless option |None| is selected.
2997 % It executes |get_pagebody| which returns a node of type
2998 % \node{vlist}-0, then scans this \node{vlist}: expected are
2999 % \node{vlist}-0 (full width block) or \node{hlist}-2 (multi
3000 % column block).
3001 % The vertical position of the current node is stored in the |vpos|
3002 % dimension (integer in `sp’ units, 1\,pt~=~65536\,sp). It is used to
3003 % detect short pages.
3004 %
3005 % \changes{v0.60}{2023/01/29}{Loop redesigned to properly handle
3006 % two colums.}
3007 %
3008 % \begin{macrocode}
3009 luatypo.check_page = function (head)
3010 local pageno = tex.getcount("c@page")
3011 local body = get_pagebody(head)
3012 local textwd, textht, checked, boxed
3013 local top, first, next
3014 local n2, n3, col, colno
3015 local vpos = 0
3016 local footnote = false
3017 local count = 0
3018 if body then
3019 top = body
3020 first = body.list
3021 textwd = tex.getdimen("textwidth")
3022 textht = tex.getdimen("textheight")
3023 %<dbg> texio.write_nl('Body=' .. tostring(node.type(top.id)))
3024 %<dbg> texio.write('-' .. tostring(top.subtype))
3025 %<dbg> texio.write('; First=' .. tostring(node.type(first.id)))
3026 %<dbg> texio.write('-' .. tostring(first.subtype))
3027 %<dbg> texio.write_nl(' ')
3028 end
3029 if ((first and first.id == HLIST and first.subtype == BOX) or
3030 (first and first.id == VLIST and first.subtype == 0)) and
3031 (first.width == textwd and first.height > 0 and not boxed) then
3032 % \end{macrocode}
3033 % Some classes (\cls{memoir}, \cls{tugboat} …) use one more level
3034 % of bowing for two columns, let’s step down one level.
3035 % \begin{macrocode}
3036 %<dbg> local boxwd = string.format("%.1fpt", first.width/65536)
3037 %<dbg> texio.write_nl('One step down: boxwd=' .. boxwd)
3038 %<dbg> texio.write_nl('Glue order=' .. tostring(first.glue_order))
3039 %<dbg> texio.write_nl(' ')
3040 top = body.list
3041 % \end{macrocode}
3042 % A float on top of a page is a VLIST-0 included in a VLIST-0 (body),
3043 % it should not trigger this step down. Workaround: the body will be
3044 % scanned again.
3045 % \begin{macrocode}
3046 if first.id == VLIST then
3047 boxed = body
3048 end
3049 end
3050 % \end{macrocode}
3051 % Main loop:
3052 % \begin{macrocode}
3053 while top do
3054 first = top.list
3055 next = top.next
3056 %<dbg> count = count + 1
3057 %<dbg> texio.write_nl('Page loop' .. count)
3058 %<dbg> texio.write(': top=' .. tostring(node.type(top.id)))
3059 %<dbg> texio.write('-' .. tostring(top.subtype))
3060 %<dbg> if first then
3061 %<dbg> texio.write(' first=' .. tostring(node.type(first.id)))
3062 %<dbg> texio.write('-' .. tostring(first.subtype))
3063 %<dbg> end
3064 if top and top.id == VLIST and top.subtype == 0 and
3065 top.width > textwd/2 then
3066 % \end{macrocode}
3067 % Single column, run |check_vtop| on the top vlist.
3068 % \begin{macrocode}
3069 %<dbg> local boxht = string.format("%.1fpt", top.height/65536)
3070 %<dbg> local boxwd = string.format("%.1fpt", top.width/65536)
3071 %<dbg> texio.write_nl('**VLIST: ')
3072 %<dbg> texio.write(tostring(node.type(top.id)))
3073 %<dbg> texio.write('-' .. tostring(top.subtype))
3074 %<dbg> texio.write(' wd=' .. boxwd .. ' ht=' .. boxht)
3075 %<dbg> texio.write_nl(' ')
3076 local n, ok = check_vtop(top,colno,vpos)
3077 if ok then checked = true end
3078 if n then
3079 next = n
3080 end
3081 elseif (top and top.id == HLIST and top.subtype == BOX) and
3082 (first and first.id == VLIST and first.subtype == 0) and
3083 (first.height > 0 and first.width > 0) then
3084 % \end{macrocode}
3085 % Two or more columns, each one is boxed in a vlist.\par
3086 % Run |check_vtop| on every column.
3087 % \begin{macrocode}
3088 %<dbg> texio.write_nl('**MULTICOL type1:')
3089 %<dbg> texio.write_nl(' ')
3090 colno = 0
3091 for col in traverse_id(VLIST, first) do
3092 colno = colno + 1
3093 %<dbg> texio.write_nl('Start of col.' .. colno)
3094 %<dbg> texio.write_nl(' ')
3095 local n, ok = check_vtop(col,colno,vpos)
3096 if ok then checked = true end
3097 %<dbg> texio.write_nl('End of col.' .. colno)
3098 %<dbg> texio.write_nl(' ')
3099 end
3100 colno = nil
3101 top = top.next
3102 %<dbg> texio.write_nl('MULTICOL type1 END: next=')
3103 %<dbg> texio.write(tostring(node.type(top.id)))
3104 %<dbg> texio.write('-' .. tostring(top.subtype))
3105 %<dbg> texio.write_nl(' ')
3106 elseif (top and top.id == HLIST and top.subtype == BOX) and
3107 (first and first.id == HLIST and first.subtype == BOX) and
3108 (first.height > 0 and first.width > 0) then
3109 % \end{macrocode}
3110 % Two or more columns, each one is boxed in an hlist which
3111 % holds a vlist.\par
3112 % Run |check_vtop| on every column.
3113 % \begin{macrocode}
3114 %<dbg> texio.write_nl('**MULTICOL type2:')
3115 %<dbg> texio.write_nl(' ')
3116 colno = 0
3117 for n in traverse_id(HLIST, first) do
3118 colno = colno + 1
3119 local col = n.list
3120 if col and col.list then
3121 %<dbg> texio.write_nl('Start of col.' .. colno)
3122 %<dbg> texio.write_nl(' ')
3123 local n, ok = check_vtop(col,colno,vpos)
3124 if ok then checked = true end
3125 %<dbg> texio.write_nl('End of col.' .. colno)
3126 %<dbg> texio.write_nl(' ')
3127 end
3128 end
3129 colno = nil
3130 end
3131 % \end{macrocode}
3132 % Workaround for top floats: check the whole body again.
3133 % \begin{macrocode}
3134 if boxed and not next then
3135 next = boxed
3136 boxed = nil
3137 end
3138 top = next
3139 end
3140 if not checked then
3141 luatypo.failedlist = luatypo.failedlist .. tostring(pageno) .. ", "
3142 %<dbg> texio.write_nl(' ')
3143 %<dbg> texio.write_nl('WARNING: no text line found on page ')
3144 %<dbg> texio.write(tostring(pageno))
3145 %<dbg> texio.write_nl(' ')
3146 end
3147 return true
3148 end
3149 return luatypo.check_page
3150 \end{luacode}
3151 % \end{macrocode}
3152 % \end{macro}
3153 %
3154 % \changes{v0.50}{2021/05/02}{Callback `pre\_output\_filter’ replaced
3155 % by `pre\_shipout\_filter’, in the former the material is not boxed
3156 % yet and footnotes are not visible.}
3157 %
3158 % NOTE: |effective_glue| requires a `parent’ node, as pointed out by
3159 % Marcel Krüger on S.E., this implies using |pre_shipout_filter|
3160 % instead of |pre_output_filter|.
3161 %
3162 % Add the |luatypo.check_page| function to the |pre_shipout_filter|
3163 % callback (with priority 1 for colour attributes to be effective),
3164 % unless option |None| is selected.
3165 %
3166 % \begin{macrocode}
3167 \AtBeginDocument{%
3168 \directlua{
3169 if not luatypo.None then
3170 luatexbase.add_to_callback
3171 ("pre_shipout_filter",luatypo.check_page,"check_page",1)
3172 end
3173 }%
3174 }
3175 % \end{macrocode}
3176 %
3177 % Load a config file if present in LaTeX’s search path or
3178 % set reasonnable defaults.
3179 %
3180 % \changes{v0.61}{2023/02/07}{Colours mygrey, myred renamed as
3181 % LTgrey, LTred.}
3182 %
3183 % \begin{macrocode}
3184 \InputIfFileExists{lua-typo.cfg}%
3185 {\PackageInfo{lua-typo.sty}{"lua-typo.cfg" file loaded}}%
3186 {\PackageInfo{lua-typo.sty}{"lua-typo.cfg" file not found.
3187 \MessageBreak Providing default values.}%
3188 \definecolor{LTgrey}{gray}{0.6}%
3189 \definecolor{LTred}{rgb}{1,0.55,0}
3190 \definecolor{LTline}{rgb}{0.7,0,0.3}
3191 \luatypoSetColor1{red}% Paragraph last full line hyphenated
3192 \luatypoSetColor2{red}% Page last word hyphenated
3193 \luatypoSetColor3{red}% Hyphens on to many consecutive lines
3194 \luatypoSetColor4{red}% Short word at end of line
3195 \luatypoSetColor5{cyan}% Widow
3196 \luatypoSetColor6{cyan}% Orphan
3197 \luatypoSetColor7{cyan}% Paragraph ending on a short line
3198 \luatypoSetColor8{blue}% Overfull lines
3199 \luatypoSetColor9{blue}% Underfull lines
3200 \luatypoSetColor{10}{red}% Nearly empty page
3201 \luatypoSetColor{11}{LTred}% First word matches
3202 \luatypoSetColor{12}{LTred}% Last word matches
3203 \luatypoSetColor{13}{LTgrey}% Paragraph ending on a nearly full line
3204 \luatypoSetColor{14}{cyan}% Footnote split
3205 \luatypoSetColor{15}{red}% Too short first (final) word on the page
3206 \luatypoSetColor{16}{LTline}% Line color for multiple flaws
3207 \luatypoSetColor{17}{red}% Margin note ending too low
3208 \luatypoBackPI=1em\relax
3209 \luatypoBackFuzz=2pt\relax
3210 \ifdim\parindent=0pt \luatypoLLminWD=20pt\relax
3211 \else\luatypoLLminWD=2\parindent\relax\fi
3212 \luatypoStretchMax=200\relax
3213 \luatypoHyphMax=2\relax
3214 \luatypoPageMin=5\relax
3215 \luatypoMinFull=3\relax
3216 \luatypoMinPart=4\relax
3217 \luatypoMinLen=4\relax
3218 \luatypoMarginparTol=\baselineskip
3219 }%
3220 % \end{macrocode}
3221 % \iffalse
3222 %</sty>
3223 % \fi
3224 %
3225 % \section{Configuration file}
3226 %
3227 % \iffalse
3228 %<*cfg>
3229 % \fi
3230 %
3231 % \let\theCodelineNo\relax
3232 % \begin{macrocode}
3233 %%% Configuration file for lua-typo.sty
3234 %%% These settings can also be overruled in the preamble.
3235
3236 %% Minimum gap between end of paragraphs’ last lines and the right margin
3237 \luatypoBackPI=1em\relax
3238 \luatypoBackFuzz=2pt\relax
3239
3240 %% Minimum length of paragraphs’ last lines
3241 \ifdim\parindent=0pt \luatypoLLminWD=20pt\relax
3242 \else \luatypoLLminWD=2\parindent\relax
3243 \fi
3244
3245 %% Maximum number of consecutive hyphenated lines
3246 \luatypoHyphMax=2\relax
3247
3248 %% Nearly empty pages: minimum number of lines
3249 \luatypoPageMin=5\relax
3250
3251 %% Maximum acceptable stretch before a line is tagged as Underfull
3252 \luatypoStretchMax=200\relax
3253
3254 %% Minimum number of matching characters for words at begin/end of line
3255 \luatypoMinFull=3\relax
3256 \luatypoMinPart=4\relax
3257
3258 %% Minimum number of characters for the first word on a page if it ends
3259 %% a sentence (version >= 0.65).
3260 \ifdefined\luatypoMinLen \luatypoMinLen=4\relax\fi
3261
3262 %% Acceptable marginpars must end at |\luatypoMarginparTol| under
3263 %% the page’s last line or above (version >= 0.85).
3264 \ifdefined\luatypoMarginparTol \luatypoMarginparTol=\baselineskip \fi
3265
3266 %% Default colours = red, cyan, blue, LTgrey, LTred, LTline.
3267 \definecolor{LTgrey}{gray}{0.6}
3268 \definecolor{LTred}{rgb}{1,0.55,0}
3269 \definecolor{LTline}{rgb}{0.7,0,0.3}
3270 \luatypoSetColor1{red}% Paragraph last full line hyphenated
3271 \luatypoSetColor2{red}% Page last word hyphenated
3272 \luatypoSetColor3{red}% Hyphens on to many consecutive lines
3273 \luatypoSetColor4{red}% Short word at end of line
3274 \luatypoSetColor5{cyan}% Widow
3275 \luatypoSetColor6{cyan}% Orphan
3276 \luatypoSetColor7{cyan}% Paragraph ending on a short line
3277 \luatypoSetColor8{blue}% Overfull lines
3278 \luatypoSetColor9{blue}% Underfull lines
3279 \luatypoSetColor{10}{red}% Nearly empty page
3280 \luatypoSetColor{11}{LTred}% First word matches
3281 \luatypoSetColor{12}{LTred}% Last word matches
3282 \luatypoSetColor{13}{LTgrey}% Paragraph ending on a nearly full line
3283 \luatypoSetColor{14}{cyan}% Footnote split
3284 \luatypoSetColor{15}{red}% Too short first (final) word on the page
3285 \luatypoSetColor{16}{LTline}% Line color for multiple flaws
3286 \luatypoSetColor{17}{red}% Margin note ending too low
3287
3288 %% Language specific settings (example for French):
3289 %% short words (two letters max) to be avoided at end of lines.
3290 %%\luatypoOneChar{french}{"A À Ô Y"}
3291 %%\luatypoTwoChars{french}{"Ah Au Ça Çà Ce De Il Je La Là Le Ma Me Ne Ni
3292 %% Oh On Or Ou Où Sa Se Si Ta Tu Va Vu"}
3293 % \end{macrocode}
3294 %
3295 % \iffalse
3296 %</cfg>
3297 % \fi
3298 %
3299 % \changes{v0.60}{2023/02/02}{Debugging stuff added.}
3300 %
3301 % \section{Debugging lua-typo}
3302 %
3303 % Personal stuff useful \emph{only} for maintaining the
3304 % \pkg{lua-typo} package has been added at the end of
3305 % \file{lua-typo.dtx} in version~0.60.
3306 % It is not extracted unless a) both `|\iffalse|’ and `|\fi|’ on
3307 % lines 41 and 46 at the beginning of \file{lua-typo.dtx} are
3308 % commented out and b) all files are generated again by a
3309 % |luatex lua-typo.dtx| command; then a (very) verbose version of
3310 % \file{lua-typo.sty} is generated together with
3311 % a \file{scan-page.sty} file which can be used instead of
3312 % \file{lua-typo.sty} to show the structured list of nodes
3313 % found in a document.
3314 %
3315 % \iffalse
3316 %<*scan>
3317 % \fi
3318 %
3319 % \begin{Debugging}
3320 % \begin{macrocode}
3321 \ifdefined\directlua
3322 \RequirePackage{luatexbase,luacode,luacolor}
3323 \RequirePackage{kvoptions,atveryend}
3324 \else
3325 \PackageError{This package is meant for LuaTeX only! Aborting}
3326 {No more information available, sorry!}
3327 \fi
3328
3329 \newdimen\luatypoLLminWD
3330 \newdimen\luatypoBackPI
3331 \newdimen\luatypoBackFuzz
3332 \newcount\luatypoStretchMax
3333 \newcount\luatypoHyphMax
3334 \newcount\luatypoPageMin
3335 \newcount\luatypoMinFull
3336 \newcount\luatypoMinPart
3337 \newcount\luatypo@LANGno
3338 \newcount\luatypo@options
3339 \newtoks\luatypo@single
3340 \newtoks\luatypo@double
3341
3342 \AtBeginDocument{%
3343 \directlua{
3344 luatypo.HYPHmax = tex.count.luatypoHyphMax
3345 luatypo.PAGEmin = tex.count.luatypoPageMin
3346 luatypo.Stretch = tex.count.luatypoStretchMax
3347 luatypo.MinFull = tex.count.luatypoMinFull
3348 luatypo.MinPart = tex.count.luatypoMinPart
3349 luatypo.LLminWD = tex.dimen.luatypoLLminWD
3350 luatypo.BackPI = tex.dimen.luatypoBackPI
3351 luatypo.BackFuzz = tex.dimen.luatypoBackFuzz
3352 }%
3353 }
3354
3355 \AtVeryEndDocument{%
3356 \directlua{
3357 texio.write_nl(' ')
3358 texio.write_nl('***************************')
3359 texio.write_nl('*** PAGE SCANNING ONLY: ***')
3360 texio.write_nl('*** NO CHECK PERFORMED! ***')
3361 texio.write_nl('***************************')
3362 texio.write_nl(' ')
3363 }%
3364 }
3365
3366 \newcommand*{\luatypoOneChar}[2]{}
3367 \newcommand*{\luatypoTwoChars}[2]{}
3368 \newcommand*{\luatypoSetColor}[2]{}
3369
3370 \begin{luacode}
3371 luatypo = { }
3372 luatypo.single = { }
3373 luatypo.double = { }
3374 luatypo.colortbl = { }
3375 luatypo.pagelist = " "
3376 luatypo.failedlist = " "
3377
3378 local hyphcount = 0
3379 local pageno = 0
3380 local prevno = 0
3381 local pageflag = false
3382
3383 local DISC = node.id("disc")
3384 local GLYPH = node.id("glyph")
3385 local GLUE = node.id("glue")
3386 local KERN = node.id("kern")
3387 local HLIST = node.id("hlist")
3388 local VLIST = node.id("vlist")
3389 local LPAR = node.id("local_par")
3390 local MKERN = node.id("margin_kern")
3391 local PENALTY = node.id("penalty")
3392 local USRSKIP = 0
3393 local PARSKIP = 3
3394 local LEFTSKIP = 8
3395 local TOPSKIP = 10
3396 local PARFILL = 15
3397 local LINE = 1
3398 local BOX = 2
3399 local USER = 0
3400
3401 local dimensions = node.dimensions
3402 local rangedimensions = node.rangedimensions
3403 local effective_glue = node.effective_glue
3404 local set_attribute = node.set_attribute
3405 local slide = node.slide
3406 local traverse = node.traverse
3407 local traverse_id = node.traverse_id
3408 local has_field = node.has_field
3409 local uses_font = node.uses_font
3410 local is_glyph = node.is_glyph
3411
3412 % \end{macrocode}
3413 % Some helpers functions.
3414 % \begin{macrocode}
3415 local get_pagebody = function (head)
3416 local textht = tex.getdimen("textheight")
3417 local fn = head.list
3418 local body
3419 repeat
3420 fn = fn.next
3421 until fn.id == VLIST and fn.height > 0
3422 local ht = string.format("%.1fpt", fn.height/65536)
3423 local dp = string.format("%.1fpt", fn.depth/65536)
3424 texio.write_nl("SKIP vlist: ht=" .. ht .. " dp=" .. dp)
3425 first = fn.list
3426 repeat
3427 for n in traverse_id(VLIST,first) do
3428 if n.subtype == 0 and n.height >= textht-1 then
3429 if n.height <= textht+8 then
3430 local ht = string.format("%.1fpt", n.height/65536)
3431 texio.write_nl('BODY found: ht=' .. ht)
3432 texio.write('=' .. n.height .. 'sp')
3433 texio.write_nl(' ')
3434 body = n
3435 break
3436 else
3437 first = n.list
3438 end
3439 else
3440 texio.write_nl('Skip short VLIST:')
3441 local ht = string.format("%.1fpt", n.height/65536)
3442 local dp = string.format("%.1fpt", n.depth/65536)
3443 texio.write('ht=' .. ht .. '=' .. n.height .. 'sp')
3444 texio.write('; dp=' .. dp)
3445 end
3446 end
3447 until body or not first
3448 if not body then
3449 texio.write_nl('***lua-typo ERROR: PAGE BODY *NOT* FOUND!***')
3450 end
3451 return body
3452 end
3453
3454 local print_subtype = function (node,parent)
3455 local n = node
3456 if n.id == GLYPH then
3457 texio.write(utf8.char(n.char))
3458 elseif n.id == GLUE then
3459 texio.write(tostring(n.subtype))
3460 real_pt = string.format("%.1fpt", effective_glue(n,parent)/65536)
3461 texio.write(' realwd=' .. real_pt)
3462 elseif n.id == DISC then
3463 local c = ""
3464 if n.replace then
3465 for nn in traverse_id(GLYPH, n.replace) do
3466 c = c .. utf8.char(nn.char)
3467 end
3468 texio.write(c)
3469 end
3470 if n.pre then
3471 c = ""
3472 for nn in traverse_id(GLYPH, n.pre) do
3473 c = c .. utf8.char(nn.char)
3474 end
3475 texio.write(' pre=' .. c)
3476 end
3477 if n.post then
3478 c = ""
3479 for nn in traverse_id(GLYPH, n.post) do
3480 c = c .. utf8.char(nn.char)
3481 end
3482 texio.write(' post=' .. c)
3483 end
3484 elseif n.subtype and n.subtype < 256 then
3485 texio.write(tostring(n.subtype))
3486 if n.height and n.depth then
3487 ht_pt = string.format("%.1fpt", n.height/65536)
3488 dp_pt = string.format("%.1fpt", n.depth/65536)
3489 texio.write(' ht=' .. ht_pt .. ' dp=' .. dp_pt)
3490 if n.width then
3491 wd_pt = string.format("%.1fpt", n.width/65536)
3492 texio.write(' wd=' .. wd_pt)
3493 end
3494 end
3495 end
3496 end
3497
3498 % \end{macrocode}
3499 % Main function. It prints a structured list of nodes found on the
3500 % page body (header and footer excluded, footnotes included).
3501 % \begin{macrocode}
3502 local scanvlist = function (head)
3503 local textht = tex.getdimen("textheight")
3504 local textwd = tex.getdimen("textwidth")
3505 local pageno = tex.getcount("c@page")
3506 texio.write_nl('PAGE ' .. pageno)
3507 texio.write(' textheight='.. string.format("%.1fpt", textht/65536))
3508 texio.write(' textwidth=' .. string.format("%.1fpt", textwd/65536))
3509 local linecount = 0
3510 local body, parent, ht_pt, dp_pt, real_pt
3511 body = get_pagebody(head)
3512 if body then
3513 parent = body
3514 head = body.head
3515 texio.write_nl('Enter outer vbox (body) of type ')
3516 texio.write(tostring(node.type(body.id)))
3517 texio.write('-')
3518 texio.write(tostring(body.subtype))
3519 else
3520 texio.write_nl('Function get_pagebody returned NIL!')
3521 texio.write_nl('=> Scanning whole page: node type ')
3522 texio.write(tostring(node.type(head.id)))
3523 texio.write('-')
3524 texio.write(tostring(head.subtype))
3525 end
3526 while head do
3527 texio.write_nl(tostring(node.type(head.id)))
3528 texio.write('-')
3529 print_subtype(head,body)
3530 if head.kern then
3531 ht_pt = string.format("%.1fpt", head.kern/65536)
3532 texio.write(' KERN ht/wd=' .. ht_pt)
3533 end
3534 local next = head.next
3535 local first = head.head
3536 for n in traverse(first) do
3537 parent = head
3538 texio.write_nl(' ' .. tostring(node.type(n.id)))
3539 texio.write('-')
3540 print_subtype(n,head)
3541 if n.id == VLIST or n.id == HLIST then
3542 local ff = n.head
3543 for nn in traverse(ff) do
3544 parent = n
3545 texio.write_nl(' ' .. tostring(node.type(nn.id)))
3546 texio.write('-')
3547 print_subtype(nn,n)
3548 if nn.id == VLIST or nn.id == HLIST then
3549 local f3 = nn.head
3550 for n3 in traverse(f3) do
3551 parent = nn
3552 texio.write_nl(' ' .. tostring(node.type(n3.id)))
3553 texio.write('-')
3554 print_subtype(n3,nn)
3555 if n3.id == VLIST or n3.id == HLIST then
3556 local f4 = n3.head
3557 for n4 in traverse(f4) do
3558 parent = n3
3559 texio.write_nl(' ' .. tostring(node.type(n4.id)))
3560 texio.write('-')
3561 print_subtype(n4,n3)
3562 if n4.id == VLIST or n4.id == HLIST then
3563 local f5 = n4.head
3564 for n5 in traverse(f5) do
3565 parent = n4
3566 texio.write_nl(' ' .. tostring(node.type(n5.id)))
3567 texio.write('-')
3568 print_subtype(n5,n4)
3569 end
3570 end
3571 end
3572 end
3573 end
3574 end
3575 end
3576 end
3577 end
3578 head = next
3579 end
3580 return true
3581 end
3582
3583 % \end{macrocode}
3584 % Add the main function to callback |pre_shipout_filter|.
3585 % \begin{macrocode}
3586 luatexbase.add_to_callback("pre_shipout_filter",scanvlist,"check_vlists")
3587 % \end{macrocode}
3588 \end{luacode}
3589 % \end{Debugging}
3590 %
3591 % \iffalse
3592 %</scan>
3593 % \fi
3594 %
3595 % \Finale
3596 \endinput
3597
3598 %%% Local Variables:
3599 %%% fill-column: 72
3600 %%% coding: utf-8
3601 %%% TeX-engine: luatex
3602 %%% End: