diff --git a/CHANGELOG.md b/CHANGELOG.md index 60c019b51..8b0acaf33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Reader-facing changes, newest first. The design is `docs/DESIGN.md`. ## Unreleased +- Fixed: in the PDF reader, a paragraph, a caption or a theorem holding an index entry, such as `word\index{word}`, or a colour given by a model, such as `\color[HTML]{3366AA}`, is translated. Such a paragraph had stayed in the original language. - Fixed: in the PDF reader, a citation's preview shows the entry the paper cites by its own key, such as `\cite{doe2020}` showing the entry written `\bibitem{doe2020}`: where the reader had taken the entry above or one in the other column for it, it now shows the right one, and where it cannot tell, it shows none and keeps the jump. A reference written in APA style (apacite), its authors in an environment of their own, is one entry: its preview had shown the authors alone. - Fixed: in the PDF reader, a heading the paper's class sets in capitals after storing its title, such as a numbered section of a REVTeX 4.0 paper, and a proof's title under thmtools, such as `\begin{proof}[Proof of Theorem 2]`, are translated as headings: the section keeps its number as printed, and a heading of two lines is one heading. The number had been sent to the translator as a word, and a two-line heading translated as two pieces. - Fixed: in the PDF reader, a paper that opens or closes a list, a box, a theorem or a displayed formula with a command of its own, such as `\ben` for `\begin{enumerate}` or `\ethm` for `\end{theorem}`, is translated paragraph by paragraph as printed, its formulas kept as printed. Such paragraphs had stayed in the original language, or run together with the formula's text sent to the translator. diff --git a/docs/PDF-READER.md b/docs/PDF-READER.md index 51bb008fb..5b14af8ca 100644 --- a/docs/PDF-READER.md +++ b/docs/PDF-READER.md @@ -10768,6 +10768,41 @@ body closed by a closing macro of its own sets the environment whole: no opener. `\begin{X}` than the environment's own arguments read whole by their declaration (an argument's prose, a table's arguments split with the source), and a display's opener whose end this reading does not find, are read as before. +### 18.120 What the marking reads as setting no ink, the instrument states empty (the coordinator's ruling of 2026-11-28, fix phase F4) + +The census's lay left paragraphs whole in the original (`unproven`, `lay/entry.ts`) for an element TeX sets no glyph for and the +marking knows it: an index entry, `word\index{word}`, in every paragraph, theorem and caption of a paper that indexes its terms, +and a colour given by a model, `\color[HTML]{3366AA}`. The marking (`marks/marks.ts` `classOf`) reads such a placeholder as +setting no ink by TeX's own tables and gives it no mark: one of TeX's and LaTeX's control words that set none (`INVISIBLE`: +`\index`, `\label`, `\color`, the phantoms, a skip, a kern), or one the role table proves can set no letters +(`source/arg-roles.ts` `textless`: a register's or a length's setting, a definition). With no mark it has no point, and no +compile states its places. The class table (`classesOf`) reads these two as `other`, a class drawn from its ink +(`locate/work.ts` `INKED_CLASSES`), so the locate found no ink for the element and nothing stated it empty, and the typesetter +read an inked element whose ink was not found (`lay/read.ts`). The instrument stated empty only a text macro of the marking's +null (a `.bbl`'s `\newblock`). + +**One classification for both readers** (`instrument/instrument.ts` `inklessPieces`): a placeholder the marking reads as setting +no ink (`INVISIBLE`, `textless`, read from its source as `classOf` reads it) is stated empty, whatever class the element carries, +where that class is one drawn from its ink; a class that draws none (a space, `zero`) reads no such statement. The locate then +states it `text: ''`, drawn as nothing, proven. Over the 245 no element moves; over the 599, 112 placeholders of 4 papers (an +`\index` 104, a `\color` with a model 8) in 65 units, and the 56 of those units the lay held `unproven` are laid; nothing else +moves. A `\color` at a table cell's head, which TeX sets before the cell's start, was stated as set outside the unit's text +(`El.keep`) and is now stated empty (the locate reads `empty` first): drawn as nothing either way. + +**What it protects.** `unproven` keeps out a unit whose element may set ink the text group erases and nothing draws again (a +formula, a year, an algorithm's line). These set none by TeX's definition, and only where the command is TeX's or LaTeX's: the +marking reads the name by its spelling, so a command the paper defines (`instrument/instrument.ts` `ownCommandsOf`: the source +reader's own reading of the paper's definitions, `\renewcommand{\index}[1]{\textdagger}`, `\let\index…`) is read by its +definition and is not stated empty, its call held unproven as before (stated empty, the dagger TeX sets would be erased with +the paragraph and drawn by nothing). One whose definition sets its argument is a span of text, no placeholder (§18.119). The +text macro of the marking's null stated empty before this item (a `.bbl`'s `\newblock`) is kept as it was: a class's own +`\newblock`, defined in the paper's files of many papers, sets no ink, and telling which definition sets ink is the +definition's reading, not this one's. None of the 56 units this item lays stands at a command its paper defines. Of the marking's +null the rest keep their statements: an alignment's tab, a stray brace, a parameter or a script mark (a table's rows read as +prose would be laid as prose over a table; a script mark in text sets a formula), and a forced break and a tie, which state +their own kinds. A paper's macro, a `\rule` the probe asks about, and a register's setting the source reader keeps with the +command after it (`\looseness=-1 \vspace`, read as a paper's macro) stay unproven where their ink is not found. + ## 19. The engine's contract **Today's engine and the rebuild's.** This chapter describes today's engine, `src/pdf-reader/engine/`, which our server diff --git a/lab/release-check/census-ledger.json b/lab/release-check/census-ledger.json index 6cea106e3..e5f3e8f5a 100644 --- a/lab/release-check/census-ledger.json +++ b/lab/release-check/census-ledger.json @@ -2,8 +2,8 @@ "format": "readarxiv/census-ledger 1", "about": "The census's ledger (this repository): the measures that may only fall or hold (lab/release-check/census-ratchet.mjs MEASURES), for the tree NOW and for AFTER (NOW less what the cut-over deletes), as the last integrated round measured them. Generated by `node lab/release-check/census.mjs --record`, never edited by hand; a value is raised only by `--record --raise= --reason=\"…\"`, kept below in `raises` with its reason and commit.", "recorded": { - "commit": "39a80a77e154a6b0ed098ecba40dc210c34767e4", - "at": "2026-11-27T21:25:56.029Z" + "commit": "1d69af5316d2f5a45be2e700ba9f536f090f0497", + "at": "2026-11-27T23:14:55.337Z" }, "trees": { "NOW": { @@ -21,7 +21,7 @@ "cycles": 7, "chains": 1, "gplReached": 3, - "productCode": 134711, + "productCode": 134733, "productModules": 744, "contentVersions": 9, "budgetsUnmeasured": 249, @@ -601,7 +601,7 @@ }, "productCode": { "extension": 19028, - "pkg:engine": 43599, + "pkg:engine": 43621, "pkg:format": 950, "pkg:reader": 18905, "pkg:text": 803, @@ -3869,6 +3869,15 @@ "reason": "ref-keys: a bibliography entry's key read by the source reader (bibKeyOf) and carried to the landing (targets.ts entryOfName, byKeyOf: a citation lands on its entry by the paper's own key, the point's rule its check); an environment written in an entry read inside the entry's unit (entryEnvironment). productCode +102.", "commit": "39a80a77e154a6b0ed098ecba40dc210c34767e4", "at": "2026-11-27T21:25:56.029Z" + }, + { + "tree": "NOW", + "measure": "productCode", + "from": 134711, + "to": 134733, + "reason": "lane f4-a (fix phase F4, PR-1, merged with the line f8c54a826): the instrument states empty every placeholder the marking reads as setting no ink (INVISIBLE, textless) of a class drawn from ink, never at a command the paper defines (ownCommandsOf); PDF-READER §18.120. productCode +22 over the line's ledger (pkg:engine: instrument/instrument.ts).", + "commit": "1d69af5316d2f5a45be2e700ba9f536f090f0497", + "at": "2026-11-27T23:14:55.337Z" } ] } diff --git a/packages/engine/src/instrument/instrument.ts b/packages/engine/src/instrument/instrument.ts index 980f0a7e1..df7be564b 100644 --- a/packages/engine/src/instrument/instrument.ts +++ b/packages/engine/src/instrument/instrument.ts @@ -33,6 +33,7 @@ import { import { groupFacts } from '../marks/faces.ts' import { holdsLetter } from '../locate/figure-lines.ts' import { isInk } from '../locate/lines.ts' +import { INKED_CLASSES } from '../locate/work.ts' import { linkTargetOf, unicodeOf } from '../locate/ink.ts' import { ownersOf, ROLE } from '../instrument.ts' import { readPdf } from '../read.ts' @@ -44,6 +45,7 @@ import { followsOf, headEnd, INK_ANY, + INVISIBLE, joinedRead, leadStep, probeFactsOf, @@ -54,7 +56,8 @@ import { } from '../marks/marks.ts' import { ownOf } from '../own/own.ts' import { READ_ALONE, regionsOf, WANT } from '../own/stream.ts' -import { BACKREF_LIST, forcedBreak, lastTexLog, startOf, statedGlue } from '../source/latex-front.ts' +import { BACKREF_LIST, forcedBreak, lastTexLog, startOf, statedGlue, texFilesOf } from '../source/latex-front.ts' +import { paperOf, textless } from '../source/arg-roles.ts' import { bundleUnitsOf } from './units.ts' import { phClass, texToText } from './layer1.ts' import { textPieceOf } from '../source/text-piece.ts' @@ -71,7 +74,7 @@ import type { PdfJs } from '../read.ts' import type { BlockCell } from './language.ts' import type { Ownership } from '../own/own.ts' import type { PieceLike } from '../marks/marks.ts' -import type { OpenPiece, PhPiece, SourcePiece, SourceUnit } from '../source/latex-front.ts' +import type { Fsys, OpenPiece, PhPiece, SourcePiece, SourceUnit } from '../source/latex-front.ts' import type { DocGlyph } from '../doc.ts' // ---------------------------------------------------------------- the types of what the adapter reads and states @@ -145,6 +148,9 @@ export type InstrumentPaper = { pseudocode?: readonly number[] tableBlocks?: readonly (readonly BlockCell[])[] theoremNames?: readonly string[] | null + /** its files and its main file (compile/live.ts openPaper's): the commands it defines are read from them (ownCommandsOf) */ + fsys?: Fsys + meta?: { main?: string | null } } /** instrumentOf's input: the paper, our marked final pass's bytes, the marks file's options, the marked compile's last log, * PDF.js and its document options, and what made it */ @@ -1262,17 +1268,39 @@ export function placesOf( return places } +/** the commands a paper's files define (source/arg-roles.ts paperOf over its TeX files, the source reader's own reading: \\newcommand's + * and \\def's families, \\let, …), or null where its files are not given */ +export function ownCommandsOf(paper: InstrumentPaper): { has(name: string): boolean } | null { + const main = paper.meta?.main + return paper.fsys && main ? paperOf(texFilesOf(paper.fsys, main)).own : null +} + /** The pieces whose span the instrument states empty, TeX setting no ink for them where they stand, by unit index and piece - * id: a paper's macro the marking's probe said sets none (its `inkless`, to which the marking gives no point); and a text - * macro (classesOf's macro or umacro) the marking never marks, its rendering never ink by the marking's own reading (marks.ts - * classOf null: INVISIBLE, STRUCTURE, textless; a .bbl's \newblock, \ttfamily, \sloppy), whose places therefore no compile - * states. Stated empty, such a piece is drawn as nothing, proven (El.text ''); stated nothing, the typesetter leaves its - * unit unproven (a paper's own macro of no stated ink and no text: lay/read.ts), every BibTeX entry English. `units` the - * source units, `classes` each - * unit's classesOf by piece id */ + * id: a paper's macro the marking's probe said sets none (its `inkless`, to which the marking gives no point); and an element + * the marking reads as setting no ink by TeX's own tables, to which it gives no mark (marks.ts classOf null: one of TeX's and + * LaTeX's control words that set none, INVISIBLE: `\\index`, `\\color`, `\\label`, a skip, a .bbl's \\newblock, \\ttfamily, + * \\sloppy; or one the role table proves can set no letters, source/arg-roles.ts textless: a register's or a length's setting), + * whose places therefore no compile states, whatever class the element carries: one classification for both readers. Where + * its class is one the reading draws from its ink (locate/work.ts INKED_CLASSES: an `\\index{…}` or a `\\color[HTML]{…}` the + * class table reads as `other`, a text macro), stated empty it is drawn as nothing, proven (El.text ''); stated nothing, the + * typesetter left its unit unproven (an inked element of no found ink and no text: lay/read.ts), the original's: every + * BibTeX entry English, every paragraph holding an index entry. Of the marking's null, not an alignment's tab, a stray brace, + * a parameter or a script mark (STRUCTURE): a table's rows read as prose would then be laid as prose over a table, and a + * script mark in text sets a formula; nor a forced break (a space's class, which states its own kind). A class that draws no + * ink (a space, `zero`) reads no such statement: those are left out. The marking reads the name by its spelling: a command + * the paper defines (`own`, ownCommandsOf: `\\renewcommand{\\index}[1]{\\textdagger}`, its call still a placeholder) is read by + * its definition, which may set ink the paragraph's text range then holds, erased with the text and drawn by nothing were it + * stated empty; none such is stated, and with `own` not given none of this reading is made. (The text macro of the marking's + * null, the statement made before this one, is kept as it was: a class's own `\\newblock` is defined in the paper's files of + * many papers and sets no ink; telling which definition sets ink is the definition's reading, not this one's.) `units` the + * source units, `classes` each unit's classesOf by piece id, `own` the commands the paper defines */ export function inklessPieces( units: readonly Unit[], - { classes, inkless = null }: { classes: ClassesBy; inkless?: readonly string[] | null }, + { + classes, + inkless = null, + own = null, + }: { classes: ClassesBy; inkless?: readonly string[] | null; own?: { has(name: string): boolean } | null }, ): PieceRef[] { const noInk: ReadonlySet = new Set(inkless ?? []) const out: PieceRef[] = [] @@ -1282,7 +1310,20 @@ export function inklessPieces( if (p.t !== 'ph') return const marked = classOf(p), cls = classes[i]?.get(String(k))?.cls - if ((marked === 'macro' && noInk.has(p.src)) || (marked === null && (cls === 'macro' || cls === 'umacro'))) + // (the marking's reading of no ink, as classOf reads it: its source alone, its spelling. It holds only for a command the + // paper does not define: one the paper defines (`own`) is read by its definition, which the spelling does not tell, so + // its statement is not made. With `own` unknown, none of this reading is made) + const cmd = /^\\([A-Za-z@]+)/.exec(p.src ?? '')?.[1] + const noInkRead = + marked === null && + own !== null && + !(cmd !== undefined && own.has(cmd)) && + (INVISIBLE.test(p.src ?? '') || textless(p.src ?? '')) + if ( + (marked === 'macro' && noInk.has(p.src)) || + (marked === null && (cls === 'macro' || cls === 'umacro')) || + (noInkRead && cls !== undefined && INKED_CLASSES.has(cls)) + ) out.push({ unit: i, piece: String(k) }) }), ) @@ -2546,7 +2587,7 @@ export async function instrumentOf({ // (the pieces TeX sets no ink for (inklessPieces), and those TeX's points prove set nothing of their own (boundedEmpty): their // span stated empty, by unit index and piece id) // (and the pairs' tail arguments TeX's tail samples answered set nothing: probeFactsOf's `tails`, marks.ts tailsSettingNothing) - const empty = inklessPieces(units, { classes: classesBy, inkless }) + const empty = inklessPieces(units, { classes: classesBy, inkless, own: ownCommandsOf(paper) }) const stated = new Set(empty.map((x) => `${x.unit}|${x.piece}`)) // (and the placeholders TeX joined to the macro before them, marks.ts joinedPieces: their ink is that macro's, read through by // its opening point, and they set nothing apart from it) diff --git a/packages/engine/tests/every-element-stated.test.ts b/packages/engine/tests/every-element-stated.test.ts new file mode 100644 index 000000000..568dc09d9 --- /dev/null +++ b/packages/engine/tests/every-element-stated.test.ts @@ -0,0 +1,141 @@ +// An element TeX sets no ink for, by the marking's own reading, is stated empty by the instrument too. The marking (marks.ts +// classOf) gives no mark to a placeholder it reads as setting no ink by TeX's own tables: one of TeX's and LaTeX's control words +// that set none (INVISIBLE: `\index`, `\label`, `\color`, the phantoms, a skip, a kern…) or one the role table proves can set no +// letters (source/arg-roles.ts textless: a register's or a length's setting, a definition). Such a piece has no point, so no +// compile states its places. Where the element's class is one the reading draws from its ink (an `\index{…}` or a +// `\color[HTML]{…}` the class table reads as `other`), the instrument stated it nothing: its element was neither found nor +// stated empty, and the typesetter left its unit unproven, the original's (lay/read.ts: an inked element whose ink was not +// found may have been erased with the text and drawn by nothing). The instrument read only a text macro of the marking's null +// so (inklessPieces). One classification for both readers now: what the marking reads as setting no ink is stated empty, +// whatever class the element carries. What `unproven` protects is untouched: a paper's own macro, a formula, a rule the +// probe asks about, an alignment's tab (a table's rows read as prose, laid as prose over a table) keep their statements. +// Content of our own, through the source reader (openPaper) and the instrument's own reading of its units (classesOf, +// inklessPieces), as instrumentOf calls them. +import { describe, expect, it } from 'vitest' +import { openPaper } from '../src/compile/live.ts' +import { classesOf, elementKindOf, inklessPieces } from '../src/instrument/instrument.ts' +import { classOf } from '../src/marks/marks.ts' +import { paperOf } from '../src/source/arg-roles.ts' +import { texFilesOf } from '../src/source/latex-front.ts' + +const enc = (s: string) => new TextEncoder().encode(s) +type Ph = { t: string; s?: string; src?: string } +/** a document's units, each unit's classes as the instrument reads them, and the pieces it states empty (by `unit|piece`) */ +function stated(body: string, preamble = '') { + const paper = openPaper( + new Map([['main.tex', enc(`\\documentclass{article}\n${preamble}\\begin{document}\n${body}\n\\end{document}\n`)]]), + ) + const units = paper.units as { kind: string; pieces: Ph[] }[] + const classes = units.map((u) => new Map(classesOf(u.pieces as never))) + // (the commands the paper defines, as the source reader reads them: what instrumentOf hands inklessPieces) + const own = paperOf(texFilesOf(paper.fsys, paper.meta.main!)).own + const empty = new Set( + inklessPieces(units as never, { classes: classes as never, own }).map((x) => `${x.unit}|${x.piece}`), + ) + /** the placeholder whose source begins so, in the first unit holding one: its class, kind and whether it is stated empty */ + const at = (begins: string) => { + for (const [i, u] of units.entries()) { + const k = u.pieces.findIndex((p) => p.t === 'ph' && (p.src ?? '').startsWith(begins)) + if (k < 0) continue + const p = u.pieces[k]! + return { + marking: classOf(p as never), + cls: classes[i]!.get(String(k))?.cls, + kind: elementKindOf(p as never), + empty: empty.has(`${i}|${k}`), + } + } + return null + } + return { units, at } +} +const WORDS = 'Our own words of a paragraph, long enough to be a unit of its own,' + +describe('an element the marking reads as setting no ink is stated empty by the instrument', () => { + it('an \\index in a paragraph is stated empty', () => { + const r = stated( + `${WORDS} with an entry\\index{entry!of ours} in it and more words after it.`, + '\\usepackage{makeidx}\n', + ) + expect(r.at('\\index')).toMatchObject({ marking: null, cls: 'other', empty: true }) + }) + + it('a \\color declaration with a model in a paragraph is stated empty', () => { + const r = stated( + `${WORDS} {\\color[HTML]{3366AA} red words of ours} and more words after it.`, + '\\usepackage{xcolor}\n', + ) + expect(r.at('\\color')).toMatchObject({ marking: null, cls: 'other', empty: true }) + }) + + it('a \\color declaration the class table reads as setting nothing (`zero`, a class drawn from no ink) is stated nothing: no reading needs it', () => { + const r = stated(`${WORDS} {\\color{red} red words of ours} and more words after it.`, '\\usepackage{xcolor}\n') + expect(r.at('\\color')).toMatchObject({ marking: null, cls: 'zero', empty: false }) + }) +}) + +describe('what keeps its statement (controls)', () => { + it('a paper’s macro of no found ink is not stated empty: TeX may set glyphs for it, which only its probe tells', () => { + const r = stated(`${WORDS} with our \\sys{} in it and more words after it.`, '\\newcommand{\\sys}{SysName}\n') + expect(r.at('\\sys')).toMatchObject({ marking: 'macro', empty: false }) + }) + + it('an alignment tab is not stated empty: a table read as prose would be laid as prose over a table', () => { + const r = stated( + '\\begin{deluxetable}{lc}\n\\startdata\nOur own words in a row & 12 \\\\\nMore words in a row & 13\n\\enddata\n\\end{deluxetable}', + '\\newenvironment{deluxetable}[1]{}{}\\newcommand{\\startdata}{}\\newcommand{\\enddata}{}\n', + ) + expect(r.at('&')).toMatchObject({ marking: null, cls: 'other', empty: false }) + }) + + it('a \\rule in a box stays asked: TeX’s ink section says whether it is a strut or a bar', () => { + const r = stated(`${WORDS} with a square \\mbox{\\rule{1ex}{1ex}} of ours and more words after it.`) + expect(r.at('\\rule')).toMatchObject({ marking: 'macro', empty: false }) + }) + + it('a tie and a forced break keep their kinds', () => { + const r = stated(`${WORDS} with a tie~here and a break\\\\ there and more words after it.`) + expect(r.at('~')).toMatchObject({ kind: 'space', cls: 'space', empty: false }) + expect(r.at('\\\\')).toMatchObject({ kind: 'break', empty: false }) + }) + + it('an \\index the paper defines to print a mark (its argument unused: still a placeholder) is not stated empty', () => { + // (the marking reads `\\index` by its spelling and gives it no mark; TeX sets the dagger. Stated empty, the paragraph would + // be laid and the dagger, in its text's range, erased with it and drawn by nothing: the paper's own command is read by its + // definition, never by its spelling) + const r = stated( + `${WORDS} with an entry\\index{entry} in it and more words after it.`, + '\\renewcommand{\\index}[1]{\\textdagger}\n', + ) + expect(r.at('\\index')).toMatchObject({ marking: null, cls: 'other', empty: false }) + const s = stated( + `${WORDS} with an entry\\index{entry} in it and more words after it.`, + '\\let\\index\\textdagger\n', + ) + expect(s.at('\\index')).toMatchObject({ empty: false }) + }) + + it('a command of the role table’s textless kind the paper defines to print a mark is not stated empty', () => { + const r = stated( + `${WORDS} with a counter\\setcounter{x}{2} in it and more words after it.`, + '\\newcounter{x}\\renewcommand{\\setcounter}[2]{\\textdagger}\n', + ) + expect(r.at('\\setcounter')).toMatchObject({ empty: false }) + }) + + it('a paper’s own \\index that sets its argument is no placeholder: its words are the unit’s text', () => { + const r = stated( + `${WORDS} with an entry\\index{shown} in it and more words after it.`, + '\\renewcommand{\\index}[1]{#1}\n', + ) + expect(r.at('\\index')).toBeNull() + }) + + it('a register’s setting the marking reads as a paper’s macro (a skip read with it) is not stated empty', () => { + // (the source reader keeps `\looseness=-1 \vspace` one placeholder: the marking reads it as a macro, asked, not as textless) + const r = stated( + `${WORDS} and more words after it.\\looseness=-1 \\vspace{1pt}\n\nAnother paragraph of ours, long enough.`, + ) + expect(r.at('\\looseness')).toMatchObject({ marking: 'macro', empty: false }) + }) +}) diff --git a/tests/pdf-reader/every-element-stated-tex.test.ts b/tests/pdf-reader/every-element-stated-tex.test.ts new file mode 100644 index 000000000..8a1c97f63 --- /dev/null +++ b/tests/pdf-reader/every-element-stated-tex.test.ts @@ -0,0 +1,151 @@ +// @vitest-environment node +import { execFileSync, spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { getDocument, OPS } from 'pdfjs-dist/legacy/build/pdf.mjs' +import { describe, expect, it } from 'vitest' +import { openPaper } from '../../packages/engine/src/compile/live.ts' +import { markedOfPaper } from '../../packages/engine/src/compile/paper.ts' +import { instrumentOf } from '../../packages/engine/src/instrument/instrument.ts' +import { compileImageRef } from '../../lab/pdf/spikes/compile-image.mjs' +import { DOCUMENT_OPTIONS } from './helpers/ocg-pdfs' + +// An element the marking reads as setting no ink (marks.ts classOf null: INVISIBLE, textless) is stated empty by the instrument +// (instrument/instrument.ts inklessPieces), whatever class the element carries: an `\index{…}` and a `\color[HTML]{…}` the +// class table reads as `other`, an inked class, which the instrument stated nothing and the typesetter therefore left unproven. +// Asked of TeX itself, in the pinned TeX Live image, offline, on content of our own: the marked original as the prepare makes +// it (markedOfPaper), its instrument (instrumentOf) states the two pieces empty; and TeX sets no glyph for them, the paper's +// own compile with them and without them setting the same text items in the same places (what "stated empty" claims: their +// unit drawn with nothing in their place loses no ink of the original's) + +const IMAGE = compileImageRef() +const docker = spawnSync('docker', ['image', 'inspect', IMAGE], { stdio: 'ignore' }).status === 0 +type Compiled = { ok: boolean; pdf: Uint8Array | null; log: string; aux: string | null; bbl: null; ms: number } +type Request = { main: string; overrides: Map } +/** a compile in the image: the files given, pdflatex three times */ +function compileIn(files: ReadonlyMap, main = 'main.tex', passes = 3): Compiled { + const dir = mkdtempSync(join(tmpdir(), 'axt-stated-')) + try { + for (const [p, b] of files) { + mkdirSync(dirname(join(dir, p)), { recursive: true }) + writeFileSync(join(dir, p), b) + } + for (let pass = 0; pass < passes; pass++) { + // (each pass's PDF its own: one a pass that dies leaves behind is never read as the run's) + rmSync(join(dir, main.replace(/\.tex$/, '.pdf')), { force: true }) + try { + execFileSync('docker', ['run', '--rm', '--network', 'none', '-v', `${dir}:/work`, '-w', '/work', IMAGE, 'pdflatex', '-interaction=nonstopmode', main], { stdio: 'pipe', timeout: 300_000 }) + } catch { + /* errors are the log's */ + } + } + const stem = main.replace(/\.tex$/, '') + const read = (f: string) => { + try { + return readFileSync(join(dir, f)) + } catch { + return null + } + } + const pdf = read(`${stem}.pdf`) + return { ok: !!pdf, pdf: pdf ? new Uint8Array(pdf) : null, log: read(`${stem}.log`)?.toString('latin1') ?? '', aux: read(`${stem}.aux`)?.toString('latin1') ?? null, bbl: null, ms: 1 } + } finally { + rmSync(dir, { recursive: true, force: true }) + } +} +/** every text item of a PDF, its text and its place, by page */ +const itemsOf = async (pdf: Uint8Array) => { + const doc = await getDocument({ data: pdf.slice(), verbosity: 0 }).promise + const out: string[] = [] + for (let n = 1; n <= doc.numPages; n++) + for (const it of (await (await doc.getPage(n)).getTextContent()).items as { str: string; transform: number[] }[]) + if (it.str.trim()) out.push(`${n} ${it.transform[4]?.toFixed(2)} ${it.transform[5]?.toFixed(2)} ${it.str}`) + await doc.loadingTask.destroy() + return out +} +const enc = (s: string) => new TextEncoder().encode(s) +const doc = (body: string) => + [ + '\\documentclass{article}', + '\\usepackage{xcolor}', + '\\usepackage{makeidx}', + '\\makeindex', + '\\begin{document}', + body, + '\\end{document}', + ].join('\n') +const WITH = + 'Our own words of a first paragraph, with an entry\\index{entry!of ours} standing in it, and more words of ours after it to fill the line out and go on.\n\n' + + 'Our own words of a second paragraph, {\\color[HTML]{3366AA} some words of ours in a colour} and more words of ours after them to fill the line.' +const WITHOUT = WITH.replace('\\index{entry!of ours}', '').replace('\\color[HTML]{3366AA} ', '') + +/** a document of ours as the prepare marks it (markedOfPaper) and its instrument (instrumentOf): the pieces it states empty, and + * the unit and piece of the placeholder whose source begins so */ +async function stated(tex: string) { + const files = new Map([['main.tex', enc(tex)]]) + const paper = openPaper(files) + const compiles: Compiled[] = [] + const compile = async ({ main, overrides }: Request) => { + const c = compileIn(new Map([...files, ...overrides]), main) + compiles.push(c) + return c + } + const made = await markedOfPaper(paper, { compile: compile as never, final: false }) + if (!('pdf' in made) || !made.pdf) throw new Error(`no marked original: ${JSON.stringify(made).slice(0, 300)}`) + const pdf = made.pdf as Uint8Array + const last = compiles.find((c) => c.pdf && c.pdf.length === pdf.length && c.pdf.every((b, i) => b === pdf[i])) + const m = made as { options?: Record; probeLog?: string } + const { instrument } = await instrumentOf({ + paper: paper as never, + finalPdf: pdf, + options: m.options ?? {}, + log: last?.log ?? '', + probeLog: m.probeLog ?? null, + pdfjs: { getDocument, OPS } as never, + documentOptions: DOCUMENT_OPTIONS, + made: { compiler: 'pdflatex', tree: '2025', front: 'today' }, + }) + const empty = new Set((instrument.empty ?? []).map((x) => `${x.unit}|${x.piece}`)) + /** the unit and piece of the placeholder whose source begins so */ + const where = (begins: string) => { + for (const [i, u] of paper.units.entries()) { + const k = (u.pieces as { t: string; src?: string }[]).findIndex((p) => p.t === 'ph' && (p.src ?? '').startsWith(begins)) + if (k >= 0) return `${i}|${k}` + } + return null + } + return { files, empty, where } +} + +describe.skipIf(!docker)('an element TeX sets no ink for, by the marking’s own reading, stated empty', () => { + it('an \\index and a \\color with a model: stated empty by the instrument, and TeX sets no glyph for them', async () => { + const { files, empty, where } = await stated(doc(WITH)) + expect(where('\\index')).not.toBeNull() + expect(where('\\color[HTML]')).not.toBeNull() + expect(empty.has(where('\\index')!)).toBe(true) + expect(empty.has(where('\\color[HTML]')!)).toBe(true) + // (TeX's own: the paper's compile with them and without them sets the same text items in the same places) + const own = compileIn(files) + const bare = compileIn(new Map([['main.tex', enc(doc(WITHOUT))]])) + expect(own.ok && bare.ok).toBe(true) + expect(await itemsOf(own.pdf!)).toEqual(await itemsOf(bare.pdf!)) + }, 900_000) + + it('an \\index the paper defines to print a mark: TeX sets it, and the instrument does not state it empty', async () => { + // (the marking reads `\\index` by its spelling and gives it no mark; stated empty, the paragraph would be laid and the + // dagger TeX set, in its text's range, erased with the text and drawn by nothing) + const own = '\\renewcommand{\\index}[1]{\\textdagger}\n' + const body = 'Our own words of a paragraph, with an entry\\index{entry} standing in it, and more words of ours after it to fill the line out.' + const tex = doc(body).replace('\\begin{document}', `${own}\\begin{document}`) + const { files, empty, where } = await stated(tex) + expect(where('\\index')).not.toBeNull() + expect(empty.has(where('\\index')!)).toBe(false) + // (TeX's own: the call sets a glyph, the dagger, which the text without it does not hold) + const withIt = compileIn(files) + const without = compileIn(new Map([['main.tex', enc(tex.replace('\\index{entry}', ''))]])) + expect(withIt.ok && without.ok).toBe(true) + expect((await itemsOf(withIt.pdf!)).join(' ')).toContain('\u2020') + expect((await itemsOf(without.pdf!)).join(' ')).not.toContain('\u2020') + }, 900_000) +})