curd-editor 0.8.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
//! Finding text in the file, and in every file of the project.
//!
//! A search ignores case unless the query has a capital letter in it, so
//! `main` finds `Main` but `Main` finds only `Main`.

use std::path::Path;

#[cfg(test)]
mod tests;

/// A project search stops after this many matching lines.
pub const MAX_HITS: usize = 2000;
/// Files bigger than this are not searched: they are rarely code.
const MAX_FILE_BYTES: u64 = 1_000_000;

/// A line in one of the project's files that holds the text searched for.
#[derive(Debug, PartialEq)]
pub struct Hit {
    /// The file, relative to the project folder.
    pub file: String,
    /// Column and line of the first match on the line, counted from 0.
    pub x: usize,
    pub y: usize,
    /// The line itself, without the spaces around it.
    pub text: String,
}

/// Every line of `files` (relative to `root`) that holds `query`. Files
/// that are not text are skipped.
pub fn in_files(root: &Path, files: &[String], query: &str) -> Vec<Hit> {
    let mut hits = Vec::new();
    for file in files {
        let path = root.join(file);
        if std::fs::metadata(&path).is_ok_and(|data| data.len() > MAX_FILE_BYTES) {
            continue;
        }
        let Ok(text) = std::fs::read_to_string(&path) else {
            continue;
        };
        for (y, line) in text.lines().enumerate() {
            if let Some(x) = matches(line, query).first() {
                hits.push(Hit {
                    file: file.clone(),
                    x: *x,
                    y,
                    text: line.trim().to_string(),
                });
                if hits.len() == MAX_HITS {
                    return hits;
                }
            }
        }
    }
    hits
}

/// The character columns where `query` starts in `line`. Matches do not
/// overlap.
pub fn matches(line: &str, query: &str) -> Vec<usize> {
    let exact = query.chars().any(char::is_uppercase);
    let key = |c: char| {
        if exact {
            c
        } else {
            c.to_lowercase().next().unwrap_or(c)
        }
    };
    let needle: Vec<char> = query.chars().map(key).collect();
    let hay: Vec<char> = line.chars().map(key).collect();
    let mut found = Vec::new();
    let mut x = 0;
    while !needle.is_empty() && x + needle.len() <= hay.len() {
        if hay[x..x + needle.len()] == needle[..] {
            found.push(x);
            x += needle.len();
        } else {
            x += 1;
        }
    }
    found
}

/// The nearest match to `from` (column, line), looking down the file when
/// `forward` and up it otherwise, and carrying on from the other end of
/// the file when it runs out. A match exactly at `from` counts only when
/// `inclusive`.
pub fn find(
    lines: &[String],
    query: &str,
    from: (usize, usize),
    forward: bool,
    inclusive: bool,
) -> Option<(usize, usize)> {
    let count = lines.len();
    if count == 0 {
        return None;
    }
    let (x, y) = from;
    // Look at the starting line, each other line once, and then the
    // starting line again for what lies on the far side of `from`.
    for step in 0..=count {
        let line = if forward { (y + step) % count } else { (y + count - step) % count };
        let found = matches(&lines[line], query);
        let hit = match (forward, step) {
            (true, 0) => found.into_iter().find(|start| *start > x || (inclusive && *start == x)),
            (true, _) => found.into_iter().next(),
            (false, 0) => found.into_iter().rfind(|start| *start < x),
            (false, _) => found.into_iter().next_back(),
        };
        if let Some(start) = hit {
            return Some((start, line));
        }
    }
    None
}