feat: bracketed paste (#397)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: bracketed paste This introduces support for input via bracketed paste, where escape characters in the pasted input are not interpreted. Pasted input are marked as a special field in the KeyMsg. This is useful because pasted input may need sanitation in individual widgets. * fix(key): support bracketed paste with short reads Some terminal emulators feed the bracketed paste data in multiple chunks, which may not be aligned on a 256 byte boundary. So it's possible for `input.Read` to return less than 256 bytes read but while there's still more data to be read to complete a bracketed paste input. ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Christian Muehlhaeuser <muesli@gmail.com>
Diff stats
13 files+222 added−51 removed
- other:+222 added−51 removed
Provenance
- Commit
2b46020- Tree
3991067- Author
Raphael 'kena' Poss <knz@thaumogen.net>- Committer
GitHub <noreply@github.com>- Parent
ab7e5ea
13 files changed+222 added−51 removed
modified:examples/simple/testdata/TestApp.golden+2 added-2 removed
1-[?25lHi. This program will exit in 10 seconds. To quit sooner press any key1+[?25l[?2004hHi. This program will exit in 10 seconds. To quit sooner press any key2 [70D[1A[70D[2KHi. This program will exit in 9 seconds. To quit sooner press any key.3-[70D[2K[?25h[?1002l[?1003l[?1006l3+[70D[2K[?2004l[?25h[?1002l[?1003l[?1006lmodified:key_sequences.go+49 added-1 removed
1 package tea2 3-import "sort"3+import (4+ "bytes"5+ "sort"6+ "unicode/utf8"7+)8 9 // extSequences is used by the map-based algorithm below. It contains10 // the sequences plus their alternatives with an escape character11 // prefixed, plus the control chars, plus the space.60 unmodified lines72 }73 74 return false, 0, nil75 }76+77+// detectBracketedPaste detects an input pasted while bracketed78+// paste mode was enabled.79+//80+// Note: this function is a no-op if bracketed paste was not enabled81+// on the terminal, since in that case we'd never see this82+// particular escape sequence.83+func detectBracketedPaste(input []byte) (hasBp bool, width int, msg Msg) {84+ // Detect the start sequence.85+ const bpStart = "\x1b[200~"86+ if len(input) < len(bpStart) || string(input[:len(bpStart)]) != bpStart {87+ return false, 0, nil88+ }89+90+ // Skip over the start sequence.91+ input = input[len(bpStart):]92+93+ // If we saw the start sequence, then we must have an end sequence94+ // as well. Find it.95+ const bpEnd = "\x1b[201~"96+ idx := bytes.Index(input, []byte(bpEnd))97+ inputLen := len(bpStart) + idx + len(bpEnd)98+ if idx == -1 {99+ // We have encountered the end of the input buffer without seeing100+ // the marker for the end of the bracketed paste.101+ // Tell the outer loop we have done a short read and we want more.102+ return true, 0, nil103+ }104+105+ // The paste is everything in-between.106+ paste := input[:idx]107+108+ // All there is in-between is runes, not to be interpreted further.109+ k := Key{Type: KeyRunes, Paste: true}110+ for len(paste) > 0 {111+ r, w := utf8.DecodeRune(paste)112+ if r != utf8.RuneError {113+ k.Runes = append(k.Runes, r)114+ }115+ paste = paste[w:]116+ }117+118+ return true, inputLen, KeyMsg(k)119+}modified:key_test.go+14 added-12 removed
432 unmodified lines433 {"alt+esc",434 []byte{'\x1b', '\x1b'},435 []Msg{KeyMsg{Type: KeyEsc, Alt: true}},436 },437- // Bracketed paste does not work yet.438- {"?CSI[50 48 48 126]? a b ?CSI[50 48 49 126]?",437+ {"[a b] o",438 []byte{439 '\x1b', '[', '2', '0', '0', '~',440 'a', ' ', 'b',441+ '\x1b', '[', '2', '0', '1', '~',442+ 'o',443+ },444+ []Msg{445+ KeyMsg{Type: KeyRunes, Runes: []rune("a b"), Paste: true},446+ KeyMsg{Type: KeyRunes, Runes: []rune("o")},447+ },448+ },449+ {"[a\x03\nb]",450+ []byte{451+ '\x1b', '[', '2', '0', '0', '~',452+ 'a', '\x03', '\n', 'b',453 '\x1b', '[', '2', '0', '1', '~'},454 []Msg{444- // What we expect once bracketed paste is recognized properly:445- //446- // KeyMsg{Type: KeyRunes, Runes: []rune("a b")},447- //448- // What we get instead (for now):449- unknownCSISequenceMsg{0x1b, 0x5b, 0x32, 0x30, 0x30, 0x7e},450- KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},455+ KeyMsg{Type: KeyRunes, Runes: []rune("a\x03\nb"), Paste: true},451- KeyMsg{Type: KeySpace, Runes: []rune{' '}},452- KeyMsg{Type: KeyRunes, Runes: []rune{'b'}},453- unknownCSISequenceMsg{0x1b, 0x5b, 0x32, 0x30, 0x31, 0x7e},456 },457 },458 }459 if runtime.GOOS != "windows" {235 unmodified linesmodified:key.go+27 added-5 removed
3 unmodified lines4 "context"5 "fmt"6 "io"7 "regexp"8+ "strings"9 "unicode/utf8"10 )11 12 // KeyMsg contains information about a keypress. KeyMsgs are always sent to41 unmodified lines54 type Key struct {55 Type KeyType56 Runes []rune57 Alt bool58+ Paste bool59 }60 61 // String returns a friendly string representation for a key. It's safe (and62 // encouraged) for use in key comparison.1 unmodified line64 // k := Key{Type: KeyEnter}65 // fmt.Println(k)66 // // Output: enter67 func (k Key) String() (str string) {68+ var buf strings.Builder69 if k.Alt {67- str += "alt+"70+ buf.WriteString("alt+")71 }72 if k.Type == KeyRunes {70- str += string(k.Runes)71- return str73+ if k.Paste {74+ // Note: bubbles/keys bindings currently do string compares to75+ // recognize shortcuts. Since pasted text should never activate76+ // shortcuts, we need to ensure that the binding code doesn't77+ // match Key events that result from pastes. We achieve this78+ // here by enclosing pastes in '[...]' so that the string79+ // comparison in Matches() fails in that case.80+ buf.WriteByte('[')81+ }82+ buf.WriteString(string(k.Runes))83+ if k.Paste {84+ buf.WriteByte(']')85+ }86+ return buf.String()87 } else if s, ok := keyNames[k.Type]; ok {73- str += s74- return str88+ buf.WriteString(s)89+ return buf.String()90 }91 return ""92 }93 533 unmodified lines627 }628 }629 }630 631+ // Detect bracketed paste.632+ var foundbp bool633+ foundbp, w, msg = detectBracketedPaste(b)634+ if foundbp {635+ return636+ }637+638 // Detect escape sequence and control characters other than NUL,639 // possibly with an escape character in front to mark the Alt640 // modifier.641 var foundSeq bool67 unmodified linesmodified:nil_renderer.go+20 added-17 removed
1 package tea2 3 type nilRenderer struct{}4 5-func (n nilRenderer) start() {}6-func (n nilRenderer) stop() {}7-func (n nilRenderer) kill() {}8-func (n nilRenderer) write(_ string) {}9-func (n nilRenderer) repaint() {}10-func (n nilRenderer) clearScreen() {}11-func (n nilRenderer) altScreen() bool { return false }12-func (n nilRenderer) enterAltScreen() {}13-func (n nilRenderer) exitAltScreen() {}14-func (n nilRenderer) showCursor() {}15-func (n nilRenderer) hideCursor() {}16-func (n nilRenderer) enableMouseCellMotion() {}17-func (n nilRenderer) disableMouseCellMotion() {}18-func (n nilRenderer) enableMouseAllMotion() {}19-func (n nilRenderer) disableMouseAllMotion() {}20-func (n nilRenderer) enableMouseSGRMode() {}21-func (n nilRenderer) disableMouseSGRMode() {}5+func (n nilRenderer) start() {}6+func (n nilRenderer) stop() {}7+func (n nilRenderer) kill() {}8+func (n nilRenderer) write(_ string) {}9+func (n nilRenderer) repaint() {}10+func (n nilRenderer) clearScreen() {}11+func (n nilRenderer) altScreen() bool { return false }12+func (n nilRenderer) enterAltScreen() {}13+func (n nilRenderer) exitAltScreen() {}14+func (n nilRenderer) showCursor() {}15+func (n nilRenderer) hideCursor() {}16+func (n nilRenderer) enableMouseCellMotion() {}17+func (n nilRenderer) disableMouseCellMotion() {}18+func (n nilRenderer) enableMouseAllMotion() {}19+func (n nilRenderer) disableMouseAllMotion() {}20+func (n nilRenderer) enableBracketedPaste() {}21+func (n nilRenderer) disableBracketedPaste() {}22+func (n nilRenderer) enableMouseSGRMode() {}23+func (n nilRenderer) disableMouseSGRMode() {}24+func (n nilRenderer) bracketedPasteActive() bool { return false }modified:options_test.go+6 added-2 removed
79 unmodified lines80 t.Run("alt screen", func(t *testing.T) {81 exercise(t, WithAltScreen(), withAltScreen)82 })83 84+ t.Run("bracketed paste disabled", func(t *testing.T) {85+ exercise(t, WithoutBracketedPaste(), withoutBracketedPaste)86+ })87+88 t.Run("ansi compression", func(t *testing.T) {89 exercise(t, WithANSICompressor(), withANSICompressor)90 })91 26 unmodified lines118 })119 })120 121 t.Run("multiple", func(t *testing.T) {118- p := NewProgram(nil, WithMouseAllMotion(), WithAltScreen(), WithInputTTY())119- for _, opt := range []startupOptions{withMouseAllMotion, withAltScreen} {122+ p := NewProgram(nil, WithMouseAllMotion(), WithoutBracketedPaste(), WithAltScreen(), WithInputTTY())123+ for _, opt := range []startupOptions{withMouseAllMotion, withoutBracketedPaste, withAltScreen} {124 if !p.startupOptions.has(opt) {125 t.Errorf("expected startup options have %v, got %v", opt, p.startupOptions)126 }127 if p.inputType != ttyInput {5 unmodified linesmodified:options.go+7 added
99 unmodified lines100 p.startupOptions |= withAltScreen101 }102 }103 104+// WithoutBracketedPaste starts the program with bracketed paste disabled.105+func WithoutBracketedPaste() ProgramOption {106+ return func(p *Program) {107+ p.startupOptions |= withoutBracketedPaste108+ }109+}110+111 // WithMouseCellMotion starts the program with the mouse enabled in "cell112 // motion" mode.113 //114 // Cell motion mode enables mouse click, release, and wheel events. Mouse111 unmodified linesmodified:renderer.go+11 added
54 unmodified lines55 enableMouseSGRMode()56 57 // disableMouseSGRMode disables mouse extended mode (SGR).58 disableMouseSGRMode()59+60+ // enableBracketedPaste enables bracketed paste, where characters61+ // inside the input are not interpreted when pasted as a whole.62+ enableBracketedPaste()63+64+ // disableBracketedPaste disables bracketed paste.65+ disableBracketedPaste()66+67+ // bracketedPasteActive reports whether bracketed paste mode is68+ // currently enabled.69+ bracketedPasteActive() bool70 }71 72 // repaintMsg forces a full repaint.73 type repaintMsg struct{}modified:screen_test.go+14 added-9 removed
12 unmodified lines13 }{14 {15 name: "clear_screen",16 cmds: []Cmd{ClearScreen},17- expected: "\x1b[?25l\x1b[2J\x1b[1;1H\x1b[1;1Hsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",17+ expected: "\x1b[?25l\x1b[?2004h\x1b[2J\x1b[1;1H\x1b[1;1Hsuccess\r\n\x1b[0D\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",18 },19 {20 name: "altscreen",21 cmds: []Cmd{EnterAltScreen, ExitAltScreen},22- expected: "\x1b[?25l\x1b[?1049h\x1b[2J\x1b[1;1H\x1b[1;1H\x1b[?25l\x1b[?1049l\x1b[?25lsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",22+ expected: "\x1b[?25l\x1b[?2004h\x1b[?1049h\x1b[2J\x1b[1;1H\x1b[1;1H\x1b[?25l\x1b[?1049l\x1b[?25lsuccess\r\n\x1b[0D\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",23 },24 {25 name: "altscreen_autoexit",26 cmds: []Cmd{EnterAltScreen},27- expected: "\x1b[?25l\x1b[?1049h\x1b[2J\x1b[1;1H\x1b[1;1H\x1b[?25lsuccess\r\n\x1b[2;0H\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h",27+ expected: "\x1b[?25l\x1b[?2004h\x1b[?1049h\x1b[2J\x1b[1;1H\x1b[1;1H\x1b[?25lsuccess\r\n\x1b[2;0H\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h",28 },29 {30 name: "mouse_cellmotion",31 cmds: []Cmd{EnableMouseCellMotion},32- expected: "\x1b[?25l\x1b[?1002h\x1b[?1006hsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",32+ expected: "\x1b[?25l\x1b[?2004h\x1b[?1002h\x1b[?1006hsuccess\r\n\x1b[0D\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",33 },34 {35 name: "mouse_allmotion",36 cmds: []Cmd{EnableMouseAllMotion},37- expected: "\x1b[?25l\x1b[?1003h\x1b[?1006hsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",37+ expected: "\x1b[?25l\x1b[?2004h\x1b[?1003h\x1b[?1006hsuccess\r\n\x1b[0D\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",38 },39 {40 name: "mouse_disable",41 cmds: []Cmd{EnableMouseAllMotion, DisableMouse},42- expected: "\x1b[?25l\x1b[?1003h\x1b[?1006h\x1b[?1002l\x1b[?1003l\x1b[?1006lsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",42+ expected: "\x1b[?25l\x1b[?2004h\x1b[?1003h\x1b[?1006h\x1b[?1002l\x1b[?1003l\x1b[?1006lsuccess\r\n\x1b[0D\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",43 },44 {45 name: "cursor_hide",46 cmds: []Cmd{HideCursor},47- expected: "\x1b[?25l\x1b[?25lsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",47+ expected: "\x1b[?25l\x1b[?2004h\x1b[?25lsuccess\r\n\x1b[0D\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",48 },49 {50 name: "cursor_hideshow",51 cmds: []Cmd{HideCursor, ShowCursor},52- expected: "\x1b[?25l\x1b[?25l\x1b[?25hsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",52+ expected: "\x1b[?25l\x1b[?2004h\x1b[?25l\x1b[?25hsuccess\r\n\x1b[0D\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",53 },54+ {55+ name: "bp_stop_start",56+ cmds: []Cmd{DisableBracketedPaste, EnableBracketedPaste},57+ expected: "\x1b[?25l\x1b[?2004h\x1b[?2004l\x1b[?2004hsuccess\r\n\x1b[0D\x1b[2K\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",58+ },59 }60 61 for _, test := range tests {62 t.Run(test.name, func(t *testing.T) {10 unmodified lines73 t.Fatal(err)74 }75 76 if buf.String() != test.expected {72- t.Errorf("expected embedded sequence, got %q", buf.String())77+ t.Errorf("expected embedded sequence:\n%q\ngot:\n%q", test.expected, buf.String())78 }79 })80 }81 }modified:screen.go+28 added
114 unmodified lines115 // showCursorMsg is an internal command used to show the cursor. You can send116 // this message with ShowCursor.117 type showCursorMsg struct{}118 119+// EnableBracketedPaste is a special command that tells the Bubble Tea program120+// to accept bracketed paste input.121+//122+// Note that bracketed paste will be automatically disabled when the123+// program quits.124+func EnableBracketedPaste() Msg {125+ return enableBracketedPasteMsg{}126+}127+128+// enableBracketedPasteMsg in an internal message signals that129+// bracketed paste should be enabled. You can send an130+// enableBracketedPasteMsg with EnableBracketedPaste.131+type enableBracketedPasteMsg struct{}132+133+// DisableBracketedPaste is a special command that tells the Bubble Tea program134+// to accept bracketed paste input.135+//136+// Note that bracketed paste will be automatically disabled when the137+// program quits.138+func DisableBracketedPaste() Msg {139+ return disableBracketedPasteMsg{}140+}141+142+// disableBracketedPasteMsg in an internal message signals that143+// bracketed paste should be disabled. You can send an144+// disableBracketedPasteMsg with DisableBracketedPaste.145+type disableBracketedPasteMsg struct{}146+147 // EnterAltScreen enters the alternate screen buffer, which consumes the entire148 // terminal window. ExitAltScreen will return the terminal to its former state.149 //150 // Deprecated: Use the WithAltScreen ProgramOption instead.52 unmodified linesmodified:standard_renderer.go+26 added
43 unmodified lines44 45 // essentially whether or not we're using the full size of the terminal46 altScreenActive bool47 48+ // whether or not we're currently using bracketed paste49+ bpActive bool50+51 // renderer dimensions; usually the size of the window52 width int53 height int54 357 unmodified lines412 413 r.out.DisableMouseExtendedMode()414 }415 416+func (r *standardRenderer) enableBracketedPaste() {417+ r.mtx.Lock()418+ defer r.mtx.Unlock()419+420+ r.out.EnableBracketedPaste()421+ r.bpActive = true422+}423+424+func (r *standardRenderer) disableBracketedPaste() {425+ r.mtx.Lock()426+ defer r.mtx.Unlock()427+428+ r.out.DisableBracketedPaste()429+ r.bpActive = false430+}431+432+func (r *standardRenderer) bracketedPasteActive() bool {433+ r.mtx.Lock()434+ defer r.mtx.Unlock()435+436+ return r.bpActive437+}438+439 // setIgnoredLines specifies lines not to be touched by the standard Bubble Tea440 // renderer.441 func (r *standardRenderer) setIgnoredLines(from int, to int) {442 // Lock if we're going to be clearing some lines since we don't want263 unmodified linesmodified:tea.go+17 added-3 removed
79 unmodified lines80 // Options to customize the program during its initialization. These are81 // generally set with ProgramOptions.82 //83 // The options here are treated as bits.84-type startupOptions byte84+type startupOptions int1685 86 func (s startupOptions) has(option startupOptions) bool {87 return s&option != 088 }3 unmodified lines92 withMouseCellMotion93 withMouseAllMotion94 withANSICompressor95 withoutSignalHandler96-96 // Catching panics is incredibly useful for restoring the terminal to a97 // usable state after a panic occurs. When this is set, Bubble Tea will98 // recover from panics, print the stack trace, and disable raw mode. This99 // feature is on by default.100 withoutCatchPanics101+ withoutBracketedPaste102 )103 104 // handlers manages series of channels returned by various processes. It allows105 // us to wait for those processes to terminate before exiting the program.49 unmodified lines155 // was the altscreen active before releasing the terminal?156 altScreenWasActive bool157 ignoreSignals uint32158 159+ bpWasActive bool // was the bracketed paste mode active before releasing the terminal?160+161 // Stores the original reference to stdin for cases where input is not a162 // TTY on windows and we've automatically opened CONIN$ to receive input.163 // When the program exits this will be restored.164 //196 unmodified lines361 362 case hideCursorMsg:363 p.renderer.hideCursor()364 365+ case enableBracketedPasteMsg:366+ p.renderer.enableBracketedPaste()367+368+ case disableBracketedPasteMsg:369+ p.renderer.disableBracketedPaste()370+371 case execMsg:372 // NB: this blocks.373 p.exec(msg.cmd, msg.fn)374 128 unmodified lines503 // Honor program startup options.504 if p.startupOptions&withAltScreen != 0 {505 p.renderer.enterAltScreen()506 }507+ if p.startupOptions&withoutBracketedPaste == 0 {508+ p.renderer.enableBracketedPaste()509+ }510 if p.startupOptions&withMouseCellMotion != 0 {511 p.renderer.enableMouseCellMotion()512 p.renderer.enableMouseSGRMode()513 } else if p.startupOptions&withMouseAllMotion != 0 {152 unmodified lines666 p.renderer.stop()667 }668 669 p.altScreenWasActive = p.renderer.altScreen()670+ p.bpWasActive = p.renderer.bracketedPasteActive()671 return p.restoreTerminalState()672 }673 674 // RestoreTerminal reinitializes the Program's input reader, restores the7 unmodified lines682 }683 if err := p.initCancelReader(); err != nil {684 return err685 }674-686 if p.altScreenWasActive {687 p.renderer.enterAltScreen()688 } else {689 // entering alt screen already causes a repaint.1 unmodified line691 }692 if p.renderer != nil {693 p.renderer.start()694 }695+ if p.bpWasActive {696+ p.renderer.enableBracketedPaste()697+ }698 699 // If the output is a terminal, it may have been resized while another700 // process was at the foreground, in which case we may not have received701 // SIGWINCH. Detect any size change now and propagate the new size as29 unmodified linesmodified:tty.go+1 added
32 unmodified lines33 // restoreTerminalState restores the terminal to the state prior to running the34 // Bubble Tea program.35 func (p *Program) restoreTerminalState() error {36 if p.renderer != nil {37+ p.renderer.disableBracketedPaste()38 p.renderer.showCursor()39 p.disableMouse()40 41 if p.renderer.altScreen() {79 unmodified lines