badness 0.4.0

An LSP, formatter, and linter for LaTeX
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! The `badness` command-line interface.
//!
//! Phase 2 MVP: a `format` subcommand that formats `.tex` files in place (or
//! stdin → stdout), plus `--check` to report whether files are already
//! formatted. The formatter itself is an identity lowering for now (see
//! `formatter::core`), so formatting is byte-for-byte stable.
//!
//! Deferred (later Phase 2): `build.rs` man pages / shell completions /
//! markdown via `clap_mangen` / `clap_complete` / `clap-markdown`, and
//! directory-walking file discovery.

use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use badness::config::Config;
use badness::file_discovery::{
    ExcludeFilter, FileDiscoveryError, FileKind, collect_lint_files, file_kind_or_tex,
};
use badness::formatter::{
    FormatStyle, WrapMode, check_paths_with_style, format_file_with_packages,
    format_with_style_flavored,
};
use badness::linter::{
    Diagnostic, OutputMode, RuleSelection, apply_fixes, check_document, lint_document,
    render_findings,
};
use std::collections::HashMap;

use badness::parser::{LexConfig, parse_with_flavor};
use badness::project::labels::{document_label_names, is_document_root};
use badness::project::{
    CiteFileFacts, FileFacts, IncludeGraph, ResolvedCitations, ResolvedLabels,
    collect_bib_resource_targets, collect_include_edge_keys,
};
use badness::semantic::SemanticModel;
use badness::syntax::SyntaxNode;
use clap::{Parser, Subcommand, ValueEnum};
use rowan::NodeOrToken;
use smol_str::SmolStr;

/// CLI surface for [`WrapMode`]. Kept here (not in the formatter) so the
/// formatter API stays clap-free, mirroring arity's `cli.rs` convention.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum WrapArg {
    /// Greedy fill: wrap words to the line width (default).
    Reflow,
    /// One sentence per line. (Not yet implemented — behaves like `preserve`.)
    Sentence,
    /// Semantic line breaks (sembr.org). (Not yet implemented — like `preserve`.)
    Semantic,
    /// Leave authored line breaks untouched.
    Preserve,
}

impl From<WrapArg> for WrapMode {
    fn from(arg: WrapArg) -> Self {
        match arg {
            WrapArg::Reflow => WrapMode::Reflow,
            WrapArg::Sentence => WrapMode::Sentence,
            WrapArg::Semantic => WrapMode::Semantic,
            WrapArg::Preserve => WrapMode::Preserve,
        }
    }
}

#[derive(Parser)]
#[command(
    name = "badness",
    version,
    about = "A formatter, linter, and language server for LaTeX"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
    /// Path to a `badness.toml` to use instead of discovering one. Applies to
    /// `format` and `lint`; ignored by `parse`, `lsp`, and `init`.
    #[arg(long, value_name = "PATH", global = true, conflicts_with = "no_config")]
    config: Option<PathBuf>,
    /// Ignore any `badness.toml` and use built-in defaults.
    #[arg(long, global = true)]
    no_config: bool,
}

#[derive(Subcommand)]
enum Command {
    /// Format LaTeX source.
    ///
    /// With paths, formats each file in place. With no paths, reads stdin and
    /// writes the formatted result to stdout.
    Format {
        /// Files to format. Omit to read from stdin.
        paths: Vec<PathBuf>,
        /// Report which files would change without writing them. Exits non-zero
        /// if any file is not already formatted.
        #[arg(long)]
        check: bool,
        /// Name the stdin buffer so its language is dispatched by extension
        /// (`.bib` → BibTeX, anything else → LaTeX). No file is read or written;
        /// only the extension is used. Ignored when paths are given.
        #[arg(long, value_name = "PATH")]
        stdin_filepath: Option<PathBuf>,
        /// Maximum line width before the formatter breaks a line.
        #[arg(long)]
        line_width: Option<usize>,
        /// Number of spaces per indent step.
        #[arg(long)]
        indent_width: Option<usize>,
        /// How to lay out line breaks inside a paragraph.
        #[arg(long, value_enum)]
        wrap: Option<WrapArg>,
        /// Gitignore-style pattern to skip during directory discovery (repeatable).
        /// Added on top of any `exclude`/`extend-exclude` from `badness.toml`.
        #[arg(long, value_name = "PATTERN")]
        exclude: Vec<String>,
    },
    /// Lint LaTeX source, reporting parse diagnostics.
    ///
    /// With paths, lints each file. With no paths, reads stdin. Exits non-zero
    /// if any diagnostics are reported.
    Lint {
        /// Files to lint. Omit to read from stdin.
        paths: Vec<PathBuf>,
        /// Apply safe autofixes in place, then report what remains. Requires
        /// path arguments; has no effect on stdin (there is nothing to write).
        #[arg(long)]
        fix: bool,
        /// Also apply fixes that may change typeset output (requires `--fix`).
        #[arg(long)]
        unsafe_fixes: bool,
        /// Name the stdin buffer so its language is dispatched by extension
        /// (`.bib` → BibTeX, anything else → LaTeX). No file is read or written;
        /// only the extension is used. Ignored when paths are given.
        #[arg(long, value_name = "PATH")]
        stdin_filepath: Option<PathBuf>,
        /// Gitignore-style pattern to skip during directory discovery (repeatable).
        /// Added on top of any `exclude`/`extend-exclude` from `badness.toml`.
        #[arg(long, value_name = "PATTERN")]
        exclude: Vec<String>,
        /// Run only these rules (repeatable). Overrides `[lint] select` from
        /// `badness.toml` when given.
        #[arg(long, value_name = "RULE")]
        select: Vec<String>,
        /// Disable these rules (repeatable). Overrides `[lint] ignore` from
        /// `badness.toml` when given.
        #[arg(long, value_name = "RULE")]
        ignore: Vec<String>,
    },
    /// Parse LaTeX source and print its concrete syntax tree (CST).
    ///
    /// A debugging aid: prints the lossless parse tree as an indented
    /// `KIND@range` listing, with token text, followed by any parse errors.
    /// With a path, parses that file. With no path, reads stdin.
    Parse {
        /// File to parse. Omit to read from stdin.
        path: Option<PathBuf>,
    },
    /// Run the language server over stdio.
    Lsp,
    /// Write a commented starter `badness.toml` to the current directory.
    Init {
        /// Overwrite an existing `badness.toml`.
        #[arg(long)]
        force: bool,
    },
}

fn main() -> ExitCode {
    let Cli {
        command,
        config: config_arg,
        no_config,
    } = Cli::parse();
    match command {
        Command::Format {
            paths,
            check,
            stdin_filepath,
            line_width,
            indent_width,
            wrap,
            exclude,
        } => {
            // Discover/load `badness.toml` from the working directory (one config
            // per invocation, like arity's CLI). The exclude filter is rooted at
            // the config's directory so its patterns resolve relative to it.
            let anchor = match cwd_anchor() {
                Ok(anchor) => anchor,
                Err(code) => return code,
            };
            let (config, config_path) =
                match resolve_config(config_arg.as_deref(), no_config, &anchor) {
                    Ok(resolved) => resolved,
                    Err(code) => return code,
                };
            let exclude_filter =
                match build_exclude_filter(&config, config_path.as_deref(), &anchor, &exclude) {
                    Ok(filter) => filter,
                    Err(code) => return code,
                };

            let mut style = FormatStyle::from(&config.format);
            if let Some(w) = line_width {
                style.line_width = w;
            }
            if let Some(w) = indent_width {
                style.indent_width = w;
            }
            // Wrap precedence: `--wrap` > config `wrap` > file-kind default. The
            // override is `None` only when neither is set, leaving each file on its
            // kind's default wrap (`.sty`/`.cls`/`.dtx`/`.ins` → Preserve, `.tex` →
            // Reflow), resolved per file at dispatch.
            let wrap_override: Option<WrapMode> =
                wrap.map(Into::into).or(config.format.wrap.map(Into::into));
            run_format(
                &paths,
                check,
                stdin_filepath.as_deref(),
                style,
                wrap_override,
                &exclude_filter,
            )
        }
        Command::Lint {
            paths,
            fix,
            unsafe_fixes,
            stdin_filepath,
            exclude,
            select,
            ignore,
        } => {
            let anchor = match cwd_anchor() {
                Ok(anchor) => anchor,
                Err(code) => return code,
            };
            let (mut config, config_path) =
                match resolve_config(config_arg.as_deref(), no_config, &anchor) {
                    Ok(resolved) => resolved,
                    Err(code) => return code,
                };
            let exclude_filter =
                match build_exclude_filter(&config, config_path.as_deref(), &anchor, &exclude) {
                    Ok(filter) => filter,
                    Err(code) => return code,
                };
            // CLI `--select`/`--ignore` override the configured selection when given.
            if !select.is_empty() {
                config.lint.select = Some(select);
            }
            if !ignore.is_empty() {
                config.lint.ignore = ignore;
            }
            let (rules, unknown) =
                RuleSelection::resolve(config.lint.select.as_deref(), &config.lint.ignore);
            for id in &unknown {
                eprintln!("badness: warning: unknown lint rule `{id}`");
            }
            run_lint(
                &paths,
                fix,
                unsafe_fixes,
                stdin_filepath.as_deref(),
                &exclude_filter,
                &rules,
            )
        }
        Command::Parse { path } => run_parse(path.as_deref()),
        Command::Lsp => run_lsp(),
        Command::Init { force } => run_init(force),
    }
}

/// The directory to anchor config discovery and exclude-pattern roots at: the
/// current working directory.
fn cwd_anchor() -> Result<PathBuf, ExitCode> {
    std::env::current_dir().map_err(|err| {
        eprintln!("badness: cannot determine the current directory: {err}");
        ExitCode::from(2)
    })
}

/// Resolve the effective config, mapping any [`ConfigError`] to a stderr message
/// and exit code 2.
fn resolve_config(
    explicit: Option<&Path>,
    no_config: bool,
    anchor: &Path,
) -> Result<(Config, Option<PathBuf>), ExitCode> {
    Config::resolve(explicit, no_config, anchor).map_err(|err| {
        eprintln!("badness: {err}");
        ExitCode::from(2)
    })
}

/// Build the directory-discovery exclude filter from the resolved config plus any
/// `--exclude` CLI patterns. Patterns resolve relative to the directory holding
/// `badness.toml` (or `anchor` when there is no config file).
fn build_exclude_filter(
    config: &Config,
    config_path: Option<&Path>,
    anchor: &Path,
    cli_excludes: &[String],
) -> Result<ExcludeFilter, ExitCode> {
    let root = config_path
        .and_then(Path::parent)
        .unwrap_or(anchor)
        .to_path_buf();
    let patterns = config.exclude_patterns(cli_excludes);
    ExcludeFilter::new(&root, &patterns).map_err(|err| {
        eprintln!("badness: {err}");
        ExitCode::from(2)
    })
}

/// A commented starter `badness.toml` showing every key at its default.
const STARTER_CONFIG: &str = "\
# badness configuration. All keys are optional; values shown are the defaults.

# Gitignore-style patterns to skip during directory discovery. `exclude` replaces
# the built-in default set (`.git/`); `extend-exclude` adds on top of it. Both
# apply to `format` and `lint`.
# exclude = [\".git/\"]
# extend-exclude = []

[format]
# line-width = 80
# indent-width = 2
# wrap = \"reflow\"  # reflow | sentence | semantic | preserve
                     # omit to use each file kind's default
                     # (.tex -> reflow, .sty/.cls/.dtx/.ins -> preserve)

[lint]
# select = [\"...\"]  # if set, only these rules run
# ignore = []        # rules to disable
";

/// `badness init`: write a commented starter config to `<cwd>/badness.toml`.
fn run_init(force: bool) -> ExitCode {
    let anchor = match cwd_anchor() {
        Ok(anchor) => anchor,
        Err(code) => return code,
    };
    let path = anchor.join(badness::config::CONFIG_FILE_NAME);
    if path.exists() && !force {
        eprintln!(
            "badness: {} already exists; pass --force to overwrite",
            path.display()
        );
        return ExitCode::from(2);
    }
    match std::fs::write(&path, STARTER_CONFIG) {
        Ok(()) => {
            println!("Wrote {}", path.display());
            ExitCode::SUCCESS
        }
        Err(err) => {
            eprintln!("badness: failed to write {}: {err}", path.display());
            ExitCode::from(2)
        }
    }
}

/// Run the language server, mapping a startup failure to a non-zero exit.
fn run_lsp() -> ExitCode {
    match badness::lsp::run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("badness: language server error: {err}");
            ExitCode::FAILURE
        }
    }
}

/// Cap on fixpoint iterations per file, guarding against a fix that fails to
/// clear its own diagnostic.
const MAX_FIX_ITERATIONS: usize = 10;

/// Lint each path (or stdin), rendering parse diagnostics. Exits non-zero if
/// any diagnostics are reported or any file fails to read. With `fix`, safe
/// autofixes (plus unsafe ones when `unsafe_fixes` is set) are applied in place
/// first; the reporting pass below then shows whatever findings remain.
fn run_lint(
    paths: &[PathBuf],
    fix: bool,
    unsafe_fixes: bool,
    stdin_filepath: Option<&Path>,
    exclude: &ExcludeFilter,
    rules: &RuleSelection,
) -> ExitCode {
    // Apply fixes in place first; the reporting pass below then re-reads from
    // disk and shows whatever findings remain. Mirrors arity's two-pass flow.
    // Stdin (no paths) has nowhere to write back, so `--fix` only acts on files.
    if fix
        && !paths.is_empty()
        && let Some(code) = apply_fixes_to_paths(paths, unsafe_fixes, exclude, rules)
    {
        return code;
    }

    // Hold each file's text (and which pipeline it feeds) in memory keyed by the
    // label we report it under, so the renderer can fetch source for snippets
    // without re-reading from disk (and so stdin, which has no path, still gets a
    // source). Stdin has no extension to dispatch on, so it is LaTeX unless
    // `--stdin-filepath` names the buffer (`.bib` → BibTeX); the label stays
    // `<stdin>` regardless, so the named path never reaches the report or disk.
    let mut sources: Vec<(PathBuf, String, FileKind)> = Vec::new();
    let mut failed = false;

    if paths.is_empty() {
        let mut input = String::new();
        if let Err(err) = std::io::stdin().read_to_string(&mut input) {
            eprintln!("badness: cannot read stdin: {err}");
            return ExitCode::FAILURE;
        }
        let kind = stdin_filepath.map_or(FileKind::Tex, file_kind_or_tex);
        sources.push((PathBuf::from("<stdin>"), input, kind));
    } else {
        let files = match collect_lint_files(paths, exclude) {
            Ok(files) => files,
            Err(err) => {
                report_discovery_error(&err);
                return ExitCode::FAILURE;
            }
        };
        if files.is_empty() {
            eprintln!(
                "badness: no .tex, .sty, .cls, .dtx, .ins, or .bib files found under the provided input paths"
            );
            return ExitCode::FAILURE;
        }
        for (path, kind) in files {
            match std::fs::read_to_string(&path) {
                Ok(content) => sources.push((path, content, kind)),
                Err(err) => {
                    eprintln!("badness: cannot read {}: {err}", path.display());
                    failed = true;
                }
            }
        }
    }

    // Parse and build the per-file model for every LaTeX source first: cross-file
    // label resolution needs the whole analyzed set before any one file can be
    // linted. `.bib` files have no cross-file resolution yet (Phase 4), so each is
    // linted standalone via the bib driver and its findings folded straight in.
    // Lint rules run off these parses — no salsa needed on the CLI path (the salsa
    // firewall is an editor-incrementality concern; mirrors arity's
    // `check_document`). The resolver reuses the *same* pure helpers the salsa
    // queries do (`document_label_names`, `is_document_root`,
    // `collect_include_edge_keys`, `ResolvedLabels::build`), so CLI and LSP agree.
    let mut diagnostics: Vec<Diagnostic> = Vec::new();
    let mut analyzed: Vec<(&PathBuf, SyntaxNode, SemanticModel)> = Vec::new();
    let mut facts: Vec<FileFacts> = Vec::new();
    let mut label_inputs = Vec::new();
    let mut cite_facts: Vec<CiteFileFacts> = Vec::new();
    // Cite keys per analyzed `.bib` path, feeding the cross-file citation resolver.
    let mut bib_keys: HashMap<PathBuf, Vec<SmolStr>> = HashMap::new();
    for (path, content, kind) in &sources {
        match kind {
            FileKind::Bib => {
                // Build the model once: it yields both the lint diagnostics and the
                // cite keys this `.bib` contributes to the citation resolver.
                let parsed = badness::bib::parse(content);
                diagnostics.extend(parsed.errors.iter().map(|err| Diagnostic {
                    rule: "parse",
                    severity: badness::linter::Severity::Error,
                    path: path.clone(),
                    start: err.start,
                    end: err.end,
                    message: err.message.clone(),
                    fix: None,
                }));
                let root = parsed.syntax();
                let model = badness::bib::semantic::Model::build(&root);
                bib_keys.insert(
                    path.clone(),
                    model.entries().iter().map(|e| e.key.clone()).collect(),
                );
                diagnostics.extend(badness::bib::linter::lint_document(path, &root, &model));
            }
            FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
                let parsed = parse_with_flavor(content, kind.lex_config());
                diagnostics.extend(
                    parsed
                        .errors
                        .iter()
                        .map(|err| Diagnostic::from_parse(path.clone(), err)),
                );
                let root = SyntaxNode::new_root(parsed.green);
                let model = SemanticModel::build(&root);
                facts.push(FileFacts {
                    path: path.clone(),
                    include_edges: collect_include_edge_keys(&root, path.parent()),
                });
                label_inputs.push((
                    path.clone(),
                    document_label_names(&model),
                    is_document_root(&root),
                ));
                cite_facts.push(CiteFileFacts {
                    path: path.clone(),
                    bib_targets: collect_bib_resource_targets(&root, path.parent()),
                    nocite_all: model.has_wildcard_nocite(),
                    is_document_root: is_document_root(&root),
                });
                analyzed.push((path, root, model));
            }
        }
    }

    let graph = IncludeGraph::build(&facts, None);
    let resolved = ResolvedLabels::build(&label_inputs, &graph);
    let resolved_citations = ResolvedCitations::build(&cite_facts, &graph, &bib_keys);
    for (path, root, model) in &analyzed {
        diagnostics.extend(lint_document(
            path,
            root,
            model,
            Some(&resolved),
            Some(&resolved_citations),
        ));
    }

    // Drop findings from rules the config/CLI deselected. Parse diagnostics
    // (`rule == "parse"`) are always kept (see `RuleSelection::is_active`).
    diagnostics.retain(|d| rules.is_active(d.rule));

    // Findings from the two pipelines arrive interleaved by file; sort so the
    // renderer presents them deterministically (by path, then position).
    diagnostics.sort_by(|a, b| {
        a.path
            .cmp(&b.path)
            .then(a.start.cmp(&b.start))
            .then(a.end.cmp(&b.end))
            .then(a.rule.cmp(b.rule))
    });

    if !diagnostics.is_empty() {
        let source_for = |path: &Path| {
            sources
                .iter()
                .find(|(p, _, _)| p == path)
                .map(|(_, text, _)| text.clone())
        };
        eprint!(
            "{}",
            render_findings(&diagnostics, OutputMode::Pretty, &source_for)
        );
    }

    if failed || !diagnostics.is_empty() {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

/// Discover lintable files under `paths` and apply autofixes in place. Returns
/// `Some(exit_code)` only on a hard error (discovery / IO); on success returns
/// `None` so the caller falls through to the normal reporting pass. Mirrors
/// arity's `apply_fixes_to_paths`.
///
/// Both `.tex` and `.bib` files are fixed, each through its own linter; rules that
/// emit no autofix (the report-only majority) leave their findings for the
/// reporting pass that follows.
fn apply_fixes_to_paths(
    paths: &[PathBuf],
    include_unsafe: bool,
    exclude: &ExcludeFilter,
    rules: &RuleSelection,
) -> Option<ExitCode> {
    let files = match collect_lint_files(paths, exclude) {
        Ok(files) => files,
        Err(err) => {
            report_discovery_error(&err);
            return Some(ExitCode::FAILURE);
        }
    };
    if files.is_empty() {
        eprintln!("badness: no .tex or .bib files found under the provided input paths");
        return Some(ExitCode::FAILURE);
    }
    for (path, kind) in files {
        match fix_file(&path, kind, include_unsafe, rules) {
            Ok(0) => {}
            Ok(n) => eprintln!("{}: {n} fix{} applied", path.display(), plural(n)),
            Err(err) => {
                eprintln!("badness: cannot fix {}: {err}", path.display());
                return Some(ExitCode::FAILURE);
            }
        }
    }
    None
}

/// Run the fixpoint loop on a single file and write it back if anything changed.
/// Returns the number of individual fixes applied. Re-lints after each round so
/// fixes can cascade; bounded by [`MAX_FIX_ITERATIONS`]. Mirrors arity's
/// `fix_file`. Routes to the LaTeX or BibTeX linter by [`FileKind`]. `rules` gates
/// which findings contribute fixes, so a deselected rule's autofix never applies.
fn fix_file(
    path: &Path,
    kind: FileKind,
    include_unsafe: bool,
    rules: &RuleSelection,
) -> std::io::Result<usize> {
    let mut content = std::fs::read_to_string(path)?;
    let mut total = 0usize;
    for _ in 0..MAX_FIX_ITERATIONS {
        let diagnostics = match kind {
            FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
                check_document(path, &content, kind.lex_config())
            }
            FileKind::Bib => badness::bib::linter::check_document(path, &content),
        };
        let fixes: Vec<_> = diagnostics
            .into_iter()
            .filter(|d| rules.is_active(d.rule))
            .filter_map(|d| d.fix)
            .collect();
        if fixes.is_empty() {
            break;
        }
        let outcome = apply_fixes(&content, &fixes, include_unsafe);
        if outcome.applied == 0 {
            break;
        }
        total += outcome.applied;
        content = outcome.output;
    }
    if total > 0 {
        std::fs::write(path, &content)?;
    }
    Ok(total)
}

fn plural(n: usize) -> &'static str {
    if n == 1 { "" } else { "es" }
}

/// Parse a single file (or stdin) and print its CST to stdout. Parse errors are
/// printed after the tree; the command exits non-zero if any are reported.
fn run_parse(path: Option<&Path>) -> ExitCode {
    let input = match path {
        Some(path) => match std::fs::read_to_string(path) {
            Ok(content) => content,
            Err(err) => {
                eprintln!("badness: cannot read {}: {err}", path.display());
                return ExitCode::FAILURE;
            }
        },
        None => {
            let mut input = String::new();
            if let Err(err) = std::io::stdin().read_to_string(&mut input) {
                eprintln!("badness: cannot read stdin: {err}");
                return ExitCode::FAILURE;
            }
            input
        }
    };

    let config = path.map_or(LexConfig::default(), |p| file_kind_or_tex(p).lex_config());
    let parsed = parse_with_flavor(&input, config);
    let mut out = String::new();
    render_cst(&parsed.syntax(), 0, &mut out);
    if let Err(err) = std::io::stdout().write_all(out.as_bytes()) {
        eprintln!("badness: cannot write stdout: {err}");
        return ExitCode::FAILURE;
    }

    if parsed.errors.is_empty() {
        ExitCode::SUCCESS
    } else {
        for err in &parsed.errors {
            eprintln!("error @{}..{}: {}", err.start, err.end, err.message);
        }
        ExitCode::FAILURE
    }
}

/// Render a CST as an indented `KIND@range` tree, with token text. Kept in sync
/// with the test renderer in `tests/parser.rs`.
fn render_cst(node: &SyntaxNode, depth: usize, out: &mut String) {
    out.push_str(&format!(
        "{:indent$}{:?}@{:?}\n",
        "",
        node.kind(),
        node.text_range(),
        indent = depth * 2
    ));
    for child in node.children_with_tokens() {
        match child {
            NodeOrToken::Node(n) => render_cst(&n, depth + 1, out),
            NodeOrToken::Token(t) => out.push_str(&format!(
                "{:indent$}{:?}@{:?} {:?}\n",
                "",
                t.kind(),
                t.text_range(),
                t.text(),
                indent = (depth + 1) * 2
            )),
        }
    }
}

fn run_format(
    paths: &[PathBuf],
    check: bool,
    stdin_filepath: Option<&Path>,
    style: FormatStyle,
    wrap_override: Option<WrapMode>,
    exclude: &ExcludeFilter,
) -> ExitCode {
    if check {
        return run_check(paths, style, wrap_override, exclude);
    }
    if paths.is_empty() {
        // Stdin has no directory to walk, so the exclude filter never applies.
        run_format_stdin(stdin_filepath, style, wrap_override)
    } else {
        run_format_paths(paths, style, wrap_override, exclude)
    }
}

/// `--check`: report unformatted files, exit code 1 if any.
fn run_check(
    paths: &[PathBuf],
    style: FormatStyle,
    wrap_override: Option<WrapMode>,
    exclude: &ExcludeFilter,
) -> ExitCode {
    match check_paths_with_style(paths, style, wrap_override, exclude) {
        Ok(result) => {
            if result.changed_files.is_empty() {
                ExitCode::SUCCESS
            } else {
                for path in &result.changed_files {
                    eprintln!("would reformat {}", path.display());
                }
                eprintln!(
                    "{} of {} file(s) would be reformatted",
                    result.changed_files.len(),
                    result.checked_files
                );
                ExitCode::FAILURE
            }
        }
        Err(err) => {
            eprintln!("badness: {err}");
            ExitCode::FAILURE
        }
    }
}

/// No paths: read stdin, format, write to stdout. The pipeline is chosen from
/// `stdin_filepath`'s extension (`.bib` → BibTeX, else LaTeX); with no name given,
/// stdin stays LaTeX, the long-standing conservative default.
fn run_format_stdin(
    stdin_filepath: Option<&Path>,
    mut style: FormatStyle,
    wrap_override: Option<WrapMode>,
) -> ExitCode {
    let mut input = String::new();
    if let Err(err) = std::io::stdin().read_to_string(&mut input) {
        eprintln!("badness: cannot read stdin: {err}");
        return ExitCode::FAILURE;
    }
    let kind = stdin_filepath.map_or(FileKind::Tex, file_kind_or_tex);
    style.wrap = wrap_override.unwrap_or(kind.default_wrap());
    let formatted = match kind {
        FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
            format_with_style_flavored(&input, style, kind.lex_config()).map_err(|e| e.to_string())
        }
        FileKind::Bib => badness::bib::format_with_style(&input, style).map_err(|e| e.to_string()),
    };
    match formatted {
        Ok(formatted) => {
            if let Err(err) = std::io::stdout().write_all(formatted.as_bytes()) {
                eprintln!("badness: cannot write stdout: {err}");
                return ExitCode::FAILURE;
            }
            ExitCode::SUCCESS
        }
        Err(msg) => {
            eprintln!("badness: {msg}");
            ExitCode::FAILURE
        }
    }
}

/// Print a file-discovery error to stderr, prefixed like the other CLI errors.
fn report_discovery_error(err: &FileDiscoveryError) {
    match err {
        FileDiscoveryError::NonTexFilePath { path } => {
            eprintln!(
                "badness: input file {} is not a .tex file; only .tex files are supported",
                path.display()
            );
        }
        FileDiscoveryError::UnsupportedLintFilePath { path } => {
            eprintln!(
                "badness: input file {} is not a .tex, .sty, .cls, .dtx, .ins, or .bib file",
                path.display()
            );
        }
        FileDiscoveryError::WalkError { path, message } => {
            eprintln!(
                "badness: failed while scanning {}: {message}",
                path.display()
            );
        }
    }
}

/// Resolve the input paths to `.tex`/`.bib` files and format each in place,
/// writing only files whose content changes. Each file is routed to its own
/// formatter by [`FileKind`].
fn run_format_paths(
    paths: &[PathBuf],
    mut style: FormatStyle,
    wrap_override: Option<WrapMode>,
    exclude: &ExcludeFilter,
) -> ExitCode {
    let files = match collect_lint_files(paths, exclude) {
        Ok(files) => files,
        Err(err) => {
            report_discovery_error(&err);
            return ExitCode::FAILURE;
        }
    };
    if files.is_empty() {
        eprintln!(
            "badness: no .tex, .sty, .cls, .dtx, .ins, or .bib files found under the provided input paths"
        );
        return ExitCode::FAILURE;
    }

    let mut failed = false;
    for (path, kind) in &files {
        let content = match std::fs::read_to_string(path) {
            Ok(content) => content,
            Err(err) => {
                eprintln!("badness: cannot read {}: {err}", path.display());
                failed = true;
                continue;
            }
        };
        style.wrap = wrap_override.unwrap_or(kind.default_wrap());
        let formatted = match kind {
            FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
                format_file_with_packages(&content, path, style, kind.lex_config())
                    .map_err(|e| e.to_string())
            }
            FileKind::Bib => {
                badness::bib::format_with_style(&content, style).map_err(|e| e.to_string())
            }
        };
        match formatted {
            Ok(formatted) => {
                if formatted != *content
                    && let Err(err) = std::fs::write(path, formatted)
                {
                    eprintln!("badness: cannot write {}: {err}", path.display());
                    failed = true;
                }
            }
            Err(msg) => {
                eprintln!("badness: cannot format {}: {msg}", path.display());
                failed = true;
            }
        }
    }
    if failed {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}