ycdemo / fzf / src/ tui/ light.go

package tui

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"
	"unicode/utf8"

	"github.com/junegunn/fzf/src/util"

	"golang.org/x/term"
)

const (
	defaultWidth  = 80
	defaultHeight = 24

	defaultEscDelay = 100
	escPollInterval = 5
	offsetPollTries = 10
	queryTimeout    = 500 * time.Millisecond
	maxInputBuffer  = 1024 * 1024
	escapeLookback  = 256
)

const DefaultTtyDevice string = "/dev/tty"

var offsetRegexp = regexp.MustCompile("\x00?\x1b\\[([0-9]+);([0-9]+)R")
var offsetRegexpBegin = regexp.MustCompile("^\x1b\\[[0-9]+;[0-9]+R")

// DECRPM reply to the DECRQM query for bracketed paste mode. Ps is 1 or 3 when
// the mode was already set, 2 or 4 when reset, 0 when the terminal does not
// recognize the mode.
var pasteModeRegexp = regexp.MustCompile("\x00?\x1b\\[\\?2004;([0-4])\\$y")
var pasteModeRegexpBegin = regexp.MustCompile("^\x1b\\[\\?2004;[0-4]\\$y")

// A report to ask the terminal for, and the reply to recognize it by.
type termQuery struct {
	seq   string
	reply *regexp.Regexp
}

var offsetQuery = termQuery{"6n", offsetRegexp}
var pasteModeQuery = termQuery{"?2004$p", pasteModeRegexp}

// What we ask the terminal at startup, in the order the queries go out.
// A terminal answers them in that order, so the cursor position query is last
// and also ends the wait: every terminal fzf supports answers it, so once its
// reply arrives, a query still unanswered is one the terminal does not know
// rather than one we stopped waiting for too early.
//
// Terminals that don't support the paste mode query (DECRQM) might leave
// 'p' on the screen. To handle such cases, we query the position before and
// after it, compare them, and clean the artifact if they don't match.
//
// Reference: https://ansicode.eversources.app/en/sequence/decrqm
var startupQueries = []termQuery{offsetQuery, pasteModeQuery, offsetQuery}

func (r *LightRenderer) Bell() {
	r.flushRaw("\a")
}

func (r *LightRenderer) PassThrough(str string) {
	r.queued.WriteString("\x1b7" + str + "\x1b8")
	r.invalidateSGR()
}

func (r *LightRenderer) stderr(str string) {
	r.stderrInternal(str, true, "")
}

const DIM string = "\x1b[2m"
const CR string = DIM + "␍"
const LF string = DIM + "␊"

type getCharResult int

const (
	getCharSuccess getCharResult = iota
	getCharError
	getCharCancelled
)

func (r getCharResult) ok() bool {
	return r == getCharSuccess
}

func (r *LightRenderer) stderrInternal(str string, allowNLCR bool, resetCode string) {
	bytes := []byte(str)
	runes := []rune{}
	for len(bytes) > 0 {
		r, sz := utf8.DecodeRune(bytes)
		nlcr := r == '\n' || r == '\r'
		isC1 := r >= 0x80 && r <= 0x9F
		if (r >= 32 && !isC1) || r == '\x1b' || nlcr {
			if nlcr && !allowNLCR {
				if r == '\r' {
					runes = append(runes, []rune(CR+resetCode)...)
				} else {
					runes = append(runes, []rune(LF+resetCode)...)
				}
			} else if r != utf8.RuneError {
				runes = append(runes, r)
			}
		}
		bytes = bytes[sz:]
	}
	r.queued.WriteString(string(runes))
}

func (r *LightRenderer) csi(code string) string {
	fullcode := "\x1b[" + code
	r.stderr(fullcode)
	return fullcode
}

// setSGR emits the given SGR sequence only when the terminal is not already
// in that state. Sequences built by csiColor start with a reset parameter,
// so each of them fully determines the state on its own. The zero value of
// r.sgr never matches a sequence, so the first update after Init, Resume, or
// invalidateSGR is always emitted.
func (r *LightRenderer) setSGR(code string) {
	if code != r.sgr {
		r.stderr(code)
		r.sgr = code
	}
}

// invalidateSGR marks the terminal SGR state as unknown, e.g. after raw
// output that may have changed it behind the renderer's back.
func (r *LightRenderer) invalidateSGR() {
	r.sgr = ""
}

func (r *LightRenderer) flush() {
	if r.queued.Len() > 0 {
		// Leave the terminal in the default SGR state between frames
		r.setSGR("\x1b[0m")
		// Wrap the frame in synchronized update mode (2026) so that the
		// terminal applies it atomically. Terminals without support ignore
		// the unknown private mode and behave as before.
		raw := "\x1b[?2026h\x1b[?7l\x1b[?25l" + r.queued.String()
		if r.showCursor {
			raw += "\x1b[?25h"
		}
		raw += "\x1b[?7h\x1b[?2026l"
		r.flushRaw(raw)
		r.queued.Reset()
	}
}

func (r *LightRenderer) flushRaw(sequence string) {
	fmt.Fprint(r.ttyout, sequence)
}

// Light renderer
type LightRenderer struct {
	theme         *ColorTheme
	mouse         bool
	forceBlack    bool
	clearOnExit   bool
	prevDownTime  time.Time
	clicks        [][2]int
	ttyin         *os.File
	ttyout        *os.File
	cancel        func()
	buffer        []byte
	origState     *term.State
	width         int
	height        int
	yoffset       int
	xoffset       int
	tabstop       int
	escDelay      int
	fullscreen    bool
	upOneLine     bool
	queued        strings.Builder
	sgr           string
	y             int
	x             int
	maxHeightFunc func(int) int
	showCursor    bool
	mutex         sync.Mutex

	// Whether bracketed paste was already on before we enabled it. Nil when
	// the terminal did not answer the query.
	pasteWasSet *bool

	// Windows only
	ttyinChannel    chan byte
	inHandle        uintptr
	outHandle       uintptr
	origStateInput  uint32
	origStateOutput uint32
}

type LightWindow struct {
	renderer      *LightRenderer
	colored       bool
	windowType    WindowType
	border        BorderStyle
	top           int
	left          int
	width         int
	height        int
	posx          int
	posy          int
	tabstop       int
	fg            Color
	bg            Color
	wrapSign      string
	wrapSignWidth int
}

func NewLightRenderer(ttyDefault string, ttyin *os.File, theme *ColorTheme, forceBlack bool, mouse bool, tabstop int, clearOnExit bool, fullscreen bool, maxHeightFunc func(int) int) (Renderer, error) {
	out, err := openTtyOut(ttyDefault)
	if err != nil {
		out = os.Stderr
	}
	r := LightRenderer{
		theme:         theme,
		forceBlack:    forceBlack,
		mouse:         mouse,
		clearOnExit:   clearOnExit,
		ttyin:         ttyin,
		ttyout:        out,
		yoffset:       0,
		tabstop:       tabstop,
		fullscreen:    fullscreen,
		upOneLine:     false,
		maxHeightFunc: maxHeightFunc,
		showCursor:    true}
	return &r, nil
}

func repeat(r rune, times int) string {
	if times > 0 {
		return strings.Repeat(string(r), times)
	}
	return ""
}

func atoi(s string, defaultValue int) int {
	value, err := strconv.Atoi(s)
	if err != nil {
		return defaultValue
	}
	return value
}

func (r *LightRenderer) Init() error {
	r.escDelay = atoi(os.Getenv("ESCDELAY"), defaultEscDelay)

	if err := r.initPlatform(); err != nil {
		return err
	}
	r.updateTerminalSize()

	if r.fullscreen {
		r.smcup()
	}

	// Ask everything in one round trip, before the offset is needed.
	y, x, pasteWasSet := r.queryStartup()
	r.pasteWasSet = pasteWasSet

	if !r.fullscreen {
		r.mouse = r.mouse && y >= 0
		// When --no-clear is used for repetitive relaunching, there is a small
		// time frame between fzf processes where the user keystrokes are not
		// captured by either of fzf process which can cause x offset to be
		// increased and we're left with unwanted extra new line.
		if x > 0 && r.clearOnExit {
			r.upOneLine = true
			r.xoffset = x
			r.makeSpace()
		}
		// We assume that --no-clear is used for repetitive relaunching of fzf.
		// So we do not clear the lower bottom of the screen.
		if r.clearOnExit {
			r.csi("J")
		}
		for i := 1; i < r.MaxY(); i++ {
			r.makeSpace()
		}
	}

	r.enableModes()
	r.csi(fmt.Sprintf("%dA", r.MaxY()-1))
	r.csi("G")
	r.csi("K")
	if !r.clearOnExit && !r.fullscreen {
		r.stderr("\x1b7") // DECSC: save cursor position
	}
	if !r.fullscreen && r.mouse {
		r.yoffset, _ = r.findOffset()
	}
	return nil
}

func (r *LightRenderer) Resize(maxHeightFunc func(int) int) {
	r.maxHeightFunc = maxHeightFunc
}

func (r *LightRenderer) makeSpace() {
	r.stderr("\n")
	r.csi("G")
}

func (r *LightRenderer) move(y int, x int) {
	if r.y < y {
		r.csi(fmt.Sprintf("%dB", y-r.y))
	} else if r.y > y {
		r.csi(fmt.Sprintf("%dA", r.y-y))
	}
	if x == 0 {
		r.stderr("\r")
	} else {
		r.csi(fmt.Sprintf("%dG", x+1))
	}
	r.y = y
	r.x = x
}

func (r *LightRenderer) origin() {
	r.move(0, 0)
}

func getEnv(name string, defaultValue int) int {
	env := os.Getenv(name)
	if len(env) == 0 {
		return defaultValue
	}
	return atoi(env, defaultValue)
}

// Bytes of a CSI sequence: parameter and intermediate bytes continue it, a
// final byte ends it. Order is not enforced. Strictness would only make fzf
// give up on a sequence it could have framed.
//
// https://vt100.net/emu/dec_ansi_parser
func csiContinues(b byte) bool { return b >= 0x20 && b <= 0x3f }
func csiFinal(b byte) bool     { return b >= 0x40 && b <= 0x7e }

// csiEnd returns the length of the CSI or SS3 sequence at the start of the
// buffer, 0 if it has no final byte yet, or -1 if it is malformed.
func csiEnd(buffer []byte) int {
	digits := true
	for i := 2; i < len(buffer); i++ {
		b := buffer[i]
		// rxvt ends keys with $ after at least one digit, as in \e[7$ for
		// SHIFT-HOME and \e[23$ for SHIFT-F11. Elsewhere $ is an intermediate byte.
		if csiFinal(b) || b == '
		
		
		
		
	

 && digits && i > 2 {
			return i + 1
		}
		if !csiContinues(b) {
			return -1
		}
		digits = digits && b >= '0' && b <= '9'
	}
	return 0
}

// stringEnd returns the length of the string sequence (DCS, OSC or APC) at the
// start of the buffer, or 0 while nothing has ended it. A terminator is
// included, an ESC that introduces another sequence is not.
func stringEnd(buffer []byte) int {
	if len(buffer) < 2 {
		return 0
	}
	// Every one of them ends with ST. BEL ends an OSC as well, because xterm has
	// always allowed it, but stopping at a BEL inside a DCS or APC payload would
	// frame only its first half and leave the rest to be typed into the query.
	bel := buffer[1] == ']'
	for i := 2; i < len(buffer); i++ {
		switch buffer[i] {
		case '\a':
			if bel {
				return i + 1
			}
		case Esc.Byte():
			if i+1 == len(buffer) {
				return 0 // ST may still be arriving
			}
			if buffer[i+1] == '\\' {
				return i + 2
			}
			// Any other ESC ends the string and introduces a sequence of its
			// own, so frame only what precedes it and leave the ESC to be
			// parsed again. Scanning past it would swallow that sequence too.
			return i
		}
	}
	return 0
}

// rxvtKeyEnd reports whether the byte ends a key such as \e[7~ for Home.
// rxvt marks modifiers with the final byte: $ for SHIFT, ^ for CTRL, @ for both.
func rxvtKeyEnd(b byte) bool {
	return b == '~' || b == '
		
		
		
		
	

 || b == '^' || b == '@'
}

// csiIntroducer reports whether the byte after ESC starts a sequence that is
// framed by a final byte. The parser routes CSI and SS3 through the same
// parameterized subcases, so both are framed by csiEnd.
func csiIntroducer(b byte) bool {
	return b == '[' || b == 'O'
}

// stringIntroducer reports whether the byte after ESC starts a string sequence.
// Only the three that terminals reply with: OSC for colors, title and clipboard,
// DCS for XTVERSION, DECRQSS and XTGETTCAP, APC for Kitty graphics. Nothing
// sends SOS or PM.
func stringIntroducer(b byte) bool {
	switch b {
	case 'P', ']', '_':
		return true
	}
	return false
}

// stringReply reports whether a framed string sequence starts the way a
// terminal's reply does. Its introducer is also ALT-], ALT-P or ALT-_, and typed
// text after one, ended by CTRL-G or another key, frames like a reply when it
// all arrives in one read.
func stringReply(buffer []byte) bool {
	payload := buffer[2:]
	switch buffer[1] {
	case ']': // Ps ; ...
		i := 0
		for i < len(payload) && payload[i] >= '0' && payload[i] <= '9' {
			i++
		}
		return i > 0 && i < len(payload) && payload[i] == ';'
	case 'P': // >| or !| for the version, [01]$r or [01]+r for settings
		if len(payload) < 2 {
			return false
		}
		if payload[1] == '|' {
			return payload[0] == '>' || payload[0] == '!'
		}
		return len(payload) >= 3 && (payload[0] == '0' || payload[0] == '1') &&
			(payload[1] == '
		
		
		
		
	

 || payload[1] == '+') && payload[2] == 'r'
	case '_': // G, then key=value
		return len(payload) >= 3 && payload[0] == 'G' &&
			(payload[1] >= 'a' && payload[1] <= 'z' || payload[1] >= 'A' && payload[1] <= 'Z') &&
			payload[2] == '='
	}
	return false
}

// stillArriving reports whether the CSI or SS3 sequence at the start of the
// buffer may still be completed by more input. It must be the only one in the buffer:
// whatever follows it, another sequence or a byte that ended it, means it is not
// waiting for anything.
func stillArriving(buffer []byte) bool {
	return bytes.IndexByte(buffer[1:], Esc.Byte()) < 0 && incompleteEscape(buffer)
}

// incompleteEscape reports whether the buffer ends in a CSI or SS3 sequence that
// has not been terminated yet. The read loop keeps waiting while it does, so a
// fragment reaches the parser only once that wait has run out. A string sequence
// is never waited for, because its introducer is also ALT-], ALT-P or ALT-_.
func incompleteEscape(buffer []byte) bool {
	// Only the tail can hold a sequence still arriving. This runs once per byte
	// read, so scanning all of a large paste would make the read quadratic.
	tail := buffer
	if len(tail) > escapeLookback {
		tail = tail[len(tail)-escapeLookback:]
	}
	start := bytes.LastIndexByte(tail, Esc.Byte())
	if start < 0 || len(tail)-start < 2 {
		return false
	}
	// SS3 is judged like CSI: declaring it finished after one byte made the
	// parser give up on a split \eO1;5A. A malformed sequence is not waited for,
	// as nothing can complete it.
	return csiIntroducer(tail[start+1]) && csiEnd(tail[start:]) == 0
}

func (r *LightRenderer) getBytes(cancellable bool) ([]byte, getCharResult, error) {
	return r.getBytesInternal(cancellable, r.buffer, false)
}

func (r *LightRenderer) getBytesInternal(cancellable bool, buffer []byte, nonblock bool) ([]byte, getCharResult, error) {
	c, result := r.getch(cancellable, nonblock)
	if result == getCharCancelled {
		return buffer, getCharCancelled, nil
	}
	if !nonblock && !result.ok() {
		r.Close()
		return nil, getCharError, errors.New("failed to read " + DefaultTtyDevice)
	}

	retries := 0
	if c == Esc.Int() || nonblock {
		retries = r.escDelay / escPollInterval
	}
	// A non-blocking read that found nothing has no byte to record. Recording
	// one would put a NUL in the middle of a reply still being assembled.
	if result.ok() {
		buffer = append(buffer, byte(c))
	}

	pc := c
	for {
		c, result = r.getch(false, true)
		if !result.ok() {
			if retries > 0 {
				retries--
				time.Sleep(escPollInterval * time.Millisecond)
				continue
			}
			break
		} else if c == Esc.Int() && pc != c {
			retries = r.escDelay / escPollInterval
		} else {
			retries = 0
		}
		buffer = append(buffer, byte(c))
		// Keep waiting while a sequence is still arriving. Dropping the budget
		// after every byte left fzf parsing whatever the read happened to end on.
		// Past the introducer this is not the ESC key, so the wait costs no
		// Escape latency and ESCDELAY=0 must not reduce it to nothing.
		if retries == 0 && incompleteEscape(buffer) {
			retries = max(r.escDelay, defaultEscDelay) / escPollInterval
		}
		pc = c

		// This should never happen under normal conditions,
		// so terminate fzf immediately.
		if len(buffer) > maxInputBuffer {
			r.Close()
			return nil, getCharError, fmt.Errorf("input buffer overflow (%d): %v", len(buffer), buffer)
		}
	}

	return buffer, getCharSuccess, nil
}

func (r *LightRenderer) GetChar(cancellable bool) Event {
	var err error
	var result getCharResult
	if len(r.buffer) == 0 {
		r.buffer, result, err = r.getBytes(cancellable)
		if err != nil {
			return Event{Fatal, 0, nil}
		}
		if result == getCharCancelled {
			return Event{Invalid, 0, nil}
		}
	}
	if len(r.buffer) == 0 {
		return Event{Fatal, 0, nil}
	}

	sz := 1
	defer func() {
		r.buffer = r.buffer[sz:]
	}()

	switch r.buffer[0] {
	case CtrlC.Byte():
		return Event{CtrlC, 0, nil}
	case CtrlG.Byte():
		return Event{CtrlG, 0, nil}
	case CtrlQ.Byte():
		return Event{CtrlQ, 0, nil}
	case 127:
		return Event{Backspace, 0, nil}
	case 8:
		return Event{CtrlBackspace, 0, nil}
	case 0:
		return Event{CtrlSpace, 0, nil}
	case 28:
		return Event{CtrlBackSlash, 0, nil}
	case 29:
		return Event{CtrlRightBracket, 0, nil}
	case 30:
		return Event{CtrlCaret, 0, nil}
	case 31:
		return Event{CtrlSlash, 0, nil}
	case Esc.Byte():
		ev := r.escSequence(&sz)
		// Second chance, but only for an unfinished sequence. Re-reading
		// otherwise blocks until the next keystroke, holding back whatever
		// follows in the buffer.
		if ev.Type == Invalid && stillArriving(r.buffer) {
			waited := len(r.buffer)
			var buffer []byte
			buffer, result, err = r.getBytes(true)
			if err != nil {
				return Event{Fatal, 0, nil}
			}
			r.buffer = buffer
			if result == getCharCancelled {
				return Event{Invalid, 0, nil}
			}

			ev = r.escSequence(&sz)
			// This read has no time limit, so what it returned may be the next
			// keystroke rather than the rest of the sequence. Never drop it.
			if ev.Type == Invalid && sz > waited {
				sz = waited
			}
		}
		return ev
	}

	// CTRL-A ~ CTRL-Z
	if r.buffer[0] <= CtrlZ.Byte() {
		return Event{EventType(r.buffer[0]), 0, nil}
	}
	char, rsz := utf8.DecodeRune(r.buffer)
	if char == utf8.RuneError {
		return Event{Esc, 0, nil}
	}
	sz = rsz
	return Event{Rune, char, nil}
}

func (r *LightRenderer) CancelGetChar() {
	r.mutex.Lock()
	if r.cancel != nil {
		r.cancel()
		r.cancel = nil
	}
	r.mutex.Unlock()
}

func (r *LightRenderer) setCancel(f func()) {
	r.mutex.Lock()
	r.cancel = f
	r.mutex.Unlock()
}

// escSequence parses an escape sequence, then checks a CSI or SS3 result
// against its frame. parseEscSequence can stop after a few bytes, and consuming
// only those would leave the rest to be typed into the query. Complete
// sequences it does not recognize are dropped there, unless they could be an
// ALT key followed by typed text.
func (r *LightRenderer) escSequence(sz *int) Event {
	ev := r.parseEscSequence(sz)
	if len(r.buffer) < 3 || !csiIntroducer(r.buffer[1]) {
		return ev
	}
	// A frame missing its final byte may still be arriving
	end := csiEnd(r.buffer)
	if end <= 0 {
		return ev
	}
	// The parser can also set the size before checking the bytes and then give
	// up, counting typed input past the frame, as in \e[3;1u followed by ~
	if ev.Type == Invalid && *sz > end {
		*sz = end
	}
	// Four bytes or fewer could be ALT-[ or ALT-O and typed text, and rxvt sends
	// keys of that size fzf does not know, such as \e[3^ for CTRL-DELETE
	if end <= 4 {
		return ev
	}
	// A key matched on a prefix, such as Home for \e[70;5u, or a sequence given
	// up on partway
	if end > *sz {
		*sz = end
		return Event{Invalid, 0, nil}
	}
	return ev
}

func (r *LightRenderer) parseEscSequence(sz *int) Event {
	if len(r.buffer) < 2 {
		return Event{Esc, 0, nil}
	}

	loc := offsetRegexpBegin.FindIndex(r.buffer)
	if loc != nil && loc[0] == 0 {
		*sz = loc[1]
		return Event{Invalid, 0, nil}
	}

	loc = pasteModeRegexpBegin.FindIndex(r.buffer)
	if loc != nil && loc[0] == 0 {
		*sz = loc[1]
		return Event{Invalid, 0, nil}
	}

	*sz = 2
	if r.buffer[1] == 8 {
		return Event{CtrlAltBackspace, 0, nil}
	}
	if r.buffer[1] >= 1 && r.buffer[1] <= 'z'-'a'+1 {
		return CtrlAltKey(rune(r.buffer[1] + 'a' - 1))
	}
	alt := false
	if len(r.buffer) > 2 && r.buffer[1] == Esc.Byte() {
		r.buffer = r.buffer[1:]
		alt = true
	}
	switch r.buffer[1] {
	case Esc.Byte():
		return Event{Esc, 0, nil}
	case 127:
		return Event{AltBackspace, 0, nil}
	case '[', 'O':
		if len(r.buffer) < 3 {
			return Event{Invalid, 0, nil}
		}
		*sz = 3
		switch r.buffer[2] {
		case 'D':
			if alt {
				return Event{AltLeft, 0, nil}
			}
			return Event{Left, 0, nil}
		case 'C':
			if alt {
				// Ugh..
				return Event{AltRight, 0, nil}
			}
			return Event{Right, 0, nil}
		case 'B':
			if alt {
				return Event{AltDown, 0, nil}
			}
			return Event{Down, 0, nil}
		case 'A':
			if alt {
				return Event{AltUp, 0, nil}
			}
			return Event{Up, 0, nil}
		case 'Z':
			return Event{ShiftTab, 0, nil}
		case 'H':
			return Event{Home, 0, nil}
		case 'F':
			return Event{End, 0, nil}
		case '<':
			return r.mouseSequence(sz)
		case 'P':
			return Event{F1, 0, nil}
		case 'Q':
			return Event{F2, 0, nil}
		case 'R':
			return Event{F3, 0, nil}
		case 'S':
			return Event{F4, 0, nil}
		case '1', '2', '3', '4', '5', '6', '7', '8':
			if len(r.buffer) < 4 {
				return Event{Invalid, 0, nil}
			}
			// A byte that cannot continue the sequence, such as Enter after
			// ALT-[ and a digit, is a key of its own
			if csiEnd(r.buffer) < 0 {
				break
			}
			*sz = 4
			switch r.buffer[2] {
			case '2':
				if r.buffer[3] == '~' {
					return Event{Insert, 0, nil}
				}
				if len(r.buffer) > 4 && r.buffer[4] == '~' {
					*sz = 5
					switch r.buffer[3] {
					case '0':
						return Event{F9, 0, nil}
					case '1':
						return Event{F10, 0, nil}
					case '3':
						return Event{F11, 0, nil}
					case '4':
						return Event{F12, 0, nil}
					}
				}
				// Bracketed paste mode: \e[200~ ... \e[201~
				if len(r.buffer) > 5 && r.buffer[3] == '0' && (r.buffer[4] == '0' || r.buffer[4] == '1') && r.buffer[5] == '~' {
					*sz = 6
					if r.buffer[4] == '0' {
						return Event{BracketedPasteBegin, 0, nil}
					}
					return Event{BracketedPasteEnd, 0, nil}
				}
				return Event{Invalid, 0, nil} // INS
			case '3':
				if r.buffer[3] == '~' {
					return Event{Delete, 0, nil}
				}
				if len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {
					*sz = 7
					switch r.buffer[5] {
					case '0':
						return Event{AltShiftDelete, 0, nil}
					case '1':
						return Event{AltDelete, 0, nil}
					case '2':
						return Event{AltShiftDelete, 0, nil}
					case '3':
						return Event{CtrlAltDelete, 0, nil}
					case '4':
						return Event{CtrlAltShiftDelete, 0, nil}
					case '5':
						return Event{CtrlAltDelete, 0, nil}
					case '6':
						return Event{CtrlAltShiftDelete, 0, nil}
					}
				}
				if len(r.buffer) > 5 && r.buffer[5] == '~' {
					*sz = 6
					switch r.buffer[4] {
					case '2':
						return Event{ShiftDelete, 0, nil}
					case '3':
						return Event{AltDelete, 0, nil}
					case '4':
						return Event{AltShiftDelete, 0, nil}
					case '5':
						return Event{CtrlDelete, 0, nil}
					case '6':
						return Event{CtrlShiftDelete, 0, nil}
					case '7':
						return Event{CtrlAltDelete, 0, nil}
					case '8':
						return Event{CtrlAltShiftDelete, 0, nil}
					case '9':
						return Event{AltDelete, 0, nil}
					}
				}
				return Event{Invalid, 0, nil}
			case '4':
				if rxvtKeyEnd(r.buffer[3]) {
					return Event{End, 0, nil}
				}
			case '5':
				if r.buffer[3] == '~' {
					return Event{PageUp, 0, nil}
				}
				if len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {
					*sz = 7
					switch r.buffer[5] {
					case '0':
						return Event{AltShiftPageUp, 0, nil}
					case '1':
						return Event{AltPageUp, 0, nil}
					case '2':
						return Event{AltShiftPageUp, 0, nil}
					case '3':
						return Event{CtrlAltPageUp, 0, nil}
					case '4':
						return Event{CtrlAltShiftPageUp, 0, nil}
					case '5':
						return Event{CtrlAltPageUp, 0, nil}
					case '6':
						return Event{CtrlAltShiftPageUp, 0, nil}
					}
				}
				if len(r.buffer) > 5 && r.buffer[5] == '~' {
					*sz = 6
					switch r.buffer[4] {
					case '2':
						return Event{ShiftPageUp, 0, nil}
					case '3':
						return Event{AltPageUp, 0, nil}
					case '4':
						return Event{AltShiftPageUp, 0, nil}
					case '5':
						return Event{CtrlPageUp, 0, nil}
					case '6':
						return Event{CtrlShiftPageUp, 0, nil}
					case '7':
						return Event{CtrlAltPageUp, 0, nil}
					case '8':
						return Event{CtrlAltShiftPageUp, 0, nil}
					case '9':
						return Event{AltPageUp, 0, nil}
					}
				}
				return Event{Invalid, 0, nil}
			case '6':
				if r.buffer[3] == '~' {
					return Event{PageDown, 0, nil}
				}
				if len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {
					*sz = 7
					switch r.buffer[5] {
					case '0':
						return Event{AltShiftPageDown, 0, nil}
					case '1':
						return Event{AltPageDown, 0, nil}
					case '2':
						return Event{AltShiftPageDown, 0, nil}
					case '3':
						return Event{CtrlAltPageDown, 0, nil}
					case '4':
						return Event{CtrlAltShiftPageDown, 0, nil}
					case '5':
						return Event{CtrlAltPageDown, 0, nil}
					case '6':
						return Event{CtrlAltShiftPageDown, 0, nil}
					}
				}
				if len(r.buffer) > 5 && r.buffer[5] == '~' {
					*sz = 6
					switch r.buffer[4] {
					case '2':
						return Event{ShiftPageDown, 0, nil}
					case '3':
						return Event{AltPageDown, 0, nil}
					case '4':
						return Event{AltShiftPageDown, 0, nil}
					case '5':
						return Event{CtrlPageDown, 0, nil}
					case '6':
						return Event{CtrlShiftPageDown, 0, nil}
					case '7':
						return Event{CtrlAltPageDown, 0, nil}
					case '8':
						return Event{CtrlAltShiftPageDown, 0, nil}
					case '9':
						return Event{AltPageDown, 0, nil}
					}
				}
				return Event{Invalid, 0, nil}
			case '7':
				if rxvtKeyEnd(r.buffer[3]) {
					return Event{Home, 0, nil}
				}
			case '8':
				if rxvtKeyEnd(r.buffer[3]) {
					return Event{End, 0, nil}
				}
			case '1':
				switch r.buffer[3] {
				case '~':
					return Event{Home, 0, nil}
				case '1', '2', '3', '4', '5', '7', '8', '9':
					if len(r.buffer) > 4 && r.buffer[4] == '~' {
						*sz = 5
						switch r.buffer[3] {
						case '1':
							return Event{F1, 0, nil}
						case '2':
							return Event{F2, 0, nil}
						case '3':
							return Event{F3, 0, nil}
						case '4':
							return Event{F4, 0, nil}
						case '5':
							return Event{F5, 0, nil}
						case '7':
							return Event{F6, 0, nil}
						case '8':
							return Event{F7, 0, nil}
						case '9':
							return Event{F8, 0, nil}
						}
					}
					return Event{Invalid, 0, nil}
				case ';':
					if len(r.buffer) < 6 {
						return Event{Invalid, 0, nil}
					}
					*sz = 6
					switch r.buffer[4] {
					case '1', '2', '3', '4', '5', '6', '7', '8', '9':
						//                   Kitty      iTerm2     WezTerm
						// ARROW             "\e[1;1D"
						// SHIFT-ARROW       "\e[1;2D"
						// ALT-SHIFT-ARROW   "\e[1;4D"  "\e[1;10D" "\e[1;4D"
						// CTRL-SHIFT-ARROW  "\e[1;6D"             N/A
						// CMD-SHIFT-ARROW   "\e[1;10D" N/A        N/A ("\e[1;2D")
						ctrl := bytes.IndexByte([]byte{'5', '6', '7', '8'}, r.buffer[4]) >= 0
						alt := bytes.IndexByte([]byte{'3', '4', '7', '8'}, r.buffer[4]) >= 0
						shift := bytes.IndexByte([]byte{'2', '4', '6', '8'}, r.buffer[4]) >= 0
						char := r.buffer[5]
						if r.buffer[4] == '9' {
							ctrl = false
							alt = true
							shift = false
							if len(r.buffer) < 6 {
								return Event{Invalid, 0, nil}
							}
							*sz = 6
							char = r.buffer[5]
						} else if r.buffer[4] == '1' && bytes.IndexByte([]byte{'0', '1', '2', '3', '4', '5', '6'}, r.buffer[5]) >= 0 {
							ctrl = bytes.IndexByte([]byte{'3', '4', '5', '6'}, r.buffer[5]) >= 0
							alt = true
							shift = bytes.IndexByte([]byte{'0', '2', '4', '6'}, r.buffer[5]) >= 0
							if len(r.buffer) < 7 {
								return Event{Invalid, 0, nil}
							}
							*sz = 7
							char = r.buffer[6]
						}
						ctrlShift := ctrl && shift
						ctrlAlt := ctrl && alt
						altShift := alt && shift
						ctrlAltShift := ctrl && alt && shift
						switch char {
						case 'A':
							if ctrlAltShift {
								return Event{CtrlAltShiftUp, 0, nil}
							}
							if ctrlAlt {
								return Event{CtrlAltUp, 0, nil}
							}
							if ctrlShift {
								return Event{CtrlShiftUp, 0, nil}
							}
							if altShift {
								return Event{AltShiftUp, 0, nil}
							}
							if ctrl {
								return Event{CtrlUp, 0, nil}
							}
							if alt {
								return Event{AltUp, 0, nil}
							}
							if shift {
								return Event{ShiftUp, 0, nil}
							}
							return Event{Up, 0, nil}
						case 'B':
							if ctrlAltShift {
								return Event{CtrlAltShiftDown, 0, nil}
							}
							if ctrlAlt {
								return Event{CtrlAltDown, 0, nil}
							}
							if ctrlShift {
								return Event{CtrlShiftDown, 0, nil}
							}
							if altShift {
								return Event{AltShiftDown, 0, nil}
							}
							if ctrl {
								return Event{CtrlDown, 0, nil}
							}
							if alt {
								return Event{AltDown, 0, nil}
							}
							if shift {
								return Event{ShiftDown, 0, nil}
							}
							return Event{Down, 0, nil}
						case 'C':
							if ctrlAltShift {
								return Event{CtrlAltShiftRight, 0, nil}
							}
							if ctrlAlt {
								return Event{CtrlAltRight, 0, nil}
							}
							if ctrlShift {
								return Event{CtrlShiftRight, 0, nil}
							}
							if altShift {
								return Event{AltShiftRight, 0, nil}
							}
							if ctrl {
								return Event{CtrlRight, 0, nil}
							}
							if shift {
								return Event{ShiftRight, 0, nil}
							}
							if alt {
								return Event{AltRight, 0, nil}
							}
							return Event{Right, 0, nil}
						case 'D':
							if ctrlAltShift {
								return Event{CtrlAltShiftLeft, 0, nil}
							}
							if ctrlAlt {
								return Event{CtrlAltLeft, 0, nil}
							}
							if ctrlShift {
								return Event{CtrlShiftLeft, 0, nil}
							}
							if altShift {
								return Event{AltShiftLeft, 0, nil}
							}
							if ctrl {
								return Event{CtrlLeft, 0, nil}
							}
							if alt {
								return Event{AltLeft, 0, nil}
							}
							if shift {
								return Event{ShiftLeft, 0, nil}
							}
							return Event{Left, 0, nil}
						case 'H':
							if ctrlAltShift {
								return Event{CtrlAltShiftHome, 0, nil}
							}
							if ctrlAlt {
								return Event{CtrlAltHome, 0, nil}
							}
							if ctrlShift {
								return Event{CtrlShiftHome, 0, nil}
							}
							if altShift {
								return Event{AltShiftHome, 0, nil}
							}
							if ctrl {
								return Event{CtrlHome, 0, nil}
							}
							if alt {
								return Event{AltHome, 0, nil}
							}
							if shift {
								return Event{ShiftHome, 0, nil}
							}
							return Event{Home, 0, nil}
						case 'F':
							if ctrlAltShift {
								return Event{CtrlAltShiftEnd, 0, nil}
							}
							if ctrlAlt {
								return Event{CtrlAltEnd, 0, nil}
							}
							if ctrlShift {
								return Event{CtrlShiftEnd, 0, nil}
							}
							if altShift {
								return Event{AltShiftEnd, 0, nil}
							}
							if ctrl {
								return Event{CtrlEnd, 0, nil}
							}
							if alt {
								return Event{AltEnd, 0, nil}
							}
							if shift {
								return Event{ShiftEnd, 0, nil}
							}
							return Event{End, 0, nil}
						}
					} // r.buffer[4]
				} // r.buffer[3]
			} // r.buffer[2]
		} // r.buffer[2]
	} // r.buffer[1]
	// Nothing matched. A framed sequence is dropped whole: reading its
	// introducer as an ALT-key below would type the rest into the query.
	// Unterminated ones are left alone, as that is how ALT-[, ALT-O, ALT-],
	// ALT-P and ALT-_ arrive.
	if csiIntroducer(r.buffer[1]) {
		// ALT-[ or ALT-O and one or two typed characters can look like a short
		// sequence, so ask for at least two bytes before the final byte
		if end := csiEnd(r.buffer); end > 4 {
			*sz = end
			return Event{Invalid, 0, nil}
		}
	} else if stringIntroducer(r.buffer[1]) {
		if end := stringEnd(r.buffer); end > 0 && stringReply(r.buffer) {
			*sz = end
			return Event{Invalid, 0, nil}
		}
	}

	rest := bytes.NewBuffer(r.buffer[1:])
	c, size, err := rest.ReadRune()
	if err == nil {
		*sz = 1 + size
		return AltKey(c)
	}
	return Event{Invalid, 0, nil}
}

// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking
func (r *LightRenderer) mouseSequence(sz *int) Event {
	// "\e[<0;0;0M"
	if len(r.buffer) < 9 || !r.mouse {
		return Event{Invalid, 0, nil}
	}

	// Not past the frame, where M or m can be a key typed later
	frame := csiEnd(r.buffer)
	if frame <= 0 || r.buffer[frame-1] != 'm' && r.buffer[frame-1] != 'M' {
		return Event{Invalid, 0, nil}
	}
	rest := r.buffer[*sz:]
	end := frame - 1 - *sz

	elems := strings.SplitN(string(rest[:end]), ";", 3)
	if len(elems) != 3 {
		return Event{Invalid, 0, nil}
	}

	t := atoi(elems[0], -1)
	x := atoi(elems[1], -1) - 1
	y := atoi(elems[2], -1) - 1 - r.yoffset
	if t < 0 || x < 0 {
		return Event{Invalid, 0, nil}
	}
	*sz += end + 1

	down := rest[end] == 'M'

	scroll := 0
	wheel := t >= 64
	if wheel {
		t -= 64
		// SGR wheel button codes: 64=up, 65=down, 66=left, 67=right
		switch t & 0b11 {
		case 0:
			scroll = 1
		case 1:
			scroll = -1
		}
	}

	// middle := t & 0b1
	left := t&0b11 == 0
	ctrl := t&0b10000 > 0
	alt := t&0b01000 > 0
	shift := t&0b00100 > 0
	drag := t&0b100000 > 0 // 32

	if wheel {
		return Event{Mouse, 0, &MouseEvent{y, x, scroll, false, false, false, ctrl, alt, shift}}
	}

	double := false
	if down && !drag {
		now := time.Now()
		if !left { // Right double click is not allowed
			r.clicks = [][2]int{}
		} else if now.Sub(r.prevDownTime) < doubleClickDuration {
			r.clicks = append(r.clicks, [2]int{x, y})
		} else {
			r.clicks = [][2]int{{x, y}}
		}
		r.prevDownTime = now
	} else {
		n := len(r.clicks)
		if len(r.clicks) > 1 && r.clicks[n-2][0] == r.clicks[n-1][0] && r.clicks[n-2][1] == r.clicks[n-1][1] &&
			time.Since(r.prevDownTime) < doubleClickDuration {
			double = true
			if double {
				r.clicks = [][2]int{}
			}
		}
	}
	return Event{Mouse, 0, &MouseEvent{y, x, 0, left, down, double, ctrl, alt, shift}}
}

func (r *LightRenderer) smcup() {
	r.flush()
	r.flushRaw("\x1b[?1049h")
}

func (r *LightRenderer) rmcup() {
	r.flush()
	r.flushRaw("\x1b[?1049l")
}

func (r *LightRenderer) Pause(clear bool) {
	r.disableModes()
	r.restoreTerminal()
	if clear {
		if r.fullscreen {
			r.rmcup()
		} else {
			r.smcup()
			r.csi("H")
		}
		r.flush()
	}
}

func (r *LightRenderer) enableModes() {
	if r.mouse {
		r.csi("?1000h")
		r.csi("?1002h")
		r.csi("?1006h")
	}
	r.csi("?2004h") // Enable bracketed paste mode
}

func (r *LightRenderer) disableMouse() {
	if r.mouse {
		r.csi("?1000l")
		r.csi("?1002l")
		r.csi("?1006l")
	}
}

func (r *LightRenderer) disableModes() {
	r.disableMouse()
	// Put bracketed paste back the way we found it. A shell that runs fzf from
	// a line editor widget re-enables the mode only when the editor starts, so
	// forcing it off here would leave it off for the rest of the session.
	// Terminals that did not answer the query fall back to disabling, which is
	// what fzf has always done.
	if r.pasteWasSet != nil && *r.pasteWasSet {
		r.csi("?2004h")
	} else {
		r.csi("?2004l")
	}
}

func (r *LightRenderer) Resume(clear bool, sigcont bool) {
	r.setupTerminal()
	// The programs that ran in the meantime may have left the terminal in an
	// arbitrary SGR state
	r.invalidateSGR()
	if clear {
		if r.fullscreen {
			r.smcup()
		} else {
			r.rmcup()
		}
		r.enableModes()
		r.flush()
	} else if sigcont && !r.fullscreen && r.mouse {
		// NOTE: SIGCONT (Coming back from CTRL-Z):
		// It's highly likely that the offset we obtained at the beginning is
		// no longer correct, so we simply disable mouse input.
		r.disableMouse()
		r.mouse = false
	}
}

func (r *LightRenderer) Clear() {
	if r.fullscreen {
		r.csi("H")
	}
	r.origin()
	r.csi("J")
	r.flush()
}

func (r *LightRenderer) NeedScrollbarRedraw() bool {
	return false
}

func (r *LightRenderer) ShouldEmitResizeEvent() bool {
	return false
}

func (r *LightRenderer) RefreshWindows(windows []Window) {
	r.flush()
}

func (r *LightRenderer) Refresh() {
	r.updateTerminalSize()
}

func (r *LightRenderer) Close() {
	if r.clearOnExit {
		if r.fullscreen {
			r.rmcup()
		} else {
			r.origin()
			// Erase our own area first, then step back onto the line the
			// prompt was on, so nothing on that line is touched
			r.csi("J")
			if r.upOneLine {
				r.csi("A")
				r.csi(fmt.Sprintf("%dG", r.xoffset+1))
			}
		}
	} else if !r.fullscreen {
		r.stderr("\x1b8") // DECRC: restore cursor position
	}
	if !r.showCursor {
		r.csi("?25h")
	}
	r.disableModes()
	r.flush()
	r.restoreTerminal()
	r.closePlatform()
}

func (r *LightRenderer) Top() int {
	return r.yoffset
}

func (r *LightRenderer) MaxX() int {
	return r.width
}

func (r *LightRenderer) MaxY() int {
	if r.height == 0 {
		r.updateTerminalSize()
	}
	return r.height
}

func (r *LightRenderer) NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window {
	width = max(0, width)
	height = max(0, height)
	w := &LightWindow{
		renderer:   r,
		colored:    r.theme.Colored,
		windowType: windowType,
		border:     borderStyle,
		top:        top,
		left:       left,
		width:      width,
		height:     height,
		tabstop:    r.tabstop,
		fg:         colDefault,
		bg:         colDefault}
	switch windowType {
	case WindowBase:
		w.fg = r.theme.Fg.Color
		w.bg = r.theme.Bg.Color
	case WindowList:
		w.fg = r.theme.ListFg.Color
		w.bg = r.theme.ListBg.Color
	case WindowInput:
		w.fg = r.theme.Input.Color
		w.bg = r.theme.InputBg.Color
	case WindowHeader:
		w.fg = r.theme.Header.Color
		w.bg = r.theme.HeaderBg.Color
	case WindowFooter:
		w.fg = r.theme.Footer.Color
		w.bg = r.theme.FooterBg.Color
	case WindowPreview:
		w.fg = r.theme.PreviewFg.Color
		w.bg = r.theme.PreviewBg.Color
	}
	if erase && !w.bg.IsDefault() && w.border.shape != BorderNone && w.height > 0 {
		// fzf --color bg:blue --border --padding 1,2
		w.Erase()
	}
	w.drawBorder(false)
	return w
}

func (w *LightWindow) DrawBorder() {
	w.drawBorder(false)
}

func (w *LightWindow) DrawHBorder() {
	w.drawBorder(true)
}

// drawHLine fills row `row` with `line` between optional left/right caps.
// A zero rune means "no cap"; caps are placed at the very edges of `w`.
func (w *LightWindow) drawHLine(row int, line, leftCap, rightCap rune, color ColorPair) {
	w.Move(row, 0)
	hw := runeWidth(line)
	width := w.width
	if leftCap != 0 {
		w.CPrint(color, string(leftCap))
		width -= runeWidth(leftCap)
	}
	if rightCap != 0 {
		width -= runeWidth(rightCap)
	}
	if width < 0 {
		width = 0
	}
	inner := width / hw
	rem := width - inner*hw
	w.CPrint(color, repeat(line, inner)+repeat(' ', rem))
	if rightCap != 0 {
		w.CPrint(color, string(rightCap))
	}
}

func (w *LightWindow) DrawHSeparator(row int, windowType WindowType, useBottom bool) {
	if w.height == 0 {
		return
	}
	shape := w.border.shape
	if shape == BorderNone {
		return
	}
	color := BorderColor(windowType)
	line := w.border.top
	if useBottom {
		line = w.border.bottom
	}
	var leftCap, rightCap rune
	if shape.HasLeft() {
		leftCap = w.border.leftMid
	}
	if shape.HasRight() {
		rightCap = w.border.rightMid
	}
	w.drawHLine(row, line, leftCap, rightCap, color)
}

func (w *LightWindow) PaintSectionFrame(topContent, bottomContent int, windowType WindowType, edge SectionEdge) {
	if w.height == 0 || w.border.shape == BorderNone {
		return
	}
	color := BorderColor(windowType)
	shape := w.border.shape
	hasLeft := shape.HasLeft()
	hasRight := shape.HasRight()
	rightW := runeWidth(w.border.right)
	// Content rows: overpaint left/right verticals + their 1-char margin.
	for row := topContent; row <= bottomContent; row++ {
		if hasLeft {
			w.Move(row, 0)
			w.CPrint(color, string(w.border.left)+" ")
		}
		if hasRight {
			w.Move(row, w.width-rightW-1)
			w.CPrint(color, " "+string(w.border.right))
		}
	}
	if edge == SectionEdgeTop && shape.HasTop() {
		var leftCap, rightCap rune
		if hasLeft {
			leftCap = w.border.topLeft
		}
		if hasRight {
			rightCap = w.border.topRight
		}
		w.drawHLine(0, w.border.top, leftCap, rightCap, color)
	}
	if edge == SectionEdgeBottom && shape.HasBottom() {
		var leftCap, rightCap rune
		if hasLeft {
			leftCap = w.border.bottomLeft
		}
		if hasRight {
			rightCap = w.border.bottomRight
		}
		w.drawHLine(w.height-1, w.border.bottom, leftCap, rightCap, color)
	}
}

func (w *LightWindow) drawBorder(onlyHorizontal bool) {
	if w.height == 0 {
		return
	}
	shape := w.border.shape
	if shape == BorderNone {
		return
	}
	color := BorderColor(w.windowType)
	hasLeft := shape.HasLeft()
	hasRight := shape.HasRight()

	if shape.HasTop() {
		var leftCap, rightCap rune
		if hasLeft {
			leftCap = w.border.topLeft
		}
		if hasRight {
			rightCap = w.border.topRight
		}
		w.drawHLine(0, w.border.top, leftCap, rightCap, color)
	}
	if !onlyHorizontal && (hasLeft || hasRight) {
		vw := runeWidth(w.border.left)
		for y := 0; y < w.height; y++ {
			// Corner rows are already painted by drawHLine above / below.
			if (y == 0 && shape.HasTop()) || (y == w.height-1 && shape.HasBottom()) {
				continue
			}
			if hasLeft {
				w.Move(y, 0)
				w.CPrint(color, string(w.border.left)+" ")
			}
			if hasRight {
				w.Move(y, w.width-vw-1)
				w.CPrint(color, " "+string(w.border.right))
			}
		}
	}
	if shape.HasBottom() {
		var leftCap, rightCap rune
		if hasLeft {
			leftCap = w.border.bottomLeft
		}
		if hasRight {
			rightCap = w.border.bottomRight
		}
		w.drawHLine(w.height-1, w.border.bottom, leftCap, rightCap, color)
	}
}

func (w *LightWindow) stderrInternal(str string, allowNLCR bool, resetCode string) {
	w.renderer.stderrInternal(str, allowNLCR, resetCode)
}

func (w *LightWindow) Top() int {
	return w.top
}

func (w *LightWindow) Left() int {
	return w.left
}

func (w *LightWindow) Width() int {
	return w.width
}

func (w *LightWindow) Height() int {
	return w.height
}

func (w *LightWindow) Refresh() {
}

func (w *LightWindow) X() int {
	return w.posx
}

func (w *LightWindow) Y() int {
	return w.posy
}

func (w *LightWindow) EncloseX(x int) bool {
	return x >= w.left && x < (w.left+w.width)
}

func (w *LightWindow) EncloseY(y int) bool {
	return y >= w.top && y < (w.top+w.height)
}

func (w *LightWindow) Enclose(y int, x int) bool {
	return w.EncloseX(x) && w.EncloseY(y)
}

func (w *LightWindow) Move(y int, x int) {
	w.posx = x
	w.posy = y

	w.renderer.move(w.Top()+y, w.Left()+x)
}

func (w *LightWindow) MoveAndClear(y int, x int) {
	w.Move(y, x)
	// We should not delete preview window on the right
	// csi("K")
	w.Print(repeat(' ', w.width-x))
	w.Move(y, x)
}

func attrCodes(attr Attr) []string {
	codes := []string{}
	if (attr & AttrClear) > 0 {
		return codes
	}
	if (attr&Bold) > 0 || (attr&BoldForce) > 0 {
		codes = append(codes, "1")
	}
	if (attr & Dim) > 0 {
		codes = append(codes, "2")
	}
	if (attr & Italic) > 0 {
		codes = append(codes, "3")
	}
	if (attr & Underline) > 0 {
		switch attr.UnderlineStyle() {
		case UlStyleDouble:
			codes = append(codes, "4:2")
		case UlStyleCurly:
			codes = append(codes, "4:3")
		case UlStyleDotted:
			codes = append(codes, "4:4")
		case UlStyleDashed:
			codes = append(codes, "4:5")
		default:
			codes = append(codes, "4")
		}
	}
	if (attr & Blink) > 0 {
		codes = append(codes, "5")
	}
	if (attr & Reverse) > 0 {
		codes = append(codes, "7")
	}
	if (attr & StrikeThrough) > 0 {
		codes = append(codes, "9")
	}
	return codes
}

func colorCodes(fg Color, bg Color) []string {
	codes := []string{}
	appendCode := func(c Color, offset int) {
		if c == colDefault {
			return
		}
		if c.is24() {
			r := (c >> 16) & 0xff
			g := (c >> 8) & 0xff
			b := (c) & 0xff
			codes = append(codes, fmt.Sprintf("%d;2;%d;%d;%d", 38+offset, r, g, b))
		} else if c >= colBlack && c <= colWhite {
			codes = append(codes, fmt.Sprintf("%d", int(c)+30+offset))
		} else if c > colWhite && c < 16 {
			codes = append(codes, fmt.Sprintf("%d", int(c)+90+offset-8))
		} else if c >= 16 && c < 256 {
			codes = append(codes, fmt.Sprintf("%d;5;%d", 38+offset, c))
		}
	}
	appendCode(fg, 0)
	appendCode(bg, 10)
	return codes
}

func ulColorCode(c Color) string {
	if c == colDefault {
		return ""
	}
	if c.is24() {
		r := (c >> 16) & 0xff
		g := (c >> 8) & 0xff
		b := (c) & 0xff
		return fmt.Sprintf("58;2;%d;%d;%d", r, g, b)
	}
	if c >= 0 && c < 256 {
		return fmt.Sprintf("58;5;%d", c)
	}
	return ""
}

// csiColor builds the SGR sequence for the given colors and attributes
// without emitting it. The sequence starts with a reset parameter, so it
// fully determines the SGR state on its own.
func (w *LightWindow) csiColor(fg Color, bg Color, ul Color, attr Attr) (bool, string) {
	codes := append(attrCodes(attr), colorCodes(fg, bg)...)
	if ulCode := ulColorCode(ul); ulCode != "" {
		codes = append(codes, ulCode)
	}
	if len(codes) == 0 {
		return false, "\x1b[0m"
	}
	return true, "\x1b[;" + strings.Join(codes, ";") + "m"
}

func (w *LightWindow) Print(text string) {
	w.cprint2(colDefault, w.bg, AttrRegular, text)
}

func cleanse(str string) string {
	return strings.ReplaceAll(str, "\x1b", "")
}

func (w *LightWindow) CPrint(pair ColorPair, text string) {
	_, code := w.csiColor(pair.Fg(), pair.Bg(), pair.Ul(), pair.Attr())
	w.renderer.setSGR(code)
	w.stderrInternal(cleanse(text), false, code)
}

func (w *LightWindow) cprint2(fg Color, bg Color, attr Attr, text string) {
	_, code := w.csiColor(fg, bg, colDefault, attr)
	w.renderer.setSGR(code)
	w.stderrInternal(cleanse(text), false, code)
}

func (w *LightWindow) fill(str string, resetCode string) FillReturn {
	allLines := strings.Split(str, "\n")
	for i, line := range allLines {
		lines := WrapLine(line, w.posx, w.width, w.tabstop, w.wrapSignWidth)
		for j, wl := range lines {
			if w.posx < w.width {
				w.stderrInternal(wl.Text, false, resetCode)
				w.posx += wl.DisplayWidth
			}

			// Wrap line
			if j < len(lines)-1 || i < len(allLines)-1 {
				if w.posy+1 >= w.height {
					return FillSuspend
				}
				w.MoveAndClear(w.posy, w.posx)
				w.Move(w.posy+1, 0)
				w.renderer.setSGR(resetCode)
				if len(lines) > 1 {
					sign := w.wrapSign
					width := w.wrapSignWidth
					if width > w.width {
						runes, truncatedWidth := util.Truncate(w.wrapSign, w.width)
						sign = string(runes)
						width = truncatedWidth
					}
					w.stderrInternal(DIM+sign, false, resetCode)
					w.renderer.invalidateSGR()
					w.renderer.setSGR(resetCode)
					w.Move(w.posy, width)
				}
			}
		}
	}
	if w.posx >= w.Width() {
		if w.posy+1 >= w.height {
			return FillSuspend
		}
		w.Move(w.posy+1, 0)
		w.renderer.setSGR(resetCode)
		return FillNextLine
	}
	return FillContinue
}

func (w *LightWindow) setBg() string {
	// The plain reset code for the default background is still required to
	// clear the dim attribute after ␍ in the preview window
	// e.g. printf "foo\rbar" | fzf --ansi --preview 'printf "foo\rbar"'
	_, code := w.csiColor(colDefault, w.bg, colDefault, AttrRegular)
	w.renderer.setSGR(code)
	return code
}

func (w *LightWindow) LinkBegin(uri string, params string) {
	w.renderer.queued.WriteString("\x1b]8;" + params + ";" + uri + "\x1b\\")
}

func (w *LightWindow) LinkEnd() {
	w.renderer.queued.WriteString("\x1b]8;;\x1b\\")
}

func (w *LightWindow) Fill(text string) FillReturn {
	w.Move(w.posy, w.posx)
	code := w.setBg()
	return w.fill(text, code)
}

func (w *LightWindow) CFill(fg Color, bg Color, ul Color, attr Attr, text string) FillReturn {
	w.Move(w.posy, w.posx)
	if fg == colDefault {
		fg = w.fg
	}
	if bg == colDefault {
		bg = w.bg
	}
	if hasColors, resetCode := w.csiColor(fg, bg, ul, attr); hasColors {
		w.renderer.setSGR(resetCode)
		return w.fill(text, resetCode)
	}
	return w.fill(text, w.setBg())
}

func (w *LightWindow) FinishFill() {
	if w.posy < w.height {
		w.MoveAndClear(w.posy, w.posx)
	}
	for y := w.posy + 1; y < w.height; y++ {
		w.MoveAndClear(y, 0)
	}
}

func (w *LightWindow) Erase() {
	w.DrawBorder()
	w.Move(0, 0)
	w.FinishFill()
	w.Move(0, 0)
}

func (w *LightWindow) EraseMaybe() bool {
	return false
}

func (w *LightWindow) SetWrapSign(sign string, width int) {
	w.wrapSign = sign
	w.wrapSignWidth = width
}

func (r *LightRenderer) HideCursor() {
	r.showCursor = false
	r.csi("?25l")
}

func (r *LightRenderer) ShowCursor() {
	r.showCursor = true
	r.csi("?25h")
}
&& digits && i > 2 {\n\t\t\treturn i + 1\n\t\t}\n\t\tif !csiContinues(b) {\n\t\t\treturn -1\n\t\t}\n\t\tdigits = digits && b >= '0' && b \u003c= '9'\n\t}\n\treturn 0\n}\n\n// stringEnd returns the length of the string sequence (DCS, OSC or APC) at the\n// start of the buffer, or 0 while nothing has ended it. A terminator is\n// included, an ESC that introduces another sequence is not.\nfunc stringEnd(buffer []byte) int {\n\tif len(buffer) \u003c 2 {\n\t\treturn 0\n\t}\n\t// Every one of them ends with ST. BEL ends an OSC as well, because xterm has\n\t// always allowed it, but stopping at a BEL inside a DCS or APC payload would\n\t// frame only its first half and leave the rest to be typed into the query.\n\tbel := buffer[1] == ']'\n\tfor i := 2; i \u003c len(buffer); i++ {\n\t\tswitch buffer[i] {\n\t\tcase '\\a':\n\t\t\tif bel {\n\t\t\t\treturn i + 1\n\t\t\t}\n\t\tcase Esc.Byte():\n\t\t\tif i+1 == len(buffer) {\n\t\t\t\treturn 0 // ST may still be arriving\n\t\t\t}\n\t\t\tif buffer[i+1] == '\\\\' {\n\t\t\t\treturn i + 2\n\t\t\t}\n\t\t\t// Any other ESC ends the string and introduces a sequence of its\n\t\t\t// own, so frame only what precedes it and leave the ESC to be\n\t\t\t// parsed again. Scanning past it would swallow that sequence too.\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}\n\n// rxvtKeyEnd reports whether the byte ends a key such as \\e[7~ for Home.\n// rxvt marks modifiers with the final byte: $ for SHIFT, ^ for CTRL, @ for both.\nfunc rxvtKeyEnd(b byte) bool {\n\treturn b == '~' || b == ' || b == '^' || b == '@'\n}\n\n// csiIntroducer reports whether the byte after ESC starts a sequence that is\n// framed by a final byte. The parser routes CSI and SS3 through the same\n// parameterized subcases, so both are framed by csiEnd.\nfunc csiIntroducer(b byte) bool {\n\treturn b == '[' || b == 'O'\n}\n\n// stringIntroducer reports whether the byte after ESC starts a string sequence.\n// Only the three that terminals reply with: OSC for colors, title and clipboard,\n// DCS for XTVERSION, DECRQSS and XTGETTCAP, APC for Kitty graphics. Nothing\n// sends SOS or PM.\nfunc stringIntroducer(b byte) bool {\n\tswitch b {\n\tcase 'P', ']', '_':\n\t\treturn true\n\t}\n\treturn false\n}\n\n// stringReply reports whether a framed string sequence starts the way a\n// terminal's reply does. Its introducer is also ALT-], ALT-P or ALT-_, and typed\n// text after one, ended by CTRL-G or another key, frames like a reply when it\n// all arrives in one read.\nfunc stringReply(buffer []byte) bool {\n\tpayload := buffer[2:]\n\tswitch buffer[1] {\n\tcase ']': // Ps ; ...\n\t\ti := 0\n\t\tfor i \u003c len(payload) && payload[i] >= '0' && payload[i] \u003c= '9' {\n\t\t\ti++\n\t\t}\n\t\treturn i > 0 && i \u003c len(payload) && payload[i] == ';'\n\tcase 'P': // >| or !| for the version, [01]$r or [01]+r for settings\n\t\tif len(payload) \u003c 2 {\n\t\t\treturn false\n\t\t}\n\t\tif payload[1] == '|' {\n\t\t\treturn payload[0] == '>' || payload[0] == '!'\n\t\t}\n\t\treturn len(payload) >= 3 && (payload[0] == '0' || payload[0] == '1') &&\n\t\t\t(payload[1] == ' || payload[1] == '+') && payload[2] == 'r'\n\tcase '_': // G, then key=value\n\t\treturn len(payload) >= 3 && payload[0] == 'G' &&\n\t\t\t(payload[1] >= 'a' && payload[1] \u003c= 'z' || payload[1] >= 'A' && payload[1] \u003c= 'Z') &&\n\t\t\tpayload[2] == '='\n\t}\n\treturn false\n}\n\n// stillArriving reports whether the CSI or SS3 sequence at the start of the\n// buffer may still be completed by more input. It must be the only one in the buffer:\n// whatever follows it, another sequence or a byte that ended it, means it is not\n// waiting for anything.\nfunc stillArriving(buffer []byte) bool {\n\treturn bytes.IndexByte(buffer[1:], Esc.Byte()) \u003c 0 && incompleteEscape(buffer)\n}\n\n// incompleteEscape reports whether the buffer ends in a CSI or SS3 sequence that\n// has not been terminated yet. The read loop keeps waiting while it does, so a\n// fragment reaches the parser only once that wait has run out. A string sequence\n// is never waited for, because its introducer is also ALT-], ALT-P or ALT-_.\nfunc incompleteEscape(buffer []byte) bool {\n\t// Only the tail can hold a sequence still arriving. This runs once per byte\n\t// read, so scanning all of a large paste would make the read quadratic.\n\ttail := buffer\n\tif len(tail) > escapeLookback {\n\t\ttail = tail[len(tail)-escapeLookback:]\n\t}\n\tstart := bytes.LastIndexByte(tail, Esc.Byte())\n\tif start \u003c 0 || len(tail)-start \u003c 2 {\n\t\treturn false\n\t}\n\t// SS3 is judged like CSI: declaring it finished after one byte made the\n\t// parser give up on a split \\eO1;5A. A malformed sequence is not waited for,\n\t// as nothing can complete it.\n\treturn csiIntroducer(tail[start+1]) && csiEnd(tail[start:]) == 0\n}\n\nfunc (r *LightRenderer) getBytes(cancellable bool) ([]byte, getCharResult, error) {\n\treturn r.getBytesInternal(cancellable, r.buffer, false)\n}\n\nfunc (r *LightRenderer) getBytesInternal(cancellable bool, buffer []byte, nonblock bool) ([]byte, getCharResult, error) {\n\tc, result := r.getch(cancellable, nonblock)\n\tif result == getCharCancelled {\n\t\treturn buffer, getCharCancelled, nil\n\t}\n\tif !nonblock && !result.ok() {\n\t\tr.Close()\n\t\treturn nil, getCharError, errors.New(\"failed to read \" + DefaultTtyDevice)\n\t}\n\n\tretries := 0\n\tif c == Esc.Int() || nonblock {\n\t\tretries = r.escDelay / escPollInterval\n\t}\n\t// A non-blocking read that found nothing has no byte to record. Recording\n\t// one would put a NUL in the middle of a reply still being assembled.\n\tif result.ok() {\n\t\tbuffer = append(buffer, byte(c))\n\t}\n\n\tpc := c\n\tfor {\n\t\tc, result = r.getch(false, true)\n\t\tif !result.ok() {\n\t\t\tif retries > 0 {\n\t\t\t\tretries--\n\t\t\t\ttime.Sleep(escPollInterval * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t} else if c == Esc.Int() && pc != c {\n\t\t\tretries = r.escDelay / escPollInterval\n\t\t} else {\n\t\t\tretries = 0\n\t\t}\n\t\tbuffer = append(buffer, byte(c))\n\t\t// Keep waiting while a sequence is still arriving. Dropping the budget\n\t\t// after every byte left fzf parsing whatever the read happened to end on.\n\t\t// Past the introducer this is not the ESC key, so the wait costs no\n\t\t// Escape latency and ESCDELAY=0 must not reduce it to nothing.\n\t\tif retries == 0 && incompleteEscape(buffer) {\n\t\t\tretries = max(r.escDelay, defaultEscDelay) / escPollInterval\n\t\t}\n\t\tpc = c\n\n\t\t// This should never happen under normal conditions,\n\t\t// so terminate fzf immediately.\n\t\tif len(buffer) > maxInputBuffer {\n\t\t\tr.Close()\n\t\t\treturn nil, getCharError, fmt.Errorf(\"input buffer overflow (%d): %v\", len(buffer), buffer)\n\t\t}\n\t}\n\n\treturn buffer, getCharSuccess, nil\n}\n\nfunc (r *LightRenderer) GetChar(cancellable bool) Event {\n\tvar err error\n\tvar result getCharResult\n\tif len(r.buffer) == 0 {\n\t\tr.buffer, result, err = r.getBytes(cancellable)\n\t\tif err != nil {\n\t\t\treturn Event{Fatal, 0, nil}\n\t\t}\n\t\tif result == getCharCancelled {\n\t\t\treturn Event{Invalid, 0, nil}\n\t\t}\n\t}\n\tif len(r.buffer) == 0 {\n\t\treturn Event{Fatal, 0, nil}\n\t}\n\n\tsz := 1\n\tdefer func() {\n\t\tr.buffer = r.buffer[sz:]\n\t}()\n\n\tswitch r.buffer[0] {\n\tcase CtrlC.Byte():\n\t\treturn Event{CtrlC, 0, nil}\n\tcase CtrlG.Byte():\n\t\treturn Event{CtrlG, 0, nil}\n\tcase CtrlQ.Byte():\n\t\treturn Event{CtrlQ, 0, nil}\n\tcase 127:\n\t\treturn Event{Backspace, 0, nil}\n\tcase 8:\n\t\treturn Event{CtrlBackspace, 0, nil}\n\tcase 0:\n\t\treturn Event{CtrlSpace, 0, nil}\n\tcase 28:\n\t\treturn Event{CtrlBackSlash, 0, nil}\n\tcase 29:\n\t\treturn Event{CtrlRightBracket, 0, nil}\n\tcase 30:\n\t\treturn Event{CtrlCaret, 0, nil}\n\tcase 31:\n\t\treturn Event{CtrlSlash, 0, nil}\n\tcase Esc.Byte():\n\t\tev := r.escSequence(&sz)\n\t\t// Second chance, but only for an unfinished sequence. Re-reading\n\t\t// otherwise blocks until the next keystroke, holding back whatever\n\t\t// follows in the buffer.\n\t\tif ev.Type == Invalid && stillArriving(r.buffer) {\n\t\t\twaited := len(r.buffer)\n\t\t\tvar buffer []byte\n\t\t\tbuffer, result, err = r.getBytes(true)\n\t\t\tif err != nil {\n\t\t\t\treturn Event{Fatal, 0, nil}\n\t\t\t}\n\t\t\tr.buffer = buffer\n\t\t\tif result == getCharCancelled {\n\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\t}\n\n\t\t\tev = r.escSequence(&sz)\n\t\t\t// This read has no time limit, so what it returned may be the next\n\t\t\t// keystroke rather than the rest of the sequence. Never drop it.\n\t\t\tif ev.Type == Invalid && sz > waited {\n\t\t\t\tsz = waited\n\t\t\t}\n\t\t}\n\t\treturn ev\n\t}\n\n\t// CTRL-A ~ CTRL-Z\n\tif r.buffer[0] \u003c= CtrlZ.Byte() {\n\t\treturn Event{EventType(r.buffer[0]), 0, nil}\n\t}\n\tchar, rsz := utf8.DecodeRune(r.buffer)\n\tif char == utf8.RuneError {\n\t\treturn Event{Esc, 0, nil}\n\t}\n\tsz = rsz\n\treturn Event{Rune, char, nil}\n}\n\nfunc (r *LightRenderer) CancelGetChar() {\n\tr.mutex.Lock()\n\tif r.cancel != nil {\n\t\tr.cancel()\n\t\tr.cancel = nil\n\t}\n\tr.mutex.Unlock()\n}\n\nfunc (r *LightRenderer) setCancel(f func()) {\n\tr.mutex.Lock()\n\tr.cancel = f\n\tr.mutex.Unlock()\n}\n\n// escSequence parses an escape sequence, then checks a CSI or SS3 result\n// against its frame. parseEscSequence can stop after a few bytes, and consuming\n// only those would leave the rest to be typed into the query. Complete\n// sequences it does not recognize are dropped there, unless they could be an\n// ALT key followed by typed text.\nfunc (r *LightRenderer) escSequence(sz *int) Event {\n\tev := r.parseEscSequence(sz)\n\tif len(r.buffer) \u003c 3 || !csiIntroducer(r.buffer[1]) {\n\t\treturn ev\n\t}\n\t// A frame missing its final byte may still be arriving\n\tend := csiEnd(r.buffer)\n\tif end \u003c= 0 {\n\t\treturn ev\n\t}\n\t// The parser can also set the size before checking the bytes and then give\n\t// up, counting typed input past the frame, as in \\e[3;1u followed by ~\n\tif ev.Type == Invalid && *sz > end {\n\t\t*sz = end\n\t}\n\t// Four bytes or fewer could be ALT-[ or ALT-O and typed text, and rxvt sends\n\t// keys of that size fzf does not know, such as \\e[3^ for CTRL-DELETE\n\tif end \u003c= 4 {\n\t\treturn ev\n\t}\n\t// A key matched on a prefix, such as Home for \\e[70;5u, or a sequence given\n\t// up on partway\n\tif end > *sz {\n\t\t*sz = end\n\t\treturn Event{Invalid, 0, nil}\n\t}\n\treturn ev\n}\n\nfunc (r *LightRenderer) parseEscSequence(sz *int) Event {\n\tif len(r.buffer) \u003c 2 {\n\t\treturn Event{Esc, 0, nil}\n\t}\n\n\tloc := offsetRegexpBegin.FindIndex(r.buffer)\n\tif loc != nil && loc[0] == 0 {\n\t\t*sz = loc[1]\n\t\treturn Event{Invalid, 0, nil}\n\t}\n\n\tloc = pasteModeRegexpBegin.FindIndex(r.buffer)\n\tif loc != nil && loc[0] == 0 {\n\t\t*sz = loc[1]\n\t\treturn Event{Invalid, 0, nil}\n\t}\n\n\t*sz = 2\n\tif r.buffer[1] == 8 {\n\t\treturn Event{CtrlAltBackspace, 0, nil}\n\t}\n\tif r.buffer[1] >= 1 && r.buffer[1] \u003c= 'z'-'a'+1 {\n\t\treturn CtrlAltKey(rune(r.buffer[1] + 'a' - 1))\n\t}\n\talt := false\n\tif len(r.buffer) > 2 && r.buffer[1] == Esc.Byte() {\n\t\tr.buffer = r.buffer[1:]\n\t\talt = true\n\t}\n\tswitch r.buffer[1] {\n\tcase Esc.Byte():\n\t\treturn Event{Esc, 0, nil}\n\tcase 127:\n\t\treturn Event{AltBackspace, 0, nil}\n\tcase '[', 'O':\n\t\tif len(r.buffer) \u003c 3 {\n\t\t\treturn Event{Invalid, 0, nil}\n\t\t}\n\t\t*sz = 3\n\t\tswitch r.buffer[2] {\n\t\tcase 'D':\n\t\t\tif alt {\n\t\t\t\treturn Event{AltLeft, 0, nil}\n\t\t\t}\n\t\t\treturn Event{Left, 0, nil}\n\t\tcase 'C':\n\t\t\tif alt {\n\t\t\t\t// Ugh..\n\t\t\t\treturn Event{AltRight, 0, nil}\n\t\t\t}\n\t\t\treturn Event{Right, 0, nil}\n\t\tcase 'B':\n\t\t\tif alt {\n\t\t\t\treturn Event{AltDown, 0, nil}\n\t\t\t}\n\t\t\treturn Event{Down, 0, nil}\n\t\tcase 'A':\n\t\t\tif alt {\n\t\t\t\treturn Event{AltUp, 0, nil}\n\t\t\t}\n\t\t\treturn Event{Up, 0, nil}\n\t\tcase 'Z':\n\t\t\treturn Event{ShiftTab, 0, nil}\n\t\tcase 'H':\n\t\t\treturn Event{Home, 0, nil}\n\t\tcase 'F':\n\t\t\treturn Event{End, 0, nil}\n\t\tcase '\u003c':\n\t\t\treturn r.mouseSequence(sz)\n\t\tcase 'P':\n\t\t\treturn Event{F1, 0, nil}\n\t\tcase 'Q':\n\t\t\treturn Event{F2, 0, nil}\n\t\tcase 'R':\n\t\t\treturn Event{F3, 0, nil}\n\t\tcase 'S':\n\t\t\treturn Event{F4, 0, nil}\n\t\tcase '1', '2', '3', '4', '5', '6', '7', '8':\n\t\t\tif len(r.buffer) \u003c 4 {\n\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\t}\n\t\t\t// A byte that cannot continue the sequence, such as Enter after\n\t\t\t// ALT-[ and a digit, is a key of its own\n\t\t\tif csiEnd(r.buffer) \u003c 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t*sz = 4\n\t\t\tswitch r.buffer[2] {\n\t\t\tcase '2':\n\t\t\t\tif r.buffer[3] == '~' {\n\t\t\t\t\treturn Event{Insert, 0, nil}\n\t\t\t\t}\n\t\t\t\tif len(r.buffer) > 4 && r.buffer[4] == '~' {\n\t\t\t\t\t*sz = 5\n\t\t\t\t\tswitch r.buffer[3] {\n\t\t\t\t\tcase '0':\n\t\t\t\t\t\treturn Event{F9, 0, nil}\n\t\t\t\t\tcase '1':\n\t\t\t\t\t\treturn Event{F10, 0, nil}\n\t\t\t\t\tcase '3':\n\t\t\t\t\t\treturn Event{F11, 0, nil}\n\t\t\t\t\tcase '4':\n\t\t\t\t\t\treturn Event{F12, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Bracketed paste mode: \\e[200~ ... \\e[201~\n\t\t\t\tif len(r.buffer) > 5 && r.buffer[3] == '0' && (r.buffer[4] == '0' || r.buffer[4] == '1') && r.buffer[5] == '~' {\n\t\t\t\t\t*sz = 6\n\t\t\t\t\tif r.buffer[4] == '0' {\n\t\t\t\t\t\treturn Event{BracketedPasteBegin, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t\treturn Event{BracketedPasteEnd, 0, nil}\n\t\t\t\t}\n\t\t\t\treturn Event{Invalid, 0, nil} // INS\n\t\t\tcase '3':\n\t\t\t\tif r.buffer[3] == '~' {\n\t\t\t\t\treturn Event{Delete, 0, nil}\n\t\t\t\t}\n\t\t\t\tif len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {\n\t\t\t\t\t*sz = 7\n\t\t\t\t\tswitch r.buffer[5] {\n\t\t\t\t\tcase '0':\n\t\t\t\t\t\treturn Event{AltShiftDelete, 0, nil}\n\t\t\t\t\tcase '1':\n\t\t\t\t\t\treturn Event{AltDelete, 0, nil}\n\t\t\t\t\tcase '2':\n\t\t\t\t\t\treturn Event{AltShiftDelete, 0, nil}\n\t\t\t\t\tcase '3':\n\t\t\t\t\t\treturn Event{CtrlAltDelete, 0, nil}\n\t\t\t\t\tcase '4':\n\t\t\t\t\t\treturn Event{CtrlAltShiftDelete, 0, nil}\n\t\t\t\t\tcase '5':\n\t\t\t\t\t\treturn Event{CtrlAltDelete, 0, nil}\n\t\t\t\t\tcase '6':\n\t\t\t\t\t\treturn Event{CtrlAltShiftDelete, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(r.buffer) > 5 && r.buffer[5] == '~' {\n\t\t\t\t\t*sz = 6\n\t\t\t\t\tswitch r.buffer[4] {\n\t\t\t\t\tcase '2':\n\t\t\t\t\t\treturn Event{ShiftDelete, 0, nil}\n\t\t\t\t\tcase '3':\n\t\t\t\t\t\treturn Event{AltDelete, 0, nil}\n\t\t\t\t\tcase '4':\n\t\t\t\t\t\treturn Event{AltShiftDelete, 0, nil}\n\t\t\t\t\tcase '5':\n\t\t\t\t\t\treturn Event{CtrlDelete, 0, nil}\n\t\t\t\t\tcase '6':\n\t\t\t\t\t\treturn Event{CtrlShiftDelete, 0, nil}\n\t\t\t\t\tcase '7':\n\t\t\t\t\t\treturn Event{CtrlAltDelete, 0, nil}\n\t\t\t\t\tcase '8':\n\t\t\t\t\t\treturn Event{CtrlAltShiftDelete, 0, nil}\n\t\t\t\t\tcase '9':\n\t\t\t\t\t\treturn Event{AltDelete, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\tcase '4':\n\t\t\t\tif rxvtKeyEnd(r.buffer[3]) {\n\t\t\t\t\treturn Event{End, 0, nil}\n\t\t\t\t}\n\t\t\tcase '5':\n\t\t\t\tif r.buffer[3] == '~' {\n\t\t\t\t\treturn Event{PageUp, 0, nil}\n\t\t\t\t}\n\t\t\t\tif len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {\n\t\t\t\t\t*sz = 7\n\t\t\t\t\tswitch r.buffer[5] {\n\t\t\t\t\tcase '0':\n\t\t\t\t\t\treturn Event{AltShiftPageUp, 0, nil}\n\t\t\t\t\tcase '1':\n\t\t\t\t\t\treturn Event{AltPageUp, 0, nil}\n\t\t\t\t\tcase '2':\n\t\t\t\t\t\treturn Event{AltShiftPageUp, 0, nil}\n\t\t\t\t\tcase '3':\n\t\t\t\t\t\treturn Event{CtrlAltPageUp, 0, nil}\n\t\t\t\t\tcase '4':\n\t\t\t\t\t\treturn Event{CtrlAltShiftPageUp, 0, nil}\n\t\t\t\t\tcase '5':\n\t\t\t\t\t\treturn Event{CtrlAltPageUp, 0, nil}\n\t\t\t\t\tcase '6':\n\t\t\t\t\t\treturn Event{CtrlAltShiftPageUp, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(r.buffer) > 5 && r.buffer[5] == '~' {\n\t\t\t\t\t*sz = 6\n\t\t\t\t\tswitch r.buffer[4] {\n\t\t\t\t\tcase '2':\n\t\t\t\t\t\treturn Event{ShiftPageUp, 0, nil}\n\t\t\t\t\tcase '3':\n\t\t\t\t\t\treturn Event{AltPageUp, 0, nil}\n\t\t\t\t\tcase '4':\n\t\t\t\t\t\treturn Event{AltShiftPageUp, 0, nil}\n\t\t\t\t\tcase '5':\n\t\t\t\t\t\treturn Event{CtrlPageUp, 0, nil}\n\t\t\t\t\tcase '6':\n\t\t\t\t\t\treturn Event{CtrlShiftPageUp, 0, nil}\n\t\t\t\t\tcase '7':\n\t\t\t\t\t\treturn Event{CtrlAltPageUp, 0, nil}\n\t\t\t\t\tcase '8':\n\t\t\t\t\t\treturn Event{CtrlAltShiftPageUp, 0, nil}\n\t\t\t\t\tcase '9':\n\t\t\t\t\t\treturn Event{AltPageUp, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\tcase '6':\n\t\t\t\tif r.buffer[3] == '~' {\n\t\t\t\t\treturn Event{PageDown, 0, nil}\n\t\t\t\t}\n\t\t\t\tif len(r.buffer) > 6 && r.buffer[6] == '~' && r.buffer[4] == '1' {\n\t\t\t\t\t*sz = 7\n\t\t\t\t\tswitch r.buffer[5] {\n\t\t\t\t\tcase '0':\n\t\t\t\t\t\treturn Event{AltShiftPageDown, 0, nil}\n\t\t\t\t\tcase '1':\n\t\t\t\t\t\treturn Event{AltPageDown, 0, nil}\n\t\t\t\t\tcase '2':\n\t\t\t\t\t\treturn Event{AltShiftPageDown, 0, nil}\n\t\t\t\t\tcase '3':\n\t\t\t\t\t\treturn Event{CtrlAltPageDown, 0, nil}\n\t\t\t\t\tcase '4':\n\t\t\t\t\t\treturn Event{CtrlAltShiftPageDown, 0, nil}\n\t\t\t\t\tcase '5':\n\t\t\t\t\t\treturn Event{CtrlAltPageDown, 0, nil}\n\t\t\t\t\tcase '6':\n\t\t\t\t\t\treturn Event{CtrlAltShiftPageDown, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(r.buffer) > 5 && r.buffer[5] == '~' {\n\t\t\t\t\t*sz = 6\n\t\t\t\t\tswitch r.buffer[4] {\n\t\t\t\t\tcase '2':\n\t\t\t\t\t\treturn Event{ShiftPageDown, 0, nil}\n\t\t\t\t\tcase '3':\n\t\t\t\t\t\treturn Event{AltPageDown, 0, nil}\n\t\t\t\t\tcase '4':\n\t\t\t\t\t\treturn Event{AltShiftPageDown, 0, nil}\n\t\t\t\t\tcase '5':\n\t\t\t\t\t\treturn Event{CtrlPageDown, 0, nil}\n\t\t\t\t\tcase '6':\n\t\t\t\t\t\treturn Event{CtrlShiftPageDown, 0, nil}\n\t\t\t\t\tcase '7':\n\t\t\t\t\t\treturn Event{CtrlAltPageDown, 0, nil}\n\t\t\t\t\tcase '8':\n\t\t\t\t\t\treturn Event{CtrlAltShiftPageDown, 0, nil}\n\t\t\t\t\tcase '9':\n\t\t\t\t\t\treturn Event{AltPageDown, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\tcase '7':\n\t\t\t\tif rxvtKeyEnd(r.buffer[3]) {\n\t\t\t\t\treturn Event{Home, 0, nil}\n\t\t\t\t}\n\t\t\tcase '8':\n\t\t\t\tif rxvtKeyEnd(r.buffer[3]) {\n\t\t\t\t\treturn Event{End, 0, nil}\n\t\t\t\t}\n\t\t\tcase '1':\n\t\t\t\tswitch r.buffer[3] {\n\t\t\t\tcase '~':\n\t\t\t\t\treturn Event{Home, 0, nil}\n\t\t\t\tcase '1', '2', '3', '4', '5', '7', '8', '9':\n\t\t\t\t\tif len(r.buffer) > 4 && r.buffer[4] == '~' {\n\t\t\t\t\t\t*sz = 5\n\t\t\t\t\t\tswitch r.buffer[3] {\n\t\t\t\t\t\tcase '1':\n\t\t\t\t\t\t\treturn Event{F1, 0, nil}\n\t\t\t\t\t\tcase '2':\n\t\t\t\t\t\t\treturn Event{F2, 0, nil}\n\t\t\t\t\t\tcase '3':\n\t\t\t\t\t\t\treturn Event{F3, 0, nil}\n\t\t\t\t\t\tcase '4':\n\t\t\t\t\t\t\treturn Event{F4, 0, nil}\n\t\t\t\t\t\tcase '5':\n\t\t\t\t\t\t\treturn Event{F5, 0, nil}\n\t\t\t\t\t\tcase '7':\n\t\t\t\t\t\t\treturn Event{F6, 0, nil}\n\t\t\t\t\t\tcase '8':\n\t\t\t\t\t\t\treturn Event{F7, 0, nil}\n\t\t\t\t\t\tcase '9':\n\t\t\t\t\t\t\treturn Event{F8, 0, nil}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\t\tcase ';':\n\t\t\t\t\tif len(r.buffer) \u003c 6 {\n\t\t\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\t\t\t}\n\t\t\t\t\t*sz = 6\n\t\t\t\t\tswitch r.buffer[4] {\n\t\t\t\t\tcase '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\t\t\t\t\t// Kitty iTerm2 WezTerm\n\t\t\t\t\t\t// ARROW \"\\e[1;1D\"\n\t\t\t\t\t\t// SHIFT-ARROW \"\\e[1;2D\"\n\t\t\t\t\t\t// ALT-SHIFT-ARROW \"\\e[1;4D\" \"\\e[1;10D\" \"\\e[1;4D\"\n\t\t\t\t\t\t// CTRL-SHIFT-ARROW \"\\e[1;6D\" N/A\n\t\t\t\t\t\t// CMD-SHIFT-ARROW \"\\e[1;10D\" N/A N/A (\"\\e[1;2D\")\n\t\t\t\t\t\tctrl := bytes.IndexByte([]byte{'5', '6', '7', '8'}, r.buffer[4]) >= 0\n\t\t\t\t\t\talt := bytes.IndexByte([]byte{'3', '4', '7', '8'}, r.buffer[4]) >= 0\n\t\t\t\t\t\tshift := bytes.IndexByte([]byte{'2', '4', '6', '8'}, r.buffer[4]) >= 0\n\t\t\t\t\t\tchar := r.buffer[5]\n\t\t\t\t\t\tif r.buffer[4] == '9' {\n\t\t\t\t\t\t\tctrl = false\n\t\t\t\t\t\t\talt = true\n\t\t\t\t\t\t\tshift = false\n\t\t\t\t\t\t\tif len(r.buffer) \u003c 6 {\n\t\t\t\t\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t*sz = 6\n\t\t\t\t\t\t\tchar = r.buffer[5]\n\t\t\t\t\t\t} else if r.buffer[4] == '1' && bytes.IndexByte([]byte{'0', '1', '2', '3', '4', '5', '6'}, r.buffer[5]) >= 0 {\n\t\t\t\t\t\t\tctrl = bytes.IndexByte([]byte{'3', '4', '5', '6'}, r.buffer[5]) >= 0\n\t\t\t\t\t\t\talt = true\n\t\t\t\t\t\t\tshift = bytes.IndexByte([]byte{'0', '2', '4', '6'}, r.buffer[5]) >= 0\n\t\t\t\t\t\t\tif len(r.buffer) \u003c 7 {\n\t\t\t\t\t\t\t\treturn Event{Invalid, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t*sz = 7\n\t\t\t\t\t\t\tchar = r.buffer[6]\n\t\t\t\t\t\t}\n\t\t\t\t\t\tctrlShift := ctrl && shift\n\t\t\t\t\t\tctrlAlt := ctrl && alt\n\t\t\t\t\t\taltShift := alt && shift\n\t\t\t\t\t\tctrlAltShift := ctrl && alt && shift\n\t\t\t\t\t\tswitch char {\n\t\t\t\t\t\tcase 'A':\n\t\t\t\t\t\t\tif ctrlAltShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltShiftUp, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlAlt {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltUp, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlShiftUp, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif altShift {\n\t\t\t\t\t\t\t\treturn Event{AltShiftUp, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrl {\n\t\t\t\t\t\t\t\treturn Event{CtrlUp, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif alt {\n\t\t\t\t\t\t\t\treturn Event{AltUp, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif shift {\n\t\t\t\t\t\t\t\treturn Event{ShiftUp, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn Event{Up, 0, nil}\n\t\t\t\t\t\tcase 'B':\n\t\t\t\t\t\t\tif ctrlAltShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltShiftDown, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlAlt {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltDown, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlShiftDown, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif altShift {\n\t\t\t\t\t\t\t\treturn Event{AltShiftDown, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrl {\n\t\t\t\t\t\t\t\treturn Event{CtrlDown, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif alt {\n\t\t\t\t\t\t\t\treturn Event{AltDown, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif shift {\n\t\t\t\t\t\t\t\treturn Event{ShiftDown, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn Event{Down, 0, nil}\n\t\t\t\t\t\tcase 'C':\n\t\t\t\t\t\t\tif ctrlAltShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltShiftRight, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlAlt {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltRight, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlShiftRight, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif altShift {\n\t\t\t\t\t\t\t\treturn Event{AltShiftRight, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrl {\n\t\t\t\t\t\t\t\treturn Event{CtrlRight, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif shift {\n\t\t\t\t\t\t\t\treturn Event{ShiftRight, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif alt {\n\t\t\t\t\t\t\t\treturn Event{AltRight, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn Event{Right, 0, nil}\n\t\t\t\t\t\tcase 'D':\n\t\t\t\t\t\t\tif ctrlAltShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltShiftLeft, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlAlt {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltLeft, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlShiftLeft, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif altShift {\n\t\t\t\t\t\t\t\treturn Event{AltShiftLeft, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrl {\n\t\t\t\t\t\t\t\treturn Event{CtrlLeft, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif alt {\n\t\t\t\t\t\t\t\treturn Event{AltLeft, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif shift {\n\t\t\t\t\t\t\t\treturn Event{ShiftLeft, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn Event{Left, 0, nil}\n\t\t\t\t\t\tcase 'H':\n\t\t\t\t\t\t\tif ctrlAltShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltShiftHome, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlAlt {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltHome, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlShiftHome, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif altShift {\n\t\t\t\t\t\t\t\treturn Event{AltShiftHome, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrl {\n\t\t\t\t\t\t\t\treturn Event{CtrlHome, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif alt {\n\t\t\t\t\t\t\t\treturn Event{AltHome, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif shift {\n\t\t\t\t\t\t\t\treturn Event{ShiftHome, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn Event{Home, 0, nil}\n\t\t\t\t\t\tcase 'F':\n\t\t\t\t\t\t\tif ctrlAltShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltShiftEnd, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlAlt {\n\t\t\t\t\t\t\t\treturn Event{CtrlAltEnd, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrlShift {\n\t\t\t\t\t\t\t\treturn Event{CtrlShiftEnd, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif altShift {\n\t\t\t\t\t\t\t\treturn Event{AltShiftEnd, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ctrl {\n\t\t\t\t\t\t\t\treturn Event{CtrlEnd, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif alt {\n\t\t\t\t\t\t\t\treturn Event{AltEnd, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif shift {\n\t\t\t\t\t\t\t\treturn Event{ShiftEnd, 0, nil}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn Event{End, 0, nil}\n\t\t\t\t\t\t}\n\t\t\t\t\t} // r.buffer[4]\n\t\t\t\t} // r.buffer[3]\n\t\t\t} // r.buffer[2]\n\t\t} // r.buffer[2]\n\t} // r.buffer[1]\n\t// Nothing matched. A framed sequence is dropped whole: reading its\n\t// introducer as an ALT-key below would type the rest into the query.\n\t// Unterminated ones are left alone, as that is how ALT-[, ALT-O, ALT-],\n\t// ALT-P and ALT-_ arrive.\n\tif csiIntroducer(r.buffer[1]) {\n\t\t// ALT-[ or ALT-O and one or two typed characters can look like a short\n\t\t// sequence, so ask for at least two bytes before the final byte\n\t\tif end := csiEnd(r.buffer); end > 4 {\n\t\t\t*sz = end\n\t\t\treturn Event{Invalid, 0, nil}\n\t\t}\n\t} else if stringIntroducer(r.buffer[1]) {\n\t\tif end := stringEnd(r.buffer); end > 0 && stringReply(r.buffer) {\n\t\t\t*sz = end\n\t\t\treturn Event{Invalid, 0, nil}\n\t\t}\n\t}\n\n\trest := bytes.NewBuffer(r.buffer[1:])\n\tc, size, err := rest.ReadRune()\n\tif err == nil {\n\t\t*sz = 1 + size\n\t\treturn AltKey(c)\n\t}\n\treturn Event{Invalid, 0, nil}\n}\n\n// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking\nfunc (r *LightRenderer) mouseSequence(sz *int) Event {\n\t// \"\\e[\u003c0;0;0M\"\n\tif len(r.buffer) \u003c 9 || !r.mouse {\n\t\treturn Event{Invalid, 0, nil}\n\t}\n\n\t// Not past the frame, where M or m can be a key typed later\n\tframe := csiEnd(r.buffer)\n\tif frame \u003c= 0 || r.buffer[frame-1] != 'm' && r.buffer[frame-1] != 'M' {\n\t\treturn Event{Invalid, 0, nil}\n\t}\n\trest := r.buffer[*sz:]\n\tend := frame - 1 - *sz\n\n\telems := strings.SplitN(string(rest[:end]), \";\", 3)\n\tif len(elems) != 3 {\n\t\treturn Event{Invalid, 0, nil}\n\t}\n\n\tt := atoi(elems[0], -1)\n\tx := atoi(elems[1], -1) - 1\n\ty := atoi(elems[2], -1) - 1 - r.yoffset\n\tif t \u003c 0 || x \u003c 0 {\n\t\treturn Event{Invalid, 0, nil}\n\t}\n\t*sz += end + 1\n\n\tdown := rest[end] == 'M'\n\n\tscroll := 0\n\twheel := t >= 64\n\tif wheel {\n\t\tt -= 64\n\t\t// SGR wheel button codes: 64=up, 65=down, 66=left, 67=right\n\t\tswitch t & 0b11 {\n\t\tcase 0:\n\t\t\tscroll = 1\n\t\tcase 1:\n\t\t\tscroll = -1\n\t\t}\n\t}\n\n\t// middle := t & 0b1\n\tleft := t&0b11 == 0\n\tctrl := t&0b10000 > 0\n\talt := t&0b01000 > 0\n\tshift := t&0b00100 > 0\n\tdrag := t&0b100000 > 0 // 32\n\n\tif wheel {\n\t\treturn Event{Mouse, 0, &MouseEvent{y, x, scroll, false, false, false, ctrl, alt, shift}}\n\t}\n\n\tdouble := false\n\tif down && !drag {\n\t\tnow := time.Now()\n\t\tif !left { // Right double click is not allowed\n\t\t\tr.clicks = [][2]int{}\n\t\t} else if now.Sub(r.prevDownTime) \u003c doubleClickDuration {\n\t\t\tr.clicks = append(r.clicks, [2]int{x, y})\n\t\t} else {\n\t\t\tr.clicks = [][2]int{{x, y}}\n\t\t}\n\t\tr.prevDownTime = now\n\t} else {\n\t\tn := len(r.clicks)\n\t\tif len(r.clicks) > 1 && r.clicks[n-2][0] == r.clicks[n-1][0] && r.clicks[n-2][1] == r.clicks[n-1][1] &&\n\t\t\ttime.Since(r.prevDownTime) \u003c doubleClickDuration {\n\t\t\tdouble = true\n\t\t\tif double {\n\t\t\t\tr.clicks = [][2]int{}\n\t\t\t}\n\t\t}\n\t}\n\treturn Event{Mouse, 0, &MouseEvent{y, x, 0, left, down, double, ctrl, alt, shift}}\n}\n\nfunc (r *LightRenderer) smcup() {\n\tr.flush()\n\tr.flushRaw(\"\\x1b[?1049h\")\n}\n\nfunc (r *LightRenderer) rmcup() {\n\tr.flush()\n\tr.flushRaw(\"\\x1b[?1049l\")\n}\n\nfunc (r *LightRenderer) Pause(clear bool) {\n\tr.disableModes()\n\tr.restoreTerminal()\n\tif clear {\n\t\tif r.fullscreen {\n\t\t\tr.rmcup()\n\t\t} else {\n\t\t\tr.smcup()\n\t\t\tr.csi(\"H\")\n\t\t}\n\t\tr.flush()\n\t}\n}\n\nfunc (r *LightRenderer) enableModes() {\n\tif r.mouse {\n\t\tr.csi(\"?1000h\")\n\t\tr.csi(\"?1002h\")\n\t\tr.csi(\"?1006h\")\n\t}\n\tr.csi(\"?2004h\") // Enable bracketed paste mode\n}\n\nfunc (r *LightRenderer) disableMouse() {\n\tif r.mouse {\n\t\tr.csi(\"?1000l\")\n\t\tr.csi(\"?1002l\")\n\t\tr.csi(\"?1006l\")\n\t}\n}\n\nfunc (r *LightRenderer) disableModes() {\n\tr.disableMouse()\n\t// Put bracketed paste back the way we found it. A shell that runs fzf from\n\t// a line editor widget re-enables the mode only when the editor starts, so\n\t// forcing it off here would leave it off for the rest of the session.\n\t// Terminals that did not answer the query fall back to disabling, which is\n\t// what fzf has always done.\n\tif r.pasteWasSet != nil && *r.pasteWasSet {\n\t\tr.csi(\"?2004h\")\n\t} else {\n\t\tr.csi(\"?2004l\")\n\t}\n}\n\nfunc (r *LightRenderer) Resume(clear bool, sigcont bool) {\n\tr.setupTerminal()\n\t// The programs that ran in the meantime may have left the terminal in an\n\t// arbitrary SGR state\n\tr.invalidateSGR()\n\tif clear {\n\t\tif r.fullscreen {\n\t\t\tr.smcup()\n\t\t} else {\n\t\t\tr.rmcup()\n\t\t}\n\t\tr.enableModes()\n\t\tr.flush()\n\t} else if sigcont && !r.fullscreen && r.mouse {\n\t\t// NOTE: SIGCONT (Coming back from CTRL-Z):\n\t\t// It's highly likely that the offset we obtained at the beginning is\n\t\t// no longer correct, so we simply disable mouse input.\n\t\tr.disableMouse()\n\t\tr.mouse = false\n\t}\n}\n\nfunc (r *LightRenderer) Clear() {\n\tif r.fullscreen {\n\t\tr.csi(\"H\")\n\t}\n\tr.origin()\n\tr.csi(\"J\")\n\tr.flush()\n}\n\nfunc (r *LightRenderer) NeedScrollbarRedraw() bool {\n\treturn false\n}\n\nfunc (r *LightRenderer) ShouldEmitResizeEvent() bool {\n\treturn false\n}\n\nfunc (r *LightRenderer) RefreshWindows(windows []Window) {\n\tr.flush()\n}\n\nfunc (r *LightRenderer) Refresh() {\n\tr.updateTerminalSize()\n}\n\nfunc (r *LightRenderer) Close() {\n\tif r.clearOnExit {\n\t\tif r.fullscreen {\n\t\t\tr.rmcup()\n\t\t} else {\n\t\t\tr.origin()\n\t\t\t// Erase our own area first, then step back onto the line the\n\t\t\t// prompt was on, so nothing on that line is touched\n\t\t\tr.csi(\"J\")\n\t\t\tif r.upOneLine {\n\t\t\t\tr.csi(\"A\")\n\t\t\t\tr.csi(fmt.Sprintf(\"%dG\", r.xoffset+1))\n\t\t\t}\n\t\t}\n\t} else if !r.fullscreen {\n\t\tr.stderr(\"\\x1b8\") // DECRC: restore cursor position\n\t}\n\tif !r.showCursor {\n\t\tr.csi(\"?25h\")\n\t}\n\tr.disableModes()\n\tr.flush()\n\tr.restoreTerminal()\n\tr.closePlatform()\n}\n\nfunc (r *LightRenderer) Top() int {\n\treturn r.yoffset\n}\n\nfunc (r *LightRenderer) MaxX() int {\n\treturn r.width\n}\n\nfunc (r *LightRenderer) MaxY() int {\n\tif r.height == 0 {\n\t\tr.updateTerminalSize()\n\t}\n\treturn r.height\n}\n\nfunc (r *LightRenderer) NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window {\n\twidth = max(0, width)\n\theight = max(0, height)\n\tw := &LightWindow{\n\t\trenderer: r,\n\t\tcolored: r.theme.Colored,\n\t\twindowType: windowType,\n\t\tborder: borderStyle,\n\t\ttop: top,\n\t\tleft: left,\n\t\twidth: width,\n\t\theight: height,\n\t\ttabstop: r.tabstop,\n\t\tfg: colDefault,\n\t\tbg: colDefault}\n\tswitch windowType {\n\tcase WindowBase:\n\t\tw.fg = r.theme.Fg.Color\n\t\tw.bg = r.theme.Bg.Color\n\tcase WindowList:\n\t\tw.fg = r.theme.ListFg.Color\n\t\tw.bg = r.theme.ListBg.Color\n\tcase WindowInput:\n\t\tw.fg = r.theme.Input.Color\n\t\tw.bg = r.theme.InputBg.Color\n\tcase WindowHeader:\n\t\tw.fg = r.theme.Header.Color\n\t\tw.bg = r.theme.HeaderBg.Color\n\tcase WindowFooter:\n\t\tw.fg = r.theme.Footer.Color\n\t\tw.bg = r.theme.FooterBg.Color\n\tcase WindowPreview:\n\t\tw.fg = r.theme.PreviewFg.Color\n\t\tw.bg = r.theme.PreviewBg.Color\n\t}\n\tif erase && !w.bg.IsDefault() && w.border.shape != BorderNone && w.height > 0 {\n\t\t// fzf --color bg:blue --border --padding 1,2\n\t\tw.Erase()\n\t}\n\tw.drawBorder(false)\n\treturn w\n}\n\nfunc (w *LightWindow) DrawBorder() {\n\tw.drawBorder(false)\n}\n\nfunc (w *LightWindow) DrawHBorder() {\n\tw.drawBorder(true)\n}\n\n// drawHLine fills row `row` with `line` between optional left/right caps.\n// A zero rune means \"no cap\"; caps are placed at the very edges of `w`.\nfunc (w *LightWindow) drawHLine(row int, line, leftCap, rightCap rune, color ColorPair) {\n\tw.Move(row, 0)\n\thw := runeWidth(line)\n\twidth := w.width\n\tif leftCap != 0 {\n\t\tw.CPrint(color, string(leftCap))\n\t\twidth -= runeWidth(leftCap)\n\t}\n\tif rightCap != 0 {\n\t\twidth -= runeWidth(rightCap)\n\t}\n\tif width \u003c 0 {\n\t\twidth = 0\n\t}\n\tinner := width / hw\n\trem := width - inner*hw\n\tw.CPrint(color, repeat(line, inner)+repeat(' ', rem))\n\tif rightCap != 0 {\n\t\tw.CPrint(color, string(rightCap))\n\t}\n}\n\nfunc (w *LightWindow) DrawHSeparator(row int, windowType WindowType, useBottom bool) {\n\tif w.height == 0 {\n\t\treturn\n\t}\n\tshape := w.border.shape\n\tif shape == BorderNone {\n\t\treturn\n\t}\n\tcolor := BorderColor(windowType)\n\tline := w.border.top\n\tif useBottom {\n\t\tline = w.border.bottom\n\t}\n\tvar leftCap, rightCap rune\n\tif shape.HasLeft() {\n\t\tleftCap = w.border.leftMid\n\t}\n\tif shape.HasRight() {\n\t\trightCap = w.border.rightMid\n\t}\n\tw.drawHLine(row, line, leftCap, rightCap, color)\n}\n\nfunc (w *LightWindow) PaintSectionFrame(topContent, bottomContent int, windowType WindowType, edge SectionEdge) {\n\tif w.height == 0 || w.border.shape == BorderNone {\n\t\treturn\n\t}\n\tcolor := BorderColor(windowType)\n\tshape := w.border.shape\n\thasLeft := shape.HasLeft()\n\thasRight := shape.HasRight()\n\trightW := runeWidth(w.border.right)\n\t// Content rows: overpaint left/right verticals + their 1-char margin.\n\tfor row := topContent; row \u003c= bottomContent; row++ {\n\t\tif hasLeft {\n\t\t\tw.Move(row, 0)\n\t\t\tw.CPrint(color, string(w.border.left)+\" \")\n\t\t}\n\t\tif hasRight {\n\t\t\tw.Move(row, w.width-rightW-1)\n\t\t\tw.CPrint(color, \" \"+string(w.border.right))\n\t\t}\n\t}\n\tif edge == SectionEdgeTop && shape.HasTop() {\n\t\tvar leftCap, rightCap rune\n\t\tif hasLeft {\n\t\t\tleftCap = w.border.topLeft\n\t\t}\n\t\tif hasRight {\n\t\t\trightCap = w.border.topRight\n\t\t}\n\t\tw.drawHLine(0, w.border.top, leftCap, rightCap, color)\n\t}\n\tif edge == SectionEdgeBottom && shape.HasBottom() {\n\t\tvar leftCap, rightCap rune\n\t\tif hasLeft {\n\t\t\tleftCap = w.border.bottomLeft\n\t\t}\n\t\tif hasRight {\n\t\t\trightCap = w.border.bottomRight\n\t\t}\n\t\tw.drawHLine(w.height-1, w.border.bottom, leftCap, rightCap, color)\n\t}\n}\n\nfunc (w *LightWindow) drawBorder(onlyHorizontal bool) {\n\tif w.height == 0 {\n\t\treturn\n\t}\n\tshape := w.border.shape\n\tif shape == BorderNone {\n\t\treturn\n\t}\n\tcolor := BorderColor(w.windowType)\n\thasLeft := shape.HasLeft()\n\thasRight := shape.HasRight()\n\n\tif shape.HasTop() {\n\t\tvar leftCap, rightCap rune\n\t\tif hasLeft {\n\t\t\tleftCap = w.border.topLeft\n\t\t}\n\t\tif hasRight {\n\t\t\trightCap = w.border.topRight\n\t\t}\n\t\tw.drawHLine(0, w.border.top, leftCap, rightCap, color)\n\t}\n\tif !onlyHorizontal && (hasLeft || hasRight) {\n\t\tvw := runeWidth(w.border.left)\n\t\tfor y := 0; y \u003c w.height; y++ {\n\t\t\t// Corner rows are already painted by drawHLine above / below.\n\t\t\tif (y == 0 && shape.HasTop()) || (y == w.height-1 && shape.HasBottom()) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif hasLeft {\n\t\t\t\tw.Move(y, 0)\n\t\t\t\tw.CPrint(color, string(w.border.left)+\" \")\n\t\t\t}\n\t\t\tif hasRight {\n\t\t\t\tw.Move(y, w.width-vw-1)\n\t\t\t\tw.CPrint(color, \" \"+string(w.border.right))\n\t\t\t}\n\t\t}\n\t}\n\tif shape.HasBottom() {\n\t\tvar leftCap, rightCap rune\n\t\tif hasLeft {\n\t\t\tleftCap = w.border.bottomLeft\n\t\t}\n\t\tif hasRight {\n\t\t\trightCap = w.border.bottomRight\n\t\t}\n\t\tw.drawHLine(w.height-1, w.border.bottom, leftCap, rightCap, color)\n\t}\n}\n\nfunc (w *LightWindow) stderrInternal(str string, allowNLCR bool, resetCode string) {\n\tw.renderer.stderrInternal(str, allowNLCR, resetCode)\n}\n\nfunc (w *LightWindow) Top() int {\n\treturn w.top\n}\n\nfunc (w *LightWindow) Left() int {\n\treturn w.left\n}\n\nfunc (w *LightWindow) Width() int {\n\treturn w.width\n}\n\nfunc (w *LightWindow) Height() int {\n\treturn w.height\n}\n\nfunc (w *LightWindow) Refresh() {\n}\n\nfunc (w *LightWindow) X() int {\n\treturn w.posx\n}\n\nfunc (w *LightWindow) Y() int {\n\treturn w.posy\n}\n\nfunc (w *LightWindow) EncloseX(x int) bool {\n\treturn x >= w.left && x \u003c (w.left+w.width)\n}\n\nfunc (w *LightWindow) EncloseY(y int) bool {\n\treturn y >= w.top && y \u003c (w.top+w.height)\n}\n\nfunc (w *LightWindow) Enclose(y int, x int) bool {\n\treturn w.EncloseX(x) && w.EncloseY(y)\n}\n\nfunc (w *LightWindow) Move(y int, x int) {\n\tw.posx = x\n\tw.posy = y\n\n\tw.renderer.move(w.Top()+y, w.Left()+x)\n}\n\nfunc (w *LightWindow) MoveAndClear(y int, x int) {\n\tw.Move(y, x)\n\t// We should not delete preview window on the right\n\t// csi(\"K\")\n\tw.Print(repeat(' ', w.width-x))\n\tw.Move(y, x)\n}\n\nfunc attrCodes(attr Attr) []string {\n\tcodes := []string{}\n\tif (attr & AttrClear) > 0 {\n\t\treturn codes\n\t}\n\tif (attr&Bold) > 0 || (attr&BoldForce) > 0 {\n\t\tcodes = append(codes, \"1\")\n\t}\n\tif (attr & Dim) > 0 {\n\t\tcodes = append(codes, \"2\")\n\t}\n\tif (attr & Italic) > 0 {\n\t\tcodes = append(codes, \"3\")\n\t}\n\tif (attr & Underline) > 0 {\n\t\tswitch attr.UnderlineStyle() {\n\t\tcase UlStyleDouble:\n\t\t\tcodes = append(codes, \"4:2\")\n\t\tcase UlStyleCurly:\n\t\t\tcodes = append(codes, \"4:3\")\n\t\tcase UlStyleDotted:\n\t\t\tcodes = append(codes, \"4:4\")\n\t\tcase UlStyleDashed:\n\t\t\tcodes = append(codes, \"4:5\")\n\t\tdefault:\n\t\t\tcodes = append(codes, \"4\")\n\t\t}\n\t}\n\tif (attr & Blink) > 0 {\n\t\tcodes = append(codes, \"5\")\n\t}\n\tif (attr & Reverse) > 0 {\n\t\tcodes = append(codes, \"7\")\n\t}\n\tif (attr & StrikeThrough) > 0 {\n\t\tcodes = append(codes, \"9\")\n\t}\n\treturn codes\n}\n\nfunc colorCodes(fg Color, bg Color) []string {\n\tcodes := []string{}\n\tappendCode := func(c Color, offset int) {\n\t\tif c == colDefault {\n\t\t\treturn\n\t\t}\n\t\tif c.is24() {\n\t\t\tr := (c >> 16) & 0xff\n\t\t\tg := (c >> 8) & 0xff\n\t\t\tb := (c) & 0xff\n\t\t\tcodes = append(codes, fmt.Sprintf(\"%d;2;%d;%d;%d\", 38+offset, r, g, b))\n\t\t} else if c >= colBlack && c \u003c= colWhite {\n\t\t\tcodes = append(codes, fmt.Sprintf(\"%d\", int(c)+30+offset))\n\t\t} else if c > colWhite && c \u003c 16 {\n\t\t\tcodes = append(codes, fmt.Sprintf(\"%d\", int(c)+90+offset-8))\n\t\t} else if c >= 16 && c \u003c 256 {\n\t\t\tcodes = append(codes, fmt.Sprintf(\"%d;5;%d\", 38+offset, c))\n\t\t}\n\t}\n\tappendCode(fg, 0)\n\tappendCode(bg, 10)\n\treturn codes\n}\n\nfunc ulColorCode(c Color) string {\n\tif c == colDefault {\n\t\treturn \"\"\n\t}\n\tif c.is24() {\n\t\tr := (c >> 16) & 0xff\n\t\tg := (c >> 8) & 0xff\n\t\tb := (c) & 0xff\n\t\treturn fmt.Sprintf(\"58;2;%d;%d;%d\", r, g, b)\n\t}\n\tif c >= 0 && c \u003c 256 {\n\t\treturn fmt.Sprintf(\"58;5;%d\", c)\n\t}\n\treturn \"\"\n}\n\n// csiColor builds the SGR sequence for the given colors and attributes\n// without emitting it. The sequence starts with a reset parameter, so it\n// fully determines the SGR state on its own.\nfunc (w *LightWindow) csiColor(fg Color, bg Color, ul Color, attr Attr) (bool, string) {\n\tcodes := append(attrCodes(attr), colorCodes(fg, bg)...)\n\tif ulCode := ulColorCode(ul); ulCode != \"\" {\n\t\tcodes = append(codes, ulCode)\n\t}\n\tif len(codes) == 0 {\n\t\treturn false, \"\\x1b[0m\"\n\t}\n\treturn true, \"\\x1b[;\" + strings.Join(codes, \";\") + \"m\"\n}\n\nfunc (w *LightWindow) Print(text string) {\n\tw.cprint2(colDefault, w.bg, AttrRegular, text)\n}\n\nfunc cleanse(str string) string {\n\treturn strings.ReplaceAll(str, \"\\x1b\", \"\")\n}\n\nfunc (w *LightWindow) CPrint(pair ColorPair, text string) {\n\t_, code := w.csiColor(pair.Fg(), pair.Bg(), pair.Ul(), pair.Attr())\n\tw.renderer.setSGR(code)\n\tw.stderrInternal(cleanse(text), false, code)\n}\n\nfunc (w *LightWindow) cprint2(fg Color, bg Color, attr Attr, text string) {\n\t_, code := w.csiColor(fg, bg, colDefault, attr)\n\tw.renderer.setSGR(code)\n\tw.stderrInternal(cleanse(text), false, code)\n}\n\nfunc (w *LightWindow) fill(str string, resetCode string) FillReturn {\n\tallLines := strings.Split(str, \"\\n\")\n\tfor i, line := range allLines {\n\t\tlines := WrapLine(line, w.posx, w.width, w.tabstop, w.wrapSignWidth)\n\t\tfor j, wl := range lines {\n\t\t\tif w.posx \u003c w.width {\n\t\t\t\tw.stderrInternal(wl.Text, false, resetCode)\n\t\t\t\tw.posx += wl.DisplayWidth\n\t\t\t}\n\n\t\t\t// Wrap line\n\t\t\tif j \u003c len(lines)-1 || i \u003c len(allLines)-1 {\n\t\t\t\tif w.posy+1 >= w.height {\n\t\t\t\t\treturn FillSuspend\n\t\t\t\t}\n\t\t\t\tw.MoveAndClear(w.posy, w.posx)\n\t\t\t\tw.Move(w.posy+1, 0)\n\t\t\t\tw.renderer.setSGR(resetCode)\n\t\t\t\tif len(lines) > 1 {\n\t\t\t\t\tsign := w.wrapSign\n\t\t\t\t\twidth := w.wrapSignWidth\n\t\t\t\t\tif width > w.width {\n\t\t\t\t\t\trunes, truncatedWidth := util.Truncate(w.wrapSign, w.width)\n\t\t\t\t\t\tsign = string(runes)\n\t\t\t\t\t\twidth = truncatedWidth\n\t\t\t\t\t}\n\t\t\t\t\tw.stderrInternal(DIM+sign, false, resetCode)\n\t\t\t\t\tw.renderer.invalidateSGR()\n\t\t\t\t\tw.renderer.setSGR(resetCode)\n\t\t\t\t\tw.Move(w.posy, width)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif w.posx >= w.Width() {\n\t\tif w.posy+1 >= w.height {\n\t\t\treturn FillSuspend\n\t\t}\n\t\tw.Move(w.posy+1, 0)\n\t\tw.renderer.setSGR(resetCode)\n\t\treturn FillNextLine\n\t}\n\treturn FillContinue\n}\n\nfunc (w *LightWindow) setBg() string {\n\t// The plain reset code for the default background is still required to\n\t// clear the dim attribute after ␍ in the preview window\n\t// e.g. printf \"foo\\rbar\" | fzf --ansi --preview 'printf \"foo\\rbar\"'\n\t_, code := w.csiColor(colDefault, w.bg, colDefault, AttrRegular)\n\tw.renderer.setSGR(code)\n\treturn code\n}\n\nfunc (w *LightWindow) LinkBegin(uri string, params string) {\n\tw.renderer.queued.WriteString(\"\\x1b]8;\" + params + \";\" + uri + \"\\x1b\\\\\")\n}\n\nfunc (w *LightWindow) LinkEnd() {\n\tw.renderer.queued.WriteString(\"\\x1b]8;;\\x1b\\\\\")\n}\n\nfunc (w *LightWindow) Fill(text string) FillReturn {\n\tw.Move(w.posy, w.posx)\n\tcode := w.setBg()\n\treturn w.fill(text, code)\n}\n\nfunc (w *LightWindow) CFill(fg Color, bg Color, ul Color, attr Attr, text string) FillReturn {\n\tw.Move(w.posy, w.posx)\n\tif fg == colDefault {\n\t\tfg = w.fg\n\t}\n\tif bg == colDefault {\n\t\tbg = w.bg\n\t}\n\tif hasColors, resetCode := w.csiColor(fg, bg, ul, attr); hasColors {\n\t\tw.renderer.setSGR(resetCode)\n\t\treturn w.fill(text, resetCode)\n\t}\n\treturn w.fill(text, w.setBg())\n}\n\nfunc (w *LightWindow) FinishFill() {\n\tif w.posy \u003c w.height {\n\t\tw.MoveAndClear(w.posy, w.posx)\n\t}\n\tfor y := w.posy + 1; y \u003c w.height; y++ {\n\t\tw.MoveAndClear(y, 0)\n\t}\n}\n\nfunc (w *LightWindow) Erase() {\n\tw.DrawBorder()\n\tw.Move(0, 0)\n\tw.FinishFill()\n\tw.Move(0, 0)\n}\n\nfunc (w *LightWindow) EraseMaybe() bool {\n\treturn false\n}\n\nfunc (w *LightWindow) SetWrapSign(sign string, width int) {\n\tw.wrapSign = sign\n\tw.wrapSignWidth = width\n}\n\nfunc (r *LightRenderer) HideCursor() {\n\tr.showCursor = false\n\tr.csi(\"?25l\")\n}\n\nfunc (r *LightRenderer) ShowCursor() {\n\tr.showCursor = true\n\tr.csi(\"?25h\")\n}\n","preview":null,"history":null,"version":"b8c6ac7a18d1915c14d8241f828f8f1802507a48"},"/_session?shell=1":null}