vorto 0.4.0

A terminal text editor with tree-sitter syntax highlighting and LSP support
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
//! Insertion-side primitives: typing characters and newlines, opening
//! lines, replacing the char under the cursor, and the auto-pair /
//! auto-indent heuristics layered on top.
//!
//! `*_smart` variants ([`Buffer::insert_char_smart`],
//! [`Buffer::delete_char_before_smart`]) are the single-cursor paths the
//! input layer uses; the multi-cursor fan-out drives raw
//! [`Buffer::insert_char`] / [`Buffer::delete_char_before`] directly so
//! the per-cursor `col` shift bookkeeping stays valid.

use super::{Buffer, IndentSettings, char_to_byte};

impl Buffer {
    pub fn insert_char(&mut self, c: char) {
        let line = &mut self.lines[self.cursor.row];
        let byte_idx = char_to_byte(line, self.cursor.col);
        line.insert(byte_idx, c);
        self.cursor.col += 1;
        self.touch();
    }

    /// Insert `c` at the cursor with three modern-editor behaviours
    /// layered on top of [`insert_char`]:
    ///
    /// 1. **Skip-over** — if `c` is a paired closer (`)` / `]` / `}` /
    ///    quote) and the next character on the line is already the same
    ///    closer, we just advance the cursor. This is what makes
    ///    `()`-then-type-`)` land outside the pair instead of producing
    ///    `())`.
    /// 2. **Dedent on close** — `}` / `)` / `]` typed on a line that's
    ///    pure whitespace before the cursor pulls the line back one
    ///    indent level first.
    /// 3. **Auto-pair** — opener (`(` `[` `{` quote) inserts its closer
    ///    right after, leaving the cursor between. Suppressed when
    ///    grabbing the closer would capture an existing identifier
    ///    (next char is alphanumeric / `_`), and additionally for
    ///    quotes when the previous char looks like word context (an
    ///    apostrophe in `it's`) or is the same quote (cursor inside an
    ///    empty `""`).
    ///
    /// Single-cursor only: the multi-cursor fan-out path goes through
    /// raw [`insert_char`] to keep cursor-shift bookkeeping simple.
    pub fn insert_char_smart(&mut self, c: char, indent: IndentSettings) {
        let next = self.char_at_cursor();
        let prev = self.char_before_cursor();

        if is_auto_pair_closer(c) && next == Some(c) {
            self.cursor.col += 1;
            return;
        }

        if matches!(c, '}' | ')' | ']') && self.line_is_blank_before_cursor() {
            self.dedent_current_line(indent);
        }

        self.insert_char(c);

        if let Some(closer) = auto_pair_closer(c)
            && should_auto_pair(c, prev, next)
        {
            self.insert_char(closer);
            self.cursor.col -= 1;
        }
    }

    /// Char at the cursor's logical position, or `None` past end-of-line.
    pub fn char_at_cursor(&self) -> Option<char> {
        self.lines
            .get(self.cursor.row)
            .and_then(|line| line.chars().nth(self.cursor.col))
    }

    /// Char immediately before the cursor on the current row, or `None`
    /// at column 0.
    pub fn char_before_cursor(&self) -> Option<char> {
        if self.cursor.col == 0 {
            return None;
        }
        self.lines
            .get(self.cursor.row)
            .and_then(|line| line.chars().nth(self.cursor.col - 1))
    }

    /// True when every character on the cursor row strictly *before*
    /// the cursor column is whitespace. An empty line (cursor at
    /// col 0) qualifies too, vacuously.
    pub fn line_is_blank_before_cursor(&self) -> bool {
        let line = &self.lines[self.cursor.row];
        line.chars().take(self.cursor.col).all(|c| c.is_whitespace())
    }

    /// Add one indent level at the start of `row`. Picks tabs vs
    /// spaces by looking at the row's existing leading whitespace:
    /// any `\t` in the leading run means tab, otherwise spaces; an
    /// empty leading run falls back to `indent.use_tabs`. Cursor
    /// follows the shift when it's on this row.
    pub fn indent_line(&mut self, row: usize, indent: IndentSettings) {
        if row >= self.lines.len() {
            return;
        }
        let line = &self.lines[row];
        let leading: String = line.chars().take_while(|c| c.is_whitespace()).collect();
        let use_tabs = if leading.is_empty() {
            indent.use_tabs
        } else {
            leading.contains('\t')
        };
        let prefix: String = if use_tabs {
            "\t".to_string()
        } else {
            " ".repeat(indent.width.max(1))
        };
        let added_chars = prefix.chars().count();
        self.lines[row].insert_str(0, &prefix);
        if self.cursor.row == row {
            self.cursor.col += added_chars;
        }
        self.touch();
    }

    /// Strip one indent level from the start of `row`. Same rounding
    /// rules as [`dedent_current_line`] — tab-terminated leading
    /// whitespace drops one trailing `\t`; space-terminated rounds
    /// down to the nearest multiple of `indent.width` strictly below
    /// the current count. Cursor follows on the affected row.
    pub fn dedent_line(&mut self, row: usize, indent: IndentSettings) {
        if row >= self.lines.len() {
            return;
        }
        let line = self.lines[row].clone();
        let leading: String = line.chars().take_while(|c| c.is_whitespace()).collect();
        if leading.is_empty() {
            return;
        }
        let remove_chars = if leading.ends_with('\t') {
            1
        } else {
            let trailing_spaces = leading.chars().rev().take_while(|c| *c == ' ').count();
            let w = indent.width.max(1);
            let target = (trailing_spaces.saturating_sub(1) / w) * w;
            trailing_spaces - target
        };
        if remove_chars == 0 {
            return;
        }
        let leading_char_count = leading.chars().count();
        let delete_start_char = leading_char_count - remove_chars;
        let delete_start_byte = char_to_byte(&line, delete_start_char);
        let delete_end_byte = char_to_byte(&line, delete_start_char + remove_chars);
        self.lines[row].replace_range(delete_start_byte..delete_end_byte, "");
        if self.cursor.row == row {
            self.cursor.col = self.cursor.col.saturating_sub(remove_chars);
        }
        self.touch();
    }

    /// Strip one indent level from the start of the cursor row,
    /// adjusting `cursor.col` to follow. Tab-terminated leading
    /// whitespace drops one trailing `\t`; space-terminated leading
    /// whitespace rounds *down* to the nearest multiple of
    /// `indent.width` strictly below the current column count
    /// (so 8 → 4, 7 → 4, 4 → 0 with width 4).
    pub fn dedent_current_line(&mut self, indent: IndentSettings) {
        let line = self.lines[self.cursor.row].clone();
        let leading: String = line.chars().take_while(|c| c.is_whitespace()).collect();
        if leading.is_empty() {
            return;
        }
        let remove_chars = if leading.ends_with('\t') {
            1
        } else {
            let trailing_spaces = leading.chars().rev().take_while(|c| *c == ' ').count();
            let w = indent.width.max(1);
            let target = (trailing_spaces.saturating_sub(1) / w) * w;
            trailing_spaces - target
        };
        let leading_char_count = leading.chars().count();
        let delete_start_char = leading_char_count - remove_chars;
        let delete_start_byte = char_to_byte(&line, delete_start_char);
        let delete_end_byte = char_to_byte(&line, delete_start_char + remove_chars);
        self.lines[self.cursor.row].replace_range(delete_start_byte..delete_end_byte, "");
        self.cursor.col = self.cursor.col.saturating_sub(remove_chars);
        self.touch();
    }

    pub fn insert_newline(&mut self, indent: IndentSettings) {
        // Splitting at column 0 just inserts a blank line *above* the
        // current content. The right half is the original line verbatim
        // — running auto-indent on it would re-indent text that the
        // user already placed at column 0 (e.g. tree-sitter's
        // `@indent.begin` fires on `func main() {` and would otherwise
        // push it one level deeper).
        if self.cursor.col == 0 {
            self.lines.insert(self.cursor.row, String::new());
            self.cursor.row += 1;
            self.touch();
            return;
        }
        let line = self.lines[self.cursor.row].clone();
        let byte_idx = char_to_byte(&line, self.cursor.col);
        let (left, right) = line.split_at(byte_idx);
        let left_owned = left.to_string();
        let right_owned = right.to_string();
        // Newline-specific indent rule (narrower than `o`/`O`): copy
        // the left half's leading whitespace, then add one level only
        // when tree-sitter's @indent.begin fires *and* the new line
        // isn't itself starting with an opener. We deliberately skip
        // the trailing-`{`/`(`/`[` heuristic — pressing Enter at the
        // end of `func main() {` shouldn't push the cursor into the
        // body, and splitting at `func main |{` shouldn't push the
        // brace deeper than the header.
        let prev = left_owned.chars().last();
        let next_ch = right_owned.chars().next();
        let base = copy_leading_indent(&left_owned, indent);
        let ts_begin = self
            .highlighter
            .as_ref()
            .is_some_and(|h| h.indent_begins_at(self.cursor.row));
        let next_is_opener = matches!(next_ch, Some('{' | '(' | '['));
        let mut new_indent = if ts_begin && !next_is_opener {
            add_one_indent_level(&base, indent)
        } else {
            base
        };

        // Empty-pair split: pressing Enter between an opener and its
        // matching closer (auto-paired or hand-typed) drops the closer
        // onto its own row at the original line's *base* indent, with
        // a blank +1-indented row between for the cursor. Without this
        // the closer would ride the inner indent and look like
        // `    }` inside `fn foo() {`, which the user expects to snap
        // back to column 0.
        let is_empty_pair = match (prev, next_ch) {
            (Some(p), Some(n)) => auto_pair_closer(p) == Some(n),
            _ => false,
        };
        if is_empty_pair {
            let base_indent = copy_leading_indent(&left_owned, indent);
            let mut closer_line = base_indent.clone();
            closer_line.push_str(&right_owned);
            let middle = add_one_indent_level(&base_indent, indent);
            self.cursor.col = middle.chars().count();
            self.lines[self.cursor.row] = left_owned;
            self.lines.insert(self.cursor.row + 1, middle);
            self.lines.insert(self.cursor.row + 2, closer_line);
            self.cursor.row += 1;
            self.touch();
            return;
        }

        // Closer at the start of the right half: the new line carries
        // the closer, so strip one indent level from the body indent —
        // without this, splitting before a `}` keeps the body's indent
        // and the closer sits one level too deep.
        if matches!(next_ch, Some('}' | ')' | ']')) {
            new_indent = strip_one_indent_level(&new_indent, indent);
        }

        self.lines[self.cursor.row] = left_owned;
        let mut next = new_indent.clone();
        next.push_str(&right_owned);
        self.lines.insert(self.cursor.row + 1, next);
        self.cursor.row += 1;
        self.cursor.col = new_indent.chars().count();
        self.touch();
    }

    pub fn insert_line_below(&mut self, indent: IndentSettings) {
        let reference = self.lines[self.cursor.row].clone();
        let new_indent =
            compute_new_line_indent(&reference, self.cursor.row, &self.highlighter, indent);
        let col = new_indent.chars().count();
        self.lines.insert(self.cursor.row + 1, new_indent);
        self.cursor.row += 1;
        self.cursor.col = col;
        self.touch();
    }

    pub fn insert_line_above(&mut self, indent: IndentSettings) {
        // For `O`, match the indent of the line being pushed down —
        // the tree-sitter `@indent.begin` opening (if any) belongs to
        // that line, so we copy its leading whitespace verbatim
        // without adding an extra level.
        let new_indent = copy_leading_indent(&self.lines[self.cursor.row], indent);
        let col = new_indent.chars().count();
        self.lines.insert(self.cursor.row, new_indent);
        self.cursor.col = col;
        self.touch();
    }

    /// Delete the character under the cursor (vim's `x`). No-op past
    /// end of line. Cursor follows via `clamp_col` so it doesn't end up
    /// past-the-end after deleting the last char.
    pub fn delete_char_under_cursor(&mut self) {
        let line = &mut self.lines[self.cursor.row];
        if self.cursor.col < line.chars().count() {
            let byte_idx = char_to_byte(line, self.cursor.col);
            let ch = line[byte_idx..].chars().next().unwrap();
            line.replace_range(byte_idx..byte_idx + ch.len_utf8(), "");
            self.touch();
            self.clamp_col(false);
        }
    }

    /// Backspace primitive: delete the char before the cursor, or join
    /// with the previous line at column 0. The auto-pair / smart-indent
    /// behaviour wraps this in [`delete_char_before_smart`].
    pub fn delete_char_before(&mut self) {
        if self.cursor.col > 0 {
            let line = &mut self.lines[self.cursor.row];
            let byte_idx = char_to_byte(line, self.cursor.col - 1);
            let ch = line[byte_idx..].chars().next().unwrap();
            line.replace_range(byte_idx..byte_idx + ch.len_utf8(), "");
            self.cursor.col -= 1;
            self.touch();
        } else if self.cursor.row > 0 {
            // Join with the previous line.
            let line = self.lines.remove(self.cursor.row);
            self.cursor.row -= 1;
            self.cursor.col = self.lines[self.cursor.row].chars().count();
            self.lines[self.cursor.row].push_str(&line);
            self.touch();
        }
    }

    /// Replace the character under the cursor with `ch`. No-op on an
    /// empty line — vim's `r` errors there; we silently skip.
    pub fn replace_char(&mut self, ch: char) {
        let line = &mut self.lines[self.cursor.row];
        if self.cursor.col >= line.chars().count() {
            return;
        }
        let byte_idx = char_to_byte(line, self.cursor.col);
        let old_ch = line[byte_idx..].chars().next().unwrap();
        line.replace_range(byte_idx..byte_idx + old_ch.len_utf8(), &ch.to_string());
        self.touch();
    }

    /// Backspace with auto-pair awareness and smart-indent dedent:
    /// - When the char being deleted is an opener and the next char is
    ///   its matching closer, both go.
    /// - When the cursor sits in pure leading whitespace (every char on
    ///   the row before the cursor is whitespace, and `col > 0`), one
    ///   full indent level is removed instead of a single space —
    ///   standard "smart backspace" / "tab stops" behaviour. Closer-led
    ///   lines (`}` / `)` / `]`) collapse the same way as a side
    ///   effect, mirroring the dedent-on-type rule for closers.
    /// - At `col == 0` when the row above is blank (whitespace only) and
    ///   the current row's first non-whitespace char is a closer, do
    ///   the join *and* dedent the joined row by one level. The blank
    ///   row above carries no contextual indent, so an orphaned closer
    ///   left at a deeper level should collapse instead of just sliding
    ///   up at the same depth.
    /// - Otherwise falls through to [`Buffer::delete_char_before`].
    ///
    /// Single-cursor only — the multi-cursor fan-out keeps using the
    /// dumb version so the per-cursor `col -= 1` shift stays valid.
    pub fn delete_char_before_smart(&mut self, indent: IndentSettings) {
        let prev = self.char_before_cursor();
        let next = self.char_at_cursor();
        if let (Some(p), Some(n)) = (prev, next)
            && auto_pair_closer(p) == Some(n)
        {
            let line = &mut self.lines[self.cursor.row];
            let start_byte = char_to_byte(line, self.cursor.col - 1);
            let end_byte = char_to_byte(line, self.cursor.col + 1);
            line.replace_range(start_byte..end_byte, "");
            self.cursor.col -= 1;
            self.touch();
            return;
        }
        if self.cursor.col > 0 && self.line_is_blank_before_cursor() {
            self.dedent_current_line(indent);
            return;
        }
        if self.cursor.col == 0 && self.cursor.row > 0 {
            let prev_blank = self.lines[self.cursor.row - 1]
                .chars()
                .all(|c| c.is_whitespace());
            let curr_starts_with_closer = matches!(
                self.lines[self.cursor.row]
                    .chars()
                    .find(|c| !c.is_whitespace()),
                Some('}' | ')' | ']')
            );
            if prev_blank && curr_starts_with_closer {
                self.delete_char_before();
                self.dedent_current_line(indent);
                return;
            }
        }
        self.delete_char_before();
    }
}

/// Maps an auto-pair opener to its closer. Quotes are self-paired
/// (closer == opener). Returns `None` for any non-opener.
fn auto_pair_closer(c: char) -> Option<char> {
    match c {
        '(' => Some(')'),
        '[' => Some(']'),
        '{' => Some('}'),
        '"' => Some('"'),
        '\'' => Some('\''),
        '`' => Some('`'),
        _ => None,
    }
}

/// True when `c` is a closer that participates in skip-over (typing it
/// where the same char already sits just advances the cursor).
fn is_auto_pair_closer(c: char) -> bool {
    matches!(c, ')' | ']' | '}' | '"' | '\'' | '`')
}

/// Decide whether typing `opener` should also insert its closer, given
/// the chars to either side of the cursor. Brackets only check the
/// right side (don't capture an existing identifier); quotes also gate
/// on the left side to dodge apostrophes inside words and the inner
/// edge of an existing quoted region.
fn should_auto_pair(opener: char, prev: Option<char>, next: Option<char>) -> bool {
    if let Some(n) = next
        && (n.is_alphanumeric() || n == '_')
    {
        return false;
    }
    if matches!(opener, '"' | '\'' | '`')
        && let Some(p) = prev
        && (p.is_alphanumeric() || p == '_' || p == opener)
    {
        return false;
    }
    true
}

/// Remove one indent level from the end of `indent` (which must be
/// pure leading whitespace). Tab-terminated runs drop one `\t`;
/// space-terminated runs round *down* to the nearest multiple of
/// `settings.width` strictly below the current count — same rules
/// `dedent_current_line` applies to a buffer row.
fn strip_one_indent_level(indent: &str, settings: IndentSettings) -> String {
    if indent.is_empty() {
        return String::new();
    }
    if indent.ends_with('\t') {
        let mut out = indent.to_string();
        out.pop();
        return out;
    }
    let trailing_spaces = indent.chars().rev().take_while(|c| *c == ' ').count();
    if trailing_spaces == 0 {
        return indent.to_string();
    }
    let w = settings.width.max(1);
    let target = (trailing_spaces.saturating_sub(1) / w) * w;
    let remove = trailing_spaces - target;
    indent[..indent.len() - remove].to_string()
}

/// Leading-whitespace prefix of `line`, copied verbatim so the new
/// line preserves whatever tabs-vs-spaces mix the reference uses.
fn copy_leading_indent(line: &str, _settings: IndentSettings) -> String {
    line.chars()
        .take_while(|c| c.is_whitespace() && *c != '\n')
        .collect()
}

/// Build the indent string for a brand-new line that sits *after*
/// `ref_row` in the buffer (vim's `o` / `O`). Strategy:
///
/// 1. Copy `reference_line`'s existing leading whitespace — the basic
///    vim `autoindent` behaviour, used when nothing else fires.
/// 2. Add one extra indent level when either signal fires:
///    - tree-sitter `indents.scm` reports an `@indent.begin` node
///      opening on `ref_row` (and spanning past it), or
///    - the reference line's last non-whitespace char is `{` / `(`
///      / `[`. Universal fallback for languages without indents.scm.
///
/// `insert_newline` deliberately uses a narrower rule (see inline)
/// — pressing Enter on `func main() {` shouldn't auto-indent, but
/// `o` on the same line should land in the body.
fn compute_new_line_indent(
    reference_line: &str,
    ref_row: usize,
    highlighter: &Option<crate::syntax::Highlighter>,
    settings: IndentSettings,
) -> String {
    let base = copy_leading_indent(reference_line, settings);
    let ts_begin = highlighter
        .as_ref()
        .is_some_and(|h| h.indent_begins_at(ref_row));
    let trailing_opener = reference_line
        .trim_end()
        .chars()
        .last()
        .is_some_and(|c| matches!(c, '{' | '(' | '['));
    if ts_begin || trailing_opener {
        add_one_indent_level(&base, settings)
    } else {
        base
    }
}

/// Append one indent level to `base`. Tab-indented bases get an extra
/// `\t`; space-indented (or empty) bases get `settings.width` spaces,
/// honoring `settings.use_tabs` only when there's nothing to mimic.
fn add_one_indent_level(base: &str, settings: IndentSettings) -> String {
    let use_tabs = if base.is_empty() {
        settings.use_tabs
    } else {
        base.contains('\t')
    };
    let mut out = base.to_string();
    if use_tabs {
        out.push('\t');
    } else {
        for _ in 0..settings.width.max(1) {
            out.push(' ');
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn settings() -> IndentSettings {
        IndentSettings {
            width: 4,
            use_tabs: false,
        }
    }

    #[test]
    fn indent_line_adds_spaces_for_empty_leading() {
        let mut b = Buffer::new();
        b.lines = vec!["let x = 1;".into()];
        b.cursor.row = 0;
        b.cursor.col = 4;
        b.indent_line(0, settings());
        assert_eq!(b.lines[0], "    let x = 1;");
        assert_eq!(b.cursor.col, 8);
    }

    #[test]
    fn indent_line_uses_tab_when_leading_has_tab() {
        let mut b = Buffer::new();
        b.lines = vec!["\tx".into()];
        b.cursor.row = 0;
        b.indent_line(0, settings());
        assert_eq!(b.lines[0], "\t\tx");
    }

    #[test]
    fn indent_line_falls_back_to_use_tabs_on_blank_leading() {
        let mut b = Buffer::new();
        b.lines = vec!["x".into()];
        let s = IndentSettings { width: 4, use_tabs: true };
        b.indent_line(0, s);
        assert_eq!(b.lines[0], "\tx");
    }

    #[test]
    fn dedent_line_removes_one_level_of_spaces() {
        let mut b = Buffer::new();
        b.lines = vec!["        x".into()];
        b.cursor.row = 0;
        b.cursor.col = 8;
        b.dedent_line(0, settings());
        assert_eq!(b.lines[0], "    x");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn dedent_line_rounds_partial_indent_down() {
        let mut b = Buffer::new();
        b.lines = vec!["       x".into()]; // 7 spaces
        b.dedent_line(0, settings());
        assert_eq!(b.lines[0], "    x");
    }

    #[test]
    fn dedent_line_strips_trailing_tab() {
        let mut b = Buffer::new();
        b.lines = vec!["\t\tx".into()];
        b.dedent_line(0, settings());
        assert_eq!(b.lines[0], "\tx");
    }

    #[test]
    fn dedent_line_noop_on_no_leading_whitespace() {
        let mut b = Buffer::new();
        b.lines = vec!["x".into()];
        b.cursor.col = 0;
        b.dedent_line(0, settings());
        assert_eq!(b.lines[0], "x");
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn open_below_copies_leading_whitespace() {
        let mut b = Buffer::new();
        b.lines = vec!["    let x = 1;".into(), "    let y = 2;".into()];
        b.cursor.row = 0;
        b.insert_line_below(settings());
        assert_eq!(b.lines[1], "    ");
        assert_eq!(b.cursor.row, 1);
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn open_below_adds_level_after_opening_brace() {
        let mut b = Buffer::new();
        b.lines = vec!["fn foo() {".into(), "}".into()];
        b.cursor.row = 0;
        b.insert_line_below(settings());
        assert_eq!(b.lines[1], "    ");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn open_below_uses_tabs_when_reference_does() {
        let mut b = Buffer::new();
        b.lines = vec!["\tfn foo() {".into(), "}".into()];
        b.cursor.row = 0;
        b.insert_line_below(settings());
        assert_eq!(b.lines[1], "\t\t");
    }

    #[test]
    fn open_above_copies_indent_without_adding_level() {
        let mut b = Buffer::new();
        b.lines = vec!["    let x = 1;".into()];
        b.cursor.row = 0;
        b.insert_line_above(settings());
        assert_eq!(b.lines[0], "    ");
        assert_eq!(b.cursor.row, 0);
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn newline_at_col_zero_leaves_original_line_unindented() {
        // Splitting at the very start of a line should drop a blank
        // line above and leave the original content where it sat —
        // even when the line opens a block (e.g. `func main() {`),
        // which would otherwise trip the trailing-opener / tree-sitter
        // `@indent.begin` rule and prepend an indent.
        let mut b = Buffer::new();
        b.lines = vec!["func main() {".into()];
        b.cursor.row = 0;
        b.cursor.col = 0;
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "");
        assert_eq!(b.lines[1], "func main() {");
        assert_eq!(b.cursor.row, 1);
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn newline_at_col_zero_preserves_existing_indent() {
        // Same shortcut, but the original line already has indent —
        // the right half keeps it verbatim, no extra level added.
        let mut b = Buffer::new();
        b.lines = vec!["    let x = 1;".into()];
        b.cursor.row = 0;
        b.cursor.col = 0;
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "");
        assert_eq!(b.lines[1], "    let x = 1;");
        assert_eq!(b.cursor.row, 1);
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn newline_after_trailing_opener_does_not_auto_indent() {
        // Pressing Enter at end of `func main() {` no longer adds an
        // indent level on its own — the trailing `{`/`(`/`[` heuristic
        // was too eager. Tree-sitter's @indent.begin handles real
        // cases; here there's no highlighter, so the new line stays
        // at base indent.
        let mut b = Buffer::new();
        b.lines = vec!["func main() {".into()];
        b.cursor.row = 0;
        b.cursor.col = 13; // end of line
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "func main() {");
        assert_eq!(b.lines[1], "");
        assert_eq!(b.cursor.row, 1);
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn newline_before_opener_keeps_base_indent() {
        // `func main |{` — splitting before `{` should leave the new
        // line (which starts with `{`) at the function header's base
        // indent, not one level deeper.
        let mut b = Buffer::new();
        b.lines = vec!["func main {".into()];
        b.cursor.row = 0;
        b.cursor.col = 10; // before '{'
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "func main ");
        assert_eq!(b.lines[1], "{");
        assert_eq!(b.cursor.row, 1);
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn newline_before_opener_preserves_outer_indent() {
        let mut b = Buffer::new();
        b.lines = vec!["    if cond ".into(), "(x) {}".into()];
        // Place cursor before `(` on line 1 to exercise the
        // opener-at-start rule with a non-empty base indent.
        b.lines = vec!["    if cond (x".into()];
        b.cursor.row = 0;
        b.cursor.col = 12; // before '('
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "    if cond ");
        assert_eq!(b.lines[1], "    (x");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn newline_splits_and_carries_indent() {
        let mut b = Buffer::new();
        b.lines = vec!["    let x = foo + bar;".into()];
        b.cursor.row = 0;
        b.cursor.col = 16; // between '+' and ' bar'
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "    let x = foo ");
        assert_eq!(b.lines[1], "    + bar;");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn close_bracket_dedents_when_line_is_blank() {
        // Typed `}` on a line that's all whitespace: dedent one
        // level, then insert.
        let mut b = Buffer::new();
        b.lines = vec!["fn foo() {".into(), "        ".into()];
        b.cursor.row = 1;
        b.cursor.col = 8;
        b.insert_char_smart('}', settings());
        assert_eq!(b.lines[1], "    }");
        assert_eq!(b.cursor.col, 5);
    }

    #[test]
    fn close_bracket_no_dedent_when_text_precedes() {
        // `}` after real code stays where the user typed it.
        let mut b = Buffer::new();
        b.lines = vec!["    let x = HashMap::new(".into()];
        b.cursor.row = 0;
        b.cursor.col = 25;
        b.insert_char_smart(')', settings());
        assert_eq!(b.lines[0], "    let x = HashMap::new()");
        assert_eq!(b.cursor.col, 26);
    }

    #[test]
    fn close_bracket_dedents_partial_indent() {
        // 7 spaces with width 4 → drop 3 to land on 4.
        let mut b = Buffer::new();
        b.lines = vec!["       ".into()];
        b.cursor.row = 0;
        b.cursor.col = 7;
        b.insert_char_smart(']', settings());
        assert_eq!(b.lines[0], "    ]");
        assert_eq!(b.cursor.col, 5);
    }

    #[test]
    fn close_bracket_dedents_tab_indent() {
        let mut b = Buffer::new();
        b.lines = vec!["\t\t".into()];
        b.cursor.row = 0;
        b.cursor.col = 2;
        b.insert_char_smart('}', settings());
        assert_eq!(b.lines[0], "\t}");
        assert_eq!(b.cursor.col, 2);
    }

    #[test]
    fn close_bracket_clears_indent_when_already_at_one_level() {
        let mut b = Buffer::new();
        b.lines = vec!["    ".into()];
        b.cursor.row = 0;
        b.cursor.col = 4;
        b.insert_char_smart('}', settings());
        assert_eq!(b.lines[0], "}");
        assert_eq!(b.cursor.col, 1);
    }

    #[test]
    fn auto_pair_inserts_matching_closer_and_keeps_cursor_between() {
        let mut b = Buffer::new();
        b.lines = vec!["foo".into()];
        b.cursor.row = 0;
        b.cursor.col = 3;
        b.insert_char_smart('(', settings());
        assert_eq!(b.lines[0], "foo()");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn auto_pair_skip_over_closer_when_next_char_matches() {
        let mut b = Buffer::new();
        b.lines = vec!["()".into()];
        b.cursor.row = 0;
        b.cursor.col = 1; // between '(' and ')'
        b.insert_char_smart(')', settings());
        assert_eq!(b.lines[0], "()");
        assert_eq!(b.cursor.col, 2);
    }

    #[test]
    fn auto_pair_suppressed_when_next_char_is_word() {
        let mut b = Buffer::new();
        b.lines = vec!["foo".into()];
        b.cursor.row = 0;
        b.cursor.col = 0; // about to type `(` before the `f`
        b.insert_char_smart('(', settings());
        assert_eq!(b.lines[0], "(foo");
        assert_eq!(b.cursor.col, 1);
    }

    #[test]
    fn auto_pair_quote_suppressed_after_word_char() {
        // Apostrophe in `it's` shouldn't grow into `it''`.
        let mut b = Buffer::new();
        b.lines = vec!["it".into()];
        b.cursor.row = 0;
        b.cursor.col = 2;
        b.insert_char_smart('\'', settings());
        assert_eq!(b.lines[0], "it'");
        assert_eq!(b.cursor.col, 3);
    }

    #[test]
    fn auto_pair_quote_pairs_after_punctuation() {
        let mut b = Buffer::new();
        b.lines = vec!["print(".into()];
        b.cursor.row = 0;
        b.cursor.col = 6;
        b.insert_char_smart('"', settings());
        assert_eq!(b.lines[0], "print(\"\"");
        assert_eq!(b.cursor.col, 7);
    }

    #[test]
    fn delete_char_before_smart_removes_empty_pair() {
        let mut b = Buffer::new();
        b.lines = vec!["foo()".into()];
        b.cursor.row = 0;
        b.cursor.col = 4; // between '(' and ')'
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "foo");
        assert_eq!(b.cursor.col, 3);
    }

    #[test]
    fn delete_char_before_smart_falls_through_when_not_empty_pair() {
        // Backspace inside `(x)` between `(` and `x` only removes `(`.
        let mut b = Buffer::new();
        b.lines = vec!["(x)".into()];
        b.cursor.row = 0;
        b.cursor.col = 1;
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "x)");
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn newline_inside_empty_braces_spreads_three_lines() {
        // Mid-line Enter between `{` and `}` (auto-paired or hand-typed)
        // drops the closer onto its own row at the base indent, with a
        // blank +1-indented row between for the cursor. Without the
        // 3-line spread the closer rides the inner indent.
        let mut b = Buffer::new();
        b.lines = vec!["fn foo() {}".into()];
        b.cursor.row = 0;
        b.cursor.col = 10; // between '{' and '}'
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "fn foo() {");
        assert_eq!(b.lines[1], "    ");
        assert_eq!(b.lines[2], "}");
        assert_eq!(b.cursor.row, 1);
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn newline_inside_empty_braces_preserves_outer_indent() {
        let mut b = Buffer::new();
        b.lines = vec!["    if cond {}".into()];
        b.cursor.row = 0;
        b.cursor.col = 13; // between '{' and '}'
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "    if cond {");
        assert_eq!(b.lines[1], "        ");
        assert_eq!(b.lines[2], "    }");
        assert_eq!(b.cursor.row, 1);
        assert_eq!(b.cursor.col, 8);
    }

    #[test]
    fn newline_inside_empty_parens_also_spreads() {
        let mut b = Buffer::new();
        b.lines = vec!["foo()".into()];
        b.cursor.row = 0;
        b.cursor.col = 4; // between '(' and ')'
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "foo(");
        assert_eq!(b.lines[1], "    ");
        assert_eq!(b.lines[2], ")");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn newline_before_closer_strips_one_indent_level() {
        // Cursor sits before the `}` after a real statement: the new
        // line carries the closer, so it should land one indent level
        // out from the body — `}` aligned to the block's opener, not
        // riding the body indent.
        let mut b = Buffer::new();
        b.lines = vec!["        bar();}".into()];
        b.cursor.row = 0;
        b.cursor.col = 14; // before '}'
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "        bar();");
        assert_eq!(b.lines[1], "    }");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn newline_before_closer_clears_indent_at_one_level() {
        let mut b = Buffer::new();
        b.lines = vec!["    bar();]".into()];
        b.cursor.row = 0;
        b.cursor.col = 10; // before ']'
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "    bar();");
        assert_eq!(b.lines[1], "]");
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn newline_before_closer_strips_one_tab() {
        let mut b = Buffer::new();
        b.lines = vec!["\t\tbar();)".into()];
        b.cursor.row = 0;
        b.cursor.col = 8; // before ')'
        b.insert_newline(settings());
        assert_eq!(b.lines[0], "\t\tbar();");
        assert_eq!(b.lines[1], "\t)");
    }

    #[test]
    fn backspace_before_closer_collapses_one_indent_level() {
        // Cursor on a blank-before-closer line: backspace pulls the
        // closer back one full indent level instead of nibbling a
        // single space at a time.
        let mut b = Buffer::new();
        b.lines = vec!["        }".into()];
        b.cursor.row = 0;
        b.cursor.col = 8; // before '}'
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "    }");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn backspace_before_closer_clears_indent_at_one_level() {
        let mut b = Buffer::new();
        b.lines = vec!["    }".into()];
        b.cursor.row = 0;
        b.cursor.col = 4;
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "}");
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn backspace_before_closer_strips_tab() {
        let mut b = Buffer::new();
        b.lines = vec!["\t\t]".into()];
        b.cursor.row = 0;
        b.cursor.col = 2;
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "\t]");
        assert_eq!(b.cursor.col, 1);
    }

    #[test]
    fn backspace_does_not_dedent_when_text_precedes_closer() {
        // Real content before the closer — normal one-char backspace.
        let mut b = Buffer::new();
        b.lines = vec!["    x)".into()];
        b.cursor.row = 0;
        b.cursor.col = 5; // between 'x' and ')'
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "    )");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn backspace_inside_closer_line_indent_dedents() {
        // Cursor anywhere inside the leading-whitespace run of a line
        // that's "indent + closer" — backspace dedents the whole line
        // by one level, not just one space.
        let mut b = Buffer::new();
        b.lines = vec!["        }".into()];
        b.cursor.row = 0;
        b.cursor.col = 4; // mid-indent, not at the closer
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "    }");
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn backspace_on_closer_line_with_trailing_content_dedents() {
        let mut b = Buffer::new();
        b.lines = vec!["        });".into()];
        b.cursor.row = 0;
        b.cursor.col = 8; // before ')'
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "    });");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn backspace_inside_pure_whitespace_line_dedents() {
        // Empty-but-indented line (e.g., the middle row of the 3-line
        // spread after Enter inside `{}`). Backspace should collapse
        // one indent level, not nibble a single space.
        let mut b = Buffer::new();
        b.lines = vec!["    ".into()];
        b.cursor.row = 0;
        b.cursor.col = 4;
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "");
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn backspace_in_indent_before_content_dedents() {
        // Cursor in leading whitespace before regular content — also
        // dedents (standard smart-backspace behaviour).
        let mut b = Buffer::new();
        b.lines = vec!["        let x = 1;".into()];
        b.cursor.row = 0;
        b.cursor.col = 8; // right before 'let'
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "    let x = 1;");
        assert_eq!(b.cursor.col, 4);
    }

    #[test]
    fn backspace_past_first_non_blank_is_normal_one_char() {
        // Once we're into content, backspace is one char as usual.
        let mut b = Buffer::new();
        b.lines = vec!["    let x = 1;".into()];
        b.cursor.row = 0;
        b.cursor.col = 7; // between 't' of 'let' and ' '
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines[0], "    le x = 1;");
        assert_eq!(b.cursor.col, 6);
    }

    #[test]
    fn backspace_at_col0_of_closer_line_above_empty_joins_and_dedents() {
        // Closer line orphaned over an empty row: Backspace at col 0
        // should both eat the empty row above and dedent the closer.
        let mut b = Buffer::new();
        b.lines = vec!["".into(), "    }".into()];
        b.cursor.row = 1;
        b.cursor.col = 0;
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines, vec!["}".to_string()]);
        assert_eq!(b.cursor.row, 0);
        assert_eq!(b.cursor.col, 0);
    }

    #[test]
    fn backspace_at_col0_of_closer_line_above_blank_joins_and_dedents() {
        // Whitespace-only row above counts as blank too.
        let mut b = Buffer::new();
        b.lines = vec!["    ".into(), "        }".into()];
        b.cursor.row = 1;
        b.cursor.col = 0;
        b.delete_char_before_smart(settings());
        // Join concatenates leading whitespace, then one level dedent.
        assert_eq!(b.lines, vec!["        }".to_string()]);
        assert_eq!(b.cursor.row, 0);
    }

    #[test]
    fn backspace_at_col0_above_content_does_not_dedent() {
        // Row above has real content — vanilla join, no dedent.
        let mut b = Buffer::new();
        b.lines = vec!["foo".into(), "    }".into()];
        b.cursor.row = 1;
        b.cursor.col = 0;
        b.delete_char_before_smart(settings());
        assert_eq!(b.lines, vec!["foo    }".to_string()]);
        assert_eq!(b.cursor.row, 0);
        assert_eq!(b.cursor.col, 3);
    }
}