Skip to content
Myr

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. ---------

authored by Raphael 'kena' Poss · committed by GitHub · parent ab7e5ea · Browse files · 13 files+222 added−51 removed
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

13 files+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 key2Hi. This program will exit in 9 seconds. To quit sooner press any key.3[?25h[?1002l[?1003l[?1006l3[?2004l[?25h[?1002l[?1003l[?1006l
modified:key_sequences.go+49 added-1 removed
1package tea23import "sort"3import (4 "bytes"5 "sort"6 "unicode/utf8"7)89// 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 lines
72 }7374 return false, 0, nil75}7677// 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.83func 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 }8990 // Skip over the start sequence.91 input = input[len(bpStart):]9293 // 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 }104105 // The paste is everything in-between.106 paste := input[:idx]107108 // 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 }117118 return true, inputLen, KeyMsg(k)119}
modified:key_test.go+14 added-12 removed
432 unmodified lines
433 {"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 lines
modified:key.go+27 added-5 removed
3 unmodified lines
4 "context"5 "fmt"6 "io"7 "regexp"8 "strings"9 "unicode/utf8"10)1112// KeyMsg contains information about a keypress. KeyMsgs are always sent to
41 unmodified lines
54type Key struct {55 Type KeyType56 Runes []rune57 Alt bool58 Paste bool59}6061// String returns a friendly string representation for a key. It's safe (and62// encouraged) for use in key comparison.
1 unmodified line
64// k := Key{Type: KeyEnter}65// fmt.Println(k)66// // Output: enter67func (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 lines
627 }628 }629 }630631 // Detect bracketed paste.632 var foundbp bool633 foundbp, w, msg = detectBracketedPaste(b)634 if foundbp {635 return636 }637638 // 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 bool
67 unmodified lines
modified:nil_renderer.go+20 added-17 removed
1package tea23type nilRenderer struct{}45func (n nilRenderer) start() {}6func (n nilRenderer) stop() {}7func (n nilRenderer) kill() {}8func (n nilRenderer) write(_ string) {}9func (n nilRenderer) repaint() {}10func (n nilRenderer) clearScreen() {}11func (n nilRenderer) altScreen() bool { return false }12func (n nilRenderer) enterAltScreen() {}13func (n nilRenderer) exitAltScreen() {}14func (n nilRenderer) showCursor() {}15func (n nilRenderer) hideCursor() {}16func (n nilRenderer) enableMouseCellMotion() {}17func (n nilRenderer) disableMouseCellMotion() {}18func (n nilRenderer) enableMouseAllMotion() {}19func (n nilRenderer) disableMouseAllMotion() {}20func (n nilRenderer) enableMouseSGRMode() {}21func (n nilRenderer) disableMouseSGRMode() {}5func (n nilRenderer) start() {}6func (n nilRenderer) stop() {}7func (n nilRenderer) kill() {}8func (n nilRenderer) write(_ string) {}9func (n nilRenderer) repaint() {}10func (n nilRenderer) clearScreen() {}11func (n nilRenderer) altScreen() bool { return false }12func (n nilRenderer) enterAltScreen() {}13func (n nilRenderer) exitAltScreen() {}14func (n nilRenderer) showCursor() {}15func (n nilRenderer) hideCursor() {}16func (n nilRenderer) enableMouseCellMotion() {}17func (n nilRenderer) disableMouseCellMotion() {}18func (n nilRenderer) enableMouseAllMotion() {}19func (n nilRenderer) disableMouseAllMotion() {}20func (n nilRenderer) enableBracketedPaste() {}21func (n nilRenderer) disableBracketedPaste() {}22func (n nilRenderer) enableMouseSGRMode() {}23func (n nilRenderer) disableMouseSGRMode() {}24func (n nilRenderer) bracketedPasteActive() bool { return false }
modified:options_test.go+6 added-2 removed
79 unmodified lines
80 t.Run("alt screen", func(t *testing.T) {81 exercise(t, WithAltScreen(), withAltScreen)82 })8384 t.Run("bracketed paste disabled", func(t *testing.T) {85 exercise(t, WithoutBracketedPaste(), withoutBracketedPaste)86 })8788 t.Run("ansi compression", func(t *testing.T) {89 exercise(t, WithANSICompressor(), withANSICompressor)90 })91
26 unmodified lines
118 })119 })120121 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 lines
modified:options.go+7 added
99 unmodified lines
100 p.startupOptions |= withAltScreen101 }102}103104// WithoutBracketedPaste starts the program with bracketed paste disabled.105func WithoutBracketedPaste() ProgramOption {106 return func(p *Program) {107 p.startupOptions |= withoutBracketedPaste108 }109}110111// WithMouseCellMotion starts the program with the mouse enabled in "cell112// motion" mode.113//114// Cell motion mode enables mouse click, release, and wheel events. Mouse
111 unmodified lines
modified:renderer.go+11 added
54 unmodified lines
55 enableMouseSGRMode()5657 // disableMouseSGRMode disables mouse extended mode (SGR).58 disableMouseSGRMode()5960 // enableBracketedPaste enables bracketed paste, where characters61 // inside the input are not interpreted when pasted as a whole.62 enableBracketedPaste()6364 // disableBracketedPaste disables bracketed paste.65 disableBracketedPaste()6667 // bracketedPasteActive reports whether bracketed paste mode is68 // currently enabled.69 bracketedPasteActive() bool70}7172// repaintMsg forces a full repaint.73type repaintMsg struct{}
modified:screen_test.go+14 added-9 removed
12 unmodified lines
13 }{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 }6061 for _, test := range tests {62 t.Run(test.name, func(t *testing.T) {
10 unmodified lines
73 t.Fatal(err)74 }7576 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 lines
115// showCursorMsg is an internal command used to show the cursor. You can send116// this message with ShowCursor.117type showCursorMsg struct{}118119// 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.124func EnableBracketedPaste() Msg {125 return enableBracketedPasteMsg{}126}127128// enableBracketedPasteMsg in an internal message signals that129// bracketed paste should be enabled. You can send an130// enableBracketedPasteMsg with EnableBracketedPaste.131type enableBracketedPasteMsg struct{}132133// 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.138func DisableBracketedPaste() Msg {139 return disableBracketedPasteMsg{}140}141142// disableBracketedPasteMsg in an internal message signals that143// bracketed paste should be disabled. You can send an144// disableBracketedPasteMsg with DisableBracketedPaste.145type disableBracketedPasteMsg struct{}146147// 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 lines
modified:standard_renderer.go+26 added
43 unmodified lines
4445 // essentially whether or not we're using the full size of the terminal46 altScreenActive bool4748 // whether or not we're currently using bracketed paste49 bpActive bool5051 // renderer dimensions; usually the size of the window52 width int53 height int54
357 unmodified lines
412413 r.out.DisableMouseExtendedMode()414}415416func (r *standardRenderer) enableBracketedPaste() {417 r.mtx.Lock()418 defer r.mtx.Unlock()419420 r.out.EnableBracketedPaste()421 r.bpActive = true422}423424func (r *standardRenderer) disableBracketedPaste() {425 r.mtx.Lock()426 defer r.mtx.Unlock()427428 r.out.DisableBracketedPaste()429 r.bpActive = false430}431432func (r *standardRenderer) bracketedPasteActive() bool {433 r.mtx.Lock()434 defer r.mtx.Unlock()435436 return r.bpActive437}438439// setIgnoredLines specifies lines not to be touched by the standard Bubble Tea440// renderer.441func (r *standardRenderer) setIgnoredLines(from int, to int) {442 // Lock if we're going to be clearing some lines since we don't want
263 unmodified lines
modified:tea.go+17 added-3 removed
79 unmodified lines
80// Options to customize the program during its initialization. These are81// generally set with ProgramOptions.82//83// The options here are treated as bits.84type startupOptions byte84type startupOptions int168586func (s startupOptions) has(option startupOptions) bool {87 return s&option != 088}
3 unmodified lines
92 withMouseCellMotion93 withMouseAllMotion94 withANSICompressor95 withoutSignalHandler9696 // 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)103104// 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 lines
155 // was the altscreen active before releasing the terminal?156 altScreenWasActive bool157 ignoreSignals uint32158159 bpWasActive bool // was the bracketed paste mode active before releasing the terminal?160161 // 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 lines
361362 case hideCursorMsg:363 p.renderer.hideCursor()364365 case enableBracketedPasteMsg:366 p.renderer.enableBracketedPaste()367368 case disableBracketedPasteMsg:369 p.renderer.disableBracketedPaste()370371 case execMsg:372 // NB: this blocks.373 p.exec(msg.cmd, msg.fn)374
128 unmodified lines
503 // 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 lines
666 p.renderer.stop()667 }668669 p.altScreenWasActive = p.renderer.altScreen()670 p.bpWasActive = p.renderer.bracketedPasteActive()671 return p.restoreTerminalState()672}673674// RestoreTerminal reinitializes the Program's input reader, restores the
7 unmodified lines
682 }683 if err := p.initCancelReader(); err != nil {684 return err685 }674686 if p.altScreenWasActive {687 p.renderer.enterAltScreen()688 } else {689 // entering alt screen already causes a repaint.
1 unmodified line
691 }692 if p.renderer != nil {693 p.renderer.start()694 }695 if p.bpWasActive {696 p.renderer.enableBracketedPaste()697 }698699 // 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 as
29 unmodified lines
modified:tty.go+1 added
32 unmodified lines
33// restoreTerminalState restores the terminal to the state prior to running the34// Bubble Tea program.35func (p *Program) restoreTerminalState() error {36 if p.renderer != nil {37 p.renderer.disableBracketedPaste()38 p.renderer.showCursor()39 p.disableMouse()4041 if p.renderer.altScreen() {
79 unmodified lines