Skip to content
Myr

Restore bracketed paste mode instead of forcing it off

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Ask the terminal whether the mode is already on (DECRQM) and put it back that way on exit. Forcing it off broke pasting in shells that run fzf from a line editor widget, which enable the mode only when the editor starts. Terminals that do not answer fall back to disabling it. - Startup queries go out in one write, cursor position last. Every terminal answers DSR, so its reply bounds the wait: a paste reply still missing by then means the terminal does not know the query. - Bound the first read with select(2). Terminals that never answer escape sequences, such as FreeBSD virtual terminals, blocked startup until a key was pressed, and that keystroke was then discarded. Fix #4887 Fix #2860 Fix #976

authored by Junegunn Choi · committed by Junegunn Choi · parent 2885df8 · Browse files · 4 files+166 added−17 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+166 added−17 removed

  • other:+166 added−17 removed

4 files+166 added−17 removed

modified:src/tui/light_unix.go+101 added-12 removed
6 unmodified lines
7 "os"8 "os/exec"9 "strings"10 "syscall"11 "time"1213 "github.com/junegunn/fzf/src/util"14 "golang.org/x/sys/unix"15 "golang.org/x/term"
77 unmodified lines
93 r.height = r.maxHeightFunc(getEnv("LINES", defaultHeight))94 }95}9696func (r *LightRenderer) findOffset() (row int, col int) {97 r.csi("6n")97// waitReadable reports whether the tty has something to read before the98// deadline. A terminal that does not recognize a query answers nothing at all,99// so the read that follows must be able to stop waiting, or fzf would wait for100// the user to press a key instead of drawing itself. The timeout is generous101// because a terminal that does answer exceeds it only when the link is slow102// enough to be unusable anyway.103func (r *LightRenderer) waitReadable(timeout time.Duration) bool {104 fd := r.fd()105 deadline := time.Now().Add(timeout)106 for {107 remaining := time.Until(deadline)108 if remaining <= 0 {109 return false110 }111 var rfds unix.FdSet112 if fd >= len(rfds.Bits)*unix.NFDBITS {113 return false114 }115 rfds.Set(fd)116 // Recomputed each time round: Linux select rewrites the timeout with117 // the time left, other systems leave it alone118 tv := unix.NsecToTimeval(int64(remaining))119 n, err := unix.Select(fd+1, &rfds, nil, nil, &tv)120 if err == syscall.EINTR {121 continue122 }123 if err != nil {124 // Nothing was confirmed readable, and the read that follows125 // reports the failure if the fd is really broken126 return false127 }128 return n > 0129 }130}131132// queryTerminal sends every query in a single write and reads until the last133// one is answered. Returns the submatches of each reply, nil for a query the134// terminal ignored. Replies are cut out of what we read as they are recognized,135// so whatever is left over is input the user typed during the round trip.136func (r *LightRenderer) queryTerminal(queries []termQuery) [][][]byte {137 for _, query := range queries {138 r.csi(query.seq)139 }140 r.flush()99 var err error100 bytes := []byte{}141142 replies := make([][][]byte, len(queries))143 buffer := []byte{}144 for tries := range offsetPollTries {102 bytes, _, err = r.getBytesInternal(false, bytes, tries > 0)145 // Only the first read blocks, so that is the one to put a bound on146 if tries == 0 && !r.waitReadable(queryTimeout) {147 return replies148 }149150 var err error151 buffer, _, err = r.getBytesInternal(false, buffer, tries > 0)152 if err != nil {104 return -1, -1153 return replies154 }155107 offsets := offsetRegexp.FindSubmatch(bytes)108 if len(offsets) > 3 {109 // Add anything we skipped over to the input buffer110 r.buffer = append(r.buffer, offsets[1]...)111 return atoi(string(offsets[2]), 0) - 1, atoi(string(offsets[3]), 0) - 1156 for idx, query := range queries {157 if replies[idx] != nil {158 continue159 }160 loc := query.reply.FindSubmatchIndex(buffer)161 if loc == nil {162 continue163 }164 groups := make([][]byte, len(loc)/2)165 for group := range groups {166 if loc[group*2] >= 0 {167 groups[group] = buffer[loc[group*2]:loc[group*2+1]]168 }169 }170 replies[idx] = groups171 // Capping the prefix makes append copy, leaving groups valid172 buffer = append(buffer[:loc[0]:loc[0]], buffer[loc[1]:]...)173 }174175 if replies[len(queries)-1] != nil {176 break177 }178 }114 return -1, -1179180 r.buffer = append(r.buffer, buffer...)181 return replies182}183184func (r *LightRenderer) queryStartup() (row int, col int, pasteWasSet *bool) {185 replies := r.queryTerminal(startupQueries)186 if paste := replies[0]; paste != nil && paste[1][0] != '0' {187 // 1 = set, 3 = permanently set188 set := paste[1][0] == '1' || paste[1][0] == '3'189 pasteWasSet = &set190 }191 row, col = parseOffset(replies[1])192 return193}194195func parseOffset(reply [][]byte) (row int, col int) {196 if reply == nil {197 return -1, -1198 }199 return atoi(string(reply[1]), 0) - 1, atoi(string(reply[2]), 0) - 1200}201202func (r *LightRenderer) findOffset() (row int, col int) {203 return parseOffset(r.queryTerminal(startupQueries[1:])[0])204}205206func (r *LightRenderer) getch(cancellable bool, nonblock bool) (int, getCharResult) {207 fd := r.fd()208 getter := func() (int, getCharResult) {209 b := make([]byte, 1)
61 unmodified lines
modified:src/tui/light_windows.go+7 added
149 unmodified lines
150 }151 return int(bufferInfo.CursorPosition.Y), int(bufferInfo.CursorPosition.X)152}153154// The console API answers for the cursor, and there is no reply to parse for155// bracketed paste, so fzf keeps disabling the mode on exit here.156func (r *LightRenderer) queryStartup() (row int, col int, pasteWasSet *bool) {157 row, col = r.findOffset()158 return159}160161func (r *LightRenderer) getch(cancellable bool, nonblock bool) (int, getCharResult) {162 if !nonblock && !cancellable {163 bc := <-r.ttyinChannel164 return int(bc), getCharSuccess
26 unmodified lines
modified:src/tui/light.go+56 added-5 removed
22 unmodified lines
2324 defaultEscDelay = 10025 escPollInterval = 526 offsetPollTries = 1027 queryTimeout = 500 * time.Millisecond28 maxInputBuffer = 1024 * 102429 maxSelectTries = 10030)3132const DefaultTtyDevice string = "/dev/tty"3333var offsetRegexp = regexp.MustCompile("(.*?)\x00?\x1b\\[([0-9]+);([0-9]+)R")34var offsetRegexp = regexp.MustCompile("\x00?\x1b\\[([0-9]+);([0-9]+)R")35var offsetRegexpBegin = regexp.MustCompile("^\x1b\\[[0-9]+;[0-9]+R")3637// DECRPM reply to the DECRQM query for bracketed paste mode. Ps is 1 or 3 when38// the mode was already set, 2 or 4 when reset, 0 when the terminal does not39// recognize the mode.40var pasteModeRegexp = regexp.MustCompile("\x00?\x1b\\[\\?2004;([0-4])\\$y")41var pasteModeRegexpBegin = regexp.MustCompile("^\x1b\\[\\?2004;[0-4]\\$y")4243// A report to ask the terminal for, and the reply to recognize it by.44type termQuery struct {45 seq string46 reply *regexp.Regexp47}4849// What we ask the terminal at startup, in the order the queries go out. A50// terminal answers them in that order, so the cursor position query is last and51// also ends the wait: every terminal fzf supports answers it, so once its reply52// arrives, a query still unanswered is one the terminal does not know rather53// than one we stopped waiting for too early.54var startupQueries = []termQuery{55 {"?2004$p", pasteModeRegexp},56 {"6n", offsetRegexp},57}5859func (r *LightRenderer) Bell() {60 r.flushRaw("\a")61}62
117 unmodified lines
180 maxHeightFunc func(int) int181 showCursor bool182 mutex sync.Mutex183184 // Whether bracketed paste was already on before we enabled it. Nil when185 // the terminal did not answer the query.186 pasteWasSet *bool187188 // Windows only189 ttyinChannel chan byte190 inHandle uintptr191 outHandle uintptr
64 unmodified lines
256 r.updateTerminalSize()257258 if r.fullscreen {259 r.smcup()233 } else {234 y, x := r.findOffset()260 }261262 // Ask everything in one round trip, before the offset is needed.263 y, x, pasteWasSet := r.queryStartup()264 r.pasteWasSet = pasteWasSet265266 if !r.fullscreen {267 r.mouse = r.mouse && y >= 0268 // When --no-clear is used for repetitive relaunching, there is a small269 // time frame between fzf processes where the user keystrokes are not270 // captured by either of fzf process which can cause x offset to be
78 unmodified lines
349 retries := 0350 if c == Esc.Int() || nonblock {351 retries = r.escDelay / escPollInterval352 }353 // A non-blocking read that found nothing has no byte to record. Recording354 // one would put a NUL in the middle of a reply still being assembled.355 if result.ok() {321 buffer = append(buffer, byte(c))356 buffer = append(buffer, byte(c))357 }358359 pc := c360 for {361 c, result = r.getch(false, true)
119 unmodified lines
481 *sz = loc[1]482 return Event{Invalid, 0, nil}483 }484485 loc = pasteModeRegexpBegin.FindIndex(r.buffer)486 if loc != nil && loc[0] == 0 {487 *sz = loc[1]488 return Event{Invalid, 0, nil}489 }490491 *sz = 2492 if r.buffer[1] == 8 {493 return Event{CtrlAltBackspace, 0, nil}494 }
565 unmodified lines
1060}10611062func (r *LightRenderer) disableModes() {1063 r.disableMouse()1064 // Put bracketed paste back the way we found it. A shell that runs fzf from1065 // a line editor widget re-enables the mode only when the editor starts, so1066 // forcing it off here would leave it off for the rest of the session.1067 // Terminals that did not answer the query fall back to disabling, which is1068 // what fzf has always done.1069 if r.pasteWasSet != nil && *r.pasteWasSet {1070 r.csi("?2004h")1071 } else {1022 r.csi("?2004l")1072 r.csi("?2004l")1073 }1074}10751076func (r *LightRenderer) Resume(clear bool, sigcont bool) {1077 r.setupTerminal()
563 unmodified lines
modified:CHANGELOG.md+2 added
10 unmodified lines
11 - Accented Latin and fullwidth forms get the faster reading but not the faster queries, because those characters can still match their ASCII counterparts12 - ASCII input is unaffected13- Fixed an image from a preview command being torn apart when its rows are separated by IND instead of newlines, as `chafa` does under tmux (#4885)14- Fixed `replace-query` corrupting the item text when the query is edited afterwards15- fzf no longer turns bracketed paste mode off on exit when the terminal already had it on, which broke pasting in shells that run fzf from a line editor widget (#4887)16- Fixed startup blocking on terminals that never answer escape sequences, such as FreeBSD virtual terminals. fzf waited for a reply until a key was pressed, then dropped that keystroke (#2860, #976)17180.74.219------20- Performance optimizations for short queries
3408 unmodified lines