kakemono 0.24.2

Convert PDF, Word, Excel, PowerPoint and EPUB documents and web pages to HTML, Markdown, EPUB, LaTeX and JSON in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Code in the friendly mode: listings (monospaced text set as a block, with
//! optional syntax colour) and algorithms rebuilt as text from the text
//! layer of their float.

mod highlight;

use super::*;
use crate::model::{HLine, Line, MONO, Span};
use highlight::{Carry, Lang, detect, highlight_line};

/// Width of a monospaced character in em, for fonts whose glyph widths
/// cannot be measured (Courier and most code fonts).
const MONO_ADVANCE_EM: f32 = 0.6;
/// A gap of more than this many line pitches between two lines of code is
/// an empty line of the listing.
const BLANK_LINE_MIN_PITCHES: f32 = 1.6;
/// Lines of a listing that start less than this apart (in font sizes) are
/// at the same indentation level.
const INDENT_LEVEL_TOLERANCE_EM: f32 = 0.4;
/// Line pitch assumed for a listing of one line, in em of its font size.
const LONE_LINE_PITCH_EM: f32 = 1.2;
/// Listings with at least this many lines get line numbers.
const NUMBERED_MIN_LINES: usize = 5;
/// Fewest lines of an algorithm rebuilt as text.
const ALGORITHM_MIN_LINES: usize = 3;
/// Lines whose x positions differ by less than this (points) are at the
/// same indentation level.
const INDENT_TOLERANCE_PT: f32 = 2.0;
/// Deepest indentation class of an algorithm line (`in3`).
const ALGORITHM_MAX_INDENT: usize = 3;
/// A line of an algorithm with at most this many characters (a radical
/// sign drawn apart) is merged into the line beside it.
const ORPHAN_MAX_CHARS: usize = 2;
/// Words that start the first line of an algorithm written as pseudocode.
const ALGORITHM_OPENERS: [&str; 12] = [
    "Require",
    "Ensure",
    "Input",
    "Output",
    "Initialize",
    "Initialise",
    "procedure",
    "function",
    "for",
    "while",
    "repeat",
    "Data",
];
/// Words that start a control line of pseudocode (`repeat`, `until`, ...).
const ALGORITHM_CONTROL_WORDS: [&str; 10] = [
    "repeat", "until", "for", "while", "if", "else", "end", "return", "do", "loop",
];
/// Assignment signs of pseudocode.
const ALGORITHM_ASSIGNMENTS: [&str; 2] = ["\u{2190}", ":="];
/// Words of the unnumbered header lines of an algorithm (inputs, outputs).
const ALGORITHM_HEADERS: [&str; 5] = ["Require", "Ensure", "Input", "Output", "Data"];

/// Whether `block` is a code listing found by the analysis, or a paragraph
/// set entirely in a monospaced font (a piece of code), apart from spaces.
pub(crate) fn is_code_paragraph(block: &Block) -> bool {
    if matches!(block.kind, BlockKind::Code) {
        return block.hlines.len() == block.lines.len();
    }
    matches!(block.kind, BlockKind::Paragraph { in_abstract: false })
        && block.spans.iter().any(|span| !span.text.trim().is_empty())
        && block
            .spans
            .iter()
            .all(|span| span.style & MONO != 0 || span.text.trim().is_empty())
        && block.hlines.len() == block.lines.len()
}

/// The lines of code of consecutive code paragraphs, with their
/// indentation rebuilt from the positions of the lines. An empty line is
/// kept where the gap between two lines is more than
/// [`BLANK_LINE_MIN_PITCHES`] line pitches.
///
/// Code set in two columns (side by side, or running on from one column to
/// the next) is indented column by column, each part from its own left
/// edge: a part starts where a line lies wholly right (or left) of all the
/// lines of the part before it.
///
/// A listing of a document without pages (Word, EPUB) has no lines: its
/// rows are its lines, with their own indentation.
pub(crate) fn listing_lines(blocks: &[&Block]) -> Vec<String> {
    if blocks.iter().all(|block| block.lines.is_empty()) {
        return blocks
            .iter()
            .flat_map(|block| &block.rows)
            .map(|row| row.iter().map(|span| span.text.as_str()).collect())
            .collect();
    }
    let pitch = line_pitch(blocks);
    let mut parts: Vec<Vec<(&Line, &HLine)>> = Vec::new();
    // The left and right ends of the current part's lines on their page.
    let mut hull: Option<(usize, f32, f32)> = None;
    for block in blocks {
        for (line, hline) in block.lines.iter().zip(&block.hlines) {
            // On a new page too: the code goes on in the same column, or
            // it moved (from the right column to the left one of the next
            // page).
            let moves = hull.is_some_and(|(_, x0, x1)| line.bbox.x0 >= x1 || line.bbox.x1 <= x0);
            match parts.last_mut() {
                Some(part) if !moves => part.push((line, hline)),
                _ => parts.push(vec![(line, hline)]),
            }
            hull = Some(match hull {
                Some((page, x0, x1)) if !moves && page == line.page => {
                    (page, x0.min(line.bbox.x0), x1.max(line.bbox.x1))
                }
                _ => (line.page, line.bbox.x0, line.bbox.x1),
            });
        }
    }
    parts.iter().flat_map(|part| part_lines(part, pitch)).collect()
}

/// The text of the lines of one column of a listing, indented from its
/// left edge.
fn part_lines(part: &[(&Line, &HLine)], pitch: f32) -> Vec<String> {
    let all: Vec<&Line> = part.iter().map(|(line, _)| *line).collect();
    let starts = indent_starts(&all);
    let base = starts.first().copied().unwrap_or(0.0);
    let width = listing_char_width(&all);
    let mut lines = Vec::new();
    let mut previous: Option<&Line> = None;
    for (line, hline) in part {
        if let Some(prev) = previous
            && prev.page == line.page
            && line.baseline - prev.baseline > BLANK_LINE_MIN_PITCHES * pitch
        {
            lines.push(String::new());
        }
        let mut text: String = hline.spans.iter().map(|span| span.text.as_str()).collect();
        if text.ends_with(' ') {
            text.pop();
        }
        if hline.soft_hyphen {
            text.push('-');
        }
        let start = indent_start(&starts, line.bbox.x0);
        let indent = ((start - base) / width).round().max(0.0) as usize;
        lines.push(format!("{}{}", " ".repeat(indent), text.trim_start()));
        previous = Some(line);
    }
    lines
}

/// The usual distance between consecutive baselines of code lines (the
/// smallest one on a page), or 1.2 times the font size when there is a
/// single line.
fn line_pitch(blocks: &[&Block]) -> f32 {
    let lines: Vec<&Line> = blocks.iter().flat_map(|block| block.lines.iter()).collect();
    lines
        .windows(2)
        .filter(|pair| pair[0].page == pair[1].page)
        .map(|pair| pair[1].baseline - pair[0].baseline)
        .filter(|pitch| *pitch > 0.0)
        .fold(f32::INFINITY, f32::min)
        .min(
            lines
                .first()
                .map_or(f32::INFINITY, |line| LONE_LINE_PITCH_EM * line.size),
        )
}

/// The lines of a float whose text is all monospaced (a listing set as a
/// float), with their indentation, or `None` when some of its text is not
/// monospaced.
pub(crate) fn float_listing_lines(block: &Block) -> Option<Vec<String>> {
    let spans = &block.inner_spans;
    let mono = spans
        .iter()
        .flatten()
        .all(|span| span.style & MONO != 0 || span.text.trim().is_empty());
    if block.inner_lines.len() < 2 || !mono {
        return None;
    }
    let base = block
        .inner_lines
        .iter()
        .map(|line| line.bbox.x0)
        .fold(f32::INFINITY, f32::min);
    Some(
        block
            .inner_lines
            .iter()
            .zip(spans)
            .map(|(line, line_spans)| {
                let text: String = line_spans.iter().map(|span| span.text.as_str()).collect();
                let indent = ((line.bbox.x0 - base) / char_width(line)).round().max(0.0) as usize;
                format!("{}{}", " ".repeat(indent), text.trim())
            })
            .collect(),
    )
}

/// The left edges at which the lines of a listing start, one per
/// indentation level: edges within [`INDENT_LEVEL_TOLERANCE_EM`] of each
/// other are one level (code set on fixed columns in a proportional font
/// starts its lines a little apart), represented by the leftmost.
fn indent_starts(lines: &[&Line]) -> Vec<f32> {
    let mut edges: Vec<(f32, f32)> = lines.iter().map(|line| (line.bbox.x0, line.size)).collect();
    edges.sort_by(|a, b| a.0.total_cmp(&b.0));
    let mut starts: Vec<f32> = Vec::new();
    let mut last = f32::NEG_INFINITY;
    for (edge, size) in edges {
        if edge - last > INDENT_LEVEL_TOLERANCE_EM * size {
            starts.push(edge);
        }
        last = edge;
    }
    starts
}

/// The indentation level (its start) of a line starting at `x0`.
fn indent_start(starts: &[f32], x0: f32) -> f32 {
    starts.iter().rev().find(|start| **start <= x0).copied().unwrap_or(x0)
}

/// The advance of one character of a listing, in points: the median over
/// all its lines, so that every line is indented on the same columns.
fn listing_char_width(lines: &[&Line]) -> f32 {
    let mut widths: Vec<f32> = lines
        .iter()
        .flat_map(|line| line.glyphs.iter())
        .filter(|glyph| glyph.text.chars().count() == 1)
        .map(|glyph| glyph.x1 - glyph.x0)
        .filter(|width| *width > 0.0)
        .collect();
    widths.sort_by(f32::total_cmp);
    widths
        .get(widths.len() / 2)
        .copied()
        .unwrap_or_else(|| MONO_ADVANCE_EM * lines.first().map_or(1.0, |line| line.size.max(1.0)))
}

/// The advance of one character of a monospaced line, in points.
fn char_width(line: &Line) -> f32 {
    let mut widths: Vec<f32> = line
        .glyphs
        .iter()
        .filter(|glyph| glyph.text.chars().count() == 1)
        .map(|glyph| glyph.x1 - glyph.x0)
        .filter(|width| *width > 0.0)
        .collect();
    widths.sort_by(f32::total_cmp);
    widths
        .get(widths.len() / 2)
        .copied()
        .unwrap_or(MONO_ADVANCE_EM * line.size.max(1.0))
}

/// A code listing: an optional caption, the Colour and Copy buttons, and
/// the lines in a `<pre class="listing">`, coloured when the language was
/// recognised with confidence (otherwise only strings, comments and
/// numbers are marked, and shown plain unless the reader asks for colour).
pub(crate) fn listing_html(lines: &[String], caption: &str, id: &str) -> String {
    let code = lines.join("\n");
    let (lang, confident) = detect(&code);
    let lang = if confident { lang } else { Lang::Generic };
    let mut carry = Carry::None;
    let body: String = lines
        .iter()
        .map(|line| format!("<span class=\"l\">{}</span>", highlight_line(line, lang, &mut carry)))
        .collect();
    let mut classes = String::from("listing");
    if lines.len() >= NUMBERED_MIN_LINES {
        classes.push_str(" numbered");
    }
    if confident {
        classes.push_str(" hl");
    }
    let caption = if caption.is_empty() {
        String::new()
    } else {
        format!("<figcaption>{caption}</figcaption>")
    };
    format!(
        "<figure class=\"code\"{id}><div class=\"code-head\">{caption}<div class=\"code-tools\">\
<button class=\"btn code-hl\" type=\"button\" aria-pressed=\"{confident}\" aria-label=\"Colour code\">Colour</button>\
<button class=\"btn code-copy\" type=\"button\" aria-label=\"Copy code\"><span class=\"cp\">Copy</span><span class=\"ok\">Copied</span></button>\
</div></div><div class=\"code-box\"><pre class=\"{classes}\" tabindex=\"0\" data-lang=\"{}\" translate=\"no\"><code>{body}</code></pre></div></figure>\n",
        lang_name(lang)
    )
}

/// The name of a language for the `data-lang` attribute.
fn lang_name(lang: Lang) -> &'static str {
    match lang {
        Lang::Python => "python",
        Lang::CFamily => "c",
        Lang::JavaScript => "javascript",
        Lang::Go => "go",
        Lang::Rust => "rust",
        Lang::Generic => "text",
    }
}

/// One line of an algorithm float.
struct AlgoLine {
    /// Styled text of the line.
    spans: Vec<Span>,
    /// The source line (position and glyphs).
    line: Line,
}

/// The algorithm of a float rebuilt as text (`<div class="algo">`), when
/// its text layer reads as pseudocode: at least [`ALGORITHM_MIN_LINES`]
/// lines, the first one starting with one of [`ALGORITHM_OPENERS`] or a
/// line number, or else lines that assign (`x ← ...`) and lines of control
/// (`repeat`, `return`, ...). `None` otherwise (the float keeps its
/// picture).
pub(crate) fn algorithm_html(block: &Block) -> Option<String> {
    let mut lines: Vec<AlgoLine> = block
        .inner_lines
        .iter()
        .zip(&block.inner_spans)
        .map(|(line, spans)| AlgoLine {
            spans: spans.clone(),
            line: line.clone(),
        })
        .collect();
    merge_orphans(&mut lines);
    lines.retain(|algo| !plain(&algo.spans).is_empty());
    let texts: Vec<String> = lines.iter().map(|algo| plain(&algo.spans)).collect();
    if lines.len() < ALGORITHM_MIN_LINES || !reads_as_pseudocode(&texts) {
        return None;
    }
    let levels = indent_levels(&lines);
    let mut out = String::from("<div class=\"algo\">");
    let mut number = 0;
    for (algo, level) in lines.iter().zip(levels) {
        let text = plain(&algo.spans);
        let header = ALGORITHM_HEADERS.iter().any(|word| text.starts_with(word));
        let (statement, comment) = split_comment(&algo.spans, &text);
        let num = if header {
            String::new()
        } else {
            number += 1;
            number.to_string()
        };
        let cmt = comment
            .map(|spans| format!("<span class=\"cmt\">{}</span>", spans_html(&spans)))
            .unwrap_or_default();
        out.push_str(&format!(
            "<div class=\"ln{}\"><i>{num}</i><div class=\"st in{level}\"><span>{}</span>{cmt}</div></div>",
            if header { " req" } else { "" },
            spans_html(&statement)
        ));
    }
    out.push_str("</div>");
    Some(out)
}

/// Whether the lines of a float (their text) read as pseudocode: the
/// first one opens an algorithm, or some line assigns and some line starts
/// with a control word ("θ, φ ← Initialize parameters", "repeat", ...,
/// "return θ, φ").
fn reads_as_pseudocode(texts: &[String]) -> bool {
    let assigns = texts
        .iter()
        .any(|text| ALGORITHM_ASSIGNMENTS.iter().any(|sign| text.contains(sign)));
    let controls = texts.iter().any(|text| {
        let word: String = text.trim_start().chars().take_while(|ch| ch.is_alphabetic()).collect();
        ALGORITHM_CONTROL_WORDS.contains(&word.as_str())
    });
    texts.first().is_some_and(|first| opens_algorithm(first)) || (assigns && controls)
}

/// Whether the first line of a float's text opens an algorithm.
fn opens_algorithm(first: &str) -> bool {
    let word: String = first.chars().take_while(|ch| ch.is_alphanumeric()).collect();
    ALGORITHM_OPENERS.contains(&word.as_str()) || first.split_once([':', '.']).is_some_and(|(num, _)| num == "1")
}

/// Merges lines of one or two characters (a radical sign set apart from
/// its line) into the line with the nearest baseline, at the position of
/// their glyphs.
fn merge_orphans(lines: &mut Vec<AlgoLine>) {
    let mut idx = 0;
    while idx < lines.len() {
        let text = plain(&lines[idx].spans);
        let orphan = !text.is_empty() && text.chars().count() <= ORPHAN_MAX_CHARS && lines.len() > 1;
        let host = orphan
            .then(|| nearest_line(lines, idx))
            .flatten()
            .filter(|&host| (lines[host].line.baseline - lines[idx].line.baseline).abs() < lines[idx].line.size);
        match host {
            Some(host) => {
                let x0 = lines[idx].line.bbox.x0;
                let at = char_offset_at(&lines[host].line, x0);
                insert_text(&mut lines[host].spans, at, &text);
                lines.remove(idx);
            }
            None => idx += 1,
        }
    }
}

/// The other line whose baseline is closest to that of `lines[idx]`.
fn nearest_line(lines: &[AlgoLine], idx: usize) -> Option<usize> {
    let baseline = lines[idx].line.baseline;
    (0..lines.len()).filter(|&other| other != idx).min_by(|&a, &b| {
        let da = (lines[a].line.baseline - baseline).abs();
        let db = (lines[b].line.baseline - baseline).abs();
        da.total_cmp(&db)
    })
}

/// The character offset in the text of `line` (glyphs joined with a space
/// where a glyph has `space_before`) of the first glyph that starts at or
/// right of `x`.
fn char_offset_at(line: &Line, x: f32) -> usize {
    let mut offset = 0;
    for (glyph_idx, glyph) in line.glyphs.iter().enumerate() {
        if glyph.space_before && glyph_idx > 0 {
            offset += 1;
        }
        if glyph.x0 >= x {
            return offset;
        }
        offset += glyph.text.chars().count();
    }
    offset
}

/// Inserts `text` into `spans` at character offset `at` (at the end when
/// the offset is past it), in the style of the span it falls in.
fn insert_text(spans: &mut [Span], at: usize, text: &str) {
    let mut start = 0;
    let count = spans.len();
    for (idx, span) in spans.iter_mut().enumerate() {
        let len = span.text.chars().count();
        if at <= start + len || idx + 1 == count {
            let byte = span
                .text
                .char_indices()
                .nth(at.saturating_sub(start))
                .map_or(span.text.len(), |(byte, _)| byte);
            span.text.insert_str(byte, text);
            return;
        }
        start += len;
    }
}

/// Splits `spans` at character offset `at`.
fn split_spans(spans: &[Span], at: usize) -> (Vec<Span>, Vec<Span>) {
    let (mut head, mut tail) = (Vec::new(), Vec::new());
    let mut start = 0;
    for span in spans {
        let len = span.text.chars().count();
        if start + len <= at {
            head.push(span.clone());
        } else if start >= at {
            tail.push(span.clone());
        } else {
            let byte = span
                .text
                .char_indices()
                .nth(at - start)
                .map_or(span.text.len(), |(byte, _)| byte);
            let mut first = span.clone();
            first.text.truncate(byte);
            let mut second = span.clone();
            second.text = span.text[byte..].to_string();
            head.push(first);
            tail.push(second);
        }
        start += len;
    }
    (head, tail)
}

/// Splits off a trailing comment: `▷ text`, `// text`, or a parenthesised
/// phrase starting with a capital letter after a space ("(Update
/// parameters)"). Returns the statement and the comment, if any.
fn split_comment(spans: &[Span], text: &str) -> (Vec<Span>, Option<Vec<Span>>) {
    let chars: Vec<char> = text.chars().collect();
    let marker = chars
        .iter()
        .position(|ch| *ch == '▷')
        .or_else(|| text.find(" // ").map(|byte| text[..byte].chars().count() + 1));
    let at = marker.or_else(|| trailing_parenthetical(&chars));
    match at {
        Some(at) if at > 0 => {
            // `plain` trims the start: account for leading spaces.
            let lead = spans.iter().map(|span| span.text.as_str()).collect::<String>();
            let skipped = lead.chars().take_while(|ch| ch.is_whitespace()).count();
            let (statement, comment) = split_spans(spans, at + skipped);
            (statement, Some(comment))
        }
        _ => (spans.to_vec(), None),
    }
}

/// The start of a final "(Capitalised words)" group preceded by a space.
fn trailing_parenthetical(chars: &[char]) -> Option<usize> {
    if chars.last() != Some(&')') {
        return None;
    }
    let mut depth = 0;
    for idx in (0..chars.len()).rev() {
        match chars[idx] {
            ')' => depth += 1,
            '(' => {
                depth -= 1;
                if depth == 0 {
                    let words = chars.get(idx + 1).is_some_and(|ch| ch.is_uppercase()) && chars[idx..].contains(&' ');
                    let spaced = idx > 0 && chars[idx - 1] == ' ';
                    return (words && spaced).then_some(idx);
                }
            }
            _ => {}
        }
    }
    None
}

/// The indentation level of each line (0 to [`ALGORITHM_MAX_INDENT`]):
/// the rank of its left edge among the distinct left edges of the
/// statements; header lines are level 0.
fn indent_levels(lines: &[AlgoLine]) -> Vec<usize> {
    let is_header = |algo: &AlgoLine| {
        ALGORITHM_HEADERS
            .iter()
            .any(|word| plain(&algo.spans).starts_with(word))
    };
    let mut edges: Vec<f32> = lines
        .iter()
        .filter(|algo| !is_header(algo))
        .map(|algo| algo.line.bbox.x0)
        .collect();
    edges.sort_by(f32::total_cmp);
    edges.dedup_by(|a, b| (*a - *b).abs() < INDENT_TOLERANCE_PT);
    lines
        .iter()
        .map(|algo| {
            if is_header(algo) {
                return 0;
            }
            let x0 = algo.line.bbox.x0;
            edges
                .iter()
                .take_while(|edge| **edge < x0 - INDENT_TOLERANCE_PT)
                .count()
                .min(ALGORITHM_MAX_INDENT)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The lines as owned strings.
    fn texts(lines: &[&str]) -> Vec<String> {
        lines.iter().map(|line| (*line).to_string()).collect()
    }

    #[test]
    fn pseudocode_without_an_opener_is_recognised() {
        // Algorithm 1 of the VAE paper (arXiv:1312.6114).
        let vae = texts(&[
            "θ, φ ← Initialize parameters",
            "repeat",
            "XM ← Random minibatch of M datapoints",
            "until convergence of parameters (θ, φ)",
            "return θ, φ",
        ]);
        assert!(reads_as_pseudocode(&vae));
        assert!(reads_as_pseudocode(&texts(&["Require: α", "m0 ← 0", "end while"])));
        assert!(reads_as_pseudocode(&texts(&["1: x := 0", "2: y := 1", "3: z := 2"])));
    }

    #[test]
    fn text_that_is_not_pseudocode_keeps_its_picture() {
        // Labels of a diagram: an arrow but no control line.
        assert!(!reads_as_pseudocode(&texts(&["Encoder ← input", "Decoder", "Loss"])));
        // Control words but no assignment.
        assert!(!reads_as_pseudocode(&texts(&[
            "If the input is long",
            "the model",
            "returns early"
        ])));
        assert!(!reads_as_pseudocode(&[]));
    }
}