retach 0.10.0

Persistent terminal sessions with native scrollback passthrough
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};

use super::style::StyleId;

/// Single character cell in the terminal grid, with style and display width.
/// Combining marks are stored at the Row level (>99.99% of cells have none).
#[derive(Clone, Copy, Debug)]
pub struct Cell {
    pub c: char,
    /// Interned style ID — look up via StyleTable.
    pub style_id: StyleId,
    /// Display width: 1 for normal, 2 for wide char first cell, 0 for wide char continuation
    pub width: u8,
}

impl Cell {
    /// Creates a new cell.
    #[inline]
    pub fn new(c: char, style_id: StyleId, width: u8) -> Self {
        Self { c, style_id, width }
    }
}

impl Hash for Cell {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.c.hash(state);
        self.style_id.hash(state);
        self.width.hash(state);
    }
}

impl Default for Cell {
    fn default() -> Self {
        Self {
            c: ' ',
            style_id: StyleId::default(),
            width: 1,
        }
    }
}

/// A terminal row: a vector of cells plus sparse combining marks storage.
/// Combining marks (diacritics, etc.) are stored separately because >99.99%
/// of cells never have them. This keeps Cell at 8 bytes instead of 24.
///
/// # Direct mutation
///
/// `Row` is externally mutable (`DerefMut` to `[Cell]`, `push`, `insert`,
/// …). Direct mutation does not maintain wide-character pair invariants
/// (a width-2 base cell followed by a width-0 continuation cell) — keeping
/// those pairs consistent is the caller's responsibility. The emulator
/// only guarantees invariants for content it wrote itself.
#[derive(Clone, Debug)]
pub struct Row {
    cells: Vec<Cell>,
    /// Combining marks per column. Empty in the vast majority of rows.
    combining: Vec<(u16, Vec<char>)>,
}

/// A positioned glyph in a [`Row`]: base char, combining marks, display
/// width, and interned style. Produced by [`Row::graphemes`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Grapheme<'a> {
    /// Cell column (0-based). Jumps by 2 after a wide glyph.
    pub col: u16,
    /// Base character (the printable glyph).
    pub c: char,
    /// Combining marks attached to this cell (usually empty).
    pub combining: &'a [char],
    /// Display width: 1 normal, 2 wide.
    pub width: u8,
    /// Interned style — resolve via [`resolve_style`](crate::screen::TerminalEmulator::resolve_style).
    pub style_id: StyleId,
}

impl Row {
    /// Create a new row with `cols` default cells.
    pub fn new(cols: usize) -> Self {
        Self {
            cells: vec![Cell::default(); cols],
            combining: Vec::new(),
        }
    }

    /// Create a Row from an existing `Vec<Cell>` (for migration).
    pub fn from_cells(cells: Vec<Cell>) -> Self {
        Self {
            cells,
            combining: Vec::new(),
        }
    }

    /// Returns combining marks for the given column (empty if none).
    #[inline]
    pub fn combining(&self, col: u16) -> &[char] {
        for &(c, ref marks) in &self.combining {
            if c == col {
                return marks;
            }
        }
        &[]
    }

    /// Push a combining mark onto the given column.
    pub fn push_combining(&mut self, col: u16, mark: char) {
        for &mut (c, ref mut marks) in &mut self.combining {
            if c == col {
                marks.push(mark);
                return;
            }
        }
        self.combining.push((col, vec![mark]));
    }

    /// Number of combining marks on the given column.
    #[inline]
    pub fn combining_len(&self, col: u16) -> usize {
        for &(c, ref marks) in &self.combining {
            if c == col {
                return marks.len();
            }
        }
        0
    }

    /// Clear combining marks for the given column.
    pub fn clear_combining(&mut self, col: u16) {
        self.combining.retain(|&(c, _)| c != col);
    }

    /// Clear all combining marks for this row.
    pub fn clear_all_combining(&mut self) {
        self.combining.clear();
    }

    /// Clear combining marks for columns in the range [from, to).
    pub fn clear_combining_range(&mut self, from: u16, to: u16) {
        self.combining.retain(|&(c, _)| c < from || c >= to);
    }

    /// Number of cells in this row.
    #[inline]
    pub fn len(&self) -> usize {
        self.cells.len()
    }

    /// Number of cells up to and including the last content cell. This encodes
    /// the RENDERER's notion of content specifically: a cell counts as content
    /// if it has a non-blank char (blank = `' '` or NUL `'\0'`) OR a non-default
    /// style. Combining marks do NOT extend content — they attach to a base char
    /// which itself counts. Returns 0 for a blank row.
    pub fn content_len(&self) -> usize {
        self.cells
            .iter()
            .rposition(|c| (c.c != ' ' && c.c != '\0') || !c.style_id.is_default())
            .map(|p| p + 1)
            .unwrap_or(0)
    }

    /// Whether this row has no cells.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.cells.is_empty()
    }

    /// Resize the row to `new_len` cells, filling with `value`.
    pub fn resize(&mut self, new_len: usize, value: Cell) {
        if new_len < self.cells.len() {
            // Remove combining marks for truncated columns
            let limit = new_len as u16;
            self.combining.retain(|&(c, _)| c < limit);
        }
        self.cells.resize(new_len, value);
    }

    /// Remove a cell at index, shifting subsequent cells left.
    /// Adjusts combining mark column indices accordingly.
    pub fn remove(&mut self, index: usize) -> Cell {
        let col = index as u16;
        // Remove combining marks for the deleted column
        self.combining.retain(|&(c, _)| c != col);
        // Shift combining marks for columns after the deleted one
        for &mut (ref mut c, _) in &mut self.combining {
            if *c > col {
                *c -= 1;
            }
        }
        self.cells.remove(index)
    }

    /// Insert a cell at index, shifting subsequent cells right.
    /// Adjusts combining mark column indices accordingly.
    pub fn insert(&mut self, index: usize, cell: Cell) {
        let col = index as u16;
        // Shift combining marks for columns at or after the insertion point
        for &mut (ref mut c, _) in &mut self.combining {
            if *c >= col {
                *c = c.saturating_add(1);
            }
        }
        self.cells.insert(index, cell);
    }

    /// Push a cell at the end.
    pub fn push(&mut self, cell: Cell) {
        self.cells.push(cell);
    }

    /// Clean up orphaned wide-char halves at a column boundary during resize/restore.
    /// `new_cols` is the number of columns the row will be truncated to.
    /// Must be called BEFORE `resize()` when the row is longer than `new_cols`.
    pub(crate) fn fix_wide_char_orphan_at_boundary(&mut self, new_cols: usize) {
        if new_cols == 0 || self.cells.len() <= new_cols {
            return;
        }
        let last = new_cols - 1;
        if self.cells[last].width == 2 {
            self.cells[last] = Cell::default();
        } else if last > 0 && self.cells[last].width == 0 {
            self.cells[last] = Cell::default();
            self.cells[last - 1] = Cell::default();
        }
    }

    /// Pop the last cell.
    pub fn pop(&mut self) -> Option<Cell> {
        if let Some(cell) = self.cells.pop() {
            let col = self.cells.len() as u16;
            self.combining.retain(|&(c, _)| c != col);
            Some(cell)
        } else {
            None
        }
    }

    /// Iterate over cells.
    pub fn iter(&self) -> std::slice::Iter<'_, Cell> {
        self.cells.iter()
    }

    /// Mutably iterate over cells.
    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Cell> {
        self.cells.iter_mut()
    }

    /// Positioned glyphs left-to-right; wide-char continuation cells
    /// (`width == 0`) are skipped. Yields ALL non-continuation cells,
    /// including trailing blanks — use [`Row::text`] for trimmed text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use retach::screen::{Screen, TerminalEmulator};
    ///
    /// let mut screen = Screen::new(20, 4, 0);
    /// screen.process("世界".as_bytes());
    /// let rows: Vec<_> = screen.visible_rows().collect();
    /// let glyphs: Vec<char> = rows[0].graphemes()
    ///     .take_while(|g| (g.col as usize) < rows[0].content_len())
    ///     .map(|g| g.c)
    ///     .collect();
    /// assert_eq!(glyphs, vec!['世', '界']);
    /// ```
    pub fn graphemes(&self) -> impl Iterator<Item = Grapheme<'_>> + '_ {
        self.cells
            .iter()
            .enumerate()
            .filter(|(_, cell)| cell.width != 0)
            .map(|(i, cell)| Grapheme {
                col: i as u16,
                c: cell.c,
                combining: self.combining(i as u16),
                width: cell.width,
                style_id: cell.style_id,
            })
    }

    /// Plain text of the row: styles dropped, combining marks included,
    /// trailing blank cells trimmed (a trailing *styled* blank counts as
    /// content and is kept, matching the renderer's notion of content).
    pub fn text(&self) -> String {
        let content_len = self.content_len();
        let mut out = String::with_capacity(content_len);
        for g in self.graphemes() {
            if (g.col as usize) >= content_len {
                break;
            }
            out.push(g.c);
            out.extend(g.combining.iter().copied());
        }
        out
    }
}

impl Hash for Row {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.cells.hash(state);
        self.combining.hash(state);
    }
}

impl Deref for Row {
    type Target = [Cell];

    fn deref(&self) -> &[Cell] {
        &self.cells
    }
}

impl DerefMut for Row {
    fn deref_mut(&mut self) -> &mut [Cell] {
        &mut self.cells
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cell_size() {
        let size = std::mem::size_of::<Cell>();
        assert!(size <= 8, "Cell should be <= 8 bytes, got {size}");
    }

    #[test]
    fn row_combining_basic() {
        let mut row = Row::new(10);
        assert_eq!(row.combining(0), &[] as &[char]);
        row.push_combining(0, '\u{0301}');
        assert_eq!(row.combining(0), &['\u{0301}']);
        assert_eq!(row.combining_len(0), 1);
        row.push_combining(0, '\u{0308}');
        assert_eq!(row.combining_len(0), 2);
        assert_eq!(row.combining(0), &['\u{0301}', '\u{0308}']);
    }

    #[test]
    fn row_clear_combining() {
        let mut row = Row::new(10);
        row.push_combining(3, '\u{0301}');
        assert_eq!(row.combining_len(3), 1);
        row.clear_combining(3);
        assert_eq!(row.combining_len(3), 0);
    }

    #[test]
    fn row_remove_shifts_combining() {
        let mut row = Row::new(10);
        row.push_combining(5, '\u{0301}');
        row.remove(3);
        // Column 5 should now be at column 4
        assert_eq!(row.combining(4), &['\u{0301}']);
        assert_eq!(row.combining(5), &[] as &[char]);
    }

    #[test]
    fn row_insert_shifts_combining() {
        let mut row = Row::new(10);
        row.push_combining(3, '\u{0301}');
        row.insert(2, Cell::default());
        // Column 3 should now be at column 4
        assert_eq!(row.combining(4), &['\u{0301}']);
        assert_eq!(row.combining(3), &[] as &[char]);
    }

    #[test]
    fn row_resize_truncates_combining() {
        let mut row = Row::new(10);
        row.push_combining(8, '\u{0301}');
        row.resize(5, Cell::default());
        assert_eq!(row.combining(8), &[] as &[char]);
    }

    #[test]
    fn row_fix_wide_char_orphan_at_boundary_width2() {
        let mut row = Row::new(10);
        row[4].width = 2;
        row[5].width = 0;
        row.fix_wide_char_orphan_at_boundary(5);
        assert_eq!(row[4].c, ' ');
        assert_eq!(row[4].width, 1);
    }

    #[test]
    fn row_fix_wide_char_orphan_at_boundary_continuation() {
        let mut row = Row::new(10);
        row[3].width = 2;
        row[4].width = 0;
        row.fix_wide_char_orphan_at_boundary(5);
        // Cell at last (4) is a continuation — blank it and its base (3)
        assert_eq!(row[3].c, ' ');
        assert_eq!(row[3].width, 1);
        assert_eq!(row[4].c, ' ');
        assert_eq!(row[4].width, 1);
    }

    #[test]
    fn row_fix_wide_char_orphan_noop_when_short() {
        let mut row = Row::new(5);
        row[2].c = 'A';
        row.fix_wide_char_orphan_at_boundary(10); // row shorter than boundary
        assert_eq!(row[2].c, 'A'); // unchanged
    }

    #[test]
    fn content_len_blank_row_is_zero() {
        assert_eq!(Row::new(10).content_len(), 0);
    }

    #[test]
    fn content_len_counts_to_last_non_blank() {
        let mut row = Row::new(10);
        row[0].c = 'a';
        row[3].c = 'b';
        assert_eq!(row.content_len(), 4);
    }

    #[test]
    fn content_len_counts_styled_blank_as_content() {
        let mut row = Row::new(10);
        row[5].style_id = StyleId(1);
        assert_eq!(row.content_len(), 6);
    }

    #[test]
    fn content_len_includes_wide_char_continuation() {
        let mut row = Row::new(6);
        row[0].c = '';
        row[0].width = 2;
        row[1].c = '\0';
        row[1].width = 0;
        // Real emulator (grid.rs::set_cell) writes the continuation cell as
        // Cell::new('\0', <wide char's style>, 0). Here the wide char has the
        // default style, so the continuation cell is blank ('\0' + default
        // style) and content stops at the base char.
        assert_eq!(row.content_len(), 1);
    }

    #[test]
    fn graphemes_skips_wide_continuation_and_attaches_combining() {
        let mut row = Row::new(6);
        row[0].c = 'a';
        row[1].c = '';
        row[1].width = 2;
        row[2].width = 0; // continuation
        row[3].c = 'x';
        row.push_combining(3, '\u{0301}');

        let gs: Vec<_> = row.graphemes().collect();
        assert_eq!(gs.len(), 5); // cols 0,1,3,4,5 — col 2 (continuation) skipped
        assert_eq!((gs[0].col, gs[0].c, gs[0].width), (0, 'a', 1));
        assert_eq!((gs[1].col, gs[1].c, gs[1].width), (1, '', 2));
        assert_eq!((gs[2].col, gs[2].c), (3, 'x'));
        assert_eq!(gs[2].combining, &['\u{0301}']);
        assert!(gs[3].combining.is_empty());
        assert_eq!(gs[4].col, 5); // trailing blank IS yielded
    }

    #[test]
    fn text_trims_trailing_blanks_and_includes_combining() {
        let mut row = Row::new(10);
        row[0].c = 'h';
        row[1].c = '';
        row[1].width = 2;
        row[2].width = 0;
        row[3].c = 'i';
        row.push_combining(3, '\u{0301}');
        assert_eq!(row.text(), "h界i\u{0301}");
    }

    #[test]
    fn text_blank_row_is_empty() {
        assert_eq!(Row::new(10).text(), "");
    }

    #[test]
    fn text_keeps_interior_blanks() {
        let mut row = Row::new(10);
        row[0].c = 'a';
        row[4].c = 'b';
        assert_eq!(row.text(), "a   b");
    }

    #[test]
    fn text_styled_wide_char_at_end() {
        // A styled wide char's continuation inherits the style and extends
        // content_len; text() must still emit the glyph exactly once.
        let mut row = Row::new(6);
        row[0].c = '';
        row[0].width = 2;
        row[0].style_id = StyleId(1);
        row[1] = Cell::new('\0', StyleId(1), 0); // continuation, styled
        assert_eq!(row.text(), "");
    }

    #[test]
    fn graphemes_carry_style_id() {
        let mut row = Row::new(4);
        row[0].c = 'a';
        row[0].style_id = StyleId(7);
        let g = row.graphemes().next().unwrap();
        assert_eq!(g.style_id, StyleId(7));
    }
}