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 / region scroll / reflow / both alt swaps; known
176    /// exception: the accrual sub-region branch, #449) — a stale span would
177    /// otherwise 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, reflow, both alt
1170    /// swaps. (Known exception: a top-anchored sub-region scroll accrues to
1171    /// scrollback WITHOUT funneling, desyncing anchors below the bottom margin
1172    /// — tracked as #449, a pre-#436 gap shared with selection and markers.)
1173    /// In-line *column* shifts (ICH/DCH, insert-mode print) and
1174    /// in-place erases (ED/EL/ECH, overwrite) deliberately do NOT funnel — the
1175    /// set stales in place there exactly like the selection sibling and
1176    /// xterm's decorations, healed by the consumer's debounced re-search on
1177    /// output (which those mutations are). Search matches are query-derived
1178    /// (the engine holds matches, not the query, and the *set* itself may have
1179    /// changed), so unlike the user-authored selection they are dropped rather
1180    /// than re-anchored. Clearing avoids painting wrong content for the frame
1181    /// between the mutation and the consumer's refresh.
1182    fn invalidate_search_highlights(&mut self) {
1183        self.search_highlights.clear();
1184        // #436: the active designation is a stored SPAN, no longer structurally
1185        // tied to the set — clear it in the same funnel or it would keep
1186        // painting coordinates that now hold arbitrary other text.
1187        self.active_search_highlight = None;
1188    }
1189
1190    /// Register a decoration marker at viewport `row`, returning its stable id
1191    /// (#118). The row is resolved to an absolute buffer line (like a selection
1192    /// anchor), so the marker tracks that content through scroll/eviction/reflow.
1193    /// The active buffer's marker list (#177 S0) — alt while on the alt screen,
1194    /// else normal. Add/rotate/project operate on this; primary-scoped queries
1195    /// (`command_marks`/`command_lines`) and scrollback eviction read
1196    /// `normal_markers` directly.
1197    fn markers(&self) -> &Vec<Marker> {
1198        if self.on_alt {
1199            &self.alt_markers
1200        } else {
1201            &self.normal_markers
1202        }
1203    }
1204
1205    /// Mutable [`Self::markers`].
1206    fn markers_mut(&mut self) -> &mut Vec<Marker> {
1207        if self.on_alt {
1208            &mut self.alt_markers
1209        } else {
1210            &mut self.normal_markers
1211        }
1212    }
1213
1214    pub fn add_marker(&mut self, row: usize) -> MarkerId {
1215        // On the alt screen this anchors an *alt-scoped* marker (#187): per-buffer
1216        // storage (#186) keeps it out of the primary list, and it is disposed on
1217        // alt-leave — xterm's per-buffer `addMarker` + `clearAllMarkers`. No dead
1218        // sentinel is needed anymore; `markers_mut` routes to the active buffer.
1219        let line = self.viewport_to_abs(row, 0).line;
1220        self.push_marker(line, 0, MarkerKind::Plain)
1221    }
1222
1223    /// Push a marker anchored at absolute `(line, col)` with `kind`, returning its
1224    /// id. The shared core of `add_marker` (viewport row, `col = 0`) and OSC-133
1225    /// command marks (cursor line + column) — one place owns id allocation + the
1226    /// `markers` list.
1227    fn push_marker(&mut self, line: usize, col: usize, kind: MarkerKind) -> MarkerId {
1228        let id = MarkerId(self.next_marker_id);
1229        self.next_marker_id += 1;
1230        self.markers_mut().push(Marker {
1231            id,
1232            line,
1233            col,
1234            kind,
1235        });
1236        id
1237    }
1238
1239    /// Record an OSC 133 command-boundary mark at the cursor's current line
1240    /// (#158). Ignored on the alt screen: unlike the decoration guards that
1241    /// per-buffer storage retired (#187), this one stands on a *semantic* — OSC
1242    /// 133 is shell integration, which only runs on the primary screen, so an alt
1243    /// 133 is meaningless (there is no command to bound). Command nav/announce read
1244    /// the *normal* buffer's marks (`command_marks`/`command_lines`, primary-scoped
1245    /// since #186), so even a stray alt 133 could not reach them — but there is no
1246    /// value in creating an alt-scoped command mark nothing consumes (#188). The
1247    /// cursor line is `scrollback ++ screen`-absolute, independent of
1248    /// `display_offset` (the cursor is always in the grid, never scrollback).
1249    fn add_command_mark(&mut self, kind: MarkerKind) {
1250        if self.on_alt {
1251            return;
1252        }
1253        let line = self.scrollback.len() + self.cursor.row;
1254        self.push_marker(line, self.cursor.col, kind);
1255    }
1256
1257    /// The OSC 133 command-boundary marks in buffer order — `(id, absolute line,
1258    /// kind)` (#158). Plain decoration markers (#118) are excluded. The consumer
1259    /// pairs prompt/command/finished marks and drives navigation/announce policy
1260    /// (#160); core only parses and anchors them.
1261    pub fn command_marks(&self) -> Vec<(MarkerId, usize, MarkerKind)> {
1262        // Primary-scoped: OSC-133 shell integration marks live on the normal
1263        // buffer, so command nav/announce read it even while on the alt screen.
1264        self.normal_markers
1265            .iter()
1266            .filter(|m| m.kind != MarkerKind::Plain)
1267            .map(|m| (m.id, m.line, m.kind))
1268            .collect()
1269    }
1270
1271    /// The executed shell commands recovered from OSC-133 marks, in buffer order
1272    /// (#166) — the data behind screen-reader command navigation. Each
1273    /// [`CommandLine`] pairs a CommandStart(B) with the following OutputStart(C)
1274    /// to extract the *typed command* (the prompt before B and the output after C
1275    /// excluded via the captured columns, VSCode `extractCommandLine` parity), and
1276    /// attaches the trailing CommandFinished(D) exit. A command still being typed
1277    /// (B with no C yet) is not navigable — its text has no bound — so it is
1278    /// omitted until output starts.
1279    pub fn command_lines(&self) -> Vec<CommandLine> {
1280        let mut out: Vec<CommandLine> = Vec::new();
1281        // (B line, B col) awaiting its matching C. Marks arrive in buffer order.
1282        let mut pending: Option<(usize, usize)> = None;
1283        // Primary-scoped (see `command_marks`): the normal buffer's marks.
1284        for m in &self.normal_markers {
1285            match m.kind {
1286                MarkerKind::CommandStart => pending = Some((m.line, m.col)),
1287                MarkerKind::OutputStart => {
1288                    if let Some((b_line, b_col)) = pending.take() {
1289                        // Columns bound the command precisely even though output was
1290                        // written after C — `extract_lines` reads current cells but
1291                        // clips to `[b_col, c_col)`, excluding both prompt and output.
1292                        // Command marks anchor primary content — read the primary
1293                        // grid so the text is right even while on the alt screen (#192).
1294                        let command =
1295                            self.extract_lines(self.primary_grid(), b_line, b_col, m.line, m.col);
1296                        out.push(CommandLine {
1297                            line: self.doc_line_of(self.primary_grid(), b_line),
1298                            command,
1299                            exit: None,
1300                        });
1301                    }
1302                }
1303                MarkerKind::CommandFinished(exit) => {
1304                    // The exit belongs to the most recent command not yet closed;
1305                    // the `is_none` guard stops a stray D from clobbering a code.
1306                    if let Some(last) = out.last_mut()
1307                        && last.exit.is_none()
1308                    {
1309                        last.exit = exit;
1310                    }
1311                }
1312                MarkerKind::Plain | MarkerKind::PromptStart => {}
1313            }
1314        }
1315        out
1316    }
1317
1318    /// The document (logical) line index that absolute buffer line `abs` renders
1319    /// into within [`Term::accessible_text`] — the number of hard line-ends before
1320    /// it (soft-wrapped rows share one logical line). Primary-screen coordinates,
1321    /// matching `accessible_text`'s `start = 0` for the primary screen; command
1322    /// marks are primary-only. O(abs) per call — fine for an on-demand query over
1323    /// the handful of commands in a session.
1324    fn doc_line_of(&self, grid: &Grid, abs: usize) -> usize {
1325        (0..abs)
1326            .filter(|&l| {
1327                !self
1328                    .line_in(grid, l)
1329                    .last()
1330                    .is_some_and(|c| c.is_wrapline())
1331            })
1332            .count()
1333    }
1334
1335    /// Remove a marker by id (#118). Disposing it fires `MarkerDisposed` so the
1336    /// consumer's cleanup is one path whether the marker left by eviction or by
1337    /// this explicit call (xterm's `dispose()` likewise always fires onDispose).
1338    /// A no-op for an unknown/already-disposed id.
1339    pub fn remove_marker(&mut self, id: MarkerId) {
1340        // Id-based, buffer-agnostic: search both lists (ids are unique across
1341        // buffers) so a marker is removed whichever screen it lives on (#177 S0).
1342        let before = self.normal_markers.len() + self.alt_markers.len();
1343        self.normal_markers.retain(|m| m.id != id);
1344        self.alt_markers.retain(|m| m.id != id);
1345        if self.normal_markers.len() + self.alt_markers.len() != before {
1346            self.events.push(TermEvent::MarkerDisposed(id));
1347        }
1348    }
1349
1350    /// Shift markers down one absolute line after the oldest history line is
1351    /// evicted; a marker *on* that line (abs 0) has left the buffer, so it is
1352    /// disposed and announced (#118) — the marker analogue of
1353    /// `selection_evict_oldest`, but a list with per-marker disposal.
1354    fn markers_evict_oldest(&mut self) {
1355        // Scrollback eviction is primary-only (the alt screen has none).
1356        let mut disposed = Vec::new();
1357        self.normal_markers.retain_mut(|m| {
1358            if m.line == 0 {
1359                disposed.push(m.id);
1360                false
1361            } else {
1362                m.line -= 1;
1363                true
1364            }
1365        });
1366        for id in disposed {
1367            self.events.push(TermEvent::MarkerDisposed(id));
1368        }
1369    }
1370
1371    /// Rotate markers within an in-screen region scroll of absolute lines
1372    /// `[top, bottom]` (`up` = a line dropped at `top`, else at `bottom`) — the
1373    /// marker analogue of `selection_rotate_region`. A marker on the dropped edge
1374    /// has left the buffer, so it is disposed and announced (#118).
1375    fn markers_rotate_region(&mut self, top: usize, bottom: usize, up: bool) {
1376        let mut disposed = Vec::new();
1377        self.markers_mut().retain_mut(|m| {
1378            if m.line < top || m.line > bottom {
1379                return true; // outside the region — unchanged
1380            }
1381            let dropped_edge = if up { top } else { bottom };
1382            if m.line == dropped_edge {
1383                disposed.push(m.id);
1384                false
1385            } else {
1386                m.line = if up { m.line - 1 } else { m.line + 1 };
1387                true
1388            }
1389        });
1390        for id in disposed {
1391            self.events.push(TermEvent::MarkerDisposed(id));
1392        }
1393    }
1394
1395    /// The active buffer's markers projected onto the current viewport — one
1396    /// `MarkerPosition` per marker whose line is visible, off-screen markers
1397    /// omitted. The alt screen projects its own (alt-scoped) markers now (#187);
1398    /// they are disposed on alt-leave, so a primary frame never shows them.
1399    fn marker_positions(&self) -> Vec<MarkerPosition> {
1400        let top = self.scrollback.len() - self.display_offset;
1401        let rows = self.grid.rows();
1402        self.markers()
1403            .iter()
1404            .filter_map(|m| {
1405                let row = m.line.checked_sub(top)?;
1406                (row < rows).then_some(MarkerPosition {
1407                    id: m.id,
1408                    row,
1409                    kind: m.kind,
1410                })
1411            })
1412            .collect()
1413    }
1414
1415    /// Every live marker's absolute buffer line (#120 S3) — the off-viewport
1416    /// superset of `marker_positions`, for the overview ruler. No viewport filter:
1417    /// a marker scrolled out of view is still reported (that is the ruler's job),
1418    /// its `line` in the same `[0, scrollback + rows)` frame as the header's
1419    /// `scrollback_len`/`display_offset`.
1420    fn all_marker_lines(&self) -> Vec<MarkerLine> {
1421        self.markers()
1422            .iter()
1423            .map(|m| MarkerLine {
1424                id: m.id,
1425                line: m.line as u32,
1426            })
1427            .collect()
1428    }
1429
1430    /// Begin a selection of `ty` at viewport `(row, col)`, `side`.
1431    pub fn selection_begin(&mut self, row: usize, col: usize, side: Side, ty: SelectionType) {
1432        let anchor = Anchor {
1433            point: self.viewport_to_abs(row, col),
1434            side,
1435        };
1436        self.selection = Some(Selection {
1437            ty,
1438            anchor,
1439            focus: anchor,
1440        });
1441    }
1442
1443    /// Extend the live selection's focus to viewport `(row, col)`, `side`.
1444    pub fn selection_extend(&mut self, row: usize, col: usize, side: Side) {
1445        let focus = Anchor {
1446            point: self.viewport_to_abs(row, col),
1447            side,
1448        };
1449        if let Some(sel) = &mut self.selection {
1450            sel.focus = focus;
1451        }
1452    }
1453
1454    /// Clear the selection.
1455    pub fn selection_clear(&mut self) {
1456        self.selection = None;
1457    }
1458
1459    /// Shift the selection up by one absolute line after the oldest history line
1460    /// is evicted by the scrollback cap. An endpoint clamps to the new top; if
1461    /// the whole selection was on the evicted line, it is cleared.
1462    fn selection_evict_oldest(&mut self) {
1463        let Some((a, f)) = self
1464            .selection
1465            .as_ref()
1466            .map(|s| (s.anchor.point.line, s.focus.point.line))
1467        else {
1468            return;
1469        };
1470        if a == 0 && f == 0 {
1471            self.selection = None;
1472            return;
1473        }
1474        if let Some(sel) = &mut self.selection {
1475            sel.anchor.point.line = a.saturating_sub(1);
1476            sel.focus.point.line = f.saturating_sub(1);
1477        }
1478    }
1479
1480    /// Rotate the selection within an in-screen scroll of absolute lines
1481    /// `[top, bottom]`. `up` = content scrolled up (a line dropped at `top`);
1482    /// otherwise down (dropped at `bottom`). Called once per scrolled line (delta
1483    /// 1) by linefeed/RI/SU/SD/IL/DL.
1484    ///
1485    /// Mirrors alacritty `Selection::rotate`: an endpoint pushed past the region
1486    /// edge is *clamped* to that edge (upper → `top`/col 0/Left, lower →
1487    /// `bottom`/last col/Right; columns/side kept for Block), preserving the part
1488    /// of the selection still in the buffer. The whole selection clears only on a
1489    /// true *overtake* — the upper endpoint crossing the bottom while the lower
1490    /// stays inside, or the lower falling above the upper (a selection wholly on
1491    /// the dropped line). (#174: this replaced a policy that cleared on any
1492    /// endpoint touching the dropped edge, dropping still-valid content.)
1493    fn selection_rotate_region(&mut self, top: usize, bottom: usize, up: bool) {
1494        let (ty, anchor, focus) = match self.selection.as_ref() {
1495            Some(s) => (s.ty, s.anchor, s.focus),
1496            None => return,
1497        };
1498        let last_col = self.grid.cols().saturating_sub(1);
1499        // Order the endpoints by buffer position; the upper (`start`) clamps to
1500        // the region top, the lower (`end`) to the bottom. Remember which is the
1501        // anchor so the result writes back to the right field.
1502        let anchor_is_start = anchor.point <= focus.point;
1503        let (mut start, mut end) = if anchor_is_start {
1504            (anchor, focus)
1505        } else {
1506            (focus, anchor)
1507        };
1508
1509        let (top_i, bottom_i) = (top as isize, bottom as isize);
1510        // The endpoint's line after the one-line scroll, or `None` if it's outside
1511        // the region (untouched). The dropped-edge line shifts *past* the edge (to
1512        // be clamped/overtaken below), matching alacritty's `line - delta`.
1513        let shift = |line: usize| -> Option<isize> {
1514            if line < top || line > bottom {
1515                None
1516            } else if up {
1517                Some(line as isize - 1)
1518            } else {
1519                Some(line as isize + 1)
1520            }
1521        };
1522
1523        // Upper endpoint: clamp to the region top when pushed above it; clear if it
1524        // overtook the region bottom (down-scroll) while the lower stays inside.
1525        if let Some(nl) = shift(start.point.line) {
1526            if nl > bottom_i && (end.point.line as isize) <= bottom_i {
1527                self.selection = None;
1528                return;
1529            }
1530            if nl < top_i {
1531                start.point.line = top;
1532                if ty != SelectionType::Block {
1533                    start.point.col = 0;
1534                    start.side = Side::Left;
1535                }
1536            } else {
1537                start.point.line = nl as usize;
1538            }
1539        }
1540        // Lower endpoint: clear if it fell above the (rotated) upper endpoint;
1541        // else clamp to the region bottom when pushed below it.
1542        if let Some(nl) = shift(end.point.line) {
1543            if nl < start.point.line as isize {
1544                self.selection = None;
1545                return;
1546            }
1547            if nl > bottom_i {
1548                end.point.line = bottom;
1549                if ty != SelectionType::Block {
1550                    end.point.col = last_col;
1551                    end.side = Side::Right;
1552                }
1553            } else {
1554                end.point.line = nl as usize;
1555            }
1556        }
1557
1558        if let Some(sel) = &mut self.selection {
1559            if anchor_is_start {
1560                (sel.anchor, sel.focus) = (start, end);
1561            } else {
1562                (sel.anchor, sel.focus) = (end, start);
1563            }
1564        }
1565    }
1566
1567    /// The selection projected onto the current viewport: one inclusive-column
1568    /// span per visible row. Rows scrolled off-screen (above or below) are
1569    /// dropped. Empty when nothing is selected. See `SelectionSpan`.
1570    pub fn selection_range(&self) -> Vec<SelectionSpan> {
1571        let Some(resolved) = self.resolve() else {
1572            return Vec::new();
1573        };
1574        let rows = self.grid.rows();
1575        // Absolute index of viewport row 0.
1576        let top = self.scrollback.len() - self.display_offset;
1577        let mut spans = Vec::new();
1578
1579        // Add a span for absolute `line` with inclusive cols `left..=right`, if
1580        // the line is currently visible.
1581        let mut push = |line: usize, left: usize, right: usize| {
1582            if line >= top {
1583                let row = line - top;
1584                if row < rows {
1585                    spans.push(SelectionSpan { row, left, right });
1586                }
1587            }
1588        };
1589
1590        match resolved {
1591            Resolved::Linear {
1592                start_line,
1593                from,
1594                end_line,
1595                to,
1596            } => {
1597                for line in start_line..=end_line {
1598                    let len = self.abs_line(line).len();
1599                    let left = if line == start_line { from } else { 0 };
1600                    let right_excl = if line == end_line { to.min(len) } else { len };
1601                    if right_excl > left {
1602                        push(line, left, right_excl - 1);
1603                    }
1604                }
1605            }
1606            Resolved::Block {
1607                line0,
1608                line1,
1609                from,
1610                to,
1611            } => {
1612                if to > from {
1613                    for line in line0..=line1 {
1614                        push(line, from, to - 1);
1615                    }
1616                }
1617            }
1618        }
1619        spans
1620    }
1621
1622    /// Resolve the live selection into absolute-coordinate bounds per type:
1623    /// a `Linear` run (char/word/line, which join soft wraps) or a `Block`
1624    /// rectangle. `None` when nothing is selected. Columns are half-open
1625    /// (`from..to`). Shared by `selection_text` and `selection_range`.
1626    fn resolve(&self) -> Option<Resolved> {
1627        let sel = self.selection.as_ref()?;
1628        let (start, end) = sel.ordered();
1629        Some(match sel.ty {
1630            SelectionType::Char => {
1631                // Half-open columns: each side decides if its own cell is in.
1632                let from = match start.side {
1633                    Side::Left => start.point.col,
1634                    Side::Right => start.point.col + 1,
1635                };
1636                let to = match end.side {
1637                    Side::Left => end.point.col,
1638                    Side::Right => end.point.col + 1,
1639                };
1640                Resolved::Linear {
1641                    start_line: start.point.line,
1642                    from,
1643                    end_line: end.point.line,
1644                    to,
1645                }
1646            }
1647            SelectionType::Word => {
1648                // Snap both ends to word boundaries (side is ignored).
1649                let ws = self.word_start(start.point);
1650                let we = self.word_end(end.point);
1651                Resolved::Linear {
1652                    start_line: ws.line,
1653                    from: ws.col,
1654                    end_line: we.line,
1655                    to: we.col + 1,
1656                }
1657            }
1658            SelectionType::Line => Resolved::Linear {
1659                start_line: start.point.line,
1660                from: 0,
1661                end_line: end.point.line,
1662                to: self.grid.cols(),
1663            },
1664            SelectionType::Block => {
1665                // Rectangular: the same column range on every row. Columns come
1666                // from the two anchors (min/max, with each edge's side).
1667                let cols = self.grid.cols();
1668                let (a, b) = (sel.anchor, sel.focus);
1669                let (lcol, lside, rcol, rside) = if a.point.col <= b.point.col {
1670                    (a.point.col, a.side, b.point.col, b.side)
1671                } else {
1672                    (b.point.col, b.side, a.point.col, a.side)
1673                };
1674                let from = match lside {
1675                    Side::Left => lcol,
1676                    Side::Right => lcol + 1,
1677                };
1678                let to = match rside {
1679                    Side::Left => rcol,
1680                    Side::Right => rcol + 1,
1681                };
1682                Resolved::Block {
1683                    line0: a.point.line.min(b.point.line),
1684                    line1: a.point.line.max(b.point.line),
1685                    from,
1686                    to: to.min(cols).max(from),
1687                }
1688            }
1689        })
1690    }
1691
1692    /// The selected text (for copy), or `None` when nothing is selected.
1693    pub fn selection_text(&self) -> Option<String> {
1694        match self.resolve()? {
1695            Resolved::Linear {
1696                start_line,
1697                from,
1698                end_line,
1699                to,
1700            } => Some(self.extract_lines(&self.grid, start_line, from, end_line, to)),
1701            Resolved::Block {
1702                line0,
1703                line1,
1704                from,
1705                to,
1706            } => {
1707                // Each row independently — no soft-wrap joining.
1708                let mut out = String::new();
1709                for line in line0..=line1 {
1710                    let hi = to.min(self.abs_line(line).len());
1711                    let mut seg = String::new();
1712                    for col in from..hi {
1713                        self.append_cell(&self.grid, &mut seg, line, col);
1714                    }
1715                    out.push_str(seg.trim_end());
1716                    if line != line1 {
1717                        out.push('\n');
1718                    }
1719                }
1720                Some(out)
1721            }
1722        }
1723    }
1724
1725    /// Append the text at absolute `(line, col)` — its base glyph plus any
1726    /// combining marks from the row's map — to `out`. Wide-char spacers
1727    /// contribute nothing.
1728    fn append_cell(&self, grid: &Grid, out: &mut String, line: usize, col: usize) {
1729        let cell = &self.line_in(grid, line)[col];
1730        if cell.is_spacer() {
1731            return;
1732        }
1733        out.push(cell.c());
1734        if let Some(marks) = self.combining_in(grid, line, col) {
1735            out.extend(marks);
1736        }
1737    }
1738
1739    /// The whole buffer as one text document (#150): scrollback + screen assembled
1740    /// into logical lines (soft-wrap joined, wide-spacers skipped, trailing blanks
1741    /// trimmed at the logical end) — the accessible-view a screen reader reads as
1742    /// a document, distinct from the viewport row tree (#119). Reuses the
1743    /// selection extraction ([`extract_lines`](Self::extract_lines)) over the full
1744    /// range. On the alt screen only the alt buffer is shown — its "scrollback" is
1745    /// the *primary* buffer's, not this app's — mirroring `viewport_logical_lines`'
1746    /// alt floor.
1747    pub fn accessible_text(&self) -> String {
1748        let total = self.scrollback.len() + self.grid.rows();
1749        if total == 0 {
1750            return String::new();
1751        }
1752        let start = if self.on_alt {
1753            self.scrollback.len()
1754        } else {
1755            0
1756        };
1757        let mut doc = self.extract_lines(&self.grid, start, 0, total - 1, usize::MAX);
1758        // Trim *trailing* empty lines (blank screen rows below the content) — pure
1759        // noise to a listener, and what a fresh screen would otherwise emit. Keep
1760        // *internal* blank lines (paragraph breaks between command outputs) — a
1761        // document wants those, unlike the viewport tree which drops all empties.
1762        doc.truncate(doc.trim_end_matches('\n').len());
1763        doc
1764    }
1765
1766    /// Concatenate the selected cells from `(start_line, from)` to
1767    /// `(end_line, to_end)` (half-open columns on the first/last line, whole
1768    /// lines between). Soft-wrapped rows (WRAPLINE) accumulate into one *logical*
1769    /// line so trailing-blank trimming happens only at the logical end — spaces
1770    /// at a wrap boundary are real content. A hard line-end flushes with `\n`.
1771    fn extract_lines(
1772        &self,
1773        grid: &Grid,
1774        start_line: usize,
1775        from: usize,
1776        end_line: usize,
1777        to_end: usize,
1778    ) -> String {
1779        let mut out = String::new();
1780        let mut current = String::new();
1781        for line in start_line..=end_line {
1782            let cells = self.line_in(grid, line);
1783            let left = if line == start_line { from } else { 0 };
1784            let right = if line == end_line {
1785                to_end.min(cells.len())
1786            } else {
1787                cells.len()
1788            };
1789            // A degenerate range (sides inverting one cell) gives left > right;
1790            // clamp to empty rather than panic on the slice.
1791            let right = right.max(left);
1792            for col in left..right {
1793                self.append_cell(grid, &mut current, line, col);
1794            }
1795
1796            let is_last = line == end_line;
1797            let soft = cells.last().is_some_and(|c| c.is_wrapline());
1798            if is_last || !soft {
1799                out.push_str(current.trim_end());
1800                current.clear();
1801                if !is_last {
1802                    out.push('\n');
1803                }
1804            }
1805        }
1806        out
1807    }
1808
1809    /// The lowest absolute line a soft-wrap buffer walk may reach. On the alt screen
1810    /// `scrollback` holds the *primary* buffer's history — a separate logical space —
1811    /// so a walk floors at `scrollback.len()` (the alt grid's first line) and must not
1812    /// join across it. Mirrors the `search()` (#144) and `viewport_logical_lines`
1813    /// (#113) floors: justerm's single `[scrollback ++ grid]` buffer reproduces the
1814    /// primary↔alt isolation xterm gets from separate `Buffer` objects.
1815    fn abs_floor(&self) -> usize {
1816        if self.on_alt {
1817            self.scrollback.len()
1818        } else {
1819            0
1820        }
1821    }
1822
1823    /// The cell position before `(line, col)` in the *logical* line — the column
1824    /// to the left, or the end of the previous row if it soft-wrapped into this
1825    /// one. `None` at the buffer start or across a hard line-end.
1826    fn prev_pos(&self, line: usize, col: usize) -> Option<(usize, usize)> {
1827        if col > 0 {
1828            return Some((line, col - 1));
1829        }
1830        // Only step up while the previous row is still on *this* buffer (>= floor):
1831        // on alt, row 0 (`line == scrollback.len()`) must not join the primary
1832        // scrollback row below it, even when that row carries WRAPLINE (#207).
1833        if line > self.abs_floor() {
1834            let prev = self.abs_line(line - 1);
1835            if prev.last().is_some_and(|c| c.is_wrapline()) {
1836                return Some((line - 1, prev.len() - 1));
1837            }
1838        }
1839        None
1840    }
1841
1842    /// The cell position after `(line, col)` in the *logical* line — the column
1843    /// to the right, or the start of the next row if this row soft-wrapped.
1844    /// `None` at the buffer end or across a hard line-end.
1845    fn next_pos(&self, line: usize, col: usize) -> Option<(usize, usize)> {
1846        let cells = self.abs_line(line);
1847        if col + 1 < cells.len() {
1848            return Some((line, col + 1));
1849        }
1850        let total = self.scrollback.len() + self.grid.rows();
1851        // Symmetric floor guard (#207): a row below the floor (primary scrollback on
1852        // alt) must not soft-wrap-join down into the alt grid. `line >= floor` holds
1853        // for any position reachable on alt once `prev_pos` is floored; kept explicit
1854        // so no future caller can cross from a primary row.
1855        if line >= self.abs_floor()
1856            && line + 1 < total
1857            && cells.last().is_some_and(|c| c.is_wrapline())
1858        {
1859            return Some((line + 1, 0));
1860        }
1861        None
1862    }
1863
1864    /// Walk left to the first cell of `p`'s word (a maximal run of non-boundary
1865    /// chars), following a soft wrap into the previous row.
1866    fn word_start(&self, p: BufferPoint) -> BufferPoint {
1867        let cells = self.abs_line(p.line);
1868        let (mut line, mut col) = (p.line, p.col.min(cells.len().saturating_sub(1)));
1869        while let Some((pl, pc)) = self.prev_pos(line, col) {
1870            if is_word_boundary(self.abs_line(pl)[pc].c()) {
1871                break;
1872            }
1873            line = pl;
1874            col = pc;
1875        }
1876        BufferPoint { line, col }
1877    }
1878
1879    /// Walk right to the last cell of `p`'s word, following a soft wrap into the
1880    /// next row.
1881    fn word_end(&self, p: BufferPoint) -> BufferPoint {
1882        let cells = self.abs_line(p.line);
1883        let (mut line, mut col) = (p.line, p.col.min(cells.len().saturating_sub(1)));
1884        while let Some((nl, nc)) = self.next_pos(line, col) {
1885            if is_word_boundary(self.abs_line(nl)[nc].c()) {
1886                break;
1887            }
1888            line = nl;
1889            col = nc;
1890        }
1891        BufferPoint { line, col }
1892    }
1893
1894    /// Resize the screen to `cols` x `rows`. Rows dropped off the top (on shrink)
1895    /// enter scrollback. Column reflow of soft-wrapped lines is layered on top
1896    /// separately (#7). The whole screen is damaged.
1897    pub fn resize(&mut self, cols: usize, rows: usize) {
1898        // A terminal is never 0-wide/0-tall; clamp so the math below (rows - 1,
1899        // chunking by cols) can't underflow or divide by zero.
1900        let cols = cols.max(1);
1901        let rows = rows.max(1);
1902        let old_cols = self.grid.cols();
1903        let limit = self.scrollback_limit;
1904
1905        // A reflow moves match coordinates (and can change the match set), so the
1906        // query-derived highlights are invalidated; the consumer re-searches at
1907        // the new width. The selection re-anchors below — it is user-authored.
1908        self.invalidate_search_highlights();
1909
1910        // Both screens are resized. Scrollback pairs with the PRIMARY screen
1911        // (whichever is active) — the alt screen has no history of its own.
1912        let dims = ReflowDims {
1913            old_cols,
1914            cols,
1915            rows,
1916            limit,
1917        };
1918        let scrollback = std::mem::take(&mut self.scrollback);
1919        if self.on_alt {
1920            // Active = alt (cursor, no scrollback); inactive = primary. Selection
1921            // is primary-only and cleared on alt enter, so no anchors to track.
1922            // Alt markers DO ride this reflow (#187): justerm column-reflows the
1923            // alt grid, so a marker must follow its content or it drifts off. Their
1924            // stored line is `base + alt_row` (base = primary scrollback len), so
1925            // convert to alt-local rows for the pane, and re-anchor on the reflowed
1926            // base afterward (the primary scrollback below may rewrap its length).
1927            let old_base = scrollback.len();
1928            let alt_pts: Vec<(usize, usize)> = self
1929                .alt_markers
1930                .iter()
1931                .map(|m| (m.line - old_base, 0))
1932                .collect();
1933            let alt = self.grid.take_lines();
1934            let r_alt = reflow_pane(alt, VecDeque::new(), self.cursor.point(), &alt_pts, dims);
1935            self.grid.set_screen(r_alt.screen, cols, rows);
1936            self.cursor.set_point(r_alt.cursor, rows, cols);
1937
1938            // Primary is inactive here, but markers anchor *primary* content, so
1939            // they reflow with it (the selection is already cleared on alt enter).
1940            let marker_pts: Vec<(usize, usize)> =
1941                self.normal_markers.iter().map(|m| (m.line, 0)).collect();
1942            let primary = self.alt_grid.take_lines();
1943            let r = reflow_pane(
1944                primary,
1945                scrollback,
1946                self.saved_cursor.point(),
1947                &marker_pts,
1948                dims,
1949            );
1950            self.alt_grid.set_screen(r.screen, cols, rows);
1951            self.scrollback = r.scrollback;
1952            self.saved_cursor.set_point(r.cursor, rows, cols);
1953            for (i, m) in self.normal_markers.iter_mut().enumerate() {
1954                m.line = r.extras[i].0;
1955            }
1956            let new_base = self.scrollback.len();
1957            for (i, m) in self.alt_markers.iter_mut().enumerate() {
1958                m.line = new_base + r_alt.extras[i].0;
1959            }
1960        } else {
1961            // Active = primary (cursor, scrollback); inactive = alt. The selection
1962            // anchors (absolute) reflow alongside the cursor so they keep their
1963            // content across a column change.
1964            let sel_pts: Vec<(usize, usize)> = self
1965                .selection
1966                .as_ref()
1967                .map(|s| {
1968                    vec![
1969                        (s.anchor.point.line, s.anchor.point.col),
1970                        (s.focus.point.line, s.focus.point.col),
1971                    ]
1972                })
1973                .unwrap_or_default();
1974            // Markers reflow on the same pane by (line, col) — the column matters
1975            // for OSC-133 command marks, whose B/C columns bound the extracted
1976            // command text (#166). They ride after the selection points so each
1977            // reads its own reflowed slot back from `extras` (#118).
1978            let mut pts = sel_pts.clone();
1979            pts.extend(self.normal_markers.iter().map(|m| (m.line, m.col)));
1980
1981            let primary = self.grid.take_lines();
1982            let r = reflow_pane(primary, scrollback, self.cursor.point(), &pts, dims);
1983            self.grid.set_screen(r.screen, cols, rows);
1984            self.scrollback = r.scrollback;
1985            self.cursor.set_point(r.cursor, rows, cols);
1986            if let Some(sel) = &mut self.selection {
1987                sel.anchor.point = BufferPoint {
1988                    line: r.extras[0].0,
1989                    col: r.extras[0].1,
1990                };
1991                sel.focus.point = BufferPoint {
1992                    line: r.extras[1].0,
1993                    col: r.extras[1].1,
1994                };
1995            }
1996            let marker_off = sel_pts.len();
1997            for (i, m) in self.normal_markers.iter_mut().enumerate() {
1998                m.line = r.extras[marker_off + i].0;
1999                m.col = r.extras[marker_off + i].1;
2000            }
2001
2002            let alt = self.alt_grid.take_lines();
2003            let r = reflow_pane(alt, VecDeque::new(), (0, 0), &[], dims);
2004            self.alt_grid.set_screen(r.screen, cols, rows);
2005        }
2006
2007        // Margins reset to the full screen; tab stops reset to the default grid.
2008        self.cursor.pending_wrap = false;
2009        self.scroll_top = 0;
2010        self.scroll_bottom = rows - 1;
2011        self.tabs = default_tabs(cols);
2012        self.display_offset = self.display_offset.min(self.scrollback.len());
2013
2014        // Damage tracking is sized to the screen; a resize repaints everything,
2015        // so drop any pending scroll op (it points at the old rows).
2016        self.line_damage = vec![LineBounds::undamaged(cols); rows];
2017        self.scroll = None;
2018        self.mark_fully_damaged();
2019    }
2020
2021    pub fn grid(&self) -> &Grid {
2022        &self.grid
2023    }
2024
2025    pub fn cursor(&self) -> &Cursor {
2026        &self.cursor
2027    }
2028
2029    /// Whether bracketed-paste mode (DEC ?2004) is enabled. The input encoder
2030    /// (#11) reads this to decide whether to wrap pasted text in markers.
2031    pub fn bracketed_paste(&self) -> bool {
2032        self.bracketed_paste
2033    }
2034
2035    // ---- input encoding (#11) ------------------------------------------------
2036
2037    /// Encode a key event to bytes using the active cursor-key mode (DECCKM)
2038    /// and the kitty keyboard-protocol flags (`encode_key` consults both).
2039    pub fn encode_key(&self, ev: KeyEvent) -> Option<Vec<u8>> {
2040        encode_key(
2041            &ev,
2042            self.app_cursor_keys,
2043            self.application_keypad,
2044            self.kitty_flags,
2045        )
2046    }
2047
2048    /// Encode a mouse event using the active tracking mode + encoding. `None`
2049    /// when reporting is off or the event is filtered by the mode.
2050    pub fn encode_mouse(&self, ev: MouseEvent) -> Option<Vec<u8>> {
2051        encode_mouse(&ev, self.mouse_protocol, self.mouse_encoding)
2052    }
2053
2054    /// Encode pasted text, wrapping it in bracketed-paste markers when ?2004 is
2055    /// on.
2056    pub fn encode_paste(&self, text: &str) -> Vec<u8> {
2057        encode_paste(text, self.bracketed_paste)
2058    }
2059
2060    /// Encode a focus change (`CSI I`/`CSI O`), or `None` when focus reporting
2061    /// (?1004) is off.
2062    pub fn encode_focus(&self, focused: bool) -> Option<Vec<u8>> {
2063        encode_focus(focused, self.focus_events)
2064    }
2065
2066    /// Take the consumer events queued since the last drain, emptying the queue.
2067    pub fn drain_events(&mut self) -> Vec<TermEvent> {
2068        std::mem::take(&mut self.events)
2069    }
2070
2071    /// Take the reply bytes queued since the last drain (DA/DSR/DECRQM answers),
2072    /// emptying the buffer. The consumer writes them back to the PTY.
2073    pub fn drain_replies(&mut self) -> Vec<u8> {
2074        std::mem::take(&mut self.replies)
2075    }
2076
2077    /// Device Status Report (CSI Ps n): 6 = cursor position, 5 = operating
2078    /// status. Queues the reply for `drain_replies` (#27).
2079    fn device_status_report(&mut self, param: u16) {
2080        match param {
2081            6 => {
2082                // CSI row;col R, 1-based — region-relative under origin mode
2083                // (the coordinate system the app is addressing in).
2084                let row = if self.origin_mode {
2085                    self.cursor.row.saturating_sub(self.scroll_top)
2086                } else {
2087                    self.cursor.row
2088                } + 1;
2089                let col = self.cursor.col + 1;
2090                self.replies
2091                    .extend_from_slice(format!("\x1b[{row};{col}R").as_bytes());
2092            }
2093            5 => self.replies.extend_from_slice(b"\x1b[0n"), // status: OK
2094            _ => {}
2095        }
2096    }
2097
2098    /// Kitty keyboard-protocol negotiation (#23). `lead` is the leading CSI
2099    /// intermediate: `?` query, `>` push, `=` set, `<` pop.
2100    fn kitty_dispatch(&mut self, lead: u8, params: &Params) {
2101        match lead {
2102            // Query → report the current flags as `CSI ? flags u` (#27 channel).
2103            b'?' => self
2104                .replies
2105                .extend_from_slice(format!("\x1b[?{}u", self.kitty_flags).as_bytes()),
2106            // Push: save the current flags, then set the new ones (default 0).
2107            b'>' => {
2108                const KITTY_STACK_CAP: usize = 16;
2109                if self.kitty_stack.len() >= KITTY_STACK_CAP {
2110                    self.kitty_stack.remove(0); // drop the oldest on overflow
2111                }
2112                self.kitty_stack.push(self.kitty_flags);
2113                self.kitty_flags = param_or(params, 0, 0) as u8;
2114            }
2115            // Pop `n` (default 1): restore from the stack, 0 once empty.
2116            b'<' => {
2117                for _ in 0..param_or(params, 0, 1) {
2118                    self.kitty_flags = self.kitty_stack.pop().unwrap_or(0);
2119                }
2120            }
2121            // Set in place (no push): mode 1 replace, 2 or-in, 3 and-not.
2122            b'=' => {
2123                let flags = param_or(params, 0, 0) as u8;
2124                self.kitty_flags = match param_or(params, 1, 1) {
2125                    1 => flags,
2126                    2 => self.kitty_flags | flags,
2127                    3 => self.kitty_flags & !flags,
2128                    _ => self.kitty_flags,
2129                };
2130            }
2131            _ => {}
2132        }
2133    }
2134
2135    /// DECRQM (CSI ? Ps $ p): report whether DEC private mode `Ps` is set —
2136    /// `CSI ? Ps ; val $ y` with val 1=set, 2=reset, 0=not recognized (#27).
2137    fn decrqm(&mut self, mode: u16) {
2138        let state = match mode {
2139            1 => Some(self.app_cursor_keys),
2140            // DECANM (#84): set = ANSI mode (the normal state), reset = VT52.
2141            2 => Some(!self.vt52_mode),
2142            6 => Some(self.origin_mode),
2143            // DECCOLM: derived from the actual width, never a tracked flag — a
2144            // flag would lie if the consumer ignored the resize request (#82).
2145            3 => Some(self.grid.cols() == 132),
2146            7 => Some(self.autowrap),
2147            45 => Some(self.reverse_wraparound),
2148            9 => Some(self.mouse_protocol == MouseProtocol::X10),
2149            66 => Some(self.application_keypad),
2150            12 => Some(self.cursor.blink),
2151            25 => Some(self.cursor.visible),
2152            // Mouse tracking is a single-state enum (the levels are mutually
2153            // exclusive — an app enables one), so querying ?1000 while ?1002 is
2154            // active reports "reset". Faithful to that model.
2155            1000 => Some(self.mouse_protocol == MouseProtocol::Normal),
2156            1002 => Some(self.mouse_protocol == MouseProtocol::ButtonEvent),
2157            1003 => Some(self.mouse_protocol == MouseProtocol::AnyEvent),
2158            1004 => Some(self.focus_events),
2159            1006 => Some(self.mouse_encoding == MouseEncoding::Sgr),
2160            1015 => Some(self.mouse_encoding == MouseEncoding::Urxvt),
2161            1005 => Some(self.mouse_encoding == MouseEncoding::Utf8),
2162            1016 => Some(self.mouse_encoding == MouseEncoding::SgrPixels),
2163            47 | 1047 | 1049 => Some(self.on_alt),
2164            2004 => Some(self.bracketed_paste),
2165            2026 => Some(self.synchronized_output),
2166            2027 => Some(self.grapheme_clustering),
2167            2031 => Some(self.color_scheme_updates),
2168            9001 => Some(self.win32_input_mode),
2169            _ => None,
2170        };
2171        let val = match state {
2172            Some(true) => 1,
2173            Some(false) => 2,
2174            None => 0,
2175        };
2176        self.replies
2177            .extend_from_slice(format!("\x1b[?{mode};{val}$y").as_bytes());
2178    }
2179
2180    /// Resolve a cell's `link` index (OSC 8) to its URI, or `None` if the index
2181    /// is out of range. The renderer reads `Cell.link`, then this, to make a
2182    /// cell clickable (#26).
2183    pub fn hyperlink(&self, link: core::num::NonZeroU32) -> Option<&str> {
2184        self.hyperlink_pool
2185            .get(link.get() as usize - 1)
2186            .map(String::as_str)
2187    }
2188
2189    // ---- cursor / scroll primitives ------------------------------------------
2190
2191    /// Move down one line. At the bottom margin, scroll the region instead;
2192    /// below the region, just descend (no scroll). Column is unchanged (raw LF;
2193    /// CR is what returns to column 0).
2194    fn linefeed(&mut self) {
2195        // New-line mode (LNM ?20): a line feed also returns to column 0 (#71).
2196        if self.newline_mode {
2197            self.carriage_return();
2198        }
2199        if self.cursor.row == self.scroll_bottom {
2200            // A top-anchored primary-screen scroll pushes the evicted top line
2201            // into scrollback history.
2202            if self.scroll_top == 0 && !self.on_alt {
2203                // Scrollback accrues whenever the scroll is top-anchored on the
2204                // primary screen (`scroll_top == 0`) — but the O(1) ring handshake
2205                // only applies to a *full-screen* scroll (`scroll_bottom` at the
2206                // last row). A top-anchored *sub-region* (`[0..k]`, k < rows-1)
2207                // still accrues, yet must scroll only its region, so it keeps the
2208                // copy + region scroll. These are distinct predicates (ADR-0009).
2209                let evicted = if self.scroll_bottom == self.grid.rows() - 1 {
2210                    // Full-screen hot path: move the evicted top row out, install
2211                    // a recycled blank as the new bottom (zero-alloc steady state).
2212                    let blank = self
2213                        .recycled_row
2214                        .take()
2215                        .unwrap_or_else(|| Row::from_cells(Vec::with_capacity(self.grid.cols())));
2216                    self.grid.scroll_up_recycle(blank)
2217                } else {
2218                    // Top-anchored sub-region: copy row 0, then region-scroll
2219                    // `[0..=scroll_bottom]` (rows below stay fixed).
2220                    let evicted = self.grid.row_owned(0);
2221                    self.grid
2222                        .scroll_up_region(self.scroll_top, self.scroll_bottom);
2223                    evicted
2224                };
2225                self.scrollback.push_back(evicted);
2226                // Follow-bottom = stay: if the user is scrolled up, bump the
2227                // offset so the same lines stay in view instead of being yanked
2228                // to the bottom.
2229                if self.display_offset > 0 {
2230                    self.display_offset = (self.display_offset + 1).min(self.scrollback.len());
2231                }
2232                // Cap: evict the oldest line past the limit. The view is anchored
2233                // to history, so dropping the front shifts the offset down too
2234                // (xterm.js trims ybase and ydisp together) — also keeps the
2235                // offset within `[0, len]`. The evicted row is parked for reuse.
2236                if self.scrollback.len() > self.scrollback_limit {
2237                    self.recycled_row = self.scrollback.pop_front();
2238                    // Every absolute index just shifted down by one; move the
2239                    // selection with it so its anchors keep their content.
2240                    self.selection_evict_oldest();
2241                    // Query-derived highlights can't survive the index shift (see
2242                    // the method doc); selection re-anchors, highlights invalidate.
2243                    self.invalidate_search_highlights();
2244                    // Markers are persistent anchors: shift them down with the
2245                    // index, disposing any whose line was the evicted one (#118).
2246                    self.markers_evict_oldest();
2247                    if self.display_offset > 0 {
2248                        // Scrolled up: evicting the oldest line advanced the
2249                        // viewport, so it must be repainted (the "frozen while
2250                        // scrolled" rule does not apply when the view itself moved).
2251                        self.display_offset -= 1;
2252                        self.mark_fully_damaged();
2253                    }
2254                }
2255            } else {
2256                // Region (top margin > 0) or alt-screen scroll: the evicted line
2257                // does NOT enter scrollback, so content moves *within* the screen
2258                // and absolute indices in the region shift. Rotate the selection
2259                // up so it follows; an endpoint on the dropped line clears it.
2260                let base = self.scrollback.len();
2261                self.selection_rotate_region(
2262                    base + self.scroll_top,
2263                    base + self.scroll_bottom,
2264                    true,
2265                );
2266                // Rotate the active buffer's markers with the content (#187):
2267                // per-buffer storage (#186) scopes them, so an alt scroll rotates
2268                // *alt* marks and leaves the frozen primary list untouched — no
2269                // guard needed. `markers_rotate_region` routes via `markers_mut`.
2270                self.markers_rotate_region(base + self.scroll_top, base + self.scroll_bottom, true);
2271                self.invalidate_search_highlights();
2272                self.grid
2273                    .scroll_up_region(self.scroll_top, self.scroll_bottom);
2274            }
2275            self.record_scroll(self.scroll_top, self.scroll_bottom, 1);
2276        } else if self.cursor.row + 1 < self.grid.rows() {
2277            self.cursor.row += 1;
2278        }
2279    }
2280
2281    /// DECSTBM (CSI r): set the top/bottom scroll margins (1-based inclusive).
2282    /// An invalid region (top ≥ bottom) is ignored.
2283    fn set_scroll_region(&mut self, top: usize, bottom: usize) {
2284        let bottom = bottom.min(self.grid.rows());
2285        if top >= bottom {
2286            return;
2287        }
2288        self.scroll_top = top - 1;
2289        self.scroll_bottom = bottom - 1;
2290        self.goto(0, 0); // DECSTBM homes the cursor (absolute)
2291    }
2292
2293    // ---- alt screen (DEC 1049) -----------------------------------------------
2294
2295    /// Enter the alternate screen: save the cursor, swap in the other grid, and
2296    /// clear it.
2297    /// Save the cursor into the alt-screen slot — `?1048` set, and the first
2298    /// half of `?1049` enter (#72).
2299    fn save_alt_cursor(&mut self) {
2300        self.saved_cursor = self.cursor;
2301    }
2302
2303    /// Restore the cursor from the alt-screen slot — `?1048` reset, and the
2304    /// second half of `?1049` leave. DECTCEM visibility is a standalone mode, not
2305    /// part of the save, so preserve it across the restore (#38/#72).
2306    fn restore_alt_cursor(&mut self) {
2307        let visible = self.cursor.visible;
2308        self.cursor = self.saved_cursor;
2309        self.cursor.visible = visible;
2310    }
2311
2312    /// Switch to the (cleared) alternate buffer without touching the cursor —
2313    /// `?47`/`?1047` set, and the second half of `?1049` enter (#72).
2314    fn switch_to_alt(&mut self) {
2315        if self.on_alt {
2316            return;
2317        }
2318        std::mem::swap(&mut self.grid, &mut self.alt_grid);
2319        self.grid.clear();
2320        self.on_alt = true;
2321        self.display_offset = 0; // the alt screen has no scrollback to view
2322        self.selection = None; // a selection cannot survive a screen swap
2323        self.invalidate_search_highlights(); // matches index the primary buffer
2324        self.mark_fully_damaged();
2325    }
2326
2327    /// Switch back to the primary buffer without touching the cursor —
2328    /// `?47`/`?1047` reset, and the first half of `?1049` leave (#72).
2329    fn switch_to_primary(&mut self) {
2330        if !self.on_alt {
2331            return;
2332        }
2333        // Dispose the alt buffer's markers on leave — xterm `activateNormalBuffer`
2334        // → `clearAllMarkers` (#177 S0). Empty while the alt guards stand, so this
2335        // fires nothing today; it's the seam the alt-marker slices (#187) build on.
2336        for m in self.alt_markers.drain(..) {
2337            self.events.push(TermEvent::MarkerDisposed(m.id));
2338        }
2339        std::mem::swap(&mut self.grid, &mut self.alt_grid);
2340        self.on_alt = false;
2341        self.display_offset = 0; // return to the primary at its bottom
2342        self.selection = None; // a selection cannot survive a screen swap
2343        self.invalidate_search_highlights(); // matches index the swapped-out buffer
2344        self.mark_fully_damaged();
2345    }
2346
2347    fn enter_alt_screen(&mut self) {
2348        if self.on_alt {
2349            return;
2350        }
2351        self.save_alt_cursor();
2352        self.switch_to_alt();
2353    }
2354
2355    /// Leave the alternate screen: swap the primary grid back in and restore the
2356    /// saved cursor.
2357    fn leave_alt_screen(&mut self) {
2358        if !self.on_alt {
2359            return;
2360        }
2361        self.switch_to_primary();
2362        self.restore_alt_cursor();
2363    }
2364
2365    /// RI (ESC M): move up one line. At the top margin, scroll the region down
2366    /// instead.
2367    fn reverse_index(&mut self) {
2368        if self.cursor.row == self.scroll_top {
2369            // RI never enters scrollback; the region scrolls down within the
2370            // screen, so absolute indices in it shift down. Rotate the selection.
2371            let base = self.scrollback.len();
2372            self.selection_rotate_region(base + self.scroll_top, base + self.scroll_bottom, false);
2373            // Rotate the active buffer's markers (#187) — alt-scoped on the alt
2374            // screen, so no guard (see `linefeed`).
2375            self.markers_rotate_region(base + self.scroll_top, base + self.scroll_bottom, false);
2376            self.invalidate_search_highlights();
2377            self.grid
2378                .scroll_down_region(self.scroll_top, self.scroll_bottom);
2379            self.record_scroll(self.scroll_top, self.scroll_bottom, -1);
2380        } else if self.cursor.row > 0 {
2381            self.cursor.row -= 1;
2382        }
2383    }
2384
2385    // ---- cursor save/restore (DECSC / DECRC) ---------------------------------
2386
2387    /// DECSC (ESC 7): save the cursor position, pen, pending-wrap, and origin
2388    /// mode. Visibility is not saved (DECTCEM is separate).
2389    fn save_cursor(&mut self) {
2390        self.decsc = SavedCursor {
2391            row: self.cursor.row,
2392            col: self.cursor.col,
2393            pen: self.cursor.pen,
2394            pending_wrap: self.cursor.pending_wrap,
2395            origin_mode: self.origin_mode,
2396            charsets: self.charsets,
2397            gl: self.gl,
2398        };
2399    }
2400
2401    /// DECRC (ESC 8): restore what DECSC saved. Origin mode is restored (per
2402    /// ADR-0004); visibility is left as-is. The position is clamped to the
2403    /// current screen in case it shrank since the save.
2404    fn restore_cursor(&mut self) {
2405        let s = self.decsc;
2406        self.cursor.row = s.row.min(self.grid.rows() - 1);
2407        self.cursor.col = s.col.min(self.grid.cols() - 1);
2408        self.cursor.pen = s.pen;
2409        self.cursor.pending_wrap = s.pending_wrap;
2410        self.origin_mode = s.origin_mode;
2411        self.charsets = s.charsets;
2412        self.gl = s.gl;
2413    }
2414
2415    /// RIS (ESC c) — full reset to the power-on state (#53). Reconstruct every
2416    /// screen/mode field to its construction default (preserving only the
2417    /// dimensions and the scrollback cap), but keep the consumer-bound output
2418    /// queues (`replies`/`events`) that accrued earlier in this `feed`, and
2419    /// signal a full repaint. The vte parser lives outside `Term`, so replacing
2420    /// `self` does not disturb in-progress parsing. Mirrors xterm.js fullReset.
2421    fn full_reset(&mut self) {
2422        let replies = std::mem::take(&mut self.replies);
2423        let mut events = std::mem::take(&mut self.events);
2424        // RIS wipes the buffer, so every marker's line is gone — announce each
2425        // disposal so the consumer drops its decorations (and isn't confused when
2426        // the reset id counter reissues the same ids). The events survive the
2427        // reset below (#118).
2428        events.extend(
2429            self.normal_markers
2430                .iter()
2431                .chain(&self.alt_markers)
2432                .map(|m| TermEvent::MarkerDisposed(m.id)),
2433        );
2434        let (cols, rows) = (self.grid.cols(), self.grid.rows());
2435        *self = Term::with_scrollback(cols, rows, self.scrollback_limit);
2436        self.replies = replies;
2437        self.events = events;
2438        self.mark_fully_damaged();
2439    }
2440
2441    /// DECSTR (CSI ! p) — soft reset (#53). Resets a defined subset of modes to
2442    /// their defaults *without* destroying screen content or scrollback, moving
2443    /// the active cursor, or touching the mouse/focus reporting subsystem. Per
2444    /// xterm.js softReset, autowrap returns to ON (the xterm default), not off.
2445    fn soft_reset(&mut self) {
2446        self.cursor.visible = true;
2447        self.cursor.pen = Pen::default();
2448        self.scroll_top = 0;
2449        self.scroll_bottom = self.grid.rows() - 1;
2450        self.origin_mode = false;
2451        self.app_cursor_keys = false;
2452        self.bracketed_paste = false;
2453        self.grapheme_clustering = false; // ?2027 back to the wcwidth-compat default (#295)
2454        self.autowrap = true; // xterm default is ON (not the VT100 "off")
2455        self.insert_mode = false;
2456        self.charsets = [Charset::Ascii; 4];
2457        self.gl = 0;
2458        self.decsc = SavedCursor::default();
2459    }
2460
2461    fn carriage_return(&mut self) {
2462        self.cursor.col = 0;
2463        self.cursor.pending_wrap = false;
2464    }
2465
2466    /// DECSCUSR (CSI Ps SP q): set the caret shape + blink (#89). 0/2 = steady
2467    /// block, 1 = blinking block; 3/4 = blinking/steady underline; 5/6 =
2468    /// blinking/steady bar (odd = blink). 0 resets to the default (steady block).
2469    /// An unknown param leaves the style unchanged. Mirrors xterm.js.
2470    fn set_cursor_style(&mut self, param: u16) {
2471        let (shape, blink) = match param {
2472            0 | 2 => (CursorShape::Block, false),
2473            1 => (CursorShape::Block, true),
2474            3 => (CursorShape::Underline, true),
2475            4 => (CursorShape::Underline, false),
2476            5 => (CursorShape::Bar, true),
2477            6 => (CursorShape::Bar, false),
2478            _ => return,
2479        };
2480        self.cursor.shape = shape;
2481        self.cursor.blink = blink;
2482    }
2483
2484    /// Backspace (BS, 0x08): move the cursor one column left. With reverse
2485    /// wraparound (?45) a backspace at column 0 of a *soft-wrapped* row moves
2486    /// back to the last column of the previous row — undoing one autowrap. Only
2487    /// soft wraps reverse (the previous row carries `WRAPLINE`); a hard CR/LF
2488    /// line does not. BS only (not cursor-left), matching xterm.js (#80).
2489    fn backspace(&mut self) {
2490        self.cursor.pending_wrap = false;
2491        if self.cursor.col > 0 {
2492            self.cursor.col -= 1;
2493            return;
2494        }
2495        if self.reverse_wraparound
2496            && self.cursor.row > self.scroll_top
2497            && self.cursor.row <= self.scroll_bottom
2498        {
2499            let prev = self.cursor.row - 1;
2500            let last = self.grid.cols() - 1;
2501            if self.grid.cell(prev, last).is_wrapline() {
2502                self.grid
2503                    .cell_mut(prev, last)
2504                    .remove_flags(CellFlags::WRAPLINE);
2505                self.cursor.row = prev;
2506                self.cursor.col = last;
2507            }
2508        }
2509    }
2510
2511    /// Auto-wrap at end of line: line-feed then return to column 0.
2512    fn wrapline(&mut self) {
2513        self.linefeed();
2514        self.cursor.col = 0;
2515        self.cursor.pending_wrap = false;
2516    }
2517
2518    // ---- tab stops (HT / HTS / TBC) ------------------------------------------
2519
2520    /// HT: advance to the next set tab stop, or the last column if none remain
2521    /// (no wrap).
2522    fn put_tab(&mut self) {
2523        let cols = self.grid.cols();
2524        let mut col = self.cursor.col;
2525        while col + 1 < cols {
2526            col += 1;
2527            if self.tabs[col] {
2528                break;
2529            }
2530        }
2531        self.cursor.col = col;
2532        self.cursor.pending_wrap = false;
2533    }
2534
2535    /// HTS (ESC H): set a tab stop at the cursor column.
2536    fn set_tab_stop(&mut self) {
2537        let col = self.cursor.col;
2538        self.tabs[col] = true;
2539    }
2540
2541    /// TBC (CSI g): clear the tab stop at the cursor (mode 0) or all stops
2542    /// (mode 3).
2543    fn clear_tab_stop(&mut self, mode: u16) {
2544        match mode {
2545            0 => {
2546                let col = self.cursor.col;
2547                self.tabs[col] = false;
2548            }
2549            3 => self.tabs.iter_mut().for_each(|t| *t = false),
2550            _ => {}
2551        }
2552    }
2553
2554    // ---- printing ------------------------------------------------------------
2555
2556    /// Write one glyph at the cursor, handling deferred wrap and the wide-char
2557    /// spacer, then advance the cursor (deferring the wrap if it hits the edge).
2558    fn write_glyph(&mut self, c: char, width: usize) {
2559        let cols = self.grid.cols();
2560
2561        // Resolve a deferred last-column wrap before placing the next glyph.
2562        // The row being left soft-wrapped: mark its last cell so reflow (#7) can
2563        // tell it from a hard CR/LF line-end.
2564        if self.cursor.pending_wrap {
2565            let row = self.cursor.row;
2566            self.grid
2567                .cell_mut(row, cols - 1)
2568                .insert_flags(CellFlags::WRAPLINE);
2569            self.wrapline();
2570        }
2571
2572        // A width-2 glyph that cannot fit in the last column wraps first — unless
2573        // autowrap is off, in which case it is dropped (xterm.js `continue`), not
2574        // squeezed or wrapped.
2575        if width == 2 && self.cursor.col + 1 >= cols {
2576            if !self.autowrap {
2577                return;
2578            }
2579            // Mark the row soft-wrapped, like the pending-wrap path above: the
2580            // vacated last column is a continuation, not a hard line-end. Search,
2581            // logical lines (#113), and reflow (#7) all read WRAPLINE for the join.
2582            // Also tag it a leading spacer so the text extractors skip the blank
2583            // (xterm's LEADING_WIDE_CHAR_SPACER) instead of joining "ab한"→"ab 한".
2584            let vacated = self.grid.cell_mut(self.cursor.row, cols - 1);
2585            vacated.insert_flags(CellFlags::WRAPLINE);
2586            vacated.set_leading_spacer();
2587            self.wrapline();
2588        }
2589
2590        // Insert mode (IRM): open a `width`-wide gap at the cursor first, shifting
2591        // the row's tail right (off-edge cells discarded, wide halves repaired),
2592        // then write into the gap — mirrors xterm.js's insertCells (#64).
2593        if self.insert_mode {
2594            self.insert_chars(width);
2595        }
2596
2597        let (row, col) = (self.cursor.row, self.cursor.col);
2598
2599        // Overwriting one half of an existing wide glyph orphans the other —
2600        // clear it so no stray lead/spacer is left behind.
2601        let last = col + width - 1;
2602        if col > 0 && self.grid.cell(row, col).is_wide_spacer() {
2603            self.grid.cell_mut(row, col - 1).reset();
2604        }
2605        if last + 1 < cols && self.grid.cell(row, last).is_wide() {
2606            self.grid.cell_mut(row, last + 1).reset();
2607        }
2608
2609        let mut cell = self.cursor.pen.cell(c);
2610        if width == 2 {
2611            cell.insert_flags(CellFlags::WIDE_CHAR);
2612        }
2613        *self.grid.cell_mut(row, col) = cell;
2614        // Stamp the open hyperlink, if any, into the row's link map (#26/#46).
2615        if let Some(link) = self.current_link {
2616            self.grid.row_mut(row).set_link(col, link);
2617        }
2618
2619        // The trailing column of a wide glyph carries a distinct spacer marker —
2620        // and the same link, so a hover/selection over either half agrees.
2621        if width == 2 && col + 1 < cols {
2622            let mut spacer = self.cursor.pen.cell(' ');
2623            spacer.insert_flags(CellFlags::WIDE_CHAR_SPACER);
2624            *self.grid.cell_mut(row, col + 1) = spacer;
2625            if let Some(link) = self.current_link {
2626                self.grid.row_mut(row).set_link(col + 1, link);
2627            }
2628        }
2629
2630        // Record damage for the cell(s) just written.
2631        self.damage_span(row, col, col + width - 1);
2632
2633        // Advance. Reaching/passing the last column sets pending-wrap instead of
2634        // wrapping eagerly — the cursor parks on the last column.
2635        let new_col = col + width;
2636        if new_col >= cols {
2637            self.cursor.col = cols - 1;
2638            // With autowrap off (DECAWM ?7l) the cursor pins to the last column
2639            // and the next glyph overwrites in place — no deferred wrap (#63).
2640            self.cursor.pending_wrap = self.autowrap;
2641        } else {
2642            self.cursor.col = new_col;
2643        }
2644    }
2645
2646    /// Attach a combining mark (width-0 code point) to the grapheme it modifies —
2647    /// the cell the cursor just left. With pending-wrap the cursor still sits on
2648    /// the just-written last-column glyph, so attach in place (no back-up, no
2649    /// deferred wrap); otherwise step back one column, and once more over a
2650    /// wide-char spacer to reach its lead. Stored in the grapheme side-table.
2651    fn push_combining(&mut self, c: char) {
2652        let row = self.cursor.row;
2653        let mut col = if self.cursor.pending_wrap {
2654            self.cursor.col
2655        } else {
2656            self.cursor.col.saturating_sub(1)
2657        };
2658        if self.grid.cell(row, col).is_wide_spacer() {
2659            col = col.saturating_sub(1);
2660        }
2661        // Append the mark to the row's combining map at this column (setting the
2662        // cell's combining bit). No global pool — the cluster rides the row.
2663        self.grid.row_mut(row).push_combining(col, c);
2664        self.damage_span(row, col, col);
2665    }
2666
2667    /// Mode 2027 (#295): if `c` **extends** the previous cell's grapheme cluster (UAX #29), append
2668    /// it to that cell's side-table — no new cell, no cursor advance — and return `true`. Otherwise
2669    /// return `false` so `print` takes the normal per-scalar path (a break starts a new cell).
2670    ///
2671    /// The break state is reconstructed fresh from the previous cell's stored cluster (base scalar +
2672    /// side-table marks) rather than persisted across calls, so cursor moves / CR-LF can't corrupt
2673    /// it (mirrors ghostty). Width promotion for a narrow base (a flag's second RI, a text-base +
2674    /// VS16) is handled by the caller in a later step; here the base's existing width holds.
2675    fn try_grapheme_join(&mut self, c: char) -> bool {
2676        let row = self.cursor.row;
2677        // Locate the previous cluster's base cell, exactly as `push_combining`: with pending-wrap
2678        // the cursor still sits on the last glyph; else step back one, and over a wide spacer.
2679        let col = if self.cursor.pending_wrap {
2680            self.cursor.col
2681        } else if self.cursor.col == 0 {
2682            return false; // nothing precedes on this row
2683        } else {
2684            self.cursor.col - 1
2685        };
2686        let col = if self.grid.cell(row, col).is_wide_spacer() {
2687            col.saturating_sub(1)
2688        } else {
2689            col
2690        };
2691        // Reconstruct the previous cluster's text: base scalar + any already-joined scalars.
2692        let mut prev = String::new();
2693        prev.push(self.grid.cell(row, col).c());
2694        if let Some(marks) = self.grid.row_ref(row).combining_at(col) {
2695            prev.extend(marks.iter().copied());
2696        }
2697        if !crate::grapheme::grapheme_extends(&prev, c) {
2698            return false;
2699        }
2700        // Join: ride the side-table (no new cell).
2701        self.grid.row_mut(row).push_combining(col, c);
2702        // Width promotion: a flag's second regional indicator, or a text-base + VS16, grows the
2703        // cluster to width 2. `UnicodeWidthStr` gives the cluster width (RI-pair → 2, VS16 → 2). If
2704        // the base cell is still narrow, widen it in place.
2705        let cluster_w = {
2706            prev.push(c);
2707            UnicodeWidthStr::width(prev.as_str())
2708        };
2709        if cluster_w == 2 && !self.grid.cell(row, col).is_wide() {
2710            self.promote_cluster_to_wide(row, col);
2711        } else if cluster_w == 1 && self.grid.cell(row, col).is_wide() {
2712            // The mirror case: a default-wide emoji + VS15 (text selector) shrinks to width 1.
2713            self.demote_cluster_to_narrow(row, col);
2714        }
2715        self.damage_span(row, col, col);
2716        true
2717    }
2718
2719    /// Shrink a wide cluster cell back to a single-width cell (#295): a default-wide emoji joined by
2720    /// VS15 (U+FE0E, the text selector) requests text presentation → width 1. Remove `WIDE_CHAR`,
2721    /// free the spacer, and back the cursor up over it (the inverse of `promote_cluster_to_wide`).
2722    fn demote_cluster_to_narrow(&mut self, row: usize, col: usize) {
2723        let cols = self.grid.cols();
2724        self.grid
2725            .cell_mut(row, col)
2726            .remove_flags(CellFlags::WIDE_CHAR);
2727        if col + 1 < cols {
2728            self.grid.cell_mut(row, col + 1).reset(); // free the now-unused spacer
2729        }
2730        // The cluster shrank 2→1: the cursor sat just past the wide cell (col+2, or pending-wrap on
2731        // the last column); it now sits just past the single-width cell at col+1.
2732        self.cursor.pending_wrap = false;
2733        self.cursor.col = (col + 1).min(cols - 1);
2734        self.damage_span(row, col, (col + 1).min(cols - 1));
2735    }
2736
2737    /// Widen a narrow base cell to a double-width cluster in place (#295): set `WIDE_CHAR`, write
2738    /// its spacer, and step the cursor over it. Only reached when a joining scalar (flag's 2nd RI,
2739    /// VS16) promotes the cluster to width 2. A base pinned at the last column has no room for a
2740    /// spacer — relocation is a later step; until then it stays narrow (rare, renders single-width).
2741    fn promote_cluster_to_wide(&mut self, row: usize, col: usize) {
2742        let cols = self.grid.cols();
2743        if col + 1 >= cols {
2744            // No spacer room at the last column: relocate the whole cluster to the next line as a
2745            // wide cell (the row soft-wraps), mirroring write_glyph's wide-at-boundary wrap (#303).
2746            self.relocate_cluster_wide(row, col);
2747            return;
2748        }
2749        // Overwriting col+1 with the spacer can orphan the far half of a WIDE glyph standing there
2750        // (the cursor may have been repositioned before the joining scalar arrived). Reset that
2751        // orphan, exactly as write_glyph does (2462-2470), so no dangling spacer survives.
2752        if self.grid.cell(row, col + 1).is_wide() && col + 2 < cols {
2753            self.grid.cell_mut(row, col + 2).reset();
2754        }
2755        self.grid
2756            .cell_mut(row, col)
2757            .insert_flags(CellFlags::WIDE_CHAR);
2758        let mut spacer = self.cursor.pen.cell(' ');
2759        spacer.insert_flags(CellFlags::WIDE_CHAR_SPACER);
2760        *self.grid.cell_mut(row, col + 1) = spacer;
2761        // The cursor sat at col+1 (just past the narrow base); move it over the new spacer, applying
2762        // the same last-column pending-wrap rule as a wide write.
2763        let new_col = col + 2;
2764        if new_col >= cols {
2765            self.cursor.col = cols - 1;
2766            self.cursor.pending_wrap = self.autowrap;
2767        } else {
2768            self.cursor.col = new_col;
2769        }
2770        self.damage_span(row, col, col + 1);
2771    }
2772
2773    /// Relocate a last-column narrow cluster to the next line as a wide cell (#303): its base +
2774    /// side-table marks move to `(next_row, 0..=1)` and the vacated last column becomes a soft-wrap
2775    /// (WRAPLINE + leading spacer), exactly as `write_glyph` wraps a wide glyph that can't fit. With
2776    /// autowrap off, or a 1-column screen (no room for a wide cell anywhere), it stays narrow.
2777    fn relocate_cluster_wide(&mut self, row: usize, col: usize) {
2778        let cols = self.grid.cols();
2779        if cols < 2 || !self.autowrap {
2780            return; // nowhere to place a wide cell — leave it narrow
2781        }
2782        // Capture the base cell (glyph + attrs) and its marks before vacating.
2783        let base = *self.grid.cell(row, col);
2784        let marks: Vec<char> = self
2785            .combining_at(row, col)
2786            .map(<[char]>::to_vec)
2787            .unwrap_or_default();
2788        // Vacate the last column as a soft-wrap leading spacer (mirrors write_glyph 2457-2459).
2789        // reset() clears the base's combining bit, so its stale marks entry is never read again.
2790        let vacated = self.grid.cell_mut(row, col);
2791        vacated.reset();
2792        vacated.insert_flags(CellFlags::WRAPLINE);
2793        vacated.set_leading_spacer();
2794        self.damage_span(row, col, col);
2795        // Advance to the next line (scrolls if at the bottom); cursor lands at col 0.
2796        self.wrapline();
2797        let nr = self.cursor.row;
2798        // Re-place the base as a wide lead + spacer, re-attaching the marks fresh (drop the combining
2799        // bit so push_combining starts a clean cluster at the new column).
2800        let mut lead = base;
2801        lead.set_combined(false);
2802        lead.insert_flags(CellFlags::WIDE_CHAR);
2803        *self.grid.cell_mut(nr, 0) = lead;
2804        for m in marks {
2805            self.grid.row_mut(nr).push_combining(0, m);
2806        }
2807        let mut spacer = self.cursor.pen.cell(' ');
2808        spacer.insert_flags(CellFlags::WIDE_CHAR_SPACER);
2809        *self.grid.cell_mut(nr, 1) = spacer;
2810        // Cursor just past the wide cell (pending-wrap if it fills a 2-column row).
2811        if cols <= 2 {
2812            self.cursor.col = cols - 1;
2813            self.cursor.pending_wrap = self.autowrap;
2814        } else {
2815            self.cursor.col = 2;
2816            self.cursor.pending_wrap = false;
2817        }
2818        self.damage_span(nr, 0, 1);
2819    }
2820
2821    // ---- cursor movement (CSI A/B/C/D/G/d/H/f) -------------------------------
2822
2823    fn move_up(&mut self, n: usize) {
2824        self.cursor.row = self.cursor.row.saturating_sub(n);
2825        self.cursor.pending_wrap = false;
2826    }
2827
2828    fn move_down(&mut self, n: usize) {
2829        self.cursor.row = (self.cursor.row + n).min(self.grid.rows() - 1);
2830        self.cursor.pending_wrap = false;
2831    }
2832
2833    fn move_forward(&mut self, n: usize) {
2834        self.cursor.col = (self.cursor.col + n).min(self.grid.cols() - 1);
2835        self.cursor.pending_wrap = false;
2836    }
2837
2838    fn move_back(&mut self, n: usize) {
2839        self.cursor.col = self.cursor.col.saturating_sub(n);
2840        self.cursor.pending_wrap = false;
2841    }
2842
2843    fn set_col(&mut self, col: usize) {
2844        self.cursor.col = col.min(self.grid.cols() - 1);
2845        self.cursor.pending_wrap = false;
2846    }
2847
2848    fn set_row(&mut self, row: usize) {
2849        self.cursor.row = row.min(self.grid.rows() - 1);
2850        self.cursor.pending_wrap = false;
2851    }
2852
2853    fn goto(&mut self, row: usize, col: usize) {
2854        // Origin mode addresses rows relative to the scroll region's top margin
2855        // and clamps to its bottom; otherwise rows are absolute to the screen.
2856        let (offset, max_row) = if self.origin_mode {
2857            (self.scroll_top, self.scroll_bottom)
2858        } else {
2859            (0, self.grid.rows() - 1)
2860        };
2861        self.cursor.row = (row + offset).min(max_row);
2862        self.cursor.col = col.min(self.grid.cols() - 1);
2863        self.cursor.pending_wrap = false;
2864    }
2865
2866    // ---- erase (CSI J / K) ---------------------------------------------------
2867
2868    /// Clear cells `from..to` on `row`.
2869    ///
2870    /// Background Color Erase (BCE): erased cells carry the current SGR
2871    /// background only — fg and text attributes reset to default (matches
2872    /// xterm/alacritty, where the fill is `cursor.template.bg.into()`).
2873    fn clear_cells(&mut self, row: usize, from: usize, to: usize) {
2874        let cols = self.grid.cols();
2875        // Don't orphan a wide char straddling the erase boundary.
2876        if from > 0 && self.grid.cell(row, from).is_wide_spacer() {
2877            self.grid.cell_mut(row, from - 1).reset();
2878        }
2879        if to > from && to < cols && self.grid.cell(row, to - 1).is_wide() {
2880            self.grid.cell_mut(row, to).reset();
2881        }
2882
2883        let bg = self.cursor.pen.bg;
2884        for col in from..to {
2885            let cell = self.grid.cell_mut(row, col);
2886            cell.reset();
2887            cell.set_bg(bg);
2888        }
2889        if to > from {
2890            self.damage_span(row, from, to - 1);
2891        }
2892    }
2893
2894    /// Erase in display (ED): 0 = cursor→end, 1 = start→cursor, 2 = all.
2895    fn erase_display(&mut self, mode: u16) {
2896        let (cols, rows) = (self.grid.cols(), self.grid.rows());
2897        let (cr, cc) = (self.cursor.row, self.cursor.col);
2898        match mode {
2899            0 => {
2900                self.clear_cells(cr, cc, cols);
2901                for row in (cr + 1)..rows {
2902                    self.clear_cells(row, 0, cols);
2903                }
2904            }
2905            1 => {
2906                for row in 0..cr {
2907                    self.clear_cells(row, 0, cols);
2908                }
2909                self.clear_cells(cr, 0, cc + 1);
2910            }
2911            2 => {
2912                for row in 0..rows {
2913                    self.clear_cells(row, 0, cols);
2914                }
2915            }
2916            _ => {}
2917        }
2918    }
2919
2920    /// Erase in line (EL): 0 = cursor→end, 1 = start→cursor, 2 = whole line.
2921    fn erase_line(&mut self, mode: u16) {
2922        let cols = self.grid.cols();
2923        let (cr, cc) = (self.cursor.row, self.cursor.col);
2924        match mode {
2925            0 => self.clear_cells(cr, cc, cols),
2926            1 => self.clear_cells(cr, 0, cc + 1),
2927            2 => self.clear_cells(cr, 0, cols),
2928            _ => {}
2929        }
2930    }
2931
2932    // ---- intra-line editing (ICH / DCH / ECH) --------------------------------
2933
2934    /// ECH (CSI Pn X): erase `n` cells in place from the cursor — no shift.
2935    /// BCE-filled (via `clear_cells`); pending-wrap is left untouched.
2936    fn erase_chars(&mut self, n: usize) {
2937        let cols = self.grid.cols();
2938        let (row, col) = (self.cursor.row, self.cursor.col);
2939        let to = (col + n).min(cols);
2940        self.clear_cells(row, col, to);
2941    }
2942
2943    /// ICH (CSI Pn @): insert `n` blanks at the cursor, shifting the rest of the
2944    /// line right; cells pushed past the right edge are lost. The opened gap is
2945    /// BCE-filled; pending-wrap is left untouched.
2946    fn insert_chars(&mut self, n: usize) {
2947        let cols = self.grid.cols();
2948        let (r, col) = (self.cursor.row, self.cursor.col);
2949        let n = n.min(cols - col);
2950        if n == 0 {
2951            return;
2952        }
2953        let bg = self.cursor.pen.bg;
2954        let row = self.grid.row_mut(r);
2955        // Shift [col .. cols-n) right by n; the tail falls off the edge. The
2956        // combining map follows the moved cells (the bit travels with the raw
2957        // copy, the cluster data must too).
2958        row.copy_within(col..cols - n, col + n);
2959        row.move_maps(col..cols - n, col + n);
2960        for cell in &mut row[col..col + n] {
2961            cell.reset();
2962            cell.set_bg(bg);
2963        }
2964        // Repair wide-char halves split at the seams (no-orphan invariant):
2965        // a lead just before the gap lost its spacer; the first shifted cell may
2966        // be a spacer whose lead did not move.
2967        if col > 0 && self.grid.cell(r, col - 1).is_wide() {
2968            self.grid.cell_mut(r, col - 1).reset();
2969        }
2970        if col + n < cols && self.grid.cell(r, col + n).is_wide_spacer() {
2971            self.grid.cell_mut(r, col + n).reset();
2972        }
2973        // A lead shifted to the last column lost its spacer off the edge.
2974        if self.grid.cell(r, cols - 1).is_wide() {
2975            self.grid.cell_mut(r, cols - 1).reset();
2976        }
2977        self.damage_span(r, col, cols - 1);
2978    }
2979
2980    /// DCH (CSI Pn P): delete `n` cells at the cursor, shifting the tail left; the
2981    /// vacated cells at the right are BCE-blanked. Pending-wrap is left untouched.
2982    fn delete_chars(&mut self, n: usize) {
2983        let cols = self.grid.cols();
2984        let (r, col) = (self.cursor.row, self.cursor.col);
2985        let n = n.min(cols - col);
2986        if n == 0 {
2987            return;
2988        }
2989        let bg = self.cursor.pen.bg;
2990        let row = self.grid.row_mut(r);
2991        // Shift [col+n .. cols) left to [col ..); BCE-fill the vacated tail. The
2992        // combining map follows the moved cells.
2993        row.copy_within(col + n..cols, col);
2994        row.move_maps(col + n..cols, col);
2995        for cell in &mut row[cols - n..cols] {
2996            cell.reset();
2997            cell.set_bg(bg);
2998        }
2999        // Repair wide-char halves split by the deletion (no-orphan invariant):
3000        // a lead just before the cut lost its spacer; the cell now at the cursor
3001        // may be a spacer whose lead was deleted.
3002        if col > 0 && self.grid.cell(r, col - 1).is_wide() {
3003            self.grid.cell_mut(r, col - 1).reset();
3004        }
3005        if self.grid.cell(r, col).is_wide_spacer() {
3006            self.grid.cell_mut(r, col).reset();
3007        }
3008        self.damage_span(r, col, cols - 1);
3009    }
3010
3011    // ---- line/region editing (IL / DL / SU / SD) -----------------------------
3012
3013    /// Scroll rows `[top..=bottom]` by `n` lines, BCE-filling the exposed lines.
3014    /// `down` inserts blanks at the top (content moves down); otherwise content
3015    /// moves up and blanks appear at the bottom. Reuses the one-line region scroll
3016    /// primitives (so damage + scroll-op accumulation come for free), then fills
3017    /// the exposed lines with the current SGR background.
3018    fn scroll_region_lines(&mut self, top: usize, bottom: usize, n: usize, down: bool) {
3019        let height = bottom - top + 1;
3020        let n = n.min(height);
3021        if n == 0 {
3022            return;
3023        }
3024        // Anchors (selection #3, markers #118/#158) live at absolute buffer lines;
3025        // SU/SD/IL/DL don't accrue scrollback, so `base` is stable across the loop.
3026        let base = self.scrollback.len();
3027        for _ in 0..n {
3028            if down {
3029                self.grid.scroll_down_region(top, bottom);
3030                self.record_scroll(top, bottom, -1);
3031            } else {
3032                self.grid.scroll_up_region(top, bottom);
3033                self.record_scroll(top, bottom, 1);
3034            }
3035            // Rotate anchors with the content, like `linefeed`/`reverse_index`
3036            // (#162). `up` = content moved up = the non-`down` case. Markers rotate
3037            // with the active buffer (#187) — alt-scoped on the alt screen, so no
3038            // guard; the selection is cleared on alt enter.
3039            self.selection_rotate_region(base + top, base + bottom, !down);
3040            self.markers_rotate_region(base + top, base + bottom, !down);
3041        }
3042        self.invalidate_search_highlights();
3043        // BCE-fill the n exposed lines (the primitives blank to default).
3044        let bg = self.cursor.pen.bg;
3045        let (fill_top, fill_end) = if down {
3046            (top, top + n)
3047        } else {
3048            (bottom + 1 - n, bottom + 1)
3049        };
3050        let cols = self.grid.cols();
3051        for r in fill_top..fill_end {
3052            for c in 0..cols {
3053                let cell = self.grid.cell_mut(r, c);
3054                cell.reset();
3055                cell.set_bg(bg);
3056            }
3057        }
3058    }
3059
3060    /// SU (CSI Pn S): scroll the scroll region up by `n`.
3061    fn scroll_up_lines(&mut self, n: usize) {
3062        self.scroll_region_lines(self.scroll_top, self.scroll_bottom, n, false);
3063    }
3064
3065    /// SD (CSI Pn T): scroll the scroll region down by `n`.
3066    fn scroll_down_lines(&mut self, n: usize) {
3067        self.scroll_region_lines(self.scroll_top, self.scroll_bottom, n, true);
3068    }
3069
3070    /// IL (CSI Pn L): insert `n` blank lines at the cursor, scrolling
3071    /// `[cursor..=scroll_bottom]` down. A no-op when the cursor is outside the
3072    /// scroll region.
3073    fn insert_lines(&mut self, n: usize) {
3074        let cur = self.cursor.row;
3075        if cur < self.scroll_top || cur > self.scroll_bottom {
3076            return;
3077        }
3078        self.scroll_region_lines(cur, self.scroll_bottom, n, true);
3079    }
3080
3081    /// DL (CSI Pn M): delete `n` lines at the cursor, scrolling
3082    /// `[cursor..=scroll_bottom]` up. A no-op when the cursor is outside the
3083    /// scroll region.
3084    fn delete_lines(&mut self, n: usize) {
3085        let cur = self.cursor.row;
3086        if cur < self.scroll_top || cur > self.scroll_bottom {
3087            return;
3088        }
3089        self.scroll_region_lines(cur, self.scroll_bottom, n, false);
3090    }
3091
3092    // ---- SGR (CSI m) ---------------------------------------------------------
3093
3094    fn sgr(&mut self, params: &Params) {
3095        let pen = &mut self.cursor.pen;
3096        let mut iter = params.iter();
3097        while let Some(param) = iter.next() {
3098            let code = param.first().copied().unwrap_or(0);
3099            match code {
3100                0 => pen.reset(),
3101                1 => pen.flags.insert(CellFlags::BOLD),
3102                2 => pen.flags.insert(CellFlags::DIM),
3103                3 => pen.flags.insert(CellFlags::ITALIC),
3104                4 => pen.flags.insert(CellFlags::UNDERLINE),
3105                5 => pen.flags.insert(CellFlags::BLINK),
3106                7 => pen.flags.insert(CellFlags::INVERSE),
3107                8 => pen.flags.insert(CellFlags::HIDDEN),
3108                9 => pen.flags.insert(CellFlags::STRIKETHROUGH),
3109                22 => pen.flags.remove(CellFlags::BOLD | CellFlags::DIM),
3110                23 => pen.flags.remove(CellFlags::ITALIC),
3111                24 => pen.flags.remove(CellFlags::UNDERLINE),
3112                25 => pen.flags.remove(CellFlags::BLINK),
3113                27 => pen.flags.remove(CellFlags::INVERSE),
3114                28 => pen.flags.remove(CellFlags::HIDDEN),
3115                29 => pen.flags.remove(CellFlags::STRIKETHROUGH),
3116                30..=37 => pen.fg = Color::Indexed((code - 30) as u8),
3117                38 => {
3118                    if let Some(c) = parse_extended_color(param, &mut iter) {
3119                        pen.fg = c;
3120                    }
3121                }
3122                39 => pen.fg = Color::Default,
3123                40..=47 => pen.bg = Color::Indexed((code - 40) as u8),
3124                48 => {
3125                    if let Some(c) = parse_extended_color(param, &mut iter) {
3126                        pen.bg = c;
3127                    }
3128                }
3129                49 => pen.bg = Color::Default,
3130                // bright foreground/background (aixterm) → palette 8..=15.
3131                90..=97 => pen.fg = Color::Indexed((code - 90 + 8) as u8),
3132                100..=107 => pen.bg = Color::Indexed((code - 100 + 8) as u8),
3133                _ => {}
3134            }
3135        }
3136    }
3137}
3138
3139/// Parse `38`/`48` extended colour, in either form:
3140/// - sub-parameter (colon) form inline in `param`: `38:5:n`, `38:2:r:g:b`
3141///   (optionally `38:2:cs:r:g:b` with a colorspace id), or
3142/// - legacy (semicolon) form: pull the following top-level params from `iter`.
3143fn parse_extended_color<'a, I>(param: &[u16], iter: &mut I) -> Option<Color>
3144where
3145    I: Iterator<Item = &'a [u16]>,
3146{
3147    if param.len() > 1 {
3148        // Colon sub-parameter form: kind is param[1].
3149        match param[1] {
3150            2 => {
3151                // 38:2:r:g:b (len 5) or 38:2:cs:r:g:b (len 6, colorspace skipped).
3152                let off = if param.len() >= 6 { 3 } else { 2 };
3153                let r = *param.get(off)? as u8;
3154                let g = *param.get(off + 1)? as u8;
3155                let b = *param.get(off + 2)? as u8;
3156                Some(Color::Rgb(r, g, b))
3157            }
3158            5 => Some(Color::Indexed(*param.get(2)? as u8)),
3159            _ => None,
3160        }
3161    } else {
3162        // Legacy semicolon form: kind, then its operands, are separate params.
3163        match iter.next()?.first().copied()? {
3164            2 => {
3165                let r = iter.next()?.first().copied()? as u8;
3166                let g = iter.next()?.first().copied()? as u8;
3167                let b = iter.next()?.first().copied()? as u8;
3168                Some(Color::Rgb(r, g, b))
3169            }
3170            5 => Some(Color::Indexed(iter.next()?.first().copied()? as u8)),
3171            _ => None,
3172        }
3173    }
3174}
3175
3176/// Reflow one screen (joined with its `scrollback`) to `cols` x `rows`, tracking
3177/// `point` (a cursor in screen coordinates). Returns the new screen rows, the new
3178/// scrollback (capped to `limit`), and the new point. The alt screen passes an
3179/// empty scrollback and discards the returned one.
3180/// The fixed dimensions a resize reflows toward.
3181#[derive(Clone, Copy)]
3182struct ReflowDims {
3183    old_cols: usize,
3184    cols: usize,
3185    rows: usize,
3186    limit: usize,
3187}
3188
3189/// The result of reflowing one pane.
3190struct PaneReflow {
3191    screen: Vec<Row>,
3192    scrollback: VecDeque<Row>,
3193    /// The cursor's new screen-relative position.
3194    cursor: (usize, usize),
3195    /// Each tracked extra point's new **absolute** position, index-aligned with
3196    /// the `extra_abs` argument.
3197    extras: Vec<(usize, usize)>,
3198}
3199
3200/// Reflow one pane (its `scrollback` joined with `screen`) to `dims`, tracking
3201/// the screen-relative cursor `point` plus any `extra_abs` points given in
3202/// **absolute** `[scrollback ++ screen]` coordinates (selection anchors).
3203fn reflow_pane(
3204    screen: Vec<Row>,
3205    scrollback: VecDeque<Row>,
3206    point: (usize, usize),
3207    extra_abs: &[(usize, usize)],
3208    dims: ReflowDims,
3209) -> PaneReflow {
3210    let scroll_len = scrollback.len();
3211    let mut all: Vec<Row> = scrollback.into();
3212    all.extend(screen);
3213
3214    // The cursor is screen-relative; lift it to absolute, then track it together
3215    // with the already-absolute extras.
3216    let mut pts: Vec<(usize, usize)> = Vec::with_capacity(1 + extra_abs.len());
3217    pts.push((scroll_len + point.0, point.1));
3218    pts.extend_from_slice(extra_abs);
3219
3220    let pts = if dims.cols != dims.old_cols {
3221        let (reflowed, np) = crate::grid::reflow(all, dims.cols, &pts);
3222        all = reflowed;
3223        np
3224    } else {
3225        pts
3226    };
3227
3228    let split = all.len().saturating_sub(dims.rows);
3229    let history: Vec<Row> = all.drain(0..split).collect();
3230    let mut sb: VecDeque<Row> = history.into();
3231    let mut dropped = 0usize;
3232    while sb.len() > dims.limit {
3233        sb.pop_front();
3234        dropped += 1;
3235    }
3236
3237    // The cursor returns to screen-relative (its absolute index minus the
3238    // history split). The extras stay absolute, shifted down by any lines the
3239    // cap dropped from the front of history.
3240    PaneReflow {
3241        cursor: (pts[0].0.saturating_sub(split), pts[0].1),
3242        extras: pts[1..]
3243            .iter()
3244            .map(|&(l, c)| (l.saturating_sub(dropped), c))
3245            .collect(),
3246        screen: all,
3247        scrollback: sb,
3248    }
3249}
3250
3251/// Whether `c` ends a word for Word (semantic) selection. Whitespace plus a
3252/// punctuation set mirroring Alacritty's default `semantic_escape_chars`, so
3253/// path/URL-ish runs (`.`, `/`, `-`) stay one word.
3254fn is_word_boundary(c: char) -> bool {
3255    c.is_whitespace() || ",│`|:\"'()[]{}<>".contains(c)
3256}
3257
3258/// Whether the run `hay[i..i+len]` is bounded by non-word characters on both sides — the `\bword\b`
3259/// sense for whole-word search (#314). A word char is alphanumeric or `_` (the regex `\w` set),
3260/// deliberately distinct from `is_word_boundary`'s wider semantic-selection set.
3261fn word_bounded(hay: &[char], i: usize, len: usize) -> bool {
3262    // A word char is alphanumeric, `_`, OR a grapheme-extending mark (width 0: combining marks,
3263    // ZWJ, variation selectors) — so a mark attached to a base is never read as a word boundary,
3264    // matching the regex `\b` sense (`\w` includes `\p{M}`) and staying consistent across the
3265    // literal and regex paths on decomposed graphemes (#314 Lens 1).
3266    let is_word = |c: char| c.is_alphanumeric() || c == '_' || c.width() == Some(0);
3267    let left = i == 0 || !is_word(hay[i - 1]);
3268    let right = i + len == hay.len() || !is_word(hay[i + len]);
3269    left && right
3270}
3271
3272/// Default tab stops: one every 8 columns (incl. column 0), matching xterm.
3273fn default_tabs(cols: usize) -> Vec<bool> {
3274    (0..cols).map(|i| i % 8 == 0).collect()
3275}
3276
3277/// First sub-parameter of CSI param `idx`, or `default` when absent or zero
3278/// (a zero/omitted numeric param means "1" for cursor movement and "0" for
3279/// erase — callers pass the right default).
3280fn param_or(params: &Params, idx: usize, default: u16) -> u16 {
3281    match params.iter().nth(idx).and_then(|p| p.first().copied()) {
3282        Some(v) if v != 0 => v,
3283        _ => default,
3284    }
3285}
3286
3287impl Term {
3288    /// Apply one DEC private mode set (`'h'`) or reset (`'l'`). DECSET/DECRST
3289    /// carry a list of modes, so `csi_dispatch` folds this over every parameter
3290    /// (#56); each mode is an independent toggle, not a stack.
3291    fn set_dec_private_mode(&mut self, action: char, mode: u16) {
3292        match (action, mode) {
3293            ('h', 1049) => self.enter_alt_screen(),
3294            ('l', 1049) => self.leave_alt_screen(),
3295            // Legacy alt-screen variants (#72): ?47/?1047 switch the buffer
3296            // without saving the cursor; ?1048 saves/restores the cursor without
3297            // switching. ?1049 is the two combined.
3298            ('h', 47) | ('h', 1047) => self.switch_to_alt(),
3299            ('l', 47) | ('l', 1047) => self.switch_to_primary(),
3300            ('h', 1048) => self.save_alt_cursor(),
3301            ('l', 1048) => self.restore_alt_cursor(),
3302            ('h', 6) => {
3303                // DECOM: set homes the cursor to the region top.
3304                self.origin_mode = true;
3305                self.goto(0, 0);
3306            }
3307            ('l', 6) => self.origin_mode = false, // unset leaves the cursor put
3308            ('h', 7) => self.autowrap = true,     // DECAWM
3309            ('l', 7) => self.autowrap = false,
3310            ('h', 45) => self.reverse_wraparound = true, // reverse wraparound (#80)
3311            ('l', 45) => self.reverse_wraparound = false,
3312            // DECCOLM (#82): the engine is dimension-free, so emit a request the
3313            // consumer may honor by resizing — no screen/cursor/margin change here.
3314            ('h', 3) => self.events.push(TermEvent::ColumnMode { cols: 132 }),
3315            ('l', 3) => self.events.push(TermEvent::ColumnMode { cols: 80 }),
3316            ('h', 25) => self.cursor.visible = true, // DECTCEM show
3317            ('l', 25) => self.cursor.visible = false, // DECTCEM hide
3318            ('h', 12) => self.cursor.blink = true,   // att610 cursor blink (#81)
3319            ('l', 12) => self.cursor.blink = false,
3320            ('h', 2004) => self.bracketed_paste = true,
3321            ('l', 2004) => self.bracketed_paste = false,
3322            ('h', 2026) => self.synchronized_output = true, // synchronized output (#73)
3323            ('l', 2026) => self.synchronized_output = false,
3324            ('h', 2027) => self.grapheme_clustering = true, // grapheme-cluster mode (#295)
3325            ('l', 2027) => self.grapheme_clustering = false,
3326            ('h', 2031) => self.color_scheme_updates = true, // color-scheme notifications (#85)
3327            ('l', 2031) => self.color_scheme_updates = false,
3328            ('h', 9001) => self.win32_input_mode = true, // win32-input-mode (#86)
3329            ('l', 9001) => self.win32_input_mode = false,
3330
3331            // Input-encoding modes (#11): DECCKM, mouse tracking + encoding,
3332            // focus reporting. Each set assigns the level; each reset clears
3333            // it (apps enable/disable the same mode, not a stack).
3334            ('h', 1) => self.app_cursor_keys = true, // DECCKM
3335            ('l', 1) => self.app_cursor_keys = false,
3336            ('h', 66) => self.application_keypad = true, // DECNKM (#74)
3337            ('l', 66) => self.application_keypad = false,
3338            // DECANM (#84): set = ANSI (the normal state); reset enters VT52. Only
3339            // the reset is meaningful — `?2h` is a no-op (already ANSI).
3340            ('l', 2) => self.vt52_mode = true,
3341            ('h', 9) => self.mouse_protocol = MouseProtocol::X10, // X10 mouse (#70)
3342            ('h', 1000) => self.mouse_protocol = MouseProtocol::Normal,
3343            ('h', 1002) => self.mouse_protocol = MouseProtocol::ButtonEvent,
3344            ('h', 1003) => self.mouse_protocol = MouseProtocol::AnyEvent,
3345            ('l', 9) | ('l', 1000) | ('l', 1002) | ('l', 1003) => {
3346                self.mouse_protocol = MouseProtocol::Off
3347            }
3348            ('h', 1006) => self.mouse_encoding = MouseEncoding::Sgr,
3349            ('l', 1006) => self.mouse_encoding = MouseEncoding::Default,
3350            ('h', 1015) => self.mouse_encoding = MouseEncoding::Urxvt,
3351            ('l', 1015) => self.mouse_encoding = MouseEncoding::Default,
3352            ('h', 1005) => self.mouse_encoding = MouseEncoding::Utf8,
3353            ('l', 1005) => self.mouse_encoding = MouseEncoding::Default,
3354            ('h', 1016) => self.mouse_encoding = MouseEncoding::SgrPixels,
3355            ('l', 1016) => self.mouse_encoding = MouseEncoding::Default,
3356            ('h', 1004) => self.focus_events = true,
3357            ('l', 1004) => self.focus_events = false,
3358
3359            _ => {} // other DEC modes are later slices
3360        }
3361    }
3362
3363    /// Dispatch one VT52 escape sequence (`ESC <final>`), reached only while
3364    /// `vt52_mode` is set (#84). VT52 is a pre-ANSI dialect: the cursor/erase
3365    /// finals map to the same `Term` primitives the ANSI path uses. `ESC <`
3366    /// returns to ANSI. Unknown finals are ignored.
3367    fn vt52_dispatch(&mut self, byte: u8) {
3368        match byte {
3369            b'A' => self.move_up(1),         // cursor up
3370            b'B' => self.move_down(1),       // cursor down
3371            b'C' => self.move_forward(1),    // cursor right
3372            b'D' => self.move_back(1),       // cursor left
3373            b'H' => self.goto(0, 0),         // cursor home
3374            b'I' => self.reverse_index(),    // reverse line feed
3375            b'J' => self.erase_display(0),   // erase cursor → end of screen
3376            b'K' => self.erase_line(0),      // erase cursor → end of line
3377            b'Y' => self.vt52_y_pending = 2, // direct address: two coord bytes follow
3378            // Identify (DECID): reply `ESC / Z` — "I am a VT52".
3379            b'Z' => self.replies.extend_from_slice(b"\x1b/Z"),
3380            b'=' => self.application_keypad = true, // enter alternate keypad
3381            b'>' => self.application_keypad = false, // exit alternate keypad
3382            b'<' => self.vt52_mode = false,         // exit VT52, return to ANSI
3383            // RIS (`ESC c`) is honored even here: it is a hard "recover from any
3384            // state" reset, and `full_reset` rebuilds `Term` with `vt52_mode`
3385            // cleared, so RIS always escapes VT52 back to ANSI. VT52 defines no
3386            // other meaning for `ESC c`.
3387            b'c' => self.full_reset(),
3388            // Graphics mode (`ESC F`/`ESC G`) is a documented non-goal: the VT52
3389            // graphics glyph set differs from DEC Special Graphics, so reusing that
3390            // charset would render the wrong glyphs. No-op rather than approximate.
3391            b'F' | b'G' => {}
3392            _ => {} // unknown VT52 finals are ignored
3393        }
3394    }
3395
3396    /// Consume one `ESC Y` coordinate byte (#84). The first byte is the row, the
3397    /// second the column; each decodes as `value - 0x20`. On the second byte the
3398    /// cursor is addressed (`goto` clamps out-of-range coordinates). Reached only
3399    /// from `print` while `vt52_y_pending > 0`.
3400    fn vt52_take_coord(&mut self, c: char) {
3401        let coord = (c as usize).saturating_sub(0x20);
3402        if self.vt52_y_pending == 2 {
3403            self.vt52_y_row = coord;
3404            self.vt52_y_pending = 1;
3405        } else {
3406            self.vt52_y_pending = 0;
3407            self.goto(self.vt52_y_row, coord);
3408        }
3409    }
3410}
3411
3412impl Perform for Term {
3413    fn print(&mut self, c: char) {
3414        // VT52 `ESC Y` direct addressing (#84): vte delivers the two coordinate
3415        // bytes here (it returned to ground after the `Y` final), so intercept
3416        // them before they would be written as glyphs.
3417        if self.vt52_y_pending > 0 {
3418            self.vt52_take_coord(c);
3419            return;
3420        }
3421        // Translate through the active (GL) character set first (#62): under DEC
3422        // Special Graphics a printable byte becomes a line-drawing glyph.
3423        let c = self.charsets[self.gl].map(c);
3424        // Grapheme-cluster mode (DEC ?2027, #295): if `c` extends the previous cell's cluster,
3425        // join it there instead of placing a new cell. OFF → the per-char (wcwidth) path below.
3426        if self.grapheme_clustering && self.try_grapheme_join(c) {
3427            return;
3428        }
3429        match c.width() {
3430            // Zero-width (combining marks): the grapheme-cluster side-table is a
3431            // later slice; drop for now rather than mis-place it as its own cell.
3432            // A zero-width code point is a combining mark — attach it to the
3433            // previous base glyph rather than dropping it.
3434            Some(0) => self.push_combining(c),
3435            None => {}
3436            Some(width) => self.write_glyph(c, width),
3437        }
3438    }
3439
3440    fn execute(&mut self, byte: u8) {
3441        match byte {
3442            // LF, VT, FF all line-feed.
3443            b'\n' | 0x0b | 0x0c => self.linefeed(),
3444            b'\r' => self.carriage_return(),
3445            0x08 => self.backspace(),
3446            b'\t' => self.put_tab(),
3447            0x07 => self.events.push(TermEvent::Bell), // BEL (#12)
3448            0x0e => self.gl = 1,                       // SO (LS1): GL = G1 (#62)
3449            0x0f => self.gl = 0,                       // SI (LS0): GL = G0
3450            _ => {}
3451        }
3452    }
3453
3454    fn csi_dispatch(&mut self, params: &Params, intermediates: &[u8], _ignore: bool, action: char) {
3455        // Kitty keyboard-protocol negotiation: CSI > / = / < / ? ... u. The
3456        // leading intermediate distinguishes it from plain `CSI u` (SCORC) (#23).
3457        if action == 'u'
3458            && let Some(&lead) = intermediates.first()
3459            && matches!(lead, b'>' | b'<' | b'=' | b'?')
3460        {
3461            self.kitty_dispatch(lead, params);
3462            return;
3463        }
3464        // DEC private modes arrive with a '?' intermediate.
3465        if intermediates.first() == Some(&b'?') {
3466            // DECRQM (CSI ? Ps $ p) — report whether mode Ps is set. The '$'
3467            // intermediate distinguishes it from a plain `?...p`. It queries a
3468            // single mode, so it keys off the first parameter only.
3469            if action == 'p' && intermediates.contains(&b'$') {
3470                self.decrqm(param_or(params, 0, 0));
3471                return;
3472            }
3473            // Private DSR (CSI ? Ps n): ?996 = color-scheme query (#85). The
3474            // theme-agnostic engine relays it as an event for the consumer.
3475            if action == 'n' {
3476                if param_or(params, 0, 0) == 996 {
3477                    self.events.push(TermEvent::ColorSchemeQuery);
3478                }
3479                return;
3480            }
3481            // DECSET/DECRST carry a *list* of modes; apply set/reset to EVERY
3482            // parameter, not just the first — htop batches `?1006;1000h` into one
3483            // CSI, so folding only params[0] dropped the 1000 (#56).
3484            for mode in params.iter().filter_map(|p| p.first().copied()) {
3485                self.set_dec_private_mode(action, mode);
3486            }
3487            return;
3488        }
3489        // DECSTR soft reset: CSI ! p (#53).
3490        if intermediates.first() == Some(&b'!') && action == 'p' {
3491            self.soft_reset();
3492            return;
3493        }
3494        // DECSCUSR set cursor style: CSI Ps SP q (space intermediate) (#89). An
3495        // absent param means 1 (block blink); an explicit 0 means reset — so the
3496        // raw value matters and `param_or` (which folds 0 to its default) is wrong.
3497        if intermediates.first() == Some(&b' ') && action == 'q' {
3498            let param = params.iter().next().and_then(|p| p.first().copied());
3499            self.set_cursor_style(param.unwrap_or(1));
3500            return;
3501        }
3502        // Other private/intermediate sequences are later slices; ignore them
3503        // rather than misinterpret.
3504        if !intermediates.is_empty() {
3505            return;
3506        }
3507        match action {
3508            'A' => self.move_up(param_or(params, 0, 1) as usize),
3509            'B' | 'e' => self.move_down(param_or(params, 0, 1) as usize),
3510            'C' | 'a' => self.move_forward(param_or(params, 0, 1) as usize),
3511            'D' => self.move_back(param_or(params, 0, 1) as usize),
3512            'G' | '`' => self.set_col(param_or(params, 0, 1) as usize - 1),
3513            'd' => self.set_row(param_or(params, 0, 1) as usize - 1),
3514            'H' | 'f' => {
3515                let row = param_or(params, 0, 1) as usize - 1;
3516                let col = param_or(params, 1, 1) as usize - 1;
3517                self.goto(row, col);
3518            }
3519            'J' => self.erase_display(param_or(params, 0, 0)),
3520            'K' => self.erase_line(param_or(params, 0, 0)),
3521            'X' => self.erase_chars(param_or(params, 0, 1) as usize),
3522            '@' => self.insert_chars(param_or(params, 0, 1) as usize),
3523            'P' => self.delete_chars(param_or(params, 0, 1) as usize),
3524            'S' => self.scroll_up_lines(param_or(params, 0, 1) as usize),
3525            'T' => self.scroll_down_lines(param_or(params, 0, 1) as usize),
3526            'L' => self.insert_lines(param_or(params, 0, 1) as usize),
3527            'M' => self.delete_lines(param_or(params, 0, 1) as usize),
3528            'g' => self.clear_tab_stop(param_or(params, 0, 0)),
3529            'r' => {
3530                let rows = self.grid.rows() as u16;
3531                let top = param_or(params, 0, 1) as usize;
3532                let bottom = param_or(params, 1, rows) as usize;
3533                self.set_scroll_region(top, bottom);
3534            }
3535            'm' => self.sgr(params),
3536            's' => self.save_cursor(),    // SCOSC (CSI s) — alias of DECSC
3537            'u' => self.restore_cursor(), // SCORC (CSI u) — alias of DECRC
3538            // DA1 (primary device attributes, CSI c): advertise VT220 + ANSI
3539            // colour — the levels justerm actually implements (#27).
3540            'c' => self.replies.extend_from_slice(b"\x1b[?62;22c"),
3541            'n' => self.device_status_report(param_or(params, 0, 0)),
3542            // Non-private SM/RM. Folded over every parameter (modes can batch,
3543            // like the private path #56). IRM (4) and LNM (20) so far.
3544            'h' => {
3545                for m in params.iter().filter_map(|p| p.first().copied()) {
3546                    match m {
3547                        4 => self.insert_mode = true,
3548                        20 => self.newline_mode = true,
3549                        _ => {}
3550                    }
3551                }
3552            }
3553            'l' => {
3554                for m in params.iter().filter_map(|p| p.first().copied()) {
3555                    match m {
3556                        4 => self.insert_mode = false,
3557                        20 => self.newline_mode = false,
3558                        _ => {}
3559                    }
3560                }
3561            }
3562            _ => {}
3563        }
3564    }
3565
3566    fn esc_dispatch(&mut self, intermediates: &[u8], _ignore: bool, byte: u8) {
3567        // VT52 mode (#84): the pre-ANSI dialect reuses the same `ESC <final>`
3568        // tokens vte already produces, but with different meanings, so it is a
3569        // mode-gated branch here rather than a separate parser. All VT52 sequences
3570        // are intermediate-free; anything with an intermediate is not VT52.
3571        if self.vt52_mode && intermediates.is_empty() {
3572            self.vt52_dispatch(byte);
3573            return;
3574        }
3575        if let Some(&i) = intermediates.first() {
3576            // SCS: designate a charset to G0 (`ESC ( F`) or G1 (`ESC ) F`) (#62).
3577            if matches!(i, b'(' | b')') {
3578                let set = match byte {
3579                    b'0' => Charset::DecSpecialGraphics,
3580                    b'A' => Charset::Uk,
3581                    b'B' => Charset::Ascii,
3582                    _ => return, // other sets are later slices
3583                };
3584                self.charsets[if i == b'(' { 0 } else { 1 }] = set;
3585            }
3586            // Other intermediates (G2/G3 designators, etc.) are later slices.
3587            return;
3588        }
3589        match byte {
3590            b'D' => self.linefeed(), // IND (line-feed without CR)
3591            b'E' => {
3592                // NEL (next line): carriage return + line-feed.
3593                self.carriage_return();
3594                self.linefeed();
3595            }
3596            b'H' => self.set_tab_stop(),             // HTS
3597            b'M' => self.reverse_index(),            // RI
3598            b'7' => self.save_cursor(),              // DECSC
3599            b'8' => self.restore_cursor(),           // DECRC
3600            b'c' => self.full_reset(),               // RIS (#53)
3601            b'=' => self.application_keypad = true,  // DECKPAM (#74)
3602            b'>' => self.application_keypad = false, // DECKPNM
3603            _ => {}
3604        }
3605    }
3606
3607    /// OSC dispatch (#12 event surface): title (0/2), cwd (7). OSC 8 hyperlink
3608    /// is per-cell state, handled in its own slice (#26), not here.
3609    fn osc_dispatch(&mut self, params: &[&[u8]], _bell_terminated: bool) {
3610        // params[0] is the OSC number; params[1..] the payload fields.
3611        let Some(&number) = params.first() else {
3612            return;
3613        };
3614        match number {
3615            // OSC 0 = icon + window title, OSC 2 = window title. Both set title.
3616            b"0" | b"2" => {
3617                if let Some(&title) = params.get(1) {
3618                    self.events.push(TermEvent::Title(
3619                        String::from_utf8_lossy(title).into_owned(),
3620                    ));
3621                }
3622            }
3623            // OSC 7 = current working directory (a file:// URI).
3624            b"7" => {
3625                if let Some(&cwd) = params.get(1) {
3626                    self.events
3627                        .push(TermEvent::Cwd(String::from_utf8_lossy(cwd).into_owned()));
3628                }
3629            }
3630            // OSC 133 = FinalTerm/iTerm2 shell-integration command marks (#158):
3631            // `A` prompt start, `B` command start, `C` output start, `D[;exit]`
3632            // command finished. Each anchors a kinded marker at the cursor line;
3633            // pairing + navigation is consumer policy (#160). Unknown subcommands
3634            // (or none) are ignored. `D`'s exit field parses to `i32`, else None.
3635            b"133" => match params.get(1).copied() {
3636                Some(b"A") => self.add_command_mark(MarkerKind::PromptStart),
3637                Some(b"B") => self.add_command_mark(MarkerKind::CommandStart),
3638                Some(b"C") => self.add_command_mark(MarkerKind::OutputStart),
3639                Some(b"D") => {
3640                    let exit = params
3641                        .get(2)
3642                        .and_then(|p| core::str::from_utf8(p).ok())
3643                        .and_then(|s| s.parse::<i32>().ok());
3644                    self.add_command_mark(MarkerKind::CommandFinished(exit));
3645                }
3646                _ => {}
3647            },
3648            // OSC 8 = hyperlink: `OSC 8 ; params ; URI`. A non-empty URI opens a
3649            // link (interned + made current); an empty URI closes it. `params`
3650            // (e.g. `id=…`) is ignored for now — id-grouping is a later refinement.
3651            b"8" => {
3652                let uri = params.get(2).copied().unwrap_or(b"");
3653                if uri.is_empty() {
3654                    self.current_link = None;
3655                } else {
3656                    self.hyperlink_pool
3657                        .push(String::from_utf8_lossy(uri).into_owned());
3658                    self.current_link =
3659                        core::num::NonZeroU32::new(self.hyperlink_pool.len() as u32);
3660                }
3661            }
3662            // OSC 4 = set/query an ANSI palette entry: `OSC 4 ; index ; spec`
3663            // (#122). The engine forwards index + raw spec; the consumer applies
3664            // it to its palette (theme-agnostic — the cell keeps `Indexed`).
3665            b"4" => {
3666                // One event per `index ; spec` pair (xterm's `while slots > 1`).
3667                let mut rest = &params[1..];
3668                while let [idx, spec, tail @ ..] = rest {
3669                    rest = tail;
3670                    if let Ok(index) = String::from_utf8_lossy(idx).parse::<u8>() {
3671                        if *spec == b"?" {
3672                            self.events.push(TermEvent::QueryPaletteColor { index });
3673                        } else {
3674                            self.events.push(TermEvent::SetPaletteColor {
3675                                index,
3676                                spec: String::from_utf8_lossy(spec).into_owned(),
3677                            });
3678                        }
3679                    }
3680                }
3681            }
3682            // OSC 104 = reset palette entries (#122): no arg resets the whole
3683            // table, else one event per named index.
3684            b"104" => {
3685                if params.len() <= 1 {
3686                    self.events.push(TermEvent::ResetPaletteColor(None));
3687                } else {
3688                    for &idx in &params[1..] {
3689                        if let Ok(index) = String::from_utf8_lossy(idx).parse::<u8>() {
3690                            self.events.push(TermEvent::ResetPaletteColor(Some(index)));
3691                        }
3692                    }
3693                }
3694            }
3695            // OSC 10/11 = set/query the default foreground/background, stacking
3696            // specs across the [fg, bg] slots (#122, #137). OSC 10 starts at fg,
3697            // OSC 11 at bg. The engine forwards raw specs (theme-agnostic).
3698            b"10" => self.special_color(params, 0),
3699            b"11" => self.special_color(params, 1),
3700            // OSC 110 / 111 = reset the default foreground / background (#122).
3701            b"110" => self.events.push(TermEvent::ResetForeground),
3702            b"111" => self.events.push(TermEvent::ResetBackground),
3703            _ => {} // other OSCs are later slices
3704        }
3705    }
3706}