curd-editor 0.10.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, selection, search and replace, a git menu, and language-server colours, errors and completion
//! Quick open: type a few letters of a file's name and jump to it.
//!
//! The same list is used for anything else picked by typing: branches,
//! git commands, the matches of a project search.

use std::path::Path;

use crate::git;

#[cfg(test)]
mod tests;

/// Folders that are never worth searching when git cannot tell us what is
/// ignored.
const SKIPPED_FOLDERS: [&str; 4] = [".git", "target", "node_modules", "__pycache__"];
/// Stop listing a project without git after this many files.
const MAX_FILES: usize = 20_000;

pub struct Finder {
    pub query: String,
    /// Every file in the project, relative to the project folder.
    files: Vec<String>,
    /// The files matching the query, best first.
    matches: Vec<usize>,
    pub selected: usize,
    /// True for a plain list: the items keep their order, and one matches
    /// when it contains the query. Otherwise they are file paths, matched
    /// loosely and sorted best first.
    plain: bool,
}

/// Every file in the project `root`, relative to it: what git tracks or
/// would track, or everything when the project is not in git.
pub fn project_files(root: &Path) -> Vec<String> {
    // Git lists nothing for a folder that is itself ignored (or empty):
    // look for ourselves then, too.
    git::list_files(root)
        .filter(|files| !files.is_empty())
        .unwrap_or_else(|| {
            let mut files = Vec::new();
            walk(root, "", &mut files);
            files
        })
}

/// How well `path` matches `query`: lower is better, `None` is no match.
/// Capital letters are ignored. A match in the file's name beats one
/// elsewhere in the path, and the letters may be spread out (`edrs` finds
/// `editor.rs`).
fn score(query: &str, path: &str) -> Option<usize> {
    let query = query.to_lowercase();
    let path = path.to_lowercase();
    let name = path.rsplit('/').next().unwrap_or(&path);
    let rank = if name.starts_with(&query) {
        0
    } else if name.contains(&query) {
        1
    } else if path.contains(&query) {
        2
    } else {
        // The letters in order, with anything in between.
        let mut letters = path.chars();
        if !query.chars().all(|wanted| letters.any(|c| c == wanted)) {
            return None;
        }
        3
    };
    // Among equally good matches, shorter paths come first.
    Some(rank * 10_000 + path.len())
}

/// Every file below `dir`, relative to it, for projects without git.
fn walk(dir: &Path, prefix: &str, files: &mut Vec<String>) {
    let Ok(listing) = std::fs::read_dir(dir) else {
        return;
    };
    let mut items: Vec<_> = listing.flatten().collect();
    items.sort_by_key(|item| item.file_name());
    for item in items {
        if files.len() >= MAX_FILES {
            return;
        }
        let name = item.file_name().to_string_lossy().into_owned();
        let path = format!("{prefix}{name}");
        if item.path().is_dir() {
            if !SKIPPED_FOLDERS.contains(&name.as_str()) {
                walk(&item.path(), &format!("{path}/"), files);
            }
        } else {
            files.push(path);
        }
    }
}

impl Finder {
    /// Lists the project's files.
    pub fn new(root: &Path) -> Self {
        Self::with_files(project_files(root))
    }

    pub fn with_files(files: Vec<String>) -> Self {
        Self::build(files, false)
    }

    /// A plain list of `items` to pick from, kept in the order given.
    pub fn list(items: Vec<String>) -> Self {
        Self::build(items, true)
    }

    fn build(files: Vec<String>, plain: bool) -> Self {
        let mut finder = Self {
            query: String::new(),
            files,
            matches: Vec::new(),
            selected: 0,
            plain,
        };
        finder.update();
        finder
    }

    /// Works out the matches again after the query changed.
    fn update(&mut self) {
        self.selected = 0;
        if self.plain {
            let query = self.query.to_lowercase();
            self.matches = (0..self.files.len())
                .filter(|index| self.files[*index].to_lowercase().contains(&query))
                .collect();
            return;
        }
        let mut scored: Vec<(usize, usize)> = self
            .files
            .iter()
            .enumerate()
            .filter_map(|(index, path)| Some((score(&self.query, path)?, index)))
            .collect();
        scored.sort();
        self.matches = scored.into_iter().map(|(_, index)| index).collect();
    }

    pub fn type_char(&mut self, c: char) {
        self.query.push(c);
        self.update();
    }

    pub fn backspace(&mut self) {
        self.query.pop();
        self.update();
    }

    /// Moves the selection `rows` down (up, when negative).
    pub fn move_by(&mut self, rows: isize) {
        let last = self.matches.len().saturating_sub(1) as isize;
        self.selected = (self.selected as isize + rows).clamp(0, last) as usize;
    }

    /// The matching files, best first, starting far enough down the list
    /// that the selected one is among the first `count`. Each comes with
    /// whether it is the selected one.
    pub fn visible(&self, count: usize) -> Vec<(&str, bool)> {
        let first = (self.selected + 1).saturating_sub(count);
        self.matches
            .iter()
            .enumerate()
            .skip(first)
            .take(count)
            .map(|(position, index)| (self.files[*index].as_str(), position == self.selected))
            .collect()
    }

    /// Selects the item on row `row` of the `count` rows that `visible`
    /// shows. Returns false if there is nothing on that row.
    pub fn select_row(&mut self, row: usize, count: usize) -> bool {
        let first = (self.selected + 1).saturating_sub(count);
        let on_row = row < count && first + row < self.matches.len();
        if on_row {
            self.selected = first + row;
        }
        on_row
    }

    /// Which of the items given at the start is selected.
    pub fn chosen_index(&self) -> Option<usize> {
        self.matches.get(self.selected).copied()
    }

    /// The selected file, relative to the project folder.
    pub fn chosen(&self) -> Option<&str> {
        self.matches
            .get(self.selected)
            .map(|index| self.files[*index].as_str())
    }
}