paperos 0.2.0

A programmable editor built on the Runact actor runtime
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
//! VT-style terminal grid: per-cell character + style, cursor, scrollback.
//!
//! This is the data structure the terminal panel renders from. It lives
//! in the extension layer (src/extensions/terminal/), never in core —
//! terminal emulation is an extension concern per AGENTS.md.

use ratatui::style::Style;

/// One terminal cell: a character plus its SGR style.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cell {
    pub ch: char,
    pub style: Style,
}

impl Default for Cell {
    fn default() -> Self {
        Cell {
            ch: ' ',
            style: Style::default(),
        }
    }
}

/// A VT-style grid: scrollback rows + visible rows, per-cell styles,
/// and a cursor. All positions are absolute (scrollback + visible);
/// the visible window is the last `visible` rows.
#[derive(Debug, Clone)]
pub struct TermGrid {
    /// All rows, oldest first: scrollback rows then visible rows.
    rows: Vec<Vec<Cell>>,
    /// Maximum number of scrollback rows retained.
    scrollback_cap: usize,
    /// Number of visible (on-screen) rows.
    visible: usize,
    cols: usize,
    /// Absolute cursor row (may point into scrollback while scrolling).
    cursor_row: usize,
    cursor_col: usize,
    /// Viewport offset: rows above the live bottom (0 = live view).
    /// Set by PageUp/PageDown; snapped to 0 on user input.
    view_offset: usize,
}

impl TermGrid {
    /// A grid with no scrollback.
    pub fn new(cols: usize, rows: usize) -> Self {
        Self::scrollback(cols, rows, 0)
    }

    /// A grid with `scrollback_cap` rows of history above the visible area.
    pub fn scrollback(cols: usize, visible: usize, scrollback_cap: usize) -> Self {
        TermGrid {
            rows: vec![vec![Cell::default(); cols]; visible],
            scrollback_cap,
            visible,
            cols,
            cursor_row: 0,
            cursor_col: 0,
            view_offset: 0,
        }
    }

    /// Number of visible rows.
    pub fn rows(&self) -> usize {
        self.visible
    }

    /// Number of columns.
    pub fn cols(&self) -> usize {
        self.cols
    }

    /// Cursor position as (visible_row, col) in the LIVE view (VT
    /// semantics — used by tests; the render path uses cursor_in_view).
    pub fn cursor(&self) -> (usize, usize) {
        (
            self.cursor_row.saturating_sub(self.scrollback_len()),
            self.cursor_col,
        )
    }

    /// Cursor row relative to the current viewport, or None when the
    /// cursor is scrolled out of view (viewport is in history).
    pub fn cursor_in_view(&self) -> Option<usize> {
        let rel = self.cursor_row as i64 - self.view_start() as i64;
        if rel >= 0 && (rel as usize) < self.visible {
            Some(rel as usize)
        } else {
            None
        }
    }

    /// Count of scrollback (history) rows.
    pub fn scrollback_len(&self) -> usize {
        self.rows.len().saturating_sub(self.visible)
    }

    /// Current viewport offset (rows above the live bottom; 0 = live).
    pub fn scroll_offset(&self) -> usize {
        self.view_offset
    }

    /// Scroll the viewport by `delta` rows (positive = into history).
    /// Clamped to [0, scrollback_len].
    pub fn scroll_viewport(&mut self, delta: i64) {
        let max = self.scrollback_len() as i64;
        self.view_offset = (self.view_offset as i64 + delta).clamp(0, max) as usize;
    }

    /// Snap the viewport back to the live (bottom) view.
    pub fn reset_viewport(&mut self) {
        self.view_offset = 0;
    }

    /// Absolute index of the first row in the current viewport.
    fn view_start(&self) -> usize {
        self.rows
            .len()
            .saturating_sub(self.visible + self.view_offset)
    }

    /// Cell at viewport (row, col), if in bounds.
    pub fn cell(&self, row: usize, col: usize) -> Option<&Cell> {
        let abs = row + self.view_start();
        self.rows.get(abs).and_then(|r| r.get(col))
    }

    /// Write one char at the cursor, advancing; wrap at the right edge.
    pub fn put(&mut self, ch: char, style: Style) {
        if self.cols == 0 || self.visible == 0 {
            return;
        }
        if self.cursor_col >= self.cols {
            self.cursor_col = 0;
            self.cursor_row += 1;
        }
        self.ensure_cursor_row();
        let row = &mut self.rows[self.cursor_row];
        row[self.cursor_col] = Cell { ch, style };
        self.cursor_col += 1;
    }

    /// Move cursor down one row (no column change) — LF in raw mode.
    pub fn linefeed(&mut self) {
        if self.visible == 0 {
            return;
        }
        self.cursor_row += 1;
        self.ensure_cursor_row();
    }

    /// Newline: down one row, column to 0.
    pub fn newline(&mut self) {
        self.linefeed();
        self.cursor_col = 0;
    }

    /// Carriage return: column to 0.
    pub fn carriage_return(&mut self) {
        self.cursor_col = 0;
    }

    /// Backspace: cursor left, clamped at 0. (Used by the vte parser.)
    #[allow(dead_code)]
    pub fn backspace(&mut self) {
        self.cursor_col = self.cursor_col.saturating_sub(1);
    }

    /// Tab: advance to the next multiple of 8, wrapping to a new row.
    pub fn tab(&mut self) {
        if self.cols == 0 {
            return;
        }
        let next = (self.cursor_col / 8 + 1) * 8;
        if next >= self.cols {
            self.cursor_col = 0;
            self.newline();
        } else {
            self.cursor_col = next;
        }
    }

    /// Scroll the visible window up by `n` rows (content moves up;
    /// blank rows appear at the bottom, oldest scrollback drops off).
    pub fn scroll_up(&mut self, n: usize) {
        let before_len = self.rows.len();
        for _ in 0..n {
            if self.rows.len() >= self.scrollback_cap + self.visible {
                self.rows.remove(0);
                self.cursor_row = self.cursor_row.saturating_sub(1);
            }
            self.rows.push(vec![Cell::default(); self.cols]);
        }
        // While the user is scrolled into history, keep the viewport
        // anchored to the same rows as new output arrives (the offset
        // counts from the live bottom, which just moved).
        if self.view_offset > 0 {
            self.view_offset += self.rows.len() - before_len;
        }
    }

    /// Resize the grid to (cols, visible rows). Preserves the tail of
    /// existing content that fits; blank-fills the rest. Cursor is
    /// clamped into the new bounds.
    pub fn resize(&mut self, cols: usize, visible: usize) {
        for row in &mut self.rows {
            row.resize(cols, Cell::default());
        }
        while self.rows.len() < visible {
            self.rows.push(vec![Cell::default(); cols]);
        }
        self.cols = cols;
        self.visible = visible;
        self.view_offset = self.view_offset.min(self.scrollback_len());
        let base = self.scrollback_len();
        self.cursor_row = self.cursor_row.min(base + visible.saturating_sub(1));
        self.cursor_col = self.cursor_col.min(cols.saturating_sub(1));
    }

    /// Move the cursor to an absolute (row, col) within the visible
    /// area (0-based, clamped). Used by CUP (ESC [ r ; c H).
    pub fn move_to(&mut self, row: usize, col: usize) {
        let base = self.scrollback_len();
        self.cursor_row = (base + row).min(base + self.visible.saturating_sub(1));
        self.cursor_col = col.min(self.cols.saturating_sub(1));
    }

    /// Move the cursor by (drow, dcol), clamped to the visible area.
    pub fn move_cursor(&mut self, drow: i64, dcol: i64) {
        let base = self.scrollback_len() as i64;
        let row = (self.cursor_row as i64 + drow).clamp(base, base + self.visible as i64 - 1);
        self.cursor_row = row as usize;
        self.cursor_col = (self.cursor_col as i64 + dcol).clamp(0, self.cols as i64 - 1) as usize;
    }

    /// Erase modes for ED (ESC [ n J): 0=below, 1=above, 2=all, 3=all+scrollback.
    pub fn erase_in_display(&mut self, mode: u16) {
        let start = self.scrollback_len();
        let (fr, to) = match mode {
            0 => (self.cursor_row, self.rows.len()),
            1 => (start, self.cursor_row + 1),
            2 | 3 => (start, self.rows.len()),
            _ => return,
        };
        for row in self.rows.iter_mut().take(to).skip(fr) {
            for cell in row.iter_mut() {
                *cell = Cell::default();
            }
        }
        if mode == 3 {
            // Also drop scrollback entirely.
            let visible_rows: Vec<Vec<Cell>> = self.rows.drain(start..).collect();
            self.rows = visible_rows;
            self.view_offset = 0;
        }
    }

    /// Erase modes for EL (ESC [ n K): 0=to end of line, 1=to start, 2=whole line.
    pub fn erase_in_line(&mut self, mode: u16) {
        let (fr, to) = match mode {
            0 => (self.cursor_col, self.cols),
            1 => (0, (self.cursor_col + 1).min(self.cols)),
            2 => (0, self.cols),
            _ => return,
        };
        if let Some(row) = self.rows.get_mut(self.cursor_row) {
            for cell in row.iter_mut().take(to).skip(fr) {
                *cell = Cell::default();
            }
        }
    }

    /// Plain-text projection: one String per visible row, trailing
    /// spaces trimmed. This is what the terminal BufferActor's lines
    /// hold — the invariant "buffer lines describe what is on screen".
    pub fn text_projection(&self) -> Vec<String> {
        let start = self.view_start();
        let end = (start + self.visible).min(self.rows.len());
        self.rows[start..end]
            .iter()
            .map(|r| {
                let s: String = r.iter().map(|c| c.ch).collect();
                s.trim_end().to_string()
            })
            .collect()
    }

    /// Ensure cursor_row points at a writable row: if it moved past the
    /// last visible row, scroll up and pin it to the bottom.
    fn ensure_cursor_row(&mut self) {
        if self.visible == 0 {
            return;
        }
        let last = self.scrollback_len() + self.visible - 1;
        if self.cursor_row > last {
            self.scroll_up(self.cursor_row - last);
            self.cursor_row = self.scrollback_len() + self.visible - 1;
        }
    }
}

#[cfg(test)]
impl TermGrid {
    /// Test-only: visible row count (asserts internal invariant).
    fn visible_rows_hint(&self) -> usize {
        self.visible
    }
}

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

    #[test]
    fn new_grid_has_default_cells() {
        let g = TermGrid::new(4, 2);
        assert_eq!(g.rows(), 2);
        assert_eq!(g.cols(), 4);
        assert_eq!(g.cell(0, 0), Some(&Cell::default()));
        assert_eq!(g.cursor(), (0, 0));
    }

    #[test]
    fn put_advances_cursor_and_wraps() {
        let mut g = TermGrid::new(4, 2);
        for ch in "ABCDE".chars() {
            g.put(ch, Style::default());
        }
        // 5 chars into 4 cols: E wrapped to row 1
        assert_eq!(g.cursor(), (1, 1));
        assert_eq!(g.cell(0, 0).unwrap().ch, 'A');
        assert_eq!(g.cell(1, 0).unwrap().ch, 'E');
    }

    #[test]
    fn newline_and_linefeed() {
        let mut g = TermGrid::new(4, 2);
        g.put('x', Style::default());
        g.put('y', Style::default());
        g.newline();
        assert_eq!(g.cursor(), (1, 0));
        g.put('z', Style::default());
        g.linefeed(); // LF alone: down, column kept
        assert_eq!(g.cursor(), (1, 1));
    }

    #[test]
    fn viewport_offset_clamps_and_resets() {
        let mut g = TermGrid::scrollback(4, 2, 10);
        for i in 0..6u8 {
            g.put(char::from(b'0' + i), Style::default());
            g.newline();
        }
        assert_eq!(g.scrollback_len(), 5);
        g.scroll_viewport(100); // clamps at scrollback top
        assert_eq!(g.scroll_offset(), 5);
        g.scroll_viewport(-100); // clamps at 0
        assert_eq!(g.scroll_offset(), 0);
        g.scroll_viewport(3);
        g.reset_viewport();
        assert_eq!(g.scroll_offset(), 0);
    }

    #[test]
    fn viewport_anchors_while_output_arrives() {
        let mut g = TermGrid::scrollback(4, 2, 100);
        for i in 0..6u8 {
            g.put(char::from(b'0' + i), Style::default());
            g.newline();
        }
        g.scroll_viewport(5); // scrolled to the very top of history
                              // More output arrives: the same rows must stay on screen.
        g.put('x', Style::default());
        g.newline();
        g.put('y', Style::default());
        g.newline();
        assert_eq!(
            g.scroll_offset(),
            7,
            "offset grows with new rows (anchored)"
        );
        assert_eq!(
            g.cell(0, 0).unwrap().ch,
            '0',
            "top visible row is still the oldest"
        );
    }

    #[test]
    fn cursor_hidden_when_viewport_in_history() {
        let mut g = TermGrid::scrollback(4, 2, 100);
        for i in 0..6u8 {
            g.put(char::from(b'0' + i), Style::default());
            g.newline();
        }
        assert!(g.cursor_in_view().is_some(), "live view shows the cursor");
        g.scroll_viewport(3);
        assert!(
            g.cursor_in_view().is_none(),
            "history view hides the cursor"
        );
    }

    #[test]
    fn writing_past_bottom_scrolls() {
        let mut g = TermGrid::scrollback(4, 2, 10);
        // Write 6 lines of one char each. Lines 0-3 scroll off into
        // scrollback; the visible window shows lines 4 and 5.
        for i in 0..6u8 {
            g.put(char::from(b'0' + i), Style::default());
            g.newline();
        }
        assert_eq!(g.visible_rows_hint(), 2);
        // 6 newline-terminated lines: after the 6th newline the cursor
        // tried to move to row 6 (past the 2-row window), scrolling once
        // more — 6 written rows + 1 blank = 7 total, 2 visible, 5 in
        // scrollback (cap 10 not hit).
        assert_eq!(g.scrollback_len(), 5);
        // Visible top row is written line 5 ('5'); line 4 just scrolled off.
        assert_eq!(g.cell(0, 0).unwrap().ch, '5');
        // Bottom visible row is the blank row the 6th newline revealed.
        assert_eq!(g.cell(1, 0).unwrap().ch, ' ');
    }

    #[test]
    fn text_projection_trims_trailing_spaces() {
        let mut g = TermGrid::new(4, 2);
        g.put('h', Style::default());
        g.put('i', Style::default());
        assert_eq!(g.text_projection(), vec!["hi".to_string(), String::new()]);
        let empty = TermGrid::new(4, 2);
        assert_eq!(empty.text_projection(), vec![String::new(), String::new()]);
    }

    #[test]
    fn erase_in_display_clears_screen_keeps_cursor() {
        let mut g = TermGrid::new(4, 2);
        g.put('a', Style::default());
        g.put('b', Style::default());
        g.erase_in_display(2);
        assert_eq!(g.text_projection(), vec![String::new(), String::new()]);
        assert_eq!(g.cursor(), (0, 2));
    }

    #[test]
    fn move_cursor_clamps_to_visible_area() {
        let mut g = TermGrid::new(10, 3);
        g.move_cursor(99, 0); // clamp to bottom row
        assert_eq!(g.cursor(), (2, 0));
        g.move_cursor(0, 99); // clamp to last col
        assert_eq!(g.cursor(), (2, 9));
        g.move_cursor(-99, -99); // clamp to top-left
        assert_eq!(g.cursor(), (0, 0));
    }

    #[test]
    fn tab_advances_to_multiple_of_eight() {
        let mut g = TermGrid::new(20, 2);
        g.tab();
        assert_eq!(g.cursor(), (0, 8));
        g.tab();
        assert_eq!(g.cursor(), (0, 16));
    }

    #[test]
    fn erase_in_line_modes() {
        let mut g = TermGrid::new(10, 1);
        for ch in "0123456789".chars() {
            g.put(ch, Style::default());
        }
        g.carriage_return();
        g.move_cursor(0, 5);
        g.erase_in_line(0); // clear from col 5 to end
        assert_eq!(g.text_projection(), vec!["01234".to_string()]);
        g.erase_in_line(2); // clear whole line
        assert_eq!(g.text_projection(), vec![String::new()]);
    }
}