Skip to content
Myr

terminal.go

This file

Path

src/terminal.go

8,876 lines · 248.1 KiB · Go

Last changed by

Trigger focus event after reload (#4931)Junegunn Choibefore adoption25adb67

History of this file

Take it

1package fzf23import (4	"bufio"5	"context"6	"encoding/json"7	"fmt"8	"io"9	"maps"10	"math"11	"net"12	"os"13	"os/exec"14	"os/signal"15	"regexp"16	"slices"17	"sort"18	"strconv"19	"strings"20	"sync"21	"sync/atomic"22	"syscall"23	"time"24	"unicode"2526	"github.com/rivo/uniseg"2728	"github.com/junegunn/fzf/src/tui"29	"github.com/junegunn/fzf/src/util"30)3132// import "github.com/pkg/profile"3334/*35Placeholder regex is used to extract placeholders from fzf's template36strings. Acts as input validation for parsePlaceholder function.37Describes the syntax, but it is fairly lenient.3839The following pseudo regex has been reverse engineered from the40implementation. It is overly strict, but better describes what's possible.41As such it is not useful for validation, but rather to generate test42cases for example.4344	\\?(?:                                      # escaped type45	    {\+?s?f?r?RANGE(?:,RANGE)*}             # token type46	    {q[:s?RANGE]}                           # query type47	    |{\+?n?f?}                              # item type (notice no mandatory element inside brackets)48	)49	RANGE = (?:50	    (?:-?[0-9]+)?\.\.(?:-?[0-9]+)?          # ellipsis syntax for token range (x..y)51	    |-?[0-9]+                               # shorthand syntax (x..x)52	)53*/54var placeholder *regexp.Regexp55var whiteSuffix *regexp.Regexp56var offsetComponentRegex *regexp.Regexp57var offsetTrimCharsRegex *regexp.Regexp58var passThroughBeginRegex *regexp.Regexp59var passThroughEndTmuxRegex *regexp.Regexp60var sixelBeginRegex *regexp.Regexp61var cursorBackRegex *regexp.Regexp62var ttyin *os.File6364var inTmux = len(os.Getenv("TMUX")) > 06566const clearCode string = "\x1b[2J"6768// Number of maximum focus events to process synchronously69const maxFocusEvents = 100007071// execute-silent and transform* actions will block user input for this duration.72// After this duration, users can press CTRL-C to terminate the command.73const blockDuration = 1 * time.Second7475// Skip exporting FZF_CURRENT_ITEM when the item is larger than this, so a huge76// item cannot overflow ARG_MAX and break exec for preview and other commands.77const maxCurrentItemEnvSize = 64 * 10247879func init() {80	placeholder = regexp.MustCompile(`\\?(?:{[+*sfr]*[0-9,-.]*}|{q(?::s?[0-9,-.]+)?}|{fzf:(?:query|action|prompt)}|{[+*]?f?nf?})`)81	whiteSuffix = regexp.MustCompile(`\s*$`)82	offsetComponentRegex = regexp.MustCompile(`([+-][0-9]+)|(-?/[1-9][0-9]*)`)83	offsetTrimCharsRegex = regexp.MustCompile(`[^0-9/+-]`)8485	// Parts of the preview output that should be passed through to the terminal86	// * https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it87	// * https://sw.kovidgoyal.net/kitty/graphics-protocol88	// * https://en.wikipedia.org/wiki/Sixel89	// * https://iterm2.com/documentation-images.html90	/*91		passThroughRegex = regexp.MustCompile(`92			  \x1bPtmux;\x1b\x1b  .*?  [^\x1b]\x1b\\93			| \x1b(_G|P[0-9;]*q)  .*?  \x1b\\\r?94			| \x1b]1337;          .*?  (\a|\x1b\\)95		`)96	*/97	passThroughBeginRegex = regexp.MustCompile(`\x1bPtmux;\x1b\x1b|\x1b(_G|P[0-9;]*q)|\x1b]1337;`)98	passThroughEndTmuxRegex = regexp.MustCompile(`[^\x1b]\x1b\\`)99	sixelBeginRegex = regexp.MustCompile(`^\x1bP[0-9;]*q`)100101	// CUB right before an IND, used to return to the column a row started on102	cursorBackRegex = regexp.MustCompile(`\x1b\[([0-9]*)D$`)103}104105type jumpMode int106107const (108	jumpDisabled jumpMode = iota109	jumpEnabled110	jumpAcceptEnabled111)112113type resumableState int114115const (116	disabledState resumableState = iota117	pausedState118	enabledState119)120121func (s resumableState) Enabled() bool {122	return s == enabledState123}124125func (s *resumableState) Force(flag bool) {126	if flag {127		*s = enabledState128	} else {129		*s = disabledState130	}131}132133func (s *resumableState) Set(flag bool) {134	if *s == disabledState {135		return136	}137138	if flag {139		*s = enabledState140	} else {141		*s = pausedState142	}143}144145type commandSpec struct {146	command   string147	tempFiles []string148}149150type quitSignal struct {151	code int152	err  error153}154155type waitState struct {156	blocked   bool157	blockedAt time.Time158	pending   []*action159	searching bool // a search is in progress or the input is still loading160}161162type previewer struct {163	version    int64164	lines      []string165	offset     int166	scrollable bool167	final      bool168	following  resumableState169	spinner    string170	bar        []bool171	xw         [2]int172}173174type previewed struct {175	version   int64176	numLines  int177	offset    int178	filled    bool179	image     bool180	wipe      bool181	wireframe bool182}183184type eachLine struct {185	line string186	err  error187}188189type itemLine struct {190	valid     bool191	firstLine int192	numLines  int193	cy        int194	current   bool195	selected  bool196	label     string197	queryLen  int198	width     int199	hasBar    bool200	result    Result201	empty     bool202	other     bool203	hidden    bool204}205206func (t *Terminal) inListWindow() bool {207	return t.window != t.inputWindow && t.window != t.headerWindow && t.window != t.headerLinesWindow && t.window != t.footerWindow208}209210func (t *Terminal) markEmptyLine(line int) {211	if t.inListWindow() {212		t.prevLines[line] = itemLine{valid: true, firstLine: line, empty: true}213	}214}215216func (t *Terminal) markOtherLine(line int) {217	if t.inListWindow() {218		t.prevLines[line] = itemLine{valid: true, firstLine: line, other: true}219	}220}221222type fitpad struct {223	fit int224	pad int225}226227type labelPrinter func(tui.Window, int)228229type markerClass int230231const (232	markerSingle markerClass = iota233	markerTop234	markerMiddle235	markerBottom236)237238type StatusItem struct {239	Index     int    `json:"index"`240	Text      string `json:"text"`241	Positions []int  `json:"positions,omitempty"`242}243244type Status struct {245	Reading    bool         `json:"reading"`246	Progress   int          `json:"progress"`247	Query      string       `json:"query"`248	Position   int          `json:"position"`249	Sort       bool         `json:"sort"`250	TotalCount int          `json:"totalCount"`251	MatchCount int          `json:"matchCount"`252	Current    *StatusItem  `json:"current"`253	Matches    []StatusItem `json:"matches"`254	Selected   []StatusItem `json:"selected"`255}256257type versionedCallback struct {258	version  int64259	callback func()260}261262type runningCmd struct {263	cmd       *exec.Cmd264	tempFiles []string265}266267// Terminal represents terminal input/output268type Terminal struct {269	initDelay            time.Duration270	infoCommand          string271	infoStyle            infoStyle272	infoPrefix           string273	wrap                 bool274	wrapWord             bool275	wrapSign             string276	wrapSignWidth        int277	previewWrapSign      string278	previewWrapSignWidth int279	ghost                string280	separator            labelPrinter281	separatorLen         int282	separatorAuto        bool283	spinner              []string284	promptString         string285	prompt               func()286	promptLen            int287	borderLabel          labelPrinter288	borderLabelLen       int289	borderLabelOpts      labelOpts290	previewLabel         labelPrinter291	previewLabelLen      int292	previewLabelOpts     labelOpts293	inputLabel           labelPrinter294	inputLabelLen        int295	inputLabelOpts       labelOpts296	headerLabel          labelPrinter297	headerLabelLen       int298	headerLabelOpts      labelOpts299	footerLabel          labelPrinter300	footerLabelLen       int301	footerLabelOpts      labelOpts302	gutterReverse        bool303	gutterRawReverse     bool304	pointer              string305	pointerLen           int306	pointerEmpty         string307	pointerEmptyRaw      string308	marker               string309	markerLen            int310	markerEmpty          string311	markerMultiLine      [3]string312	queryLen             [2]int313	layout               layoutType314	fullscreen           bool315	keepRight            bool316	hscroll              bool317	hscrollOff           int318	scrollOff            int319	gap                  int320	gapLine              labelPrinter321	gapLineLen           int322	wordRubout           string323	wordNext             string324	subWordRubout        string325	subWordNext          string326	cx                   int327	cy                   int328	offset               int329	xoffset              int330	yanked               []rune331	input                []rune332	inputOverride        *[]rune333	pasting              *[]rune334	multi                int335	multiLine            bool336	sort                 bool337	toggleSort           bool338	track                trackOption339	idNth                []Range340	trackKey             string341	trackBlocked         bool342	trackSync            bool343	trackKeyCache        map[int32]bool344	wait                 waitState345	pendingSelections    map[string]selectedItem346	targetIndex          int32347	delimiter            Delimiter348	expect               map[tui.Event]string349	keymap               map[tui.Event][]*action350	keymapOrg            map[tui.Event][]*action351	pressed              string352	printQueue           []string353	printQuery           bool354	history              *History355	cycle                bool356	highlightLine        bool357	headerVisible        bool358	headerFirst          bool359	headerLines          int360	header               []Item361	header0              []string362	footer               []string363	ellipsis             string364	scrollbar            string365	previewScrollbar     string366	ansi                 bool367	freezeLeft           int368	freezeRight          int369	nthAttr              tui.Attr370	nth                  []Range371	nthCurrent           []Range372	withNthDefault       string373	withNthExpr          string374	withNthEnabled       bool375	acceptNth            func([]Token, int32) string376	tabstop              int377	margin               [4]sizeSpec378	padding              [4]sizeSpec379	unicode              bool380	listenAddr           *listenAddress381	listenPort           *int382	listener             net.Listener383	listenUnsafe         bool384	borderShape          tui.BorderShape385	listBorderShape      tui.BorderShape386	inputBorderShape     tui.BorderShape387	headerBorderShape    tui.BorderShape388	headerLinesShape     tui.BorderShape389	footerBorderShape    tui.BorderShape390	listLabel            labelPrinter391	listLabelLen         int392	listLabelOpts        labelOpts393	cleanExit            bool394	executor             *util.Executor395	paused               bool396	inputless            bool397	border               tui.Window398	window               tui.Window399	inputWindow          tui.Window400	inputBorder          tui.Window401	headerWindow         tui.Window402	headerBorder         tui.Window403	headerLinesWindow    tui.Window404	headerLinesBorder    tui.Window405	footerWindow         tui.Window406	footerBorder         tui.Window407	wborder              tui.Window408	pborder              tui.Window409	pwindow              tui.Window410	borderWidth          int411	count                int412	progress             int413	hasStartActions      bool414	hasResultActions     bool415	hasFocusActions      bool416	hasLoadActions       bool417	hasResizeActions     bool418	triggerLoad          bool419	pendingReqList       bool420	filterSelection      bool421	reading              bool422	running              *util.AtomicBool423	failed               *string424	jumping              jumpMode425	jumpLabels           string426	printer              func(string)427	printsep             string428	merger               *Merger429	passMerger           *Merger430	resultMerger         *Merger431	matchMap             map[int32]Result432	selected             map[int32]selectedItem433	version              int64434	revision             revision435	bgVersion            int64436	runningCmds          *util.ConcurrentSet[*runningCmd]437	reqBox               *util.EventBox438	initialPreviewOpts   previewOpts439	previewOpts          previewOpts440	activePreviewOpts    *previewOpts441	previewer            previewer442	previewed            previewed443	previewBox           *util.EventBox444	eventBox             *util.EventBox445	mutex                sync.Mutex446	uiMutex              sync.Mutex447	initFunc             func() error448	prevLines            []itemLine449	suppress             bool450	startChan            chan fitpad451	killChan             chan bool452	killedChan           chan bool453	serverInputChan      chan []*action454	callbackChan         chan versionedCallback455	bgQueue              map[action][]func(bool)456	bgSemaphore          chan struct{}457	bgSemaphores         map[action]chan struct{}458	keyChan              chan tui.Event459	eventChan            chan tui.Event460	timerChan            chan tui.Event461	slab                 *util.Slab462	theme                *tui.ColorTheme463	tui                  tui.Renderer464	ttyDefault           string465	ttyin                *os.File466	executing            *util.AtomicBool467	termSize             tui.TermSize468	lastAction           actionType469	lastKey              string470	lastFocus            focusedItem471	areaLines            int472	areaColumns          int473	forcePreview         bool474	clickHeaderLine      int475	clickHeaderColumn    int476	clickFooterLine      int477	clickFooterColumn    int478	proxyScript          string479	setNativeLabel       func(string)480	numLinesCache        map[int32]numLinesCacheValue481	raw                  bool482	lastActivity         time.Time483}484485type numLinesCacheValue struct {486	atMost   int487	numLines int488}489490type selectedItem struct {491	at   time.Time492	item *Item493}494495type focusedItem struct {496	major int // revision.major; changes on reload497	item  *Item498}499500type byTimeOrder []selectedItem501502func (a byTimeOrder) Len() int {503	return len(a)504}505506func (a byTimeOrder) Swap(i, j int) {507	a[i], a[j] = a[j], a[i]508}509510func (a byTimeOrder) Less(i, j int) bool {511	return a[i].at.Before(a[j].at)512}513514// EventTypes are listed in the order of their priority.515const (516	reqResize util.EventType = iota517	reqReinit518	reqFullRedraw519	reqRedraw520521	reqJump522	reqPrompt523	reqInfo524	reqHeader525	reqFooter526	reqList527	reqRedrawInputLabel528	reqRedrawHeaderLabel529	reqRedrawFooterLabel530	reqRedrawListLabel531	reqRedrawBorderLabel532	reqRedrawPreviewLabel533534	reqPreviewReady535	reqPreviewEnqueue536	reqPreviewDisplay537	reqPreviewRefresh538	reqPreviewDelayed539540	reqActivate541	reqClose542	reqPrintQuery543	reqBecome544	reqQuit545	reqFatal546)547548func isTerminalEvent(et util.EventType) bool {549	switch et {550	case reqClose, reqPrintQuery, reqBecome, reqQuit, reqFatal:551		return true552	}553	return false554}555556type action struct {557	t actionType558	a string559}560561//go:generate stringer -type=actionType562type actionType int563564const (565	actIgnore actionType = iota566	actStart567	actClick568	actInvalid569	actBracketedPasteBegin570	actBracketedPasteEnd571	actChar572	actMouse573	actBeginningOfLine574	actAbort575	actAccept576	actAcceptNonEmpty577	actAcceptOrPrintQuery578	actBackwardChar579	actBackwardDeleteChar580	actBackwardDeleteCharEof581	actBackwardWord582	actBackwardSubWord583	actCancel584585	actChangeBorderLabel586	actChangeGhost587	actChangeHeader588	actChangeHeaderLines589	actChangeFooter590	actChangeHeaderLabel591	actChangeFooterLabel592	actChangeInputLabel593	actChangeListLabel594	actChangeMulti595	actChangeNth596	actChangeWithNth597	actChangePointer598	actChangePreview599	actChangePreviewLabel600	actChangePreviewWindow601	actChangePrompt602	actChangeQuery603604	actClearScreen605	actClearQuery606	actClearSelection607	actClose608	actDeleteChar609	actDeleteCharEof610	actEndOfLine611	actFatal612	actForwardChar613	actForwardWord614	actForwardSubWord615	actKillLine616	actKillWord617	actKillSubWord618	actUnixLineDiscard619	actUnixWordRubout620	actYank621	actBackwardKillWord622	actBackwardKillSubWord623	actSelectAll624	actDeselectAll625	actToggle626	actToggleSearch627	actToggleAll628	actToggleDown629	actToggleUp630	actToggleIn631	actToggleOut632	actToggleTrack633	actToggleTrackCurrent634	actToggleHeader635	actToggleWrap636	actToggleWrapWord637	actToggleMultiLine638	actToggleHscroll639	actToggleRaw640	actEnableRaw641	actDisableRaw642	actTrackCurrent643	actToggleInput644	actHideInput645	actShowInput646	actUntrackCurrent647	actDown648	actDownMatch649	actUp650	actUpMatch651	actPageUp652	actPageDown653	actPosition654	actHalfPageUp655	actHalfPageDown656	actOffsetUp657	actOffsetDown658	actOffsetMiddle659	actJump660	actJumpAccept // XXX Deprecated in favor of jump:accept binding661	actPrintQuery // XXX Deprecated (not very useful, just use --print-query)662	actRefreshPreview663	actReplaceQuery664	actToggleSort665	actShowPreview666	actHidePreview667	actTogglePreview668	actTogglePreviewWrap669	actTogglePreviewWrapWord670671	actTransform672	actTransformBorderLabel673	actTransformGhost674	actTransformHeader675	actTransformHeaderLines676	actTransformFooter677	actTransformHeaderLabel678	actTransformFooterLabel679	actTransformInputLabel680	actTransformListLabel681	actTransformNth682	actTransformWithNth683	actTransformPointer684	actTransformPreviewLabel685	actTransformPrompt686	actTransformQuery687	actTransformSearch688689	actTrigger690691	actBgTransform692	actBgTransformBorderLabel693	actBgTransformGhost694	actBgTransformHeader695	actBgTransformHeaderLines696	actBgTransformFooter697	actBgTransformHeaderLabel698	actBgTransformFooterLabel699	actBgTransformInputLabel700	actBgTransformListLabel701	actBgTransformNth702	actBgTransformWithNth703	actBgTransformPointer704	actBgTransformPreviewLabel705	actBgTransformPrompt706	actBgTransformQuery707	actBgTransformSearch708709	actBgCancel710711	actSearch712	actPreview713	actPreviewTop714	actPreviewBottom715	actPreviewUp716	actPreviewDown717	actPreviewPageUp718	actPreviewPageDown719	actPreviewHalfPageUp720	actPreviewHalfPageDown721	actPrevHistory722	actPrevSelected723	actPrint724	actPut725	actNextHistory726	actNextSelected727	actExecute728	actExecuteSilent729	actExecuteMulti // Deprecated730	actSigStop731	actBest732	actFirst733	actLast734	actReload735	actReloadSync736	actDisableSearch737	actEnableSearch738	actSelect739	actDeselect740	actUnbind741	actRebind742	actToggleBind743	actBecome744	actShowHeader745	actHideHeader746	actBell747	actExclude748	actExcludeMulti749	actAsync750	actWait751)752753func (a actionType) Name() string {754	return util.ToKebabCase(a.String()[3:])755}756757func processExecution(action actionType) bool {758	switch action {759	case actTransform,760		actTransformBorderLabel,761		actTransformGhost,762		actTransformHeader,763		actTransformHeaderLines,764		actTransformFooter,765		actTransformHeaderLabel,766		actTransformFooterLabel,767		actTransformInputLabel,768		actTransformListLabel,769		actTransformNth,770		actTransformWithNth,771		actTransformPointer,772		actTransformPreviewLabel,773		actTransformPrompt,774		actTransformQuery,775		actTransformSearch,776		actBgTransform,777		actBgTransformBorderLabel,778		actBgTransformGhost,779		actBgTransformHeader,780		actBgTransformHeaderLines,781		actBgTransformFooter,782		actBgTransformHeaderLabel,783		actBgTransformFooterLabel,784		actBgTransformInputLabel,785		actBgTransformListLabel,786		actBgTransformNth,787		actBgTransformWithNth,788		actBgTransformPointer,789		actBgTransformPreviewLabel,790		actBgTransformPrompt,791		actBgTransformQuery,792		actBgTransformSearch,793		actPreview,794		actChangePreview,795		actRefreshPreview,796		actExecute,797		actExecuteSilent,798		actExecuteMulti,799		actReload,800		actReloadSync,801		actBecome:802		return true803	}804	return false805}806807type placeholderFlags struct {808	plus          bool809	asterisk      bool810	preserveSpace bool811	number        bool812	forceUpdate   bool813	file          bool814	raw           bool815}816817type withNthSpec struct {818	fn func([]Token, int32) string // nil = clear (restore original)819}820821type searchRequest struct {822	sort        bool823	sync        bool824	nth         *[]Range825	withNth     *withNthSpec826	headerLines *int827	command     *commandSpec828	environ     []string829	changed     bool830	denylist    []int32831	revision    revision832}833834type previewRequest struct {835	template     string836	scrollOffset int837	list         [3][]*Item // current, select, and all matched items838	env          []string839	query        string840}841842type previewResult struct {843	version int64844	lines   []string845	offset  int846	spinner string847}848849func toActions(types ...actionType) []*action {850	actions := make([]*action, len(types))851	for idx, t := range types {852		actions[idx] = &action{t: t, a: ""}853	}854	return actions855}856857func defaultKeymap() map[tui.Event][]*action {858	keymap := make(map[tui.Event][]*action)859	add := func(e tui.EventType, a actionType) {860		keymap[e.AsEvent()] = toActions(a)861	}862	addEvent := func(e tui.Event, a actionType) {863		keymap[e] = toActions(a)864	}865866	add(tui.Fatal, actFatal)867	add(tui.Invalid, actInvalid)868	add(tui.BracketedPasteBegin, actBracketedPasteBegin)869	add(tui.BracketedPasteEnd, actBracketedPasteEnd)870	add(tui.CtrlA, actBeginningOfLine)871	add(tui.CtrlB, actBackwardChar)872	add(tui.CtrlC, actAbort)873	add(tui.CtrlG, actAbort)874	add(tui.CtrlQ, actAbort)875	add(tui.Esc, actAbort)876	add(tui.CtrlD, actDeleteCharEof)877	add(tui.CtrlE, actEndOfLine)878	add(tui.CtrlF, actForwardChar)879	add(tui.Backspace, actBackwardDeleteChar)880	add(tui.CtrlBackspace, actBackwardDeleteChar)881	add(tui.Tab, actToggleDown)882	add(tui.ShiftTab, actToggleUp)883	add(tui.CtrlJ, actDown)884	add(tui.CtrlK, actUp)885	add(tui.CtrlL, actClearScreen)886	add(tui.Enter, actAccept)887	add(tui.CtrlN, actDownMatch)888	add(tui.CtrlP, actUpMatch)889	add(tui.AltDown, actDownMatch)890	add(tui.AltUp, actUpMatch)891	add(tui.CtrlU, actUnixLineDiscard)892	add(tui.CtrlW, actUnixWordRubout)893	add(tui.CtrlY, actYank)894	if !util.IsWindows() {895		add(tui.CtrlZ, actSigStop)896	}897	add(tui.CtrlSlash, actToggleWrapWord)898	addEvent(tui.AltKey('/'), actToggleWrapWord)899900	addEvent(tui.AltKey('b'), actBackwardWord)901	add(tui.ShiftLeft, actBackwardWord)902	add(tui.AltLeft, actBackwardWord)903	addEvent(tui.AltKey('f'), actForwardWord)904	add(tui.ShiftRight, actForwardWord)905	add(tui.AltRight, actForwardWord)906	addEvent(tui.AltKey('d'), actKillWord)907	add(tui.AltBackspace, actBackwardKillWord)908909	add(tui.Up, actUp)910	add(tui.Down, actDown)911	add(tui.Left, actBackwardChar)912	add(tui.Right, actForwardChar)913914	add(tui.Home, actBeginningOfLine)915	add(tui.End, actEndOfLine)916	add(tui.Delete, actDeleteChar)917	add(tui.PageUp, actPageUp)918	add(tui.PageDown, actPageDown)919920	add(tui.ShiftUp, actPreviewUp)921	add(tui.ShiftDown, actPreviewDown)922923	add(tui.Mouse, actMouse)924	add(tui.LeftClick, actClick)925	add(tui.RightClick, actToggle)926	add(tui.SLeftClick, actToggle)927	add(tui.SRightClick, actToggle)928929	add(tui.ScrollUp, actUp)930	add(tui.ScrollDown, actDown)931	keymap[tui.SScrollUp.AsEvent()] = toActions(actToggle, actUp)932	keymap[tui.SScrollDown.AsEvent()] = toActions(actToggle, actDown)933934	add(tui.PreviewScrollUp, actPreviewUp)935	add(tui.PreviewScrollDown, actPreviewDown)936	return keymap937}938939func trimQuery(query string) []rune {940	return []rune(strings.ReplaceAll(query, "\t", " "))941}942943func mayTriggerPreview(opts *Options) bool {944	if opts.ListenAddr != nil {945		return true946	}947	for _, actions := range opts.Keymap {948		for _, action := range actions {949			switch action.t {950			case actPreview, actChangePreview, actTransform, actBgTransform:951				return true952			}953		}954	}955	return false956}957958func makeSpinner(unicode bool) []string {959	if unicode {960		return []string{`⠋`, `⠙`, `⠹`, `⠸`, `⠼`, `⠴`, `⠦`, `⠧`, `⠇`, `⠏`}961	}962	return []string{`-`, `\`, `|`, `/`, `-`, `\`, `|`, `/`}963}964965func evaluateHeight(opts *Options, termHeight int) int {966	size := opts.Height.size967	if opts.Height.percent {968		if opts.Height.inverse {969			size = 100 - size970		}971		return max(int(size*float64(termHeight)/100.0), opts.MinHeight)972	}973	if opts.Height.inverse {974		size = float64(termHeight) - size975	}976	return int(size)977}978979// NewTerminal returns new Terminal object980func NewTerminal(opts *Options, eventBox *util.EventBox, executor *util.Executor) (*Terminal, error) {981	input := trimQuery(opts.Query)982	var delay time.Duration983	if opts.Sync {984		delay = 0985	} else if opts.Tac {986		delay = initialDelayTac987	} else {988		delay = initialDelay989	}990	var previewBox *util.EventBox991	// We need to start the previewer even when --preview option is not specified992	// * if HTTP server is enabled993	// * if 'preview' or 'change-preview' action is bound to a key994	// * if 'transform' action is bound to a key995	if len(opts.Preview.command) > 0 || mayTriggerPreview(opts) {996		previewBox = util.NewEventBox()997	}998	var renderer tui.Renderer999	fullscreen := !opts.Height.auto && (opts.Height.size == 0 || opts.Height.percent && opts.Height.size == 100)1000	var err error1001	// Reuse ttyin if available to avoid having multiple file descriptors open1002	// when you run fzf multiple times in your Go program. Closing it is known to1003	// cause problems with 'become' action and invalid terminal state after exit.1004	if ttyin == nil {1005		if ttyin, err = tui.TtyIn(opts.TtyDefault); err != nil {1006			return nil, err1007		}1008	}1009	if fullscreen {1010		if tui.HasFullscreenRenderer() {1011			renderer = tui.NewFullscreenRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop)1012		} else {1013			renderer, err = tui.NewLightRenderer(opts.TtyDefault, ttyin, opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit,1014				true, func(h int) int { return h })1015		}1016	} else {1017		maxHeightFunc := func(termHeight int) int {1018			// Minimum height required to render fzf excluding margin and padding1019			effectiveMinHeight := minHeight1020			if previewBox != nil && opts.Preview.aboveOrBelow() {1021				effectiveMinHeight += 1 + borderLines(opts.Preview.Border(opts.Layout))1022			}1023			if opts.noSeparatorLine() {1024				effectiveMinHeight--1025			}1026			effectiveMinHeight += borderLines(opts.BorderShape)1027			return min(termHeight, max(evaluateHeight(opts, termHeight), effectiveMinHeight))1028		}1029		renderer, err = tui.NewLightRenderer(opts.TtyDefault, ttyin, opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit, false, maxHeightFunc)1030	}1031	if err != nil {1032		return nil, err1033	}1034	if opts.Inputless {1035		renderer.HideCursor()1036	}1037	wordRubout := "[^\\pL\\pN][\\pL\\pN]"1038	wordNext := "[\\pL\\pN][^\\pL\\pN]|(.$)"1039	subWordRubout := "[a-z][A-Z]|[^\\pL\\pN][\\pL\\pN]"1040	subWordNext := "[a-z][A-Z]|[\\pL\\pN][^\\pL\\pN]|(.$)"1041	if opts.FileWord {1042		sep := regexp.QuoteMeta(string(os.PathSeparator))1043		wordRubout = fmt.Sprintf("%s[^%s]", sep, sep)1044		wordNext = fmt.Sprintf("[^%s]%s|(.$)", sep, sep)1045	}1046	keymapCopy := maps.Clone(opts.Keymap)10471048	em := EmptyMerger(revision{})1049	t := Terminal{1050		initDelay:          delay,1051		infoCommand:        opts.InfoCommand,1052		infoStyle:          opts.InfoStyle,1053		infoPrefix:         opts.InfoPrefix,1054		ghost:              opts.Ghost,1055		separator:          nil,1056		spinner:            makeSpinner(opts.Unicode),1057		promptString:       opts.Prompt,1058		queryLen:           [2]int{0, 0},1059		layout:             opts.Layout,1060		fullscreen:         fullscreen,1061		keepRight:          opts.KeepRight,1062		hscroll:            opts.Hscroll,1063		hscrollOff:         opts.HscrollOff,1064		scrollOff:          opts.ScrollOff,1065		pointer:            *opts.Pointer,1066		pointerLen:         uniseg.StringWidth(*opts.Pointer),1067		marker:             *opts.Marker,1068		markerLen:          uniseg.StringWidth(*opts.Marker),1069		markerMultiLine:    *opts.MarkerMulti,1070		wordRubout:         wordRubout,1071		wordNext:           wordNext,1072		subWordRubout:      subWordRubout,1073		subWordNext:        subWordNext,1074		cx:                 len(input),1075		cy:                 0,1076		offset:             0,1077		xoffset:            0,1078		yanked:             []rune{},1079		input:              input,1080		multi:              opts.Multi,1081		multiLine:          opts.ReadZero && opts.MultiLine,1082		wrap:               opts.Wrap,1083		wrapWord:           opts.WrapWord,1084		sort:               opts.Sort > 0,1085		toggleSort:         opts.ToggleSort,1086		track:              opts.Track,1087		idNth:              opts.IdNth,1088		targetIndex:        minItem.Index(),1089		delimiter:          opts.Delimiter,1090		expect:             opts.Expect,1091		keymap:             opts.Keymap,1092		keymapOrg:          keymapCopy,1093		pressed:            "",1094		printQuery:         opts.PrintQuery,1095		history:            opts.History,1096		margin:             opts.Margin,1097		padding:            opts.Padding,1098		unicode:            opts.Unicode,1099		listenAddr:         opts.ListenAddr,1100		listenUnsafe:       opts.Unsafe,1101		borderShape:        opts.BorderShape,1102		listBorderShape:    opts.ListBorderShape,1103		inputBorderShape:   opts.InputBorderShape,1104		headerBorderShape:  opts.HeaderBorderShape,1105		headerLinesShape:   opts.HeaderLinesShape,1106		footerBorderShape:  opts.FooterBorderShape,1107		borderWidth:        1,1108		listLabel:          nil,1109		listLabelOpts:      opts.ListLabel,1110		borderLabel:        nil,1111		borderLabelOpts:    opts.BorderLabel,1112		previewLabel:       nil,1113		previewLabelOpts:   opts.PreviewLabel,1114		inputLabel:         nil,1115		inputLabelOpts:     opts.InputLabel,1116		headerLabel:        nil,1117		headerLabelOpts:    opts.HeaderLabel,1118		footerLabel:        nil,1119		footerLabelOpts:    opts.FooterLabel,1120		cleanExit:          opts.ClearOnExit,1121		executor:           executor,1122		paused:             opts.Phony,1123		inputless:          opts.Inputless,1124		cycle:              opts.Cycle,1125		highlightLine:      opts.CursorLine,1126		headerVisible:      true,1127		headerFirst:        opts.HeaderFirst,1128		headerLines:        opts.HeaderLines,1129		gap:                opts.Gap,1130		header:             []Item{},1131		footer:             opts.Footer,1132		header0:            opts.Header,1133		ansi:               opts.Ansi,1134		freezeLeft:         opts.FreezeLeft,1135		freezeRight:        opts.FreezeRight,1136		nthAttr:            opts.Theme.Nth.Attr,1137		nth:                opts.Nth,1138		nthCurrent:         opts.Nth,1139		withNthDefault:     opts.WithNthExpr,1140		withNthExpr:        opts.WithNthExpr,1141		withNthEnabled:     opts.WithNth != nil,1142		tabstop:            opts.Tabstop,1143		raw:                opts.Raw,1144		hasStartActions:    false,1145		hasResultActions:   false,1146		hasFocusActions:    false,1147		hasLoadActions:     false,1148		triggerLoad:        false,1149		reading:            true,1150		running:            util.NewAtomicBool(true),1151		failed:             nil,1152		jumping:            jumpDisabled,1153		jumpLabels:         opts.JumpLabels,1154		printer:            opts.Printer,1155		printsep:           opts.PrintSep,1156		proxyScript:        opts.ProxyScript,1157		setNativeLabel:     nativeLabelSetter(),1158		merger:             em,1159		passMerger:         em,1160		resultMerger:       em,1161		matchMap:           make(map[int32]Result),1162		selected:           make(map[int32]selectedItem),1163		runningCmds:        util.NewConcurrentSet[*runningCmd](),1164		reqBox:             util.NewEventBox(),1165		initialPreviewOpts: opts.Preview,1166		previewOpts:        opts.Preview,1167		activePreviewOpts:  &opts.Preview,1168		previewer:          previewer{0, []string{}, 0, false, true, disabledState, "", []bool{}, [2]int{0, 0}},1169		previewed:          previewed{0, 0, 0, false, false, false, false},1170		previewBox:         previewBox,1171		eventBox:           eventBox,1172		mutex:              sync.Mutex{},1173		uiMutex:            sync.Mutex{},1174		suppress:           true,1175		slab:               util.MakeSlab(slab16Size, slab32Size),1176		theme:              opts.Theme,1177		startChan:          make(chan fitpad, 1),1178		killChan:           make(chan bool),1179		killedChan:         make(chan bool),1180		serverInputChan:    make(chan []*action, 100),1181		callbackChan:       make(chan versionedCallback, maxBgProcesses),1182		bgQueue:            make(map[action][]func(bool)),1183		bgSemaphore:        make(chan struct{}, maxBgProcesses),1184		bgSemaphores:       make(map[action]chan struct{}),1185		keyChan:            make(chan tui.Event),1186		eventChan:          make(chan tui.Event, 7), // start | (load + result + result-final + zero|one) | (focus) | (resize)1187		timerChan:          make(chan tui.Event),    // unbuffered: every() ticks coalesce when main loop is busy1188		tui:                renderer,1189		ttyDefault:         opts.TtyDefault,1190		ttyin:              ttyin,1191		initFunc:           func() error { return renderer.Init() },1192		executing:          util.NewAtomicBool(false),1193		lastAction:         actStart,1194		lastFocus:          focusedItem{},1195		lastActivity:       time.Now(),1196		numLinesCache:      make(map[int32]numLinesCacheValue),1197		// The initial load counts as a search in progress ('start:wait').1198		// Set before the reader starts so the first final result clears it.1199		wait: waitState{searching: true}}1200	if opts.AcceptNth != nil {1201		t.acceptNth = opts.AcceptNth(t.delimiter)1202	}12031204	baseTheme := opts.BaseTheme1205	if baseTheme == nil {1206		baseTheme = renderer.DefaultTheme()1207	}1208	// If the list border can't host an inline separator, the runtime later coerces1209	// BorderInline to BorderLine. Mirror that here so theme color inheritance matches1210	// the final rendering rather than the user's requested shape.1211	inlineListSupported := opts.ListBorderShape.HasTop() && opts.ListBorderShape.HasBottom()1212	headerInline := inlineListSupported && (opts.HeaderBorderShape == tui.BorderInline || opts.HeaderLinesShape == tui.BorderInline)1213	footerInline := inlineListSupported && opts.FooterBorderShape == tui.BorderInline1214	hasHeader := opts.HeaderBorderShape.Visible() || opts.HeaderLinesShape.Visible()1215	// This should be called before accessing tui.Color*1216	tui.InitTheme(opts.Theme, baseTheme, opts.Bold, opts.Black, opts.InputBorderShape.Visible(), hasHeader, headerInline, footerInline)12171218	// Gutter character1219	var gutterChar, gutterRawChar string1220	if opts.Gutter != nil {1221		gutterChar = *opts.Gutter1222	} else if t.unicode {1223		gutterChar = "▌"1224	} else {1225		gutterChar = " "1226		t.gutterReverse = true1227	}12281229	if opts.GutterRaw != nil {1230		gutterRawChar = *opts.GutterRaw1231	} else if t.unicode {1232		gutterRawChar = "▖"1233	} else {1234		gutterRawChar = ":"1235		t.gutterRawReverse = false1236	}12371238	t.prompt, t.promptLen = t.parsePrompt(opts.Prompt)1239	// Pre-calculated empty pointer and marker signs1240	if t.pointerLen == 0 {1241		t.pointerEmpty = ""1242		t.pointerEmptyRaw = ""1243	} else {1244		t.pointerEmpty = gutterChar + strings.Repeat(" ", max(0, t.pointerLen-1))1245		t.pointerEmptyRaw = gutterRawChar + strings.Repeat(" ", max(0, t.pointerLen-1))1246	}1247	t.markerEmpty = strings.Repeat(" ", t.markerLen)12481249	// Labels1250	t.listLabel, t.listLabelLen = t.ansiLabelPrinter(opts.ListLabel.label, &tui.ColListLabel, false)1251	t.borderLabel, t.borderLabelLen = t.ansiLabelPrinter(opts.BorderLabel.label, &tui.ColBorderLabel, false)1252	t.previewLabel, t.previewLabelLen = t.ansiLabelPrinter(opts.PreviewLabel.label, &tui.ColPreviewLabel, false)1253	t.inputLabel, t.inputLabelLen = t.ansiLabelPrinter(opts.InputLabel.label, &tui.ColInputLabel, false)1254	t.headerLabel, t.headerLabelLen = t.ansiLabelPrinter(opts.HeaderLabel.label, &tui.ColHeaderLabel, false)1255	t.footerLabel, t.footerLabelLen = t.ansiLabelPrinter(opts.FooterLabel.label, &tui.ColFooterLabel, false)12561257	// Determine border shape1258	if t.borderShape == tui.BorderLine {1259		if t.fullscreen {1260			t.borderShape = tui.BorderNone1261		} else {1262			t.borderShape = tui.BorderTop1263		}1264	}12651266	// Determine input border shape1267	t.inputBorderShape = resolveInputBorderShape(t.layout, t.inputBorderShape)12681269	// Inline borders are embedded between the list's top and bottom horizontals.1270	// Shapes missing either one (none/phantom/line/single-sided) fall back to a plain1271	// horizontal separator (same as BorderLine).1272	inlineSupported := t.listBorderShape.HasTop() && t.listBorderShape.HasBottom()1273	if !inlineSupported {1274		if t.headerBorderShape == tui.BorderInline {1275			t.headerBorderShape = tui.BorderLine1276		}1277		if t.headerLinesShape == tui.BorderInline {1278			t.headerLinesShape = tui.BorderLine1279		}1280		if t.footerBorderShape == tui.BorderInline {1281			t.footerBorderShape = tui.BorderLine1282		}1283	}12841285	// Determine header border shape1286	if t.headerBorderShape == tui.BorderLine {1287		if t.layout == layoutReverse {1288			t.headerBorderShape = tui.BorderBottom1289		} else {1290			t.headerBorderShape = tui.BorderTop1291		}1292	}12931294	// Determine header lines border shape1295	if t.headerLinesShape == tui.BorderLine {1296		if t.layout == layoutDefault {1297			t.headerLinesShape = tui.BorderTop1298		} else {1299			t.headerLinesShape = tui.BorderBottom1300		}1301	}13021303	// Determine footer border shape1304	if t.footerBorderShape == tui.BorderLine {1305		if t.layout == layoutReverse {1306			t.footerBorderShape = tui.BorderTop1307		} else {1308			t.footerBorderShape = tui.BorderBottom1309		}1310	}13111312	// The default separator can be suppressed at runtime depending on the1313	// window layout (see separatorLength)1314	t.separatorAuto = opts.Separator == nil1315	bar := "─"1316	if opts.Separator != nil {1317		bar = *opts.Separator1318	} else if !t.unicode {1319		bar = "-"1320	}1321	if len(bar) > 0 {1322		t.separator, t.separatorLen = t.ansiLabelPrinter(bar, &tui.ColSeparator, true)1323	}13241325	// Gap line1326	if t.gap > 0 && len(*opts.GapLine) > 0 {1327		t.gapLine, t.gapLineLen = t.ansiLabelPrinter(*opts.GapLine, &tui.ColGapLine, true)1328	}13291330	if opts.Ellipsis != nil {1331		t.ellipsis = *opts.Ellipsis1332	} else if t.unicode {1333		t.ellipsis = "··"1334	} else {1335		t.ellipsis = ".."1336	}13371338	if t.unicode {1339		t.wrapSign = "↳ "1340		t.borderWidth = uniseg.StringWidth("│")1341	} else {1342		t.wrapSign = "> "1343	}1344	if opts.WrapSign != nil {1345		t.wrapSign = *opts.WrapSign1346	}1347	t.wrapSign, t.wrapSignWidth = t.processTabsStr(t.wrapSign, 0)1348	t.previewWrapSign = t.wrapSign1349	t.previewWrapSignWidth = t.wrapSignWidth1350	if opts.PreviewWrapSign != nil {1351		t.previewWrapSign, t.previewWrapSignWidth = t.processTabsStr(*opts.PreviewWrapSign, 0)1352	}1353	if opts.Scrollbar == nil {1354		if t.unicode && t.borderWidth == 1 {1355			t.scrollbar = "│"1356		} else {1357			t.scrollbar = "|"1358		}1359		t.previewScrollbar = t.scrollbar1360	} else {1361		runes := []rune(*opts.Scrollbar)1362		if len(runes) > 0 {1363			t.scrollbar = string(runes[0])1364			t.previewScrollbar = t.scrollbar1365			if len(runes) > 1 {1366				t.previewScrollbar = string(runes[1])1367			}1368		}1369	}13701371	var resizeActions []*action1372	resizeActions, t.hasResizeActions = t.keymap[tui.Resize.AsEvent()]1373	if t.tui.ShouldEmitResizeEvent() {1374		t.keymap[tui.Resize.AsEvent()] = append(toActions(actClearScreen), resizeActions...)1375	}1376	_, t.hasStartActions = t.keymap[tui.Start.AsEvent()]1377	_, t.hasResultActions = t.keymap[tui.Result.AsEvent()]1378	if _, prs := t.keymap[tui.ResultFinal.AsEvent()]; prs {1379		t.hasResultActions = true1380	}1381	_, t.hasFocusActions = t.keymap[tui.Focus.AsEvent()]1382	_, t.hasLoadActions = t.keymap[tui.Load.AsEvent()]13831384	if t.listenAddr != nil {1385		listener, port, err := startHttpServer(*t.listenAddr, t.serverInputChan, t.dumpStatus)1386		if err != nil {1387			return nil, err1388		}1389		t.listener = listener1390		if port > 0 {1391			t.listenPort = &port1392		}1393	}13941395	if t.hasStartActions {1396		t.eventChan <- tui.Start.AsEvent()1397	}13981399	return &t, nil1400}14011402func (t *Terminal) deferActivation() bool {1403	return t.initDelay == 0 && (t.hasStartActions || t.hasLoadActions || t.hasResultActions || t.hasFocusActions)1404}14051406func (t *Terminal) environ() []string {1407	return t.environImpl(false)1408}14091410func (t *Terminal) environForPreview() []string {1411	return t.environImpl(true)1412}14131414func (t *Terminal) environImpl(forPreview bool) []string {1415	env := os.Environ()1416	if t.listenAddr != nil && len(t.listenAddr.sock) > 0 {1417		env = append(env, "FZF_SOCK="+t.listenAddr.sock)1418	}1419	if t.listenPort != nil {1420		env = append(env, fmt.Sprintf("FZF_PORT=%d", *t.listenPort))1421	}1422	env = append(env, "FZF_QUERY="+string(t.input))1423	env = append(env, "FZF_ACTION="+t.lastAction.Name())1424	env = append(env, "FZF_KEY="+t.lastKey)1425	idleMs := time.Since(t.lastActivity).Milliseconds()1426	env = append(env, fmt.Sprintf("FZF_IDLE_TIME=%d", idleMs/1000))1427	env = append(env, fmt.Sprintf("FZF_IDLE_TIME_MS=%d", idleMs))1428	env = append(env, "FZF_PROMPT="+string(t.promptString))1429	env = append(env, "FZF_GHOST="+string(t.ghost))1430	env = append(env, "FZF_POINTER="+string(t.pointer))1431	env = append(env, "FZF_PREVIEW_LABEL="+t.previewLabelOpts.label)1432	env = append(env, "FZF_BORDER_LABEL="+t.borderLabelOpts.label)1433	env = append(env, "FZF_LIST_LABEL="+t.listLabelOpts.label)1434	env = append(env, "FZF_INPUT_LABEL="+t.inputLabelOpts.label)1435	env = append(env, "FZF_HEADER_LABEL="+t.headerLabelOpts.label)1436	direction := "down"1437	if t.layout == layoutDefault {1438		direction = "up"1439	}1440	env = append(env, "FZF_DIRECTION="+direction)1441	if len(t.nthCurrent) > 0 {1442		env = append(env, "FZF_NTH="+RangesToString(t.nthCurrent))1443	}1444	if len(t.withNthExpr) > 0 {1445		env = append(env, "FZF_WITH_NTH="+t.withNthExpr)1446	}1447	if t.raw {1448		val := "0"1449		if t.isCurrentItemMatch() {1450			val = "1"1451		}1452		env = append(env, "FZF_RAW="+val)1453	}1454	inputState := "enabled"1455	if t.inputless {1456		inputState = "hidden"1457	} else if t.paused {1458		inputState = "disabled"1459	}1460	if t.wrap {1461		if t.wrapWord {1462			env = append(env, "FZF_WRAP=word")1463		} else {1464			env = append(env, "FZF_WRAP=char")1465		}1466	}1467	env = append(env, "FZF_INPUT_STATE="+inputState)1468	env = append(env, fmt.Sprintf("FZF_TOTAL_COUNT=%d", t.count))1469	env = append(env, fmt.Sprintf("FZF_MATCH_COUNT=%d", t.resultMerger.Length()))1470	env = append(env, fmt.Sprintf("FZF_SELECT_COUNT=%d", len(t.selected)))1471	env = append(env, fmt.Sprintf("FZF_LINES=%d", t.areaLines))1472	env = append(env, fmt.Sprintf("FZF_COLUMNS=%d", t.areaColumns))1473	env = append(env, fmt.Sprintf("FZF_POS=%d", min(t.merger.Length(), t.cy+1)))1474	if item := t.currentItem(); item != nil {1475		// Skip if the value contains a NUL byte (exec(2) would reject the env)1476		// or is too large (a huge item can overflow ARG_MAX and break exec1477		// entirely for preview and other child commands).1478		if s := item.AsString(t.ansi); !strings.ContainsRune(s, 0) && len(s) <= maxCurrentItemEnvSize {1479			env = append(env, "FZF_CURRENT_ITEM="+s)1480		}1481	}1482	env = append(env, fmt.Sprintf("FZF_CLICK_HEADER_LINE=%d", t.clickHeaderLine))1483	env = append(env, fmt.Sprintf("FZF_CLICK_HEADER_COLUMN=%d", t.clickHeaderColumn))1484	env = append(env, fmt.Sprintf("FZF_CLICK_FOOTER_LINE=%d", t.clickFooterLine))1485	env = append(env, fmt.Sprintf("FZF_CLICK_FOOTER_COLUMN=%d", t.clickFooterColumn))1486	env = t.addClickHeaderWord(env)1487	env = t.addClickFooterWord(env)14881489	// Add preview environment variables if preview is enabled1490	pwindowSize := t.pwindowSize()1491	if pwindowSize.Lines > 0 {1492		lines := fmt.Sprintf("LINES=%d", pwindowSize.Lines)1493		columns := fmt.Sprintf("COLUMNS=%d", pwindowSize.Columns)1494		if forPreview {1495			env = append(env, lines)1496			env = append(env, columns)1497		}1498		env = append(env, "FZF_PREVIEW_"+lines)1499		env = append(env, "FZF_PREVIEW_"+columns)1500		env = append(env, fmt.Sprintf("FZF_PREVIEW_TOP=%d", t.tui.Top()+t.pwindow.Top()))1501		env = append(env, fmt.Sprintf("FZF_PREVIEW_LEFT=%d", t.pwindow.Left()))1502	}15031504	return env1505}15061507func borderLines(shape tui.BorderShape) int {1508	lines := 01509	if shape.HasTop() {1510		lines++1511	}1512	if shape.HasBottom() {1513		lines++1514	}1515	return lines1516}15171518func borderColumns(shape tui.BorderShape, borderWidth int) int {1519	columns := 01520	if shape.HasLeft() {1521		columns += 1 + borderWidth1522	}1523	if shape.HasRight() {1524		columns += 1 + borderWidth1525	}1526	return columns1527}15281529func (t *Terminal) visibleHeaderLines() int {1530	if !t.headerVisible {1531		return 01532	}1533	return len(t.header0) + t.headerLines1534}15351536func (t *Terminal) visibleHeaderLinesInList() int {1537	if t.headerWindow != nil || t.headerLinesWindow != nil {1538		return 01539	}1540	return t.visibleHeaderLines()1541}15421543func (t *Terminal) visibleInputLinesInList() int {1544	if t.inputWindow != nil || t.inputless {1545		return 01546	}1547	if t.noSeparatorLine() {1548		return 11549	}1550	return 21551}15521553// Extra number of lines needed to display fzf1554func (t *Terminal) extraLines() int {1555	// borderLines() reports zero for BorderInline, but addInline() still1556	// reserves a divider line for it1557	sectionLines := func(shape tui.BorderShape) int {1558		if shape == tui.BorderInline {1559			return 11560		}1561		return borderLines(shape)1562	}1563	extra := 01564	if !t.inputless {1565		extra++1566		if !t.noSeparatorLine() {1567			extra++1568		}1569		if t.inputBorderShape.Visible() {1570			extra += borderLines(t.inputBorderShape)1571		}1572	}1573	if t.listBorderShape.Visible() {1574		extra += borderLines(t.listBorderShape)1575	}1576	if t.headerVisible {1577		if t.hasHeaderWindow() {1578			extra += sectionLines(t.headerBorderShape)1579		}1580		extra += len(t.header0)1581		if w, shape := t.determineHeaderLinesShape(); w {1582			extra += sectionLines(shape)1583		}1584		extra += t.headerLines1585	}1586	if len(t.footer) > 0 {1587		extra += sectionLines(t.footerBorderShape)1588		extra += len(t.footer)1589	}1590	return extra1591}15921593func (t *Terminal) MaxFitAndPad() (int, int) {1594	_, screenHeight, marginInt, paddingInt := t.adjustMarginAndPadding()1595	padHeight := marginInt[0] + marginInt[2] + paddingInt[0] + paddingInt[2]1596	fit := screenHeight - padHeight - t.extraLines()1597	return fit, padHeight1598}15991600func (t *Terminal) ansiLabelPrinter(str string, color *tui.ColorPair, fill bool) (labelPrinter, int) {1601	// Nothing to do1602	if len(str) == 0 {1603		return nil, 01604	}16051606	// Extract ANSI color codes1607	str = firstLine(str)1608	text, colors, _ := extractColor(str, nil, nil)1609	runes := []rune(text)16101611	// Simpler printer for strings without ANSI colors or tab characters1612	if colors == nil && !strings.ContainsRune(text, '\t') {1613		length := util.StringWidth(text)1614		if length == 0 {1615			return nil, 01616		}1617		printFn := func(window tui.Window, limit int) {1618			ellipsis := []rune{}1619			ellipsisWidth := 01620			if !fill {1621				ellipsis, ellipsisWidth = util.Truncate(t.ellipsis, limit)1622			}1623			if length > limit {1624				trimmedRunes, _ := t.trimRight(runes, limit-ellipsisWidth)1625				window.CPrint(*color, string(trimmedRunes)+string(ellipsis))1626			} else if fill {1627				window.CPrint(*color, util.RepeatToFill(text, length, limit))1628			} else {1629				window.CPrint(*color, text)1630			}1631		}1632		return printFn, length1633	}16341635	// Printer that correctly handles ANSI color codes and tab characters1636	item := &Item{text: util.RunesToChars(runes), colors: colors}1637	length := t.displayWidth(runes)1638	if length == 0 {1639		return nil, 01640	}1641	result := Result{item: item}1642	var offsets []colorOffset1643	printFn := func(window tui.Window, limit int) {1644		if offsets == nil {1645			// tui.Col* are not initialized until renderer.Init()1646			offsets = result.colorOffsets(nil, nil, t.theme, *color, *color, t.nthAttr, 0, false)1647		}1648		for limit > 0 {1649			if length > limit {1650				trimmedRunes, _ := t.trimRight(runes, limit)1651				t.printColoredString(window, trimmedRunes, offsets, *color)1652				break1653			} else if fill {1654				t.printColoredString(window, runes, offsets, *color)1655				limit -= length1656			} else {1657				t.printColoredString(window, runes, offsets, *color)1658				break1659			}1660		}1661	}1662	return printFn, length1663}16641665// Temporarily switch 'window' so that we can use the existing windows with1666// a different window1667func (t *Terminal) withWindow(w tui.Window, f func()) {1668	prevWindow := t.window1669	if w != nil {1670		t.window = w1671	}1672	f()1673	t.window = prevWindow1674}16751676func (t *Terminal) parsePrompt(prompt string) (func(), int) {1677	var state *ansiState1678	prompt = firstLine(prompt)1679	trimmed, colors, _ := extractColor(prompt, state, nil)1680	item := &Item{text: util.ToChars([]byte(trimmed)), colors: colors}16811682	// "Prompt>  "1683	//  -------    // Do not apply ANSI attributes to the trailing whitespaces1684	//             // unless the part has a non-default ANSI state1685	loc := whiteSuffix.FindStringIndex(trimmed)1686	if loc != nil {1687		blankState := ansiOffset{[2]int32{int32(loc[0]), int32(loc[1])}, ansiState{tui.ColPrompt.Fg(), tui.ColPrompt.Bg(), -1, tui.AttrClear, -1, nil}}1688		if item.colors != nil {1689			lastColor := (*item.colors)[len(*item.colors)-1]1690			if lastColor.offset[1] < int32(loc[1]) {1691				blankState.offset[0] = lastColor.offset[1]1692				colors := append(*item.colors, blankState)1693				item.colors = &colors1694			}1695		} else {1696			colors := []ansiOffset{blankState}1697			item.colors = &colors1698		}1699	}1700	output := func() {1701		wrap := t.wrap1702		t.wrap = false1703		t.withWindow(t.inputWindow, func() {1704			preTask := func(markerClass) int {1705				return 11706			}1707			t.printHighlighted(1708				Result{item: item}, tui.ColPrompt, tui.ColPrompt, false, false, false, 0, 0, true, preTask, nil, 0)1709		})1710		t.wrap = wrap1711	}1712	_, promptLen := t.processTabsStr(trimmed, 0)17131714	return output, promptLen1715}17161717func (t *Terminal) noSeparatorLine() bool {1718	return t.inputless || noSeparatorLine(t.infoStyle, t.separatorLength() > 0)1719}17201721// Effective length of the horizontal separator. The default separator is1722// suppressed when the input section is already visually separated from the1723// list section by a border line.1724func (t *Terminal) separatorLength() int {1725	if t.separatorAuto && t.separatedByBorder() {1726		return 01727	}1728	return t.separatorLen1729}17301731// BorderLine for the input border resolves to a single line on the side1732// facing the list section1733func resolveInputBorderShape(layout layoutType, shape tui.BorderShape) tui.BorderShape {1734	if shape != tui.BorderLine {1735		return shape1736	}1737	if layout == layoutReverse {1738		return tui.BorderBottom1739	}1740	return tui.BorderTop1741}17421743// Whether the input border draws a line on the side facing the list section1744func inputBorderFacesList(layout layoutType, shape tui.BorderShape) bool {1745	shape = resolveInputBorderShape(layout, shape)1746	if layout == layoutReverse {1747		return shape.HasBottom()1748	}1749	return shape.HasTop()1750}17511752// Whether a border line is already drawn between the info line and the1753// section next to it on the list side, making the default horizontal1754// separator redundant1755func (t *Terminal) separatedByBorder() bool {1756	// The input border itself draws a line on the side facing the list section1757	if inputBorderFacesList(t.layout, t.inputBorderShape) {1758		return true1759	}1760	// A preview window at 'next' position sits right next to the input1761	// section, in front of the sections handled below1762	anyNext := false1763	for po := &t.previewOpts; po != nil; po = po.alternative {1764		if po.position == posNext {1765			anyNext = true1766			break1767		}1768	}1769	if anyNext && t.hasPreviewer() {1770		// The separator is hidden only when every spec in the threshold chain1771		// displays a preview window at 'next' position with a border line1772		// facing the input section. We cannot single out the active spec;1773		// which one is active depends on the terminal size, and the1774		// resolution (computePreviewSize in resizeWindows) itself consults1775		// noSeparatorLine. When not every spec qualifies, err on the side of1776		// showing the separator.1777		if len(t.previewOpts.command) == 0 {1778			// No preview command, so no preview window is normally shown, but1779			// the preview(...) action can still display one at any time1780			return false1781		}1782		// NOTE: resizeWindows can clear 'hidden' mid-layout when the1783		// preview(...) action forces the window, so the frame being laid out1784		// can briefly disagree with this decision until the next relayout1785		for po := &t.previewOpts; po != nil; po = po.alternative {1786			if po.position != posNext || po.hidden || po.size.size == 0 || !t.borderFacingInput(po.Border(t.layout)) {1787				return false1788			}1789		}1790		return true1791	}1792	hasHeaderLinesWindow, headerLinesShape := t.determineHeaderLinesShape()1793	hasHeaderWindow := t.hasHeaderWindow()1794	// Mirror of hasInputWindow in resizeWindows; a 'next' preview position1795	// gives the input section its own window even when no preview window is1796	// shown. A 'next' spec here implies there is no previewer (the block1797	// above returns otherwise), and without a previewer the position is1798	// resolved from the first spec alone, so a 'next' in a threshold1799	// alternative does not count.1800	hasInputWindow := t.previewOpts.position == posNext || t.inputBorderShape.Visible() || hasHeaderWindow || hasHeaderLinesWindow1801	if !hasInputWindow {1802		// The input section is embedded in the list window and no border1803		// separates the two1804		return false1805	}18061807	// The input section has its own window. Determine which section it is1808	// facing, and check if the border of that section draws a line toward it.1809	// NOTE: hasHeaderWindow can be true with no header content when the input1810	// border is visible (see Terminal.hasHeaderWindow). An empty header window1811	// takes no space, so it cannot be the facing section.1812	hasHeaderSection := hasHeaderWindow && t.visibleHeaderLines() > 01813	if hasHeaderSection && !t.headerFirst && t.headerBorderShape != tui.BorderInline {1814		// Header section is facing the input section. An inline header is1815		// excluded; it is drawn inside the list border and is covered by the1816		// branches below.1817		return t.borderFacingInput(t.headerBorderShape)1818	}1819	// Header lines section is facing the input section, except in1820	// reverse-list layout where it is on the other side of the list section,1821	// or with --header-first and no header section where it is moved past1822	// the input section1823	if hasHeaderLinesWindow && t.layout != layoutReverseList && (hasHeaderWindow || !t.headerFirst) {1824		return t.borderFacingInput(headerLinesShape)1825	}1826	// The input section sits right next to the list section1827	return t.borderFacingInput(t.listBorderShape)1828}18291830// Whether the border of the section next to the input section on the list1831// side draws a horizontal line facing the info line1832func (t *Terminal) borderFacingInput(shape tui.BorderShape) bool {1833	if shape == tui.BorderInline {1834		// Embedded between the horizontal lines of the list border1835		return true1836	}1837	if t.layout == layoutReverse {1838		return shape.HasTop()1839	}1840	return shape.HasBottom()1841}18421843func getScrollbar(perLine int, total int, height int, offset int) (int, int) {1844	if total == 0 || total*perLine <= height {1845		return 0, 01846	}1847	barLength := max(1, height*height/(total*perLine))1848	var barStart int1849	if total == height {1850		barStart = 01851	} else {1852		barStart = min(height-barLength, (height*perLine-barLength)*offset/(total*perLine-height))1853	}1854	return barLength, barStart1855}18561857func (t *Terminal) barCol() int {1858	if len(t.scrollbar) == 0 && !t.listBorderShape.HasRight() && !t.borderShape.HasRight() && !t.hasPreviewWindowOnRight() {1859		return 01860	}1861	return 11862}18631864func (t *Terminal) wrapCols() int {1865	if !t.wrap {1866		return 0 // No wrap1867	}1868	return max(t.window.Width()-(t.pointerLen+t.markerLen+t.barCol()), 1)1869}18701871func (t *Terminal) clearNumLinesCache() {1872	t.numLinesCache = make(map[int32]numLinesCacheValue)1873}18741875// Number of lines the item takes including the gap1876func (t *Terminal) numItemLines(item *Item, atMost int) (int, bool) {1877	var numLines int1878	if !t.wrap && !t.multiLine {1879		numLines = 1 + t.gap1880		return numLines, numLines > atMost1881	}1882	if cached, prs := t.numLinesCache[item.Index()]; prs {1883		// Can we use this cache? Let's be conservative.1884		if cached.atMost <= atMost {1885			return cached.numLines, false1886		}1887	}1888	var overflow bool1889	if !t.wrap && t.multiLine {1890		numLines, overflow = item.text.NumLines(atMost)1891	} else {1892		var lines [][]rune1893		lines, overflow = item.text.Lines(t.multiLine, atMost, t.wrapCols(), t.wrapSignWidth, t.tabstop, t.wrapWord)1894		numLines = len(lines)1895	}1896	numLines += t.gap1897	if !overflow {1898		t.numLinesCache[item.Index()] = numLinesCacheValue{atMost, numLines}1899	}1900	return numLines, overflow || numLines > atMost1901}19021903func (t *Terminal) itemLines(item *Item, atMost int) ([][]rune, bool) {1904	if !t.wrap && !t.multiLine {1905		text := make([]rune, item.text.Length())1906		copy(text, item.text.ToRunes())1907		return [][]rune{text}, false1908	}1909	return item.text.Lines(t.multiLine, atMost, t.wrapCols(), t.wrapSignWidth, t.tabstop, t.wrapWord)1910}19111912// Estimate the average number of lines per item. Instead of going through all1913// items, we only check a few items around the current cursor position.1914func (t *Terminal) avgNumLines() int {1915	if !t.wrap && !t.multiLine {1916		return 11917	}19181919	maxItems := t.maxItems()1920	numLines := 01921	count := 01922	total := t.merger.Length()1923	offset := max(0, min(t.offset, total-maxItems-1))1924	for idx := 0; idx < maxItems && idx+offset < total; idx++ {1925		result := t.merger.Get(idx + offset)1926		lines, _ := t.numItemLines(result.item, maxItems)1927		numLines += lines1928		count++1929	}1930	if count == 0 {1931		return 11932	}1933	return numLines / count1934}19351936func (t *Terminal) getScrollbar() (int, int) {1937	return getScrollbar(t.avgNumLines(), t.merger.Length(), t.maxItems(), t.offset)1938}19391940// Input returns current query string1941func (t *Terminal) Input() (bool, []rune) {1942	t.mutex.Lock()1943	defer t.mutex.Unlock()1944	paused := t.paused1945	src := t.input1946	if t.inputOverride != nil {1947		paused = false1948		src = *t.inputOverride1949	}1950	return paused, copySlice(src)1951}19521953// PauseRendering blocks the terminal from reading items.1954// Must be paired with ResumeRendering.1955func (t *Terminal) PauseRendering() {1956	t.mutex.Lock()1957}19581959// ResumeRendering releases the lock acquired by PauseRendering.1960func (t *Terminal) ResumeRendering() {1961	t.mutex.Unlock()1962}19631964// UpdateCount updates the count information1965func (t *Terminal) UpdateCount(cnt int, final bool, failedCommand *string) {1966	t.mutex.Lock()1967	t.count = cnt1968	if t.hasLoadActions && t.reading && final {1969		t.triggerLoad = true1970	}1971	t.reading = !final1972	t.failed = failedCommand1973	suppressed := t.suppress1974	t.mutex.Unlock()1975	t.reqBox.Set(reqInfo, nil)19761977	// We want to defer activating the interface when --sync is used and any of1978	// start, load, or result events are bound1979	if suppressed && final && !t.deferActivation() {1980		t.reqBox.Set(reqActivate, nil)1981	}1982}19831984func (t *Terminal) changeHeader(header string) bool {1985	var lines []string1986	if len(header) > 0 {1987		lines = strings.Split(strings.TrimSuffix(header, "\n"), "\n")1988	}1989	needFullRedraw := len(t.header0) != len(lines)1990	t.header0 = lines1991	t.clickHeaderLine = 01992	t.clickHeaderColumn = 01993	return needFullRedraw1994}19951996func (t *Terminal) changeFooter(footer string) bool {1997	var lines []string1998	if len(footer) > 0 {1999		lines = strings.Split(strings.TrimSuffix(footer, "\n"), "\n")2000	}

The first 2,000 of 8,876 lines.