guidebook 0.1.73

HonKit/GitBook compatible static book generator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
use anyhow::Result;
use std::collections::HashMap;
use std::fs;
use std::path::Path;

/// Glossary containing all terms and their definitions
#[derive(Debug, Clone, Default)]
pub struct Glossary {
    /// Map from term to definition
    pub entries: HashMap<String, String>,
    /// Terms sorted by length (longest first) for replacement
    pub sorted_terms: Vec<String>,
}

impl Glossary {
    /// Load glossary from GLOSSARY.md file
    pub fn load(book_dir: &Path) -> Result<Self> {
        let glossary_path = book_dir.join("GLOSSARY.md");
        if !glossary_path.exists() {
            return Ok(Self::default());
        }

        let content = fs::read_to_string(&glossary_path)?;
        Self::parse(&content)
    }

    /// Parse GLOSSARY.md content
    pub fn parse(content: &str) -> Result<Self> {
        let mut entries = HashMap::new();
        let mut current_term: Option<String> = None;
        let mut current_definition = String::new();

        for line in content.lines() {
            let trimmed = line.trim();

            // Skip the main heading (# GLOSSARY)
            if trimmed.starts_with("# ") {
                continue;
            }

            // Check for term heading (## Term)
            if let Some(heading) = trimmed.strip_prefix("## ") {
                // Save previous entry if exists
                if let Some(term) = current_term.take() {
                    let definition = current_definition.trim().to_string();
                    if !definition.is_empty() {
                        entries.insert(term, definition);
                    }
                }

                // Start new entry
                current_term = Some(heading.trim().to_string());
                current_definition.clear();
                continue;
            }

            // Accumulate definition lines
            if current_term.is_some() && !trimmed.is_empty() {
                if !current_definition.is_empty() {
                    current_definition.push(' ');
                }
                current_definition.push_str(trimmed);
            }
        }

        // Save last entry
        if let Some(term) = current_term {
            let definition = current_definition.trim().to_string();
            if !definition.is_empty() {
                entries.insert(term, definition);
            }
        }

        // Sort terms by length (longest first) to avoid partial replacements
        let mut sorted_terms: Vec<String> = entries.keys().cloned().collect();
        sorted_terms.sort_by_key(|b| std::cmp::Reverse(b.len()));

        Ok(Self {
            entries,
            sorted_terms,
        })
    }

    /// Check if glossary is empty
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get definition for a term
    pub fn get(&self, term: &str) -> Option<&String> {
        self.entries.get(term)
    }
}

/// Apply glossary terms to HTML content
/// Wraps matching terms in <span class="glossary-term" data-definition="...">
pub fn apply_glossary(html: &str, glossary: &Glossary) -> String {
    if glossary.is_empty() {
        return html.to_string();
    }

    let mut result = html.to_string();

    // Process each term (longest first to avoid partial replacements)
    for term in &glossary.sorted_terms {
        if let Some(definition) = glossary.get(term) {
            result = replace_term_in_html(&result, term, definition);
        }
    }

    result
}

/// Replace a term in HTML content, avoiding replacements inside:
/// - HTML tags
/// - Existing glossary spans
/// - Code blocks (<code>, <pre>)
/// - Anchor tags (<a>)
/// - Heading tags (<h1> through <h6>)
/// - Script tags (<script>)
/// - Elements with class="no-glossary"
/// - Already processed terms
fn replace_term_in_html(html: &str, term: &str, definition: &str) -> String {
    let mut result = String::new();
    let mut chars = html.char_indices().peekable();
    let mut in_tag = false;
    let mut in_code = false;
    let mut in_glossary_span = false;
    let mut in_anchor = false;
    let mut in_heading = false;
    let mut in_script = false;
    let mut no_glossary_stack: Vec<String> = Vec::new(); // Stack of tag names with no-glossary class
    let mut tag_content = String::new();
    // Quote character of the attribute value we are currently inside
    // (a '>' inside a quoted attribute value does not close the tag)
    let mut attr_quote: Option<char> = None;

    while let Some((i, c)) = chars.next() {
        // Check if we're entering an HTML tag
        if c == '<' && !in_tag {
            in_tag = true;
            tag_content.clear();
            attr_quote = None;
            result.push(c);
            continue;
        }

        // Track quoted attribute values inside tags
        if in_tag {
            match attr_quote {
                Some(q) if c == q => attr_quote = None,
                None if c == '"' || c == '\'' => attr_quote = Some(c),
                _ => {}
            }
        }

        // Check if we're exiting an HTML tag
        if c == '>' && in_tag && attr_quote.is_none() {
            in_tag = false;
            result.push(c);

            // Check tag type
            let tag_lower = tag_content.to_lowercase();

            // Code and pre tags
            if tag_lower.starts_with("code") || tag_lower.starts_with("pre") {
                in_code = true;
            } else if tag_lower.starts_with("/code") || tag_lower.starts_with("/pre") {
                in_code = false;
            }
            // Glossary span
            else if tag_lower.starts_with("span") && tag_lower.contains("glossary-term") {
                in_glossary_span = true;
            } else if tag_lower.starts_with("/span") && in_glossary_span {
                in_glossary_span = false;
            }
            // Anchor tags
            else if tag_lower.starts_with("a ") || tag_lower == "a" {
                in_anchor = true;
            } else if tag_lower.starts_with("/a") {
                in_anchor = false;
            }
            // Heading tags (h1-h6)
            else if tag_lower.starts_with('h') && tag_lower.len() >= 2 {
                let second_char = tag_lower.chars().nth(1);
                if matches!(second_char, Some('1'..='6')) {
                    // Check it's not just a prefix (e.g., "header")
                    let third_char = tag_lower.chars().nth(2);
                    if third_char.is_none() || !third_char.unwrap().is_alphabetic() {
                        in_heading = true;
                    }
                }
            } else if tag_lower.starts_with("/h") && tag_lower.len() >= 3 {
                let third_char = tag_lower.chars().nth(2);
                if matches!(third_char, Some('1'..='6')) {
                    in_heading = false;
                }
            }
            // Script tags
            else if tag_lower.starts_with("script") {
                in_script = true;
            } else if tag_lower.starts_with("/script") {
                in_script = false;
            }

            // no-glossary class detection (can be on any element)
            // Check for opening tags with no-glossary class.
            // Void elements (<img>, <br>, ...) and self-closing tags never get
            // a closing tag — pushing them would leave the stack non-empty and
            // silently disable the glossary for the rest of the page.
            if !tag_lower.starts_with('/')
                && tag_lower.contains("class=")
                && tag_lower.contains("no-glossary")
                && !tag_lower.trim_end().ends_with('/')
            {
                // Extract the tag name (first word before space or end)
                let tag_name = tag_lower
                    .split_whitespace()
                    .next()
                    .unwrap_or("")
                    .to_string();
                if !tag_name.is_empty() && !is_void_element(&tag_name) {
                    no_glossary_stack.push(tag_name);
                }
            }
            // Track closing tags for no-glossary elements
            if tag_lower.starts_with('/') && !no_glossary_stack.is_empty() {
                // Extract closing tag name (remove leading /)
                let closing_tag = tag_lower
                    .trim_start_matches('/')
                    .split_whitespace()
                    .next()
                    .unwrap_or("");
                // Pop from stack if it matches the most recent no-glossary element
                if let Some(last) = no_glossary_stack.last() {
                    if last == closing_tag {
                        no_glossary_stack.pop();
                    }
                }
            }

            continue;
        }

        // Collect tag content
        if in_tag {
            tag_content.push(c);
            result.push(c);
            continue;
        }

        // Skip replacement inside excluded elements
        if in_code
            || in_glossary_span
            || in_anchor
            || in_heading
            || in_script
            || !no_glossary_stack.is_empty()
        {
            result.push(c);
            continue;
        }

        // Check if the term starts here
        if html[i..].starts_with(term) {
            // Make sure it's a word boundary (not part of a larger word).
            // Boundary is blocked only when the adjacent character continues
            // the same script run as the term edge (e.g. "API" in "APIARY",
            // "用語" in "専門用語集"). Different scripts (kanji term followed
            // by hiragana particle, etc.) are valid boundaries in Japanese.
            let term_first = term.chars().next().unwrap_or(' ');
            let term_last = term.chars().last().unwrap_or(' ');
            let before_ok =
                i == 0 || !is_same_word_run(result.chars().last().unwrap_or(' '), term_first);
            let after_idx = i + term.len();
            let after_ok = after_idx >= html.len()
                || !is_same_word_run(term_last, html[after_idx..].chars().next().unwrap_or(' '));

            if before_ok && after_ok {
                // Escape definition for HTML attribute
                let escaped_def = html_escape_attribute(definition);
                result.push_str(&format!(
                    r#"<span class="glossary-term" data-definition="{}">{}</span>"#,
                    escaped_def, term
                ));

                // Skip the term characters (chars, not bytes — the term may
                // contain multi-byte characters)
                for _ in 0..term.chars().count() - 1 {
                    chars.next();
                }
                continue;
            }
        }

        result.push(c);
    }

    result
}

/// HTML void elements — they never have a closing tag
fn is_void_element(tag_name: &str) -> bool {
    matches!(
        tag_name,
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
    )
}

/// Script class used for word-boundary detection
#[derive(PartialEq)]
enum CharClass {
    /// Non-word character (punctuation, whitespace, symbols)
    None,
    /// Alphanumeric (ASCII and fullwidth letters/digits)
    Alnum,
    Hiragana,
    Katakana,
    Kanji,
}

fn char_class(c: char) -> CharClass {
    match c {
        '\u{3041}'..='\u{309F}' => CharClass::Hiragana,
        '\u{30A0}'..='\u{30FF}' | '\u{31F0}'..='\u{31FF}' | '\u{FF66}'..='\u{FF9F}' => {
            CharClass::Katakana
        }
        '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' => {
            CharClass::Kanji
        }
        _ if c.is_alphanumeric() => CharClass::Alnum,
        _ => CharClass::None,
    }
}

/// Two adjacent characters belong to the same word run (so a term edge
/// touching such a character is NOT a word boundary)
fn is_same_word_run(a: char, b: char) -> bool {
    let ca = char_class(a);
    if ca == CharClass::None {
        return false;
    }
    ca == char_class(b)
}

/// Escape a string for use in an HTML attribute
fn html_escape_attribute(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

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

    #[test]
    fn test_parse_glossary() {
        let content = r#"# GLOSSARY

## API
Application Programming Interface の略

## SDK
Software Development Kit の略
"#;

        let glossary = Glossary::parse(content).unwrap();
        assert_eq!(glossary.entries.len(), 2);
        assert_eq!(
            glossary.get("API"),
            Some(&"Application Programming Interface の略".to_string())
        );
        assert_eq!(
            glossary.get("SDK"),
            Some(&"Software Development Kit の略".to_string())
        );
    }

    #[test]
    fn test_parse_multiline_definition() {
        let content = r#"# GLOSSARY

## REST
Representational State Transfer の略。
Web APIの設計スタイルの一つ。
"#;

        let glossary = Glossary::parse(content).unwrap();
        assert_eq!(
            glossary.get("REST"),
            Some(
                &"Representational State Transfer の略。 Web APIの設計スタイルの一つ。".to_string()
            )
        );
    }

    #[test]
    fn test_apply_glossary() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = "<p>This is an API example.</p>";
        let result = apply_glossary(html, &glossary);
        assert!(result
            .contains(r#"<span class="glossary-term" data-definition="Interface">API</span>"#));
    }

    #[test]
    fn test_apply_glossary_in_code() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = "<p>Use the <code>API</code> endpoint.</p>";
        let result = apply_glossary(html, &glossary);
        // API inside code should not be wrapped
        assert!(result.contains("<code>API</code>"));
        assert!(!result.contains("glossary-term"));
    }

    #[test]
    fn test_apply_glossary_word_boundary() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = "<p>The APIARY tool is different from API.</p>";
        let result = apply_glossary(html, &glossary);
        // APIARY should not be affected
        assert!(result.contains("APIARY"));
        // But standalone API should be wrapped
        assert!(result.contains("glossary-term"));
    }

    #[test]
    fn test_empty_glossary() {
        let glossary = Glossary::default();
        assert!(glossary.is_empty());
    }

    #[test]
    fn test_sorted_terms_longest_first() {
        let content = r#"# GLOSSARY

## API
Application Programming Interface

## REST API
RESTful API

## REST
Representational State Transfer
"#;

        let glossary = Glossary::parse(content).unwrap();
        // REST API should come before REST and API
        assert_eq!(glossary.sorted_terms[0], "REST API");
    }

    #[test]
    fn test_apply_glossary_in_anchor() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = r#"<p>See <a href="/api">API documentation</a> for more info about API.</p>"#;
        let result = apply_glossary(html, &glossary);
        // API inside anchor should not be wrapped
        assert!(result.contains(">API documentation</a>"));
        // But standalone API outside anchor should be wrapped
        assert!(result.contains(
            r#"<span class="glossary-term" data-definition="Interface">API</span>.</p>"#
        ));
    }

    #[test]
    fn test_apply_glossary_in_heading() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = "<h1>API Overview</h1><p>Learn about API.</p>";
        let result = apply_glossary(html, &glossary);
        // API inside h1 should not be wrapped
        assert!(result.contains("<h1>API Overview</h1>"));
        // But API in paragraph should be wrapped
        assert!(result
            .contains(r#"<span class="glossary-term" data-definition="Interface">API</span>"#));
    }

    #[test]
    fn test_apply_glossary_in_all_headings() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();

        // Test h1 through h6
        for level in 1..=6 {
            let html = format!("<h{}>API</h{}>", level, level);
            let result = apply_glossary(&html, &glossary);
            assert!(
                !result.contains("glossary-term"),
                "h{} should exclude glossary",
                level
            );
            assert!(result.contains(&format!("<h{}>API</h{}>", level, level)));
        }
    }

    #[test]
    fn test_apply_glossary_in_script() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = r#"<script>const API = "test";</script><p>Use the API.</p>"#;
        let result = apply_glossary(html, &glossary);
        // API inside script should not be wrapped
        assert!(result.contains(r#"<script>const API = "test";</script>"#));
        // But API in paragraph should be wrapped
        assert!(result
            .contains(r#"<span class="glossary-term" data-definition="Interface">API</span>"#));
    }

    #[test]
    fn test_apply_glossary_no_glossary_class() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = r#"<p>About API.</p><div class="no-glossary">API is excluded here.</div><p>API again.</p>"#;
        let result = apply_glossary(html, &glossary);
        // API inside no-glossary div should not be wrapped
        assert!(result.contains(r#"<div class="no-glossary">API is excluded here.</div>"#));
        // But API outside should be wrapped (count occurrences)
        let glossary_count = result.matches("glossary-term").count();
        assert_eq!(
            glossary_count, 2,
            "Should have 2 glossary terms (before and after no-glossary)"
        );
    }

    #[test]
    fn test_apply_glossary_no_glossary_nested() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = r#"<div class="no-glossary"><p>API in <span>nested API</span> element.</p></div><p>API outside.</p>"#;
        let result = apply_glossary(html, &glossary);
        // API inside no-glossary (even nested) should not be wrapped
        assert!(result.contains(r#"<div class="no-glossary"><p>API in <span>nested API</span>"#));
        // But API outside should be wrapped
        assert!(result.contains(
            r#"<span class="glossary-term" data-definition="Interface">API</span> outside"#
        ));
    }

    #[test]
    fn test_apply_glossary_header_not_matched() {
        // Ensure "header" element is not confused with "h1"-"h6"
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = "<header>API in header</header><p>API in p.</p>";
        let result = apply_glossary(html, &glossary);
        // API inside header element should still be wrapped (header != h1-h6)
        let glossary_count = result.matches("glossary-term").count();
        assert_eq!(glossary_count, 2, "Both API occurrences should be wrapped");
    }

    #[test]
    fn test_apply_glossary_anchor_with_attributes() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = r#"<a href="/doc" class="link" target="_blank">API Guide</a> and API."#;
        let result = apply_glossary(html, &glossary);
        // API inside anchor with attributes should not be wrapped
        assert!(result.contains(">API Guide</a>"));
        // API outside should be wrapped
        assert!(result
            .contains(r#"<span class="glossary-term" data-definition="Interface">API</span>."#));
    }

    // ── Fuzz-like edge case tests ──

    #[test]
    fn test_fuzz_empty_glossary_content() {
        let result = Glossary::parse("");
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_fuzz_heading_only_no_definition() {
        let result = Glossary::parse("## TermWithNoDefinition\n");
        assert!(result.is_ok());
    }

    #[test]
    fn test_fuzz_special_chars_in_term() {
        let inputs = vec![
            "## C++\nLanguage",
            "## C#\nLanguage",
            "## .NET\nFramework",
            "## $variable\nShell variable",
            "## term<script>\nXSS attempt",
        ];
        for input in inputs {
            let result = Glossary::parse(input);
            assert!(result.is_ok(), "Should not panic on: {}", input);
        }
    }

    #[test]
    fn test_fuzz_apply_glossary_empty_html() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let result = apply_glossary("", &glossary);
        assert_eq!(result, "");
    }

    #[test]
    fn test_fuzz_apply_glossary_malformed_html() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let inputs = vec![
            "<p>Unclosed tag with API",
            "<<>>API<<>>",
            "<p>API</p><p>API</p><p>API</p>",
            "<div style='color:red'>API</div>",
        ];
        for input in inputs {
            let result = apply_glossary(input, &glossary);
            let _ = result; // Should not panic
        }
    }

    #[test]
    fn test_apply_glossary_japanese_term_no_text_loss() {
        // Regression: term.len() (bytes) was used to skip chars, eating
        // the text following a multi-byte term
        let glossary = Glossary::parse("## 用語\n説明文です。").unwrap();
        let html = "<p>用語 とは何か。</p>";
        let result = apply_glossary(html, &glossary);
        assert!(
            result.contains("とは何か。"),
            "text after the term must be preserved: {}",
            result
        );
        assert!(result
            .contains(r#"<span class="glossary-term" data-definition="説明文です。">用語</span>"#));
    }

    #[test]
    fn test_apply_glossary_japanese_term_in_sentence() {
        // Regression: is_word_char treated all non-ASCII as word chars,
        // so a kanji term followed by hiragana never matched
        let glossary = Glossary::parse("## 用語\n説明").unwrap();
        let html = "<p>この用語について説明します。</p>";
        let result = apply_glossary(html, &glossary);
        assert!(
            result.contains("glossary-term"),
            "kanji term adjacent to hiragana should match: {}",
            result
        );
    }

    #[test]
    fn test_apply_glossary_japanese_compound_not_matched() {
        // A term inside a larger kanji compound is not a word boundary
        let glossary = Glossary::parse("## 用語\n説明").unwrap();
        let html = "<p>専門用語集を参照。</p>";
        let result = apply_glossary(html, &glossary);
        assert!(
            !result.contains("glossary-term"),
            "term inside kanji compound should not match: {}",
            result
        );
    }

    #[test]
    fn test_gt_inside_attribute_value_does_not_close_tag() {
        // Regression: a '>' inside a quoted attribute value was treated as
        // the tag close, so the rest of the attribute became "text" and got
        // glossary spans injected inside the attribute value
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = r#"<div title="see notes>API here">text about API</div>"#;
        let result = apply_glossary(html, &glossary);
        assert!(
            result.contains(r#"title="see notes>API here""#),
            "attribute value must stay intact: {}",
            result
        );
        // The API in the body text still gets wrapped
        assert!(
            result.contains(r#"about <span class="glossary-term""#),
            "body text API must still be wrapped: {}",
            result
        );
    }

    #[test]
    fn test_no_glossary_on_void_element_does_not_stick() {
        // Regression: <img class="no-glossary"> pushed onto the stack and
        // never popped, silently disabling the glossary for the whole page
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html =
            r#"<img src="pic.png" class="no-glossary" alt="d"/><p>This API should be wrapped.</p>"#;
        let result = apply_glossary(html, &glossary);
        assert!(
            result.contains("glossary-term"),
            "glossary must not be disabled after a void no-glossary element: {}",
            result
        );
    }

    #[test]
    fn test_no_glossary_self_closing_div_does_not_stick() {
        let glossary = Glossary::parse("## API\nInterface").unwrap();
        let html = r#"<div class="no-glossary"/><p>API here.</p>"#;
        let result = apply_glossary(html, &glossary);
        assert!(result.contains("glossary-term"), "{}", result);
    }

    #[test]
    fn test_fuzz_very_long_term() {
        let term = "A".repeat(10000);
        let content = format!("## {}\nDefinition", term);
        let result = Glossary::parse(&content);
        assert!(result.is_ok());
    }

    #[test]
    fn test_fuzz_many_terms() {
        let mut content = String::from("# Glossary\n\n");
        for i in 0..500 {
            content.push_str(&format!("## Term{}\nDefinition {}\n\n", i, i));
        }
        let result = Glossary::parse(&content);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().entries.len(), 500);
    }
}