jsslint-core 1.1.0

Rule engine behind the Journal of Statistical Software (JSS) LaTeX/BibTeX style checker. Powers the jsslint CLI, WASM, Python, and R distributions.
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! Capitalization rules — mirrors `journals/jss/rules/capitalization.py`
//! (JSS-CAP-001/002/004; JSS-CAP-003 is retired — see
//! `specs/003-jss-rule-catalogue/catalogue.yaml`'s `retired_rule_ids`).
//!
//! `check_cap_001` spans every tex-like fragment in the document (not
//! just one `ParsedTex`) so `_doc_pkg_names_lower`'s `\pkg{}` scan
//! matches Python's `doc.all_tex_like()` — see its doc comment.

use super::tex_common::tex_violation_with_fix;
use crate::report::Violation;
use crate::terms::TERMS;
use crate::tex::extract;
use crate::tex::node::{GroupNode, MacroNode, Node};
use crate::tex::prose::{Slot, MARKUP_MACROS};
use crate::tex::{position::LineIndex, ParsedTex};
use regex::Regex;
use std::collections::HashSet;
use std::sync::LazyLock;

const TITLE_STOPWORDS: &[&str] = &[
    "a", "an", "the", "and", "or", "but", "nor", "for", "so", "yet", "at", "by", "in", "of", "on",
    "to", "up", "via", "with", "as", "is", "vs",
];

const CAP_SECTION_MACROS: &[&str] = &[
    "section",
    "section*",
    "subsection",
    "subsection*",
    "subsubsection",
    "subsubsection*",
];

const EXTRA_PROPER_NOUNS: &[&str] = &[
    "American",
    "Asian",
    "Australian",
    "Austrian",
    "Belgian",
    "British",
    "Canadian",
    "Chinese",
    "Czech",
    "Dutch",
    "English",
    "European",
    "Finnish",
    "French",
    "German",
    "Greek",
    "Indian",
    "Iranian",
    "Irish",
    "Italian",
    "Japanese",
    "Korean",
    "Latin",
    "Mexican",
    "Norwegian",
    "Polish",
    "Portuguese",
    "Russian",
    "Scottish",
    "Spanish",
    "Swedish",
    "Swiss",
    "Turkish",
    "Welsh",
    "Bayes",
    "Bayesian",
    "Bernoulli",
    "Boole",
    "Boolean",
    "Cauchy",
    "Cholesky",
    "Clayton",
    "Cox",
    "Dirichlet",
    "Euclidean",
    "Fisher",
    "Frank",
    "Gauss",
    "Gaussian",
    "Gumbel",
    "Lagrange",
    "Laplace",
    "Markov",
    "Maxwell",
    "Monte",
    "Carlo",
    "Newton",
    "Pareto",
    "Pearson",
    "Poisson",
    "Riemann",
    "Shannon",
    "Wald",
    "Weibull",
    "Wishart",
    "Apple",
    "Google",
    "Linux",
    "Microsoft",
    "Oracle",
    "Unix",
    "Windows",
    "Beijing",
    "Berlin",
    "Bavaria",
    "Boston",
    "China",
    "Germany",
    "Ireland",
    "Spain",
    "Innsbruck",
    "Vienna",
    "Wien",
    "Alzheimer",
    "Campylobacter",
    "Faithful",
    "Indians",
    "Listeria",
    "Moby",
    "Newport",
    "Pima",
    "Salmonella",
];

static PROPER_NOUNS: LazyLock<HashSet<String>> = LazyLock::new(|| {
    let mut set: HashSet<String> = TERMS
        .languages
        .iter()
        .cloned()
        .chain(TERMS.r_packages.iter().cloned())
        .collect();
    set.extend(EXTRA_PROPER_NOUNS.iter().map(|s| s.to_string()));
    set
});

static PROPER_NOUNS_LOWER: LazyLock<HashSet<String>> =
    LazyLock::new(|| PROPER_NOUNS.iter().map(|s| s.to_lowercase()).collect());

/// Mirrors `capitalization.py::_first_group_arg` — unlike the
/// `typography`/`code_style` variants, this one SKIPS a leading
/// optional `[...]` arg (needed for `\section[short]{long}`, where the
/// mandatory `{long}` group is what capitalization rules must check).
fn first_group_arg_brace_only<'a>(
    macro_node: &'a MacroNode,
    parent: &[Slot<'a>],
    idx: usize,
) -> Option<&'a GroupNode> {
    for arg in &macro_node.args {
        if let Some(Node::Group(g)) = arg {
            if g.delims == crate::tex::node::GroupDelims::Bracket {
                continue;
            }
            return Some(g);
        }
    }
    extract::next_group_arg(parent, idx)
}

/// Mirrors `capitalization.py::_group_plain_text`: recurses into
/// nested groups, but skips a group immediately following a markup
/// macro (`\pkg`/`\proglang`/`\code`/...) — that group is the macro's
/// unknown-macro sibling argument, whose author-chosen casing must not
/// leak into the plain-text projection.
fn group_plain_text(group: &GroupNode) -> String {
    let mut parts = String::new();
    let mut skip_next_group = false;
    for child in &group.nodelist {
        match child {
            Node::Chars(c) => {
                skip_next_group = false;
                parts.push_str(&c.chars);
            }
            Node::Group(g) => {
                if skip_next_group {
                    skip_next_group = false;
                    continue;
                }
                parts.push_str(&group_plain_text(g));
            }
            Node::Macro(m) => {
                if m.macroname == "label" {
                    continue;
                }
                skip_next_group = MARKUP_MACROS.contains(&m.macroname.as_str());
            }
            _ => {}
        }
    }
    parts
}

fn words(text: &str) -> Vec<&str> {
    static SPLIT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\s\-]+").unwrap());
    SPLIT_RE
        .split(text.trim())
        .filter(|w| !w.is_empty())
        .collect()
}

fn word_letters_lower(word: &str) -> String {
    word.chars()
        .filter(|c| c.is_ascii_alphabetic())
        .collect::<String>()
        .to_lowercase()
}

fn is_capitalised_word(word: &str) -> bool {
    match word.chars().find(|c| c.is_ascii_alphabetic()) {
        None => true,
        Some(c) => c.is_uppercase(),
    }
}

// --- JSS-CAP-001 --------------------------------------------------------

static FUNCTION_CALL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[A-Za-z][A-Za-z0-9_.]*\(\)?$").unwrap());
static TITLE_LEADING_MARKUP_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\{?\s*\\(pkg|proglang|code|fct|verb)\b").unwrap());

/// Raw-source-shaped probe of a title's leading token. Mirrors
/// `capitalization.py::_title_source`.
fn title_source(group: &GroupNode) -> String {
    let mut parts = String::new();
    for child in &group.nodelist {
        match child {
            Node::Chars(c) => {
                parts.push_str(&c.chars);
                if !c.chars.trim().is_empty() {
                    break;
                }
            }
            Node::Macro(m) => {
                parts.push('\\');
                parts.push_str(&m.macroname);
                break;
            }
            Node::Group(g) => {
                parts.push('{');
                parts.push_str(&title_source(g));
                break;
            }
            _ => {}
        }
    }
    parts
}

fn pkg_token(word: &str) -> String {
    let kept: String = word
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || *c == '.')
        .collect();
    kept.trim_matches('.').to_lowercase()
}

/// Mirrors `capitalization.py::_doc_pkg_names_lower` for a single
/// fragment; `check_cap_001` unions this across every fragment.
fn doc_pkg_names_lower(nodes: &[Node]) -> HashSet<String> {
    let mut out = HashSet::new();
    extract::iter_with_parent_visit(nodes, &mut |parent: &[Slot], idx, node| {
        let Node::Macro(m) = node else { return };
        if m.macroname != "pkg" {
            return;
        }
        let text = extract::macro_args_text(m, parent, idx);
        if !text.is_empty() {
            let tok = pkg_token(&text);
            if !tok.is_empty() {
                out.insert(tok);
            }
        }
    });
    out
}

// --- shared "capitalise the first word after a colon" check --------------
//
// Both JSS styles agree on the colon: sentence style capitalises "the
// first word after a colon or a hyphen", title style says "Do capitalize
// the first word after a colon". We enforce the COLON only (capital-
// after-hyphen deliberately not enforced — see catalogue notes for
// CAP-002). Mirrors `capitalization.py::_lowercase_after_colon_offender`.

/// Package / language names whose canonical form is lowercase (`zoo`,
/// `ggplot2`, `mgcv`). A colon-leading token matching one is a known
/// code identifier, not a forgotten capital — exempt it.
static LOWERCASE_CANONICAL_TERMS: LazyLock<HashSet<String>> = LazyLock::new(|| {
    TERMS
        .languages
        .iter()
        .chain(TERMS.r_packages.iter())
        .filter(|t| t.chars().next().map(|c| c.is_lowercase()).unwrap_or(false))
        .map(|t| pkg_token(t))
        .filter(|t| !t.is_empty())
        .collect()
});

// Beyond the standard JSS semantic-markup set, also recognise `\class`
// (S4 class names) and typewriter-font wrappers (`\texttt`/`{\tt ...}`/
// `\ttfamily`) authors use for code tokens after a colon.
static COLON_MARKUP_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\\(?:pkg|proglang|code|fct|verb|class|texttt|ttfamily|tt)\b").unwrap()
});
static AFTER_COLON_REST_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?s):\s*(.+)").unwrap());
static AFTER_COLON_TOKEN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r":\s*(\S+)").unwrap());

/// Reconstruct a light LaTeX source of `group` preserving markup macros
/// and math delimiters (which `group_plain_text` strips). Mirrors
/// `capitalization.py::_markup_source`.
fn markup_source(group: &GroupNode) -> String {
    let mut parts = String::new();
    for child in &group.nodelist {
        match child {
            Node::Chars(c) => parts.push_str(&c.chars),
            Node::Math(_) => parts.push('$'),
            Node::Macro(m) => {
                if m.macroname == "label" {
                    continue;
                }
                // Trailing space guarantees a word boundary even when the
                // parser consumed the macro's post-space (`{\tt as.xts}`).
                parts.push('\\');
                parts.push_str(&m.macroname);
                parts.push(' ');
            }
            Node::Group(g) => {
                parts.push('{');
                parts.push_str(&markup_source(g));
                parts.push('}');
            }
            _ => {}
        }
    }
    parts
}

/// True if the first non-space token after a colon is a markup macro or
/// inline math. Mirrors `capitalization.py::_after_colon_is_markup`.
fn after_colon_is_markup(raw: &str) -> bool {
    let Some(caps) = AFTER_COLON_REST_RE.captures(raw) else {
        return false;
    };
    let mut rest = caps.get(1).unwrap().as_str().trim_start();
    while let Some(stripped) = rest.strip_prefix('{') {
        rest = stripped.trim_start();
    }
    if rest.starts_with('$') {
        return true;
    }
    COLON_MARKUP_RE.is_match(rest)
}

/// True if the first token after the first colon starts with a lowercase
/// letter and no exemption applies. Mirrors
/// `capitalization.py::_lowercase_after_colon_offender`.
fn lowercase_after_colon_offender(group: &GroupNode) -> bool {
    let plain = group_plain_text(group);
    let Some(caps) = AFTER_COLON_TOKEN_RE.captures(&plain) else {
        return false;
    };
    let after = caps.get(1).unwrap().as_str();
    match after.chars().next() {
        Some(c) if c.is_alphabetic() => {}
        _ => return false, // (b) non-letter first char
    }
    if LOWERCASE_CANONICAL_TERMS.contains(&pkg_token(after)) {
        return false; // (c) known lowercase-canonical term
    }
    if after_colon_is_markup(&markup_source(group)) {
        return false; // (a) markup/math immediately after colon
    }
    !is_capitalised_word(after)
}

/// JSS-CAP-001 — `\title{}` is in title style.
/// `doc_pkgs_lower` spans every tex-like fragment, NOT just this one:
/// a `.Rmd` paper's `\pkg{}` mentions (which exempt that package's own
/// name from the title-case check) can live in a different prose
/// block than `\title{}` itself. Mirrors `capitalization.py::check_jss_cap_001`
/// computing `_doc_pkg_names_lower(doc)` once, over the whole document,
/// before its per-fragment walk — see `check_cap_001`, the public
/// entry point that assembles it across all fragments first.
fn check_cap_001_fragment(
    file: &str,
    parsed: &ParsedTex,
    doc_pkgs_lower: &HashSet<String>,
) -> Vec<Violation> {
    let line_index = LineIndex::with_offset(&parsed.chars, parsed.line_offset);
    let mut out = Vec::new();

    extract::iter_with_parent_visit(&parsed.nodes, &mut |parent: &[Slot], idx, node| {
        let Node::Macro(m) = node else { return };
        if m.macroname != "title" {
            return;
        }
        let Some(group) = first_group_arg_brace_only(m, parent, idx) else {
            return;
        };
        let text = group_plain_text(group);
        let ws = words(&text);
        if ws.is_empty() {
            return;
        }
        if text.trim_start().starts_with('-')
            && TITLE_LEADING_MARKUP_RE.is_match(&title_source(group))
        {
            return;
        }
        let has_principal = ws.iter().any(|w| {
            let low = word_letters_lower(w);
            !low.is_empty() && !TITLE_STOPWORDS.contains(&low.as_str())
        });
        if !has_principal {
            return;
        }
        let first = ws[0];
        let first_lower = word_letters_lower(first);
        let first_word_exempt = PROPER_NOUNS_LOWER.contains(&first_lower)
            || doc_pkgs_lower.contains(&pkg_token(first))
            || FUNCTION_CALL_RE.is_match(first);
        if !first_word_exempt
            && (!is_capitalised_word(first) || ws.iter().all(|w| *w == w.to_lowercase()))
        {
            out.push(tex_violation_with_fix(
                file,
                &line_index,
                m.span.pos,
                "JSS-CAP-001",
                Some("Use title style: capitalise principal words in the title.".to_string()),
                None,
            ));
            return;
        }
        // Title style: "Do capitalize the first word after a colon."
        if lowercase_after_colon_offender(group) {
            out.push(tex_violation_with_fix(
                file,
                &line_index,
                m.span.pos,
                "JSS-CAP-001",
                Some("Use title style: capitalise the first word after ':' (or wrap it in \\code{}/\\pkg{} if it is a code identifier or package name).".to_string()),
                None,
            ));
            return;
        }
        for word in &ws[1..] {
            let bare = word_letters_lower(word);
            if bare.is_empty() || bare.chars().count() < 4 {
                continue;
            }
            if *word == word.to_lowercase() && !TITLE_STOPWORDS.contains(&bare.as_str()) {
                if PROPER_NOUNS_LOWER.contains(&bare) || doc_pkgs_lower.contains(&bare) {
                    continue;
                }
                out.push(tex_violation_with_fix(
                    file,
                    &line_index,
                    m.span.pos,
                    "JSS-CAP-001",
                    Some(format!(
                        "Use title style: capitalise principal words in the title (found lowercase {}).",
                        super::py_repr(word)
                    )),
                    None,
                ));
                break;
            }
        }
    });
    out
}

/// JSS-CAP-001 — paper title uses title-style capitalisation. Mirrors
/// `capitalization.py::check_jss_cap_001`'s document-wide
/// `_doc_pkg_names_lower(doc)` pre-pass — called once per document
/// with every tex-like fragment.
pub fn check_cap_001(fragments: &[(&str, &ParsedTex)]) -> Vec<Violation> {
    let mut doc_pkgs_lower = HashSet::new();
    for (_, parsed) in fragments {
        doc_pkgs_lower.extend(doc_pkg_names_lower(&parsed.nodes));
    }
    let mut out = Vec::new();
    for (file, parsed) in fragments {
        out.extend(check_cap_001_fragment(file, parsed, &doc_pkgs_lower));
    }
    out
}

// --- shared sentence-style engine (CAP-002) ------------------------------

static LIST_NUMBERING: &str = r"(?:[(\[]\d+[)\]]|\d+[).]|[(\[][a-z][)\]]|[(\[][ivx]{1,4}[)\]])";

static SENTENCE_BOUNDARY_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r"[.:?!]\s+(?:{LIST_NUMBERING}\s+)?(\S)")).unwrap());
static CAPTION_LEADING_LABEL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r"^\s*{LIST_NUMBERING}\s+(\S)")).unwrap());
static HYPHEN_SPLIT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-+").unwrap());
static WORD_TRIM_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[^A-Za-z0-9]+|[^A-Za-z0-9]+$").unwrap());
static NON_SPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\S+").unwrap());

/// `(word, is_boundary, is_hyphen_piece)`. Mirrors
/// `capitalization.py::_words_with_boundary`.
fn words_with_boundary(text: &str) -> Vec<(String, bool, bool)> {
    let mut boundary_offsets: HashSet<usize> = HashSet::new();
    for caps in SENTENCE_BOUNDARY_RE.captures_iter(text) {
        boundary_offsets.insert(caps.get(1).unwrap().start());
    }
    if let Some(caps) = CAPTION_LEADING_LABEL_RE.captures(text) {
        boundary_offsets.insert(caps.get(1).unwrap().start());
    }
    let mut out = Vec::new();
    for source_match in NON_SPACE_RE.find_iter(text) {
        let source_word = source_match.as_str();
        let is_boundary = boundary_offsets.contains(&source_match.start());
        for (piece_idx, piece) in HYPHEN_SPLIT_RE.split(source_word).enumerate() {
            let clean = WORD_TRIM_RE.replace_all(piece, "").to_string();
            if clean.is_empty() {
                continue;
            }
            out.push((clean, is_boundary && piece_idx == 0, piece_idx > 0));
        }
    }
    out
}

/// Mirrors `capitalization.py::_looks_like_abbrev`.
fn looks_like_abbrev(token: &str) -> bool {
    let letters: Vec<char> = token.chars().filter(|c| c.is_ascii_alphabetic()).collect();
    if letters.is_empty() {
        return false;
    }
    let n = letters.len();
    if (2..=6).contains(&n) && letters.iter().all(|c| c.is_uppercase()) {
        return true;
    }
    if (3..=7).contains(&n)
        && letters[n - 1].is_lowercase()
        && n > 2
        && letters[..n - 1].iter().all(|c| c.is_uppercase())
    {
        return true;
    }
    for i in 1..n {
        if letters[i].is_uppercase() && letters[i - 1].is_lowercase() {
            return true;
        }
    }
    false
}

fn is_code_identifier(word: &str) -> bool {
    if word.chars().any(|c| c.is_ascii_digit()) {
        return true;
    }
    let letters: Vec<char> = word.chars().filter(|c| c.is_ascii_alphabetic()).collect();
    letters.iter().skip(1).any(|c| c.is_uppercase())
}

fn is_capitalised_offender(word: &str, proper_nouns: &HashSet<String>) -> bool {
    let bare: String = word.chars().filter(|c| c.is_ascii_alphabetic()).collect();
    if bare.is_empty() {
        return false;
    }
    if bare.chars().count() == 1 {
        return false;
    }
    if !bare.chars().next().unwrap().is_uppercase() {
        return false;
    }
    if is_code_identifier(word) {
        return false;
    }
    if proper_nouns.contains(&bare) {
        return false;
    }
    if TITLE_STOPWORDS.contains(&bare.to_lowercase().as_str()) {
        return false;
    }
    if looks_like_abbrev(&bare) {
        return false;
    }
    true
}

fn is_run_eligible(word: &str) -> bool {
    let bare: String = word.chars().filter(|c| c.is_ascii_alphabetic()).collect();
    if bare.chars().count() < 2 {
        return false;
    }
    if is_code_identifier(word) {
        return false;
    }
    bare.chars().next().unwrap().is_uppercase()
}

const PROPER_NOUN_RUN_MAX: usize = 3;

/// Fires when >= `min_offenders` distinct offending capitalisations
/// appear in `group`. Mirrors `capitalization.py::_check_sentence_style`.
#[allow(clippy::too_many_arguments)]
fn check_sentence_style(
    file: &str,
    line_index: &LineIndex,
    pos: usize,
    group: &GroupNode,
    rule_id: &str,
    suggestion: &str,
    collapse_runs: bool,
    proper_nouns: &HashSet<String>,
    min_offenders: usize,
    out: &mut Vec<Violation>,
) {
    let text = group_plain_text(group);
    let words = words_with_boundary(&text);
    if words.is_empty() {
        return;
    }

    let mut seen: HashSet<String> = HashSet::new();
    let mut offenders = 0usize;
    let n = words.len();
    let mut i = 0usize;
    while i < n {
        let (word, is_boundary, _) = &words[i];
        let is_start = i == 0 || *is_boundary;
        if !is_run_eligible(word) {
            i += 1;
            continue;
        }

        let run_start = i;
        let mut j = i + 1;
        let mut all_hyphen_joined = true;
        while j < n {
            let (nw, nb, nh) = &words[j];
            if *nb || !is_run_eligible(nw) {
                break;
            }
            if !nh {
                all_hyphen_joined = false;
            }
            j += 1;
        }
        let run: Vec<&str> = words[run_start..j]
            .iter()
            .map(|(w, _, _)| w.as_str())
            .collect();
        let run_text = run
            .iter()
            .map(|w| w.to_lowercase())
            .collect::<Vec<_>>()
            .join("-");
        let any_known = run
            .iter()
            .any(|p| proper_nouns.contains(*p) || looks_like_abbrev(p));
        let any_stopword = run
            .iter()
            .any(|p| TITLE_STOPWORDS.contains(&p.to_lowercase().as_str()));

        let is_compound = (collapse_runs || all_hyphen_joined)
            && run.len() >= 2
            && run.len() <= PROPER_NOUN_RUN_MAX
            && !any_stopword;

        if is_compound {
            if !any_known && !is_start && !seen.contains(&run_text) {
                seen.insert(run_text);
                offenders += 1;
            }
            i = j;
            continue;
        }

        let run_meta = &words[run_start..j];
        for (k, (w, _, w_is_hyphen)) in run_meta.iter().enumerate() {
            if k == 0 && is_start {
                continue;
            }
            if *w_is_hyphen && k > 0 {
                continue;
            }
            if is_capitalised_offender(w, proper_nouns) {
                let key = w.to_lowercase();
                if seen.contains(&key) {
                    continue;
                }
                seen.insert(key);
                offenders += 1;
            }
        }
        i = j;
    }

    if offenders >= min_offenders {
        out.push(tex_violation_with_fix(
            file,
            line_index,
            pos,
            rule_id,
            Some(suggestion.to_string()),
            None,
        ));
    }
}

/// JSS-CAP-002 — section titles are in sentence style.
pub fn check_cap_002(file: &str, parsed: &ParsedTex) -> Vec<Violation> {
    let line_index = LineIndex::with_offset(&parsed.chars, parsed.line_offset);
    let mut out = Vec::new();
    extract::iter_with_parent_visit(&parsed.nodes, &mut |parent: &[Slot], idx, node| {
        let Node::Macro(m) = node else { return };
        if !CAP_SECTION_MACROS.contains(&m.macroname.as_str()) {
            return;
        }
        let Some(group) = first_group_arg_brace_only(m, parent, idx) else {
            return;
        };
        check_sentence_style(
            file,
            &line_index,
            m.span.pos,
            group,
            "JSS-CAP-002",
            "Use sentence style: capitalise only the first word (proper names remain capitalised).",
            false,
            &PROPER_NOUNS,
            1,
            &mut out,
        );
        // Sentence style also capitalises "the first word after a
        // colon"; independent of the over-capitalisation check above.
        if lowercase_after_colon_offender(group) {
            out.push(tex_violation_with_fix(
                file,
                &line_index,
                m.span.pos,
                "JSS-CAP-002",
                Some("Use sentence style: capitalise the first word after ':' (or wrap it in \\code{}/\\pkg{} if it is a code identifier or package name).".to_string()),
                None,
            ));
        }
    });
    out
}

// --- JSS-CAP-004 ----------------------------------------------------------

fn keyword_case_violation(entries: &[String]) -> bool {
    for entry in entries {
        let ws: Vec<&str> = entry.split_whitespace().collect();
        if ws.len() < 2 {
            continue;
        }
        let mut offenders = 0;
        for word in &ws[1..] {
            let bare: String = word.chars().filter(|c| c.is_ascii_alphabetic()).collect();
            if bare.is_empty() {
                continue;
            }
            if !bare.chars().next().unwrap().is_uppercase() {
                continue;
            }
            if PROPER_NOUNS.contains(&bare) {
                continue;
            }
            if TITLE_STOPWORDS.contains(&bare.to_lowercase().as_str()) {
                continue;
            }
            if looks_like_abbrev(&bare) {
                continue;
            }
            offenders += 1;
        }
        if offenders >= 1 {
            return true;
        }
    }
    false
}

/// JSS-CAP-004 — `\Keywords{}` entries are in sentence case,
/// comma-separated.
pub fn check_cap_004(file: &str, parsed: &ParsedTex) -> Vec<Violation> {
    let line_index = LineIndex::with_offset(&parsed.chars, parsed.line_offset);
    let mut out = Vec::new();
    extract::iter_with_parent_visit(&parsed.nodes, &mut |parent: &[Slot], idx, node| {
        let Node::Macro(m) = node else { return };
        if m.macroname != "Keywords" {
            return;
        }
        let Some(group) = first_group_arg_brace_only(m, parent, idx) else {
            return;
        };
        let text = group_plain_text(group);
        let entries: Vec<String> = text
            .split(',')
            .map(|e| e.trim().to_string())
            .filter(|e| !e.is_empty())
            .collect();
        // Only Title Case across entries is a defect; a fully-lowercase
        // list is the journal's published convention (F5 narrowing).
        if keyword_case_violation(&entries) {
            out.push(tex_violation_with_fix(
                file,
                &line_index,
                m.span.pos,
                "JSS-CAP-004",
                Some(
                    "Use sentence case for keywords: do not capitalise words after the first in an entry (proper names and abbreviations excepted)."
                        .to_string(),
                ),
                None,
            ));
        }
    });
    out
}