vorto 0.14.0

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
//! Language and LSP-server registry.
//!
//! Two top-level TOML sections live here:
//!
//! - `[lsp.<server-name>]` — server definitions (command, args, root
//!   markers). Built-in defaults are seeded from Rust; user entries
//!   field-level overlay onto the built-ins (so users can tweak just
//!   `args` without re-typing `command`). Entirely new servers can
//!   also be defined.
//! - `[languages.<lang-name>]` — language definitions (extensions,
//!   grammar, comment token, editor overrides) plus an `lsp` field
//!   that *references* server names from the `[lsp]` table.
//!
//! ```toml
//! [lsp.vtsls]
//! command = "vtsls"
//! args = ["--stdio"]
//!
//! [languages.typescript]
//! lsp = ["vtsls", "typescript-language-server"]
//! ```
//!
//! Overlay rule (field-level): a user-supplied `Some(_)` field
//! replaces the default; `None` (= unset) leaves the default in place.
//! `lsp` (the reference list on a language) is replaced whole, not
//! merged — users who want to add to the default set must re-state
//! the names they want.
//!
//! File layout: this module file owns the data types and the
//! `LanguageRegistry` entry point. The two big jobs are split off:
//!
//! - [`builtins`] — out-of-the-box `[lsp]` and `[languages]` defaults.
//! - [`resolve`] — merge user TOML onto the built-ins and expand
//!   each language's `lsp` reference list against the server table.

mod builtins;
mod resolve;

use std::collections::HashMap;
use std::path::PathBuf;

use anyhow::{Result, anyhow};
use serde::Deserialize;

use super::editor::EditorToml;

// ────────────────────────────────────────────────────────────────────────
// LSP server schema
// ────────────────────────────────────────────────────────────────────────

/// Raw `[lsp.<name>]` entry as it appears in user TOML. Every field is
/// `Option<T>` so partial overrides can field-level overlay onto the
/// built-in defaults.
#[derive(Debug, Default, Deserialize, Clone)]
pub struct LspToml {
    pub command: Option<String>,
    pub args: Option<Vec<String>>,
    pub language_id: Option<String>,
    pub root_markers: Option<Vec<String>>,
}

/// Fully-resolved LSP-server record. The key from the `[lsp]` table
/// becomes `name`; downstream code uses `(<lang>, name)` to identify
/// each spawned client.
#[derive(Debug, Clone)]
pub struct LspConfig {
    pub name: String,
    pub command: String,
    pub args: Vec<String>,
    /// LSP `languageId` sent in `didOpen`. `None` falls back to the
    /// language name — typically the right thing when a server is
    /// dedicated to one language, and also fine when a server serves
    /// multiple langs (each `didOpen` then carries that file's own
    /// language name).
    pub language_id: Option<String>,
    pub root_markers: Vec<String>,
}

impl LspConfig {
    /// Apply a partial user override. Only `Some` fields on `user`
    /// replace this entry's values; the rest survive.
    fn overlay(&mut self, user: LspToml) {
        if let Some(c) = user.command {
            self.command = c;
        }
        if let Some(a) = user.args {
            self.args = a;
        }
        if user.language_id.is_some() {
            self.language_id = user.language_id;
        }
        if let Some(r) = user.root_markers {
            self.root_markers = r;
        }
    }

    /// Promote a user-only TOML entry (no built-in to overlay onto)
    /// into a full record. `command` is required for new entries —
    /// without it there's nothing to spawn.
    fn from_user(name: &str, user: LspToml) -> Result<Self> {
        let command = user.command.ok_or_else(|| {
            anyhow!(
                "[lsp.{}] is a new server (no built-in to overlay onto) and \
                 must define `command`",
                name
            )
        })?;
        Ok(Self {
            name: name.to_string(),
            command,
            args: user.args.unwrap_or_default(),
            language_id: user.language_id,
            root_markers: user.root_markers.unwrap_or_default(),
        })
    }
}

// ────────────────────────────────────────────────────────────────────────
// Formatter schema
// ────────────────────────────────────────────────────────────────────────

/// Raw `[languages.<name>.formatter]` entry as it appears in TOML.
/// `command` is required when the user defines a new entry; both fields
/// land here as `Option` so a missing `formatter` table on the language
/// can be distinguished from an explicitly-cleared one.
#[derive(Debug, Default, Deserialize, Clone)]
pub struct FormatterToml {
    pub command: Option<String>,
    pub args: Option<Vec<String>>,
}

/// Fully-resolved external formatter. The buffer's text is piped on
/// stdin; stdout becomes the new text. A missing `formatter` on the
/// resolved `Language` means "fall back to `textDocument/formatting`
/// against the first attached LSP".
#[derive(Debug, Clone)]
pub struct FormatterConfig {
    pub command: String,
    pub args: Vec<String>,
}

// ────────────────────────────────────────────────────────────────────────
// Language schema
// ────────────────────────────────────────────────────────────────────────

/// Raw `[languages.<name>]` entry as it appears in TOML / built-in
/// defaults. `Option<T>` everywhere so the overlay step can
/// distinguish "user wrote nothing" from a meaningful empty value.
#[derive(Debug, Default, Deserialize, Clone)]
pub struct LanguageConfig {
    pub extensions: Option<Vec<String>>,
    /// Exact filenames (case-sensitive) that map to this language even
    /// when they have no extension — `Dockerfile`, `Makefile`,
    /// `Containerfile`, etc. Checked *before* the extension table so a
    /// file literally named `Dockerfile` resolves regardless of any
    /// `.dockerfile` extension also being registered.
    pub filenames: Option<Vec<String>>,
    /// Grammar filename stem (without the `.so` / `.dylib` / `.dll`
    /// extension). Defaults to the language name itself.
    pub grammar: Option<String>,
    /// Override directory for `<grammar>.{so,dylib,dll}` — overrides
    /// the global grammar dir for just this language.
    pub grammar_dir: Option<PathBuf>,
    /// Override directory for `<lang>/highlights.scm` — overrides the
    /// global query dir for just this language.
    pub query_dir: Option<PathBuf>,
    /// Single-line comment prefix used by the `gc` operator (e.g.
    /// `"//"` for Rust, `"#"` for Python). Unset disables line
    /// commenting for the language.
    pub comment_token: Option<String>,
    /// Block-comment delimiter pair used by the `gb` operator
    /// (e.g. `("/*", "*/")` for C-family, `("<!--", "-->")` for HTML).
    /// Unset means the language has no native block comment — `gb`
    /// falls back to per-row line comments using `comment_token`.
    pub block_comment_token: Option<(String, String)>,
    /// Editor-setting overrides for this language. Fields are
    /// flattened into `[languages.<name>]` (e.g. `tab_width = 8` sits
    /// directly on the language table, not under `[…].editor`).
    /// Field-level overlay onto the global `[editor]` defaults.
    #[serde(default, flatten)]
    pub editor: EditorToml,
    /// Server names (keys from the `[lsp]` table) to attach to buffers
    /// of this language. Replaced whole on overlay, not merged.
    pub lsp: Option<Vec<String>>,
    /// External formatter invoked on save. The buffer's text is piped
    /// on stdin and stdout becomes the new buffer text. Unset means
    /// "fall back to `textDocument/formatting` against the attached
    /// LSP". Replaced whole on overlay, not merged — `command` and
    /// `args` go together, partial overrides don't pay rent here.
    pub formatter: Option<FormatterToml>,
}

impl LanguageConfig {
    /// Overlay `user` onto `self`. Any `Some` field in `user` wins;
    /// the rest of `self` survives.
    pub fn overlay(&mut self, user: LanguageConfig) {
        if user.extensions.is_some() {
            self.extensions = user.extensions;
        }
        if user.filenames.is_some() {
            self.filenames = user.filenames;
        }
        if user.grammar.is_some() {
            self.grammar = user.grammar;
        }
        if user.grammar_dir.is_some() {
            self.grammar_dir = user.grammar_dir;
        }
        if user.query_dir.is_some() {
            self.query_dir = user.query_dir;
        }
        if user.comment_token.is_some() {
            self.comment_token = user.comment_token;
        }
        if user.block_comment_token.is_some() {
            self.block_comment_token = user.block_comment_token;
        }
        // Editor settings are field-level overlay so users can flip
        // just one knob (typically `tab_width`) without re-stating the
        // others.
        if user.editor.indent_width.is_some() {
            self.editor.indent_width = user.editor.indent_width;
        }
        if user.editor.tab_width.is_some() {
            self.editor.tab_width = user.editor.tab_width;
        }
        if user.editor.use_tabs.is_some() {
            self.editor.use_tabs = user.editor.use_tabs;
        }
        if user.editor.show_whitespace.is_some() {
            self.editor.show_whitespace = user.editor.show_whitespace;
        }
        if user.lsp.is_some() {
            self.lsp = user.lsp;
        }
        if user.formatter.is_some() {
            self.formatter = user.formatter;
        }
    }
}

/// Fully-resolved language record. This is what the runtime works with.
#[derive(Debug, Clone)]
pub struct Language {
    pub name: String,
    pub extensions: Vec<String>,
    /// Exact filenames that map to this language. See
    /// [`LanguageConfig::filenames`].
    pub filenames: Vec<String>,
    pub grammar: String,
    pub grammar_dir: Option<PathBuf>,
    pub query_dir: Option<PathBuf>,
    pub comment_token: Option<String>,
    pub block_comment_token: Option<(String, String)>,
    /// Per-language editor-setting overrides.
    pub editor: EditorToml,
    /// LSP servers attached to this language, expanded from the name
    /// references on `LanguageConfig.lsp`. Empty when the language has
    /// no LSP configured.
    pub lsp: Vec<LspConfig>,
    /// External formatter, if configured. `None` means save-time
    /// formatting falls through to `textDocument/formatting` against
    /// the first attached LSP — or is a no-op when no LSP is attached.
    pub formatter: Option<FormatterConfig>,
}

// ────────────────────────────────────────────────────────────────────────
// Registry
// ────────────────────────────────────────────────────────────────────────

/// Catalog of resolved languages with name and extension lookups.
/// Built once at startup from the user's TOML overlaid on the built-in
/// defaults.
#[derive(Debug, Clone, Default)]
pub struct LanguageRegistry {
    by_name: HashMap<String, Language>,
    extension_to_name: HashMap<String, String>,
    /// Lookup for bare-filename matches (e.g. `Dockerfile`, `Makefile`).
    /// Consulted *before* the extension index in `by_path`.
    filename_to_name: HashMap<String, String>,
    /// LSP `languageId` per file extension. Distinct from the language
    /// name because the LSP protocol's id space is fixed by spec —
    /// `.tsx` must announce `"typescriptreact"` even though we route
    /// it through our own `tsx` language entry. Extensions missing
    /// here fall back to the language name at `didOpen` time.
    extension_to_language_id: HashMap<String, String>,
}

impl LanguageRegistry {
    /// Build the catalog from the user's `[languages]` and `[lsp]`
    /// tables. Returns an error when a language references an unknown
    /// LSP server name, or when a user-defined `[lsp.<name>]` entry
    /// lacks `command`.
    pub fn build(
        user_languages: HashMap<String, LanguageConfig>,
        user_lsp: HashMap<String, LspToml>,
    ) -> Result<Self> {
        let lsp_table = resolve::resolve_lsp_table(user_lsp)?;
        let by_name = resolve::resolve(user_languages, &lsp_table)?;
        let extension_to_name = resolve::build_extension_index(&by_name);
        let filename_to_name = resolve::build_filename_index(&by_name);
        Ok(Self {
            by_name,
            extension_to_name,
            filename_to_name,
            extension_to_language_id: builtins::builtin_extension_language_ids(),
        })
    }

    /// Resolve a file extension (without the leading `.`) to its
    /// language entry, if any.
    pub fn by_extension(&self, ext: &str) -> Option<&Language> {
        let name = self.extension_to_name.get(ext)?;
        self.by_name.get(name)
    }

    /// Resolve a bare filename (the last path component, e.g.
    /// `"Dockerfile"`) to its language entry. Case-sensitive.
    pub fn by_filename(&self, filename: &str) -> Option<&Language> {
        let name = self.filename_to_name.get(filename)?;
        self.by_name.get(name)
    }

    /// One-stop language lookup for a filesystem path. Tries the bare
    /// filename first (so `Dockerfile` resolves), then falls back to
    /// the file extension. Returns `None` when neither matches.
    pub fn by_path(&self, path: &std::path::Path) -> Option<&Language> {
        if let Some(name) = path.file_name().and_then(|s| s.to_str())
            && let Some(lang) = self.by_filename(name)
        {
            return Some(lang);
        }
        let ext = path.extension().and_then(|s| s.to_str())?;
        self.by_extension(ext)
    }

    /// LSP `languageId` for this file extension. `None` means "no
    /// override — let the LSP layer default to the language name."
    pub fn language_id_for_extension(&self, ext: &str) -> Option<&str> {
        self.extension_to_language_id.get(ext).map(String::as_str)
    }

    /// Iterate every resolved language entry. Used by the `:lsp`
    /// status modal to enumerate which languages have an LSP server
    /// configured.
    pub fn iter(&self) -> impl Iterator<Item = &Language> {
        self.by_name.values()
    }
}

#[cfg(test)]
mod tests {
    use super::builtins::{builtin_languages, builtin_lsp};
    use super::resolve::{build_extension_index, resolve, resolve_lsp_table};
    use super::*;

    fn empty_lsp() -> HashMap<String, LspConfig> {
        resolve_lsp_table(HashMap::new()).unwrap()
    }

    #[test]
    fn builtins_include_rust() {
        let m = builtin_languages();
        assert!(m.contains_key("rust"));
        assert_eq!(
            m["rust"].extensions.as_deref(),
            Some(&["rs".to_string()][..])
        );
    }

    #[test]
    fn builtin_lsp_includes_vtsls_and_tsserver() {
        let m = builtin_lsp();
        assert!(m.contains_key("vtsls"));
        assert!(m.contains_key("typescript-language-server"));
    }

    #[test]
    fn overlay_replaces_only_provided_fields() {
        let mut base = LanguageConfig {
            extensions: Some(vec!["rs".into()]),
            grammar: Some("rust".into()),
            ..Default::default()
        };
        let user = LanguageConfig {
            grammar: Some("rust-tree-sitter".into()),
            ..Default::default()
        };
        base.overlay(user);
        assert_eq!(base.grammar.as_deref(), Some("rust-tree-sitter"));
        assert_eq!(base.extensions.as_deref(), Some(&["rs".to_string()][..]));
    }

    #[test]
    fn resolve_adds_user_only_language() {
        let mut user = HashMap::new();
        user.insert(
            "brainfuck".into(),
            LanguageConfig {
                extensions: Some(vec!["bf".into()]),
                ..Default::default()
            },
        );
        let langs = resolve(user, &empty_lsp()).unwrap();
        assert!(langs.contains_key("brainfuck"));
        assert_eq!(langs["brainfuck"].grammar, "brainfuck");
        assert!(langs["brainfuck"].lsp.is_empty());
    }

    #[test]
    fn resolve_falls_back_to_default_when_user_omits_field() {
        let mut user = HashMap::new();
        user.insert(
            "rust".into(),
            LanguageConfig {
                grammar: Some("rust-custom".into()),
                ..Default::default()
            },
        );
        let langs = resolve(user, &empty_lsp()).unwrap();
        assert_eq!(langs["rust"].grammar, "rust-custom");
        assert_eq!(langs["rust"].extensions, vec!["rs"]);
        // Built-in LSP ref survives the partial override.
        assert_eq!(langs["rust"].lsp.len(), 1);
        assert_eq!(langs["rust"].lsp[0].name, "rust-analyzer");
    }

    #[test]
    fn extension_index_routes_to_language_name() {
        let langs = resolve(HashMap::new(), &empty_lsp()).unwrap();
        let idx = build_extension_index(&langs);
        assert_eq!(idx.get("rs"), Some(&"rust".to_string()));
        assert_eq!(idx.get("py"), Some(&"python".to_string()));
    }

    #[test]
    fn by_path_resolves_dockerfile_via_filename() {
        let registry = LanguageRegistry::build(HashMap::new(), HashMap::new()).unwrap();
        let lang = registry
            .by_path(std::path::Path::new("/srv/app/Dockerfile"))
            .expect("Dockerfile should resolve via filename match");
        assert_eq!(lang.name, "dockerfile");
    }

    #[test]
    fn by_path_resolves_makefile_via_filename() {
        let registry = LanguageRegistry::build(HashMap::new(), HashMap::new()).unwrap();
        let lang = registry
            .by_path(std::path::Path::new("./Makefile"))
            .expect("Makefile should resolve via filename match");
        assert_eq!(lang.name, "make");
    }

    #[test]
    fn by_path_falls_back_to_extension() {
        let registry = LanguageRegistry::build(HashMap::new(), HashMap::new()).unwrap();
        let lang = registry
            .by_path(std::path::Path::new("/x/main.rs"))
            .expect("main.rs should resolve via extension");
        assert_eq!(lang.name, "rust");
    }

    #[test]
    fn typescript_resolves_to_two_servers() {
        let langs = resolve(HashMap::new(), &empty_lsp()).unwrap();
        let ts = &langs["typescript"];
        let names: Vec<&str> = ts.lsp.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["vtsls", "typescript-language-server"]);
    }

    #[test]
    fn user_lsp_overlay_replaces_only_provided_fields() {
        let mut user_lsp: HashMap<String, LspToml> = HashMap::new();
        user_lsp.insert(
            "vtsls".into(),
            LspToml {
                args: Some(vec!["--my-flag".into()]),
                ..Default::default()
            },
        );
        let table = resolve_lsp_table(user_lsp).unwrap();
        let entry = &table["vtsls"];
        assert_eq!(entry.command, "vtsls"); // built-in survived
        assert_eq!(entry.args, vec!["--my-flag"]); // user replaced
    }

    #[test]
    fn user_lsp_new_entry_requires_command() {
        let mut user_lsp: HashMap<String, LspToml> = HashMap::new();
        user_lsp.insert(
            "my-server".into(),
            LspToml {
                args: Some(vec!["--stdio".into()]),
                ..Default::default()
            },
        );
        assert!(resolve_lsp_table(user_lsp).is_err());
    }

    #[test]
    fn user_lsp_new_entry_with_command_succeeds() {
        let mut user_lsp: HashMap<String, LspToml> = HashMap::new();
        user_lsp.insert(
            "my-server".into(),
            LspToml {
                command: Some("my-bin".into()),
                args: Some(vec!["--stdio".into()]),
                ..Default::default()
            },
        );
        let table = resolve_lsp_table(user_lsp).unwrap();
        assert_eq!(table["my-server"].command, "my-bin");
    }

    #[test]
    fn language_ref_to_unknown_server_errors() {
        let mut user_langs: HashMap<String, LanguageConfig> = HashMap::new();
        user_langs.insert(
            "rust".into(),
            LanguageConfig {
                lsp: Some(vec!["nonexistent".into()]),
                ..Default::default()
            },
        );
        let err = resolve(user_langs, &empty_lsp()).unwrap_err();
        assert!(err.to_string().contains("nonexistent"));
    }

    #[test]
    fn user_can_pick_subset_of_servers() {
        // User keeps only one server for typescript.
        let mut user_langs: HashMap<String, LanguageConfig> = HashMap::new();
        user_langs.insert(
            "typescript".into(),
            LanguageConfig {
                lsp: Some(vec!["typescript-language-server".into()]),
                ..Default::default()
            },
        );
        let langs = resolve(user_langs, &empty_lsp()).unwrap();
        assert_eq!(langs["typescript"].lsp.len(), 1);
        assert_eq!(
            langs["typescript"].lsp[0].name,
            "typescript-language-server"
        );
    }
}