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
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
pub mod input;
pub mod motions;
pub mod operators;
pub mod search;
pub mod visual;

use std::collections::HashMap;

use crate::{
    BlockInsertState, EditRecord, FindDirection, GutterConfig, Operator, Register, SearchState,
    Snapshot, VimMode, VimModeConfig, YankHighlight, SCROLLOFF,
};

/// A self-contained Vim editor instance with its own buffer, cursor, mode, and state.
/// Each view that needs a Vim editor creates its own VimEditor.
pub struct VimEditor {
    pub lines: Vec<String>,
    pub cursor_row: usize,
    pub cursor_col: usize,
    pub mode: VimMode,
    pub config: VimModeConfig,

    // Scroll
    pub scroll_offset: usize,
    pub horizontal_scroll: usize,
    pub visible_height: usize,
    /// When true, the next `ensure_cursor_visible()` call is skipped once.
    /// Set by viewport-scroll commands (Ctrl-d, Ctrl-e) so the scrolloff
    /// clamp doesn't undo the deliberate viewport shift.
    pub skip_next_visible: bool,

    // Undo/Redo
    pub undo_stack: Vec<Snapshot>,
    pub redo_stack: Vec<Snapshot>,

    // Registers
    pub unnamed_register: Register,

    // Search
    pub search: SearchState,

    // Visual mode anchor
    pub visual_anchor: Option<(usize, usize)>,

    // Pending operator/count for Normal mode commands
    pub pending_count: Option<usize>,
    pub pending_operator: Option<Operator>,
    pub pending_g: bool,
    pub pending_register: bool, // waiting for register name after "
    pub use_system_clipboard: bool, // next yank/paste uses system clipboard
    pub pending_find: Option<(FindDirection, bool)>, // for f/F/t/T (direction, before_flag)
    pub last_find: Option<(FindDirection, bool, char)>, // for ;/, repeat
    pub pending_replace: bool, // for r command
    pub pending_z: bool, // for z-prefix (zz, zt, zb)
    pub pending_gc: bool, // for gcc (toggle comment)
    pub pending_text_object: Option<bool>, // Some(false)=inner, Some(true)=around
    pub pending_mark: bool, // for m command (set mark)
    pub pending_goto_mark: Option<bool>, // Some(true)=exact (`), Some(false)=line (')
    pub pending_bracket: Option<char>, // for ]d, [d diagnostic navigation
    pub pending_macro_record: bool, // waiting for register char after q
    pub pending_macro_play: bool, // waiting for register char after @

    // Repeat (dot)
    pub last_edit: Option<EditRecord>,
    pub recording_edit: Vec<crossterm::event::KeyEvent>,
    pub is_recording: bool,

    // Marks: char → (row, col)
    pub marks: HashMap<char, (usize, usize)>,

    // Macros: register → recorded keys
    pub macro_registers: HashMap<char, Vec<crossterm::event::KeyEvent>>,
    pub recording_macro: Option<char>,
    pub macro_buffer: Vec<crossterm::event::KeyEvent>,
    pub last_macro: Option<char>,

    // Block insert (visual block I/A/c)
    pub block_insert: Option<BlockInsertState>,

    // Yank highlight
    pub yank_highlight: Option<YankHighlight>,

    // Status
    pub modified: bool,
    pub command_line: String,

    // Command mode (:)
    pub command_active: bool,
    pub command_buffer: String,

    // Live substitution preview
    pub preview_lines: Option<Vec<String>>,
    /// Highlight ranges for replacement text in preview: (row, start_col, end_col)
    pub preview_highlights: Vec<(usize, usize, usize)>,

    /// Optional gutter diff signs configuration.
    /// When `None` (the default), rendering is unchanged.
    pub gutter: Option<GutterConfig>,
}

impl VimEditor {
    pub fn new(content: &str, config: VimModeConfig) -> Self {
        let expanded = content.replace('\t', "    ");
        let lines: Vec<String> = if expanded.is_empty() {
            vec![String::new()]
        } else {
            expanded.lines().map(String::from).collect()
        };

        Self {
            lines,
            cursor_row: 0,
            cursor_col: 0,
            mode: VimMode::Normal,
            config,
            scroll_offset: 0,
            horizontal_scroll: 0,
            visible_height: 20,
            skip_next_visible: false,
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            unnamed_register: Register::default(),
            search: SearchState::default(),
            visual_anchor: None,
            pending_count: None,
            pending_operator: None,
            pending_g: false,
            pending_register: false,
            use_system_clipboard: false,
            pending_find: None,
            last_find: None,
            pending_replace: false,
            pending_z: false,
            pending_gc: false,
            pending_text_object: None,
            pending_mark: false,
            pending_goto_mark: None,
            pending_bracket: None,
            pending_macro_record: false,
            pending_macro_play: false,
            last_edit: None,
            recording_edit: Vec::new(),
            is_recording: false,
            marks: HashMap::new(),
            macro_registers: HashMap::new(),
            recording_macro: None,
            macro_buffer: Vec::new(),
            last_macro: None,
            block_insert: None,
            yank_highlight: None,
            modified: false,
            command_line: String::new(),
            command_active: false,
            command_buffer: String::new(),
            preview_lines: None,
            preview_highlights: Vec::new(),
            gutter: None,
        }
    }

    pub fn new_empty(config: VimModeConfig) -> Self {
        Self::new("", config)
    }

    pub fn set_content(&mut self, content: &str) {
        let expanded = content.replace('\t', "    ");
        self.lines = if expanded.is_empty() {
            vec![String::new()]
        } else {
            expanded.lines().map(String::from).collect()
        };
        self.cursor_row = 0;
        self.cursor_col = 0;
        self.scroll_offset = 0;
        self.undo_stack.clear();
        self.redo_stack.clear();
        self.modified = false;
    }

    pub fn content(&self) -> String {
        self.lines.join("\n")
    }

    /// Get the visually selected text
    pub fn selected_text(&self) -> Option<String> {
        let ((sr, sc), (er, ec)) = self.visual_range()?;
        let kind = match &self.mode {
            super::VimMode::Visual(k) => k.clone(),
            _ => return None,
        };

        match kind {
            super::VisualKind::Line => {
                Some(self.lines[sr..=er].join("\n"))
            }
            super::VisualKind::Char => {
                if sr == er {
                    let line = &self.lines[sr];
                    let s = sc.min(line.len());
                    let e = (ec + 1).min(line.len());
                    Some(line[s..e].to_string())
                } else {
                    let mut text = String::new();
                    let first = &self.lines[sr];
                    text.push_str(&first[sc.min(first.len())..]);
                    for row in (sr + 1)..er {
                        text.push('\n');
                        text.push_str(&self.lines[row]);
                    }
                    text.push('\n');
                    let last = &self.lines[er];
                    text.push_str(&last[..(ec + 1).min(last.len())]);
                    Some(text)
                }
            }
            super::VisualKind::Block => {
                let left = sc.min(ec);
                let right = sc.max(ec) + 1;
                let mut text = String::new();
                for row in sr..=er {
                    let line = &self.lines[row];
                    let s = left.min(line.len());
                    let e = right.min(line.len());
                    if !text.is_empty() {
                        text.push('\n');
                    }
                    text.push_str(&line[s..e]);
                }
                Some(text)
            }
        }
    }

    #[allow(dead_code)]
    pub fn line_count(&self) -> usize {
        self.lines.len()
    }

    /// Returns the cursor shape hint for the current mode.
    pub fn cursor_shape(&self) -> crate::CursorShape {
        if self.pending_replace {
            return crate::CursorShape::Underline;
        }
        match &self.mode {
            VimMode::Normal => crate::CursorShape::Block,
            VimMode::Insert => crate::CursorShape::Bar,
            VimMode::Replace => crate::CursorShape::Underline,
            VimMode::Visual(_) => crate::CursorShape::Block,
        }
    }

    pub fn current_line(&self) -> &str {
        self.lines.get(self.cursor_row).map(|s| s.as_str()).unwrap_or("")
    }

    pub fn current_line_len(&self) -> usize {
        self.current_line().len()
    }

    /// Clamp cursor column to valid range for current line
    pub fn clamp_cursor(&mut self) {
        let max_col = match self.mode {
            VimMode::Insert | VimMode::Replace => self.current_line_len(),
            _ => self.current_line_len().saturating_sub(1).max(0),
        };
        if self.cursor_col > max_col {
            self.cursor_col = max_col;
        }
        if self.cursor_row >= self.lines.len() {
            self.cursor_row = self.lines.len().saturating_sub(1);
        }
    }

    /// Save current state for undo
    pub fn save_undo(&mut self) {
        self.undo_stack.push(Snapshot {
            lines: self.lines.clone(),
            cursor_row: self.cursor_row,
            cursor_col: self.cursor_col,
        });
        self.redo_stack.clear();
    }

    /// Undo last change
    pub fn undo(&mut self) {
        if let Some(snapshot) = self.undo_stack.pop() {
            self.redo_stack.push(Snapshot {
                lines: self.lines.clone(),
                cursor_row: self.cursor_row,
                cursor_col: self.cursor_col,
            });
            self.lines = snapshot.lines;
            self.cursor_row = snapshot.cursor_row;
            self.cursor_col = snapshot.cursor_col;
            self.clamp_cursor();
            self.modified = true;
        }
    }

    /// Redo last undone change
    pub fn redo(&mut self) {
        if let Some(snapshot) = self.redo_stack.pop() {
            self.undo_stack.push(Snapshot {
                lines: self.lines.clone(),
                cursor_row: self.cursor_row,
                cursor_col: self.cursor_col,
            });
            self.lines = snapshot.lines;
            self.cursor_row = snapshot.cursor_row;
            self.cursor_col = snapshot.cursor_col;
            self.clamp_cursor();
            self.modified = true;
        }
    }

    /// Ensure scroll keeps cursor visible with scrolloff
    pub fn ensure_cursor_visible(&mut self) {
        let scrolloff = SCROLLOFF.min(self.visible_height / 2);

        if self.cursor_row < self.scroll_offset + scrolloff {
            self.scroll_offset = self.cursor_row.saturating_sub(scrolloff);
        }

        if self.cursor_row + scrolloff >= self.scroll_offset + self.visible_height {
            self.scroll_offset = (self.cursor_row + scrolloff + 1).saturating_sub(self.visible_height);
        }
    }

    // --- Insert mode text operations ---

    pub fn insert_char(&mut self, c: char) {
        if self.cursor_row < self.lines.len() {
            let col = self.cursor_col.min(self.lines[self.cursor_row].len());
            self.lines[self.cursor_row].insert(col, c);
            self.cursor_col = col + 1;
            self.modified = true;
        }
    }

    pub fn insert_newline(&mut self) {
        if self.cursor_row < self.lines.len() {
            let col = self.cursor_col.min(self.lines[self.cursor_row].len());
            let indent = {
                let line = &self.lines[self.cursor_row];
                let trimmed = line.trim_start();
                line[..line.len() - trimmed.len()].to_string()
            };
            let rest = self.lines[self.cursor_row][col..].to_string();
            self.lines[self.cursor_row].truncate(col);
            self.cursor_row += 1;
            self.lines
                .insert(self.cursor_row, format!("{}{}", indent, rest));
            self.cursor_col = indent.len();
            self.modified = true;
        }
    }

    pub fn backspace(&mut self) {
        if self.cursor_col > 0 {
            let col = self.cursor_col.min(self.lines[self.cursor_row].len());
            if col > 0 {
                self.lines[self.cursor_row].remove(col - 1);
                self.cursor_col = col - 1;
                self.modified = true;
            }
        } else if self.cursor_row > 0 {
            let current_line = self.lines.remove(self.cursor_row);
            self.cursor_row -= 1;
            self.cursor_col = self.lines[self.cursor_row].len();
            self.lines[self.cursor_row].push_str(&current_line);
            self.modified = true;
        }
    }

    // --- Delete operations ---

    pub fn delete_char_at_cursor(&mut self) {
        if self.cursor_row < self.lines.len() {
            let line_len = self.lines[self.cursor_row].len();
            if self.cursor_col < line_len {
                let ch = self.lines[self.cursor_row].remove(self.cursor_col);
                self.unnamed_register = Register {
                    content: ch.to_string(),
                    linewise: false,
                };
                self.modified = true;
                self.clamp_cursor();
            }
        }
    }

    #[allow(dead_code)]
    pub fn delete_line(&mut self, row: usize) -> Option<String> {
        if row < self.lines.len() {
            let line = self.lines.remove(row);
            if self.lines.is_empty() {
                self.lines.push(String::new());
            }
            self.clamp_cursor();
            self.modified = true;
            Some(line)
        } else {
            None
        }
    }

    pub fn delete_lines(&mut self, start: usize, count: usize) -> String {
        let end = (start + count).min(self.lines.len());
        let removed: Vec<String> = self.lines.drain(start..end).collect();
        if self.lines.is_empty() {
            self.lines.push(String::new());
        }
        if self.cursor_row >= self.lines.len() {
            self.cursor_row = self.lines.len() - 1;
        }
        self.clamp_cursor();
        self.modified = true;
        removed.join("\n")
    }

    pub fn delete_range(&mut self, start_col: usize, end_col: usize, row: usize) -> String {
        if row >= self.lines.len() {
            return String::new();
        }
        let line_len = self.lines[row].len();
        let s = start_col.min(line_len);
        let e = end_col.min(line_len);
        if s >= e {
            return String::new();
        }
        let removed: String = self.lines[row][s..e].to_string();
        self.lines[row] = format!("{}{}", &self.lines[row][..s], &self.lines[row][e..]);
        self.modified = true;
        removed
    }

    // --- Paste ---

    /// Resolve paste content: system clipboard first, then unnamed register fallback.
    fn resolve_paste_register(&self) -> Register {
        if let Some(text) = Self::read_system_clipboard() {
            let linewise = text.ends_with('\n');
            let content = if linewise {
                text.trim_end_matches('\n').to_string()
            } else {
                text
            };
            // Multi-line content from clipboard is always treated as linewise
            let linewise = linewise || content.contains('\n');
            Register { content, linewise }
        } else {
            self.unnamed_register.clone()
        }
    }

    #[allow(dead_code)]
    pub fn paste_after(&mut self) {
        let reg = self.resolve_paste_register();
        if reg.content.is_empty() {
            return;
        }
        self.save_undo();
        if reg.linewise {
            let new_lines: Vec<String> = reg.content.lines().map(String::from).collect();
            let insert_at = (self.cursor_row + 1).min(self.lines.len());
            for (i, line) in new_lines.into_iter().enumerate() {
                self.lines.insert(insert_at + i, line);
            }
            self.cursor_row = insert_at;
            self.cursor_col = 0;
        } else {
            let col = (self.cursor_col + 1).min(self.lines[self.cursor_row].len());
            self.lines[self.cursor_row].insert_str(col, &reg.content);
            self.cursor_col = col + reg.content.len() - 1;
        }
        self.modified = true;
    }

    #[allow(dead_code)]
    pub fn paste_before(&mut self) {
        let reg = self.resolve_paste_register();
        if reg.content.is_empty() {
            return;
        }
        self.save_undo();
        if reg.linewise {
            let new_lines: Vec<String> = reg.content.lines().map(String::from).collect();
            for (i, line) in new_lines.into_iter().enumerate() {
                self.lines.insert(self.cursor_row + i, line);
            }
            self.cursor_col = 0;
        } else {
            let col = self.cursor_col.min(self.lines[self.cursor_row].len());
            self.lines[self.cursor_row].insert_str(col, &reg.content);
            self.cursor_col = col + reg.content.len() - 1;
        }
        self.modified = true;
    }

    // --- Join lines ---

    pub fn join_lines(&mut self) {
        if self.cursor_row + 1 < self.lines.len() {
            self.save_undo();
            let next_line = self.lines.remove(self.cursor_row + 1);
            let trimmed = next_line.trim_start();
            let join_col = self.lines[self.cursor_row].len();
            if !self.lines[self.cursor_row].is_empty() && !trimmed.is_empty() {
                self.lines[self.cursor_row].push(' ');
                self.cursor_col = join_col;
            } else {
                self.cursor_col = join_col;
            }
            self.lines[self.cursor_row].push_str(trimmed);
            self.modified = true;
        }
    }

    // --- Indentation ---

    pub fn indent_line(&mut self, row: usize) {
        if row < self.lines.len() {
            self.lines[row].insert_str(0, "    ");
            self.modified = true;
        }
    }

    pub fn dedent_line(&mut self, row: usize) {
        if row < self.lines.len() {
            let line = &self.lines[row];
            let spaces = line.len() - line.trim_start().len();
            let remove = spaces.min(4);
            if remove > 0 {
                self.lines[row] = self.lines[row][remove..].to_string();
                self.modified = true;
            }
        }
    }

    /// Get effective count: pending_count or 1
    pub fn take_count(&mut self) -> usize {
        self.pending_count.take().unwrap_or(1)
    }

    /// Update command line based on current mode
    pub fn update_command_line(&mut self) {
        if self.command_active {
            self.command_line = format!(":{}", self.command_buffer);
            // Live preview: highlight substitution pattern + replacement
            self.search.pattern = self
                .extract_substitute_pattern()
                .unwrap_or_default();
            if let Some((lines, hl)) = self.compute_substitute_preview() {
                self.preview_lines = Some(lines);
                self.preview_highlights = hl;
            } else {
                self.preview_lines = None;
                self.preview_highlights.clear();
            }
            return;
        }
        self.command_line = match &self.mode {
            VimMode::Normal => {
                if self.search.active {
                    let prefix = if self.search.forward { "/" } else { "?" };
                    format!("{}{}", prefix, self.search.input_buffer)
                } else if self.pending_operator.is_some() || self.pending_count.is_some() {
                    let mut s = String::new();
                    if let Some(n) = self.pending_count {
                        s.push_str(&n.to_string());
                    }
                    if let Some(op) = &self.pending_operator {
                        s.push(match op {
                            Operator::Delete => 'd',
                            Operator::Yank => 'y',
                            Operator::Change => 'c',
                            Operator::Indent => '>',
                            Operator::Dedent => '<',
                            Operator::Uppercase => 'U',
                            Operator::Lowercase => 'u',
                            Operator::ToggleCase => '~',
                        });
                    }
                    s
                } else {
                    self.diagnostic_message_at_cursor().unwrap_or_default()
                }
            }
            VimMode::Insert => "-- INSERT --".to_string(),
            VimMode::Replace => "-- REPLACE --".to_string(),
            VimMode::Visual(kind) => {
                let label = match kind {
                    super::VisualKind::Char => "VISUAL",
                    super::VisualKind::Line => "VISUAL LINE",
                    super::VisualKind::Block => "VISUAL BLOCK",
                };
                format!("-- {} --", label)
            }
        };
        // Append macro recording indicator
        if let Some(reg) = self.recording_macro {
            if self.command_line.is_empty() {
                self.command_line = format!("recording @{}", reg);
            } else {
                self.command_line = format!("{}  recording @{}", self.command_line, reg);
            }
        }
    }

    /// Get the diagnostic message for the line at the cursor, if any.
    fn diagnostic_message_at_cursor(&self) -> Option<String> {
        let g = self.gutter.as_ref()?;
        let diag = g.diagnostics.get(&self.cursor_row)?;
        diag.message.clone()
    }

    /// Extract the search pattern from a partial substitution command in command_buffer.
    fn extract_substitute_pattern(&self) -> Option<String> {
        let (pattern, _, _, _) = self.extract_substitute_parts()?;
        Some(pattern)
    }

    /// Parse partial substitution command, returning (pattern, replacement, range_all, flags).
    /// Handles incomplete input gracefully (e.g., `:s/hol` without closing delimiter).
    fn extract_substitute_parts(&self) -> Option<(String, Option<String>, bool, String)> {
        let cmd = self.command_buffer.trim();

        // Strip range prefix and determine if % (all lines)
        let (all, rest) = if let Some(after) = cmd.strip_prefix('%') {
            (true, after)
        } else if let Some(pos) = cmd.find('s') {
            let prefix = &cmd[..pos];
            if prefix.is_empty() || prefix.chars().all(|c| c.is_ascii_digit() || c == ',') {
                (false, &cmd[pos..])
            } else {
                return None;
            }
        } else {
            return None;
        };

        if !rest.starts_with('s') || rest.len() < 3 {
            return None;
        }

        let delim = rest.as_bytes()[1] as char;
        if delim.is_alphanumeric() {
            return None;
        }

        // Parse: s/pattern/replacement/flags — each part may be incomplete
        let body = &rest[2..];
        let mut parts: Vec<String> = Vec::new();
        let mut current = String::new();
        let mut chars = body.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\\' {
                if let Some(&next) = chars.peek() {
                    if next == delim {
                        current.push(next);
                        chars.next();
                        continue;
                    }
                }
                current.push(c);
            } else if c == delim {
                parts.push(current.clone());
                current.clear();
            } else {
                current.push(c);
            }
        }

        let pattern = if let Some(p) = parts.first() {
            if p.is_empty() { return None; }
            p.clone()
        } else if !current.is_empty() {
            // Still typing the pattern (no closing delimiter yet)
            return Some((current, None, all, String::new()));
        } else {
            return None;
        };

        let replacement = if parts.len() >= 2 {
            Some(parts[1].clone())
        } else if !current.is_empty() {
            // Still typing the replacement
            Some(current.clone())
        } else {
            // Just closed the pattern delimiter, replacement is empty so far
            Some(String::new())
        };

        let flags = if parts.len() >= 3 {
            parts[2].clone()
        } else if parts.len() >= 2 {
            current
        } else {
            String::new()
        };

        Some((pattern, replacement, all, flags))
    }

    /// Determine if a pattern should be case-insensitive (smartcase):
    /// all-lowercase → insensitive, any uppercase → sensitive.
    /// The `i` flag forces insensitive regardless.
    fn is_smartcase_insensitive(pattern: &str, flags: &str) -> bool {
        if flags.contains('i') {
            return true;
        }
        // Smartcase: if pattern has no uppercase letters, match case-insensitively
        !pattern.chars().any(|c| c.is_uppercase())
    }

    /// Compute preview lines and highlight ranges for replacement text.
    #[allow(clippy::type_complexity)]
    fn compute_substitute_preview(
        &self,
    ) -> Option<(Vec<String>, Vec<(usize, usize, usize)>)> {
        let (pattern, replacement, all, flags) = self.extract_substitute_parts()?;
        let replacement = replacement?;

        let case_insensitive = Self::is_smartcase_insensitive(&pattern, &flags);
        let global = flags.contains('g');

        let regex_pattern = if case_insensitive {
            format!("(?i){}", pattern)
        } else {
            pattern
        };
        let re = regex::Regex::new(&regex_pattern).ok()?;

        let (start, end) = if all {
            (0, self.lines.len().saturating_sub(1))
        } else {
            (self.cursor_row, self.cursor_row)
        };

        let mut preview = self.lines.clone();
        let mut highlights = Vec::new();

        for row in start..=end.min(preview.len().saturating_sub(1)) {
            let line = &self.lines[row];
            // Build new line and track replacement positions
            let mut new_line = String::new();
            let mut last_end = 0;
            let matches: Vec<_> = re.find_iter(line).collect();
            let match_count = if global { matches.len() } else { matches.len().min(1) };

            for m in matches.iter().take(match_count) {
                new_line.push_str(&line[last_end..m.start()]);
                let rep_start = new_line.len();
                // Expand replacement (handles $1, $2 etc.)
                let expanded = re.replace(m.as_str(), replacement.as_str());
                new_line.push_str(&expanded);
                let rep_end = new_line.len();
                if rep_start < rep_end {
                    highlights.push((row, rep_start, rep_end));
                }
                last_end = m.end();
            }
            new_line.push_str(&line[last_end..]);
            preview[row] = new_line;
        }

        Some((preview, highlights))
    }

    // --- System clipboard ---

    pub fn copy_to_system_clipboard(&self, text: &str) {
        // Try xclip first, then xsel, then wl-copy (Wayland)
        let cmds: &[(&str, &[&str])] = &[
            ("wl-copy", &[]),
            ("xclip", &["-selection", "clipboard"]),
            ("xsel", &["--clipboard", "--input"]),
        ];
        for (cmd, args) in cmds {
            if let Ok(mut child) = std::process::Command::new(cmd)
                .args(*args)
                .stdin(std::process::Stdio::piped())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn()
            {
                if let Some(mut stdin) = child.stdin.take() {
                    use std::io::Write;
                    let _ = stdin.write_all(text.as_bytes());
                }
                let _ = child.wait();
                return;
            }
        }
    }

    pub fn read_system_clipboard() -> Option<String> {
        let cmds: &[(&str, &[&str])] = &[
            ("wl-paste", &["--no-newline"]),
            ("xclip", &["-selection", "clipboard", "-o"]),
            ("xsel", &["--clipboard", "--output"]),
        ];
        for (cmd, args) in cmds {
            if let Ok(output) = std::process::Command::new(cmd)
                .args(*args)
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::null())
                .output()
                && output.status.success()
            {
                if let Ok(text) = String::from_utf8(output.stdout) {
                    if !text.is_empty() {
                        return Some(text);
                    }
                }
            }
        }
        None
    }
}