From 900232b3e7424c989555c0203d6ca30f4f80fee4 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:00:59 +0700 Subject: [PATCH 1/4] fix(emu): ICH on a wide character's second half erases it vt100's Row::insert moves the wide-continuation flag onto the inserted blank, so with the cursor on the second column of a wide character `CSI @` kept the character whole and inserted after it. xterm's InsertChar (util.c 1887) clears the character the cursor splits with RepairInsertChar first. ICH now reaches the emulator as a Motion event. With the cursor on a wide continuation, the sequence is replaced by one vte ignores, the character is erased with ECH from its first half, and the ICH is fed again from the cursor's column. Otherwise the final byte goes to vt100 as before. Closes #822 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 6 ++ crates/termlens/src/emu/seq.rs | 18 +++++ crates/termlens/src/emu/vt100.rs | 119 ++++++++++++++++++++++++++++++- 3 files changed, 142 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 470ee1b..cc3e319 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,12 @@ reads that marker. `xterm-256color`, and a recording with no frame takes the terminal's size at `record` rather than 80x24. A test that bounded `timestamp` by the export should bound it by the call to `record`. (#850) +- `ICH` (`CSI @`) with the cursor on the second half of a wide character + erases the character before it inserts, as xterm's `InsertChar` does: + `漢x`, `CSI 2 G`, `CSI @` shows three blank columns and then `x`. + termlens kept the character whole and inserted the blank after it, + `漢 x`. A test that expected the character after such an insert should + expect blanks in its place. (#822) ### Fixed diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index b2d885b..35175fa 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -299,6 +299,17 @@ pub(crate) enum TabOp { Back(u16), } +/// A cursor motion or a character edit the emulator carries out in place +/// of vt100, which starts it from somewhere xterm does not. Whether it +/// differs depends on the cursor, which lives in the grid, so the tracker +/// names the operation and its count and the emulator resolves it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Motion { + /// `ICH` (`CSI Ps @`): insert `n` blank cells at the cursor. xterm + /// erases a wide character the cursor splits first (#822). + InsertChars(u16), +} + /// Which glyph set a G0–G3 designation currently names. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Charset { @@ -509,6 +520,11 @@ pub(crate) enum SeqEvent { /// The emulator takes the escape from vt100 and feeds both parsers the /// line feed, as it draws `REP`'s characters (#816). Index { next_line: bool }, + /// A [`Motion`] completed, which the emulator carries out from the + /// cursor xterm would start it from: the bytes before the final byte + /// are fed, the cursor read, and the final byte either fed as it is or + /// replaced by the motion written out in moves vt100 gets right. + Motion(Motion), } /// A terminal query the application issued. The tracker classifies; @@ -2168,6 +2184,8 @@ impl SeqTracker { } b'I' => return SeqEvent::Tabs(TabOp::Forward(count)), b'Z' => return SeqEvent::Tabs(TabOp::Back(count)), + // ICH by its first parameter, as vt100 and xterm read it. + b'@' => return SeqEvent::Motion(Motion::InsertChars(count)), // ED 3, erase the saved lines. vt100 reads the first // parameter alone, and so does this. b'J' if ps == 3 => return SeqEvent::ScrollbackErased, diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index c17191a..01f4078 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -7,7 +7,7 @@ use std::num::NonZeroU16; use std::sync::Arc; use std::time::{Duration, Instant}; -use super::seq::{SeqEvent, SeqTracker, TabOp}; +use super::seq::{Motion, SeqEvent, SeqTracker, TabOp}; use super::shadow::{AttrShadow, ColorNormalizer}; use super::unhandled::{CutOsc, Unhandled}; use super::{Emulator, FrameSpan, InputModes, ModeState, MouseEncoding, Processed, Stop}; @@ -971,6 +971,45 @@ fn primary_sgr(cell: &::vt100::Cell) -> String { sgr } +/// What ends a CSI the emulator carries out itself in place of its final +/// byte: [`REP_IGNORED`], which vte ignores, so neither parser acts on the +/// sequence and the record lists nothing. +const CSI_IGNORED: &[u8] = REP_IGNORED; + +impl Vt100Emulator { + /// Carry out a [`Motion`] whose bytes before the final one are fed: + /// `last` is that final byte, fed as it is when vt100 does what xterm + /// does from this cursor, and replaced by [`CSI_IGNORED`] and moves + /// vt100 gets right when it does not. Both parsers are fed either way, + /// so the shadow keeps the same shape. + fn carry_out(&mut self, motion: Motion, last: &[u8]) { + let screen = self.parser.screen(); + let (row, col) = screen.cursor_position(); + match motion { + Motion::InsertChars(n) => { + // xterm's `InsertChar` (util.c 1887) repairs a wide + // character the cursor splits before it shifts the row: + // `DamagedCurCells` finds it and `RepairInsertChar` clears + // it with `ClearInLine2`. vt100's `Row::insert` moves the + // continuation flag onto the inserted blank instead, and + // the character stayed whole on the far side of it (#822). + // So the character is erased first, by `ECH` from its first + // half in the attributes in force, and the `ICH` follows. + let splits = col > 0 + && screen + .cell(row, col) + .is_some_and(::vt100::Cell::is_wide_continuation); + if splits { + self.feed(CSI_IGNORED); + self.feed(format!("\x1b[{col}G\x1b[2X\x1b[{}G\x1b[{n}@", col + 1).as_bytes()); + } else { + self.feed(last); + } + } + } + } +} + impl Emulator for Vt100Emulator { fn process(&mut self, bytes: &[u8]) -> Processed { // How much of this segment the grid has already been given. A @@ -1185,6 +1224,12 @@ impl Emulator for Vt100Emulator { self.feed(if next_line { b"\r\n" } else { b"\n" }); None } + SeqEvent::Motion(motion) => { + self.feed_staged(&bytes[fed..i]); + fed = i + 1; + self.carry_out(motion, &bytes[i..=i]); + None + } SeqEvent::None => None, SeqEvent::SyncBegin => { // Stamped here, at the byte that opened the update, @@ -5423,4 +5468,76 @@ mod tests { } } } + + /// `ICH` with the cursor on the second half of a wide character erases + /// the character before it shifts the row, as xterm's `InsertChar` + /// does (`RepairInsertChar`, util.c 1887). vt100 kept the character + /// whole and inserted after it (#822). On the first half nothing is + /// split, and the character moves right whole in both. + #[test] + fn ich_on_the_second_half_of_a_wide_character_erases_it() { + for (stream, text, cursor) in [ + ("\u{6f22}x\x1b[2G\x1b[@", " x", (0, 1)), + ("\u{6f22}x\x1b[2G\x1b[2@", " x", (0, 1)), + ("\u{6f22}x\x1b[2G\x1b[0@", " x", (0, 1)), + ("\u{6f22}x\x1b[1G\x1b[@", " \u{6f22}x", (0, 0)), + ("ab\u{6f22}x\x1b[4G\x1b[@y", "ab y x", (0, 4)), + ] { + let (whole, bytewise) = whole_and_bytewise(2, 10, 0, stream.as_bytes()); + assert_eq!(observed(&whole), observed(&bytewise), "{stream:?}"); + let s = whole.snapshot(); + assert_eq!(s.row_text(0).trim_end(), text, "{stream:?}: {s}"); + assert_eq!((s.cursor().0, s.cursor().1), cursor, "{stream:?}: {s}"); + assert!( + s.unsupported().is_empty(), + "{stream:?}: {:?}", + s.unsupported() + ); + } + // The erase is in the attributes in force, as xterm's + // `ClearInLine2` clears with the current background. + let s = emu_with_size(2, 10, "\u{6f22}x\x1b[2G\x1b[41m\x1b[@".as_bytes()).snapshot(); + assert_eq!(s.cell(0, 0).unwrap().style().bg, Color::Indexed(1), "{s}"); + } + + /// Random short streams of the motions and edits the emulator carries + /// out itself (#814, #820, #821, #822), mixed with text, wide + /// characters, controls and SGR, fed whole and a character at a time: + /// no screen may depend on where a read split. Ignored for its run + /// time; `cargo test -- --ignored motions_never_depend` runs it. + #[test] + #[ignore = "a bounded random search, run by hand"] + fn motions_never_depend_on_the_split() { + const PIECES: &[&str] = &[ + "abcde", + "x", + "\u{6f22}", + "\r", + "\n", + "\r\n", + "\x1b[41m", + "\x1b[0m", + "\x1b[2G", + "\x1b[5G", + "\x1b[@", + "\x1b[2@", + "\x1b[3;2H", + ]; + let mut seed: u64 = 0x0814_0820_0821_0822; + let mut next = move |n: usize| { + seed = seed + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + usize::try_from(seed >> 33).unwrap() % n + }; + for case in 0..4000 { + let stream: String = (0..12).map(|_| PIECES[next(PIECES.len())]).collect(); + let (whole, bytewise) = whole_and_bytewise(4, 6, 2, stream.as_bytes()); + assert_eq!( + observed(&whole), + observed(&bytewise), + "case {case}: {stream:?}" + ); + } + } } From 88287463f4d7cc6ca3ae3624d0b7146b52d7aa2f Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:05:15 +0700 Subject: [PATCH 2/4] fix(emu): move as xterm does around scroll margins and origin mode termlens handed DECSTBM, CUD, CUU, CNL, CPL, RI and VPA to vt100, which differs from xterm in five places: - DECSTBM homed to the top margin; xterm's CASE_DECSTBM (charproc.c 4773) homes with CursorSet, to row 0 outside origin mode. - An invalid DECSTBM removed the region; xterm sets one only if its bottom is below its top and otherwise ignores the sequence. - CUD and CUU (and CNL, CPL) from outside the region went to the screen's edge; xterm's CursorDown and CursorUp (cursor.c 251, 271) stop at the near margin unless the cursor starts beyond it. - RI at row 0 above the region scrolled the region; xterm's RevIndex (cursor.c 319) is CursorUp there. - VPA ignored origin mode; xterm's CASE_VPA counts from the top margin and clamps to the bottom one. The tracker now reads DECSTBM by xterm's rule, which set_margins and so the cursor report follow, and names each of these as a Motion. The emulator feeds the final byte to vt100 where vt100 agrees, and where it does not, replaces it with a sequence vte ignores and moves the cursor with VPA and CHA, which vt100 takes as absolute in every mode. Closes #821 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 11 ++ crates/termlens/src/emu/seq.rs | 79 ++++++++++--- crates/termlens/src/emu/vt100.rs | 193 ++++++++++++++++++++++++++++++- docs/DESIGN.md | 4 +- 4 files changed, 270 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc3e319..78095e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,17 @@ reads that marker. termlens kept the character whole and inserted the blank after it, `漢 x`. A test that expected the character after such an insert should expect blanks in its place. (#822) +- The scroll region and origin mode move the cursor as xterm's do. + `DECSTBM` homes the cursor to row 0 outside origin mode, where it went + to the top margin, and a region whose bottom is not below its top is + ignored, where it removed the region. `CUD`, `CNL`, `CUU` and `CPL` + from outside the region stop at its near margin, where they went on to + the screen's edge. `RI` above the region moves the cursor up and + scrolls nothing, where at row 0 it scrolled the region down. And `VPA` + under origin mode counts from the top margin and stops at the bottom + one, where it counted from row 0. A test that expected the old + positions should expect xterm's: a program that writes a header with + `CSI 3;5 r` then text now draws it at the top-left. (#821) ### Fixed diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index 35175fa..d4ddebe 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -308,6 +308,34 @@ pub(crate) enum Motion { /// `ICH` (`CSI Ps @`): insert `n` blank cells at the cursor. xterm /// erases a wide character the cursor splits first (#822). InsertChars(u16), + /// `CUU` (`CSI Ps A`): up `n` rows. xterm stops at the top margin + /// unless the cursor starts above it (`CursorUp`, cursor.c 271); + /// vt100 stops there only from inside the region (#821). + Up(u16), + /// `CUD` (`CSI Ps B`): down `n` rows, stopping at the bottom margin + /// unless the cursor starts below it (`CursorDown`, cursor.c 251). + Down(u16), + /// `CNL` (`CSI Ps E`): [`Down`](Self::Down) and a carriage return + /// (`CursorNextLine`, cursor.c 527). + NextLine(u16), + /// `CPL` (`CSI Ps F`): [`Up`](Self::Up) and a carriage return. + PrevLine(u16), + /// `VPA` (`CSI Ps d`): to row `n`, counted from one. xterm counts it + /// from the top margin under origin mode and clamps it to the bottom + /// one (`CASE_VPA` through `CursorSet`, charproc.c 3952); vt100 counts + /// from the top of the screen whatever the mode (#821). + Row(u16), + /// `RI` (`ESC M`). xterm scrolls only at the top margin, and above + /// the region it is `CursorUp` (`RevIndex`, cursor.c 319); vt100 + /// scrolled the region from row 0 above it (#821). + ReverseIndex, + /// `DECSTBM` (`CSI Pt ; Pb r`). xterm sets a region only when its + /// bottom is below its top, ignores the sequence otherwise, and homes + /// the cursor to row 0 outside origin mode (`CASE_DECSTBM`, charproc.c + /// 4773). vt100 took an invalid region for none and homed to the top + /// margin (#821). `valid` is xterm's test, which the tracker has + /// already applied to the margins it holds. + Margins { valid: bool }, } /// Which glyph set a G0–G3 designation currently names. @@ -343,7 +371,9 @@ struct SavedCharsets { /// region (#686). They follow vt100's rules rather than xterm's wherever /// the two differ, since a report is read back as a `CUP` that vt100 /// carries out, and vt100 decides whether a line moves: a region per grid, -/// `1049` clearing the alternate grid's, a resize clearing both. +/// `1049` clearing the alternate grid's, a resize clearing both. The one +/// exception is `DECSTBM` itself, which follows xterm's rule: the emulator +/// keeps a region xterm ignores from vt100, so the two agree (#821). /// The charset slot is xterm's `screen->sc[screen->whichBuf]`, one per /// screen, so a restore on the main screen never reads what the alternate /// screen saved (#685). @@ -1281,6 +1311,12 @@ impl SeqTracker { self.frame().bottom.unwrap_or(self.rows - 1) } + /// The top margin of the screen on display, 0-based: the region's + /// first row, or 0 with no region set. + pub(crate) fn top_margin(&self) -> u16 { + self.frame().top + } + /// Whether origin mode (`DECOM`) is set on the screen on display. pub(crate) fn origin_mode(&self) -> bool { self.frame().origin @@ -1329,11 +1365,13 @@ impl SeqTracker { frame.origin = frame.saved_origin; } - /// `DECSTBM` (`CSI Pt ; Pb r`), read as vt100 reads it: an omitted or - /// zero margin is the screen's edge, a bottom past the screen is its - /// last row, and a region that does not have its top above its bottom - /// is no region at all. - fn set_margins(&mut self) { + /// `DECSTBM` (`CSI Pt ; Pb r`), read as xterm reads it (`CASE_DECSTBM`, + /// charproc.c 4773): an omitted or zero margin is the screen's edge, a + /// bottom past the screen is its last row, and a region that does not + /// have its top above its bottom is ignored, leaving the region as it + /// was. vt100 took that one for no region at all, and the emulator now + /// keeps it from vt100 (#821). Returns whether the region was set. + fn set_margins(&mut self) -> bool { let given = |param: u32, default: u16| match u16::try_from(param).unwrap_or(u16::MAX) { 0 => default, value => value, @@ -1349,12 +1387,12 @@ impl SeqTracker { given(self.csi_second_param, self.rows) }; let (top, bottom) = (top - 1, (bottom - 1).min(self.rows - 1)); + if top >= bottom { + return false; + } let frame = self.frame_mut(); - (frame.top, frame.bottom) = if top < bottom { - (top, Some(bottom)) - } else { - (0, None) - }; + (frame.top, frame.bottom) = (top, Some(bottom)); + true } /// Set or reset one of the modes that move a [`ScreenFrame`], in vt100's @@ -2042,7 +2080,10 @@ impl SeqTracker { // of 2026, whose Begin returns from a list that names one of these // too. match (self.csi_prefix, b) { - (0, b'r') => self.set_margins(), + (0, b'r') => { + let valid = self.set_margins(); + return SeqEvent::Motion(Motion::Margins { valid }); + } // SCOSC / SCORC. With a parameter `CSI s` is DECSLRM in xterm // and `CSI u` belongs to kitty's keyboard protocol. (0, b's') if params_empty => self.save_charsets(), @@ -2184,8 +2225,14 @@ impl SeqTracker { } b'I' => return SeqEvent::Tabs(TabOp::Forward(count)), b'Z' => return SeqEvent::Tabs(TabOp::Back(count)), - // ICH by its first parameter, as vt100 and xterm read it. + // ICH and the vertical motions by their first parameter, + // as vt100 and xterm read them. b'@' => return SeqEvent::Motion(Motion::InsertChars(count)), + b'A' => return SeqEvent::Motion(Motion::Up(count)), + b'B' => return SeqEvent::Motion(Motion::Down(count)), + b'E' => return SeqEvent::Motion(Motion::NextLine(count)), + b'F' => return SeqEvent::Motion(Motion::PrevLine(count)), + b'd' => return SeqEvent::Motion(Motion::Row(count)), // ED 3, erase the saved lines. vt100 reads the first // parameter alone, and so does this. b'J' if ps == 3 => return SeqEvent::ScrollbackErased, @@ -3053,6 +3100,12 @@ impl SeqTracker { }; State::Ground } + // RI, which the emulator carries out where it differs from + // vt100's (#821). + b'M' => { + event = SeqEvent::Motion(Motion::ReverseIndex); + State::Ground + } // DECID, the VT100's DA1 (#833). b'Z' => { event = SeqEvent::Query(Query::Decid); diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index 01f4078..4318b14 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -984,7 +984,36 @@ impl Vt100Emulator { /// so the shadow keeps the same shape. fn carry_out(&mut self, motion: Motion, last: &[u8]) { let screen = self.parser.screen(); + let (_, cols) = size(screen); let (row, col) = screen.cursor_position(); + let (top, bottom) = (self.tracker.top_margin(), self.tracker.bottom_margin()); + let origin = self.tracker.origin_mode(); + // The column a vertical motion keeps, and the row xterm's leaves + // the cursor on, when vt100's would differ: from outside the + // region xterm stops at the near margin where vt100 goes on to + // the screen's edge, and under origin mode VPA counts from the top + // margin where vt100 counts from row 0. Inside the region and + // outside origin mode vt100 already does what xterm does. + let col_kept = col.min(cols - 1); + let vertical = match motion { + Motion::Up(n) | Motion::PrevLine(n) if row > bottom => { + Some(row.saturating_sub(n).max(top)) + } + Motion::Down(n) | Motion::NextLine(n) if row < top => { + Some(row.saturating_add(n).min(bottom)) + } + Motion::Row(n) if origin => Some((n - 1).saturating_add(top).min(bottom)), + _ => None, + }; + if let Some(to) = vertical { + let col = match motion { + Motion::NextLine(_) | Motion::PrevLine(_) => 0, + _ => col_kept, + }; + self.feed(CSI_IGNORED); + self.move_to(to, col); + return; + } match motion { Motion::InsertChars(n) => { // xterm's `InsertChar` (util.c 1887) repairs a wide @@ -1006,8 +1035,38 @@ impl Vt100Emulator { self.feed(last); } } + // Above the region xterm's `RI` is `CursorUp`, which stops at + // row 0; vt100 scrolled the region down from there. The escape + // is taken from vt100 as `IND`'s is. + Motion::ReverseIndex if row < top => { + self.feed(ESC_IGNORED); + self.move_to(row.saturating_sub(1), col_kept); + } + // An ignored region is ignored whole, the cursor included. A + // region set homes the cursor to row 0 outside origin mode; + // vt100 homes it to the top margin, where origin mode puts it. + Motion::Margins { valid: false } => self.feed(CSI_IGNORED), + Motion::Margins { valid: true } => { + self.feed(last); + if !origin { + self.feed(b"\x1b[H"); + } + } + Motion::Up(_) + | Motion::Down(_) + | Motion::NextLine(_) + | Motion::PrevLine(_) + | Motion::Row(_) + | Motion::ReverseIndex => self.feed(last), } } + + /// Move the cursor to `row`, `col` of the screen, whatever the margins + /// and origin mode: vt100's `VPA` and `CHA` count from the top-left + /// corner in every mode. + fn move_to(&mut self, row: u16, col: u16) { + self.feed(format!("\x1b[{}d\x1b[{}G", row + 1, col + 1).as_bytes()); + } } impl Emulator for Vt100Emulator { @@ -3219,7 +3278,16 @@ mod tests { // xterm's: at a pending wrap, from the last column // (#809). let pending = raw.screen().cursor_position().1 >= cols; - raw.process(piece.as_bytes()); + // And sets a region as xterm does: one whose bottom is + // not below its top is ignored, and a region set homes + // the cursor to row 0 (#821). + let region = piece.ends_with('r'); + if !region || piece == "\x1b[r" || rows > 2 { + raw.process(piece.as_bytes()); + if region { + raw.process(b"\x1b[H"); + } + } if piece == "\x1b[K" && pending { raw.process(format!("\x1b[{cols}G\x1b[K").as_bytes()); } @@ -5371,9 +5439,10 @@ mod tests { (3, 0), ), // A resize clears the region, and a region that is no region - // leaves the whole screen one. + // is ignored, as xterm ignores it (#821): the one before stays. ("\x1b[1;2r\x1b[3;3rRESIZE\x1b[4;5H\x1b[LX", (3, 0)), - ("\x1b[1;2r\x1b[3;3r\x1b[4;5H\x1b[LX", (3, 0)), + ("\x1b[1;2r\x1b[3;3r\x1b[4;5H\x1b[LX", (3, 4)), + ("\x1b[3;3r\x1b[4;5H\x1b[LX", (3, 0)), ("\x1b[1;2r\x1b[4;5H\x1b[LX", (3, 4)), ] { let (before, after) = stream.split_once("RESIZE").unwrap_or((stream, "")); @@ -5500,6 +5569,112 @@ mod tests { assert_eq!(s.cell(0, 0).unwrap().style().bg, Color::Indexed(1), "{s}"); } + /// The scroll region and origin mode move the cursor as xterm's do + /// (#821): `DECSTBM` sets a region only when its bottom is below its + /// top and homes to row 0 outside origin mode (`CASE_DECSTBM`, + /// charproc.c 4773); `CUD`, `CUU`, `CNL` and `CPL` stop at the near + /// margin from outside the region (`CursorDown` and `CursorUp`, + /// cursor.c 251 and 271); `RI` above the region is `CursorUp` + /// (`RevIndex`, cursor.c 319); and `VPA` under origin mode counts from + /// the top margin and stops at the bottom one (`CASE_VPA`, charproc.c + /// 3952). One case per row of the issue's table, on 10x6. + #[test] + fn the_scroll_region_and_origin_mode_move_the_cursor_as_xterm_does() { + let rows = "0\r\n1\r\n2\r\n3\r\n4\r\n5"; + for (stream, text, cursor) in [ + // a + ("top\x1b[3;5rX".to_owned(), "Xop\n\n\n\n\n", (0, 1)), + // b + ( + format!("{rows}\x1b[2;4r\x1b[4;4r\x1b[4;1H\nX"), + "0\n2\n3\nX\n4\n5", + (3, 1), + ), + ( + format!("{rows}\x1b[2;4r\x1b[9;99r\x1b[4;1H\nX"), + "0\n2\n3\nX\n4\n5", + (3, 1), + ), + // c + ( + "\x1b[3;4r\x1b[1;1H\x1b[10BX".to_owned(), + "\n\n\nX\n\n", + (3, 1), + ), + ( + "\x1b[2;3r\x1b[6;1H\x1b[10AX".to_owned(), + "\nX\n\n\n\n", + (1, 1), + ), + ( + "\x1b[3;4r\x1b[1;5H\x1b[10EX".to_owned(), + "\n\n\nX\n\n", + (3, 1), + ), + ( + "\x1b[2;3r\x1b[6;5H\x1b[10FX".to_owned(), + "\nX\n\n\n\n", + (1, 1), + ), + // From inside the region the margins stop them, as before. + ( + "\x1b[2;3r\x1b[2;1H\x1b[10BX".to_owned(), + "\n\nX\n\n\n", + (2, 1), + ), + ( + "\x1b[2;3r\x1b[3;1H\x1b[10AX".to_owned(), + "\nX\n\n\n\n", + (1, 1), + ), + // d + ( + format!("{rows}\x1b[3;5r\x1b[1;1H\x1bM"), + "0\n1\n2\n3\n4\n5", + (0, 0), + ), + ( + format!("{rows}\x1b[3;5r\x1b[2;3H\x1bMX"), + "0 X\n1\n2\n3\n4\n5", + (0, 3), + ), + // At the top margin it still scrolls the region. + ( + format!("{rows}\x1b[3;5r\x1b[3;1H\x1bM"), + "0\n1\n\n2\n3\n5", + (2, 0), + ), + // e + ( + "\x1b[3;5r\x1b[?6h\x1b[1dX".to_owned(), + "\n\nX\n\n\n", + (2, 1), + ), + ( + "\x1b[3;5r\x1b[?6h\x1b[9dX".to_owned(), + "\n\n\n\nX\n", + (4, 1), + ), + ("\x1b[3;5r\x1b[1dX".to_owned(), "X\n\n\n\n\n", (0, 1)), + ] { + let (whole, bytewise) = whole_and_bytewise(6, 10, 0, stream.as_bytes()); + assert_eq!(observed(&whole), observed(&bytewise), "{stream:?}"); + let s = whole.snapshot(); + assert_eq!(s.text(), text, "{stream:?}: {s}"); + assert_eq!((s.cursor().0, s.cursor().1), cursor, "{stream:?}: {s}"); + assert!( + s.unsupported().is_empty(), + "{stream:?}: {:?}", + s.unsupported() + ); + } + // The report counts from the margin xterm's `DECSTBM` left set, + // under origin mode: an ignored region leaves the one before. + let emu = emu_with_size(6, 10, b"\x1b[2;4r\x1b[4;4r\x1b[?6h\x1b[2;3H"); + assert_eq!(emu.reported_position(), (1, 2)); + assert_eq!(emu.snapshot().cursor(), (2, 2, true)); + } + /// Random short streams of the motions and edits the emulator carries /// out itself (#814, #820, #821, #822), mixed with text, wide /// characters, controls and SGR, fed whole and a character at a time: @@ -5522,6 +5697,18 @@ mod tests { "\x1b[@", "\x1b[2@", "\x1b[3;2H", + "\x1b[2;3r", + "\x1b[3;3r", + "\x1b[r", + "\x1b[?6h", + "\x1b[?6l", + "\x1b[3A", + "\x1b[3B", + "\x1b[2E", + "\x1b[2F", + "\x1b[2d", + "\x1b[9d", + "\x1bM", ]; let mut seed: u64 = 0x0814_0820_0821_0822; let mut next = move |n: usize| { diff --git a/docs/DESIGN.md b/docs/DESIGN.md index b43e9c2..6912c50 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -131,7 +131,9 @@ it. Under origin mode (`DECOM`) the report counts rows from the top margin, as xterm's does, so an application that restores the position with `CUP` lands where it was; the backend keeps neither the margins nor the mode where termlens can read them, so the sequence tracker follows -both, by the backend's rules (#689). Replies are built under the state +both (#689). A region is set by xterm's rule, which the emulator holds +the backend to, and so are the motions the margins and origin mode stop +or count from (#821). Replies are built under the state lock but written after it is released — the state lock and the writer lock are never held together. From eb41d3aeea7da0b848deb948ab9793dafddeb049 Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:10:15 +0700 Subject: [PATCH 3/4] fix(emu): keep the cursor and margins across screen switches vt100 keeps a cursor, a scroll region and origin mode per grid, and `?1049h` clears the alternate grid's, so `?1049h` and `?47h` put the cursor at the alternate screen's top-left with no region, and `?47l` put it back where the main screen last had it. In xterm all three belong to the terminal: SwitchBufs (charproc.c 9564) swaps the line buffers and moves neither the cursor nor top_marg and bot_marg, and ORIGIN is one of its flags. Every child enters through smcup, which is `?1049h`, so the cursor after start-up differed from xterm's. The tracker now carries the margins and origin mode across 47 and 1049, and the emulator feeds the switch's final byte alone, then sets the new grid's region and origin mode from the tracker and puts the cursor back: where it was, or for `?1049h` on the last column with the wrap reset by ClearScreen, or for `?1049l` where vt100 restored it. Two corners stay apart from xterm and are listed in LIMITATIONS: a pending wrap carried by `?47` onto a blank last column, and a list that names origin mode with the switch. Closes #820 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 9 ++ crates/termlens/src/emu/seq.rs | 37 ++++-- crates/termlens/src/emu/vt100.rs | 200 +++++++++++++++++++++++++++---- docs/DESIGN.md | 4 +- docs/LIMITATIONS.md | 11 ++ 5 files changed, 228 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78095e3..f78fe2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -119,6 +119,15 @@ reads that marker. one, where it counted from row 0. A test that expected the old positions should expect xterm's: a program that writes a header with `CSI 3;5 r` then text now draws it at the top-left. (#821) +- A switch of screens keeps the cursor, the scroll region and origin + mode, as xterm's does, which keeps one of each for both screens. + `CSI ? 1049 h` and `CSI ? 47 h` left the cursor at the top-left of the + alternate screen with no region and origin mode off, and `CSI ? 47 l` + put it back where the main screen last had it; `CSI ? 1049 l` still + restores the cursor `CSI ? 1049 h` saved. Every child enters through + `smcup`, which is `CSI ? 1049 h`, so a test that asserted the cursor at + 0,0 right after start-up should expect it where the program left it on + the main screen, or have the program position it first. (#820) ### Fixed diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index d4ddebe..432b887 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -368,12 +368,13 @@ struct SavedCharsets { /// The margins and origin mode are kept for the cursor position report, /// which counts rows from the top margin under origin mode (#689), and for /// `IL` and `DL`, which move the cursor to the left margin only inside the -/// region (#686). They follow vt100's rules rather than xterm's wherever -/// the two differ, since a report is read back as a `CUP` that vt100 -/// carries out, and vt100 decides whether a line moves: a region per grid, -/// `1049` clearing the alternate grid's, a resize clearing both. The one -/// exception is `DECSTBM` itself, which follows xterm's rule: the emulator -/// keeps a region xterm ignores from vt100, so the two agree (#821). +/// region (#686). They must be the ones vt100 holds, since a report is +/// read back as a `CUP` that vt100 carries out, and vt100 decides whether +/// a line moves. Where vt100's rules differ from xterm's, the emulator +/// holds vt100 to xterm's, and these follow them: `DECSTBM` ignores a +/// region whose bottom is not below its top (#821), a switch of screens +/// carries the margins and origin mode across, as xterm keeps one set of +/// each (#820), and a resize clears both screens'. /// The charset slot is xterm's `screen->sc[screen->whichBuf]`, one per /// screen, so a restore on the main screen never reads what the alternate /// screen saved (#685). @@ -1396,8 +1397,15 @@ impl SeqTracker { } /// Set or reset one of the modes that move a [`ScreenFrame`], in vt100's - /// way. + /// way, but for the margins and origin mode, which go with a switch of + /// screens: xterm keeps one set of each, beside the cursor, for both + /// (`SwitchBufs`, charproc.c 9564, moves neither), and the emulator + /// carries vt100's across to match (#820). fn set_frame_mode(&mut self, mode: u16, set: bool) { + let carried = { + let frame = self.frame(); + (frame.top, frame.bottom, frame.origin) + }; match (mode, set) { (6, _) => self.frame_mut().origin = set, (47, _) => self.alternate = set, @@ -1420,10 +1428,25 @@ impl SeqTracker { } (1049, false) => { self.alternate = false; + let frame = self.frame_mut(); + (frame.top, frame.bottom, frame.origin) = carried; self.restore_cursor(); + return; } _ => {} } + if matches!(mode, 47 | 1049) { + let frame = self.frame_mut(); + (frame.top, frame.bottom, frame.origin) = carried; + } + } + + /// Whether the CSI just completed named `1049`, whose reset restores + /// the cursor saved on the main screen and whose set clears a pending + /// wrap with the screen, where `47` moves the cursor in neither + /// direction (charproc.c 7732 and 7759). + pub(crate) fn named_1049(&self) -> bool { + self.csi_frame_modes[..usize::from(self.csi_frame_mode_count)].contains(&1049) } /// Carry out a [`TabOp`] at cursor column `col`, returning the column the diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index 4318b14..13f7390 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -1067,6 +1067,58 @@ impl Vt100Emulator { fn move_to(&mut self, row: u16, col: u16) { self.feed(format!("\x1b[{}d\x1b[{}G", row + 1, col + 1).as_bytes()); } + + /// [`move_to`](Self::move_to), or for the column past the last, where + /// vt100 keeps a cursor pending wrap, the last column drawn again, + /// which is the one way to put a cursor back there (#753). + fn place_cursor(&mut self, row: u16, col: u16) { + let (_, cols) = size(self.parser.screen()); + if col < cols { + self.move_to(row, col); + } else { + self.feed(format!("\x1b[{}d", row + 1).as_bytes()); + self.redraw_last_column(row); + } + } + + /// Carry the cursor, the margins and origin mode across a switch of + /// screens, which vt100 keeps per grid and xterm per terminal: + /// `SwitchBufs` (charproc.c 9564) swaps the line buffers and moves + /// neither the cursor nor `top_marg` and `bot_marg`, and origin mode is + /// one of the terminal's flags (#820). vt100 put the cursor where the + /// other grid last had it, and `?1049h` cleared the alternate grid's + /// cursor, region and mode, so `ab` CR LF `abc` `CSI ? 1049 h` `X` drew + /// the `X` at the top-left. + /// + /// `before` is the cursor and the screen on display before the switch's + /// final byte. The margins and the mode are the tracker's, which has + /// carried them already. The cursor is the one before the switch, but + /// for `1049`: its set clears the screen, which resets a pending wrap + /// (`ClearScreen`, util.c 2356), and its reset restores the cursor + /// saved on the main screen, as vt100 has done (charproc.c 7732). A + /// list that also names `6` homes the cursor on one side of the switch + /// or the other; it is carried from before the list, as if it named the + /// switch alone. + fn carry_across_switch(&mut self, before: ((u16, u16), bool), leaving: bool) { + let ((row, col), was_alternate) = before; + let screen = self.parser.screen(); + let switched = screen.alternate_screen() != was_alternate; + let named_1049 = self.tracker.named_1049(); + if !switched && !named_1049 { + return; + } + let (_, cols) = size(screen); + let (row, col) = match (named_1049, leaving) { + (true, true) => screen.cursor_position(), + (true, false) => (row, col.min(cols - 1)), + (false, _) => (row, col), + }; + let (top, bottom) = (self.tracker.top_margin(), self.tracker.bottom_margin()); + let origin = if self.tracker.origin_mode() { 'h' } else { 'l' }; + // Both home the cursor in vt100, which is put back after them. + self.feed(format!("\x1b[{};{}r\x1b[?6{origin}", top + 1, bottom + 1).as_bytes()); + self.place_cursor(row, col); + } } impl Emulator for Vt100Emulator { @@ -1195,19 +1247,27 @@ impl Emulator for Vt100Emulator { // On the way in, everything before the final byte goes // first, so the capture that feed runs reads the main // screen's history while it is still the one on display - // (#622); the final byte goes with the rest of the read. + // (#622). // - // On the way out the final byte goes too, so that - // capture reads the main screen back before the rest of - // the read scrolls it. A taller resize while it was + // On the way out the final byte's own feed is the + // capture that reads the main screen back, before the + // rest of the read scrolls it. A taller resize while it was // hidden pulled rows back out of its history; settled in // one feed with new rows scrolling off, the rows pulled // back and the rows pushed cancelled in the length, and // the copy kept a row the grid had taken back and lost // the row that scrolled, by where the read split (#682). - let end = if leaving { i + 1 } else { i }; - self.feed_staged(&bytes[fed..end]); - fed = end; + // + // The final byte is fed alone both ways, so the cursor + // and the margins can be carried across the switch as + // xterm keeps them (#820): read before it, and set on + // the new screen after it. + self.feed_staged(&bytes[fed..i]); + let screen = self.parser.screen(); + let before = (screen.cursor_position(), screen.alternate_screen()); + self.feed_staged(&bytes[i..=i]); + fed = i + 1; + self.carry_across_switch(before, leaving); None } SeqEvent::Tabs(op) => { @@ -2075,7 +2135,7 @@ mod tests { let emu = emu_with(b"\x1b[9mstruck\x1b[?1049hALT"); let s = emu.snapshot(); - assert!(s.cell(0, 0).unwrap().style().strikethrough, "{s}"); + assert!(s.cell(0, 6).unwrap().style().strikethrough, "{s}"); } /// A 96-character or a `%` designation replaces the set in force, as @@ -2892,13 +2952,15 @@ mod tests { // The alternate screen keeps no history, so it grows at the // bottom; the main screen behind it moves down only by the rows // its history holds, as when it is on display (#684). After the - // exit the cursor is back after the `e`. - for (scrollback, text) in [ - (0, "c\nd\neX\n\n\n"), - (1, "b\nc\nd\neX\n\n"), - (1000, "a\nb\nc\nd\neX\n"), + // exit of `1049` the cursor is back after the `e`; `47` saves + // nothing and keeps the cursor where the alternate screen left it, + // as xterm does (#820). + for (scrollback, saved, kept) in [ + (0, "c\nd\neX\n\n\n", "c X\nd\ne\n\n\n"), + (1, "b\nc\nd\neX\n\n", "b X\nc\nd\ne\n\n"), + (1000, "a\nb\nc\nd\neX\n", "a X\nb\nc\nd\ne\n"), ] { - for enter in ["\x1b[?1049h", "\x1b[?47h"] { + for (enter, text) in [("\x1b[?1049h", saved), ("\x1b[?47h", kept)] { let mut emu = Vt100Emulator::new(3, 10, scrollback, crate::graphics::DEFAULT_CAPTURE, false); feed_all(&mut emu, b"a\r\nb\r\nc\r\nd\r\ne"); @@ -2907,8 +2969,6 @@ mod tests { let s = emu.snapshot(); assert_eq!(s.text(), "TUI\n\n\n\n\n", "{enter:?}"); assert_eq!((s.cursor().0, s.cursor().1), (0, 3), "{enter:?}"); - // `47` saves nothing, and the main grid's own cursor moved - // with its text. feed_all(&mut emu, format!("{}X", enter.replace('h', "l")).as_bytes()); let s = emu.snapshot(); assert_eq!(s.text(), text, "scrollback({scrollback}), {enter:?}"); @@ -2931,7 +2991,7 @@ mod tests { let mut emu = Vt100Emulator::new(3, 10, 0, crate::graphics::DEFAULT_CAPTURE, false); feed_all( &mut emu, - format!("a\r\nb\r\nc\r\nd\x1b[?1049h{open}").as_bytes(), + format!("a\r\nb\r\nc\r\nd\x1b[?1049h\x1b[H{open}").as_bytes(), ); emu.set_size(6, 10); feed_all(&mut emu, close.as_bytes()); @@ -3253,11 +3313,17 @@ mod tests { let mut raw = ::vt100::Parser::new(nz(rows), nz(cols), 5); // Whether the copy is vt100's history, or only ends with it. let mut exact = true; + // The region set, one-based, as termlens carries it. + let mut margins: Option<(u16, u16)> = None; for step in 0..40 { let alternate = raw.screen().alternate_screen(); if next(5) == 0 { + let was = (rows, cols); rows = 2 + u16::try_from(next(5)).unwrap(); cols = 3 + u16::try_from(next(10)).unwrap(); + if (rows, cols) != was { + margins = None; + } // The reference resizes as termlens does, which is // vt100's but for where a taller screen's new rows go // (#684): the rows each history holds are the same. @@ -3282,10 +3348,32 @@ mod tests { // not below its top is ignored, and a region set homes // the cursor to row 0 (#821). let region = piece.ends_with('r'); + let before = raw.screen().cursor_position(); if !region || piece == "\x1b[r" || rows > 2 { raw.process(piece.as_bytes()); if region { raw.process(b"\x1b[H"); + margins = (piece != "\x1b[r").then_some((2, 3)); + } + } + if piece == "\x1bc" { + margins = None; + } + // And carries the cursor and the region across a + // switch of screens (#820): the cursor from before + // `1049h`, with no wrap pending, and the one `1049l` + // restored, which a save and a restore keep across the + // region's homing here. + if piece.starts_with("\x1b[?1049") { + let set = margins.map_or_else( + || "\x1b[r".to_owned(), + |(top, bottom)| format!("\x1b[{top};{bottom}r"), + ); + if piece.ends_with('h') { + let (row, col) = (before.0 + 1, before.1.min(cols - 1) + 1); + raw.process(format!("{set}\x1b[{row};{col}H").as_bytes()); + } else { + raw.process(format!("\x1b7{set}\x1b8").as_bytes()); } } if piece == "\x1b[K" && pending { @@ -5131,16 +5219,20 @@ mod tests { /// its own in vt100, and the ANSI form reports insert mode; both were /// "not recognized" or unanswered (#830). #[test] - fn decrqm_reports_origin_mode_per_screen_and_insert_mode() { + fn decrqm_reports_origin_mode_across_screens_and_insert_mode() { let mut emu = emu_with(b"\x1b[?6h\x1b[4h"); assert_eq!(emu.mode_state(6), ModeState::Set); assert_eq!(emu.ansi_mode_state(4), ModeState::Set); assert_eq!(emu.ansi_mode_state(20), ModeState::NotRecognized); + // Origin mode is one of xterm's flags, not a screen's: it goes + // with a switch (#820), and `1049` restores the one it saved. feed_all(&mut emu, b"\x1b[?1049h"); - assert_eq!(emu.mode_state(6), ModeState::Reset, "the alternate screen"); - feed_all(&mut emu, b"\x1b[?1049l\x1b[4l"); + assert_eq!(emu.mode_state(6), ModeState::Set, "the alternate screen"); + feed_all(&mut emu, b"\x1b[?6l\x1b[?1049l\x1b[4l"); assert_eq!(emu.mode_state(6), ModeState::Set, "the main screen again"); assert_eq!(emu.ansi_mode_state(4), ModeState::Reset); + feed_all(&mut emu, b"\x1b[?47h\x1b[?6l\x1b[?47l"); + assert_eq!(emu.mode_state(6), ModeState::Reset, "back from `47`"); } /// `DECSTR` clears the rendition, as xterm's soft reset does: a @@ -5420,15 +5512,17 @@ mod tests { #[test] fn insert_and_delete_line_outside_the_region_leave_the_cursor() { // Outside the scroll region xterm ignores both, and so does vt100: - // the cursor keeps its column. On the margins it is inside. Each - // screen has its own region: `47` keeps the alternate grid's, and - // `1049` clears it (#686). + // the cursor keeps its column. On the margins it is inside (#686). + // The region goes with a switch of screens, as xterm keeps one for + // both (#820). for (stream, at) in [ ("\x1b[2;3r\x1b[4;5H\x1b[LX", (3, 4)), ("\x1b[2;3r\x1b[1;5H\x1b[MX", (0, 4)), ("\x1b[2;3r\x1b[3;5H\x1b[LX", (2, 0)), ("\x1b[2;3r\x1b[2;5H\x1b[MX", (1, 0)), - ("\x1b[2;3r\x1b[?47h\x1b[4;5H\x1b[LX", (3, 0)), + ("\x1b[2;3r\x1b[?47h\x1b[4;5H\x1b[LX", (3, 4)), + ("\x1b[2;3r\x1b[?1049h\x1b[4;5H\x1b[LX", (3, 4)), + ("\x1b[2;3r\x1b[?47h\x1b[r\x1b[?47l\x1b[4;5H\x1b[LX", (3, 0)), ("\x1b[2;3r\x1b[?47h\x1b[?47l\x1b[4;5H\x1b[LX", (3, 4)), ( "\x1b[?47h\x1b[1;2r\x1b[?47l\x1b[?47h\x1b[4;5H\x1b[LX", @@ -5436,7 +5530,7 @@ mod tests { ), ( "\x1b[?47h\x1b[1;2r\x1b[?47l\x1b[?1049h\x1b[4;5H\x1b[LX", - (3, 0), + (3, 4), ), // A resize clears the region, and a region that is no region // is ignored, as xterm ignores it (#821): the one before stays. @@ -5675,6 +5769,56 @@ mod tests { assert_eq!(emu.snapshot().cursor(), (2, 2, true)); } + /// A switch of screens keeps the cursor, the scroll region and origin + /// mode, as xterm's does: `SwitchBufs` (charproc.c 9564) swaps the + /// line buffers and moves neither the cursor nor the margins, and + /// origin mode is one of the terminal's flags. vt100 keeps all three + /// per grid, and `?1049h` cleared the alternate grid's (#820). One case + /// per row of the issue's table, on 10x4. + #[test] + fn a_switch_of_screens_keeps_the_cursor_and_the_region() { + for (stream, text, cursor) in [ + ("ab\r\nabc\x1b[?1049hX", "\n X\n\n", (1, 4)), + ("ab\r\nabc\x1b[?47hX", "\n X\n\n", (1, 4)), + ("abc\x1b[?47h\x1b[4;6H\x1b[?47lX", "abc\n\n\n X", (3, 6)), + ( + "\x1b[2;3r\x1b[?1049h\x1b[2;1Ha\r\nb\r\nc", + "\nb\nc\n", + (2, 1), + ), + // Origin mode goes across too, and `CUP` counts from the + // region's top on the alternate screen. + ("\x1b[2;3r\x1b[?6h\x1b[?1049h\x1b[1;1HX", "\nX\n\n", (1, 1)), + // The region set on the alternate screen comes back with + // `47`, and `1049` restores the cursor it saved. + ( + "\x1b[3;4H\x1b[?1049h\x1b[2;3r\x1b[?1049lX\x1b[3;1H\nY", + "\n X\nY\n", + (2, 1), + ), + ("\x1b[?47h\x1b[2;3r\x1b[?47l\x1b[3;1H\nX", "\n\nX\n", (2, 1)), + // `1049` clears the screen, and with it a pending wrap; `47` + // keeps one, and the next character starts the next row. + ("abcdefghij\x1b[?1049hX", " X\n\n\n", (0, 9)), + ("abcdefghij\x1b[?47hX", "\nX\n\n", (1, 1)), + ] { + let (whole, bytewise) = whole_and_bytewise(4, 10, 0, stream.as_bytes()); + assert_eq!(observed(&whole), observed(&bytewise), "{stream:?}"); + let s = whole.snapshot(); + assert_eq!(s.text(), text, "{stream:?}: {s}"); + assert_eq!((s.cursor().0, s.cursor().1), cursor, "{stream:?}: {s}"); + assert!( + s.unsupported().is_empty(), + "{stream:?}: {:?}", + s.unsupported() + ); + } + // The report counts from the carried margin under the carried mode. + let emu = emu_with(b"\x1b[2;3r\x1b[?6h\x1b[?1049h\x1b[2;2H"); + assert_eq!(emu.reported_position(), (1, 1)); + assert_eq!(emu.snapshot().cursor(), (2, 1, true)); + } + /// Random short streams of the motions and edits the emulator carries /// out itself (#814, #820, #821, #822), mixed with text, wide /// characters, controls and SGR, fed whole and a character at a time: @@ -5709,6 +5853,12 @@ mod tests { "\x1b[2d", "\x1b[9d", "\x1bM", + "\x1b[?1049h", + "\x1b[?1049l", + "\x1b[?47h", + "\x1b[?47l", + "\x1b7", + "\x1b8", ]; let mut seed: u64 = 0x0814_0820_0821_0822; let mut next = move |n: usize| { diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 6912c50..3d2a174 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -133,7 +133,9 @@ with `CUP` lands where it was; the backend keeps neither the margins nor the mode where termlens can read them, so the sequence tracker follows both (#689). A region is set by xterm's rule, which the emulator holds the backend to, and so are the motions the margins and origin mode stop -or count from (#821). Replies are built under the state +or count from (#821); a switch of screens carries the margins, the mode +and the cursor across, as xterm keeps one of each for both screens where +the backend keeps one per screen (#820). Replies are built under the state lock but written after it is released — the state lock and the writer lock are never held together. diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md index a096d55..88ed96d 100644 --- a/docs/LIMITATIONS.md +++ b/docs/LIMITATIONS.md @@ -101,6 +101,17 @@ CHANGELOG entry. `VPA` leave the wrap pending, `CUB` and `BS` land a column right of xterm's, and `ICH` and `DCH` change nothing (#814). The erases start from the last column and cancel the wrap, as xterm's do. +- **A switch of screens keeps the cursor, the scroll region and origin + mode**, as xterm's does: `?1049h`, `?47h` and `?47l` leave the cursor + where it was, and `?1049l` restores the one `?1049h` saved. Two cases + differ from xterm. A pending wrap carried by `?47` onto a screen whose + last column is blank there reads as the start of the next row, where + the next character lands, rather than as the last column (on the + bottom row that character then overwrites the row's start instead of + scrolling); and a list naming origin mode with the switch + (`CSI ? 6 ; 1049 h`) carries the cursor from before the list, where + xterm homes it (#820). `?1047` is not carried out at all, and + `unsupported()` names it. - **Tab stops are the application's to set.** `HTS` (`ESC H`), `TBC` (`CSI g`, `CSI 3 g`), `CHT` (`CSI I`) and `CBT` (`CSI Z`) all work, and a plain `\t` honours whatever stops are set rather than a fixed eight. From 8523aeaa483994dfcb381003686b0d93411fb96a Mon Sep 17 00:00:00 2001 From: Vyncint Ng <115854244+vyncint@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:16:14 +0700 Subject: [PATCH 4/4] fix(emu): leave a pending wrap from the last column, as xterm does After a character in the last column xterm keeps the cursor on that column with its wrap flag set, and CursorUp, CursorDown, CursorSet and CursorBack (cursor.c), InsertChar and DeleteChar (util.c) and the line feed, xtermIndex through CursorDown, reset the flag and work from that column. vt100 keeps the cursor one column past the margin, so CUU, CUD, VPA, RI and a line feed left the wrap pending, CUB and BS landed a column right of xterm's, and ICH and DCH changed nothing. CUB, DCH, LF (and VT, FF) and BS join the Motion events. At a pending wrap the CSIs are replaced by moves from the last column, the controls are preceded by a CHA to it, and IND cancels the wrap before its line feed. A line feed or backspace is checked against the grid only when a byte since the last carriage return could have left a wrap pending, so the common CR LF costs no split feed. The other way round, as the issue's comments note: xterm keeps the wrap through HT, CHT and CBT (set_cur_col never resets it) and through a resize (ScreenResize clamps with set_cur_col). HT and CHT at a pending wrap now move nothing, and a resize to a screen no wider draws the last column again to put the wrap back. CBT counts back from the last column but cannot keep the wrap on an earlier one, which vt100 cannot hold; that, a wider resize, a DECRC after a resize, and BS or LF inside an escape sequence are listed in LIMITATIONS. Closes #814 Signed-off-by: Vyncint Ng <115854244+vyncint@users.noreply.github.com> --- CHANGELOG.md | 15 ++ crates/termlens/src/emu/seq.rs | 33 ++++ crates/termlens/src/emu/vt100.rs | 290 ++++++++++++++++++++++++++++--- docs/LIMITATIONS.md | 23 ++- 4 files changed, 329 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f78fe2f..2266604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -128,6 +128,21 @@ reads that marker. `smcup`, which is `CSI ? 1049 h`, so a test that asserted the cursor at 0,0 right after start-up should expect it where the program left it on the main screen, or have the program position it first. (#820) +- At a pending wrap, the motions and edits xterm starts from the cursor's + column start from the last column and cancel the wrap, as xterm's do. + After a character in the last column, `CUU`, `CUD` and `VPA` leave the + cursor on the last column of the row they reach, `CUB` and `BS` count + left from it, `ICH` and `DCH` act on it, and a line feed (`LF`, `VT`, + `FF`, `IND`) and `RI` move from it, so on five columns `abcde` + `CSI D` `X` is `abcXe` and `abcde` LF `X` puts the `X` under the `e`. + `HT` and `CHT` there keep the wrap, and so does a resize to a screen no + wider, so the next character starts the next row. termlens kept the + cursor past the margin: the motions left the wrap pending, `CUB` and + `BS` landed a column right of xterm's, `ICH` and `DCH` changed nothing, + and the tab motions and a resize cancelled the wrap. A test that + expected the next character on the following row after one of the + motions or edits, or over the last column after a tab or a resize, + should expect xterm's place. (#814) ### Fixed diff --git a/crates/termlens/src/emu/seq.rs b/crates/termlens/src/emu/seq.rs index 432b887..379c17f 100644 --- a/crates/termlens/src/emu/seq.rs +++ b/crates/termlens/src/emu/seq.rs @@ -336,6 +336,29 @@ pub(crate) enum Motion { /// margin (#821). `valid` is xterm's test, which the tracker has /// already applied to the margins it holds. Margins { valid: bool }, + /// `DCH` (`CSI Ps P`): delete `n` cells at the cursor, which xterm + /// starts from the last column at a pending wrap (`DeleteChar`, util.c + /// 1987; #814). + DeleteChars(u16), + /// `CUB` (`CSI Ps D`): left `n` columns, which xterm counts from the + /// last column at a pending wrap (`CursorBack`, cursor.c; #814). + Back(u16), + /// `LF`, `VT` or `FF` in ground: xterm's `CASE_VMOT`, `xtermIndex`, + /// which resets a pending wrap through `CursorDown` (charproc.c 3738). + /// vt100 kept the wrap pending on the next row (#814). + LineFeed, + /// `BS` in ground: `CursorBack(1)` (charproc.c 3707), from the last + /// column at a pending wrap (#814). + Backspace, +} + +impl Motion { + /// Whether this is a C0 control, which the emulator acts on only when + /// a wrap may be pending: the common line feed after a carriage + /// return then costs nothing. + pub(crate) fn is_control(self) -> bool { + matches!(self, Self::LineFeed | Self::Backspace) + } } /// Which glyph set a G0–G3 designation currently names. @@ -2256,6 +2279,8 @@ impl SeqTracker { b'E' => return SeqEvent::Motion(Motion::NextLine(count)), b'F' => return SeqEvent::Motion(Motion::PrevLine(count)), b'd' => return SeqEvent::Motion(Motion::Row(count)), + b'D' => return SeqEvent::Motion(Motion::Back(count)), + b'P' => return SeqEvent::Motion(Motion::DeleteChars(count)), // ED 3, erase the saved lines. vt100 reads the first // parameter alone, and so does this. b'J' if ps == 3 => return SeqEvent::ScrollbackErased, @@ -2946,6 +2971,14 @@ impl SeqTracker { // application set a stop of its own — a table drawn // half from each. HT => event = SeqEvent::Tabs(TabOp::Forward(1)), + // The controls that cancel a pending wrap from the + // last column in xterm (#814). + 0x0a..=0x0c if self.utf8_remaining == 0 => { + event = SeqEvent::Motion(Motion::LineFeed); + } + 0x08 if self.utf8_remaining == 0 => { + event = SeqEvent::Motion(Motion::Backspace); + } _ => {} } // Anything that is not a C0 control or DEL. Named once diff --git a/crates/termlens/src/emu/vt100.rs b/crates/termlens/src/emu/vt100.rs index 13f7390..855a414 100644 --- a/crates/termlens/src/emu/vt100.rs +++ b/crates/termlens/src/emu/vt100.rs @@ -80,6 +80,12 @@ pub(crate) struct Vt100Emulator { /// and so only between sequences — see /// [`end_origin_mode`](Self::end_origin_mode). origin_owed: [bool; 2], + /// Whether vt100's cursor is known not to be pending wrap once the + /// read so far is fed: set by a carriage return and by a line feed or + /// a backspace the emulator has settled, cleared by any other byte or + /// feed. A line feed or a backspace is read against the grid, which + /// splits the feed, only when this is clear (#814). + wrap_settled: bool, } /// The images a logged kitty escape names, as its [`Placement`] carried @@ -154,6 +160,7 @@ impl Vt100Emulator { cell_size: None, staged: Vec::new(), origin_owed: [false; 2], + wrap_settled: false, } } @@ -315,6 +322,7 @@ impl Vt100Emulator { // U+FFFD would be dropped on the way in — see `stand_in_for_replacement`. let bytes = stand_in_for_replacement(bytes); let normalized = self.colors.feed(&bytes); + self.wrap_settled = false; self.parser.process(&normalized); // What the emulator told the record of a CSI this feed carried ends // here, taken or not. @@ -368,7 +376,30 @@ impl Vt100Emulator { // at the right margin is dropped by `TabStops::set`, on purpose — // clamping it would set a stop the application never asked for, // and that stop outlives the wrap once the grid is widened. - let col = self.parser.screen().cursor_position().1; + let screen = self.parser.screen(); + let (col, cols) = (screen.cursor_position().1, size(screen).1); + // At a pending wrap xterm's cursor is on the last column with the + // wrap kept through all three tab motions: `TabToNextStop` and + // `TabToPrevStop` (tabs.c) move it with `set_cur_col`, a plain + // store that never resets the flag. A forward motion finds the + // last column, where the cursor is, so nothing moves and the wrap + // stays; vt100's own `HT` would cancel it, so that byte is not fed. + // A back motion counts from the last column and lands on an + // earlier one, where xterm keeps the wrap pending and vt100 cannot, + // since its pending wrap is the column past the margin; the cursor + // goes to the stop with no wrap pending (#814, LIMITATIONS). + let pending = col >= cols; + if pending && matches!(op, TabOp::Forward(_)) { + if last != b"\t" { + self.feed_staged(last); + } + return; + } + let col = if matches!(op, TabOp::Back(_)) { + col.min(cols - 1) + } else { + col + }; let target = self.tracker.tab_op(op, col); self.feed_staged(last); if let Some(target) = target { @@ -984,31 +1015,43 @@ impl Vt100Emulator { /// so the shadow keeps the same shape. fn carry_out(&mut self, motion: Motion, last: &[u8]) { let screen = self.parser.screen(); - let (_, cols) = size(screen); + let (rows, cols) = size(screen); let (row, col) = screen.cursor_position(); + // xterm keeps a cursor pending wrap on the last column, and each of + // these starts from that column and resets the wrap: `CursorUp`, + // `CursorDown`, `CursorSet` and `CursorBack` (cursor.c), and + // `InsertChar` and `DeleteChar` (util.c), all end in `ResetWrap`, + // as does `xtermIndex`, the line feed, through `CursorDown`. vt100 + // keeps the cursor a column past the last instead, where these + // left a wrap pending or counted from (#814). + let pending = col >= cols; + let at = col.min(cols - 1); let (top, bottom) = (self.tracker.top_margin(), self.tracker.bottom_margin()); let origin = self.tracker.origin_mode(); - // The column a vertical motion keeps, and the row xterm's leaves - // the cursor on, when vt100's would differ: from outside the - // region xterm stops at the near margin where vt100 goes on to - // the screen's edge, and under origin mode VPA counts from the top - // margin where vt100 counts from row 0. Inside the region and - // outside origin mode vt100 already does what xterm does. - let col_kept = col.min(cols - 1); + // The row xterm's vertical motion leaves the cursor on, when + // vt100's would differ: from outside the region xterm stops at the + // near margin where vt100 goes on to the screen's edge (#821), + // under origin mode VPA counts from the top margin where vt100 + // counts from row 0 (#821), and at a pending wrap vt100 keeps the + // wrap. Inside the region, outside origin mode and with no wrap + // pending, vt100 already does what xterm does. let vertical = match motion { - Motion::Up(n) | Motion::PrevLine(n) if row > bottom => { - Some(row.saturating_sub(n).max(top)) + Motion::Up(n) | Motion::PrevLine(n) if row > bottom || pending => { + let min = if row < top { 0 } else { top }; + Some(row.saturating_sub(n).max(min)) } - Motion::Down(n) | Motion::NextLine(n) if row < top => { - Some(row.saturating_add(n).min(bottom)) + Motion::Down(n) | Motion::NextLine(n) if row < top || pending => { + let max = if row > bottom { rows - 1 } else { bottom }; + Some(row.saturating_add(n).min(max)) } Motion::Row(n) if origin => Some((n - 1).saturating_add(top).min(bottom)), + Motion::Row(n) if pending => Some((n - 1).min(rows - 1)), _ => None, }; if let Some(to) = vertical { let col = match motion { Motion::NextLine(_) | Motion::PrevLine(_) => 0, - _ => col_kept, + _ => at, }; self.feed(CSI_IGNORED); self.move_to(to, col); @@ -1023,28 +1066,53 @@ impl Vt100Emulator { // continuation flag onto the inserted blank instead, and // the character stayed whole on the far side of it (#822). // So the character is erased first, by `ECH` from its first - // half in the attributes in force, and the `ICH` follows. - let splits = col > 0 + // half in the attributes in force, and the `ICH` follows, + // from the last column at a pending wrap (#814). + let splits = at > 0 && screen - .cell(row, col) + .cell(row, at) .is_some_and(::vt100::Cell::is_wide_continuation); - if splits { + if splits || pending { self.feed(CSI_IGNORED); - self.feed(format!("\x1b[{col}G\x1b[2X\x1b[{}G\x1b[{n}@", col + 1).as_bytes()); + if splits { + self.feed(format!("\x1b[{at}G\x1b[2X").as_bytes()); + } + self.feed(format!("\x1b[{}G\x1b[{n}@", at + 1).as_bytes()); } else { self.feed(last); } } + Motion::DeleteChars(n) if pending => { + self.feed(CSI_IGNORED); + self.feed(format!("\x1b[{cols}G\x1b[{n}P").as_bytes()); + } + // xterm's `CursorBack` goes left from the last column, without + // reverse wrap, which termlens does not model. + Motion::Back(n) if pending => { + self.feed(CSI_IGNORED); + self.move_to(row, at.saturating_sub(n)); + } // Above the region xterm's `RI` is `CursorUp`, which stops at // row 0; vt100 scrolled the region down from there. The escape // is taken from vt100 as `IND`'s is. Motion::ReverseIndex if row < top => { self.feed(ESC_IGNORED); - self.move_to(row.saturating_sub(1), col_kept); + self.move_to(row.saturating_sub(1), at); + } + // A line feed and a backspace go on as vt100 has them, from + // the last column: before them, since they are no sequence a + // move could cut. Both leave no wrap pending. + Motion::LineFeed | Motion::Backspace => { + if pending { + self.feed(format!("\x1b[{cols}G").as_bytes()); + } + self.feed(last); + self.wrap_settled = true; } - // An ignored region is ignored whole, the cursor included. A - // region set homes the cursor to row 0 outside origin mode; - // vt100 homes it to the top margin, where origin mode puts it. + // An ignored region is ignored whole, the cursor and a pending + // wrap included. A region set homes the cursor to row 0 + // outside origin mode; vt100 homes it to the top margin, where + // origin mode puts it. Motion::Margins { valid: false } => self.feed(CSI_IGNORED), Motion::Margins { valid: true } => { self.feed(last); @@ -1052,12 +1120,32 @@ impl Vt100Emulator { self.feed(b"\x1b[H"); } } + // `RI` from the region or below it, where vt100 moves and + // scrolls as xterm does, but keeps a pending wrap. + Motion::ReverseIndex => { + self.feed(last); + if pending { + self.feed(format!("\x1b[{cols}G").as_bytes()); + } + } Motion::Up(_) | Motion::Down(_) | Motion::NextLine(_) | Motion::PrevLine(_) | Motion::Row(_) - | Motion::ReverseIndex => self.feed(last), + | Motion::DeleteChars(_) + | Motion::Back(_) => self.feed(last), + } + } + + /// Put a cursor pending wrap back on the last column, which is how + /// vt100 cancels a wrap, before a line feed `IND` hands it: xterm's + /// `xtermIndex` resets the wrap through `CursorDown` (#814). + fn cancel_pending_wrap(&mut self) { + let screen = self.parser.screen(); + let (_, cols) = size(screen); + if screen.cursor_position().1 >= cols { + self.feed(format!("\x1b[{cols}G").as_bytes()); } } @@ -1132,6 +1220,8 @@ impl Emulator for Vt100Emulator { // Where the bytes a reservation or a selector already accounted for // end, so each character is looked at once. let mut run_until = 0; + // Nothing outside a read is tracked, so a read starts unsettled. + self.wrap_settled = false; for (i, &byte) in bytes.iter().enumerate() { // A resize inside a sequence ended origin mode in the tracker // and owes it to vt100, where the sequence has ended (#826). @@ -1340,9 +1430,13 @@ impl Emulator for Vt100Emulator { self.feed_staged(&bytes[fed..i]); self.feed(ESC_IGNORED); fed = i + 1; + self.cancel_pending_wrap(); self.feed(if next_line { b"\r\n" } else { b"\n" }); None } + // A line feed or a backspace with no wrap pending is vt100's + // as it is, in the feed with the rest of the read. + SeqEvent::Motion(motion) if motion.is_control() && self.wrap_settled => None, SeqEvent::Motion(motion) => { self.feed_staged(&bytes[fed..i]); fed = i + 1; @@ -1359,6 +1453,14 @@ impl Emulator for Vt100Emulator { None } }; + // A carriage return the grid executes leaves no wrap pending, + // and neither does a line feed or a backspace the arm above + // settled; any other byte may (#814). + match byte { + b'\r' if !self.tracker.mid_sequence() => self.wrap_settled = true, + 0x08 | 0x0a..=0x0c if !self.tracker.mid_sequence() => {} + _ => self.wrap_settled = false, + } // A CSI with a parameter the application left empty reaches the // record with a 0 in its place, so the record is told which, // between the bytes before the final byte and that byte (#827). @@ -1624,6 +1726,16 @@ impl Emulator for Vt100Emulator { // sequences, and inside one the resize is settled when the main // screen is back, as before. let behind = self.parser.screen().alternate_screen() && !self.tracker.mid_sequence(); + // xterm's `ScreenResize` (screen.c 2217) keeps the wrap flag: it + // clamps the cursor's column with `set_cur_col`, a plain store, so + // the next character starts the next row whatever the new size. + // vt100 clamps its cursor to the last column, which cancels a wrap + // it keeps a column past it (#814). Read here, put back below. + let (wrapped, old_cols) = { + let screen = self.parser.screen(); + let (_, old_cols) = size(screen); + (screen.cursor_position().1 >= old_cols, old_cols) + }; if behind { self.parser.process(SHOW_MAIN_GRID); self.shadow.feed_verbatim(SHOW_MAIN_GRID); @@ -1646,6 +1758,17 @@ impl Emulator for Vt100Emulator { self.parser.process(SHOW_ALTERNATE_GRID); self.shadow.feed_verbatim(SHOW_ALTERNATE_GRID); } + // The wrap goes back as the last column drawn again, on a screen + // no wider: on a wider one xterm's cursor stays on the old last + // column with the wrap pending, which vt100 cannot hold, and is + // left where vt100 puts it (LIMITATIONS). Bytes, so not inside a + // sequence, which they would cut. + let (row, col) = self.parser.screen().cursor_position(); + let cols = size(self.parser.screen()).1; + if wrapped && col < cols && cols <= old_cols && !self.tracker.mid_sequence() { + self.feed(format!("\x1b[{}d", row + 1).as_bytes()); + self.redraw_last_column(row); + } self.end_origin_mode(); } } @@ -3330,6 +3453,7 @@ mod tests { // Behind the alternate screen the main grid is resized // on display, and its history read then (#678). emu.set_size(rows, cols); + let wrapped = raw.screen().cursor_position().1 >= was.1; if alternate { raw.process(SHOW_MAIN_GRID); } @@ -3337,6 +3461,22 @@ mod tests { if alternate { raw.process(SHOW_ALTERNATE_GRID); } + // And keeps a pending wrap through a resize no wider, + // drawing the last column again (#814). + let (row, col) = raw.screen().cursor_position(); + if wrapped && col < cols && cols <= was.1 { + let last = raw + .screen() + .cell(row, cols - 1) + .unwrap() + .contents() + .to_owned(); + if last.is_empty() { + raw.process(format!("\x1b[{}d\x1b[1G", row + 2).as_bytes()); + } else { + raw.process(format!("\x1b[{cols}G{last}").as_bytes()); + } + } } else { let piece = pieces[next(pieces.len())]; feed_all(&mut emu, piece.as_bytes()); @@ -3344,6 +3484,11 @@ mod tests { // xterm's: at a pending wrap, from the last column // (#809). let pending = raw.screen().cursor_position().1 >= cols; + // A line feed at a pending wrap goes down from the last + // column, as xterm's does (#814). + if piece == "\n" && pending { + raw.process(format!("\x1b[{cols}G").as_bytes()); + } // And sets a region as xterm does: one whose bottom is // not below its top is ignored, and a region set homes // the cursor to row 0 (#821). @@ -5819,6 +5964,93 @@ mod tests { assert_eq!(emu.snapshot().cursor(), (2, 1, true)); } + /// At a pending wrap the motions and edits xterm starts from the + /// cursor's column start from the last column and cancel the wrap + /// (#814): `CursorUp`, `CursorDown`, `CursorSet` and `CursorBack` + /// (cursor.c), `InsertChar` and `DeleteChar` (util.c), and the line + /// feed, `xtermIndex`, all end in `ResetWrap`. vt100 kept the cursor a + /// column past the last. The tab motions keep the wrap, as xterm's + /// `set_cur_col` never resets it (tabs.c). One case per row of the + /// issue's tables, on 5x3. + #[test] + fn a_pending_wrap_is_left_from_the_last_column() { + for (stream, text) in [ + ("\nabcde\x1b[AX", " X\nabcde\n"), + ("abcde\x1b[BX", "abcde\n X\n"), + ("abcde\x1b[2dX", "abcde\n X\n"), + ("abcde\x1b[DX", "abcXe\n\n"), + ("abcde\x1b[2DX", "abXde\n\n"), + ("abcde\x08X", "abcXe\n\n"), + ("abcde\x1b[@X", "abcdX\n\n"), + ("abcde\x1b[PX", "abcdX\n\n"), + ("abcde\x1b[3PX", "abcdX\n\n"), + // The line feed, by every byte xterm takes for one, and `IND`. + ("abcde\nX", "abcde\n X\n"), + ("abcde\x0bX", "abcde\n X\n"), + ("abcde\x0cX", "abcde\n X\n"), + ("abcde\x1bDX", "abcde\n X\n"), + ("abcde\nfghij\nX", " f\nghij\n X"), + // `RI`, and `CNL` and `CPL`, which go to the first column. + ("\nabcde\x1bMX", " X\nabcde\n"), + ("abcde\x1b[EX", "abcde\nX\n"), + ("\nabcde\x1b[FX", "X\nabcde\n"), + // `HT` and `CHT` keep the wrap: the next character starts the + // next row. + ("abcde\tX", "abcde\nX\n"), + ("abcde\x1b[IX", "abcde\nX\n"), + ("abcde\x1b[2IX", "abcde\nX\n"), + // A carriage return first leaves nothing pending. + ("abcde\r\nX", "abcde\nX\n"), + ("abcde\r\x08X", "Xbcde\n\n"), + ] { + let (whole, bytewise) = whole_and_bytewise(3, 5, 0, stream.as_bytes()); + assert_eq!(observed(&whole), observed(&bytewise), "{stream:?}"); + let s = whole.snapshot(); + assert_eq!(s.text(), text, "{stream:?}: {s}"); + assert!( + s.unsupported().is_empty(), + "{stream:?}: {:?}", + s.unsupported() + ); + } + // `CBT` counts back from the last column, where xterm keeps the + // wrap pending on the stop it lands on, which vt100 cannot hold: + // the cursor lands there with no wrap (LIMITATIONS). + let s = emu_with_size(3, 10, b"abcdefghij\x1b[ZX").snapshot(); + assert_eq!(s.text(), "abcdefghXj\n\n", "{s}"); + let s = emu_with_size(3, 9, b"abcdefghi\x1b[ZX").snapshot(); + assert_eq!(s.text(), "Xbcdefghi\n\n", "{s}"); + } + + /// A resize keeps a pending wrap, as xterm's `ScreenResize` does: it + /// clamps the cursor's column with `set_cur_col` and leaves the wrap + /// flag, so the next character starts the next row (#814). On a wider + /// screen xterm's cursor stays on the old last column with the wrap + /// pending, which vt100 cannot hold; it is left a column past the old + /// last, where vt100 puts it (LIMITATIONS). + #[test] + fn a_resize_keeps_a_pending_wrap() { + for ((rows, cols), text) in [ + ((4, 5), "abcde\nX\n\n"), + ((2, 5), "abcde\nX"), + ((3, 4), "abcd\nX\n"), + ((3, 8), "abcdeX\n\n"), + ] { + let mut emu = emu_with_size(3, 5, b"\x1b[41mabcde\x1b[0m"); + emu.set_size(rows, cols); + feed_all(&mut emu, b"X"); + let s = emu.snapshot(); + assert_eq!(s.text(), text, "{rows}x{cols}: {s}"); + // The last column is drawn again in its own attributes. + let last = cols.min(5) - 1; + assert_eq!( + s.cell(0, last).unwrap().style().bg, + Color::Indexed(1), + "{s}" + ); + } + } + /// Random short streams of the motions and edits the emulator carries /// out itself (#814, #820, #821, #822), mixed with text, wide /// characters, controls and SGR, fed whole and a character at a time: @@ -5859,6 +6091,16 @@ mod tests { "\x1b[?47l", "\x1b7", "\x1b8", + "abcdef", + "\x08", + "\t", + "\x0b", + "\x1bD", + "\x1b[D", + "\x1b[2P", + "\x1b[I", + "\x1b[Z", + "\x1b[K", ]; let mut seed: u64 = 0x0814_0820_0821_0822; let mut next = move |n: usize| { diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md index 88ed96d..58fe733 100644 --- a/docs/LIMITATIONS.md +++ b/docs/LIMITATIONS.md @@ -93,14 +93,21 @@ CHANGELOG entry. modelled: text past the right margin still wraps, and `unsupported()` names the sequence. `CSI ? 7 h`, which every ncurses program sends, asks for what the emulator already does and is not named. -- **At a pending wrap, relative motions, `ICH` and `DCH` count from past - the margin.** After a character in the last column, xterm keeps the - cursor on that column with the wrap pending, and `CUU`, `CUD`, `VPA`, - `CUB`, `BS`, `ICH` and `DCH` cancel the wrap and work from that column. - The backend keeps the cursor one column past it, so `CUU`, `CUD` and - `VPA` leave the wrap pending, `CUB` and `BS` land a column right of - xterm's, and `ICH` and `DCH` change nothing (#814). The erases start - from the last column and cancel the wrap, as xterm's do. +- **A pending wrap is xterm's, but for four corners.** After a character + in the last column, xterm keeps the cursor on that column with the wrap + pending. `CUU`, `CUD`, `VPA`, `CUB`, `BS`, `ICH`, `DCH`, `RI`, a line + feed and the erases cancel the wrap and work from that column, and + `HT`, `CHT` and a resize keep it, here as there (#809, #814). The + backend holds a pending wrap only as the column past the last, so four + cases differ from xterm. `CBT` lands on its stop with no wrap pending, + where xterm keeps the wrap pending there and the next character starts + the next row. A resize to a wider screen leaves the cursor a column past + the old last one, where xterm keeps it on that column with the wrap + pending. A `DECRC` after a resize puts back a cursor saved at a pending + wrap with the wrap gone: the backend clamps its saved cursor and does + not expose it, so termlens cannot tell such a save from another. And a + `BS` or a line feed inside an escape sequence, which a terminal carries + out in passing, leaves the wrap as the backend has it. - **A switch of screens keeps the cursor, the scroll region and origin mode**, as xterm's does: `?1049h`, `?47h` and `?47l` leave the cursor where it was, and `?1049l` restores the one `?1049h` saved. Two cases