curd-editor 0.27.1

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
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
//! Changing the text: typing and deleting, selections, whole lines, undo.

use super::*;

impl Editor {
    // ---- Editing -------------------------------------------------------
    //
    // Every change to the text goes through the four methods below, which
    // keep the cursor, the folds and the language server in step with the
    // document.

    /// Inserts `c` at the cursor.
    pub(super) fn insert_char(&mut self, c: char) {
        if self.is_only_to_look_at() {
            return;
        }
        // Editing a collapsed line opens it, so nothing changes out of sight.
        self.folds.unfold(self.cursor_y);
        let at = self.lsp_position(self.cursor_x, self.cursor_y);
        self.history.record(Change::Insert { x: self.cursor_x, y: self.cursor_y, c });
        self.document.insert_char(self.cursor_x, self.cursor_y, c);
        self.highlights.inserted(self.cursor_x, self.cursor_y);
        self.rescan(self.cursor_y, 0);
        self.text_changed(at, at, &c.to_string(), c);
        self.cursor_x += 1;
    }

    /// Splits the line at the cursor and moves to the start of the new line.
    pub(super) fn insert_newline(&mut self) {
        if self.is_only_to_look_at() {
            return;
        }
        self.folds.unfold(self.cursor_y);
        let at = self.lsp_position(self.cursor_x, self.cursor_y);
        self.history.record(Change::Insert { x: self.cursor_x, y: self.cursor_y, c: '\n' });
        self.document.insert_newline(self.cursor_x, self.cursor_y);
        self.highlights.split(self.cursor_x, self.cursor_y);
        self.rescan(self.cursor_y, 1);
        self.text_changed(at, at, "\n", '\n');
        self.lines_shifted(self.cursor_y, 1);
        self.cursor_y += 1;
        self.cursor_x = 0;
    }

    /// Deletes the character before the cursor, or joins this line onto the
    /// one above when the cursor is at the start of a line.
    pub(super) fn backspace(&mut self) {
        self.folds.unfold(self.cursor_y);
        if self.cursor_x > 0 {
            self.cursor_x -= 1;
            self.delete_at_cursor();
        } else if self.cursor_y > 0 {
            // The line above may be hidden inside a fold: open it first.
            self.folds.reveal(self.cursor_y - 1);
            self.cursor_y -= 1;
            self.cursor_x = self.document.line_len(self.cursor_y);
            self.delete_at_cursor();
        }
    }

    /// Deletes the character under the cursor, or joins the next line onto
    /// this one when the cursor is at the end of a line.
    pub(super) fn delete(&mut self) {
        self.folds.unfold(self.cursor_y);
        self.delete_at_cursor();
    }

    /// True (after saying so) for a view, which cannot be changed.
    pub(super) fn is_only_to_look_at(&mut self) -> bool {
        if self.view.is_some() {
            self.message = "This shows changes and cannot be edited: Enter goes to the line in its file".into();
        }
        self.view.is_some()
    }

    pub(super) fn delete_at_cursor(&mut self) {
        if self.is_only_to_look_at() {
            return;
        }
        let (x, y) = (self.cursor_x, self.cursor_y);
        let start = self.lsp_position(x, y);
        if let Some(c) = self.document.lines.get(y).and_then(|line| line.chars().nth(x)) {
            let end = self.lsp_position(x + 1, y);
            self.history.record(Change::Delete { x, y, c });
            self.document.delete_char(x, y);
            self.highlights.deleted(x, y);
            self.rescan(y, 0);
            self.text_changed(start, end, "", c);
        } else if y + 1 < self.document.len() {
            // Joining lines: the line break itself is what gets deleted.
            self.folds.unfold(y + 1);
            self.history.record(Change::Delete { x, y, c: '\n' });
            self.document.delete_char(x, y);
            self.highlights.joined(y, x);
            self.rescan(y, -1);
            self.text_changed(start, (y + 1, 0), "", '\n');
            self.lines_shifted(y, -1);
        }
    }

    /// Updates the built-in colouring after an edit on line `y` that added
    /// `added` lines below it (-1 when the next line was joined onto it).
    pub(super) fn rescan(&mut self, y: usize, added: isize) {
        if self.language.is_none() {
            return;
        }
        match added {
            1 => self.line_states.insert(y + 1, LineState::Code),
            -1 => drop(self.line_states.remove(y + 1)),
            _ => {}
        }
        // The first edit of an empty document creates its first line.
        self.line_states.resize(self.document.len(), LineState::Code);
        // The lines to look at again are only noted here. They are looked
        // at once, when the key (or the paste, or the undo) has been dealt
        // with: a paste is thousands of edits, and a quote in it would
        // otherwise have the rest of the file scanned again and again.
        let last = y + added.max(0) as usize;
        self.stale = Some(match self.stale {
            None => (y, last),
            Some((from, to)) => {
                // Lines below the edit moved with it.
                let to = if y <= to { (to as isize + added).max(y as isize) as usize } else { to };
                (from.min(y), to.max(last))
            }
        });
    }

    /// Brings the built-in colouring up to date with the edits made since
    /// the last time.
    pub(super) fn recolour(&mut self) {
        if let (Some((from, to)), Some(language)) = (self.stale.take(), self.language) {
            self.line_states.resize(self.document.len(), LineState::Code);
            highlight::rescan(&mut self.line_states, &self.document.lines, language, from, to);
        }
    }

    /// Where character `x` of line `y` is in the language server's terms.
    pub(super) fn lsp_position(&self, x: usize, y: usize) -> (usize, usize) {
        let line = self.document.lines.get(y).map_or("", String::as_str);
        (y, self.encoding().to_units(line, x))
    }

    pub(super) fn encoding(&self) -> Encoding {
        self.lsp
            .as_ref()
            .map_or(Encoding::Utf32, |lsp| lsp.borrow().encoding())
    }

    /// Called after every edit with the range that was replaced.
    ///
    /// `touched` is the character that was put in or taken out. Where the
    /// blocks are only has to be worked out again if it could have moved
    /// one: a bracket or a line break, or anything at all in a language
    /// whose blocks go by indentation.
    pub(super) fn text_changed(&mut self, start: (usize, usize), end: (usize, usize), text: &str, touched: char) {
        let by_indent = self.language.is_some_and(Language::blocks_by_indent);
        if by_indent || matches!(touched, '{' | '}' | '\n') {
            self.blocks = OnceCell::new();
        }
        self.marks = OnceCell::new();
        if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
            lsp.borrow_mut().change(path, start, end, text);
        }
    }

    /// Called when `delta` lines were added (or removed, when negative)
    /// just below line `y`, so line-based notes keep pointing at the same code.
    pub(super) fn lines_shifted(&mut self, y: usize, delta: isize) {
        self.folds.shift_after(y, delta);
        for diagnostic in &mut self.diagnostics {
            for line in [&mut diagnostic.line, &mut diagnostic.end_line] {
                if *line > y {
                    *line = (*line as isize + delta) as usize;
                }
            }
        }
    }

    /// A character typed by the user. A `}` typed on an otherwise blank line
    /// steps back one indent level so it lines up with its opening line.
    pub(super) fn type_char(&mut self, c: char) {
        if c == '}' && self.cursor_x > 0 && self.text_before_cursor().chars().all(|c| c == ' ') {
            for _ in 0..self.indent().len().min(self.cursor_x) {
                self.backspace();
            }
        }
        self.insert_char(c);
    }

    /// Pasted text goes in exactly as it is: no auto-indent, no snippets.
    pub fn paste(&mut self, text: &str) {
        self.message.clear();
        self.info.clear();
        self.completion = None;
        if let Some(prompt) = &mut self.prompt {
            // Pasting into the status bar question: one line only.
            prompt.text.extend(text.chars().filter(|c| !c.is_control()));
            self.prompt_changed();
            return;
        }
        self.history.begin((self.cursor_x, self.cursor_y), false);
        self.delete_selection();
        self.insert_text(text);
        self.history.commit((self.cursor_x, self.cursor_y));
        self.recolour();
    }

    // ---- Selecting, copying and cutting --------------------------------

    /// Where the selected text starts and ends, if any is selected.
    pub(super) fn selection(&self) -> Option<((usize, usize), (usize, usize))> {
        let anchor = self.anchor?;
        let cursor = (self.cursor_x, self.cursor_y);
        match (anchor.1, anchor.0).cmp(&(cursor.1, cursor.0)) {
            std::cmp::Ordering::Less => Some((anchor, cursor)),
            std::cmp::Ordering::Greater => Some((cursor, anchor)),
            std::cmp::Ordering::Equal => None,
        }
    }

    /// The whole cursor line with its line break, which is what copy and
    /// cut take when nothing is selected.
    pub(super) fn line_range(&self) -> Option<((usize, usize), (usize, usize))> {
        let y = self.cursor_y;
        if y + 1 < self.document.len() {
            Some(((0, y), (0, y + 1)))
        } else if self.document.line_len(y) > 0 {
            Some(((0, y), (self.document.line_len(y), y)))
        } else {
            None
        }
    }

    /// The text from `start` up to `end`.
    pub(super) fn text_between(&self, start: (usize, usize), end: (usize, usize)) -> String {
        let mut text = String::new();
        let lines = self.document.lines.iter().enumerate();
        for (y, line) in lines.take(end.1 + 1).skip(start.1) {
            let from = if y == start.1 { start.0 } else { 0 };
            let line = line.chars().skip(from);
            if y == end.1 {
                text.extend(line.take(end.0 - from));
            } else {
                text.extend(line);
                text.push('\n');
            }
        }
        text
    }

    pub(super) fn select_all(&mut self) {
        let Some(last) = self.document.len().checked_sub(1) else {
            return;
        };
        self.anchor = Some((0, 0));
        (self.cursor_x, self.cursor_y) = (self.document.line_len(last), last);
    }

    /// Copies the selected text, or the cursor line when nothing is
    /// selected. Returns the range that was copied.
    pub(super) fn copy(&mut self) -> Option<((usize, usize), (usize, usize))> {
        let (start, end) = self.selection().or_else(|| self.line_range())?;
        let text = self.text_between(start, end);
        self.message = match end.1 - start.1 {
            0 => format!("Copied {} characters", text.chars().count()),
            lines => format!("Copied {} lines", lines + (end.0 > 0) as usize),
        };
        self.copied = Some(text);
        Some((start, end))
    }

    /// Copies like `copy`, then takes the text out.
    pub(super) fn cut(&mut self) {
        if let Some((start, end)) = self.copy() {
            self.anchor = Some(start);
            (self.cursor_x, self.cursor_y) = end;
            self.delete_selection();
            self.message = self.message.replacen("Copied", "Cut", 1);
        }
    }

    /// Takes out the selected text. Returns false if nothing was selected.
    pub(super) fn delete_selection(&mut self) -> bool {
        let Some((start, end)) = self.selection() else {
            return false;
        };
        self.anchor = None;
        (self.cursor_x, self.cursor_y) = end;
        while (self.cursor_y, self.cursor_x) > (start.1, start.0) {
            self.backspace();
        }
        true
    }

    // ---- Whole lines: indent, comment, move, duplicate ------------------

    /// The first and last line the selection touches, or the cursor line
    /// when nothing is selected.
    pub(super) fn selected_lines(&self) -> (usize, usize) {
        match self.selection() {
            // A selection that ends at the very start of a line does not
            // include that line.
            Some((start, end)) if end.0 == 0 => (start.1, end.1 - 1),
            Some((start, end)) => (start.1, end.1),
            None => (self.cursor_y, self.cursor_y),
        }
    }

    /// After changing the lines `first..=last`: selects them whole if
    /// there was a selection, or else puts the cursor back at column `x`.
    pub(super) fn after_line_edit(&mut self, first: usize, last: usize, x: usize, y: usize) {
        if self.anchor.is_some() {
            self.anchor = Some((0, first));
            (self.cursor_x, self.cursor_y) = (self.document.line_len(last), last);
            self.keep_selection = true;
        } else {
            (self.cursor_x, self.cursor_y) = (x, y);
        }
    }

    /// Moves the selected lines (or the cursor line) one level in, or out.
    pub(super) fn shift_lines(&mut self, inwards: bool) {
        let (first, last) = self.selected_lines();
        let (mut x, y) = (self.cursor_x, self.cursor_y);
        let unit = self.indent();
        for line in first..=last.min(self.document.len().saturating_sub(1)) {
            (self.cursor_x, self.cursor_y) = (0, line);
            if inwards {
                if self.document.line_len(line) > 0 {
                    unit.chars().for_each(|c| self.insert_char(c));
                }
            } else {
                let spaces = self.document.lines.get(line).map_or(0, |text| {
                    text.chars().take(unit.len()).take_while(|c| *c == ' ').count()
                });
                for _ in 0..spaces {
                    self.delete();
                }
                if line == y {
                    x = x.saturating_sub(spaces);
                }
            }
        }
        self.after_line_edit(first, last, x, y);
    }

    /// Turns the selected lines (or the cursor line) into comments, or
    /// back into code if they all are comments already.
    pub(super) fn toggle_comment(&mut self) {
        let Some(token) = self.language.map(highlight::line_comment) else {
            self.message = "No comment style known for this kind of file".into();
            return;
        };
        let (first, last) = self.selected_lines();
        let (x, y) = (self.cursor_x, self.cursor_y);
        let indent_of = |line: &String| line.chars().take_while(|c| *c == ' ').count();
        let lines: Vec<(usize, usize)> = (first..=last)
            .filter_map(|line| Some((line, self.document.lines.get(line)?)))
            .filter(|(_, text)| !text.trim().is_empty())
            .map(|(line, text)| (line, indent_of(text)))
            .collect();
        let commented = lines.iter().all(|(line, indent)| {
            self.document.lines[*line].chars().skip(*indent).collect::<String>().starts_with(token)
        });
        // New comment marks line up at the shallowest line's indentation.
        let column = lines.iter().map(|(_, indent)| *indent).min().unwrap_or(0);
        for (line, indent) in lines {
            if commented {
                (self.cursor_x, self.cursor_y) = (indent, line);
                for _ in 0..token.chars().count() {
                    self.delete();
                }
                if self.document.lines[line].chars().nth(indent) == Some(' ') {
                    self.delete();
                }
            } else {
                (self.cursor_x, self.cursor_y) = (column, line);
                self.insert_text(&format!("{token} "));
            }
        }
        self.after_line_edit(first, last, x, y);
    }

    /// Swaps the cursor line with the one below it (`down`) or above it,
    /// and follows it there.
    pub(super) fn move_line(&mut self, down: bool) {
        let (x, y) = (self.cursor_x, self.cursor_y);
        // The lower of the two lines is the one that is taken out and put
        // back in above the other.
        let lower = y + down as usize;
        if lower == 0 || lower >= self.document.len() {
            return;
        }
        self.folds.reveal(lower - 1);
        self.folds.reveal(lower);
        let text = self.document.lines[lower].clone();
        (self.cursor_x, self.cursor_y) = (0, lower);
        for _ in 0..text.chars().count() {
            self.delete();
        }
        self.backspace();
        (self.cursor_x, self.cursor_y) = (0, lower - 1);
        text.chars().for_each(|c| self.insert_char(c));
        self.insert_newline();
        (self.cursor_x, self.cursor_y) = (x, if down { y + 1 } else { y - 1 });
    }

    /// Puts a copy of the cursor line below it, and moves onto the copy.
    pub(super) fn duplicate_line(&mut self) {
        let Some(text) = self.document.lines.get(self.cursor_y).cloned() else {
            return;
        };
        let x = self.cursor_x;
        self.cursor_x = self.document.line_len(self.cursor_y);
        self.insert_newline();
        text.chars().for_each(|c| self.insert_char(c));
        self.cursor_x = x;
    }

    /// Selects the word under the cursor, as a double click does.
    pub fn select_word(&mut self) {
        let Some(line) = self.document.lines.get(self.cursor_y) else {
            return;
        };
        let chars: Vec<char> = line.chars().collect();
        let mut start = self.cursor_x.min(chars.len());
        let mut end = start;
        while start > 0 && is_word_char(chars[start - 1]) {
            start -= 1;
        }
        while end < chars.len() && is_word_char(chars[end]) {
            end += 1;
        }
        if start < end {
            self.anchor = Some((start, self.cursor_y));
            self.cursor_x = end;
        }
    }

    /// Puts the cursor on line `y` (counted from 0), at column `x`.
    pub fn jump_to(&mut self, x: usize, y: usize) {
        self.anchor = None;
        self.completion = None;
        self.cursor_y = y.min(self.document.len().saturating_sub(1));
        self.folds.reveal(self.cursor_y);
        self.cursor_x = x.min(self.document.line_len(self.cursor_y));
    }

    /// Replaces the whole text with `lines`, which is what the file on
    /// disk holds now. It can be undone like any other change.
    pub fn reload(&mut self, lines: &[String]) {
        let cursor = (self.cursor_x, self.cursor_y);
        self.anchor = None;
        self.completion = None;
        self.prompt = None;
        self.history.begin(cursor, false);
        self.select_all();
        self.delete_selection();
        for (y, line) in lines.iter().enumerate() {
            if y > 0 {
                self.insert_newline();
            }
            line.chars().for_each(|c| self.insert_char(c));
        }
        self.jump_to(cursor.0, cursor.1);
        self.history.commit((self.cursor_x, self.cursor_y));
        self.history.mark_saved();
        self.document.dirty = false;
        self.recolour();
        self.message = "Reloaded: the file changed on disk".into();
    }

    /// Puts `text` in at the cursor exactly as it is.
    pub(super) fn insert_text(&mut self, text: &str) {
        for c in text.chars() {
            match c {
                '\n' => self.insert_newline(),
                '\r' => {}
                '\t' => self.indent().chars().for_each(|c| self.insert_char(c)),
                c => self.insert_char(c),
            }
        }
    }

    // ---- Undo and redo -------------------------------------------------

    /// Takes back the last step: a run of typing, a paste, a snippet.
    pub(super) fn undo(&mut self) {
        let Some(step) = self.history.undo() else {
            self.message = "Nothing to undo".into();
            return;
        };
        for change in step.changes.iter().rev() {
            match *change {
                Change::Insert { x, y, .. } => self.remove_at(x, y),
                Change::Delete { x, y, c } => self.put_at(x, y, c),
            }
        }
        (self.cursor_x, self.cursor_y) = step.before;
        self.document.dirty = !self.history.is_saved();
    }

    /// Does again the step that was last undone.
    pub(super) fn redo(&mut self) {
        let Some(step) = self.history.redo() else {
            self.message = "Nothing to redo".into();
            return;
        };
        for change in &step.changes {
            match *change {
                Change::Insert { x, y, c } => self.put_at(x, y, c),
                Change::Delete { x, y, .. } => self.remove_at(x, y),
            }
        }
        (self.cursor_x, self.cursor_y) = step.after;
        self.document.dirty = !self.history.is_saved();
    }

    /// Puts character `c` (or a line break) in at column `x` of line `y`.
    pub(super) fn put_at(&mut self, x: usize, y: usize, c: char) {
        self.folds.reveal(y);
        (self.cursor_x, self.cursor_y) = (x, y);
        match c {
            '\n' => self.insert_newline(),
            c => self.insert_char(c),
        }
    }

    /// Takes out the character (or line break) at column `x` of line `y`.
    pub(super) fn remove_at(&mut self, x: usize, y: usize) {
        self.folds.reveal(y);
        (self.cursor_x, self.cursor_y) = (x, y);
        self.delete_at_cursor();
    }

    /// The part of the cursor line that is left of the cursor.
    pub(super) fn text_before_cursor(&self) -> String {
        match self.document.lines.get(self.cursor_y) {
            Some(line) => line.chars().take(self.cursor_x).collect(),
            None => String::new(),
        }
    }

    /// One level of indentation: four spaces, or two in YAML.
    pub(super) fn indent(&self) -> &'static str {
        Language::indent(self.language)
    }

    /// The indentation a new line should start with: the same as the current
    /// line, plus one level after an opening bracket (or `:` in Python).
    pub(super) fn indent_for_new_line(&self) -> String {
        let before = self.text_before_cursor();
        let mut indent: String = before.chars().take_while(|c| *c == ' ').collect();
        let opens_block = match before.trim_end().chars().last() {
            Some('{' | '(' | '[') => true,
            Some(':') => self.language.is_some_and(Language::blocks_by_indent),
            _ => false,
        };
        if opens_block {
            indent.push_str(self.indent());
        }
        indent
    }

    /// The word before the cursor.
    pub(super) fn word_before_cursor(&self) -> String {
        let before = self.text_before_cursor();
        let start = self.word_start();
        before.chars().skip(start).collect()
    }

    /// The column where the word before the cursor starts (the cursor's
    /// own column, if there is no word there).
    pub(super) fn word_start(&self) -> usize {
        let before = self.text_before_cursor();
        let word = before.chars().rev().take_while(|c| is_word_char(*c)).count();
        before.chars().count() - word
    }

    /// The snippet the word before the cursor stands for, if it is a
    /// trigger word.
    pub(super) fn snippet_at_cursor(&self) -> Option<&'static str> {
        let word = self.word_before_cursor();
        self.language.and_then(|language| language.snippet(&word))
    }

    /// Tab expands the word before the cursor if it is a snippet trigger,
    /// and otherwise indents.
    pub(super) fn tab(&mut self) {
        match self.snippet_at_cursor() {
            Some(body) => {
                let word = self.word_before_cursor();
                self.expand_snippet(word.chars().count(), body);
                self.message = format!("Expanded snippet: {word}");
            }
            None => self.indent().chars().for_each(|c| self.insert_char(c)),
        }
    }

    /// Replaces the `trigger_len` characters before the cursor with `body`.
    pub(super) fn expand_snippet(&mut self, trigger_len: usize, body: &str) {
        for _ in 0..trigger_len {
            self.backspace();
        }
        let indent: String = self
            .text_before_cursor()
            .chars()
            .take_while(|c| *c == ' ')
            .collect();

        let mut cursor_target = None;
        let mut chars = body.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                '$' if chars.peek() == Some(&'0') => {
                    chars.next();
                    cursor_target = Some((self.cursor_x, self.cursor_y));
                }
                '\n' => {
                    self.insert_newline();
                    indent.chars().for_each(|c| self.insert_char(c));
                }
                c => self.insert_char(c),
            }
        }
        if let Some((x, y)) = cursor_target {
            self.cursor_x = x;
            self.cursor_y = y;
        }
    }

    /// Ctrl+S: saves, first asking for a name if the file has none.
    pub(super) fn save_or_ask(&mut self) {
        if self.is_only_to_look_at() {
            return;
        }
        if self.document.path.is_none() {
            self.open_prompt(PromptKind::SaveAs);
        } else {
            self.save();
        }
    }

    /// Writes the file. Returns whether that worked.
    pub(super) fn save(&mut self) -> bool {
        let result = self.document.save();
        self.message = match &result {
            Ok(()) => {
                self.just_saved = true;
                self.history.mark_saved();
                self.sync_lsp();
                if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
                    lsp.borrow_mut().did_save(path);
                }
                format!("Saved {} lines", self.document.len())
            }
            Err(error) => format!("Could not save: {error}"),
        };
        result.is_ok()
    }

    /// Gives a file that has no name the name `name` and saves it there.
    /// A file that already exists is never overwritten this way.
    pub(super) fn save_as(&mut self, name: &str) {
        let name = name.trim();
        if name.is_empty() {
            self.message = "Not saved: no file name given".into();
            return;
        }
        if Path::new(name).exists() {
            self.message = format!("Not saved: {name} already exists");
            return;
        }
        self.document.path = Some(name.to_string());
        if !self.save() {
            self.document.path = None;
            return;
        }
        // Now that it has a name it has a language too.
        self.abs_path = std::fs::canonicalize(name)
            .or_else(|_| std::path::absolute(name))
            .ok()
            .map(|path| path.to_string_lossy().into_owned());
        self.language = Language::from_path(name);
        self.line_states = match self.language {
            Some(language) => highlight::line_states(&self.document.lines, language),
            None => Vec::new(),
        };
        self.blocks = OnceCell::new();
        self.renamed = true;
    }
}