Skip to main content

justerm_core/term/
search.rs

1//! The search query surface: finding matches across the whole buffer, and holding
2//! the highlight set the consumer hands back so it rides the frame.
3//!
4//! The engine-finds / consumer-navigates split this implements is stated once, in
5//! [`crate::search`] — do not restate it here, and read it there.
6//!
7//! What is worth saying at *this* site is why one private method lives in a query
8//! module but is called eight times from the write path. `invalidate_search_highlights`
9//! drops the held set rather than re-anchoring it, because a held match is
10//! **query-derived**: the engine keeps matches, not the query, and the set itself may
11//! have changed under the mutation. The selection is the contrast, and it is not a
12//! clean one — it is re-anchored where it can be, and *cleared* where it cannot (both
13//! alt swaps set `selection = None` on the line above the call, since neither buffer's
14//! coordinates mean anything in the other). So the rule is about what is
15//! **reproducible by the consumer**, not about re-anchoring always being available.
16//!
17//! Visibility: the seven entry points are public API and stay `pub fn` — an inherent
18//! impl's methods are reached through the type, not the module path, so a private child
19//! module does not hide them. `invalidate_search_highlights` takes `pub(super)` because
20//! its callers are the write path in `term.rs`; `word_bounded` stays private because its
21//! only caller came with it.
22
23use unicode_width::UnicodeWidthChar;
24
25use crate::search::{Match, SearchOptions};
26use crate::selection::SelectionSpan;
27
28use super::Term;
29
30impl Term {
31    /// Literal search over the whole buffer (`[scrollback ++ screen]`), returning
32    /// every non-overlapping match top-to-bottom in absolute coordinates. Matches
33    /// cross soft-wrapped rows (one logical line) and skip wide-char spacers.
34    /// Smart-case: a query with no uppercase matches case-insensitively.
35    pub fn search(&self, query: &str) -> Vec<Match> {
36        self.search_with(query, SearchOptions::default())
37    }
38
39    /// Search with explicit [`SearchOptions`] — regex, whole-word, and a case-sensitivity override
40    /// on top of the literal + smart-case [`search`](Self::search) (#314). Same coordinates,
41    /// soft-wrap join, spacer skip, and grapheme-mark inclusion (#304) as `search`.
42    pub fn search_with(&self, query: &str, opts: SearchOptions) -> Vec<Match> {
43        let q: Vec<char> = query.chars().collect();
44        if q.is_empty() {
45            return Vec::new();
46        }
47        // Smart-case unless overridden: case-insensitive iff the query has no uppercase.
48        let ci = opts
49            .case_sensitive
50            .map_or_else(|| !q.iter().any(|c| c.is_uppercase()), |cs| !cs);
51        // Fold to a single representative char so the haystack stays 1:1 with its
52        // positions (rare multi-char case expansions take their first char).
53        let fold = |c: char| {
54            if ci {
55                c.to_lowercase().next().unwrap_or(c)
56            } else {
57                c
58            }
59        };
60        let needle: Vec<char> = q.iter().map(|&c| fold(c)).collect();
61        // Regex mode: build the pattern once (case-insensitivity from the same smart-case/override
62        // decision). An invalid pattern yields no matches rather than erroring (#314).
63        let re = if opts.regex {
64            match regex::RegexBuilder::new(query).case_insensitive(ci).build() {
65                Ok(re) => Some(re),
66                Err(_) => return Vec::new(),
67            }
68        } else {
69            None
70        };
71        let total = self.scrollback.len() + self.grid.rows();
72
73        // Floored: primary matches are unreachable on alt, and a primary WRAPLINE row
74        // would otherwise soft-wrap-join into the alt grid and corrupt the haystack at
75        // the boundary. (#144)
76        let floor = self.abs_floor();
77        let mut matches = Vec::new();
78        let mut r = floor;
79        while r < total {
80            // Build the logical line at `r`: join soft-wrapped rows, recording
81            // each char's source position and skipping wide-char spacers.
82            let mut hay: Vec<char> = Vec::new();
83            let mut pos: Vec<(usize, usize)> = Vec::new();
84            let mut line = r;
85            loop {
86                let cells = self.abs_line(line);
87                for (col, cell) in cells.iter().enumerate() {
88                    if cell.is_spacer() {
89                        continue;
90                    }
91                    // Build the haystack UNFOLDED (regex needs the original text; its own
92                    // case-insensitive flag handles case). The literal path folds at compare time.
93                    hay.push(cell.c());
94                    pos.push((line, col));
95                    // Include the cell's grapheme side-table marks — combining marks, and under
96                    // mode 2027 the joined emoji scalars (2nd RI, ZWJ-joined emoji, skin tone) —
97                    // so a clustered scalar is findable, not just the base (#304). Each maps to the
98                    // same cell column, mirroring `append_cell`'s base+marks extraction.
99                    if let Some(marks) = self.combining_at(line, col) {
100                        for &m in marks {
101                            hay.push(m);
102                            pos.push((line, col));
103                        }
104                    }
105                }
106                let soft = self.abs_row(line).is_wrapped();
107                if soft && line + 1 < total {
108                    line += 1;
109                } else {
110                    break;
111                }
112            }
113            // Trim trailing blank padding (only a logical line's tail can be blank), so a regex `$`
114            // anchor or a greedy `.*` doesn't run into the grid's blank cells — mirrors
115            // `viewport_logical_lines`'s trim (#314 Lens 1). Keeps hay/pos in lockstep.
116            // The predicate is `' '` and not `is_whitespace()` (#685): this decides where the
117            // haystack *ends*, so a property test moved `$` onto the wrong column as well as
118            // making a written U+00A0 unfindable. See
119            // `docs/map/invariant/only-u0020-can-be-padding.md`.
120            while hay.last().is_some_and(|c| *c == ' ') {
121                hay.pop();
122                pos.pop();
123            }
124
125            // A match at char-index range [cs, ce) → a Match, whole-word-filtered and deduped.
126            // (Marks map many hay entries to one column (#304), so a repeated in-cluster scalar can
127            // yield consecutive identical Matches — collapse them.)
128            let push_range = |cs: usize, ce: usize, matches: &mut Vec<Match>| {
129                if opts.whole_word && !word_bounded(&hay, cs, ce - cs) {
130                    return;
131                }
132                let m = Match {
133                    start_line: pos[cs].0,
134                    start_col: pos[cs].1,
135                    end_line: pos[ce - 1].0,
136                    end_col: pos[ce - 1].1,
137                };
138                if matches.last() != Some(&m) {
139                    matches.push(m);
140                }
141            };
142
143            if let Some(re) = &re {
144                // Regex over the (unfolded) logical line; map each match's byte range to char indices.
145                let hay_str: String = hay.iter().collect();
146                for mat in re.find_iter(&hay_str) {
147                    if mat.start() == mat.end() {
148                        continue; // skip empty matches (e.g. `a*` between chars)
149                    }
150                    let cs = hay_str[..mat.start()].chars().count();
151                    let ce = hay_str[..mat.end()].chars().count();
152                    push_range(cs, ce, &mut matches);
153                }
154            } else {
155                // Slide the literal needle non-overlapping, folding each hay char at compare time.
156                let mut i = 0;
157                while needle.len() <= hay.len() && i + needle.len() <= hay.len() {
158                    let hit = hay[i..i + needle.len()]
159                        .iter()
160                        .enumerate()
161                        .all(|(k, &c)| fold(c) == needle[k]);
162                    if hit {
163                        let before = matches.len();
164                        push_range(i, i + needle.len(), &mut matches);
165                        // Advance past a real (accepted) match; a whole-word-rejected run advances by
166                        // one so a later, word-bounded position at an overlapping offset is still tried.
167                        i += if matches.len() > before {
168                            needle.len()
169                        } else {
170                            1
171                        };
172                    } else {
173                        i += 1;
174                    }
175                }
176            }
177            r = line + 1;
178        }
179        matches
180    }
181
182    /// Scroll the viewport so a match's start line is visible (placed at the top
183    /// when it sits in history; the live view when it is already on screen).
184    pub fn search_scroll_to(&mut self, m: &Match) {
185        let target = self.scrollback.len().saturating_sub(m.start_line);
186        self.set_display_offset(target);
187    }
188
189    /// Project a match onto the current viewport as inclusive-column spans, one
190    /// per visible row (off-screen parts dropped) — for the renderer to
191    /// highlight, like `selection_range`.
192    ///
193    /// **Both column ends are bounded here, and the `left` half is not an accident of
194    /// symmetry (#678).** A [`Match`]'s columns are *consumer-supplied* by design:
195    /// [`Term::set_active_search_match`] documents taking one the caller assembled
196    /// outside the engine's own result set (the past-cap path, #436), and `Match`'s
197    /// fields are public. So the usual guarantee — "the engine found it, therefore it is
198    /// in range" — does not hold on this path, and only the *index* form
199    /// ([`Term::set_active_search_highlight`]) keeps it by construction.
200    ///
201    /// Left unbounded, a start column past the last one made `right >= left` fail on the
202    /// match's **own** row and dropped it, so a multi-row match lost its first row while
203    /// the rest painted — the shape that reads as "the highlight is fine" at a glance,
204    /// and the reason this was not a visible defect for as long as it existed.
205    ///
206    /// Bounded **here** rather than at the three storing intakes. #671 is the sibling but
207    /// **not** the same shape: it did not touch `selection_range`, whose `left` is still
208    /// unbounded — it clamped selection's *producer* (`Term::viewport_to_abs`), which made
209    /// the read-site asymmetry unreachable. Search has no producer to clamp, because the
210    /// coordinate **is** the consumer's, which is exactly why the same asymmetry stayed
211    /// live here. `right` is already bounded in this expression, so the bound restores a
212    /// symmetry rather than adding a rule, and the write side is three intakes, one taking
213    /// a whole `Vec`. The bound is the row's extent, which is the *grid* width — both row
214    /// producers resize every row to `grid.cols()` — so a short line does not shrink a
215    /// match reaching past its text.
216    ///
217    /// **The references split 1–1 on the guard, and clamping is the chosen side, not the
218    /// obvious one.** alacritty clamps a column unconditionally (`Point::grid_clamp`, run
219    /// on both endpoints before any per-type arithmetic); xterm **hides** — its decoration
220    /// renderer carries a commented arm for precisely this input (*"exceeded the container
221    /// width, so hide"*), which is justerm's *old* outcome. What breaks the tie is that the
222    /// old outcome was neither: it dropped one row and painted the rest. The cost of
223    /// clamping is recorded with it in `reference-facts.md` — on a grid ending in a wide
224    /// glyph the clamped column can be the pair's trailing spacer, so a span can cover half
225    /// a glyph (the #454 class), which hiding would not have produced.
226    pub fn match_spans(&self, m: &Match) -> Vec<SelectionSpan> {
227        let rows = self.grid.rows();
228        let top = self.scrollback.len() - self.display_offset;
229        let mut spans = Vec::new();
230        for line in m.start_line..=m.end_line {
231            if line < top {
232                continue;
233            }
234            let row = line - top;
235            if row >= rows {
236                break;
237            }
238            let last = self.abs_line(line).len().saturating_sub(1);
239            let left = if line == m.start_line {
240                m.start_col.min(last)
241            } else {
242                0
243            };
244            let right = if line == m.end_line {
245                m.end_col.min(last)
246            } else {
247                last
248            };
249            // #454: widen onto whole wide-glyph pairs, the same rule `selection_range` applies. This
250            // surface needs it for a reason the selection does not have — a `Match` may be AUTHORED
251            // by the consumer (`set_active_search_match`, the past-cap path), and #678's clamp lands
252            // an out-of-range column on the last cell, which is a trailing spacer whenever the row
253            // ends in a wide glyph. Measured there: `start_col: 99` on a 6-column row holding
254            // `abcd한` projected to `left: 5, right: 5` — the glyph's right half alone.
255            let (left, right) = (self.pair_start(line, left), self.pair_end(line, right));
256            if right >= left {
257                spans.push(SelectionSpan { row, left, right });
258            }
259        }
260        spans
261    }
262
263    /// Set the search highlights to paint (#108). The consumer owns the
264    /// `Vec<Match>` (it drives next/prev); handing it back here lets `frame()`
265    /// project the highlights onto the viewport. An empty vec clears them.
266    pub fn set_search_highlights(&mut self, matches: Vec<Match>) {
267        self.search_highlights = matches;
268        // A new set voids the designation: a stale index could be accidentally
269        // in range and light wrong content (#428). The consumer re-designates.
270        self.active_search_highlight = None;
271    }
272
273    /// Designate which member of the held highlight set is the *active* match
274    /// (#428) — the one the consumer's next/prev navigation currently points at.
275    /// `frame()` projects it into `overlay.active_match` (it also stays in
276    /// `overlay.matches`; the renderer's ranking resolves the overlap, #424).
277    /// `None` or an out-of-range index projects nothing; the designation resets
278    /// whenever a new set is passed to [`set_search_highlights`](Self::set_search_highlights).
279    /// The index resolves to its span at call time (#436) — both designation
280    /// APIs converge on one stored representation.
281    pub fn set_active_search_highlight(&mut self, index: Option<usize>) {
282        self.active_search_highlight = index.and_then(|i| self.search_highlights.get(i)).copied();
283    }
284
285    /// Designate the *active* match by its absolute span (#436), independent of
286    /// the held highlight set — the past-cap path: a backend that caps its
287    /// hand-over (the documented 1000, xterm's `highlightLimit`) can still give
288    /// the current match its active emphasis, exactly as xterm creates the
289    /// active decoration from the found result outside the capped list. The
290    /// span projects through the same viewport math as any match (wrap-aware);
291    /// it need not be a member of the held set, so past the cap the match
292    /// paints the ACTIVE colour only (no plain highlight underneath). `None`
293    /// clears. Same lifecycle as the index form: reset on every
294    /// [`set_search_highlights`](Self::set_search_highlights) hand-over and on
295    /// any coordinate-shifting invalidation.
296    pub fn set_active_search_match(&mut self, m: Option<Match>) {
297        self.active_search_highlight = m;
298    }
299
300    /// Invalidate the held search highlights (#108). Called wherever a buffer
301    /// mutation shifts the *line* coordinates the matches were found at — cap
302    /// eviction, in-screen region/RI/SU/SD/IL/DL scroll, the accrual
303    /// sub-region scroll (#449 — which also re-anchors selection/markers below
304    /// the margin, `selection_shift_below_margin`), reflow, both alt swaps.
305    /// In-line *column* shifts (ICH/DCH, insert-mode print) and
306    /// in-place erases (ED/EL/ECH, overwrite) deliberately do NOT funnel — the
307    /// set stales in place there, **healed by the consumer's debounced re-search
308    /// on output** (which those mutations are; `justerm-web`'s search controller
309    /// re-runs the active query after a debounce so highlights track the buffer).
310    /// That healing is the whole of the argument, and it is the reason the
311    /// sibling defect in the *marker* surface had to be fixed in the engine
312    /// instead (#750): `command_lines` is pulled on a user action, so nothing
313    /// re-derives it and the wrong answer reproduces forever.
314    ///
315    /// **The comparison to xterm's decorations used to stand here and is now
316    /// half false (#750).** A search highlight in xterm.js is a decoration
317    /// registered on its own marker (`addons/addon-search/src/DecorationManager.ts`),
318    /// and `DecorationService` disposes a decoration with its marker — so ED,
319    /// which calls `Buffer.clearMarkers` through `_resetBufferLine`, **does**
320    /// retire xterm's search highlights. EL, ECH and an overwrite retire
321    /// nothing there, which is the half that still holds. justerm reaches a
322    /// different answer for ED because it split one reference mechanism into two
323    /// (a marker list and this flat set), and the two halves have different
324    /// consumers: only this one has a re-search behind it. Search matches are query-derived
325    /// (the engine holds matches, not the query, and the *set* itself may have
326    /// changed), so unlike the user-authored selection they are dropped rather
327    /// than re-anchored. Clearing avoids painting wrong content for the frame
328    /// between the mutation and the consumer's refresh.
329    pub(super) fn invalidate_search_highlights(&mut self) {
330        self.search_highlights.clear();
331        // #436: the active designation is a stored SPAN, no longer structurally
332        // tied to the set — clear it in the same funnel or it would keep
333        // painting coordinates that now hold arbitrary other text.
334        self.active_search_highlight = None;
335    }
336}
337
338/// Whether the run `hay[i..i+len]` is bounded by non-word characters on both sides — the `\bword\b`
339/// sense for whole-word search (#314). A word char is alphanumeric or `_` (the regex `\w` set),
340/// deliberately distinct from selection's semantic-selection set.
341///
342/// **#545 made that set consumer-injectable and deliberately left this one alone**, so the two
343/// now differ in kind and not only in contents: whole-word *search* is the `\b` sense of the
344/// pattern the consumer already supplied, while word *selection* is a separator list the consumer
345/// supplies separately. Both references that have a whole-word search agree — xterm.js keeps a
346/// hardcoded `NON_WORD_CHARACTERS` in its search addon (`addons/addon-search/src/SearchEngine.ts`)
347/// that is not its configurable `wordSeparator` and is not even equal to it, and alacritty has no
348/// whole-word option at all (the user writes `\b`, so `\w` decides). Threading
349/// `word_separators` in here would make one knob silently redefine `\b`.
350fn word_bounded(hay: &[char], i: usize, len: usize) -> bool {
351    // A word char is alphanumeric, `_`, OR a grapheme-extending mark (width 0: combining marks,
352    // ZWJ, variation selectors) — so a mark attached to a base is never read as a word boundary,
353    // matching the regex `\b` sense (`\w` includes `\p{M}`) and staying consistent across the
354    // literal and regex paths on decomposed graphemes (#314 Lens 1).
355    let is_word = |c: char| c.is_alphanumeric() || c == '_' || c.width() == Some(0);
356    let left = i == 0 || !is_word(hay[i - 1]);
357    let right = i + len == hay.len() || !is_word(hay[i + len]);
358    left && right
359}