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
//! Questions asked in the status bar: find, replace, go to line, save as.

use super::*;

impl Editor {
    // ---- Questions in the status bar -----------------------------------

    /// The words in front of the answer to the question `kind`.
    pub(super) fn prompt_label(&self, kind: PromptKind) -> String {
        match kind {
            PromptKind::Find => "Find: ".into(),
            PromptKind::SaveAs => "Save as: ".into(),
            PromptKind::Replace => "Replace: ".into(),
            PromptKind::With => format!("Replace {} with: ", self.replace_what),
            PromptKind::GoTo => "Go to line: ".into(),
        }
    }

    /// The text whose matches are shown while a question is open.
    pub(super) fn shown_query(&self) -> Option<&str> {
        match &self.prompt {
            Some(Prompt { kind: PromptKind::Find | PromptKind::Replace, text }) => Some(text),
            Some(Prompt { kind: PromptKind::With, .. }) => Some(&self.replace_what),
            _ => None,
        }
    }

    pub(super) fn open_prompt(&mut self, kind: PromptKind) {
        self.completion = None;
        self.find_from = (self.cursor_x, self.cursor_y);
        self.prompt = Some(Prompt {
            kind,
            text: String::new(),
        });
    }

    /// A key pressed while a question is open in the status bar.
    pub(super) fn prompt_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        let Some(prompt) = &mut self.prompt else {
            return;
        };
        let kind = prompt.kind;
        let finding = !matches!(kind, PromptKind::SaveAs | PromptKind::GoTo);
        match key.code {
            KeyCode::Esc => self.prompt = None,
            KeyCode::Char('f') if (ctrl || alt) && finding => self.find_step(true),
            KeyCode::Char('a') if (ctrl || alt) && kind == PromptKind::With => self.replace_all(),
            KeyCode::Char(c) if !ctrl && !alt => {
                prompt.text.push(c);
                self.prompt_changed();
            }
            KeyCode::Backspace => {
                prompt.text.pop();
                self.prompt_changed();
            }
            KeyCode::Down if finding => self.find_step(true),
            KeyCode::Up if finding => self.find_step(false),
            KeyCode::Enter => {
                let text = prompt.text.clone();
                match kind {
                    PromptKind::Find => self.find_step(true),
                    PromptKind::Replace if text.is_empty() => self.prompt = None,
                    PromptKind::Replace => {
                        self.replace_what = text;
                        self.prompt = Some(Prompt {
                            kind: PromptKind::With,
                            text: String::new(),
                        });
                        self.message = "Enter replaces this one, Alt+A all, Down skips".into();
                    }
                    PromptKind::With => self.replace_one(),
                    PromptKind::SaveAs => {
                        self.prompt = None;
                        self.save_as(&text);
                    }
                    PromptKind::GoTo => {
                        self.prompt = None;
                        match text.trim().parse::<usize>() {
                            Ok(number) if number > 0 => self.jump_to(0, number - 1),
                            _ => self.message = format!("Not a line number: {text}"),
                        }
                    }
                }
            }
            _ => {}
        }
    }

    /// Puts `with` in place of the match of `what` that starts at the cursor.
    pub(super) fn replace_here(&mut self, what: &str, with: &str) {
        self.folds.reveal(self.cursor_y);
        for _ in 0..what.chars().count() {
            self.delete();
        }
        self.insert_text(with);
    }

    /// What was asked to be replaced, and what with.
    pub(super) fn replacement(&self) -> (String, String) {
        let with = self.prompt.as_ref().map(|prompt| prompt.text.clone());
        (self.replace_what.clone(), with.unwrap_or_default())
    }

    /// Replaces the match under the cursor and moves on to the next one.
    pub(super) fn replace_one(&mut self) {
        let (what, with) = self.replacement();
        let on_match = self
            .document
            .lines
            .get(self.cursor_y)
            .is_some_and(|line| search::matches(line, &what).contains(&self.cursor_x));
        if on_match {
            self.history.begin((self.cursor_x, self.cursor_y), false);
            self.replace_here(&what, &with);
            self.history.commit((self.cursor_x, self.cursor_y));
        }
        let from = (self.cursor_x, self.cursor_y);
        match search::find(&self.document.lines, &what, from, true, true) {
            Some((x, y)) => self.jump_to(x, y),
            None => {
                self.prompt = None;
                self.message = "Replaced the last match".into();
            }
        }
    }

    /// Replaces every match in the file, as one step to undo.
    pub(super) fn replace_all(&mut self) {
        let (what, with) = self.replacement();
        self.prompt = None;
        self.history.begin((self.cursor_x, self.cursor_y), false);
        let mut count = 0;
        for y in 0..self.document.len() {
            // From the right, so the columns of the matches still to do
            // stay where they are.
            for x in search::matches(&self.document.lines[y], &what).into_iter().rev() {
                (self.cursor_x, self.cursor_y) = (x, y);
                self.replace_here(&what, &with);
                count += 1;
            }
        }
        self.history.commit((self.cursor_x, self.cursor_y));
        self.message = format!("Replaced {count} matches of {what}");
    }

    /// The search text changed: show the first match at or after the place
    /// the search started from.
    pub(super) fn prompt_changed(&mut self) {
        let Some(Prompt { kind: PromptKind::Find | PromptKind::Replace, text }) = &self.prompt else {
            return;
        };
        let query = text.clone();
        (self.cursor_x, self.cursor_y) = self.find_from;
        self.jump_to_match(&query, true, true);
        self.last_query = query;
    }

    /// Enter or the arrows in a search: on to the next match, or back to
    /// the one before.
    pub(super) fn find_step(&mut self, forward: bool) {
        let query = match &self.prompt {
            Some(prompt) if prompt.kind == PromptKind::With => self.replace_what.clone(),
            Some(prompt) if !prompt.text.is_empty() => prompt.text.clone(),
            _ => self.last_query.clone(),
        };
        self.jump_to_match(&query, forward, false);
    }

    /// Jumps to the next match of the last search, without asking again.
    pub(super) fn find_again(&mut self) {
        if self.last_query.is_empty() {
            self.message = "Nothing searched for yet: Ctrl+F or Alt+F starts a search".into();
        } else {
            let query = self.last_query.clone();
            self.jump_to_match(&query, true, false);
        }
    }

    /// Moves the cursor to the nearest match of `query`, if there is one.
    pub(super) fn jump_to_match(&mut self, query: &str, forward: bool, inclusive: bool) {
        if query.is_empty() {
            return;
        }
        let from = (self.cursor_x, self.cursor_y);
        match search::find(&self.document.lines, query, from, forward, inclusive) {
            Some((x, y)) => {
                self.folds.reveal(y);
                (self.cursor_x, self.cursor_y) = (x, y);
            }
            None => self.message = format!("No match for {query}"),
        }
    }
}