Skip to main content

justerm_core/
term.rs

1//! The terminal state model: a `vte::Perform` that maps parsed VT actions onto
2//! the grid, cursor, and pen. This is where the "hidden VT state" lives —
3//! pending-wrap, the wide-char spacer, and the pen (BCE seam).
4
5use std::collections::VecDeque;
6
7use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
8use vte::{Params, Perform};
9
10use crate::cell::{Cell, CellFlags};
11use crate::color::Color;
12use crate::cursor::{Cursor, CursorShape, Pen};
13use crate::damage::{LineBounds, LineDamage, ScrollOp, TermDamage};
14use crate::event::TermEvent;
15use crate::grid::{Grid, Row};
16use crate::input::{
17    KeyEvent, MouseEncoding, MouseEvent, MouseProtocol, encode_focus, encode_key, encode_mouse,
18    encode_paste,
19};
20use crate::logical::LogicalLine;
21use crate::search::{Match, SearchOptions};
22use crate::selection::{Anchor, BufferPoint, Selection, SelectionSpan, SelectionType, Side};
23use crate::serialize::{
24    Frame, FrameKind, MarkerId, MarkerKind, MarkerLine, MarkerPosition, Overlay, Span,
25};
26
27/// Owns the authoritative screen state and applies VT actions to it.
28pub struct Term {
29    grid: Grid,
30    /// The inactive screen. Swapped with `grid` on alt-screen enter/leave; holds
31    /// whichever of primary/alternate is not currently shown. The alt screen has
32    /// no scrollback (#3 only rings the primary).
33    alt_grid: Grid,
34    cursor: Cursor,
35    /// Cursor saved on alt-screen enter (DEC 1049), restored on leave.
36    saved_cursor: Cursor,
37    /// Whether the alternate screen is currently active. Guards enter/leave so a
38    /// double-enter or double-leave is a no-op.
39    on_alt: bool,
40    /// One flag per column: is there a tab stop here? Explicit per-column state
41    /// (HTS sets, TBC clears), not a fixed modulo. Default = every 8th column.
42    tabs: Vec<bool>,
43    /// Origin mode (DECOM ?6): when set, cursor addressing is relative to the
44    /// scroll region's top margin (and clamped to it).
45    origin_mode: bool,
46    /// Autowrap (DECAWM ?7): default on. When off, a glyph past the right margin
47    /// pins the cursor to the last column and overwrites in place instead of
48    /// wrapping to the next line (matches xterm.js) (#63).
49    autowrap: bool,
50    /// Insert mode (IRM, the non-private SM/RM mode 4): default off (replace).
51    /// When on, a printed glyph shifts the row's tail right first (#64).
52    insert_mode: bool,
53    /// New-line mode (LNM, the non-private SM/RM mode 20): default off. When on,
54    /// a line feed also carriage-returns (`convertEol`). Output-only — the Enter
55    /// key still encodes CR, matching xterm.js (#71).
56    newline_mode: bool,
57    /// Reverse wraparound (DEC ?45): default off. When on, a *backspace* at
58    /// column 0 of a soft-wrapped row moves back to the end of the previous row
59    /// (BS only, soft wraps only — matches xterm.js) (#80).
60    reverse_wraparound: bool,
61    /// Bracketed-paste mode (DEC ?2004). The engine owns the flag; the input
62    /// encoder (#11) reads it to decide whether to wrap pasted text in markers.
63    bracketed_paste: bool,
64    /// Synchronized output (DEC ?2026): the app brackets a frame of output so the
65    /// renderer can paint it atomically. The engine only *tracks* the flag — the
66    /// consumer owns the paint-hold and the spec-mandated timeout (#73).
67    synchronized_output: bool,
68    /// Color-scheme-update notifications (DEC ?2031): the app asked to be told
69    /// when the light/dark scheme changes. The engine is theme-agnostic — it only
70    /// tracks the flag; the consumer (which knows the scheme) drives the ?997
71    /// notification via `report_color_scheme` (#85).
72    color_scheme_updates: bool,
73    /// Grapheme-cluster mode (DEC ?2027, default OFF): the app opted into UAX #29 grapheme-cluster
74    /// width — a ZWJ / skin-tone / flag / emoji+VS16 sequence is clustered into ONE cell instead of
75    /// one cell per scalar (#295). OFF keeps the per-char (wcwidth-compatible) behaviour so the
76    /// cursor stays in sync with wcwidth apps — clustering is opt-in for exactly that reason (#301).
77    grapheme_clustering: bool,
78    /// win32-input-mode (DEC ?9001): the app asked for keys as raw Windows
79    /// key-records. The engine only *tracks* the flag — the raw record encoding
80    /// (`CSI Vk;Sc;Uc;Kd;Cs;Rc _`) is a non-goal (raw passthrough, no semantic
81    /// conversion), left to the ConPTY consumer; `encode_key` is unchanged (#86).
82    win32_input_mode: bool,
83    /// Application cursor keys (DECCKM ?1): when set, cursor keys / Home / End
84    /// encode as SS3 rather than CSI (see `input.rs`).
85    app_cursor_keys: bool,
86    /// Application keypad mode (DECNKM ?66 / DECKPAM `ESC =` / DECKPNM `ESC >`):
87    /// tracked for protocol completeness + DECRQM, but NOT yet acted on in key
88    /// encoding — xterm.js tracks it the same way and never reads it (#74).
89    application_keypad: bool,
90    /// VT52 compatibility mode (DECANM ?2 *reset*): when set, `esc_dispatch` is
91    /// re-routed into the pre-ANSI VT52 dialect (`ESC A`-style sequences) instead
92    /// of the ANSI meaning. `ESC <` clears it. Default off (ANSI). (#84)
93    vt52_mode: bool,
94    /// VT52 `ESC Y row col` direct-addressing state (#84). vte tokenizes `ESC Y`
95    /// as a final and returns to ground, so the two coordinate bytes arrive as
96    /// `print()` calls — not part of the escape sequence. This counts them down
97    /// (2 → 1 → 0; 0 = not addressing) and `vt52_y_row` parks the first (row)
98    /// until the second (col) lands. Each byte decodes as `value - 0x20`.
99    vt52_y_pending: u8,
100    vt52_y_row: usize,
101    /// Mouse tracking mode — what events the app asked to be reported
102    /// (?1000/?1002/?1003). `Off` by default.
103    mouse_protocol: MouseProtocol,
104    /// Mouse coordinate encoding (default X10 vs ?1006 SGR).
105    mouse_encoding: MouseEncoding,
106    /// Focus in/out reporting (?1004): emit `CSI I`/`CSI O` on focus change.
107    focus_events: bool,
108    /// Kitty keyboard-protocol progressive-enhancement flags currently in effect
109    /// (bit0 disambiguate, bit1 report-events, bit2 alt-keys, bit3 all-as-escape,
110    /// bit4 associated-text). 0 = legacy. `encode_key` consults these (#23).
111    kitty_flags: u8,
112    /// Saved `kitty_flags` for the protocol's push/pop stack (`CSI > u` pushes,
113    /// `CSI < u` pops). Capped depth — overflow drops the oldest entry.
114    kitty_stack: Vec<u8>,
115    /// Consumer events (title / bell / cwd) accumulated since the last
116    /// `drain_events` (#12). Pull, not push — see `event.rs`.
117    events: Vec<TermEvent>,
118    /// Outbound reply bytes (DA/DSR/DECRQM query answers, #27) accumulated
119    /// during `feed` for the consumer to write back to the PTY. Raw bytes →
120    /// PTY, kept separate from typed `events` → UI.
121    replies: Vec<u8>,
122    /// Hyperlink side-table (OSC 8): each entry is one link's URI, referenced by
123    /// `Cell.link` (1-based). Append-only (#26).
124    hyperlink_pool: Vec<String>,
125    /// The hyperlink currently open (OSC 8 with a URI), stamped onto every glyph
126    /// written until closed (OSC 8 with empty URI). Ambient pen-like state — not
127    /// part of the pen/SGR, and *not* cleared by an SGR reset.
128    current_link: Option<core::num::NonZeroU32>,
129    /// Scroll region top/bottom margins (DECSTBM), 0-based inclusive. A
130    /// line-feed at `scroll_bottom` scrolls only rows `[scroll_top..=scroll_bottom]`.
131    /// Default = the full screen.
132    scroll_top: usize,
133    scroll_bottom: usize,
134    /// Lines that have scrolled off the top of the primary screen, oldest at the
135    /// front. Accrues only on a top-anchored, primary-screen scroll.
136    scrollback: VecDeque<Row>,
137    /// How many lines the viewport is scrolled up from the bottom. 0 = following
138    /// the live screen; clamped to `[0, scrollback.len()]`.
139    display_offset: usize,
140    /// Maximum scrollback lines retained; the oldest are evicted past this.
141    scrollback_limit: usize,
142    /// A spare row buffer recycled across full-screen scrolls: the cap-evicted
143    /// oldest line is parked here and reused as the next scroll's blank bottom,
144    /// so a steady-state flood allocates nothing (ADR-0009).
145    recycled_row: Option<Row>,
146    /// Per-line damage bounds since the last `reset_damage` (ack), one per row.
147    line_damage: Vec<LineBounds>,
148    /// A first-class scroll recorded since the last `reset_damage`.
149    scroll: Option<ScrollOp>,
150    /// The whole screen changed (alt switch / clear / later resize+flood) — the
151    /// renderer must redraw everything.
152    full_damage: bool,
153    /// The cursor `(row, col)` at the last `reset_damage` (ack) — where the
154    /// consumer last saw the caret. A pure cursor move records no content
155    /// damage, so `damage()` folds this *old* cell plus the current one into the
156    /// frame; without it a cell-invert caret ghosts at the old spot (mirrors
157    /// Alacritty's `last_cursor`). #38.
158    prev_cursor: (usize, usize),
159    /// The live selection, in absolute buffer coordinates. `None` when nothing
160    /// is selected. See `selection.rs`.
161    selection: Option<Selection>,
162    /// The search highlights the consumer asked to paint (#108). Search
163    /// matches are consumer-owned (it drives next/prev), so the engine holds only
164    /// the set handed back via `set_search_highlights`, and `frame()` projects it
165    /// onto the viewport — the same anchoring path as the selection.
166    search_highlights: Vec<Match>,
167    /// The *active* (current) search match (#428), stored as its absolute span
168    /// (#436) — designated by the consumer (next/prev is its policy) either as
169    /// an index into `search_highlights` (resolved to the span at call time) or
170    /// directly by span, which a capping backend uses for a past-cap match
171    /// (xterm creates its active decoration from the found result, OUTSIDE the
172    /// capped highlight list). A span is NOT structurally tied to the set, so
173    /// every path that voids the set must void this too: `set_search_highlights`
174    /// (hand-over reset, #428) and `invalidate_search_highlights` (the single
175    /// funnel for eviction / every region scroll incl. the accrual sub-region
176    /// branch (#449) / reflow / both alt swaps) — a stale span would otherwise
177    /// keep painting coordinates that now hold other text.
178    active_search_highlight: Option<Match>,
179    /// Engine-owned decoration markers (#118), split per buffer like xterm's
180    /// `BufferSet` (#177 S0): each a stable id bound to an absolute buffer line
181    /// that re-anchors through eviction/scroll/reflow like a selection anchor. The
182    /// active buffer's list is selected by `on_alt` — `markers`/`markers_mut`.
183    /// `alt_markers` stays empty while the alt guards (#158/#164) are in place; it
184    /// is disposed on alt-leave (xterm `clearAllMarkers`). `next_marker_id` hands
185    /// out monotonic ids across both buffers so ids never alias.
186    normal_markers: Vec<Marker>,
187    alt_markers: Vec<Marker>,
188    next_marker_id: u32,
189    /// Cursor state saved by DECSC (ESC 7), restored by DECRC (ESC 8). A slot
190    /// separate from `saved_cursor` (which is the alt-screen save). Defaults to
191    /// home/default so a DECRC with no prior DECSC restores a sane state.
192    decsc: SavedCursor,
193    /// SCS-designated character sets G0..G3 (#62). `gl` indexes the active (GL)
194    /// set, switched by SI (→G0) / SO (→G1). First cut uses G0/G1.
195    charsets: [Charset; 4],
196    gl: usize,
197}
198
199/// A character set designated by SCS (#62). First cut: ASCII (default), DEC
200/// Special Graphics (line-drawing), and UK. G2/G3 and the GR half are later.
201#[derive(Clone, Copy, PartialEq, Eq, Default)]
202enum Charset {
203    #[default]
204    Ascii,
205    DecSpecialGraphics,
206    Uk,
207}
208
209impl Charset {
210    /// Map one GL byte (a `char` in the 7-bit range) through this set. ASCII and
211    /// any out-of-range char pass through; UK swaps `#`→£; DEC Special Graphics
212    /// translates `_`..`~` to the line-drawing / symbol glyphs.
213    fn map(self, c: char) -> char {
214        match self {
215            Charset::Ascii => c,
216            Charset::Uk if c == '#' => '£',
217            Charset::Uk => c,
218            Charset::DecSpecialGraphics => dec_special_graphics(c),
219        }
220    }
221}
222
223/// The VT100 DEC Special Graphics set: bytes `_`..`~` (0x5F..0x7E) map to the
224/// box-drawing and symbol glyphs. Matches xterm/alacritty; anything outside the
225/// range passes through unchanged.
226fn dec_special_graphics(c: char) -> char {
227    // Keys ``..`~` only — `_` (0x5F) is deliberately absent, matching xterm.js /
228    // alacritty (it passes through as a literal underscore), not the strict-DEC
229    // "0x5F = blank" reading.
230    match c {
231        '`' => '◆',
232        'a' => '▒',
233        'b' => '␉',
234        'c' => '␌',
235        'd' => '␍',
236        'e' => '␊',
237        'f' => '°',
238        'g' => '±',
239        'h' => '␤',
240        'i' => '␋',
241        'j' => '┘',
242        'k' => '┐',
243        'l' => '┌',
244        'm' => '└',
245        'n' => '┼',
246        'o' => '⎺',
247        'p' => '⎻',
248        'q' => '─',
249        'r' => '⎼',
250        's' => '⎽',
251        't' => '├',
252        'u' => '┤',
253        'v' => '┴',
254        'w' => '┬',
255        'x' => '│',
256        'y' => '≤',
257        'z' => '≥',
258        '{' => 'π',
259        '|' => '≠',
260        '}' => '£',
261        '~' => '·',
262        other => other,
263    }
264}
265
266/// Default scrollback retention when not specified.
267const DEFAULT_SCROLLBACK: usize = 10_000;
268
269/// The state DECSC (ESC 7) saves and DECRC (ESC 8) restores: position, pen/SGR,
270/// pending-wrap, and origin mode (per ADR-0004 — DECRC restores origin mode,
271/// which Alacritty omits). Cursor *visibility* is deliberately not part of this
272/// (DECTCEM is separate from DECSC).
273#[derive(Clone, Copy, Default)]
274struct SavedCursor {
275    row: usize,
276    col: usize,
277    pen: Pen,
278    pending_wrap: bool,
279    origin_mode: bool,
280    /// SCS charset state at save time — DECSC/DECRC round-trip the designated
281    /// sets and the active GL shift (#62).
282    charsets: [Charset; 4],
283    gl: usize,
284}
285
286/// An engine-owned decoration marker (#118): a stable id bound to an absolute
287/// buffer line. The line shifts in lockstep with eviction/region scroll/reflow
288/// (the same coordinate moves the selection anchor tracks); the marker is
289/// dropped when its line leaves the buffer.
290struct Marker {
291    id: MarkerId,
292    line: usize,
293    /// The cursor column at emit time (#166). Meaningful for OSC-133 command
294    /// marks — CommandStart(B)/OutputStart(C) columns bound the *typed command*
295    /// (excluding the prompt), like VSCode's `commandStartX`/`commandExecutedX`.
296    /// Plain `add_marker` decorations are row-granular and carry `col = 0`.
297    col: usize,
298    /// Plain for a `add_marker` decoration; a command-boundary role for an
299    /// OSC 133 mark (#158). All kinds share the anchor/eviction machinery.
300    kind: MarkerKind,
301}
302
303/// One executed shell command recovered from OSC-133 marks (#166), for
304/// screen-reader command navigation. The consumer jumps prompt-to-prompt over
305/// these and announces `command` + a success/fail signal from `exit`.
306#[derive(Debug, Clone, PartialEq, Eq)]
307pub struct CommandLine {
308    /// The command's jump anchor as a *document* line — the logical-line index of
309    /// the CommandStart(B) mark within [`Term::accessible_text`], so the consumer
310    /// reveals the right row of the accessible view (soft-wrapped rows collapse to
311    /// one logical line). This is core's analog of VSCode's
312    /// `bufferToEditorLineMapping`; the frame-mode web side has no wrap info to
313    /// map it itself.
314    pub line: usize,
315    /// The typed command text, prompt- and output-excluded (B→C columns).
316    pub command: String,
317    /// The CommandFinished(D) exit code, if the shell reported one and the
318    /// command has finished.
319    pub exit: Option<i32>,
320}
321
322/// A selection resolved to absolute-coordinate bounds, ready for text extraction
323/// or viewport-span projection. Columns are half-open (`from..to`).
324enum Resolved {
325    /// Char/Word/Line: a run that joins soft-wrapped rows. Columns apply to the
326    /// first/last line; middle lines are whole.
327    Linear {
328        start_line: usize,
329        from: usize,
330        end_line: usize,
331        to: usize,
332    },
333    /// Block: a rectangle — the same `from..to` columns on every row.
334    Block {
335        line0: usize,
336        line1: usize,
337        from: usize,
338        to: usize,
339    },
340}
341
342/// Collect per-line damage bounds into damaged `LineDamage` spans (undamaged
343/// lines dropped). Shared by `damage` (content-only) and `frame_damage`
344/// (content + cursor cells).
345fn bounds_to_lines(bounds: &[LineBounds]) -> Vec<LineDamage> {
346    bounds
347        .iter()
348        .enumerate()
349        .filter(|(_, b)| b.is_damaged())
350        .map(|(line, b)| {
351            let (left, right) = b.span();
352            LineDamage { line, left, right }
353        })
354        .collect()
355}
356
357impl Term {
358    pub fn new(cols: usize, rows: usize) -> Self {
359        Self::with_scrollback(cols, rows, DEFAULT_SCROLLBACK)
360    }
361
362    pub fn with_scrollback(cols: usize, rows: usize, scrollback_limit: usize) -> Self {
363        Term {
364            grid: Grid::new(cols, rows),
365            alt_grid: Grid::new(cols, rows),
366            cursor: Cursor::default(),
367            saved_cursor: Cursor::default(),
368            on_alt: false,
369            origin_mode: false,
370            autowrap: true,
371            insert_mode: false,
372            newline_mode: false,
373            reverse_wraparound: false,
374            bracketed_paste: false,
375            synchronized_output: false,
376            color_scheme_updates: false,
377            grapheme_clustering: false,
378            win32_input_mode: false,
379            app_cursor_keys: false,
380            application_keypad: false,
381            vt52_mode: false,
382            vt52_y_pending: 0,
383            vt52_y_row: 0,
384            mouse_protocol: MouseProtocol::Off,
385            mouse_encoding: MouseEncoding::Default,
386            focus_events: false,
387            kitty_flags: 0,
388            kitty_stack: Vec::new(),
389            events: Vec::new(),
390            replies: Vec::new(),
391            hyperlink_pool: Vec::new(),
392            current_link: None,
393            tabs: default_tabs(cols),
394            scroll_top: 0,
395            scroll_bottom: rows - 1,
396            scrollback: VecDeque::new(),
397            display_offset: 0,
398            scrollback_limit,
399            recycled_row: None,
400            line_damage: vec![LineBounds::undamaged(cols); rows],
401            scroll: None,
402            full_damage: false,
403            prev_cursor: (0, 0), // matches the default cursor's home position
404            selection: None,
405            search_highlights: Vec::new(),
406            active_search_highlight: None,
407            normal_markers: Vec::new(),
408            alt_markers: Vec::new(),
409            next_marker_id: 0,
410            decsc: SavedCursor::default(),
411            charsets: [Charset::Ascii; 4],
412            gl: 0,
413        }
414    }
415
416    /// What changed since the last `reset_damage()` — line ranges, each with a
417    /// changed column span. See ADR-0003.
418    pub fn damage(&self) -> TermDamage {
419        if self.full_damage {
420            return TermDamage::Full;
421        }
422        // Scrolled up under follow-bottom "stay": the viewport is frozen, so
423        // screen changes below it are not visible — report nothing. (A user
424        // scroll that moves the viewport sets full_damage above.)
425        if self.display_offset > 0 {
426            return TermDamage::Partial(Vec::new());
427        }
428        TermDamage::Partial(bounds_to_lines(&self.line_damage))
429    }
430
431    /// Render damage: content damage plus the cursor cells, for [`Term::frame`].
432    ///
433    /// A pure cursor move changes no cell *content*, so [`Term::damage`] (which
434    /// stays content-only, the cadence/flow-control primitive) would miss it —
435    /// yet a cell-invert caret must clear its old spot and ink the new one. So
436    /// the frame producer folds the old (last-acked) + current cursor cells in,
437    /// but only when the cursor actually moved: a still cursor needs no redraw,
438    /// keeping an idle frame empty. Mirrors Alacritty's `last_cursor`. #38.
439    fn frame_damage(&self) -> TermDamage {
440        if self.full_damage {
441            return TermDamage::Full;
442        }
443        if self.display_offset > 0 {
444            return TermDamage::Partial(Vec::new());
445        }
446        let cur = self.cursor.point();
447        if cur == self.prev_cursor {
448            return TermDamage::Partial(bounds_to_lines(&self.line_damage));
449        }
450        let mut bounds = self.line_damage.clone();
451        bounds[cur.0].expand(cur.1, cur.1);
452        let pr = self.prev_cursor.0.min(self.grid.rows() - 1);
453        let pc = self.prev_cursor.1.min(self.grid.cols() - 1);
454        bounds[pr].expand(pc, pc);
455        TermDamage::Partial(bounds_to_lines(&bounds))
456    }
457
458    /// Clear accumulated damage. The consumer calls this after applying a frame
459    /// (the ack); the next `damage()` reflects only changes since.
460    pub fn reset_damage(&mut self) {
461        for b in &mut self.line_damage {
462            b.reset();
463        }
464        self.scroll = None;
465        self.full_damage = false;
466        // The consumer has now seen the caret at the current position; the next
467        // frame's cursor-move damage is measured from here (#38).
468        self.prev_cursor = self.cursor.point();
469    }
470
471    /// Mark the whole screen damaged (alt switch / clear / flood, and a consumer
472    /// reattach that needs a full re-sync — see [`crate::Engine::mark_fully_damaged`]).
473    pub fn mark_fully_damaged(&mut self) {
474        self.full_damage = true;
475    }
476
477    /// Record that columns `[left, right]` of `row` changed.
478    fn damage_span(&mut self, row: usize, left: usize, right: usize) {
479        self.line_damage[row].expand(left, right);
480    }
481
482    /// The first-class scroll recorded since the last `reset_damage`, if any.
483    /// Suppressed while scrolled up — a content scroll must not shift the frozen
484    /// viewport.
485    pub fn scroll_delta(&self) -> Option<ScrollOp> {
486        if self.display_offset > 0 {
487            return None;
488        }
489        self.scroll
490    }
491
492    /// Build a serializable [`Frame`] from the current damage + grid + grapheme
493    /// pool (#6). `Full` ships every row; `Partial` ships the damaged spans. The
494    /// global side-table is remapped to **frame-local** indices — the engine pool
495    /// is append-only and leaky, so a frame carries only the clusters its cells
496    /// reference, renumbered, with each cell's `extra` rewritten to the local id.
497    pub fn frame(&self) -> Frame {
498        let cols = self.grid.cols();
499        let rows = self.grid.rows();
500        let (kind, line_spans): (FrameKind, Vec<(usize, usize, usize)>) = match self.frame_damage()
501        {
502            TermDamage::Full => (
503                FrameKind::Full,
504                (0..rows).map(|l| (l, 0, cols - 1)).collect(),
505            ),
506            TermDamage::Partial(lines) => (
507                FrameKind::Partial,
508                lines
509                    .into_iter()
510                    .map(|d| (d.line, d.left, d.right))
511                    .collect(),
512            ),
513        };
514
515        let mut side_table: Vec<Vec<char>> = Vec::new();
516        // Same frame-local renumber for the hyperlink side-table (#26).
517        let mut link_table: Vec<String> = Vec::new();
518        let mut link_remap = vec![0u16; self.hyperlink_pool.len() + 1];
519        // Cells come from the viewport at `display_offset`, not the live grid:
520        // viewport row `line` is absolute buffer line `top + line` (scrollback
521        // when scrolled up, the live grid when `display_offset == 0`, where
522        // `top == scrollback.len()` and this is identical to reading the grid).
523        // Without this, a wire consumer — cells reach it only through `frame()` —
524        // could never display scrollback (#48).
525        let top = self.scrollback.len() - self.display_offset;
526        let mut spans = Vec::with_capacity(line_spans.len());
527        for (line, left, right) in line_spans {
528            let mut cells = Vec::with_capacity(right - left + 1);
529            let mut combining = std::collections::BTreeMap::new();
530            let mut links = std::collections::BTreeMap::new();
531            let row = self.abs_row(top + line);
532            for col in left..=right {
533                let cell = row[col];
534                // Combining clusters and hyperlinks live in the row's maps; each
535                // tagged cell contributes its reference to the frame, recorded on
536                // the span by span-relative column (the cell holds only the bit).
537                if let Some(marks) = row.combining_at(col) {
538                    side_table.push(marks.to_vec());
539                    let idx = core::num::NonZeroU32::new(side_table.len() as u32)
540                        .expect("side_table just pushed, len >= 1");
541                    combining.insert(col - left, idx);
542                }
543                if let Some(lidx) = row.link_at(col) {
544                    // Renumber the global pool index to a contiguous frame-local
545                    // one (only referenced URIs ship), same as the old per-cell link.
546                    let l = lidx.get() as usize;
547                    if link_remap[l] == 0 {
548                        link_table.push(self.hyperlink_pool[l - 1].clone());
549                        link_remap[l] = link_table.len() as u16;
550                    }
551                    let fidx = core::num::NonZeroU32::new(link_remap[l] as u32)
552                        .expect("link_remap just set, nonzero");
553                    links.insert(col - left, fidx);
554                }
555                cells.push(cell);
556            }
557            spans.push(Span {
558                line: line as u16,
559                left: left as u16,
560                right: right as u16,
561                cells,
562                combining,
563                links,
564            });
565        }
566
567        Frame {
568            cols: cols as u16,
569            rows: rows as u16,
570            kind,
571            // The live cursor: position in screen coords + DECTCEM visibility.
572            // Reported, not drawn — the consumer renders the caret (#38).
573            cursor_row: self.cursor.row as u16,
574            cursor_col: self.cursor.col as u16,
575            // Hidden while scrolled up: the live cursor is off the frozen
576            // viewport, and a cell-invert caret would otherwise ink over
577            // scrollback. Consistent with the frozen-damage policy (no cursor
578            // damage is emitted while scrolled) and with xterm.js / alacritty,
579            // which hide the caret when it falls outside the visible rows (#48).
580            cursor_visible: self.cursor.visible && self.display_offset == 0,
581            cursor_shape: self.cursor.shape,
582            cursor_blink: self.cursor.blink,
583            // Viewport scroll position for the consumer's scrollbar (ADR-0013).
584            display_offset: self.display_offset as u32,
585            scrollback_len: self.scrollback.len() as u32,
586            // The mouse tracking mode as a routing mask (#129): which mouse events
587            // the app wants, derived from the protocol by the single source
588            // `encode_mouse` shares. The consumer routes app-vs-local on it.
589            mouse_events: self.mouse_protocol.wanted_events(),
590            // Alt-screen flag (#149): buffer-global state the consumer can't
591            // derive from viewport damage; the a11y announce policy gates on it.
592            alt_screen: self.on_alt,
593            scroll: self.scroll_delta(),
594            spans,
595            side_table,
596            link_table,
597            // Interaction overlays projected onto this viewport (#108): the
598            // engine-owned selection and the consumer-supplied search highlights,
599            // each re-projected here so the scroll offset is applied once, by the
600            // same authority that projects the cells.
601            overlay: Overlay {
602                selection: self.selection_range(),
603                matches: self
604                    .search_highlights
605                    .iter()
606                    .flat_map(|m| self.match_spans(m))
607                    .collect(),
608                // The consumer-designated active match (#428), projected through
609                // the same `match_spans` math — usually also present in `matches`
610                // above (the renderer's ranking resolves the overlap, #424), but
611                // a span designation may sit OUTSIDE a capped hand-over (#436).
612                active_match: self
613                    .active_search_highlight
614                    .as_ref()
615                    .map(|m| self.match_spans(m))
616                    .unwrap_or_default(),
617                markers: self.marker_positions(),
618                marker_lines: self.all_marker_lines(),
619            },
620        }
621    }
622
623    /// Record a scroll of rows `[top, bottom]` by `count` (positive = up).
624    ///
625    /// Damage is indexed by row position, so it must follow the content the
626    /// scroll just moved: rotate the bounds the same way and mark the newly
627    /// exposed line fully damaged (it is new blank content for the consumer).
628    fn record_scroll(&mut self, top: usize, bottom: usize, count: isize) {
629        let cols = self.grid.cols();
630        match count {
631            1 => {
632                self.line_damage[top..=bottom].rotate_left(1);
633                self.line_damage[bottom] = LineBounds::fully_damaged(cols);
634            }
635            -1 => {
636                self.line_damage[top..=bottom].rotate_right(1);
637                self.line_damage[top] = LineBounds::fully_damaged(cols);
638            }
639            _ => {}
640        }
641        // Accumulate repeated scrolls of the same region into one op (flow
642        // control). A *different* region cannot be expressed as one op, so
643        // degrade to full rather than silently dropping the earlier scroll.
644        match self.scroll {
645            Some(op) if op.top == top && op.bottom == bottom => {
646                self.scroll = Some(ScrollOp {
647                    top,
648                    bottom,
649                    count: op.count + count,
650                });
651            }
652            None => self.scroll = Some(ScrollOp { top, bottom, count }),
653            Some(_) => {
654                self.scroll = None;
655                self.mark_fully_damaged();
656            }
657        }
658    }
659
660    /// Number of lines currently held in scrollback history.
661    pub fn scrollback_len(&self) -> usize {
662        self.scrollback.len()
663    }
664
665    /// Whether the app has an open synchronized-output block (DEC ?2026, #73).
666    pub fn synchronized_output(&self) -> bool {
667        self.synchronized_output
668    }
669
670    /// Whether the app enabled color-scheme-update notifications (DEC ?2031, #85).
671    pub fn color_scheme_updates(&self) -> bool {
672        self.color_scheme_updates
673    }
674
675    /// Whether the app enabled grapheme-cluster mode (DEC ?2027, #295): emoji ZWJ / skin-tone /
676    /// flag / VS16 sequences are clustered into one cell. OFF (default) is per-char, wcwidth-compat.
677    pub fn grapheme_clustering(&self) -> bool {
678        self.grapheme_clustering
679    }
680
681    /// Whether the app enabled win32-input-mode (DEC ?9001, #86). The engine does
682    /// not encode the raw key-records itself (a non-goal); a ConPTY consumer reads
683    /// this to decide whether to emit them.
684    pub fn win32_input_mode(&self) -> bool {
685        self.win32_input_mode
686    }
687
688    /// Queue a color-scheme report (`CSI ? 997 ; 1 n` dark / `; 2 n` light) on the
689    /// reply channel. The consumer calls this to answer a `ColorSchemeQuery` event
690    /// or, when its scheme changes and `color_scheme_updates()` is set, to send the
691    /// unsolicited notification. The engine never stores or interprets the scheme
692    /// (#85).
693    pub fn report_color_scheme(&mut self, dark: bool) {
694        let ps = if dark { 1 } else { 2 };
695        self.replies
696            .extend_from_slice(format!("\x1b[?997;{ps}n").as_bytes());
697    }
698
699    /// OSC 10/11 set/query the default fg/bg, stacking the `;`-separated specs
700    /// across the `[foreground, background]` slots — xterm's
701    /// `_setOrReportSpecialColor` offset loop (#137). OSC 10 starts at slot 0
702    /// (fg → bg), OSC 11 at slot 1 (bg). A `?` spec is a query. xterm's 3rd slot
703    /// (cursor / OSC 12) is out of scope, so the stack caps at two slots — extra
704    /// specs are dropped.
705    fn special_color(&mut self, params: &[&[u8]], start: usize) {
706        for (i, &spec) in params[1..].iter().enumerate() {
707            let event = match start + i {
708                0 if spec == b"?" => TermEvent::QueryForeground,
709                0 => TermEvent::SetForeground(String::from_utf8_lossy(spec).into_owned()),
710                1 if spec == b"?" => TermEvent::QueryBackground,
711                1 => TermEvent::SetBackground(String::from_utf8_lossy(spec).into_owned()),
712                _ => break, // past [fg, bg] — cursor (OSC 12) unsupported
713            };
714            self.events.push(event);
715        }
716    }
717
718    /// Answer an OSC 4 palette query (#122): wrap the consumer-supplied spec for
719    /// `index` in the OSC 4 reply envelope, ST-terminated.
720    pub fn report_palette_color(&mut self, index: u8, spec: &str) {
721        self.replies
722            .extend_from_slice(format!("\x1b]4;{index};{spec}\x1b\\").as_bytes());
723    }
724
725    /// Answer an OSC 10 foreground query (#122): wrap the consumer-supplied spec
726    /// in the OSC 10 reply envelope, ST-terminated.
727    pub fn report_foreground(&mut self, spec: &str) {
728        self.replies
729            .extend_from_slice(format!("\x1b]10;{spec}\x1b\\").as_bytes());
730    }
731
732    /// Answer an OSC 11 background query (#122): wrap the consumer-supplied spec
733    /// (it knows its palette) in the OSC 11 reply envelope, ST-terminated. The
734    /// engine formats the envelope only — it never knows the colour.
735    pub fn report_background(&mut self, spec: &str) {
736        self.replies
737            .extend_from_slice(format!("\x1b]11;{spec}\x1b\\").as_bytes());
738    }
739
740    /// The cells of visible row `i` (0..rows) at the current scroll position.
741    /// The viewport windows into `[history.. ; screen..]`: rows above
742    /// `scrollback.len()` come from history, the rest from the live screen.
743    pub fn viewport_line(&self, i: usize) -> &[Cell] {
744        let top = self.scrollback.len() - self.display_offset;
745        let idx = top + i;
746        if idx < self.scrollback.len() {
747            &self.scrollback[idx]
748        } else {
749            self.grid.row(idx - self.scrollback.len())
750        }
751    }
752
753    /// Scroll the viewport up by `n` lines into history (clamped to the oldest).
754    pub fn scroll_up(&mut self, n: usize) {
755        let target = (self.display_offset + n).min(self.scrollback.len());
756        self.set_display_offset(target);
757    }
758
759    /// Scroll the viewport down by `n` lines toward the live screen.
760    pub fn scroll_down(&mut self, n: usize) {
761        let target = self.display_offset.saturating_sub(n);
762        self.set_display_offset(target);
763    }
764
765    /// Jump the viewport back to the live screen (follow the bottom).
766    pub fn scroll_to_bottom(&mut self) {
767        self.set_display_offset(0);
768    }
769
770    /// Move the viewport. A user scroll changes which lines are visible, so the
771    /// whole viewport is repainted (full damage) when the offset actually moves.
772    fn set_display_offset(&mut self, offset: usize) {
773        // The alt screen has no scrollback to view; scroll intents are no-ops.
774        if self.on_alt {
775            return;
776        }
777        if offset != self.display_offset {
778            self.display_offset = offset;
779            self.mark_fully_damaged();
780        }
781    }
782
783    // ---- selection -----------------------------------------------------------
784
785    /// Map a viewport cell `(row, col)` to an absolute buffer point. The top
786    /// visible row is `scrollback.len() - display_offset`, so viewport row `i`
787    /// is that plus `i`.
788    fn viewport_to_abs(&self, row: usize, col: usize) -> BufferPoint {
789        let top = self.scrollback.len() - self.display_offset;
790        BufferPoint {
791            line: top + row,
792            col,
793        }
794    }
795
796    /// The primary-screen grid, wherever it currently lives — swapped into
797    /// `alt_grid` while on the alt screen (#192). Command marks anchor *primary*
798    /// content, so extracting their text must read this, not the active grid.
799    fn primary_grid(&self) -> &Grid {
800        if self.on_alt {
801            &self.alt_grid
802        } else {
803            &self.grid
804        }
805    }
806
807    /// The cells of absolute buffer line `line`, reading the screen portion from
808    /// `grid` (scrollback is shared). Callers pick the active grid (`abs_line`) or
809    /// the primary grid (`primary_grid`, for command-mark text on the alt screen).
810    fn line_in<'a>(&'a self, grid: &'a Grid, line: usize) -> &'a [Cell] {
811        if line < self.scrollback.len() {
812            &self.scrollback[line]
813        } else {
814            grid.row(line - self.scrollback.len())
815        }
816    }
817
818    /// The whole row of absolute buffer line `line` from `grid` (see `line_in`).
819    fn row_in<'a>(&'a self, grid: &'a Grid, line: usize) -> &'a Row {
820        if line < self.scrollback.len() {
821            &self.scrollback[line]
822        } else {
823            grid.row_ref(line - self.scrollback.len())
824        }
825    }
826
827    /// The cells of absolute buffer line `line` on the *active* screen.
828    fn abs_line(&self, line: usize) -> &[Cell] {
829        self.line_in(&self.grid, line)
830    }
831
832    /// The whole row of absolute buffer line `line` on the *active* screen.
833    fn abs_row(&self, line: usize) -> &Row {
834        self.row_in(&self.grid, line)
835    }
836
837    /// The combining marks at absolute `(line, col)` reading `grid`, or `None` —
838    /// flag-gated through the row's map, so a stale entry is never surfaced.
839    fn combining_in<'a>(&'a self, grid: &'a Grid, line: usize, col: usize) -> Option<&'a [char]> {
840        self.row_in(grid, line).combining_at(col)
841    }
842
843    /// The combining marks at absolute `(line, col)` on the *active* screen.
844    fn combining_at(&self, line: usize, col: usize) -> Option<&[char]> {
845        self.combining_in(&self.grid, line, col)
846    }
847
848    /// The hyperlink-pool index at **screen** `(row, col)` (the live grid), or
849    /// `None` — flag-gated through the row's link map. Resolve to the URI with
850    /// [`Term::hyperlink`]. Mirrors `grid().cell(row, col)`.
851    pub(crate) fn screen_link_at(&self, row: usize, col: usize) -> Option<core::num::NonZeroU32> {
852        self.grid.row_ref(row).link_at(col)
853    }
854
855    /// The hyperlink-pool index at **viewport** `(row, col)` (visible window,
856    /// history included at the current scroll), or `None`. Mirrors
857    /// `viewport_line(row)`.
858    pub(crate) fn viewport_link_at(&self, row: usize, col: usize) -> Option<core::num::NonZeroU32> {
859        let idx = self.scrollback.len() - self.display_offset + row;
860        self.abs_row(idx).link_at(col)
861    }
862
863    /// The viewport's logical lines (#113/ADR-0017): each line's text plus a
864    /// per-char map to its viewport `(row, col)`. Wide-char spacers are skipped
865    /// and trailing blanks trimmed (so the text is 1:1 with `cells`). Empty rows
866    /// are dropped. The cell-aware assembly the consumer can't do in frame mode.
867    pub fn viewport_logical_lines(&self) -> Vec<LogicalLine> {
868        let rows = self.grid.rows();
869        let total = self.scrollback.len() + rows;
870        let top = self.scrollback.len() - self.display_offset; // abs line of viewport row 0
871        let bottom = top + rows; // abs lines [top, bottom) are on screen
872
873        // If viewport row 0 is a wrap-continuation, walk up into scrollback to
874        // the logical line's true start so an edge-spanning URL still matches.
875        // On the alt screen the scrollback belongs to the *primary* buffer, so
876        // the walk must stop at the screen top (`scrollback.len()`) — the alt
877        // buffer is separate (selection clears on alt-swap for the same reason).
878        let floor = if self.on_alt {
879            self.scrollback.len()
880        } else {
881            0
882        };
883        let mut start = top;
884        while start > floor
885            && self
886                .abs_line(start - 1)
887                .last()
888                .is_some_and(|c| c.is_wrapline())
889        {
890            start -= 1;
891        }
892
893        let mut out = Vec::new();
894        let mut line = start;
895        while line < bottom {
896            // Accumulate one logical line forward while each row soft-wraps; the
897            // tail may run past `bottom` (off-screen below) — included too.
898            let mut text = String::new();
899            let mut map: Vec<(i32, usize)> = Vec::new();
900            let mut cur = line;
901            loop {
902                let cells = self.abs_line(cur);
903                for (col, cell) in cells.iter().enumerate() {
904                    if cell.is_spacer() {
905                        continue;
906                    }
907                    // Signed viewport row: < 0 above the top, >= rows below.
908                    let vrow = cur as i32 - top as i32;
909                    text.push(cell.c());
910                    map.push((vrow, col));
911                    // Combining marks (#45) ride the same cell — append each and
912                    // map it to that cell so `text` stays 1:1 with `cells`.
913                    if let Some(marks) = self.combining_at(cur, col) {
914                        for &m in marks {
915                            text.push(m);
916                            map.push((vrow, col));
917                        }
918                    }
919                }
920                let soft = cells.last().is_some_and(|c| c.is_wrapline());
921                if soft && cur + 1 < total {
922                    cur += 1;
923                } else {
924                    break;
925                }
926            }
927            // Trim trailing blanks (only the last row can have them), keeping
928            // `text` and `cells` in lockstep.
929            let trimmed = text.trim_end();
930            map.truncate(trimmed.chars().count());
931            text.truncate(trimmed.len());
932            if !text.is_empty() {
933                out.push(LogicalLine { text, cells: map });
934            }
935            line = cur + 1;
936        }
937        out
938    }
939
940    /// Literal search over the whole buffer (`[scrollback ++ screen]`), returning
941    /// every non-overlapping match top-to-bottom in absolute coordinates. Matches
942    /// cross soft-wrapped rows (one logical line) and skip wide-char spacers.
943    /// Smart-case: a query with no uppercase matches case-insensitively.
944    pub fn search(&self, query: &str) -> Vec<Match> {
945        self.search_with(query, SearchOptions::default())
946    }
947
948    /// Search with explicit [`SearchOptions`] — regex, whole-word, and a case-sensitivity override
949    /// on top of the literal + smart-case [`search`](Self::search) (#314). Same coordinates,
950    /// soft-wrap join, spacer skip, and grapheme-mark inclusion (#304) as `search`.
951    pub fn search_with(&self, query: &str, opts: SearchOptions) -> Vec<Match> {
952        let q: Vec<char> = query.chars().collect();
953        if q.is_empty() {
954            return Vec::new();
955        }
956        // Smart-case unless overridden: case-insensitive iff the query has no uppercase.
957        let ci = opts
958            .case_sensitive
959            .map_or_else(|| !q.iter().any(|c| c.is_uppercase()), |cs| !cs);
960        // Fold to a single representative char so the haystack stays 1:1 with its
961        // positions (rare multi-char case expansions take their first char).
962        let fold = |c: char| {
963            if ci {
964                c.to_lowercase().next().unwrap_or(c)
965            } else {
966                c
967            }
968        };
969        let needle: Vec<char> = q.iter().map(|&c| fold(c)).collect();
970        // Regex mode: build the pattern once (case-insensitivity from the same smart-case/override
971        // decision). An invalid pattern yields no matches rather than erroring (#314).
972        let re = if opts.regex {
973            match regex::RegexBuilder::new(query).case_insensitive(ci).build() {
974                Ok(re) => Some(re),
975                Err(_) => return Vec::new(),
976            }
977        } else {
978            None
979        };
980        let total = self.scrollback.len() + self.grid.rows();
981
982        // On the alt screen the scrollback belongs to the *primary* buffer, so the
983        // walk must start at the screen top (`scrollback.len()`): primary matches are
984        // unreachable on alt, and a primary WRAPLINE row would otherwise soft-wrap-join
985        // into the alt grid and corrupt the haystack at the boundary. Mirrors the
986        // `viewport_logical_lines` floor (#113) — the alt buffer is separate (selection
987        // clears on alt-swap for the same reason). (#144)
988        let floor = if self.on_alt {
989            self.scrollback.len()
990        } else {
991            0
992        };
993        let mut matches = Vec::new();
994        let mut r = floor;
995        while r < total {
996            // Build the logical line at `r`: join soft-wrapped rows, recording
997            // each char's source position and skipping wide-char spacers.
998            let mut hay: Vec<char> = Vec::new();
999            let mut pos: Vec<(usize, usize)> = Vec::new();
1000            let mut line = r;
1001            loop {
1002                let cells = self.abs_line(line);
1003                for (col, cell) in cells.iter().enumerate() {
1004                    if cell.is_spacer() {
1005                        continue;
1006                    }
1007                    // Build the haystack UNFOLDED (regex needs the original text; its own
1008                    // case-insensitive flag handles case). The literal path folds at compare time.
1009                    hay.push(cell.c());
1010                    pos.push((line, col));
1011                    // Include the cell's grapheme side-table marks — combining marks, and under
1012                    // mode 2027 the joined emoji scalars (2nd RI, ZWJ-joined emoji, skin tone) —
1013                    // so a clustered scalar is findable, not just the base (#304). Each maps to the
1014                    // same cell column, mirroring `append_cell`'s base+marks extraction.
1015                    if let Some(marks) = self.combining_at(line, col) {
1016                        for &m in marks {
1017                            hay.push(m);
1018                            pos.push((line, col));
1019                        }
1020                    }
1021                }
1022                let soft = cells.last().is_some_and(|c| c.is_wrapline());
1023                if soft && line + 1 < total {
1024                    line += 1;
1025                } else {
1026                    break;
1027                }
1028            }
1029            // Trim trailing blank padding (only a logical line's tail can be blank), so a regex `$`
1030            // anchor or a greedy `.*` doesn't run into the grid's blank cells — mirrors
1031            // `viewport_logical_lines`'s trim (#314 Lens 1). Keeps hay/pos in lockstep.
1032            while hay.last().is_some_and(|c| c.is_whitespace()) {
1033                hay.pop();
1034                pos.pop();
1035            }
1036
1037            // A match at char-index range [cs, ce) → a Match, whole-word-filtered and deduped.
1038            // (Marks map many hay entries to one column (#304), so a repeated in-cluster scalar can
1039            // yield consecutive identical Matches — collapse them.)
1040            let push_range = |cs: usize, ce: usize, matches: &mut Vec<Match>| {
1041                if opts.whole_word && !word_bounded(&hay, cs, ce - cs) {
1042                    return;
1043                }
1044                let m = Match {
1045                    start_line: pos[cs].0,
1046                    start_col: pos[cs].1,
1047                    end_line: pos[ce - 1].0,
1048                    end_col: pos[ce - 1].1,
1049                };
1050                if matches.last() != Some(&m) {
1051                    matches.push(m);
1052                }
1053            };
1054
1055            if let Some(re) = &re {
1056                // Regex over the (unfolded) logical line; map each match's byte range to char indices.
1057                let hay_str: String = hay.iter().collect();
1058                for mat in re.find_iter(&hay_str) {
1059                    if mat.start() == mat.end() {
1060                        continue; // skip empty matches (e.g. `a*` between chars)
1061                    }
1062                    let cs = hay_str[..mat.start()].chars().count();
1063                    let ce = hay_str[..mat.end()].chars().count();
1064                    push_range(cs, ce, &mut matches);
1065                }
1066            } else {
1067                // Slide the literal needle non-overlapping, folding each hay char at compare time.
1068                let mut i = 0;
1069                while needle.len() <= hay.len() && i + needle.len() <= hay.len() {
1070                    let hit = hay[i..i + needle.len()]
1071                        .iter()
1072                        .enumerate()
1073                        .all(|(k, &c)| fold(c) == needle[k]);
1074                    if hit {
1075                        let before = matches.len();
1076                        push_range(i, i + needle.len(), &mut matches);
1077                        // Advance past a real (accepted) match; a whole-word-rejected run advances by
1078                        // one so a later, word-bounded position at an overlapping offset is still tried.
1079                        i += if matches.len() > before {
1080                            needle.len()
1081                        } else {
1082                            1
1083                        };
1084                    } else {
1085                        i += 1;
1086                    }
1087                }
1088            }
1089            r = line + 1;
1090        }
1091        matches
1092    }
1093
1094    /// Scroll the viewport so a match's start line is visible (placed at the top
1095    /// when it sits in history; the live view when it is already on screen).
1096    pub fn search_scroll_to(&mut self, m: &Match) {
1097        let target = self.scrollback.len().saturating_sub(m.start_line);
1098        self.set_display_offset(target);
1099    }
1100
1101    /// Project a match onto the current viewport as inclusive-column spans, one
1102    /// per visible row (off-screen parts dropped) — for the renderer to
1103    /// highlight, like `selection_range`.
1104    pub fn match_spans(&self, m: &Match) -> Vec<SelectionSpan> {
1105        let rows = self.grid.rows();
1106        let top = self.scrollback.len() - self.display_offset;
1107        let mut spans = Vec::new();
1108        for line in m.start_line..=m.end_line {
1109            if line < top {
1110                continue;
1111            }
1112            let row = line - top;
1113            if row >= rows {
1114                break;
1115            }
1116            let last = self.abs_line(line).len().saturating_sub(1);
1117            let left = if line == m.start_line { m.start_col } else { 0 };
1118            let right = if line == m.end_line {
1119                m.end_col.min(last)
1120            } else {
1121                last
1122            };
1123            if right >= left {
1124                spans.push(SelectionSpan { row, left, right });
1125            }
1126        }
1127        spans
1128    }
1129
1130    /// Set the search highlights to paint (#108). The consumer owns the
1131    /// `Vec<Match>` (it drives next/prev); handing it back here lets `frame()`
1132    /// project the highlights onto the viewport. An empty vec clears them.
1133    pub fn set_search_highlights(&mut self, matches: Vec<Match>) {
1134        self.search_highlights = matches;
1135        // A new set voids the designation: a stale index could be accidentally
1136        // in range and light wrong content (#428). The consumer re-designates.
1137        self.active_search_highlight = None;
1138    }
1139
1140    /// Designate which member of the held highlight set is the *active* match
1141    /// (#428) — the one the consumer's next/prev navigation currently points at.
1142    /// `frame()` projects it into `overlay.active_match` (it also stays in
1143    /// `overlay.matches`; the renderer's ranking resolves the overlap, #424).
1144    /// `None` or an out-of-range index projects nothing; the designation resets
1145    /// whenever a new set is passed to [`set_search_highlights`](Self::set_search_highlights).
1146    /// The index resolves to its span at call time (#436) — both designation
1147    /// APIs converge on one stored representation.
1148    pub fn set_active_search_highlight(&mut self, index: Option<usize>) {
1149        self.active_search_highlight = index.and_then(|i| self.search_highlights.get(i)).copied();
1150    }
1151
1152    /// Designate the *active* match by its absolute span (#436), independent of
1153    /// the held highlight set — the past-cap path: a backend that caps its
1154    /// hand-over (the documented 1000, xterm's `highlightLimit`) can still give
1155    /// the current match its active emphasis, exactly as xterm creates the
1156    /// active decoration from the found result outside the capped list. The
1157    /// span projects through the same viewport math as any match (wrap-aware);
1158    /// it need not be a member of the held set, so past the cap the match
1159    /// paints the ACTIVE colour only (no plain highlight underneath). `None`
1160    /// clears. Same lifecycle as the index form: reset on every
1161    /// [`set_search_highlights`](Self::set_search_highlights) hand-over and on
1162    /// any coordinate-shifting invalidation.
1163    pub fn set_active_search_match(&mut self, m: Option<Match>) {
1164        self.active_search_highlight = m;
1165    }
1166
1167    /// Invalidate the held search highlights (#108). Called wherever a buffer
1168    /// mutation shifts the *line* coordinates the matches were found at — cap
1169    /// eviction, in-screen region/RI/SU/SD/IL/DL scroll, the accrual
1170    /// sub-region scroll (#449 — which also re-anchors selection/markers below
1171    /// the margin, `selection_shift_below_margin`), reflow, both alt swaps.
1172    /// In-line *column* shifts (ICH/DCH, insert-mode print) and
1173    /// in-place erases (ED/EL/ECH, overwrite) deliberately do NOT funnel — the
1174    /// set stales in place there exactly like the selection sibling and
1175    /// xterm's decorations, healed by the consumer's debounced re-search on
1176    /// output (which those mutations are). Search matches are query-derived
1177    /// (the engine holds matches, not the query, and the *set* itself may have
1178    /// changed), so unlike the user-authored selection they are dropped rather
1179    /// than re-anchored. Clearing avoids painting wrong content for the frame
1180    /// between the mutation and the consumer's refresh.
1181    fn invalidate_search_highlights(&mut self) {
1182        self.search_highlights.clear();
1183        // #436: the active designation is a stored SPAN, no longer structurally
1184        // tied to the set — clear it in the same funnel or it would keep
1185        // painting coordinates that now hold arbitrary other text.
1186        self.active_search_highlight = None;
1187    }
1188
1189    /// Register a decoration marker at viewport `row`, returning its stable id
1190    /// (#118). The row is resolved to an absolute buffer line (like a selection
1191    /// anchor), so the marker tracks that content through scroll/eviction/reflow.
1192    /// The active buffer's marker list (#177 S0) — alt while on the alt screen,
1193    /// else normal. Add/rotate/project operate on this; primary-scoped queries
1194    /// (`command_marks`/`command_lines`) and scrollback eviction read
1195    /// `normal_markers` directly.
1196    fn markers(&self) -> &Vec<Marker> {
1197        if self.on_alt {
1198            &self.alt_markers
1199        } else {
1200            &self.normal_markers
1201        }
1202    }
1203
1204    /// Mutable [`Self::markers`].
1205    fn markers_mut(&mut self) -> &mut Vec<Marker> {
1206        if self.on_alt {
1207            &mut self.alt_markers
1208        } else {
1209            &mut self.normal_markers
1210        }
1211    }
1212
1213    pub fn add_marker(&mut self, row: usize) -> MarkerId {
1214        // On the alt screen this anchors an *alt-scoped* marker (#187): per-buffer
1215        // storage (#186) keeps it out of the primary list, and it is disposed on
1216        // alt-leave — xterm's per-buffer `addMarker` + `clearAllMarkers`. No dead
1217        // sentinel is needed anymore; `markers_mut` routes to the active buffer.
1218        let line = self.viewport_to_abs(row, 0).line;
1219        self.push_marker(line, 0, MarkerKind::Plain)
1220    }
1221
1222    /// Push a marker anchored at absolute `(line, col)` with `kind`, returning its
1223    /// id. The shared core of `add_marker` (viewport row, `col = 0`) and OSC-133
1224    /// command marks (cursor line + column) — one place owns id allocation + the
1225    /// `markers` list.
1226    fn push_marker(&mut self, line: usize, col: usize, kind: MarkerKind) -> MarkerId {
1227        let id = MarkerId(self.next_marker_id);
1228        self.next_marker_id += 1;
1229        self.markers_mut().push(Marker {
1230            id,
1231            line,
1232            col,
1233            kind,
1234        });
1235        id
1236    }
1237
1238    /// Record an OSC 133 command-boundary mark at the cursor's current line
1239    /// (#158). Ignored on the alt screen: unlike the decoration guards that
1240    /// per-buffer storage retired (#187), this one stands on a *semantic* — OSC
1241    /// 133 is shell integration, which only runs on the primary screen, so an alt
1242    /// 133 is meaningless (there is no command to bound). Command nav/announce read
1243    /// the *normal* buffer's marks (`command_marks`/`command_lines`, primary-scoped
1244    /// since #186), so even a stray alt 133 could not reach them — but there is no
1245    /// value in creating an alt-scoped command mark nothing consumes (#188). The
1246    /// cursor line is `scrollback ++ screen`-absolute, independent of
1247    /// `display_offset` (the cursor is always in the grid, never scrollback).
1248    fn add_command_mark(&mut self, kind: MarkerKind) {
1249        if self.on_alt {
1250            return;
1251        }
1252        let line = self.scrollback.len() + self.cursor.row;
1253        self.push_marker(line, self.cursor.col, kind);
1254    }
1255
1256    /// The OSC 133 command-boundary marks in buffer order — `(id, absolute line,
1257    /// kind)` (#158). Plain decoration markers (#118) are excluded. The consumer
1258    /// pairs prompt/command/finished marks and drives navigation/announce policy
1259    /// (#160); core only parses and anchors them.
1260    pub fn command_marks(&self) -> Vec<(MarkerId, usize, MarkerKind)> {
1261        // Primary-scoped: OSC-133 shell integration marks live on the normal
1262        // buffer, so command nav/announce read it even while on the alt screen.
1263        self.normal_markers
1264            .iter()
1265            .filter(|m| m.kind != MarkerKind::Plain)
1266            .map(|m| (m.id, m.line, m.kind))
1267            .collect()
1268    }
1269
1270    /// The executed shell commands recovered from OSC-133 marks, in buffer order
1271    /// (#166) — the data behind screen-reader command navigation. Each
1272    /// [`CommandLine`] pairs a CommandStart(B) with the following OutputStart(C)
1273    /// to extract the *typed command* (the prompt before B and the output after C
1274    /// excluded via the captured columns, VSCode `extractCommandLine` parity), and
1275    /// attaches the trailing CommandFinished(D) exit. A command still being typed
1276    /// (B with no C yet) is not navigable — its text has no bound — so it is
1277    /// omitted until output starts.
1278    pub fn command_lines(&self) -> Vec<CommandLine> {
1279        let mut out: Vec<CommandLine> = Vec::new();
1280        // (B line, B col) awaiting its matching C. Marks arrive in buffer order.
1281        let mut pending: Option<(usize, usize)> = None;
1282        // Primary-scoped (see `command_marks`): the normal buffer's marks.
1283        for m in &self.normal_markers {
1284            match m.kind {
1285                MarkerKind::CommandStart => pending = Some((m.line, m.col)),
1286                MarkerKind::OutputStart => {
1287                    if let Some((b_line, b_col)) = pending.take() {
1288                        // Columns bound the command precisely even though output was
1289                        // written after C — `extract_lines` reads current cells but
1290                        // clips to `[b_col, c_col)`, excluding both prompt and output.
1291                        // Command marks anchor primary content — read the primary
1292                        // grid so the text is right even while on the alt screen (#192).
1293                        let command =
1294                            self.extract_lines(self.primary_grid(), b_line, b_col, m.line, m.col);
1295                        out.push(CommandLine {
1296                            line: self.doc_line_of(self.primary_grid(), b_line),
1297                            command,
1298                            exit: None,
1299                        });
1300                    }
1301                }
1302                MarkerKind::CommandFinished(exit) => {
1303                    // The exit belongs to the most recent command not yet closed;
1304                    // the `is_none` guard stops a stray D from clobbering a code.
1305                    if let Some(last) = out.last_mut()
1306                        && last.exit.is_none()
1307                    {
1308                        last.exit = exit;
1309                    }
1310                }
1311                MarkerKind::Plain | MarkerKind::PromptStart => {}
1312            }
1313        }
1314        out
1315    }
1316
1317    /// The document (logical) line index that absolute buffer line `abs` renders
1318    /// into within [`Term::accessible_text`] — the number of hard line-ends before
1319    /// it (soft-wrapped rows share one logical line). Primary-screen coordinates,
1320    /// matching `accessible_text`'s `start = 0` for the primary screen; command
1321    /// marks are primary-only. O(abs) per call — fine for an on-demand query over
1322    /// the handful of commands in a session.
1323    fn doc_line_of(&self, grid: &Grid, abs: usize) -> usize {
1324        (0..abs)
1325            .filter(|&l| {
1326                !self
1327                    .line_in(grid, l)
1328                    .last()
1329                    .is_some_and(|c| c.is_wrapline())
1330            })
1331            .count()
1332    }
1333
1334    /// Remove a marker by id (#118). Disposing it fires `MarkerDisposed` so the
1335    /// consumer's cleanup is one path whether the marker left by eviction or by
1336    /// this explicit call (xterm's `dispose()` likewise always fires onDispose).
1337    /// A no-op for an unknown/already-disposed id.
1338    pub fn remove_marker(&mut self, id: MarkerId) {
1339        // Id-based, buffer-agnostic: search both lists (ids are unique across
1340        // buffers) so a marker is removed whichever screen it lives on (#177 S0).
1341        let before = self.normal_markers.len() + self.alt_markers.len();
1342        self.normal_markers.retain(|m| m.id != id);
1343        self.alt_markers.retain(|m| m.id != id);
1344        if self.normal_markers.len() + self.alt_markers.len() != before {
1345            self.events.push(TermEvent::MarkerDisposed(id));
1346        }
1347    }
1348
1349    /// Shift markers down one absolute line after the oldest history line is
1350    /// evicted; a marker *on* that line (abs 0) has left the buffer, so it is
1351    /// disposed and announced (#118) — the marker analogue of
1352    /// `selection_evict_oldest`, but a list with per-marker disposal.
1353    /// The marker analogue of `selection_shift_below_margin` (#449) — primary
1354    /// only, because the accrual branch that needs it is primary-only.
1355    fn markers_shift_below_margin(&mut self, from: usize) {
1356        for m in &mut self.normal_markers {
1357            if m.line >= from {
1358                m.line += 1;
1359            }
1360        }
1361    }
1362
1363    fn markers_evict_oldest(&mut self) {
1364        // Scrollback eviction is primary-only (the alt screen has none).
1365        let mut disposed = Vec::new();
1366        self.normal_markers.retain_mut(|m| {
1367            if m.line == 0 {
1368                disposed.push(m.id);
1369                false
1370            } else {
1371                m.line -= 1;
1372                true
1373            }
1374        });
1375        for id in disposed {
1376            self.events.push(TermEvent::MarkerDisposed(id));
1377        }
1378    }
1379
1380    /// Rotate markers within an in-screen region scroll of absolute lines
1381    /// `[top, bottom]` (`up` = a line dropped at `top`, else at `bottom`) — the
1382    /// marker analogue of `selection_rotate_region`. A marker on the dropped edge
1383    /// has left the buffer, so it is disposed and announced (#118).
1384    fn markers_rotate_region(&mut self, top: usize, bottom: usize, up: bool) {
1385        let mut disposed = Vec::new();
1386        self.markers_mut().retain_mut(|m| {
1387            if m.line < top || m.line > bottom {
1388                return true; // outside the region — unchanged
1389            }
1390            let dropped_edge = if up { top } else { bottom };
1391            if m.line == dropped_edge {
1392                disposed.push(m.id);
1393                false
1394            } else {
1395                m.line = if up { m.line - 1 } else { m.line + 1 };
1396                true
1397            }
1398        });
1399        for id in disposed {
1400            self.events.push(TermEvent::MarkerDisposed(id));
1401        }
1402    }
1403
1404    /// The active buffer's markers projected onto the current viewport — one
1405    /// `MarkerPosition` per marker whose line is visible, off-screen markers
1406    /// omitted. The alt screen projects its own (alt-scoped) markers now (#187);
1407    /// they are disposed on alt-leave, so a primary frame never shows them.
1408    fn marker_positions(&self) -> Vec<MarkerPosition> {
1409        let top = self.scrollback.len() - self.display_offset;
1410        let rows = self.grid.rows();
1411        self.markers()
1412            .iter()
1413            .filter_map(|m| {
1414                let row = m.line.checked_sub(top)?;
1415                (row < rows).then_some(MarkerPosition {
1416                    id: m.id,
1417                    row,
1418                    kind: m.kind,
1419                })
1420            })
1421            .collect()
1422    }
1423
1424    /// Every live marker's absolute buffer line (#120 S3) — the off-viewport
1425    /// superset of `marker_positions`, for the overview ruler. No viewport filter:
1426    /// a marker scrolled out of view is still reported (that is the ruler's job),
1427    /// its `line` in the same `[0, scrollback + rows)` frame as the header's
1428    /// `scrollback_len`/`display_offset`.
1429    fn all_marker_lines(&self) -> Vec<MarkerLine> {
1430        self.markers()
1431            .iter()
1432            .map(|m| MarkerLine {
1433                id: m.id,
1434                line: m.line as u32,
1435            })
1436            .collect()
1437    }
1438
1439    /// Begin a selection of `ty` at viewport `(row, col)`, `side`.
1440    pub fn selection_begin(&mut self, row: usize, col: usize, side: Side, ty: SelectionType) {
1441        let anchor = Anchor {
1442            point: self.viewport_to_abs(row, col),
1443            side,
1444        };
1445        self.selection = Some(Selection {
1446            ty,
1447            anchor,
1448            focus: anchor,
1449        });
1450    }
1451
1452    /// Extend the live selection's focus to viewport `(row, col)`, `side`.
1453    pub fn selection_extend(&mut self, row: usize, col: usize, side: Side) {
1454        let focus = Anchor {
1455            point: self.viewport_to_abs(row, col),
1456            side,
1457        };
1458        if let Some(sel) = &mut self.selection {
1459            sel.focus = focus;
1460        }
1461    }
1462
1463    /// Clear the selection.
1464    pub fn selection_clear(&mut self) {
1465        self.selection = None;
1466    }
1467
1468    /// Shift the selection up by one absolute line after the oldest history line
1469    /// is evicted by the scrollback cap. An endpoint clamps to the new top; if
1470    /// the whole selection was on the evicted line, it is cleared.
1471    /// Shift selection endpoints anchored at absolute line `>= from` down by
1472    /// one (#449): a top-anchored sub-region scroll grew scrollback while the
1473    /// rows below the margin stayed fixed on screen, so their content's
1474    /// absolute index rose +1 and the anchors must follow it. Endpoints above
1475    /// `from` (in-region / scrollback content, whose indices are stable) are
1476    /// untouched — per endpoint, so a selection straddling the margin keeps
1477    /// both ends on their content.
1478    fn selection_shift_below_margin(&mut self, from: usize) {
1479        if let Some(sel) = &mut self.selection {
1480            if sel.anchor.point.line >= from {
1481                sel.anchor.point.line += 1;
1482            }
1483            if sel.focus.point.line >= from {
1484                sel.focus.point.line += 1;
1485            }
1486        }
1487    }
1488
1489    fn selection_evict_oldest(&mut self) {
1490        let Some((a, f)) = self
1491            .selection
1492            .as_ref()
1493            .map(|s| (s.anchor.point.line, s.focus.point.line))
1494        else {
1495            return;
1496        };
1497        if a == 0 && f == 0 {
1498            self.selection = None;
1499            return;
1500        }
1501        if let Some(sel) = &mut self.selection {
1502            sel.anchor.point.line = a.saturating_sub(1);
1503            sel.focus.point.line = f.saturating_sub(1);
1504        }
1505    }
1506
1507    /// Rotate the selection within an in-screen scroll of absolute lines
1508    /// `[top, bottom]`. `up` = content scrolled up (a line dropped at `top`);
1509    /// otherwise down (dropped at `bottom`). Called once per scrolled line (delta
1510    /// 1) by linefeed/RI/SU/SD/IL/DL.
1511    ///
1512    /// Mirrors alacritty `Selection::rotate`: an endpoint pushed past the region
1513    /// edge is *clamped* to that edge (upper → `top`/col 0/Left, lower →
1514    /// `bottom`/last col/Right; columns/side kept for Block), preserving the part
1515    /// of the selection still in the buffer. The whole selection clears only on a
1516    /// true *overtake* — the upper endpoint crossing the bottom while the lower
1517    /// stays inside, or the lower falling above the upper (a selection wholly on
1518    /// the dropped line). (#174: this replaced a policy that cleared on any
1519    /// endpoint touching the dropped edge, dropping still-valid content.)
1520    fn selection_rotate_region(&mut self, top: usize, bottom: usize, up: bool) {
1521        let (ty, anchor, focus) = match self.selection.as_ref() {
1522            Some(s) => (s.ty, s.anchor, s.focus),
1523            None => return,
1524        };
1525        let last_col = self.grid.cols().saturating_sub(1);
1526        // Order the endpoints by buffer position; the upper (`start`) clamps to
1527        // the region top, the lower (`end`) to the bottom. Remember which is the
1528        // anchor so the result writes back to the right field.
1529        let anchor_is_start = anchor.point <= focus.point;
1530        let (mut start, mut end) = if anchor_is_start {
1531            (anchor, focus)
1532        } else {
1533            (focus, anchor)
1534        };
1535
1536        let (top_i, bottom_i) = (top as isize, bottom as isize);
1537        // The endpoint's line after the one-line scroll, or `None` if it's outside
1538        // the region (untouched). The dropped-edge line shifts *past* the edge (to
1539        // be clamped/overtaken below), matching alacritty's `line - delta`.
1540        let shift = |line: usize| -> Option<isize> {
1541            if line < top || line > bottom {
1542                None
1543            } else if up {
1544                Some(line as isize - 1)
1545            } else {
1546                Some(line as isize + 1)
1547            }
1548        };
1549
1550        // Upper endpoint: clamp to the region top when pushed above it; clear if it
1551        // overtook the region bottom (down-scroll) while the lower stays inside.
1552        if let Some(nl) = shift(start.point.line) {
1553            if nl > bottom_i && (end.point.line as isize) <= bottom_i {
1554                self.selection = None;
1555                return;
1556            }
1557            if nl < top_i {
1558                start.point.line = top;
1559                if ty != SelectionType::Block {
1560                    start.point.col = 0;
1561                    start.side = Side::Left;
1562                }
1563            } else {
1564                start.point.line = nl as usize;
1565            }
1566        }
1567        // Lower endpoint: clear if it fell above the (rotated) upper endpoint;
1568        // else clamp to the region bottom when pushed below it.
1569        if let Some(nl) = shift(end.point.line) {
1570            if nl < start.point.line as isize {
1571                self.selection = None;
1572                return;
1573            }
1574            if nl > bottom_i {
1575                end.point.line = bottom;
1576                if ty != SelectionType::Block {
1577                    end.point.col = last_col;
1578                    end.side = Side::Right;
1579                }
1580            } else {
1581                end.point.line = nl as usize;
1582            }
1583        }
1584
1585        if let Some(sel) = &mut self.selection {
1586            if anchor_is_start {
1587                (sel.anchor, sel.focus) = (start, end);
1588            } else {
1589                (sel.anchor, sel.focus) = (end, start);
1590            }
1591        }
1592    }
1593
1594    /// The selection projected onto the current viewport: one inclusive-column
1595    /// span per visible row. Rows scrolled off-screen (above or below) are
1596    /// dropped. Empty when nothing is selected. See `SelectionSpan`.
1597    pub fn selection_range(&self) -> Vec<SelectionSpan> {
1598        let Some(resolved) = self.resolve() else {
1599            return Vec::new();
1600        };
1601        let rows = self.grid.rows();
1602        // Absolute index of viewport row 0.
1603        let top = self.scrollback.len() - self.display_offset;
1604        let mut spans = Vec::new();
1605
1606        // Add a span for absolute `line` with inclusive cols `left..=right`, if
1607        // the line is currently visible.
1608        let mut push = |line: usize, left: usize, right: usize| {
1609            if line >= top {
1610                let row = line - top;
1611                if row < rows {
1612                    spans.push(SelectionSpan { row, left, right });
1613                }
1614            }
1615        };
1616
1617        match resolved {
1618            Resolved::Linear {
1619                start_line,
1620                from,
1621                end_line,
1622                to,
1623            } => {
1624                for line in start_line..=end_line {
1625                    let len = self.abs_line(line).len();
1626                    let left = if line == start_line { from } else { 0 };
1627                    let right_excl = if line == end_line { to.min(len) } else { len };
1628                    if right_excl > left {
1629                        push(line, left, right_excl - 1);
1630                    }
1631                }
1632            }
1633            Resolved::Block {
1634                line0,
1635                line1,
1636                from,
1637                to,
1638            } => {
1639                if to > from {
1640                    for line in line0..=line1 {
1641                        push(line, from, to - 1);
1642                    }
1643                }
1644            }
1645        }
1646        spans
1647    }
1648
1649    /// Resolve the live selection into absolute-coordinate bounds per type:
1650    /// a `Linear` run (char/word/line, which join soft wraps) or a `Block`
1651    /// rectangle. `None` when nothing is selected. Columns are half-open
1652    /// (`from..to`). Shared by `selection_text` and `selection_range`.
1653    fn resolve(&self) -> Option<Resolved> {
1654        let sel = self.selection.as_ref()?;
1655        let (start, end) = sel.ordered();
1656        Some(match sel.ty {
1657            SelectionType::Char => {
1658                // Half-open columns: each side decides if its own cell is in.
1659                let from = match start.side {
1660                    Side::Left => start.point.col,
1661                    Side::Right => start.point.col + 1,
1662                };
1663                let to = match end.side {
1664                    Side::Left => end.point.col,
1665                    Side::Right => end.point.col + 1,
1666                };
1667                Resolved::Linear {
1668                    start_line: start.point.line,
1669                    from,
1670                    end_line: end.point.line,
1671                    to,
1672                }
1673            }
1674            SelectionType::Word => {
1675                // Snap both ends to word boundaries (side is ignored).
1676                let ws = self.word_start(start.point);
1677                let we = self.word_end(end.point);
1678                Resolved::Linear {
1679                    start_line: ws.line,
1680                    from: ws.col,
1681                    end_line: we.line,
1682                    to: we.col + 1,
1683                }
1684            }
1685            SelectionType::Line => Resolved::Linear {
1686                start_line: start.point.line,
1687                from: 0,
1688                end_line: end.point.line,
1689                to: self.grid.cols(),
1690            },
1691            SelectionType::Block => {
1692                // Rectangular: the same column range on every row. Columns come
1693                // from the two anchors (min/max, with each edge's side).
1694                let cols = self.grid.cols();
1695                let (a, b) = (sel.anchor, sel.focus);
1696                let (lcol, lside, rcol, rside) = if a.point.col <= b.point.col {
1697                    (a.point.col, a.side, b.point.col, b.side)
1698                } else {
1699                    (b.point.col, b.side, a.point.col, a.side)
1700                };
1701                let from = match lside {
1702                    Side::Left => lcol,
1703                    Side::Right => lcol + 1,
1704                };
1705                let to = match rside {
1706                    Side::Left => rcol,
1707                    Side::Right => rcol + 1,
1708                };
1709                Resolved::Block {
1710                    line0: a.point.line.min(b.point.line),
1711                    line1: a.point.line.max(b.point.line),
1712                    from,
1713                    to: to.min(cols).max(from),
1714                }
1715            }
1716        })
1717    }
1718
1719    /// The selected text (for copy), or `None` when nothing is selected.
1720    pub fn selection_text(&self) -> Option<String> {
1721        match self.resolve()? {
1722            Resolved::Linear {
1723                start_line,
1724                from,
1725                end_line,
1726                to,
1727            } => Some(self.extract_lines(&self.grid, start_line, from, end_line, to)),
1728            Resolved::Block {
1729                line0,
1730                line1,
1731                from,
1732                to,
1733            } => {
1734                // Each row independently — no soft-wrap joining.
1735                let mut out = String::new();
1736                for line in line0..=line1 {
1737                    let hi = to.min(self.abs_line(line).len());
1738                    let mut seg = String::new();
1739                    for col in from..hi {
1740                        self.append_cell(&self.grid, &mut seg, line, col);
1741                    }
1742                    out.push_str(seg.trim_end());
1743                    if line != line1 {
1744                        out.push('\n');
1745                    }
1746                }
1747                Some(out)
1748            }
1749        }
1750    }
1751
1752    /// Append the text at absolute `(line, col)` — its base glyph plus any
1753    /// combining marks from the row's map — to `out`. Wide-char spacers
1754    /// contribute nothing.
1755    fn append_cell(&self, grid: &Grid, out: &mut String, line: usize, col: usize) {
1756        let cell = &self.line_in(grid, line)[col];
1757        if cell.is_spacer() {
1758            return;
1759        }
1760        out.push(cell.c());
1761        if let Some(marks) = self.combining_in(grid, line, col) {
1762            out.extend(marks);
1763        }
1764    }
1765
1766    /// The whole buffer as one text document (#150): scrollback + screen assembled
1767    /// into logical lines (soft-wrap joined, wide-spacers skipped, trailing blanks
1768    /// trimmed at the logical end) — the accessible-view a screen reader reads as
1769    /// a document, distinct from the viewport row tree (#119). Reuses the
1770    /// selection extraction ([`extract_lines`](Self::extract_lines)) over the full
1771    /// range. On the alt screen only the alt buffer is shown — its "scrollback" is
1772    /// the *primary* buffer's, not this app's — mirroring `viewport_logical_lines`'
1773    /// alt floor.
1774    pub fn accessible_text(&self) -> String {
1775        let total = self.scrollback.len() + self.grid.rows();
1776        if total == 0 {
1777            return String::new();
1778        }
1779        let start = if self.on_alt {
1780            self.scrollback.len()
1781        } else {
1782            0
1783        };
1784        let mut doc = self.extract_lines(&self.grid, start, 0, total - 1, usize::MAX);
1785        // Trim *trailing* empty lines (blank screen rows below the content) — pure
1786        // noise to a listener, and what a fresh screen would otherwise emit. Keep
1787        // *internal* blank lines (paragraph breaks between command outputs) — a
1788        // document wants those, unlike the viewport tree which drops all empties.
1789        doc.truncate(doc.trim_end_matches('\n').len());
1790        doc
1791    }
1792
1793    /// Concatenate the selected cells from `(start_line, from)` to
1794    /// `(end_line, to_end)` (half-open columns on the first/last line, whole
1795    /// lines between). Soft-wrapped rows (WRAPLINE) accumulate into one *logical*
1796    /// line so trailing-blank trimming happens only at the logical end — spaces
1797    /// at a wrap boundary are real content. A hard line-end flushes with `\n`.
1798    fn extract_lines(
1799        &self,
1800        grid: &Grid,
1801        start_line: usize,
1802        from: usize,
1803        end_line: usize,
1804        to_end: usize,
1805    ) -> String {
1806        let mut out = String::new();
1807        let mut current = String::new();
1808        for line in start_line..=end_line {
1809            let cells = self.line_in(grid, line);
1810            let left = if line == start_line { from } else { 0 };
1811            let right = if line == end_line {
1812                to_end.min(cells.len())
1813            } else {
1814                cells.len()
1815            };
1816            // A degenerate range (sides inverting one cell) gives left > right;
1817            // clamp to empty rather than panic on the slice.
1818            let right = right.max(left);
1819            for col in left..right {
1820                self.append_cell(grid, &mut current, line, col);
1821            }
1822
1823            let is_last = line == end_line;
1824            let soft = cells.last().is_some_and(|c| c.is_wrapline());
1825            if is_last || !soft {
1826                out.push_str(current.trim_end());
1827                current.clear();
1828                if !is_last {
1829                    out.push('\n');
1830                }
1831            }
1832        }
1833        out
1834    }
1835
1836    /// The lowest absolute line a soft-wrap buffer walk may reach. On the alt screen
1837    /// `scrollback` holds the *primary* buffer's history — a separate logical space —
1838    /// so a walk floors at `scrollback.len()` (the alt grid's first line) and must not
1839    /// join across it. Mirrors the `search()` (#144) and `viewport_logical_lines`
1840    /// (#113) floors: justerm's single `[scrollback ++ grid]` buffer reproduces the
1841    /// primary↔alt isolation xterm gets from separate `Buffer` objects.
1842    fn abs_floor(&self) -> usize {
1843        if self.on_alt {
1844            self.scrollback.len()
1845        } else {
1846            0
1847        }
1848    }
1849
1850    /// The cell position before `(line, col)` in the *logical* line — the column
1851    /// to the left, or the end of the previous row if it soft-wrapped into this
1852    /// one. `None` at the buffer start or across a hard line-end.
1853    fn prev_pos(&self, line: usize, col: usize) -> Option<(usize, usize)> {
1854        if col > 0 {
1855            return Some((line, col - 1));
1856        }
1857        // Only step up while the previous row is still on *this* buffer (>= floor):
1858        // on alt, row 0 (`line == scrollback.len()`) must not join the primary
1859        // scrollback row below it, even when that row carries WRAPLINE (#207).
1860        if line > self.abs_floor() {
1861            let prev = self.abs_line(line - 1);
1862            if prev.last().is_some_and(|c| c.is_wrapline()) {
1863                return Some((line - 1, prev.len() - 1));
1864            }
1865        }
1866        None
1867    }
1868
1869    /// The cell position after `(line, col)` in the *logical* line — the column
1870    /// to the right, or the start of the next row if this row soft-wrapped.
1871    /// `None` at the buffer end or across a hard line-end.
1872    fn next_pos(&self, line: usize, col: usize) -> Option<(usize, usize)> {
1873        let cells = self.abs_line(line);
1874        if col + 1 < cells.len() {
1875            return Some((line, col + 1));
1876        }
1877        let total = self.scrollback.len() + self.grid.rows();
1878        // Symmetric floor guard (#207): a row below the floor (primary scrollback on
1879        // alt) must not soft-wrap-join down into the alt grid. `line >= floor` holds
1880        // for any position reachable on alt once `prev_pos` is floored; kept explicit
1881        // so no future caller can cross from a primary row.
1882        if line >= self.abs_floor()
1883            && line + 1 < total
1884            && cells.last().is_some_and(|c| c.is_wrapline())
1885        {
1886            return Some((line + 1, 0));
1887        }
1888        None
1889    }
1890
1891    /// Walk left to the first cell of `p`'s word (a maximal run of non-boundary
1892    /// chars), following a soft wrap into the previous row.
1893    fn word_start(&self, p: BufferPoint) -> BufferPoint {
1894        let cells = self.abs_line(p.line);
1895        let (mut line, mut col) = (p.line, p.col.min(cells.len().saturating_sub(1)));
1896        while let Some((pl, pc)) = self.prev_pos(line, col) {
1897            if is_word_boundary(self.abs_line(pl)[pc].c()) {
1898                break;
1899            }
1900            line = pl;
1901            col = pc;
1902        }
1903        BufferPoint { line, col }
1904    }
1905
1906    /// Walk right to the last cell of `p`'s word, following a soft wrap into the
1907    /// next row.
1908    fn word_end(&self, p: BufferPoint) -> BufferPoint {
1909        let cells = self.abs_line(p.line);
1910        let (mut line, mut col) = (p.line, p.col.min(cells.len().saturating_sub(1)));
1911        while let Some((nl, nc)) = self.next_pos(line, col) {
1912            if is_word_boundary(self.abs_line(nl)[nc].c()) {
1913                break;
1914            }
1915            line = nl;
1916            col = nc;
1917        }
1918        BufferPoint { line, col }
1919    }
1920
1921    /// Resize the screen to `cols` x `rows`. Rows dropped off the top (on shrink)
1922    /// enter scrollback. Column reflow of soft-wrapped lines is layered on top
1923    /// separately (#7). The whole screen is damaged.
1924    pub fn resize(&mut self, cols: usize, rows: usize) {
1925        // A terminal is never 0-wide/0-tall; clamp so the math below (rows - 1,
1926        // chunking by cols) can't underflow or divide by zero.
1927        let cols = cols.max(1);
1928        let rows = rows.max(1);
1929        let old_cols = self.grid.cols();
1930        let limit = self.scrollback_limit;
1931
1932        // A reflow moves match coordinates (and can change the match set), so the
1933        // query-derived highlights are invalidated; the consumer re-searches at
1934        // the new width. The selection re-anchors below — it is user-authored.
1935        self.invalidate_search_highlights();
1936
1937        // Both screens are resized. Scrollback pairs with the PRIMARY screen
1938        // (whichever is active) — the alt screen has no history of its own.
1939        let dims = ReflowDims {
1940            old_cols,
1941            cols,
1942            rows,
1943            limit,
1944        };
1945        let scrollback = std::mem::take(&mut self.scrollback);
1946        if self.on_alt {
1947            // Active = alt (cursor, no scrollback); inactive = primary. Selection
1948            // is primary-only and cleared on alt enter, so no anchors to track.
1949            // Alt markers DO ride this reflow (#187): justerm column-reflows the
1950            // alt grid, so a marker must follow its content or it drifts off. Their
1951            // stored line is `base + alt_row` (base = primary scrollback len), so
1952            // convert to alt-local rows for the pane, and re-anchor on the reflowed
1953            // base afterward (the primary scrollback below may rewrap its length).
1954            let old_base = scrollback.len();
1955            let alt_pts: Vec<(usize, usize)> = self
1956                .alt_markers
1957                .iter()
1958                .map(|m| (m.line - old_base, 0))
1959                .collect();
1960            let alt = self.grid.take_lines();
1961            let r_alt = reflow_pane(alt, VecDeque::new(), self.cursor.point(), &alt_pts, dims);
1962            self.grid.set_screen(r_alt.screen, cols, rows);
1963            self.cursor.set_point(r_alt.cursor, rows, cols);
1964
1965            // Primary is inactive here, but markers anchor *primary* content, so
1966            // they reflow with it (the selection is already cleared on alt enter).
1967            let marker_pts: Vec<(usize, usize)> =
1968                self.normal_markers.iter().map(|m| (m.line, 0)).collect();
1969            let primary = self.alt_grid.take_lines();
1970            let r = reflow_pane(
1971                primary,
1972                scrollback,
1973                self.saved_cursor.point(),
1974                &marker_pts,
1975                dims,
1976            );
1977            self.alt_grid.set_screen(r.screen, cols, rows);
1978            self.scrollback = r.scrollback;
1979            self.saved_cursor.set_point(r.cursor, rows, cols);
1980            for (i, m) in self.normal_markers.iter_mut().enumerate() {
1981                m.line = r.extras[i].0;
1982            }
1983            let new_base = self.scrollback.len();
1984            for (i, m) in self.alt_markers.iter_mut().enumerate() {
1985                m.line = new_base + r_alt.extras[i].0;
1986            }
1987        } else {
1988            // Active = primary (cursor, scrollback); inactive = alt. The selection
1989            // anchors (absolute) reflow alongside the cursor so they keep their
1990            // content across a column change.
1991            let sel_pts: Vec<(usize, usize)> = self
1992                .selection
1993                .as_ref()
1994                .map(|s| {
1995                    vec![
1996                        (s.anchor.point.line, s.anchor.point.col),
1997                        (s.focus.point.line, s.focus.point.col),
1998                    ]
1999                })
2000                .unwrap_or_default();
2001            // Markers reflow on the same pane by (line, col) — the column matters
2002            // for OSC-133 command marks, whose B/C columns bound the extracted
2003            // command text (#166). They ride after the selection points so each
2004            // reads its own reflowed slot back from `extras` (#118).
2005            let mut pts = sel_pts.clone();
2006            pts.extend(self.normal_markers.iter().map(|m| (m.line, m.col)));
2007
2008            let primary = self.grid.take_lines();
2009            let r = reflow_pane(primary, scrollback, self.cursor.point(), &pts, dims);
2010            self.grid.set_screen(r.screen, cols, rows);
2011            self.scrollback = r.scrollback;
2012            self.cursor.set_point(r.cursor, rows, cols);
2013            if let Some(sel) = &mut self.selection {
2014                sel.anchor.point = BufferPoint {
2015                    line: r.extras[0].0,
2016                    col: r.extras[0].1,
2017                };
2018                sel.focus.point = BufferPoint {
2019                    line: r.extras[1].0,
2020                    col: r.extras[1].1,
2021                };
2022            }
2023            let marker_off = sel_pts.len();
2024            for (i, m) in self.normal_markers.iter_mut().enumerate() {
2025                m.line = r.extras[marker_off + i].0;
2026                m.col = r.extras[marker_off + i].1;
2027            }
2028
2029            let alt = self.alt_grid.take_lines();
2030            let r = reflow_pane(alt, VecDeque::new(), (0, 0), &[], dims);
2031            self.alt_grid.set_screen(r.screen, cols, rows);
2032        }
2033
2034        // Margins reset to the full screen; tab stops reset to the default grid.
2035        self.cursor.pending_wrap = false;
2036        self.scroll_top = 0;
2037        self.scroll_bottom = rows - 1;
2038        self.tabs = default_tabs(cols);
2039        self.display_offset = self.display_offset.min(self.scrollback.len());
2040
2041        // Damage tracking is sized to the screen; a resize repaints everything,
2042        // so drop any pending scroll op (it points at the old rows).
2043        self.line_damage = vec![LineBounds::undamaged(cols); rows];
2044        self.scroll = None;
2045        self.mark_fully_damaged();
2046    }
2047
2048    pub fn grid(&self) -> &Grid {
2049        &self.grid
2050    }
2051
2052    pub fn cursor(&self) -> &Cursor {
2053        &self.cursor
2054    }
2055
2056    /// Whether bracketed-paste mode (DEC ?2004) is enabled. The input encoder
2057    /// (#11) reads this to decide whether to wrap pasted text in markers.
2058    pub fn bracketed_paste(&self) -> bool {
2059        self.bracketed_paste
2060    }
2061
2062    // ---- input encoding (#11) ------------------------------------------------
2063
2064    /// Encode a key event to bytes using the active cursor-key mode (DECCKM)
2065    /// and the kitty keyboard-protocol flags (`encode_key` consults both).
2066    pub fn encode_key(&self, ev: KeyEvent) -> Option<Vec<u8>> {
2067        encode_key(
2068            &ev,
2069            self.app_cursor_keys,
2070            self.application_keypad,
2071            self.kitty_flags,
2072        )
2073    }
2074
2075    /// Encode a mouse event using the active tracking mode + encoding. `None`
2076    /// when reporting is off or the event is filtered by the mode.
2077    pub fn encode_mouse(&self, ev: MouseEvent) -> Option<Vec<u8>> {
2078        encode_mouse(&ev, self.mouse_protocol, self.mouse_encoding)
2079    }
2080
2081    /// Encode pasted text, wrapping it in bracketed-paste markers when ?2004 is
2082    /// on.
2083    pub fn encode_paste(&self, text: &str) -> Vec<u8> {
2084        encode_paste(text, self.bracketed_paste)
2085    }
2086
2087    /// Encode a focus change (`CSI I`/`CSI O`), or `None` when focus reporting
2088    /// (?1004) is off.
2089    pub fn encode_focus(&self, focused: bool) -> Option<Vec<u8>> {
2090        encode_focus(focused, self.focus_events)
2091    }
2092
2093    /// Take the consumer events queued since the last drain, emptying the queue.
2094    pub fn drain_events(&mut self) -> Vec<TermEvent> {
2095        std::mem::take(&mut self.events)
2096    }
2097
2098    /// Take the reply bytes queued since the last drain (DA/DSR/DECRQM answers),
2099    /// emptying the buffer. The consumer writes them back to the PTY.
2100    pub fn drain_replies(&mut self) -> Vec<u8> {
2101        std::mem::take(&mut self.replies)
2102    }
2103
2104    /// Device Status Report (CSI Ps n): 6 = cursor position, 5 = operating
2105    /// status. Queues the reply for `drain_replies` (#27).
2106    fn device_status_report(&mut self, param: u16) {
2107        match param {
2108            6 => {
2109                // CSI row;col R, 1-based — region-relative under origin mode
2110                // (the coordinate system the app is addressing in).
2111                let row = if self.origin_mode {
2112                    self.cursor.row.saturating_sub(self.scroll_top)
2113                } else {
2114                    self.cursor.row
2115                } + 1;
2116                let col = self.cursor.col + 1;
2117                self.replies
2118                    .extend_from_slice(format!("\x1b[{row};{col}R").as_bytes());
2119            }
2120            5 => self.replies.extend_from_slice(b"\x1b[0n"), // status: OK
2121            _ => {}
2122        }
2123    }
2124
2125    /// Kitty keyboard-protocol negotiation (#23). `lead` is the leading CSI
2126    /// intermediate: `?` query, `>` push, `=` set, `<` pop.
2127    fn kitty_dispatch(&mut self, lead: u8, params: &Params) {
2128        match lead {
2129            // Query → report the current flags as `CSI ? flags u` (#27 channel).
2130            b'?' => self
2131                .replies
2132                .extend_from_slice(format!("\x1b[?{}u", self.kitty_flags).as_bytes()),
2133            // Push: save the current flags, then set the new ones (default 0).
2134            b'>' => {
2135                const KITTY_STACK_CAP: usize = 16;
2136                if self.kitty_stack.len() >= KITTY_STACK_CAP {
2137                    self.kitty_stack.remove(0); // drop the oldest on overflow
2138                }
2139                self.kitty_stack.push(self.kitty_flags);
2140                self.kitty_flags = param_or(params, 0, 0) as u8;
2141            }
2142            // Pop `n` (default 1): restore from the stack, 0 once empty.
2143            b'<' => {
2144                for _ in 0..param_or(params, 0, 1) {
2145                    self.kitty_flags = self.kitty_stack.pop().unwrap_or(0);
2146                }
2147            }
2148            // Set in place (no push): mode 1 replace, 2 or-in, 3 and-not.
2149            b'=' => {
2150                let flags = param_or(params, 0, 0) as u8;
2151                self.kitty_flags = match param_or(params, 1, 1) {
2152                    1 => flags,
2153                    2 => self.kitty_flags | flags,
2154                    3 => self.kitty_flags & !flags,
2155                    _ => self.kitty_flags,
2156                };
2157            }
2158            _ => {}
2159        }
2160    }
2161
2162    /// DECRQM (CSI ? Ps $ p): report whether DEC private mode `Ps` is set —
2163    /// `CSI ? Ps ; val $ y` with val 1=set, 2=reset, 0=not recognized (#27).
2164    fn decrqm(&mut self, mode: u16) {
2165        let state = match mode {
2166            1 => Some(self.app_cursor_keys),
2167            // DECANM (#84): set = ANSI mode (the normal state), reset = VT52.
2168            2 => Some(!self.vt52_mode),
2169            6 => Some(self.origin_mode),
2170            // DECCOLM: derived from the actual width, never a tracked flag — a
2171            // flag would lie if the consumer ignored the resize request (#82).
2172            3 => Some(self.grid.cols() == 132),
2173            7 => Some(self.autowrap),
2174            45 => Some(self.reverse_wraparound),
2175            9 => Some(self.mouse_protocol == MouseProtocol::X10),
2176            66 => Some(self.application_keypad),
2177            12 => Some(self.cursor.blink),
2178            25 => Some(self.cursor.visible),
2179            // Mouse tracking is a single-state enum (the levels are mutually
2180            // exclusive — an app enables one), so querying ?1000 while ?1002 is
2181            // active reports "reset". Faithful to that model.
2182            1000 => Some(self.mouse_protocol == MouseProtocol::Normal),
2183            1002 => Some(self.mouse_protocol == MouseProtocol::ButtonEvent),
2184            1003 => Some(self.mouse_protocol == MouseProtocol::AnyEvent),
2185            1004 => Some(self.focus_events),
2186            1006 => Some(self.mouse_encoding == MouseEncoding::Sgr),
2187            1015 => Some(self.mouse_encoding == MouseEncoding::Urxvt),
2188            1005 => Some(self.mouse_encoding == MouseEncoding::Utf8),
2189            1016 => Some(self.mouse_encoding == MouseEncoding::SgrPixels),
2190            47 | 1047 | 1049 => Some(self.on_alt),
2191            2004 => Some(self.bracketed_paste),
2192            2026 => Some(self.synchronized_output),
2193            2027 => Some(self.grapheme_clustering),
2194            2031 => Some(self.color_scheme_updates),
2195            9001 => Some(self.win32_input_mode),
2196            _ => None,
2197        };
2198        let val = match state {
2199            Some(true) => 1,
2200            Some(false) => 2,
2201            None => 0,
2202        };
2203        self.replies
2204            .extend_from_slice(format!("\x1b[?{mode};{val}$y").as_bytes());
2205    }
2206
2207    /// Resolve a cell's `link` index (OSC 8) to its URI, or `None` if the index
2208    /// is out of range. The renderer reads `Cell.link`, then this, to make a
2209    /// cell clickable (#26).
2210    pub fn hyperlink(&self, link: core::num::NonZeroU32) -> Option<&str> {
2211        self.hyperlink_pool
2212            .get(link.get() as usize - 1)
2213            .map(String::as_str)
2214    }
2215
2216    // ---- cursor / scroll primitives ------------------------------------------
2217
2218    /// Move down one line. At the bottom margin, scroll the region instead;
2219    /// below the region, just descend (no scroll). Column is unchanged (raw LF;
2220    /// CR is what returns to column 0).
2221    fn linefeed(&mut self) {
2222        // New-line mode (LNM ?20): a line feed also returns to column 0 (#71).
2223        if self.newline_mode {
2224            self.carriage_return();
2225        }
2226        if self.cursor.row == self.scroll_bottom {
2227            // A top-anchored primary-screen scroll pushes the evicted top line
2228            // into scrollback history.
2229            if self.scroll_top == 0 && !self.on_alt {
2230                // Scrollback accrues whenever the scroll is top-anchored on the
2231                // primary screen (`scroll_top == 0`) — but the O(1) ring handshake
2232                // only applies to a *full-screen* scroll (`scroll_bottom` at the
2233                // last row). A top-anchored *sub-region* (`[0..k]`, k < rows-1)
2234                // still accrues, yet must scroll only its region, so it keeps the
2235                // copy + region scroll. These are distinct predicates (ADR-0009).
2236                let evicted = if self.scroll_bottom == self.grid.rows() - 1 {
2237                    // Full-screen hot path: move the evicted top row out, install
2238                    // a recycled blank as the new bottom (zero-alloc steady state).
2239                    let blank = self
2240                        .recycled_row
2241                        .take()
2242                        .unwrap_or_else(|| Row::from_cells(Vec::with_capacity(self.grid.cols())));
2243                    self.grid.scroll_up_recycle(blank)
2244                } else {
2245                    // Top-anchored sub-region: copy row 0, then region-scroll
2246                    // `[0..=scroll_bottom]` (rows below stay fixed).
2247                    //
2248                    // #449: the fixed rows keep their GRID position while
2249                    // scrollback grows, so their content's concatenated absolute
2250                    // index shifts +1 — re-anchor the content-tracking anchors
2251                    // (selection, markers; alacritty's swap-back of the fixed
2252                    // bottom lines is the screen-relative equivalent of this)
2253                    // and invalidate the query-derived highlights
2254                    // (drop-not-re-anchor policy, #108). In-region and
2255                    // scrollback content keeps stable indices — untouched.
2256                    let below = self.scrollback.len() + self.scroll_bottom + 1;
2257                    self.selection_shift_below_margin(below);
2258                    self.markers_shift_below_margin(below);
2259                    self.invalidate_search_highlights();
2260                    let evicted = self.grid.row_owned(0);
2261                    self.grid
2262                        .scroll_up_region(self.scroll_top, self.scroll_bottom);
2263                    evicted
2264                };
2265                self.scrollback.push_back(evicted);
2266                // Follow-bottom = stay: if the user is scrolled up, bump the
2267                // offset so the same lines stay in view instead of being yanked
2268                // to the bottom.
2269                if self.display_offset > 0 {
2270                    self.display_offset = (self.display_offset + 1).min(self.scrollback.len());
2271                }
2272                // Cap: evict the oldest line past the limit. The view is anchored
2273                // to history, so dropping the front shifts the offset down too
2274                // (xterm.js trims ybase and ydisp together) — also keeps the
2275                // offset within `[0, len]`. The evicted row is parked for reuse.
2276                if self.scrollback.len() > self.scrollback_limit {
2277                    self.recycled_row = self.scrollback.pop_front();
2278                    // Every absolute index just shifted down by one; move the
2279                    // selection with it so its anchors keep their content.
2280                    self.selection_evict_oldest();
2281                    // Query-derived highlights can't survive the index shift (see
2282                    // the method doc); selection re-anchors, highlights invalidate.
2283                    self.invalidate_search_highlights();
2284                    // Markers are persistent anchors: shift them down with the
2285                    // index, disposing any whose line was the evicted one (#118).
2286                    self.markers_evict_oldest();
2287                    if self.display_offset > 0 {
2288                        // Scrolled up: evicting the oldest line advanced the
2289                        // viewport, so it must be repainted (the "frozen while
2290                        // scrolled" rule does not apply when the view itself moved).
2291                        self.display_offset -= 1;
2292                        self.mark_fully_damaged();
2293                    }
2294                }
2295            } else {
2296                // Region (top margin > 0) or alt-screen scroll: the evicted line
2297                // does NOT enter scrollback, so content moves *within* the screen
2298                // and absolute indices in the region shift. Rotate the selection
2299                // up so it follows; an endpoint on the dropped line clears it.
2300                let base = self.scrollback.len();
2301                self.selection_rotate_region(
2302                    base + self.scroll_top,
2303                    base + self.scroll_bottom,
2304                    true,
2305                );
2306                // Rotate the active buffer's markers with the content (#187):
2307                // per-buffer storage (#186) scopes them, so an alt scroll rotates
2308                // *alt* marks and leaves the frozen primary list untouched — no
2309                // guard needed. `markers_rotate_region` routes via `markers_mut`.
2310                self.markers_rotate_region(base + self.scroll_top, base + self.scroll_bottom, true);
2311                self.invalidate_search_highlights();
2312                self.grid
2313                    .scroll_up_region(self.scroll_top, self.scroll_bottom);
2314            }
2315            self.record_scroll(self.scroll_top, self.scroll_bottom, 1);
2316        } else if self.cursor.row + 1 < self.grid.rows() {
2317            self.cursor.row += 1;
2318        }
2319    }
2320
2321    /// DECSTBM (CSI r): set the top/bottom scroll margins (1-based inclusive).
2322    /// An invalid region (top ≥ bottom) is ignored.
2323    fn set_scroll_region(&mut self, top: usize, bottom: usize) {
2324        let bottom = bottom.min(self.grid.rows());
2325        if top >= bottom {
2326            return;
2327        }
2328        self.scroll_top = top - 1;
2329        self.scroll_bottom = bottom - 1;
2330        self.goto(0, 0); // DECSTBM homes the cursor (absolute)
2331    }
2332
2333    // ---- alt screen (DEC 1049) -----------------------------------------------
2334
2335    /// Enter the alternate screen: save the cursor, swap in the other grid, and
2336    /// clear it.
2337    /// Save the cursor into the alt-screen slot — `?1048` set, and the first
2338    /// half of `?1049` enter (#72).
2339    fn save_alt_cursor(&mut self) {
2340        self.saved_cursor = self.cursor;
2341    }
2342
2343    /// Restore the cursor from the alt-screen slot — `?1048` reset, and the
2344    /// second half of `?1049` leave. DECTCEM visibility is a standalone mode, not
2345    /// part of the save, so preserve it across the restore (#38/#72).
2346    fn restore_alt_cursor(&mut self) {
2347        let visible = self.cursor.visible;
2348        self.cursor = self.saved_cursor;
2349        self.cursor.visible = visible;
2350    }
2351
2352    /// Switch to the (cleared) alternate buffer without touching the cursor —
2353    /// `?47`/`?1047` set, and the second half of `?1049` enter (#72).
2354    fn switch_to_alt(&mut self) {
2355        if self.on_alt {
2356            return;
2357        }
2358        std::mem::swap(&mut self.grid, &mut self.alt_grid);
2359        self.grid.clear();
2360        self.on_alt = true;
2361        self.display_offset = 0; // the alt screen has no scrollback to view
2362        self.selection = None; // a selection cannot survive a screen swap
2363        self.invalidate_search_highlights(); // matches index the primary buffer
2364        self.mark_fully_damaged();
2365    }
2366
2367    /// Switch back to the primary buffer without touching the cursor —
2368    /// `?47`/`?1047` reset, and the first half of `?1049` leave (#72).
2369    fn switch_to_primary(&mut self) {
2370        if !self.on_alt {
2371            return;
2372        }
2373        // Dispose the alt buffer's markers on leave — xterm `activateNormalBuffer`
2374        // → `clearAllMarkers` (#177 S0). Empty while the alt guards stand, so this
2375        // fires nothing today; it's the seam the alt-marker slices (#187) build on.
2376        for m in self.alt_markers.drain(..) {
2377            self.events.push(TermEvent::MarkerDisposed(m.id));
2378        }
2379        std::mem::swap(&mut self.grid, &mut self.alt_grid);
2380        self.on_alt = false;
2381        self.display_offset = 0; // return to the primary at its bottom
2382        self.selection = None; // a selection cannot survive a screen swap
2383        self.invalidate_search_highlights(); // matches index the swapped-out buffer
2384        self.mark_fully_damaged();
2385    }
2386
2387    fn enter_alt_screen(&mut self) {
2388        if self.on_alt {
2389            return;
2390        }
2391        self.save_alt_cursor();
2392        self.switch_to_alt();
2393    }
2394
2395    /// Leave the alternate screen: swap the primary grid back in and restore the
2396    /// saved cursor.
2397    fn leave_alt_screen(&mut self) {
2398        if !self.on_alt {
2399            return;
2400        }
2401        self.switch_to_primary();
2402        self.restore_alt_cursor();
2403    }
2404
2405    /// RI (ESC M): move up one line. At the top margin, scroll the region down
2406    /// instead.
2407    fn reverse_index(&mut self) {
2408        if self.cursor.row == self.scroll_top {
2409            // RI never enters scrollback; the region scrolls down within the
2410            // screen, so absolute indices in it shift down. Rotate the selection.
2411            let base = self.scrollback.len();
2412            self.selection_rotate_region(base + self.scroll_top, base + self.scroll_bottom, false);
2413            // Rotate the active buffer's markers (#187) — alt-scoped on the alt
2414            // screen, so no guard (see `linefeed`).
2415            self.markers_rotate_region(base + self.scroll_top, base + self.scroll_bottom, false);
2416            self.invalidate_search_highlights();
2417            self.grid
2418                .scroll_down_region(self.scroll_top, self.scroll_bottom);
2419            self.record_scroll(self.scroll_top, self.scroll_bottom, -1);
2420        } else if self.cursor.row > 0 {
2421            self.cursor.row -= 1;
2422        }
2423    }
2424
2425    // ---- cursor save/restore (DECSC / DECRC) ---------------------------------
2426
2427    /// DECSC (ESC 7): save the cursor position, pen, pending-wrap, and origin
2428    /// mode. Visibility is not saved (DECTCEM is separate).
2429    fn save_cursor(&mut self) {
2430        self.decsc = SavedCursor {
2431            row: self.cursor.row,
2432            col: self.cursor.col,
2433            pen: self.cursor.pen,
2434            pending_wrap: self.cursor.pending_wrap,
2435            origin_mode: self.origin_mode,
2436            charsets: self.charsets,
2437            gl: self.gl,
2438        };
2439    }
2440
2441    /// DECRC (ESC 8): restore what DECSC saved. Origin mode is restored (per
2442    /// ADR-0004); visibility is left as-is. The position is clamped to the
2443    /// current screen in case it shrank since the save.
2444    fn restore_cursor(&mut self) {
2445        let s = self.decsc;
2446        self.cursor.row = s.row.min(self.grid.rows() - 1);
2447        self.cursor.col = s.col.min(self.grid.cols() - 1);
2448        self.cursor.pen = s.pen;
2449        self.cursor.pending_wrap = s.pending_wrap;
2450        self.origin_mode = s.origin_mode;
2451        self.charsets = s.charsets;
2452        self.gl = s.gl;
2453    }
2454
2455    /// RIS (ESC c) — full reset to the power-on state (#53). Reconstruct every
2456    /// screen/mode field to its construction default (preserving only the
2457    /// dimensions and the scrollback cap), but keep the consumer-bound output
2458    /// queues (`replies`/`events`) that accrued earlier in this `feed`, and
2459    /// signal a full repaint. The vte parser lives outside `Term`, so replacing
2460    /// `self` does not disturb in-progress parsing. Mirrors xterm.js fullReset.
2461    fn full_reset(&mut self) {
2462        let replies = std::mem::take(&mut self.replies);
2463        let mut events = std::mem::take(&mut self.events);
2464        // RIS wipes the buffer, so every marker's line is gone — announce each
2465        // disposal so the consumer drops its decorations (and isn't confused when
2466        // the reset id counter reissues the same ids). The events survive the
2467        // reset below (#118).
2468        events.extend(
2469            self.normal_markers
2470                .iter()
2471                .chain(&self.alt_markers)
2472                .map(|m| TermEvent::MarkerDisposed(m.id)),
2473        );
2474        let (cols, rows) = (self.grid.cols(), self.grid.rows());
2475        *self = Term::with_scrollback(cols, rows, self.scrollback_limit);
2476        self.replies = replies;
2477        self.events = events;
2478        self.mark_fully_damaged();
2479    }
2480
2481    /// DECSTR (CSI ! p) — soft reset (#53). Resets a defined subset of modes to
2482    /// their defaults *without* destroying screen content or scrollback, moving
2483    /// the active cursor, or touching the mouse/focus reporting subsystem. Per
2484    /// xterm.js softReset, autowrap returns to ON (the xterm default), not off.
2485    fn soft_reset(&mut self) {
2486        self.cursor.visible = true;
2487        self.cursor.pen = Pen::default();
2488        self.scroll_top = 0;
2489        self.scroll_bottom = self.grid.rows() - 1;
2490        self.origin_mode = false;
2491        self.app_cursor_keys = false;
2492        self.bracketed_paste = false;
2493        self.grapheme_clustering = false; // ?2027 back to the wcwidth-compat default (#295)
2494        self.autowrap = true; // xterm default is ON (not the VT100 "off")
2495        self.insert_mode = false;
2496        self.charsets = [Charset::Ascii; 4];
2497        self.gl = 0;
2498        self.decsc = SavedCursor::default();
2499    }
2500
2501    fn carriage_return(&mut self) {
2502        self.cursor.col = 0;
2503        self.cursor.pending_wrap = false;
2504    }
2505
2506    /// DECSCUSR (CSI Ps SP q): set the caret shape + blink (#89). 0/2 = steady
2507    /// block, 1 = blinking block; 3/4 = blinking/steady underline; 5/6 =
2508    /// blinking/steady bar (odd = blink). 0 resets to the default (steady block).
2509    /// An unknown param leaves the style unchanged. Mirrors xterm.js.
2510    fn set_cursor_style(&mut self, param: u16) {
2511        let (shape, blink) = match param {
2512            0 | 2 => (CursorShape::Block, false),
2513            1 => (CursorShape::Block, true),
2514            3 => (CursorShape::Underline, true),
2515            4 => (CursorShape::Underline, false),
2516            5 => (CursorShape::Bar, true),
2517            6 => (CursorShape::Bar, false),
2518            _ => return,
2519        };
2520        self.cursor.shape = shape;
2521        self.cursor.blink = blink;
2522    }
2523
2524    /// Backspace (BS, 0x08): move the cursor one column left. With reverse
2525    /// wraparound (?45) a backspace at column 0 of a *soft-wrapped* row moves
2526    /// back to the last column of the previous row — undoing one autowrap. Only
2527    /// soft wraps reverse (the previous row carries `WRAPLINE`); a hard CR/LF
2528    /// line does not. BS only (not cursor-left), matching xterm.js (#80).
2529    fn backspace(&mut self) {
2530        self.cursor.pending_wrap = false;
2531        if self.cursor.col > 0 {
2532            self.cursor.col -= 1;
2533            return;
2534        }
2535        if self.reverse_wraparound
2536            && self.cursor.row > self.scroll_top
2537            && self.cursor.row <= self.scroll_bottom
2538        {
2539            let prev = self.cursor.row - 1;
2540            let last = self.grid.cols() - 1;
2541            if self.grid.cell(prev, last).is_wrapline() {
2542                self.grid
2543                    .cell_mut(prev, last)
2544                    .remove_flags(CellFlags::WRAPLINE);
2545                self.cursor.row = prev;
2546                self.cursor.col = last;
2547            }
2548        }
2549    }
2550
2551    /// Auto-wrap at end of line: line-feed then return to column 0.
2552    fn wrapline(&mut self) {
2553        self.linefeed();
2554        self.cursor.col = 0;
2555        self.cursor.pending_wrap = false;
2556    }
2557
2558    // ---- tab stops (HT / HTS / TBC) ------------------------------------------
2559
2560    /// HT: advance to the next set tab stop, or the last column if none remain
2561    /// (no wrap).
2562    fn put_tab(&mut self) {
2563        let cols = self.grid.cols();
2564        let mut col = self.cursor.col;
2565        while col + 1 < cols {
2566            col += 1;
2567            if self.tabs[col] {
2568                break;
2569            }
2570        }
2571        self.cursor.col = col;
2572        self.cursor.pending_wrap = false;
2573    }
2574
2575    /// HTS (ESC H): set a tab stop at the cursor column.
2576    fn set_tab_stop(&mut self) {
2577        let col = self.cursor.col;
2578        self.tabs[col] = true;
2579    }
2580
2581    /// TBC (CSI g): clear the tab stop at the cursor (mode 0) or all stops
2582    /// (mode 3).
2583    fn clear_tab_stop(&mut self, mode: u16) {
2584        match mode {
2585            0 => {
2586                let col = self.cursor.col;
2587                self.tabs[col] = false;
2588            }
2589            3 => self.tabs.iter_mut().for_each(|t| *t = false),
2590            _ => {}
2591        }
2592    }
2593
2594    // ---- printing ------------------------------------------------------------
2595
2596    /// Write one glyph at the cursor, handling deferred wrap and the wide-char
2597    /// spacer, then advance the cursor (deferring the wrap if it hits the edge).
2598    fn write_glyph(&mut self, c: char, width: usize) {
2599        let cols = self.grid.cols();
2600
2601        // Resolve a deferred last-column wrap before placing the next glyph.
2602        // The row being left soft-wrapped: mark its last cell so reflow (#7) can
2603        // tell it from a hard CR/LF line-end.
2604        if self.cursor.pending_wrap {
2605            let row = self.cursor.row;
2606            self.grid
2607                .cell_mut(row, cols - 1)
2608                .insert_flags(CellFlags::WRAPLINE);
2609            self.wrapline();
2610        }
2611
2612        // A width-2 glyph that cannot fit in the last column wraps first — unless
2613        // autowrap is off, in which case it is dropped (xterm.js `continue`), not
2614        // squeezed or wrapped.
2615        if width == 2 && self.cursor.col + 1 >= cols {
2616            if !self.autowrap {
2617                return;
2618            }
2619            // Mark the row soft-wrapped, like the pending-wrap path above: the
2620            // vacated last column is a continuation, not a hard line-end. Search,
2621            // logical lines (#113), and reflow (#7) all read WRAPLINE for the join.
2622            // Also tag it a leading spacer so the text extractors skip the blank
2623            // (xterm's LEADING_WIDE_CHAR_SPACER) instead of joining "ab한"→"ab 한".
2624            let vacated = self.grid.cell_mut(self.cursor.row, cols - 1);
2625            vacated.insert_flags(CellFlags::WRAPLINE);
2626            vacated.set_leading_spacer();
2627            self.wrapline();
2628        }
2629
2630        // Insert mode (IRM): open a `width`-wide gap at the cursor first, shifting
2631        // the row's tail right (off-edge cells discarded, wide halves repaired),
2632        // then write into the gap — mirrors xterm.js's insertCells (#64).
2633        if self.insert_mode {
2634            self.insert_chars(width);
2635        }
2636
2637        let (row, col) = (self.cursor.row, self.cursor.col);
2638
2639        // Overwriting one half of an existing wide glyph orphans the other —
2640        // clear it so no stray lead/spacer is left behind.
2641        let last = col + width - 1;
2642        if col > 0 && self.grid.cell(row, col).is_wide_spacer() {
2643            self.grid.cell_mut(row, col - 1).reset();
2644        }
2645        if last + 1 < cols && self.grid.cell(row, last).is_wide() {
2646            self.grid.cell_mut(row, last + 1).reset();
2647        }
2648
2649        let mut cell = self.cursor.pen.cell(c);
2650        if width == 2 {
2651            cell.insert_flags(CellFlags::WIDE_CHAR);
2652        }
2653        *self.grid.cell_mut(row, col) = cell;
2654        // Stamp the open hyperlink, if any, into the row's link map (#26/#46).
2655        if let Some(link) = self.current_link {
2656            self.grid.row_mut(row).set_link(col, link);
2657        }
2658
2659        // The trailing column of a wide glyph carries a distinct spacer marker —
2660        // and the same link, so a hover/selection over either half agrees.
2661        if width == 2 && col + 1 < cols {
2662            let mut spacer = self.cursor.pen.cell(' ');
2663            spacer.insert_flags(CellFlags::WIDE_CHAR_SPACER);
2664            *self.grid.cell_mut(row, col + 1) = spacer;
2665            if let Some(link) = self.current_link {
2666                self.grid.row_mut(row).set_link(col + 1, link);
2667            }
2668        }
2669
2670        // Record damage for the cell(s) just written.
2671        self.damage_span(row, col, col + width - 1);
2672
2673        // Advance. Reaching/passing the last column sets pending-wrap instead of
2674        // wrapping eagerly — the cursor parks on the last column.
2675        let new_col = col + width;
2676        if new_col >= cols {
2677            self.cursor.col = cols - 1;
2678            // With autowrap off (DECAWM ?7l) the cursor pins to the last column
2679            // and the next glyph overwrites in place — no deferred wrap (#63).
2680            self.cursor.pending_wrap = self.autowrap;
2681        } else {
2682            self.cursor.col = new_col;
2683        }
2684    }
2685
2686    /// Attach a combining mark (width-0 code point) to the grapheme it modifies —
2687    /// the cell the cursor just left. With pending-wrap the cursor still sits on
2688    /// the just-written last-column glyph, so attach in place (no back-up, no
2689    /// deferred wrap); otherwise step back one column, and once more over a
2690    /// wide-char spacer to reach its lead. Stored in the grapheme side-table.
2691    fn push_combining(&mut self, c: char) {
2692        let row = self.cursor.row;
2693        let mut col = if self.cursor.pending_wrap {
2694            self.cursor.col
2695        } else {
2696            self.cursor.col.saturating_sub(1)
2697        };
2698        if self.grid.cell(row, col).is_wide_spacer() {
2699            col = col.saturating_sub(1);
2700        }
2701        // Append the mark to the row's combining map at this column (setting the
2702        // cell's combining bit). No global pool — the cluster rides the row.
2703        self.grid.row_mut(row).push_combining(col, c);
2704        self.damage_span(row, col, col);
2705    }
2706
2707    /// Mode 2027 (#295): if `c` **extends** the previous cell's grapheme cluster (UAX #29), append
2708    /// it to that cell's side-table — no new cell, no cursor advance — and return `true`. Otherwise
2709    /// return `false` so `print` takes the normal per-scalar path (a break starts a new cell).
2710    ///
2711    /// The break state is reconstructed fresh from the previous cell's stored cluster (base scalar +
2712    /// side-table marks) rather than persisted across calls, so cursor moves / CR-LF can't corrupt
2713    /// it (mirrors ghostty). Width promotion for a narrow base (a flag's second RI, a text-base +
2714    /// VS16) is handled by the caller in a later step; here the base's existing width holds.
2715    fn try_grapheme_join(&mut self, c: char) -> bool {
2716        let row = self.cursor.row;
2717        // Locate the previous cluster's base cell, exactly as `push_combining`: with pending-wrap
2718        // the cursor still sits on the last glyph; else step back one, and over a wide spacer.
2719        let col = if self.cursor.pending_wrap {
2720            self.cursor.col
2721        } else if self.cursor.col == 0 {
2722            return false; // nothing precedes on this row
2723        } else {
2724            self.cursor.col - 1
2725        };
2726        let col = if self.grid.cell(row, col).is_wide_spacer() {
2727            col.saturating_sub(1)
2728        } else {
2729            col
2730        };
2731        // Reconstruct the previous cluster's text: base scalar + any already-joined scalars.
2732        let mut prev = String::new();
2733        prev.push(self.grid.cell(row, col).c());
2734        if let Some(marks) = self.grid.row_ref(row).combining_at(col) {
2735            prev.extend(marks.iter().copied());
2736        }
2737        if !crate::grapheme::grapheme_extends(&prev, c) {
2738            return false;
2739        }
2740        // Join: ride the side-table (no new cell).
2741        self.grid.row_mut(row).push_combining(col, c);
2742        // Width promotion: a flag's second regional indicator, or a text-base + VS16, grows the
2743        // cluster to width 2. `UnicodeWidthStr` gives the cluster width (RI-pair → 2, VS16 → 2). If
2744        // the base cell is still narrow, widen it in place.
2745        let cluster_w = {
2746            prev.push(c);
2747            UnicodeWidthStr::width(prev.as_str())
2748        };
2749        if cluster_w == 2 && !self.grid.cell(row, col).is_wide() {
2750            self.promote_cluster_to_wide(row, col);
2751        } else if cluster_w == 1 && self.grid.cell(row, col).is_wide() {
2752            // The mirror case: a default-wide emoji + VS15 (text selector) shrinks to width 1.
2753            self.demote_cluster_to_narrow(row, col);
2754        }
2755        self.damage_span(row, col, col);
2756        true
2757    }
2758
2759    /// Shrink a wide cluster cell back to a single-width cell (#295): a default-wide emoji joined by
2760    /// VS15 (U+FE0E, the text selector) requests text presentation → width 1. Remove `WIDE_CHAR`,
2761    /// free the spacer, and back the cursor up over it (the inverse of `promote_cluster_to_wide`).
2762    fn demote_cluster_to_narrow(&mut self, row: usize, col: usize) {
2763        let cols = self.grid.cols();
2764        self.grid
2765            .cell_mut(row, col)
2766            .remove_flags(CellFlags::WIDE_CHAR);
2767        if col + 1 < cols {
2768            self.grid.cell_mut(row, col + 1).reset(); // free the now-unused spacer
2769        }
2770        // The cluster shrank 2→1: the cursor sat just past the wide cell (col+2, or pending-wrap on
2771        // the last column); it now sits just past the single-width cell at col+1.
2772        self.cursor.pending_wrap = false;
2773        self.cursor.col = (col + 1).min(cols - 1);
2774        self.damage_span(row, col, (col + 1).min(cols - 1));
2775    }
2776
2777    /// Widen a narrow base cell to a double-width cluster in place (#295): set `WIDE_CHAR`, write
2778    /// its spacer, and step the cursor over it. Only reached when a joining scalar (flag's 2nd RI,
2779    /// VS16) promotes the cluster to width 2. A base pinned at the last column has no room for a
2780    /// spacer — relocation is a later step; until then it stays narrow (rare, renders single-width).
2781    fn promote_cluster_to_wide(&mut self, row: usize, col: usize) {
2782        let cols = self.grid.cols();
2783        if col + 1 >= cols {
2784            // No spacer room at the last column: relocate the whole cluster to the next line as a
2785            // wide cell (the row soft-wraps), mirroring write_glyph's wide-at-boundary wrap (#303).
2786            self.relocate_cluster_wide(row, col);
2787            return;
2788        }
2789        // Overwriting col+1 with the spacer can orphan the far half of a WIDE glyph standing there
2790        // (the cursor may have been repositioned before the joining scalar arrived). Reset that
2791        // orphan, exactly as write_glyph does (2462-2470), so no dangling spacer survives.
2792        if self.grid.cell(row, col + 1).is_wide() && col + 2 < cols {
2793            self.grid.cell_mut(row, col + 2).reset();
2794        }
2795        self.grid
2796            .cell_mut(row, col)
2797            .insert_flags(CellFlags::WIDE_CHAR);
2798        let mut spacer = self.cursor.pen.cell(' ');
2799        spacer.insert_flags(CellFlags::WIDE_CHAR_SPACER);
2800        *self.grid.cell_mut(row, col + 1) = spacer;
2801        // The cursor sat at col+1 (just past the narrow base); move it over the new spacer, applying
2802        // the same last-column pending-wrap rule as a wide write.
2803        let new_col = col + 2;
2804        if new_col >= cols {
2805            self.cursor.col = cols - 1;
2806            self.cursor.pending_wrap = self.autowrap;
2807        } else {
2808            self.cursor.col = new_col;
2809        }
2810        self.damage_span(row, col, col + 1);
2811    }
2812
2813    /// Relocate a last-column narrow cluster to the next line as a wide cell (#303): its base +
2814    /// side-table marks move to `(next_row, 0..=1)` and the vacated last column becomes a soft-wrap
2815    /// (WRAPLINE + leading spacer), exactly as `write_glyph` wraps a wide glyph that can't fit. With
2816    /// autowrap off, or a 1-column screen (no room for a wide cell anywhere), it stays narrow.
2817    fn relocate_cluster_wide(&mut self, row: usize, col: usize) {
2818        let cols = self.grid.cols();
2819        if cols < 2 || !self.autowrap {
2820            return; // nowhere to place a wide cell — leave it narrow
2821        }
2822        // Capture the base cell (glyph + attrs) and its marks before vacating.
2823        let base = *self.grid.cell(row, col);
2824        let marks: Vec<char> = self
2825            .combining_at(row, col)
2826            .map(<[char]>::to_vec)
2827            .unwrap_or_default();
2828        // Vacate the last column as a soft-wrap leading spacer (mirrors write_glyph 2457-2459).
2829        // reset() clears the base's combining bit, so its stale marks entry is never read again.
2830        let vacated = self.grid.cell_mut(row, col);
2831        vacated.reset();
2832        vacated.insert_flags(CellFlags::WRAPLINE);
2833        vacated.set_leading_spacer();
2834        self.damage_span(row, col, col);
2835        // Advance to the next line (scrolls if at the bottom); cursor lands at col 0.
2836        self.wrapline();
2837        let nr = self.cursor.row;
2838        // Re-place the base as a wide lead + spacer, re-attaching the marks fresh (drop the combining
2839        // bit so push_combining starts a clean cluster at the new column).
2840        let mut lead = base;
2841        lead.set_combined(false);
2842        lead.insert_flags(CellFlags::WIDE_CHAR);
2843        *self.grid.cell_mut(nr, 0) = lead;
2844        for m in marks {
2845            self.grid.row_mut(nr).push_combining(0, m);
2846        }
2847        let mut spacer = self.cursor.pen.cell(' ');
2848        spacer.insert_flags(CellFlags::WIDE_CHAR_SPACER);
2849        *self.grid.cell_mut(nr, 1) = spacer;
2850        // Cursor just past the wide cell (pending-wrap if it fills a 2-column row).
2851        if cols <= 2 {
2852            self.cursor.col = cols - 1;
2853            self.cursor.pending_wrap = self.autowrap;
2854        } else {
2855            self.cursor.col = 2;
2856            self.cursor.pending_wrap = false;
2857        }
2858        self.damage_span(nr, 0, 1);
2859    }
2860
2861    // ---- cursor movement (CSI A/B/C/D/G/d/H/f) -------------------------------
2862
2863    fn move_up(&mut self, n: usize) {
2864        self.cursor.row = self.cursor.row.saturating_sub(n);
2865        self.cursor.pending_wrap = false;
2866    }
2867
2868    fn move_down(&mut self, n: usize) {
2869        self.cursor.row = (self.cursor.row + n).min(self.grid.rows() - 1);
2870        self.cursor.pending_wrap = false;
2871    }
2872
2873    fn move_forward(&mut self, n: usize) {
2874        self.cursor.col = (self.cursor.col + n).min(self.grid.cols() - 1);
2875        self.cursor.pending_wrap = false;
2876    }
2877
2878    fn move_back(&mut self, n: usize) {
2879        self.cursor.col = self.cursor.col.saturating_sub(n);
2880        self.cursor.pending_wrap = false;
2881    }
2882
2883    fn set_col(&mut self, col: usize) {
2884        self.cursor.col = col.min(self.grid.cols() - 1);
2885        self.cursor.pending_wrap = false;
2886    }
2887
2888    fn set_row(&mut self, row: usize) {
2889        self.cursor.row = row.min(self.grid.rows() - 1);
2890        self.cursor.pending_wrap = false;
2891    }
2892
2893    fn goto(&mut self, row: usize, col: usize) {
2894        // Origin mode addresses rows relative to the scroll region's top margin
2895        // and clamps to its bottom; otherwise rows are absolute to the screen.
2896        let (offset, max_row) = if self.origin_mode {
2897            (self.scroll_top, self.scroll_bottom)
2898        } else {
2899            (0, self.grid.rows() - 1)
2900        };
2901        self.cursor.row = (row + offset).min(max_row);
2902        self.cursor.col = col.min(self.grid.cols() - 1);
2903        self.cursor.pending_wrap = false;
2904    }
2905
2906    // ---- erase (CSI J / K) ---------------------------------------------------
2907
2908    /// Clear cells `from..to` on `row`.
2909    ///
2910    /// Background Color Erase (BCE): erased cells carry the current SGR
2911    /// background only — fg and text attributes reset to default (matches
2912    /// xterm/alacritty, where the fill is `cursor.template.bg.into()`).
2913    fn clear_cells(&mut self, row: usize, from: usize, to: usize) {
2914        let cols = self.grid.cols();
2915        // Don't orphan a wide char straddling the erase boundary.
2916        if from > 0 && self.grid.cell(row, from).is_wide_spacer() {
2917            self.grid.cell_mut(row, from - 1).reset();
2918        }
2919        if to > from && to < cols && self.grid.cell(row, to - 1).is_wide() {
2920            self.grid.cell_mut(row, to).reset();
2921        }
2922
2923        let bg = self.cursor.pen.bg;
2924        for col in from..to {
2925            let cell = self.grid.cell_mut(row, col);
2926            cell.reset();
2927            cell.set_bg(bg);
2928        }
2929        if to > from {
2930            self.damage_span(row, from, to - 1);
2931        }
2932    }
2933
2934    /// Erase in display (ED): 0 = cursor→end, 1 = start→cursor, 2 = all.
2935    fn erase_display(&mut self, mode: u16) {
2936        let (cols, rows) = (self.grid.cols(), self.grid.rows());
2937        let (cr, cc) = (self.cursor.row, self.cursor.col);
2938        match mode {
2939            0 => {
2940                self.clear_cells(cr, cc, cols);
2941                for row in (cr + 1)..rows {
2942                    self.clear_cells(row, 0, cols);
2943                }
2944            }
2945            1 => {
2946                for row in 0..cr {
2947                    self.clear_cells(row, 0, cols);
2948                }
2949                self.clear_cells(cr, 0, cc + 1);
2950            }
2951            2 => {
2952                for row in 0..rows {
2953                    self.clear_cells(row, 0, cols);
2954                }
2955            }
2956            _ => {}
2957        }
2958    }
2959
2960    /// Erase in line (EL): 0 = cursor→end, 1 = start→cursor, 2 = whole line.
2961    fn erase_line(&mut self, mode: u16) {
2962        let cols = self.grid.cols();
2963        let (cr, cc) = (self.cursor.row, self.cursor.col);
2964        match mode {
2965            0 => self.clear_cells(cr, cc, cols),
2966            1 => self.clear_cells(cr, 0, cc + 1),
2967            2 => self.clear_cells(cr, 0, cols),
2968            _ => {}
2969        }
2970    }
2971
2972    // ---- intra-line editing (ICH / DCH / ECH) --------------------------------
2973
2974    /// ECH (CSI Pn X): erase `n` cells in place from the cursor — no shift.
2975    /// BCE-filled (via `clear_cells`); pending-wrap is left untouched.
2976    fn erase_chars(&mut self, n: usize) {
2977        let cols = self.grid.cols();
2978        let (row, col) = (self.cursor.row, self.cursor.col);
2979        let to = (col + n).min(cols);
2980        self.clear_cells(row, col, to);
2981    }
2982
2983    /// ICH (CSI Pn @): insert `n` blanks at the cursor, shifting the rest of the
2984    /// line right; cells pushed past the right edge are lost. The opened gap is
2985    /// BCE-filled; pending-wrap is left untouched.
2986    fn insert_chars(&mut self, n: usize) {
2987        let cols = self.grid.cols();
2988        let (r, col) = (self.cursor.row, self.cursor.col);
2989        let n = n.min(cols - col);
2990        if n == 0 {
2991            return;
2992        }
2993        let bg = self.cursor.pen.bg;
2994        let row = self.grid.row_mut(r);
2995        // Shift [col .. cols-n) right by n; the tail falls off the edge. The
2996        // combining map follows the moved cells (the bit travels with the raw
2997        // copy, the cluster data must too).
2998        row.copy_within(col..cols - n, col + n);
2999        row.move_maps(col..cols - n, col + n);
3000        for cell in &mut row[col..col + n] {
3001            cell.reset();
3002            cell.set_bg(bg);
3003        }
3004        // Repair wide-char halves split at the seams (no-orphan invariant):
3005        // a lead just before the gap lost its spacer; the first shifted cell may
3006        // be a spacer whose lead did not move.
3007        if col > 0 && self.grid.cell(r, col - 1).is_wide() {
3008            self.grid.cell_mut(r, col - 1).reset();
3009        }
3010        if col + n < cols && self.grid.cell(r, col + n).is_wide_spacer() {
3011            self.grid.cell_mut(r, col + n).reset();
3012        }
3013        // A lead shifted to the last column lost its spacer off the edge.
3014        if self.grid.cell(r, cols - 1).is_wide() {
3015            self.grid.cell_mut(r, cols - 1).reset();
3016        }
3017        self.damage_span(r, col, cols - 1);
3018    }
3019
3020    /// DCH (CSI Pn P): delete `n` cells at the cursor, shifting the tail left; the
3021    /// vacated cells at the right are BCE-blanked. Pending-wrap is left untouched.
3022    fn delete_chars(&mut self, n: usize) {
3023        let cols = self.grid.cols();
3024        let (r, col) = (self.cursor.row, self.cursor.col);
3025        let n = n.min(cols - col);
3026        if n == 0 {
3027            return;
3028        }
3029        let bg = self.cursor.pen.bg;
3030        let row = self.grid.row_mut(r);
3031        // Shift [col+n .. cols) left to [col ..); BCE-fill the vacated tail. The
3032        // combining map follows the moved cells.
3033        row.copy_within(col + n..cols, col);
3034        row.move_maps(col + n..cols, col);
3035        for cell in &mut row[cols - n..cols] {
3036            cell.reset();
3037            cell.set_bg(bg);
3038        }
3039        // Repair wide-char halves split by the deletion (no-orphan invariant):
3040        // a lead just before the cut lost its spacer; the cell now at the cursor
3041        // may be a spacer whose lead was deleted.
3042        if col > 0 && self.grid.cell(r, col - 1).is_wide() {
3043            self.grid.cell_mut(r, col - 1).reset();
3044        }
3045        if self.grid.cell(r, col).is_wide_spacer() {
3046            self.grid.cell_mut(r, col).reset();
3047        }
3048        self.damage_span(r, col, cols - 1);
3049    }
3050
3051    // ---- line/region editing (IL / DL / SU / SD) -----------------------------
3052
3053    /// Scroll rows `[top..=bottom]` by `n` lines, BCE-filling the exposed lines.
3054    /// `down` inserts blanks at the top (content moves down); otherwise content
3055    /// moves up and blanks appear at the bottom. Reuses the one-line region scroll
3056    /// primitives (so damage + scroll-op accumulation come for free), then fills
3057    /// the exposed lines with the current SGR background.
3058    fn scroll_region_lines(&mut self, top: usize, bottom: usize, n: usize, down: bool) {
3059        let height = bottom - top + 1;
3060        let n = n.min(height);
3061        if n == 0 {
3062            return;
3063        }
3064        // Anchors (selection #3, markers #118/#158) live at absolute buffer lines;
3065        // SU/SD/IL/DL don't accrue scrollback, so `base` is stable across the loop.
3066        let base = self.scrollback.len();
3067        for _ in 0..n {
3068            if down {
3069                self.grid.scroll_down_region(top, bottom);
3070                self.record_scroll(top, bottom, -1);
3071            } else {
3072                self.grid.scroll_up_region(top, bottom);
3073                self.record_scroll(top, bottom, 1);
3074            }
3075            // Rotate anchors with the content, like `linefeed`/`reverse_index`
3076            // (#162). `up` = content moved up = the non-`down` case. Markers rotate
3077            // with the active buffer (#187) — alt-scoped on the alt screen, so no
3078            // guard; the selection is cleared on alt enter.
3079            self.selection_rotate_region(base + top, base + bottom, !down);
3080            self.markers_rotate_region(base + top, base + bottom, !down);
3081        }
3082        self.invalidate_search_highlights();
3083        // BCE-fill the n exposed lines (the primitives blank to default).
3084        let bg = self.cursor.pen.bg;
3085        let (fill_top, fill_end) = if down {
3086            (top, top + n)
3087        } else {
3088            (bottom + 1 - n, bottom + 1)
3089        };
3090        let cols = self.grid.cols();
3091        for r in fill_top..fill_end {
3092            for c in 0..cols {
3093                let cell = self.grid.cell_mut(r, c);
3094                cell.reset();
3095                cell.set_bg(bg);
3096            }
3097        }
3098    }
3099
3100    /// SU (CSI Pn S): scroll the scroll region up by `n`.
3101    fn scroll_up_lines(&mut self, n: usize) {
3102        self.scroll_region_lines(self.scroll_top, self.scroll_bottom, n, false);
3103    }
3104
3105    /// SD (CSI Pn T): scroll the scroll region down by `n`.
3106    fn scroll_down_lines(&mut self, n: usize) {
3107        self.scroll_region_lines(self.scroll_top, self.scroll_bottom, n, true);
3108    }
3109
3110    /// IL (CSI Pn L): insert `n` blank lines at the cursor, scrolling
3111    /// `[cursor..=scroll_bottom]` down. A no-op when the cursor is outside the
3112    /// scroll region.
3113    fn insert_lines(&mut self, n: usize) {
3114        let cur = self.cursor.row;
3115        if cur < self.scroll_top || cur > self.scroll_bottom {
3116            return;
3117        }
3118        self.scroll_region_lines(cur, self.scroll_bottom, n, true);
3119    }
3120
3121    /// DL (CSI Pn M): delete `n` lines at the cursor, scrolling
3122    /// `[cursor..=scroll_bottom]` up. A no-op when the cursor is outside the
3123    /// scroll region.
3124    fn delete_lines(&mut self, n: usize) {
3125        let cur = self.cursor.row;
3126        if cur < self.scroll_top || cur > self.scroll_bottom {
3127            return;
3128        }
3129        self.scroll_region_lines(cur, self.scroll_bottom, n, false);
3130    }
3131
3132    // ---- SGR (CSI m) ---------------------------------------------------------
3133
3134    fn sgr(&mut self, params: &Params) {
3135        let pen = &mut self.cursor.pen;
3136        let mut iter = params.iter();
3137        while let Some(param) = iter.next() {
3138            let code = param.first().copied().unwrap_or(0);
3139            match code {
3140                0 => pen.reset(),
3141                1 => pen.flags.insert(CellFlags::BOLD),
3142                2 => pen.flags.insert(CellFlags::DIM),
3143                3 => pen.flags.insert(CellFlags::ITALIC),
3144                4 => pen.flags.insert(CellFlags::UNDERLINE),
3145                5 => pen.flags.insert(CellFlags::BLINK),
3146                7 => pen.flags.insert(CellFlags::INVERSE),
3147                8 => pen.flags.insert(CellFlags::HIDDEN),
3148                9 => pen.flags.insert(CellFlags::STRIKETHROUGH),
3149                22 => pen.flags.remove(CellFlags::BOLD | CellFlags::DIM),
3150                23 => pen.flags.remove(CellFlags::ITALIC),
3151                24 => pen.flags.remove(CellFlags::UNDERLINE),
3152                25 => pen.flags.remove(CellFlags::BLINK),
3153                27 => pen.flags.remove(CellFlags::INVERSE),
3154                28 => pen.flags.remove(CellFlags::HIDDEN),
3155                29 => pen.flags.remove(CellFlags::STRIKETHROUGH),
3156                30..=37 => pen.fg = Color::Indexed((code - 30) as u8),
3157                38 => {
3158                    if let Some(c) = parse_extended_color(param, &mut iter) {
3159                        pen.fg = c;
3160                    }
3161                }
3162                39 => pen.fg = Color::Default,
3163                40..=47 => pen.bg = Color::Indexed((code - 40) as u8),
3164                48 => {
3165                    if let Some(c) = parse_extended_color(param, &mut iter) {
3166                        pen.bg = c;
3167                    }
3168                }
3169                49 => pen.bg = Color::Default,
3170                // bright foreground/background (aixterm) → palette 8..=15.
3171                90..=97 => pen.fg = Color::Indexed((code - 90 + 8) as u8),
3172                100..=107 => pen.bg = Color::Indexed((code - 100 + 8) as u8),
3173                _ => {}
3174            }
3175        }
3176    }
3177}
3178
3179/// Parse `38`/`48` extended colour, in either form:
3180/// - sub-parameter (colon) form inline in `param`: `38:5:n`, `38:2:r:g:b`
3181///   (optionally `38:2:cs:r:g:b` with a colorspace id), or
3182/// - legacy (semicolon) form: pull the following top-level params from `iter`.
3183fn parse_extended_color<'a, I>(param: &[u16], iter: &mut I) -> Option<Color>
3184where
3185    I: Iterator<Item = &'a [u16]>,
3186{
3187    if param.len() > 1 {
3188        // Colon sub-parameter form: kind is param[1].
3189        match param[1] {
3190            2 => {
3191                // 38:2:r:g:b (len 5) or 38:2:cs:r:g:b (len 6, colorspace skipped).
3192                let off = if param.len() >= 6 { 3 } else { 2 };
3193                let r = *param.get(off)? as u8;
3194                let g = *param.get(off + 1)? as u8;
3195                let b = *param.get(off + 2)? as u8;
3196                Some(Color::Rgb(r, g, b))
3197            }
3198            5 => Some(Color::Indexed(*param.get(2)? as u8)),
3199            _ => None,
3200        }
3201    } else {
3202        // Legacy semicolon form: kind, then its operands, are separate params.
3203        match iter.next()?.first().copied()? {
3204            2 => {
3205                let r = iter.next()?.first().copied()? as u8;
3206                let g = iter.next()?.first().copied()? as u8;
3207                let b = iter.next()?.first().copied()? as u8;
3208                Some(Color::Rgb(r, g, b))
3209            }
3210            5 => Some(Color::Indexed(iter.next()?.first().copied()? as u8)),
3211            _ => None,
3212        }
3213    }
3214}
3215
3216/// Reflow one screen (joined with its `scrollback`) to `cols` x `rows`, tracking
3217/// `point` (a cursor in screen coordinates). Returns the new screen rows, the new
3218/// scrollback (capped to `limit`), and the new point. The alt screen passes an
3219/// empty scrollback and discards the returned one.
3220/// The fixed dimensions a resize reflows toward.
3221#[derive(Clone, Copy)]
3222struct ReflowDims {
3223    old_cols: usize,
3224    cols: usize,
3225    rows: usize,
3226    limit: usize,
3227}
3228
3229/// The result of reflowing one pane.
3230struct PaneReflow {
3231    screen: Vec<Row>,
3232    scrollback: VecDeque<Row>,
3233    /// The cursor's new screen-relative position.
3234    cursor: (usize, usize),
3235    /// Each tracked extra point's new **absolute** position, index-aligned with
3236    /// the `extra_abs` argument.
3237    extras: Vec<(usize, usize)>,
3238}
3239
3240/// Reflow one pane (its `scrollback` joined with `screen`) to `dims`, tracking
3241/// the screen-relative cursor `point` plus any `extra_abs` points given in
3242/// **absolute** `[scrollback ++ screen]` coordinates (selection anchors).
3243fn reflow_pane(
3244    screen: Vec<Row>,
3245    scrollback: VecDeque<Row>,
3246    point: (usize, usize),
3247    extra_abs: &[(usize, usize)],
3248    dims: ReflowDims,
3249) -> PaneReflow {
3250    let scroll_len = scrollback.len();
3251    let mut all: Vec<Row> = scrollback.into();
3252    all.extend(screen);
3253
3254    // The cursor is screen-relative; lift it to absolute, then track it together
3255    // with the already-absolute extras.
3256    let mut pts: Vec<(usize, usize)> = Vec::with_capacity(1 + extra_abs.len());
3257    pts.push((scroll_len + point.0, point.1));
3258    pts.extend_from_slice(extra_abs);
3259
3260    let pts = if dims.cols != dims.old_cols {
3261        let (reflowed, np) = crate::grid::reflow(all, dims.cols, &pts);
3262        all = reflowed;
3263        np
3264    } else {
3265        pts
3266    };
3267
3268    let split = all.len().saturating_sub(dims.rows);
3269    let history: Vec<Row> = all.drain(0..split).collect();
3270    let mut sb: VecDeque<Row> = history.into();
3271    let mut dropped = 0usize;
3272    while sb.len() > dims.limit {
3273        sb.pop_front();
3274        dropped += 1;
3275    }
3276
3277    // The cursor returns to screen-relative (its absolute index minus the
3278    // history split). The extras stay absolute, shifted down by any lines the
3279    // cap dropped from the front of history.
3280    PaneReflow {
3281        cursor: (pts[0].0.saturating_sub(split), pts[0].1),
3282        extras: pts[1..]
3283            .iter()
3284            .map(|&(l, c)| (l.saturating_sub(dropped), c))
3285            .collect(),
3286        screen: all,
3287        scrollback: sb,
3288    }
3289}
3290
3291/// Whether `c` ends a word for Word (semantic) selection. Whitespace plus a
3292/// punctuation set mirroring Alacritty's default `semantic_escape_chars`, so
3293/// path/URL-ish runs (`.`, `/`, `-`) stay one word.
3294fn is_word_boundary(c: char) -> bool {
3295    c.is_whitespace() || ",│`|:\"'()[]{}<>".contains(c)
3296}
3297
3298/// Whether the run `hay[i..i+len]` is bounded by non-word characters on both sides — the `\bword\b`
3299/// sense for whole-word search (#314). A word char is alphanumeric or `_` (the regex `\w` set),
3300/// deliberately distinct from `is_word_boundary`'s wider semantic-selection set.
3301fn word_bounded(hay: &[char], i: usize, len: usize) -> bool {
3302    // A word char is alphanumeric, `_`, OR a grapheme-extending mark (width 0: combining marks,
3303    // ZWJ, variation selectors) — so a mark attached to a base is never read as a word boundary,
3304    // matching the regex `\b` sense (`\w` includes `\p{M}`) and staying consistent across the
3305    // literal and regex paths on decomposed graphemes (#314 Lens 1).
3306    let is_word = |c: char| c.is_alphanumeric() || c == '_' || c.width() == Some(0);
3307    let left = i == 0 || !is_word(hay[i - 1]);
3308    let right = i + len == hay.len() || !is_word(hay[i + len]);
3309    left && right
3310}
3311
3312/// Default tab stops: one every 8 columns (incl. column 0), matching xterm.
3313fn default_tabs(cols: usize) -> Vec<bool> {
3314    (0..cols).map(|i| i % 8 == 0).collect()
3315}
3316
3317/// First sub-parameter of CSI param `idx`, or `default` when absent or zero
3318/// (a zero/omitted numeric param means "1" for cursor movement and "0" for
3319/// erase — callers pass the right default).
3320fn param_or(params: &Params, idx: usize, default: u16) -> u16 {
3321    match params.iter().nth(idx).and_then(|p| p.first().copied()) {
3322        Some(v) if v != 0 => v,
3323        _ => default,
3324    }
3325}
3326
3327impl Term {
3328    /// Apply one DEC private mode set (`'h'`) or reset (`'l'`). DECSET/DECRST
3329    /// carry a list of modes, so `csi_dispatch` folds this over every parameter
3330    /// (#56); each mode is an independent toggle, not a stack.
3331    fn set_dec_private_mode(&mut self, action: char, mode: u16) {
3332        match (action, mode) {
3333            ('h', 1049) => self.enter_alt_screen(),
3334            ('l', 1049) => self.leave_alt_screen(),
3335            // Legacy alt-screen variants (#72): ?47/?1047 switch the buffer
3336            // without saving the cursor; ?1048 saves/restores the cursor without
3337            // switching. ?1049 is the two combined.
3338            ('h', 47) | ('h', 1047) => self.switch_to_alt(),
3339            ('l', 47) | ('l', 1047) => self.switch_to_primary(),
3340            ('h', 1048) => self.save_alt_cursor(),
3341            ('l', 1048) => self.restore_alt_cursor(),
3342            ('h', 6) => {
3343                // DECOM: set homes the cursor to the region top.
3344                self.origin_mode = true;
3345                self.goto(0, 0);
3346            }
3347            ('l', 6) => self.origin_mode = false, // unset leaves the cursor put
3348            ('h', 7) => self.autowrap = true,     // DECAWM
3349            ('l', 7) => self.autowrap = false,
3350            ('h', 45) => self.reverse_wraparound = true, // reverse wraparound (#80)
3351            ('l', 45) => self.reverse_wraparound = false,
3352            // DECCOLM (#82): the engine is dimension-free, so emit a request the
3353            // consumer may honor by resizing — no screen/cursor/margin change here.
3354            ('h', 3) => self.events.push(TermEvent::ColumnMode { cols: 132 }),
3355            ('l', 3) => self.events.push(TermEvent::ColumnMode { cols: 80 }),
3356            ('h', 25) => self.cursor.visible = true, // DECTCEM show
3357            ('l', 25) => self.cursor.visible = false, // DECTCEM hide
3358            ('h', 12) => self.cursor.blink = true,   // att610 cursor blink (#81)
3359            ('l', 12) => self.cursor.blink = false,
3360            ('h', 2004) => self.bracketed_paste = true,
3361            ('l', 2004) => self.bracketed_paste = false,
3362            ('h', 2026) => self.synchronized_output = true, // synchronized output (#73)
3363            ('l', 2026) => self.synchronized_output = false,
3364            ('h', 2027) => self.grapheme_clustering = true, // grapheme-cluster mode (#295)
3365            ('l', 2027) => self.grapheme_clustering = false,
3366            ('h', 2031) => self.color_scheme_updates = true, // color-scheme notifications (#85)
3367            ('l', 2031) => self.color_scheme_updates = false,
3368            ('h', 9001) => self.win32_input_mode = true, // win32-input-mode (#86)
3369            ('l', 9001) => self.win32_input_mode = false,
3370
3371            // Input-encoding modes (#11): DECCKM, mouse tracking + encoding,
3372            // focus reporting. Each set assigns the level; each reset clears
3373            // it (apps enable/disable the same mode, not a stack).
3374            ('h', 1) => self.app_cursor_keys = true, // DECCKM
3375            ('l', 1) => self.app_cursor_keys = false,
3376            ('h', 66) => self.application_keypad = true, // DECNKM (#74)
3377            ('l', 66) => self.application_keypad = false,
3378            // DECANM (#84): set = ANSI (the normal state); reset enters VT52. Only
3379            // the reset is meaningful — `?2h` is a no-op (already ANSI).
3380            ('l', 2) => self.vt52_mode = true,
3381            ('h', 9) => self.mouse_protocol = MouseProtocol::X10, // X10 mouse (#70)
3382            ('h', 1000) => self.mouse_protocol = MouseProtocol::Normal,
3383            ('h', 1002) => self.mouse_protocol = MouseProtocol::ButtonEvent,
3384            ('h', 1003) => self.mouse_protocol = MouseProtocol::AnyEvent,
3385            ('l', 9) | ('l', 1000) | ('l', 1002) | ('l', 1003) => {
3386                self.mouse_protocol = MouseProtocol::Off
3387            }
3388            ('h', 1006) => self.mouse_encoding = MouseEncoding::Sgr,
3389            ('l', 1006) => self.mouse_encoding = MouseEncoding::Default,
3390            ('h', 1015) => self.mouse_encoding = MouseEncoding::Urxvt,
3391            ('l', 1015) => self.mouse_encoding = MouseEncoding::Default,
3392            ('h', 1005) => self.mouse_encoding = MouseEncoding::Utf8,
3393            ('l', 1005) => self.mouse_encoding = MouseEncoding::Default,
3394            ('h', 1016) => self.mouse_encoding = MouseEncoding::SgrPixels,
3395            ('l', 1016) => self.mouse_encoding = MouseEncoding::Default,
3396            ('h', 1004) => self.focus_events = true,
3397            ('l', 1004) => self.focus_events = false,
3398
3399            _ => {} // other DEC modes are later slices
3400        }
3401    }
3402
3403    /// Dispatch one VT52 escape sequence (`ESC <final>`), reached only while
3404    /// `vt52_mode` is set (#84). VT52 is a pre-ANSI dialect: the cursor/erase
3405    /// finals map to the same `Term` primitives the ANSI path uses. `ESC <`
3406    /// returns to ANSI. Unknown finals are ignored.
3407    fn vt52_dispatch(&mut self, byte: u8) {
3408        match byte {
3409            b'A' => self.move_up(1),         // cursor up
3410            b'B' => self.move_down(1),       // cursor down
3411            b'C' => self.move_forward(1),    // cursor right
3412            b'D' => self.move_back(1),       // cursor left
3413            b'H' => self.goto(0, 0),         // cursor home
3414            b'I' => self.reverse_index(),    // reverse line feed
3415            b'J' => self.erase_display(0),   // erase cursor → end of screen
3416            b'K' => self.erase_line(0),      // erase cursor → end of line
3417            b'Y' => self.vt52_y_pending = 2, // direct address: two coord bytes follow
3418            // Identify (DECID): reply `ESC / Z` — "I am a VT52".
3419            b'Z' => self.replies.extend_from_slice(b"\x1b/Z"),
3420            b'=' => self.application_keypad = true, // enter alternate keypad
3421            b'>' => self.application_keypad = false, // exit alternate keypad
3422            b'<' => self.vt52_mode = false,         // exit VT52, return to ANSI
3423            // RIS (`ESC c`) is honored even here: it is a hard "recover from any
3424            // state" reset, and `full_reset` rebuilds `Term` with `vt52_mode`
3425            // cleared, so RIS always escapes VT52 back to ANSI. VT52 defines no
3426            // other meaning for `ESC c`.
3427            b'c' => self.full_reset(),
3428            // Graphics mode (`ESC F`/`ESC G`) is a documented non-goal: the VT52
3429            // graphics glyph set differs from DEC Special Graphics, so reusing that
3430            // charset would render the wrong glyphs. No-op rather than approximate.
3431            b'F' | b'G' => {}
3432            _ => {} // unknown VT52 finals are ignored
3433        }
3434    }
3435
3436    /// Consume one `ESC Y` coordinate byte (#84). The first byte is the row, the
3437    /// second the column; each decodes as `value - 0x20`. On the second byte the
3438    /// cursor is addressed (`goto` clamps out-of-range coordinates). Reached only
3439    /// from `print` while `vt52_y_pending > 0`.
3440    fn vt52_take_coord(&mut self, c: char) {
3441        let coord = (c as usize).saturating_sub(0x20);
3442        if self.vt52_y_pending == 2 {
3443            self.vt52_y_row = coord;
3444            self.vt52_y_pending = 1;
3445        } else {
3446            self.vt52_y_pending = 0;
3447            self.goto(self.vt52_y_row, coord);
3448        }
3449    }
3450}
3451
3452impl Perform for Term {
3453    fn print(&mut self, c: char) {
3454        // VT52 `ESC Y` direct addressing (#84): vte delivers the two coordinate
3455        // bytes here (it returned to ground after the `Y` final), so intercept
3456        // them before they would be written as glyphs.
3457        if self.vt52_y_pending > 0 {
3458            self.vt52_take_coord(c);
3459            return;
3460        }
3461        // Translate through the active (GL) character set first (#62): under DEC
3462        // Special Graphics a printable byte becomes a line-drawing glyph.
3463        let c = self.charsets[self.gl].map(c);
3464        // Grapheme-cluster mode (DEC ?2027, #295): if `c` extends the previous cell's cluster,
3465        // join it there instead of placing a new cell. OFF → the per-char (wcwidth) path below.
3466        if self.grapheme_clustering && self.try_grapheme_join(c) {
3467            return;
3468        }
3469        match c.width() {
3470            // Zero-width (combining marks): the grapheme-cluster side-table is a
3471            // later slice; drop for now rather than mis-place it as its own cell.
3472            // A zero-width code point is a combining mark — attach it to the
3473            // previous base glyph rather than dropping it.
3474            Some(0) => self.push_combining(c),
3475            None => {}
3476            Some(width) => self.write_glyph(c, width),
3477        }
3478    }
3479
3480    fn execute(&mut self, byte: u8) {
3481        match byte {
3482            // LF, VT, FF all line-feed.
3483            b'\n' | 0x0b | 0x0c => self.linefeed(),
3484            b'\r' => self.carriage_return(),
3485            0x08 => self.backspace(),
3486            b'\t' => self.put_tab(),
3487            0x07 => self.events.push(TermEvent::Bell), // BEL (#12)
3488            0x0e => self.gl = 1,                       // SO (LS1): GL = G1 (#62)
3489            0x0f => self.gl = 0,                       // SI (LS0): GL = G0
3490            _ => {}
3491        }
3492    }
3493
3494    fn csi_dispatch(&mut self, params: &Params, intermediates: &[u8], _ignore: bool, action: char) {
3495        // Kitty keyboard-protocol negotiation: CSI > / = / < / ? ... u. The
3496        // leading intermediate distinguishes it from plain `CSI u` (SCORC) (#23).
3497        if action == 'u'
3498            && let Some(&lead) = intermediates.first()
3499            && matches!(lead, b'>' | b'<' | b'=' | b'?')
3500        {
3501            self.kitty_dispatch(lead, params);
3502            return;
3503        }
3504        // DEC private modes arrive with a '?' intermediate.
3505        if intermediates.first() == Some(&b'?') {
3506            // DECRQM (CSI ? Ps $ p) — report whether mode Ps is set. The '$'
3507            // intermediate distinguishes it from a plain `?...p`. It queries a
3508            // single mode, so it keys off the first parameter only.
3509            if action == 'p' && intermediates.contains(&b'$') {
3510                self.decrqm(param_or(params, 0, 0));
3511                return;
3512            }
3513            // Private DSR (CSI ? Ps n): ?996 = color-scheme query (#85). The
3514            // theme-agnostic engine relays it as an event for the consumer.
3515            if action == 'n' {
3516                if param_or(params, 0, 0) == 996 {
3517                    self.events.push(TermEvent::ColorSchemeQuery);
3518                }
3519                return;
3520            }
3521            // DECSET/DECRST carry a *list* of modes; apply set/reset to EVERY
3522            // parameter, not just the first — htop batches `?1006;1000h` into one
3523            // CSI, so folding only params[0] dropped the 1000 (#56).
3524            for mode in params.iter().filter_map(|p| p.first().copied()) {
3525                self.set_dec_private_mode(action, mode);
3526            }
3527            return;
3528        }
3529        // DECSTR soft reset: CSI ! p (#53).
3530        if intermediates.first() == Some(&b'!') && action == 'p' {
3531            self.soft_reset();
3532            return;
3533        }
3534        // DECSCUSR set cursor style: CSI Ps SP q (space intermediate) (#89). An
3535        // absent param means 1 (block blink); an explicit 0 means reset — so the
3536        // raw value matters and `param_or` (which folds 0 to its default) is wrong.
3537        if intermediates.first() == Some(&b' ') && action == 'q' {
3538            let param = params.iter().next().and_then(|p| p.first().copied());
3539            self.set_cursor_style(param.unwrap_or(1));
3540            return;
3541        }
3542        // Other private/intermediate sequences are later slices; ignore them
3543        // rather than misinterpret.
3544        if !intermediates.is_empty() {
3545            return;
3546        }
3547        match action {
3548            'A' => self.move_up(param_or(params, 0, 1) as usize),
3549            'B' | 'e' => self.move_down(param_or(params, 0, 1) as usize),
3550            'C' | 'a' => self.move_forward(param_or(params, 0, 1) as usize),
3551            'D' => self.move_back(param_or(params, 0, 1) as usize),
3552            'G' | '`' => self.set_col(param_or(params, 0, 1) as usize - 1),
3553            'd' => self.set_row(param_or(params, 0, 1) as usize - 1),
3554            'H' | 'f' => {
3555                let row = param_or(params, 0, 1) as usize - 1;
3556                let col = param_or(params, 1, 1) as usize - 1;
3557                self.goto(row, col);
3558            }
3559            'J' => self.erase_display(param_or(params, 0, 0)),
3560            'K' => self.erase_line(param_or(params, 0, 0)),
3561            'X' => self.erase_chars(param_or(params, 0, 1) as usize),
3562            '@' => self.insert_chars(param_or(params, 0, 1) as usize),
3563            'P' => self.delete_chars(param_or(params, 0, 1) as usize),
3564            'S' => self.scroll_up_lines(param_or(params, 0, 1) as usize),
3565            'T' => self.scroll_down_lines(param_or(params, 0, 1) as usize),
3566            'L' => self.insert_lines(param_or(params, 0, 1) as usize),
3567            'M' => self.delete_lines(param_or(params, 0, 1) as usize),
3568            'g' => self.clear_tab_stop(param_or(params, 0, 0)),
3569            'r' => {
3570                let rows = self.grid.rows() as u16;
3571                let top = param_or(params, 0, 1) as usize;
3572                let bottom = param_or(params, 1, rows) as usize;
3573                self.set_scroll_region(top, bottom);
3574            }
3575            'm' => self.sgr(params),
3576            's' => self.save_cursor(),    // SCOSC (CSI s) — alias of DECSC
3577            'u' => self.restore_cursor(), // SCORC (CSI u) — alias of DECRC
3578            // DA1 (primary device attributes, CSI c): advertise VT220 + ANSI
3579            // colour — the levels justerm actually implements (#27).
3580            'c' => self.replies.extend_from_slice(b"\x1b[?62;22c"),
3581            'n' => self.device_status_report(param_or(params, 0, 0)),
3582            // Non-private SM/RM. Folded over every parameter (modes can batch,
3583            // like the private path #56). IRM (4) and LNM (20) so far.
3584            'h' => {
3585                for m in params.iter().filter_map(|p| p.first().copied()) {
3586                    match m {
3587                        4 => self.insert_mode = true,
3588                        20 => self.newline_mode = true,
3589                        _ => {}
3590                    }
3591                }
3592            }
3593            'l' => {
3594                for m in params.iter().filter_map(|p| p.first().copied()) {
3595                    match m {
3596                        4 => self.insert_mode = false,
3597                        20 => self.newline_mode = false,
3598                        _ => {}
3599                    }
3600                }
3601            }
3602            _ => {}
3603        }
3604    }
3605
3606    fn esc_dispatch(&mut self, intermediates: &[u8], _ignore: bool, byte: u8) {
3607        // VT52 mode (#84): the pre-ANSI dialect reuses the same `ESC <final>`
3608        // tokens vte already produces, but with different meanings, so it is a
3609        // mode-gated branch here rather than a separate parser. All VT52 sequences
3610        // are intermediate-free; anything with an intermediate is not VT52.
3611        if self.vt52_mode && intermediates.is_empty() {
3612            self.vt52_dispatch(byte);
3613            return;
3614        }
3615        if let Some(&i) = intermediates.first() {
3616            // SCS: designate a charset to G0 (`ESC ( F`) or G1 (`ESC ) F`) (#62).
3617            if matches!(i, b'(' | b')') {
3618                let set = match byte {
3619                    b'0' => Charset::DecSpecialGraphics,
3620                    b'A' => Charset::Uk,
3621                    b'B' => Charset::Ascii,
3622                    _ => return, // other sets are later slices
3623                };
3624                self.charsets[if i == b'(' { 0 } else { 1 }] = set;
3625            }
3626            // Other intermediates (G2/G3 designators, etc.) are later slices.
3627            return;
3628        }
3629        match byte {
3630            b'D' => self.linefeed(), // IND (line-feed without CR)
3631            b'E' => {
3632                // NEL (next line): carriage return + line-feed.
3633                self.carriage_return();
3634                self.linefeed();
3635            }
3636            b'H' => self.set_tab_stop(),             // HTS
3637            b'M' => self.reverse_index(),            // RI
3638            b'7' => self.save_cursor(),              // DECSC
3639            b'8' => self.restore_cursor(),           // DECRC
3640            b'c' => self.full_reset(),               // RIS (#53)
3641            b'=' => self.application_keypad = true,  // DECKPAM (#74)
3642            b'>' => self.application_keypad = false, // DECKPNM
3643            _ => {}
3644        }
3645    }
3646
3647    /// OSC dispatch (#12 event surface): title (0/2), cwd (7). OSC 8 hyperlink
3648    /// is per-cell state, handled in its own slice (#26), not here.
3649    fn osc_dispatch(&mut self, params: &[&[u8]], _bell_terminated: bool) {
3650        // params[0] is the OSC number; params[1..] the payload fields.
3651        let Some(&number) = params.first() else {
3652            return;
3653        };
3654        match number {
3655            // OSC 0 = icon + window title, OSC 2 = window title. Both set title.
3656            b"0" | b"2" => {
3657                if let Some(&title) = params.get(1) {
3658                    self.events.push(TermEvent::Title(
3659                        String::from_utf8_lossy(title).into_owned(),
3660                    ));
3661                }
3662            }
3663            // OSC 7 = current working directory (a file:// URI).
3664            b"7" => {
3665                if let Some(&cwd) = params.get(1) {
3666                    self.events
3667                        .push(TermEvent::Cwd(String::from_utf8_lossy(cwd).into_owned()));
3668                }
3669            }
3670            // OSC 133 = FinalTerm/iTerm2 shell-integration command marks (#158):
3671            // `A` prompt start, `B` command start, `C` output start, `D[;exit]`
3672            // command finished. Each anchors a kinded marker at the cursor line;
3673            // pairing + navigation is consumer policy (#160). Unknown subcommands
3674            // (or none) are ignored. `D`'s exit field parses to `i32`, else None.
3675            b"133" => match params.get(1).copied() {
3676                Some(b"A") => self.add_command_mark(MarkerKind::PromptStart),
3677                Some(b"B") => self.add_command_mark(MarkerKind::CommandStart),
3678                Some(b"C") => self.add_command_mark(MarkerKind::OutputStart),
3679                Some(b"D") => {
3680                    let exit = params
3681                        .get(2)
3682                        .and_then(|p| core::str::from_utf8(p).ok())
3683                        .and_then(|s| s.parse::<i32>().ok());
3684                    self.add_command_mark(MarkerKind::CommandFinished(exit));
3685                }
3686                _ => {}
3687            },
3688            // OSC 8 = hyperlink: `OSC 8 ; params ; URI`. A non-empty URI opens a
3689            // link (interned + made current); an empty URI closes it. `params`
3690            // (e.g. `id=…`) is ignored for now — id-grouping is a later refinement.
3691            b"8" => {
3692                let uri = params.get(2).copied().unwrap_or(b"");
3693                if uri.is_empty() {
3694                    self.current_link = None;
3695                } else {
3696                    self.hyperlink_pool
3697                        .push(String::from_utf8_lossy(uri).into_owned());
3698                    self.current_link =
3699                        core::num::NonZeroU32::new(self.hyperlink_pool.len() as u32);
3700                }
3701            }
3702            // OSC 4 = set/query an ANSI palette entry: `OSC 4 ; index ; spec`
3703            // (#122). The engine forwards index + raw spec; the consumer applies
3704            // it to its palette (theme-agnostic — the cell keeps `Indexed`).
3705            b"4" => {
3706                // One event per `index ; spec` pair (xterm's `while slots > 1`).
3707                let mut rest = &params[1..];
3708                while let [idx, spec, tail @ ..] = rest {
3709                    rest = tail;
3710                    if let Ok(index) = String::from_utf8_lossy(idx).parse::<u8>() {
3711                        if *spec == b"?" {
3712                            self.events.push(TermEvent::QueryPaletteColor { index });
3713                        } else {
3714                            self.events.push(TermEvent::SetPaletteColor {
3715                                index,
3716                                spec: String::from_utf8_lossy(spec).into_owned(),
3717                            });
3718                        }
3719                    }
3720                }
3721            }
3722            // OSC 104 = reset palette entries (#122): no arg resets the whole
3723            // table, else one event per named index.
3724            b"104" => {
3725                if params.len() <= 1 {
3726                    self.events.push(TermEvent::ResetPaletteColor(None));
3727                } else {
3728                    for &idx in &params[1..] {
3729                        if let Ok(index) = String::from_utf8_lossy(idx).parse::<u8>() {
3730                            self.events.push(TermEvent::ResetPaletteColor(Some(index)));
3731                        }
3732                    }
3733                }
3734            }
3735            // OSC 10/11 = set/query the default foreground/background, stacking
3736            // specs across the [fg, bg] slots (#122, #137). OSC 10 starts at fg,
3737            // OSC 11 at bg. The engine forwards raw specs (theme-agnostic).
3738            b"10" => self.special_color(params, 0),
3739            b"11" => self.special_color(params, 1),
3740            // OSC 110 / 111 = reset the default foreground / background (#122).
3741            b"110" => self.events.push(TermEvent::ResetForeground),
3742            b"111" => self.events.push(TermEvent::ResetBackground),
3743            _ => {} // other OSCs are later slices
3744        }
3745    }
3746}