Skip to main content

gpui_m3/components/
code_buffer.rs

1//! Text model of [`super::CodeEditor`]: lines, one selection, editing commands and undo history.
2//!
3//! It knows nothing about GPUI, so the editing rules (indentation, bracket pairs, undo grouping)
4//! are tested on their own. Positions are `(line, byte column)`; lines never contain `'\n'`.
5
6use std::ops::Range;
7
8use unicode_segmentation::UnicodeSegmentation;
9
10/// A position in a [`CodeBuffer`]: zero-based line and byte column within that line.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct BufferPos {
13    pub line: usize,
14    pub col: usize,
15}
16
17impl BufferPos {
18    pub const fn new(line: usize, col: usize) -> Self {
19        Self { line, col }
20    }
21}
22
23/// The selection: `anchor` stays put while `head` (the caret) moves.
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
25pub struct BufferSelection {
26    pub anchor: BufferPos,
27    pub head: BufferPos,
28}
29
30impl BufferSelection {
31    pub fn caret(pos: BufferPos) -> Self {
32        Self {
33            anchor: pos,
34            head: pos,
35        }
36    }
37
38    pub fn is_empty(&self) -> bool {
39        self.anchor == self.head
40    }
41
42    /// The selected range, start before end.
43    pub fn range(&self) -> Range<BufferPos> {
44        if self.anchor <= self.head {
45            self.anchor..self.head
46        } else {
47            self.head..self.anchor
48        }
49    }
50
51    /// The caret sits at the start of the selection.
52    pub fn reversed(&self) -> bool {
53        self.head < self.anchor
54    }
55
56    /// Lines the selection touches. A selection that ends at column 0 of a later line does not
57    /// count that line (selecting whole lines with Shift+Down).
58    pub fn lines(&self) -> Range<usize> {
59        let r = self.range();
60        let last = if r.end.col == 0 && r.end.line > r.start.line {
61            r.end.line - 1
62        } else {
63            r.end.line
64        };
65        r.start.line..last + 1
66    }
67}
68
69/// Kind of edit, used to group consecutive typing into one undo step.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71enum EditKind {
72    Insert,
73    Delete,
74    Other,
75}
76
77#[derive(Clone, Debug)]
78struct Edit {
79    start: BufferPos,
80    old: String,
81    new: String,
82}
83
84#[derive(Clone, Debug)]
85struct Transaction {
86    id: u64,
87    kind: EditKind,
88    edits: Vec<Edit>,
89    before: BufferSelection,
90    after: BufferSelection,
91}
92
93const PAIRS: [(char, char); 6] = [
94    ('(', ')'),
95    ('[', ']'),
96    ('{', '}'),
97    ('"', '"'),
98    ('\'', '\''),
99    ('`', '`'),
100];
101
102fn closer_for(open: char) -> Option<char> {
103    PAIRS.iter().find(|(o, _)| *o == open).map(|(_, c)| *c)
104}
105
106fn is_closer(c: char) -> bool {
107    PAIRS.iter().any(|(_, close)| *close == c)
108}
109
110fn is_quote(c: char) -> bool {
111    matches!(c, '"' | '\'' | '`')
112}
113
114fn is_word(c: char) -> bool {
115    c.is_alphanumeric() || c == '_'
116}
117
118#[derive(PartialEq, Eq, Clone, Copy)]
119enum CharClass {
120    Space,
121    Word,
122    Punct,
123}
124
125fn class(c: char) -> CharClass {
126    if c.is_whitespace() {
127        CharClass::Space
128    } else if is_word(c) {
129        CharClass::Word
130    } else {
131        CharClass::Punct
132    }
133}
134
135/// End position of `text` inserted at `start`.
136fn end_of(start: BufferPos, text: &str) -> BufferPos {
137    match text.rfind('\n') {
138        Some(i) => BufferPos::new(start.line + text.matches('\n').count(), text.len() - i - 1),
139        None => BufferPos::new(start.line, start.col + text.len()),
140    }
141}
142
143/// Lines, one selection and an undo history, with code-editing commands.
144#[derive(Clone, Debug)]
145pub struct CodeBuffer {
146    lines: Vec<String>,
147    selection: BufferSelection,
148    /// Column (in characters) that vertical moves try to keep.
149    goal: Option<usize>,
150    undo: Vec<Transaction>,
151    redo: Vec<Transaction>,
152    next_id: u64,
153    saved: u64,
154    break_group: bool,
155    edited_from: Option<usize>,
156    crlf: bool,
157    /// Spaces per indentation level (4 by default).
158    pub tab_size: usize,
159    /// Indent with `'\t'` instead of spaces.
160    pub hard_tabs: bool,
161    /// Insert and skip over closing brackets and quotes.
162    pub auto_pair: bool,
163}
164
165impl Default for CodeBuffer {
166    fn default() -> Self {
167        Self::new("")
168    }
169}
170
171impl CodeBuffer {
172    pub fn new(text: &str) -> Self {
173        let mut buffer = Self {
174            lines: vec![String::new()],
175            selection: BufferSelection::default(),
176            goal: None,
177            undo: Vec::new(),
178            redo: Vec::new(),
179            next_id: 1,
180            saved: 0,
181            break_group: false,
182            edited_from: None,
183            crlf: false,
184            tab_size: 4,
185            hard_tabs: false,
186            auto_pair: true,
187        };
188        buffer.set_text(text);
189        buffer
190    }
191
192    /// Replaces the whole text, clears the history and marks it saved (loading a file).
193    /// `"\r\n"` line endings are remembered and restored by [`CodeBuffer::text`].
194    pub fn set_text(&mut self, text: &str) {
195        self.crlf = text.contains("\r\n");
196        let normalized = text.replace("\r\n", "\n");
197        self.lines = normalized.split('\n').map(str::to_owned).collect();
198        self.selection = BufferSelection::default();
199        self.goal = None;
200        self.undo.clear();
201        self.redo.clear();
202        self.saved = 0;
203        self.edited_from = Some(0);
204    }
205
206    /// The whole text, with the line endings it was loaded with.
207    pub fn text(&self) -> String {
208        self.lines.join(if self.crlf { "\r\n" } else { "\n" })
209    }
210
211    pub fn line_count(&self) -> usize {
212        self.lines.len()
213    }
214
215    pub fn line(&self, ix: usize) -> &str {
216        self.lines.get(ix).map(String::as_str).unwrap_or("")
217    }
218
219    pub fn lines(&self) -> impl Iterator<Item = &str> {
220        self.lines.iter().map(String::as_str)
221    }
222
223    /// Length in bytes of the longest line.
224    pub fn longest_line_len(&self) -> usize {
225        self.lines.iter().map(String::len).max().unwrap_or(0)
226    }
227
228    pub fn selection(&self) -> BufferSelection {
229        self.selection
230    }
231
232    pub fn cursor(&self) -> BufferPos {
233        self.selection.head
234    }
235
236    /// Text between two positions (joined with `'\n'`).
237    pub fn text_in(&self, range: Range<BufferPos>) -> String {
238        let (start, end) = (self.clip(range.start), self.clip(range.end));
239        if start.line == end.line {
240            return self.lines[start.line][start.col..end.col.max(start.col)].to_owned();
241        }
242        let mut out = self.lines[start.line][start.col..].to_owned();
243        for line in &self.lines[start.line + 1..end.line] {
244            out.push('\n');
245            out.push_str(line);
246        }
247        out.push('\n');
248        out.push_str(&self.lines[end.line][..end.col]);
249        out
250    }
251
252    pub fn selected_text(&self) -> String {
253        self.text_in(self.selection.range())
254    }
255
256    /// Whether the text differs from the last [`CodeBuffer::mark_saved`] (or load).
257    pub fn is_dirty(&self) -> bool {
258        self.version() != self.saved
259    }
260
261    pub fn mark_saved(&mut self) {
262        self.saved = self.version();
263        self.break_group = true;
264    }
265
266    fn version(&self) -> u64 {
267        self.undo.last().map_or(0, |t| t.id)
268    }
269
270    pub fn can_undo(&self) -> bool {
271        !self.undo.is_empty()
272    }
273
274    pub fn can_redo(&self) -> bool {
275        !self.redo.is_empty()
276    }
277
278    /// First line changed since the last call (for highlighter caches), if any.
279    pub fn take_edited_from(&mut self) -> Option<usize> {
280        self.edited_from.take()
281    }
282
283    /// The next edit starts a new undo step even if it continues the current typing.
284    pub fn break_undo_group(&mut self) {
285        self.break_group = true;
286    }
287
288    /// The same position kept inside the text and on a character boundary.
289    pub fn clip(&self, pos: BufferPos) -> BufferPos {
290        let line = pos.line.min(self.lines.len() - 1);
291        let text = &self.lines[line];
292        let mut col = pos.col.min(text.len());
293        while !text.is_char_boundary(col) {
294            col -= 1;
295        }
296        BufferPos::new(line, col)
297    }
298
299    fn end(&self) -> BufferPos {
300        let last = self.lines.len() - 1;
301        BufferPos::new(last, self.lines[last].len())
302    }
303
304    // ---- Offsets (for the platform input handler) ----
305
306    /// Byte offset of a position in the `'\n'`-joined text.
307    pub fn offset_of(&self, pos: BufferPos) -> usize {
308        let pos = self.clip(pos);
309        self.lines[..pos.line]
310            .iter()
311            .map(|l| l.len() + 1)
312            .sum::<usize>()
313            + pos.col
314    }
315
316    /// Position of a byte offset in the `'\n'`-joined text.
317    pub fn pos_of(&self, mut offset: usize) -> BufferPos {
318        for (i, line) in self.lines.iter().enumerate() {
319            if offset <= line.len() {
320                return self.clip(BufferPos::new(i, offset));
321            }
322            offset -= line.len() + 1;
323        }
324        self.end()
325    }
326
327    /// UTF-16 offset of a position in the `'\n'`-joined text.
328    pub fn utf16_of(&self, pos: BufferPos) -> usize {
329        let pos = self.clip(pos);
330        self.lines[..pos.line]
331            .iter()
332            .map(|l| l.encode_utf16().count() + 1)
333            .sum::<usize>()
334            + self.lines[pos.line][..pos.col].encode_utf16().count()
335    }
336
337    /// Position of a UTF-16 offset in the `'\n'`-joined text.
338    pub fn pos_of_utf16(&self, mut offset: usize) -> BufferPos {
339        for (i, line) in self.lines.iter().enumerate() {
340            let len = line.encode_utf16().count();
341            if offset <= len {
342                let mut units = 0;
343                for (col, ch) in line.char_indices() {
344                    if units >= offset {
345                        return BufferPos::new(i, col);
346                    }
347                    units += ch.len_utf16();
348                }
349                return BufferPos::new(i, line.len());
350            }
351            offset -= len + 1;
352        }
353        self.end()
354    }
355
356    // ---- Characters around a position ----
357
358    fn char_before(&self, pos: BufferPos) -> Option<char> {
359        self.lines[pos.line][..pos.col].chars().next_back()
360    }
361
362    fn char_after(&self, pos: BufferPos) -> Option<char> {
363        self.lines[pos.line][pos.col..].chars().next()
364    }
365
366    fn prev_pos(&self, pos: BufferPos) -> BufferPos {
367        if pos.col == 0 {
368            if pos.line == 0 {
369                return pos;
370            }
371            return BufferPos::new(pos.line - 1, self.lines[pos.line - 1].len());
372        }
373        let line = &self.lines[pos.line];
374        let col = line[..pos.col]
375            .grapheme_indices(true)
376            .next_back()
377            .map_or(0, |(i, _)| i);
378        BufferPos::new(pos.line, col)
379    }
380
381    fn next_pos(&self, pos: BufferPos) -> BufferPos {
382        let line = &self.lines[pos.line];
383        if pos.col >= line.len() {
384            if pos.line + 1 >= self.lines.len() {
385                return pos;
386            }
387            return BufferPos::new(pos.line + 1, 0);
388        }
389        let col = line[pos.col..]
390            .graphemes(true)
391            .next()
392            .map_or(line.len(), |g| pos.col + g.len());
393        BufferPos::new(pos.line, col)
394    }
395
396    fn word_start(&self, pos: BufferPos) -> BufferPos {
397        if pos.col == 0 {
398            return self.prev_pos(pos);
399        }
400        let line = &self.lines[pos.line];
401        let mut chars = line[..pos.col].char_indices().rev().peekable();
402        let mut col = pos.col;
403        while let Some(&(i, c)) = chars.peek() {
404            if !c.is_whitespace() {
405                break;
406            }
407            col = i;
408            chars.next();
409        }
410        if let Some(&(_, c)) = chars.peek() {
411            let k = class(c);
412            while let Some(&(i, c)) = chars.peek() {
413                if class(c) != k {
414                    break;
415                }
416                col = i;
417                chars.next();
418            }
419        }
420        BufferPos::new(pos.line, col)
421    }
422
423    fn word_end(&self, pos: BufferPos) -> BufferPos {
424        let line = &self.lines[pos.line];
425        if pos.col >= line.len() {
426            return self.next_pos(pos);
427        }
428        let mut chars = line[pos.col..].char_indices().peekable();
429        let mut col = pos.col;
430        while let Some(&(i, c)) = chars.peek() {
431            if !c.is_whitespace() {
432                break;
433            }
434            col = pos.col + i + c.len_utf8();
435            chars.next();
436        }
437        if let Some(&(_, c)) = chars.peek() {
438            let k = class(c);
439            while let Some(&(i, c)) = chars.peek() {
440                if class(c) != k {
441                    break;
442                }
443                col = pos.col + i + c.len_utf8();
444                chars.next();
445            }
446        }
447        BufferPos::new(pos.line, col)
448    }
449
450    /// Characters before a column (the column vertical moves keep).
451    fn char_col(&self, pos: BufferPos) -> usize {
452        self.lines[pos.line][..pos.col].chars().count()
453    }
454
455    fn col_for_chars(&self, line: usize, chars: usize) -> usize {
456        let text = &self.lines[line];
457        text.char_indices()
458            .nth(chars)
459            .map_or(text.len(), |(i, _)| i)
460    }
461
462    fn indent_of(&self, line: usize) -> &str {
463        let text = &self.lines[line];
464        let n = text.len() - text.trim_start_matches([' ', '\t']).len();
465        &text[..n]
466    }
467
468    fn indent_unit(&self) -> String {
469        if self.hard_tabs {
470            "\t".into()
471        } else {
472            " ".repeat(self.tab_size.max(1))
473        }
474    }
475
476    // ---- BufferSelection and movement ----
477
478    fn place(&mut self, head: BufferPos, select: bool) {
479        let head = self.clip(head);
480        self.selection.head = head;
481        if !select {
482            self.selection.anchor = head;
483        }
484    }
485
486    /// Moves the caret (extending the selection with `select`). Mouse clicks use this.
487    pub fn set_cursor(&mut self, pos: BufferPos, select: bool) {
488        self.goal = None;
489        self.place(pos, select);
490    }
491
492    pub fn set_selection(&mut self, selection: BufferSelection) {
493        self.goal = None;
494        self.selection = BufferSelection {
495            anchor: self.clip(selection.anchor),
496            head: self.clip(selection.head),
497        };
498    }
499
500    pub fn select_all(&mut self) {
501        self.goal = None;
502        self.selection = BufferSelection {
503            anchor: BufferPos::default(),
504            head: self.end(),
505        };
506    }
507
508    /// Selects the word (or run of spaces or punctuation) at `pos` (double click).
509    pub fn select_word_at(&mut self, pos: BufferPos) {
510        let pos = self.clip(pos);
511        let line = &self.lines[pos.line];
512        let Some(c) = line[pos.col..]
513            .chars()
514            .next()
515            .or_else(|| line[..pos.col].chars().next_back())
516        else {
517            self.set_cursor(pos, false);
518            return;
519        };
520        let k = class(c);
521        let start = line[..pos.col]
522            .char_indices()
523            .rev()
524            .take_while(|(_, c)| class(*c) == k)
525            .last()
526            .map_or(pos.col, |(i, _)| i);
527        let end = line[pos.col..]
528            .char_indices()
529            .take_while(|(_, c)| class(*c) == k)
530            .last()
531            .map_or(pos.col, |(i, c)| pos.col + i + c.len_utf8());
532        self.goal = None;
533        self.selection = BufferSelection {
534            anchor: BufferPos::new(pos.line, start),
535            head: BufferPos::new(pos.line, end),
536        };
537    }
538
539    /// Selects a whole line, including its line break (triple click).
540    pub fn select_line(&mut self, line: usize) {
541        let line = line.min(self.lines.len() - 1);
542        let head = if line + 1 < self.lines.len() {
543            BufferPos::new(line + 1, 0)
544        } else {
545            BufferPos::new(line, self.lines[line].len())
546        };
547        self.goal = None;
548        self.selection = BufferSelection {
549            anchor: BufferPos::new(line, 0),
550            head,
551        };
552    }
553
554    pub fn move_left(&mut self, select: bool) {
555        self.goal = None;
556        if !select && !self.selection.is_empty() {
557            let start = self.selection.range().start;
558            self.place(start, false);
559        } else {
560            let to = self.prev_pos(self.selection.head);
561            self.place(to, select);
562        }
563    }
564
565    pub fn move_right(&mut self, select: bool) {
566        self.goal = None;
567        if !select && !self.selection.is_empty() {
568            let end = self.selection.range().end;
569            self.place(end, false);
570        } else {
571            let to = self.next_pos(self.selection.head);
572            self.place(to, select);
573        }
574    }
575
576    /// Moves `lines` up (negative) or down, keeping the column. Past the first or last line the
577    /// caret goes to the start or end of the text.
578    pub fn move_vertically(&mut self, lines: isize, select: bool) {
579        let head = self.selection.head;
580        let goal = match self.goal {
581            Some(goal) => goal,
582            None => self.char_col(head),
583        };
584        self.goal = Some(goal);
585        let target = head.line as isize + lines;
586        let to = if target < 0 {
587            BufferPos::default()
588        } else if target as usize >= self.lines.len() {
589            self.end()
590        } else {
591            let line = target as usize;
592            BufferPos::new(line, self.col_for_chars(line, goal))
593        };
594        self.place(to, select);
595    }
596
597    pub fn move_word_left(&mut self, select: bool) {
598        self.goal = None;
599        let to = self.word_start(self.selection.head);
600        self.place(to, select);
601    }
602
603    pub fn move_word_right(&mut self, select: bool) {
604        self.goal = None;
605        let to = self.word_end(self.selection.head);
606        self.place(to, select);
607    }
608
609    /// Smart Home: to the first non-blank character, or to column 0 if already there.
610    pub fn move_home(&mut self, select: bool) {
611        self.goal = None;
612        let head = self.selection.head;
613        let indent = self.indent_of(head.line).len();
614        let col = if head.col == indent { 0 } else { indent };
615        self.place(BufferPos::new(head.line, col), select);
616    }
617
618    pub fn move_end(&mut self, select: bool) {
619        self.goal = None;
620        let line = self.selection.head.line;
621        self.place(BufferPos::new(line, self.lines[line].len()), select);
622    }
623
624    pub fn move_to_start(&mut self, select: bool) {
625        self.goal = None;
626        self.place(BufferPos::default(), select);
627    }
628
629    pub fn move_to_end(&mut self, select: bool) {
630        self.goal = None;
631        let end = self.end();
632        self.place(end, select);
633    }
634
635    // ---- Editing ----
636
637    /// Replaces `range` with `text` without recording history; returns the end of the new text.
638    fn splice(&mut self, range: Range<BufferPos>, text: &str) -> BufferPos {
639        let (start, end) = (self.clip(range.start), self.clip(range.end));
640        let tail = self.lines[end.line][end.col..].to_owned();
641        let head = self.lines[start.line][..start.col].to_owned();
642        let mut new_lines: Vec<String> = text.split('\n').map(str::to_owned).collect();
643        let last = new_lines.len() - 1;
644        let end_pos = end_of(start, text);
645        new_lines[0].insert_str(0, &head);
646        new_lines[last].push_str(&tail);
647        self.lines.splice(start.line..=end.line, new_lines);
648        self.edited_from = Some(self.edited_from.map_or(start.line, |l| l.min(start.line)));
649        end_pos
650    }
651
652    /// Records one replacement inside a transaction.
653    fn record(&mut self, edits: &mut Vec<Edit>, range: Range<BufferPos>, text: &str) -> BufferPos {
654        let (start, end) = (self.clip(range.start), self.clip(range.end));
655        let old = self.text_in(start..end);
656        let end = self.splice(start..end, text);
657        edits.push(Edit {
658            start,
659            old,
660            new: text.to_owned(),
661        });
662        end
663    }
664
665    fn transact(&mut self, kind: EditKind, f: impl FnOnce(&mut Self, &mut Vec<Edit>)) {
666        let before = self.selection;
667        let mut edits = Vec::new();
668        f(self, &mut edits);
669        self.goal = None;
670        if edits.is_empty() {
671            return;
672        }
673        self.redo.clear();
674        let after = self.selection;
675        let merge = !self.break_group
676            && kind != EditKind::Other
677            && self.undo.last().is_some_and(|last| {
678                last.kind == kind && last.after == before && last.id != self.saved
679            });
680        self.break_group = false;
681        if merge {
682            let last = self.undo.last_mut().unwrap();
683            last.edits.extend(edits);
684            last.after = after;
685        } else {
686            let id = self.next_id;
687            self.next_id += 1;
688            self.undo.push(Transaction {
689                id,
690                kind,
691                edits,
692                before,
693                after,
694            });
695        }
696    }
697
698    fn replace_selection(&mut self, text: &str, kind: EditKind) {
699        self.transact(kind, |b, edits| {
700            let end = b.record(edits, b.selection.range(), text);
701            b.selection = BufferSelection::caret(end);
702        });
703    }
704
705    /// Replaces the selection with `text` as one undo step (paste, completion, drop).
706    pub fn insert(&mut self, text: &str) {
707        let text = text.replace("\r\n", "\n");
708        self.replace_selection(&text, EditKind::Other);
709    }
710
711    /// Replaces a range (an IME composition, a find-and-replace) and puts the caret after it.
712    pub fn replace(&mut self, range: Range<BufferPos>, text: &str) {
713        self.transact(EditKind::Other, |b, edits| {
714            let end = b.record(edits, range, text);
715            b.selection = BufferSelection::caret(end);
716        });
717    }
718
719    /// Typed text: single characters pair brackets and quotes, skip over a closing one that is
720    /// already there, and wrap a selection; consecutive typing undoes as one step.
721    pub fn type_text(&mut self, text: &str) {
722        let mut chars = text.chars();
723        let (Some(c), None) = (chars.next(), chars.next()) else {
724            self.replace_selection(&text.replace("\r\n", "\n"), EditKind::Insert);
725            return;
726        };
727        if c == '\n' {
728            self.newline();
729            return;
730        }
731        if !self.auto_pair {
732            self.replace_selection(text, EditKind::Insert);
733            return;
734        }
735        let sel = self.selection;
736        let head = sel.head;
737        // A closing character that is already next to the caret: step over it.
738        if sel.is_empty() && is_closer(c) && self.char_after(head) == Some(c) {
739            let to = self.next_pos(head);
740            self.set_cursor(to, false);
741            self.break_group = true;
742            return;
743        }
744        if let Some(close) = closer_for(c) {
745            if !sel.is_empty() {
746                // Wrap the selection, keeping it selected inside the pair.
747                let range = sel.range();
748                self.transact(EditKind::Other, |b, edits| {
749                    let mut close_buf = [0; 4];
750                    b.record(
751                        edits,
752                        range.end..range.end,
753                        close.encode_utf8(&mut close_buf),
754                    );
755                    let mut open_buf = [0; 4];
756                    b.record(
757                        edits,
758                        range.start..range.start,
759                        c.encode_utf8(&mut open_buf),
760                    );
761                    let shift = |p: BufferPos| {
762                        if p.line == range.start.line {
763                            BufferPos::new(p.line, p.col + c.len_utf8())
764                        } else {
765                            p
766                        }
767                    };
768                    b.selection = BufferSelection {
769                        anchor: shift(sel.anchor),
770                        head: shift(sel.head),
771                    };
772                });
773                return;
774            }
775            let next_ok = self
776                .char_after(head)
777                .is_none_or(|n| n.is_whitespace() || is_closer(n) || n == ',' || n == ';');
778            let prev = self.char_before(head);
779            let prev_ok = !is_quote(c) || prev.is_none_or(|p| !is_word(p) && p != c);
780            if next_ok && prev_ok {
781                let pair = format!("{c}{close}");
782                self.transact(EditKind::Insert, |b, edits| {
783                    b.record(edits, head..head, &pair);
784                    b.selection =
785                        BufferSelection::caret(BufferPos::new(head.line, head.col + c.len_utf8()));
786                });
787                return;
788            }
789        }
790        self.replace_selection(text, EditKind::Insert);
791    }
792
793    /// Enter: keeps the line's indentation, adds a level after an opening bracket and moves the
794    /// matching closing bracket to its own line.
795    pub fn newline(&mut self) {
796        let range = self.selection.range();
797        let start = range.start;
798        let indent = self.indent_of(start.line);
799        let indent = indent[..indent.len().min(start.col)].to_owned();
800        let before = self.lines[start.line][..start.col]
801            .trim_end()
802            .chars()
803            .next_back();
804        let after = self.lines[range.end.line][range.end.col..].chars().next();
805        let opens = before.filter(|c| matches!(c, '(' | '[' | '{'));
806        let unit = self.indent_unit();
807        self.transact(EditKind::Other, |b, edits| match opens {
808            Some(open) if after == closer_for(open) => {
809                let text = format!("\n{indent}{unit}\n{indent}");
810                b.record(edits, range.clone(), &text);
811                b.selection = BufferSelection::caret(BufferPos::new(
812                    start.line + 1,
813                    indent.len() + unit.len(),
814                ));
815            }
816            Some(_) => {
817                let end = b.record(edits, range.clone(), &format!("\n{indent}{unit}"));
818                b.selection = BufferSelection::caret(end);
819            }
820            None => {
821                let end = b.record(edits, range.clone(), &format!("\n{indent}"));
822                b.selection = BufferSelection::caret(end);
823            }
824        });
825    }
826
827    /// Backspace: deletes the selection, an empty bracket pair, one indentation level inside
828    /// leading spaces, or the previous character.
829    pub fn backspace(&mut self) {
830        let sel = self.selection;
831        if !sel.is_empty() {
832            self.replace_selection("", EditKind::Delete);
833            return;
834        }
835        let head = sel.head;
836        if head == BufferPos::default() {
837            return;
838        }
839        let mut start = self.prev_pos(head);
840        let mut end = head;
841        let before = self.char_before(head);
842        let after = self.char_after(head);
843        if self.auto_pair
844            && let (Some(b), Some(a)) = (before, after)
845            && closer_for(b) == Some(a)
846        {
847            end = self.next_pos(head);
848        } else if !self.hard_tabs && head.col > 0 {
849            let leading = &self.lines[head.line][..head.col];
850            if leading.chars().all(|c| c == ' ') {
851                let size = self.tab_size.max(1);
852                let back = match head.col % size {
853                    0 => size,
854                    r => r,
855                };
856                start = BufferPos::new(head.line, head.col - back);
857            }
858        }
859        self.transact(EditKind::Delete, |b, edits| {
860            b.record(edits, start..end, "");
861            b.selection = BufferSelection::caret(start);
862        });
863    }
864
865    /// Delete: deletes the selection or the next character.
866    pub fn delete(&mut self) {
867        if !self.selection.is_empty() {
868            self.replace_selection("", EditKind::Delete);
869            return;
870        }
871        let head = self.selection.head;
872        let end = self.next_pos(head);
873        if end == head {
874            return;
875        }
876        self.transact(EditKind::Delete, |b, edits| {
877            b.record(edits, head..end, "");
878            b.selection = BufferSelection::caret(head);
879        });
880    }
881
882    /// Deletes to the start of the word (Ctrl+Backspace).
883    pub fn delete_word_left(&mut self) {
884        if self.selection.is_empty() {
885            let to = self.word_start(self.selection.head);
886            self.place(to, true);
887        }
888        self.replace_selection("", EditKind::Other);
889    }
890
891    /// Deletes to the end of the word (Ctrl+Delete).
892    pub fn delete_word_right(&mut self) {
893        if self.selection.is_empty() {
894            let to = self.word_end(self.selection.head);
895            self.place(to, true);
896        }
897        self.replace_selection("", EditKind::Other);
898    }
899
900    /// Tab: with a selection over several lines, indents them all; otherwise inserts spaces up
901    /// to the next tab stop (or a tab character with [`CodeBuffer::hard_tabs`]).
902    pub fn indent(&mut self) {
903        let sel = self.selection;
904        if sel.is_empty() {
905            let text = if self.hard_tabs {
906                "\t".to_owned()
907            } else {
908                let size = self.tab_size.max(1);
909                " ".repeat(size - self.char_col(sel.head) % size)
910            };
911            self.replace_selection(&text, EditKind::Other);
912            return;
913        }
914        let lines = sel.lines();
915        let unit = self.indent_unit();
916        self.shift_lines(lines, |_| (0, unit.clone()));
917    }
918
919    /// Shift+Tab: removes one indentation level from every line the selection touches.
920    pub fn outdent(&mut self) {
921        let lines = self.selection.lines();
922        let size = self.tab_size.max(1);
923        let snapshot: Vec<(usize, usize)> = lines
924            .clone()
925            .map(|l| {
926                let text = &self.lines[l];
927                let n = if text.starts_with('\t') {
928                    1
929                } else {
930                    text.chars().take(size).take_while(|c| *c == ' ').count()
931                };
932                (l, n)
933            })
934            .collect();
935        self.shift_lines(lines, |l| {
936            let n = snapshot
937                .iter()
938                .find(|(line, _)| *line == l)
939                .map_or(0, |s| s.1);
940            (n, String::new())
941        });
942    }
943
944    /// Replaces the first `remove` bytes of each line with `insert`, keeping the selection on the
945    /// same text.
946    fn shift_lines(&mut self, lines: Range<usize>, f: impl Fn(usize) -> (usize, String)) {
947        let sel = self.selection;
948        let changes: Vec<(usize, usize, String)> = lines
949            .map(|l| {
950                let (remove, insert) = f(l);
951                (l, remove, insert)
952            })
953            .filter(|(_, remove, insert)| *remove > 0 || !insert.is_empty())
954            .collect();
955        if changes.is_empty() {
956            return;
957        }
958        let adjust = |p: BufferPos| -> BufferPos {
959            match changes.iter().find(|(l, _, _)| *l == p.line) {
960                Some((_, remove, insert)) => {
961                    BufferPos::new(p.line, p.col.saturating_sub(*remove) + insert.len())
962                }
963                None => p,
964            }
965        };
966        let after = BufferSelection {
967            anchor: adjust(sel.anchor),
968            head: adjust(sel.head),
969        };
970        self.transact(EditKind::Other, |b, edits| {
971            for (line, remove, insert) in &changes {
972                b.record(
973                    edits,
974                    BufferPos::new(*line, 0)..BufferPos::new(*line, *remove),
975                    insert,
976                );
977            }
978            b.selection = after;
979        });
980    }
981
982    pub fn undo(&mut self) -> bool {
983        let Some(t) = self.undo.pop() else {
984            return false;
985        };
986        for edit in t.edits.iter().rev() {
987            let end = end_of(edit.start, &edit.new);
988            self.splice(edit.start..end, &edit.old);
989        }
990        self.selection = t.before;
991        self.goal = None;
992        self.break_group = true;
993        self.redo.push(t);
994        true
995    }
996
997    pub fn redo(&mut self) -> bool {
998        let Some(t) = self.redo.pop() else {
999            return false;
1000        };
1001        for edit in &t.edits {
1002            let end = end_of(edit.start, &edit.old);
1003            self.splice(edit.start..end, &edit.new);
1004        }
1005        self.selection = t.after;
1006        self.goal = None;
1007        self.break_group = true;
1008        self.undo.push(t);
1009        true
1010    }
1011}
1012
1013#[cfg(test)]
1014mod tests {
1015    use super::*;
1016
1017    fn at(line: usize, col: usize) -> BufferPos {
1018        BufferPos::new(line, col)
1019    }
1020
1021    fn typed(b: &mut CodeBuffer, text: &str) {
1022        for c in text.chars() {
1023            b.type_text(&c.to_string());
1024        }
1025    }
1026
1027    #[test]
1028    fn splits_lines_and_keeps_crlf() {
1029        let b = CodeBuffer::new("a\r\nbc\r\n");
1030        assert_eq!(b.line_count(), 3);
1031        assert_eq!(b.line(1), "bc");
1032        assert_eq!(b.text(), "a\r\nbc\r\n");
1033        assert!(!b.is_dirty());
1034    }
1035
1036    #[test]
1037    fn inserts_multiline_text_and_reads_ranges() {
1038        let mut b = CodeBuffer::new("hello world");
1039        b.set_cursor(at(0, 5), false);
1040        b.insert(",\nnew\nline");
1041        assert_eq!(b.text(), "hello,\nnew\nline world");
1042        assert_eq!(b.cursor(), at(2, 4));
1043        assert_eq!(b.text_in(at(0, 3)..at(2, 2)), "lo,\nnew\nli");
1044        assert_eq!(b.offset_of(at(1, 1)), 8);
1045        assert_eq!(b.pos_of(8), at(1, 1));
1046    }
1047
1048    #[test]
1049    fn utf16_offsets_round_trip() {
1050        let b = CodeBuffer::new("aĆ±šŸ˜€\nx");
1051        let pos = at(1, 1);
1052        let u = b.utf16_of(pos);
1053        assert_eq!(u, 6); // a Ʊ šŸ˜€(2) \n x
1054        assert_eq!(b.pos_of_utf16(u), pos);
1055        assert_eq!(b.pos_of_utf16(2), at(0, 3));
1056    }
1057
1058    #[test]
1059    fn typing_undoes_as_one_step_and_redo_restores() {
1060        let mut b = CodeBuffer::new("");
1061        typed(&mut b, "let x");
1062        assert_eq!(b.text(), "let x");
1063        assert!(b.is_dirty());
1064        assert!(b.undo());
1065        assert_eq!(b.text(), "");
1066        assert!(!b.is_dirty());
1067        assert!(b.redo());
1068        assert_eq!(b.text(), "let x");
1069        assert_eq!(b.cursor(), at(0, 5));
1070    }
1071
1072    #[test]
1073    fn moving_the_caret_starts_a_new_undo_step() {
1074        let mut b = CodeBuffer::new("");
1075        typed(&mut b, "ab");
1076        b.move_left(false);
1077        typed(&mut b, "X");
1078        assert_eq!(b.text(), "aXb");
1079        b.undo();
1080        assert_eq!(b.text(), "ab");
1081        b.undo();
1082        assert_eq!(b.text(), "");
1083    }
1084
1085    #[test]
1086    fn saving_marks_clean_and_does_not_merge_into_the_saved_step() {
1087        let mut b = CodeBuffer::new("");
1088        typed(&mut b, "ab");
1089        b.mark_saved();
1090        assert!(!b.is_dirty());
1091        typed(&mut b, "c");
1092        assert!(b.is_dirty());
1093        b.undo();
1094        assert_eq!(b.text(), "ab");
1095        assert!(!b.is_dirty());
1096    }
1097
1098    #[test]
1099    fn a_new_edit_clears_redo() {
1100        let mut b = CodeBuffer::new("");
1101        typed(&mut b, "a");
1102        b.undo();
1103        typed(&mut b, "b");
1104        assert!(!b.redo());
1105        assert_eq!(b.text(), "b");
1106    }
1107
1108    #[test]
1109    fn newline_keeps_indentation() {
1110        let mut b = CodeBuffer::new("    let x = 1;");
1111        b.move_end(false);
1112        b.newline();
1113        assert_eq!(b.text(), "    let x = 1;\n    ");
1114        assert_eq!(b.cursor(), at(1, 4));
1115    }
1116
1117    #[test]
1118    fn newline_after_brace_indents_and_splits_the_pair() {
1119        let mut b = CodeBuffer::new("  fn f() {}");
1120        b.set_cursor(at(0, 10), false);
1121        b.newline();
1122        assert_eq!(b.text(), "  fn f() {\n      \n  }");
1123        assert_eq!(b.cursor(), at(1, 6));
1124        // Without a closing brace next to the caret, it only adds a level.
1125        let mut b = CodeBuffer::new("if x {");
1126        b.move_end(false);
1127        b.newline();
1128        assert_eq!(b.text(), "if x {\n    ");
1129    }
1130
1131    #[test]
1132    fn tab_inserts_to_the_next_stop_and_shift_tab_outdents() {
1133        let mut b = CodeBuffer::new("ab");
1134        b.set_cursor(at(0, 1), false);
1135        b.indent();
1136        assert_eq!(b.text(), "a   b");
1137        assert_eq!(b.cursor(), at(0, 4));
1138        b.outdent();
1139        assert_eq!(b.text(), "a   b"); // the line had no leading indentation
1140        let mut b = CodeBuffer::new("      x");
1141        b.move_end(false);
1142        b.outdent();
1143        assert_eq!(b.text(), "  x");
1144        assert_eq!(b.cursor(), at(0, 3));
1145    }
1146
1147    #[test]
1148    fn tab_indents_every_selected_line_and_keeps_the_selection() {
1149        let mut b = CodeBuffer::new("a\nb\nc");
1150        b.set_selection(BufferSelection {
1151            anchor: at(0, 1),
1152            head: at(2, 0),
1153        });
1154        b.indent();
1155        // The last line is not touched: the selection ends at its column 0.
1156        assert_eq!(b.text(), "    a\n    b\nc");
1157        assert_eq!(b.selection().anchor, at(0, 5));
1158        assert_eq!(b.selection().head, at(2, 0));
1159        b.outdent();
1160        assert_eq!(b.text(), "a\nb\nc");
1161        b.undo();
1162        assert_eq!(b.text(), "    a\n    b\nc");
1163        b.undo();
1164        assert_eq!(b.text(), "a\nb\nc");
1165    }
1166
1167    #[test]
1168    fn hard_tabs_indent_with_tab_characters() {
1169        let mut b = CodeBuffer::new("x\ny");
1170        b.hard_tabs = true;
1171        b.select_all();
1172        b.indent();
1173        assert_eq!(b.text(), "\tx\n\ty");
1174        b.outdent();
1175        assert_eq!(b.text(), "x\ny");
1176    }
1177
1178    #[test]
1179    fn backspace_in_leading_spaces_removes_one_level() {
1180        let mut b = CodeBuffer::new("      x");
1181        b.set_cursor(at(0, 6), false);
1182        b.backspace();
1183        assert_eq!(b.text(), "    x");
1184        b.backspace();
1185        assert_eq!(b.text(), "x");
1186    }
1187
1188    #[test]
1189    fn brackets_pair_skip_and_delete_together() {
1190        let mut b = CodeBuffer::new("");
1191        typed(&mut b, "f(");
1192        assert_eq!(b.text(), "f()");
1193        assert_eq!(b.cursor(), at(0, 2));
1194        typed(&mut b, "a)");
1195        assert_eq!(b.text(), "f(a)");
1196        assert_eq!(b.cursor(), at(0, 4));
1197        let mut b = CodeBuffer::new("");
1198        typed(&mut b, "[");
1199        b.backspace();
1200        assert_eq!(b.text(), "");
1201    }
1202
1203    #[test]
1204    fn brackets_do_not_pair_before_a_word_and_quotes_not_after_one() {
1205        let mut b = CodeBuffer::new("x");
1206        b.set_cursor(at(0, 0), false);
1207        typed(&mut b, "(");
1208        assert_eq!(b.text(), "(x");
1209        let mut b = CodeBuffer::new("don");
1210        b.move_end(false);
1211        typed(&mut b, "'");
1212        assert_eq!(b.text(), "don'");
1213        let mut b = CodeBuffer::new("");
1214        typed(&mut b, "\"hi\"");
1215        assert_eq!(b.text(), "\"hi\"");
1216    }
1217
1218    #[test]
1219    fn typing_a_bracket_wraps_the_selection() {
1220        let mut b = CodeBuffer::new("call x now");
1221        b.set_selection(BufferSelection {
1222            anchor: at(0, 5),
1223            head: at(0, 6),
1224        });
1225        typed(&mut b, "(");
1226        assert_eq!(b.text(), "call (x) now");
1227        assert_eq!(b.selected_text(), "x");
1228    }
1229
1230    #[test]
1231    fn deleting_across_lines_joins_them() {
1232        let mut b = CodeBuffer::new("ab\ncd");
1233        b.set_cursor(at(1, 0), false);
1234        b.backspace();
1235        assert_eq!(b.text(), "abcd");
1236        assert_eq!(b.cursor(), at(0, 2));
1237        b.delete();
1238        assert_eq!(b.text(), "abd");
1239    }
1240
1241    #[test]
1242    fn vertical_moves_keep_the_goal_column() {
1243        let mut b = CodeBuffer::new("abcdef\nab\nabcdef");
1244        b.set_cursor(at(0, 5), false);
1245        b.move_vertically(1, false);
1246        assert_eq!(b.cursor(), at(1, 2));
1247        b.move_vertically(1, false);
1248        assert_eq!(b.cursor(), at(2, 5));
1249        b.move_vertically(5, false);
1250        assert_eq!(b.cursor(), at(2, 6));
1251    }
1252
1253    #[test]
1254    fn word_moves_and_double_click_selection() {
1255        let mut b = CodeBuffer::new("let foo_bar = 1;");
1256        b.set_cursor(at(0, 0), false);
1257        b.move_word_right(false);
1258        assert_eq!(b.cursor(), at(0, 3));
1259        b.move_word_right(false);
1260        assert_eq!(b.cursor(), at(0, 11));
1261        b.move_word_left(false);
1262        assert_eq!(b.cursor(), at(0, 4));
1263        b.select_word_at(at(0, 6));
1264        assert_eq!(b.selected_text(), "foo_bar");
1265    }
1266
1267    #[test]
1268    fn smart_home_toggles_between_indent_and_column_zero() {
1269        let mut b = CodeBuffer::new("    x");
1270        b.move_end(false);
1271        b.move_home(false);
1272        assert_eq!(b.cursor(), at(0, 4));
1273        b.move_home(false);
1274        assert_eq!(b.cursor(), at(0, 0));
1275    }
1276
1277    #[test]
1278    fn edited_from_reports_the_first_changed_line() {
1279        let mut b = CodeBuffer::new("a\nb\nc");
1280        b.take_edited_from();
1281        b.set_cursor(at(2, 1), false);
1282        typed(&mut b, "x");
1283        assert_eq!(b.take_edited_from(), Some(2));
1284        assert_eq!(b.take_edited_from(), None);
1285    }
1286
1287    #[test]
1288    fn selection_lines_skip_a_trailing_column_zero() {
1289        let s = BufferSelection {
1290            anchor: at(3, 2),
1291            head: at(1, 0),
1292        };
1293        assert_eq!(s.lines(), 1..4);
1294        let s = BufferSelection {
1295            anchor: at(1, 0),
1296            head: at(3, 0),
1297        };
1298        assert_eq!(s.lines(), 1..3);
1299    }
1300}