Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
223 changes: 193 additions & 30 deletions libs/cmdio/cmdiotest/termtest/emulator.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package termtest

import (
"runtime"
"strings"

"github.com/charmbracelet/x/ansi"
Expand All @@ -10,18 +11,17 @@ import (
// byte stream bubbletea writes to its output into a 2D screen of plain text
// so tests can match against `screen text` goldens.
//
// Scope is deliberately narrow: bubbletea's stock renderer (which is what
// the cmdio prompt/select models run through) emits a small subset of CSI
// sequences — cursor moves, erase-line, set/reset-mode for cursor
// visibility — plus printable runes, CR, LF, and BS. Alt-screen switches,
// scroll regions, charsets, DCS, and friends are recognised by the
// underlying ansi parser but intentionally ignored: they do not affect cell
// text. SGR styling, DEC private modes, keyboard protocol switches and
// terminal queries are recorded alongside the text for the styled, modes
// and queries goldens (see observe.go), without changing what String
// returns. Cursor movement covers the usual CUU/CUD/CUP family and the
// unprefixed SCO save/restore pair (CSI s and CSI u); prefixed forms such as
// the kitty keyboard CSI ? u and CSI > n u do not move the cursor.
// Scope is deliberately narrow. bubbletea v1's standard renderer only moves
// the cursor with CUU, EL, CUP and CRLF (its IL and DECSTBM live in the
// deprecated insertTop, which cmdio does not use). The other cell and cursor
// sequences handled here (REP, ECH, ICH, DCH, IRM, IL, DL, SU, SD, DECSTBM,
// RI, CHT, CBT) are the ones the cell renderer of charm.land/bubbletea/v2
// v2.1.1 emits through github.com/charmbracelet/ultraviolet
// (terminal_renderer.go, terminal_renderer_hardscroll.go). SGR styling,
// alt-screen switches, charsets and OSC are recognised by the underlying ansi
// parser but do not affect cell text. Styles, modes and queries are recorded
// alongside the text for the styled, modes and queries goldens (see
// observe.go), without changing what String returns.
type emulator struct {
width, height int
grid [][]rune
Expand All @@ -30,8 +30,23 @@ type emulator struct {
// Saved cursor (DECSC/DECRC; ESC 7 / ESC 8).
savedRow, savedCol int

// mapNewline makes LF also return to column 0, like a cooked tty's
// ONLCR. Off by default: bubbletea v1 writes CRLF itself.
// Scroll region rows (DECSTBM), inclusive.
top, bottom int

// insert is IRM (CSI 4 h): printed runes shift the rest of the line right.
insert bool

// lastRune is the most recently printed rune, repeated by REP. Zero
// until something is printed.
lastRune rune

// mapNewline makes LF also return to column 0, like a cooked tty's ONLCR
// output translation. bubbletea v2 assumes that mapping whenever its input
// is not a TTY, except on Windows (charm.land/bubbletea/v2 v2.1.1
// tea.go:1107 "mapNl := runtime.GOOS != \"windows\" && p.ttyInput == nil";
// ultraviolet terminal_renderer.go:1645-1649). termtest feeds input
// through a pipe, so it follows the same rule. v1 always writes CRLF, so
// the setting does not affect it.
mapNewline bool

// Observation state for the styled, modes and queries goldens. None of
Expand All @@ -48,7 +63,7 @@ type emulator struct {
}

func newEmulator(width, height int) *emulator {
e := &emulator{width: width, height: height}
e := &emulator{width: width, height: height, mapNewline: runtime.GOOS != "windows"}
e.reset()
e.parser = ansi.NewParser()
e.parser.SetHandler(ansi.Handler{
Expand Down Expand Up @@ -77,6 +92,9 @@ func (e *emulator) reset() {
e.privateModes = map[int]bool{}
e.row, e.col = 0, 0
e.savedRow, e.savedCol = 0, 0
e.top, e.bottom = 0, e.height-1
e.insert = false
e.lastRune = 0
}

// Write feeds bytes into the parser.
Expand Down Expand Up @@ -107,9 +125,13 @@ func (e *emulator) handlePrint(r rune) {
return
}
if e.inBounds() {
if e.insert {
e.insertCells(1)
}
e.grid[e.row][e.col] = r
e.styles[e.row][e.col] = e.pen
}
e.lastRune = r
e.col++
}

Expand All @@ -123,10 +145,8 @@ func (e *emulator) handleControl(b byte) {
case 0x09: // HT: next tab stop (every 8 columns).
stop := ((e.col / 8) + 1) * 8
e.col = min(stop, e.width-1)
case 0x0a: // LF: move down one line, no scroll.
if e.row+1 < e.height {
e.row++
}
case 0x0a: // LF: move down a line (scrolling at the bottom margin), then to column 0 if mapped.
e.index()
if e.mapNewline {
e.col = 0
}
Expand All @@ -140,9 +160,78 @@ func (e *emulator) handleControl(b byte) {
// the mode and query sequences do not move the cursor or change cell text;
// observeCsi records the ones the goldens pin.
func (e *emulator) handleCsi(cmd ansi.Cmd, params ansi.Params) {
// Prefixed and intermediate CSIs are terminal queries and mode switches
// (DEC private modes, DECRQM "CSI ? 2026 $ p", kitty keyboard
// "CSI > 1 u" / "CSI < u" / "CSI ? u", modifyOtherKeys "CSI > 4;2 m"),
// never cursor or cell operations. Without this check "CSI > 1 u" would
// be read as SCO restore-cursor.
e.observeCsi(cmd, params)
if cmd.Prefix() != 0 || cmd.Intermediate() != 0 {
return
}
n, _, _ := params.Param(0, 1)
switch cmd.Final() {
case 'b': // REP: repeat the last printed rune n times.
// A real terminal ignores REP before anything has been printed.
if e.lastRune == 0 {
break
}
for range n {
e.handlePrint(e.lastRune)
}
case 'X': // ECH: erase n cells from the cursor without moving it.
if e.inBounds() {
for i := e.col; i < min(e.col+n, e.width); i++ {
e.clearCell(e.row, i)
}
}
case '@': // ICH: insert n blank cells at the cursor.
if e.inBounds() {
e.insertCells(n)
}
case 'P': // DCH: delete n cells at the cursor, shifting the rest left.
if e.inBounds() {
e.deleteCells(n)
}
case 'L': // IL: insert n blank lines at the cursor row.
if e.row >= e.top && e.row <= e.bottom {
e.scrollDown(e.row, n)
e.col = 0
}
case 'M': // DL: delete n lines at the cursor row.
if e.row >= e.top && e.row <= e.bottom {
e.scrollUp(e.row, n)
e.col = 0
}
case 'S': // SU: scroll the region up n lines.
e.scrollUp(e.top, n)
case 'T': // SD: scroll the region down n lines.
// The five-parameter form is xterm mouse highlight tracking.
if len(params) <= 1 {
e.scrollDown(e.top, n)
}
case 'r': // DECSTBM: set scroll region (1-based, inclusive); homes the cursor.
top, _, _ := params.Param(0, 1)
bottom, _, _ := params.Param(1, e.height)
top, bottom = clamp(top-1, 0, e.height-1), clamp(bottom-1, 0, e.height-1)
if top < bottom {
e.top, e.bottom = top, bottom
e.row, e.col = 0, 0
}
case 'h', 'l': // SM / RM: only IRM (mode 4) affects cell text.
for i := range params {
if params[i].Param(0) == 4 {
e.insert = cmd.Final() == 'h'
}
}
case 'I': // CHT: forward n tab stops.
for range n {
e.handleControl(0x09)
}
case 'Z': // CBT: back n tab stops.
for range n {
e.col = max(((e.col+7)/8-1)*8, 0)
}
case 'A': // CUU: cursor up
e.row = max(e.row-n, 0)
case 'B', 'e': // CUD / VPR: cursor down
Expand Down Expand Up @@ -173,22 +262,26 @@ func (e *emulator) handleCsi(cmd ansi.Cmd, params ansi.Params) {
n, _, _ := params.Param(0, 0)
e.eraseLine(n)
case 's': // SCO save cursor
if cmd.Prefix() == 0 {
e.savedRow, e.savedCol = e.row, e.col
}
case 'u': // SCO restore cursor; prefixed forms are kitty keyboard sequences.
if cmd.Prefix() == 0 {
e.row, e.col = e.savedRow, e.savedCol
}
// All other CSI commands (SGR 'm', mode set/reset 'h'/'l', cursor
// show/hide '?25h/l', etc.) are no-ops for cell text.
e.savedRow, e.savedCol = e.row, e.col
case 'u': // SCO restore cursor
e.row, e.col = e.savedRow, e.savedCol
// All other CSI commands (SGR 'm', etc.) are no-ops for cell text.
}
}

// handleEsc handles ESC sequences: only the C1-equivalent cursor save/restore
// (ESC 7 / ESC 8) matter for cell positions.
// handleEsc handles the ESC sequences that matter for cell positions:
// cursor save/restore (ESC 7 / ESC 8) and reverse index (ESC M).
func (e *emulator) handleEsc(cmd ansi.Cmd) {
if cmd.Intermediate() != 0 {
return // charset designations etc.
}
switch cmd.Final() {
case 'M': // RI: up one line, scrolling down at the top margin.
if e.row == e.top {
e.scrollDown(e.top, 1)
} else if e.row > 0 {
e.row--
}
case '7': // DECSC: save cursor
e.savedRow, e.savedCol = e.row, e.col
case '8': // DECRC: restore cursor
Expand Down Expand Up @@ -255,6 +348,76 @@ func (e *emulator) clearCell(r, c int) {
e.styles[r][c] = cellStyle{}
}

// index moves the cursor down one row, scrolling the region up when the
// cursor sits on its bottom margin.
func (e *emulator) index() {
switch {
case e.row == e.bottom:
e.scrollUp(e.top, 1)
case e.row+1 < e.height:
e.row++
}
}

// insertCells shifts the cells from the cursor right by n, dropping cells
// pushed past the right margin, and blanks the gap.
func (e *emulator) insertCells(n int) {
line, styles := e.grid[e.row], e.styles[e.row]
n = min(n, e.width-e.col)
copy(line[e.col+n:], line[e.col:e.width-n])
copy(styles[e.col+n:], styles[e.col:e.width-n])
for i := e.col; i < e.col+n; i++ {
e.clearCell(e.row, i)
}
}

// deleteCells removes n cells at the cursor, shifting the rest of the line
// left and blanking the right margin.
func (e *emulator) deleteCells(n int) {
line, styles := e.grid[e.row], e.styles[e.row]
n = min(n, e.width-e.col)
copy(line[e.col:], line[e.col+n:])
copy(styles[e.col:], styles[e.col+n:])
for i := e.width - n; i < e.width; i++ {
e.clearCell(e.row, i)
}
}

// scrollUp removes n lines at row from, shifting the lines below it up to
// the bottom margin and blanking the bottom n lines of the region.
func (e *emulator) scrollUp(from, n int) {
n = min(n, e.bottom-from+1)
region, styles := e.grid[from:e.bottom+1], e.styles[from:e.bottom+1]
copy(region, region[n:])
copy(styles, styles[n:])
for i := len(region) - n; i < len(region); i++ {
region[i] = blankRow(e.width)
styles[i] = make([]cellStyle, e.width)
}
}

// scrollDown inserts n blank lines at row from, shifting the lines below it
// down and dropping those pushed past the bottom margin.
func (e *emulator) scrollDown(from, n int) {
n = min(n, e.bottom-from+1)
region, styles := e.grid[from:e.bottom+1], e.styles[from:e.bottom+1]
copy(region[n:], region)
copy(styles[n:], styles)
for i := range n {
region[i] = blankRow(e.width)
styles[i] = make([]cellStyle, e.width)
}
}

// blankRow returns a row of width spaces.
func blankRow(width int) []rune {
row := make([]rune, width)
for i := range row {
row[i] = ' '
}
return row
}

func (e *emulator) inBounds() bool {
return e.row >= 0 && e.row < e.height && e.col >= 0 && e.col < e.width
}
Expand Down
Loading
Loading