vimltui 0.2.11

A self-contained, embeddable Vim editor for Ratatui TUI applications
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
//! # vimltui
//!
//! A self-contained, embeddable Vim editor for [Ratatui](https://ratatui.rs) TUI applications.
//!
//! `vimltui` provides a fully functional Vim editing experience that you can drop into any
//! Ratatui-based terminal application. Each [`VimEditor`] instance owns its own text buffer,
//! cursor, mode, undo/redo history, search state, and registers — completely independent
//! from your application state.
//!
//! ## Features
//!
//! - **Normal / Insert / Visual** modes (Char, Line, Block)
//! - **Operator + Motion** composition (`dw`, `ci"`, `y$`, `>j`, `gUw`, ...)
//! - **f / F / t / T** character find motions
//! - **Search** with `/`, `?`, `n`, `N` and match highlighting
//! - **Dot repeat** (`.`) for last edit
//! - **Undo / Redo** with snapshot stack
//! - **Command mode** (`:w`, `:q`, `:wq`, `:123`)
//! - **Registers** and system clipboard integration
//! - **Text objects** (`iw`, `i"`, `i(`)
//! - **Relative line numbers** in the built-in renderer
//! - **Pluggable syntax highlighting** via the [`SyntaxHighlighter`] trait
//!
//! ## Quick Start
//!
//! ```rust
//! use vimltui::{VimEditor, VimModeConfig};
//!
//! // Create an editor with full editing capabilities
//! let mut editor = VimEditor::new("Hello, Vim!", VimModeConfig::default());
//!
//! // Create a read-only viewer (visual selection only, no insert)
//! let mut viewer = VimEditor::new("Read only content", VimModeConfig::read_only());
//!
//! // Get the current content back
//! let text = editor.content();
//! ```
//!
//! ## Handling Input
//!
//! ```rust,no_run
//! use vimltui::{VimEditor, VimModeConfig, EditorAction};
//! use crossterm::event::KeyEvent;
//!
//! let mut editor = VimEditor::new("", VimModeConfig::default());
//!
//! // In your event loop:
//! // let action = editor.handle_key(key_event);
//! // match action {
//! //     EditorAction::Handled => { /* editor consumed the key */ }
//! //     EditorAction::Unhandled(key) => { /* pass to your app's handler */ }
//! //     EditorAction::Save => { /* user typed :w */ }
//! //     EditorAction::Close => { /* user typed :q */ }
//! //     EditorAction::ForceClose => { /* user typed :q! */ }
//! //     EditorAction::SaveAndClose => { /* user typed :wq */ }
//! // }
//! ```
//!
//! ## Rendering
//!
//! Use the built-in renderer with your own [`SyntaxHighlighter`]:
//!
//! ```rust
//! use vimltui::{VimTheme, PlainHighlighter, SyntaxHighlighter};
//! use ratatui::style::Color;
//! use ratatui::text::Span;
//!
//! // Built-in PlainHighlighter for no syntax coloring
//! let highlighter = PlainHighlighter;
//!
//! // Or implement your own:
//! struct SqlHighlighter;
//! impl SyntaxHighlighter for SqlHighlighter {
//!     fn highlight_line<'a>(&self, line: &'a str, spans: &mut Vec<Span<'a>>) {
//!         spans.push(Span::raw(line));
//!     }
//! }
//! ```

pub mod editor;
pub mod render;

use std::collections::HashMap;
use crossterm::event::KeyEvent;
use ratatui::style::Color;
use ratatui::text::Span;

// Re-export the primary type for convenience
pub use editor::VimEditor;

/// Vim editing mode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VimMode {
    Normal,
    Insert,
    Replace,
    Visual(VisualKind),
}

/// Cursor shape hint for renderers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CursorShape {
    Block,
    Bar,
    Underline,
}

/// Visual selection kind.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VisualKind {
    Char,
    Line,
    Block,
}

/// Configures which Vim modes are available in an editor instance.
#[derive(Debug, Clone)]
pub struct VimModeConfig {
    pub insert_allowed: bool,
    pub visual_allowed: bool,
}

impl Default for VimModeConfig {
    fn default() -> Self {
        Self {
            insert_allowed: true,
            visual_allowed: true,
        }
    }
}

impl VimModeConfig {
    /// Read-only mode: visual selection is allowed but insert is disabled.
    pub fn read_only() -> Self {
        Self {
            insert_allowed: false,
            visual_allowed: true,
        }
    }
}

/// Actions returned from [`VimEditor::handle_key()`] to inform the parent application.
pub enum EditorAction {
    /// The editor consumed the key — no further action needed.
    Handled,
    /// The editor does not handle this key — bubble up to the parent.
    Unhandled(KeyEvent),
    /// Save buffer (`:w` or `Ctrl+S`).
    Save,
    /// Close buffer (`:q`).
    Close,
    /// Force close without saving (`:q!`).
    ForceClose,
    /// Save and close (`:wq`, `:x`).
    SaveAndClose,
    /// Toggle line comment on the current line (`gcc` in Normal mode).
    ToggleComment,
    /// Toggle block comment on the visual selection (`gc` in Visual mode).
    /// Contains (start_row, end_row) of the selection.
    ToggleBlockComment { start_row: usize, end_row: usize },
    /// Go to definition at cursor position (`gd` in Normal mode).
    /// The consumer implements the actual navigation.
    GoToDefinition,
    /// Show hover/documentation at cursor position (`K` in Normal mode).
    /// The consumer implements the actual display.
    Hover,
}

/// Leader key (space by default, like modern Neovim setups).
pub const LEADER_KEY: char = ' ';

/// Operator waiting for a motion (e.g., `d` waits for `w` → `dw`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Operator {
    Delete,
    Yank,
    Change,
    Indent,
    Dedent,
    Uppercase,
    Lowercase,
    ToggleCase,
}

/// The range affected by a motion, used by operators.
#[derive(Debug, Clone)]
pub struct MotionRange {
    pub start_row: usize,
    pub start_col: usize,
    pub end_row: usize,
    pub end_col: usize,
    pub linewise: bool,
}

/// Snapshot of editor state for undo/redo.
#[derive(Debug, Clone)]
pub struct Snapshot {
    pub lines: Vec<String>,
    pub cursor_row: usize,
    pub cursor_col: usize,
}

/// Register content (for yank/paste).
#[derive(Debug, Clone, Default)]
pub struct Register {
    pub content: String,
    pub linewise: bool,
}

/// State for incremental search (`/` and `?`).
#[derive(Debug, Clone)]
pub struct SearchState {
    pub pattern: String,
    pub forward: bool,
    pub active: bool,
    pub input_buffer: String,
}

impl Default for SearchState {
    fn default() -> Self {
        Self {
            pattern: String::new(),
            forward: true,
            active: false,
            input_buffer: String::new(),
        }
    }
}

/// Recorded keystrokes for dot-repeat (`.`).
#[derive(Debug, Clone)]
pub struct EditRecord {
    pub keys: Vec<KeyEvent>,
}

/// State saved when entering block insert/append/change mode.
/// Used to replay the first-line edits on all other lines when Esc is pressed.
#[derive(Debug, Clone)]
pub struct BlockInsertState {
    /// The rows affected by the block operation (inclusive).
    pub start_row: usize,
    pub end_row: usize,
    /// The column at which text is inserted on each row.
    pub col: usize,
}

/// Temporary highlight for yanked text (like Neovim's `vim.highlight.on_yank()`).
#[derive(Debug, Clone)]
pub struct YankHighlight {
    pub start_row: usize,
    pub start_col: usize,
    pub end_row: usize,
    pub end_col: usize,
    pub linewise: bool,
    pub created_at: std::time::Instant,
}

impl YankHighlight {
    /// Duration the highlight stays visible.
    const DURATION_MS: u128 = 150;

    pub fn is_expired(&self) -> bool {
        self.created_at.elapsed().as_millis() > Self::DURATION_MS
    }
}

/// A diff sign for a specific line, rendered to the RIGHT of the line number.
///
/// Consumers populate [`GutterConfig::signs`] with these values.
/// When empty, the gutter renders exactly as before (zero overhead).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GutterSign {
    /// Line was added (new) — green `│` and green line number.
    Added,
    /// Line was modified — yellow `│` and yellow line number.
    Modified,
    /// Lines were deleted above this position — red `▲`.
    DeletedAbove,
    /// Lines were deleted below this position — red `▼`.
    DeletedBelow,
}

/// Diagnostic severity level, determines the icon and color in the gutter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    /// Error — red `✘`.
    Error,
    /// Warning — yellow `⚠`.
    Warning,
}

/// A diagnostic for a specific line, rendered to the LEFT of the line number.
///
/// Consumers populate [`GutterConfig::diagnostics`] with these values.
/// When non-empty, the gutter reserves 2 extra characters for the diagnostic
/// column (`[icon][space]`). When empty, no extra space is used.
///
/// When the cursor is on a line with a diagnostic that has a `message`,
/// the message is shown in the command line.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    /// Severity level (determines icon and color).
    pub severity: DiagnosticSeverity,
    /// Optional message shown in the command line when the cursor is on this line.
    pub message: Option<String>,
}

/// Configuration for gutter signs and diagnostics.
///
/// Set [`VimEditor::gutter`] to `Some(GutterConfig { .. })` to enable
/// indicators in the gutter. When `None` (the default), rendering is unchanged.
///
/// The gutter layout with both features active:
/// `[diagnostic][space][number][space][diff_sign]`
///
/// Each column is independently optional — diagnostics only add width when
/// the `diagnostics` map is non-empty; diff signs only replace the trailing
/// space when the `signs` map is non-empty.
#[derive(Debug, Clone)]
pub struct GutterConfig {
    /// Diff signs per line index (right of number).
    pub signs: HashMap<usize, GutterSign>,
    /// Diagnostics per line index (left of number).
    pub diagnostics: HashMap<usize, Diagnostic>,
    /// Color for "added" signs and line numbers (default: `Green`).
    pub sign_added: Color,
    /// Color for "modified" signs and line numbers (default: `Yellow`).
    pub sign_modified: Color,
    /// Color for "deleted" signs (default: `Red`).
    pub sign_deleted: Color,
    /// Color for "error" diagnostic signs (default: `Red`).
    pub sign_error: Color,
    /// Color for "warning" diagnostic signs (default: `Yellow`).
    pub sign_warning: Color,
}

impl Default for GutterConfig {
    fn default() -> Self {
        Self {
            signs: HashMap::new(),
            diagnostics: HashMap::new(),
            sign_added: Color::Green,
            sign_modified: Color::Yellow,
            sign_deleted: Color::Red,
            sign_error: Color::Red,
            sign_warning: Color::Yellow,
        }
    }
}

/// Direction for `f`/`F`/`t`/`T` character find motions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FindDirection {
    Forward,
    Backward,
}

/// Theme colors used by the built-in [`render`] module.
///
/// Each application maps its own theme struct to `VimTheme` before calling
/// [`render::render()`].
#[derive(Debug, Clone)]
pub struct VimTheme {
    pub border_focused: Color,
    pub border_unfocused: Color,
    pub border_insert: Color,
    pub editor_bg: Color,
    pub line_nr: Color,
    pub line_nr_active: Color,
    pub visual_bg: Color,
    pub visual_fg: Color,
    pub dim: Color,
    pub accent: Color,
    /// Background for search matches (all occurrences).
    pub search_match_bg: Color,
    /// Background for the current search match (where the cursor is).
    pub search_current_bg: Color,
    /// Foreground for search match text.
    pub search_match_fg: Color,
    /// Background for yank highlight flash.
    pub yank_highlight_bg: Color,
    /// Background for live substitution replacement preview.
    pub substitute_preview_bg: Color,
    /// Background for matching bracket highlight.
    pub match_bracket_bg: Color,
    /// Foreground for matching bracket highlight.
    pub match_bracket_fg: Color,
}

/// Trait for language-specific syntax highlighting.
///
/// Implement this for your language (SQL, JSON, YAML, etc.) and pass it to the
/// [`render`] module. See [`PlainHighlighter`] for a no-op reference implementation.
pub trait SyntaxHighlighter {
    /// Highlight a full line and append styled [`Span`]s.
    fn highlight_line<'a>(&self, line: &'a str, spans: &mut Vec<Span<'a>>);

    /// Highlight a segment of a line (used when part of the line has visual selection).
    /// Defaults to [`highlight_line`](SyntaxHighlighter::highlight_line).
    fn highlight_segment<'a>(&self, text: &'a str, spans: &mut Vec<Span<'a>>) {
        self.highlight_line(text, spans);
    }
}

/// No-op highlighter — renders text without any syntax coloring.
pub struct PlainHighlighter;

impl SyntaxHighlighter for PlainHighlighter {
    fn highlight_line<'a>(&self, line: &'a str, spans: &mut Vec<Span<'a>>) {
        if !line.is_empty() {
            spans.push(Span::raw(line));
        }
    }
}

/// Number of lines kept visible above/below the cursor when scrolling.
pub const SCROLLOFF: usize = 3;