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
//! What the editor knows about the code: foldable blocks, and what the
//! language server says.

use super::*;

impl Editor {
    // ---- Folding -------------------------------------------------------

    /// Where the foldable blocks are: by indentation in Python, by braces
    /// everywhere else. Worked out once per edit and then reused.
    pub(super) fn blocks(&self) -> &Blocks {
        self.blocks.get_or_init(|| {
            if self.language.is_some_and(Language::blocks_by_indent) {
                Blocks::by_indent(&self.document.lines)
            } else {
                Blocks::by_braces(&self.document.lines)
            }
        })
    }

    /// Expands the fold on the cursor line, or else collapses the block that
    /// starts on, or surrounds, the cursor line.
    pub(super) fn toggle_fold(&mut self) {
        if self.folds.unfold(self.cursor_y) {
            self.message = "Unfolded".into();
            return;
        }
        let blocks = self.blocks();
        let block = blocks
            .end(self.cursor_y)
            .map(|end| (self.cursor_y, end))
            .or_else(|| blocks.enclosing(self.cursor_y));
        match block {
            Some((start, end)) => {
                self.folds.fold(start, end);
                self.cursor_y = start;
                self.message = format!("Folded {} lines", end - start);
            }
            None => self.message = "No block to fold here".into(),
        }
    }

    /// Expands everything if anything is folded; otherwise collapses every
    /// outermost block.
    pub(super) fn toggle_all_folds(&mut self) {
        if !self.folds.is_empty() {
            self.folds.clear();
            self.message = "Unfolded all".into();
            return;
        }
        let blocks = self.blocks().top_level();
        for (start, end) in &blocks {
            self.folds.fold(*start, *end);
        }
        // The cursor may now be inside a collapsed block.
        self.cursor_y = self.folds.header_of(self.cursor_y);
        self.message = match blocks.len() {
            0 => "No blocks to fold".into(),
            count => format!("Folded {count} blocks"),
        };
    }

    // ---- Language server -----------------------------------------------

    /// Sends any edits the language server has not seen yet.
    pub fn sync_lsp(&mut self) {
        if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
            let lines = &self.document.lines;
            lsp.borrow_mut().flush(path, &|| lines.join("\n"));
        }
    }

    /// Sends a question about the cursor position (hover, definition).
    /// The answer arrives later through `apply_reply`.
    pub(super) fn ask_lsp(&mut self, question: fn(&mut Client, &str, usize, usize)) {
        let (line, units) = self.lsp_position(self.cursor_x, self.cursor_y);
        // The server must know about the latest edits before it answers.
        self.sync_lsp();
        match (&self.lsp, &self.abs_path) {
            (Some(lsp), Some(path)) => {
                let mut lsp = lsp.borrow_mut();
                if lsp.is_ready() {
                    question(&mut lsp, path, line, units);
                } else {
                    self.message = format!("{} is still starting", lsp.name);
                }
            }
            _ => self.message = "No language server for this file".into(),
        }
    }

    /// Acts on something the language server told us.
    pub fn apply_reply(&mut self, reply: Reply) {
        match reply {
            Reply::Ready => {
                if let Some(lsp) = &self.lsp {
                    self.message = format!("{} ready", lsp.borrow().name);
                }
            }
            Reply::Diagnostics(diagnostics) => self.diagnostics = diagnostics,
            Reply::Hover(lines) if lines.is_empty() => {
                self.message = "Nothing to show here".into();
            }
            Reply::Hover(lines) => self.info = lines,
            Reply::Definition(None) => self.message = "No definition found".into(),
            Reply::Definition(Some(location)) => self.go_to(location),
            Reply::Tokens(tokens) => {
                self.highlights = Highlights::new(&tokens, &self.document.lines, self.encoding());
            }
            Reply::Completion(id, items) => {
                // Only wanted if it answers the newest request and the
                // cursor is still in the word it was asked for.
                let word = (self.word_start(), self.cursor_y);
                if self.completion_request != Some(id)
                    || self.completion_word != Some(word)
                    || self.prompt.is_some()
                {
                    return;
                }
                match items {
                    Some(items) => {
                        self.completion = Some(Completion {
                            items,
                            shown: Vec::new(),
                            selected: 0,
                            moved: false,
                            start: word.0,
                            y: word.1,
                        });
                        self.refilter();
                    }
                    // The server gave up because more was typed meanwhile.
                    None => {
                        self.completion_word = None;
                        self.ask_completion(false);
                    }
                }
            }
            Reply::Nothing => {}
        }
    }

    /// Jumps to a definition, if it is in the open file.
    pub(super) fn go_to(&mut self, location: Location) {
        let in_this_file = [&self.abs_path, &self.document.path]
            .iter()
            .any(|path| path.as_deref() == Some(location.path.as_str()));
        if !in_this_file || location.line >= self.document.len() {
            // Only one file can be open, so say where it is instead.
            let name = Path::new(&location.path)
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or(&location.path);
            self.message = format!("Defined in {name}, line {}", location.line + 1);
            return;
        }
        self.folds.reveal(location.line);
        self.cursor_y = location.line;
        self.cursor_x = self
            .encoding()
            .to_chars(&self.document.lines[location.line], location.units);
        self.message = format!("Jumped to line {}", location.line + 1);
    }

    /// The first problem reported on line `y`, if any. Errors come before
    /// warnings when a line has both.
    pub(super) fn diagnostic_on(&self, y: usize) -> Option<&Diagnostic> {
        self.diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.line == y)
            .min_by_key(|diagnostic| match diagnostic.severity {
                Severity::Error => 0,
                Severity::Warning => 1,
                Severity::Info => 2,
            })
    }
}