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
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
Provenance
- Commit
dab626b- Tree
c8d9e13- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
2885df8
4 files changed+166 added−17 removed
modified:src/tui/light_unix.go+101 added-12 removed
6 unmodified lines7 "os"8 "os/exec"9 "strings"10 "syscall"11+ "time"12 13 "github.com/junegunn/fzf/src/util"14 "golang.org/x/sys/unix"15 "golang.org/x/term"77 unmodified lines93 r.height = r.maxHeightFunc(getEnv("LINES", defaultHeight))94 }95 }96 96-func (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.103+func (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+}131+132+// 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.136+func (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{}141+142+ 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+ }149+150+ var err error151+ buffer, _, err = r.getBytesInternal(false, buffer, tries > 0)152 if err != nil {104- return -1, -1153+ return replies154 }155 107- 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 }174+175+ if replies[len(queries)-1] != nil {176+ break177+ }178 }114- return -1, -1179+180+ r.buffer = append(r.buffer, buffer...)181+ return replies182 }183 184+func (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+}194+195+func 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+}201+202+func (r *LightRenderer) findOffset() (row int, col int) {203+ return parseOffset(r.queryTerminal(startupQueries[1:])[0])204+}205+206 func (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 linesmodified:src/tui/light_windows.go+7 added
149 unmodified lines150 }151 return int(bufferInfo.CursorPosition.Y), int(bufferInfo.CursorPosition.X)152 }153 154+// 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.156+func (r *LightRenderer) queryStartup() (row int, col int, pasteWasSet *bool) {157+ row, col = r.findOffset()158+ return159+}160+161 func (r *LightRenderer) getch(cancellable bool, nonblock bool) (int, getCharResult) {162 if !nonblock && !cancellable {163 bc := <-r.ttyinChannel164 return int(bc), getCharSuccess26 unmodified linesmodified:src/tui/light.go+56 added-5 removed
22 unmodified lines23 24 defaultEscDelay = 10025 escPollInterval = 526 offsetPollTries = 1027+ queryTimeout = 500 * time.Millisecond28 maxInputBuffer = 1024 * 102429 maxSelectTries = 10030 )31 32 const DefaultTtyDevice string = "/dev/tty"33 33-var offsetRegexp = regexp.MustCompile("(.*?)\x00?\x1b\\[([0-9]+);([0-9]+)R")34+var offsetRegexp = regexp.MustCompile("\x00?\x1b\\[([0-9]+);([0-9]+)R")35 var offsetRegexpBegin = regexp.MustCompile("^\x1b\\[[0-9]+;[0-9]+R")36 37+// 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.40+var pasteModeRegexp = regexp.MustCompile("\x00?\x1b\\[\\?2004;([0-4])\\$y")41+var pasteModeRegexpBegin = regexp.MustCompile("^\x1b\\[\\?2004;[0-4]\\$y")42+43+// A report to ask the terminal for, and the reply to recognize it by.44+type termQuery struct {45+ seq string46+ reply *regexp.Regexp47+}48+49+// 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.54+var startupQueries = []termQuery{55+ {"?2004$p", pasteModeRegexp},56+ {"6n", offsetRegexp},57+}58+59 func (r *LightRenderer) Bell() {60 r.flushRaw("\a")61 }62 117 unmodified lines180 maxHeightFunc func(int) int181 showCursor bool182 mutex sync.Mutex183 184+ // Whether bracketed paste was already on before we enabled it. Nil when185+ // the terminal did not answer the query.186+ pasteWasSet *bool187+188 // Windows only189 ttyinChannel chan byte190 inHandle uintptr191 outHandle uintptr64 unmodified lines256 r.updateTerminalSize()257 258 if r.fullscreen {259 r.smcup()233- } else {234- y, x := r.findOffset()260+ }261+262+ // Ask everything in one round trip, before the offset is needed.263+ y, x, pasteWasSet := r.queryStartup()264+ r.pasteWasSet = pasteWasSet265+266+ 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 be78 unmodified lines349 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+ }358 359 pc := c360 for {361 c, result = r.getch(false, true)119 unmodified lines481 *sz = loc[1]482 return Event{Invalid, 0, nil}483 }484 485+ loc = pasteModeRegexpBegin.FindIndex(r.buffer)486+ if loc != nil && loc[0] == 0 {487+ *sz = loc[1]488+ return Event{Invalid, 0, nil}489+ }490+491 *sz = 2492 if r.buffer[1] == 8 {493 return Event{CtrlAltBackspace, 0, nil}494 }565 unmodified lines1060 }1061 1062 func (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 }1075 1076 func (r *LightRenderer) Resume(clear bool, sigcont bool) {1077 r.setupTerminal()563 unmodified linesmodified:CHANGELOG.md+2 added
10 unmodified lines11 - 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)17 18 0.74.219 ------20 - Performance optimizations for short queries3408 unmodified lines