vorto 0.12.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
//! Resolved user configuration loaded from `~/.config/vorto/config.toml`.
//!
//! The public type [`Config`] is a pure data struct holding the final,
//! ready-to-use settings (`keymap`, `cursor_shapes`, `languages`,
//! `grammar_dir`, `query_dir`). [`Config::load`] consumes a TOML file
//! (when present) and produces a `Config`; everything else in this
//! module is internal plumbing.
//!
//! Schema:
//!
//! ```toml
//! [[bind]]
//! keys   = "<C-s>"      # vim-style key notation; see `keys::parse_sequence`
//! action = "save"        # named action; see `keys::action_to_token`
//!
//! [[bind]]
//! keys   = "<space>w"   # 2-key sequence — installed in the Leader context
//! action = "save"
//! ```
//!
//! Bindings either **override** an existing default (same key sequence)
//! or **add** new ones. Only single keys (Initial context) and
//! `<space>X` two-key sequences (Leader context) are supported in v1.

mod command;
mod cursor;
mod editor;
mod finder;
mod keymap;
mod keys;
mod languages;

use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail};
use crossterm::event::KeyCode;
use serde::Deserialize;

pub use command::{COMMAND_BINDS, CommandBind};
pub use cursor::{CursorShape, CursorShapes};
pub use editor::{EditorConfig, EditorToml, IndentGuideStyle};
pub use finder::{FinderConfig, FinderToml};
pub use keymap::{
    BRACKET_NEXT_BINDINGS, BRACKET_PREV_BINDINGS, CTRL_W_BINDINGS, GOTO_BINDINGS, KeySig, Keymap,
    LEADER_DEFAULTS, OBJECT_BINDINGS, OP_PENDING_BINDINGS, WINDOW_BINDINGS, Z_BINDINGS,
};
pub use languages::{
    FormatterConfig, Language, LanguageConfig, LanguageRegistry, LspConfig, LspToml,
};

use cursor::{CursorConfig, resolve_cursor_shapes};
use keymap::LEADER;
use keys::{action_to_token, parse_sequence};

/// Resolved configuration — the runtime state of "what settings is the
/// app currently using". Pure data: every field is filled in by
/// [`Config::load`] and never mutated afterward.
pub struct Config {
    pub keymap: Keymap,
    pub cursor_shapes: CursorShapes,
    pub languages: LanguageRegistry,
    /// Global editor settings, applied to every buffer that doesn't get
    /// a more specific override from a `[languages.<name>]` block.
    pub editor: EditorConfig,
    /// File picker / tree explorer behavior — currently just the
    /// `hidden_patterns` glob list.
    pub finder: FinderConfig,
    /// User-defined grammar recipes from `[grammars.<name>]`. Augments
    /// the built-in catalog; an entry whose name matches a built-in
    /// overrides it. Sorted by name for stable output.
    pub grammars: Vec<GrammarSource>,
    /// Absolute path to the grammar directory (`<grammar>.{so,dylib,dll}`).
    pub grammar_dir: PathBuf,
    /// Absolute path to the query directory (`<lang>/highlights.scm`).
    pub query_dir: PathBuf,
}

/// Raw `[grammars.<name>]` entry: where to fetch a grammar's source.
/// Mirrors the built-in recipe shape. The git URL is `source` (alias
/// `src`); `rev` pins a tag/branch/commit (omit it to build the latest
/// default branch); `subpath` selects a grammar inside a monorepo.
#[derive(Debug, Deserialize, Clone)]
struct GrammarToml {
    #[serde(alias = "src")]
    source: String,
    #[serde(default)]
    rev: Option<String>,
    #[serde(default)]
    subpath: Option<String>,
}

/// A resolved user grammar recipe, with the table-key name folded in.
#[derive(Debug, Clone)]
pub struct GrammarSource {
    pub name: String,
    pub source: String,
    pub rev: Option<String>,
    pub subpath: Option<String>,
}

impl Config {
    /// Load and resolve the user config from `path` (if it exists).
    /// Missing file or `None` path yields a Config seeded entirely from
    /// built-in defaults.
    pub fn load(path: Option<&Path>) -> Result<Self> {
        let toml = Toml::load(path)?;
        Self::resolve(toml)
    }

    fn resolve(toml: Toml) -> Result<Self> {
        let mut keymap = Keymap::vim_default();
        for (i, b) in toml.bind.iter().enumerate() {
            install_binding(&mut keymap, &b.keys, &b.action)
                .with_context(|| format!("bind[{}] ({} → {})", i, b.keys, b.action))?;
        }

        let cursor_shapes = resolve_cursor_shapes(&toml.cursor)?;
        let editor = EditorConfig::default().overlay(&toml.editor);
        let finder = FinderConfig::default().overlay(&toml.finder);
        let languages = LanguageRegistry::build(toml.languages, toml.lsp)?;
        let mut grammars: Vec<GrammarSource> = toml
            .grammars
            .into_iter()
            .map(|(name, g)| GrammarSource {
                name,
                source: g.source,
                rev: g.rev,
                subpath: g.subpath,
            })
            .collect();
        grammars.sort_by(|a, b| a.name.cmp(&b.name));
        let grammar_dir = toml
            .grammar_dir
            .map(PathBuf::from)
            .unwrap_or_else(|| default_subdir("grammars"));
        let query_dir = toml
            .query_dir
            .map(PathBuf::from)
            .unwrap_or_else(|| default_subdir("queries"));

        Ok(Self {
            keymap,
            cursor_shapes,
            languages,
            editor,
            finder,
            grammars,
            grammar_dir,
            query_dir,
        })
    }
}

// ────────────────────────────────────────────────────────────────────────
// TOML schema (private — implementation detail of `Config::load`).
// ────────────────────────────────────────────────────────────────────────

#[derive(Debug, Default, Deserialize)]
struct Toml {
    #[serde(default)]
    bind: Vec<BindEntry>,
    #[serde(default)]
    cursor: CursorConfig,
    /// Global `[editor]` table. Per-language overrides flatten the same
    /// fields directly into each `[languages.<name>]` table.
    #[serde(default)]
    editor: EditorToml,
    /// `[finder]` table — file picker / explorer behavior.
    #[serde(default)]
    finder: FinderToml,
    /// `[languages.<name>]` blocks. Resolved against built-in defaults
    /// by [`LanguageRegistry::build`].
    #[serde(default)]
    languages: std::collections::HashMap<String, LanguageConfig>,
    /// `[lsp.<server-name>]` blocks. Built-in servers can be partially
    /// overlaid (e.g. just `args`); entirely new servers must include
    /// `command`. Referenced from `[languages.<lang>].lsp = ["<name>"]`.
    #[serde(default)]
    lsp: std::collections::HashMap<String, LspToml>,
    /// `[grammars.<name>]` blocks — user-defined grammar recipes that
    /// make `vorto grammar install <name>` work for grammars not in the
    /// built-in catalog. Resolved into [`Config::grammars`].
    #[serde(default)]
    grammars: std::collections::HashMap<String, GrammarToml>,
    /// Directory holding `<grammar>.{so,dylib,dll}`. Defaults to
    /// `<config>/grammars`.
    grammar_dir: Option<String>,
    /// Directory holding `<lang>/highlights.scm`. Defaults to
    /// `<config>/queries`.
    query_dir: Option<String>,
}

impl Toml {
    fn load(path: Option<&Path>) -> Result<Self> {
        let Some(path) = path else {
            return Ok(Self::default());
        };
        if !path.exists() {
            return Ok(Self::default());
        }
        let text = std::fs::read_to_string(path)
            .with_context(|| format!("reading config {}", path.display()))?;
        toml::from_str(&text).with_context(|| format!("parsing config {}", path.display()))
    }
}

/// Single `[[bind]]` row from the TOML schema.
#[derive(Debug, Deserialize)]
struct BindEntry {
    keys: String,
    action: String,
}

// ────────────────────────────────────────────────────────────────────────
// Path resolution
// ────────────────────────────────────────────────────────────────────────

/// Resolve the config-file path. Workspace-local `.vorto/config.toml`
/// (or a plain `.vorto` file) in the current directory wins; otherwise
/// honors `$XDG_CONFIG_HOME` if set, then falls back to
/// `$HOME/.config/vorto/config.toml`.
pub fn default_path() -> Option<PathBuf> {
    if let Ok(cwd) = std::env::current_dir()
        && let Some(p) = workspace_path(&cwd)
    {
        return Some(p);
    }
    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
        let p = PathBuf::from(xdg).join("vorto/config.toml");
        if p.exists() {
            return Some(p);
        }
    }
    let home = std::env::var_os("HOME")?;
    let p = PathBuf::from(home).join(".config/vorto/config.toml");
    Some(p)
}

/// Look for a workspace-local config rooted at `cwd`. Supports two
/// layouts: `<cwd>/.vorto/config.toml` (directory form, mirroring the
/// global `~/.config/vorto/` layout) and `<cwd>/.vorto` (single TOML
/// file). Returns `None` if neither exists.
fn workspace_path(cwd: &Path) -> Option<PathBuf> {
    let vorto = cwd.join(".vorto");
    let meta = std::fs::metadata(&vorto).ok()?;
    if meta.is_dir() {
        let p = vorto.join("config.toml");
        return p.exists().then_some(p);
    }
    if meta.is_file() {
        return Some(vorto);
    }
    None
}

fn default_subdir(name: &str) -> PathBuf {
    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
        return PathBuf::from(xdg).join("vorto").join(name);
    }
    if let Some(home) = std::env::var_os("HOME") {
        return PathBuf::from(home).join(".config/vorto").join(name);
    }
    PathBuf::from(name)
}

// ────────────────────────────────────────────────────────────────────────
// Binding application
// ────────────────────────────────────────────────────────────────────────

fn install_binding(keymap: &mut Keymap, keys: &str, action: &str) -> Result<()> {
    let sequence = parse_sequence(keys)?;
    let token = action_to_token(action).ok_or_else(|| anyhow!("unknown action: {}", action))?;
    match sequence.as_slice() {
        [k] => {
            keymap.bind_initial(*k, token);
        }
        [first, second] if first.code == KeyCode::Char(LEADER) && first.modifiers.is_empty() => {
            keymap.bind_leader(*second, token);
        }
        [_, _] => bail!(
            "only `<space>X` two-key sequences are supported; got: {}",
            keys
        ),
        _ => bail!(
            "sequences of more than 2 keys aren't supported yet; got: {}",
            keys
        ),
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::action::{DirectKind, Token};
    use crossterm::event::KeyModifiers;

    #[test]
    fn install_leader_binding() {
        let mut km = Keymap::vim_default();
        install_binding(&mut km, "<space>w", "save").unwrap();
        let sig = KeySig::new(KeyCode::Char('w'), KeyModifiers::NONE);
        assert_eq!(km.leader.get(&sig), Some(&Token::Direct(DirectKind::Save)));
    }

    #[test]
    fn install_overrides_existing() {
        let mut km = Keymap::vim_default();
        install_binding(&mut km, "u", "quit").unwrap();
        let sig = KeySig::new(KeyCode::Char('u'), KeyModifiers::NONE);
        assert_eq!(km.initial.get(&sig), Some(&Token::Direct(DirectKind::Quit)));
    }

    #[test]
    fn parse_inline_array_form() {
        let text = r#"
bind = [
  { keys = "<C-s>", action = "save" },
  { keys = "<space>w", action = "save" },
]
"#;
        let toml: Toml = toml::from_str(text).unwrap();
        assert_eq!(toml.bind.len(), 2);
        assert_eq!(toml.bind[0].keys, "<C-s>");
        assert_eq!(toml.bind[1].action, "save");
    }

    #[test]
    fn cursor_defaults_when_unset() {
        let toml: Toml = toml::from_str("").unwrap();
        let shapes = resolve_cursor_shapes(&toml.cursor).unwrap();
        assert!(matches!(shapes.normal, CursorShape::Block));
        assert!(matches!(shapes.insert, CursorShape::Bar));
        assert!(matches!(shapes.visual, CursorShape::Underbar));
    }

    #[test]
    fn cursor_overrides() {
        let text = r#"
[cursor]
normal = "bar"
insert = "underbar"
visual = "block"
"#;
        let toml: Toml = toml::from_str(text).unwrap();
        let shapes = resolve_cursor_shapes(&toml.cursor).unwrap();
        assert!(matches!(shapes.normal, CursorShape::Bar));
        assert!(matches!(shapes.insert, CursorShape::Underbar));
        assert!(matches!(shapes.visual, CursorShape::Block));
    }

    #[test]
    fn cursor_unknown_shape() {
        let text = r#"
[cursor]
normal = "diamond"
"#;
        let toml: Toml = toml::from_str(text).unwrap();
        assert!(resolve_cursor_shapes(&toml.cursor).is_err());
    }

    #[test]
    fn parse_languages_table() {
        let text = r#"
[languages.rust]
extensions = ["rs", "rlib"]

[languages.fish]
extensions = ["fish"]
grammar = "fish-shell"
"#;
        let toml: Toml = toml::from_str(text).unwrap();
        assert_eq!(toml.languages.len(), 2);
        assert_eq!(
            toml.languages["rust"].extensions.as_deref(),
            Some(&["rs".to_string(), "rlib".to_string()][..])
        );
        assert_eq!(
            toml.languages["fish"].grammar.as_deref(),
            Some("fish-shell")
        );
    }

    #[test]
    fn workspace_path_prefers_directory_config() {
        let root = std::env::temp_dir().join(format!(
            "vorto-test-ws-dir-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0),
        ));
        let dot_vorto = root.join(".vorto");
        std::fs::create_dir_all(&dot_vorto).unwrap();
        let cfg = dot_vorto.join("config.toml");
        std::fs::write(&cfg, "").unwrap();

        assert_eq!(workspace_path(&root), Some(cfg));
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn workspace_path_accepts_single_file() {
        let root = std::env::temp_dir().join(format!(
            "vorto-test-ws-file-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0),
        ));
        std::fs::create_dir_all(&root).unwrap();
        let dot_vorto = root.join(".vorto");
        std::fs::write(&dot_vorto, "").unwrap();

        assert_eq!(workspace_path(&root), Some(dot_vorto));
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn workspace_path_absent_returns_none() {
        let root = std::env::temp_dir().join(format!(
            "vorto-test-ws-none-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0),
        ));
        std::fs::create_dir_all(&root).unwrap();

        assert_eq!(workspace_path(&root), None);
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn parse_table_array_form() {
        let text = r#"
[[bind]]
keys = "<C-s>"
action = "save"

[[bind]]
keys = "<space>w"
action = "save"
"#;
        let toml: Toml = toml::from_str(text).unwrap();
        assert_eq!(toml.bind.len(), 2);
        assert_eq!(toml.bind[0].keys, "<C-s>");
    }
}