curd-editor 0.5.0

A small terminal code editor with language-server support, folding and snippets
//! Colours for the text, as worked out by the language server.
//!
//! The editor has no grammar for any language. The server sends "semantic
//! tokens": this range is a keyword, that one a function name. They are
//! kept here per line, in character columns, and nudged along as the user
//! types so the colours stay put until the server's next answer arrives.

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

#[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 coloured stretch of one line: characters `start..end`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Token {
    pub start: usize,
    pub end: usize,
    pub kind: 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,
            }));
        }
    }
}