curd-editor 0.6.0

A small terminal code editor: projects with a file tree, git status, tabs, quick open and language-server support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Colours for the text, from two sources, the same way VS Code does it.
//!
//! - A small built-in scanner (`lex_line`) colours keywords, strings,
//!   comments and numbers. It knows very little, but it is instant: colours
//!   are there the moment a file opens and on every key press.
//! - The language server sends "semantic tokens": this range is a keyword,
//!   that one a function name. It understands the code properly but answers
//!   a moment later, so its colours are laid over the scanner's when they
//!   arrive. They are kept here per line, in character columns, and nudged
//!   along as the user types.

use crate::lsp::{Encoding, SemanticToken};
use crate::snippets::Language;

#[cfg(test)]
mod tests;

/// What a piece of code is. Each kind gets its own colour.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TokenKind {
    Keyword,
    Function,
    Type,
    String,
    Constant,
    Comment,
    Macro,
    Namespace,
}

impl TokenKind {
    /// The kind for one of LSP's token type names. Servers add names of
    /// their own, so anything unknown (and plain variables) gets no colour.
    pub fn from_name(name: &str) -> Option<Self> {
        Some(match name {
            "keyword" | "modifier" | "selfKeyword" | "selfTypeKeyword" => Self::Keyword,
            "function" | "method" | "member" => Self::Function,
            "type" | "class" | "struct" | "enum" | "interface" | "union" | "typeParameter"
            | "typeAlias" | "builtinType" | "concept" => Self::Type,
            "string" | "char" | "character" | "regexp" | "escapeSequence" | "formatSpecifier" => {
                Self::String
            }
            "number" | "boolean" | "enumMember" | "const" | "constParameter" => Self::Constant,
            "comment" => Self::Comment,
            "macro" | "decorator" | "attribute" | "derive" | "builtinAttribute" | "lifetime"
            | "label" => Self::Macro,
            "namespace" | "module" => Self::Namespace,
            _ => return None,
        })
    }
}

/// A stretch of one line, characters `start..end`, and what it is.
/// `None` means the server looked at it and it gets no colour (a plain
/// variable, say), which overrides the built-in scanner's guess.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Token {
    pub start: usize,
    pub end: usize,
    pub kind: Option<TokenKind>,
}

/// The coloured stretches of every line of the document.
#[derive(Default)]
pub struct Highlights {
    lines: Vec<Vec<Token>>,
}

impl Highlights {
    /// Builds the per-line table from the server's answer, converting its
    /// columns (counted in `encoding` units) to character columns.
    pub fn new(tokens: &[SemanticToken], lines: &[String], encoding: Encoding) -> Self {
        let mut table = vec![Vec::new(); lines.len()];
        for token in tokens {
            let Some(line) = lines.get(token.line) else {
                continue;
            };
            let start = encoding.to_chars(line, token.start);
            let end = encoding.to_chars(line, token.start + token.length);
            if start < end {
                table[token.line].push(Token {
                    start,
                    end,
                    kind: token.kind,
                });
            }
        }
        Self { lines: table }
    }

    /// The coloured stretches of line `y`, left to right.
    pub fn on(&self, y: usize) -> &[Token] {
        self.lines.get(y).map_or(&[], Vec::as_slice)
    }

    /// A character was typed at column `x` of line `y`.
    pub fn inserted(&mut self, x: usize, y: usize) {
        for token in self.lines.get_mut(y).into_iter().flatten() {
            if token.start >= x {
                token.start += 1;
                token.end += 1;
            } else if token.end >= x {
                // Typing inside or right after a word keeps its colour.
                token.end += 1;
            }
        }
    }

    /// The character at column `x` of line `y` was deleted.
    pub fn deleted(&mut self, x: usize, y: usize) {
        if let Some(tokens) = self.lines.get_mut(y) {
            for token in tokens.iter_mut() {
                if token.start > x {
                    token.start -= 1;
                    token.end -= 1;
                } else if token.end > x {
                    token.end -= 1;
                }
            }
            tokens.retain(|token| token.start < token.end);
        }
    }

    /// Line `y` was split at column `x`; what was right of `x` is now the
    /// start of a new line below.
    pub fn split(&mut self, x: usize, y: usize) {
        let Some(tokens) = self.lines.get_mut(y) else {
            return;
        };
        let mut below = Vec::new();
        for token in tokens.iter_mut() {
            if token.end > x {
                below.push(Token {
                    start: token.start.saturating_sub(x),
                    end: token.end - x,
                    kind: token.kind,
                });
                token.end = token.end.min(x);
            }
        }
        tokens.retain(|token| token.start < token.end);
        self.lines.insert(y + 1, below);
    }

    /// Line `y + 1` was joined onto the end of line `y`, which was `len`
    /// characters long.
    pub fn joined(&mut self, y: usize, len: usize) {
        if y + 1 < self.lines.len() {
            let below = self.lines.remove(y + 1);
            self.lines[y].extend(below.into_iter().map(|token| Token {
                start: token.start + len,
                end: token.end + len,
                kind: token.kind,
            }));
        }
    }
}

// ---- The built-in scanner -----------------------------------------------

/// What a line starts inside of: ordinary code, or a comment or string that
/// was opened on an earlier line and not closed yet.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum LineState {
    #[default]
    Code,
    Comment,
    Text(Delimiter),
}

/// What closes a string that can run over several lines.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Delimiter {
    /// `"`: an ordinary Rust string.
    Double,
    /// A backtick: JavaScript templates and Go raw strings.
    Backtick,
    /// Three of this quote character: Python.
    Triple(char),
    /// `"` followed by this many `#`: Rust raw strings.
    Raw(usize),
}

/// The words the scanner knows for one language.
struct Syntax {
    keywords: &'static [&'static str],
    constants: &'static [&'static str],
    types: &'static [&'static str],
    line_comment: &'static str,
    /// True if `/* ... */` is a comment.
    block_comments: bool,
}

impl Syntax {
    fn of(language: Language) -> &'static Self {
        match language {
            Language::Rust => &Self {
                keywords: &[
                    "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else",
                    "enum", "extern", "fn", "for", "if", "impl", "in", "let", "loop", "match",
                    "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static",
                    "struct", "super", "trait", "type", "unsafe", "use", "where", "while",
                ],
                constants: &["true", "false"],
                types: &[
                    "bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize", "i8",
                    "i16", "i32", "i64", "i128", "isize", "f32", "f64",
                ],
                line_comment: "//",
                block_comments: true,
            },
            Language::Python => &Self {
                keywords: &[
                    "and", "as", "assert", "async", "await", "break", "class", "continue", "def",
                    "del", "elif", "else", "except", "finally", "for", "from", "global", "if",
                    "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise",
                    "return", "self", "try", "while", "with", "yield",
                ],
                constants: &["True", "False", "None"],
                types: &[
                    "bool", "bytes", "dict", "float", "int", "list", "object", "set", "str",
                    "tuple",
                ],
                line_comment: "#",
                block_comments: false,
            },
            Language::JavaScript => &Self {
                keywords: &[
                    "abstract", "as", "async", "await", "break", "case", "catch", "class",
                    "const", "continue", "debugger", "declare", "default", "delete", "do",
                    "else", "enum", "export", "extends", "finally", "for", "from", "function",
                    "if", "implements", "import", "in", "instanceof", "interface", "let",
                    "namespace", "new", "of", "private", "protected", "public", "readonly",
                    "return", "static", "super", "switch", "this", "throw", "try", "type",
                    "typeof", "var", "void", "while", "with", "yield",
                ],
                constants: &["true", "false", "null", "undefined", "NaN"],
                types: &["any", "boolean", "never", "number", "object", "string", "unknown"],
                line_comment: "//",
                block_comments: true,
            },
            Language::C => &Self {
                keywords: &[
                    "auto", "break", "case", "catch", "class", "const", "constexpr", "continue",
                    "default", "delete", "do", "else", "enum", "extern", "for", "goto", "if",
                    "inline", "namespace", "new", "operator", "override", "private",
                    "protected", "public", "register", "return", "sizeof", "static", "struct",
                    "switch", "template", "this", "throw", "try", "typedef", "typename",
                    "union", "using", "virtual", "volatile", "while",
                ],
                constants: &["true", "false", "NULL", "nullptr"],
                types: &[
                    "bool", "char", "double", "float", "int", "long", "short", "signed",
                    "size_t", "unsigned", "void",
                ],
                line_comment: "//",
                block_comments: true,
            },
            Language::Go => &Self {
                keywords: &[
                    "break", "case", "chan", "const", "continue", "default", "defer", "else",
                    "fallthrough", "for", "func", "go", "goto", "if", "import", "interface",
                    "map", "package", "range", "return", "select", "struct", "switch", "type",
                    "var",
                ],
                constants: &["true", "false", "nil", "iota"],
                types: &[
                    "any", "bool", "byte", "error", "float32", "float64", "int", "int8",
                    "int16", "int32", "int64", "rune", "string", "uint", "uint8", "uint16",
                    "uint32", "uint64",
                ],
                line_comment: "//",
                block_comments: true,
            },
        }
    }
}

fn is_word(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

/// Where the comment or string that `state` is inside of ends, looking
/// from `from`. `None` if it runs past the end of this line.
fn closing(chars: &[char], from: usize, state: LineState, language: Language) -> Option<usize> {
    let at = |i: usize, c: char| chars.get(i) == Some(&c);
    let escapes = match state {
        LineState::Text(Delimiter::Raw(_)) => false,
        LineState::Text(Delimiter::Backtick) => language != Language::Go,
        _ => true,
    };
    let mut i = from;
    while i < chars.len() {
        let end = match state {
            LineState::Code => return Some(from),
            LineState::Comment => (at(i, '*') && at(i + 1, '/')).then_some(i + 2),
            LineState::Text(Delimiter::Double) => at(i, '"').then_some(i + 1),
            LineState::Text(Delimiter::Backtick) => at(i, '`').then_some(i + 1),
            LineState::Text(Delimiter::Triple(quote)) => {
                (0..3).all(|k| at(i + k, quote)).then_some(i + 3)
            }
            LineState::Text(Delimiter::Raw(hashes)) => {
                (at(i, '"') && (1..=hashes).all(|k| at(i + k, '#'))).then_some(i + 1 + hashes)
            }
        };
        if end.is_some() {
            return end;
        }
        // A backslash hides the next character, so `\"` does not end a string.
        if escapes && state != LineState::Comment && chars[i] == '\\' {
            i += 1;
        }
        i += 1;
    }
    None
}

/// The end of a one-line string or character that opens at `start` with
/// `quote`. An unclosed one runs to the end of the line.
fn quoted_end(chars: &[char], start: usize, quote: char) -> usize {
    let mut i = start + 1;
    while i < chars.len() {
        match chars[i] {
            '\\' => i += 1,
            c if c == quote => return i + 1,
            _ => {}
        }
        i += 1;
    }
    chars.len()
}

/// Colours one line with the built-in scanner, adding what it finds to
/// `out`. `state` says what the line starts inside of; the return value is
/// the state for the line after it.
pub fn lex_line(
    line: &str,
    language: Language,
    state: LineState,
    out: &mut Vec<Token>,
) -> LineState {
    let syntax = Syntax::of(language);
    let chars: Vec<char> = line.chars().collect();
    let len = chars.len();
    let at = |i: usize, c: char| chars.get(i) == Some(&c);
    let mut push = |start: usize, end: usize, kind: TokenKind| {
        if start < end {
            out.push(Token {
                start,
                end,
                kind: Some(kind),
            });
        }
    };
    // The comment or string we are inside of, and where it started.
    let mut open = state;
    let mut open_start = 0;
    let mut i = 0;

    loop {
        if open != LineState::Code {
            let kind = match open {
                LineState::Comment => TokenKind::Comment,
                _ => TokenKind::String,
            };
            match closing(&chars, i, open, language) {
                Some(end) => {
                    push(open_start, end, kind);
                    i = end;
                    open = LineState::Code;
                }
                None => {
                    push(open_start, len, kind);
                    return open;
                }
            }
        }
        if i >= len {
            return LineState::Code;
        }
        let c = chars[i];

        if c.is_whitespace() {
            i += 1;
        } else if syntax.line_comment.chars().enumerate().all(|(k, c)| at(i + k, c)) {
            push(i, len, TokenKind::Comment);
            return LineState::Code;
        } else if syntax.block_comments && c == '/' && at(i + 1, '*') {
            (open, open_start) = (LineState::Comment, i);
            i += 2;
        } else if c == '"' || c == '\'' || c == '`' {
            // Strings: which quotes exist, and which can span lines,
            // depends on the language.
            let multi_line = match (language, c) {
                (Language::Rust, '"') => Some((Delimiter::Double, 1)),
                (Language::Python, _) if c != '`' && at(i + 1, c) && at(i + 2, c) => {
                    Some((Delimiter::Triple(c), 3))
                }
                (Language::JavaScript | Language::Go, '`') => Some((Delimiter::Backtick, 1)),
                _ => None,
            };
            if let Some((delimiter, width)) = multi_line {
                (open, open_start) = (LineState::Text(delimiter), i);
                i += width;
            } else if c == '`' {
                i += 1;
            } else if language == Language::Rust && !at(i + 1, '\\') && !at(i + 2, '\'') {
                // Rust: `'a` with no closing quote is a lifetime, not a character.
                let end = (i + 1..len).find(|j| !is_word(chars[*j])).unwrap_or(len);
                push(i, end, TokenKind::Macro);
                i = end.max(i + 1);
            } else {
                let end = quoted_end(&chars, i, c);
                push(i, end, TokenKind::String);
                i = end;
            }
        } else if c.is_ascii_digit() {
            let mut end = i + 1;
            while end < len
                && (is_word(chars[end])
                    || (chars[end] == '.' && chars.get(end + 1).is_some_and(char::is_ascii_digit)))
            {
                end += 1;
            }
            push(i, end, TokenKind::Constant);
            i = end;
        } else if is_word(c) {
            let mut end = (i..len).find(|j| !is_word(chars[*j])).unwrap_or(len);
            let word: String = chars[i..end].iter().collect();

            // Rust raw strings start with what looks like a word: r"..." or br#"..."#.
            let raw_hashes = (end..len).take_while(|j| chars[*j] == '#').count();
            if language == Language::Rust
                && (word == "r" || word == "br")
                && at(end + raw_hashes, '"')
            {
                (open, open_start) = (LineState::Text(Delimiter::Raw(raw_hashes)), i);
                i = end + raw_hashes + 1;
                continue;
            }

            let kind = if syntax.keywords.contains(&word.as_str()) {
                Some(TokenKind::Keyword)
            } else if syntax.constants.contains(&word.as_str()) {
                Some(TokenKind::Constant)
            } else if syntax.types.contains(&word.as_str()) {
                Some(TokenKind::Type)
            } else if language == Language::Rust && at(end, '!') && !at(end + 1, '=') {
                // A macro call such as println!
                end += 1;
                Some(TokenKind::Macro)
            } else if at(end, '(') {
                Some(TokenKind::Function)
            } else if c.is_uppercase() {
                // By convention: SHOUTING is a constant, Capitalised a type.
                let shouting = word.len() > 1 && !word.chars().any(char::is_lowercase);
                Some(if shouting { TokenKind::Constant } else { TokenKind::Type })
            } else {
                None
            };
            if let Some(kind) = kind {
                push(i, end, kind);
            }
            i = end;
        } else if (c == '@' && language == Language::Python)
            || (c == '#' && language == Language::C)
        {
            // Python decorators and C preprocessor lines like #include.
            let end = (i + 1..len).find(|j| !is_word(chars[*j])).unwrap_or(len);
            push(i, end, TokenKind::Macro);
            i = end.max(i + 1);
        } else if c == '#' && language == Language::Rust && (at(i + 1, '[') || at(i + 1, '!')) {
            // A Rust attribute such as #[derive(Debug)].
            let end = (i..len).find(|j| chars[*j] == ']').map_or(len, |j| j + 1);
            push(i, end, TokenKind::Macro);
            i = end;
        } else {
            i += 1;
        }
    }
}

/// What each line of the file starts inside of. Finding this means scanning
/// the file from the top, so the editor keeps the answer and updates it
/// with `rescan` after each edit.
pub fn line_states(lines: &[String], language: Language) -> Vec<LineState> {
    let mut states = vec![LineState::Code; lines.len()];
    rescan(&mut states, lines, language, 0, lines.len());
    states
}

/// Brings `states` up to date after an edit. Scanning starts at line
/// `first` and always covers the lines up to `last_changed`; after that it
/// stops as soon as a line starts the same way it did before, because
/// nothing below it can have changed. Most edits rescan a single line.
///
/// `states` must already have one entry per line.
pub fn rescan(
    states: &mut [LineState],
    lines: &[String],
    language: Language,
    first: usize,
    last_changed: usize,
) {
    let mut scratch = Vec::new();
    for y in first..lines.len().saturating_sub(1) {
        scratch.clear();
        let next = lex_line(&lines[y], language, states[y], &mut scratch);
        if y >= last_changed && states[y + 1] == next {
            break;
        }
        states[y + 1] = next;
    }
}