curd-editor 0.3.0

A tiny terminal code editor with line numbers, folding and snippets
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
use std::io::{stdout, Write};
use std::path::Path;

use crossterm::{
    cursor::{Hide, MoveTo, Show},
    event::{read, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
    queue,
    style::{Attribute, Print, SetAttribute},
    terminal::{Clear, ClearType},
};

use crate::document::Document;
use crate::folds::{self, Folds};
use crate::snippets::Language;
use crate::terminal::Terminal;

#[cfg(test)]
mod tests;

const TAB: &str = "    ";

pub struct Editor {
    document: Document,
    /// Decides which snippets are available. `None` for unknown file types.
    language: Option<Language>,
    folds: Folds,
    should_quit: bool,
    cursor_x: usize,
    cursor_y: usize,
    row_offset: usize,
    col_offset: usize,
    /// Shown in the status bar until the next key press.
    message: String,
    /// True after Ctrl+Q was pressed once with unsaved changes.
    quit_pending: bool,
}

impl Editor {
    pub fn new(document: Document) -> Self {
        Self {
            language: document.path.as_deref().and_then(Language::from_path),
            document,
            folds: Folds::default(),
            should_quit: false,
            cursor_x: 0,
            cursor_y: 0,
            row_offset: 0,
            col_offset: 0,
            message: String::new(),
            quit_pending: false,
        }
    }

    pub fn run(&mut self) -> std::io::Result<()> {
        while !self.should_quit {
            let (width, height) = Terminal::size()?;
            // The last screen row is the status bar.
            let text_rows = height.saturating_sub(1);
            self.scroll(width.saturating_sub(self.gutter_width()), text_rows);
            self.draw(width, text_rows)?;
            // Any event (including a window resize) triggers a redraw.
            match read()? {
                Event::Key(key) => self.handle_key(key),
                Event::Paste(text) => self.paste(&text),
                _ => {}
            }
        }
        Ok(())
    }

    fn handle_key(&mut self, key: KeyEvent) {
        // Windows reports both key press and key release; only act on press.
        if key.kind == KeyEventKind::Release {
            return;
        }
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);

        // Messages and the quit confirmation only last until the next key.
        let quit_was_pending = std::mem::take(&mut self.quit_pending);
        self.message.clear();

        match key.code {
            KeyCode::Char('q') if ctrl => {
                if self.document.dirty && !quit_was_pending {
                    self.quit_pending = true;
                    self.message = "Unsaved changes! Ctrl+Q again to quit".into();
                } else {
                    self.should_quit = true;
                }
            }
            KeyCode::Char('s') if ctrl => self.save(),
            KeyCode::Char('k') if ctrl => self.toggle_fold(),
            KeyCode::Char(c) if !ctrl && !alt => self.type_char(c),
            KeyCode::Tab => self.tab(),
            KeyCode::Enter => {
                let indent = self.indent_for_new_line();
                self.insert_newline();
                indent.chars().for_each(|c| self.insert_char(c));
            }
            KeyCode::Backspace => self.backspace(),
            KeyCode::Delete => self.delete(),
            KeyCode::Up => {
                if let Some(y) = self.folds.prev_visible(self.cursor_y) {
                    self.cursor_y = y;
                }
            }
            KeyCode::Down => {
                if let Some(y) = self.folds.next_visible(self.cursor_y, self.document.len()) {
                    self.cursor_y = y;
                }
            }
            KeyCode::Left => {
                if self.cursor_x > 0 {
                    self.cursor_x -= 1;
                }
            }
            KeyCode::Right => {
                if self.cursor_x < self.document.line_len(self.cursor_y) {
                    self.cursor_x += 1;
                }
            }
            KeyCode::Home => self.cursor_x = 0,
            KeyCode::End => self.cursor_x = self.document.line_len(self.cursor_y),
            _ => {}
        }

        self.clamp_cursor_x();
    }

    /// Moving to a shorter line: don't leave the cursor past its end.
    fn clamp_cursor_x(&mut self) {
        let len = self.document.line_len(self.cursor_y);
        if self.cursor_x > len {
            self.cursor_x = len;
        }
    }

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

    /// Inserts `c` at the cursor.
    fn insert_char(&mut self, c: char) {
        // Editing a collapsed line opens it, so nothing changes out of sight.
        self.folds.unfold(self.cursor_y);
        self.document.insert_char(self.cursor_x, self.cursor_y, c);
        self.cursor_x += 1;
    }

    /// Splits the line at the cursor and moves to the start of the new line.
    fn insert_newline(&mut self) {
        self.folds.unfold(self.cursor_y);
        self.document.insert_newline(self.cursor_x, self.cursor_y);
        self.folds.shift_after(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.
    fn backspace(&mut self) {
        self.folds.unfold(self.cursor_y);
        if self.cursor_x > 0 {
            self.cursor_x -= 1;
            self.document.delete_char(self.cursor_x, self.cursor_y);
        } 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.document.delete_char(self.cursor_x, self.cursor_y);
            self.folds.shift_after(self.cursor_y, -1);
        }
    }

    /// Deletes the character under the cursor, or joins the next line onto
    /// this one when the cursor is at the end of a line.
    fn delete(&mut self) {
        self.folds.unfold(self.cursor_y);
        if self.cursor_x < self.document.line_len(self.cursor_y) {
            self.document.delete_char(self.cursor_x, self.cursor_y);
        } else if self.cursor_y + 1 < self.document.len() {
            self.folds.unfold(self.cursor_y + 1);
            self.document.delete_char(self.cursor_x, self.cursor_y);
            self.folds.shift_after(self.cursor_y, -1);
        }
    }

    /// 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.
    fn type_char(&mut self, c: char) {
        if c == '}' && self.cursor_x > 0 && self.text_before_cursor().chars().all(|c| c == ' ') {
            for _ in 0..TAB.len().min(self.cursor_x) {
                self.backspace();
            }
        }
        self.insert_char(c);
    }

    /// Pasted text goes in exactly as it is: no auto-indent, no snippets.
    fn paste(&mut self, text: &str) {
        self.quit_pending = false;
        self.message.clear();
        for c in text.chars() {
            match c {
                '\n' => self.insert_newline(),
                '\r' => {}
                '\t' => TAB.chars().for_each(|c| self.insert_char(c)),
                c => self.insert_char(c),
            }
        }
    }

    /// The part of the cursor line that is left of the cursor.
    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(),
        }
    }

    /// The indentation a new line should start with: the same as the current
    /// line, plus one level after an opening bracket (or `:` in Python).
    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 == Some(Language::Python),
            _ => false,
        };
        if opens_block {
            indent.push_str(TAB);
        }
        indent
    }

    /// Tab expands the word before the cursor if it is a snippet trigger,
    /// and otherwise indents.
    fn tab(&mut self) {
        let before = self.text_before_cursor();
        let word_len = before
            .chars()
            .rev()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .count();
        let word: String = before.chars().skip(before.chars().count() - word_len).collect();

        match self.language.and_then(|language| language.snippet(&word)) {
            Some(body) => {
                self.expand_snippet(word_len, body);
                self.message = format!("Expanded snippet: {word}");
            }
            None => TAB.chars().for_each(|c| self.insert_char(c)),
        }
    }

    /// Replaces the `trigger_len` characters before the cursor with `body`.
    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;
        }
    }

    // ---- Folding -------------------------------------------------------

    /// Ctrl+K: expands the fold on the cursor line, or else collapses the
    /// `{ ... }` block that starts on, or surrounds, the cursor line.
    fn toggle_fold(&mut self) {
        if self.folds.unfold(self.cursor_y) {
            self.message = "Unfolded".into();
            return;
        }
        let lines = &self.document.lines;
        let block = folds::block_end(lines, self.cursor_y)
            .map(|end| (self.cursor_y, end))
            .or_else(|| folds::enclosing_block(lines, self.cursor_y));
        match block {
            Some((start, end)) => {
                self.folds.fold(start, end);
                self.cursor_y = start;
                self.message = format!("Folded {} lines (Ctrl+K unfolds)", end - start);
            }
            None => self.message = "No { } block to fold here".into(),
        }
    }

    fn save(&mut self) {
        self.message = match self.document.save() {
            Ok(()) => format!("Saved {} lines", self.document.len()),
            Err(error) => format!("Could not save: {error}"),
        };
    }

    // ---- Drawing -------------------------------------------------------

    /// Width of the line-number column, including the fold marker after the
    /// number. An empty document shows the welcome screen with no gutter.
    fn gutter_width(&self) -> usize {
        if self.document.is_empty() {
            0
        } else {
            self.document.len().to_string().len() + 1
        }
    }

    /// Moves the view so the cursor is inside a text area of `width` x `height`.
    fn scroll(&mut self, width: usize, height: usize) {
        // The top line may have been hidden by a fold or removed by an edit.
        self.row_offset = self.folds.header_of(self.row_offset.min(self.cursor_y));
        while height > 0 && self.folds.rows_between(self.row_offset, self.cursor_y) >= height {
            match self.folds.next_visible(self.row_offset, self.document.len()) {
                Some(next) => self.row_offset = next,
                None => break,
            }
        }
        if self.cursor_x < self.col_offset {
            self.col_offset = self.cursor_x;
        }
        if width > 0 && self.cursor_x >= self.col_offset + width {
            self.col_offset = self.cursor_x - width + 1;
        }
    }

    /// The text shown for line `y`. A collapsed block shows its first and
    /// last line joined by `...`, like `fn main() { ... }`.
    fn display_line(&self, y: usize) -> String {
        let line = &self.document.lines[y];
        match self.folds.end_of(y) {
            Some(end) => format!("{line} ... {}", self.document.lines[end].trim()),
            None => line.clone(),
        }
    }

    /// The status bar text, exactly `width` characters wide: the file name
    /// (or a message) on the left, the cursor position on the right.
    fn status_line(&self, width: usize) -> String {
        let left = if !self.message.is_empty() {
            self.message.clone()
        } else {
            // Just the file name: a full path rarely fits.
            let name = self
                .document
                .path
                .as_deref()
                .and_then(|path| Path::new(path).file_name())
                .and_then(|name| name.to_str())
                .unwrap_or("[No Name]");
            let modified = if self.document.dirty { " [modified]" } else { "" };
            format!("{name}{modified}")
        };
        let right = format!("Ln {}, Col {}", self.cursor_y + 1, self.cursor_x + 1);

        let left_len = left.chars().count();
        let line = if left_len + 1 + right.len() <= width {
            let gap = width - left_len - right.len();
            format!("{left}{}{right}", " ".repeat(gap))
        } else {
            // Not enough room for both: the left part matters more.
            left
        };
        let mut line: String = line.chars().take(width).collect();
        let padding = width - line.chars().count();
        line.push_str(&" ".repeat(padding));
        line
    }

    /// Draws `text_rows` rows of text followed by the status bar.
    fn draw(&self, width: usize, text_rows: usize) -> std::io::Result<()> {
        let mut out = stdout();
        let gutter = self.gutter_width();
        let text_width = width.saturating_sub(gutter);

        queue!(out, Hide, Clear(ClearType::All), MoveTo(0, 0))?;

        // Collapsed lines are skipped, so walk the visible lines one by one.
        let mut next_line = Some(self.row_offset).filter(|y| *y < self.document.len());
        for row in 0..text_rows {
            if let Some(y) = next_line {
                // Line number, then `+` on a collapsed block.
                let marker = if self.folds.end_of(y).is_some() { '+' } else { ' ' };
                let number = format!("{:>1$}{marker}", y + 1, gutter - 1);
                let visible: String = self
                    .display_line(y)
                    .chars()
                    .skip(self.col_offset)
                    .take(text_width)
                    .collect();
                queue!(
                    out,
                    SetAttribute(Attribute::Dim),
                    Print(number),
                    SetAttribute(Attribute::Reset),
                    Print(visible)
                )?;
                next_line = self.folds.next_visible(y, self.document.len());
            } else if self.document.is_empty() && row == text_rows / 3 {
                let msg = concat!("curd editor -- v", env!("CARGO_PKG_VERSION"));
                let padding = width.saturating_sub(msg.len()) / 2;
                queue!(out, Print(format!("~{}{}", " ".repeat(padding), msg)))?;
            } else {
                queue!(out, Print("~"))?;
            }
            queue!(out, Print("\r\n"))?;
        }

        queue!(
            out,
            SetAttribute(Attribute::Reverse),
            Print(self.status_line(width)),
            SetAttribute(Attribute::Reset)
        )?;

        let screen_x = (gutter + self.cursor_x - self.col_offset) as u16;
        let screen_y = self.folds.rows_between(self.row_offset, self.cursor_y) as u16;
        queue!(out, MoveTo(screen_x, screen_y), Show)?;
        out.flush()?;
        Ok(())
    }
}