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
//! Starting language servers and passing on what they say.

use super::*;

impl Workspace {
    // ---- Language servers ---------------------------------------------

    /// Puts a language server in charge of `editor`'s file, starting one
    /// unless a server for the same language and project is running.
    pub(super) fn attach_lsp(&mut self, editor: &mut Editor) {
        let (Some(events), Some(path)) = (&self.events, editor.abs_path.clone()) else {
            return;
        };
        let setting = self.lsp_setting.as_deref();
        let Some(spec) = ServerSpec::for_file(editor.language, &path, setting) else {
            return;
        };
        let folder = Path::new(&path).parent().unwrap_or(Path::new("/"));
        let root = find_root(folder, spec.root_markers);
        let key = format!("{} {:?} {}", spec.command, spec.args, root.display());

        let client = match self.servers.iter().find(|server| server.key == key) {
            Some(server) => server.client.clone(),
            None => {
                let id = self.next_server;
                self.next_server += 1;
                let events = events.clone();
                let forward = move |message| {
                    let _ = events.send(AppEvent::Lsp(id, message));
                };
                match Client::start(&spec, &root, forward) {
                    Ok(client) => {
                        editor.message = format!("Starting {}...", client.name);
                        let client = Rc::new(RefCell::new(client));
                        self.servers.push(Server {
                            id,
                            key,
                            client: client.clone(),
                        });
                        client
                    }
                    Err(_) => {
                        editor.message =
                            format!("No language server: {} not found", spec.command);
                        return;
                    }
                }
            }
        };
        let lines = &editor.document.lines;
        client
            .borrow_mut()
            .open(&path, spec.language_id, &|| lines.join("\n"));
        editor.attach_lsp(client);
    }

    /// Handles a message from language server `id`, or its exit.
    pub(super) fn handle_lsp(&mut self, id: usize, message: Option<Value>) {
        let Some(position) = self.servers.iter().position(|server| server.id == id) else {
            return;
        };
        let client = self.servers[position].client.clone();
        let uses_it = |editor: &Editor| editor.lsp.as_ref().is_some_and(|lsp| Rc::ptr_eq(lsp, &client));

        let Some(message) = message else {
            // The server exited: carry on as a plain editor.
            let name = client.borrow().name.clone();
            self.servers.remove(position);
            for (index, editor) in self.editors.iter_mut().enumerate() {
                if uses_it(editor) {
                    editor.detach_lsp();
                    if index == self.active {
                        editor.message = format!("Language server {name} stopped");
                    }
                }
            }
            return;
        };

        let editors = &self.editors;
        let text_of = |path: &str| {
            editors
                .iter()
                .find(|editor| editor.abs_path.as_deref() == Some(path))
                .map(|editor| editor.document.lines.join("\n"))
                .unwrap_or_default()
        };
        let (path, reply) = client.borrow_mut().handle(&message, &text_of);
        let in_front = self.editors.get(self.active).and_then(|editor| editor.abs_path.clone());

        match reply {
            Reply::Nothing => {}
            Reply::Ready => {
                if let Some(editor) = self.editors.get_mut(self.active).filter(|editor| uses_it(editor))
                {
                    editor.apply_reply(Reply::Ready);
                }
            }
            // Answers to a question only matter while the file that asked
            // is still in front.
            Reply::Hover(_) | Reply::Definition(_) if path != in_front => {}
            Reply::Definition(Some(mut location)) => {
                // A definition in another file: open that file, then jump.
                if Some(&location.path) != in_front.as_ref()
                    && Path::new(&location.path).is_file()
                    && self.open(Path::new(&location.path))
                    && let Some(opened) = self.editors[self.active].abs_path.clone()
                {
                    location.path = opened;
                }
                self.editors[self.active].apply_reply(Reply::Definition(Some(location)));
            }
            reply => {
                if let Some(editor) = self
                    .editors
                    .iter_mut()
                    .find(|editor| editor.abs_path.is_some() && editor.abs_path == path)
                {
                    editor.apply_reply(reply);
                }
            }
        }
    }

    /// Asks git, on a background thread, what state the project is in and
    /// what each open file looked like in the last commit. The answers
    /// arrive later as `AppEvent::Git` and `AppEvent::Committed`.
    pub(super) fn refresh_git(&self) {
        if let Some(events) = &self.events {
            let events = events.clone();
            let root = self.tree.root().to_path_buf();
            let open: Vec<String> = self
                .editors
                .iter()
                .filter_map(|editor| editor.abs_path.clone())
                .collect();
            std::thread::spawn(move || {
                let _ = events.send(AppEvent::Git(git::load(&root)));
                for path in open {
                    let lines = git::committed_lines(Path::new(&path));
                    let _ = events.send(AppEvent::Committed(path, lines));
                }
            });
        }
    }
}