vorto 0.15.1

A Vim-flavored modal terminal editor with batteries included: tree-sitter, LSP, fuzzy pickers, vim-surround, multi-cursor, and optional Copilot.
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
//! `vorto grammar …` subcommand dispatcher.
//!
//! Three operations:
//!
//! * `list` — print every built-in recipe with installed/missing status.
//! * `install <name>…` (or `--all`) — fetch, build, and place the
//!   `.so`/`.dylib`/`.dll` into the configured `grammar_dir`.
//! * `remove <name>…` — delete the installed library.
//!
//! The grammar directory is read from the same `Config::load` path the
//! editor uses, so anything installed here is immediately picked up next
//! time the editor starts.
//!
//! The recipe catalog is the built-in list plus any user
//! `[grammars.<name>]` entries from config (a user entry overrides a
//! built-in of the same name). User-defined grammars install just like
//! built-ins, except their queries are user-supplied — only built-ins
//! carry bundled `.scm` files.

use std::path::Path;

use anyhow::{Result, bail};

use crate::config::{self, Config, GrammarSource, LanguageRegistry};

use super::assets;
use super::build;
use super::recipe::{GrammarRecipe, builtin_recipes};

/// Entry point invoked from `main` when `argv[1] == "grammar"`. `args`
/// is everything after the `grammar` token.
pub fn run(args: &[String]) -> Result<()> {
    let cfg = Config::load(config::default_path().as_deref())?;
    let grammar_dir = cfg.grammar_dir.as_path();
    let query_dir = cfg.query_dir.as_path();
    // Built-in catalog plus any user `[grammars.*]` recipes (a user
    // entry whose name matches a built-in overrides it).
    let recipes = merged_recipes(&cfg.grammars);

    match args.split_first() {
        None => {
            print_usage();
            Ok(())
        }
        Some((cmd, rest)) => match cmd.as_str() {
            "list" | "ls" => list(rest, &recipes, &cfg.languages, grammar_dir, query_dir),
            "install" | "add" => install(rest, &recipes, grammar_dir, query_dir),
            "install-queries" | "refresh-queries" => install_queries(rest, &recipes, query_dir),
            "bundle" => bundle(rest),
            "remove" | "rm" | "uninstall" => remove(rest, grammar_dir),
            "help" | "-h" | "--help" => {
                print_usage();
                Ok(())
            }
            other => {
                print_usage();
                bail!("unknown grammar subcommand: `{}`", other);
            }
        },
    }
}

/// Built-in recipes overlaid with the user's `[grammars.*]` entries.
/// A user entry with the same name as a built-in replaces it (so users
/// can repoint a grammar at a fork or newer revision); new names are
/// appended.
///
/// Public so the in-editor `:grammar` command can build the same
/// config-aware catalog the CLI uses.
pub fn merged_recipes(user: &[GrammarSource]) -> Vec<GrammarRecipe> {
    let mut recipes = builtin_recipes();
    for g in user {
        let recipe =
            GrammarRecipe::from_config(&g.name, &g.source, g.rev.as_deref(), g.subpath.as_deref());
        match recipes.iter_mut().find(|r| r.name == g.name) {
            Some(slot) => *slot = recipe,
            None => recipes.push(recipe),
        }
    }
    recipes
}

fn find<'a>(recipes: &'a [GrammarRecipe], name: &str) -> Option<&'a GrammarRecipe> {
    recipes.iter().find(|r| r.name == name)
}

fn print_usage() {
    eprintln!("usage: vorto grammar <command> [args]");
    eprintln!();
    eprintln!("commands:");
    eprintln!("  list [-v]                         show install status (grouped; -v for detail)");
    eprintln!("  install <name>... | --all         build and install one or more grammars");
    eprintln!("  install-queries <name>... | --all overwrite installed .scm files from the");
    eprintln!("                                    vendored bundle (no library rebuild)");
    eprintln!("  remove <name>...                  delete installed grammar libraries");
    eprintln!("  bundle                            build all built-ins -> gzip'd libs in");
    eprintln!("                                    assets/grammars-prebuilt/<target>/, and write");
    eprintln!("                                    THIRD_PARTY_LICENSES from the cloned sources");
    eprintln!();
    eprintln!("examples:");
    eprintln!("  vorto grammar install rust python");
    eprintln!("  vorto grammar install --all");
    eprintln!("  vorto grammar install-queries python");
    eprintln!("  vorto grammar list");
    eprintln!();
    eprintln!("define non-built-in grammars in config under [grammars.<name>]:");
    eprintln!("  [grammars.nim]");
    eprintln!("  source  = \"https://github.com/alaviss/tree-sitter-nim\"");
    eprintln!("  rev     = \"abc123\"   # optional; omit to build the latest default branch");
    eprintln!("  subpath = \"sub\"      # optional; for monorepos");
}

fn list(
    args: &[String],
    recipes: &[GrammarRecipe],
    languages: &LanguageRegistry,
    grammar_dir: &Path,
    query_dir: &Path,
) -> Result<()> {
    if args.iter().any(|a| a == "-v" || a == "--verbose") {
        return list_verbose(recipes, languages, grammar_dir, query_dir);
    }

    println!("grammar dir: {}", grammar_dir.display());
    println!("query dir:   {}", query_dir.display());
    println!();

    // Three states: a grammar is "installed" once its library plus every
    // bundled query is on disk; "lib only" means the library built but
    // some queries are missing (rare — usually manual tinkering); the
    // rest are "missing". Empty groups are skipped so the common case is
    // just installed/missing.
    let (mut installed, mut lib_only, mut missing) = (Vec::new(), Vec::new(), Vec::new());
    for r in recipes {
        if build::installed_path(r.name, grammar_dir).is_none() {
            missing.push(r.name);
        } else if build::is_fully_installed(r.name, grammar_dir, query_dir) {
            installed.push(r.name);
        } else {
            lib_only.push(r.name);
        }
    }
    let total = installed.len() + lib_only.len() + missing.len();

    print_group("installed", &installed);
    print_group("lib only, queries missing", &lib_only);
    print_group("missing", &missing);

    println!(
        "{} total · {} installed · {} missing",
        total,
        installed.len() + lib_only.len(),
        missing.len()
    );

    // Grammars referenced by `[languages.*]` config that have no recipe
    // at all (built-in or user `[grammars.*]`). These can't be installed
    // via `grammar install` — the user supplies the `.so` — so they get
    // their own section with per-entry status.
    let custom = custom_grammars(recipes, languages, grammar_dir);
    if !custom.is_empty() {
        println!();
        println!("custom (from config) ({}):", custom.len());
        for c in &custom {
            let glyph = if c.installed { "✓" } else { "✗" };
            println!("  {} {}", glyph, c.grammar);
        }
        if custom.iter().any(|c| !c.installed) {
            println!(
                "  (✗ = no library found and no recipe — add a `[grammars.<name>]` entry to install it, or drop the compiled `.so` in yourself)"
            );
        }
    }

    println!("(-v for repo URLs and per-grammar query detail)");
    Ok(())
}

/// A grammar referenced by a `[languages.*]` config entry that has no
/// recipe at all — the user is responsible for supplying its library.
struct CustomGrammar {
    grammar: String,
    installed: bool,
}

/// Collect grammars referenced by config languages that have no recipe
/// (neither built-in nor user `[grammars.*]`), deduped by grammar stem
/// and sorted by name. Each language may override the global grammar
/// dir, so install status is checked against the language's effective
/// dir.
fn custom_grammars(
    recipes: &[GrammarRecipe],
    languages: &LanguageRegistry,
    grammar_dir: &Path,
) -> Vec<CustomGrammar> {
    use std::collections::HashSet;
    let has_recipe: HashSet<&str> = recipes.iter().map(|r| r.name).collect();
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    for lang in languages.iter() {
        if has_recipe.contains(lang.grammar.as_str()) || !seen.insert(lang.grammar.clone()) {
            continue;
        }
        let dir = lang.grammar_dir.as_deref().unwrap_or(grammar_dir);
        out.push(CustomGrammar {
            grammar: lang.grammar.clone(),
            installed: build::installed_path(&lang.grammar, dir).is_some(),
        });
    }
    out.sort_by(|a, b| a.grammar.cmp(&b.grammar));
    out
}

/// Print `<label> (<n>):` followed by the names laid out in aligned,
/// terminal-width-aware columns. No-op for an empty group.
fn print_group(label: &str, names: &[&str]) {
    if names.is_empty() {
        return;
    }
    println!("{} ({}):", label, names.len());

    const INDENT: usize = 2;
    let term_w = crossterm::terminal::size()
        .map(|(c, _)| c as usize)
        .unwrap_or(80);
    let col_w = names.iter().map(|n| n.len()).max().unwrap_or(1) + 2;
    let cols = (term_w.saturating_sub(INDENT) / col_w).max(1);

    for row in names.chunks(cols) {
        let mut line = " ".repeat(INDENT);
        for name in row {
            line.push_str(&format!("{:<width$}", name, width = col_w));
        }
        println!("{}", line.trim_end());
    }
    println!();
}

/// The detailed, one-block-per-grammar view (repo URL, subpath, library
/// and query status). Reachable via `list -v`.
fn list_verbose(
    recipes: &[GrammarRecipe],
    languages: &LanguageRegistry,
    grammar_dir: &Path,
    query_dir: &Path,
) -> Result<()> {
    println!("grammar dir: {}", grammar_dir.display());
    println!("query dir:   {}", query_dir.display());
    println!();
    for r in recipes {
        let lib_status = match build::installed_path(r.name, grammar_dir) {
            Some(_) => "lib ✓",
            None => "lib ✗",
        };
        let installed = build::installed_queries(r.name, query_dir);
        let bundled = assets::bundled_query_names(r.name);
        let query_status = match (installed.is_empty(), bundled.is_empty()) {
            (false, _) => format!("queries: {} (installed)", installed.join(",")),
            (true, false) => format!("queries: {} (bundled, not installed)", bundled.join(",")),
            (true, true) => "queries: none bundled".to_string(),
        };
        let subpath = r.subpath.map(|s| format!(" [{}]", s)).unwrap_or_default();
        println!(
            "  {:<12} {}{}\n               {} | {}",
            r.name, r.repo, subpath, lib_status, query_status
        );
    }

    let custom = custom_grammars(recipes, languages, grammar_dir);
    if !custom.is_empty() {
        println!();
        println!("custom (from config):");
        for c in &custom {
            let lib_status = if c.installed { "lib ✓" } else { "lib ✗" };
            println!(
                "  {:<12} (no recipe — user-supplied)\n               {}",
                c.grammar, lib_status
            );
        }
    }
    Ok(())
}

fn install(
    args: &[String],
    recipes: &[GrammarRecipe],
    grammar_dir: &Path,
    query_dir: &Path,
) -> Result<()> {
    let recipes = match args.first().map(String::as_str) {
        None => {
            bail!("install: need at least one grammar name (or `--all`)");
        }
        Some("--all") => recipes.to_vec(),
        _ => {
            let mut out = Vec::new();
            for name in args {
                match find(recipes, name) {
                    Some(r) => out.push(r.clone()),
                    None => bail!(
                        "unknown grammar `{}`. Run `vorto grammar list` for the catalog, or define it under `[grammars.{}]` in your config.",
                        name,
                        name
                    ),
                }
            }
            out
        }
    };

    // Skip already-installed up front so the parallel worker pool
    // only sees real work. Sequential and noted inline so users see
    // the skip reason next to the name.
    let mut pending = Vec::new();
    for r in &recipes {
        if build::is_fully_installed(r.name, grammar_dir, query_dir) {
            eprintln!("==> {} already installed, skipping", r.name);
        } else {
            pending.push(r.clone());
        }
    }
    if pending.is_empty() {
        return Ok(());
    }

    // Worker pool: cap at CPU count and the job count. The per-job
    // work is mostly cc-bound (the parser is a single ~600k-line
    // translation unit), so more workers than physical cores just
    // thrashes the scheduler. Stderr is locked per-recipe so each
    // grammar's "==> installing"/"lib"/"queries" lines stay grouped.
    let workers = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4)
        .min(pending.len());
    let next = std::sync::atomic::AtomicUsize::new(0);
    let stderr_lock = std::sync::Mutex::new(());
    let failures = std::sync::Mutex::new(Vec::<&str>::new());

    std::thread::scope(|s| {
        for _ in 0..workers {
            s.spawn(|| {
                loop {
                    let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    if i >= pending.len() {
                        break;
                    }
                    let r = &pending[i];
                    let result = build::install(r, grammar_dir, query_dir);
                    let mut buf = String::new();
                    use std::fmt::Write;
                    writeln!(buf, "==> installing {} ({})", r.name, r.repo).ok();
                    match result {
                        Ok(report) => {
                            writeln!(buf, "    lib: {}", report.library.display()).ok();
                            if report.queries.is_empty() {
                                writeln!(
                                    buf,
                                    "    queries: none bundled — drop your own .scm into {}/{}/",
                                    query_dir.display(),
                                    r.name
                                )
                                .ok();
                            } else {
                                let names: Vec<String> = report
                                    .queries
                                    .iter()
                                    .filter_map(|p| {
                                        p.file_name().map(|n| n.to_string_lossy().into_owned())
                                    })
                                    .collect();
                                writeln!(
                                    buf,
                                    "    queries: {} ({} files)",
                                    names.join(", "),
                                    report.queries.len()
                                )
                                .ok();
                            }
                        }
                        Err(e) => {
                            writeln!(buf, "    failed: {:#}", e).ok();
                            failures.lock().unwrap().push(r.name);
                        }
                    }
                    let _g = stderr_lock.lock().unwrap();
                    eprint!("{}", buf);
                }
            });
        }
    });

    let failures = failures.into_inner().unwrap();
    if !failures.is_empty() {
        bail!("failed to install: {}", failures.join(", "));
    }
    Ok(())
}

/// Queries-only refresh. Rewrites `<query_dir>/<name>/*.scm` from the
/// compile-time-embedded bundle for each named grammar (or every
/// built-in recipe under `--all`), without touching the loaded `.so`.
/// `install` skips when a grammar is already fully installed, so this
/// is the way to pick up an in-repo edit to `assets/queries/*.scm`
/// without uninstalling and rebuilding the grammar.
fn install_queries(args: &[String], recipes: &[GrammarRecipe], query_dir: &Path) -> Result<()> {
    let recipes = match args.first().map(String::as_str) {
        None => {
            bail!("install-queries: need at least one grammar name (or `--all`)");
        }
        Some("--all") => recipes.to_vec(),
        _ => {
            let mut out = Vec::new();
            for name in args {
                match find(recipes, name) {
                    Some(r) => out.push(r.clone()),
                    None => bail!(
                        "unknown grammar `{}`. Run `vorto grammar list` for the catalog.",
                        name
                    ),
                }
            }
            out
        }
    };

    let mut failures = Vec::new();
    for r in &recipes {
        eprintln!("==> refreshing queries for {}", r.name);
        match build::write_vendored_queries(query_dir, r.name) {
            Ok(written) if written.is_empty() => {
                eprintln!("    queries: none bundled for `{}`", r.name);
            }
            Ok(written) => {
                let names: Vec<String> = written
                    .iter()
                    .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
                    .collect();
                eprintln!(
                    "    queries: {} ({} files)",
                    names.join(", "),
                    written.len()
                );
            }
            Err(e) => {
                eprintln!("    failed: {:#}", e);
                failures.push(r.name);
            }
        }
    }
    if !failures.is_empty() {
        bail!("failed to refresh: {}", failures.join(", "));
    }
    Ok(())
}

/// One grammar's captured licenses: `(name, repo URL, [(filename, text)])`.
/// Names/URLs come from the `'static` built-in catalog.
type GrammarLicenses = (&'static str, &'static str, Vec<(String, String)>);

/// Build every built-in grammar for the host target and write each as a
/// gzip-compressed `<name>.<ext>.gz` under
/// `assets/grammars-prebuilt/<target-triple>/`. This is the producer side
/// of the `bundled-grammars` feature: release CI runs it once per target,
/// then builds vorto with `--features bundled-grammars` so `build.rs`
/// `include_bytes!`'s these artifacts. A dev/CI tool, so it always builds
/// the full built-in catalog (not user `[grammars.*]` recipes).
fn bundle(_args: &[String]) -> Result<()> {
    // gzip `lib` into `<out_dir>/<name>.<ext>.gz`, returning the
    // compressed size.
    fn gzip_to(lib: &Path, out_dir: &Path, name: &str, ext: &str) -> Result<u64> {
        use std::io::Write;
        let raw = std::fs::read(lib)?;
        let dst = out_dir.join(format!("{name}.{ext}.gz"));
        let f = std::fs::File::create(&dst)?;
        let mut enc = flate2::write::GzEncoder::new(f, flate2::Compression::best());
        enc.write_all(&raw)?;
        enc.finish()?;
        Ok(std::fs::metadata(&dst)?.len())
    }

    let target = env!("BUILD_TARGET");
    let ext = build::dylib_ext();
    let out_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("assets")
        .join("grammars-prebuilt")
        .join(target);
    std::fs::create_dir_all(&out_dir)?;
    eprintln!("bundling for target {target} -> {}", out_dir.display());

    // Throwaway build roots; we only keep the gzip'd library.
    let tmp = std::env::temp_dir().join(format!("vorto-bundle-{}", std::process::id()));
    let build_grammar_dir = tmp.join("grammars");
    let build_query_dir = tmp.join("queries");

    let recipes = builtin_recipes();
    let next = std::sync::atomic::AtomicUsize::new(0);
    let io_lock = std::sync::Mutex::new(());
    let failures = std::sync::Mutex::new(Vec::<&str>::new());
    // Per-grammar license files captured from each clone.
    let collected = std::sync::Mutex::new(Vec::<GrammarLicenses>::new());
    let workers = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4)
        .min(recipes.len());

    std::thread::scope(|s| {
        for _ in 0..workers {
            s.spawn(|| {
                loop {
                    let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    if i >= recipes.len() {
                        break;
                    }
                    let r = &recipes[i];
                    let res = build::install(r, &build_grammar_dir, &build_query_dir).and_then(
                        |report| {
                            let bytes = gzip_to(&report.library, &out_dir, r.name, ext)?;
                            collected
                                .lock()
                                .unwrap()
                                .push((r.name, r.repo, report.licenses));
                            Ok(bytes)
                        },
                    );
                    let _g = io_lock.lock().unwrap();
                    match res {
                        Ok(bytes) => eprintln!("==> {} ({} bytes gz)", r.name, bytes),
                        Err(e) => {
                            eprintln!("==> {} FAILED: {:#}", r.name, e);
                            failures.lock().unwrap().push(r.name);
                        }
                    }
                }
            });
        }
    });

    let _ = std::fs::remove_dir_all(&tmp);
    let failures = failures.into_inner().unwrap();
    if !failures.is_empty() {
        bail!("failed to bundle: {}", failures.join(", "));
    }
    eprintln!("done: {} grammars -> {}", recipes.len(), out_dir.display());

    let mut collected = collected.into_inner().unwrap();
    collected.sort_by(|a, b| a.0.cmp(b.0));
    write_third_party_licenses(&collected)?;
    Ok(())
}

/// Assemble `THIRD_PARTY_LICENSES` from the license files captured during
/// [`bundle`] plus the vendored nvim-treesitter license that covers the
/// derived `.scm` queries. Lives next to the source tree so the release
/// archive can ship it. No network — everything comes from the clones
/// `bundle` already made and one committed asset.
fn write_third_party_licenses(grammars: &[GrammarLicenses]) -> Result<()> {
    use std::fmt::Write as _;

    let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
    let mut doc = String::new();
    doc.push_str(
        "THIRD-PARTY LICENSES\n\
         ====================\n\n\
         vorto itself is licensed under MIT OR Apache-2.0 (see LICENSE-MIT,\n\
         LICENSE-APACHE). The components below are redistributed in release\n\
         binaries built with the `bundled-grammars` feature: pre-built\n\
         tree-sitter grammar libraries embedded in the binary, and the\n\
         tree-sitter query files (`.scm`) bundled via include_dir!.\n\n",
    );

    // ── Grammars ──────────────────────────────────────────────────────
    doc.push_str(
        "================================================================\n\
         Tree-sitter grammars (embedded native libraries)\n\
         ================================================================\n\n",
    );
    // Dedup repos shared by multiple grammars (e.g. typescript + tsx).
    let mut seen_repos: Vec<&str> = Vec::new();
    for (name, repo, files) in grammars {
        if seen_repos.contains(repo) {
            continue;
        }
        seen_repos.push(repo);
        // Every grammar name that resolves to this repo, for clarity.
        let names: Vec<&str> = grammars
            .iter()
            .filter(|(_, r, _)| r == repo)
            .map(|(n, _, _)| *n)
            .collect();
        let _ = writeln!(
            doc,
            "----------------------------------------------------------------"
        );
        let _ = writeln!(doc, "grammar(s): {}", names.join(", "));
        let _ = writeln!(doc, "source: {repo}");
        let _ = writeln!(
            doc,
            "----------------------------------------------------------------"
        );
        if files.is_empty() {
            let _ = writeln!(
                doc,
                "(!) no LICENSE file found in the upstream source — verify manually for `{name}`."
            );
        }
        for (fname, text) in files {
            let _ = writeln!(doc, "[{fname}]");
            doc.push_str(text);
            if !text.ends_with('\n') {
                doc.push('\n');
            }
        }
        doc.push('\n');
    }

    // ── Queries (nvim-treesitter–derived) ─────────────────────────────
    let derived = nvim_derived_langs();
    doc.push_str(
        "================================================================\n\
         Tree-sitter query files (.scm)\n\
         ================================================================\n\n",
    );
    let _ = writeln!(
        doc,
        "Many bundled `.scm` query files are derived from nvim-treesitter\n\
         (https://github.com/nvim-treesitter/nvim-treesitter), licensed\n\
         Apache-2.0. Each derived file carries a `;; Based on nvim-treesitter`\n\
         header naming its exact source commit. Languages affected:\n  {}\n",
        derived.join(", ")
    );
    doc.push('\n');
    // nvim-treesitter ships plain Apache-2.0 text (no project-specific
    // notice), so the file is named for the license, not the project; the
    // "this covers nvim-treesitter-derived queries" attribution is carried
    // by the section header below and the per-`.scm` headers.
    let nvim_license = manifest.join("assets/licenses/Apache-2.0.txt");
    match std::fs::read_to_string(&nvim_license) {
        Ok(text) => {
            doc.push_str("----------------------------------------------------------------\n");
            doc.push_str("nvim-treesitter — Apache-2.0\n");
            doc.push_str("----------------------------------------------------------------\n");
            doc.push_str(&text);
            if !text.ends_with('\n') {
                doc.push('\n');
            }
        }
        Err(_) => {
            bail!(
                "missing vendored license {} — commit nvim-treesitter's Apache-2.0 LICENSE there",
                nvim_license.display()
            );
        }
    }

    let out = manifest.join("THIRD_PARTY_LICENSES");
    std::fs::write(&out, doc)?;
    eprintln!("wrote {}", out.display());
    Ok(())
}

/// Languages whose bundled queries are derived from nvim-treesitter,
/// detected by scanning the embedded `.scm` for the attribution header.
/// Self-updating, so adding/removing a derived query keeps the generated
/// notice accurate.
fn nvim_derived_langs() -> Vec<String> {
    let mut langs: Vec<String> = assets::QUERIES
        .dirs()
        .filter_map(|dir| {
            let derived = dir
                .files()
                .any(|f| String::from_utf8_lossy(f.contents()).contains("nvim-treesitter"));
            if derived {
                dir.path()
                    .file_name()
                    .and_then(|s| s.to_str())
                    .map(|s| s.to_string())
            } else {
                None
            }
        })
        .collect();
    langs.sort();
    langs
}

fn remove(args: &[String], grammar_dir: &Path) -> Result<()> {
    if args.is_empty() {
        bail!("remove: need at least one grammar name");
    }
    for name in args {
        let removed = build::remove(name, grammar_dir)?;
        if removed {
            eprintln!("removed: {}", name);
        } else {
            eprintln!("not installed: {}", name);
        }
    }
    Ok(())
}