curd-editor 0.7.0

A small terminal code editor: file tree, git status and change markers, tabs, undo, search, and language-server colours, errors and completion
//! Finding text in the file.
//!
//! A search ignores case unless the query has a capital letter in it, so
//! `main` finds `Main` but `Main` finds only `Main`.

#[cfg(test)]
mod tests;

/// 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
}