Skip to main content

justerm_core/term/
selection.rs

1//! The selection surface: the gesture entry points, the three fixups that keep an
2//! anchor pointing at its content while the buffer moves under it, and two text
3//! extractors — `selection_text` for the selected run, and `accessible_text`, which
4//! reads the *active* buffer as one document (floored on the alt screen, like every
5//! other absolute walk) and lives here only because it reuses the same extraction path,
6//! not because it is a selection.
7//!
8//! The coordinate model — absolute `[scrollback ++ screen]` line indices, why they
9//! survive an ordinary scroll, and the three places they do not — is stated in
10//! [`crate::selection`]. Read it there; this module is the `Term` half of it.
11//!
12//! What is local to this site is the shape of that `Term` half. Three fixups
13//! (`selection_shift_below_margin`, `selection_evict_oldest`, `selection_rotate_region`)
14//! are `pub(super)` because the write path calls them from `term.rs` — each one beside
15//! its decoration-marker counterpart, since both are absolute anchors and a buffer
16//! motion moves them together. That pairing was weighed as a reason to merge the two
17//! surfaces into one module and rejected in #584; the grounds and the counter-evidence
18//! are recorded there, not re-argued here.
19//!
20//! `resolve` and `Resolved` stay private: every caller travelled into this module with
21//! them. The remaining entry points are public API and keep `pub fn` — an inherent
22//! impl's methods are reached through the type, not the module path, so a private child
23//! module does not hide them.
24
25use crate::selection::{Anchor, Selection, SelectionSpan, SelectionType, Side};
26
27use super::Term;
28
29/// A selection resolved to absolute-coordinate bounds, ready for text extraction
30/// or viewport-span projection. Columns are half-open (`from..to`).
31enum Resolved {
32    /// Char/Word/Line: a run that joins soft-wrapped rows. Columns apply to the
33    /// first/last line; middle lines are whole.
34    Linear {
35        start_line: usize,
36        from: usize,
37        end_line: usize,
38        to: usize,
39    },
40    /// Block: a rectangle — the same `from..to` columns on every row.
41    Block {
42        line0: usize,
43        line1: usize,
44        from: usize,
45        to: usize,
46    },
47}
48
49impl Term {
50    /// Begin a selection of `ty` at viewport `(row, col)`, `side`.
51    pub fn selection_begin(&mut self, row: usize, col: usize, side: Side, ty: SelectionType) {
52        let anchor = Anchor {
53            point: self.viewport_to_abs(row, col),
54            side,
55        };
56        self.selection = Some(Selection {
57            ty,
58            anchor,
59            focus: anchor,
60        });
61    }
62
63    /// Extend the live selection's focus to viewport `(row, col)`, `side`.
64    pub fn selection_extend(&mut self, row: usize, col: usize, side: Side) {
65        let focus = Anchor {
66            point: self.viewport_to_abs(row, col),
67            side,
68        };
69        if let Some(sel) = &mut self.selection {
70            sel.focus = focus;
71        }
72    }
73
74    /// Clear the selection.
75    pub fn selection_clear(&mut self) {
76        self.selection = None;
77    }
78
79    /// Shift selection endpoints anchored at absolute line `>= from` down by
80    /// one (#449): a top-anchored sub-region scroll grew scrollback while the
81    /// rows below the margin stayed fixed on screen, so their content's
82    /// absolute index rose +1 and the anchors must follow it. Endpoints above
83    /// `from` (in-region / scrollback content, whose indices are stable) are
84    /// untouched — per endpoint, so a selection straddling the margin keeps
85    /// both ends on their content.
86    pub(super) fn selection_shift_below_margin(&mut self, from: usize) {
87        if let Some(sel) = &mut self.selection {
88            if sel.anchor.point.line >= from {
89                sel.anchor.point.line += 1;
90            }
91            if sel.focus.point.line >= from {
92                sel.focus.point.line += 1;
93            }
94        }
95    }
96
97    /// Shift the selection up by one absolute line after the oldest history line
98    /// is evicted by the scrollback cap. An endpoint clamps to the new top; if
99    /// the whole selection was on the evicted line, it is cleared.
100    pub(super) fn selection_evict_oldest(&mut self) {
101        let Some((a, f)) = self
102            .selection
103            .as_ref()
104            .map(|s| (s.anchor.point.line, s.focus.point.line))
105        else {
106            return;
107        };
108        if a == 0 && f == 0 {
109            self.selection = None;
110            return;
111        }
112        if let Some(sel) = &mut self.selection {
113            sel.anchor.point.line = a.saturating_sub(1);
114            sel.focus.point.line = f.saturating_sub(1);
115        }
116    }
117
118    /// Rotate the selection within an in-screen scroll of absolute lines
119    /// `[top, bottom]`. `up` = content scrolled up (a line dropped at `top`);
120    /// otherwise down (dropped at `bottom`). Called once per scrolled line (delta
121    /// 1) by linefeed/RI/SU/SD/IL/DL.
122    ///
123    /// Mirrors alacritty `Selection::rotate`: an endpoint pushed past the region
124    /// edge is *clamped* to that edge (upper → `top`/col 0/Left, lower →
125    /// `bottom`/last col/Right; columns/side kept for Block), preserving the part
126    /// of the selection still in the buffer. The whole selection clears only on a
127    /// true *overtake* — the upper endpoint crossing the bottom while the lower
128    /// stays inside, or the lower falling above the upper (a selection wholly on
129    /// the dropped line). (#174: this replaced a policy that cleared on any
130    /// endpoint touching the dropped edge, dropping still-valid content.)
131    pub(super) fn selection_rotate_region(&mut self, top: usize, bottom: usize, up: bool) {
132        let (ty, anchor, focus) = match self.selection.as_ref() {
133            Some(s) => (s.ty, s.anchor, s.focus),
134            None => return,
135        };
136        let last_col = self.grid.cols().saturating_sub(1);
137        // Order the endpoints by buffer position; the upper (`start`) clamps to
138        // the region top, the lower (`end`) to the bottom. Remember which is the
139        // anchor so the result writes back to the right field.
140        let anchor_is_start = anchor.point <= focus.point;
141        let (mut start, mut end) = if anchor_is_start {
142            (anchor, focus)
143        } else {
144            (focus, anchor)
145        };
146
147        let (top_i, bottom_i) = (top as isize, bottom as isize);
148        // The endpoint's line after the one-line scroll, or `None` if it's outside
149        // the region (untouched). The dropped-edge line shifts *past* the edge (to
150        // be clamped/overtaken below), matching alacritty's `line - delta`.
151        let shift = |line: usize| -> Option<isize> {
152            if line < top || line > bottom {
153                None
154            } else if up {
155                Some(line as isize - 1)
156            } else {
157                Some(line as isize + 1)
158            }
159        };
160
161        // Upper endpoint: clamp to the region top when pushed above it; clear if it
162        // overtook the region bottom (down-scroll) while the lower stays inside.
163        if let Some(nl) = shift(start.point.line) {
164            if nl > bottom_i && (end.point.line as isize) <= bottom_i {
165                self.selection = None;
166                return;
167            }
168            if nl < top_i {
169                start.point.line = top;
170                if ty != SelectionType::Block {
171                    start.point.col = 0;
172                    start.side = Side::Left;
173                }
174            } else {
175                start.point.line = nl as usize;
176            }
177        }
178        // Lower endpoint: clear if it fell above the (rotated) upper endpoint;
179        // else clamp to the region bottom when pushed below it.
180        if let Some(nl) = shift(end.point.line) {
181            if nl < start.point.line as isize {
182                self.selection = None;
183                return;
184            }
185            if nl > bottom_i {
186                end.point.line = bottom;
187                if ty != SelectionType::Block {
188                    end.point.col = last_col;
189                    end.side = Side::Right;
190                }
191            } else {
192                end.point.line = nl as usize;
193            }
194        }
195
196        if let Some(sel) = &mut self.selection {
197            if anchor_is_start {
198                (sel.anchor, sel.focus) = (start, end);
199            } else {
200                (sel.anchor, sel.focus) = (end, start);
201            }
202        }
203    }
204
205    /// The selection projected onto the current viewport: one inclusive-column
206    /// span per visible row. Rows scrolled off-screen (above or below) are
207    /// dropped. Empty when nothing is selected. See `SelectionSpan`.
208    pub fn selection_range(&self) -> Vec<SelectionSpan> {
209        let Some(resolved) = self.resolve() else {
210            return Vec::new();
211        };
212        let rows = self.grid.rows();
213        // Absolute index of viewport row 0.
214        let top = self.scrollback.len() - self.display_offset;
215        let mut spans = Vec::new();
216
217        // Add a span for absolute `line` with inclusive cols `left..=right`, if
218        // the line is currently visible.
219        let mut push = |line: usize, left: usize, right: usize| {
220            if line >= top {
221                let row = line - top;
222                if row < rows {
223                    spans.push(SelectionSpan { row, left, right });
224                }
225            }
226        };
227
228        match resolved {
229            Resolved::Linear {
230                start_line,
231                from,
232                end_line,
233                to,
234            } => {
235                for line in start_line..=end_line {
236                    // Bound before reading, not after (#660). `abs_line` indexes the grid
237                    // unguarded, so a line past the last visible row panics here — and the
238                    // `push` closure below, which does apply the bound, never gets to run.
239                    // The sibling projection already has this ordering right:
240                    // `Term::match_spans` (`term/search.rs`) does `if row >= rows { break }`
241                    // *before* its own `abs_line`, so this loop was the local outlier.
242                    //
243                    // This is not a clamp and truncates nothing observable: the function
244                    // already drops off-screen rows silently and says so ("Empty when … the
245                    // selection is fully scrolled off-screen"), so making the existing
246                    // filter total converts a panic into the drop the contract promises.
247                    // All three references bound at read time too — alacritty's
248                    // `Selection::to_range` goes through `grid_clamp`, xterm.js's
249                    // `translateBufferLineToString` returns `''` for a missing line, and
250                    // ghostty clamps a pin's column against its own page.
251                    //
252                    // **Unreachable as this crate stands, and that is recorded rather than
253                    // enjoyed.** With the anchor clamped at `viewport_to_abs` and the alt
254                    // drop in `resize`, no path is known that reaches this loop with a line
255                    // past the last row — measured: removing this bound reds no test in the
256                    // suite. It is kept for the reason the `right - left + 1` widening in
257                    // `serialize.rs` is kept (#582): it costs nothing, it makes the function
258                    // total on its own rather than by trusting a guard two files away, and
259                    // the walk it protects is one careless edit from an out-of-bounds index.
260                    if line < top {
261                        continue;
262                    }
263                    if line - top >= rows {
264                        break;
265                    }
266                    let len = self.abs_line(line).len();
267                    // Both ends, not one (ADR-0026 D3). `right_excl` was bounded and `left`
268                    // was not, which is not half a guard: the raw end survives into the
269                    // `right_excl > left` test below and drops the row instead of shortening
270                    // it — silently, and only ever the *start* row, so a multi-row selection
271                    // looks intact. Unreachable as this crate stands (#671 clamps the
272                    // producer, `resize` re-clamps reflowed points, alt drops the selection),
273                    // and kept for the reason the bound above it is kept: it makes the
274                    // function total on its own rather than by trusting a guard two files
275                    // away. `match_spans` is the same expression in `term/search.rs`, where
276                    // the coordinate IS the consumer's and this is the only guard there is.
277                    let left = if line == start_line { from.min(len) } else { 0 };
278                    let right_excl = if line == end_line { to.min(len) } else { len };
279                    if right_excl > left {
280                        push(line, left, right_excl - 1);
281                    }
282                }
283            }
284            Resolved::Block {
285                line0,
286                line1,
287                from,
288                to,
289            } => {
290                // The Block arm bounds against the grid rather than each line, because a
291                // rectangle is the same columns on every row by definition — `resolve`
292                // already clipped `to` with `.min(cols)`, so only `from` was open
293                // (ADR-0026 D3/D4). Same reachability as the Linear arm above.
294                let cols = self.grid.cols();
295                let from = from.min(cols);
296                if to > from {
297                    for line in line0..=line1 {
298                        // Per row, not once for the rectangle (#454): the same column range meets a
299                        // pair at a different place on every row, so the widening cannot be hoisted
300                        // out of this loop the way the rectangle's own bound can. A row where it
301                        // fires is one column wider than the rectangle — the price of never
302                        // painting half a glyph, and what all three references pay too (each
303                        // applies its pair rule with no rectangular-selection exemption).
304                        push(
305                            line,
306                            self.pair_start(line, from),
307                            self.pair_end(line, to - 1),
308                        );
309                    }
310                }
311            }
312        }
313        spans
314    }
315
316    /// Resolve the live selection into absolute-coordinate bounds per type:
317    /// a `Linear` run (char/word/line, which join soft wraps) or a `Block`
318    /// rectangle. `None` when nothing is selected. Columns are half-open
319    /// (`from..to`). Shared by `selection_text` and `selection_range`.
320    fn resolve(&self) -> Option<Resolved> {
321        let sel = self.selection.as_ref()?;
322        let (start, end) = sel.ordered();
323        let resolved = match sel.ty {
324            SelectionType::Char => {
325                // Half-open columns: each side decides if its own cell is in.
326                let from = match start.side {
327                    Side::Left => start.point.col,
328                    Side::Right => start.point.col + 1,
329                };
330                let to = match end.side {
331                    Side::Left => end.point.col,
332                    Side::Right => end.point.col + 1,
333                };
334                Resolved::Linear {
335                    start_line: start.point.line,
336                    from,
337                    end_line: end.point.line,
338                    to,
339                }
340            }
341            SelectionType::Word => {
342                // Snap both ends to word boundaries (side is ignored).
343                let ws = self.word_start(start.point);
344                let we = self.word_end(end.point);
345                Resolved::Linear {
346                    start_line: ws.line,
347                    from: ws.col,
348                    end_line: we.line,
349                    to: we.col + 1,
350                }
351            }
352            SelectionType::Line => Resolved::Linear {
353                start_line: start.point.line,
354                from: 0,
355                end_line: end.point.line,
356                to: self.grid.cols(),
357            },
358            SelectionType::Block => {
359                // Rectangular: the same column range on every row. Columns come
360                // from the two anchors (min/max, with each edge's side).
361                let cols = self.grid.cols();
362                let (a, b) = (sel.anchor, sel.focus);
363                let (lcol, lside, rcol, rside) = if a.point.col <= b.point.col {
364                    (a.point.col, a.side, b.point.col, b.side)
365                } else {
366                    (b.point.col, b.side, a.point.col, a.side)
367                };
368                let from = match lside {
369                    Side::Left => lcol,
370                    Side::Right => lcol + 1,
371                };
372                let to = match rside {
373                    Side::Left => rcol,
374                    Side::Right => rcol + 1,
375                };
376                Resolved::Block {
377                    line0: a.point.line.min(b.point.line),
378                    line1: a.point.line.max(b.point.line),
379                    from,
380                    to: to.min(cols).max(from),
381                }
382            }
383        };
384        Some(match resolved {
385            Resolved::Linear {
386                start_line,
387                from,
388                end_line,
389                to,
390            } => {
391                // An empty run stays empty. The pair rule widens a range that *includes* half a
392                // pair, and a zero-width one includes no cell — but its single column can still sit
393                // between a lead and its spacer, where widening would conjure the glyph out of a
394                // press that selected nothing (#914). Tested before any pair handling, from the
395                // endpoints alone, as every reference decides it.
396                if start_line == end_line && from >= to {
397                    return Some(Resolved::Linear {
398                        start_line,
399                        from,
400                        end_line,
401                        to,
402                    });
403                }
404                // Both ends move OUTWARD, each on its own line: a Linear run's two ends can sit
405                // on different rows, and a pair never spans rows.
406                let from = self.pair_start(start_line, from);
407                let to = if to > 0 {
408                    self.pair_end(end_line, to - 1) + 1
409                } else {
410                    to
411                };
412                Resolved::Linear {
413                    start_line,
414                    from,
415                    end_line,
416                    to,
417                }
418            }
419            block => block,
420        })
421    }
422
423    /// Pull a range's **first** column left when it lands on a wide glyph's trailing spacer, so a
424    /// range can never start inside a pair (#454). Returns `col` unchanged otherwise.
425    ///
426    /// A width-2 glyph is one thing, and this crate's other answers already said so before this one
427    /// existed: a spacer extracts as nothing, so `selection_text` can only ever return the whole
428    /// glyph or none of it. A range that stopped between the halves therefore made the *highlight*
429    /// and the *copy* describe different text — measured on `"漢ab"`, anchoring on the spacer and
430    /// dragging right highlighted two cells of the glyph plus `a` while copying `a` alone.
431    ///
432    /// The pair must **agree**: a spacer is only pulled onto a cell that is actually its lead. That
433    /// is what keeps the degenerate shapes safe rather than merely unlikely — `Row::resize` narrows
434    /// straight through a pair and leaves a lead with no spacer, which ADR-0025 D4's scope records as
435    /// a *legal* buffer state and not a repair site.
436    ///
437    /// `is_wide_spacer` and not `is_spacer`: the latter also matches the wide-wrap artefact
438    /// (`C_LEADING_SPACER`), which marks a row's last column when a lead did not fit — a different
439    /// fact, and one whose partner is on another row.
440    pub(super) fn pair_start(&self, line: usize, col: usize) -> usize {
441        let cell = |c: usize| self.abs_line(line).get(c).copied();
442        if col > 0
443            && cell(col).is_some_and(|c| c.is_wide_spacer())
444            && cell(col - 1).is_some_and(|c| c.is_wide())
445        {
446            col - 1
447        } else {
448            col
449        }
450    }
451
452    /// The mirror of [`pair_start`](Self::pair_start): push a range's **last** column right when it
453    /// lands on a wide glyph's lead, so a range can never end inside a pair (#454). `col` is
454    /// *inclusive*, and the same agreement rule applies — a lead whose spacer was truncated away
455    /// ends the range where it sits.
456    ///
457    /// **The agreement half of both predicates is unobservable on this side, and that is recorded
458    /// rather than tested.** Weakening either one — `pair_end` accepting any right neighbour, or
459    /// `pair_start` any left one — reds no test in the suite, measured across all four call sites
460    /// (Linear, both Block arms, `match_spans`). Not because the tests are weak: the states they
461    /// exclude are a lead beside a non-spacer mid-row and a spacer with no lead, which are exactly
462    /// what #529 stopped the engine from producing, and the row-end case is already covered by the
463    /// bound. They are kept because the same rule in `justerm-renderer` (`pair::partner_at`) *is*
464    /// observable — it reads consumer-authored decoration rects and preedit-patched flags — and one
465    /// rule with two spellings is how two layers drift apart. Valid while core keeps both halves of a
466    /// pair in step (ADR-0025 D4).
467    pub(super) fn pair_end(&self, line: usize, col: usize) -> usize {
468        let cell = |c: usize| self.abs_line(line).get(c).copied();
469        if cell(col).is_some_and(|c| c.is_wide())
470            && cell(col + 1).is_some_and(|c| c.is_wide_spacer())
471        {
472            col + 1
473        } else {
474            col
475        }
476    }
477
478    /// The selected text (for copy), or `None` when nothing is selected.
479    pub fn selection_text(&self) -> Option<String> {
480        match self.resolve()? {
481            Resolved::Linear {
482                start_line,
483                from,
484                end_line,
485                to,
486            } => Some(self.extract_lines(&self.grid, start_line, from, end_line, to)),
487            Resolved::Block {
488                line0,
489                line1,
490                from,
491                to,
492            } => {
493                // Each row independently — no soft-wrap joining.
494                let mut out = String::new();
495                for line in line0..=line1 {
496                    let hi = to.min(self.abs_line(line).len());
497                    // The same per-row widening `selection_range` applies, and for the same reason:
498                    // these two are the pair of observables #454 exists to keep in agreement, so a
499                    // rule applied to one of them alone would rebuild the defect on the other.
500                    // `to > from` is the guard `selection_range`'s Block arm already had; without it
501                    // here an empty rectangle painted nothing and copied the glyph under it (#914).
502                    let (lo, hi) = if hi > 0 && to > from {
503                        (self.pair_start(line, from), self.pair_end(line, hi - 1) + 1)
504                    } else {
505                        (from, hi)
506                    };
507                    let mut seg = String::new();
508                    for col in lo..hi {
509                        self.append_cell(&self.grid, &mut seg, line, col);
510                    }
511                    out.push_str(seg.trim_end_matches(' '));
512                    if line != line1 {
513                        out.push('\n');
514                    }
515                }
516                Some(out)
517            }
518        }
519    }
520
521    /// The whole buffer as one text document (#150): scrollback + screen assembled
522    /// into logical lines (soft-wrap joined, wide-spacers skipped, trailing blanks
523    /// trimmed at the logical end) — the accessible-view a screen reader reads as
524    /// a document, distinct from the viewport row tree (#119). Reuses the
525    /// selection extraction (`extract_lines`) over the full
526    /// range. On the alt screen only the alt buffer is shown — its "scrollback" is
527    /// the *primary* buffer's, not this app's — mirroring `viewport_logical_lines`'
528    /// alt floor.
529    pub fn accessible_text(&self) -> String {
530        let total = self.scrollback.len() + self.grid.rows();
531        if total == 0 {
532            return String::new();
533        }
534        let start = self.abs_floor();
535        let mut doc = self.extract_lines(&self.grid, start, 0, total - 1, usize::MAX);
536        // Trim *trailing* empty lines (blank screen rows below the content) — pure
537        // noise to a listener, and what a fresh screen would otherwise emit. Keep
538        // *internal* blank lines (paragraph breaks between command outputs) — a
539        // document wants those, unlike the viewport tree which drops all empties.
540        doc.truncate(doc.trim_end_matches('\n').len());
541        doc
542    }
543}