Skip to main content

oxinav_core/
search.rs

1//! Searching file contents: what a query means and what a hit holds.
2//!
3//! The rules live here so they can be tested without touching disk; the
4//! searching itself goes through `Filesystem::search`, which the real
5//! filesystem implements with ripgrep's library crates.
6
7use crate::error::OxiNavError;
8use crate::pane::Pane;
9use std::path::PathBuf;
10
11/// The most hits a search reports. Past this the pattern is too broad for a
12/// list to help, and the search stops. Safe to tune.
13pub const MAX_HITS: usize = 1_000;
14
15/// The most characters of a matching line shown in the results. Safe to
16/// tune.
17pub const MAX_SNIPPET: usize = 200;
18
19/// What to search for, and which files to look in.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct SearchQuery {
22    /// A regular expression, as ripgrep reads one.
23    pub pattern: String,
24    pub case_insensitive: bool,
25    /// Search dot-prefixed files and directories too.
26    pub include_hidden: bool,
27    /// Only search files whose names match this glob (`pane::matches_filter`).
28    pub name_glob: Option<String>,
29}
30
31impl SearchQuery {
32    /// A query for `pattern`, scoped the way `pane` is showing things: its
33    /// hidden-file setting and its name filter. `None` for a blank pattern.
34    ///
35    /// Case follows ripgrep's smart case: insensitive unless the pattern has
36    /// an uppercase letter of its own. An escaped letter (`\S`, `\W`) is a
37    /// character class, not a letter to match, so it does not count.
38    pub fn new(pattern: &str, pane: &Pane) -> Option<Self> {
39        if pattern.trim().is_empty() {
40            return None;
41        }
42        Some(Self {
43            pattern: pattern.to_string(),
44            case_insensitive: !has_literal_uppercase(pattern),
45            include_hidden: pane.show_hidden,
46            name_glob: pane.filter.clone(),
47        })
48    }
49}
50
51/// Whether ripgrep's regex engine accepts `query`'s pattern, so a mistake
52/// can be reported where it was typed rather than after a search starts.
53pub fn check_pattern(query: &SearchQuery) -> Result<(), OxiNavError> {
54    grep_regex::RegexMatcherBuilder::new()
55        .case_insensitive(query.case_insensitive)
56        .line_terminator(Some(b'\n'))
57        .build(&query.pattern)
58        .map(|_| ())
59        .map_err(|error| OxiNavError::InvalidPattern(pattern_error(&error.to_string())))
60}
61
62/// The regex crate's parse error, reduced to its one-line reason. The full
63/// message quotes the pattern back inside a wrapper the user never typed
64/// (`(?:foo()`), with a caret under it, which reads worse than the reason.
65pub fn pattern_error(message: &str) -> String {
66    message
67        .lines()
68        .rev()
69        .find_map(|line| line.trim().strip_prefix("error: "))
70        .unwrap_or(message)
71        .to_string()
72}
73
74fn has_literal_uppercase(pattern: &str) -> bool {
75    let mut escaped = false;
76    for c in pattern.chars() {
77        if escaped {
78            escaped = false;
79        } else if c == '\\' {
80            escaped = true;
81        } else if c.is_uppercase() {
82            return true;
83        }
84    }
85    false
86}
87
88/// One matching line.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct SearchHit {
91    pub path: PathBuf,
92    /// 1-based, as editors and `rg` count.
93    pub line: u64,
94    /// The line, shortened for display by [`snippet`].
95    pub text: String,
96}
97
98/// How a search ended.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum SearchEnd {
101    /// Every file was searched.
102    Finished,
103    /// Cancelled before the end; the hits so far stand.
104    Stopped,
105    /// More than [`MAX_HITS`] matched, so the search stopped there.
106    Capped,
107}
108
109/// A matching line as the results list shows it: without its line ending or
110/// leading indentation, and cut to [`MAX_SNIPPET`] characters.
111pub fn snippet(line: &str) -> String {
112    let line = line.trim_start().trim_end_matches(['\n', '\r']);
113    match line.char_indices().nth(MAX_SNIPPET) {
114        Some((cut, _)) => format!("{}\u{2026}", &line[..cut]),
115        None => line.to_string(),
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    fn pane(show_hidden: bool, filter: Option<&str>) -> Pane {
124        let mut pane = Pane::new(PathBuf::from("/proj"));
125        pane.show_hidden = show_hidden;
126        pane.filter = filter.map(str::to_string);
127        pane
128    }
129
130    #[test]
131    fn blank_patterns_are_not_queries() {
132        assert_eq!(SearchQuery::new("", &pane(false, None)), None);
133        assert_eq!(SearchQuery::new("   ", &pane(false, None)), None);
134    }
135
136    #[test]
137    fn smart_case_follows_uppercase_letters() {
138        let query = |p| SearchQuery::new(p, &pane(false, None)).unwrap();
139        assert!(query("todo").case_insensitive);
140        assert!(!query("Todo").case_insensitive);
141        assert!(!query("fn Main").case_insensitive);
142        // Escapes are classes, not letters.
143        assert!(query(r"\Sfoo\W").case_insensitive);
144        assert!(!query(r"\SFoo").case_insensitive);
145    }
146
147    #[test]
148    fn scope_comes_from_the_pane() {
149        let query = SearchQuery::new("x", &pane(true, Some("*.rs"))).unwrap();
150        assert!(query.include_hidden);
151        assert_eq!(query.name_glob.as_deref(), Some("*.rs"));
152
153        let query = SearchQuery::new("x", &pane(false, None)).unwrap();
154        assert!(!query.include_hidden);
155        assert_eq!(query.name_glob, None);
156    }
157
158    #[test]
159    fn invalid_patterns_are_caught_before_searching() {
160        let query = |p| SearchQuery::new(p, &pane(false, None)).unwrap();
161        assert!(check_pattern(&query(r"fn\s+main")).is_ok());
162        assert!(matches!(
163            check_pattern(&query("foo(")),
164            Err(OxiNavError::InvalidPattern(_))
165        ));
166    }
167
168    #[test]
169    fn pattern_errors_are_reduced_to_their_reason() {
170        let full = "regex parse error:\n    (?:foo()\n    ^\nerror: unclosed group";
171        assert_eq!(pattern_error(full), "unclosed group");
172        assert_eq!(pattern_error("something else"), "something else");
173    }
174
175    #[test]
176    fn snippets_lose_indentation_and_line_endings() {
177        assert_eq!(snippet("    let x = 1;\r\n"), "let x = 1;");
178    }
179
180    #[test]
181    fn long_snippets_are_cut_on_a_character_boundary() {
182        let line = "é".repeat(MAX_SNIPPET + 10);
183        let cut = snippet(&line);
184        assert_eq!(cut.chars().count(), MAX_SNIPPET + 1);
185        assert!(cut.ends_with('\u{2026}'));
186        assert_eq!(snippet(&"é".repeat(MAX_SNIPPET)), "é".repeat(MAX_SNIPPET));
187    }
188}