curd-editor 0.27.2

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! Opening, closing and switching between files, and making, renaming
//! and deleting them from the file tree.

use super::*;

impl Workspace {
    // ---- Opening, closing and switching files -------------------------

    /// Shows `text` in the status bar until the next key.
    pub(super) fn say(&mut self, text: String) {
        match self.editors.get_mut(self.active) {
            Some(editor) => editor.message = text,
            None => self.message = text,
        }
    }

    /// Opens the file at `path`, or brings it to the front if it is open
    /// already. A path with nothing there yet starts a new file. Returns
    /// false if it could not be opened.
    pub fn open(&mut self, path: &Path) -> bool {
        // One spelling per file, so the same file is never opened twice.
        let path = std::fs::canonicalize(path)
            .or_else(|_| std::path::absolute(path))
            .unwrap_or_else(|_| path.to_path_buf());
        let text = path.to_string_lossy().into_owned();
        let name = path.file_name().map_or_else(
            || text.clone(),
            |name| name.to_string_lossy().into_owned(),
        );

        if let Some(index) = self
            .editors
            .iter()
            .position(|editor| editor.abs_path.as_deref() == Some(text.as_str()))
        {
            self.active = index;
        } else if path.is_dir() {
            self.say(format!("{name} is a folder"));
            return false;
        } else {
            let document = match Document::open(&text) {
                Ok(document) => document,
                Err(error) => {
                    self.say(format!("Could not open {name}: {error}"));
                    return false;
                }
            };
            let mut editor = Editor::new(document);
            self.attach_lsp(&mut editor);
            // An untouched empty file made way for the first real one.
            let placeholder = self.editors.len() == 1
                && self.editors[0].document.path.is_none()
                && !self.editors[0].document.dirty;
            if placeholder {
                self.editors.clear();
            }
            self.editors.push(editor);
            self.active = self.editors.len() - 1;
            self.show_branch();
            // Find out what the new file looked like in the last commit.
            self.refresh_git();
        }
        self.focus = Focus::Editor;
        self.tree.reveal(&path);
        true
    }

    /// Brings tab `index` to the front.
    pub(super) fn activate(&mut self, index: usize) {
        if index < self.editors.len() {
            self.active = index;
            self.focus = Focus::Editor;
            if let Some(path) = self.editors[index].abs_path.clone() {
                self.tree.reveal(Path::new(&path));
            }
        }
    }

    /// Moves `step` tabs to the right (left, when negative), wrapping round.
    pub(super) fn next_tab(&mut self, step: isize) {
        let count = self.editors.len() as isize;
        if count > 0 {
            self.activate((self.active as isize + step).rem_euclid(count) as usize);
        }
    }

    /// Closes the file in front. With unsaved changes it takes a second
    /// press.
    pub(super) fn close_active(&mut self, was_pending: bool) {
        let Some(editor) = self.editors.get_mut(self.active) else {
            return;
        };
        if editor.document.dirty && !was_pending {
            self.close_pending = true;
            editor.message = "Unsaved changes! Close again to discard".into();
            return;
        }
        let editor = self.editors.remove(self.active);
        if let (Some(lsp), Some(path)) = (&editor.lsp, &editor.abs_path) {
            lsp.borrow_mut().close(path);
        }
        drop(editor);
        // A server with no files left to look after is shut down.
        self.servers.retain(|server| !server.client.borrow().is_unused());

        self.active = self.active.min(self.editors.len().saturating_sub(1));
        if self.editors.is_empty() {
            self.show_folder();
        } else {
            self.activate(self.active);
        }
    }

    /// Closes tab `index`, as a click on its close mark does. A file with
    /// unsaved changes takes a second click.
    pub(super) fn close_tab(&mut self, index: usize) {
        let pending = std::mem::take(&mut self.close_pending) && index == self.active;
        if index < self.editors.len() {
            self.activate(index);
            self.close_active(pending);
        }
    }

    /// Quits, unless files have unsaved changes: then it takes a second
    /// press.
    pub(super) fn quit(&mut self, was_pending: bool) {
        let unsaved = self.editors.iter().filter(|editor| editor.document.dirty).count();
        if unsaved == 0 || was_pending {
            self.should_quit = true;
            return;
        }
        self.quit_pending = true;
        // Show one of the files in question.
        if !self.editors[self.active].document.dirty {
            let first = self.editors.iter().position(|editor| editor.document.dirty);
            self.activate(first.unwrap_or(self.active));
        }
        self.say(match unsaved {
            1 => "Unsaved changes! Ctrl+Q again to quit".into(),
            _ => format!("Unsaved changes in {unsaved} files! Ctrl+Q again to quit"),
        });
    }

    // ---- Files and folders ----------------------------------------------

    /// The folder a new file belongs in: the one selected in the tree, or
    /// the one the selected file is in.
    pub(super) fn selected_folder(&self) -> PathBuf {
        match self.tree.selected() {
            Some(entry) if entry.is_dir => entry.path.clone(),
            Some(entry) => entry.path.parent().unwrap_or(self.tree.root()).to_path_buf(),
            None => self.tree.root().to_path_buf(),
        }
    }

    /// `n` and `f` in the tree: asks for the name of a new file or folder.
    pub(super) fn ask_new(&mut self, picker: Picker) {
        self.file_target = self.selected_folder();
        self.pick(picker, Vec::new());
    }

    /// `r` in the tree: asks for a new name for the selected file or folder.
    pub(super) fn ask_rename(&mut self) {
        let Some(entry) = self.tree.selected() else {
            return;
        };
        self.file_target = entry.path.clone();
        let name = entry.name.clone();
        self.pick(Picker::Rename, Vec::new());
        if let Some(finder) = &mut self.finder {
            finder.query = name;
        }
    }

    /// The open files that are `path` or inside it.
    pub(super) fn open_under(&self, path: &Path) -> Vec<usize> {
        (0..self.editors.len())
            .filter(|index| {
                let file = self.editors[*index].abs_path.as_deref().map(Path::new);
                file.is_some_and(|file| file.starts_with(path))
            })
            .collect()
    }

    /// Closes the open files that are `path` or inside it, whatever state
    /// they are in. Returns where each one was, below `path`.
    pub(super) fn close_under(&mut self, path: &Path) -> Vec<PathBuf> {
        let mut closed = Vec::new();
        for index in self.open_under(path).into_iter().rev() {
            let editor = self.editors.remove(index);
            if let (Some(lsp), Some(file)) = (&editor.lsp, &editor.abs_path) {
                lsp.borrow_mut().close(file);
            }
            let file = PathBuf::from(editor.abs_path.unwrap_or_default());
            closed.push(file.strip_prefix(path).unwrap_or(Path::new("")).to_path_buf());
        }
        self.servers.retain(|server| !server.client.borrow().is_unused());
        self.active = self.active.min(self.editors.len().saturating_sub(1));
        closed
    }

    /// True (after saying so) if a file that is `path` or inside it has
    /// unsaved changes.
    pub(super) fn unsaved_under(&mut self, path: &Path) -> bool {
        let unsaved = self.open_under(path).iter().any(|index| self.editors[*index].document.dirty);
        if unsaved {
            self.say("Save or close the file first: it has unsaved changes".into());
        }
        unsaved
    }

    /// Makes the new file or folder `name` (which may name folders on the
    /// way: `src/util/text.rs`) in the folder that was selected.
    pub(super) fn make_new(&mut self, name: &str, folder: bool) {
        let path = self.file_target.join(name);
        if path.exists() {
            return self.say(format!("{name} already exists"));
        }
        let made = if folder {
            std::fs::create_dir_all(&path)
        } else {
            std::fs::create_dir_all(path.parent().unwrap_or(&self.file_target))
                .and_then(|()| std::fs::write(&path, ""))
        };
        if let Err(error) = made {
            return self.say(format!("Could not make {name}: {error}"));
        }
        self.tree.refresh();
        self.refresh_git();
        if folder {
            self.tree.reveal(&path);
            self.say(format!("Made the folder {name}"));
        } else {
            self.open(&path);
        }
    }

    /// Gives the file or folder that was selected the new name `name`.
    /// Open files in it are opened again where they now are.
    pub(super) fn rename_to(&mut self, name: &str) {
        let from = self.file_target.clone();
        let to = from.parent().unwrap_or(self.tree.root()).join(name);
        if to == from || self.unsaved_under(&from) {
            return;
        }
        if to.exists() {
            return self.say(format!("{name} already exists"));
        }
        if let Err(error) = std::fs::rename(&from, &to) {
            return self.say(format!("Could not rename it: {error}"));
        }
        let moved = self.close_under(&from);
        self.tree.refresh();
        self.refresh_git();
        let focus = self.focus;
        for below in moved.into_iter().rev() {
            // A file is itself; a file in a renamed folder is below it.
            let path = if below.as_os_str().is_empty() { to.clone() } else { to.join(below) };
            self.open(&path);
        }
        self.focus = focus;
        self.tree.reveal(&to);
        self.say(format!("Renamed to {name}"));
    }

    /// `d` in the tree: deletes the selected file or folder, on the second
    /// press.
    pub(super) fn delete_selected(&mut self, pending: Option<PathBuf>) {
        let Some(entry) = self.tree.selected() else {
            return;
        };
        let (path, name, is_dir) = (entry.path.clone(), entry.name.clone(), entry.is_dir);
        if self.unsaved_under(&path) {
            return;
        }
        if pending.as_ref() != Some(&path) {
            let what = if is_dir { " and everything in it" } else { "" };
            self.say(format!("Delete {name}{what}? Press d again"));
            self.delete_pending = Some(path);
            return;
        }
        let removed = if is_dir { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) };
        if let Err(error) = removed {
            return self.say(format!("Could not delete {name}: {error}"));
        }
        self.close_under(&path);
        self.tree.refresh();
        self.refresh_git();
        if !self.has_files() {
            self.show_folder();
        }
        self.say(format!("Deleted {name}"));
    }
}