Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent-tui): match /find against unwrapped text so a term that word-wraps is found

thinhlpg8ec970b89e76
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index a9cb9ed5c..7d5bf6998 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -59,7 +59,7 @@ See [Sessions](/docs/agent/sessions).
| `/shells` (alias `/jobs`) | Inspect background shell commands the agent left running: one `• command` row each, with how long it has run; `x` stops the selected one |
| `/stop` | Stop every background shell command at once |
| `/monitors` | Inspect the monitors watching for a condition: id, name, polls so far and script; `x` stops the selected one |
-| `/find <term>` | Search the whole transcript (case-insensitive) and jump to the nearest match, unfolding it if needed. <kbd>Enter</kbd> / <kbd>Shift</kbd>+<kbd>Enter</kbd> step to the next / previous match, wrapping at the ends, while the input is empty (they type nothing, so the start of your next message is never eaten); a term that word-wraps across two lines is not matched; <kbd>Esc</kbd> or the next message clears it. A miss is reported in the footer |
+| `/find <term>` | Search the whole transcript (case-insensitive) and jump to the nearest match, unfolding it if needed. A term that wraps across two lines is still found and highlighted on both, and the match count does not change when you resize the window. <kbd>Enter</kbd> / <kbd>Shift</kbd>+<kbd>Enter</kbd> step to the next / previous match, wrapping at the ends, while the input is empty (they type nothing, so the start of your next message is never eaten); <kbd>Esc</kbd> or the next message clears it. A miss is reported in the footer |
See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-todos), and
[Context and compaction](/docs/agent/context).
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index a116acf44..c3839ce84 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -1961,6 +1961,8 @@ struct Row {
/// re-parse its markdown and re-highlight its diffs 20 times a second;
/// only a width change invalidates the entry.
cache: std::cell::RefCell<Option<RowRender>>,
+ /// The row's text before wrapping, filled on first use by `flat`.
+ flat: std::cell::RefCell<Option<Vec<String>>>,
}
/// A row's rendered lines plus the height they occupy once the body
@@ -2129,6 +2131,7 @@ impl From<RowKind> for Row {
Row {
kind,
cache: std::cell::RefCell::new(None),
+ flat: std::cell::RefCell::new(None),
}
}
}
@@ -2157,6 +2160,20 @@ impl Row {
self.cache.borrow().as_ref().map_or(0, |r| r.height)
}
+ /// What the row says unwrapped (see `find::flat_text`), rendered once at
+ /// `find::FLAT_WIDTH` and kept: it does not depend on the terminal, and
+ /// `/find` reads it on every step. Rows are replaced rather than edited, so
+ /// it never goes stale.
+ fn flat(&self) -> std::cell::Ref<'_, Vec<String>> {
+ if self.flat.borrow().is_none() {
+ let lines = self.kind.render(find::FLAT_WIDTH);
+ *self.flat.borrow_mut() = Some(find::flat_text(&lines));
+ }
+ std::cell::Ref::map(self.flat.borrow(), |flat| {
+ flat.as_ref().expect("filled above")
+ })
+ }
+
fn fill(&self, width: u16) {
if self
.cache
@@ -2752,6 +2769,7 @@ impl Transcript {
idx: Some(i),
height: row.height(width),
lines: None,
+ flat: None,
}
}
}
@@ -2759,6 +2777,7 @@ impl Transcript {
idx: Some(i),
height: row.height(width),
lines: None,
+ flat: None,
},
};
if find_hit.is_some_and(|h| h.row == i && !h.detail) {
@@ -2808,7 +2827,15 @@ impl Transcript {
find_at = Some(content_h);
}
}
- let seg = Segment::eager(Some(i), detail, width);
+ let mut seg = Segment::eager(Some(i), detail, width);
+ // The lingering reasoning tail is a bounded view of the block,
+ // not a wrapped copy of its detail, so it has no unwrapped form.
+ if find.is_some() && !(active_reasoning && !expanded) {
+ let index = region_index.get_or_insert_with(|| self.region_index());
+ seg.flat = self
+ .region_detail_in(index, i, find::FLAT_WIDTH)
+ .map(|lines| find::flat_text(&lines));
+ }
content_h = content_h.saturating_add(seg.height);
segs.push(seg);
}
@@ -5629,17 +5656,25 @@ impl App {
}
}
- /// Every committed line matching `needle`, top to bottom. Scans what the
- /// rows render to, folded detail included, rather than only what is on
- /// screen: the transcript is built from `display_log`, so this covers the
- /// whole session. The streaming tail is not committed yet and is skipped.
+ /// Every committed logical line matching `needle`, top to bottom. Scans
+ /// what the rows render to, folded detail included, rather than only what
+ /// is on screen: the transcript is built from `display_log`, so this covers
+ /// the whole session. The streaming tail is not committed yet and is
+ /// skipped.
+ ///
+ /// Matching runs on each part's unwrapped text and a hit is a logical line
+ /// of it, so a term that word-wraps across two rendered lines is found and
+ /// the count is the same at any terminal width.
fn find_hits(&self, needle: &str) -> Vec<find::Hit> {
let width = self.transcript.render_width();
let mut hits = Vec::new();
- let mut scan = |row: usize, detail: bool, lines: &[Line<'static>]| {
- for (line, l) in lines.iter().enumerate() {
- if !find::match_ranges(&find::line_text(l), needle).is_empty() {
- hits.push(find::Hit { row, detail, line });
+ let mut scan = |row: usize, detail: bool, lines: &[Line<'static>], flat: &[String]| {
+ let mut last = None;
+ for found in find::occurrences(lines, Some(flat), needle) {
+ // One hit per logical line, however many times it matches.
+ if last != Some(found.logical) {
+ last = Some(found.logical);
+ hits.push(find::Hit { row, detail, line: found.logical });
}
}
};
@@ -5649,10 +5684,15 @@ impl App {
// on each `/find` and step was most of the scan's cost.
row.fill(width);
if let Some(cached) = row.cache.borrow().as_ref() {
- scan(i, false, &cached.lines);
+ scan(i, false, &cached.lines, &row.flat());
}
if let Some(detail) = self.transcript.region_detail_in(&index, i, width) {
- scan(i, true, &detail);
+ let flat = self
+ .transcript
+ .region_detail_in(&index, i, find::FLAT_WIDTH)
+ .map(|lines| find::flat_text(&lines))
+ .unwrap_or_default();
+ scan(i, true, &detail, &flat);
}
}
hits
@@ -21160,6 +21200,10 @@ struct Segment {
idx: Option<usize>,
height: u16,
lines: Option<Vec<Line<'static>>>,
+ /// An expanded region's text before wrapping, read only while a search is
+ /// active. A committed row's is kept on the row itself; every other
+ /// inline segment is searched as rendered.
+ flat: Option<Vec<String>>,
}
impl Segment {
@@ -21168,6 +21212,7 @@ impl Segment {
idx,
height: wrapped_height_of(&lines, width),
lines: Some(lines),
+ flat: None,
}
}
}
@@ -21200,6 +21245,7 @@ impl BodyLayout {
idx: None,
height: pad,
lines: Some(vec![Line::raw(""); pad as usize]),
+ flat: None,
},
);
self.content_h = self.content_h.saturating_add(pad);
@@ -21235,6 +21281,7 @@ impl BodyLayout {
let seg_end = at.saturating_add(seg.height);
if seg_end > scroll && at < end {
first_start.get_or_insert(at);
+ let committed = seg.lines.is_none();
let lines = match seg.lines {
Some(lines) => lines,
// Committed rows are cloned out of the cache only here.
@@ -21249,11 +21296,19 @@ impl BodyLayout {
// cache never holds a highlighted copy.
match find {
Some((needle, hit)) => {
- visible.extend(lines.into_iter().enumerate().map(|(li, line)| {
- let current =
- self.find_seg == Some(n) && hit.is_some_and(|h| h.line == li);
- find::highlight_line(line, needle, current)
- }))
+ // Matched on the unwrapped text, so a term that wrapped
+ // is painted on each line it lands on. A committed row
+ // keeps that text itself; an expanded region carries it.
+ let row = seg.idx.filter(|_| committed).and_then(|i| rows.get(i));
+ let kept = row.map(Row::flat);
+ let flat = match (&kept, &seg.flat) {
+ (Some(kept), _) => Some(kept.as_slice()),
+ (None, Some(flat)) => Some(flat.as_slice()),
+ (None, None) => None,
+ };
+ let found = find::occurrences(&lines, flat, needle);
+ let current = hit.filter(|_| self.find_seg == Some(n)).map(|h| h.line);
+ visible.extend(find::paint_lines(lines, &found, current));
}
None => visible.extend(lines),
}
@@ -21472,25 +21527,33 @@ fn draw(f: &mut Frame, app: &mut App) {
}
app.transcript.reveal = None;
let find_hit = app.find.as_ref().and_then(|f| f.current_hit());
- if let (Some(start), Some(hit)) = (layout.find_at, find_hit) {
- // Down to the matching line inside its segment, measured with the same
- // wrap the body uses. Only on the jump frame, so the lines above it are
- // cloned once per step, not every frame.
+ let find_needle = app.find.as_ref().and_then(|f| find::needle(&f.term));
+ if let (Some(start), Some(hit), Some(needle)) =
+ (layout.find_at, find_hit, find_needle.as_deref())
+ {
+ // Down to the line the match starts on inside its segment (the match
+ // may have wrapped, so its logical line is not a rendered line), measured
+ // with the same wrap the body uses. Only on the jump frame, so the lines
+ // above it are cloned once per step, not every frame.
let above = layout
.segs
.get(layout.find_seg.unwrap_or(usize::MAX))
- .map(|seg| match &seg.lines {
- Some(lines) => lines[..hit.line.min(lines.len())].to_vec(),
- None => app
- .transcript
- .rows
- .get(hit.row)
- .map(|row| {
- let mut lines = row.lines(width);
- lines.truncate(hit.line);
- lines
- })
- .unwrap_or_default(),
+ .map(|seg| {
+ let (mut lines, kept) = match &seg.lines {
+ Some(lines) => (lines.clone(), None),
+ None => match app.transcript.rows.get(hit.row) {
+ Some(row) => (row.lines(width), Some(row.flat())),
+ None => (Vec::new(), None),
+ },
+ };
+ let flat = kept.as_deref().map(Vec::as_slice).or(seg.flat.as_deref());
+ let first = find::occurrences(&lines, flat, needle)
+ .iter()
+ .find(|o| o.logical == hit.line)
+ .and_then(|o| o.pieces.first())
+ .map_or(0, |(line, _)| *line);
+ lines.truncate(first);
+ lines
})
.map_or(0, |lines| wrapped_height(lines, width));
// A third of the way down rather than the top edge, so what led up to
@@ -21498,7 +21561,6 @@ fn draw(f: &mut Frame, app: &mut App) {
let target = start.saturating_add(above).saturating_sub(inner_h / 3);
app.scrollback = max_back.saturating_sub(target);
}
- let find_needle = app.find.as_ref().and_then(|f| find::needle(&f.term));
if let Some(find) = app.find.as_mut() {
find.jump = false;
}
@@ -47171,6 +47233,81 @@ mod tests {
assert!(shown.contains("secret-output-xyz"), "{shown}");
}
+ /// A turn whose answer has three paragraphs; "brown fox" is in the first and
+ /// the last, so where it wraps depends on the width.
+ fn wrapping_answer_app() -> TestApp {
+ let mut app = test_app();
+ app.submit_user("hi".to_string());
+ app.apply(StreamEvent::Token {
+ text: "alpha the quick brown fox jumps over the lazy dog\n\n\
+ nothing to see in this one\n\n\
+ omega another quick brown fox leaps over a sleeping hound"
+ .into(),
+ });
+ app.on_done("stop".into(), None);
+ app
+ }
+
+ /// The text of every highlighted cell, in reading order.
+ fn lit_text(buf: &Buffer) -> String {
+ let mut out = String::new();
+ for y in 0..buf.area.height {
+ for x in 0..buf.area.width {
+ let style = buf[(x, y)].style();
+ let reversed = style
+ .add_modifier
+ .contains(ratatui::style::Modifier::REVERSED);
+ if reversed || style.bg == Some(Color::Yellow) {
+ out.push_str(buf[(x, y)].symbol());
+ }
+ }
+ }
+ out
+ }
+
+ // Regression for a term that word-wraps: matching ran on each rendered
+ // line, so "brown fox" was missed wherever the wrap fell between the words,
+ // and the hit count moved as the window was resized.
+ #[tokio::test]
+ async fn find_matches_a_term_that_wraps_at_any_width() {
+ let mut split_somewhere = false;
+ for width in 14..=100u16 {
+ let mut app = wrapping_answer_app();
+ run_command(&mut app, "find brown fox", &no_mcp()).await;
+ let buf = find_frame(&mut app, width, 70);
+ let hits = app.find.as_ref().unwrap().hits.len();
+ assert_eq!(hits, 2, "one hit per paragraph at width {width}");
+ // Stepping rescans at the new width; it must find the same two.
+ press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
+ let buf_after = find_frame(&mut app, width, 70);
+ assert_eq!(app.find.as_ref().unwrap().hits.len(), 2, "after a step at width {width}");
+
+ // Every occurrence is highlighted whole, on whichever lines it fell.
+ for b in [&buf, &buf_after] {
+ let lit: String = lit_text(b).split_whitespace().collect();
+ assert_eq!(lit, "brownfoxbrownfox", "highlighted at width {width}");
+ }
+ let text = frame_text(&buf);
+ let rows: Vec<&str> = text.lines().collect();
+ split_somewhere |= rows.windows(2).any(|p| {
+ p[0].trim_end().ends_with("brown") && p[1].trim_start().starts_with("fox")
+ });
+ }
+ assert!(split_somewhere, "no width wrapped between the words, so this proved nothing");
+ }
+
+ // The same session searched at two widths steps through the same hits.
+ #[tokio::test]
+ async fn the_hit_count_does_not_change_when_the_window_is_resized() {
+ let mut app = wrapping_answer_app();
+ run_command(&mut app, "find brown fox", &no_mcp()).await;
+ let wide = app.find.as_ref().unwrap().hits.clone();
+ let _ = find_frame(&mut app, 18, 70);
+ press(&mut app, KeyCode::Enter, KeyModifiers::SHIFT).await;
+ let narrow = app.find.as_ref().unwrap().hits.clone();
+ assert_eq!(wide, narrow);
+ }
+
#[test]
fn find_is_a_listed_command_and_keybinding() {
assert!(SLASH_COMMANDS.iter().any(|c| c.name == "/find"));
diff --git a/src-tauri/src/core/cli/tui/find.rs b/src-tauri/src/core/cli/tui/find.rs
index 6bfc50205..7a58fdfad 100644
--- a/src-tauri/src/core/cli/tui/find.rs
+++ b/src-tauri/src/core/cli/tui/find.rs
@@ -11,10 +11,12 @@ use std::ops::Range;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
-/// One matching line: its transcript row, whether it sits in that row's folded
-/// detail (what Ctrl-O or a click reveals) rather than the row itself, and the
-/// line within that part. The field order makes the derived ordering top to
-/// bottom as drawn, which is the order Enter walks.
+/// One matching logical line: its transcript row, whether it sits in that row's
+/// folded detail (what Ctrl-O or a click reveals) rather than the row itself,
+/// and the line within that part as the row says it before the terminal wraps
+/// it. That index does not move when the window resizes, which is what keeps the
+/// hit count and the current hit steady. The field order makes the derived
+/// ordering top to bottom as drawn, which is the order Enter walks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct Hit {
pub(super) row: usize,
@@ -104,14 +106,169 @@ fn current_style() -> Style {
.add_modifier(Modifier::BOLD)
}
-/// `line` with every occurrence of `needle` painted over its own style. Spans
-/// are split at match edges, so a match that straddles two styled spans is
-/// still covered whole. A line without a match comes back unchanged. When
-/// `current` is set the line is the jumped-to hit, and only its first match
-/// gets the current style: hits are whole lines, so that is the one a step landed
-/// on, and the rest stay reversed.
-pub(super) fn highlight_line(line: Line<'static>, needle: &str, current: bool) -> Line<'static> {
- let ranges = match_ranges(&line_text(&line), needle);
+/// The width a row is rendered at to read what it says before the terminal
+/// cuts it into lines. Wide enough that prose does not wrap in practice; a
+/// band that pads to the width (a user turn) stays cheap at this size.
+pub(super) const FLAT_WIDTH: u16 = 2000;
+
+/// `lines` as text, one entry per line, trailing blanks dropped: a row's
+/// unwrapped form when `lines` were rendered at [`FLAT_WIDTH`]. Each entry is a
+/// *logical* line, whose index does not depend on the terminal width.
+pub(super) fn flat_text(lines: &[Line<'_>]) -> Vec<String> {
+ lines
+ .iter()
+ .map(|l| line_text(l).trim_end().to_string())
+ .collect()
+}
+
+/// One place the search term occurs.
+#[derive(Debug, PartialEq, Eq)]
+pub(super) struct Occurrence {
+ /// The logical (unwrapped) line it sits in: the identity of a `Hit`, so the
+ /// hit count and what Enter walks do not change when the window resizes.
+ pub(super) logical: usize,
+ /// Where it lands on the lines as rendered at the current width: one
+ /// (rendered line, byte range in that line's text) per line it spans. A
+ /// term that word-wrapped has a piece on each line.
+ pub(super) pieces: Vec<(usize, Range<usize>)>,
+}
+
+/// Every occurrence of the already-lowercased `needle` in a row part, matched
+/// against its unwrapped text `flat` (see [`flat_text`]) and mapped back onto
+/// `lines`, the part as rendered at the current width. Without `flat` the
+/// rendered lines are the text.
+///
+/// The mapping lines the two renderings up by their non-blank characters, so a
+/// wrap that swallows a space, or a gutter glyph repeated on a continuation
+/// line, does not matter. When they do not line up (a table re-laid out, a
+/// label cut short at a narrow width) the rendered lines are searched on their
+/// own, as they were before the term could span lines.
+pub(super) fn occurrences(
+ lines: &[Line<'_>],
+ flat: Option<&[String]>,
+ needle: &str,
+) -> Vec<Occurrence> {
+ let rendered: Vec<String> = lines.iter().map(line_text).collect();
+ let Some(flat) = flat else {
+ return per_line(&rendered, needle);
+ };
+ let found: Vec<(usize, Range<usize>)> = flat
+ .iter()
+ .enumerate()
+ .flat_map(|(l, text)| match_ranges(text, needle).into_iter().map(move |r| (l, r)))
+ .collect();
+ if found.is_empty() {
+ return Vec::new();
+ }
+ // Nothing wrapped at this width: the unwrapped ranges are the pieces.
+ if rendered.len() == flat.len()
+ && rendered
+ .iter()
+ .zip(flat)
+ .all(|(shown, whole)| shown.trim_end() == whole)
+ {
+ return found
+ .into_iter()
+ .map(|(l, r)| Occurrence {
+ logical: l,
+ pieces: vec![(l, r)],
+ })
+ .collect();
+ }
+ let (whole, shown) = (Glyphs::of(flat), Glyphs::of(&rendered));
+ let Some(map) = whole.onto(&shown) else {
+ return per_line(&rendered, needle);
+ };
+ found
+ .into_iter()
+ .filter_map(|(logical, range)| {
+ let mut pieces: Vec<(usize, Range<usize>)> = Vec::new();
+ for g in whole.within(logical, &range) {
+ let (line, at) = shown.at[map[g]];
+ let end = at + shown.chars[map[g]].len_utf8();
+ match pieces.last_mut() {
+ Some((l, r)) if *l == line => r.end = end,
+ _ => pieces.push((line, at..end)),
+ }
+ }
+ (!pieces.is_empty()).then_some(Occurrence { logical, pieces })
+ })
+ .collect()
+}
+
+/// Occurrences inside single lines, each its own logical line.
+fn per_line(texts: &[String], needle: &str) -> Vec<Occurrence> {
+ texts
+ .iter()
+ .enumerate()
+ .flat_map(|(l, text)| {
+ match_ranges(text, needle)
+ .into_iter()
+ .map(move |r| Occurrence {
+ logical: l,
+ pieces: vec![(l, r)],
+ })
+ })
+ .collect()
+}
+
+/// The non-blank characters of some lines, and where each one sits.
+struct Glyphs {
+ chars: Vec<char>,
+ /// (line, byte offset) of each character.
+ at: Vec<(usize, usize)>,
+ /// Index in `chars` of each line's first character, then `chars.len()`.
+ starts: Vec<usize>,
+}
+
+impl Glyphs {
+ fn of(texts: &[String]) -> Glyphs {
+ let mut g = Glyphs {
+ chars: Vec::new(),
+ at: Vec::new(),
+ starts: Vec::new(),
+ };
+ for (line, text) in texts.iter().enumerate() {
+ g.starts.push(g.chars.len());
+ for (byte, c) in text.char_indices().filter(|(_, c)| !c.is_whitespace()) {
+ g.chars.push(c);
+ g.at.push((line, byte));
+ }
+ }
+ g.starts.push(g.chars.len());
+ g
+ }
+
+ /// Indices of the characters of `line` inside `range`.
+ fn within(&self, line: usize, range: &Range<usize>) -> Range<usize> {
+ let (from, to) = (self.starts[line], self.starts[line + 1]);
+ let before = |at: usize| self.at[from..to].partition_point(|&(_, byte)| byte < at);
+ from + before(range.start)..from + before(range.end)
+ }
+
+ /// For each of this one's characters, the index of the same character in
+ /// `other`, which may carry extras (a gutter glyph repeated on every
+ /// continuation line). `None` when this one has text `other` does not.
+ fn onto(&self, other: &Glyphs) -> Option<Vec<usize>> {
+ let mut map = Vec::with_capacity(self.chars.len());
+ let mut next = 0;
+ for c in &self.chars {
+ let skip = other.chars[next..].iter().position(|o| o == c)?;
+ map.push(next + skip);
+ next += skip + 1;
+ }
+ Some(map)
+ }
+}
+
+/// `line` with `ranges` painted over its own styles, in order. Spans are split
+/// at the edges, so a range that straddles two styled spans is still covered
+/// whole. A `true` range is the match the viewport jumped to and gets the
+/// current style; the rest are reversed.
+pub(super) fn highlight_ranges(
+ line: Line<'static>,
+ ranges: &[(Range<usize>, bool)],
+) -> Line<'static> {
if ranges.is_empty() {
return line;
}
@@ -122,14 +279,24 @@ pub(super) fn highlight_line(line: Line<'static>, needle: &str, current: bool) -
let (start, end) = (offset, offset + text.len());
offset = end;
let mut cut = start;
- for (n, r) in ranges.iter().enumerate() {
+ for (r, current) in ranges {
if r.start >= end || r.end <= start {
continue;
}
- let paint = if current && n == 0 { current_style() } else { match_style() };
- let (a, b) = (r.start.max(start), r.end.min(end));
+ let paint = if *current {
+ current_style()
+ } else {
+ match_style()
+ };
+ let (a, b) = (r.start.max(start).max(cut), r.end.min(end));
+ if b <= a {
+ continue;
+ }
if a > cut {
- spans.push(Span::styled(text[cut - start..a - start].to_string(), span.style));
+ spans.push(Span::styled(
+ text[cut - start..a - start].to_string(),
+ span.style,
+ ));
}
spans.push(Span::styled(
text[a - start..b - start].to_string(),
@@ -141,10 +308,36 @@ pub(super) fn highlight_line(line: Line<'static>, needle: &str, current: bool) -
spans.push(Span::styled(text[cut - start..].to_string(), span.style));
}
}
- Line {
- spans,
- ..line
+ Line { spans, ..line }
+}
+
+/// `lines` with every occurrence painted, each piece onto the line it landed
+/// on. `current` is the logical line of the jumped-to hit: only its first
+/// occurrence gets the current style, so the one a step landed on stands apart
+/// from the rest of the line.
+pub(super) fn paint_lines(
+ lines: Vec<Line<'static>>,
+ found: &[Occurrence],
+ current: Option<usize>,
+) -> Vec<Line<'static>> {
+ if found.is_empty() {
+ return lines;
+ }
+ let mut ranges: Vec<Vec<(Range<usize>, bool)>> = vec![Vec::new(); lines.len()];
+ let mut landed = false;
+ for o in found {
+ let is_current = current == Some(o.logical) && !std::mem::replace(&mut landed, true);
+ for (line, range) in &o.pieces {
+ if let Some(on_line) = ranges.get_mut(*line) {
+ on_line.push((range.clone(), is_current));
+ }
+ }
}
+ lines
+ .into_iter()
+ .zip(ranges)
+ .map(|(line, on_line)| highlight_ranges(line, &on_line))
+ .collect()
}
/// The match a fresh search lands on: the last one at or above `bottom_row`
@@ -155,11 +348,7 @@ pub(super) fn nearest(hits: &[Hit], bottom_row: usize) -> Option<usize> {
if hits.is_empty() {
return None;
}
- Some(
- hits.iter()
- .rposition(|h| h.row <= bottom_row)
- .unwrap_or(0),
- )
+ Some(hits.iter().rposition(|h| h.row <= bottom_row).unwrap_or(0))
}
/// Index of the match after (`forward`) or before `from`, wrapping at either
@@ -226,7 +415,7 @@ mod tests {
Span::styled("say he", Style::new().green()),
Span::styled("llo there", Style::new().blue()),
]);
- let out = highlight_line(line.clone(), "hello", false);
+ let out = paint(line.clone(), "hello", false);
assert_eq!(line_text(&out), line_text(&line), "text is unchanged");
let painted: String = out
.spans
@@ -248,16 +437,16 @@ mod tests {
#[test]
fn highlight_marks_the_current_match_distinctly() {
- let out = highlight_line(Line::raw("a needle"), "needle", true);
+ let out = paint(Line::raw("a needle"), "needle", true);
let hit = out.spans.iter().find(|s| s.content == "needle").unwrap();
assert_eq!(hit.style.bg, Some(Color::Yellow));
- let plain = highlight_line(Line::raw("no match here"), "needle", true);
+ let plain = paint(Line::raw("no match here"), "needle", true);
assert_eq!(plain, Line::raw("no match here"));
}
#[test]
fn only_the_first_match_on_the_current_line_gets_the_current_style() {
- let out = highlight_line(Line::raw("needle and needle"), "needle", true);
+ let out = paint(Line::raw("needle and needle"), "needle", true);
let bands: Vec<bool> = out
.spans
.iter()
@@ -297,4 +486,149 @@ mod tests {
};
assert!(hit(1, 9) < detail && detail < hit(2, 0));
}
+
+ /// `needle` painted onto one unwrapped line the way `draw` does it, with the
+ /// first match as the current one when `current`.
+ fn paint(line: Line<'static>, needle: &str, current: bool) -> Line<'static> {
+ let ranges: Vec<(Range<usize>, bool)> = match_ranges(&line_text(&line), needle)
+ .into_iter()
+ .enumerate()
+ .map(|(n, r)| (r, current && n == 0))
+ .collect();
+ highlight_ranges(line, &ranges)
+ }
+
+ fn rows(texts: &[&str]) -> Vec<Line<'static>> {
+ texts.iter().map(|t| Line::raw(t.to_string())).collect()
+ }
+
+ fn flat(texts: &[&str]) -> Vec<String> {
+ texts.iter().map(|t| t.to_string()).collect()
+ }
+
+ /// The text each piece of `o` covers on `lines`.
+ fn covered(lines: &[&str], o: &Occurrence) -> Vec<String> {
+ o.pieces
+ .iter()
+ .map(|(l, r)| lines[*l][r.clone()].to_string())
+ .collect()
+ }
+
+ #[test]
+ fn a_term_that_wraps_across_two_lines_is_found_with_a_piece_on_each() {
+ let shown = ["• the quick brown", " fox jumps"];
+ let found = occurrences(
+ &rows(&shown),
+ Some(&flat(&["• the quick brown fox jumps"])),
+ "brown fox",
+ );
+ assert_eq!(found.len(), 1);
+ assert_eq!(found[0].logical, 0);
+ assert_eq!(covered(&shown, &found[0]), vec!["brown", "fox"]);
+ }
+
+ #[test]
+ fn the_count_is_the_same_at_every_width() {
+ let whole = flat(&["foo bar foo bar"]);
+ for shown in [
+ vec!["foo bar foo bar"],
+ vec!["foo bar", "foo bar"],
+ vec!["foo", "bar foo", "bar"],
+ vec!["foo", "bar", "foo", "bar"],
+ ] {
+ let found = occurrences(&rows(&shown), Some(&whole), "foo bar");
+ assert_eq!(found.len(), 2, "{shown:?}");
+ assert!(found.iter().all(|o| o.logical == 0), "{shown:?}");
+ // However it wrapped, each occurrence covers all of "foo bar".
+ for o in &found {
+ assert_eq!(
+ covered(&shown, o).join(" ").replace(" ", " "),
+ "foo bar",
+ "{shown:?}"
+ );
+ }
+ }
+ }
+
+ // Lines that are separate in the source stay separate: a term does not run
+ // from the end of one paragraph into the next.
+ #[test]
+ fn a_term_does_not_span_a_real_line_break() {
+ let found = occurrences(
+ &rows(&["alpha", "beta"]),
+ Some(&flat(&["alpha", "beta"])),
+ "alpha beta",
+ );
+ assert!(found.is_empty());
+ }
+
+ #[test]
+ fn a_gutter_glyph_repeated_on_each_continuation_line_is_skipped() {
+ let shown = ["│ alpha beta", "│ gamma delta"];
+ let found = occurrences(
+ &rows(&shown),
+ Some(&flat(&["│ alpha beta gamma delta"])),
+ "beta gamma",
+ );
+ assert_eq!(found.len(), 1);
+ assert_eq!(covered(&shown, &found[0]), vec!["beta", "gamma"]);
+ }
+
+ #[test]
+ fn each_logical_line_keeps_its_own_index() {
+ let shown = ["one hit", "two", "again hit"];
+ let found = occurrences(&rows(&shown), Some(&flat(&shown)), "hit");
+ assert_eq!(
+ found.iter().map(|o| o.logical).collect::<Vec<_>>(),
+ vec![0, 2]
+ );
+ }
+
+ // The rendered lines differ from the unwrapped text beyond wrapping (a
+ // label cut short at a narrow width), so there is nothing to map onto:
+ // search what is shown, and never invent a match for text that is not.
+ #[test]
+ fn text_that_is_not_on_screen_is_not_matched() {
+ let shown = rows(&["label long…"]);
+ let whole = flat(&["label long enough to be cut"]);
+ assert!(occurrences(&shown, Some(&whole), "enough").is_empty());
+ let found = occurrences(&shown, Some(&whole), "label");
+ assert_eq!(found.len(), 1);
+ assert_eq!(found[0].pieces, vec![(0, 0..5)]);
+ }
+
+ #[test]
+ fn without_unwrapped_text_each_rendered_line_is_searched_on_its_own() {
+ let found = occurrences(&rows(&["a hit", "no", "hit hit"]), None, "hit");
+ assert_eq!(found.len(), 3);
+ assert_eq!(found[2].logical, 2);
+ }
+
+ #[test]
+ fn a_wrapped_term_is_painted_on_both_lines() {
+ let shown = ["say hel", "lo there"];
+ // "hel" and "lo" are two pieces of one occurrence, painted on their own lines.
+ let found = occurrences(&rows(&shown), Some(&flat(&["say hello there"])), "hello");
+ assert_eq!(found.len(), 1);
+ let painted: Vec<String> = (0..2)
+ .map(|l| {
+ let ranges: Vec<(Range<usize>, bool)> = found
+ .iter()
+ .flat_map(|o| {
+ o.pieces
+ .iter()
+ .filter(|(pl, _)| *pl == l)
+ .map(|(_, r)| (r.clone(), true))
+ })
+ .collect();
+ highlight_ranges(Line::raw(shown[l].to_string()), &ranges)
+ .spans
+ .iter()
+ .filter(|s| s.style.bg == Some(Color::Yellow))
+ .map(|s| s.content.as_ref())
+ .collect()
+ })
+ .collect();
+ assert_eq!(painted, vec!["hel", "lo"]);
+ }
}