Skip to content
Myr

tui.go

This file

Path

src/tui/tui.go

1,527 lines · 37.3 KiB · Go

Last changed by

Add result-final eventJunegunn Choibefore adoption5dd698b

History of this file

Take it

1package tui23import (4	"strconv"5	"strings"6	"time"7	"unicode"89	"github.com/junegunn/fzf/src/util"10	"github.com/rivo/uniseg"11)1213type Attr int321415const (16	AttrUndefined = Attr(0)17	AttrRegular   = Attr(1 << 8)18	AttrClear     = Attr(1 << 9)19	BoldForce     = Attr(1 << 10)20	FullBg        = Attr(1 << 11)21	Strip         = Attr(1 << 12)2223	// Underline style stored in bits 13-15 (3 bits, values 0-4)24	// Only meaningful when the Underline attribute bit is also set.25	// 0 = solid (default)26	UnderlineStyleShift = 1327	UnderlineStyleMask  = Attr(0b111 << UnderlineStyleShift)28	UlStyleDouble       = Attr(0b001 << UnderlineStyleShift)29	UlStyleCurly        = Attr(0b010 << UnderlineStyleShift)30	UlStyleDotted       = Attr(0b011 << UnderlineStyleShift)31	UlStyleDashed       = Attr(0b100 << UnderlineStyleShift)32)3334func (a Attr) UnderlineStyle() Attr {35	return a & UnderlineStyleMask36}3738func (a Attr) Merge(b Attr) Attr {39	if b&AttrRegular > 0 {40		// Only keep bold attribute set by the system41		return (b &^ AttrRegular) | (a & BoldForce)42	}4344	merged := (a &^ AttrRegular) | b45	// When b sets Underline, use b's underline style instead of OR'ing46	if b&Underline > 0 {47		merged = (merged &^ UnderlineStyleMask) | (b & UnderlineStyleMask)48	}49	return merged50}5152// Types of user action53//54//go:generate stringer -type=EventType55type EventType int5657const (58	Rune EventType = iota5960	CtrlA61	CtrlB62	CtrlC63	CtrlD64	CtrlE65	CtrlF66	CtrlG67	CtrlH68	Tab69	CtrlJ70	CtrlK71	CtrlL72	Enter73	CtrlN74	CtrlO75	CtrlP76	CtrlQ77	CtrlR78	CtrlS79	CtrlT80	CtrlU81	CtrlV82	CtrlW83	CtrlX84	CtrlY85	CtrlZ86	Esc87	CtrlSpace8889	// https://apple.stackexchange.com/questions/24261/how-do-i-send-c-that-is-control-slash-to-the-terminal90	CtrlBackSlash91	CtrlRightBracket92	CtrlCaret93	CtrlSlash9495	ShiftTab96	Backspace9798	Delete99	PageUp100	PageDown101102	Up103	Down104	Left105	Right106	Home107	End108	Insert109110	ShiftUp111	ShiftDown112	ShiftLeft113	ShiftRight114	ShiftDelete115	ShiftHome116	ShiftEnd117	ShiftPageUp118	ShiftPageDown119120	F1121	F2122	F3123	F4124	F5125	F6126	F7127	F8128	F9129	F10130	F11131	F12132133	AltBackspace134135	AltUp136	AltDown137	AltLeft138	AltRight139	AltDelete140	AltHome141	AltEnd142	AltPageUp143	AltPageDown144145	AltShiftUp146	AltShiftDown147	AltShiftLeft148	AltShiftRight149	AltShiftDelete150	AltShiftHome151	AltShiftEnd152	AltShiftPageUp153	AltShiftPageDown154155	CtrlUp156	CtrlDown157	CtrlLeft158	CtrlRight159	CtrlHome160	CtrlEnd161	CtrlBackspace162	CtrlDelete163	CtrlPageUp164	CtrlPageDown165166	Alt167	CtrlAlt168169	CtrlAltUp170	CtrlAltDown171	CtrlAltLeft172	CtrlAltRight173	CtrlAltHome174	CtrlAltEnd175	CtrlAltBackspace176	CtrlAltDelete177	CtrlAltPageUp178	CtrlAltPageDown179180	CtrlShiftUp181	CtrlShiftDown182	CtrlShiftLeft183	CtrlShiftRight184	CtrlShiftHome185	CtrlShiftEnd186	CtrlShiftDelete187	CtrlShiftPageUp188	CtrlShiftPageDown189190	CtrlAltShiftUp191	CtrlAltShiftDown192	CtrlAltShiftLeft193	CtrlAltShiftRight194	CtrlAltShiftHome195	CtrlAltShiftEnd196	CtrlAltShiftDelete197	CtrlAltShiftPageUp198	CtrlAltShiftPageDown199200	Mouse201	DoubleClick202	LeftClick203	RightClick204	SLeftClick205	SRightClick206	ScrollUp207	ScrollDown208	SScrollUp209	SScrollDown210	PreviewScrollUp211	PreviewScrollDown212213	// Synthetic / non-user events. Everything from Invalid onward is214	// either internally generated or a state-change notification, not215	// direct user input. Use `>= Invalid` to gate activity tracking.216	// BracketedPasteBegin/End sit here too: they enclose user input217	// (which arrives as Rune events) and should not appear in FZF_KEY.218	Invalid219	Fatal220	BracketedPasteBegin221	BracketedPasteEnd222	Resize223	Change224	BackwardEOF225	Start226	Load227	Focus228	One229	Zero230	Result231	Jump232	JumpCancel233	ClickHeader234	ClickFooter235	Multi236	Every237	ResultFinal238)239240func (t EventType) AsEvent() Event {241	return Event{t, 0, nil}242}243244func (t EventType) Int() int {245	return int(t)246}247248func (t EventType) Byte() byte {249	return byte(t)250}251252func (e Event) Comparable() Event {253	// Ignore MouseEvent pointer254	return Event{e.Type, e.Char, nil}255}256257// Printable returns true if the event is a printable character that can be258// inserted into the query (e.g. via the 'put' action).259func (e Event) Printable() bool {260	return e.Type == Rune && unicode.IsGraphic(e.Char)261}262263func (e Event) KeyName() string {264	if me := e.MouseEvent; me != nil {265		return me.Name()266	}267268	if e.Type >= Invalid {269		return ""270	}271272	switch e.Type {273	case Rune:274		if e.Char == ' ' {275			return "space"276		}277		return string(e.Char)278	case Alt:279		return "alt-" + string(e.Char)280	case CtrlAlt:281		return "ctrl-alt-" + string(e.Char)282	case CtrlBackSlash:283		return "ctrl-\\"284	case CtrlRightBracket:285		return "ctrl-]"286	case CtrlCaret:287		return "ctrl-^"288	case CtrlSlash:289		return "ctrl-/"290	}291292	return util.ToKebabCase(e.Type.String())293}294295func Key(r rune) Event {296	return Event{Rune, r, nil}297}298299func AltKey(r rune) Event {300	return Event{Alt, r, nil}301}302303func CtrlAltKey(r rune) Event {304	return Event{CtrlAlt, r, nil}305}306307const (308	doubleClickDuration = 500 * time.Millisecond309)310311type Color int32312313func (c Color) IsDefault() bool {314	return c == colDefault315}316317func (c Color) is24() bool {318	return c > 0 && (c&(1<<24)) > 0319}320321type ColorAttr struct {322	Color Color323	Attr  Attr324}325326func (a ColorAttr) IsColorDefined() bool {327	return a.Color != colUndefined328}329330func (a ColorAttr) IsAttrDefined() bool {331	return a.Attr&^BoldForce != AttrUndefined332}333334func (a ColorAttr) IsUndefined() bool {335	return !a.IsColorDefined() && !a.IsAttrDefined()336}337338func NewColorAttr() ColorAttr {339	return ColorAttr{Color: colUndefined, Attr: AttrUndefined}340}341342func (a ColorAttr) Merge(other ColorAttr) ColorAttr {343	if other.Color != colUndefined {344		a.Color = other.Color345	}346	if other.Attr != AttrUndefined {347		a.Attr = a.Attr.Merge(other.Attr)348	}349	return a350}351352const (353	colUndefined Color = -2354	colDefault   Color = -1355)356357const (358	colBlack Color = iota359	colRed360	colGreen361	colYellow362	colBlue363	colMagenta364	colCyan365	colWhite366	colGrey367	colBrightRed368	colBrightGreen369	colBrightYellow370	colBrightBlue371	colBrightMagenta372	colBrightCyan373	colBrightWhite374)375376type FillReturn int377378const (379	FillContinue FillReturn = iota380	FillNextLine381	FillSuspend382)383384type ColorPair struct {385	fg   Color386	bg   Color387	ul   Color388	attr Attr389}390391func HexToColor(rrggbb string) Color {392	r, _ := strconv.ParseInt(rrggbb[1:3], 16, 0)393	g, _ := strconv.ParseInt(rrggbb[3:5], 16, 0)394	b, _ := strconv.ParseInt(rrggbb[5:7], 16, 0)395	return Color((1 << 24) + (r << 16) + (g << 8) + b)396}397398func NewColorPair(fg Color, bg Color, attr Attr) ColorPair {399	return ColorPair{fg, bg, colDefault, attr}400}401402func NoColorPair() ColorPair {403	return ColorPair{-1, -1, -1, 0}404}405406func (p ColorPair) Fg() Color {407	return p.fg408}409410func (p ColorPair) Bg() Color {411	return p.bg412}413414func (p ColorPair) Ul() Color {415	return p.ul416}417418func (p ColorPair) WithUl(ul Color) ColorPair {419	dup := p420	dup.ul = ul421	return dup422}423424func (p ColorPair) Attr() Attr {425	return p.attr426}427428func (p ColorPair) IsFullBgMarker() bool {429	return p.attr&FullBg > 0430}431432func (p ColorPair) ShouldStripColors() bool {433	return p.attr&Strip > 0434}435436func (p ColorPair) HasBg() bool {437	return p.attr&Reverse == 0 && p.bg != colDefault ||438		p.attr&Reverse > 0 && p.fg != colDefault439}440441func (p ColorPair) merge(other ColorPair, except Color) ColorPair {442	dup := p443	dup.attr = dup.attr.Merge(other.attr)444	if other.fg != except {445		dup.fg = other.fg446	}447	if other.bg != except {448		dup.bg = other.bg449	}450	if other.ul != except {451		dup.ul = other.ul452	}453	return dup454}455456func (p ColorPair) WithAttr(attr Attr) ColorPair {457	dup := p458	dup.attr = dup.attr.Merge(attr)459	return dup460}461462func (p ColorPair) WithNewAttr(attr Attr) ColorPair {463	dup := p464	dup.attr = attr465	return dup466}467468func (p ColorPair) WithFg(fg ColorAttr) ColorPair {469	dup := p470	fgPair := ColorPair{fg.Color, colUndefined, colUndefined, fg.Attr}471	return dup.Merge(fgPair)472}473474func (p ColorPair) WithBg(bg ColorAttr) ColorPair {475	dup := p476	bgPair := ColorPair{colUndefined, bg.Color, colUndefined, bg.Attr}477	return dup.Merge(bgPair)478}479480func (p ColorPair) MergeAttr(other ColorPair) ColorPair {481	return p.WithAttr(other.attr)482}483484func (p ColorPair) Merge(other ColorPair) ColorPair {485	return p.merge(other, colUndefined)486}487488func (p ColorPair) MergeNonDefault(other ColorPair) ColorPair {489	return p.merge(other, colDefault)490}491492type ColorTheme struct {493	Colored          bool494	Input            ColorAttr495	Ghost            ColorAttr496	Disabled         ColorAttr497	Fg               ColorAttr498	Bg               ColorAttr499	ListFg           ColorAttr500	ListBg           ColorAttr501	AltBg            ColorAttr502	Nth              ColorAttr503	Nomatch          ColorAttr504	SelectedFg       ColorAttr505	SelectedBg       ColorAttr506	SelectedMatch    ColorAttr507	PreviewFg        ColorAttr508	PreviewBg        ColorAttr509	DarkBg           ColorAttr510	Gutter           ColorAttr511	AltGutter        ColorAttr512	Prompt           ColorAttr513	InputBg          ColorAttr514	InputBorder      ColorAttr515	InputLabel       ColorAttr516	Match            ColorAttr517	Current          ColorAttr518	CurrentMatch     ColorAttr519	Spinner          ColorAttr520	Info             ColorAttr521	Pointer          ColorAttr522	Marker           ColorAttr523	Header           ColorAttr524	HeaderBg         ColorAttr525	HeaderBorder     ColorAttr526	HeaderLabel      ColorAttr527	Footer           ColorAttr528	FooterBg         ColorAttr529	FooterBorder     ColorAttr530	FooterLabel      ColorAttr531	Separator        ColorAttr532	Scrollbar        ColorAttr533	Border           ColorAttr534	PreviewBorder    ColorAttr535	PreviewLabel     ColorAttr536	PreviewScrollbar ColorAttr537	BorderLabel      ColorAttr538	ListLabel        ColorAttr539	ListBorder       ColorAttr540	GapLine          ColorAttr541	NthCurrentAttr   Attr // raw current-fg attr (before fg merge) for nth overlay542	NthSelectedAttr  Attr // raw selected-fg attr (before ListFg inherit) for nth overlay543}544545type Event struct {546	Type       EventType547	Char       rune548	MouseEvent *MouseEvent549}550551type MouseEvent struct {552	Y      int553	X      int554	S      int555	Left   bool556	Down   bool557	Double bool558	Ctrl   bool559	Alt    bool560	Shift  bool561}562563func (e MouseEvent) Mod() bool {564	return e.Ctrl || e.Alt || e.Shift565}566567func (e MouseEvent) Name() string {568	name := ""569	if e.Down {570		return name571	}572573	if e.Ctrl {574		name += "ctrl-"575	}576	if e.Alt {577		name += "alt-"578	}579	if e.Shift {580		name += "shift-"581	}582	if e.Double {583		name += "double-"584	}585	if !e.Left {586		name += "right-"587	}588	return name + "click"589}590591type BorderShape int592593const (594	BorderUndefined BorderShape = iota595	BorderLine596	BorderNone597	BorderPhantom598	BorderRounded599	BorderSharp600	BorderBold601	BorderBlock602	BorderThinBlock603	BorderDouble604	BorderHorizontal605	BorderVertical606	BorderTop607	BorderBottom608	BorderLeft609	BorderRight610	BorderInline611	BorderDashed612)613614func (s BorderShape) HasLeft() bool {615	switch s {616	case BorderNone, BorderPhantom, BorderLine, BorderInline, BorderRight, BorderTop, BorderBottom, BorderHorizontal: // No Left617		return false618	}619	return true620}621622func (s BorderShape) HasRight() bool {623	switch s {624	case BorderNone, BorderPhantom, BorderLine, BorderInline, BorderLeft, BorderTop, BorderBottom, BorderHorizontal: // No right625		return false626	}627	return true628}629630func (s BorderShape) HasTop() bool {631	switch s {632	case BorderNone, BorderPhantom, BorderLine, BorderInline, BorderLeft, BorderRight, BorderBottom, BorderVertical: // No top633		return false634	}635	return true636}637638func (s BorderShape) HasBottom() bool {639	switch s {640	case BorderNone, BorderPhantom, BorderLine, BorderInline, BorderLeft, BorderRight, BorderTop, BorderVertical: // No bottom641		return false642	}643	return true644}645646func (s BorderShape) Visible() bool {647	return s != BorderNone648}649650type BorderStyle struct {651	shape       BorderShape652	top         rune653	bottom      rune654	left        rune655	right       rune656	topLeft     rune657	topRight    rune658	bottomLeft  rune659	bottomRight rune660	leftMid     rune661	rightMid    rune662}663664type BorderCharacter int665666func MakeBorderStyle(shape BorderShape, unicode bool) BorderStyle {667	if shape == BorderNone || shape == BorderPhantom {668		return BorderStyle{669			shape:       BorderNone,670			top:         ' ',671			bottom:      ' ',672			left:        ' ',673			right:       ' ',674			topLeft:     ' ',675			topRight:    ' ',676			bottomLeft:  ' ',677			bottomRight: ' ',678			leftMid:     ' ',679			rightMid:    ' '}680	}681	if !unicode {682		return BorderStyle{683			shape:       shape,684			top:         '-',685			bottom:      '-',686			left:        '|',687			right:       '|',688			topLeft:     '+',689			topRight:    '+',690			bottomLeft:  '+',691			bottomRight: '+',692			leftMid:     '+',693			rightMid:    '+',694		}695	}696	switch shape {697	case BorderSharp:698		return BorderStyle{699			shape:       shape,700			top:         '─',701			bottom:      '─',702			left:        '│',703			right:       '│',704			topLeft:     '┌',705			topRight:    '┐',706			bottomLeft:  '└',707			bottomRight: '┘',708			leftMid:     '├',709			rightMid:    '┤',710		}711	case BorderBold:712		return BorderStyle{713			shape:       shape,714			top:         '━',715			bottom:      '━',716			left:        '┃',717			right:       '┃',718			topLeft:     '┏',719			topRight:    '┓',720			bottomLeft:  '┗',721			bottomRight: '┛',722			leftMid:     '┣',723			rightMid:    '┫',724		}725	case BorderBlock:726		// ▛▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▜727		// ▌                  ▐728		// ▙▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▟729		return BorderStyle{730			shape:       shape,731			top:         '▀',732			bottom:      '▄',733			left:        '▌',734			right:       '▐',735			topLeft:     '▛',736			topRight:    '▜',737			bottomLeft:  '▙',738			bottomRight: '▟',739			leftMid:     '▌',740			rightMid:    '▐',741		}742743	case BorderThinBlock:744		// 🭽▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔🭾745		// ▏                  ▕746		// 🭼▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁🭿747		return BorderStyle{748			shape:       shape,749			top:         '▔',750			bottom:      '▁',751			left:        '▏',752			right:       '▕',753			topLeft:     '🭽',754			topRight:    '🭾',755			bottomLeft:  '🭼',756			bottomRight: '🭿',757			leftMid:     '▏',758			rightMid:    '▕',759		}760761	case BorderDouble:762		return BorderStyle{763			shape:       shape,764			top:         '═',765			bottom:      '═',766			left:        '║',767			right:       '║',768			topLeft:     '╔',769			topRight:    '╗',770			bottomLeft:  '╚',771			bottomRight: '╝',772			leftMid:     '╠',773			rightMid:    '╣',774		}775	case BorderDashed:776		// Terminal cells are taller than wide (~2:1), so horizontals can use a777		// sparse stub per cell while verticals need more dashes per cell to look778		// evenly dashed. Rounded corners and sharp T-junction mids.779		return BorderStyle{780			shape:       shape,781			top:         '╶',782			bottom:      '╶',783			left:        '┆',784			right:       '┆',785			topLeft:     '╭',786			topRight:    '╮',787			bottomLeft:  '╰',788			bottomRight: '╯',789			leftMid:     '├',790			rightMid:    '┤',791		}792	}793	return BorderStyle{794		shape:       shape,795		top:         '─',796		bottom:      '─',797		left:        '│',798		right:       '│',799		topLeft:     '╭',800		topRight:    '╮',801		bottomLeft:  '╰',802		bottomRight: '╯',803		leftMid:     '├',804		rightMid:    '┤',805	}806}807808type TermSize struct {809	Lines    int810	Columns  int811	PxWidth  int812	PxHeight int813}814815type WindowType int816817const (818	WindowBase WindowType = iota819	WindowList820	WindowPreview821	WindowInput822	WindowHeader823	WindowFooter824)825826// BorderColor returns the ColorPair used to draw borders for the given WindowType.827func BorderColor(wt WindowType) ColorPair {828	switch wt {829	case WindowList:830		return ColListBorder831	case WindowInput:832		return ColInputBorder833	case WindowHeader:834		return ColHeaderBorder835	case WindowFooter:836		return ColFooterBorder837	case WindowPreview:838		return ColPreviewBorder839	}840	return ColBorder841}842843// SectionEdge selects which outer edge of the frame an inline section844// should claim when PaintSectionFrame overpaints its adjacent border.845// SectionEdgeNone paints only the inner verticals (for sections that846// don't touch the outer top or bottom).847type SectionEdge int848849const (850	SectionEdgeNone SectionEdge = iota851	SectionEdgeTop852	SectionEdgeBottom853)854855type Renderer interface {856	DefaultTheme() *ColorTheme857	Init() error858	Resize(maxHeightFunc func(int) int)859	Pause(clear bool)860	Resume(clear bool, sigcont bool)861	Clear()862	RefreshWindows(windows []Window)863	Refresh()864	Close()865	PassThrough(string)866	NeedScrollbarRedraw() bool867	ShouldEmitResizeEvent() bool868	Bell()869	HideCursor()870	ShowCursor()871872	GetChar(cancellable bool) Event873	CancelGetChar()874875	Top() int876	MaxX() int877	MaxY() int878879	Size() TermSize880881	NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window882}883884type Window interface {885	Top() int886	Left() int887	Width() int888	Height() int889890	DrawBorder()891	DrawHBorder()892	// DrawHSeparator draws an inline horizontal separator at `row` (relative to the893	// window's top) using the color for `windowType`. The separator is conceptually894	// the section's inner edge (e.g. the bottom border of an inline header), so the895	// whole row including junctions carries the section's fg + bg. When useBottom is896	// true the `bottom` horizontal char is used instead of `top`; for thinblock/block897	// styles this keeps the thin line bonded to the list content on the opposite side.898	DrawHSeparator(row int, windowType WindowType, useBottom bool)899	// PaintSectionFrame overpaints the border cells around the rows [topContent,900	// bottomContent] (inclusive, relative to the window's top) with the color for901	// `windowType`. When edge is SectionEdgeTop / SectionEdgeBottom, the902	// corresponding outer horizontal (+ corners) is also painted, letting the903	// inline section claim that edge of the outer frame.904	PaintSectionFrame(topContent, bottomContent int, windowType WindowType, edge SectionEdge)905	Refresh()906	FinishFill()907908	X() int909	Y() int910	EncloseX(x int) bool911	EncloseY(y int) bool912	Enclose(y int, x int) bool913914	Move(y int, x int)915	MoveAndClear(y int, x int)916	Print(text string)917	CPrint(color ColorPair, text string)918	Fill(text string) FillReturn919	CFill(fg Color, bg Color, ul Color, attr Attr, text string) FillReturn920	LinkBegin(uri string, params string)921	LinkEnd()922	Erase()923	EraseMaybe() bool924925	SetWrapSign(string, int)926}927928type FullscreenRenderer struct {929	theme        *ColorTheme930	mouse        bool931	forceBlack   bool932	tabstop      int933	prevDownTime time.Time934	clicks       [][2]int935	showCursor   bool936}937938func NewFullscreenRenderer(theme *ColorTheme, forceBlack bool, mouse bool, tabstop int) Renderer {939	r := &FullscreenRenderer{940		theme:        theme,941		mouse:        mouse,942		forceBlack:   forceBlack,943		tabstop:      tabstop,944		prevDownTime: time.Unix(0, 0),945		clicks:       [][2]int{},946		showCursor:   true}947	return r948}949950var (951	NoColorTheme *ColorTheme952	EmptyTheme   *ColorTheme953	Default16    *ColorTheme954	Dark256      *ColorTheme955	Light256     *ColorTheme956957	ColPrompt               ColorPair958	ColNormal               ColorPair959	ColInput                ColorPair960	ColDisabled             ColorPair961	ColGhost                ColorPair962	ColMatch                ColorPair963	ColPointer              ColorPair964	ColPointerEmpty         ColorPair965	ColPointerEmptyChar     ColorPair966	ColAltPointerEmpty      ColorPair967	ColAltPointerEmptyChar  ColorPair968	ColMarker               ColorPair969	ColSelected             ColorPair970	ColSelectedMatch        ColorPair971	ColCurrent              ColorPair972	ColCurrentMatch         ColorPair973	ColCurrentPointer       ColorPair974	ColCurrentPointerEmpty  ColorPair975	ColCurrentMarker        ColorPair976	ColCurrentSelectedEmpty ColorPair977	ColSpinner              ColorPair978	ColInfo                 ColorPair979	ColHeader               ColorPair980	ColHeaderBorder         ColorPair981	ColHeaderLabel          ColorPair982	ColFooter               ColorPair983	ColFooterBorder         ColorPair984	ColFooterLabel          ColorPair985	ColSeparator            ColorPair986	ColScrollbar            ColorPair987	ColGapLine              ColorPair988	ColBorder               ColorPair989	ColPreview              ColorPair990	ColPreviewBorder        ColorPair991	ColBorderLabel          ColorPair992	ColPreviewLabel         ColorPair993	ColPreviewScrollbar     ColorPair994	ColPreviewSpinner       ColorPair995	ColListBorder           ColorPair996	ColListLabel            ColorPair997	ColInputBorder          ColorPair998	ColInputLabel           ColorPair999)10001001func init() {1002	defaultColor := ColorAttr{colDefault, AttrUndefined}1003	undefined := ColorAttr{colUndefined, AttrUndefined}10041005	NoColorTheme = &ColorTheme{1006		Colored: false,1007		// Root colors. Everything else is left undefined so that overriding a1008		// root (e.g. --color bw,bg:blue) propagates to the derived colors,1009		// just like in the colored base themes.1010		Input:       defaultColor,1011		Fg:          defaultColor,1012		Bg:          defaultColor,1013		DarkBg:      defaultColor,1014		Prompt:      defaultColor,1015		Match:       defaultColor,1016		Spinner:     defaultColor,1017		Info:        defaultColor,1018		Pointer:     defaultColor,1019		Marker:      defaultColor,1020		Header:      defaultColor,1021		Footer:      defaultColor,1022		BorderLabel: defaultColor,1023		// Derived colors. Left undefined so they inherit from a root.1024		ListFg:           undefined,1025		ListBg:           undefined,1026		AltBg:            undefined,1027		SelectedFg:       undefined,1028		SelectedBg:       undefined,1029		SelectedMatch:    undefined,1030		Current:          undefined,1031		CurrentMatch:     undefined,1032		Border:           undefined,1033		Ghost:            undefined,1034		Disabled:         undefined,1035		PreviewFg:        undefined,1036		PreviewBg:        undefined,1037		Gutter:           undefined,1038		AltGutter:        undefined,1039		PreviewBorder:    undefined,1040		PreviewScrollbar: undefined,1041		PreviewLabel:     undefined,1042		ListLabel:        undefined,1043		ListBorder:       undefined,1044		Separator:        undefined,1045		Scrollbar:        undefined,1046		InputBg:          undefined,1047		InputBorder:      undefined,1048		InputLabel:       undefined,1049		HeaderBg:         undefined,1050		HeaderBorder:     undefined,1051		HeaderLabel:      undefined,1052		FooterBg:         undefined,1053		FooterBorder:     undefined,1054		FooterLabel:      undefined,1055		GapLine:          undefined,1056		Nth:              undefined,1057		Nomatch:          undefined,1058	}10591060	EmptyTheme = &ColorTheme{1061		Colored:          true,1062		Input:            undefined,1063		Fg:               undefined,1064		Bg:               undefined,1065		ListFg:           undefined,1066		ListBg:           undefined,1067		AltBg:            undefined,1068		SelectedFg:       undefined,1069		SelectedBg:       undefined,1070		SelectedMatch:    undefined,1071		DarkBg:           undefined,1072		Prompt:           undefined,1073		Match:            undefined,1074		Current:          undefined,1075		CurrentMatch:     undefined,1076		Spinner:          undefined,1077		Info:             undefined,1078		Pointer:          undefined,1079		Marker:           undefined,1080		Header:           undefined,1081		Footer:           undefined,1082		Border:           undefined,1083		BorderLabel:      undefined,1084		ListLabel:        undefined,1085		ListBorder:       undefined,1086		Ghost:            undefined,1087		Disabled:         undefined,1088		PreviewFg:        undefined,1089		PreviewBg:        undefined,1090		Gutter:           undefined,1091		AltGutter:        undefined,1092		PreviewBorder:    undefined,1093		PreviewScrollbar: undefined,1094		PreviewLabel:     undefined,1095		Separator:        undefined,1096		Scrollbar:        undefined,1097		InputBg:          undefined,1098		InputBorder:      undefined,1099		InputLabel:       undefined,1100		HeaderBg:         undefined,1101		HeaderBorder:     undefined,1102		HeaderLabel:      undefined,1103		FooterBg:         undefined,1104		FooterBorder:     undefined,1105		FooterLabel:      undefined,1106		GapLine:          undefined,1107		Nth:              undefined,1108		Nomatch:          undefined,1109	}11101111	Default16 = &ColorTheme{1112		Colored:          true,1113		Input:            defaultColor,1114		Fg:               defaultColor,1115		Bg:               defaultColor,1116		ListFg:           undefined,1117		ListBg:           undefined,1118		AltBg:            undefined,1119		SelectedFg:       undefined,1120		SelectedBg:       undefined,1121		SelectedMatch:    undefined,1122		DarkBg:           ColorAttr{colGrey, AttrUndefined},1123		Prompt:           ColorAttr{colBlue, AttrUndefined},1124		Match:            ColorAttr{colGreen, AttrUndefined},1125		Current:          ColorAttr{colBrightWhite, AttrUndefined},1126		CurrentMatch:     ColorAttr{colBrightGreen, AttrUndefined},1127		Spinner:          ColorAttr{colGreen, AttrUndefined},1128		Info:             ColorAttr{colYellow, AttrUndefined},1129		Pointer:          ColorAttr{colRed, AttrUndefined},1130		Marker:           ColorAttr{colMagenta, AttrUndefined},1131		Header:           ColorAttr{colCyan, AttrUndefined},1132		Footer:           ColorAttr{colCyan, AttrUndefined},1133		Border:           undefined,1134		BorderLabel:      defaultColor,1135		Ghost:            undefined,1136		Disabled:         undefined,1137		PreviewFg:        undefined,1138		PreviewBg:        undefined,1139		Gutter:           undefined,1140		AltGutter:        undefined,1141		PreviewBorder:    undefined,1142		PreviewScrollbar: undefined,1143		PreviewLabel:     undefined,1144		ListLabel:        undefined,1145		ListBorder:       undefined,1146		Separator:        undefined,1147		Scrollbar:        undefined,1148		InputBg:          undefined,1149		InputBorder:      undefined,1150		InputLabel:       undefined,1151		HeaderBg:         undefined,1152		HeaderBorder:     undefined,1153		HeaderLabel:      undefined,1154		FooterBg:         undefined,1155		FooterBorder:     undefined,1156		FooterLabel:      undefined,1157		GapLine:          undefined,1158		Nth:              undefined,1159		Nomatch:          undefined,1160	}11611162	Dark256 = &ColorTheme{1163		Colored:          true,1164		Input:            defaultColor,1165		Fg:               defaultColor,1166		Bg:               defaultColor,1167		ListFg:           undefined,1168		ListBg:           undefined,1169		AltBg:            undefined,1170		SelectedFg:       undefined,1171		SelectedBg:       undefined,1172		SelectedMatch:    undefined,1173		DarkBg:           ColorAttr{236, AttrUndefined},1174		Prompt:           ColorAttr{110, AttrUndefined},1175		Match:            ColorAttr{108, AttrUndefined},1176		Current:          ColorAttr{254, AttrUndefined},1177		CurrentMatch:     ColorAttr{151, AttrUndefined},1178		Spinner:          ColorAttr{148, AttrUndefined},1179		Info:             ColorAttr{144, AttrUndefined},1180		Pointer:          ColorAttr{161, AttrUndefined},1181		Marker:           ColorAttr{168, AttrUndefined},1182		Header:           ColorAttr{109, AttrUndefined},1183		Footer:           ColorAttr{109, AttrUndefined},1184		Border:           ColorAttr{59, AttrUndefined},1185		BorderLabel:      ColorAttr{145, AttrUndefined},1186		Ghost:            undefined,1187		Disabled:         undefined,1188		PreviewFg:        undefined,1189		PreviewBg:        undefined,1190		Gutter:           undefined,1191		AltGutter:        undefined,1192		PreviewBorder:    undefined,1193		PreviewScrollbar: undefined,1194		PreviewLabel:     undefined,1195		ListLabel:        undefined,1196		ListBorder:       undefined,1197		Separator:        undefined,1198		Scrollbar:        undefined,1199		InputBg:          undefined,1200		InputBorder:      undefined,1201		InputLabel:       undefined,1202		HeaderBg:         undefined,1203		HeaderBorder:     undefined,1204		HeaderLabel:      undefined,1205		FooterBg:         undefined,1206		FooterBorder:     undefined,1207		FooterLabel:      undefined,1208		GapLine:          undefined,1209		Nth:              undefined,1210		Nomatch:          undefined,1211	}12121213	Light256 = &ColorTheme{1214		Colored:          true,1215		Input:            defaultColor,1216		Fg:               defaultColor,1217		Bg:               defaultColor,1218		ListFg:           undefined,1219		ListBg:           undefined,1220		AltBg:            undefined,1221		SelectedFg:       undefined,1222		SelectedBg:       undefined,1223		SelectedMatch:    undefined,1224		DarkBg:           ColorAttr{251, AttrUndefined},1225		Prompt:           ColorAttr{25, AttrUndefined},1226		Match:            ColorAttr{66, AttrUndefined},1227		Current:          ColorAttr{237, AttrUndefined},1228		CurrentMatch:     ColorAttr{23, AttrUndefined},1229		Spinner:          ColorAttr{65, AttrUndefined},1230		Info:             ColorAttr{101, AttrUndefined},1231		Pointer:          ColorAttr{161, AttrUndefined},1232		Marker:           ColorAttr{168, AttrUndefined},1233		Header:           ColorAttr{31, AttrUndefined},1234		Footer:           ColorAttr{31, AttrUndefined},1235		Border:           ColorAttr{145, AttrUndefined},1236		BorderLabel:      ColorAttr{59, AttrUndefined},1237		Ghost:            undefined,1238		Disabled:         undefined,1239		PreviewFg:        undefined,1240		PreviewBg:        undefined,1241		Gutter:           undefined,1242		AltGutter:        undefined,1243		PreviewBorder:    undefined,1244		PreviewScrollbar: undefined,1245		PreviewLabel:     undefined,1246		ListLabel:        undefined,1247		ListBorder:       undefined,1248		Separator:        undefined,1249		Scrollbar:        undefined,1250		InputBg:          undefined,1251		InputBorder:      undefined,1252		InputLabel:       undefined,1253		HeaderBg:         undefined,1254		HeaderBorder:     undefined,1255		HeaderLabel:      undefined,1256		FooterBg:         undefined,1257		FooterBorder:     undefined,1258		FooterLabel:      undefined,1259		GapLine:          undefined,1260		Nth:              undefined,1261		Nomatch:          undefined,1262	}1263}12641265func InitTheme(theme *ColorTheme, baseTheme *ColorTheme, boldify bool, forceBlack bool, hasInputWindow bool, hasHeaderWindow bool, headerInline bool, footerInline bool) {1266	if forceBlack {1267		theme.Bg = ColorAttr{colBlack, AttrUndefined}1268	}12691270	if boldify {1271		boldify := func(c ColorAttr) ColorAttr {1272			dup := c1273			if (c.Attr & AttrRegular) == 0 {1274				dup.Attr |= BoldForce1275			}1276			return dup1277		}1278		theme.Current = boldify(theme.Current)1279		theme.CurrentMatch = boldify(theme.CurrentMatch)1280		theme.Prompt = boldify(theme.Prompt)1281		theme.Input = boldify(theme.Input)1282		theme.Pointer = boldify(theme.Pointer)1283		theme.Spinner = boldify(theme.Spinner)1284	}12851286	o := func(a ColorAttr, b ColorAttr) ColorAttr {1287		c := a1288		if b.Color != colUndefined {1289			c.Color = b.Color1290		}1291		if b.Attr != AttrUndefined {1292			c.Attr = b.Attr1293		}1294		return c1295	}1296	theme.Input = o(baseTheme.Input, theme.Input)1297	theme.Fg = o(baseTheme.Fg, theme.Fg)1298	theme.Bg = o(baseTheme.Bg, theme.Bg)1299	theme.DarkBg = o(baseTheme.DarkBg, theme.DarkBg)1300	theme.Prompt = o(baseTheme.Prompt, theme.Prompt)1301	match := theme.Match1302	if !baseTheme.Colored && match.IsUndefined() {1303		match.Attr = Underline1304	}1305	theme.Match = o(baseTheme.Match, match)1306	// These colors are not defined in the base themes.1307	// Resolve ListFg/ListBg early so Current and Selected can inherit from them.1308	theme.ListFg = o(theme.Fg, theme.ListFg)1309	theme.ListBg = o(theme.Bg, theme.ListBg)1310	// Inherit from 'list-fg', so that we don't have to write 'current-fg:dim'1311	// e.g. fzf --delimiter / --nth -1 --color fg:dim,nth:regular1312	current := theme.Current1313	if !baseTheme.Colored && current.IsUndefined() {1314		current.Attr |= Reverse1315	}1316	resolvedCurrent := o(baseTheme.Current, current)1317	theme.NthCurrentAttr = resolvedCurrent.Attr1318	theme.Current = theme.ListFg.Merge(resolvedCurrent)1319	currentMatch := theme.CurrentMatch1320	if !baseTheme.Colored && currentMatch.IsUndefined() {1321		currentMatch.Attr |= Reverse | Underline1322	}1323	theme.CurrentMatch = o(baseTheme.CurrentMatch, currentMatch)1324	theme.Spinner = o(baseTheme.Spinner, theme.Spinner)1325	theme.Info = o(baseTheme.Info, theme.Info)1326	theme.Pointer = o(baseTheme.Pointer, theme.Pointer)1327	theme.Marker = o(baseTheme.Marker, theme.Marker)1328	theme.Header = o(baseTheme.Header, theme.Header)1329	theme.Footer = o(baseTheme.Footer, theme.Footer)13301331	// If border color is undefined, set it to default color with dim attribute.1332	border := theme.Border1333	if baseTheme.Border.IsUndefined() && border.IsUndefined() {1334		border.Attr = Dim1335	}1336	theme.Border = o(baseTheme.Border, border)1337	theme.BorderLabel = o(baseTheme.BorderLabel, theme.BorderLabel)13381339	undefined := NewColorAttr()1340	scrollbarDefined := theme.Scrollbar != undefined1341	previewBorderDefined := theme.PreviewBorder != undefined13421343	theme.NthSelectedAttr = theme.SelectedFg.Attr1344	theme.SelectedFg = theme.ListFg.Merge(theme.SelectedFg)1345	theme.SelectedBg = o(theme.ListBg, theme.SelectedBg)1346	theme.SelectedMatch = o(theme.Match, theme.SelectedMatch)13471348	ghost := theme.Ghost1349	if ghost.IsUndefined() {1350		ghost.Attr = Dim1351	} else if ghost.IsColorDefined() && !ghost.IsAttrDefined() {1352		// Don't want to inherit 'bold' from 'input'1353		ghost.Attr = AttrRegular1354	}1355	theme.Ghost = o(theme.Input, ghost)1356	theme.Disabled = o(theme.Input, theme.Disabled)13571358	// Use dim gutter on non-colored themes if undefined1359	gutter := theme.Gutter1360	if !baseTheme.Colored && gutter.IsUndefined() {1361		gutter.Attr = Dim1362	}1363	theme.Gutter = o(theme.DarkBg, gutter)1364	theme.AltGutter = o(theme.Gutter, theme.AltGutter)1365	theme.PreviewFg = o(theme.Fg, theme.PreviewFg)1366	theme.PreviewBg = o(theme.Bg, theme.PreviewBg)1367	theme.PreviewLabel = o(theme.BorderLabel, theme.PreviewLabel)1368	theme.PreviewBorder = o(theme.Border, theme.PreviewBorder)1369	theme.ListLabel = o(theme.BorderLabel, theme.ListLabel)1370	theme.ListBorder = o(theme.Border, theme.ListBorder)1371	theme.Separator = o(theme.ListBorder, theme.Separator)1372	theme.Scrollbar = o(theme.ListBorder, theme.Scrollbar)1373	theme.GapLine = o(theme.ListBorder, theme.GapLine)1374	/*1375		--color list-border:green1376		--color scrollbar:red1377		--color scrollbar:red,list-border:green1378		--color scrollbar:red,preview-border:green1379	*/1380	if scrollbarDefined && !previewBorderDefined {1381		theme.PreviewScrollbar = o(theme.Scrollbar, theme.PreviewScrollbar)1382	} else {1383		theme.PreviewScrollbar = o(theme.PreviewBorder, theme.PreviewScrollbar)1384	}1385	if hasInputWindow {1386		theme.InputBg = o(theme.Bg, theme.InputBg)1387	} else {1388		// We shouldn't use input-bg if there's no separate input window1389		// e.g. fzf --color 'list-bg:green,input-bg:red' --no-input-border1390		theme.InputBg = o(theme.Bg, theme.ListBg)1391	}1392	theme.InputBorder = o(theme.Border, theme.InputBorder)1393	theme.InputLabel = o(theme.BorderLabel, theme.InputLabel)1394	if hasHeaderWindow {1395		theme.HeaderBg = o(theme.Bg, theme.HeaderBg)1396	} else {1397		theme.HeaderBg = o(theme.Bg, theme.ListBg)1398	}1399	// Inline header/footer borders sit inside the list frame, so default their color1400	// to the list-border color when the user has not explicitly set it. The inline1401	// separator then matches the surrounding frame.1402	headerBorderFallback := theme.Border1403	if headerInline {1404		headerBorderFallback = theme.ListBorder1405	}1406	theme.HeaderBorder = o(headerBorderFallback, theme.HeaderBorder)1407	theme.HeaderLabel = o(theme.BorderLabel, theme.HeaderLabel)14081409	theme.FooterBg = o(theme.Bg, theme.FooterBg)1410	footerBorderFallback := theme.Border1411	if footerInline {1412		footerBorderFallback = theme.ListBorder1413	}1414	theme.FooterBorder = o(footerBorderFallback, theme.FooterBorder)1415	theme.FooterLabel = o(theme.BorderLabel, theme.FooterLabel)14161417	if theme.Nomatch.IsUndefined() {1418		theme.Nomatch.Attr = Dim1419	}14201421	initPalette(theme)1422}14231424func initPalette(theme *ColorTheme) {1425	pair := func(fg, bg ColorAttr) ColorPair {1426		if fg.Color == colDefault && (fg.Attr&Reverse) > 0 {1427			bg.Color = colDefault1428		}1429		return ColorPair{fg.Color, bg.Color, colDefault, fg.Attr}1430	}1431	blank := theme.ListFg1432	blank.Attr = AttrRegular14331434	ColPrompt = pair(theme.Prompt, theme.InputBg)1435	ColNormal = pair(theme.ListFg, theme.ListBg)1436	ColSelected = pair(theme.SelectedFg, theme.SelectedBg)1437	ColInput = pair(theme.Input, theme.InputBg)1438	ColGhost = pair(theme.Ghost, theme.InputBg)1439	ColDisabled = pair(theme.Disabled, theme.InputBg)1440	ColMatch = pair(theme.Match, theme.ListBg)1441	ColSelectedMatch = pair(theme.SelectedMatch, theme.SelectedBg)1442	ColPointer = pair(theme.Pointer, theme.Gutter)1443	ColPointerEmpty = pair(blank, theme.Gutter)1444	ColPointerEmptyChar = pair(theme.Gutter, theme.ListBg)1445	ColAltPointerEmpty = pair(blank, theme.AltGutter)1446	ColAltPointerEmptyChar = pair(theme.AltGutter, theme.ListBg)1447	if theme.SelectedBg.Color != theme.ListBg.Color {1448		ColMarker = pair(theme.Marker, theme.SelectedBg)1449	} else {1450		ColMarker = pair(theme.Marker, theme.ListBg)1451	}1452	ColCurrent = pair(theme.Current, theme.DarkBg)1453	ColCurrentMatch = pair(theme.CurrentMatch, theme.DarkBg)1454	ColCurrentPointer = pair(theme.Pointer, theme.DarkBg)1455	ColCurrentPointerEmpty = pair(blank, theme.DarkBg)1456	ColCurrentMarker = pair(theme.Marker, theme.DarkBg)1457	ColCurrentSelectedEmpty = pair(blank, theme.DarkBg)1458	ColSpinner = pair(theme.Spinner, theme.InputBg)1459	ColInfo = pair(theme.Info, theme.InputBg)1460	ColSeparator = pair(theme.Separator, theme.InputBg)1461	ColScrollbar = pair(theme.Scrollbar, theme.ListBg)1462	ColGapLine = pair(theme.GapLine, theme.ListBg)1463	ColBorder = pair(theme.Border, theme.Bg)1464	ColBorderLabel = pair(theme.BorderLabel, theme.Bg)1465	ColPreviewLabel = pair(theme.PreviewLabel, theme.PreviewBg)1466	ColPreview = pair(theme.PreviewFg, theme.PreviewBg)1467	ColPreviewBorder = pair(theme.PreviewBorder, theme.PreviewBg)1468	ColPreviewScrollbar = pair(theme.PreviewScrollbar, theme.PreviewBg)1469	ColPreviewSpinner = pair(theme.Spinner, theme.PreviewBg)1470	ColListLabel = pair(theme.ListLabel, theme.ListBg)1471	ColListBorder = pair(theme.ListBorder, theme.ListBg)1472	ColInputBorder = pair(theme.InputBorder, theme.InputBg)1473	ColInputLabel = pair(theme.InputLabel, theme.InputBg)1474	ColHeader = pair(theme.Header, theme.HeaderBg)1475	ColHeaderBorder = pair(theme.HeaderBorder, theme.HeaderBg)1476	ColHeaderLabel = pair(theme.HeaderLabel, theme.HeaderBg)1477	ColFooter = pair(theme.Footer, theme.FooterBg)1478	ColFooterBorder = pair(theme.FooterBorder, theme.FooterBg)1479	ColFooterLabel = pair(theme.FooterLabel, theme.FooterBg)1480}14811482func runeWidth(r rune) int {1483	return uniseg.StringWidth(string(r))1484}14851486// WrappedLine represents a single visual line after character-level wrapping.1487type WrappedLine struct {1488	Text         string1489	DisplayWidth int1490}14911492// WrapLine splits a single line (no embedded \n) into visual lines1493// that fit within initialMax columns. Character-level wrapping only.1494func WrapLine(input string, prefixLength int, initialMax int, tabstop int, wrapSignWidth int) []WrappedLine {1495	lines := []WrappedLine{}1496	width := 01497	line := ""1498	gr := uniseg.NewGraphemes(input)1499	maxWidth := initialMax1500	contMax := max(1, initialMax-wrapSignWidth)1501	for gr.Next() {1502		rs := gr.Runes()1503		str := string(rs)1504		var w int1505		if len(rs) == 1 && rs[0] == '\t' {1506			w = tabstop - (prefixLength+width)%tabstop1507			str = strings.Repeat(" ", w)1508		} else if rs[0] == '\r' {1509			w++1510		} else {1511			w = uniseg.StringWidth(str)1512		}1513		width += w15141515		if prefixLength+width <= maxWidth {1516			line += str1517		} else {1518			lines = append(lines, WrappedLine{string(line), width - w})1519			line = str1520			prefixLength = 01521			width = w1522			maxWidth = contMax1523		}1524	}1525	lines = append(lines, WrappedLine{string(line), width})1526	return lines1527}