ycdemo / fzf / src/ terminal.go

package fzf

import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"maps"
	"math"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"regexp"
	"slices"
	"sort"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"time"
	"unicode"

	"github.com/rivo/uniseg"

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

// import "github.com/pkg/profile"

/*
Placeholder regex is used to extract placeholders from fzf's template
strings. Acts as input validation for parsePlaceholder function.
Describes the syntax, but it is fairly lenient.

The following pseudo regex has been reverse engineered from the
implementation. It is overly strict, but better describes what's possible.
As such it is not useful for validation, but rather to generate test
cases for example.

	\\?(?:                                      # escaped type
	    {\+?s?f?r?RANGE(?:,RANGE)*}             # token type
	    {q[:s?RANGE]}                           # query type
	    |{\+?n?f?}                              # item type (notice no mandatory element inside brackets)
	)
	RANGE = (?:
	    (?:-?[0-9]+)?\.\.(?:-?[0-9]+)?          # ellipsis syntax for token range (x..y)
	    |-?[0-9]+                               # shorthand syntax (x..x)
	)
*/
var placeholder *regexp.Regexp
var whiteSuffix *regexp.Regexp
var offsetComponentRegex *regexp.Regexp
var offsetTrimCharsRegex *regexp.Regexp
var passThroughBeginRegex *regexp.Regexp
var passThroughEndTmuxRegex *regexp.Regexp
var sixelBeginRegex *regexp.Regexp
var cursorBackRegex *regexp.Regexp
var ttyin *os.File

var inTmux = len(os.Getenv("TMUX")) > 0

const clearCode string = "\x1b[2J"

// Number of maximum focus events to process synchronously
const maxFocusEvents = 10000

// execute-silent and transform* actions will block user input for this duration.
// After this duration, users can press CTRL-C to terminate the command.
const blockDuration = 1 * time.Second

// Skip exporting FZF_CURRENT_ITEM when the item is larger than this, so a huge
// item cannot overflow ARG_MAX and break exec for preview and other commands.
const maxCurrentItemEnvSize = 64 * 1024

func init() {
	placeholder = regexp.MustCompile(`\\?(?:{[+*sfr]*[0-9,-.]*}|{q(?::s?[0-9,-.]+)?}|{fzf:(?:query|action|prompt)}|{[+*]?f?nf?})`)
	whiteSuffix = regexp.MustCompile(`\s*

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	src/terminal.go at master · ycdemo/fzf · Sailfork
	
		
) offsetComponentRegex = regexp.MustCompile(`([+-][0-9]+)|(-?/[1-9][0-9]*)`) offsetTrimCharsRegex = regexp.MustCompile(`[^0-9/+-]`) // Parts of the preview output that should be passed through to the terminal // * https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it // * https://sw.kovidgoyal.net/kitty/graphics-protocol // * https://en.wikipedia.org/wiki/Sixel // * https://iterm2.com/documentation-images.html /* passThroughRegex = regexp.MustCompile(` \x1bPtmux;\x1b\x1b .*? [^\x1b]\x1b\\ | \x1b(_G|P[0-9;]*q) .*? \x1b\\\r? | \x1b]1337; .*? (\a|\x1b\\) `) */ passThroughBeginRegex = regexp.MustCompile(`\x1bPtmux;\x1b\x1b|\x1b(_G|P[0-9;]*q)|\x1b]1337;`) passThroughEndTmuxRegex = regexp.MustCompile(`[^\x1b]\x1b\\`) sixelBeginRegex = regexp.MustCompile(`^\x1bP[0-9;]*q`) // CUB right before an IND, used to return to the column a row started on cursorBackRegex = regexp.MustCompile(`\x1b\[([0-9]*)D src/terminal.go at master · ycdemo/fzf · Sailfork
) } type jumpMode int const ( jumpDisabled jumpMode = iota jumpEnabled jumpAcceptEnabled ) type resumableState int const ( disabledState resumableState = iota pausedState enabledState ) func (s resumableState) Enabled() bool { return s == enabledState } func (s *resumableState) Force(flag bool) { if flag { *s = enabledState } else { *s = disabledState } } func (s *resumableState) Set(flag bool) { if *s == disabledState { return } if flag { *s = enabledState } else { *s = pausedState } } type commandSpec struct { command string tempFiles []string } type quitSignal struct { code int err error } type waitState struct { blocked bool blockedAt time.Time pending []*action searching bool // a search is in progress or the input is still loading } type previewer struct { version int64 lines []string offset int scrollable bool final bool following resumableState spinner string bar []bool xw [2]int } type previewed struct { version int64 numLines int offset int filled bool image bool wipe bool wireframe bool } type eachLine struct { line string err error } type itemLine struct { valid bool firstLine int numLines int cy int current bool selected bool label string queryLen int width int hasBar bool result Result empty bool other bool hidden bool } func (t *Terminal) inListWindow() bool { return t.window != t.inputWindow && t.window != t.headerWindow && t.window != t.headerLinesWindow && t.window != t.footerWindow } func (t *Terminal) markEmptyLine(line int) { if t.inListWindow() { t.prevLines[line] = itemLine{valid: true, firstLine: line, empty: true} } } func (t *Terminal) markOtherLine(line int) { if t.inListWindow() { t.prevLines[line] = itemLine{valid: true, firstLine: line, other: true} } } type fitpad struct { fit int pad int } type labelPrinter func(tui.Window, int) type markerClass int const ( markerSingle markerClass = iota markerTop markerMiddle markerBottom ) type StatusItem struct { Index int `json:"index"` Text string `json:"text"` Positions []int `json:"positions,omitempty"` } type Status struct { Reading bool `json:"reading"` Progress int `json:"progress"` Query string `json:"query"` Position int `json:"position"` Sort bool `json:"sort"` TotalCount int `json:"totalCount"` MatchCount int `json:"matchCount"` Current *StatusItem `json:"current"` Matches []StatusItem `json:"matches"` Selected []StatusItem `json:"selected"` } type versionedCallback struct { version int64 callback func() } type runningCmd struct { cmd *exec.Cmd tempFiles []string } // Terminal represents terminal input/output type Terminal struct { initDelay time.Duration infoCommand string infoStyle infoStyle infoPrefix string wrap bool wrapWord bool wrapSign string wrapSignWidth int previewWrapSign string previewWrapSignWidth int ghost string separator labelPrinter separatorLen int separatorAuto bool spinner []string promptString string prompt func() promptLen int borderLabel labelPrinter borderLabelLen int borderLabelOpts labelOpts previewLabel labelPrinter previewLabelLen int previewLabelOpts labelOpts inputLabel labelPrinter inputLabelLen int inputLabelOpts labelOpts headerLabel labelPrinter headerLabelLen int headerLabelOpts labelOpts footerLabel labelPrinter footerLabelLen int footerLabelOpts labelOpts gutterReverse bool gutterRawReverse bool pointer string pointerLen int pointerEmpty string pointerEmptyRaw string marker string markerLen int markerEmpty string markerMultiLine [3]string queryLen [2]int layout layoutType fullscreen bool keepRight bool hscroll bool hscrollOff int scrollOff int gap int gapLine labelPrinter gapLineLen int wordRubout string wordNext string subWordRubout string subWordNext string cx int cy int offset int xoffset int yanked []rune input []rune inputOverride *[]rune pasting *[]rune multi int multiLine bool sort bool toggleSort bool track trackOption idNth []Range trackKey string trackBlocked bool trackSync bool trackKeyCache map[int32]bool wait waitState pendingSelections map[string]selectedItem targetIndex int32 delimiter Delimiter expect map[tui.Event]string keymap map[tui.Event][]*action keymapOrg map[tui.Event][]*action pressed string printQueue []string printQuery bool history *History cycle bool highlightLine bool headerVisible bool headerFirst bool headerLines int header []Item header0 []string footer []string ellipsis string scrollbar string previewScrollbar string ansi bool freezeLeft int freezeRight int nthAttr tui.Attr nth []Range nthCurrent []Range withNthDefault string withNthExpr string withNthEnabled bool acceptNth func([]Token, int32) string tabstop int margin [4]sizeSpec padding [4]sizeSpec unicode bool listenAddr *listenAddress listenPort *int listener net.Listener listenUnsafe bool borderShape tui.BorderShape listBorderShape tui.BorderShape inputBorderShape tui.BorderShape headerBorderShape tui.BorderShape headerLinesShape tui.BorderShape footerBorderShape tui.BorderShape listLabel labelPrinter listLabelLen int listLabelOpts labelOpts cleanExit bool executor *util.Executor paused bool inputless bool border tui.Window window tui.Window inputWindow tui.Window inputBorder tui.Window headerWindow tui.Window headerBorder tui.Window headerLinesWindow tui.Window headerLinesBorder tui.Window footerWindow tui.Window footerBorder tui.Window wborder tui.Window pborder tui.Window pwindow tui.Window borderWidth int count int progress int hasStartActions bool hasResultActions bool hasFocusActions bool hasLoadActions bool hasResizeActions bool triggerLoad bool pendingReqList bool filterSelection bool reading bool running *util.AtomicBool failed *string jumping jumpMode jumpLabels string printer func(string) printsep string merger *Merger passMerger *Merger resultMerger *Merger matchMap map[int32]Result selected map[int32]selectedItem version int64 revision revision bgVersion int64 runningCmds *util.ConcurrentSet[*runningCmd] reqBox *util.EventBox initialPreviewOpts previewOpts previewOpts previewOpts activePreviewOpts *previewOpts previewer previewer previewed previewed previewBox *util.EventBox eventBox *util.EventBox mutex sync.Mutex uiMutex sync.Mutex initFunc func() error prevLines []itemLine suppress bool startChan chan fitpad killChan chan bool killedChan chan bool serverInputChan chan []*action callbackChan chan versionedCallback bgQueue map[action][]func(bool) bgSemaphore chan struct{} bgSemaphores map[action]chan struct{} keyChan chan tui.Event eventChan chan tui.Event timerChan chan tui.Event slab *util.Slab theme *tui.ColorTheme tui tui.Renderer ttyDefault string ttyin *os.File executing *util.AtomicBool termSize tui.TermSize lastAction actionType lastKey string lastFocus focusedItem areaLines int areaColumns int forcePreview bool clickHeaderLine int clickHeaderColumn int clickFooterLine int clickFooterColumn int proxyScript string setNativeLabel func(string) numLinesCache map[int32]numLinesCacheValue raw bool lastActivity time.Time } type numLinesCacheValue struct { atMost int numLines int } type selectedItem struct { at time.Time item *Item } type focusedItem struct { major int // revision.major; changes on reload item *Item } type byTimeOrder []selectedItem func (a byTimeOrder) Len() int { return len(a) } func (a byTimeOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byTimeOrder) Less(i, j int) bool { return a[i].at.Before(a[j].at) } // EventTypes are listed in the order of their priority. const ( reqResize util.EventType = iota reqReinit reqFullRedraw reqRedraw reqJump reqPrompt reqInfo reqHeader reqFooter reqList reqRedrawInputLabel reqRedrawHeaderLabel reqRedrawFooterLabel reqRedrawListLabel reqRedrawBorderLabel reqRedrawPreviewLabel reqPreviewReady reqPreviewEnqueue reqPreviewDisplay reqPreviewRefresh reqPreviewDelayed reqActivate reqClose reqPrintQuery reqBecome reqQuit reqFatal ) func isTerminalEvent(et util.EventType) bool { switch et { case reqClose, reqPrintQuery, reqBecome, reqQuit, reqFatal: return true } return false } type action struct { t actionType a string } //go:generate stringer -type=actionType type actionType int const ( actIgnore actionType = iota actStart actClick actInvalid actBracketedPasteBegin actBracketedPasteEnd actChar actMouse actBeginningOfLine actAbort actAccept actAcceptNonEmpty actAcceptOrPrintQuery actBackwardChar actBackwardDeleteChar actBackwardDeleteCharEof actBackwardWord actBackwardSubWord actCancel actChangeBorderLabel actChangeGhost actChangeHeader actChangeHeaderLines actChangeFooter actChangeHeaderLabel actChangeFooterLabel actChangeInfoCommand actChangeInputLabel actChangeListLabel actChangeMulti actChangeNth actChangeWithNth actChangePointer actChangePreview actChangePreviewLabel actChangePreviewWindow actChangePrompt actChangeQuery actClearScreen actClearQuery actClearSelection actClose actDeleteChar actDeleteCharEof actEndOfLine actFatal actForwardChar actForwardWord actForwardSubWord actKillLine actKillWord actKillSubWord actUnixLineDiscard actUnixWordRubout actYank actBackwardKillWord actBackwardKillSubWord actSelectAll actDeselectAll actToggle actToggleSearch actToggleAll actToggleDown actToggleUp actToggleIn actToggleOut actToggleTrack actToggleTrackCurrent actToggleHeader actToggleWrap actToggleWrapWord actToggleMultiLine actToggleHscroll actToggleRaw actEnableRaw actDisableRaw actTrackCurrent actToggleInput actHideInput actShowInput actUntrackCurrent actDown actDownMatch actUp actUpMatch actPageUp actPageDown actPosition actHalfPageUp actHalfPageDown actOffsetUp actOffsetDown actOffsetMiddle actJump actJumpAccept // XXX Deprecated in favor of jump:accept binding actPrintQuery // XXX Deprecated (not very useful, just use --print-query) actRefreshPreview actReplaceQuery actToggleSort actShowPreview actHidePreview actTogglePreview actTogglePreviewWrap actTogglePreviewWrapWord actTransform actTransformBorderLabel actTransformGhost actTransformHeader actTransformHeaderLines actTransformFooter actTransformHeaderLabel actTransformFooterLabel actTransformInfoCommand actTransformInputLabel actTransformListLabel actTransformNth actTransformWithNth actTransformPointer actTransformPreviewLabel actTransformPrompt actTransformQuery actTransformSearch actTrigger actBgTransform actBgTransformBorderLabel actBgTransformGhost actBgTransformHeader actBgTransformHeaderLines actBgTransformFooter actBgTransformHeaderLabel actBgTransformFooterLabel actBgTransformInfoCommand actBgTransformInputLabel actBgTransformListLabel actBgTransformNth actBgTransformWithNth actBgTransformPointer actBgTransformPreviewLabel actBgTransformPrompt actBgTransformQuery actBgTransformSearch actBgCancel actSearch actPreview actPreviewTop actPreviewBottom actPreviewUp actPreviewDown actPreviewPageUp actPreviewPageDown actPreviewHalfPageUp actPreviewHalfPageDown actPrevHistory actPrevSelected actPrint actPut actNextHistory actNextSelected actExecute actExecuteSilent actExecuteMulti // Deprecated actSigStop actBest actFirst actLast actReload actReloadSync actDisableSearch actEnableSearch actSelect actDeselect actUnbind actRebind actToggleBind actBecome actShowHeader actHideHeader actBell actExclude actExcludeMulti actAsync actWait ) func (a actionType) Name() string { return util.ToKebabCase(a.String()[3:]) } func processExecution(action actionType) bool { switch action { case actTransform, actTransformBorderLabel, actTransformGhost, actTransformHeader, actTransformHeaderLines, actTransformFooter, actTransformHeaderLabel, actTransformFooterLabel, actTransformInfoCommand, actTransformInputLabel, actTransformListLabel, actTransformNth, actTransformWithNth, actTransformPointer, actTransformPreviewLabel, actTransformPrompt, actTransformQuery, actTransformSearch, actBgTransform, actBgTransformBorderLabel, actBgTransformGhost, actBgTransformHeader, actBgTransformHeaderLines, actBgTransformFooter, actBgTransformHeaderLabel, actBgTransformFooterLabel, actBgTransformInfoCommand, actBgTransformInputLabel, actBgTransformListLabel, actBgTransformNth, actBgTransformWithNth, actBgTransformPointer, actBgTransformPreviewLabel, actBgTransformPrompt, actBgTransformQuery, actBgTransformSearch, actPreview, actChangePreview, actChangeInfoCommand, actRefreshPreview, actExecute, actExecuteSilent, actExecuteMulti, actReload, actReloadSync, actBecome: return true } return false } type placeholderFlags struct { plus bool asterisk bool preserveSpace bool number bool forceUpdate bool file bool raw bool } type withNthSpec struct { fn func([]Token, int32) string // nil = clear (restore original) } type searchRequest struct { sort bool sync bool nth *[]Range withNth *withNthSpec headerLines *int command *commandSpec environ []string changed bool denylist []int32 revision revision } type previewRequest struct { template string scrollOffset int list [3][]*Item // current, select, and all matched items env []string query string } type previewResult struct { version int64 lines []string offset int spinner string } func toActions(types ...actionType) []*action { actions := make([]*action, len(types)) for idx, t := range types { actions[idx] = &action{t: t, a: ""} } return actions } func defaultKeymap() map[tui.Event][]*action { keymap := make(map[tui.Event][]*action) add := func(e tui.EventType, a actionType) { keymap[e.AsEvent()] = toActions(a) } addEvent := func(e tui.Event, a actionType) { keymap[e] = toActions(a) } add(tui.Fatal, actFatal) add(tui.Invalid, actInvalid) add(tui.BracketedPasteBegin, actBracketedPasteBegin) add(tui.BracketedPasteEnd, actBracketedPasteEnd) add(tui.CtrlA, actBeginningOfLine) add(tui.CtrlB, actBackwardChar) add(tui.CtrlC, actAbort) add(tui.CtrlG, actAbort) add(tui.CtrlQ, actAbort) add(tui.Esc, actAbort) add(tui.CtrlD, actDeleteCharEof) add(tui.CtrlE, actEndOfLine) add(tui.CtrlF, actForwardChar) add(tui.Backspace, actBackwardDeleteChar) add(tui.CtrlBackspace, actBackwardDeleteChar) add(tui.Tab, actToggleDown) add(tui.ShiftTab, actToggleUp) add(tui.CtrlJ, actDown) add(tui.CtrlK, actUp) add(tui.CtrlL, actClearScreen) add(tui.Enter, actAccept) add(tui.CtrlN, actDownMatch) add(tui.CtrlP, actUpMatch) add(tui.AltDown, actDownMatch) add(tui.AltUp, actUpMatch) add(tui.CtrlU, actUnixLineDiscard) add(tui.CtrlW, actUnixWordRubout) add(tui.CtrlY, actYank) if !util.IsWindows() { add(tui.CtrlZ, actSigStop) } add(tui.CtrlSlash, actToggleWrapWord) addEvent(tui.AltKey('/'), actToggleWrapWord) addEvent(tui.AltKey('b'), actBackwardWord) add(tui.ShiftLeft, actBackwardWord) add(tui.AltLeft, actBackwardWord) addEvent(tui.AltKey('f'), actForwardWord) add(tui.ShiftRight, actForwardWord) add(tui.AltRight, actForwardWord) addEvent(tui.AltKey('d'), actKillWord) add(tui.AltBackspace, actBackwardKillWord) add(tui.Up, actUp) add(tui.Down, actDown) add(tui.Left, actBackwardChar) add(tui.Right, actForwardChar) add(tui.Home, actBeginningOfLine) add(tui.End, actEndOfLine) add(tui.Delete, actDeleteChar) add(tui.PageUp, actPageUp) add(tui.PageDown, actPageDown) add(tui.ShiftUp, actPreviewUp) add(tui.ShiftDown, actPreviewDown) add(tui.Mouse, actMouse) add(tui.LeftClick, actClick) add(tui.RightClick, actToggle) add(tui.SLeftClick, actToggle) add(tui.SRightClick, actToggle) add(tui.ScrollUp, actUp) add(tui.ScrollDown, actDown) keymap[tui.SScrollUp.AsEvent()] = toActions(actToggle, actUp) keymap[tui.SScrollDown.AsEvent()] = toActions(actToggle, actDown) add(tui.PreviewScrollUp, actPreviewUp) add(tui.PreviewScrollDown, actPreviewDown) return keymap } func trimQuery(query string) []rune { return []rune(strings.ReplaceAll(query, "\t", " ")) } func mayTriggerPreview(opts *Options) bool { if opts.ListenAddr != nil { return true } for _, actions := range opts.Keymap { for _, action := range actions { switch action.t { case actPreview, actChangePreview, actTransform, actBgTransform: return true } } } return false } func makeSpinner(unicode bool) []string { if unicode { return []string{`⠋`, `⠙`, `⠹`, `⠸`, `⠼`, `⠴`, `⠦`, `⠧`, `⠇`, `⠏`} } return []string{`-`, `\`, `|`, `/`, `-`, `\`, `|`, `/`} } func evaluateHeight(opts *Options, termHeight int) int { size := opts.Height.size if opts.Height.percent { if opts.Height.inverse { size = 100 - size } return max(int(size*float64(termHeight)/100.0), opts.MinHeight) } if opts.Height.inverse { size = float64(termHeight) - size } return int(size) } // NewTerminal returns new Terminal object func NewTerminal(opts *Options, eventBox *util.EventBox, executor *util.Executor) (*Terminal, error) { input := trimQuery(opts.Query) var delay time.Duration if opts.Sync { delay = 0 } else if opts.Tac { delay = initialDelayTac } else { delay = initialDelay } var previewBox *util.EventBox // We need to start the previewer even when --preview option is not specified // * if HTTP server is enabled // * if 'preview' or 'change-preview' action is bound to a key // * if 'transform' action is bound to a key if len(opts.Preview.command) > 0 || mayTriggerPreview(opts) { previewBox = util.NewEventBox() } var renderer tui.Renderer fullscreen := !opts.Height.auto && (opts.Height.size == 0 || opts.Height.percent && opts.Height.size == 100) var err error // Reuse ttyin if available to avoid having multiple file descriptors open // when you run fzf multiple times in your Go program. Closing it is known to // cause problems with 'become' action and invalid terminal state after exit. if ttyin == nil { if ttyin, err = tui.TtyIn(opts.TtyDefault); err != nil { return nil, err } } if fullscreen { if tui.HasFullscreenRenderer() { renderer = tui.NewFullscreenRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop) } else { renderer, err = tui.NewLightRenderer(opts.TtyDefault, ttyin, opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit, true, func(h int) int { return h }) } } else { maxHeightFunc := func(termHeight int) int { // Minimum height required to render fzf excluding margin and padding effectiveMinHeight := minHeight if previewBox != nil && opts.Preview.aboveOrBelow() { effectiveMinHeight += 1 + borderLines(opts.Preview.Border(opts.Layout)) } if opts.noSeparatorLine() { effectiveMinHeight-- } effectiveMinHeight += borderLines(opts.BorderShape) return min(termHeight, max(evaluateHeight(opts, termHeight), effectiveMinHeight)) } renderer, err = tui.NewLightRenderer(opts.TtyDefault, ttyin, opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit, false, maxHeightFunc) } if err != nil { return nil, err } if opts.Inputless { renderer.HideCursor() } wordRubout := "[^\\pL\\pN][\\pL\\pN]" wordNext := "[\\pL\\pN][^\\pL\\pN]|(.$)" subWordRubout := "[a-z][A-Z]|[^\\pL\\pN][\\pL\\pN]" subWordNext := "[a-z][A-Z]|[\\pL\\pN][^\\pL\\pN]|(.$)" if opts.FileWord { sep := regexp.QuoteMeta(string(os.PathSeparator)) wordRubout = fmt.Sprintf("%s[^%s]", sep, sep) wordNext = fmt.Sprintf("[^%s]%s|(.$)", sep, sep) } keymapCopy := maps.Clone(opts.Keymap) em := EmptyMerger(revision{}) t := Terminal{ initDelay: delay, infoCommand: opts.InfoCommand, infoStyle: opts.InfoStyle, infoPrefix: opts.InfoPrefix, ghost: opts.Ghost, separator: nil, spinner: makeSpinner(opts.Unicode), promptString: opts.Prompt, queryLen: [2]int{0, 0}, layout: opts.Layout, fullscreen: fullscreen, keepRight: opts.KeepRight, hscroll: opts.Hscroll, hscrollOff: opts.HscrollOff, scrollOff: opts.ScrollOff, pointer: *opts.Pointer, pointerLen: uniseg.StringWidth(*opts.Pointer), marker: *opts.Marker, markerLen: uniseg.StringWidth(*opts.Marker), markerMultiLine: *opts.MarkerMulti, wordRubout: wordRubout, wordNext: wordNext, subWordRubout: subWordRubout, subWordNext: subWordNext, cx: len(input), cy: 0, offset: 0, xoffset: 0, yanked: []rune{}, input: input, multi: opts.Multi, multiLine: opts.ReadZero && opts.MultiLine, wrap: opts.Wrap, wrapWord: opts.WrapWord, sort: opts.Sort > 0, toggleSort: opts.ToggleSort, track: opts.Track, idNth: opts.IdNth, targetIndex: minItem.Index(), delimiter: opts.Delimiter, expect: opts.Expect, keymap: opts.Keymap, keymapOrg: keymapCopy, pressed: "", printQuery: opts.PrintQuery, history: opts.History, margin: opts.Margin, padding: opts.Padding, unicode: opts.Unicode, listenAddr: opts.ListenAddr, listenUnsafe: opts.Unsafe, borderShape: opts.BorderShape, listBorderShape: opts.ListBorderShape, inputBorderShape: opts.InputBorderShape, headerBorderShape: opts.HeaderBorderShape, headerLinesShape: opts.HeaderLinesShape, footerBorderShape: opts.FooterBorderShape, borderWidth: 1, listLabel: nil, listLabelOpts: opts.ListLabel, borderLabel: nil, borderLabelOpts: opts.BorderLabel, previewLabel: nil, previewLabelOpts: opts.PreviewLabel, inputLabel: nil, inputLabelOpts: opts.InputLabel, headerLabel: nil, headerLabelOpts: opts.HeaderLabel, footerLabel: nil, footerLabelOpts: opts.FooterLabel, cleanExit: opts.ClearOnExit, executor: executor, paused: opts.Phony, inputless: opts.Inputless, cycle: opts.Cycle, highlightLine: opts.CursorLine, headerVisible: true, headerFirst: opts.HeaderFirst, headerLines: opts.HeaderLines, gap: opts.Gap, header: []Item{}, footer: opts.Footer, header0: opts.Header, ansi: opts.Ansi, freezeLeft: opts.FreezeLeft, freezeRight: opts.FreezeRight, nthAttr: opts.Theme.Nth.Attr, nth: opts.Nth, nthCurrent: opts.Nth, withNthDefault: opts.WithNthExpr, withNthExpr: opts.WithNthExpr, withNthEnabled: opts.WithNth != nil, tabstop: opts.Tabstop, raw: opts.Raw, hasStartActions: false, hasResultActions: false, hasFocusActions: false, hasLoadActions: false, triggerLoad: false, reading: true, running: util.NewAtomicBool(true), failed: nil, jumping: jumpDisabled, jumpLabels: opts.JumpLabels, printer: opts.Printer, printsep: opts.PrintSep, proxyScript: opts.ProxyScript, setNativeLabel: nativeLabelSetter(), merger: em, passMerger: em, resultMerger: em, matchMap: make(map[int32]Result), selected: make(map[int32]selectedItem), runningCmds: util.NewConcurrentSet[*runningCmd](), reqBox: util.NewEventBox(), initialPreviewOpts: opts.Preview, previewOpts: opts.Preview, activePreviewOpts: &opts.Preview, previewer: previewer{0, []string{}, 0, false, true, disabledState, "", []bool{}, [2]int{0, 0}}, previewed: previewed{0, 0, 0, false, false, false, false}, previewBox: previewBox, eventBox: eventBox, mutex: sync.Mutex{}, uiMutex: sync.Mutex{}, suppress: true, slab: util.MakeSlab(slab16Size, slab32Size), theme: opts.Theme, startChan: make(chan fitpad, 1), killChan: make(chan bool), killedChan: make(chan bool), serverInputChan: make(chan []*action, 100), callbackChan: make(chan versionedCallback, maxBgProcesses), bgQueue: make(map[action][]func(bool)), bgSemaphore: make(chan struct{}, maxBgProcesses), bgSemaphores: make(map[action]chan struct{}), keyChan: make(chan tui.Event), eventChan: make(chan tui.Event, 7), // start | (load + result + result-final + zero|one) | (focus) | (resize) timerChan: make(chan tui.Event), // unbuffered: every() ticks coalesce when main loop is busy tui: renderer, ttyDefault: opts.TtyDefault, ttyin: ttyin, initFunc: func() error { return renderer.Init() }, executing: util.NewAtomicBool(false), lastAction: actStart, lastFocus: focusedItem{}, lastActivity: time.Now(), numLinesCache: make(map[int32]numLinesCacheValue), // The initial load counts as a search in progress ('start:wait'). // Set before the reader starts so the first final result clears it. wait: waitState{searching: true}} if opts.AcceptNth != nil { t.acceptNth = opts.AcceptNth(t.delimiter) } baseTheme := opts.BaseTheme if baseTheme == nil { baseTheme = renderer.DefaultTheme() } // If the list border can't host an inline separator, the runtime later coerces // BorderInline to BorderLine. Mirror that here so theme color inheritance matches // the final rendering rather than the user's requested shape. inlineListSupported := opts.ListBorderShape.HasTop() && opts.ListBorderShape.HasBottom() headerInline := inlineListSupported && (opts.HeaderBorderShape == tui.BorderInline || opts.HeaderLinesShape == tui.BorderInline) footerInline := inlineListSupported && opts.FooterBorderShape == tui.BorderInline hasHeader := opts.HeaderBorderShape.Visible() || opts.HeaderLinesShape.Visible() // This should be called before accessing tui.Color* tui.InitTheme(opts.Theme, baseTheme, opts.Bold, opts.Black, opts.InputBorderShape.Visible(), hasHeader, headerInline, footerInline) // Gutter character var gutterChar, gutterRawChar string if opts.Gutter != nil { gutterChar = *opts.Gutter } else if t.unicode { gutterChar = "▌" } else { gutterChar = " " t.gutterReverse = true } if opts.GutterRaw != nil { gutterRawChar = *opts.GutterRaw } else if t.unicode { gutterRawChar = "▖" } else { gutterRawChar = ":" t.gutterRawReverse = false } t.prompt, t.promptLen = t.parsePrompt(opts.Prompt) // Pre-calculated empty pointer and marker signs if t.pointerLen == 0 { t.pointerEmpty = "" t.pointerEmptyRaw = "" } else { t.pointerEmpty = gutterChar + strings.Repeat(" ", max(0, t.pointerLen-1)) t.pointerEmptyRaw = gutterRawChar + strings.Repeat(" ", max(0, t.pointerLen-1)) } t.markerEmpty = strings.Repeat(" ", t.markerLen) // Labels t.listLabel, t.listLabelLen = t.ansiLabelPrinter(opts.ListLabel.label, &tui.ColListLabel, false) t.borderLabel, t.borderLabelLen = t.ansiLabelPrinter(opts.BorderLabel.label, &tui.ColBorderLabel, false) t.previewLabel, t.previewLabelLen = t.ansiLabelPrinter(opts.PreviewLabel.label, &tui.ColPreviewLabel, false) t.inputLabel, t.inputLabelLen = t.ansiLabelPrinter(opts.InputLabel.label, &tui.ColInputLabel, false) t.headerLabel, t.headerLabelLen = t.ansiLabelPrinter(opts.HeaderLabel.label, &tui.ColHeaderLabel, false) t.footerLabel, t.footerLabelLen = t.ansiLabelPrinter(opts.FooterLabel.label, &tui.ColFooterLabel, false) // Determine border shape if t.borderShape == tui.BorderLine { if t.fullscreen { t.borderShape = tui.BorderNone } else { t.borderShape = tui.BorderTop } } // Determine input border shape t.inputBorderShape = resolveInputBorderShape(t.layout, t.inputBorderShape) // Inline borders are embedded between the list's top and bottom horizontals. // Shapes missing either one (none/phantom/line/single-sided) fall back to a plain // horizontal separator (same as BorderLine). inlineSupported := t.listBorderShape.HasTop() && t.listBorderShape.HasBottom() if !inlineSupported { if t.headerBorderShape == tui.BorderInline { t.headerBorderShape = tui.BorderLine } if t.headerLinesShape == tui.BorderInline { t.headerLinesShape = tui.BorderLine } if t.footerBorderShape == tui.BorderInline { t.footerBorderShape = tui.BorderLine } } // Determine header border shape if t.headerBorderShape == tui.BorderLine { if t.layout == layoutReverse { t.headerBorderShape = tui.BorderBottom } else { t.headerBorderShape = tui.BorderTop } } // Determine header lines border shape if t.headerLinesShape == tui.BorderLine { if t.layout == layoutDefault { t.headerLinesShape = tui.BorderTop } else { t.headerLinesShape = tui.BorderBottom } } // Determine footer border shape if t.footerBorderShape == tui.BorderLine { if t.layout == layoutReverse { t.footerBorderShape = tui.BorderTop } else { t.footerBorderShape = tui.BorderBottom } } // The default separator can be suppressed at runtime depending on the // window layout (see separatorLength) t.separatorAuto = opts.Separator == nil bar := "─" if opts.Separator != nil { bar = *opts.Separator } else if !t.unicode { bar = "-" } if len(bar) > 0 { t.separator, t.separatorLen = t.ansiLabelPrinter(bar, &tui.ColSeparator, true) } // Gap line if t.gap > 0 && len(*opts.GapLine) > 0 { t.gapLine, t.gapLineLen = t.ansiLabelPrinter(*opts.GapLine, &tui.ColGapLine, true) } if opts.Ellipsis != nil { t.ellipsis = *opts.Ellipsis } else if t.unicode { t.ellipsis = "··" } else { t.ellipsis = ".." } if t.unicode { t.wrapSign = "↳ " t.borderWidth = uniseg.StringWidth("│") } else { t.wrapSign = "> " } if opts.WrapSign != nil { t.wrapSign = *opts.WrapSign } t.wrapSign, t.wrapSignWidth = t.processTabsStr(t.wrapSign, 0) t.previewWrapSign = t.wrapSign t.previewWrapSignWidth = t.wrapSignWidth if opts.PreviewWrapSign != nil { t.previewWrapSign, t.previewWrapSignWidth = t.processTabsStr(*opts.PreviewWrapSign, 0) } if opts.Scrollbar == nil { if t.unicode && t.borderWidth == 1 { t.scrollbar = "│" } else { t.scrollbar = "|" } t.previewScrollbar = t.scrollbar } else { runes := []rune(*opts.Scrollbar) if len(runes) > 0 { t.scrollbar = string(runes[0]) t.previewScrollbar = t.scrollbar if len(runes) > 1 { t.previewScrollbar = string(runes[1]) } } } var resizeActions []*action resizeActions, t.hasResizeActions = t.keymap[tui.Resize.AsEvent()] if t.tui.ShouldEmitResizeEvent() { t.keymap[tui.Resize.AsEvent()] = append(toActions(actClearScreen), resizeActions...) } _, t.hasStartActions = t.keymap[tui.Start.AsEvent()] _, t.hasResultActions = t.keymap[tui.Result.AsEvent()] if _, prs := t.keymap[tui.ResultFinal.AsEvent()]; prs { t.hasResultActions = true } _, t.hasFocusActions = t.keymap[tui.Focus.AsEvent()] _, t.hasLoadActions = t.keymap[tui.Load.AsEvent()] if t.listenAddr != nil { listener, port, err := startHttpServer(*t.listenAddr, t.serverInputChan, t.dumpStatus) if err != nil { return nil, err } t.listener = listener if port > 0 { t.listenPort = &port } } if t.hasStartActions { t.eventChan <- tui.Start.AsEvent() } return &t, nil } func (t *Terminal) deferActivation() bool { return t.initDelay == 0 && (t.hasStartActions || t.hasLoadActions || t.hasResultActions || t.hasFocusActions) } func (t *Terminal) environ() []string { return t.environImpl(false) } func (t *Terminal) environForPreview() []string { return t.environImpl(true) } func (t *Terminal) environImpl(forPreview bool) []string { env := os.Environ() if t.listenAddr != nil && len(t.listenAddr.sock) > 0 { env = append(env, "FZF_SOCK="+t.listenAddr.sock) } if t.listenPort != nil { env = append(env, fmt.Sprintf("FZF_PORT=%d", *t.listenPort)) } env = append(env, "FZF_QUERY="+string(t.input)) env = append(env, "FZF_ACTION="+t.lastAction.Name()) env = append(env, "FZF_KEY="+t.lastKey) idleMs := time.Since(t.lastActivity).Milliseconds() env = append(env, fmt.Sprintf("FZF_IDLE_TIME=%d", idleMs/1000)) env = append(env, fmt.Sprintf("FZF_IDLE_TIME_MS=%d", idleMs)) env = append(env, "FZF_PROMPT="+string(t.promptString)) env = append(env, "FZF_GHOST="+string(t.ghost)) env = append(env, "FZF_POINTER="+string(t.pointer)) env = append(env, "FZF_PREVIEW_LABEL="+t.previewLabelOpts.label) env = append(env, "FZF_BORDER_LABEL="+t.borderLabelOpts.label) env = append(env, "FZF_LIST_LABEL="+t.listLabelOpts.label) env = append(env, "FZF_INPUT_LABEL="+t.inputLabelOpts.label) env = append(env, "FZF_HEADER_LABEL="+t.headerLabelOpts.label) direction := "down" if t.layout == layoutDefault { direction = "up" } env = append(env, "FZF_DIRECTION="+direction) if len(t.nthCurrent) > 0 { env = append(env, "FZF_NTH="+RangesToString(t.nthCurrent)) } if len(t.withNthExpr) > 0 { env = append(env, "FZF_WITH_NTH="+t.withNthExpr) } if t.raw { val := "0" if t.isCurrentItemMatch() { val = "1" } env = append(env, "FZF_RAW="+val) } inputState := "enabled" if t.inputless { inputState = "hidden" } else if t.paused { inputState = "disabled" } if t.wrap { if t.wrapWord { env = append(env, "FZF_WRAP=word") } else { env = append(env, "FZF_WRAP=char") } } env = append(env, "FZF_INPUT_STATE="+inputState) env = append(env, fmt.Sprintf("FZF_TOTAL_COUNT=%d", t.count)) env = append(env, fmt.Sprintf("FZF_MATCH_COUNT=%d", t.resultMerger.Length())) env = append(env, fmt.Sprintf("FZF_SELECT_COUNT=%d", len(t.selected))) env = append(env, fmt.Sprintf("FZF_LINES=%d", t.areaLines)) env = append(env, fmt.Sprintf("FZF_COLUMNS=%d", t.areaColumns)) env = append(env, fmt.Sprintf("FZF_POS=%d", min(t.merger.Length(), t.cy+1))) if item := t.currentItem(); item != nil { // Skip if the value contains a NUL byte (exec(2) would reject the env) // or is too large (a huge item can overflow ARG_MAX and break exec // entirely for preview and other child commands). if s := item.AsString(t.ansi); !strings.ContainsRune(s, 0) && len(s) <= maxCurrentItemEnvSize { env = append(env, "FZF_CURRENT_ITEM="+s) } } env = append(env, fmt.Sprintf("FZF_CLICK_HEADER_LINE=%d", t.clickHeaderLine)) env = append(env, fmt.Sprintf("FZF_CLICK_HEADER_COLUMN=%d", t.clickHeaderColumn)) env = append(env, fmt.Sprintf("FZF_CLICK_FOOTER_LINE=%d", t.clickFooterLine)) env = append(env, fmt.Sprintf("FZF_CLICK_FOOTER_COLUMN=%d", t.clickFooterColumn)) env = t.addClickHeaderWord(env) env = t.addClickFooterWord(env) // Add preview environment variables if preview is enabled pwindowSize := t.pwindowSize() if pwindowSize.Lines > 0 { lines := fmt.Sprintf("LINES=%d", pwindowSize.Lines) columns := fmt.Sprintf("COLUMNS=%d", pwindowSize.Columns) if forPreview { env = append(env, lines) env = append(env, columns) } env = append(env, "FZF_PREVIEW_"+lines) env = append(env, "FZF_PREVIEW_"+columns) env = append(env, fmt.Sprintf("FZF_PREVIEW_TOP=%d", t.tui.Top()+t.pwindow.Top())) env = append(env, fmt.Sprintf("FZF_PREVIEW_LEFT=%d", t.pwindow.Left())) } return env } func borderLines(shape tui.BorderShape) int { lines := 0 if shape.HasTop() { lines++ } if shape.HasBottom() { lines++ } return lines } func borderColumns(shape tui.BorderShape, borderWidth int) int { columns := 0 if shape.HasLeft() { columns += 1 + borderWidth } if shape.HasRight() { columns += 1 + borderWidth } return columns } func (t *Terminal) visibleHeaderLines() int { if !t.headerVisible { return 0 } return len(t.header0) + t.headerLines } func (t *Terminal) visibleHeaderLinesInList() int { if t.headerWindow != nil || t.headerLinesWindow != nil { return 0 } return t.visibleHeaderLines() } func (t *Terminal) visibleInputLinesInList() int { if t.inputWindow != nil || t.inputless { return 0 } if t.noSeparatorLine() { return 1 } return 2 } // Extra number of lines needed to display fzf func (t *Terminal) extraLines() int { // borderLines() reports zero for BorderInline, but addInline() still // reserves a divider line for it sectionLines := func(shape tui.BorderShape) int { if shape == tui.BorderInline { return 1 } return borderLines(shape) } extra := 0 if !t.inputless { extra++ if !t.noSeparatorLine() { extra++ } if t.inputBorderShape.Visible() { extra += borderLines(t.inputBorderShape) } } if t.listBorderShape.Visible() { extra += borderLines(t.listBorderShape) } if t.headerVisible { if t.hasHeaderWindow() { extra += sectionLines(t.headerBorderShape) } extra += len(t.header0) if w, shape := t.determineHeaderLinesShape(); w { extra += sectionLines(shape) } extra += t.headerLines } if len(t.footer) > 0 { extra += sectionLines(t.footerBorderShape) extra += len(t.footer) } return extra } func (t *Terminal) MaxFitAndPad() (int, int) { _, screenHeight, marginInt, paddingInt := t.adjustMarginAndPadding() padHeight := marginInt[0] + marginInt[2] + paddingInt[0] + paddingInt[2] fit := screenHeight - padHeight - t.extraLines() return fit, padHeight } func (t *Terminal) ansiLabelPrinter(str string, color *tui.ColorPair, fill bool) (labelPrinter, int) { // Nothing to do if len(str) == 0 { return nil, 0 } // Extract ANSI color codes str = firstLine(str) text, colors, _ := extractColor(str, nil, nil) runes := []rune(text) // Simpler printer for strings without ANSI colors or tab characters if colors == nil && !strings.ContainsRune(text, '\t') { length := util.StringWidth(text) if length == 0 { return nil, 0 } printFn := func(window tui.Window, limit int) { ellipsis := []rune{} ellipsisWidth := 0 if !fill { ellipsis, ellipsisWidth = util.Truncate(t.ellipsis, limit) } if length > limit { trimmedRunes, _ := t.trimRight(runes, limit-ellipsisWidth) window.CPrint(*color, string(trimmedRunes)+string(ellipsis)) } else if fill { window.CPrint(*color, util.RepeatToFill(text, length, limit)) } else { window.CPrint(*color, text) } } return printFn, length } // Printer that correctly handles ANSI color codes and tab characters item := &Item{text: util.RunesToChars(runes), colors: colors} length := t.displayWidth(runes) if length == 0 { return nil, 0 } result := Result{item: item} var offsets []colorOffset printFn := func(window tui.Window, limit int) { if offsets == nil { // tui.Col* are not initialized until renderer.Init() offsets = result.colorOffsets(nil, nil, t.theme, *color, *color, t.nthAttr, 0, false) } for limit > 0 { if length > limit { trimmedRunes, _ := t.trimRight(runes, limit) t.printColoredString(window, trimmedRunes, offsets, *color) break } else if fill { t.printColoredString(window, runes, offsets, *color) limit -= length } else { t.printColoredString(window, runes, offsets, *color) break } } } return printFn, length } // Temporarily switch 'window' so that we can use the existing windows with // a different window func (t *Terminal) withWindow(w tui.Window, f func()) { prevWindow := t.window if w != nil { t.window = w } f() t.window = prevWindow } func (t *Terminal) parsePrompt(prompt string) (func(), int) { var state *ansiState prompt = firstLine(prompt) trimmed, colors, _ := extractColor(prompt, state, nil) item := &Item{text: util.ToChars([]byte(trimmed)), colors: colors} // "Prompt> " // ------- // Do not apply ANSI attributes to the trailing whitespaces // // unless the part has a non-default ANSI state loc := whiteSuffix.FindStringIndex(trimmed) if loc != nil { blankState := ansiOffset{[2]int32{int32(loc[0]), int32(loc[1])}, ansiState{tui.ColPrompt.Fg(), tui.ColPrompt.Bg(), -1, tui.AttrClear, -1, nil}} if item.colors != nil { lastColor := (*item.colors)[len(*item.colors)-1] if lastColor.offset[1] < int32(loc[1]) { blankState.offset[0] = lastColor.offset[1] colors := append(*item.colors, blankState) item.colors = &colors } } else { colors := []ansiOffset{blankState} item.colors = &colors } } output := func() { wrap := t.wrap t.wrap = false t.withWindow(t.inputWindow, func() { preTask := func(markerClass) int { return 1 } t.printHighlighted( Result{item: item}, tui.ColPrompt, tui.ColPrompt, false, false, false, 0, 0, true, preTask, nil, 0) }) t.wrap = wrap } _, promptLen := t.processTabsStr(trimmed, 0) return output, promptLen } func (t *Terminal) noSeparatorLine() bool { return t.inputless || noSeparatorLine(t.infoStyle, t.separatorLength() > 0) } // Effective length of the horizontal separator. The default separator is // suppressed when the input section is already visually separated from the // list section by a border line. func (t *Terminal) separatorLength() int { if t.separatorAuto && t.separatedByBorder() { return 0 } return t.separatorLen } // BorderLine for the input border resolves to a single line on the side // facing the list section func resolveInputBorderShape(layout layoutType, shape tui.BorderShape) tui.BorderShape { if shape != tui.BorderLine { return shape } if layout == layoutReverse { return tui.BorderBottom } return tui.BorderTop } // Whether the input border draws a line on the side facing the list section func inputBorderFacesList(layout layoutType, shape tui.BorderShape) bool { shape = resolveInputBorderShape(layout, shape) if layout == layoutReverse { return shape.HasBottom() } return shape.HasTop() } // Whether a border line is already drawn between the info line and the // section next to it on the list side, making the default horizontal // separator redundant func (t *Terminal) separatedByBorder() bool { // The input border itself draws a line on the side facing the list section if inputBorderFacesList(t.layout, t.inputBorderShape) { return true } // A preview window at 'next' position sits right next to the input // section, in front of the sections handled below anyNext := false for po := &t.previewOpts; po != nil; po = po.alternative { if po.position == posNext { anyNext = true break } } if anyNext && t.hasPreviewer() { // The separator is hidden only when every spec in the threshold chain // displays a preview window at 'next' position with a border line // facing the input section. We cannot single out the active spec; // which one is active depends on the terminal size, and the // resolution (computePreviewSize in resizeWindows) itself consults // noSeparatorLine. When not every spec qualifies, err on the side of // showing the separator. if len(t.previewOpts.command) == 0 { // No preview command, so no preview window is normally shown, but // the preview(...) action can still display one at any time return false } // NOTE: resizeWindows can clear 'hidden' mid-layout when the // preview(...) action forces the window, so the frame being laid out // can briefly disagree with this decision until the next relayout for po := &t.previewOpts; po != nil; po = po.alternative { if po.position != posNext || po.hidden || po.size.size == 0 || !t.borderFacingInput(po.Border(t.layout)) { return false } } return true } hasHeaderLinesWindow, headerLinesShape := t.determineHeaderLinesShape() hasHeaderWindow := t.hasHeaderWindow() // Mirror of hasInputWindow in resizeWindows; a 'next' preview position // gives the input section its own window even when no preview window is // shown. A 'next' spec here implies there is no previewer (the block // above returns otherwise), and without a previewer the position is // resolved from the first spec alone, so a 'next' in a threshold // alternative does not count. hasInputWindow := t.previewOpts.position == posNext || t.inputBorderShape.Visible() || hasHeaderWindow || hasHeaderLinesWindow if !hasInputWindow { // The input section is embedded in the list window and no border // separates the two return false } // The input section has its own window. Determine which section it is // facing, and check if the border of that section draws a line toward it. // NOTE: hasHeaderWindow can be true with no header content when the input // border is visible (see Terminal.hasHeaderWindow). An empty header window // takes no space, so it cannot be the facing section. hasHeaderSection := hasHeaderWindow && t.visibleHeaderLines() > 0 if hasHeaderSection && !t.headerFirst && t.headerBorderShape != tui.BorderInline { // Header section is facing the input section. An inline header is // excluded; it is drawn inside the list border and is covered by the // branches below. return t.borderFacingInput(t.headerBorderShape) } // Header lines section is facing the input section, except in // reverse-list layout where it is on the other side of the list section, // or with --header-first and no header section where it is moved past // the input section if hasHeaderLinesWindow && t.layout != layoutReverseList && (hasHeaderWindow || !t.headerFirst) { return t.borderFacingInput(headerLinesShape) } // The input section sits right next to the list section return t.borderFacingInput(t.listBorderShape) } // Whether the border of the section next to the input section on the list // side draws a horizontal line facing the info line func (t *Terminal) borderFacingInput(shape tui.BorderShape) bool { if shape == tui.BorderInline { // Embedded between the horizontal lines of the list border return true } if t.layout == layoutReverse { return shape.HasTop() } return shape.HasBottom() } func getScrollbar(perLine int, total int, height int, offset int) (int, int) { if total == 0 || total*perLine <= height { return 0, 0 } barLength := max(1, height*height/(total*perLine)) var barStart int if total == height { barStart = 0 } else { barStart = min(height-barLength, (height*perLine-barLength)*offset/(total*perLine-height)) } return barLength, barStart } func (t *Terminal) barCol() int { if len(t.scrollbar) == 0 && !t.listBorderShape.HasRight() && !t.borderShape.HasRight() && !t.hasPreviewWindowOnRight() { return 0 } return 1 } func (t *Terminal) wrapCols() int { if !t.wrap { return 0 // No wrap } return max(t.window.Width()-(t.pointerLen+t.markerLen+t.barCol()), 1) } func (t *Terminal) clearNumLinesCache() { t.numLinesCache = make(map[int32]numLinesCacheValue) } // Number of lines the item takes including the gap func (t *Terminal) numItemLines(item *Item, atMost int) (int, bool) { var numLines int if !t.wrap && !t.multiLine { numLines = 1 + t.gap return numLines, numLines > atMost } if cached, prs := t.numLinesCache[item.Index()]; prs { // Can we use this cache? Let's be conservative. if cached.atMost <= atMost { return cached.numLines, false } } var overflow bool if !t.wrap && t.multiLine { numLines, overflow = item.text.NumLines(atMost) } else { var lines [][]rune lines, overflow = item.text.Lines(t.multiLine, atMost, t.wrapCols(), t.wrapSignWidth, t.tabstop, t.wrapWord) numLines = len(lines) } numLines += t.gap if !overflow { t.numLinesCache[item.Index()] = numLinesCacheValue{atMost, numLines} } return numLines, overflow || numLines > atMost } func (t *Terminal) itemLines(item *Item, atMost int) ([][]rune, bool) { if !t.wrap && !t.multiLine { text := make([]rune, item.text.Length()) copy(text, item.text.ToRunes()) return [][]rune{text}, false } return item.text.Lines(t.multiLine, atMost, t.wrapCols(), t.wrapSignWidth, t.tabstop, t.wrapWord) } // Estimate the average number of lines per item. Instead of going through all // items, we only check a few items around the current cursor position. func (t *Terminal) avgNumLines() int { if !t.wrap && !t.multiLine { return 1 } maxItems := t.maxItems() numLines := 0 count := 0 total := t.merger.Length() offset := max(0, min(t.offset, total-maxItems-1)) for idx := 0; idx < maxItems && idx+offset < total; idx++ { result := t.merger.Get(idx + offset) lines, _ := t.numItemLines(result.item, maxItems) numLines += lines count++ } if count == 0 { return 1 } return numLines / count } func (t *Terminal) getScrollbar() (int, int) { return getScrollbar(t.avgNumLines(), t.merger.Length(), t.maxItems(), t.offset) } // Input returns current query string func (t *Terminal) Input() (bool, []rune) { t.mutex.Lock() defer t.mutex.Unlock() paused := t.paused src := t.input if t.inputOverride != nil { paused = false src = *t.inputOverride } return paused, copySlice(src) } // PauseRendering blocks the terminal from reading items. // Must be paired with ResumeRendering. func (t *Terminal) PauseRendering() { t.mutex.Lock() } // ResumeRendering releases the lock acquired by PauseRendering. func (t *Terminal) ResumeRendering() { t.mutex.Unlock() } // UpdateCount updates the count information func (t *Terminal) UpdateCount(cnt int, final bool, failedCommand *string) { t.mutex.Lock() t.count = cnt if t.hasLoadActions && t.reading && final { t.triggerLoad = true } t.reading = !final t.failed = failedCommand suppressed := t.suppress t.mutex.Unlock() t.reqBox.Set(reqInfo, nil) // We want to defer activating the interface when --sync is used and any of // start, load, or result events are bound if suppressed && final && !t.deferActivation() { t.reqBox.Set(reqActivate, nil) } } func (t *Terminal) changeHeader(header string) bool { var lines []string if len(header) > 0 { lines = strings.Split(strings.TrimSuffix(header, "\n"), "\n") } needFullRedraw := len(t.header0) != len(lines) t.header0 = lines t.clickHeaderLine = 0 t.clickHeaderColumn = 0 return needFullRedraw } func (t *Terminal) changeFooter(footer string) bool { var lines []string if len(footer) > 0 { lines = strings.Split(strings.TrimSuffix(footer, "\n"), "\n") } needFullRedraw := len(t.footer) != len(lines) t.footer = lines t.clickFooterLine = 0 t.clickFooterColumn = 0 return needFullRedraw } // UpdateHeader updates the header func (t *Terminal) UpdateHeader(header []Item) { t.mutex.Lock() // Pad to t.headerLines so that click coordinate mapping works correctly if len(header) < t.headerLines { padded := make([]Item, t.headerLines) copy(padded, header) header = padded } t.header = header t.mutex.Unlock() t.reqBox.Set(reqHeader, nil) } // UpdateProgress updates the search progress func (t *Terminal) UpdateProgress(progress float32) { t.mutex.Lock() newProgress := int(progress * 100) changed := t.progress != newProgress t.progress = newProgress t.mutex.Unlock() if changed { t.reqBox.Set(reqInfo, nil) } } // UpdateList updates Merger to display the list func (t *Terminal) UpdateList(result MatchResult) { merger := result.merger t.mutex.Lock() waitWasBlocked := t.wait.blocked wakeUp := false if result.final() { t.wait.searching = false // If waiting, unblock so main loop can execute pending actions. // Note: any final result unblocks the wait, not just the one for the // search that armed it. Back-to-back searches (--listen, bg-transform // callbacks, reload+wait) can therefore unblock early and run the // pending actions on the previous result set. Accepted; a per-search // generation token through the matcher isn't worth the complexity. if t.wait.blocked { t.unblockWait() wakeUp = len(t.wait.pending) > 0 } } prevIndex := minItem.Index() newRevision := merger.Revision() if t.revision.compatible(newRevision) && t.track != trackDisabled { if t.merger.Length() > 0 { prevIndex = t.currentIndex() } else if merger.Length() > 0 { prevIndex = merger.First().item.Index() } } if t.targetIndex != minItem.Index() { prevIndex = t.targetIndex t.targetIndex = minItem.Index() } if result.final() { t.progress = 100 } t.merger = merger t.resultMerger = merger t.passMerger = result.passMerger if t.raw { t.merger = result.passMerger t.matchMap = t.resultMerger.ToMap() } else { t.merger = result.merger t.matchMap = make(map[int32]Result) } if t.revision != newRevision { if !t.revision.compatible(newRevision) { // Reloaded: capture selection keys for restoration, then clear (reload-sync only) if t.trackSync && len(t.idNth) > 0 && t.multi > 0 && len(t.selected) > 0 { t.pendingSelections = make(map[string]selectedItem, len(t.selected)) for _, sel := range t.selected { key := t.trackKeyFor(sel.item, t.idNth) t.pendingSelections[key] = sel } } t.selected = make(map[int32]selectedItem) t.clearNumLinesCache() } else { // Trimmed by --tail: filter selection by index filtered := make(map[int32]selectedItem) minIndex := merger.minIndex maxIndex := merger.maxIndex for k, v := range t.selected { var included bool if maxIndex > minIndex { included = k >= minIndex && k < maxIndex } else if maxIndex < minIndex { // int32 overflow [==> <==] included = k >= minIndex || k < maxIndex } if included { filtered[k] = v } } t.selected = filtered } t.revision = newRevision t.version++ // Filter out selections that no longer match after with-nth change. // Must be inside the revision check so we don't consume the flag // on a stale EvtSearchFin from a previous search. if t.filterSelection && t.multi > 0 && len(t.selected) > 0 { matchMap := t.resultMerger.ToMap() filtered := make(map[int32]selectedItem) for k, v := range t.selected { if _, matched := matchMap[k]; matched { filtered[k] = v } } t.selected = filtered } t.filterSelection = false } if t.triggerLoad { t.triggerLoad = false t.pendingReqList = true t.eventChan <- tui.Load.AsEvent() } // Search for the tracked item by nth key // - reload (async): search eagerly, unblock as soon as match is found // - reload-sync: wait until stream is complete before searching trackWasBlocked := t.trackBlocked if len(t.trackKey) > 0 && (!t.trackSync || !t.reading) { found := false for i := 0; i < t.merger.Length(); i++ { item := t.merger.Get(i).item idx := item.Index() match, ok := t.trackKeyCache[idx] if !ok { match = t.trackKeyFor(item, t.idNth) == t.trackKey t.trackKeyCache[idx] = match } if match { t.cy = i if t.track.Current() { t.track.index = idx } found = true break } } if found || !t.reading { t.unblockTrack() } } else if prevIndex >= 0 { pos := t.cy - t.offset count := t.merger.Length() i := t.merger.FindIndex(prevIndex) if i >= 0 { t.cy = i t.offset = t.cy - pos } else if t.track.Current() { t.track = trackDisabled t.cy = pos t.offset = 0 } else if t.cy > count { // Try to keep the vertical position when the list shrinks t.cy = count - min(count, t.maxItems()) + pos } } // Restore selections by id-nth key after reload completes if !t.reading && t.pendingSelections != nil { for i := 0; i < t.merger.Length() && len(t.pendingSelections) > 0; i++ { item := t.merger.Get(i).item key := t.trackKeyFor(item, t.idNth) if sel, found := t.pendingSelections[key]; found { t.selected[item.Index()] = selectedItem{sel.at, item} delete(t.pendingSelections, key) } } t.pendingSelections = nil } needActivation := false if !t.reading { switch t.resultMerger.Length() { case 0: zero := tui.Zero.AsEvent() if _, prs := t.keymap[zero]; prs { t.pendingReqList = true t.eventChan <- zero } // --sync, only 'focus' is bound, but no items to focus needActivation = t.suppress && !t.hasResultActions && !t.hasLoadActions && t.hasFocusActions case 1: one := tui.One.AsEvent() if _, prs := t.keymap[one]; prs { t.pendingReqList = true t.eventChan <- one } } } if t.hasResultActions { result := tui.Result.AsEvent() if _, prs := t.keymap[result]; prs { t.pendingReqList = true t.eventChan <- result } if !t.reading { resultFinal := tui.ResultFinal.AsEvent() if _, prs := t.keymap[resultFinal]; prs { t.pendingReqList = true t.eventChan <- resultFinal } } } updateList := !t.trackBlocked && !t.pendingReqList updatePrompt := (trackWasBlocked && !t.trackBlocked) || (waitWasBlocked && !t.wait.blocked) t.mutex.Unlock() // Wake up the main loop to execute pending actions after wait unblocks. // Send from a goroutine; UpdateList runs inside the event box callback, // and an inline send on a full channel would deadlock with the main loop // blocking on eventBox.Set while trying to drain the channel. if wakeUp { go func() { t.serverInputChan <- []*action{{t: actIgnore}} }() } t.reqBox.Set(reqInfo, nil) if updateList { t.reqBox.Set(reqList, nil) } if updatePrompt { t.reqBox.Set(reqPrompt, nil) } if needActivation { t.reqBox.Set(reqActivate, nil) } } func (t *Terminal) output() bool { if t.printQuery { t.printer(string(t.input)) } if len(t.expect) > 0 { t.printer(t.pressed) } for _, s := range t.printQueue { t.printer(s) } transform := func(item *Item) string { return item.AsString(t.ansi) } if t.acceptNth != nil { transform = func(item *Item) string { return item.acceptNth(t.ansi, t.delimiter, t.acceptNth) } } found := len(t.selected) > 0 if !found { current := t.currentItem() if current != nil { t.printer(transform(current)) found = true } } else { for _, sel := range t.sortSelected() { t.printer(transform(sel.item)) } } return found } func (t *Terminal) sortSelected() []selectedItem { sels := make([]selectedItem, 0, len(t.selected)) for _, sel := range t.selected { sels = append(sels, sel) } sort.Sort(byTimeOrder(sels)) return sels } func (t *Terminal) displayWidth(runes []rune) int { width, _ := util.RunesWidth(runes, 0, t.tabstop, math.MaxInt32) return width } func (t *Terminal) displayWidthWithPrefix(str string, prefixWidth int) int { width, _ := util.RunesWidth([]rune(str), prefixWidth, t.tabstop, math.MaxInt32) return width } // displayWidthWithoutEscapes is displayWidthWithPrefix for a string that may // still carry pass-throughs and ANSI codes, neither of which take any column. func (t *Terminal) displayWidthWithoutEscapes(str string, prefixWidth int) int { _, text := extractPassThroughs(str) stripped, _, _ := extractColor(text, nil, nil) return t.displayWidthWithPrefix(stripped, prefixWidth) } const ( minWidth = 4 minHeight = 3 ) func calculateSize(base int, size sizeSpec, occupied int, minSize int) int { max := base - occupied if max < minSize { max = minSize } if size.percent { return util.Constrain(int(float64(base)*0.01*size.size), minSize, max) } return util.Constrain(int(size.size)+minSize-1, minSize, max) } func (t *Terminal) minPreviewSize(opts *previewOpts) (int, int) { border := opts.Border(t.layout) minPreviewWidth := 1 + borderColumns(border, t.borderWidth) minPreviewHeight := 1 + borderLines(border) switch opts.position { case posLeft, posRight: if len(t.scrollbar) > 0 && !border.HasRight() { // Need a column to show scrollbar minPreviewWidth++ } }