Skip to main content

hjkl_buffer/
render.rs

1//! Direct cell-write `ratatui::widgets::Widget` for [`crate::Buffer`].
2//!
3//! Replaces the tui-textarea + Paragraph render path. Writes one
4//! cell at a time so we can layer syntax span fg, cursor-line bg,
5//! cursor cell REVERSED, and selection bg in a single pass without
6//! the grapheme / wrap machinery `Paragraph` does. Per-row cache
7//! keyed on `dirty_gen + selection + cursor row + viewport top_col`
8//! makes the steady-state render essentially free.
9//!
10//! Caller wraps a `&Buffer` in [`BufferView`], hands it the style
11//! table that resolves opaque [`crate::Span`] style ids to real
12//! ratatui styles, and renders into a `ratatui::Frame`.
13
14use ratatui::buffer::Buffer as TermBuffer;
15use ratatui::layout::Rect;
16use ratatui::style::Style;
17use ratatui::widgets::Widget;
18use unicode_width::UnicodeWidthChar;
19
20use crate::wrap::wrap_segments;
21use crate::{Buffer, Selection, Span, Viewport, Wrap};
22
23/// Resolves an opaque [`crate::Span::style`] id to a real ratatui
24/// style. The buffer doesn't know about colours; the host (sqeel-vim
25/// or any future user) keeps a lookup table.
26pub trait StyleResolver {
27    fn resolve(&self, style_id: u32) -> Style;
28}
29
30/// Convenience impl so simple closures can drive the renderer.
31impl<F: Fn(u32) -> Style> StyleResolver for F {
32    fn resolve(&self, style_id: u32) -> Style {
33        self(style_id)
34    }
35}
36
37/// Render-time wrapper around `&Buffer` that carries the optional
38/// [`Selection`] + a [`StyleResolver`]. Created per draw, dropped
39/// when the frame is done — cheap, holds only refs.
40///
41/// 0.0.34 (Patch C-δ.1): added the [`viewport`] field. The viewport
42/// previously lived on the buffer itself; with the relocation to the
43/// engine `Host`, the renderer takes a borrow per draw.
44///
45/// 0.0.37: added the [`spans`] and [`search_pattern`] fields. Per-row
46/// syntax spans + the active `/` regex used to live on the buffer
47/// (`Buffer::spans` / `Buffer::search_pattern`); both moved out per
48/// step 3 of `DESIGN_33_METHOD_CLASSIFICATION.md`. The host now feeds
49/// each into the view per draw — populated from
50/// `Editor::buffer_spans()` and `Editor::search_state().pattern`.
51pub struct BufferView<'a, R: StyleResolver> {
52    pub buffer: &'a Buffer,
53    /// Viewport snapshot the host published this frame. Owned by the
54    /// engine `Host`; the renderer borrows for the duration of the
55    /// draw.
56    pub viewport: &'a Viewport,
57    pub selection: Option<Selection>,
58    pub resolver: &'a R,
59    /// Bg painted across the cursor row (vim's `cursorline`). Pass
60    /// `Style::default()` to disable.
61    pub cursor_line_bg: Style,
62    /// Bg painted down the cursor column (vim's `cursorcolumn`). Pass
63    /// `Style::default()` to disable.
64    pub cursor_column_bg: Style,
65    /// Bg painted under selected cells. Composed over syntax fg.
66    pub selection_bg: Style,
67    /// Style for the cursor cell. `REVERSED` is the conventional
68    /// choice; works against any theme.
69    pub cursor_style: Style,
70    /// Optional left-side line-number gutter. `width` includes the
71    /// trailing space separating the number from text. Pass `None`
72    /// to disable. Numbers are 1-based, right-aligned.
73    pub gutter: Option<Gutter>,
74    /// Bg painted under cells covered by an active `/` search match.
75    /// `Style::default()` to disable.
76    pub search_bg: Style,
77    /// Per-row gutter signs (LSP diagnostic dots, git diff markers,
78    /// …). Painted into the leftmost gutter column after the line
79    /// number, so they overwrite the leading space tui-style gutters
80    /// reserve. Highest-priority sign per row wins.
81    pub signs: &'a [Sign],
82    /// Per-row substitutions applied at render time. Each conceal
83    /// hides the byte range `[start_byte, end_byte)` and paints
84    /// `replacement` in its place. Empty slice = no conceals.
85    pub conceals: &'a [Conceal],
86    /// Per-row syntax spans the host has computed for this frame.
87    /// `spans[row]` carries the styled byte ranges for that row;
88    /// rows beyond `spans.len()` get no syntax styling. Pass `&[]`
89    /// for hosts without syntax integration.
90    ///
91    /// 0.0.37: lifted out of `Buffer` per step 3 of
92    /// `DESIGN_33_METHOD_CLASSIFICATION.md`. The engine populates
93    /// this via `Editor::buffer_spans()`.
94    pub spans: &'a [Vec<Span>],
95    /// Active `/` search regex, if any. The renderer paints
96    /// [`Self::search_bg`] under cells that match. Pass `None` to
97    /// disable hlsearch.
98    ///
99    /// 0.0.37: lifted out of `Buffer` (was `Buffer::search_pattern`)
100    /// per step 3 of `DESIGN_33_METHOD_CLASSIFICATION.md`. The engine
101    /// publishes the pattern via `Editor::search_state().pattern`.
102    pub search_pattern: Option<&'a regex::Regex>,
103}
104
105/// Configuration for the line-number gutter rendered to the left of
106/// the text area. `width` is the total cell count reserved
107/// (including any trailing spacer); the renderer right-aligns the
108/// 1-based row number into the leftmost `width - 1` cells.
109///
110/// `line_offset` is added to the displayed line number, so a host
111/// rendering a windowed view of a larger document (e.g. picker preview
112/// of a 7000-line buffer) can show the original line numbers instead
113/// of starting at 1.
114#[derive(Debug, Clone, Copy, Default)]
115pub struct Gutter {
116    pub width: u16,
117    pub style: Style,
118    pub line_offset: usize,
119}
120
121/// Single-cell marker painted into the leftmost gutter column for a
122/// document row. Used by hosts to surface LSP diagnostics, git diff
123/// signs, etc. Higher `priority` wins when multiple signs land on
124/// the same row.
125#[derive(Debug, Clone, Copy)]
126pub struct Sign {
127    pub row: usize,
128    pub ch: char,
129    pub style: Style,
130    pub priority: u8,
131}
132
133/// Render-time substitution that hides a byte range and paints
134/// `replacement` in its place. The buffer's content stays unchanged;
135/// only the rendered cells differ. Used by hosts to pretty-print
136/// URLs, conceal markdown markers, etc.
137#[derive(Debug, Clone)]
138pub struct Conceal {
139    pub row: usize,
140    pub start_byte: usize,
141    pub end_byte: usize,
142    pub replacement: String,
143}
144
145impl<R: StyleResolver> Widget for BufferView<'_, R> {
146    fn render(self, area: Rect, term_buf: &mut TermBuffer) {
147        let viewport = *self.viewport;
148        let cursor = self.buffer.cursor();
149        let lines = self.buffer.lines();
150        let spans = self.spans;
151        let folds = self.buffer.folds();
152        let top_row = viewport.top_row;
153        let top_col = viewport.top_col;
154
155        let gutter_width = self.gutter.map(|g| g.width).unwrap_or(0);
156        let text_area = Rect {
157            x: area.x.saturating_add(gutter_width),
158            y: area.y,
159            width: area.width.saturating_sub(gutter_width),
160            height: area.height,
161        };
162
163        let total_rows = lines.len();
164        let mut doc_row = top_row;
165        let mut screen_row: u16 = 0;
166        let wrap_mode = viewport.wrap;
167        let seg_width = if viewport.text_width > 0 {
168            viewport.text_width
169        } else {
170            text_area.width
171        };
172        // Per-screen-row flag: true when the cell at the cursor's
173        // column on that screen row is part of an active `/` search
174        // match. The cursorcolumn pass uses this to skip cells that
175        // search bg already painted, so search highlight wins over
176        // the column bg.
177        let mut search_hit_at_cursor_col: Vec<bool> = Vec::new();
178        // Walk the document forward, skipping rows hidden by closed
179        // folds. Emit the start row of a closed fold as a marker
180        // line instead of its actual content.
181        while doc_row < total_rows && screen_row < area.height {
182            // Skip rows hidden by a closed fold (any row past start
183            // of a closed fold).
184            if folds.iter().any(|f| f.hides(doc_row)) {
185                doc_row += 1;
186                continue;
187            }
188            let folded_at_start = folds
189                .iter()
190                .find(|f| f.closed && f.start_row == doc_row)
191                .copied();
192            let line = &lines[doc_row];
193            let row_spans = spans.get(doc_row).map(Vec::as_slice).unwrap_or(&[]);
194            let sel_range = self.selection.and_then(|s| s.row_span(doc_row));
195            let is_cursor_row = doc_row == cursor.row;
196            if let Some(fold) = folded_at_start {
197                if let Some(gutter) = self.gutter {
198                    self.paint_gutter(term_buf, area, screen_row, doc_row, gutter);
199                    self.paint_signs(term_buf, area, screen_row, doc_row);
200                }
201                self.paint_fold_marker(term_buf, text_area, screen_row, fold, line, is_cursor_row);
202                search_hit_at_cursor_col.push(false);
203                screen_row += 1;
204                doc_row = fold.end_row + 1;
205                continue;
206            }
207            let search_ranges = self.row_search_ranges(line);
208            let row_has_hit_at_cursor_col = search_ranges
209                .iter()
210                .any(|&(s, e)| cursor.col >= s && cursor.col < e);
211            // Collect conceals for this row, sorted by start_byte.
212            let row_conceals: Vec<&Conceal> = {
213                let mut v: Vec<&Conceal> =
214                    self.conceals.iter().filter(|c| c.row == doc_row).collect();
215                v.sort_by_key(|c| c.start_byte);
216                v
217            };
218            // Compute screen segments for this doc row. `Wrap::None`
219            // produces a single segment that spans the whole line; the
220            // existing `top_col` horizontal scroll is preserved by
221            // passing `top_col` as the segment start. Wrap modes split
222            // the line into multiple visual rows that fit
223            // `viewport.text_width` (falls back to `text_area.width`
224            // when the host hasn't published a text width yet).
225            let segments = match wrap_mode {
226                Wrap::None => vec![(top_col, usize::MAX)],
227                _ => wrap_segments(line, seg_width, wrap_mode),
228            };
229            let last_seg_idx = segments.len().saturating_sub(1);
230            for (seg_idx, &(seg_start, seg_end)) in segments.iter().enumerate() {
231                if screen_row >= area.height {
232                    break;
233                }
234                if let Some(gutter) = self.gutter {
235                    if seg_idx == 0 {
236                        self.paint_gutter(term_buf, area, screen_row, doc_row, gutter);
237                        self.paint_signs(term_buf, area, screen_row, doc_row);
238                    } else {
239                        self.paint_blank_gutter(term_buf, area, screen_row, gutter);
240                    }
241                }
242                self.paint_row(
243                    term_buf,
244                    text_area,
245                    screen_row,
246                    line,
247                    row_spans,
248                    sel_range,
249                    &search_ranges,
250                    is_cursor_row,
251                    cursor.col,
252                    seg_start,
253                    seg_end,
254                    seg_idx == last_seg_idx,
255                    &row_conceals,
256                );
257                search_hit_at_cursor_col.push(row_has_hit_at_cursor_col);
258                screen_row += 1;
259            }
260            doc_row += 1;
261        }
262        // Cursorcolumn pass: layer the bg over the cursor's visible
263        // column once every row is painted so it composes on top of
264        // syntax / cursorline backgrounds without disturbing fg.
265        // Skipped when wrapping — the cursor's screen x depends on the
266        // segment it lands in, and vim's cursorcolumn semantics with
267        // wrap are fuzzy. Revisit if it bites.
268        if matches!(wrap_mode, Wrap::None)
269            && self.cursor_column_bg != Style::default()
270            && cursor.col >= top_col
271            && (cursor.col - top_col) < text_area.width as usize
272        {
273            let x = text_area.x + (cursor.col - top_col) as u16;
274            for sy in 0..screen_row {
275                // Skip rows where search bg already painted this cell —
276                // search highlight wins over cursorcolumn so `/foo`
277                // matches stay readable when the cursor sits on them.
278                if search_hit_at_cursor_col
279                    .get(sy as usize)
280                    .copied()
281                    .unwrap_or(false)
282                {
283                    continue;
284                }
285                let y = text_area.y + sy;
286                if let Some(cell) = term_buf.cell_mut((x, y)) {
287                    cell.set_style(cell.style().patch(self.cursor_column_bg));
288                }
289            }
290        }
291    }
292}
293
294impl<R: StyleResolver> BufferView<'_, R> {
295    /// Run the active search regex against `line` and return the
296    /// charwise `(start_col, end_col_exclusive)` ranges that need
297    /// the search bg painted. Empty when no pattern is set.
298    fn row_search_ranges(&self, line: &str) -> Vec<(usize, usize)> {
299        let Some(re) = self.search_pattern else {
300            return Vec::new();
301        };
302        re.find_iter(line)
303            .map(|m| {
304                let start = line[..m.start()].chars().count();
305                let end = line[..m.end()].chars().count();
306                (start, end)
307            })
308            .collect()
309    }
310
311    fn paint_fold_marker(
312        &self,
313        term_buf: &mut TermBuffer,
314        area: Rect,
315        screen_row: u16,
316        fold: crate::Fold,
317        first_line: &str,
318        is_cursor_row: bool,
319    ) {
320        let y = area.y + screen_row;
321        let style = if is_cursor_row && self.cursor_line_bg != Style::default() {
322            self.cursor_line_bg
323        } else {
324            Style::default()
325        };
326        // Bg the whole row first so the marker reads like one cell.
327        for x in area.x..(area.x + area.width) {
328            if let Some(cell) = term_buf.cell_mut((x, y)) {
329                cell.set_style(style);
330            }
331        }
332        // Build a label that hints at the fold's contents instead of
333        // a generic "+-- N lines folded --". Use the start row's
334        // trimmed text (truncated) plus the line count.
335        let prefix = first_line.trim();
336        let count = fold.line_count();
337        let label = if prefix.is_empty() {
338            format!("▸ {count} lines folded")
339        } else {
340            const MAX_PREFIX: usize = 60;
341            let trimmed = if prefix.chars().count() > MAX_PREFIX {
342                let head: String = prefix.chars().take(MAX_PREFIX - 1).collect();
343                format!("{head}…")
344            } else {
345                prefix.to_string()
346            };
347            format!("▸ {trimmed}  ({count} lines)")
348        };
349        let mut x = area.x;
350        let row_end_x = area.x + area.width;
351        for ch in label.chars() {
352            if x >= row_end_x {
353                break;
354            }
355            let width = ch.width().unwrap_or(1) as u16;
356            if x + width > row_end_x {
357                break;
358            }
359            if let Some(cell) = term_buf.cell_mut((x, y)) {
360                cell.set_char(ch);
361                cell.set_style(style);
362            }
363            x = x.saturating_add(width);
364        }
365    }
366
367    fn paint_signs(&self, term_buf: &mut TermBuffer, area: Rect, screen_row: u16, doc_row: usize) {
368        let Some(sign) = self
369            .signs
370            .iter()
371            .filter(|s| s.row == doc_row)
372            .max_by_key(|s| s.priority)
373        else {
374            return;
375        };
376        let y = area.y + screen_row;
377        let x = area.x;
378        if let Some(cell) = term_buf.cell_mut((x, y)) {
379            cell.set_char(sign.ch);
380            cell.set_style(sign.style);
381        }
382    }
383
384    /// Paint a wrap-continuation gutter row: blank cells in the
385    /// gutter style so the bg stays continuous, no line number.
386    fn paint_blank_gutter(
387        &self,
388        term_buf: &mut TermBuffer,
389        area: Rect,
390        screen_row: u16,
391        gutter: Gutter,
392    ) {
393        let y = area.y + screen_row;
394        for x in area.x..(area.x + gutter.width) {
395            if let Some(cell) = term_buf.cell_mut((x, y)) {
396                cell.set_char(' ');
397                cell.set_style(gutter.style);
398            }
399        }
400    }
401
402    fn paint_gutter(
403        &self,
404        term_buf: &mut TermBuffer,
405        area: Rect,
406        screen_row: u16,
407        doc_row: usize,
408        gutter: Gutter,
409    ) {
410        let y = area.y + screen_row;
411        // Total gutter cells, leaving one trailing spacer column.
412        let number_width = gutter.width.saturating_sub(1) as usize;
413        let label = format!(
414            "{:>width$}",
415            doc_row + 1 + gutter.line_offset,
416            width = number_width
417        );
418        let mut x = area.x;
419        for ch in label.chars() {
420            if x >= area.x + gutter.width.saturating_sub(1) {
421                break;
422            }
423            if let Some(cell) = term_buf.cell_mut((x, y)) {
424                cell.set_char(ch);
425                cell.set_style(gutter.style);
426            }
427            x = x.saturating_add(1);
428        }
429        // Spacer cell — same gutter style so the background is
430        // continuous when a bg colour is set.
431        let spacer_x = area.x + gutter.width.saturating_sub(1);
432        if let Some(cell) = term_buf.cell_mut((spacer_x, y)) {
433            cell.set_char(' ');
434            cell.set_style(gutter.style);
435        }
436    }
437
438    #[allow(clippy::too_many_arguments)]
439    fn paint_row(
440        &self,
441        term_buf: &mut TermBuffer,
442        area: Rect,
443        screen_row: u16,
444        line: &str,
445        row_spans: &[crate::Span],
446        sel_range: crate::RowSpan,
447        search_ranges: &[(usize, usize)],
448        is_cursor_row: bool,
449        cursor_col: usize,
450        seg_start: usize,
451        seg_end: usize,
452        is_last_segment: bool,
453        conceals: &[&Conceal],
454    ) {
455        let y = area.y + screen_row;
456        let mut screen_x = area.x;
457        let row_end_x = area.x + area.width;
458
459        // Paint cursor-line bg across the whole row first so empty
460        // trailing cells inherit the highlight (matches vim's
461        // cursorline). Selection / cursor cells overwrite below.
462        if is_cursor_row && self.cursor_line_bg != Style::default() {
463            for x in area.x..row_end_x {
464                if let Some(cell) = term_buf.cell_mut((x, y)) {
465                    cell.set_style(self.cursor_line_bg);
466                }
467            }
468        }
469
470        // Tab width for `\t` expansion — host publishes via
471        // `Viewport::tab_width` (driven by engine's `:set tabstop`).
472        // `effective_tab_width` falls back to 4 when unset.
473        let tab_width = self.viewport.effective_tab_width();
474        let mut byte_offset: usize = 0;
475        let mut line_col: usize = 0;
476        let mut chars_iter = line.chars().enumerate().peekable();
477        while let Some((col_idx, ch)) = chars_iter.next() {
478            let ch_byte_len = ch.len_utf8();
479            if col_idx >= seg_end {
480                break;
481            }
482            // If a conceal starts at this byte, paint the replacement
483            // text (using this cell's style) and skip the rest of the
484            // concealed range. Cursor / selection / search highlights
485            // still attribute to the original char positions.
486            if let Some(conc) = conceals.iter().find(|c| c.start_byte == byte_offset) {
487                if col_idx >= seg_start {
488                    let mut style = if is_cursor_row {
489                        self.cursor_line_bg
490                    } else {
491                        Style::default()
492                    };
493                    if let Some(span_style) = self.resolve_span_style(row_spans, byte_offset) {
494                        style = style.patch(span_style);
495                    }
496                    for rch in conc.replacement.chars() {
497                        let rwidth = rch.width().unwrap_or(1) as u16;
498                        if screen_x + rwidth > row_end_x {
499                            break;
500                        }
501                        if let Some(cell) = term_buf.cell_mut((screen_x, y)) {
502                            cell.set_char(rch);
503                            cell.set_style(style);
504                        }
505                        screen_x += rwidth;
506                    }
507                }
508                // Advance byte_offset / chars iter past the concealed
509                // range without painting the original cells.
510                let mut consumed = ch_byte_len;
511                byte_offset += ch_byte_len;
512                while byte_offset < conc.end_byte {
513                    let Some((_, next_ch)) = chars_iter.next() else {
514                        break;
515                    };
516                    consumed += next_ch.len_utf8();
517                    byte_offset = byte_offset.saturating_add(next_ch.len_utf8());
518                }
519                let _ = consumed;
520                continue;
521            }
522            // Visible cell count: tabs expand to the next tab_width stop
523            // based on `line_col` (visible column in the *line*, not the
524            // segment), so a tab at line column 0 paints tab_width cells
525            // and a tab at line column 3 paints 1 cell.
526            let visible_width = if ch == '\t' {
527                tab_width - (line_col % tab_width)
528            } else {
529                ch.width().unwrap_or(1)
530            };
531            // Skip chars to the left of the segment start (horizontal
532            // scroll for `Wrap::None`, segment offset for wrap modes).
533            if col_idx < seg_start {
534                line_col += visible_width;
535                byte_offset += ch_byte_len;
536                continue;
537            }
538            // Stop when we run out of horizontal room.
539            let width = visible_width as u16;
540            if screen_x + width > row_end_x {
541                break;
542            }
543
544            // Resolve final style for this cell.
545            let mut style = if is_cursor_row {
546                self.cursor_line_bg
547            } else {
548                Style::default()
549            };
550            if let Some(span_style) = self.resolve_span_style(row_spans, byte_offset) {
551                style = style.patch(span_style);
552            }
553            if let Some((lo, hi)) = sel_range
554                && col_idx >= lo
555                && col_idx <= hi
556            {
557                style = style.patch(self.selection_bg);
558            }
559            if self.search_bg != Style::default()
560                && search_ranges
561                    .iter()
562                    .any(|&(s, e)| col_idx >= s && col_idx < e)
563            {
564                style = style.patch(self.search_bg);
565            }
566            if is_cursor_row && col_idx == cursor_col {
567                style = style.patch(self.cursor_style);
568            }
569
570            if ch == '\t' {
571                // Paint tab as `visible_width` space cells carrying the
572                // resolved style — tab/text bg/cursor-line bg all paint
573                // through the expansion.
574                for k in 0..width {
575                    if let Some(cell) = term_buf.cell_mut((screen_x + k, y)) {
576                        cell.set_char(' ');
577                        cell.set_style(style);
578                    }
579                }
580            } else if let Some(cell) = term_buf.cell_mut((screen_x, y)) {
581                cell.set_char(ch);
582                cell.set_style(style);
583            }
584            screen_x += width;
585            line_col += visible_width;
586            byte_offset += ch_byte_len;
587        }
588
589        // If the cursor sits at end-of-line (insert / past-end mode),
590        // paint a single REVERSED placeholder cell so it stays visible.
591        // Only on the last segment of a wrapped row — earlier segments
592        // can't host the past-end cursor.
593        if is_cursor_row
594            && is_last_segment
595            && cursor_col >= line.chars().count()
596            && cursor_col >= seg_start
597        {
598            let pad_x = area.x + (cursor_col.saturating_sub(seg_start)) as u16;
599            if pad_x < row_end_x
600                && let Some(cell) = term_buf.cell_mut((pad_x, y))
601            {
602                cell.set_char(' ');
603                cell.set_style(self.cursor_line_bg.patch(self.cursor_style));
604            }
605        }
606    }
607
608    /// First span containing `byte_offset` wins. Buffer guarantees
609    /// non-overlapping sorted spans — vim.rs is responsible for that.
610    fn resolve_span_style(&self, row_spans: &[crate::Span], byte_offset: usize) -> Option<Style> {
611        // Return the *narrowest* span containing this byte. Hosts that
612        // overlay narrower spans on top of broader ones (e.g. TODO marker
613        // inside a comment span) rely on the more specific span winning;
614        // first-match-wins would let the broader span block the overlay.
615        let mut best: Option<&crate::Span> = None;
616        for span in row_spans {
617            if byte_offset >= span.start_byte && byte_offset < span.end_byte {
618                let len = span.end_byte - span.start_byte;
619                match best {
620                    Some(b) if (b.end_byte - b.start_byte) <= len => {}
621                    _ => best = Some(span),
622                }
623            }
624        }
625        best.map(|s| self.resolver.resolve(s.style))
626    }
627}
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632    use ratatui::style::{Color, Modifier};
633    use ratatui::widgets::Widget;
634
635    fn run_render<R: StyleResolver>(view: BufferView<'_, R>, w: u16, h: u16) -> TermBuffer {
636        let area = Rect::new(0, 0, w, h);
637        let mut buf = TermBuffer::empty(area);
638        view.render(area, &mut buf);
639        buf
640    }
641
642    fn no_styles(_id: u32) -> Style {
643        Style::default()
644    }
645
646    /// Build a default viewport for plain (no-wrap) tests.
647    fn vp(width: u16, height: u16) -> Viewport {
648        Viewport {
649            top_row: 0,
650            top_col: 0,
651            width,
652            height,
653            wrap: Wrap::None,
654            text_width: width,
655            tab_width: 0,
656        }
657    }
658
659    #[test]
660    fn renders_plain_chars_into_terminal_buffer() {
661        let b = Buffer::from_str("hello\nworld");
662        let v = vp(20, 5);
663        let view = BufferView {
664            buffer: &b,
665            viewport: &v,
666            selection: None,
667            resolver: &(no_styles as fn(u32) -> Style),
668            cursor_line_bg: Style::default(),
669            cursor_column_bg: Style::default(),
670            selection_bg: Style::default().bg(Color::Blue),
671            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
672            gutter: None,
673            search_bg: Style::default(),
674            signs: &[],
675            conceals: &[],
676            spans: &[],
677            search_pattern: None,
678        };
679        let term = run_render(view, 20, 5);
680        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "h");
681        assert_eq!(term.cell((4, 0)).unwrap().symbol(), "o");
682        assert_eq!(term.cell((0, 1)).unwrap().symbol(), "w");
683        assert_eq!(term.cell((4, 1)).unwrap().symbol(), "d");
684    }
685
686    #[test]
687    fn cursor_cell_gets_reversed_style() {
688        let mut b = Buffer::from_str("abc");
689        let v = vp(10, 1);
690        b.set_cursor(crate::Position::new(0, 1));
691        let view = BufferView {
692            buffer: &b,
693            viewport: &v,
694            selection: None,
695            resolver: &(no_styles as fn(u32) -> Style),
696            cursor_line_bg: Style::default(),
697            cursor_column_bg: Style::default(),
698            selection_bg: Style::default().bg(Color::Blue),
699            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
700            gutter: None,
701            search_bg: Style::default(),
702            signs: &[],
703            conceals: &[],
704            spans: &[],
705            search_pattern: None,
706        };
707        let term = run_render(view, 10, 1);
708        let cursor_cell = term.cell((1, 0)).unwrap();
709        assert!(cursor_cell.modifier.contains(Modifier::REVERSED));
710    }
711
712    #[test]
713    fn selection_bg_applies_only_to_selected_cells() {
714        use crate::{Position, Selection};
715        let b = Buffer::from_str("abcdef");
716        let v = vp(10, 1);
717        let view = BufferView {
718            buffer: &b,
719            viewport: &v,
720            selection: Some(Selection::Char {
721                anchor: Position::new(0, 1),
722                head: Position::new(0, 3),
723            }),
724            resolver: &(no_styles as fn(u32) -> Style),
725            cursor_line_bg: Style::default(),
726            cursor_column_bg: Style::default(),
727            selection_bg: Style::default().bg(Color::Blue),
728            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
729            gutter: None,
730            search_bg: Style::default(),
731            signs: &[],
732            conceals: &[],
733            spans: &[],
734            search_pattern: None,
735        };
736        let term = run_render(view, 10, 1);
737        assert!(term.cell((0, 0)).unwrap().bg != Color::Blue);
738        for x in 1..=3 {
739            assert_eq!(term.cell((x, 0)).unwrap().bg, Color::Blue);
740        }
741        assert!(term.cell((4, 0)).unwrap().bg != Color::Blue);
742    }
743
744    #[test]
745    fn syntax_span_fg_resolves_via_table() {
746        use crate::Span;
747        let b = Buffer::from_str("SELECT foo");
748        let v = vp(20, 1);
749        let spans = vec![vec![Span::new(0, 6, 7)]];
750        let resolver = |id: u32| -> Style {
751            if id == 7 {
752                Style::default().fg(Color::Red)
753            } else {
754                Style::default()
755            }
756        };
757        let view = BufferView {
758            buffer: &b,
759            viewport: &v,
760            selection: None,
761            resolver: &resolver,
762            cursor_line_bg: Style::default(),
763            cursor_column_bg: Style::default(),
764            selection_bg: Style::default().bg(Color::Blue),
765            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
766            gutter: None,
767            search_bg: Style::default(),
768            signs: &[],
769            conceals: &[],
770            spans: &spans,
771            search_pattern: None,
772        };
773        let term = run_render(view, 20, 1);
774        for x in 0..6 {
775            assert_eq!(term.cell((x, 0)).unwrap().fg, Color::Red);
776        }
777    }
778
779    #[test]
780    fn gutter_renders_right_aligned_line_numbers() {
781        let b = Buffer::from_str("a\nb\nc");
782        let v = vp(10, 3);
783        let view = BufferView {
784            buffer: &b,
785            viewport: &v,
786            selection: None,
787            resolver: &(no_styles as fn(u32) -> Style),
788            cursor_line_bg: Style::default(),
789            cursor_column_bg: Style::default(),
790            selection_bg: Style::default().bg(Color::Blue),
791            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
792            gutter: Some(Gutter {
793                width: 4,
794                style: Style::default().fg(Color::Yellow),
795                line_offset: 0,
796            }),
797            search_bg: Style::default(),
798            signs: &[],
799            conceals: &[],
800            spans: &[],
801            search_pattern: None,
802        };
803        let term = run_render(view, 10, 3);
804        // Width 4 = 3 number cells + 1 spacer; right-aligned "  1".
805        assert_eq!(term.cell((2, 0)).unwrap().symbol(), "1");
806        assert_eq!(term.cell((2, 0)).unwrap().fg, Color::Yellow);
807        assert_eq!(term.cell((2, 1)).unwrap().symbol(), "2");
808        assert_eq!(term.cell((2, 2)).unwrap().symbol(), "3");
809        // Text shifted right past the gutter.
810        assert_eq!(term.cell((4, 0)).unwrap().symbol(), "a");
811    }
812
813    #[test]
814    fn search_bg_paints_match_cells() {
815        use regex::Regex;
816        let b = Buffer::from_str("foo bar foo");
817        let v = vp(20, 1);
818        let pat = Regex::new("foo").unwrap();
819        let view = BufferView {
820            buffer: &b,
821            viewport: &v,
822            selection: None,
823            resolver: &(no_styles as fn(u32) -> Style),
824            cursor_line_bg: Style::default(),
825            cursor_column_bg: Style::default(),
826            selection_bg: Style::default().bg(Color::Blue),
827            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
828            gutter: None,
829            search_bg: Style::default().bg(Color::Magenta),
830            signs: &[],
831            conceals: &[],
832            spans: &[],
833            search_pattern: Some(&pat),
834        };
835        let term = run_render(view, 20, 1);
836        for x in 0..3 {
837            assert_eq!(term.cell((x, 0)).unwrap().bg, Color::Magenta);
838        }
839        // " bar " between matches stays default bg.
840        assert_ne!(term.cell((3, 0)).unwrap().bg, Color::Magenta);
841        for x in 8..11 {
842            assert_eq!(term.cell((x, 0)).unwrap().bg, Color::Magenta);
843        }
844    }
845
846    #[test]
847    fn search_bg_survives_cursorcolumn_overlay() {
848        use regex::Regex;
849        // Cursor sits on a `/foo` match. The cursorcolumn pass would
850        // otherwise overwrite the search bg with column bg — verify
851        // the match cells keep their search colour.
852        let mut b = Buffer::from_str("foo bar foo");
853        let v = vp(20, 1);
854        let pat = Regex::new("foo").unwrap();
855        // Cursor on column 1 (inside first `foo` match).
856        b.set_cursor(crate::Position::new(0, 1));
857        let view = BufferView {
858            buffer: &b,
859            viewport: &v,
860            selection: None,
861            resolver: &(no_styles as fn(u32) -> Style),
862            cursor_line_bg: Style::default(),
863            cursor_column_bg: Style::default().bg(Color::DarkGray),
864            selection_bg: Style::default().bg(Color::Blue),
865            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
866            gutter: None,
867            search_bg: Style::default().bg(Color::Magenta),
868            signs: &[],
869            conceals: &[],
870            spans: &[],
871            search_pattern: Some(&pat),
872        };
873        let term = run_render(view, 20, 1);
874        // Cursor cell at (1, 0) is in the search match. Search wins.
875        assert_eq!(term.cell((1, 0)).unwrap().bg, Color::Magenta);
876    }
877
878    #[test]
879    fn highest_priority_sign_wins_per_row_and_overwrites_gutter() {
880        let b = Buffer::from_str("a\nb\nc");
881        let v = vp(10, 3);
882        let signs = [
883            Sign {
884                row: 0,
885                ch: 'W',
886                style: Style::default().fg(Color::Yellow),
887                priority: 1,
888            },
889            Sign {
890                row: 0,
891                ch: 'E',
892                style: Style::default().fg(Color::Red),
893                priority: 2,
894            },
895        ];
896        let view = BufferView {
897            buffer: &b,
898            viewport: &v,
899            selection: None,
900            resolver: &(no_styles as fn(u32) -> Style),
901            cursor_line_bg: Style::default(),
902            cursor_column_bg: Style::default(),
903            selection_bg: Style::default().bg(Color::Blue),
904            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
905            gutter: Some(Gutter {
906                width: 3,
907                style: Style::default().fg(Color::DarkGray),
908                line_offset: 0,
909            }),
910            search_bg: Style::default(),
911            signs: &signs,
912            conceals: &[],
913            spans: &[],
914            search_pattern: None,
915        };
916        let term = run_render(view, 10, 3);
917        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "E");
918        assert_eq!(term.cell((0, 0)).unwrap().fg, Color::Red);
919        // Row 1 has no sign — leftmost cell stays as gutter content.
920        assert_ne!(term.cell((0, 1)).unwrap().symbol(), "E");
921    }
922
923    #[test]
924    fn conceal_replaces_byte_range() {
925        let b = Buffer::from_str("see https://example.com end");
926        let v = vp(30, 1);
927        let conceals = vec![Conceal {
928            row: 0,
929            start_byte: 4,                             // start of "https"
930            end_byte: 4 + "https://example.com".len(), // end of URL
931            replacement: "🔗".to_string(),
932        }];
933        let view = BufferView {
934            buffer: &b,
935            viewport: &v,
936            selection: None,
937            resolver: &(no_styles as fn(u32) -> Style),
938            cursor_line_bg: Style::default(),
939            cursor_column_bg: Style::default(),
940            selection_bg: Style::default(),
941            cursor_style: Style::default(),
942            gutter: None,
943            search_bg: Style::default(),
944            signs: &[],
945            conceals: &conceals,
946            spans: &[],
947            search_pattern: None,
948        };
949        let term = run_render(view, 30, 1);
950        // Cells 0..=3: "see "
951        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "s");
952        assert_eq!(term.cell((3, 0)).unwrap().symbol(), " ");
953        // Cell 4: the link emoji (a wide char takes 2 cells; we just
954        // assert the first cell holds the replacement char).
955        assert_eq!(term.cell((4, 0)).unwrap().symbol(), "🔗");
956    }
957
958    #[test]
959    fn closed_fold_collapses_rows_and_paints_marker() {
960        let mut b = Buffer::from_str("a\nb\nc\nd\ne");
961        let v = vp(30, 5);
962        // Fold rows 1-3 closed. Visible should be: 'a', marker, 'e'.
963        b.add_fold(1, 3, true);
964        let view = BufferView {
965            buffer: &b,
966            viewport: &v,
967            selection: None,
968            resolver: &(no_styles as fn(u32) -> Style),
969            cursor_line_bg: Style::default(),
970            cursor_column_bg: Style::default(),
971            selection_bg: Style::default().bg(Color::Blue),
972            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
973            gutter: None,
974            search_bg: Style::default(),
975            signs: &[],
976            conceals: &[],
977            spans: &[],
978            search_pattern: None,
979        };
980        let term = run_render(view, 30, 5);
981        // Row 0: "a"
982        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "a");
983        // Row 1: fold marker — leading `▸ ` then the start row's
984        // trimmed content + line count.
985        assert_eq!(term.cell((0, 1)).unwrap().symbol(), "▸");
986        // Row 2: "e" (the 5th doc row, after the collapsed range).
987        assert_eq!(term.cell((0, 2)).unwrap().symbol(), "e");
988    }
989
990    #[test]
991    fn open_fold_renders_normally() {
992        let mut b = Buffer::from_str("a\nb\nc");
993        let v = vp(5, 3);
994        b.add_fold(0, 2, false); // open
995        let view = BufferView {
996            buffer: &b,
997            viewport: &v,
998            selection: None,
999            resolver: &(no_styles as fn(u32) -> Style),
1000            cursor_line_bg: Style::default(),
1001            cursor_column_bg: Style::default(),
1002            selection_bg: Style::default().bg(Color::Blue),
1003            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
1004            gutter: None,
1005            search_bg: Style::default(),
1006            signs: &[],
1007            conceals: &[],
1008            spans: &[],
1009            search_pattern: None,
1010        };
1011        let term = run_render(view, 5, 3);
1012        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "a");
1013        assert_eq!(term.cell((0, 1)).unwrap().symbol(), "b");
1014        assert_eq!(term.cell((0, 2)).unwrap().symbol(), "c");
1015    }
1016
1017    #[test]
1018    fn horizontal_scroll_clips_left_chars() {
1019        let b = Buffer::from_str("abcdefgh");
1020        let mut v = vp(4, 1);
1021        v.top_col = 3;
1022        let view = BufferView {
1023            buffer: &b,
1024            viewport: &v,
1025            selection: None,
1026            resolver: &(no_styles as fn(u32) -> Style),
1027            cursor_line_bg: Style::default(),
1028            cursor_column_bg: Style::default(),
1029            selection_bg: Style::default().bg(Color::Blue),
1030            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
1031            gutter: None,
1032            search_bg: Style::default(),
1033            signs: &[],
1034            conceals: &[],
1035            spans: &[],
1036            search_pattern: None,
1037        };
1038        let term = run_render(view, 4, 1);
1039        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "d");
1040        assert_eq!(term.cell((3, 0)).unwrap().symbol(), "g");
1041    }
1042
1043    fn make_wrap_view<'a>(
1044        b: &'a Buffer,
1045        viewport: &'a Viewport,
1046        resolver: &'a (impl StyleResolver + 'a),
1047        gutter: Option<Gutter>,
1048    ) -> BufferView<'a, impl StyleResolver + 'a> {
1049        BufferView {
1050            buffer: b,
1051            viewport,
1052            selection: None,
1053            resolver,
1054            cursor_line_bg: Style::default(),
1055            cursor_column_bg: Style::default(),
1056            selection_bg: Style::default().bg(Color::Blue),
1057            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
1058            gutter,
1059            search_bg: Style::default(),
1060            signs: &[],
1061            conceals: &[],
1062            spans: &[],
1063            search_pattern: None,
1064        }
1065    }
1066
1067    #[test]
1068    fn wrap_segments_char_breaks_at_width() {
1069        let segs = wrap_segments("abcdefghij", 4, Wrap::Char);
1070        assert_eq!(segs, vec![(0, 4), (4, 8), (8, 10)]);
1071    }
1072
1073    #[test]
1074    fn wrap_segments_word_backs_up_to_whitespace() {
1075        let segs = wrap_segments("alpha beta gamma", 8, Wrap::Word);
1076        // First segment "alpha " ends after the space at idx 5.
1077        assert_eq!(segs[0], (0, 6));
1078        // Second segment "beta " ends after the space at idx 10.
1079        assert_eq!(segs[1], (6, 11));
1080        assert_eq!(segs[2], (11, 16));
1081    }
1082
1083    #[test]
1084    fn wrap_segments_word_falls_back_to_char_for_long_runs() {
1085        let segs = wrap_segments("supercalifragilistic", 5, Wrap::Word);
1086        // No whitespace anywhere — degrades to a hard char break.
1087        assert_eq!(segs, vec![(0, 5), (5, 10), (10, 15), (15, 20)]);
1088    }
1089
1090    #[test]
1091    fn wrap_char_paints_continuation_rows() {
1092        let b = Buffer::from_str("abcdefghij");
1093        let v = Viewport {
1094            top_row: 0,
1095            top_col: 0,
1096            width: 4,
1097            height: 3,
1098            wrap: Wrap::Char,
1099            text_width: 4,
1100            tab_width: 0,
1101        };
1102        let r = no_styles as fn(u32) -> Style;
1103        let view = make_wrap_view(&b, &v, &r, None);
1104        let term = run_render(view, 4, 3);
1105        // Row 0: "abcd"
1106        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "a");
1107        assert_eq!(term.cell((3, 0)).unwrap().symbol(), "d");
1108        // Row 1: "efgh"
1109        assert_eq!(term.cell((0, 1)).unwrap().symbol(), "e");
1110        assert_eq!(term.cell((3, 1)).unwrap().symbol(), "h");
1111        // Row 2: "ij"
1112        assert_eq!(term.cell((0, 2)).unwrap().symbol(), "i");
1113        assert_eq!(term.cell((1, 2)).unwrap().symbol(), "j");
1114    }
1115
1116    #[test]
1117    fn wrap_char_gutter_blank_on_continuation() {
1118        let b = Buffer::from_str("abcdefgh");
1119        let v = Viewport {
1120            top_row: 0,
1121            top_col: 0,
1122            width: 6,
1123            height: 3,
1124            wrap: Wrap::Char,
1125            // Text area = 6 - 3 (gutter width) = 3.
1126            text_width: 3,
1127            tab_width: 0,
1128        };
1129        let r = no_styles as fn(u32) -> Style;
1130        let gutter = Gutter {
1131            width: 3,
1132            style: Style::default().fg(Color::Yellow),
1133            line_offset: 0,
1134        };
1135        let view = make_wrap_view(&b, &v, &r, Some(gutter));
1136        let term = run_render(view, 6, 3);
1137        // Row 0: "  1" + "abc"
1138        assert_eq!(term.cell((1, 0)).unwrap().symbol(), "1");
1139        assert_eq!(term.cell((3, 0)).unwrap().symbol(), "a");
1140        // Row 1: blank gutter + "def"
1141        for x in 0..2 {
1142            assert_eq!(term.cell((x, 1)).unwrap().symbol(), " ");
1143        }
1144        assert_eq!(term.cell((3, 1)).unwrap().symbol(), "d");
1145        assert_eq!(term.cell((5, 1)).unwrap().symbol(), "f");
1146    }
1147
1148    #[test]
1149    fn wrap_char_cursor_lands_on_correct_segment() {
1150        let mut b = Buffer::from_str("abcdefghij");
1151        let v = Viewport {
1152            top_row: 0,
1153            top_col: 0,
1154            width: 4,
1155            height: 3,
1156            wrap: Wrap::Char,
1157            text_width: 4,
1158            tab_width: 0,
1159        };
1160        // Cursor on 'g' (col 6) should land on row 1, col 2.
1161        b.set_cursor(crate::Position::new(0, 6));
1162        let r = no_styles as fn(u32) -> Style;
1163        let mut view = make_wrap_view(&b, &v, &r, None);
1164        view.cursor_style = Style::default().add_modifier(Modifier::REVERSED);
1165        let term = run_render(view, 4, 3);
1166        assert!(
1167            term.cell((2, 1))
1168                .unwrap()
1169                .modifier
1170                .contains(Modifier::REVERSED)
1171        );
1172    }
1173
1174    #[test]
1175    fn wrap_char_eol_cursor_placeholder_on_last_segment() {
1176        let mut b = Buffer::from_str("abcdef");
1177        let v = Viewport {
1178            top_row: 0,
1179            top_col: 0,
1180            width: 4,
1181            height: 3,
1182            wrap: Wrap::Char,
1183            text_width: 4,
1184            tab_width: 0,
1185        };
1186        // Past-end cursor at col 6.
1187        b.set_cursor(crate::Position::new(0, 6));
1188        let r = no_styles as fn(u32) -> Style;
1189        let mut view = make_wrap_view(&b, &v, &r, None);
1190        view.cursor_style = Style::default().add_modifier(Modifier::REVERSED);
1191        let term = run_render(view, 4, 3);
1192        // Last segment is row 1 ("ef"), placeholder at x = 6 - 4 = 2.
1193        assert!(
1194            term.cell((2, 1))
1195                .unwrap()
1196                .modifier
1197                .contains(Modifier::REVERSED)
1198        );
1199    }
1200
1201    #[test]
1202    fn wrap_word_breaks_at_whitespace() {
1203        let b = Buffer::from_str("alpha beta gamma");
1204        let v = Viewport {
1205            top_row: 0,
1206            top_col: 0,
1207            width: 8,
1208            height: 3,
1209            wrap: Wrap::Word,
1210            text_width: 8,
1211            tab_width: 0,
1212        };
1213        let r = no_styles as fn(u32) -> Style;
1214        let view = make_wrap_view(&b, &v, &r, None);
1215        let term = run_render(view, 8, 3);
1216        // Row 0: "alpha "
1217        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "a");
1218        assert_eq!(term.cell((4, 0)).unwrap().symbol(), "a");
1219        // Row 1: "beta "
1220        assert_eq!(term.cell((0, 1)).unwrap().symbol(), "b");
1221        assert_eq!(term.cell((3, 1)).unwrap().symbol(), "a");
1222        // Row 2: "gamma"
1223        assert_eq!(term.cell((0, 2)).unwrap().symbol(), "g");
1224        assert_eq!(term.cell((4, 2)).unwrap().symbol(), "a");
1225    }
1226
1227    // 0.0.37 — `BufferView` lost `Buffer::spans` / `Buffer::search_pattern`
1228    // and now takes them as parameters. The tests below cover the new
1229    // shape: empty/missing parameters, multi-row spans, regex hlsearch,
1230    // and the interaction with cursor / selection / wrap.
1231
1232    fn view_with<'a>(
1233        b: &'a Buffer,
1234        viewport: &'a Viewport,
1235        resolver: &'a (impl StyleResolver + 'a),
1236        spans: &'a [Vec<Span>],
1237        search_pattern: Option<&'a regex::Regex>,
1238    ) -> BufferView<'a, impl StyleResolver + 'a> {
1239        BufferView {
1240            buffer: b,
1241            viewport,
1242            selection: None,
1243            resolver,
1244            cursor_line_bg: Style::default(),
1245            cursor_column_bg: Style::default(),
1246            selection_bg: Style::default().bg(Color::Blue),
1247            cursor_style: Style::default().add_modifier(Modifier::REVERSED),
1248            gutter: None,
1249            search_bg: Style::default().bg(Color::Magenta),
1250            signs: &[],
1251            conceals: &[],
1252            spans,
1253            search_pattern,
1254        }
1255    }
1256
1257    #[test]
1258    fn empty_spans_param_renders_default_style() {
1259        let b = Buffer::from_str("hello");
1260        let v = vp(10, 1);
1261        let r = no_styles as fn(u32) -> Style;
1262        let view = view_with(&b, &v, &r, &[], None);
1263        let term = run_render(view, 10, 1);
1264        assert_eq!(term.cell((0, 0)).unwrap().symbol(), "h");
1265        assert_eq!(term.cell((0, 0)).unwrap().fg, Color::Reset);
1266    }
1267
1268    #[test]
1269    fn spans_param_paints_styled_byte_range() {
1270        let b = Buffer::from_str("abcdef");
1271        let v = vp(10, 1);
1272        let resolver = |id: u32| -> Style {
1273            if id == 3 {
1274                Style::default().fg(Color::Green)
1275            } else {
1276                Style::default()
1277            }
1278        };
1279        let spans = vec![vec![Span::new(0, 3, 3)]];
1280        let view = view_with(&b, &v, &resolver, &spans, None);
1281        let term = run_render(view, 10, 1);
1282        for x in 0..3 {
1283            assert_eq!(term.cell((x, 0)).unwrap().fg, Color::Green);
1284        }
1285        assert_ne!(term.cell((3, 0)).unwrap().fg, Color::Green);
1286    }
1287
1288    #[test]
1289    fn spans_param_handles_per_row_overlay() {
1290        let b = Buffer::from_str("abc\ndef");
1291        let v = vp(10, 2);
1292        let resolver = |id: u32| -> Style {
1293            if id == 1 {
1294                Style::default().fg(Color::Red)
1295            } else {
1296                Style::default().fg(Color::Green)
1297            }
1298        };
1299        let spans = vec![vec![Span::new(0, 3, 1)], vec![Span::new(0, 3, 2)]];
1300        let view = view_with(&b, &v, &resolver, &spans, None);
1301        let term = run_render(view, 10, 2);
1302        assert_eq!(term.cell((0, 0)).unwrap().fg, Color::Red);
1303        assert_eq!(term.cell((0, 1)).unwrap().fg, Color::Green);
1304    }
1305
1306    #[test]
1307    fn spans_param_rows_beyond_get_no_styling() {
1308        let b = Buffer::from_str("abc\ndef\nghi");
1309        let v = vp(10, 3);
1310        let resolver = |_: u32| -> Style { Style::default().fg(Color::Red) };
1311        // Only row 0 carries spans; rows 1 and 2 inherit default.
1312        let spans = vec![vec![Span::new(0, 3, 0)]];
1313        let view = view_with(&b, &v, &resolver, &spans, None);
1314        let term = run_render(view, 10, 3);
1315        assert_eq!(term.cell((0, 0)).unwrap().fg, Color::Red);
1316        assert_ne!(term.cell((0, 1)).unwrap().fg, Color::Red);
1317        assert_ne!(term.cell((0, 2)).unwrap().fg, Color::Red);
1318    }
1319
1320    #[test]
1321    fn search_pattern_none_disables_hlsearch() {
1322        let b = Buffer::from_str("foo bar foo");
1323        let v = vp(20, 1);
1324        let r = no_styles as fn(u32) -> Style;
1325        // No regex → no Magenta bg anywhere even though `search_bg` is set.
1326        let view = view_with(&b, &v, &r, &[], None);
1327        let term = run_render(view, 20, 1);
1328        for x in 0..11 {
1329            assert_ne!(term.cell((x, 0)).unwrap().bg, Color::Magenta);
1330        }
1331    }
1332
1333    #[test]
1334    fn search_pattern_regex_paints_match_bg() {
1335        use regex::Regex;
1336        let b = Buffer::from_str("xyz foo xyz");
1337        let v = vp(20, 1);
1338        let r = no_styles as fn(u32) -> Style;
1339        let pat = Regex::new("foo").unwrap();
1340        let view = view_with(&b, &v, &r, &[], Some(&pat));
1341        let term = run_render(view, 20, 1);
1342        // "foo" is at chars 4..7; bg is Magenta there only.
1343        assert_ne!(term.cell((3, 0)).unwrap().bg, Color::Magenta);
1344        for x in 4..7 {
1345            assert_eq!(term.cell((x, 0)).unwrap().bg, Color::Magenta);
1346        }
1347        assert_ne!(term.cell((7, 0)).unwrap().bg, Color::Magenta);
1348    }
1349
1350    #[test]
1351    fn search_pattern_unicode_columns_are_charwise() {
1352        use regex::Regex;
1353        // "tablé foo" — match "foo" must land on char column 6, not byte.
1354        let b = Buffer::from_str("tablé foo");
1355        let v = vp(20, 1);
1356        let r = no_styles as fn(u32) -> Style;
1357        let pat = Regex::new("foo").unwrap();
1358        let view = view_with(&b, &v, &r, &[], Some(&pat));
1359        let term = run_render(view, 20, 1);
1360        // "tablé" is 5 chars + space = 6, then "foo" at 6..9.
1361        assert_eq!(term.cell((6, 0)).unwrap().bg, Color::Magenta);
1362        assert_eq!(term.cell((8, 0)).unwrap().bg, Color::Magenta);
1363        assert_ne!(term.cell((5, 0)).unwrap().bg, Color::Magenta);
1364    }
1365
1366    #[test]
1367    fn spans_param_clamps_short_row_overlay() {
1368        // Row 0 has 3 chars; span past end shouldn't crash or smear.
1369        let b = Buffer::from_str("abc");
1370        let v = vp(10, 1);
1371        let resolver = |_: u32| -> Style { Style::default().fg(Color::Red) };
1372        let spans = vec![vec![Span::new(0, 100, 0)]];
1373        let view = view_with(&b, &v, &resolver, &spans, None);
1374        let term = run_render(view, 10, 1);
1375        for x in 0..3 {
1376            assert_eq!(term.cell((x, 0)).unwrap().fg, Color::Red);
1377        }
1378    }
1379
1380    #[test]
1381    fn spans_and_search_pattern_compose() {
1382        // hlsearch bg layers on top of the syntax span fg.
1383        use regex::Regex;
1384        let b = Buffer::from_str("foo");
1385        let v = vp(10, 1);
1386        let resolver = |_: u32| -> Style { Style::default().fg(Color::Green) };
1387        let spans = vec![vec![Span::new(0, 3, 0)]];
1388        let pat = Regex::new("foo").unwrap();
1389        let view = view_with(&b, &v, &resolver, &spans, Some(&pat));
1390        let term = run_render(view, 10, 1);
1391        let cell = term.cell((1, 0)).unwrap();
1392        assert_eq!(cell.fg, Color::Green);
1393        assert_eq!(cell.bg, Color::Magenta);
1394    }
1395}