reovim-module-vim 0.14.3

Vim policy module for reovim - keybindings and behavior
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
//! Visual mode operator commands.
//!
//! Provides commands that operate on the visual selection:
//! - `d` - Delete selection
//! - `y` - Yank (copy) selection
//! - `c` - Change selection (delete + insert mode)
//! - `>` - Indent selection
//! - `<` - Dedent selection

use {
    reovim_driver_command::{Command, CommandContext, CommandHandler, CommandResult},
    reovim_driver_session::{
        BufferApi, SessionRuntime, TransitionContext,
        api::{ChangeTracker, ModeApi, RegisterContent, Selection, SelectionMode},
    },
    reovim_kernel::api::v1::{CommandId, Position},
};

use crate::{ids, modes::VimMode};

/// Calculate the expanded range for a selection.
///
/// This converts an API Selection into start/end positions suitable for
/// text extraction and deletion, taking selection mode into account:
/// - Character mode: End is already exclusive, use as-is
/// - Line mode: Expand to full lines including trailing newline
/// - Block mode: End is already exclusive, use as-is
///
/// Phase 8 (#465): Selection.end is EXCLUSIVE (like Rust ranges).
/// The selection (0,0) to (0,5) means columns 0..5 = "hello" (5 chars).
///
/// Returns `(start, end, is_linewise)`.
fn expand_selection_range(
    selection: &Selection,
    end_line_len: Option<usize>,
    total_lines: usize,
) -> (Position, Position, bool) {
    let start = selection.start;
    let end = selection.end;

    match selection.mode {
        SelectionMode::Line => {
            // Expand to full lines, including the trailing newline
            let start = Position::new(start.line, 0);
            // For line mode, end.line is already the exclusive end line
            // For non-last lines, extend to start of end line (includes previous line's newline)
            // For last line, end at line length
            let end_line_len = end_line_len.unwrap_or(0);
            let end = if end.line < total_lines {
                Position::new(end.line, 0)
            } else {
                // End is past buffer, cap at last line's length
                Position::new(end.line - 1, end_line_len)
            };
            (start, end, true)
        }
        // Character and Block modes: End is already exclusive - use as-is
        SelectionMode::Character | SelectionMode::Block => (start, end, false),
    }
}

/// Delete selection (d in visual mode).
///
/// Deletes the selected text and stores it in the register.
/// Returns to Normal mode after execution.
#[derive(Debug, Clone, Copy, Default)]
pub struct DeleteSelection;

impl Command for DeleteSelection {
    fn id(&self) -> CommandId {
        ids::DELETE_SELECTION
    }

    fn description(&self) -> &'static str {
        "Delete visual selection"
    }
}

impl CommandHandler for DeleteSelection {
    #[cfg_attr(coverage_nightly, coverage(off))]
    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
        let Some(buffer_id) = args.buffer_id() else {
            return CommandResult::error("No active buffer");
        };

        // Get selection from active window
        let Some(selection) = runtime.windows().active().and_then(|w| w.selection.clone()) else {
            return CommandResult::Success; // No selection - no-op
        };

        // Get line info for expanding selection
        let end_line_len = runtime.buffer_line_len(buffer_id, selection.end.line);
        let total_lines = runtime.buffer_line_count(buffer_id).unwrap_or(1);

        // Expand selection to deletion range
        let (start, end, is_linewise) =
            expand_selection_range(&selection, end_line_len, total_lines);
        let cursor_pos = start;

        // Extract text for register with clipboard sync (#515)
        if let Some(text) = runtime.buffer_text_range(buffer_id, start, end) {
            let content = if is_linewise {
                RegisterContent::linewise(&text)
            } else {
                RegisterContent::characterwise(&text)
            };
            runtime.store_register_with_sync(args.register(), content);
        }

        // Delete the range
        runtime.delete_range(buffer_id, start, end);

        // Clear selection and set cursor
        if let Some(window) = runtime.windows_mut().active_mut() {
            window.selection = None;
            window.cursor = cursor_pos.into();
        }

        // #474: Notify other clients that selection was cleared
        runtime.record_selection_change(buffer_id);

        // Mode transition to Normal
        runtime.set_mode(VimMode::NORMAL_ID, TransitionContext::new());

        CommandResult::Success
    }
}

/// Yank selection (y in visual mode).
///
/// Copies the selected text to the register without deleting it.
/// Returns to Normal mode after execution.
#[derive(Debug, Clone, Copy, Default)]
pub struct YankSelection;

impl Command for YankSelection {
    fn id(&self) -> CommandId {
        ids::YANK_SELECTION
    }

    fn description(&self) -> &'static str {
        "Yank visual selection"
    }
}

impl CommandHandler for YankSelection {
    #[cfg_attr(coverage_nightly, coverage(off))]
    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
        let Some(buffer_id) = args.buffer_id() else {
            return CommandResult::error("No active buffer");
        };

        // Get selection from active window
        let Some(selection) = runtime.windows().active().and_then(|w| w.selection.clone()) else {
            return CommandResult::Success; // No selection - no-op
        };

        // Get line info for expanding selection
        let end_line_len = runtime.buffer_line_len(buffer_id, selection.end.line);
        let total_lines = runtime.buffer_line_count(buffer_id).unwrap_or(1);

        // Expand selection to yank range
        let (start, end, is_linewise) =
            expand_selection_range(&selection, end_line_len, total_lines);

        // Extract text for register with clipboard sync (#515)
        if let Some(text) = runtime.buffer_text_range(buffer_id, start, end) {
            let content = if is_linewise {
                RegisterContent::linewise(&text)
            } else {
                RegisterContent::characterwise(&text)
            };
            runtime.store_register_with_sync(args.register(), content);
        }

        // Clear selection (yank doesn't delete text or move cursor)
        if let Some(window) = runtime.windows_mut().active_mut() {
            window.selection = None;
        }

        // #474: Notify other clients that selection was cleared
        runtime.record_selection_change(buffer_id);

        // Mode transition to Normal
        runtime.set_mode(VimMode::NORMAL_ID, TransitionContext::new());

        CommandResult::Success
    }
}

/// Change selection (c in visual mode).
///
/// Deletes the selected text and enters Insert mode.
#[derive(Debug, Clone, Copy, Default)]
pub struct ChangeSelection;

impl Command for ChangeSelection {
    fn id(&self) -> CommandId {
        ids::CHANGE_SELECTION
    }

    fn description(&self) -> &'static str {
        "Change visual selection (delete and enter insert mode)"
    }
}

impl CommandHandler for ChangeSelection {
    #[cfg_attr(coverage_nightly, coverage(off))]
    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
        let Some(buffer_id) = args.buffer_id() else {
            return CommandResult::error("No active buffer");
        };

        // Get selection from active window
        let Some(selection) = runtime.windows().active().and_then(|w| w.selection.clone()) else {
            return CommandResult::Success; // No selection - no-op
        };

        // Get line info for expanding selection
        let end_line_len = runtime.buffer_line_len(buffer_id, selection.end.line);
        let total_lines = runtime.buffer_line_count(buffer_id).unwrap_or(1);

        // Expand selection to deletion range
        let (start, end, is_linewise) =
            expand_selection_range(&selection, end_line_len, total_lines);
        let cursor_pos = start;

        // Extract text for register with clipboard sync (#515)
        if let Some(text) = runtime.buffer_text_range(buffer_id, start, end) {
            let content = if is_linewise {
                RegisterContent::linewise(&text)
            } else {
                RegisterContent::characterwise(&text)
            };
            runtime.store_register_with_sync(args.register(), content);
        }

        // Delete the range
        runtime.delete_range(buffer_id, start, end);

        // Clear selection and set cursor
        if let Some(window) = runtime.windows_mut().active_mut() {
            window.selection = None;
            window.cursor = cursor_pos.into();
        }

        // #474: Notify other clients that selection was cleared
        runtime.record_selection_change(buffer_id);

        // Mode transition to Insert (change = delete + insert mode)
        runtime.set_mode(VimMode::INSERT_ID, TransitionContext::new());

        CommandResult::Success
    }
}

/// Indent selection (> in visual mode).
///
/// Increases indentation of selected lines.
/// Returns to Normal mode after execution.
#[derive(Debug, Clone, Copy, Default)]
pub struct IndentSelection;

impl Command for IndentSelection {
    fn id(&self) -> CommandId {
        ids::INDENT_SELECTION
    }

    fn description(&self) -> &'static str {
        "Indent visual selection"
    }
}

impl CommandHandler for IndentSelection {
    #[cfg_attr(coverage_nightly, coverage(off))]
    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
        let Some(buffer_id) = args.buffer_id() else {
            return CommandResult::error("No active buffer");
        };

        // Get selection from active window
        let Some(selection) = runtime.windows().active().and_then(|w| w.selection.clone()) else {
            return CommandResult::Success; // No selection - no-op
        };

        // Get line range from normalized selection
        // Phase 8 (#465): Selection.end is EXCLUSIVE (like Rust ranges)
        let start_line = selection.start.line;
        let end_line = selection.end.line; // exclusive

        // Indent each line (add tab/spaces at start)
        // Using 4 spaces as default indent
        let indent = "    ";
        for line_idx in start_line..end_line {
            runtime.insert_text(buffer_id, Position::new(line_idx, 0), indent);
        }

        // Clear selection
        if let Some(window) = runtime.windows_mut().active_mut() {
            window.selection = None;
        }

        // #474: Notify other clients that selection was cleared
        runtime.record_selection_change(buffer_id);

        runtime.set_mode(VimMode::NORMAL_ID, TransitionContext::new());

        CommandResult::Success
    }
}

/// Dedent selection (< in visual mode).
///
/// Decreases indentation of selected lines.
/// Returns to Normal mode after execution.
#[derive(Debug, Clone, Copy, Default)]
pub struct DedentSelection;

impl Command for DedentSelection {
    fn id(&self) -> CommandId {
        ids::DEDENT_SELECTION
    }

    fn description(&self) -> &'static str {
        "Dedent visual selection"
    }
}

impl CommandHandler for DedentSelection {
    #[cfg_attr(coverage_nightly, coverage(off))]
    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
        let Some(buffer_id) = args.buffer_id() else {
            return CommandResult::error("No active buffer");
        };

        // Get selection from active window
        let Some(selection) = runtime.windows().active().and_then(|w| w.selection.clone()) else {
            return CommandResult::Success; // No selection - no-op
        };

        // Get line range from normalized selection
        // Phase 8 (#465): Selection.end is EXCLUSIVE (like Rust ranges)
        let start_line = selection.start.line;
        let end_line = selection.end.line; // exclusive

        // Dedent each line (remove leading whitespace, up to 4 chars or one tab)
        for line_idx in start_line..end_line {
            if let Some(line) = runtime.buffer_line(buffer_id, line_idx) {
                let mut chars_to_remove = 0;
                for (i, c) in line.chars().enumerate() {
                    if c == '\t' {
                        chars_to_remove = i + 1;
                        break;
                    } else if c == ' ' && i < 4 {
                        chars_to_remove = i + 1;
                    } else {
                        break;
                    }
                }
                if chars_to_remove > 0 {
                    let start = Position::new(line_idx, 0);
                    let end = Position::new(line_idx, chars_to_remove);
                    runtime.delete_range(buffer_id, start, end);
                }
            }
        }

        // Clear selection
        if let Some(window) = runtime.windows_mut().active_mut() {
            window.selection = None;
        }

        // #474: Notify other clients that selection was cleared
        runtime.record_selection_change(buffer_id);

        runtime.set_mode(VimMode::NORMAL_ID, TransitionContext::new());

        CommandResult::Success
    }
}

// =============================================================================
// Case Operators in Visual Mode (#666)
// =============================================================================

/// Helper to apply a case transformation to the visual selection.
#[cfg_attr(coverage_nightly, coverage(off))]
fn execute_case_selection(
    runtime: &mut SessionRuntime<'_>,
    args: &CommandContext,
    transform: fn(&str) -> String,
) -> CommandResult {
    let Some(buffer_id) = args.buffer_id() else {
        return CommandResult::error("No active buffer");
    };

    let Some(selection) = runtime.windows().active().and_then(|w| w.selection.clone()) else {
        return CommandResult::Success;
    };

    let end_line_len = runtime.buffer_line_len(buffer_id, selection.end.line);
    let total_lines = runtime.buffer_line_count(buffer_id).unwrap_or(1);
    let (start, end, _is_linewise) = expand_selection_range(&selection, end_line_len, total_lines);

    // Read, transform, replace
    if let Some(text) = runtime.buffer_text_range(buffer_id, start, end) {
        let transformed = transform(&text);
        if transformed != text {
            runtime.delete_range(buffer_id, start, end);
            runtime.insert_text(buffer_id, start, &transformed);
        }
    }

    // Clear selection and set cursor to start of range
    if let Some(window) = runtime.windows_mut().active_mut() {
        window.selection = None;
        window.cursor = start.into();
    }

    runtime.record_selection_change(buffer_id);
    runtime.set_mode(VimMode::NORMAL_ID, TransitionContext::new());

    CommandResult::Success
}

/// Toggle case of selection (~ in visual mode).
#[derive(Debug, Clone, Copy, Default)]
pub struct ToggleCaseSelection;

impl Command for ToggleCaseSelection {
    fn id(&self) -> CommandId {
        ids::TOGGLE_CASE_SELECTION
    }

    fn description(&self) -> &'static str {
        "Toggle case of visual selection"
    }
}

// Needs visual mode + buffer state — tested by integration tests.
#[cfg_attr(coverage_nightly, coverage(off))]
impl CommandHandler for ToggleCaseSelection {
    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
        execute_case_selection(runtime, args, |s| {
            s.chars()
                .map(|c| {
                    if c.is_uppercase() {
                        c.to_lowercase().next().unwrap_or(c)
                    } else if c.is_lowercase() {
                        c.to_uppercase().next().unwrap_or(c)
                    } else {
                        c
                    }
                })
                .collect()
        })
    }
}

/// Lowercase selection (u in visual mode).
#[derive(Debug, Clone, Copy, Default)]
pub struct LowercaseSelection;

impl Command for LowercaseSelection {
    fn id(&self) -> CommandId {
        ids::LOWERCASE_SELECTION
    }

    fn description(&self) -> &'static str {
        "Lowercase visual selection"
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl CommandHandler for LowercaseSelection {
    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
        execute_case_selection(runtime, args, str::to_lowercase)
    }
}

/// Uppercase selection (U in visual mode).
#[derive(Debug, Clone, Copy, Default)]
pub struct UppercaseSelection;

impl Command for UppercaseSelection {
    fn id(&self) -> CommandId {
        ids::UPPERCASE_SELECTION
    }

    fn description(&self) -> &'static str {
        "Uppercase visual selection"
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl CommandHandler for UppercaseSelection {
    fn execute(&self, runtime: &mut SessionRuntime<'_>, args: &CommandContext) -> CommandResult {
        execute_case_selection(runtime, args, str::to_uppercase)
    }
}

#[cfg(test)]
#[allow(clippy::significant_drop_tightening, clippy::uninlined_format_args)]
#[path = "tests/operators.rs"]
mod tests;