repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/mouse.go
vendor/github.com/gdamore/tcell/v2/mouse.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "time" ) // EventMouse is a mouse event. It is sent on either mouse up or mouse down // events. It is also sent on mouse motion events - if the terminal supports // it. We make every effort to ensure that mouse release events are delivered. // Hence, click drag can be identified by a motion event with the mouse down, // without any intervening button release. On some terminals only the initiating // press and terminating release event will be delivered. // // Mouse wheel events, when reported, may appear on their own as individual // impulses; that is, there will normally not be a release event delivered // for mouse wheel movements. // // Most terminals cannot report the state of more than one button at a time -- // and some cannot report motion events unless a button is pressed. // // Applications can inspect the time between events to resolve double or // triple clicks. type EventMouse struct { t time.Time btn ButtonMask mod ModMask x int y int } // When returns the time when this EventMouse was created. func (ev *EventMouse) When() time.Time { return ev.t } // Buttons returns the list of buttons that were pressed or wheel motions. func (ev *EventMouse) Buttons() ButtonMask { return ev.btn } // Modifiers returns a list of keyboard modifiers that were pressed // with the mouse button(s). func (ev *EventMouse) Modifiers() ModMask { return ev.mod } // Position returns the mouse position in character cells. The origin // 0, 0 is at the upper left corner. func (ev *EventMouse) Position() (int, int) { return ev.x, ev.y } // NewEventMouse is used to create a new mouse event. Applications // shouldn't need to use this; its mostly for screen implementors. func NewEventMouse(x, y int, btn ButtonMask, mod ModMask) *EventMouse { return &EventMouse{t: time.Now(), x: x, y: y, btn: btn, mod: mod} } // ButtonMask is a mask of mouse buttons and wheel events. Mouse button presses // are normally delivered as both press and release events. Mouse wheel events // are normally just single impulse events. Windows supports up to eight // separate buttons plus all four wheel directions, but XTerm can only support // mouse buttons 1-3 and wheel up/down. Its not unheard of for terminals // to support only one or two buttons (think Macs). Old terminals, and true // emulations (such as vt100) won't support mice at all, of course. type ButtonMask int16 // These are the actual button values. Note that tcell version 1.x reversed buttons // two and three on *nix based terminals. We use button 1 as the primary, and // button 2 as the secondary, and button 3 (which is often missing) as the middle. const ( Button1 ButtonMask = 1 << iota // Usually the left (primary) mouse button. Button2 // Usually the right (secondary) mouse button. Button3 // Usually the middle mouse button. Button4 // Often a side button (thumb/next). Button5 // Often a side button (thumb/prev). Button6 Button7 Button8 WheelUp // Wheel motion up/away from user. WheelDown // Wheel motion down/towards user. WheelLeft // Wheel motion to left. WheelRight // Wheel motion to right. ButtonNone ButtonMask = 0 // No button or wheel events. ButtonPrimary = Button1 ButtonSecondary = Button2 ButtonMiddle = Button3 )
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/charset_unix.go
vendor/github.com/gdamore/tcell/v2/charset_unix.go
//go:build !windows && !nacl && !plan9 // +build !windows,!nacl,!plan9 // Copyright 2016 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "os" "strings" ) func getCharset() string { // Determine the character set. This can help us later. // Per POSIX, we search for LC_ALL first, then LC_CTYPE, and // finally LANG. First one set wins. locale := "" if locale = os.Getenv("LC_ALL"); locale == "" { if locale = os.Getenv("LC_CTYPE"); locale == "" { locale = os.Getenv("LANG") } } if locale == "POSIX" || locale == "C" { return "US-ASCII" } if i := strings.IndexRune(locale, '@'); i >= 0 { locale = locale[:i] } if i := strings.IndexRune(locale, '.'); i >= 0 { locale = locale[i+1:] } else { // Default assumption, and on Linux we can see LC_ALL // without a character set, which we assume implies UTF-8. return "UTF-8" } // XXX: add support for aliases return locale }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terms_dynamic.go
vendor/github.com/gdamore/tcell/v2/terms_dynamic.go
//go:build !tcell_minimal && !nacl && !js && !zos && !plan9 && !windows && !android // +build !tcell_minimal,!nacl,!js,!zos,!plan9,!windows,!android // Copyright 2019 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( // This imports a dynamic version of the terminal database, which // is built using infocmp. This relies on a working installation // of infocmp (typically supplied with ncurses). We only do this // for systems likely to have that -- i.e. UNIX based hosts. We // also don't support Android here, because you really don't want // to run external programs there. Generally the android terminals // will be automatically included anyway. "github.com/gdamore/tcell/v2/terminfo" "github.com/gdamore/tcell/v2/terminfo/dynamic" "fmt" ) func loadDynamicTerminfo(term string) (*terminfo.Terminfo, error) { if term == "" { return nil, fmt.Errorf("%w: term not set", ErrTermNotFound) } ti, _, e := dynamic.LoadTerminfo(term) if e != nil { return nil, e } return ti, nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/interrupt.go
vendor/github.com/gdamore/tcell/v2/interrupt.go
// Copyright 2015 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "time" ) // EventInterrupt is a generic wakeup event. Its can be used to // to request a redraw. It can carry an arbitrary payload, as well. type EventInterrupt struct { t time.Time v interface{} } // When returns the time when this event was created. func (ev *EventInterrupt) When() time.Time { return ev.t } // Data is used to obtain the opaque event payload. func (ev *EventInterrupt) Data() interface{} { return ev.v } // NewEventInterrupt creates an EventInterrupt with the given payload. func NewEventInterrupt(data interface{}) *EventInterrupt { return &EventInterrupt{t: time.Now(), v: data} }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/console_stub.go
vendor/github.com/gdamore/tcell/v2/console_stub.go
//go:build !windows // +build !windows // Copyright 2015 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell // NewConsoleScreen returns a console based screen. This platform // doesn't have support for any, so it returns nil and a suitable error. func NewConsoleScreen() (Screen, error) { return nil, ErrNoScreen }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/paste.go
vendor/github.com/gdamore/tcell/v2/paste.go
// Copyright 2024 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "time" ) // EventPaste is used to mark the start and end of a bracketed paste. // // An event with .Start() true will be sent to mark the start of a bracketed paste, // followed by a number of keys (string data) for the content, ending with the // an event with .End() true. type EventPaste struct { start bool t time.Time data []byte } // When returns the time when this EventPaste was created. func (ev *EventPaste) When() time.Time { return ev.t } // Start returns true if this is the start of a paste. func (ev *EventPaste) Start() bool { return ev.start } // End returns true if this is the end of a paste. func (ev *EventPaste) End() bool { return !ev.start } // NewEventPaste returns a new EventPaste. func NewEventPaste(start bool) *EventPaste { return &EventPaste{t: time.Now(), start: start} } // NewEventClipboard returns a new NewEventClipboard with a data payload func NewEventClipboard(data []byte) *EventClipboard { return &EventClipboard{t: time.Now(), data: data} } // EventClipboard represents data from the clipboard, // in response to a GetClipboard request. type EventClipboard struct { t time.Time data []byte } // Data returns the attached binary data. func (ev *EventClipboard) Data() []byte { return ev.data } // When returns the time when this event was created. func (ev *EventClipboard) When() time.Time { return ev.t }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/charset_plan9.go
vendor/github.com/gdamore/tcell/v2/charset_plan9.go
//go:build plan9 // +build plan9 // Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell // Plan 9 uses UTF-8 system-wide, so we return "UTF-8" unconditionally. func getCharset() string { return "UTF-8" }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/screen.go
vendor/github.com/gdamore/tcell/v2/screen.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import "sync" // Screen represents the physical (or emulated) screen. // This can be a terminal window or a physical console. Platforms implement // this differently. type Screen interface { // Init initializes the screen for use. Init() error // Fini finalizes the screen also releasing resources. Fini() // Clear logically erases the screen. // This is effectively a short-cut for Fill(' ', StyleDefault). Clear() // Fill fills the screen with the given character and style. // The effect of filling the screen is not visible until Show // is called (or Sync). Fill(rune, Style) // Put writes the first graphme of the given string with th // given style at the given coordinates. (Only the first grapheme // occupying either one or two cells is stored.) It returns the // remainder of the string, and the width displayed. Put(x int, y int, str string, style Style) (string, int) // PutStr writes a string starting at the given position, using the // default style. The content is clipped to the screen dimensions. PutStr(x int, y int, str string) // PutStrStyled writes a string starting at the given position, using // the given style. The cont4ent is clipped to the screen dimensions. PutStrStyled(x int, y int, str string, style Style) // SetCell is an older API, and will be removed. //jj // Deprecated: Please use Put instead. SetCell(x int, y int, style Style, ch ...rune) // Get the contents at the given location. If the // coordinates are out of range, then the values will be 0, nil, // StyleDefault. Note that the contents returned are logical contents // and may not actually be what is displayed, but rather are what will // be displayed if Show() or Sync() is called. The width is the width // in screen cells; most often this will be 1, but some East Asian // characters and emoji require two cells. Get(x, y int) (str string, style Style, width int) // GetContent is the old way to get cell contents. // // Deprecated: Use Get() instead. GetContent(x, y int) (primary rune, combining []rune, style Style, width int) // SetContent sets the contents of the given cell location. If // the coordinates are out of range, then the operation is ignored. // // The first rune is the primary non-zero width rune. The array // that follows is a possible list of combining characters to append, // and will usually be nil (no combining characters.) // // The results are not displayed until Show() or Sync() is called. // // Note that wide (East Asian full width and emoji) runes occupy two cells, // and attempts to place character at next cell to the right will have // undefined effects. Wide runes that are printed in the // last column will be replaced with a single width space on output. SetContent(x int, y int, primary rune, combining []rune, style Style) // SetStyle sets the default style to use when clearing the screen // or when StyleDefault is specified. If it is also StyleDefault, // then whatever system/terminal default is relevant will be used. SetStyle(style Style) // ShowCursor is used to display the cursor at a given location. // If the coordinates -1, -1 are given or are otherwise outside the // dimensions of the screen, the cursor will be hidden. ShowCursor(x int, y int) // HideCursor is used to hide the cursor. It's an alias for // ShowCursor(-1, -1).sim HideCursor() // SetCursorStyle is used to set the cursor style. If the style // is not supported (or cursor styles are not supported at all), // then this will have no effect. Color will be changed if supplied, // and the terminal supports doing so. SetCursorStyle(CursorStyle, ...Color) // Size returns the screen size as width, height. This changes in // response to a call to Clear or Flush. Size() (width, height int) // ChannelEvents is an infinite loop that waits for an event and // channels it into the user provided channel ch. Closing the // quit channel and calling the Fini method are cancellation // signals. When a cancellation signal is received the method // returns after closing ch. // // This method should be used as a goroutine. // // NOTE: PollEvent should not be called while this method is running. ChannelEvents(ch chan<- Event, quit <-chan struct{}) // PollEvent waits for events to arrive. Main application loops // must spin on this to prevent the application from stalling. // Furthermore, this will return nil if the Screen is finalized. PollEvent() Event // HasPendingEvent returns true if PollEvent would return an event // without blocking. If the screen is stopped and PollEvent would // return nil, then the return value from this function is unspecified. // The purpose of this function is to allow multiple events to be collected // at once, to minimize screen redraws. HasPendingEvent() bool // PostEvent tries to post an event into the event stream. This // can fail if the event queue is full. In that case, the event // is dropped, and ErrEventQFull is returned. PostEvent(ev Event) error // Deprecated: PostEventWait is unsafe, and will be removed // in the future. // // PostEventWait is like PostEvent, but if the queue is full, it // blocks until there is space in the queue, making delivery // reliable. However, it is VERY important that this function // never be called from within whatever event loop is polling // with PollEvent(), otherwise a deadlock may arise. // // For this reason, when using this function, the use of a // Goroutine is recommended to ensure no deadlock can occur. PostEventWait(ev Event) // EnableMouse enables the mouse. (If your terminal supports it.) // If no flags are specified, then all events are reported, if the // terminal supports them. EnableMouse(...MouseFlags) // DisableMouse disables the mouse. DisableMouse() // EnablePaste enables bracketed paste mode, if supported. EnablePaste() // DisablePaste disables bracketed paste mode. DisablePaste() // EnableFocus enables reporting of focus events, if your terminal supports it. EnableFocus() // DisableFocus disables reporting of focus events. DisableFocus() // HasMouse returns true if the terminal (apparently) supports a // mouse. Note that the return value of true doesn't guarantee that // a mouse/pointing device is present; a false return definitely // indicates no mouse support is available. HasMouse() bool // Colors returns the number of colors. All colors are assumed to // use the ANSI color map. If a terminal is monochrome, it will // return 0. Colors() int // Show makes all the content changes made using SetContent() visible // on the display. // // It does so in the most efficient and least visually disruptive // manner possible. Show() // Sync works like Show(), but it updates every visible cell on the // physical display, assuming that it is not synchronized with any // internal model. This may be both expensive and visually jarring, // so it should only be used when believed to actually be necessary. // // Typically, this is called as a result of a user-requested redraw // (e.g. to clear up on-screen corruption caused by some other program), // or during a resize event. Sync() // CharacterSet returns information about the character set. // This isn't the full locale, but it does give us the input/output // character set. Note that this is just for diagnostic purposes, // we normally translate input/output to/from UTF-8, regardless of // what the user's environment is. CharacterSet() string // RegisterRuneFallback adds a fallback for runes that are not // part of the character set -- for example one could register // o as a fallback for ø. This should be done cautiously for // characters that might be displayed ordinarily in language // specific text -- characters that could change the meaning of // written text would be dangerous. The intention here is to // facilitate fallback characters in pseudo-graphical applications. // // If the terminal has fallbacks already in place via an alternate // character set, those are used in preference. Also, standard // fallbacks for graphical characters in the alternate character set // terminfo string are registered implicitly. // // The display string should be the same width as original rune. // This makes it possible to register two character replacements // for full width East Asian characters, for example. // // It is recommended that replacement strings consist only of // 7-bit ASCII, since other characters may not display everywhere. RegisterRuneFallback(r rune, subst string) // UnregisterRuneFallback unmaps a replacement. It will unmap // the implicit ASCII replacements for alternate characters as well. // When an unmapped char needs to be displayed, but no suitable // glyph is available, '?' is emitted instead. It is not possible // to "disable" the use of alternate characters that are supported // by your terminal except by changing the terminal database. UnregisterRuneFallback(r rune) // CanDisplay returns true if the given rune can be displayed on // this screen. Note that this is a best-guess effort -- whether // your fonts support the character or not may be questionable. // Mostly this is for folks who work outside of Unicode. // // If checkFallbacks is true, then if any (possibly imperfect) // fallbacks are registered, this will return true. This will // also return true if the terminal can replace the glyph with // one that is visually indistinguishable from the one requested. // // Deprecated: This is not a particularly useful or reliable function, // due to limitations in fonts, etc. It will be removed in the future. CanDisplay(r rune, checkFallbacks bool) bool // Resize does nothing, since it's generally not possible to // ask a screen to resize, but it allows the Screen to implement // the View interface. Resize(int, int, int, int) // HasKey always returns true. // // Deprecated: This function always returns true. Applications // cannot reliably detect whether a key is supported or not with // modern terminal emulators. (The intended use here was to help // applications determine whether a given key stroke was supported // by the terminal, but it was never reliable.) HasKey(Key) bool // Suspend pauses input and output processing. It also restores the // terminal settings to what they were when the application started. // This can be used to, for example, run a sub-shell. Suspend() error // Resume resumes after Suspend(). Resume() error // Beep attempts to sound an OS-dependent audible alert and returns an error // when unsuccessful. Beep() error // SetSize attempts to resize the window. It also invalidates the cells and // calls the resize function. Note that if the window size is changed, it will // not be restored upon application exit. // // Many terminals cannot support this. Perversely, the "modern" Windows Terminal // does not support application-initiated resizing, whereas the legacy terminal does. // Also, some emulators can support this but may have it disabled by default. SetSize(int, int) // LockRegion sets or unsets a lock on a region of cells. A lock on a // cell prevents the cell from being redrawn. LockRegion(x, y, width, height int, lock bool) // Tty returns the underlying Tty. If the screen is not a terminal, the // returned bool will be false Tty() (Tty, bool) // SetTitle sets a window title on the screen. // Terminals may be configured to ignore this, or unable to. // Tcell may attempt to save and restore the window title on entry and exit, but // the results may vary. Use of unicode characters may not be supported. SetTitle(string) // SetClipboard is used to post arbitrary data to the system clipboard. // This need not be UTF-8 string data. It's up to the recipient to decode the // data meaningfully. Terminals may prevent this for security reasons. SetClipboard([]byte) // GetClipboard is used to request the clipboard contents. It may be ignored. // If the terminal is willing, it will be post the clipboard contents using an // EventPaste with the clipboard content as the Data() field. Terminals may // prevent this for security reasons. GetClipboard() } // NewScreen returns a default Screen suitable for the user's terminal // environment. func NewScreen() (Screen, error) { if s, e := NewTerminfoScreen(); s != nil { return s, nil } else if s, _ := NewConsoleScreen(); s != nil { return s, nil } else { return nil, e } } // MouseFlags are options to modify the handling of mouse events. // Actual events can be ORed together. type MouseFlags int const ( MouseButtonEvents = MouseFlags(1) // Click events only MouseDragEvents = MouseFlags(2) // Click-drag events (includes button events) MouseMotionEvents = MouseFlags(4) // All mouse events (includes click and drag events) ) // CursorStyle represents a given cursor style, which can include the shape and // whether the cursor blinks or is solid. Support for changing this is not universal. type CursorStyle int const ( CursorStyleDefault = CursorStyle(iota) // The default CursorStyleBlinkingBlock CursorStyleSteadyBlock CursorStyleBlinkingUnderline CursorStyleSteadyUnderline CursorStyleBlinkingBar CursorStyleSteadyBar ) // screenImpl is a subset of Screen that can be used with baseScreen to formulate // a complete implementation of Screen. See Screen for doc comments about methods. type screenImpl interface { Init() error Fini() SetStyle(style Style) ShowCursor(x int, y int) HideCursor() SetCursor(CursorStyle, Color) Size() (width, height int) EnableMouse(...MouseFlags) DisableMouse() EnablePaste() DisablePaste() EnableFocus() DisableFocus() HasMouse() bool Colors() int Show() Sync() CharacterSet() string RegisterRuneFallback(r rune, subst string) UnregisterRuneFallback(r rune) CanDisplay(r rune, checkFallbacks bool) bool Resize(int, int, int, int) HasKey(Key) bool Suspend() error Resume() error Beep() error SetSize(int, int) SetTitle(string) Tty() (Tty, bool) SetClipboard([]byte) GetClipboard() // Following methods are not part of the Screen api, but are used for interaction with // the common layer code. // Locker locks the underlying data structures so that we can access them // in a thread-safe way. sync.Locker // GetCells returns a pointer to the underlying CellBuffer that the implementation uses. // Various methods will write to these for performance, but will use the lock to do so. GetCells() *CellBuffer // StopQ is closed when the screen is shut down via Fini. It remains open if the screen // is merely suspended. StopQ() <-chan struct{} // EventQ delivers events. Events are posted to this by the screen in response to // key presses, resizes, etc. Application code receives events from this via the // Screen.PollEvent, Screen.ChannelEvents APIs. EventQ() chan Event } type baseScreen struct { screenImpl } func (b *baseScreen) Put(x int, y int, str string, style Style) (remain string, width int) { cells := b.GetCells() b.Lock() defer b.Unlock() return cells.Put(x, y, str, style) } func (b *baseScreen) PutStrStyled(x int, y int, str string, style Style) { cells := b.GetCells() b.Lock() cols, rows := cells.Size() width := 0 for str != "" && x < cols && y < rows { str, width = cells.Put(x, y, str, style) if width == 0 { break } x += width } defer b.Unlock() } func (b *baseScreen) PutStr(x, y int, str string) { b.PutStrStyled(x, y, str, StyleDefault) } func (b *baseScreen) SetCell(x int, y int, style Style, ch ...rune) { if len(ch) > 0 { b.Put(x, y, string(ch), style) } else { b.Put(x, y, " ", style) } } func (b *baseScreen) Clear() { b.Fill(' ', StyleDefault) } func (b *baseScreen) Fill(r rune, style Style) { cb := b.GetCells() b.Lock() cb.Fill(r, style) b.Unlock() } func (b *baseScreen) SetContent(x, y int, mainc rune, combc []rune, style Style) { b.Put(x, y, string(append([]rune{mainc}, combc...)), style) } func (b *baseScreen) Get(x, y int) (string, Style, int) { cells := b.GetCells() b.Lock() defer b.Unlock() return cells.Get(x, y) } func (b *baseScreen) GetContent(x, y int) (rune, []rune, Style, int) { var primary rune var combining []rune var style Style var width int cells := b.GetCells() b.Lock() primary, combining, style, width = cells.GetContent(x, y) b.Unlock() return primary, combining, style, width } func (b *baseScreen) LockRegion(x, y, width, height int, lock bool) { cells := b.GetCells() b.Lock() for j := y; j < (y + height); j += 1 { for i := x; i < (x + width); i += 1 { switch lock { case true: cells.LockCell(i, j) case false: cells.UnlockCell(i, j) } } } b.Unlock() } func (b *baseScreen) ChannelEvents(ch chan<- Event, quit <-chan struct{}) { defer close(ch) for { select { case <-quit: return case <-b.StopQ(): return case ev := <-b.EventQ(): select { case <-quit: return case <-b.StopQ(): return case ch <- ev: } } } } func (b *baseScreen) PollEvent() Event { select { case <-b.StopQ(): return nil case ev := <-b.EventQ(): return ev } } func (b *baseScreen) HasPendingEvent() bool { return len(b.EventQ()) > 0 } func (b *baseScreen) PostEventWait(ev Event) { select { case b.EventQ() <- ev: case <-b.StopQ(): } } func (b *baseScreen) PostEvent(ev Event) error { select { case b.EventQ() <- ev: return nil default: return ErrEventQFull } } func (b *baseScreen) SetCursorStyle(cs CursorStyle, ccs ...Color) { if len(ccs) > 0 { b.SetCursor(cs, ccs[0]) } else { b.SetCursor(cs, ColorNone) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/simulation.go
vendor/github.com/gdamore/tcell/v2/simulation.go
// Copyright 2024 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "sync" "unicode/utf8" "golang.org/x/text/transform" ) // NewSimulationScreen returns a SimulationScreen. Note that // SimulationScreen is also a Screen. func NewSimulationScreen(charset string) SimulationScreen { if charset == "" { charset = "UTF-8" } ss := &simscreen{charset: charset} ss.Screen = &baseScreen{screenImpl: ss} return ss } // SimulationScreen represents a screen simulation. This is intended to // be a superset of normal Screens, but also adds some important interfaces // for testing. type SimulationScreen interface { Screen // InjectKeyBytes injects a stream of bytes corresponding to // the native encoding (see charset). It turns true if the entire // set of bytes were processed and delivered as KeyEvents, false // if any bytes were not fully understood. Any bytes that are not // fully converted are discarded. InjectKeyBytes(buf []byte) bool // InjectKey injects a key event. The rune is a UTF-8 rune, post // any translation. InjectKey(key Key, r rune, mod ModMask) // InjectMouse injects a mouse event. InjectMouse(x, y int, buttons ButtonMask, mod ModMask) // GetContents returns screen contents as an array of // cells, along with the physical width & height. Note that the // physical contents will be used until the next time SetSize() // is called. GetContents() (cells []SimCell, width int, height int) // GetCursor returns the cursor details. GetCursor() (x int, y int, visible bool) // GetTitle gets the previously set title. GetTitle() string // GetClipboardData gets the actual data for the clipboard. GetClipboardData() []byte } // SimCell represents a simulated screen cell. The purpose of this // is to track on screen content. type SimCell struct { // Bytes is the actual character bytes. Normally this is // rune data, but it could be be data in another encoding system. Bytes []byte // Style is the style used to display the data. Style Style // Runes is the list of runes, unadulterated, in UTF-8. Runes []rune } type simscreen struct { physw int physh int fini bool style Style evch chan Event quit chan struct{} front []SimCell back CellBuffer clear bool cursorx int cursory int cursorvis bool mouse bool paste bool charset string encoder transform.Transformer decoder transform.Transformer fillchar rune fillstyle Style fallback map[rune]string title string clipboard []byte Screen sync.Mutex } func (s *simscreen) Init() error { s.evch = make(chan Event, 10) s.quit = make(chan struct{}) s.fillchar = 'X' s.fillstyle = StyleDefault s.mouse = false s.physw = 80 s.physh = 25 s.cursorx = -1 s.cursory = -1 s.style = StyleDefault if enc := GetEncoding(s.charset); enc != nil { s.encoder = enc.NewEncoder() s.decoder = enc.NewDecoder() } else { return ErrNoCharset } s.front = make([]SimCell, s.physw*s.physh) s.back.Resize(80, 25) // default fallbacks s.fallback = make(map[rune]string) for k, v := range RuneFallbacks { s.fallback[k] = v } return nil } func (s *simscreen) Fini() { s.Lock() s.fini = true s.back.Resize(0, 0) s.Unlock() if s.quit != nil { close(s.quit) } s.physw = 0 s.physh = 0 s.front = nil } func (s *simscreen) SetStyle(style Style) { s.Lock() s.style = style s.Unlock() } func (s *simscreen) drawCell(x, y int) int { mainc, combc, style, width := s.back.GetContent(x, y) if !s.back.Dirty(x, y) { return width } if x >= s.physw || y >= s.physh || x < 0 || y < 0 { return width } simc := &s.front[(y*s.physw)+x] if style == StyleDefault { style = s.style } simc.Style = style simc.Runes = append([]rune{mainc}, combc...) // now emit runes - taking care to not overrun width with a // wide character, and to ensure that we emit exactly one regular // character followed up by any residual combing characters simc.Bytes = nil if x > s.physw-width { simc.Runes = []rune{' '} simc.Bytes = []byte{' '} return width } lbuf := make([]byte, 12) ubuf := make([]byte, 12) nout := 0 for _, r := range simc.Runes { l := utf8.EncodeRune(ubuf, r) nout, _, _ = s.encoder.Transform(lbuf, ubuf[:l], true) if nout == 0 || lbuf[0] == '\x1a' { // skip combining if subst, ok := s.fallback[r]; ok { simc.Bytes = append(simc.Bytes, []byte(subst)...) } else if r >= ' ' && r <= '~' { simc.Bytes = append(simc.Bytes, byte(r)) } else if simc.Bytes == nil { simc.Bytes = append(simc.Bytes, '?') } } else { simc.Bytes = append(simc.Bytes, lbuf[:nout]...) } } s.back.SetDirty(x, y, false) return width } func (s *simscreen) ShowCursor(x, y int) { s.Lock() s.cursorx, s.cursory = x, y s.showCursor() s.Unlock() } func (s *simscreen) HideCursor() { s.ShowCursor(-1, -1) } func (s *simscreen) showCursor() { x, y := s.cursorx, s.cursory if x < 0 || y < 0 || x >= s.physw || y >= s.physh { s.cursorvis = false } else { s.cursorvis = true } } func (s *simscreen) hideCursor() { // does not update cursor position s.cursorvis = false } func (s *simscreen) SetCursor(CursorStyle, Color) {} func (s *simscreen) Show() { s.Lock() s.resize() s.draw() s.Unlock() } func (s *simscreen) clearScreen() { // We emulate a hardware clear by filling with a specific pattern for i := range s.front { s.front[i].Style = s.fillstyle s.front[i].Runes = []rune{s.fillchar} s.front[i].Bytes = []byte{byte(s.fillchar)} } s.clear = false } func (s *simscreen) draw() { s.hideCursor() if s.clear { s.clearScreen() } w, h := s.back.Size() for y := 0; y < h; y++ { for x := 0; x < w; x++ { width := s.drawCell(x, y) x += width - 1 } } s.showCursor() } func (s *simscreen) EnableMouse(...MouseFlags) { s.mouse = true } func (s *simscreen) DisableMouse() { s.mouse = false } func (s *simscreen) EnablePaste() { s.paste = true } func (s *simscreen) DisablePaste() { s.paste = false } func (s *simscreen) EnableFocus() { } func (s *simscreen) DisableFocus() { } func (s *simscreen) Size() (int, int) { s.Lock() w, h := s.back.Size() s.Unlock() return w, h } func (s *simscreen) resize() { w, h := s.physw, s.physh ow, oh := s.back.Size() if w != ow || h != oh { s.back.Resize(w, h) ev := NewEventResize(w, h) s.postEvent(ev) } } func (s *simscreen) Colors() int { return 256 } func (s *simscreen) postEvent(ev Event) { select { case s.evch <- ev: case <-s.quit: } } func (s *simscreen) InjectMouse(x, y int, buttons ButtonMask, mod ModMask) { ev := NewEventMouse(x, y, buttons, mod) s.postEvent(ev) } func (s *simscreen) InjectKey(key Key, r rune, mod ModMask) { ev := NewEventKey(key, r, mod) s.postEvent(ev) } func (s *simscreen) InjectKeyBytes(b []byte) bool { failed := false outer: for len(b) > 0 { if b[0] >= ' ' && b[0] <= 0x7F { // printable ASCII easy to deal with -- no encodings ev := NewEventKey(KeyRune, rune(b[0]), ModNone) s.postEvent(ev) b = b[1:] continue } if b[0] < 0x80 { // No encodings start with low numbered values if b[0] > 0 && b[0] < ' ' { // control keys switch Key(b[0]) { case KeyESC, KeyEnter, KeyTAB: s.postEvent(NewEventKey(Key(b[0]), 0, 0)) continue; default: s.postEvent(NewEventKey(Key(b[0]), rune(b[0])+'\x60', ModCtrl)) continue } } mod := ModNone ev := NewEventKey(Key(b[0]), 0, mod) s.postEvent(ev) b = b[1:] continue } utfb := make([]byte, len(b)*4) // worst case for l := 1; l < len(b); l++ { s.decoder.Reset() nout, nin, _ := s.decoder.Transform(utfb, b[:l], true) if nout != 0 { r, _ := utf8.DecodeRune(utfb[:nout]) if r != utf8.RuneError { ev := NewEventKey(KeyRune, r, ModNone) s.postEvent(ev) } b = b[nin:] continue outer } } failed = true b = b[1:] continue } return !failed } func (s *simscreen) Sync() { s.Lock() s.clear = true s.resize() s.back.Invalidate() s.draw() s.Unlock() } func (s *simscreen) CharacterSet() string { return s.charset } func (s *simscreen) SetSize(w, h int) { s.Lock() newc := make([]SimCell, w*h) for row := 0; row < h && row < s.physh; row++ { for col := 0; col < w && col < s.physw; col++ { newc[(row*w)+col] = s.front[(row*s.physw)+col] } } s.cursorx, s.cursory = -1, -1 s.physw, s.physh = w, h s.front = newc s.back.Resize(w, h) s.Unlock() } func (s *simscreen) GetContents() ([]SimCell, int, int) { s.Lock() cells, w, h := s.front, s.physw, s.physh s.Unlock() return cells, w, h } func (s *simscreen) GetCursor() (int, int, bool) { s.Lock() x, y, vis := s.cursorx, s.cursory, s.cursorvis s.Unlock() return x, y, vis } func (s *simscreen) RegisterRuneFallback(r rune, subst string) { s.Lock() s.fallback[r] = subst s.Unlock() } func (s *simscreen) UnregisterRuneFallback(r rune) { s.Lock() delete(s.fallback, r) s.Unlock() } func (s *simscreen) CanDisplay(r rune, checkFallbacks bool) bool { if enc := s.encoder; enc != nil { nb := make([]byte, 6) ob := make([]byte, 6) num := utf8.EncodeRune(ob, r) enc.Reset() dst, _, err := enc.Transform(nb, ob[:num], true) if dst != 0 && err == nil && nb[0] != '\x1A' { return true } } if !checkFallbacks { return false } if _, ok := s.fallback[r]; ok { return true } return false } func (s *simscreen) HasMouse() bool { return false } func (s *simscreen) Resize(int, int, int, int) {} func (s *simscreen) HasKey(Key) bool { return true } func (s *simscreen) Beep() error { return nil } func (s *simscreen) Suspend() error { return nil } func (s *simscreen) Resume() error { return nil } func (s *simscreen) Tty() (Tty, bool) { return nil, false } func (s *simscreen) GetCells() *CellBuffer { return &s.back } func (s *simscreen) EventQ() chan Event { return s.evch } func (s *simscreen) StopQ() <-chan struct{} { return s.quit } func (s *simscreen) SetTitle(title string) { s.title = title } func (s *simscreen) GetTitle() string { return s.title } func (s *simscreen) SetClipboard(data []byte) { s.clipboard = data } func (s *simscreen) GetClipboard() { if s.clipboard != nil { ev := NewEventClipboard(s.clipboard) s.postEvent(ev) } } func (s *simscreen) GetClipboardData() []byte { return s.clipboard }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/tty_plan9.go
vendor/github.com/gdamore/tcell/v2/tty_plan9.go
//go:build plan9 // +build plan9 // Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "bufio" "errors" "fmt" "io" "os" "strconv" "strings" "sync" "sync/atomic" ) // p9Tty implements tcell.Tty using Plan 9's /dev/cons and /dev/consctl. // Raw mode is enabled by writing "rawon" to /dev/consctl while the fd stays open. // Resize notifications are read from /dev/wctl: the first read returns geometry, // subsequent reads block until the window changes (rio(4)). // // References: // - kbdfs(8): cons/consctl rawon|rawoff semantics // - rio(4): wctl geometry and blocking-on-change behavior // - vt(1): VT100 emulator typically used for TUI programs on Plan 9 // // Limitations: // - We assume VT100-level capabilities (often no colors, no mouse). // - Window size is conservative: we return 80x24 unless overridden. // Set LINES/COLUMNS (or TCELL_LINES/TCELL_COLS) to refine. // - Mouse and bracketed paste are not wired; terminfo/xterm queries // are not attempted because vt(1) may not support them. type p9Tty struct { cons *os.File // /dev/cons (read+write) consctl *os.File // /dev/consctl (write "rawon"/"rawoff") wctl *os.File // /dev/wctl (resize notifications) // protect close/stop; Read/Write are serialized by os.File mu sync.Mutex closed atomic.Bool // resize callback onResize atomic.Value // func() wg sync.WaitGroup stopCh chan struct{} } func NewDevTty() (Tty, error) { // tcell signature return newPlan9TTY() } func NewStdIoTty() (Tty, error) { // also required by tcell // On Plan 9 there is no POSIX tty discipline on stdin/stdout; // use /dev/cons explicitly for robustness. return newPlan9TTY() } func NewDevTtyFromDev(_ string) (Tty, error) { // required by tcell // Plan 9 does not have multiple "ttys" in the POSIX sense; // always bind to /dev/cons and /dev/consctl. return newPlan9TTY() } func newPlan9TTY() (Tty, error) { cons, err := os.OpenFile("/dev/cons", os.O_RDWR, 0) if err != nil { return nil, fmt.Errorf("open /dev/cons: %w", err) } consctl, err := os.OpenFile("/dev/consctl", os.O_WRONLY, 0) if err != nil { _ = cons.Close() return nil, fmt.Errorf("open /dev/consctl: %w", err) } // /dev/wctl may not exist (console without rio); best-effort. wctl, _ := os.OpenFile("/dev/wctl", os.O_RDWR, 0) t := &p9Tty{ cons: cons, consctl: consctl, wctl: wctl, stopCh: make(chan struct{}), } return t, nil } func (t *p9Tty) Start() error { t.mu.Lock() defer t.mu.Unlock() if t.closed.Load() { return errors.New("tty closed") } // Recreate stop channel if absent or closed (supports resume). if t.stopCh == nil || isClosed(t.stopCh) { t.stopCh = make(chan struct{}) } // Put console into raw mode; remains active while consctl is open. if _, err := t.consctl.Write([]byte("rawon")); err != nil { return fmt.Errorf("enable raw mode: %w", err) } // Reopen /dev/wctl on resume; best-effort (system console may lack it). if t.wctl == nil { if f, err := os.OpenFile("/dev/wctl", os.O_RDWR, 0); err == nil { t.wctl = f } } if t.wctl != nil { t.wg.Add(1) go t.watchResize() } return nil } func (t *p9Tty) Drain() error { // Per tcell docs, this may reasonably be a no-op on non-POSIX ttys. // Read deadlines are not available on plan9 os.File; we rely on Stop(). return nil } func (t *p9Tty) Stop() error { t.mu.Lock() defer t.mu.Unlock() // Signal watcher to stop (if not already). if t.stopCh != nil && !isClosed(t.stopCh) { close(t.stopCh) } // Exit raw mode first. _, _ = t.consctl.Write([]byte("rawoff")) // Closing wctl unblocks watchResize; nil it so Start() can reopen later. if t.wctl != nil { _ = t.wctl.Close() t.wctl = nil } // Ensure watcher goroutine has exited before returning. t.wg.Wait() return nil } func (t *p9Tty) Close() error { t.mu.Lock() defer t.mu.Unlock() if t.closed.Swap(true) { return nil } if t.stopCh != nil && !isClosed(t.stopCh) { close(t.stopCh) } _, _ = t.consctl.Write([]byte("rawoff")) _ = t.cons.Close() _ = t.consctl.Close() if t.wctl != nil { _ = t.wctl.Close() t.wctl = nil } t.wg.Wait() return nil } func (t *p9Tty) Read(p []byte) (int, error) { return t.cons.Read(p) } func (t *p9Tty) Write(p []byte) (int, error) { return t.cons.Write(p) } func (t *p9Tty) NotifyResize(cb func()) { if cb == nil { t.onResize.Store((func())(nil)) return } t.onResize.Store(cb) } func (t *p9Tty) WindowSize() (WindowSize, error) { // Strategy: // 1) honor explicit overrides (TCELL_LINES/TCELL_COLS, LINES/COLUMNS), // 2) otherwise return conservative 80x24. // Reading /dev/wctl gives pixel geometry, but char cell metrics are // not generally available to non-draw clients; vt(1) is fixed-cell. lines, cols := envInt("TCELL_LINES"), envInt("TCELL_COLS") if lines == 0 { lines = envInt("LINES") } if cols == 0 { cols = envInt("COLUMNS") } if lines <= 0 { lines = 24 } if cols <= 0 { cols = 80 } return WindowSize{Width: cols, Height: lines}, nil } // watchResize blocks on /dev/wctl reads; each read returns when the window // changes size/position/state, per rio(4). We ignore the parsed geometry and // just notify tcell to re-query WindowSize(). func (t *p9Tty) watchResize() { defer t.wg.Done() r := bufio.NewReader(t.wctl) for { select { case <-t.stopCh: return default: } // Each read delivers something like: // " minx miny maxx maxy visible current\n" // We don't need to parse here; just signal. _, err := r.ReadString('\n') if err != nil { if errors.Is(err, io.EOF) { return } // transient errors: continue } if cb, _ := t.onResize.Load().(func()); cb != nil { cb() } } } func envInt(name string) int { if s := strings.TrimSpace(os.Getenv(name)); s != "" { if v, err := strconv.Atoi(s); err == nil { return v } } return 0 } // helper: safe check if a channel is closed func isClosed(ch <-chan struct{}) bool { select { case <-ch: return true default: return false } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/errors.go
vendor/github.com/gdamore/tcell/v2/errors.go
// Copyright 2015 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "errors" "time" "github.com/gdamore/tcell/v2/terminfo" ) var ( // ErrTermNotFound indicates that a suitable terminal entry could // not be found. This can result from either not having TERM set, // or from the TERM failing to support certain minimal functionality, // in particular absolute cursor addressability (the cup capability) // is required. For example, legacy "adm3" lacks this capability, // whereas the slightly newer "adm3a" supports it. This failure // occurs most often with "dumb". ErrTermNotFound = terminfo.ErrTermNotFound // ErrNoScreen indicates that no suitable screen could be found. // This may result from attempting to run on a platform where there // is no support for either termios or console I/O (such as nacl), // or from running in an environment where there is no access to // a suitable console/terminal device. (For example, running on // without a controlling TTY or with no /dev/tty on POSIX platforms.) ErrNoScreen = errors.New("no suitable screen available") // ErrNoCharset indicates that the locale environment the // program is not supported by the program, because no suitable // encoding was found for it. This problem never occurs if // the environment is UTF-8 or UTF-16. ErrNoCharset = errors.New("character set not supported") // ErrEventQFull indicates that the event queue is full, and // cannot accept more events. ErrEventQFull = errors.New("event queue full") ) // An EventError is an event representing some sort of error, and carries // an error payload. type EventError struct { t time.Time err error } // When returns the time when the event was created. func (ev *EventError) When() time.Time { return ev.t } // Error implements the error. func (ev *EventError) Error() string { return ev.err.Error() } // NewEventError creates an ErrorEvent with the given error payload. func NewEventError(err error) *EventError { return &EventError{t: time.Now(), err: err} }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/tty.go
vendor/github.com/gdamore/tcell/v2/tty.go
// Copyright 2021 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import "io" // Tty is an abstraction of a tty (traditionally "teletype"). This allows applications to // provide for alternate backends, as there are situations where the traditional /dev/tty // does not work, or where more flexible handling is required. This interface is for use // with the terminfo-style based API. It extends the io.ReadWriter API. It is reasonable // that the implementation might choose to use different underlying files for the Reader // and Writer sides of this API, as part of it's internal implementation. type Tty interface { // Start is used to activate the Tty for use. Upon return the terminal should be // in raw mode, non-blocking, etc. The implementation should take care of saving // any state that is required so that it may be restored when Stop is called. Start() error // Stop is used to stop using this Tty instance. This may be a suspend, so that other // terminal based applications can run in the foreground. Implementations should // restore any state collected at Start(), and return to ordinary blocking mode, etc. // Drain is called first to drain the input. Once this is called, no more Read // or Write calls will be made until Start is called again. Stop() error // Drain is called before Stop, and ensures that the reader will wake up appropriately // if it was blocked. This workaround is required for /dev/tty on certain UNIX systems // to ensure that Read() does not block forever. This typically arranges for the tty driver // to send data immediately (e.g. VMIN and VTIME both set zero) and sets a deadline on input. // Implementations may reasonably make this a no-op. There will still be control sequences // emitted between the time this is called, and when Stop is called. Drain() error // NotifyResize is used register a callback when the tty thinks the dimensions have // changed. The standard UNIX implementation links this to a handler for SIGWINCH. // If the supplied callback is nil, then any handler should be unregistered. NotifyResize(cb func()) // WindowSize is called to determine the terminal dimensions. This might be determined // by an ioctl or other means. WindowSize() (WindowSize, error) io.ReadWriteCloser }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/stdin_unix.go
vendor/github.com/gdamore/tcell/v2/stdin_unix.go
// Copyright 2021 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos package tcell import ( "errors" "fmt" "os" "os/signal" "strconv" "sync" "syscall" "time" "golang.org/x/sys/unix" "golang.org/x/term" ) // stdIoTty is an implementation of the Tty API based upon stdin/stdout. type stdIoTty struct { fd int in *os.File out *os.File saved *term.State sig chan os.Signal cb func() stopQ chan struct{} dev string wg sync.WaitGroup l sync.Mutex } func (tty *stdIoTty) Read(b []byte) (int, error) { return tty.in.Read(b) } func (tty *stdIoTty) Write(b []byte) (int, error) { return tty.out.Write(b) } func (tty *stdIoTty) Close() error { return nil } func (tty *stdIoTty) Start() error { tty.l.Lock() defer tty.l.Unlock() // We open another copy of /dev/tty. This is a workaround for unusual behavior // observed in macOS, apparently caused when a sub-shell (for example) closes our // own tty device (when it exits for example). Getting a fresh new one seems to // resolve the problem. (We believe this is a bug in the macOS tty driver that // fails to account for dup() references to the same file before applying close() // related behaviors to the tty.) We're also holding the original copy we opened // since closing that might have deleterious effects as well. The upshot is that // we will have up to two separate file handles open on /dev/tty. (Note that when // using stdin/stdout instead of /dev/tty this problem is not observed.) var err error tty.in = os.Stdin tty.out = os.Stdout tty.fd = int(tty.in.Fd()) if !term.IsTerminal(tty.fd) { return errors.New("device is not a terminal") } _ = tty.in.SetReadDeadline(time.Time{}) saved, err := term.MakeRaw(tty.fd) // also sets vMin and vTime if err != nil { return err } tty.saved = saved tty.stopQ = make(chan struct{}) tty.wg.Add(1) go func(stopQ chan struct{}) { defer tty.wg.Done() for { select { case <-tty.sig: tty.l.Lock() cb := tty.cb tty.l.Unlock() if cb != nil { cb() } case <-stopQ: return } } }(tty.stopQ) signal.Notify(tty.sig, syscall.SIGWINCH) return nil } func (tty *stdIoTty) Drain() error { _ = tty.in.SetReadDeadline(time.Now()) if err := tcSetBufParams(tty.fd, 0, 0); err != nil { return err } return nil } func (tty *stdIoTty) Stop() error { tty.l.Lock() if err := term.Restore(tty.fd, tty.saved); err != nil { tty.l.Unlock() return err } _ = tty.in.SetReadDeadline(time.Now()) signal.Stop(tty.sig) close(tty.stopQ) tty.l.Unlock() tty.wg.Wait() return nil } func (tty *stdIoTty) WindowSize() (WindowSize, error) { size := WindowSize{} ws, err := unix.IoctlGetWinsize(tty.fd, unix.TIOCGWINSZ) if err != nil { return size, err } w := int(ws.Col) h := int(ws.Row) if w == 0 { w, _ = strconv.Atoi(os.Getenv("COLUMNS")) } if w == 0 { w = 80 // default } if h == 0 { h, _ = strconv.Atoi(os.Getenv("LINES")) } if h == 0 { h = 25 // default } size.Width = w size.Height = h size.PixelWidth = int(ws.Xpixel) size.PixelHeight = int(ws.Ypixel) return size, nil } func (tty *stdIoTty) NotifyResize(cb func()) { tty.l.Lock() tty.cb = cb tty.l.Unlock() } // NewStdioTty opens a tty using standard input/output. func NewStdIoTty() (Tty, error) { tty := &stdIoTty{ sig: make(chan os.Signal), in: os.Stdin, out: os.Stdout, } var err error tty.fd = int(tty.in.Fd()) if !term.IsTerminal(tty.fd) { return nil, errors.New("not a terminal") } if tty.saved, err = term.GetState(tty.fd); err != nil { return nil, fmt.Errorf("failed to get state: %w", err) } return tty, nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/nonblock_unix.go
vendor/github.com/gdamore/tcell/v2/nonblock_unix.go
// Copyright 2021 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build linux || aix || zos || solaris // +build linux aix zos solaris package tcell import ( "syscall" "golang.org/x/sys/unix" ) // tcSetBufParams is used by the tty driver on UNIX systems to configure the // buffering parameters (minimum character count and minimum wait time in msec.) // This also waits for output to drain first. func tcSetBufParams(fd int, vMin uint8, vTime uint8) error { _ = syscall.SetNonblock(fd, true) tio, err := unix.IoctlGetTermios(fd, unix.TCGETS) if err != nil { return err } tio.Cc[unix.VMIN] = vMin tio.Cc[unix.VTIME] = vTime if err = unix.IoctlSetTermios(fd, unix.TCSETSW, tio); err != nil { return err } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/color.go
vendor/github.com/gdamore/tcell/v2/color.go
// Copyright 2023 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "fmt" ic "image/color" "strconv" ) // Color represents a color. The low numeric values are the same as used // by ECMA-48, and beyond that XTerm. A 24-bit RGB value may be used by // adding in the ColorIsRGB flag. For Color names we use the W3C approved // color names. // // We use a 64-bit integer to allow future expansion if we want to add an // 8-bit alpha, while still leaving us some room for extra options. // // Note that on various terminals colors may be approximated however, or // not supported at all. If no suitable representation for a color is known, // the library will simply not set any color, deferring to whatever default // attributes the terminal uses. type Color uint64 const ( // ColorDefault is used to leave the Color unchanged from whatever // system or terminal default may exist. It's also the zero value. ColorDefault Color = 0 // ColorValid is used to indicate the color value is actually // valid (initialized). This is useful to permit the zero value // to be treated as the default. ColorValid Color = 1 << 32 // ColorIsRGB is used to indicate that the numeric value is not // a known color constant, but rather an RGB value. The lower // order 3 bytes are RGB. ColorIsRGB Color = 1 << 33 // ColorSpecial is a flag used to indicate that the values have // special meaning, and live outside of the color space(s). ColorSpecial Color = 1 << 34 ) // Note that the order of these options is important -- it follows the // definitions used by ECMA and XTerm. Hence any further named colors // must begin at a value not less than 256. const ( ColorBlack = ColorValid + iota ColorMaroon ColorGreen ColorOlive ColorNavy ColorPurple ColorTeal ColorSilver ColorGray ColorRed ColorLime ColorYellow ColorBlue ColorFuchsia ColorAqua ColorWhite Color16 Color17 Color18 Color19 Color20 Color21 Color22 Color23 Color24 Color25 Color26 Color27 Color28 Color29 Color30 Color31 Color32 Color33 Color34 Color35 Color36 Color37 Color38 Color39 Color40 Color41 Color42 Color43 Color44 Color45 Color46 Color47 Color48 Color49 Color50 Color51 Color52 Color53 Color54 Color55 Color56 Color57 Color58 Color59 Color60 Color61 Color62 Color63 Color64 Color65 Color66 Color67 Color68 Color69 Color70 Color71 Color72 Color73 Color74 Color75 Color76 Color77 Color78 Color79 Color80 Color81 Color82 Color83 Color84 Color85 Color86 Color87 Color88 Color89 Color90 Color91 Color92 Color93 Color94 Color95 Color96 Color97 Color98 Color99 Color100 Color101 Color102 Color103 Color104 Color105 Color106 Color107 Color108 Color109 Color110 Color111 Color112 Color113 Color114 Color115 Color116 Color117 Color118 Color119 Color120 Color121 Color122 Color123 Color124 Color125 Color126 Color127 Color128 Color129 Color130 Color131 Color132 Color133 Color134 Color135 Color136 Color137 Color138 Color139 Color140 Color141 Color142 Color143 Color144 Color145 Color146 Color147 Color148 Color149 Color150 Color151 Color152 Color153 Color154 Color155 Color156 Color157 Color158 Color159 Color160 Color161 Color162 Color163 Color164 Color165 Color166 Color167 Color168 Color169 Color170 Color171 Color172 Color173 Color174 Color175 Color176 Color177 Color178 Color179 Color180 Color181 Color182 Color183 Color184 Color185 Color186 Color187 Color188 Color189 Color190 Color191 Color192 Color193 Color194 Color195 Color196 Color197 Color198 Color199 Color200 Color201 Color202 Color203 Color204 Color205 Color206 Color207 Color208 Color209 Color210 Color211 Color212 Color213 Color214 Color215 Color216 Color217 Color218 Color219 Color220 Color221 Color222 Color223 Color224 Color225 Color226 Color227 Color228 Color229 Color230 Color231 Color232 Color233 Color234 Color235 Color236 Color237 Color238 Color239 Color240 Color241 Color242 Color243 Color244 Color245 Color246 Color247 Color248 Color249 Color250 Color251 Color252 Color253 Color254 Color255 ColorAliceBlue = ColorIsRGB | ColorValid | 0xF0F8FF ColorAntiqueWhite = ColorIsRGB | ColorValid | 0xFAEBD7 ColorAquaMarine = ColorIsRGB | ColorValid | 0x7FFFD4 ColorAzure = ColorIsRGB | ColorValid | 0xF0FFFF ColorBeige = ColorIsRGB | ColorValid | 0xF5F5DC ColorBisque = ColorIsRGB | ColorValid | 0xFFE4C4 ColorBlanchedAlmond = ColorIsRGB | ColorValid | 0xFFEBCD ColorBlueViolet = ColorIsRGB | ColorValid | 0x8A2BE2 ColorBrown = ColorIsRGB | ColorValid | 0xA52A2A ColorBurlyWood = ColorIsRGB | ColorValid | 0xDEB887 ColorCadetBlue = ColorIsRGB | ColorValid | 0x5F9EA0 ColorChartreuse = ColorIsRGB | ColorValid | 0x7FFF00 ColorChocolate = ColorIsRGB | ColorValid | 0xD2691E ColorCoral = ColorIsRGB | ColorValid | 0xFF7F50 ColorCornflowerBlue = ColorIsRGB | ColorValid | 0x6495ED ColorCornsilk = ColorIsRGB | ColorValid | 0xFFF8DC ColorCrimson = ColorIsRGB | ColorValid | 0xDC143C ColorDarkBlue = ColorIsRGB | ColorValid | 0x00008B ColorDarkCyan = ColorIsRGB | ColorValid | 0x008B8B ColorDarkGoldenrod = ColorIsRGB | ColorValid | 0xB8860B ColorDarkGray = ColorIsRGB | ColorValid | 0xA9A9A9 ColorDarkGreen = ColorIsRGB | ColorValid | 0x006400 ColorDarkKhaki = ColorIsRGB | ColorValid | 0xBDB76B ColorDarkMagenta = ColorIsRGB | ColorValid | 0x8B008B ColorDarkOliveGreen = ColorIsRGB | ColorValid | 0x556B2F ColorDarkOrange = ColorIsRGB | ColorValid | 0xFF8C00 ColorDarkOrchid = ColorIsRGB | ColorValid | 0x9932CC ColorDarkRed = ColorIsRGB | ColorValid | 0x8B0000 ColorDarkSalmon = ColorIsRGB | ColorValid | 0xE9967A ColorDarkSeaGreen = ColorIsRGB | ColorValid | 0x8FBC8F ColorDarkSlateBlue = ColorIsRGB | ColorValid | 0x483D8B ColorDarkSlateGray = ColorIsRGB | ColorValid | 0x2F4F4F ColorDarkTurquoise = ColorIsRGB | ColorValid | 0x00CED1 ColorDarkViolet = ColorIsRGB | ColorValid | 0x9400D3 ColorDeepPink = ColorIsRGB | ColorValid | 0xFF1493 ColorDeepSkyBlue = ColorIsRGB | ColorValid | 0x00BFFF ColorDimGray = ColorIsRGB | ColorValid | 0x696969 ColorDodgerBlue = ColorIsRGB | ColorValid | 0x1E90FF ColorFireBrick = ColorIsRGB | ColorValid | 0xB22222 ColorFloralWhite = ColorIsRGB | ColorValid | 0xFFFAF0 ColorForestGreen = ColorIsRGB | ColorValid | 0x228B22 ColorGainsboro = ColorIsRGB | ColorValid | 0xDCDCDC ColorGhostWhite = ColorIsRGB | ColorValid | 0xF8F8FF ColorGold = ColorIsRGB | ColorValid | 0xFFD700 ColorGoldenrod = ColorIsRGB | ColorValid | 0xDAA520 ColorGreenYellow = ColorIsRGB | ColorValid | 0xADFF2F ColorHoneydew = ColorIsRGB | ColorValid | 0xF0FFF0 ColorHotPink = ColorIsRGB | ColorValid | 0xFF69B4 ColorIndianRed = ColorIsRGB | ColorValid | 0xCD5C5C ColorIndigo = ColorIsRGB | ColorValid | 0x4B0082 ColorIvory = ColorIsRGB | ColorValid | 0xFFFFF0 ColorKhaki = ColorIsRGB | ColorValid | 0xF0E68C ColorLavender = ColorIsRGB | ColorValid | 0xE6E6FA ColorLavenderBlush = ColorIsRGB | ColorValid | 0xFFF0F5 ColorLawnGreen = ColorIsRGB | ColorValid | 0x7CFC00 ColorLemonChiffon = ColorIsRGB | ColorValid | 0xFFFACD ColorLightBlue = ColorIsRGB | ColorValid | 0xADD8E6 ColorLightCoral = ColorIsRGB | ColorValid | 0xF08080 ColorLightCyan = ColorIsRGB | ColorValid | 0xE0FFFF ColorLightGoldenrodYellow = ColorIsRGB | ColorValid | 0xFAFAD2 ColorLightGray = ColorIsRGB | ColorValid | 0xD3D3D3 ColorLightGreen = ColorIsRGB | ColorValid | 0x90EE90 ColorLightPink = ColorIsRGB | ColorValid | 0xFFB6C1 ColorLightSalmon = ColorIsRGB | ColorValid | 0xFFA07A ColorLightSeaGreen = ColorIsRGB | ColorValid | 0x20B2AA ColorLightSkyBlue = ColorIsRGB | ColorValid | 0x87CEFA ColorLightSlateGray = ColorIsRGB | ColorValid | 0x778899 ColorLightSteelBlue = ColorIsRGB | ColorValid | 0xB0C4DE ColorLightYellow = ColorIsRGB | ColorValid | 0xFFFFE0 ColorLimeGreen = ColorIsRGB | ColorValid | 0x32CD32 ColorLinen = ColorIsRGB | ColorValid | 0xFAF0E6 ColorMediumAquamarine = ColorIsRGB | ColorValid | 0x66CDAA ColorMediumBlue = ColorIsRGB | ColorValid | 0x0000CD ColorMediumOrchid = ColorIsRGB | ColorValid | 0xBA55D3 ColorMediumPurple = ColorIsRGB | ColorValid | 0x9370DB ColorMediumSeaGreen = ColorIsRGB | ColorValid | 0x3CB371 ColorMediumSlateBlue = ColorIsRGB | ColorValid | 0x7B68EE ColorMediumSpringGreen = ColorIsRGB | ColorValid | 0x00FA9A ColorMediumTurquoise = ColorIsRGB | ColorValid | 0x48D1CC ColorMediumVioletRed = ColorIsRGB | ColorValid | 0xC71585 ColorMidnightBlue = ColorIsRGB | ColorValid | 0x191970 ColorMintCream = ColorIsRGB | ColorValid | 0xF5FFFA ColorMistyRose = ColorIsRGB | ColorValid | 0xFFE4E1 ColorMoccasin = ColorIsRGB | ColorValid | 0xFFE4B5 ColorNavajoWhite = ColorIsRGB | ColorValid | 0xFFDEAD ColorOldLace = ColorIsRGB | ColorValid | 0xFDF5E6 ColorOliveDrab = ColorIsRGB | ColorValid | 0x6B8E23 ColorOrange = ColorIsRGB | ColorValid | 0xFFA500 ColorOrangeRed = ColorIsRGB | ColorValid | 0xFF4500 ColorOrchid = ColorIsRGB | ColorValid | 0xDA70D6 ColorPaleGoldenrod = ColorIsRGB | ColorValid | 0xEEE8AA ColorPaleGreen = ColorIsRGB | ColorValid | 0x98FB98 ColorPaleTurquoise = ColorIsRGB | ColorValid | 0xAFEEEE ColorPaleVioletRed = ColorIsRGB | ColorValid | 0xDB7093 ColorPapayaWhip = ColorIsRGB | ColorValid | 0xFFEFD5 ColorPeachPuff = ColorIsRGB | ColorValid | 0xFFDAB9 ColorPeru = ColorIsRGB | ColorValid | 0xCD853F ColorPink = ColorIsRGB | ColorValid | 0xFFC0CB ColorPlum = ColorIsRGB | ColorValid | 0xDDA0DD ColorPowderBlue = ColorIsRGB | ColorValid | 0xB0E0E6 ColorRebeccaPurple = ColorIsRGB | ColorValid | 0x663399 ColorRosyBrown = ColorIsRGB | ColorValid | 0xBC8F8F ColorRoyalBlue = ColorIsRGB | ColorValid | 0x4169E1 ColorSaddleBrown = ColorIsRGB | ColorValid | 0x8B4513 ColorSalmon = ColorIsRGB | ColorValid | 0xFA8072 ColorSandyBrown = ColorIsRGB | ColorValid | 0xF4A460 ColorSeaGreen = ColorIsRGB | ColorValid | 0x2E8B57 ColorSeashell = ColorIsRGB | ColorValid | 0xFFF5EE ColorSienna = ColorIsRGB | ColorValid | 0xA0522D ColorSkyblue = ColorIsRGB | ColorValid | 0x87CEEB ColorSlateBlue = ColorIsRGB | ColorValid | 0x6A5ACD ColorSlateGray = ColorIsRGB | ColorValid | 0x708090 ColorSnow = ColorIsRGB | ColorValid | 0xFFFAFA ColorSpringGreen = ColorIsRGB | ColorValid | 0x00FF7F ColorSteelBlue = ColorIsRGB | ColorValid | 0x4682B4 ColorTan = ColorIsRGB | ColorValid | 0xD2B48C ColorThistle = ColorIsRGB | ColorValid | 0xD8BFD8 ColorTomato = ColorIsRGB | ColorValid | 0xFF6347 ColorTurquoise = ColorIsRGB | ColorValid | 0x40E0D0 ColorViolet = ColorIsRGB | ColorValid | 0xEE82EE ColorWheat = ColorIsRGB | ColorValid | 0xF5DEB3 ColorWhiteSmoke = ColorIsRGB | ColorValid | 0xF5F5F5 ColorYellowGreen = ColorIsRGB | ColorValid | 0x9ACD32 ) // These are aliases for the color gray, because some of us spell // it as grey. const ( ColorGrey = ColorGray ColorDimGrey = ColorDimGray ColorDarkGrey = ColorDarkGray ColorDarkSlateGrey = ColorDarkSlateGray ColorLightGrey = ColorLightGray ColorLightSlateGrey = ColorLightSlateGray ColorSlateGrey = ColorSlateGray ) // ColorValues maps color constants to their RGB values. var ColorValues = map[Color]int32{ ColorBlack: 0x000000, ColorMaroon: 0x800000, ColorGreen: 0x008000, ColorOlive: 0x808000, ColorNavy: 0x000080, ColorPurple: 0x800080, ColorTeal: 0x008080, ColorSilver: 0xC0C0C0, ColorGray: 0x808080, ColorRed: 0xFF0000, ColorLime: 0x00FF00, ColorYellow: 0xFFFF00, ColorBlue: 0x0000FF, ColorFuchsia: 0xFF00FF, ColorAqua: 0x00FFFF, ColorWhite: 0xFFFFFF, Color16: 0x000000, // black Color17: 0x00005F, Color18: 0x000087, Color19: 0x0000AF, Color20: 0x0000D7, Color21: 0x0000FF, // blue Color22: 0x005F00, Color23: 0x005F5F, Color24: 0x005F87, Color25: 0x005FAF, Color26: 0x005FD7, Color27: 0x005FFF, Color28: 0x008700, Color29: 0x00875F, Color30: 0x008787, Color31: 0x0087Af, Color32: 0x0087D7, Color33: 0x0087FF, Color34: 0x00AF00, Color35: 0x00AF5F, Color36: 0x00AF87, Color37: 0x00AFAF, Color38: 0x00AFD7, Color39: 0x00AFFF, Color40: 0x00D700, Color41: 0x00D75F, Color42: 0x00D787, Color43: 0x00D7AF, Color44: 0x00D7D7, Color45: 0x00D7FF, Color46: 0x00FF00, // lime Color47: 0x00FF5F, Color48: 0x00FF87, Color49: 0x00FFAF, Color50: 0x00FFd7, Color51: 0x00FFFF, // aqua Color52: 0x5F0000, Color53: 0x5F005F, Color54: 0x5F0087, Color55: 0x5F00AF, Color56: 0x5F00D7, Color57: 0x5F00FF, Color58: 0x5F5F00, Color59: 0x5F5F5F, Color60: 0x5F5F87, Color61: 0x5F5FAF, Color62: 0x5F5FD7, Color63: 0x5F5FFF, Color64: 0x5F8700, Color65: 0x5F875F, Color66: 0x5F8787, Color67: 0x5F87AF, Color68: 0x5F87D7, Color69: 0x5F87FF, Color70: 0x5FAF00, Color71: 0x5FAF5F, Color72: 0x5FAF87, Color73: 0x5FAFAF, Color74: 0x5FAFD7, Color75: 0x5FAFFF, Color76: 0x5FD700, Color77: 0x5FD75F, Color78: 0x5FD787, Color79: 0x5FD7AF, Color80: 0x5FD7D7, Color81: 0x5FD7FF, Color82: 0x5FFF00, Color83: 0x5FFF5F, Color84: 0x5FFF87, Color85: 0x5FFFAF, Color86: 0x5FFFD7, Color87: 0x5FFFFF, Color88: 0x870000, Color89: 0x87005F, Color90: 0x870087, Color91: 0x8700AF, Color92: 0x8700D7, Color93: 0x8700FF, Color94: 0x875F00, Color95: 0x875F5F, Color96: 0x875F87, Color97: 0x875FAF, Color98: 0x875FD7, Color99: 0x875FFF, Color100: 0x878700, Color101: 0x87875F, Color102: 0x878787, Color103: 0x8787AF, Color104: 0x8787D7, Color105: 0x8787FF, Color106: 0x87AF00, Color107: 0x87AF5F, Color108: 0x87AF87, Color109: 0x87AFAF, Color110: 0x87AFD7, Color111: 0x87AFFF, Color112: 0x87D700, Color113: 0x87D75F, Color114: 0x87D787, Color115: 0x87D7AF, Color116: 0x87D7D7, Color117: 0x87D7FF, Color118: 0x87FF00, Color119: 0x87FF5F, Color120: 0x87FF87, Color121: 0x87FFAF, Color122: 0x87FFD7, Color123: 0x87FFFF, Color124: 0xAF0000, Color125: 0xAF005F, Color126: 0xAF0087, Color127: 0xAF00AF, Color128: 0xAF00D7, Color129: 0xAF00FF, Color130: 0xAF5F00, Color131: 0xAF5F5F, Color132: 0xAF5F87, Color133: 0xAF5FAF, Color134: 0xAF5FD7, Color135: 0xAF5FFF, Color136: 0xAF8700, Color137: 0xAF875F, Color138: 0xAF8787, Color139: 0xAF87AF, Color140: 0xAF87D7, Color141: 0xAF87FF, Color142: 0xAFAF00, Color143: 0xAFAF5F, Color144: 0xAFAF87, Color145: 0xAFAFAF, Color146: 0xAFAFD7, Color147: 0xAFAFFF, Color148: 0xAFD700, Color149: 0xAFD75F, Color150: 0xAFD787, Color151: 0xAFD7AF, Color152: 0xAFD7D7, Color153: 0xAFD7FF, Color154: 0xAFFF00, Color155: 0xAFFF5F, Color156: 0xAFFF87, Color157: 0xAFFFAF, Color158: 0xAFFFD7, Color159: 0xAFFFFF, Color160: 0xD70000, Color161: 0xD7005F, Color162: 0xD70087, Color163: 0xD700AF, Color164: 0xD700D7, Color165: 0xD700FF, Color166: 0xD75F00, Color167: 0xD75F5F, Color168: 0xD75F87, Color169: 0xD75FAF, Color170: 0xD75FD7, Color171: 0xD75FFF, Color172: 0xD78700, Color173: 0xD7875F, Color174: 0xD78787, Color175: 0xD787AF, Color176: 0xD787D7, Color177: 0xD787FF, Color178: 0xD7AF00, Color179: 0xD7AF5F, Color180: 0xD7AF87, Color181: 0xD7AFAF, Color182: 0xD7AFD7, Color183: 0xD7AFFF, Color184: 0xD7D700, Color185: 0xD7D75F, Color186: 0xD7D787, Color187: 0xD7D7AF, Color188: 0xD7D7D7, Color189: 0xD7D7FF, Color190: 0xD7FF00, Color191: 0xD7FF5F, Color192: 0xD7FF87, Color193: 0xD7FFAF, Color194: 0xD7FFD7, Color195: 0xD7FFFF, Color196: 0xFF0000, // red Color197: 0xFF005F, Color198: 0xFF0087, Color199: 0xFF00AF, Color200: 0xFF00D7, Color201: 0xFF00FF, // fuchsia Color202: 0xFF5F00, Color203: 0xFF5F5F, Color204: 0xFF5F87, Color205: 0xFF5FAF, Color206: 0xFF5FD7, Color207: 0xFF5FFF, Color208: 0xFF8700, Color209: 0xFF875F, Color210: 0xFF8787, Color211: 0xFF87AF, Color212: 0xFF87D7, Color213: 0xFF87FF, Color214: 0xFFAF00, Color215: 0xFFAF5F, Color216: 0xFFAF87, Color217: 0xFFAFAF, Color218: 0xFFAFD7, Color219: 0xFFAFFF, Color220: 0xFFD700, Color221: 0xFFD75F, Color222: 0xFFD787, Color223: 0xFFD7AF, Color224: 0xFFD7D7, Color225: 0xFFD7FF, Color226: 0xFFFF00, // yellow Color227: 0xFFFF5F, Color228: 0xFFFF87, Color229: 0xFFFFAF, Color230: 0xFFFFD7, Color231: 0xFFFFFF, // white Color232: 0x080808, Color233: 0x121212, Color234: 0x1C1C1C, Color235: 0x262626, Color236: 0x303030, Color237: 0x3A3A3A, Color238: 0x444444, Color239: 0x4E4E4E, Color240: 0x585858, Color241: 0x626262, Color242: 0x6C6C6C, Color243: 0x767676, Color244: 0x808080, // grey Color245: 0x8A8A8A, Color246: 0x949494, Color247: 0x9E9E9E, Color248: 0xA8A8A8, Color249: 0xB2B2B2, Color250: 0xBCBCBC, Color251: 0xC6C6C6, Color252: 0xD0D0D0, Color253: 0xDADADA, Color254: 0xE4E4E4, Color255: 0xEEEEEE, ColorAliceBlue: 0xF0F8FF, ColorAntiqueWhite: 0xFAEBD7, ColorAquaMarine: 0x7FFFD4, ColorAzure: 0xF0FFFF, ColorBeige: 0xF5F5DC, ColorBisque: 0xFFE4C4, ColorBlanchedAlmond: 0xFFEBCD, ColorBlueViolet: 0x8A2BE2, ColorBrown: 0xA52A2A, ColorBurlyWood: 0xDEB887, ColorCadetBlue: 0x5F9EA0, ColorChartreuse: 0x7FFF00, ColorChocolate: 0xD2691E, ColorCoral: 0xFF7F50, ColorCornflowerBlue: 0x6495ED, ColorCornsilk: 0xFFF8DC, ColorCrimson: 0xDC143C, ColorDarkBlue: 0x00008B, ColorDarkCyan: 0x008B8B, ColorDarkGoldenrod: 0xB8860B, ColorDarkGray: 0xA9A9A9, ColorDarkGreen: 0x006400, ColorDarkKhaki: 0xBDB76B, ColorDarkMagenta: 0x8B008B, ColorDarkOliveGreen: 0x556B2F, ColorDarkOrange: 0xFF8C00, ColorDarkOrchid: 0x9932CC, ColorDarkRed: 0x8B0000, ColorDarkSalmon: 0xE9967A, ColorDarkSeaGreen: 0x8FBC8F, ColorDarkSlateBlue: 0x483D8B, ColorDarkSlateGray: 0x2F4F4F, ColorDarkTurquoise: 0x00CED1, ColorDarkViolet: 0x9400D3, ColorDeepPink: 0xFF1493, ColorDeepSkyBlue: 0x00BFFF, ColorDimGray: 0x696969, ColorDodgerBlue: 0x1E90FF, ColorFireBrick: 0xB22222, ColorFloralWhite: 0xFFFAF0, ColorForestGreen: 0x228B22, ColorGainsboro: 0xDCDCDC, ColorGhostWhite: 0xF8F8FF, ColorGold: 0xFFD700, ColorGoldenrod: 0xDAA520, ColorGreenYellow: 0xADFF2F, ColorHoneydew: 0xF0FFF0, ColorHotPink: 0xFF69B4, ColorIndianRed: 0xCD5C5C, ColorIndigo: 0x4B0082, ColorIvory: 0xFFFFF0, ColorKhaki: 0xF0E68C, ColorLavender: 0xE6E6FA, ColorLavenderBlush: 0xFFF0F5, ColorLawnGreen: 0x7CFC00, ColorLemonChiffon: 0xFFFACD, ColorLightBlue: 0xADD8E6, ColorLightCoral: 0xF08080, ColorLightCyan: 0xE0FFFF, ColorLightGoldenrodYellow: 0xFAFAD2, ColorLightGray: 0xD3D3D3, ColorLightGreen: 0x90EE90, ColorLightPink: 0xFFB6C1, ColorLightSalmon: 0xFFA07A, ColorLightSeaGreen: 0x20B2AA, ColorLightSkyBlue: 0x87CEFA, ColorLightSlateGray: 0x778899, ColorLightSteelBlue: 0xB0C4DE, ColorLightYellow: 0xFFFFE0, ColorLimeGreen: 0x32CD32, ColorLinen: 0xFAF0E6, ColorMediumAquamarine: 0x66CDAA, ColorMediumBlue: 0x0000CD, ColorMediumOrchid: 0xBA55D3, ColorMediumPurple: 0x9370DB, ColorMediumSeaGreen: 0x3CB371, ColorMediumSlateBlue: 0x7B68EE, ColorMediumSpringGreen: 0x00FA9A, ColorMediumTurquoise: 0x48D1CC, ColorMediumVioletRed: 0xC71585, ColorMidnightBlue: 0x191970, ColorMintCream: 0xF5FFFA, ColorMistyRose: 0xFFE4E1, ColorMoccasin: 0xFFE4B5, ColorNavajoWhite: 0xFFDEAD, ColorOldLace: 0xFDF5E6, ColorOliveDrab: 0x6B8E23, ColorOrange: 0xFFA500, ColorOrangeRed: 0xFF4500, ColorOrchid: 0xDA70D6, ColorPaleGoldenrod: 0xEEE8AA, ColorPaleGreen: 0x98FB98, ColorPaleTurquoise: 0xAFEEEE, ColorPaleVioletRed: 0xDB7093, ColorPapayaWhip: 0xFFEFD5, ColorPeachPuff: 0xFFDAB9, ColorPeru: 0xCD853F, ColorPink: 0xFFC0CB, ColorPlum: 0xDDA0DD, ColorPowderBlue: 0xB0E0E6, ColorRebeccaPurple: 0x663399, ColorRosyBrown: 0xBC8F8F, ColorRoyalBlue: 0x4169E1, ColorSaddleBrown: 0x8B4513, ColorSalmon: 0xFA8072, ColorSandyBrown: 0xF4A460, ColorSeaGreen: 0x2E8B57, ColorSeashell: 0xFFF5EE, ColorSienna: 0xA0522D, ColorSkyblue: 0x87CEEB, ColorSlateBlue: 0x6A5ACD, ColorSlateGray: 0x708090, ColorSnow: 0xFFFAFA, ColorSpringGreen: 0x00FF7F, ColorSteelBlue: 0x4682B4, ColorTan: 0xD2B48C, ColorThistle: 0xD8BFD8, ColorTomato: 0xFF6347, ColorTurquoise: 0x40E0D0, ColorViolet: 0xEE82EE, ColorWheat: 0xF5DEB3, ColorWhiteSmoke: 0xF5F5F5, ColorYellowGreen: 0x9ACD32, } // Special colors. const ( // ColorReset is used to indicate that the color should use the // vanilla terminal colors. (Basically go back to the defaults.) ColorReset = ColorSpecial | iota // ColorNone indicates that we should not change the color from // whatever is already displayed. This can only be used in limited // circumstances. ColorNone ) // ColorNames holds the written names of colors. Useful to present a list of // recognized named colors. var ColorNames = map[string]Color{ "black": ColorBlack, "maroon": ColorMaroon, "green": ColorGreen, "olive": ColorOlive, "navy": ColorNavy, "purple": ColorPurple, "teal": ColorTeal, "silver": ColorSilver, "gray": ColorGray, "red": ColorRed, "lime": ColorLime, "yellow": ColorYellow, "blue": ColorBlue, "fuchsia": ColorFuchsia, "aqua": ColorAqua, "white": ColorWhite, "aliceblue": ColorAliceBlue, "antiquewhite": ColorAntiqueWhite, "aquamarine": ColorAquaMarine, "azure": ColorAzure, "beige": ColorBeige, "bisque": ColorBisque, "blanchedalmond": ColorBlanchedAlmond, "blueviolet": ColorBlueViolet, "brown": ColorBrown, "burlywood": ColorBurlyWood, "cadetblue": ColorCadetBlue, "chartreuse": ColorChartreuse, "chocolate": ColorChocolate, "coral": ColorCoral, "cornflowerblue": ColorCornflowerBlue, "cornsilk": ColorCornsilk, "crimson": ColorCrimson, "darkblue": ColorDarkBlue, "darkcyan": ColorDarkCyan, "darkgoldenrod": ColorDarkGoldenrod, "darkgray": ColorDarkGray, "darkgreen": ColorDarkGreen, "darkkhaki": ColorDarkKhaki, "darkmagenta": ColorDarkMagenta, "darkolivegreen": ColorDarkOliveGreen, "darkorange": ColorDarkOrange, "darkorchid": ColorDarkOrchid, "darkred": ColorDarkRed, "darksalmon": ColorDarkSalmon, "darkseagreen": ColorDarkSeaGreen, "darkslateblue": ColorDarkSlateBlue, "darkslategray": ColorDarkSlateGray, "darkturquoise": ColorDarkTurquoise, "darkviolet": ColorDarkViolet, "deeppink": ColorDeepPink, "deepskyblue": ColorDeepSkyBlue, "dimgray": ColorDimGray, "dodgerblue": ColorDodgerBlue, "firebrick": ColorFireBrick, "floralwhite": ColorFloralWhite, "forestgreen": ColorForestGreen, "gainsboro": ColorGainsboro, "ghostwhite": ColorGhostWhite, "gold": ColorGold, "goldenrod": ColorGoldenrod, "greenyellow": ColorGreenYellow, "honeydew": ColorHoneydew, "hotpink": ColorHotPink, "indianred": ColorIndianRed, "indigo": ColorIndigo, "ivory": ColorIvory, "khaki": ColorKhaki, "lavender": ColorLavender, "lavenderblush": ColorLavenderBlush, "lawngreen": ColorLawnGreen, "lemonchiffon": ColorLemonChiffon, "lightblue": ColorLightBlue, "lightcoral": ColorLightCoral, "lightcyan": ColorLightCyan, "lightgoldenrodyellow": ColorLightGoldenrodYellow, "lightgray": ColorLightGray, "lightgreen": ColorLightGreen, "lightpink": ColorLightPink, "lightsalmon": ColorLightSalmon, "lightseagreen": ColorLightSeaGreen, "lightskyblue": ColorLightSkyBlue, "lightslategray": ColorLightSlateGray, "lightsteelblue": ColorLightSteelBlue, "lightyellow": ColorLightYellow, "limegreen": ColorLimeGreen, "linen": ColorLinen, "mediumaquamarine": ColorMediumAquamarine, "mediumblue": ColorMediumBlue, "mediumorchid": ColorMediumOrchid, "mediumpurple": ColorMediumPurple, "mediumseagreen": ColorMediumSeaGreen, "mediumslateblue": ColorMediumSlateBlue, "mediumspringgreen": ColorMediumSpringGreen, "mediumturquoise": ColorMediumTurquoise, "mediumvioletred": ColorMediumVioletRed, "midnightblue": ColorMidnightBlue, "mintcream": ColorMintCream, "mistyrose": ColorMistyRose, "moccasin": ColorMoccasin, "navajowhite": ColorNavajoWhite, "oldlace": ColorOldLace, "olivedrab": ColorOliveDrab, "orange": ColorOrange, "orangered": ColorOrangeRed, "orchid": ColorOrchid, "palegoldenrod": ColorPaleGoldenrod, "palegreen": ColorPaleGreen, "paleturquoise": ColorPaleTurquoise, "palevioletred": ColorPaleVioletRed, "papayawhip": ColorPapayaWhip, "peachpuff": ColorPeachPuff, "peru": ColorPeru, "pink": ColorPink,
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/wscreen.go
vendor/github.com/gdamore/tcell/v2/wscreen.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build js && wasm // +build js,wasm package tcell import ( "errors" "fmt" "sync" "syscall/js" "unicode/utf8" "github.com/gdamore/tcell/v2/terminfo" ) func NewTerminfoScreen() (Screen, error) { t := &wScreen{} t.fallback = make(map[rune]string) return &baseScreen{screenImpl: t}, nil } type wScreen struct { w, h int style Style cells CellBuffer running bool clear bool flagsPresent bool pasteEnabled bool mouseFlags MouseFlags cursorStyle CursorStyle quit chan struct{} evch chan Event fallback map[rune]string finiOnce sync.Once sync.Mutex } func (t *wScreen) Init() error { t.w, t.h = 80, 24 // default for html as of now t.evch = make(chan Event, 10) t.quit = make(chan struct{}) t.Lock() t.running = true t.style = StyleDefault t.cells.Resize(t.w, t.h) t.Unlock() js.Global().Set("onKeyEvent", js.FuncOf(t.onKeyEvent)) js.Global().Set("onMouseClick", js.FuncOf(t.unset)) js.Global().Set("onMouseMove", js.FuncOf(t.unset)) js.Global().Set("onFocus", js.FuncOf(t.unset)) return nil } func (t *wScreen) Fini() { t.finiOnce.Do(func() { close(t.quit) }) } func (t *wScreen) SetStyle(style Style) { t.Lock() t.style = style t.Unlock() } // paletteColor gives a more natural palette color actually matching // typical XTerm. We might in the future want to permit styling these // via CSS. var palette = map[Color]int32{ ColorBlack: 0x000000, ColorMaroon: 0xcd0000, ColorGreen: 0x00cd00, ColorOlive: 0xcdcd00, ColorNavy: 0x0000ee, ColorPurple: 0xcd00cd, ColorTeal: 0x00cdcd, ColorSilver: 0xe5e5e5, ColorGray: 0x7f7f7f, ColorRed: 0xff0000, ColorLime: 0x00ff00, ColorYellow: 0xffff00, ColorBlue: 0x5c5cff, ColorFuchsia: 0xff00ff, ColorAqua: 0x00ffff, ColorWhite: 0xffffff, } func paletteColor(c Color) int32 { if c.IsRGB() { return int32(c & 0xffffff) } if c >= ColorBlack && c <= ColorWhite { return palette[c] } return c.Hex() } func (t *wScreen) drawCell(x, y int) int { str, style, width := t.cells.Get(x, y) if !t.cells.Dirty(x, y) { return width } if style == StyleDefault { style = t.style } fg, bg := paletteColor(style.fg), paletteColor(style.bg) if fg == -1 { fg = 0xe5e5e5 } if bg == -1 { bg = 0x000000 } us, uc := style.ulStyle, paletteColor(style.ulColor) if uc == -1 { uc = 0x000000 } t.cells.SetDirty(x, y, false) js.Global().Call("drawCell", x, y, str, fg, bg, int(style.attrs), int(us), int(uc)) return width } func (t *wScreen) ShowCursor(x, y int) { t.Lock() js.Global().Call("showCursor", x, y) t.Unlock() } func (t *wScreen) SetCursor(cs CursorStyle, cc Color) { if !cc.Valid() { cc = ColorLightGray } t.Lock() js.Global().Call("setCursorStyle", curStyleClasses[cs], fmt.Sprintf("#%06x", cc.Hex())) t.Unlock() } func (t *wScreen) HideCursor() { t.ShowCursor(-1, -1) } func (t *wScreen) Show() { t.Lock() t.resize() t.draw() t.Unlock() } func (t *wScreen) clearScreen() { js.Global().Call("clearScreen", t.style.fg.Hex(), t.style.bg.Hex()) t.clear = false } func (t *wScreen) draw() { if t.clear { t.clearScreen() } for y := 0; y < t.h; y++ { for x := 0; x < t.w; x++ { width := t.drawCell(x, y) x += width - 1 } } js.Global().Call("show") } func (t *wScreen) EnableMouse(flags ...MouseFlags) { var f MouseFlags flagsPresent := false for _, flag := range flags { f |= flag flagsPresent = true } if !flagsPresent { f = MouseMotionEvents | MouseDragEvents | MouseButtonEvents } t.Lock() t.mouseFlags = f t.enableMouse(f) t.Unlock() } func (t *wScreen) enableMouse(f MouseFlags) { if f&MouseButtonEvents != 0 { js.Global().Set("onMouseClick", js.FuncOf(t.onMouseEvent)) } else { js.Global().Set("onMouseClick", js.FuncOf(t.unset)) } if f&MouseDragEvents != 0 || f&MouseMotionEvents != 0 { js.Global().Set("onMouseMove", js.FuncOf(t.onMouseEvent)) } else { js.Global().Set("onMouseMove", js.FuncOf(t.unset)) } } func (t *wScreen) DisableMouse() { t.Lock() t.mouseFlags = 0 t.enableMouse(0) t.Unlock() } func (t *wScreen) EnablePaste() { t.Lock() t.pasteEnabled = true t.enablePasting(true) t.Unlock() } func (t *wScreen) DisablePaste() { t.Lock() t.pasteEnabled = false t.enablePasting(false) t.Unlock() } func (t *wScreen) enablePasting(on bool) { if on { js.Global().Set("onPaste", js.FuncOf(t.onPaste)) } else { js.Global().Set("onPaste", js.FuncOf(t.unset)) } } func (t *wScreen) EnableFocus() { t.Lock() js.Global().Set("onFocus", js.FuncOf(t.onFocus)) t.Unlock() } func (t *wScreen) DisableFocus() { t.Lock() js.Global().Set("onFocus", js.FuncOf(t.unset)) t.Unlock() } func (s *wScreen) GetClipboard() { } func (s *wScreen) SetClipboard(_ []byte) { } func (t *wScreen) Size() (int, int) { t.Lock() w, h := t.w, t.h t.Unlock() return w, h } // resize does nothing, as asking the web window to resize // without a specified width or height will cause no change. func (t *wScreen) resize() {} func (t *wScreen) Colors() int { return 16777216 // 256 ^ 3 } func (t *wScreen) clip(x, y int) (int, int) { w, h := t.cells.Size() if x < 0 { x = 0 } if y < 0 { y = 0 } if x > w-1 { x = w - 1 } if y > h-1 { y = h - 1 } return x, y } func (t *wScreen) postEvent(ev Event) { select { case t.evch <- ev: case <-t.quit: } } func (t *wScreen) onMouseEvent(this js.Value, args []js.Value) interface{} { mod := ModNone button := ButtonNone switch args[2].Int() { case 0: if t.mouseFlags&MouseMotionEvents == 0 { // don't want this event! is a mouse motion event, but user has asked not. return nil } button = ButtonNone case 1: button = Button1 case 2: button = Button3 // Note we prefer to treat right as button 2 case 3: button = Button2 // And the middle button as button 3 } if args[3].Bool() { // mod shift mod |= ModShift } if args[4].Bool() { // mod alt mod |= ModAlt } if args[5].Bool() { // mod ctrl mod |= ModCtrl } t.postEvent(NewEventMouse(args[0].Int(), args[1].Int(), button, mod)) return nil } func (t *wScreen) onKeyEvent(this js.Value, args []js.Value) interface{} { key := args[0].String() // don't accept any modifier keys as their own if key == "Control" || key == "Alt" || key == "Meta" || key == "Shift" { return nil } mod := ModNone if args[1].Bool() { // mod shift mod |= ModShift } if args[2].Bool() { // mod alt mod |= ModAlt } if args[3].Bool() { // mod ctrl mod |= ModCtrl } if args[4].Bool() { // mod meta mod |= ModMeta } // next try function keys if k, ok := WebKeyNames[key]; ok { t.postEvent(NewEventKey(k, 0, mod)) return nil } // finally try normal, printable chars r, _ := utf8.DecodeRuneInString(key) t.postEvent(NewEventKey(KeyRune, r, mod)) return nil } func (t *wScreen) onPaste(this js.Value, args []js.Value) interface{} { t.postEvent(NewEventPaste(args[0].Bool())) return nil } func (t *wScreen) onFocus(this js.Value, args []js.Value) interface{} { t.postEvent(NewEventFocus(args[0].Bool())) return nil } // unset is a dummy function for js when we want nothing to // happen when javascript calls a function (for example, when // mouse input is disabled, when onMouseEvent() is called from // js, it redirects here and does nothing). func (t *wScreen) unset(this js.Value, args []js.Value) interface{} { return nil } func (t *wScreen) Sync() { t.Lock() t.resize() t.clear = true t.cells.Invalidate() t.draw() t.Unlock() } func (t *wScreen) CharacterSet() string { return "UTF-8" } func (t *wScreen) RegisterRuneFallback(orig rune, fallback string) { t.Lock() t.fallback[orig] = fallback t.Unlock() } func (t *wScreen) UnregisterRuneFallback(orig rune) { t.Lock() delete(t.fallback, orig) t.Unlock() } func (t *wScreen) CanDisplay(r rune, checkFallbacks bool) bool { if utf8.ValidRune(r) { return true } if !checkFallbacks { return false } if _, ok := t.fallback[r]; ok { return true } return false } func (t *wScreen) HasMouse() bool { return true } func (t *wScreen) HasKey(k Key) bool { return true } func (t *wScreen) SetSize(w, h int) { if w == t.w && h == t.h { return } t.cells.Invalidate() t.cells.Resize(w, h) js.Global().Call("resize", w, h) t.w, t.h = w, h t.postEvent(NewEventResize(w, h)) } func (t *wScreen) Resize(int, int, int, int) {} // Suspend simply pauses all input and output, and clears the screen. // There isn't a "default terminal" to go back to. func (t *wScreen) Suspend() error { t.Lock() if !t.running { t.Unlock() return nil } t.running = false t.clearScreen() t.enableMouse(0) t.enablePasting(false) js.Global().Set("onKeyEvent", js.FuncOf(t.unset)) // stop keypresses return nil } func (t *wScreen) Resume() error { t.Lock() if t.running { return errors.New("already engaged") } t.running = true t.enableMouse(t.mouseFlags) t.enablePasting(t.pasteEnabled) js.Global().Set("onKeyEvent", js.FuncOf(t.onKeyEvent)) t.Unlock() return nil } func (t *wScreen) Beep() error { js.Global().Call("beep") return nil } func (t *wScreen) Tty() (Tty, bool) { return nil, false } func (t *wScreen) GetCells() *CellBuffer { return &t.cells } func (t *wScreen) EventQ() chan Event { return t.evch } func (t *wScreen) StopQ() <-chan struct{} { return t.quit } func (t *wScreen) SetTitle(title string) { js.Global().Call("setTitle", title) } // WebKeyNames maps string names reported from HTML // (KeyboardEvent.key) to tcell accepted keys. var WebKeyNames = map[string]Key{ "Enter": KeyEnter, "Backspace": KeyBackspace, "Tab": KeyTab, "Backtab": KeyBacktab, "Escape": KeyEsc, "Backspace2": KeyBackspace2, "Delete": KeyDelete, "Insert": KeyInsert, "ArrowUp": KeyUp, "ArrowDown": KeyDown, "ArrowLeft": KeyLeft, "ArrowRight": KeyRight, "Home": KeyHome, "End": KeyEnd, "UpLeft": KeyUpLeft, // not supported by HTML "UpRight": KeyUpRight, // not supported by HTML "DownLeft": KeyDownLeft, // not supported by HTML "DownRight": KeyDownRight, // not supported by HTML "Center": KeyCenter, "PgDn": KeyPgDn, "PgUp": KeyPgUp, "Clear": KeyClear, "Exit": KeyExit, "Cancel": KeyCancel, "Pause": KeyPause, "Print": KeyPrint, "F1": KeyF1, "F2": KeyF2, "F3": KeyF3, "F4": KeyF4, "F5": KeyF5, "F6": KeyF6, "F7": KeyF7, "F8": KeyF8, "F9": KeyF9, "F10": KeyF10, "F11": KeyF11, "F12": KeyF12, "F13": KeyF13, "F14": KeyF14, "F15": KeyF15, "F16": KeyF16, "F17": KeyF17, "F18": KeyF18, "F19": KeyF19, "F20": KeyF20, "F21": KeyF21, "F22": KeyF22, "F23": KeyF23, "F24": KeyF24, "F25": KeyF25, "F26": KeyF26, "F27": KeyF27, "F28": KeyF28, "F29": KeyF29, "F30": KeyF30, "F31": KeyF31, "F32": KeyF32, "F33": KeyF33, "F34": KeyF34, "F35": KeyF35, "F36": KeyF36, "F37": KeyF37, "F38": KeyF38, "F39": KeyF39, "F40": KeyF40, "F41": KeyF41, "F42": KeyF42, "F43": KeyF43, "F44": KeyF44, "F45": KeyF45, "F46": KeyF46, "F47": KeyF47, "F48": KeyF48, "F49": KeyF49, "F50": KeyF50, "F51": KeyF51, "F52": KeyF52, "F53": KeyF53, "F54": KeyF54, "F55": KeyF55, "F56": KeyF56, "F57": KeyF57, "F58": KeyF58, "F59": KeyF59, "F60": KeyF60, "F61": KeyF61, "F62": KeyF62, "F63": KeyF63, "F64": KeyF64, } var curStyleClasses = map[CursorStyle]string{ CursorStyleDefault: "cursor-blinking-block", CursorStyleBlinkingBlock: "cursor-blinking-block", CursorStyleSteadyBlock: "cursor-steady-block", CursorStyleBlinkingUnderline: "cursor-blinking-underline", CursorStyleSteadyUnderline: "cursor-steady-underline", CursorStyleBlinkingBar: "cursor-blinking-bar", CursorStyleSteadyBar: "cursor-steady-bar", } func LookupTerminfo(name string) (ti *terminfo.Terminfo, e error) { return nil, errors.New("LookupTermInfo not supported") }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/resize.go
vendor/github.com/gdamore/tcell/v2/resize.go
// Copyright 2015 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "time" ) // EventResize is sent when the window size changes. type EventResize struct { t time.Time ws WindowSize } // NewEventResize creates an EventResize with the new updated window size, // which is given in character cells. func NewEventResize(width, height int) *EventResize { ws := WindowSize{ Width: width, Height: height, } return &EventResize{t: time.Now(), ws: ws} } // When returns the time when the Event was created. func (ev *EventResize) When() time.Time { return ev.t } // Size returns the new window size as width, height in character cells. func (ev *EventResize) Size() (int, int) { return ev.ws.Width, ev.ws.Height } // PixelSize returns the new window size as width, height in pixels. The size // will be 0,0 if the screen doesn't support this feature func (ev *EventResize) PixelSize() (int, int) { return ev.ws.PixelWidth, ev.ws.PixelHeight } type WindowSize struct { Width int Height int PixelWidth int PixelHeight int } // CellDimensions returns the dimensions of a single cell, in pixels func (ws WindowSize) CellDimensions() (int, int) { if ws.PixelWidth == 0 || ws.PixelHeight == 0 { return 0, 0 } return (ws.PixelWidth / ws.Width), (ws.PixelHeight / ws.Height) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/tscreen_unix.go
vendor/github.com/gdamore/tcell/v2/tscreen_unix.go
// Copyright 2024 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos package tcell import ( // import the stock terminals _ "github.com/gdamore/tcell/v2/terminfo/base" ) // initialize is used at application startup, and sets up the initial values // including file descriptors used for terminals and saving the initial state // so that it can be restored when the application terminates. func (t *tScreen) initialize() error { var err error if t.tty == nil { t.tty, err = NewDevTty() if err != nil { return err } } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/focus.go
vendor/github.com/gdamore/tcell/v2/focus.go
// Copyright 2023 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell // EventFocus is a focus event. It is sent when the terminal window (or tab) // gets or loses focus. type EventFocus struct { *EventTime // True if the window received focus, false if it lost focus Focused bool } func NewEventFocus(focused bool) *EventFocus { return &EventFocus{Focused: focused} }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/tty_win.go
vendor/github.com/gdamore/tcell/v2/tty_win.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build windows // +build windows package tcell import ( "encoding/binary" "errors" "sync" "syscall" "time" "unicode/utf16" "unsafe" ) var ( k32 = syscall.NewLazyDLL("kernel32.dll") ) var ( procReadConsoleInput = k32.NewProc("ReadConsoleInputW") procGetNumberOfConsoleInputEvents = k32.NewProc("GetNumberOfConsoleInputEvents") procFlushConsoleInputBuffer = k32.NewProc("FlushConsoleInputBuffer") procWaitForMultipleObjects = k32.NewProc("WaitForMultipleObjects") procSetConsoleMode = k32.NewProc("SetConsoleMode") procGetConsoleMode = k32.NewProc("GetConsoleMode") procGetConsoleScreenBufferInfo = k32.NewProc("GetConsoleScreenBufferInfo") procCreateEvent = k32.NewProc("CreateEventW") procSetEvent = k32.NewProc("SetEvent") ) const ( keyEvent uint16 = 1 mouseEvent uint16 = 2 resizeEvent uint16 = 4 menuEvent uint16 = 8 // don't use focusEvent uint16 = 16 ) type inputRecord struct { typ uint16 _ uint16 data [16]byte } type winTty struct { buf chan byte out syscall.Handle in syscall.Handle cancelFlag syscall.Handle running bool stopQ chan struct{} resizeCb func() cols uint16 rows uint16 pair []uint16 // for surrogate pairs (UTF-16) oimode uint32 // original input mode oomode uint32 // original output mode oscreen consoleInfo wg sync.WaitGroup sync.Mutex } func (w *winTty) Read(b []byte) (int, error) { // first character read blocks var num int select { case c := <-w.buf: b[0] = c num++ case <-w.stopQ: // stopping, so make sure we eat everything, which might require // very short sleeps to ensure all buffered data is consumed. break } // second character read is non-blocking for ; num < len(b); num++ { select { case c := <-w.buf: b[num] = c case <-time.After(time.Millisecond * 10): return num, nil } } return num, nil } func (w *winTty) Write(b []byte) (int, error) { esc := utf16.Encode([]rune(string(b))) if len(esc) > 0 { err := syscall.WriteConsole(w.out, &esc[0], uint32(len(esc)), nil, nil) if err != nil { return 0, err } } return len(b), nil } func (w *winTty) Close() error { _ = syscall.Close(w.in) _ = syscall.Close(w.out) return nil } func (w *winTty) Drain() error { close(w.stopQ) time.Sleep(time.Millisecond * 10) _, _, _ = procSetEvent.Call(uintptr(w.cancelFlag)) return nil } func (w *winTty) getConsoleInput() error { // cancelFlag comes first as WaitForMultipleObjects returns the lowest index // in the event that both events are signalled. waitObjects := []syscall.Handle{w.cancelFlag, w.in} // As arrays are contiguous in memory, a pointer to the first object is the // same as a pointer to the array itself. pWaitObjects := unsafe.Pointer(&waitObjects[0]) rv, _, er := procWaitForMultipleObjects.Call( uintptr(len(waitObjects)), uintptr(pWaitObjects), uintptr(0), w32Infinite) // WaitForMultipleObjects returns WAIT_OBJECT_0 + the index. switch rv { case w32WaitObject0: // w.cancelFlag return errors.New("cancelled") case w32WaitObject0 + 1: // w.in // rec := &inputRecord{} var nrec int32 rv, _, er := procGetNumberOfConsoleInputEvents.Call( uintptr(w.in), uintptr(unsafe.Pointer(&nrec))) rec := make([]inputRecord, nrec) rv, _, er = procReadConsoleInput.Call( uintptr(w.in), uintptr(unsafe.Pointer(&rec[0])), uintptr(nrec), uintptr(unsafe.Pointer(&nrec))) if rv == 0 { return er } for i := range nrec { ir := rec[i] switch ir.typ { case keyEvent: chr := ir.data[10] // we only see ASCII, key down events in VT mode // because we use win32-input-mode, we will only // see US-ASCII characters - (Q: will they be // 16-bit values with possible surrogate pairs?) select { case w.buf <- chr: case <-w.stopQ: break } case resizeEvent: w.Lock() w.cols = binary.LittleEndian.Uint16(ir.data[0:]) w.rows = binary.LittleEndian.Uint16(ir.data[2:]) cb := w.resizeCb w.Unlock() if cb != nil { cb() } default: } } return nil default: return er } } func (w *winTty) scanInput() { defer w.wg.Done() for { if e := w.getConsoleInput(); e != nil { return } } } func (w *winTty) Start() error { w.Lock() defer w.Unlock() if w.running { return errors.New("already engaged") } _, _, _ = procFlushConsoleInputBuffer.Call(uintptr(w.in)) w.stopQ = make(chan struct{}) cf, _, err := procCreateEvent.Call( uintptr(0), uintptr(1), uintptr(0), uintptr(0)) if cf == uintptr(0) { return err } w.running = true w.cancelFlag = syscall.Handle(cf) _, _, _ = procSetConsoleMode.Call(uintptr(w.in), uintptr(modeVtInput|modeResizeEn|modeExtendFlg)) _, _, _ = procSetConsoleMode.Call(uintptr(w.out), uintptr(modeVtOutput|modeNoAutoNL|modeCookedOut|modeUnderline)) w.wg.Add(1) go w.scanInput() return nil } func (w *winTty) Stop() error { w.wg.Wait() w.Lock() defer w.Unlock() _, _, _ = procSetConsoleMode.Call(uintptr(w.in), uintptr(w.oimode)) _, _, _ = procSetConsoleMode.Call(uintptr(w.out), uintptr(w.oomode)) _, _, _ = procFlushConsoleInputBuffer.Call(uintptr(w.in)) w.running = false return nil } func (w *winTty) NotifyResize(cb func()) { w.resizeCb = cb } func (w *winTty) WindowSize() (WindowSize, error) { w.Lock() defer w.Unlock() return WindowSize{Width: int(w.cols), Height: int(w.rows)}, nil } func NewDevTty() (Tty, error) { w := &winTty{} var err error w.in, err = syscall.Open("CONIN$", syscall.O_RDWR, 0) if err != nil { return nil, err } w.out, err = syscall.Open("CONOUT$", syscall.O_RDWR, 0) if err != nil { _ = syscall.Close(w.in) return nil, err } w.buf = make(chan byte, 128) _, _, _ = procGetConsoleScreenBufferInfo.Call(uintptr(w.out), uintptr(unsafe.Pointer(&w.oscreen))) _, _, _ = procGetConsoleMode.Call(uintptr(w.out), uintptr(unsafe.Pointer(&w.oomode))) _, _, _ = procGetConsoleMode.Call(uintptr(w.in), uintptr(unsafe.Pointer(&w.oimode))) w.rows = uint16(w.oscreen.size.y) w.cols = uint16(w.oscreen.size.x) return w, nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/console_win.go
vendor/github.com/gdamore/tcell/v2/console_win.go
//go:build windows // +build windows // Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "errors" "fmt" "os" "strings" "sync" "syscall" "unicode/utf16" "unsafe" ) type cScreen struct { in syscall.Handle out syscall.Handle cancelflag syscall.Handle scandone chan struct{} quit chan struct{} curx int cury int style Style fini bool truecolor bool running bool disableAlt bool // disable the alternate screen title string w int h int oscreen consoleInfo ocursor cursorInfo cursorStyle CursorStyle cursorColor Color oimode uint32 oomode uint32 cells CellBuffer focusEnable bool mouseEnabled bool wg sync.WaitGroup eventQ chan Event stopQ chan struct{} finiOnce sync.Once sync.Mutex } var winLock sync.Mutex var winPalette = []Color{ ColorBlack, ColorMaroon, ColorGreen, ColorNavy, ColorOlive, ColorPurple, ColorTeal, ColorSilver, ColorGray, ColorRed, ColorLime, ColorBlue, ColorYellow, ColorFuchsia, ColorAqua, ColorWhite, } var winColors = map[Color]Color{ ColorBlack: ColorBlack, ColorMaroon: ColorMaroon, ColorGreen: ColorGreen, ColorNavy: ColorNavy, ColorOlive: ColorOlive, ColorPurple: ColorPurple, ColorTeal: ColorTeal, ColorSilver: ColorSilver, ColorGray: ColorGray, ColorRed: ColorRed, ColorLime: ColorLime, ColorBlue: ColorBlue, ColorYellow: ColorYellow, ColorFuchsia: ColorFuchsia, ColorAqua: ColorAqua, ColorWhite: ColorWhite, } var ( u32 = syscall.NewLazyDLL("user32.dll") ) // We have to bring in the kernel32 and user32 DLLs directly, so we can get // access to some system calls that the core Go API lacks. // // Note that Windows appends some functions with W to indicate that wide // characters (Unicode) are in use. The documentation refers to them // without this suffix, as the resolution is made via preprocessor. var ( procGetConsoleCursorInfo = k32.NewProc("GetConsoleCursorInfo") procSetConsoleCursorInfo = k32.NewProc("SetConsoleCursorInfo") procSetConsoleWindowInfo = k32.NewProc("SetConsoleWindowInfo") procSetConsoleScreenBufferSize = k32.NewProc("SetConsoleScreenBufferSize") procSetConsoleTextAttribute = k32.NewProc("SetConsoleTextAttribute") procGetLargestConsoleWindowSize = k32.NewProc("GetLargestConsoleWindowSize") procMessageBeep = u32.NewProc("MessageBeep") ) const ( w32Infinite = ^uintptr(0) w32WaitObject0 = uintptr(0) ) const ( // VT100/XTerm escapes understood by the console vtShowCursor = "\x1b[?25h" vtHideCursor = "\x1b[?25l" vtCursorPos = "\x1b[%d;%dH" // Note that it is Y then X vtSgr0 = "\x1b[0m" vtBold = "\x1b[1m" vtUnderline = "\x1b[4m" vtBlink = "\x1b[5m" // Not sure if this is processed vtReverse = "\x1b[7m" vtSetFg = "\x1b[38;5;%dm" vtSetBg = "\x1b[48;5;%dm" vtSetFgRGB = "\x1b[38;2;%d;%d;%dm" // RGB vtSetBgRGB = "\x1b[48;2;%d;%d;%dm" // RGB vtCursorDefault = "\x1b[0 q" vtCursorBlinkingBlock = "\x1b[1 q" vtCursorSteadyBlock = "\x1b[2 q" vtCursorBlinkingUnderline = "\x1b[3 q" vtCursorSteadyUnderline = "\x1b[4 q" vtCursorBlinkingBar = "\x1b[5 q" vtCursorSteadyBar = "\x1b[6 q" vtDisableAm = "\x1b[?7l" vtEnableAm = "\x1b[?7h" vtEnterCA = "\x1b[?1049h\x1b[22;0;0t" vtExitCA = "\x1b[?1049l\x1b[23;0;0t" vtDoubleUnderline = "\x1b[4:2m" vtCurlyUnderline = "\x1b[4:3m" vtDottedUnderline = "\x1b[4:4m" vtDashedUnderline = "\x1b[4:5m" vtUnderColor = "\x1b[58:5:%dm" vtUnderColorRGB = "\x1b[58:2::%d:%d:%dm" vtUnderColorReset = "\x1b[59m" vtEnterUrl = "\x1b]8;%s;%s\x1b\\" // NB arg 1 is id, arg 2 is url vtExitUrl = "\x1b]8;;\x1b\\" vtCursorColorRGB = "\x1b]12;#%02x%02x%02x\007" vtCursorColorReset = "\x1b]112\007" vtSaveTitle = "\x1b[22;2t" vtRestoreTitle = "\x1b[23;2t" vtSetTitle = "\x1b]2;%s\x1b\\" ) var vtCursorStyles = map[CursorStyle]string{ CursorStyleDefault: vtCursorDefault, CursorStyleBlinkingBlock: vtCursorBlinkingBlock, CursorStyleSteadyBlock: vtCursorSteadyBlock, CursorStyleBlinkingUnderline: vtCursorBlinkingUnderline, CursorStyleSteadyUnderline: vtCursorSteadyUnderline, CursorStyleBlinkingBar: vtCursorBlinkingBar, CursorStyleSteadyBar: vtCursorSteadyBar, } // NewConsoleScreen returns a Screen for the Windows console associated // with the current process. The Screen makes use of the Windows Console // API to display content and read events. // // Deprecated: The console API based implementation will be fully replaced // with the VT based model. Use NewScreen() to get a reasonable screen // by default. func NewConsoleScreen() (Screen, error) { return &baseScreen{screenImpl: &cScreen{}}, nil } func (s *cScreen) Init() error { s.eventQ = make(chan Event, 10) s.quit = make(chan struct{}) s.scandone = make(chan struct{}) in, e := syscall.Open("CONIN$", syscall.O_RDWR, 0) if e != nil { return e } s.in = in out, e := syscall.Open("CONOUT$", syscall.O_RDWR, 0) if e != nil { _ = syscall.Close(s.in) return e } s.out = out s.truecolor = true switch os.Getenv("TCELL_TRUECOLOR") { case "disable": s.truecolor = false case "enable": s.truecolor = true } s.Lock() s.curx = -1 s.cury = -1 s.style = StyleDefault s.getCursorInfo(&s.ocursor) s.getConsoleInfo(&s.oscreen) s.getOutMode(&s.oomode) s.getInMode(&s.oimode) s.resize() s.fini = false s.setInMode(modeResizeEn | modeExtendFlg) switch os.Getenv("TCELL_ALTSCREEN") { case "enable": s.disableAlt = false // also the default case "disable": s.disableAlt = true } s.setOutMode(modeVtOutput | modeNoAutoNL | modeCookedOut | modeUnderline) var om uint32 s.getOutMode(&om) if om&modeVtOutput != modeVtOutput { return errors.New("failed to initialize: VT output not supported?") } s.Unlock() return s.engage() } func (s *cScreen) CharacterSet() string { // We are always UTF-16LE on Windows return "UTF-16LE" } func (s *cScreen) EnableMouse(...MouseFlags) { s.Lock() s.mouseEnabled = true s.enableMouse(true) s.Unlock() } func (s *cScreen) DisableMouse() { s.Lock() s.mouseEnabled = false s.enableMouse(false) s.Unlock() } func (s *cScreen) enableMouse(on bool) { if on { s.setInMode(modeResizeEn | modeMouseEn | modeExtendFlg) } else { s.setInMode(modeResizeEn | modeExtendFlg) } } // Windows lacks bracketed paste (for now) func (s *cScreen) EnablePaste() {} func (s *cScreen) DisablePaste() {} func (s *cScreen) EnableFocus() { s.Lock() s.focusEnable = true s.Unlock() } func (s *cScreen) DisableFocus() { s.Lock() s.focusEnable = false s.Unlock() } func (s *cScreen) Fini() { s.finiOnce.Do(func() { close(s.quit) s.disengage() }) } func (s *cScreen) disengage() { s.Lock() if !s.running { s.Unlock() return } s.running = false stopQ := s.stopQ _, _, _ = procSetEvent.Call(uintptr(s.cancelflag)) close(stopQ) s.Unlock() s.wg.Wait() s.emitVtString(vtCursorStyles[CursorStyleDefault]) s.emitVtString(vtCursorColorReset) s.emitVtString(vtEnableAm) if !s.disableAlt { s.emitVtString(vtRestoreTitle) s.emitVtString(vtExitCA) } s.setCursorInfo(&s.ocursor) s.setBufferSize(int(s.oscreen.size.x), int(s.oscreen.size.y)) s.setInMode(s.oimode) s.setOutMode(s.oomode) _, _, _ = procSetConsoleTextAttribute.Call( uintptr(s.out), uintptr(s.mapStyle(StyleDefault))) } func (s *cScreen) engage() error { s.Lock() defer s.Unlock() if s.running { return errors.New("already engaged") } s.stopQ = make(chan struct{}) cf, _, e := procCreateEvent.Call( uintptr(0), uintptr(1), uintptr(0), uintptr(0)) if cf == uintptr(0) { return e } s.running = true s.cancelflag = syscall.Handle(cf) s.enableMouse(s.mouseEnabled) s.setInMode(modeVtInput | modeResizeEn | modeExtendFlg) s.setOutMode(modeVtOutput | modeNoAutoNL | modeCookedOut | modeUnderline) if !s.disableAlt { s.emitVtString(vtSaveTitle) s.emitVtString(vtEnterCA) } s.emitVtString(vtDisableAm) if s.title != "" { s.emitVtString(fmt.Sprintf(vtSetTitle, s.title)) } s.clearScreen(s.style) s.hideCursor() s.cells.Invalidate() s.hideCursor() s.resize() s.draw() s.doCursor() s.wg.Add(1) go s.scanInput(s.stopQ) return nil } type cursorInfo struct { size uint32 visible uint32 } type coord struct { x int16 y int16 } func (c coord) uintptr() uintptr { // little endian, put x first return uintptr(c.x) | (uintptr(c.y) << 16) } type rect struct { left int16 top int16 right int16 bottom int16 } func (s *cScreen) emitVtString(vs string) { esc := utf16.Encode([]rune(vs)) _ = syscall.WriteConsole(s.out, &esc[0], uint32(len(esc)), nil, nil) } func (s *cScreen) showCursor() { s.emitVtString(vtShowCursor) s.emitVtString(vtCursorStyles[s.cursorStyle]) if s.cursorColor == ColorReset { s.emitVtString(vtCursorColorReset) } else if s.cursorColor.Valid() { r, g, b := s.cursorColor.RGB() s.emitVtString(fmt.Sprintf(vtCursorColorRGB, r, g, b)) } } func (s *cScreen) hideCursor() { s.emitVtString(vtHideCursor) } func (s *cScreen) ShowCursor(x, y int) { s.Lock() if !s.fini { s.curx = x s.cury = y } s.doCursor() s.Unlock() } func (s *cScreen) SetCursor(cs CursorStyle, cc Color) { s.Lock() if !s.fini { if _, ok := vtCursorStyles[cs]; ok { s.cursorStyle = cs s.cursorColor = cc s.doCursor() } } s.Unlock() } func (s *cScreen) doCursor() { x, y := s.curx, s.cury if x < 0 || y < 0 || x >= s.w || y >= s.h { s.hideCursor() } else { s.setCursorPos(x, y) s.showCursor() } } func (s *cScreen) HideCursor() { s.ShowCursor(-1, -1) } type mouseRecord struct { x int16 y int16 btns uint32 mod uint32 flags uint32 } type focusRecord struct { focused int32 // actually BOOL } const ( mouseHWheeled uint32 = 0x8 mouseVWheeled uint32 = 0x4 // mouseDoubleClick uint32 = 0x2 // mouseMoved uint32 = 0x1 ) type resizeRecord struct { x int16 y int16 } type keyRecord struct { isdown int32 repeat uint16 kcode uint16 scode uint16 ch uint16 mod uint32 } const ( // Constants per Microsoft. We don't put the modifiers // here. vkCancel = 0x03 vkBack = 0x08 // Backspace vkTab = 0x09 vkClear = 0x0c vkReturn = 0x0d vkPause = 0x13 vkEscape = 0x1b vkSpace = 0x20 vkPrior = 0x21 // PgUp vkNext = 0x22 // PgDn vkEnd = 0x23 vkHome = 0x24 vkLeft = 0x25 vkUp = 0x26 vkRight = 0x27 vkDown = 0x28 vkPrint = 0x2a vkPrtScr = 0x2c vkInsert = 0x2d vkDelete = 0x2e vkHelp = 0x2f vkF1 = 0x70 vkF2 = 0x71 vkF3 = 0x72 vkF4 = 0x73 vkF5 = 0x74 vkF6 = 0x75 vkF7 = 0x76 vkF8 = 0x77 vkF9 = 0x78 vkF10 = 0x79 vkF11 = 0x7a vkF12 = 0x7b vkF13 = 0x7c vkF14 = 0x7d vkF15 = 0x7e vkF16 = 0x7f vkF17 = 0x80 vkF18 = 0x81 vkF19 = 0x82 vkF20 = 0x83 vkF21 = 0x84 vkF22 = 0x85 vkF23 = 0x86 vkF24 = 0x87 ) var vkKeys = map[uint16]Key{ vkCancel: KeyCancel, vkBack: KeyBackspace, vkTab: KeyTab, vkClear: KeyClear, vkPause: KeyPause, vkPrint: KeyPrint, vkPrtScr: KeyPrint, vkPrior: KeyPgUp, vkNext: KeyPgDn, vkReturn: KeyEnter, vkEnd: KeyEnd, vkHome: KeyHome, vkLeft: KeyLeft, vkUp: KeyUp, vkRight: KeyRight, vkDown: KeyDown, vkInsert: KeyInsert, vkDelete: KeyDelete, vkHelp: KeyHelp, vkEscape: KeyEscape, vkSpace: ' ', vkF1: KeyF1, vkF2: KeyF2, vkF3: KeyF3, vkF4: KeyF4, vkF5: KeyF5, vkF6: KeyF6, vkF7: KeyF7, vkF8: KeyF8, vkF9: KeyF9, vkF10: KeyF10, vkF11: KeyF11, vkF12: KeyF12, vkF13: KeyF13, vkF14: KeyF14, vkF15: KeyF15, vkF16: KeyF16, vkF17: KeyF17, vkF18: KeyF18, vkF19: KeyF19, vkF20: KeyF20, vkF21: KeyF21, vkF22: KeyF22, vkF23: KeyF23, vkF24: KeyF24, } // NB: All Windows platforms are little endian. We assume this // never, ever change. The following code is endian safe. and does // not use unsafe pointers. func getu32(v []byte) uint32 { return uint32(v[0]) + (uint32(v[1]) << 8) + (uint32(v[2]) << 16) + (uint32(v[3]) << 24) } func geti32(v []byte) int32 { return int32(getu32(v)) } func getu16(v []byte) uint16 { return uint16(v[0]) + (uint16(v[1]) << 8) } func geti16(v []byte) int16 { return int16(getu16(v)) } // Convert windows dwControlKeyState to modifier mask func mod2mask(cks uint32, filter_ctrl_alt bool) ModMask { mm := ModNone // Left or right control ctrl := (cks & (0x0008 | 0x0004)) != 0 // Left or right alt alt := (cks & (0x0002 | 0x0001)) != 0 // Filter out ctrl+alt (it means AltGr) if !filter_ctrl_alt || !(ctrl && alt) { if ctrl { mm |= ModCtrl } if alt { mm |= ModAlt } } // Any shift if (cks & 0x0010) != 0 { mm |= ModShift } return mm } func mrec2btns(mbtns, flags uint32) ButtonMask { btns := ButtonNone if mbtns&0x1 != 0 { btns |= Button1 } if mbtns&0x2 != 0 { btns |= Button2 } if mbtns&0x4 != 0 { btns |= Button3 } if mbtns&0x8 != 0 { btns |= Button4 } if mbtns&0x10 != 0 { btns |= Button5 } if mbtns&0x20 != 0 { btns |= Button6 } if mbtns&0x40 != 0 { btns |= Button7 } if mbtns&0x80 != 0 { btns |= Button8 } if flags&mouseVWheeled != 0 { if mbtns&0x80000000 == 0 { btns |= WheelUp } else { btns |= WheelDown } } if flags&mouseHWheeled != 0 { if mbtns&0x80000000 == 0 { btns |= WheelRight } else { btns |= WheelLeft } } return btns } func (s *cScreen) postEvent(ev Event) { select { case s.eventQ <- ev: case <-s.quit: } } func (s *cScreen) getConsoleInput() error { // cancelFlag comes first as WaitForMultipleObjects returns the lowest index // in the event that both events are signalled. waitObjects := []syscall.Handle{s.cancelflag, s.in} // As arrays are contiguous in memory, a pointer to the first object is the // same as a pointer to the array itself. pWaitObjects := unsafe.Pointer(&waitObjects[0]) rv, _, er := procWaitForMultipleObjects.Call( uintptr(len(waitObjects)), uintptr(pWaitObjects), uintptr(0), w32Infinite) // WaitForMultipleObjects returns WAIT_OBJECT_0 + the index. switch rv { case w32WaitObject0: // s.cancelFlag return errors.New("cancelled") case w32WaitObject0 + 1: // s.in rec := &inputRecord{} var nrec int32 rv, _, er := procReadConsoleInput.Call( uintptr(s.in), uintptr(unsafe.Pointer(rec)), uintptr(1), uintptr(unsafe.Pointer(&nrec))) if rv == 0 { return er } if nrec != 1 { return nil } switch rec.typ { case keyEvent: krec := &keyRecord{} krec.isdown = geti32(rec.data[0:]) krec.repeat = getu16(rec.data[4:]) krec.kcode = getu16(rec.data[6:]) krec.scode = getu16(rec.data[8:]) krec.ch = getu16(rec.data[10:]) krec.mod = getu32(rec.data[12:]) if krec.isdown == 0 || krec.repeat < 1 { // it's a key release event, ignore it return nil } if krec.ch != 0 { // synthesized key code for krec.repeat > 0 { if krec.ch < ' ' && mod2mask(krec.mod, false) == ModCtrl { krec.ch += '\x60' } // convert shift+tab to backtab if mod2mask(krec.mod, false) == ModShift && krec.ch == vkTab { s.postEvent(NewEventKey(KeyBacktab, 0, ModNone)) } else { s.postEvent(NewEventKey(KeyRune, rune(krec.ch), mod2mask(krec.mod, true))) } krec.repeat-- } return nil } key := KeyNUL // impossible on Windows ok := false if key, ok = vkKeys[krec.kcode]; !ok { return nil } for krec.repeat > 0 { s.postEvent(NewEventKey(key, rune(krec.ch), mod2mask(krec.mod, false))) krec.repeat-- } case mouseEvent: var mrec mouseRecord mrec.x = geti16(rec.data[0:]) mrec.y = geti16(rec.data[2:]) mrec.btns = getu32(rec.data[4:]) mrec.mod = getu32(rec.data[8:]) mrec.flags = getu32(rec.data[12:]) btns := mrec2btns(mrec.btns, mrec.flags) // we ignore double click, events are delivered normally s.postEvent(NewEventMouse(int(mrec.x), int(mrec.y), btns, mod2mask(mrec.mod, false))) case resizeEvent: var rrec resizeRecord rrec.x = geti16(rec.data[0:]) rrec.y = geti16(rec.data[2:]) s.postEvent(NewEventResize(int(rrec.x), int(rrec.y))) case focusEvent: var focus focusRecord focus.focused = geti32(rec.data[0:]) s.Lock() enabled := s.focusEnable s.Unlock() if enabled { s.postEvent(NewEventFocus(focus.focused != 0)) } default: } default: return er } return nil } func (s *cScreen) scanInput(stopQ chan struct{}) { defer s.wg.Done() for { select { case <-stopQ: return default: } if e := s.getConsoleInput(); e != nil { return } } } func (s *cScreen) Colors() int { if !s.truecolor { return 16 } return 1 << 24 } var vgaColors = map[Color]uint16{ ColorBlack: 0, ColorMaroon: 0x4, ColorGreen: 0x2, ColorNavy: 0x1, ColorOlive: 0x6, ColorPurple: 0x5, ColorTeal: 0x3, ColorSilver: 0x7, ColorGrey: 0x8, ColorRed: 0xc, ColorLime: 0xa, ColorBlue: 0x9, ColorYellow: 0xe, ColorFuchsia: 0xd, ColorAqua: 0xb, ColorWhite: 0xf, } // Windows uses RGB signals func mapColor2RGB(c Color) uint16 { winLock.Lock() if v, ok := winColors[c]; ok { c = v } else { v = FindColor(c, winPalette) winColors[c] = v c = v } winLock.Unlock() if vc, ok := vgaColors[c]; ok { return vc } return 0 } // Map a tcell style to Windows attributes func (s *cScreen) mapStyle(style Style) uint16 { f, b, a := style.fg, style.bg, style.attrs fa := s.oscreen.attrs & 0xf ba := (s.oscreen.attrs) >> 4 & 0xf if f != ColorDefault && f != ColorReset { fa = mapColor2RGB(f) } if b != ColorDefault && b != ColorReset { ba = mapColor2RGB(b) } var attr uint16 // We simulate reverse by doing the color swap ourselves. // Apparently windows cannot really do this except in DBCS // views. if a&AttrReverse != 0 { attr = ba attr |= fa << 4 } else { attr = fa attr |= ba << 4 } if a&AttrBold != 0 { attr |= 0x8 } if a&AttrDim != 0 { attr &^= 0x8 } if a&AttrUnderline != 0 { // Best effort -- doesn't seem to work though. attr |= 0x8000 } // Blink is unsupported return attr } func (s *cScreen) makeVtStyle(style Style) string { esc := &strings.Builder{} fg, bg, attrs := style.fg, style.bg, style.attrs us, uc := style.ulStyle, style.ulColor esc.WriteString(vtSgr0) if attrs&(AttrBold|AttrDim) == AttrBold { esc.WriteString(vtBold) } if attrs&AttrBlink != 0 { esc.WriteString(vtBlink) } if us != UnderlineStyleNone { if uc == ColorReset { esc.WriteString(vtUnderColorReset) } else if uc.IsRGB() { r, g, b := uc.RGB() _, _ = fmt.Fprintf(esc, vtUnderColorRGB, int(r), int(g), int(b)) } else if uc.Valid() { _, _ = fmt.Fprintf(esc, vtUnderColor, uc&0xff) } esc.WriteString(vtUnderline) // legacy ConHost does not understand these but Terminal does switch us { case UnderlineStyleSolid: case UnderlineStyleDouble: esc.WriteString(vtDoubleUnderline) case UnderlineStyleCurly: esc.WriteString(vtCurlyUnderline) case UnderlineStyleDotted: esc.WriteString(vtDottedUnderline) case UnderlineStyleDashed: esc.WriteString(vtDashedUnderline) } } if attrs&AttrReverse != 0 { esc.WriteString(vtReverse) } if fg.IsRGB() { r, g, b := fg.RGB() _, _ = fmt.Fprintf(esc, vtSetFgRGB, r, g, b) } else if fg.Valid() { _, _ = fmt.Fprintf(esc, vtSetFg, fg&0xff) } if bg.IsRGB() { r, g, b := bg.RGB() _, _ = fmt.Fprintf(esc, vtSetBgRGB, r, g, b) } else if bg.Valid() { _, _ = fmt.Fprintf(esc, vtSetBg, bg&0xff) } // URL string can be long, so don't send it unless we really need to if style.url != "" { _, _ = fmt.Fprintf(esc, vtEnterUrl, style.urlId, style.url) } else { esc.WriteString(vtExitUrl) } return esc.String() } func (s *cScreen) sendVtStyle(style Style) { s.emitVtString(s.makeVtStyle(style)) } func (s *cScreen) writeString(x, y int, style Style, vtBuf, ch []uint16) { // we assume the caller has hidden the cursor if len(ch) == 0 { return } vtBuf = append(vtBuf, utf16.Encode([]rune(fmt.Sprintf(vtCursorPos, y+1, x+1)))...) styleStr := s.makeVtStyle(style) vtBuf = append(vtBuf, utf16.Encode([]rune(styleStr))...) vtBuf = append(vtBuf, ch...) _ = syscall.WriteConsole(s.out, &vtBuf[0], uint32(len(vtBuf)), nil, nil) vtBuf = vtBuf[:0] } func (s *cScreen) draw() { // allocate a scratch line bit enough for no combining chars. // if you have combining characters, you may pay for extra allocations. buf := make([]uint16, 0, s.w) var vtBuf []uint16 wcs := buf[:] lstyle := styleInvalid lx, ly := -1, -1 ra := make([]rune, 1) for y := 0; y < s.h; y++ { for x := 0; x < s.w; x++ { mainc, combc, style, width := s.cells.GetContent(x, y) dirty := s.cells.Dirty(x, y) if style == StyleDefault { style = s.style } if !dirty || style != lstyle { // write out any data queued thus far // because we are going to skip over some // cells, or because we need to change styles s.writeString(lx, ly, lstyle, vtBuf, wcs) wcs = buf[0:0] lstyle = StyleDefault if !dirty { continue } } if x > s.w-width { mainc = ' ' combc = nil width = 1 } if len(wcs) == 0 { lstyle = style lx = x ly = y } ra[0] = mainc wcs = append(wcs, utf16.Encode(ra)...) if len(combc) != 0 { wcs = append(wcs, utf16.Encode(combc)...) } for dx := 0; dx < width; dx++ { s.cells.SetDirty(x+dx, y, false) } x += width - 1 } s.writeString(lx, ly, lstyle, vtBuf, wcs) wcs = buf[0:0] lstyle = styleInvalid } } func (s *cScreen) Show() { s.Lock() if !s.fini { s.hideCursor() s.resize() s.draw() s.doCursor() } s.Unlock() } func (s *cScreen) Sync() { s.Lock() if !s.fini { s.cells.Invalidate() s.hideCursor() s.resize() s.draw() s.doCursor() } s.Unlock() } type consoleInfo struct { size coord pos coord attrs uint16 win rect maxsz coord } func (s *cScreen) getConsoleInfo(info *consoleInfo) { _, _, _ = procGetConsoleScreenBufferInfo.Call( uintptr(s.out), uintptr(unsafe.Pointer(info))) } func (s *cScreen) getCursorInfo(info *cursorInfo) { _, _, _ = procGetConsoleCursorInfo.Call( uintptr(s.out), uintptr(unsafe.Pointer(info))) } func (s *cScreen) setCursorInfo(info *cursorInfo) { _, _, _ = procSetConsoleCursorInfo.Call( uintptr(s.out), uintptr(unsafe.Pointer(info))) } func (s *cScreen) setCursorPos(x, y int) { // Note that the string is Y first. Origin is 1,1. s.emitVtString(fmt.Sprintf(vtCursorPos, y+1, x+1)) } func (s *cScreen) setBufferSize(x, y int) { _, _, _ = procSetConsoleScreenBufferSize.Call( uintptr(s.out), coord{int16(x), int16(y)}.uintptr()) } func (s *cScreen) Size() (int, int) { s.Lock() w, h := s.w, s.h s.Unlock() return w, h } func (s *cScreen) SetSize(w, h int) { xy, _, _ := procGetLargestConsoleWindowSize.Call(uintptr(s.out)) // xy is little endian packed y := int(xy >> 16) x := int(xy & 0xffff) if x == 0 || y == 0 { return } // This is a hacky workaround for Windows Terminal. // Essentially Windows Terminal (Windows 11) does not support application // initiated resizing. To detect this, we look for an extremely large size // for the maximum width. If it is > 500, then this is almost certainly // Windows Terminal, and won't support this. (Note that the legacy console // does support application resizing.) if x >= 500 { return } s.setBufferSize(x, y) r := rect{0, 0, int16(w - 1), int16(h - 1)} _, _, _ = procSetConsoleWindowInfo.Call( uintptr(s.out), uintptr(1), uintptr(unsafe.Pointer(&r))) s.resize() } func (s *cScreen) resize() { info := consoleInfo{} s.getConsoleInfo(&info) w := int((info.win.right - info.win.left) + 1) h := int((info.win.bottom - info.win.top) + 1) if s.w == w && s.h == h { return } s.cells.Resize(w, h) s.w = w s.h = h s.setBufferSize(w, h) r := rect{0, 0, int16(w - 1), int16(h - 1)} _, _, _ = procSetConsoleWindowInfo.Call( uintptr(s.out), uintptr(1), uintptr(unsafe.Pointer(&r))) select { case s.eventQ <- NewEventResize(w, h): default: } } func (s *cScreen) clearScreen(style Style) { s.sendVtStyle(style) row := strings.Repeat(" ", s.w) for y := 0; y < s.h; y++ { s.setCursorPos(0, y) s.emitVtString(row) } s.setCursorPos(0, 0) } const ( // Input modes modeExtendFlg = uint32(0x0080) modeMouseEn = uint32(0x0010) modeResizeEn = uint32(0x0008) modeVtInput = uint32(0x0200) // modeCooked = uint32(0x0001) // Output modes modeCookedOut = uint32(0x0001) modeVtOutput = uint32(0x0004) modeNoAutoNL = uint32(0x0008) modeUnderline = uint32(0x0010) // ENABLE_LVB_GRID_WORLDWIDE, needed for underlines // modeWrapEOL = uint32(0x0002) ) func (s *cScreen) setInMode(mode uint32) { _, _, _ = procSetConsoleMode.Call( uintptr(s.in), uintptr(mode)) } func (s *cScreen) setOutMode(mode uint32) { _, _, _ = procSetConsoleMode.Call( uintptr(s.out), uintptr(mode)) } func (s *cScreen) getInMode(v *uint32) { _, _, _ = procGetConsoleMode.Call( uintptr(s.in), uintptr(unsafe.Pointer(v))) } func (s *cScreen) getOutMode(v *uint32) { _, _, _ = procGetConsoleMode.Call( uintptr(s.out), uintptr(unsafe.Pointer(v))) } func (s *cScreen) SetStyle(style Style) { s.Lock() s.style = style s.Unlock() } func (s *cScreen) SetTitle(title string) { s.Lock() s.title = title s.emitVtString(fmt.Sprintf(vtSetTitle, title)) s.Unlock() } // No fallback rune support, since we have Unicode. Yay! func (s *cScreen) RegisterRuneFallback(_ rune, _ string) { } func (s *cScreen) UnregisterRuneFallback(_ rune) { } func (s *cScreen) CanDisplay(_ rune, _ bool) bool { // We presume we can display anything -- we're Unicode. // (Sadly this not precisely true. Combining characters are especially // poorly supported under Windows.) return true } func (s *cScreen) HasMouse() bool { return true } func (s *cScreen) SetClipboard(_ []byte) { } func (s *cScreen) GetClipboard() { } func (s *cScreen) Resize(int, int, int, int) {} func (s *cScreen) HasKey(_ Key) bool { return true } func (s *cScreen) Beep() error { // A simple beep. If the sound card is not available, the sound is generated // using the speaker. // // Reference: // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebeep const simpleBeep = 0xffffffff if rv, _, err := procMessageBeep.Call(simpleBeep); rv == 0 { return err } return nil } func (s *cScreen) Suspend() error { s.disengage() return nil } func (s *cScreen) Resume() error { return s.engage() } func (s *cScreen) Tty() (Tty, bool) { return nil, false } func (s *cScreen) GetCells() *CellBuffer { return &s.cells } func (s *cScreen) EventQ() chan Event { return s.eventQ } func (s *cScreen) StopQ() <-chan struct{} { return s.quit }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/charset_stub.go
vendor/github.com/gdamore/tcell/v2/charset_stub.go
//go:build nacl // +build nacl // Copyright 2015 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell func getCharset() string { return "" }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/eastasian.go
vendor/github.com/gdamore/tcell/v2/eastasian.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "os" "strings" "github.com/rivo/uniseg" ) func init() { if rw := strings.ToLower(os.Getenv("RUNEWIDTH_EASTASIAN")); rw == "1" || rw == "true" || rw == "yes" { uniseg.EastAsianAmbiguousWidth = 2 } else { uniseg.EastAsianAmbiguousWidth = 1 } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/cell.go
vendor/github.com/gdamore/tcell/v2/cell.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "github.com/rivo/uniseg" ) type cell struct { currStr string lastStr string currStyle Style lastStyle Style width int lock bool } func (c *cell) setDirty(dirty bool) { if dirty { c.lastStr = "" } else { if c.currStr == "" { c.currStr = " " } c.lastStr = c.currStr c.lastStyle = c.currStyle } } // CellBuffer represents a two-dimensional array of character cells. // This is primarily intended for use by Screen implementors; it // contains much of the common code they need. To create one, just // declare a variable of its type; no explicit initialization is necessary. // // CellBuffer is not thread safe. type CellBuffer struct { w int h int cells []cell } // SetContent sets the contents (primary rune, combining runes, // and style) for a cell at a given location. If the background or // foreground of the style is set to ColorNone, then the respective // color is left un changed. // // Deprecated: Use Put instead, which this is implemented in terms of. func (cb *CellBuffer) SetContent(x int, y int, mainc rune, combc []rune, style Style) { cb.Put(x, y, string(append([]rune{mainc}, combc...)), style) } // Put a single styled grapheme using the given string and style // at the same location. Note that only the first grapheme in the string // will bre displayed, using only the 1 or 2 (depending on width) cells // located at x, y. It returns the rest of the string, and the width used. func (cb *CellBuffer) Put(x int, y int, str string, style Style) (string, int) { var width int = 0 if x >= 0 && y >= 0 && x < cb.w && y < cb.h { var cl string c := &cb.cells[(y*cb.w)+x] state := -1 for width == 0 && str != "" { var g string g, str, width, state = uniseg.FirstGraphemeClusterInString(str, state) cl += g if g == "" { break } } // Wide characters: we want to mark the "wide" cells // dirty as well as the base cell, to make sure we consider // both cells as dirty together. We only need to do this // if we're changing content if width > 0 && cl != c.currStr { // Prevent unnecessary boundchecks for first cell, since we already // received that one. c.setDirty(true) for i := 1; i < width; i++ { cb.SetDirty(x+i, y, true) } } c.currStr = cl c.width = width if style.fg == ColorNone { style.fg = c.currStyle.fg } if style.bg == ColorNone { style.bg = c.currStyle.bg } c.currStyle = style } return str, width } // Get the contents of a character cell (or two adjacent cells), including the // the style and the display width in cells. (The width can be either 1, normally, // or 2 for East Asian full-width characters. If the width is 0, then the cell is // is empty.) func (cb *CellBuffer) Get(x, y int) (string, Style, int) { var style Style var width int var str string if x >= 0 && y >= 0 && x < cb.w && y < cb.h { c := &cb.cells[(y*cb.w)+x] str, style = c.currStr, c.currStyle if width = c.width; width == 0 || str == "" { width = 1 str = " " } } return str, style, width } // GetContent returns the contents of a character cell, including the // primary rune, any combining character runes (which will usually be // nil), the style, and the display width in cells. (The width can be // either 1, normally, or 2 for East Asian full-width characters.) // // Deprecated: Use Get, which this implemented in terms of. func (cb *CellBuffer) GetContent(x, y int) (rune, []rune, Style, int) { var style Style var width int var mainc rune var combc []rune str, style, width := cb.Get(x, y) for i, r := range str { if i == 0 { mainc = r } else { combc = append(combc, r) } } return mainc, combc, style, width } // Size returns the (width, height) in cells of the buffer. func (cb *CellBuffer) Size() (int, int) { return cb.w, cb.h } // Invalidate marks all characters within the buffer as dirty. func (cb *CellBuffer) Invalidate() { for i := range cb.cells { cb.cells[i].lastStr = "" } } // Dirty checks if a character at the given location needs to be // refreshed on the physical display. This returns true if the cell // content is different since the last time it was marked clean. func (cb *CellBuffer) Dirty(x, y int) bool { if x >= 0 && y >= 0 && x < cb.w && y < cb.h { c := &cb.cells[(y*cb.w)+x] if c.lock { return false } if c.lastStyle != c.currStyle { return true } if c.lastStr != c.currStr { return true } } return false } // SetDirty is normally used to indicate that a cell has // been displayed (in which case dirty is false), or to manually // force a cell to be marked dirty. func (cb *CellBuffer) SetDirty(x, y int, dirty bool) { if x >= 0 && y >= 0 && x < cb.w && y < cb.h { c := &cb.cells[(y*cb.w)+x] c.setDirty(dirty) } } // LockCell locks a cell from being drawn, effectively marking it "clean" until // the lock is removed. This can be used to prevent tcell from drawing a given // cell, even if the underlying content has changed. For example, when drawing a // sixel graphic directly to a TTY screen an implementer must lock the region // underneath the graphic to prevent tcell from drawing on top of the graphic. func (cb *CellBuffer) LockCell(x, y int) { if x < 0 || y < 0 { return } if x >= cb.w || y >= cb.h { return } c := &cb.cells[(y*cb.w)+x] c.lock = true } // UnlockCell removes a lock from the cell and marks it as dirty func (cb *CellBuffer) UnlockCell(x, y int) { if x < 0 || y < 0 { return } if x >= cb.w || y >= cb.h { return } c := &cb.cells[(y*cb.w)+x] c.lock = false cb.SetDirty(x, y, true) } // Resize is used to resize the cells array, with different dimensions, // while preserving the original contents. The cells will be invalidated // so that they can be redrawn. func (cb *CellBuffer) Resize(w, h int) { if cb.h == h && cb.w == w { return } newc := make([]cell, w*h) for y := 0; y < h && y < cb.h; y++ { for x := 0; x < w && x < cb.w; x++ { oc := &cb.cells[(y*cb.w)+x] nc := &newc[(y*w)+x] nc.currStr = oc.currStr nc.currStyle = oc.currStyle nc.width = oc.width nc.lastStr = "" } } cb.cells = newc cb.h = h cb.w = w } // Fill fills the entire cell buffer array with the specified character // and style. Normally choose ' ' to clear the screen. This API doesn't // support combining characters, or characters with a width larger than one. // If either the foreground or background are ColorNone, then the respective // color is unchanged. func (cb *CellBuffer) Fill(r rune, style Style) { for i := range cb.cells { c := &cb.cells[i] c.currStr = string(r) cs := style if cs.fg == ColorNone { cs.fg = c.currStyle.fg } if cs.bg == ColorNone { cs.bg = c.currStyle.bg } c.currStyle = cs c.width = 1 } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/nonblock_bsd.go
vendor/github.com/gdamore/tcell/v2/nonblock_bsd.go
// Copyright 2021 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build darwin || dragonfly || freebsd || netbsd || openbsd // +build darwin dragonfly freebsd netbsd openbsd package tcell import ( "syscall" "golang.org/x/sys/unix" ) // BSD systems use TIOC style ioctls. // tcSetBufParams is used by the tty driver on UNIX systems to configure the // buffering parameters (minimum character count and minimum wait time in msec.) // This also waits for output to drain first. func tcSetBufParams(fd int, vMin uint8, vTime uint8) error { _ = syscall.SetNonblock(fd, true) tio, err := unix.IoctlGetTermios(fd, unix.TIOCGETA) if err != nil { return err } tio.Cc[unix.VMIN] = vMin tio.Cc[unix.VTIME] = vTime if err = unix.IoctlSetTermios(fd, unix.TIOCSETAW, tio); err != nil { return err } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/attr.go
vendor/github.com/gdamore/tcell/v2/attr.go
// Copyright 2024 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell // AttrMask represents a mask of text attributes, apart from color. // Note that support for attributes may vary widely across terminals. type AttrMask uint // Attributes are not colors, but affect the display of text. They can // be combined, in some cases, but not others. (E.g. you can have Dim Italic, // but only CurlyUnderline cannot be mixed with DottedUnderline.) const ( AttrBold AttrMask = 1 << iota AttrBlink AttrReverse AttrUnderline // Deprecated: Use UnderlineStyle AttrDim AttrItalic AttrStrikeThrough AttrInvalid AttrMask = 1 << 31 // Mark the style or attributes invalid AttrNone AttrMask = 0 // Just normal text. )
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/tscreen_win.go
vendor/github.com/gdamore/tcell/v2/tscreen_win.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build windows // +build windows package tcell import ( // import the stock terminals _ "github.com/gdamore/tcell/v2/terminfo/base" ) // initialize is used at application startup, and sets up the initial values // including file descriptors used for terminals and saving the initial state // so that it can be restored when the application terminates. func (t *tScreen) initialize() error { var err error if t.tty == nil { t.tty, err = NewDevTty() if err != nil { return err } } return nil } func init() { defaultTerm = "xterm-truecolor" }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/event.go
vendor/github.com/gdamore/tcell/v2/event.go
// Copyright 2015 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "time" ) // Event is a generic interface used for passing around Events. // Concrete types follow. type Event interface { // When reports the time when the event was generated. When() time.Time } // EventTime is a simple base event class, suitable for easy reuse. // It can be used to deliver actual timer events as well. type EventTime struct { when time.Time } // When returns the time stamp when the event occurred. func (e *EventTime) When() time.Time { return e.when } // SetEventTime sets the time of occurrence for the event. func (e *EventTime) SetEventTime(t time.Time) { e.when = t } // SetEventNow sets the time of occurrence for the event to the current time. func (e *EventTime) SetEventNow() { e.SetEventTime(time.Now()) } // EventHandler is anything that handles events. If the handler has // consumed the event, it should return true. False otherwise. type EventHandler interface { HandleEvent(Event) bool }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/tscreen_plan9.go
vendor/github.com/gdamore/tcell/v2/tscreen_plan9.go
//go:build plan9 // +build plan9 // Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import "os" // initialize on Plan 9: if no TTY was provided, use the Plan 9 TTY. func (t *tScreen) initialize() error { if os.Getenv("TERM") == "" { // TERM should be "vt100" in a vt(1) window; color/mouse support will be limited. _ = os.Setenv("TERM", "vt100") } if t.tty == nil { tty, err := NewDevTty() if err != nil { return err } t.tty = tty } return nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/style.go
vendor/github.com/gdamore/tcell/v2/style.go
// Copyright 2024 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell // Style represents a complete text style, including both foreground color, // background color, and additional attributes such as "bold" or "underline". // // Note that not all terminals can display all colors or attributes, and // many might have specific incompatibilities between specific attributes // and color combinations. // // To use Style, just declare a variable of its type. type Style struct { fg Color bg Color ulStyle UnderlineStyle ulColor Color attrs AttrMask url string urlId string } // StyleDefault represents a default style, based upon the context. // It is the zero value. var StyleDefault Style // styleInvalid is just an arbitrary invalid style used internally. var styleInvalid = Style{attrs: AttrInvalid} // Foreground returns a new style based on s, with the foreground color set // as requested. ColorDefault can be used to select the global default. func (s Style) Foreground(c Color) Style { s2 := s s2.fg = c return s2 } // Background returns a new style based on s, with the background color set // as requested. ColorDefault can be used to select the global default. func (s Style) Background(c Color) Style { s2 := s s2.bg = c return s2 } // Decompose breaks a style up, returning the foreground, background, // and other attributes. The URL if set is not included. // Deprecated: Applications should not attempt to decompose style, // as this content is not sufficient to describe the actual style. func (s Style) Decompose() (fg Color, bg Color, attr AttrMask) { return s.fg, s.bg, s.attrs } func (s Style) setAttrs(attrs AttrMask, on bool) Style { s2 := s if on { s2.attrs |= attrs } else { s2.attrs &^= attrs } return s2 } // Normal returns the style with all attributes disabled. func (s Style) Normal() Style { return Style{ fg: s.fg, bg: s.bg, } } // Bold returns a new style based on s, with the bold attribute set // as requested. func (s Style) Bold(on bool) Style { return s.setAttrs(AttrBold, on) } // Blink returns a new style based on s, with the blink attribute set // as requested. func (s Style) Blink(on bool) Style { return s.setAttrs(AttrBlink, on) } // Dim returns a new style based on s, with the dim attribute set // as requested. func (s Style) Dim(on bool) Style { return s.setAttrs(AttrDim, on) } // Italic returns a new style based on s, with the italic attribute set // as requested. func (s Style) Italic(on bool) Style { return s.setAttrs(AttrItalic, on) } // Reverse returns a new style based on s, with the reverse attribute set // as requested. (Reverse usually changes the foreground and background // colors.) func (s Style) Reverse(on bool) Style { return s.setAttrs(AttrReverse, on) } // StrikeThrough sets strikethrough mode. func (s Style) StrikeThrough(on bool) Style { return s.setAttrs(AttrStrikeThrough, on) } // Underline style. Modern terminals have the option of rendering the // underline using different styles, and even different colors. type UnderlineStyle int const ( UnderlineStyleNone = UnderlineStyle(iota) UnderlineStyleSolid UnderlineStyleDouble UnderlineStyleCurly UnderlineStyleDotted UnderlineStyleDashed ) // Underline returns a new style based on s, with the underline attribute set // as requested. The parameters can be: // // bool: on / off - enables just a simple underline // UnderlineStyle: sets a specific style (should not coexist with the bool) // Color: the color to use func (s Style) Underline(params ...interface{}) Style { s2 := s for _, param := range params { switch v := param.(type) { case bool: if v { s2.ulStyle = UnderlineStyleSolid s2.attrs |= AttrUnderline } else { s2.ulStyle = UnderlineStyleNone s2.attrs &^= AttrUnderline } case UnderlineStyle: if v == UnderlineStyleNone { s2.attrs &^= AttrUnderline } else { s2.attrs |= AttrUnderline } s2.ulStyle = v case Color: s2.ulColor = v default: panic("Bad type for underline") } } return s2 } // GetUnderlineStyle returns the underline style for the style. func (s Style) GetUnderlineStyle() UnderlineStyle { return s.ulStyle } // GetUnderlineColor returns the underline color for the style. func (s Style) GetUnderlineColor() Color { return s.ulColor } // Attributes returns a new style based on s, with its attributes set as // specified. func (s Style) Attributes(attrs AttrMask) Style { s2 := s s2.attrs = attrs return s2 } // Url returns a style with the Url set. If the provided Url is not empty, // and the terminal supports it, text will typically be marked up as a clickable // link to that Url. If the Url is empty, then this mode is turned off. func (s Style) Url(url string) Style { s2 := s s2.url = url return s2 } // UrlId returns a style with the UrlId set. If the provided UrlId is not empty, // any marked up Url with this style will be given the UrlId also. If the // terminal supports it, any text with the same UrlId will be grouped as if it // were one Url, even if it spans multiple lines. func (s Style) UrlId(id string) Style { s2 := s s2.urlId = "id=" + id return s2 }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/doc.go
vendor/github.com/gdamore/tcell/v2/doc.go
// Copyright 2018 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package tcell provides a lower-level, portable API for building // programs that interact with terminals or consoles. It works with // both common (and many uncommon!) terminals or terminal emulators, // and Windows console implementations. // // It provides support for up to 256 colors, text attributes, and box drawing // elements. A database of terminals built from a real terminfo database // is provided, along with code to generate new database entries. // // Tcell offers very rich support for mice, dependent upon the terminal // of course. (Windows, XTerm, and iTerm 2 are known to work very well.) // // If the environment is not Unicode by default, such as an ISO8859 based // locale or GB18030, Tcell can convert input and output, so that your // terminal can operate in whatever locale is most convenient, while the // application program can just assume "everything is UTF-8". Reasonable // defaults are used for updating characters to something suitable for // display. Unicode box drawing characters will be converted to use the // alternate character set of your terminal, if native conversions are // not available. If no ACS is available, then some ASCII fallbacks will // be used. // // Note that support for non-UTF-8 locales (other than C) must be enabled // by the application using RegisterEncoding() -- we don't have them all // enabled by default to avoid bloating the application unnecessarily. // (These days UTF-8 is good enough for almost everyone, and nobody should // be using legacy locales anymore.) Also, actual glyphs for various code // point will only be displayed if your terminal or emulator (or the font // the emulator is using) supports them. // // A rich set of key codes is supported, with support for up to 65 function // keys, and various other special keys. package tcell
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/encoding.go
vendor/github.com/gdamore/tcell/v2/encoding.go
// Copyright 2022 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "strings" "sync" "golang.org/x/text/encoding" gencoding "github.com/gdamore/encoding" ) var encodings map[string]encoding.Encoding var encodingLk sync.Mutex var encodingFallback EncodingFallback = EncodingFallbackFail // RegisterEncoding may be called by the application to register an encoding. // The presence of additional encodings will facilitate application usage with // terminal environments where the I/O subsystem does not support Unicode. // // Windows systems use Unicode natively, and do not need any of the encoding // subsystem when using Windows Console screens. // // Please see the Go documentation for golang.org/x/text/encoding -- most of // the common ones exist already as stock variables. For example, ISO8859-15 // can be registered using the following code: // // import "golang.org/x/text/encoding/charmap" // // ... // RegisterEncoding("ISO8859-15", charmap.ISO8859_15) // // Aliases can be registered as well, for example "8859-15" could be an alias // for "ISO8859-15". // // For POSIX systems, this package will check the environment variables // LC_ALL, LC_CTYPE, and LANG (in that order) to determine the character set. // These are expected to have the following pattern: // // $language[.$codeset[@$variant] // // We extract only the $codeset part, which will usually be something like // UTF-8 or ISO8859-15 or KOI8-R. Note that if the locale is either "POSIX" // or "C", then we assume US-ASCII (the POSIX 'portable character set' // and assume all other characters are somehow invalid.) // // Modern POSIX systems and terminal emulators may use UTF-8, and for those // systems, this API is also unnecessary. For example, Darwin (MacOS X) and // modern Linux running modern xterm generally will out of the box without // any of this. Use of UTF-8 is recommended when possible, as it saves // quite a lot processing overhead. // // Note that some encodings are quite large (for example GB18030 which is a // superset of Unicode) and so the application size can be expected to // increase quite a bit as each encoding is added. // The East Asian encodings have been seen to add 100-200K per encoding to the // size of the resulting binary. func RegisterEncoding(charset string, enc encoding.Encoding) { encodingLk.Lock() charset = strings.ToLower(charset) encodings[charset] = enc encodingLk.Unlock() } // EncodingFallback describes how the system behaves when the locale // requires a character set that we do not support. The system always // supports UTF-8 and US-ASCII. On Windows consoles, UTF-16LE is also // supported automatically. Other character sets must be added using the // RegisterEncoding API. (A large group of nearly all of them can be // added using the RegisterAll function in the encoding sub package.) type EncodingFallback int const ( // EncodingFallbackFail behavior causes GetEncoding to fail // when it cannot find an encoding. EncodingFallbackFail = iota // EncodingFallbackASCII behavior causes GetEncoding to fall back // to a 7-bit ASCII encoding, if no other encoding can be found. EncodingFallbackASCII // EncodingFallbackUTF8 behavior causes GetEncoding to assume // UTF8 can pass unmodified upon failure. Note that this behavior // is not recommended, unless you are sure your terminal can cope // with real UTF8 sequences. EncodingFallbackUTF8 ) // SetEncodingFallback changes the behavior of GetEncoding when a suitable // encoding is not found. The default is EncodingFallbackFail, which // causes GetEncoding to simply return nil. func SetEncodingFallback(fb EncodingFallback) { encodingLk.Lock() encodingFallback = fb encodingLk.Unlock() } // GetEncoding is used by Screen implementors who want to locate an encoding // for the given character set name. Note that this will return nil for // either the Unicode (UTF-8) or ASCII encodings, since we don't use // encodings for them but instead have our own native methods. func GetEncoding(charset string) encoding.Encoding { charset = strings.ToLower(charset) encodingLk.Lock() defer encodingLk.Unlock() if enc, ok := encodings[charset]; ok { return enc } switch encodingFallback { case EncodingFallbackASCII: return gencoding.ASCII case EncodingFallbackUTF8: return encoding.Nop } return nil } func init() { // We always support UTF-8 and ASCII. encodings = make(map[string]encoding.Encoding) encodings["utf-8"] = gencoding.UTF8 encodings["utf8"] = gencoding.UTF8 encodings["us-ascii"] = gencoding.ASCII encodings["ascii"] = gencoding.ASCII encodings["iso646"] = gencoding.ASCII }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terms_default.go
vendor/github.com/gdamore/tcell/v2/terms_default.go
//go:build !tcell_minimal // +build !tcell_minimal // Copyright 2019 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( // This imports the default terminal entries. To disable, use the // tcell_minimal build tag. _ "github.com/gdamore/tcell/v2/terminfo/extended" )
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/input.go
vendor/github.com/gdamore/tcell/v2/input.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This file describes a generic VT input processor. It parses key sequences, // (input bytes) and loads them into events. It expects UTF-8 or UTF-16 as the input // feed, along with ECMA-48 sequences. The assumption here is that all potential // key sequences are unambiguous between terminal variants (analysis of extant terminfo // data appears to support this conjecture). This allows us to implement this once, // in the most efficient and terminal-agnostic way possible. // // There is unfortunately *one* conflict, with aixterm, for CSI-P - which is KeyDelete // in aixterm, but F1 in others. package tcell import ( "encoding/base64" "os" "strconv" "strings" "sync" "time" "unicode/utf16" "unicode/utf8" ) type inpState int const ( inpStateInit = inpState(iota) inpStateUtf inpStateEsc inpStateCsi // control sequence introducer inpStateOsc // operating system command inpStateDcs // device control string inpStateSos // start of string (unused) inpStatePm // privacy message (unused) inpStateApc // application program command inpStateSt // string terminator inpStateSs2 // single shift 2 inpStateSs3 // single shift 3 inpStateLFK // linux F-key (not ECMA-48 compliant - bogus CSI) ) type InputProcessor interface { ScanUTF8([]byte) ScanUTF16([]uint16) SetSize(rows, cols int) } func NewInputProcessor(eq chan<- Event) InputProcessor { return &inputProcessor{ evch: eq, buf: make([]rune, 0, 128), } } type inputProcessor struct { ut8 []byte ut16 []uint16 buf []rune scratch []byte csiParams []byte csiInterm []byte escaped bool btnDown bool // mouse button tracking for broken terms state inpState strState inpState // saved str state (needed for ST) timer *time.Timer expire time.Time l sync.Mutex encBuf []rune evch chan<- Event rows int // used for clipping mouse coordinates cols int // used for clipping mouse coordinates nested *inputProcessor } func (ip *inputProcessor) SetSize(w, h int) { if ip.nested != nil { ip.nested.SetSize(w, h) return } go func() { ip.l.Lock() ip.rows = h ip.cols = w ip.post(NewEventResize(w, h)) ip.l.Unlock() }() } func (ip *inputProcessor) post(ev Event) { if ip.escaped { ip.escaped = false if ke, ok := ev.(*EventKey); ok { ev = NewEventKey(ke.Key(), ke.Rune(), ke.Modifiers()|ModAlt) } } else if ke, ok := ev.(*EventKey); ok { switch ke.Key() { case keyPasteStart: ev = NewEventPaste(true) case keyPasteEnd: ev = NewEventPaste(false) } } ip.evch <- ev } func (ip *inputProcessor) escTimeout() { ip.l.Lock() defer ip.l.Unlock() if ip.state == inpStateEsc && ip.expire.Before(time.Now()) { // post it ip.state = inpStateInit ip.escaped = false ip.post(NewEventKey(KeyEsc, 0, ModNone)) } } type csiParamMode struct { M rune // Mode P int // Parameter (first) } type keyMap struct { Key Key Mod ModMask } var csiAllKeys = map[csiParamMode]keyMap{ {M: 'A'}: {Key: KeyUp}, {M: 'B'}: {Key: KeyDown}, {M: 'C'}: {Key: KeyRight}, {M: 'D'}: {Key: KeyLeft}, {M: 'F'}: {Key: KeyEnd}, {M: 'H'}: {Key: KeyHome}, {M: 'L'}: {Key: KeyInsert}, {M: 'P'}: {Key: KeyF1}, // except for aixterm, where this is Delete {M: 'Q'}: {Key: KeyF2}, {M: 'S'}: {Key: KeyF4}, {M: 'Z'}: {Key: KeyBacktab}, {M: 'a'}: {Key: KeyUp, Mod: ModShift}, {M: 'b'}: {Key: KeyDown, Mod: ModShift}, {M: 'c'}: {Key: KeyRight, Mod: ModShift}, {M: 'd'}: {Key: KeyLeft, Mod: ModShift}, {M: 'q', P: 1}: {Key: KeyF1}, // all these 'q' are for aixterm {M: 'q', P: 2}: {Key: KeyF2}, {M: 'q', P: 3}: {Key: KeyF3}, {M: 'q', P: 4}: {Key: KeyF4}, {M: 'q', P: 5}: {Key: KeyF5}, {M: 'q', P: 6}: {Key: KeyF6}, {M: 'q', P: 7}: {Key: KeyF7}, {M: 'q', P: 8}: {Key: KeyF8}, {M: 'q', P: 9}: {Key: KeyF9}, {M: 'q', P: 10}: {Key: KeyF10}, {M: 'q', P: 11}: {Key: KeyF11}, {M: 'q', P: 12}: {Key: KeyF12}, {M: 'q', P: 13}: {Key: KeyF13}, {M: 'q', P: 14}: {Key: KeyF14}, {M: 'q', P: 15}: {Key: KeyF15}, {M: 'q', P: 16}: {Key: KeyF16}, {M: 'q', P: 17}: {Key: KeyF17}, {M: 'q', P: 18}: {Key: KeyF18}, {M: 'q', P: 19}: {Key: KeyF19}, {M: 'q', P: 20}: {Key: KeyF20}, {M: 'q', P: 21}: {Key: KeyF21}, {M: 'q', P: 22}: {Key: KeyF22}, {M: 'q', P: 23}: {Key: KeyF23}, {M: 'q', P: 24}: {Key: KeyF24}, {M: 'q', P: 25}: {Key: KeyF25}, {M: 'q', P: 26}: {Key: KeyF26}, {M: 'q', P: 27}: {Key: KeyF27}, {M: 'q', P: 28}: {Key: KeyF28}, {M: 'q', P: 29}: {Key: KeyF29}, {M: 'q', P: 30}: {Key: KeyF30}, {M: 'q', P: 31}: {Key: KeyF31}, {M: 'q', P: 32}: {Key: KeyF32}, {M: 'q', P: 33}: {Key: KeyF33}, {M: 'q', P: 34}: {Key: KeyF34}, {M: 'q', P: 35}: {Key: KeyF35}, {M: 'q', P: 36}: {Key: KeyF36}, {M: 'q', P: 144}: {Key: KeyClear}, {M: 'q', P: 146}: {Key: KeyEnd}, {M: 'q', P: 150}: {Key: KeyPgUp}, {M: 'q', P: 154}: {Key: KeyPgDn}, {M: 'z', P: 214}: {Key: KeyHome}, {M: 'z', P: 216}: {Key: KeyPgUp}, {M: 'z', P: 220}: {Key: KeyEnd}, {M: 'z', P: 222}: {Key: KeyPgDn}, {M: 'z', P: 224}: {Key: KeyF1}, {M: 'z', P: 225}: {Key: KeyF2}, {M: 'z', P: 226}: {Key: KeyF3}, {M: 'z', P: 227}: {Key: KeyF4}, {M: 'z', P: 228}: {Key: KeyF5}, {M: 'z', P: 229}: {Key: KeyF6}, {M: 'z', P: 230}: {Key: KeyF7}, {M: 'z', P: 231}: {Key: KeyF8}, {M: 'z', P: 232}: {Key: KeyF9}, {M: 'z', P: 233}: {Key: KeyF10}, {M: 'z', P: 234}: {Key: KeyF11}, {M: 'z', P: 235}: {Key: KeyF12}, {M: 'z', P: 247}: {Key: KeyInsert}, {M: '^', P: 7}: {Key: KeyHome, Mod: ModCtrl}, {M: '^', P: 8}: {Key: KeyEnd, Mod: ModCtrl}, {M: '^', P: 11}: {Key: KeyF23}, {M: '^', P: 12}: {Key: KeyF24}, {M: '^', P: 13}: {Key: KeyF25}, {M: '^', P: 14}: {Key: KeyF26}, {M: '^', P: 15}: {Key: KeyF27}, {M: '^', P: 17}: {Key: KeyF28}, // 16 is a gap {M: '^', P: 18}: {Key: KeyF29}, {M: '^', P: 19}: {Key: KeyF30}, {M: '^', P: 20}: {Key: KeyF31}, {M: '^', P: 21}: {Key: KeyF32}, {M: '^', P: 23}: {Key: KeyF33}, // 22 is a gap {M: '^', P: 24}: {Key: KeyF34}, {M: '^', P: 25}: {Key: KeyF35}, {M: '^', P: 26}: {Key: KeyF36}, // 27 is a gap {M: '^', P: 28}: {Key: KeyF37}, {M: '^', P: 29}: {Key: KeyF38}, // 30 is a gap {M: '^', P: 31}: {Key: KeyF39}, {M: '^', P: 32}: {Key: KeyF40}, {M: '^', P: 33}: {Key: KeyF41}, {M: '^', P: 34}: {Key: KeyF42}, {M: '@', P: 23}: {Key: KeyF43}, {M: '@', P: 24}: {Key: KeyF44}, {M: '$', P: 2}: {Key: KeyInsert, Mod: ModShift}, {M: '$', P: 3}: {Key: KeyDelete, Mod: ModShift}, {M: '$', P: 7}: {Key: KeyHome, Mod: ModShift}, {M: '$', P: 8}: {Key: KeyEnd, Mod: ModShift}, {M: '$', P: 23}: {Key: KeyF21}, {M: '$', P: 24}: {Key: KeyF22}, {M: '~', P: 1}: {Key: KeyHome}, {M: '~', P: 2}: {Key: KeyInsert}, {M: '~', P: 3}: {Key: KeyDelete}, {M: '~', P: 4}: {Key: KeyEnd}, {M: '~', P: 5}: {Key: KeyPgUp}, {M: '~', P: 6}: {Key: KeyPgDn}, {M: '~', P: 7}: {Key: KeyHome}, {M: '~', P: 8}: {Key: KeyEnd}, {M: '~', P: 11}: {Key: KeyF1}, {M: '~', P: 12}: {Key: KeyF2}, {M: '~', P: 13}: {Key: KeyF3}, {M: '~', P: 14}: {Key: KeyF4}, {M: '~', P: 15}: {Key: KeyF5}, {M: '~', P: 17}: {Key: KeyF6}, {M: '~', P: 18}: {Key: KeyF7}, {M: '~', P: 19}: {Key: KeyF8}, {M: '~', P: 20}: {Key: KeyF9}, {M: '~', P: 21}: {Key: KeyF10}, {M: '~', P: 23}: {Key: KeyF11}, {M: '~', P: 24}: {Key: KeyF12}, {M: '~', P: 25}: {Key: KeyF13}, {M: '~', P: 26}: {Key: KeyF14}, {M: '~', P: 28}: {Key: KeyF15}, // aka KeyHelp {M: '~', P: 29}: {Key: KeyF16}, {M: '~', P: 31}: {Key: KeyF17}, {M: '~', P: 32}: {Key: KeyF18}, {M: '~', P: 33}: {Key: KeyF19}, {M: '~', P: 34}: {Key: KeyF20}, {M: '~', P: 200}: {Key: keyPasteStart}, {M: '~', P: 201}: {Key: keyPasteEnd}, } // keys reported using Kitty csi-u protocol var csiUKeys = map[int]Key{ 27: KeyESC, 9: KeyTAB, 13: KeyEnter, 127: KeyBS, 57358: KeyCapsLock, 57359: KeyScrollLock, 57360: KeyNumLock, 57361: KeyPrint, 57362: KeyPause, 57363: KeyMenu, 57376: KeyF13, 57377: KeyF14, 57378: KeyF15, 57379: KeyF16, 57380: KeyF17, 57381: KeyF18, 57382: KeyF19, 57383: KeyF20, 57384: KeyF21, 57385: KeyF22, 57386: KeyF23, 57387: KeyF24, 57388: KeyF25, 57389: KeyF26, 57390: KeyF27, 57391: KeyF28, 57392: KeyF29, 57393: KeyF30, 57394: KeyF31, 57395: KeyF32, 57396: KeyF33, 57397: KeyF34, 57398: KeyF35, // TODO: KP keys // TODO: Media keys } // windows virtual key codes per microsoft var winKeys = map[int]Key{ 0x03: KeyCancel, // vkCancel 0x08: KeyBackspace, // vkBackspace 0x09: KeyTab, // vkTab 0x0d: KeyEnter, // vkReturn 0x12: KeyClear, // vClear 0x13: KeyPause, // vkPause 0x1b: KeyEscape, // vkEscape 0x21: KeyPgUp, // vkPrior 0x22: KeyPgDn, // vkNext 0x23: KeyEnd, // vkEnd 0x24: KeyHome, // vkHome 0x25: KeyLeft, // vkLeft 0x26: KeyUp, // vkUp 0x27: KeyRight, // vkRight 0x28: KeyDown, // vkDown 0x2a: KeyPrint, // vkPrint 0x2c: KeyPrint, // vkPrtScr 0x2d: KeyInsert, // vkInsert 0x2e: KeyDelete, // vkDelete 0x2f: KeyHelp, // vkHelp 0x70: KeyF1, // vkF1 0x71: KeyF2, // vkF2 0x72: KeyF3, // vkF3 0x73: KeyF4, // vkF4 0x74: KeyF5, // vkF5 0x75: KeyF6, // vkF6 0x76: KeyF7, // vkF7 0x77: KeyF8, // vkF8 0x78: KeyF9, // vkF9 0x79: KeyF10, // vkF10 0x7a: KeyF11, // vkF11 0x7b: KeyF12, // vkF12 0x7c: KeyF13, // vkF13 0x7d: KeyF14, // vkF14 0x7e: KeyF15, // vkF15 0x7f: KeyF16, // vkF16 0x80: KeyF17, // vkF17 0x81: KeyF18, // vkF18 0x82: KeyF19, // vkF19 0x83: KeyF20, // vkF20 0x84: KeyF21, // vkF21 0x85: KeyF22, // vkF22 0x86: KeyF23, // vkF23 0x87: KeyF24, // vkF24 } // keys by their SS3 - used in application mode usually (legacy VT-style) var ss3Keys = map[rune]Key{ 'A': KeyUp, 'B': KeyDown, 'C': KeyRight, 'D': KeyLeft, 'F': KeyEnd, 'H': KeyHome, 'P': KeyF1, 'Q': KeyF2, 'R': KeyF3, 'S': KeyF4, 't': KeyF5, 'u': KeyF6, 'v': KeyF7, 'l': KeyF8, 'w': KeyF9, 'x': KeyF10, } // linux terminal uses these non ECMA keys prefixed by CSI-[ var linuxFKeys = map[rune]Key{ 'A': KeyF1, 'B': KeyF2, 'C': KeyF3, 'D': KeyF4, 'E': KeyF5, } func (ip *inputProcessor) scan() { for _, r := range ip.buf { ip.buf = ip.buf[1:] if r > 0x7F { // 8-bit extended Unicode we just treat as such - this will swallow anything else queued up ip.state = inpStateInit ip.post(NewEventKey(KeyRune, r, ModNone)) continue } switch ip.state { case inpStateInit: switch r { case '\x1b': // escape.. pending ip.state = inpStateEsc if len(ip.buf) == 0 && ip.nested == nil { ip.expire = time.Now().Add(time.Millisecond * 50) ip.timer = time.AfterFunc(time.Millisecond*60, ip.escTimeout) } case '\t': ip.post(NewEventKey(KeyTab, 0, ModNone)) case '\b', '\x7F': ip.post(NewEventKey(KeyBackspace, 0, ModNone)) case '\r': ip.post(NewEventKey(KeyEnter, 0, ModNone)) default: // Control keys - legacy handling if r < ' ' { ip.post(NewEventKey(KeyCtrlSpace+Key(r), 0, ModCtrl)) } else { ip.post(NewEventKey(KeyRune, r, ModNone)) } } case inpStateEsc: switch r { case '[': ip.state = inpStateCsi ip.csiInterm = nil ip.csiParams = nil case ']': ip.state = inpStateOsc ip.scratch = nil case 'N': ip.state = inpStateSs2 // no known uses ip.scratch = nil case 'O': ip.state = inpStateSs3 ip.scratch = nil case 'X': ip.state = inpStateSos ip.scratch = nil case '^': ip.state = inpStatePm ip.scratch = nil case '_': ip.state = inpStateApc ip.scratch = nil case '\\': // string terminator reached, (orphaned?) ip.state = inpStateInit case '\t': // Linux console only, does not conform to ECMA ip.state = inpStateInit ip.post(NewEventKey(KeyBacktab, 0, ModNone)) default: if r == '\x1b' { // leading ESC to capture alt ip.escaped = true } else { // treat as alt-key ... legacy emulators only (no CSI-u or other) ip.state = inpStateInit mod := ModAlt if r < ' ' { mod |= ModCtrl r += 0x60 } ip.post(NewEventKey(KeyRune, r, mod)) } } case inpStateCsi: // usual case for incoming keys if r >= 0x30 && r <= 0x3F { // parameter bytes ip.csiParams = append(ip.csiParams, byte(r)) } else if r >= 0x20 && r <= 0x2F { // intermediate bytes, rarely used ip.csiInterm = append(ip.csiInterm, byte(r)) } else if r >= 0x40 && r <= 0x7F { // final byte ip.handleCsi(r, ip.csiParams, ip.csiInterm) } else { // bad parse, just swallow it all ip.state = inpStateInit } case inpStateSs2: // No known uses for SS2 ip.state = inpStateInit case inpStateSs3: // typically application mode keys or older terminals ip.state = inpStateInit if k, ok := ss3Keys[r]; ok { ip.post(NewEventKey(k, 0, ModNone)) } case inpStatePm, inpStateApc, inpStateSos, inpStateDcs: // these we just eat switch r { case '\x1b': ip.strState = ip.state ip.state = inpStateSt case '\x07': // bell - some send this instead of ST ip.state = inpStateInit } case inpStateOsc: // not sure if used switch r { case '\x1b': ip.strState = ip.state ip.state = inpStateSt case '\x07': ip.handleOsc(string(ip.scratch)) default: ip.scratch = append(ip.scratch, byte(r&0x7f)) } case inpStateSt: if r == '\\' || r == '\x07' { ip.state = inpStateInit switch ip.strState { case inpStateOsc: ip.handleOsc(string(ip.scratch)) case inpStatePm, inpStateApc, inpStateSos, inpStateDcs: ip.state = inpStateInit } } else { ip.scratch = append(ip.scratch, '\x1b', byte(r)) ip.state = ip.strState } case inpStateLFK: // linux console does not follow ECMA if k, ok := linuxFKeys[r]; ok { ip.post(NewEventKey(k, 0, ModNone)) } ip.state = inpStateInit } } } func (ip *inputProcessor) handleOsc(str string) { ip.state = inpStateInit if content, ok := strings.CutPrefix(str, "52;c;"); ok { decoded := make([]byte, base64.StdEncoding.DecodedLen(len(content))) if count, err := base64.StdEncoding.Decode(decoded, []byte(content)); err == nil { ip.post(NewEventClipboard(decoded[:count])) return } } } func calcModifier(n int) ModMask { n-- m := ModNone if n&1 != 0 { m |= ModShift } if n&2 != 0 { m |= ModAlt } if n&4 != 0 { m |= ModCtrl } if n&8 != 0 { m |= ModMeta // kitty calls this Super } if n&16 != 0 { m |= ModHyper } if n&32 != 0 { m |= ModMeta // for now not separating from Super } // Not doing (kitty only): // caps_lock 0b1000000 (64) // num_lock 0b10000000 (128) return m } // func (ip *inputProcessor) handleMouse(x, y, btn int, down bool) *EventMouse { func (ip *inputProcessor) handleMouse(mode rune, params []int) { // XTerm mouse events only report at most one button at a time, // which may include a wheel button. Wheel motion events are // reported as single impulses, while other button events are reported // as separate press & release events. if len(params) < 3 { return } btn := params[0] // Some terminals will report mouse coordinates outside the // screen, especially with click-drag events. Clip the coordinates // to the screen in that case. x := max(min(params[1]-1, ip.cols-1), 0) y := max(min(params[2]-1, ip.rows-1), 0) motion := (btn & 0x20) != 0 scroll := (btn & 0x42) == 0x40 btn &^= 0x20 if mode == 'm' { // mouse release, clear all buttons btn |= 3 btn &^= 0x40 ip.btnDown = false } else if motion { /* * Some broken terminals appear to send * mouse button one motion events, instead of * encoding 35 (no buttons) into these events. * We resolve these by looking for a non-motion * event first. */ if !ip.btnDown { btn |= 3 btn &^= 0x40 } } else if !scroll { ip.btnDown = true } button := ButtonNone mod := ModNone // Mouse wheel has bit 6 set, no release events. It should be noted // that wheel events are sometimes misdelivered as mouse button events // during a click-drag, so we debounce these, considering them to be // button press events unless we see an intervening release event. switch btn & 0x43 { case 0: button = Button1 case 1: button = Button3 // Note we prefer to treat right as button 2 case 2: button = Button2 // And the middle button as button 3 case 3: button = ButtonNone case 0x40: button = WheelUp case 0x41: button = WheelDown case 0x42: button = WheelLeft case 0x43: button = WheelRight } if btn&0x4 != 0 { mod |= ModShift } if btn&0x8 != 0 { mod |= ModAlt } if btn&0x10 != 0 { mod |= ModCtrl } ip.post(NewEventMouse(x, y, button, mod)) } func (ip *inputProcessor) handleWinKey(P []int) { // win32-input-mode // ^[ [ Vk ; Sc ; Uc ; Kd ; Cs ; Rc _ // Vk: the value of wVirtualKeyCode - any number. If omitted, defaults to '0'. // Sc: the value of wVirtualScanCode - any number. If omitted, defaults to '0'. // Uc: the decimal value of UnicodeChar - for example, NUL is "0", LF is // "10", the character 'A' is "65". If omitted, defaults to '0'. // Kd: the value of bKeyDown - either a '0' or '1'. If omitted, defaults to '0'. // Cs: the value of dwControlKeyState - any number. If omitted, defaults to '0'. // Rc: the value of wRepeatCount - any number. If omitted, defaults to '1'. // // Note that some 3rd party terminal emulators (not Terminal) suffer from a bug // where other events, such as mouse events, are doubly encoded, using Vk 0 // for each character. (So a CSI-M sequence is encoded as a series of CSI-_ // sequences.) We consider this a bug in those terminal emulators -- Windows 11 // Terminal does not suffer this brain damage. (We've observed this with both Alacritty // and WezTerm.) for len(P) < 6 { P = append(P, 0) // ensure sufficient length } if P[3] == 0 { // key up event ignore ignore return } if P[0] == 0 && P[1] == 0 && P[2] > 0 && P[2] < 0x80 { // only ASCII in win32-input-mode if ip.nested == nil { ip.nested = &inputProcessor{ evch: ip.evch, rows: ip.rows, cols: ip.cols, } } ip.nested.ScanUTF8([]byte{byte(P[2])}) return } key := KeyRune chr := rune(P[2]) mod := ModNone rpt := max(1, P[5]) if k1, ok := winKeys[P[0]]; ok { chr = 0 key = k1 } else if chr == 0 && P[0] >= 0x30 && P[0] <= 0x39 { chr = rune(P[0]) } else if chr < ' ' && P[0] >= 0x41 && P[0] <= 0x5a { key = Key(P[0]) chr = 0 } else if key == 0x11 || key == 0x13 || key == 0x14 { // lone modifiers return } // Modifiers if P[4]&0x010 != 0 { mod |= ModShift } if P[4]&0x000c != 0 { mod |= ModCtrl } if P[4]&0x0003 != 0 { mod |= ModAlt } if key == KeyRune && chr > ' ' && mod == ModShift { // filter out lone shift for printable chars mod = ModNone } if chr != 0 && mod&(ModCtrl|ModAlt) == ModCtrl|ModAlt { // Filter out ctrl+alt (it means AltGr) mod = ModNone } for range rpt { if key != KeyRune || chr != 0 { ip.post(NewEventKey(key, chr, mod)) } } } func (ip *inputProcessor) handleCsi(mode rune, params []byte, intermediate []byte) { // reset state ip.state = inpStateInit if len(intermediate) != 0 { // we don't know what to do with these for now return } var parts []string var P []int hasLT := false pstr := string(params) // extract numeric parameters if strings.HasPrefix(pstr, "<") { hasLT = true pstr = pstr[1:] } if pstr != "" && pstr[0] >= '0' && pstr[0] <= '9' { parts = strings.Split(pstr, ";") for i := range parts { if parts[i] != "" { if n, e := strconv.ParseInt(parts[i], 10, 32); e == nil { P = append(P, int(n)) } } } } var P0 int if len(P) > 0 { P0 = P[0] } if hasLT { switch mode { case 'm', 'M': // mouse event, we only do SGR tracking ip.handleMouse(mode, P) } } switch mode { case 'I': // focus in ip.post(NewEventFocus(true)) return case 'O': // focus out ip.post(NewEventFocus(false)) return case '[': // linux console F-key - CSI-[ modifies next key ip.state = inpStateLFK return case 'u': // CSI-u kitty keyboard protocol if len(P) > 0 && !hasLT { mod := ModNone key := KeyRune chr := rune(0) if k1, ok := csiUKeys[P0]; ok { key = k1 chr = 0 } else { chr = rune(P0) } if len(P) > 1 { mod = calcModifier(P[1]) } ip.post(NewEventKey(key, chr, mod)) } return case '_': if len(intermediate) == 0 && len(P) > 0 { ip.handleWinKey(P) return } case '~': if len(intermediate) == 0 && len(P) >= 2 { mod := calcModifier(P[1]) if ks, ok := csiAllKeys[csiParamMode{M: mode, P: P0}]; ok { ip.post(NewEventKey(ks.Key, 0, mod)) return } if P0 == 27 && len(P) > 2 && P[2] > 0 && P[2] <= 0xff { if P[2] < ' ' || P[2] == 0x7F { ip.post(NewEventKey(Key(P[2]), 0, mod)) } else { ip.post(NewEventKey(KeyRune, rune(P[2]), mod)) } return } } } if ks, ok := csiAllKeys[csiParamMode{M: mode, P: P0}]; ok && !hasLT { if mode == '~' && len(P) > 1 && ks.Mod == ModNone { // apply modifiers if present ks.Mod = calcModifier(P[1]) } else if mode == 'P' && os.Getenv("TERM") == "aixterm" { ks.Key = KeyDelete // aixterm hack - conflicts with kitty protocol } ip.post(NewEventKey(ks.Key, 0, ks.Mod)) return } // this might have been an SS3 style key with modifiers applied if k, ok := ss3Keys[mode]; ok && P0 == 1 && len(P) > 1 { ip.post(NewEventKey(k, 0, calcModifier(P[1]))) return } // if we got here we just swallow the unknown sequence } func (ip *inputProcessor) ScanUTF8(b []byte) { ip.l.Lock() defer ip.l.Unlock() ip.ut8 = append(ip.ut8, b...) for len(ip.ut8) > 0 { // fast path, basic ascii if ip.ut8[0] < 0x7F { ip.buf = append(ip.buf, rune(ip.ut8[0])) ip.ut8 = ip.ut8[1:] } else { r, len := utf8.DecodeRune(ip.ut8) if r == utf8.RuneError { r = rune(ip.ut8[0]) len = 1 } ip.buf = append(ip.buf, r) ip.ut8 = ip.ut8[len:] } } ip.scan() } func (ip *inputProcessor) ScanUTF16(u []uint16) { ip.l.Lock() defer ip.l.Unlock() ip.ut16 = append(ip.ut16, u...) for len(ip.ut16) > 0 { if !utf16.IsSurrogate(rune(ip.ut16[0])) { ip.buf = append(ip.buf, rune(ip.ut16[0])) ip.ut16 = ip.ut16[1:] } else if len(ip.ut16) > 1 { ip.buf = append(ip.buf, utf16.DecodeRune(rune(ip.ut16[0]), rune(ip.ut16[1]))) ip.ut16 = ip.ut16[2:] } else { break } } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/tty_unix.go
vendor/github.com/gdamore/tcell/v2/tty_unix.go
// Copyright 2021 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos package tcell import ( "errors" "fmt" "os" "os/signal" "strconv" "sync" "syscall" "time" "golang.org/x/sys/unix" "golang.org/x/term" ) // devTty is an implementation of the Tty API based upon /dev/tty. type devTty struct { fd int f *os.File of *os.File // the first open of /dev/tty saved *term.State sig chan os.Signal cb func() stopQ chan struct{} dev string wg sync.WaitGroup l sync.Mutex } func (tty *devTty) Read(b []byte) (int, error) { return tty.f.Read(b) } func (tty *devTty) Write(b []byte) (int, error) { return tty.f.Write(b) } func (tty *devTty) Close() error { return tty.f.Close() } func (tty *devTty) Start() error { tty.l.Lock() defer tty.l.Unlock() // We open another copy of /dev/tty. This is a workaround for unusual behavior // observed in macOS, apparently caused when a subshell (for example) closes our // own tty device (when it exits for example). Getting a fresh new one seems to // resolve the problem. (We believe this is a bug in the macOS tty driver that // fails to account for dup() references to the same file before applying close() // related behaviors to the tty.) We're also holding the original copy we opened // since closing that might have deleterious effects as well. The upshot is that // we will have up to two separate file handles open on /dev/tty. (Note that when // using stdin/stdout instead of /dev/tty this problem is not observed.) var err error if tty.f, err = os.OpenFile(tty.dev, os.O_RDWR, 0); err != nil { return err } if !term.IsTerminal(tty.fd) { return errors.New("device is not a terminal") } _ = tty.f.SetReadDeadline(time.Time{}) saved, err := term.MakeRaw(tty.fd) // also sets vMin and vTime if err != nil { return err } tty.saved = saved tty.stopQ = make(chan struct{}) tty.wg.Add(1) go func(stopQ chan struct{}) { defer tty.wg.Done() for { select { case <-tty.sig: tty.l.Lock() cb := tty.cb tty.l.Unlock() if cb != nil { cb() } case <-stopQ: return } } }(tty.stopQ) signal.Notify(tty.sig, syscall.SIGWINCH) return nil } func (tty *devTty) Drain() error { _ = tty.f.SetReadDeadline(time.Now()) if err := tcSetBufParams(tty.fd, 0, 0); err != nil { return err } return nil } func (tty *devTty) Stop() error { tty.l.Lock() if err := term.Restore(tty.fd, tty.saved); err != nil { tty.l.Unlock() return err } _ = tty.f.SetReadDeadline(time.Now()) signal.Stop(tty.sig) close(tty.stopQ) tty.l.Unlock() tty.wg.Wait() // close our tty device -- we'll get another one if we Start again later. _ = tty.f.Close() return nil } func (tty *devTty) WindowSize() (WindowSize, error) { size := WindowSize{} ws, err := unix.IoctlGetWinsize(tty.fd, unix.TIOCGWINSZ) if err != nil { return size, err } w := int(ws.Col) h := int(ws.Row) if w == 0 { w, _ = strconv.Atoi(os.Getenv("COLUMNS")) } if w == 0 { w = 80 // default } if h == 0 { h, _ = strconv.Atoi(os.Getenv("LINES")) } if h == 0 { h = 25 // default } size.Width = w size.Height = h size.PixelWidth = int(ws.Xpixel) size.PixelHeight = int(ws.Ypixel) return size, nil } func (tty *devTty) NotifyResize(cb func()) { tty.l.Lock() tty.cb = cb tty.l.Unlock() } // NewDevTty opens a /dev/tty based Tty. func NewDevTty() (Tty, error) { return NewDevTtyFromDev("/dev/tty") } // NewDevTtyFromDev opens a tty device given a path. This can be useful to bind to other nodes. func NewDevTtyFromDev(dev string) (Tty, error) { tty := &devTty{ dev: dev, sig: make(chan os.Signal), } var err error if tty.of, err = os.OpenFile(dev, os.O_RDWR, 0); err != nil { return nil, err } tty.fd = int(tty.of.Fd()) if !term.IsTerminal(tty.fd) { _ = tty.f.Close() return nil, errors.New("not a terminal") } if tty.saved, err = term.GetState(tty.fd); err != nil { _ = tty.f.Close() return nil, fmt.Errorf("failed to get state: %w", err) } return tty, nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/key.go
vendor/github.com/gdamore/tcell/v2/key.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import ( "fmt" "strings" "time" ) // EventKey represents a key press. Usually this is a key press followed // by a key release, but since terminal programs don't have a way to report // key release events, we usually get just one event. If a key is held down // then the terminal may synthesize repeated key presses at some predefined // rate. We have no control over that, nor visibility into it. // // In some cases, we can have a modifier key, such as ModAlt, that can be // generated with a key press. (This usually is represented by having the // high bit set, or in some cases, by sending an ESC prior to the rune.) // // If the value of Key() is KeyRune, then the actual key value will be // available with the Rune() method. This will be the case for most keys. // In most situations, the modifiers will not be set. For example, if the // rune is 'A', this will be reported without the ModShift bit set, since // really can't tell if the Shift key was pressed (it might have been CAPSLOCK, // or a terminal that only can send capitals, or keyboard with separate // capital letters from lower case letters). // // Generally, terminal applications have far less visibility into keyboard // activity than graphical applications. Hence, they should avoid depending // overly much on availability of modifiers, or the availability of any // specific keys. type EventKey struct { t time.Time mod ModMask key Key ch rune } // When returns the time when this Event was created, which should closely // match the time when the key was pressed. func (ev *EventKey) When() time.Time { return ev.t } // Rune returns the rune corresponding to the key press, if it makes sense. // The result is only defined if the value of Key() is KeyRune. func (ev *EventKey) Rune() rune { return ev.ch } // Key returns a virtual key code. We use this to identify specific key // codes, such as KeyEnter, etc. Most control and function keys are reported // with unique Key values. Normal alphanumeric and punctuation keys will // generally return KeyRune here; the specific key can be further decoded // using the Rune() function. func (ev *EventKey) Key() Key { return ev.key } // Modifiers returns the modifiers that were present with the key press. Note // that not all platforms and terminals support this equally well, and some // cases we will not not know for sure. Hence, applications should avoid // using this in most circumstances. func (ev *EventKey) Modifiers() ModMask { return ev.mod } // KeyNames holds the written names of special keys. Useful to echo back a key // name, or to look up a key from a string value. var KeyNames = map[Key]string{ KeyEnter: "Enter", KeyBackspace: "Backspace", KeyTab: "Tab", KeyBacktab: "Backtab", KeyEsc: "Esc", KeyBackspace2: "Backspace2", KeyDelete: "Delete", KeyInsert: "Insert", KeyUp: "Up", KeyDown: "Down", KeyLeft: "Left", KeyRight: "Right", KeyHome: "Home", KeyEnd: "End", KeyUpLeft: "UpLeft", KeyUpRight: "UpRight", KeyDownLeft: "DownLeft", KeyDownRight: "DownRight", KeyCenter: "Center", KeyPgDn: "PgDn", KeyPgUp: "PgUp", KeyClear: "Clear", KeyExit: "Exit", KeyCancel: "Cancel", KeyPause: "Pause", KeyPrint: "Print", KeyF1: "F1", KeyF2: "F2", KeyF3: "F3", KeyF4: "F4", KeyF5: "F5", KeyF6: "F6", KeyF7: "F7", KeyF8: "F8", KeyF9: "F9", KeyF10: "F10", KeyF11: "F11", KeyF12: "F12", KeyF13: "F13", KeyF14: "F14", KeyF15: "F15", KeyF16: "F16", KeyF17: "F17", KeyF18: "F18", KeyF19: "F19", KeyF20: "F20", KeyF21: "F21", KeyF22: "F22", KeyF23: "F23", KeyF24: "F24", KeyF25: "F25", KeyF26: "F26", KeyF27: "F27", KeyF28: "F28", KeyF29: "F29", KeyF30: "F30", KeyF31: "F31", KeyF32: "F32", KeyF33: "F33", KeyF34: "F34", KeyF35: "F35", KeyF36: "F36", KeyF37: "F37", KeyF38: "F38", KeyF39: "F39", KeyF40: "F40", KeyF41: "F41", KeyF42: "F42", KeyF43: "F43", KeyF44: "F44", KeyF45: "F45", KeyF46: "F46", KeyF47: "F47", KeyF48: "F48", KeyF49: "F49", KeyF50: "F50", KeyF51: "F51", KeyF52: "F52", KeyF53: "F53", KeyF54: "F54", KeyF55: "F55", KeyF56: "F56", KeyF57: "F57", KeyF58: "F58", KeyF59: "F59", KeyF60: "F60", KeyF61: "F61", KeyF62: "F62", KeyF63: "F63", KeyF64: "F64", KeyMenu: "Menu", KeyCapsLock: "CapsLock", KeyScrollLock: "ScrollLock", KeyNumLock: "NumLock", KeyCtrlSpace: "Ctrl-Space", KeyCtrlA: "Ctrl-A", KeyCtrlB: "Ctrl-B", KeyCtrlC: "Ctrl-C", KeyCtrlD: "Ctrl-D", KeyCtrlE: "Ctrl-E", KeyCtrlF: "Ctrl-F", KeyCtrlG: "Ctrl-G", KeyCtrlH: "Ctrl-H", KeyCtrlI: "Ctrl-I", KeyCtrlJ: "Ctrl-J", KeyCtrlK: "Ctrl-K", KeyCtrlL: "Ctrl-L", KeyCtrlM: "Ctrl-M", KeyCtrlN: "Ctrl-N", KeyCtrlO: "Ctrl-O", KeyCtrlP: "Ctrl-P", KeyCtrlQ: "Ctrl-Q", KeyCtrlR: "Ctrl-R", KeyCtrlS: "Ctrl-S", KeyCtrlT: "Ctrl-T", KeyCtrlU: "Ctrl-U", KeyCtrlV: "Ctrl-V", KeyCtrlW: "Ctrl-W", KeyCtrlX: "Ctrl-X", KeyCtrlY: "Ctrl-Y", KeyCtrlZ: "Ctrl-Z", KeyCtrlLeftSq: "Ctrl-[", KeyCtrlRightSq: "Ctrl-]", KeyCtrlBackslash: "Ctrl-\\", KeyCtrlCarat: "Ctrl-^", KeyCtrlUnderscore: "Ctrl-_", } // Name returns a printable value or the key stroke. This can be used // when printing the event, for example. func (ev *EventKey) Name() string { s := "" m := []string{} if ev.mod&ModShift != 0 { m = append(m, "Shift") } if ev.mod&ModAlt != 0 { m = append(m, "Alt") } if ev.mod&ModMeta != 0 { m = append(m, "Meta") } if ev.mod&ModCtrl != 0 { m = append(m, "Ctrl") } if ev.mod&ModHyper != 0 { m = append(m, "Hyper") } ok := false if s, ok = KeyNames[ev.key]; !ok { if ev.key == KeyRune { s = "Rune[" + string(ev.ch) + "]" } else { s = fmt.Sprintf("Key[%d,%d]", ev.key, int(ev.ch)) } } if len(m) != 0 { if ev.mod&ModCtrl != 0 && strings.HasPrefix(s, "Ctrl-") { s = s[5:] } return fmt.Sprintf("%s+%s", strings.Join(m, "+"), s) } return s } // NewEventKey attempts to create a suitable event. It parses the various // ASCII control sequences if KeyRune is passed for Key, but if the caller // has more precise information it should set that specifically. Callers // that aren't sure about modifier state (most) should just pass ModNone. func NewEventKey(k Key, ch rune, mod ModMask) *EventKey { if k == KeyRune && (ch < ' ' || ch == 0x7f) { // Turn specials into proper key codes. This is for // control characters and the DEL. k = Key(ch) if mod == ModNone && ch < ' ' { switch k { case KeyBackspace, KeyTab, KeyEsc, KeyEnter: // these keys are directly typeable without CTRL default: // most likely entered with a CTRL keypress mod = ModCtrl } ch = ch + '\x60' } } if k == KeyRune && ch >= 'A' && ch <= 'Z' && mod == ModCtrl { // We don't do Ctrl-[ or backslash or those specially. k = KeyCtrlA + Key(ch-'A') } // Might be lower case if k == KeyRune && ch >= 'a' && ch <= 'z' && mod == ModCtrl { // We don't do Ctrl-[ or backslash or those specially. k = KeyCtrlA + Key(ch-'a') } // Windows reports ModShift for shifted keys. This is inconsistent // with UNIX, lets harmonize this. if k == KeyRune && mod == ModShift && ch != 0 { mod = ModNone } if k >= KeyCtrlA && k <= KeyCtrlZ { if mod&ModShift != 0 { ch = rune((k - KeyCtrlA) + 'A') } else { ch = rune((k - KeyCtrlA) + 'a') } } // Backspace2 is just another name for backspace. if k == KeyBackspace2 { k = KeyBackspace } // Shift-Tab should be Backtab. if k == KeyTab && (mod&ModShift) != 0 { k = KeyBacktab mod &^= ModShift } return &EventKey{t: time.Now(), key: k, ch: ch, mod: mod} } // ModMask is a mask of modifier keys. Note that it will not always be // possible to report modifier keys. type ModMask int16 // These are the modifiers keys that can be sent either with a key press, // or a mouse event. Note that as of now, due to the confusion associated // with Meta, and the lack of support for it on many/most platforms, the // current implementations never use it. Instead, they use ModAlt, even for // events that could possibly have been distinguished from ModAlt. const ( ModShift ModMask = 1 << iota ModCtrl ModAlt ModMeta ModHyper ModNone ModMask = 0 ) // Key is a generic value for representing keys, and especially special // keys (function keys, cursor movement keys, etc.) For normal keys, like // ASCII letters, we use KeyRune, and then expect the application to // inspect the Rune() member of the EventKey. type Key int16 // This is the list of named keys. KeyRune is special however, in that it is // a place holder key indicating that a printable character was sent. The // actual value of the rune will be transported in the Rune of the associated // EventKey. const ( KeyRune Key = iota + 256 KeyUp KeyDown KeyRight KeyLeft KeyUpLeft KeyUpRight KeyDownLeft KeyDownRight KeyCenter KeyPgUp KeyPgDn KeyHome KeyEnd KeyInsert KeyDelete KeyHelp KeyExit KeyClear KeyCancel KeyPrint KeyPause KeyBacktab KeyF1 KeyF2 KeyF3 KeyF4 KeyF5 KeyF6 KeyF7 KeyF8 KeyF9 KeyF10 KeyF11 KeyF12 KeyF13 KeyF14 KeyF15 KeyF16 KeyF17 KeyF18 KeyF19 KeyF20 KeyF21 KeyF22 KeyF23 KeyF24 KeyF25 KeyF26 KeyF27 KeyF28 KeyF29 KeyF30 KeyF31 KeyF32 KeyF33 KeyF34 KeyF35 KeyF36 KeyF37 KeyF38 KeyF39 KeyF40 KeyF41 KeyF42 KeyF43 KeyF44 KeyF45 KeyF46 KeyF47 KeyF48 KeyF49 KeyF50 KeyF51 KeyF52 KeyF53 KeyF54 KeyF55 KeyF56 KeyF57 KeyF58 KeyF59 KeyF60 KeyF61 KeyF62 KeyF63 KeyF64 KeyMenu KeyCapsLock KeyScrollLock KeyNumLock ) const ( // These key codes are used internally, and will never appear to applications. keyPasteStart Key = iota + 16384 keyPasteEnd ) // These are the control keys, they will also be reported with the // rune (lower case) and control modifier. If the shift key // or other modifiers are present then these will *NOT* be reported, // but reported instead as KeyRune. const ( KeyCtrlSpace Key = iota + 64 KeyCtrlA KeyCtrlB KeyCtrlC KeyCtrlD KeyCtrlE KeyCtrlF KeyCtrlG KeyCtrlH KeyCtrlI KeyCtrlJ KeyCtrlK KeyCtrlL KeyCtrlM KeyCtrlN KeyCtrlO KeyCtrlP KeyCtrlQ KeyCtrlR KeyCtrlS KeyCtrlT KeyCtrlU KeyCtrlV KeyCtrlW KeyCtrlX KeyCtrlY KeyCtrlZ KeyCtrlLeftSq // Escape KeyCtrlBackslash KeyCtrlRightSq KeyCtrlCarat KeyCtrlUnderscore ) // Special values - these are fixed in an attempt to make it more likely // that aliases will encode the same way. // These are the defined ASCII values for key codes. They generally match // with KeyCtrl values. const ( KeyNUL Key = iota KeySOH KeySTX KeyETX KeyEOT KeyENQ KeyACK KeyBEL KeyBS KeyTAB KeyLF KeyVT KeyFF KeyCR KeySO KeySI KeyDLE KeyDC1 KeyDC2 KeyDC3 KeyDC4 KeyNAK KeySYN KeyETB KeyCAN KeyEM KeySUB KeyESC KeyFS KeyGS KeyRS KeyUS KeyDEL Key = 0x7F ) // These keys are aliases for other names. const ( KeyBackspace = KeyBS KeyTab = KeyTAB KeyEsc = KeyESC KeyEscape = KeyESC KeyEnter = KeyCR // NB: This key will be translated to KeyBackspace KeyBackspace2 = KeyDEL )
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/tscreen.go
vendor/github.com/gdamore/tcell/v2/tscreen.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !(js && wasm) // +build !js !wasm package tcell import ( "bytes" "encoding/base64" "errors" "io" "maps" "os" "runtime" "strconv" "strings" "sync" "unicode/utf8" "golang.org/x/term" "golang.org/x/text/transform" "github.com/gdamore/tcell/v2/terminfo" ) // NewTerminfoScreen returns a Screen that uses the stock TTY interface // and POSIX terminal control, combined with a terminfo description taken from // the $TERM environment variable. It returns an error if the terminal // is not supported for any reason. // // For terminals that do not support dynamic resize events, the $LINES // $COLUMNS environment variables can be set to the actual window size, // otherwise defaults taken from the terminal database are used. func NewTerminfoScreen() (Screen, error) { return NewTerminfoScreenFromTty(nil) } // LookupTerminfo attempts to find a definition for the named $TERM falling // back to attempting to parse the output from infocmp. func LookupTerminfo(name string) (ti *terminfo.Terminfo, e error) { ti, e = terminfo.LookupTerminfo(name) if e != nil { ti, e = loadDynamicTerminfo(name) if e != nil { return nil, e } terminfo.AddTerminfo(ti) } return } var defaultTerm string // NewTerminfoScreenFromTtyTerminfo returns a Screen using a custom Tty // implementation and custom terminfo specification. // If the passed in tty is nil, then a reasonable default (typically /dev/tty) // is presumed, at least on UNIX hosts. (Windows hosts will typically fail this // call altogether.) // If passed terminfo is nil, then TERM environment variable is queried for // terminal specification. func NewTerminfoScreenFromTtyTerminfo(tty Tty, ti *terminfo.Terminfo) (s Screen, e error) { term := defaultTerm if term == "" { term = os.Getenv("TERM") } if ti == nil { ti, e = LookupTerminfo(term) if e != nil { return nil, e } } t := &tScreen{ti: ti, tty: tty} if len(ti.Mouse) > 0 { t.mouse = []byte(ti.Mouse) } t.prepareKeys() t.buildAcsMap() t.resizeQ = make(chan bool, 1) t.fallback = make(map[rune]string) maps.Copy(t.fallback, RuneFallbacks) return &baseScreen{screenImpl: t}, nil } // NewTerminfoScreenFromTty returns a Screen using a custom Tty implementation. // If the passed in tty is nil, then a reasonable default (typically /dev/tty) // is presumed, at least on UNIX hosts. (Windows hosts will typically fail this // call altogether.) func NewTerminfoScreenFromTty(tty Tty) (Screen, error) { return NewTerminfoScreenFromTtyTerminfo(tty, nil) } // tKeyCode represents a combination of a key code and modifiers. type tKeyCode struct { key Key mod ModMask } // tScreen represents a screen backed by a terminfo implementation. type tScreen struct { ti *terminfo.Terminfo tty Tty h int w int fini bool cells CellBuffer buffering bool // true if we are collecting writes to buf instead of sending directly to out buf bytes.Buffer curstyle Style style Style resizeQ chan bool quit chan struct{} keychan chan []byte cx int cy int mouse []byte clear bool cursorx int cursory int acs map[rune]string charset string encoder transform.Transformer decoder transform.Transformer fallback map[rune]string colors map[Color]Color palette []Color truecolor bool escaped bool buttondn bool finiOnce sync.Once enablePaste string disablePaste string enterUrl string exitUrl string setWinSize string enableFocus string disableFocus string doubleUnder string curlyUnder string dottedUnder string dashedUnder string underColor string underRGB string underFg string // reset underline color to foreground cursorStyles map[CursorStyle]string cursorStyle CursorStyle cursorColor Color cursorRGB string cursorFg string saved *term.State stopQ chan struct{} eventQ chan Event running bool wg sync.WaitGroup mouseFlags MouseFlags pasteEnabled bool focusEnabled bool setTitle string saveTitle string restoreTitle string title string setClipboard string startSyncOut string endSyncOut string enableCsiU string disableCsiU string disableEmojiWA bool // if true don't try to workaround emoji bugs input InputProcessor sync.Mutex } func (t *tScreen) Init() error { if e := t.initialize(); e != nil { return e } t.keychan = make(chan []byte, 10) t.charset = getCharset() if enc := GetEncoding(t.charset); enc != nil { t.encoder = enc.NewEncoder() t.decoder = enc.NewDecoder() } else { return ErrNoCharset } ti := t.ti // environment overrides w := ti.Columns h := ti.Lines if i, _ := strconv.Atoi(os.Getenv("LINES")); i != 0 { h = i } if i, _ := strconv.Atoi(os.Getenv("COLUMNS")); i != 0 { w = i } if t.ti.SetFgBgRGB != "" || t.ti.SetFgRGB != "" || t.ti.SetBgRGB != "" { t.truecolor = true } // A user who wants to have his themes honored can // set this environment variable. if os.Getenv("TCELL_TRUECOLOR") == "disable" { t.truecolor = false } // clip to reasonable limits nColors := min(t.nColors(), 256) t.colors = make(map[Color]Color, nColors) t.palette = make([]Color, nColors) for i := range nColors { t.palette[i] = Color(i) | ColorValid // identity map for our builtin colors t.colors[Color(i)|ColorValid] = Color(i) | ColorValid } t.quit = make(chan struct{}) t.eventQ = make(chan Event, 256) t.input = NewInputProcessor(t.eventQ) t.Lock() t.cx = -1 t.cy = -1 t.style = StyleDefault t.cells.Resize(w, h) t.cursorx = -1 t.cursory = -1 t.resize() t.Unlock() if err := t.engage(); err != nil { return err } return nil } func (t *tScreen) prepareBracketedPaste() { // Another workaround for lack of reporting in terminfo. // We assume if the terminal has a mouse entry, that it // offers bracketed paste. But we allow specific overrides // via our terminal database. if t.ti.Mouse != "" || t.ti.XTermLike { t.enablePaste = "\x1b[?2004h" t.disablePaste = "\x1b[?2004l" } } func (t *tScreen) prepareUnderlines() { if t.ti.XTermLike { t.doubleUnder = "\x1b[4:2m" t.curlyUnder = "\x1b[4:3m" t.dottedUnder = "\x1b[4:4m" t.dashedUnder = "\x1b[4:5m" t.underColor = "\x1b[58:5:%p1%dm" t.underRGB = "\x1b[58:2::%p1%d:%p2%d:%p3%dm" t.underFg = "\x1b[59m" } } func (t *tScreen) prepareExtendedOSC() { // Linux is a special beast - because it has a mouse entry, but does // not swallow these OSC commands properly. if strings.Contains(t.ti.Name, "linux") { return } // More stuff for limits in terminfo. This time we are applying // the most common OSC (operating system commands). Generally // terminals that don't understand these will ignore them. // Again, we condition this based on mouse capabilities. if t.ti.Mouse != "" || t.ti.XTermLike { t.enterUrl = "\x1b]8;%p2%s;%p1%s\x1b\\" t.exitUrl = "\x1b]8;;\x1b\\" } if t.ti.Mouse != "" || t.ti.XTermLike { t.setWinSize = "\x1b[8;%p1%p2%d;%dt" } if t.ti.Mouse != "" || t.ti.XTermLike { t.enableFocus = "\x1b[?1004h" t.disableFocus = "\x1b[?1004l" } if t.ti.XTermLike { t.saveTitle = "\x1b[22;2t" t.restoreTitle = "\x1b[23;2t" // this also tries to request that UTF-8 is allowed in the title t.setTitle = "\x1b[>2t\x1b]2;%p1%s\x1b\\" } if t.setClipboard == "" && t.ti.XTermLike { // this string takes a base64 string and sends it to the clipboard. // it will also be able to retrieve the clipboard using "?" as the // sent string, when we support that. t.setClipboard = "\x1b]52;c;%p1%s\x1b\\" } if t.startSyncOut == "" && t.ti.XTermLike { // this is in theory a queryable private mode, but we just assume it will be ok // The terminals we have been able to test it all either just swallow it, or // handle it. t.startSyncOut = "\x1b[?2026h" t.endSyncOut = "\x1b[?2026l" } if t.enableCsiU == "" && t.ti.XTermLike { if runtime.GOOS == "windows" && os.Getenv("TERM") == "" { // on Windows, if we don't have a TERM, use only win32-input-mode t.enableCsiU = "\x1b[?9001h" t.disableCsiU = "\x1b[?9001l" } else { // three advanced keyboard protocols: // - xterm modifyOtherKeys (uses CSI 27 ~ ) // - kitty csi-u (uses CSI u) // - win32-input-mode (uses CSI _) t.enableCsiU = "\x1b[>4;2m" + "\x1b[>1u" + "\x1b[?9001h" t.disableCsiU = "\x1b[?9001l" + "\x1b[<u" + "\x1b[>4;0m" } } } func (t *tScreen) prepareCursorStyles() { if t.ti.Mouse != "" || t.ti.XTermLike { t.cursorStyles = map[CursorStyle]string{ CursorStyleDefault: "\x1b[0 q", CursorStyleBlinkingBlock: "\x1b[1 q", CursorStyleSteadyBlock: "\x1b[2 q", CursorStyleBlinkingUnderline: "\x1b[3 q", CursorStyleSteadyUnderline: "\x1b[4 q", CursorStyleBlinkingBar: "\x1b[5 q", CursorStyleSteadyBar: "\x1b[6 q", } if t.cursorRGB == "" { t.cursorRGB = "\x1b]12;#%p1%02x%p2%02x%p3%02x\007" t.cursorFg = "\x1b]112\007" } } } func (t *tScreen) prepareKeys() { ti := t.ti if strings.HasPrefix(ti.Name, "xterm") { // assume its some form of XTerm clone t.ti.XTermLike = true ti.XTermLike = true } t.prepareBracketedPaste() t.prepareCursorStyles() t.prepareUnderlines() t.prepareExtendedOSC() } func (t *tScreen) Fini() { t.finiOnce.Do(t.finish) } func (t *tScreen) finish() { close(t.quit) t.finalize() } func (t *tScreen) SetStyle(style Style) { t.Lock() if !t.fini { t.style = style } t.Unlock() } func (t *tScreen) encodeStr(s string) []byte { var dstBuf [128]byte var buf []byte nb := dstBuf[:] dst := 0 var err error if enc := t.encoder; enc != nil { enc.Reset() dst, _, err = enc.Transform(nb, []byte(s), true) } if err != nil || dst == 0 || nb[0] == '\x1a' { // Combining characters are elided r, _ := utf8.DecodeRuneInString(s) if len(buf) == 0 { if acs, ok := t.acs[r]; ok { buf = append(buf, []byte(acs)...) } else if fb, ok := t.fallback[r]; ok { buf = append(buf, []byte(fb)...) } else { buf = append(buf, '?') } } } else { buf = append(buf, nb[:dst]...) } return buf } func (t *tScreen) sendFgBg(fg Color, bg Color, attr AttrMask) AttrMask { ti := t.ti if t.Colors() == 0 { // foreground vs background, we calculate luminance // and possibly do a reverse video if !fg.Valid() { return attr } v, ok := t.colors[fg] if !ok { v = FindColor(fg, []Color{ColorBlack, ColorWhite}) t.colors[fg] = v } switch v { case ColorWhite: return attr case ColorBlack: return attr ^ AttrReverse } } if fg == ColorReset || bg == ColorReset { t.TPuts(ti.ResetFgBg) } if t.truecolor { if ti.SetFgBgRGB != "" && fg.IsRGB() && bg.IsRGB() { r1, g1, b1 := fg.RGB() r2, g2, b2 := bg.RGB() t.TPuts(ti.TParm(ti.SetFgBgRGB, int(r1), int(g1), int(b1), int(r2), int(g2), int(b2))) return attr } if fg.IsRGB() && ti.SetFgRGB != "" { r, g, b := fg.RGB() t.TPuts(ti.TParm(ti.SetFgRGB, int(r), int(g), int(b))) fg = ColorDefault } if bg.IsRGB() && ti.SetBgRGB != "" { r, g, b := bg.RGB() t.TPuts(ti.TParm(ti.SetBgRGB, int(r), int(g), int(b))) bg = ColorDefault } } if fg.Valid() { if v, ok := t.colors[fg]; ok { fg = v } else { v = FindColor(fg, t.palette) t.colors[fg] = v fg = v } } if bg.Valid() { if v, ok := t.colors[bg]; ok { bg = v } else { v = FindColor(bg, t.palette) t.colors[bg] = v bg = v } } if fg.Valid() && bg.Valid() && ti.SetFgBg != "" { t.TPuts(ti.TParm(ti.SetFgBg, int(fg&0xff), int(bg&0xff))) } else { if fg.Valid() && ti.SetFg != "" { t.TPuts(ti.TParm(ti.SetFg, int(fg&0xff))) } if bg.Valid() && ti.SetBg != "" { t.TPuts(ti.TParm(ti.SetBg, int(bg&0xff))) } } return attr } func (t *tScreen) drawCell(x, y int) int { ti := t.ti str, style, width := t.cells.Get(x, y) if !t.cells.Dirty(x, y) { return width } if y == t.h-1 && x == t.w-1 && t.ti.AutoMargin && ti.DisableAutoMargin == "" && ti.InsertChar != "" { // our solution is somewhat goofy. // we write to the second to the last cell what we want in the last cell, then we // insert a character at that 2nd to last position to shift the last column into // place, then we rewrite that 2nd to last cell. Old terminals suck. t.TPuts(ti.TGoto(x-1, y)) defer func() { t.TPuts(ti.TGoto(x-1, y)) t.TPuts(ti.InsertChar) t.cy = y t.cx = x - 1 t.cells.SetDirty(x-1, y, true) _ = t.drawCell(x-1, y) t.TPuts(t.ti.TGoto(0, 0)) t.cy = 0 t.cx = 0 }() } else if t.cy != y || t.cx != x { t.TPuts(ti.TGoto(x, y)) t.cx = x t.cy = y } if style == StyleDefault { style = t.style } if style != t.curstyle { fg, bg, attrs := style.fg, style.bg, style.attrs t.TPuts(ti.AttrOff) attrs = t.sendFgBg(fg, bg, attrs) if attrs&AttrBold != 0 { t.TPuts(ti.Bold) } if us, uc := style.ulStyle, style.ulColor; us != UnderlineStyleNone { if t.underColor != "" || t.underRGB != "" { if uc == ColorReset { t.TPuts(t.underFg) } else if uc.IsRGB() { if t.underRGB != "" { r, g, b := uc.RGB() t.TPuts(ti.TParm(t.underRGB, int(r), int(g), int(b))) } else { if v, ok := t.colors[uc]; ok { uc = v } else { v = FindColor(uc, t.palette) t.colors[uc] = v uc = v } t.TPuts(ti.TParm(t.underColor, int(uc&0xff))) } } else if uc.Valid() { t.TPuts(ti.TParm(t.underColor, int(uc&0xff))) } } t.TPuts(ti.Underline) // to ensure everyone gets at least a basic underline switch us { case UnderlineStyleDouble: t.TPuts(t.doubleUnder) case UnderlineStyleCurly: t.TPuts(t.curlyUnder) case UnderlineStyleDotted: t.TPuts(t.dottedUnder) case UnderlineStyleDashed: t.TPuts(t.dashedUnder) } } if attrs&AttrReverse != 0 { t.TPuts(ti.Reverse) } if attrs&AttrBlink != 0 { t.TPuts(ti.Blink) } if attrs&AttrDim != 0 { t.TPuts(ti.Dim) } if attrs&AttrItalic != 0 { t.TPuts(ti.Italic) } if attrs&AttrStrikeThrough != 0 { t.TPuts(ti.StrikeThrough) } // URL string can be long, so don't send it unless we really need to if t.enterUrl != "" && t.curstyle.url != style.url { if style.url != "" { t.TPuts(ti.TParm(t.enterUrl, style.url, style.urlId)) } else { t.TPuts(t.exitUrl) } } t.curstyle = style } // now emit runes - taking care to not overrun width with a // wide character, and to ensure that we emit exactly one regular // character followed up by any residual combing characters if width < 1 { width = 1 } buf := t.encodeStr(str) str = string(buf) if width > 1 && str == "?" { // No FullWidth character support str = "? " t.cx = -1 } if x > t.w-width { // too wide to fit; emit a single space instead width = 1 str = " " } t.writeString(str) t.cx += width t.cells.SetDirty(x, y, false) if width > 1 { t.cx = -1 } return width } func (t *tScreen) ShowCursor(x, y int) { t.Lock() t.cursorx = x t.cursory = y t.Unlock() } func (t *tScreen) SetCursor(cs CursorStyle, cc Color) { t.Lock() t.cursorStyle = cs t.cursorColor = cc t.Unlock() } func (t *tScreen) HideCursor() { t.ShowCursor(-1, -1) } func (t *tScreen) showCursor() { x, y := t.cursorx, t.cursory w, h := t.cells.Size() if x < 0 || y < 0 || x >= w || y >= h { t.hideCursor() return } t.TPuts(t.ti.TGoto(x, y)) t.TPuts(t.ti.ShowCursor) if t.cursorStyles != nil { if esc, ok := t.cursorStyles[t.cursorStyle]; ok { t.TPuts(esc) } } if t.cursorRGB != "" { if t.cursorColor == ColorReset { t.TPuts(t.cursorFg) } else if t.cursorColor.Valid() { r, g, b := t.cursorColor.RGB() t.TPuts(t.ti.TParm(t.cursorRGB, int(r), int(g), int(b))) } } t.cx = x t.cy = y } // writeString sends a string to the terminal. The string is sent as-is and // this function does not expand inline padding indications (of the form // $<[delay]> where [delay] is msec). In order to have these expanded, use // TPuts. If the screen is "buffering", the string is collected in a buffer, // with the intention that the entire buffer be sent to the terminal in one // write operation at some point later. func (t *tScreen) writeString(s string) { if t.buffering { _, _ = io.WriteString(&t.buf, s) } else { _, _ = io.WriteString(t.tty, s) } } func (t *tScreen) TPuts(s string) { if t.buffering { t.ti.TPuts(&t.buf, s) } else { t.ti.TPuts(t.tty, s) } } func (t *tScreen) Show() { t.Lock() if !t.fini { t.resize() t.draw() } t.Unlock() } func (t *tScreen) clearScreen() { t.TPuts(t.ti.AttrOff) t.TPuts(t.exitUrl) _ = t.sendFgBg(t.style.fg, t.style.bg, AttrNone) t.TPuts(t.ti.Clear) t.clear = false } func (t *tScreen) startBuffering() { t.TPuts(t.startSyncOut) } func (t *tScreen) endBuffering() { t.TPuts(t.endSyncOut) } func (t *tScreen) hideCursor() { // does not update cursor position if t.ti.HideCursor != "" { t.TPuts(t.ti.HideCursor) } else { // No way to hide cursor, stick it // at bottom right of screen t.cx, t.cy = t.cells.Size() t.TPuts(t.ti.TGoto(t.cx, t.cy)) } } func (t *tScreen) draw() { // clobber cursor position, because we're going to change it all t.cx = -1 t.cy = -1 // make no style assumptions t.curstyle = styleInvalid t.buf.Reset() t.buffering = true t.startBuffering() defer func() { t.buffering = false t.endBuffering() }() // hide the cursor while we move stuff around t.hideCursor() if t.clear { t.clearScreen() } for y := 0; y < t.h; y++ { for x := 0; x < t.w; x++ { width := t.drawCell(x, y) if width > 1 { if x+1 < t.w { // this is necessary so that if we ever // go back to drawing that cell, we // actually will *draw* it. t.cells.SetDirty(x+1, y, true) } } x += width - 1 } } // restore the cursor t.showCursor() _, _ = t.buf.WriteTo(t.tty) } func (t *tScreen) EnableMouse(flags ...MouseFlags) { var f MouseFlags flagsPresent := false for _, flag := range flags { f |= flag flagsPresent = true } if !flagsPresent { f = MouseMotionEvents | MouseDragEvents | MouseButtonEvents } t.Lock() t.mouseFlags = f t.enableMouse(f) t.Unlock() } func (t *tScreen) enableMouse(f MouseFlags) { // Rather than using terminfo to find mouse escape sequences, we rely on the fact that // pretty much *every* terminal that supports mouse tracking follows the // XTerm standards (the modern ones). if len(t.mouse) != 0 { // start by disabling all tracking. t.TPuts("\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l") if f&MouseButtonEvents != 0 { t.TPuts("\x1b[?1000h") } if f&MouseDragEvents != 0 { t.TPuts("\x1b[?1002h") } if f&MouseMotionEvents != 0 { t.TPuts("\x1b[?1003h") } if f&(MouseButtonEvents|MouseDragEvents|MouseMotionEvents) != 0 { t.TPuts("\x1b[?1006h") } } } func (t *tScreen) DisableMouse() { t.Lock() t.mouseFlags = 0 t.enableMouse(0) t.Unlock() } func (t *tScreen) EnablePaste() { t.Lock() t.pasteEnabled = true t.enablePasting(true) t.Unlock() } func (t *tScreen) DisablePaste() { t.Lock() t.pasteEnabled = false t.enablePasting(false) t.Unlock() } func (t *tScreen) enablePasting(on bool) { var s string if on { s = t.enablePaste } else { s = t.disablePaste } if s != "" { t.TPuts(s) } } func (t *tScreen) EnableFocus() { t.Lock() t.focusEnabled = true t.enableFocusReporting() t.Unlock() } func (t *tScreen) DisableFocus() { t.Lock() t.focusEnabled = false t.disableFocusReporting() t.Unlock() } func (t *tScreen) enableFocusReporting() { if t.enableFocus != "" { t.TPuts(t.enableFocus) } } func (t *tScreen) disableFocusReporting() { if t.disableFocus != "" { t.TPuts(t.disableFocus) } } func (t *tScreen) Size() (int, int) { t.Lock() w, h := t.w, t.h t.Unlock() return w, h } func (t *tScreen) resize() { ws, err := t.tty.WindowSize() if err != nil { return } if ws.Width == t.w && ws.Height == t.h { return } t.cx = -1 t.cy = -1 t.cells.Resize(ws.Width, ws.Height) t.cells.Invalidate() t.h = ws.Height t.w = ws.Width t.input.SetSize(ws.Width, ws.Height) } func (t *tScreen) Colors() int { if os.Getenv("NO_COLOR") != "" { return 0 } // this doesn't change, no need for lock if t.truecolor { return 1 << 24 } return t.ti.Colors } // nColors returns the size of the built-in palette. // This is distinct from Colors(), as it will generally // always be a small number. (<= 256) func (t *tScreen) nColors() int { if os.Getenv("NO_COLOR") != "" { return 0 } return t.ti.Colors } // vtACSNames is a map of bytes defined by terminfo that are used in // the terminals Alternate Character Set to represent other glyphs. // For example, the upper left corner of the box drawing set can be // displayed by printing "l" while in the alternate character set. // It's not quite that simple, since the "l" is the terminfo name, // and it may be necessary to use a different character based on // the terminal implementation (or the terminal may lack support for // this altogether). See buildAcsMap below for detail. var vtACSNames = map[byte]rune{ '+': RuneRArrow, ',': RuneLArrow, '-': RuneUArrow, '.': RuneDArrow, '0': RuneBlock, '`': RuneDiamond, 'a': RuneCkBoard, 'b': '␉', // VT100, Not defined by terminfo 'c': '␌', // VT100, Not defined by terminfo 'd': '␋', // VT100, Not defined by terminfo 'e': '␊', // VT100, Not defined by terminfo 'f': RuneDegree, 'g': RunePlMinus, 'h': RuneBoard, 'i': RuneLantern, 'j': RuneLRCorner, 'k': RuneURCorner, 'l': RuneULCorner, 'm': RuneLLCorner, 'n': RunePlus, 'o': RuneS1, 'p': RuneS3, 'q': RuneHLine, 'r': RuneS7, 's': RuneS9, 't': RuneLTee, 'u': RuneRTee, 'v': RuneBTee, 'w': RuneTTee, 'x': RuneVLine, 'y': RuneLEqual, 'z': RuneGEqual, '{': RunePi, '|': RuneNEqual, '}': RuneSterling, '~': RuneBullet, } // buildAcsMap builds a map of characters that we translate from Unicode to // alternate character encodings. To do this, we use the standard VT100 ACS // maps. This is only done if the terminal lacks support for Unicode; we // always prefer to emit Unicode glyphs when we are able. func (t *tScreen) buildAcsMap() { acsstr := t.ti.AltChars t.acs = make(map[rune]string) for len(acsstr) > 2 { srcv := acsstr[0] dstv := string(acsstr[1]) if r, ok := vtACSNames[srcv]; ok { t.acs[r] = t.ti.EnterAcs + dstv + t.ti.ExitAcs } acsstr = acsstr[2:] } } func (t *tScreen) scanInput(buf *bytes.Buffer) { for buf.Len() > 0 { utf := make([]byte, min(8, max(buf.Len()*2, 128))) nOut, nIn, e := t.decoder.Transform(utf, buf.Bytes(), true) _ = buf.Next(nIn) t.input.ScanUTF8(utf[:nOut]) if e == transform.ErrShortSrc { return } } } func (t *tScreen) mainLoop(stopQ chan struct{}) { defer t.wg.Done() buf := &bytes.Buffer{} for { select { case <-stopQ: return case <-t.quit: return case <-t.resizeQ: t.Lock() t.cx = -1 t.cy = -1 t.resize() t.cells.Invalidate() t.draw() t.Unlock() continue case chunk := <-t.keychan: buf.Write(chunk) t.scanInput(buf) } } } func (t *tScreen) inputLoop(stopQ chan struct{}) { defer t.wg.Done() for { select { case <-stopQ: return default: } chunk := make([]byte, 128) n, e := t.tty.Read(chunk) switch e { case nil: default: t.Lock() running := t.running t.Unlock() if running { select { case t.eventQ <- NewEventError(e): case <-t.quit: } } return } if n > 0 { t.keychan <- chunk[:n] } } } func (t *tScreen) Sync() { t.Lock() t.cx = -1 t.cy = -1 if !t.fini { t.resize() t.clear = true t.cells.Invalidate() t.draw() } t.Unlock() } func (t *tScreen) CharacterSet() string { return t.charset } func (t *tScreen) RegisterRuneFallback(orig rune, fallback string) { t.Lock() t.fallback[orig] = fallback t.Unlock() } func (t *tScreen) UnregisterRuneFallback(orig rune) { t.Lock() delete(t.fallback, orig) t.Unlock() } func (t *tScreen) CanDisplay(r rune, checkFallbacks bool) bool { if enc := t.encoder; enc != nil { nb := make([]byte, 6) enc.Reset() dst, _, err := enc.Transform(nb, []byte(string(r)), true) if dst != 0 && err == nil && nb[0] != '\x1A' { return true } } // Terminal fallbacks always permitted, since we assume they are // basically nearly perfect renditions. if _, ok := t.acs[r]; ok { return true } if !checkFallbacks { return false } if _, ok := t.fallback[r]; ok { return true } return false } func (t *tScreen) HasMouse() bool { return len(t.mouse) != 0 } func (t *tScreen) HasKey(_ Key) bool { // We always return true return true } func (t *tScreen) SetSize(w, h int) { if t.setWinSize != "" { t.TPuts(t.ti.TParm(t.setWinSize, w, h)) } t.cells.Invalidate() t.resize() } func (t *tScreen) Resize(int, int, int, int) {} func (t *tScreen) Suspend() error { t.disengage() return nil } func (t *tScreen) Resume() error { return t.engage() } func (t *tScreen) Tty() (Tty, bool) { return t.tty, true } // engage is used to place the terminal in raw mode and establish screen size, etc. // Think of this is as tcell "engaging" the clutch, as it's going to be driving the // terminal interface. func (t *tScreen) engage() error { t.Lock() defer t.Unlock() if t.tty == nil { return ErrNoScreen } t.tty.NotifyResize(func() { select { case t.resizeQ <- true: default: } }) if t.running { return errors.New("already engaged") } if err := t.tty.Start(); err != nil { return err } t.running = true if ws, err := t.tty.WindowSize(); err == nil && ws.Width != 0 && ws.Height != 0 { t.cells.Resize(ws.Width, ws.Height) } stopQ := make(chan struct{}) t.stopQ = stopQ t.enableMouse(t.mouseFlags) t.enablePasting(t.pasteEnabled) if t.focusEnabled { t.enableFocusReporting() } ti := t.ti if os.Getenv("TCELL_ALTSCREEN") != "disable" { // Technically this may not be right, but every terminal we know about // (even Wyse 60) uses this to enter the alternate screen buffer, and // possibly save and restore the window title and/or icon. // (In theory there could be terminals that don't support X,Y cursor // positions without a setup command, but we don't support them.) t.TPuts(ti.EnterCA) t.TPuts(t.saveTitle) } t.TPuts(ti.EnterKeypad) t.TPuts(ti.HideCursor) t.TPuts(ti.EnableAcs) t.TPuts(ti.DisableAutoMargin) t.TPuts(ti.Clear) if t.title != "" && t.setTitle != "" { t.TPuts(t.ti.TParm(t.setTitle, t.title)) } t.TPuts(t.enableCsiU) t.wg.Add(2) go t.inputLoop(stopQ) go t.mainLoop(stopQ) return nil } // disengage is used to release the terminal back to support from the caller. // Think of this as tcell disengaging the clutch, so that another application // can take over the terminal interface. This restores the TTY mode that was // present when the application was first started. func (t *tScreen) disengage() { t.Lock() if !t.running { t.Unlock() return } t.running = false stopQ := t.stopQ close(stopQ) _ = t.tty.Drain() t.Unlock() t.tty.NotifyResize(nil) // wait for everything to shut down t.wg.Wait() // shutdown the screen and disable special modes (e.g. mouse and bracketed paste) ti := t.ti t.cells.Resize(0, 0) t.TPuts(ti.ShowCursor) if t.cursorStyles != nil && t.cursorStyle != CursorStyleDefault { t.TPuts(t.cursorStyles[CursorStyleDefault]) } if t.cursorFg != "" && t.cursorColor.Valid() { t.TPuts(t.cursorFg) } t.TPuts(ti.ResetFgBg) t.TPuts(ti.AttrOff) t.TPuts(ti.ExitKeypad) t.TPuts(ti.EnableAutoMargin) t.TPuts(t.disableCsiU) if os.Getenv("TCELL_ALTSCREEN") != "disable" { if t.restoreTitle != "" { t.TPuts(t.restoreTitle) } t.TPuts(ti.Clear) // only needed if ExitCA is empty t.TPuts(ti.ExitCA) } t.enableMouse(0) t.enablePasting(false) t.disableFocusReporting() _ = t.tty.Stop() } // Beep emits a beep to the terminal. func (t *tScreen) Beep() error { t.writeString(string(byte(7))) return nil } // finalize is used to at application shutdown, and restores the terminal // to it's initial state. It should not be called more than once. func (t *tScreen) finalize() { t.disengage() _ = t.tty.Close() } func (t *tScreen) StopQ() <-chan struct{} { return t.quit } func (t *tScreen) EventQ() chan Event { return t.eventQ } func (t *tScreen) GetCells() *CellBuffer { return &t.cells } func (t *tScreen) SetTitle(title string) { t.Lock() t.title = title if t.setTitle != "" && t.running { t.TPuts(t.ti.TParm(t.setTitle, title)) } t.Unlock() } func (t *tScreen) SetClipboard(data []byte) { // Post binary data to the system clipboard. It might be UTF-8, it might not be. t.Lock() if t.setClipboard != "" { encoded := base64.StdEncoding.EncodeToString(data) t.TPuts(t.ti.TParm(t.setClipboard, encoded)) } t.Unlock() } func (t *tScreen) GetClipboard() { t.Lock() if t.setClipboard != "" { t.TPuts(t.ti.TParm(t.setClipboard, "?")) } t.Unlock() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/terminfo.go
vendor/github.com/gdamore/tcell/v2/terminfo/terminfo.go
// Copyright 2025 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package terminfo import ( "bytes" "errors" "fmt" "io" "os" "strconv" "strings" "sync" "time" ) var ( // ErrTermNotFound indicates that a suitable terminal entry could // not be found. This can result from either not having TERM set, // or from the TERM failing to support certain minimal functionality, // in particular absolute cursor addressability (the cup capability) // is required. For example, legacy "adm3" lacks this capability, // whereas the slightly newer "adm3a" supports it. This failure // occurs most often with "dumb". ErrTermNotFound = errors.New("terminal entry not found") ) // Terminfo represents a terminfo entry. Note that we use friendly names // in Go, but when we write out JSON, we use the same names as terminfo. // The name, aliases and smous, rmous fields do not come from terminfo directly. type Terminfo struct { Name string Aliases []string Columns int // cols Lines int // lines Colors int // colors Clear string // clear EnterCA string // smcup ExitCA string // rmcup ShowCursor string // cnorm HideCursor string // civis AttrOff string // sgr0 Underline string // smul Bold string // bold Blink string // blink Reverse string // rev Dim string // dim Italic string // sitm EnterKeypad string // smkx ExitKeypad string // rmkx SetFg string // setaf SetBg string // setab ResetFgBg string // op SetCursor string // cup PadChar string // pad Mouse string // kmous AltChars string // acsc EnterAcs string // smacs ExitAcs string // rmacs EnableAcs string // enacs // These are non-standard extensions to terminfo. This includes // true color support, and some additional keys. Its kind of bizarre // that shifted variants of left and right exist, but not up and down. // Terminal support for these are going to vary amongst XTerm // emulations, so don't depend too much on them in your application. StrikeThrough string // smxx SetFgBg string // setfgbg SetFgBgRGB string // setfgbgrgb SetFgRGB string // setfrgb SetBgRGB string // setbrgb InsertChar string // string to insert a character (ich1) AutoMargin bool // true if writing to last cell in line advances TrueColor bool // true if the terminal supports direct color DisableAutoMargin string // smam EnableAutoMargin string // rmam XTermLike bool // (XT) has XTerm extensions } type stack []any func (st stack) Push(v any) stack { if b, ok := v.(bool); ok { if b { return append(st, 1) } else { return append(st, 0) } } return append(st, v) } func (st stack) PopString() (string, stack) { if len(st) > 0 { e := st[len(st)-1] var s string switch v := e.(type) { case int: s = strconv.Itoa(v) case string: s = v } return s, st[:len(st)-1] } return "", st } func (st stack) PopInt() (int, stack) { if len(st) > 0 { e := st[len(st)-1] var i int switch v := e.(type) { case int: i = v case string: i, _ = strconv.Atoi(v) } return i, st[:len(st)-1] } return 0, st } // static vars var svars [26]string type paramsBuffer struct { out bytes.Buffer buf bytes.Buffer } // Start initializes the params buffer with the initial string data. // It also locks the paramsBuffer. The caller must call End() when // finished. func (pb *paramsBuffer) Start(s string) { pb.out.Reset() pb.buf.Reset() pb.buf.WriteString(s) } // End returns the final output from TParam, but it also releases the lock. func (pb *paramsBuffer) End() string { s := pb.out.String() return s } // NextCh returns the next input character to the expander. func (pb *paramsBuffer) NextCh() (byte, error) { return pb.buf.ReadByte() } // PutCh "emits" (rather schedules for output) a single byte character. func (pb *paramsBuffer) PutCh(ch byte) { pb.out.WriteByte(ch) } // PutString schedules a string for output. func (pb *paramsBuffer) PutString(s string) { pb.out.WriteString(s) } // TParm takes a terminfo parameterized string, such as setaf or cup, and // evaluates the string, and returns the result with the parameter // applied. func (t *Terminfo) TParm(s string, p ...any) string { var stk stack var a string var ai, bi int var dvars [26]string var params [9]any var pb = &paramsBuffer{} pb.Start(s) // make sure we always have 9 parameters -- makes it easier // later to skip checks for i := 0; i < len(params) && i < len(p); i++ { params[i] = p[i] } const ( emit = iota toEnd toElse ) skip := emit for { ch, err := pb.NextCh() if err != nil { break } if ch != '%' { if skip == emit { pb.PutCh(ch) } continue } ch, err = pb.NextCh() if err != nil { // XXX Error break } if skip == toEnd { if ch == ';' { skip = emit } continue } else if skip == toElse { if ch == 'e' || ch == ';' { skip = emit } continue } switch ch { case '%': // quoted % pb.PutCh(ch) case 'i': // increment both parameters (ANSI cup support) if i, ok := params[0].(int); ok { params[0] = i + 1 } if i, ok := params[1].(int); ok { params[1] = i + 1 } case 's': // NB: 's', 'c', and 'd' below are special cased for // efficiency. They could be handled by the richer // format support below, less efficiently. a, stk = stk.PopString() pb.PutString(a) case 'c': // Integer as special character. ai, stk = stk.PopInt() pb.PutCh(byte(ai)) case 'd': ai, stk = stk.PopInt() pb.PutString(strconv.Itoa(ai)) case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'x', 'X', 'o', ':': // This is pretty suboptimal, but this is rarely used. // None of the mainstream terminals use any of this, // and it would surprise me if this code is ever // executed outside test cases. f := "%" if ch == ':' { ch, _ = pb.NextCh() } f += string(ch) for ch == '+' || ch == '-' || ch == '#' || ch == ' ' { ch, _ = pb.NextCh() f += string(ch) } for (ch >= '0' && ch <= '9') || ch == '.' { ch, _ = pb.NextCh() f += string(ch) } switch ch { case 'd', 'x', 'X', 'o': ai, stk = stk.PopInt() pb.PutString(fmt.Sprintf(f, ai)) case 's': a, stk = stk.PopString() pb.PutString(fmt.Sprintf(f, a)) case 'c': ai, stk = stk.PopInt() pb.PutString(fmt.Sprintf(f, ai)) } case 'p': // push parameter ch, _ = pb.NextCh() ai = int(ch - '1') if ai >= 0 && ai < len(params) { stk = stk.Push(params[ai]) } else { stk = stk.Push(0) } case 'P': // pop & store variable ch, _ = pb.NextCh() if ch >= 'A' && ch <= 'Z' { svars[int(ch-'A')], stk = stk.PopString() } else if ch >= 'a' && ch <= 'z' { dvars[int(ch-'a')], stk = stk.PopString() } case 'g': // recall & push variable ch, _ = pb.NextCh() if ch >= 'A' && ch <= 'Z' { stk = stk.Push(svars[int(ch-'A')]) } else if ch >= 'a' && ch <= 'z' { stk = stk.Push(dvars[int(ch-'a')]) } case '\'': // push(char) - the integer value of it ch, _ = pb.NextCh() _, _ = pb.NextCh() // must be ' but we don't check stk = stk.Push(int(ch)) case '{': // push(int) ai = 0 ch, _ = pb.NextCh() for ch >= '0' && ch <= '9' { ai *= 10 ai += int(ch - '0') ch, _ = pb.NextCh() } // ch must be '}' but no verification stk = stk.Push(ai) case 'l': // push(strlen(pop)) a, stk = stk.PopString() stk = stk.Push(len(a)) case '+': bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai + bi) case '-': bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai - bi) case '*': bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai * bi) case '/': bi, stk = stk.PopInt() ai, stk = stk.PopInt() if bi != 0 { stk = stk.Push(ai / bi) } else { stk = stk.Push(0) } case 'm': // push(pop mod pop) bi, stk = stk.PopInt() ai, stk = stk.PopInt() if bi != 0 { stk = stk.Push(ai % bi) } else { stk = stk.Push(0) } case '&': // AND bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai & bi) case '|': // OR bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai | bi) case '^': // XOR bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai ^ bi) case '~': // bit complement ai, stk = stk.PopInt() stk = stk.Push(ai ^ -1) case '!': // logical NOT ai, stk = stk.PopInt() stk = stk.Push(ai == 0) case '=': // numeric compare bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai == bi) case '>': // greater than, numeric bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai > bi) case '<': // less than, numeric bi, stk = stk.PopInt() ai, stk = stk.PopInt() stk = stk.Push(ai < bi) case '?': // start conditional case ';': skip = emit case 't': ai, stk = stk.PopInt() if ai == 0 { skip = toElse } case 'e': skip = toEnd default: pb.PutString("%" + string(ch)) } } return pb.End() } // TPuts emits the string to the writer, but expands inline padding // indications (of the form $<[delay]> where [delay] is msec) to // a suitable time (unless the terminfo string indicates this isn't needed // by specifying npc - no padding). All Terminfo based strings should be // emitted using this function. func (t *Terminfo) TPuts(w io.Writer, s string) { for { beg := strings.Index(s, "$<") if beg < 0 { // Most strings don't need padding, which is good news! _, _ = io.WriteString(w, s) return } _, _ = io.WriteString(w, s[:beg]) s = s[beg+2:] end := strings.Index(s, ">") if end < 0 { // unterminated.. just emit bytes unadulterated _, _ = io.WriteString(w, "$<"+s) return } val := s[:end] s = s[end+1:] padus := 0 unit := time.Millisecond dot := false loop: for i := range val { switch val[i] { case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': padus *= 10 padus += int(val[i] - '0') if dot { unit /= 10 } case '.': if !dot { dot = true } else { break loop } default: break loop } } // Curses historically uses padding to achieve "fine grained" // delays. We have much better clocks these days, and so we // do not rely on padding but simply sleep a bit. if len(t.PadChar) > 0 { time.Sleep(unit * time.Duration(padus)) } } } // TGoto returns a string suitable for addressing the cursor at the given // row and column. The origin 0, 0 is in the upper left corner of the screen. func (t *Terminfo) TGoto(col, row int) string { return t.TParm(t.SetCursor, row, col) } // TColor returns a string corresponding to the given foreground and background // colors. Either fg or bg can be set to -1 to elide. func (t *Terminfo) TColor(fi, bi int) string { rv := "" // As a special case, we map bright colors to lower versions if the // color table only holds 8. For the remaining 240 colors, the user // is out of luck. Someday we could create a mapping table, but its // not worth it. if t.Colors == 8 { if fi > 7 && fi < 16 { fi -= 8 } if bi > 7 && bi < 16 { bi -= 8 } } if t.Colors > fi && fi >= 0 { rv += t.TParm(t.SetFg, fi) } if t.Colors > bi && bi >= 0 { rv += t.TParm(t.SetBg, bi) } return rv } var ( dblock sync.Mutex terminfos = make(map[string]*Terminfo) ) // AddTerminfo can be called to register a new Terminfo entry. func AddTerminfo(t *Terminfo) { dblock.Lock() terminfos[t.Name] = t for _, x := range t.Aliases { terminfos[x] = t } dblock.Unlock() } // LookupTerminfo attempts to find a definition for the named $TERM. func LookupTerminfo(name string) (*Terminfo, error) { if name == "" { // else on windows: index out of bounds // on the name[0] reference below return nil, ErrTermNotFound } addtruecolor := false add256color := false switch os.Getenv("COLORTERM") { case "truecolor", "24bit", "24-bit": addtruecolor = true } dblock.Lock() t := terminfos[name] dblock.Unlock() // If the name ends in -truecolor, then fabricate an entry // from the corresponding -256color, -color, or bare terminal. if t != nil && t.TrueColor { addtruecolor = true } else if t == nil && strings.HasSuffix(name, "-truecolor") { suffixes := []string{ "-256color", "-88color", "-color", "", } base := name[:len(name)-len("-truecolor")] for _, s := range suffixes { if t, _ = LookupTerminfo(base + s); t != nil { addtruecolor = true break } } } // If the name ends in -256color, maybe fabricate using the xterm 256 color sequences if t == nil && strings.HasSuffix(name, "-256color") { suffixes := []string{ "-88color", "-color", } base := name[:len(name)-len("-256color")] for _, s := range suffixes { if t, _ = LookupTerminfo(base + s); t != nil { add256color = true break } } } if t == nil { return nil, ErrTermNotFound } switch os.Getenv("TCELL_TRUECOLOR") { case "": case "disable": addtruecolor = false default: addtruecolor = true } // If the user has requested 24-bit color with $COLORTERM, then // amend the value (unless already present). This means we don't // need to have a value present. if addtruecolor && t.SetFgBgRGB == "" && t.SetFgRGB == "" && t.SetBgRGB == "" { // Supply vanilla ISO 8613-6:1994 24-bit color sequences. t.SetFgRGB = "\x1b[38;2;%p1%d;%p2%d;%p3%dm" t.SetBgRGB = "\x1b[48;2;%p1%d;%p2%d;%p3%dm" t.SetFgBgRGB = "\x1b[38;2;%p1%d;%p2%d;%p3%d;" + "48;2;%p4%d;%p5%d;%p6%dm" } if add256color { t.Colors = 256 t.SetFg = "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m" t.SetBg = "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m" t.SetFgBg = "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m" t.ResetFgBg = "\x1b[39;49m" } return t, nil } func TerminfoNames() []string { res := make([]string, 0, len(terminfos)) for m := range terminfos { res = append(res, m) } return res }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/f/foot/foot.go
vendor/github.com/gdamore/tcell/v2/terminfo/f/foot/foot.go
// Generated automatically. DO NOT HAND-EDIT. package foot import "github.com/gdamore/tcell/v2/terminfo" func init() { // foot terminal emulator terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "foot", Aliases: []string{"foot-extra"}, Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h\x1b[22;0;0t", ExitCA: "\x1b[?1049l\x1b[23;0;0t", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38:5:%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48:5:%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38:5:%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48:5:%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", StrikeThrough: "\x1b[9m", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/a/aixterm/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/a/aixterm/term.go
// Generated automatically. DO NOT HAND-EDIT. package aixterm import "github.com/gdamore/tcell/v2/terminfo" func init() { // IBM Aixterm Terminal Emulator terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "aixterm", Columns: 80, Lines: 25, Colors: 8, Clear: "\x1b[H\x1b[J", AttrOff: "\x1b[0;10m\x1b(B", Underline: "\x1b[4m", Bold: "\x1b[1m", Reverse: "\x1b[7m", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[32m\x1b[40m", PadChar: "\x00", AltChars: "jjkkllmmnnqqttuuvvwwxx", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/a/alacritty/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/a/alacritty/term.go
// Generated automatically. DO NOT HAND-EDIT. package alacritty import "github.com/gdamore/tcell/v2/terminfo" func init() { // alacritty terminal emulator terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "alacritty", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h\x1b[22;0;0t", ExitCA: "\x1b[?1049l\x1b[23;0;0t", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", StrikeThrough: "\x1b[9m", Mouse: "\x1b[<", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/a/alacritty/direct.go
vendor/github.com/gdamore/tcell/v2/terminfo/a/alacritty/direct.go
// Generated automatically. DO NOT HAND-EDIT. package alacritty import "github.com/gdamore/tcell/v2/terminfo" func init() { // alacritty with direct color indexing terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "alacritty-direct", Columns: 80, Lines: 24, Colors: 16777216, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h\x1b[22;0;0t", ExitCA: "\x1b[?1049l\x1b[23;0;0t", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", StrikeThrough: "\x1b[9m", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", TrueColor: true, AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/a/ansi/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/a/ansi/term.go
// Generated automatically. DO NOT HAND-EDIT. package ansi import "github.com/gdamore/tcell/v2/terminfo" func init() { // ansi/pc-term compatible with color terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "ansi", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[J", AttrOff: "\x1b[0;10m", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "+\x10,\x11-\x18.\x190\xdb`\x04a\xb1f\xf8g\xf1h\xb0j\xd9k\xbfl\xdam\xc0n\xc5o~p\xc4q\xc4r\xc4s_t\xc3u\xb4v\xc1w\xc2x\xb3y\xf3z\xf2{\xe3|\xd8}\x9c~\xfe", EnterAcs: "\x1b[11m", ExitAcs: "\x1b[10m", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/r/rxvt/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/r/rxvt/term.go
// Generated automatically. DO NOT HAND-EDIT. package rxvt import "github.com/gdamore/tcell/v2/terminfo" func init() { // rxvt terminal emulator (X Window System) terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "rxvt", Aliases: []string{"rxvt-color"}, Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b=", ExitKeypad: "\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // rxvt 2.7.9 with xterm 256-colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "rxvt-256color", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b=", ExitKeypad: "\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // rxvt 2.7.9 with xterm 88-colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "rxvt-88color", Columns: 80, Lines: 24, Colors: 88, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b=", ExitKeypad: "\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // rxvt-unicode terminal (X Window System) terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "rxvt-unicode", Columns: 80, Lines: 24, Colors: 88, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[r\x1b[?1049l", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x1b(B", Underline: "\x1b[4m", Bold: "\x1b[1m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b=", ExitKeypad: "\x1b>", SetFg: "\x1b[38;5;%p1%dm", SetBg: "\x1b[48;5;%p1%dm", SetFgBg: "\x1b[38;5;%p1%d;48;5;%p2%dm", ResetFgBg: "\x1b[39;49m", AltChars: "+C,D-A.B0E``aaffgghFiGjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, InsertChar: "\x1b[@", }) // rxvt-unicode terminal with 256 colors (X Window System) terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "rxvt-unicode-256color", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[r\x1b[?1049l", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x1b(B", Underline: "\x1b[4m", Bold: "\x1b[1m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b=", ExitKeypad: "\x1b>", SetFg: "\x1b[38;5;%p1%dm", SetBg: "\x1b[48;5;%p1%dm", SetFgBg: "\x1b[38;5;%p1%d;48;5;%p2%dm", ResetFgBg: "\x1b[39;49m", AltChars: "+C,D-A.B0E``aaffgghFiGjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, InsertChar: "\x1b[@", }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/x/xterm/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/x/xterm/term.go
// Generated automatically. DO NOT HAND-EDIT. package xterm import "github.com/gdamore/tcell/v2/terminfo" func init() { // xterm terminal emulator (X Window System) terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "xterm", Aliases: []string{"xterm-debian"}, Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h\x1b[22;0;0t", ExitCA: "\x1b[?1049l\x1b[23;0;0t", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", StrikeThrough: "\x1b[9m", Mouse: "\x1b[<", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // xterm with 88 colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "xterm-88color", Columns: 80, Lines: 24, Colors: 88, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h\x1b[22;0;0t", ExitCA: "\x1b[?1049l\x1b[23;0;0t", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", StrikeThrough: "\x1b[9m", Mouse: "\x1b[<", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // xterm with 256 colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "xterm-256color", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h\x1b[22;0;0t", ExitCA: "\x1b[?1049l\x1b[23;0;0t", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", StrikeThrough: "\x1b[9m", Mouse: "\x1b[<", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/x/xterm/direct.go
vendor/github.com/gdamore/tcell/v2/terminfo/x/xterm/direct.go
// Copyright 2021 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This terminal definition is derived from the xterm-256color definition, but // makes use of the RGB property these terminals have to support direct color. // The terminfo entry for this uses a new format for the color handling introduced // by ncurses 6.1 (and used by nobody else), so this override ensures we get // good handling even in the face of this. package xterm import "github.com/gdamore/tcell/v2/terminfo" func init() { // derived from xterm-256color, but adds full RGB support terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "xterm-direct", Aliases: []string{"xterm-truecolor"}, Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h\x1b[22;0;0t", ExitCA: "\x1b[?1049l\x1b[23;0;0t", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", SetFgRGB: "\x1b[38;2;%p1%d;%p2%d;%p3%dm", SetBgRGB: "\x1b[48;2;%p1%d;%p2%d;%p3%dm", SetFgBgRGB: "\x1b[38;2;%p1%d;%p2%d;%p3%d;48;2;%p4%d;%p5%d;%p6%dm", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", StrikeThrough: "\x1b[9m", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, TrueColor: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/x/xterm_kitty/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/x/xterm_kitty/term.go
// Generated automatically. DO NOT HAND-EDIT. package xterm_kitty import "github.com/gdamore/tcell/v2/terminfo" func init() { // KovIdTTY terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "xterm-kitty", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[?1049l", ShowCursor: "\x1b[?12h\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h", ExitKeypad: "\x1b[?1l", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "++,,--..00``aaffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", StrikeThrough: "\x1b[9m", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", TrueColor: true, AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/x/xterm_ghostty/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/x/xterm_ghostty/term.go
// Generated automatically. DO NOT HAND-EDIT. package xterm_ghostty import "github.com/gdamore/tcell/v2/terminfo" func init() { // Ghostty terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "xterm-ghostty", Aliases: []string{"ghostty"}, Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[?1049l", ShowCursor: "\x1b[?12l\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b(B\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "++,,--..00``aaffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", StrikeThrough: "\x1b[9m", Mouse: "\x1b[<", SetCursor: "\x1b[%i%p1%d;%p2%dH", TrueColor: true, AutoMargin: true, InsertChar: "\x1b[@", XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/x/xfce/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/x/xfce/term.go
// Generated automatically. DO NOT HAND-EDIT. package xfce import "github.com/gdamore/tcell/v2/terminfo" func init() { // Xfce Terminal terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "xfce", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[0m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/base/base.go
vendor/github.com/gdamore/tcell/v2/terminfo/base/base.go
// Copyright 2020 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This is just a "minimalist" set of the base terminal descriptions. // It should be sufficient for most applications. // Package base contains the base terminal descriptions that are likely // to be needed by any stock application. It is imported by default in the // terminfo package, so terminal types listed here will be available to any // tcell application. package base import ( // The following imports just register themselves -- // these are the terminal types we aggregate in this package. _ "github.com/gdamore/tcell/v2/terminfo/a/ansi" _ "github.com/gdamore/tcell/v2/terminfo/t/tmux" _ "github.com/gdamore/tcell/v2/terminfo/v/vt100" _ "github.com/gdamore/tcell/v2/terminfo/v/vt102" _ "github.com/gdamore/tcell/v2/terminfo/v/vt220" _ "github.com/gdamore/tcell/v2/terminfo/x/xterm" )
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/s/screen/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/s/screen/term.go
// Generated automatically. DO NOT HAND-EDIT. package screen import "github.com/gdamore/tcell/v2/terminfo" func init() { // VT 100/ANSI X3.64 virtual terminal terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "screen", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[?1049l", ShowCursor: "\x1b[34h\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "++,,--..00``aaffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) // GNU Screen with 256 colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "screen-256color", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[?1049l", ShowCursor: "\x1b[34h\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "++,,--..00``aaffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/s/simpleterm/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/s/simpleterm/term.go
// Generated automatically. DO NOT HAND-EDIT. package simpleterm import "github.com/gdamore/tcell/v2/terminfo" func init() { // aka simpleterm terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "st", Aliases: []string{"stterm"}, Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[?1049l", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[0m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", AltChars: "+C,D-A.B0E``aaffgghFiGjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAcs: "\x1b)0", StrikeThrough: "\x1b[9m", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // simpleterm with 256 colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "st-256color", Aliases: []string{"stterm-256color"}, Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[?1049l", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[0m", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "+C,D-A.B0E``aaffgghFiGjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAcs: "\x1b)0", StrikeThrough: "\x1b[9m", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/s/sun/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/s/sun/term.go
// Copyright 2021 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This terminal definition is hand-coded, as the default terminfo for // this terminal is busted with respect to color. Unlike pretty much every // other ANSI compliant terminal, this terminal cannot combine foreground and // background escapes. The default terminfo also only provides escapes for // 16-bit color. package sun import "github.com/gdamore/tcell/v2/terminfo" func init() { // Sun Microsystems Inc. workstation console terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "sun", Aliases: []string{"sun1", "sun2"}, Columns: 80, Lines: 34, Clear: "\f", AttrOff: "\x1b[m", Reverse: "\x1b[7m", PadChar: "\x00", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, InsertChar: "\x1b[@", }) // Sun Microsystems Workstation console with color support (IA systems) terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "sun-color", Columns: 80, Lines: 34, Colors: 256, Clear: "\f", AttrOff: "\x1b[m", Bold: "\x1b[1m", Reverse: "\x1b[7m", SetFg: "\x1b[38;5;%p1%dm", SetBg: "\x1b[48;5;%p1%dm", ResetFgBg: "\x1b[0m", PadChar: "\x00", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, InsertChar: "\x1b[@", }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/g/gnome/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/g/gnome/term.go
// Generated automatically. DO NOT HAND-EDIT. package gnome import "github.com/gdamore/tcell/v2/terminfo" func init() { // GNOME Terminal terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "gnome", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[0m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // GNOME Terminal with xterm 256-colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "gnome-256color", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[0m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/dynamic/dynamic.go
vendor/github.com/gdamore/tcell/v2/terminfo/dynamic/dynamic.go
// Copyright 2021 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // The dynamic package is used to generate a terminal description dynamically, // using infocmp. This is really a method of last resort, as the performance // will be slow, and it requires a working infocmp. But, the hope is that it // will assist folks who have to deal with a terminal description that isn't // already built in. This requires infocmp to be in the user's path, and to // support reasonably the -1 option. package dynamic import ( "bytes" "errors" "fmt" "os/exec" "regexp" "strconv" "strings" "github.com/gdamore/tcell/v2/terminfo" ) type termcap struct { name string desc string aliases []string bools map[string]bool nums map[string]int strs map[string]string } func (tc *termcap) getnum(s string) int { return (tc.nums[s]) } func (tc *termcap) getflag(s string) bool { return (tc.bools[s]) } func (tc *termcap) getstr(s string) string { return (tc.strs[s]) } const ( none = iota control escaped ) var errNotAddressable = errors.New("terminal not cursor addressable") func unescape(s string) string { // Various escapes are in \x format. Control codes are // encoded as ^M (carat followed by ASCII equivalent). // escapes are: \e, \E - escape // \0 NULL, \n \l \r \t \b \f \s for equivalent C escape. buf := &bytes.Buffer{} esc := none for i := 0; i < len(s); i++ { c := s[i] switch esc { case none: switch c { case '\\': esc = escaped case '^': esc = control default: buf.WriteByte(c) } case control: buf.WriteByte(c ^ 1<<6) esc = none case escaped: switch c { case 'E', 'e': buf.WriteByte(0x1b) case '0', '1', '2', '3', '4', '5', '6', '7': if i+2 < len(s) && s[i+1] >= '0' && s[i+1] <= '7' && s[i+2] >= '0' && s[i+2] <= '7' { buf.WriteByte(((c - '0') * 64) + ((s[i+1] - '0') * 8) + (s[i+2] - '0')) i = i + 2 } else if c == '0' { buf.WriteByte(0) } case 'n': buf.WriteByte('\n') case 'r': buf.WriteByte('\r') case 't': buf.WriteByte('\t') case 'b': buf.WriteByte('\b') case 'f': buf.WriteByte('\f') case 's': buf.WriteByte(' ') default: buf.WriteByte(c) } esc = none } } return (buf.String()) } func (tc *termcap) setupterm(name string) error { cmd := exec.Command("infocmp", "-1", name) output := &bytes.Buffer{} cmd.Stdout = output tc.strs = make(map[string]string) tc.bools = make(map[string]bool) tc.nums = make(map[string]int) if err := cmd.Run(); err != nil { return fmt.Errorf("couldn't open terminfo ($TERM) file for %s: %w", name, err) } // Now parse the output. // We get comment lines (starting with "#"), followed by // a header line that looks like "<name>|<alias>|...|<desc>" // then capabilities, one per line, starting with a tab and ending // with a comma and newline. lines := strings.Split(output.String(), "\n") for len(lines) > 0 && strings.HasPrefix(lines[0], "#") { lines = lines[1:] } // Ditch trailing empty last line if lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } header := lines[0] header = strings.TrimSuffix(header, ",") names := strings.Split(header, "|") tc.name = names[0] names = names[1:] if len(names) > 0 { tc.desc = names[len(names)-1] names = names[:len(names)-1] } tc.aliases = names for _, val := range lines[1:] { if (!strings.HasPrefix(val, "\t")) || (!strings.HasSuffix(val, ",")) { return (errors.New("malformed infocmp: " + val)) } val = val[1:] val = val[:len(val)-1] if k := strings.SplitN(val, "=", 2); len(k) == 2 { tc.strs[k[0]] = unescape(k[1]) } else if k := strings.SplitN(val, "#", 2); len(k) == 2 { u, err := strconv.ParseUint(k[1], 0, 0) if err != nil { return (err) } tc.nums[k[0]] = int(u) } else { tc.bools[val] = true } } return nil } // LoadTerminfo creates a Terminfo by for named terminal by attempting to parse // the output from infocmp. This returns the terminfo entry, a description of // the terminal, and either nil or an error. func LoadTerminfo(name string) (*terminfo.Terminfo, string, error) { var tc termcap if err := tc.setupterm(name); err != nil { return nil, "", err } t := &terminfo.Terminfo{} t.Name = tc.name t.Aliases = tc.aliases t.Colors = tc.getnum("colors") t.Columns = tc.getnum("cols") t.Lines = tc.getnum("lines") t.Clear = tc.getstr("clear") t.EnterCA = tc.getstr("smcup") t.ExitCA = tc.getstr("rmcup") t.ShowCursor = tc.getstr("cnorm") t.HideCursor = tc.getstr("civis") t.AttrOff = tc.getstr("sgr0") t.Underline = tc.getstr("smul") t.Bold = tc.getstr("bold") t.Blink = tc.getstr("blink") t.Dim = tc.getstr("dim") t.Italic = tc.getstr("sitm") t.Reverse = tc.getstr("rev") t.EnterKeypad = tc.getstr("smkx") t.ExitKeypad = tc.getstr("rmkx") t.SetFg = tc.getstr("setaf") t.SetBg = tc.getstr("setab") t.SetCursor = tc.getstr("cup") t.AltChars = tc.getstr("acsc") t.EnterAcs = tc.getstr("smacs") t.ExitAcs = tc.getstr("rmacs") t.EnableAcs = tc.getstr("enacs") t.Mouse = tc.getstr("kmous") // Technically the RGB flag that is provided for xterm-direct is not // quite right. The problem is that the -direct flag that was introduced // with ncurses 6.1 requires a parsing for the parameters that we lack. // For this case we'll just assume it's XTerm compatible. Someday this // may be incorrect, but right now it is correct, and nobody uses it // anyway. if tc.getflag("Tc") { // This presumes XTerm 24-bit true color. t.TrueColor = true } else if tc.getflag("RGB") { // This is for xterm-direct, which uses a different scheme entirely. // (ncurses went a very different direction from everyone else, and // so it's unlikely anything is using this definition.) t.TrueColor = true t.SetBg = "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m" t.SetFg = "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m" } // We only support colors in ANSI 8 or 256 color mode. if t.Colors < 8 || t.SetFg == "" { t.Colors = 0 } if t.SetCursor == "" { return nil, "", errNotAddressable } // For padding, we lookup the pad char. If that isn't present, // and npc is *not* set, then we assume a null byte. t.PadChar = tc.getstr("pad") if t.PadChar == "" { if !tc.getflag("npc") { t.PadChar = "\u0000" } } // For terminals that use "standard" SGR sequences, lets combine the // foreground and background together. if strings.HasPrefix(t.SetFg, "\x1b[") && strings.HasPrefix(t.SetBg, "\x1b[") && strings.HasSuffix(t.SetFg, "m") && strings.HasSuffix(t.SetBg, "m") { fg := t.SetFg[:len(t.SetFg)-1] r := regexp.MustCompile("%p1") bg := r.ReplaceAllString(t.SetBg[2:], "%p2") t.SetFgBg = fg + ";" + bg } return t, tc.desc, nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/l/linux/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/l/linux/term.go
// Generated automatically. DO NOT HAND-EDIT. package linux import "github.com/gdamore/tcell/v2/terminfo" func init() { // Linux console terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "linux", Colors: 8, Clear: "\x1b[H\x1b[J", ShowCursor: "\x1b[?25h\x1b[?0c", HideCursor: "\x1b[?25l\x1b[?1c", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Blink: "\x1b[5m", Reverse: "\x1b[7m", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "++,,--..00``aaffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, InsertChar: "\x1b[@", }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/p/pcansi/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/p/pcansi/term.go
// Generated automatically. DO NOT HAND-EDIT. package pcansi import "github.com/gdamore/tcell/v2/terminfo" func init() { // ibm-pc terminal programs claiming to be ANSI terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "pcansi", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[J", AttrOff: "\x1b[0;10m", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[37;40m", PadChar: "\x00", AltChars: "+\x10,\x11-\x18.\x190\xdb`\x04a\xb1f\xf8g\xf1h\xb0j\xd9k\xbfl\xdam\xc0n\xc5o~p\xc4q\xc4r\xc4s_t\xc3u\xb4v\xc1w\xc2x\xb3y\xf3z\xf2{\xe3|\xd8}\x9c~\xfe", EnterAcs: "\x1b[12m", ExitAcs: "\x1b[10m", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/v/vt102/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/v/vt102/term.go
// Generated automatically. DO NOT HAND-EDIT. package vt102 import "github.com/gdamore/tcell/v2/terminfo" func init() { // DEC VT102 terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "vt102", Columns: 80, Lines: 24, Clear: "\x1b[H\x1b[J$<50>", AttrOff: "\x1b[m\x0f$<2>", Underline: "\x1b[4m$<2>", Bold: "\x1b[1m$<2>", Blink: "\x1b[5m$<2>", Reverse: "\x1b[7m$<2>", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", SetCursor: "\x1b[%i%p1%d;%p2%dH$<5>", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/v/vt220/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/v/vt220/term.go
// Generated automatically. DO NOT HAND-EDIT. package vt220 import "github.com/gdamore/tcell/v2/terminfo" func init() { // DEC VT220 terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "vt220", Aliases: []string{"vt200"}, Columns: 80, Lines: 24, Clear: "\x1b[H\x1b[J", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x1b(B", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0$<2>", ExitAcs: "\x1b(B$<4>", EnableAcs: "\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/v/vt420/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/v/vt420/term.go
// This file was originally generated automatically, // but it is edited to correct for errors in the VT420 // terminfo data. Additionally we have added extended // information for the extended F-keys. package vt420 import "github.com/gdamore/tcell/v2/terminfo" func init() { // DEC VT420 terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "vt420", Columns: 80, Lines: 24, Clear: "\x1b[H\x1b[2J$<50>", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x1b(B$<2>", Underline: "\x1b[4m", Bold: "\x1b[1m$<2>", Blink: "\x1b[5m$<2>", Reverse: "\x1b[7m$<2>", EnterKeypad: "\x1b=", ExitKeypad: "\x1b>", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0$<2>", ExitAcs: "\x1b(B$<4>", EnableAcs: "\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", SetCursor: "\x1b[%i%p1%d;%p2%dH$<10>", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/v/vt100/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/v/vt100/term.go
// Generated automatically. DO NOT HAND-EDIT. package vt100 import "github.com/gdamore/tcell/v2/terminfo" func init() { // DEC VT100 (w/advanced video) terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "vt100", Aliases: []string{"vt100-am"}, Columns: 80, Lines: 24, Clear: "\x1b[H\x1b[J$<50>", AttrOff: "\x1b[m\x0f$<2>", Underline: "\x1b[4m$<2>", Bold: "\x1b[1m$<2>", Blink: "\x1b[5m$<2>", Reverse: "\x1b[7m$<2>", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", SetCursor: "\x1b[%i%p1%d;%p2%dH$<5>", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/v/vt320/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/v/vt320/term.go
// Generated automatically. DO NOT HAND-EDIT. package vt320 import "github.com/gdamore/tcell/v2/terminfo" func init() { // DEC VT320 7 bit terminal terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "vt320", Aliases: []string{"vt300"}, Columns: 80, Lines: 24, Clear: "\x1b[H\x1b[2J", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x1b(B", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/v/vt400/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/v/vt400/term.go
// Generated automatically. DO NOT HAND-EDIT. package vt400 import "github.com/gdamore/tcell/v2/terminfo" func init() { // DEC VT400 24x80 column autowrap terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "vt400", Aliases: []string{"vt400-24", "dec-vt400"}, Columns: 80, Lines: 24, Clear: "\x1b[H\x1b[J$<10/>", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x1b(B", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, InsertChar: "\x1b[@", }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/k/konsole/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/k/konsole/term.go
// Generated automatically. DO NOT HAND-EDIT. package konsole import "github.com/gdamore/tcell/v2/terminfo" func init() { // KDE console window terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "konsole", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[0m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", StrikeThrough: "\x1b[9m", Mouse: "\x1b[<", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // KDE console window with xterm 256-colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "konsole-256color", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[0m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", StrikeThrough: "\x1b[9m", Mouse: "\x1b[<", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/k/kterm/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/k/kterm/term.go
// Generated automatically. DO NOT HAND-EDIT. package kterm import "github.com/gdamore/tcell/v2/terminfo" func init() { // kterm kanji terminal emulator (X window system) terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "kterm", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[2J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", AttrOff: "\x1b[m\x1b(B", Underline: "\x1b[4m", Bold: "\x1b[1m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "``aajjkkllmmnnooppqqrrssttuuvvwwxx~~", EnterAcs: "\x1b(0", ExitAcs: "\x1b(B", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/d/dtterm/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/d/dtterm/term.go
// Generated automatically. DO NOT HAND-EDIT. package dtterm import "github.com/gdamore/tcell/v2/terminfo" func init() { // CDE desktop terminal terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "dtterm", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[J", ShowCursor: "\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Blink: "\x1b[5m", Reverse: "\x1b[7m", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", EnableAutoMargin: "\x1b[?7h", DisableAutoMargin: "\x1b[?7l", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/extended/extended.go
vendor/github.com/gdamore/tcell/v2/terminfo/extended/extended.go
// Copyright 2024 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package extended contains an extended set of terminal descriptions. // Applications desiring to have a better chance of Just Working by // default should include this package. This will significantly increase // the size of the program. package extended import ( // The following imports just register themselves -- // these are the terminal types we aggregate in this package. _ "github.com/gdamore/tcell/v2/terminfo/a/aixterm" _ "github.com/gdamore/tcell/v2/terminfo/a/alacritty" _ "github.com/gdamore/tcell/v2/terminfo/a/ansi" _ "github.com/gdamore/tcell/v2/terminfo/c/cygwin" _ "github.com/gdamore/tcell/v2/terminfo/d/dtterm" _ "github.com/gdamore/tcell/v2/terminfo/e/emacs" _ "github.com/gdamore/tcell/v2/terminfo/f/foot" _ "github.com/gdamore/tcell/v2/terminfo/g/gnome" _ "github.com/gdamore/tcell/v2/terminfo/k/konsole" _ "github.com/gdamore/tcell/v2/terminfo/k/kterm" _ "github.com/gdamore/tcell/v2/terminfo/l/linux" _ "github.com/gdamore/tcell/v2/terminfo/p/pcansi" _ "github.com/gdamore/tcell/v2/terminfo/r/rxvt" _ "github.com/gdamore/tcell/v2/terminfo/s/screen" _ "github.com/gdamore/tcell/v2/terminfo/s/simpleterm" _ "github.com/gdamore/tcell/v2/terminfo/s/sun" _ "github.com/gdamore/tcell/v2/terminfo/t/tmux" _ "github.com/gdamore/tcell/v2/terminfo/v/vt100" _ "github.com/gdamore/tcell/v2/terminfo/v/vt102" _ "github.com/gdamore/tcell/v2/terminfo/v/vt220" _ "github.com/gdamore/tcell/v2/terminfo/v/vt320" _ "github.com/gdamore/tcell/v2/terminfo/v/vt400" _ "github.com/gdamore/tcell/v2/terminfo/v/vt420" _ "github.com/gdamore/tcell/v2/terminfo/x/xfce" _ "github.com/gdamore/tcell/v2/terminfo/x/xterm" _ "github.com/gdamore/tcell/v2/terminfo/x/xterm_ghostty" _ "github.com/gdamore/tcell/v2/terminfo/x/xterm_kitty" )
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/t/tmux/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/t/tmux/term.go
// Generated automatically. DO NOT HAND-EDIT. package tmux import "github.com/gdamore/tcell/v2/terminfo" func init() { // tmux terminal multiplexer terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "tmux", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[?1049l", ShowCursor: "\x1b[34h\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "++,,--..00``aaffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", StrikeThrough: "\x1b[9m", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) // tmux with 256 colors terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "tmux-256color", Columns: 80, Lines: 24, Colors: 256, Clear: "\x1b[H\x1b[J", EnterCA: "\x1b[?1049h", ExitCA: "\x1b[?1049l", ShowCursor: "\x1b[34h\x1b[?25h", HideCursor: "\x1b[?25l", AttrOff: "\x1b[m\x0f", Underline: "\x1b[4m", Bold: "\x1b[1m", Dim: "\x1b[2m", Italic: "\x1b[3m", Blink: "\x1b[5m", Reverse: "\x1b[7m", EnterKeypad: "\x1b[?1h\x1b=", ExitKeypad: "\x1b[?1l\x1b>", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", SetFgBg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;;%?%p2%{8}%<%t4%p2%d%e%p2%{16}%<%t10%p2%{8}%-%d%e48;5;%p2%d%;m", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "++,,--..00``aaffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", EnterAcs: "\x0e", ExitAcs: "\x0f", EnableAcs: "\x1b(B\x1b)0", StrikeThrough: "\x1b[9m", Mouse: "\x1b[M", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, XTermLike: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/c/cygwin/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/c/cygwin/term.go
// Generated automatically. DO NOT HAND-EDIT. package cygwin import "github.com/gdamore/tcell/v2/terminfo" func init() { // ANSI emulation for Cygwin terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "cygwin", Colors: 8, Clear: "\x1b[H\x1b[J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", AttrOff: "\x1b[0;10m", Underline: "\x1b[4m", Bold: "\x1b[1m", Reverse: "\x1b[7m", SetFg: "\x1b[3%p1%dm", SetBg: "\x1b[4%p1%dm", SetFgBg: "\x1b[3%p1%d;4%p2%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", AltChars: "+\x10,\x11-\x18.\x190\xdb`\x04a\xb1f\xf8g\xf1h\xb0j\xd9k\xbfl\xdam\xc0n\xc5o~p\xc4q\xc4r\xc4s_t\xc3u\xb4v\xc1w\xc2x\xb3y\xf3z\xf2{\xe3|\xd8}\x9c~\xfe", EnterAcs: "\x1b[11m", ExitAcs: "\x1b[10m", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, InsertChar: "\x1b[@", }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/gdamore/tcell/v2/terminfo/e/emacs/term.go
vendor/github.com/gdamore/tcell/v2/terminfo/e/emacs/term.go
// Generated automatically. DO NOT HAND-EDIT. package emacs import "github.com/gdamore/tcell/v2/terminfo" func init() { // GNU Emacs term.el terminal emulation terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "eterm", Columns: 80, Lines: 24, Clear: "\x1b[H\x1b[J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", AttrOff: "\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Reverse: "\x1b[7m", PadChar: "\x00", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) // Emacs term.el terminal emulator term-protocol-version 0.96 terminfo.AddTerminfo(&terminfo.Terminfo{ Name: "eterm-color", Columns: 80, Lines: 24, Colors: 8, Clear: "\x1b[H\x1b[J", EnterCA: "\x1b7\x1b[?47h", ExitCA: "\x1b[2J\x1b[?47l\x1b8", AttrOff: "\x1b[m", Underline: "\x1b[4m", Bold: "\x1b[1m", Blink: "\x1b[5m", Reverse: "\x1b[7m", SetFg: "\x1b[%p1%{30}%+%dm", SetBg: "\x1b[%p1%'('%+%dm", SetFgBg: "\x1b[%p1%{30}%+%d;%p2%'('%+%dm", ResetFgBg: "\x1b[39;49m", PadChar: "\x00", SetCursor: "\x1b[%i%p1%d;%p2%dH", AutoMargin: true, }) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/sanity-io/litter/print.go
vendor/github.com/sanity-io/litter/print.go
package litter import ( "io" "math" "strconv" ) func printBool(w io.Writer, value bool) { if value { w.Write([]byte("true")) return } w.Write([]byte("false")) } func printInt(w io.Writer, val int64, base int) { w.Write([]byte(strconv.FormatInt(val, base))) } func printUint(w io.Writer, val uint64, base int) { w.Write([]byte(strconv.FormatUint(val, base))) } func printFloat(w io.Writer, val float64, precision int) { if math.Trunc(val) == val { // Ensure that floats like 1.0 are always printed with a decimal point w.Write([]byte(strconv.FormatFloat(val, 'f', 1, precision))) } else { w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) } } func printComplex(w io.Writer, c complex128, floatPrecision int) { w.Write([]byte("complex")) printInt(w, int64(floatPrecision*2), 10) r := real(c) w.Write([]byte("(")) w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) i := imag(c) if i >= 0 { w.Write([]byte("+")) } w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) w.Write([]byte("i)")) } func printNil(w io.Writer) { w.Write([]byte("nil")) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/sanity-io/litter/pointers.go
vendor/github.com/sanity-io/litter/pointers.go
package litter import ( "fmt" "reflect" "sort" ) // mapReusedPointers takes a structure, and recursively maps all pointers mentioned in the tree, // detecting circular references, and providing a list of all pointers that was referenced at // least twice by the provided structure. func mapReusedPointers(v reflect.Value) ptrmap { pm := &pointerVisitor{} pm.consider(v) return pm.reused } // A map of pointers. type ptrinfo struct { id int parent *ptrmap } func (p *ptrinfo) label() string { if p.id == -1 { p.id = p.parent.count p.parent.count++ } return fmt.Sprintf("p%d", p.id) } type ptrkey struct { p uintptr t reflect.Type } func ptrkeyFor(v reflect.Value) (k ptrkey) { k.p = v.Pointer() for v.Kind() == reflect.Ptr { v = v.Elem() } if v.IsValid() { k.t = v.Type() } return } type ptrmap struct { m map[ptrkey]*ptrinfo count int } // Returns true if contains a pointer. func (pm *ptrmap) contains(v reflect.Value) bool { if pm.m != nil { _, ok := pm.m[ptrkeyFor(v)] return ok } return false } // Gets a pointer. func (pm *ptrmap) get(v reflect.Value) (*ptrinfo, bool) { if pm.m != nil { p, ok := pm.m[ptrkeyFor(v)] return p, ok } return nil, false } // Removes a pointer. func (pm *ptrmap) remove(v reflect.Value) { if pm.m != nil { delete(pm.m, ptrkeyFor(v)) } } // Adds a pointer. func (pm *ptrmap) add(p reflect.Value) bool { if pm.contains(p) { return false } pm.put(p) return true } // Adds a pointer (slow path). func (pm *ptrmap) put(v reflect.Value) { if pm.m == nil { pm.m = make(map[ptrkey]*ptrinfo, 31) } key := ptrkeyFor(v) if _, ok := pm.m[key]; !ok { pm.m[key] = &ptrinfo{id: -1, parent: pm} } } type pointerVisitor struct { pointers ptrmap reused ptrmap } // Recursively consider v and each of its children, updating the map according to the // semantics of MapReusedPointers func (pv *pointerVisitor) consider(v reflect.Value) { if v.Kind() == reflect.Invalid { return } if isPointerValue(v) { // pointer is 0 for unexported fields if pv.tryAddPointer(v) { // No use descending inside this value, since it have been seen before and all its descendants // have been considered return } } // Now descend into any children of this value switch v.Kind() { case reflect.Slice, reflect.Array: numEntries := v.Len() for i := 0; i < numEntries; i++ { pv.consider(v.Index(i)) } case reflect.Interface: pv.consider(v.Elem()) case reflect.Ptr: pv.consider(v.Elem()) case reflect.Map: keys := v.MapKeys() sort.Sort(mapKeySorter{ keys: keys, options: &Config, }) for _, key := range keys { pv.consider(v.MapIndex(key)) } case reflect.Struct: numFields := v.NumField() for i := 0; i < numFields; i++ { pv.consider(v.Field(i)) } } } // addPointer to the pointerMap, update reusedPointers. Returns true if pointer was reused func (pv *pointerVisitor) tryAddPointer(v reflect.Value) bool { // Is this allready known to be reused? if pv.reused.contains(v) { return true } // Have we seen it once before? if pv.pointers.contains(v) { // Add it to the register of pointers we have seen more than once pv.reused.add(v) return true } // This pointer was new to us pv.pointers.add(v) return false }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/sanity-io/litter/util.go
vendor/github.com/sanity-io/litter/util.go
package litter import ( "reflect" ) // deInterface returns values inside of non-nil interfaces when possible. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func deInterface(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } return v } func isPointerValue(v reflect.Value) bool { switch v.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: return true } return false } func isZeroValue(v reflect.Value) bool { return (isPointerValue(v) && v.IsNil()) || (v.IsValid() && v.CanInterface() && reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/sanity-io/litter/dump.go
vendor/github.com/sanity-io/litter/dump.go
package litter import ( "bytes" "fmt" "io" "os" "reflect" "regexp" "runtime" "sort" "strconv" "strings" ) var ( packageNameStripperRegexp = regexp.MustCompile(`\b[a-zA-Z_]+[a-zA-Z_0-9]+\.`) compactTypeRegexp = regexp.MustCompile(`\s*([,;{}()])\s*`) ) // Dumper is the interface for implementing custom dumper for your types. type Dumper interface { LitterDump(w io.Writer) } // Options represents configuration options for litter type Options struct { Compact bool StripPackageNames bool HidePrivateFields bool HideZeroValues bool FieldExclusions *regexp.Regexp FieldFilter func(reflect.StructField, reflect.Value) bool HomePackage string Separator string StrictGo bool DumpFunc func(reflect.Value, io.Writer) bool // DisablePointerReplacement, if true, disables the replacing of pointer data with variable names // when it's safe. This is useful for diffing two structures, where pointer variables would cause // false changes. However, circular graphs are still detected and elided to avoid infinite output. DisablePointerReplacement bool } // Config is the default config used when calling Dump var Config = Options{ StripPackageNames: false, HidePrivateFields: true, FieldExclusions: regexp.MustCompile(`^(XXX_.*)$`), // XXX_ is a prefix of fields generated by protoc-gen-go Separator: " ", } type dumpState struct { w io.Writer depth int config *Options pointers ptrmap visitedPointers ptrmap parentPointers ptrmap currentPointer *ptrinfo homePackageRegexp *regexp.Regexp } func (s *dumpState) write(b []byte) { if _, err := s.w.Write(b); err != nil { panic(err) } } func (s *dumpState) writeString(str string) { s.write([]byte(str)) } func (s *dumpState) indent() { if !s.config.Compact { s.write(bytes.Repeat([]byte(" "), s.depth)) } } func (s *dumpState) newlineWithPointerNameComment() { if ptr := s.currentPointer; ptr != nil { if s.config.Compact { s.write([]byte(fmt.Sprintf("/*%s*/", ptr.label()))) } else { s.write([]byte(fmt.Sprintf(" // %s\n", ptr.label()))) } s.currentPointer = nil return } if !s.config.Compact { s.write([]byte("\n")) } } func (s *dumpState) dumpType(v reflect.Value) { typeName := v.Type().String() if s.config.StripPackageNames { typeName = packageNameStripperRegexp.ReplaceAllLiteralString(typeName, "") } else if s.homePackageRegexp != nil { typeName = s.homePackageRegexp.ReplaceAllLiteralString(typeName, "") } if s.config.Compact { typeName = compactTypeRegexp.ReplaceAllString(typeName, "$1") } s.write([]byte(typeName)) } func (s *dumpState) dumpSlice(v reflect.Value) { s.dumpType(v) numEntries := v.Len() if numEntries == 0 { s.write([]byte("{}")) return } s.write([]byte("{")) s.newlineWithPointerNameComment() s.depth++ for i := 0; i < numEntries; i++ { s.indent() s.dumpVal(v.Index(i)) if !s.config.Compact || i < numEntries-1 { s.write([]byte(",")) } s.newlineWithPointerNameComment() } s.depth-- s.indent() s.write([]byte("}")) } func (s *dumpState) dumpStruct(v reflect.Value) { dumpPreamble := func() { s.dumpType(v) s.write([]byte("{")) s.newlineWithPointerNameComment() s.depth++ } preambleDumped := false vt := v.Type() numFields := v.NumField() for i := 0; i < numFields; i++ { vtf := vt.Field(i) if s.config.HidePrivateFields && vtf.PkgPath != "" || s.config.FieldExclusions != nil && s.config.FieldExclusions.MatchString(vtf.Name) { continue } if s.config.FieldFilter != nil && !s.config.FieldFilter(vtf, v.Field(i)) { continue } if s.config.HideZeroValues && isZeroValue(v.Field(i)) { continue } if !preambleDumped { dumpPreamble() preambleDumped = true } s.indent() s.write([]byte(vtf.Name)) if s.config.Compact { s.write([]byte(":")) } else { s.write([]byte(": ")) } s.dumpVal(v.Field(i)) if !s.config.Compact || i < numFields-1 { s.write([]byte(",")) } s.newlineWithPointerNameComment() } if preambleDumped { s.depth-- s.indent() s.write([]byte("}")) } else { // There were no fields dumped s.dumpType(v) s.write([]byte("{}")) } } func (s *dumpState) dumpMap(v reflect.Value) { if v.IsNil() { s.dumpType(v) s.writeString("(nil)") return } s.dumpType(v) keys := v.MapKeys() if len(keys) == 0 { s.write([]byte("{}")) return } s.write([]byte("{")) s.newlineWithPointerNameComment() s.depth++ sort.Sort(mapKeySorter{ keys: keys, options: s.config, }) numKeys := len(keys) for i, key := range keys { s.indent() s.dumpVal(key) if s.config.Compact { s.write([]byte(":")) } else { s.write([]byte(": ")) } s.dumpVal(v.MapIndex(key)) if !s.config.Compact || i < numKeys-1 { s.write([]byte(",")) } s.newlineWithPointerNameComment() } s.depth-- s.indent() s.write([]byte("}")) } func (s *dumpState) dumpFunc(v reflect.Value) { parts := strings.Split(runtime.FuncForPC(v.Pointer()).Name(), "/") name := parts[len(parts)-1] // Anonymous function if strings.Count(name, ".") > 1 { s.dumpType(v) } else { if s.config.StripPackageNames { name = packageNameStripperRegexp.ReplaceAllLiteralString(name, "") } else if s.homePackageRegexp != nil { name = s.homePackageRegexp.ReplaceAllLiteralString(name, "") } if s.config.Compact { name = compactTypeRegexp.ReplaceAllString(name, "$1") } s.write([]byte(name)) } } func (s *dumpState) dumpChan(v reflect.Value) { vType := v.Type() res := []byte(vType.String()) s.write(res) } func (s *dumpState) dumpCustom(v reflect.Value, buf *bytes.Buffer) { // Dump the type s.dumpType(v) if s.config.Compact { s.write(buf.Bytes()) return } // Now output the dump taking care to apply the current indentation-level // and pointer name comments. var err error firstLine := true for err == nil { var lineBytes []byte lineBytes, err = buf.ReadBytes('\n') line := strings.TrimRight(string(lineBytes), " \n") if err != nil && err != io.EOF { break } // Do not indent first line if firstLine { firstLine = false } else { s.indent() } s.write([]byte(line)) // At EOF we're done if err == io.EOF { return } s.newlineWithPointerNameComment() } panic(err) } func (s *dumpState) dump(value interface{}) { if value == nil { printNil(s.w) return } v := reflect.ValueOf(value) s.dumpVal(v) } func (s *dumpState) descendIntoPossiblePointer(value reflect.Value, f func()) { canonicalize := true if isPointerValue(value) { // If elision disabled, and this is not a circular reference, don't canonicalize if s.config.DisablePointerReplacement && s.parentPointers.add(value) { canonicalize = false } // Add to stack of pointers we're recursively descending into s.parentPointers.add(value) defer s.parentPointers.remove(value) } if !canonicalize { ptr, _ := s.pointerFor(value) s.currentPointer = ptr f() return } ptr, firstVisit := s.pointerFor(value) if ptr == nil { f() return } if firstVisit { s.currentPointer = ptr f() return } s.write([]byte(ptr.label())) } func (s *dumpState) dumpVal(value reflect.Value) { if value.Kind() == reflect.Ptr && value.IsNil() { s.write([]byte("nil")) return } v := deInterface(value) kind := v.Kind() // Try to handle with dump func if s.config.DumpFunc != nil { buf := new(bytes.Buffer) if s.config.DumpFunc(v, buf) { s.dumpCustom(v, buf) return } } // Handle custom dumpers dumperType := reflect.TypeOf((*Dumper)(nil)).Elem() if v.Type().Implements(dumperType) { s.descendIntoPossiblePointer(v, func() { // Run the custom dumper buffering the output buf := new(bytes.Buffer) dumpFunc := v.MethodByName("LitterDump") dumpFunc.Call([]reflect.Value{reflect.ValueOf(buf)}) s.dumpCustom(v, buf) }) return } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. s.write([]byte("<invalid>")) case reflect.Bool: printBool(s.w, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(s.w, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(s.w, v.Uint(), 10) case reflect.Float32: printFloat(s.w, v.Float(), 32) case reflect.Float64: printFloat(s.w, v.Float(), 64) case reflect.Complex64: printComplex(s.w, v.Complex(), 32) case reflect.Complex128: printComplex(s.w, v.Complex(), 64) case reflect.String: s.write([]byte(strconv.Quote(v.String()))) case reflect.Slice: if v.IsNil() { printNil(s.w) break } fallthrough case reflect.Array: s.descendIntoPossiblePointer(v, func() { s.dumpSlice(v) }) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { printNil(s.w) } case reflect.Ptr: s.descendIntoPossiblePointer(v, func() { if s.config.StrictGo { s.writeString(fmt.Sprintf("(func(v %s) *%s { return &v })(", v.Elem().Type(), v.Elem().Type())) s.dumpVal(v.Elem()) s.writeString(")") } else { s.writeString("&") s.dumpVal(v.Elem()) } }) case reflect.Map: s.descendIntoPossiblePointer(v, func() { s.dumpMap(v) }) case reflect.Struct: s.dumpStruct(v) case reflect.Func: s.dumpFunc(v) case reflect.Chan: s.dumpChan(v) default: if v.CanInterface() { s.writeString(fmt.Sprintf("%v", v.Interface())) } else { s.writeString(fmt.Sprintf("%v", v.String())) } } } // registers that the value has been visited and checks to see if it is one of the // pointers we will see multiple times. If it is, it returns a temporary name for this // pointer. It also returns a boolean value indicating whether this is the first time // this name is returned so the caller can decide whether the contents of the pointer // has been dumped before or not. func (s *dumpState) pointerFor(v reflect.Value) (*ptrinfo, bool) { if isPointerValue(v) { if info, ok := s.pointers.get(v); ok { firstVisit := s.visitedPointers.add(v) return info, firstVisit } } return nil, false } // prepares a new state object for dumping the provided value func newDumpState(value interface{}, options *Options, writer io.Writer) *dumpState { result := &dumpState{ config: options, pointers: mapReusedPointers(reflect.ValueOf(value)), w: writer, } if options.HomePackage != "" { result.homePackageRegexp = regexp.MustCompile(fmt.Sprintf("\\b%s\\.", options.HomePackage)) } return result } // Dump a value to stdout func Dump(value ...interface{}) { (&Config).Dump(value...) } // Sdump dumps a value to a string func Sdump(value ...interface{}) string { return (&Config).Sdump(value...) } // Dump a value to stdout according to the options func (o Options) Dump(values ...interface{}) { for i, value := range values { state := newDumpState(value, &o, os.Stdout) if i > 0 { state.write([]byte(o.Separator)) } state.dump(value) } _, _ = os.Stdout.Write([]byte("\n")) } // Sdump dumps a value to a string according to the options func (o Options) Sdump(values ...interface{}) string { buf := new(bytes.Buffer) for i, value := range values { if i > 0 { _, _ = buf.Write([]byte(o.Separator)) } state := newDumpState(value, &o, buf) state.dump(value) } return buf.String() } type mapKeySorter struct { keys []reflect.Value options *Options } func (s mapKeySorter) Len() int { return len(s.keys) } func (s mapKeySorter) Swap(i, j int) { s.keys[i], s.keys[j] = s.keys[j], s.keys[i] } func (s mapKeySorter) Less(i, j int) bool { ibuf := new(bytes.Buffer) jbuf := new(bytes.Buffer) newDumpState(s.keys[i], s.options, ibuf).dumpVal(s.keys[i]) newDumpState(s.keys[j], s.options, jbuf).dumpVal(s.keys[j]) return ibuf.String() < jbuf.String() }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/spkg/bom/discard_go14.go
vendor/github.com/spkg/bom/discard_go14.go
// +build !go1.5 package bom import "bufio" func discardBytes(buf *bufio.Reader, n int) { // cannot use the buf.Discard method as it was introduced in Go 1.5 for i := 0; i < n; i++ { buf.ReadByte() } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/spkg/bom/bom.go
vendor/github.com/spkg/bom/bom.go
// Package bom is used to clean up UTF-8 Byte Order Marks. package bom import ( "bufio" "io" ) const ( bom0 = 0xef bom1 = 0xbb bom2 = 0xbf ) // Clean returns b with the 3 byte BOM stripped off the front if it is present. // If the BOM is not present, then b is returned. func Clean(b []byte) []byte { if len(b) >= 3 && b[0] == bom0 && b[1] == bom1 && b[2] == bom2 { return b[3:] } return b } // NewReader returns an io.Reader that will skip over initial UTF-8 byte order marks. func NewReader(r io.Reader) io.Reader { buf := bufio.NewReader(r) b, err := buf.Peek(3) if err != nil { // not enough bytes return buf } if b[0] == bom0 && b[1] == bom1 && b[2] == bom2 { discardBytes(buf, 3) } return buf }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/spkg/bom/discard_go15.go
vendor/github.com/spkg/bom/discard_go15.go
// +build go1.5 package bom import "bufio" func discardBytes(buf *bufio.Reader, n int) { // the Discard method was introduced in Go 1.5 buf.Discard(n) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/golang/groupcache/lru/lru.go
vendor/github.com/golang/groupcache/lru/lru.go
/* Copyright 2013 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package lru implements an LRU cache. package lru import "container/list" // Cache is an LRU cache. It is not safe for concurrent access. type Cache struct { // MaxEntries is the maximum number of cache entries before // an item is evicted. Zero means no limit. MaxEntries int // OnEvicted optionally specifies a callback function to be // executed when an entry is purged from the cache. OnEvicted func(key Key, value interface{}) ll *list.List cache map[interface{}]*list.Element } // A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators type Key interface{} type entry struct { key Key value interface{} } // New creates a new Cache. // If maxEntries is zero, the cache has no limit and it's assumed // that eviction is done by the caller. func New(maxEntries int) *Cache { return &Cache{ MaxEntries: maxEntries, ll: list.New(), cache: make(map[interface{}]*list.Element), } } // Add adds a value to the cache. func (c *Cache) Add(key Key, value interface{}) { if c.cache == nil { c.cache = make(map[interface{}]*list.Element) c.ll = list.New() } if ee, ok := c.cache[key]; ok { c.ll.MoveToFront(ee) ee.Value.(*entry).value = value return } ele := c.ll.PushFront(&entry{key, value}) c.cache[key] = ele if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { c.RemoveOldest() } } // Get looks up a key's value from the cache. func (c *Cache) Get(key Key) (value interface{}, ok bool) { if c.cache == nil { return } if ele, hit := c.cache[key]; hit { c.ll.MoveToFront(ele) return ele.Value.(*entry).value, true } return } // Remove removes the provided key from the cache. func (c *Cache) Remove(key Key) { if c.cache == nil { return } if ele, hit := c.cache[key]; hit { c.removeElement(ele) } } // RemoveOldest removes the oldest item from the cache. func (c *Cache) RemoveOldest() { if c.cache == nil { return } ele := c.ll.Back() if ele != nil { c.removeElement(ele) } } func (c *Cache) removeElement(e *list.Element) { c.ll.Remove(e) kv := e.Value.(*entry) delete(c.cache, kv.key) if c.OnEvicted != nil { c.OnEvicted(kv.key, kv.value) } } // Len returns the number of items in the cache. func (c *Cache) Len() int { if c.cache == nil { return 0 } return c.ll.Len() } // Clear purges all stored items from the cache. func (c *Cache) Clear() { if c.OnEvicted != nil { for _, e := range c.cache { kv := e.Value.(*entry) c.OnEvicted(kv.key, kv.value) } } c.ll = nil c.cache = nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/xo/terminfo/terminfo.go
vendor/github.com/xo/terminfo/terminfo.go
// Package terminfo implements reading terminfo files in pure go. package terminfo import ( "io" "io/ioutil" "path" "strconv" "strings" ) // Error is a terminfo error. type Error string // Error satisfies the error interface. func (err Error) Error() string { return string(err) } const ( // ErrInvalidFileSize is the invalid file size error. ErrInvalidFileSize Error = "invalid file size" // ErrUnexpectedFileEnd is the unexpected file end error. ErrUnexpectedFileEnd Error = "unexpected file end" // ErrInvalidStringTable is the invalid string table error. ErrInvalidStringTable Error = "invalid string table" // ErrInvalidMagic is the invalid magic error. ErrInvalidMagic Error = "invalid magic" // ErrInvalidHeader is the invalid header error. ErrInvalidHeader Error = "invalid header" // ErrInvalidNames is the invalid names error. ErrInvalidNames Error = "invalid names" // ErrInvalidExtendedHeader is the invalid extended header error. ErrInvalidExtendedHeader Error = "invalid extended header" // ErrEmptyTermName is the empty term name error. ErrEmptyTermName Error = "empty term name" // ErrDatabaseDirectoryNotFound is the database directory not found error. ErrDatabaseDirectoryNotFound Error = "database directory not found" // ErrFileNotFound is the file not found error. ErrFileNotFound Error = "file not found" // ErrInvalidTermProgramVersion is the invalid TERM_PROGRAM_VERSION error. ErrInvalidTermProgramVersion Error = "invalid TERM_PROGRAM_VERSION" ) // Terminfo describes a terminal's capabilities. type Terminfo struct { // File is the original source file. File string // Names are the provided cap names. Names []string // Bools are the bool capabilities. Bools map[int]bool // BoolsM are the missing bool capabilities. BoolsM map[int]bool // Nums are the num capabilities. Nums map[int]int // NumsM are the missing num capabilities. NumsM map[int]bool // Strings are the string capabilities. Strings map[int][]byte // StringsM are the missing string capabilities. StringsM map[int]bool // ExtBools are the extended bool capabilities. ExtBools map[int]bool // ExtBoolsNames is the map of extended bool capabilities to their index. ExtBoolNames map[int][]byte // ExtNums are the extended num capabilities. ExtNums map[int]int // ExtNumsNames is the map of extended num capabilities to their index. ExtNumNames map[int][]byte // ExtStrings are the extended string capabilities. ExtStrings map[int][]byte // ExtStringsNames is the map of extended string capabilities to their index. ExtStringNames map[int][]byte } // Decode decodes the terminfo data contained in buf. func Decode(buf []byte) (*Terminfo, error) { var err error // check max file length if len(buf) >= maxFileLength { return nil, ErrInvalidFileSize } d := &decoder{ buf: buf, len: len(buf), } // read header h, err := d.readInts(6, 16) if err != nil { return nil, err } var numWidth int // check magic if h[fieldMagic] == magic { numWidth = 16 } else if h[fieldMagic] == magicExtended { numWidth = 32 } else { return nil, ErrInvalidMagic } // check header if hasInvalidCaps(h) { return nil, ErrInvalidHeader } // check remaining length if d.len-d.pos < capLength(h) { return nil, ErrUnexpectedFileEnd } // read names names, err := d.readBytes(h[fieldNameSize]) if err != nil { return nil, err } // check name is terminated properly i := findNull(names, 0) if i == -1 { return nil, ErrInvalidNames } names = names[:i] // read bool caps bools, boolsM, err := d.readBools(h[fieldBoolCount]) if err != nil { return nil, err } // read num caps nums, numsM, err := d.readNums(h[fieldNumCount], numWidth) if err != nil { return nil, err } // read string caps strs, strsM, err := d.readStrings(h[fieldStringCount], h[fieldTableSize]) if err != nil { return nil, err } ti := &Terminfo{ Names: strings.Split(string(names), "|"), Bools: bools, BoolsM: boolsM, Nums: nums, NumsM: numsM, Strings: strs, StringsM: strsM, } // at the end of file, so no extended caps if d.pos >= d.len { return ti, nil } // decode extended header eh, err := d.readInts(5, 16) if err != nil { return nil, err } // check extended offset field if hasInvalidExtOffset(eh) { return nil, ErrInvalidExtendedHeader } // check extended cap lengths if d.len-d.pos != extCapLength(eh, numWidth) { return nil, ErrInvalidExtendedHeader } // read extended bool caps ti.ExtBools, _, err = d.readBools(eh[fieldExtBoolCount]) if err != nil { return nil, err } // read extended num caps ti.ExtNums, _, err = d.readNums(eh[fieldExtNumCount], numWidth) if err != nil { return nil, err } // read extended string data table indexes extIndexes, err := d.readInts(eh[fieldExtOffsetCount], 16) if err != nil { return nil, err } // read string data table extData, err := d.readBytes(eh[fieldExtTableSize]) if err != nil { return nil, err } // precautionary check that exactly at end of file if d.pos != d.len { return nil, ErrUnexpectedFileEnd } var last int // read extended string caps ti.ExtStrings, last, err = readStrings(extIndexes, extData, eh[fieldExtStringCount]) if err != nil { return nil, err } extIndexes, extData = extIndexes[eh[fieldExtStringCount]:], extData[last:] // read extended bool names ti.ExtBoolNames, _, err = readStrings(extIndexes, extData, eh[fieldExtBoolCount]) if err != nil { return nil, err } extIndexes = extIndexes[eh[fieldExtBoolCount]:] // read extended num names ti.ExtNumNames, _, err = readStrings(extIndexes, extData, eh[fieldExtNumCount]) if err != nil { return nil, err } extIndexes = extIndexes[eh[fieldExtNumCount]:] // read extended string names ti.ExtStringNames, _, err = readStrings(extIndexes, extData, eh[fieldExtStringCount]) if err != nil { return nil, err } //extIndexes = extIndexes[eh[fieldExtStringCount]:] return ti, nil } // Open reads the terminfo file name from the specified directory dir. func Open(dir, name string) (*Terminfo, error) { var err error var buf []byte var filename string for _, f := range []string{ path.Join(dir, name[0:1], name), path.Join(dir, strconv.FormatUint(uint64(name[0]), 16), name), } { buf, err = ioutil.ReadFile(f) if err == nil { filename = f break } } if buf == nil { return nil, ErrFileNotFound } // decode ti, err := Decode(buf) if err != nil { return nil, err } // save original file name ti.File = filename // add to cache termCache.Lock() for _, n := range ti.Names { termCache.db[n] = ti } termCache.Unlock() return ti, nil } // boolCaps returns all bool and extended capabilities using f to format the // index key. func (ti *Terminfo) boolCaps(f func(int) string, extended bool) map[string]bool { m := make(map[string]bool, len(ti.Bools)+len(ti.ExtBools)) if !extended { for k, v := range ti.Bools { m[f(k)] = v } } else { for k, v := range ti.ExtBools { m[string(ti.ExtBoolNames[k])] = v } } return m } // BoolCaps returns all bool capabilities. func (ti *Terminfo) BoolCaps() map[string]bool { return ti.boolCaps(BoolCapName, false) } // BoolCapsShort returns all bool capabilities, using the short name as the // index. func (ti *Terminfo) BoolCapsShort() map[string]bool { return ti.boolCaps(BoolCapNameShort, false) } // ExtBoolCaps returns all extended bool capabilities. func (ti *Terminfo) ExtBoolCaps() map[string]bool { return ti.boolCaps(BoolCapName, true) } // ExtBoolCapsShort returns all extended bool capabilities, using the short // name as the index. func (ti *Terminfo) ExtBoolCapsShort() map[string]bool { return ti.boolCaps(BoolCapNameShort, true) } // numCaps returns all num and extended capabilities using f to format the // index key. func (ti *Terminfo) numCaps(f func(int) string, extended bool) map[string]int { m := make(map[string]int, len(ti.Nums)+len(ti.ExtNums)) if !extended { for k, v := range ti.Nums { m[f(k)] = v } } else { for k, v := range ti.ExtNums { m[string(ti.ExtNumNames[k])] = v } } return m } // NumCaps returns all num capabilities. func (ti *Terminfo) NumCaps() map[string]int { return ti.numCaps(NumCapName, false) } // NumCapsShort returns all num capabilities, using the short name as the // index. func (ti *Terminfo) NumCapsShort() map[string]int { return ti.numCaps(NumCapNameShort, false) } // ExtNumCaps returns all extended num capabilities. func (ti *Terminfo) ExtNumCaps() map[string]int { return ti.numCaps(NumCapName, true) } // ExtNumCapsShort returns all extended num capabilities, using the short // name as the index. func (ti *Terminfo) ExtNumCapsShort() map[string]int { return ti.numCaps(NumCapNameShort, true) } // stringCaps returns all string and extended capabilities using f to format the // index key. func (ti *Terminfo) stringCaps(f func(int) string, extended bool) map[string][]byte { m := make(map[string][]byte, len(ti.Strings)+len(ti.ExtStrings)) if !extended { for k, v := range ti.Strings { m[f(k)] = v } } else { for k, v := range ti.ExtStrings { m[string(ti.ExtStringNames[k])] = v } } return m } // StringCaps returns all string capabilities. func (ti *Terminfo) StringCaps() map[string][]byte { return ti.stringCaps(StringCapName, false) } // StringCapsShort returns all string capabilities, using the short name as the // index. func (ti *Terminfo) StringCapsShort() map[string][]byte { return ti.stringCaps(StringCapNameShort, false) } // ExtStringCaps returns all extended string capabilities. func (ti *Terminfo) ExtStringCaps() map[string][]byte { return ti.stringCaps(StringCapName, true) } // ExtStringCapsShort returns all extended string capabilities, using the short // name as the index. func (ti *Terminfo) ExtStringCapsShort() map[string][]byte { return ti.stringCaps(StringCapNameShort, true) } // Has determines if the bool cap i is present. func (ti *Terminfo) Has(i int) bool { return ti.Bools[i] } // Num returns the num cap i, or -1 if not present. func (ti *Terminfo) Num(i int) int { n, ok := ti.Nums[i] if !ok { return -1 } return n } // Printf formats the string cap i, interpolating parameters v. func (ti *Terminfo) Printf(i int, v ...interface{}) string { return Printf(ti.Strings[i], v...) } // Fprintf prints the string cap i to writer w, interpolating parameters v. func (ti *Terminfo) Fprintf(w io.Writer, i int, v ...interface{}) { Fprintf(w, ti.Strings[i], v...) } // Color takes a foreground and background color and returns string that sets // them for this terminal. func (ti *Terminfo) Colorf(fg, bg int, str string) string { maxColors := int(ti.Nums[MaxColors]) // map bright colors to lower versions if the color table only holds 8. if maxColors == 8 { if fg > 7 && fg < 16 { fg -= 8 } if bg > 7 && bg < 16 { bg -= 8 } } var s string if maxColors > fg && fg >= 0 { s += ti.Printf(SetAForeground, fg) } if maxColors > bg && bg >= 0 { s += ti.Printf(SetABackground, bg) } return s + str + ti.Printf(ExitAttributeMode) } // Goto returns a string suitable for addressing the cursor at the given // row and column. The origin 0, 0 is in the upper left corner of the screen. func (ti *Terminfo) Goto(row, col int) string { return Printf(ti.Strings[CursorAddress], row, col) } // Puts emits the string to the writer, but expands inline padding indications // (of the form $<[delay]> where [delay] is msec) to a suitable number of // padding characters (usually null bytes) based upon the supplied baud. At // high baud rates, more padding characters will be inserted. /*func (ti *Terminfo) Puts(w io.Writer, s string, lines, baud int) (int, error) { var err error for { start := strings.Index(s, "$<") if start == -1 { // most strings don't need padding, which is good news! return io.WriteString(w, s) } end := strings.Index(s, ">") if end == -1 { // unterminated... just emit bytes unadulterated. return io.WriteString(w, "$<"+s) } var c int c, err = io.WriteString(w, s[:start]) if err != nil { return n + c, err } n += c s = s[start+2:] val := s[:end] s = s[end+1:] var ms int var dot, mandatory, asterisk bool unit := 1000 for _, ch := range val { switch { case ch >= '0' && ch <= '9': ms = (ms * 10) + int(ch-'0') if dot { unit *= 10 } case ch == '.' && !dot: dot = true case ch == '*' && !asterisk: ms *= lines asterisk = true case ch == '/': mandatory = true default: break } } z, pad := ((baud/8)/unit)*ms, ti.Strings[PadChar] b := make([]byte, len(pad)*z) for bp := copy(b, pad); bp < len(b); bp *= 2 { copy(b[bp:], b[:bp]) } if (!ti.Bools[XonXoff] && baud > int(ti.Nums[PaddingBaudRate])) || mandatory { c, err = w.Write(b) if err != nil { return n + c, err } n += c } } return n, nil }*/
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/xo/terminfo/capvals.go
vendor/github.com/xo/terminfo/capvals.go
package terminfo // Code generated by gen.go. DO NOT EDIT. // Bool capabilities. const ( // The AutoLeftMargin [auto_left_margin, bw] bool capability indicates cub1 wraps from column 0 to last column. AutoLeftMargin = iota // The AutoRightMargin [auto_right_margin, am] bool capability indicates terminal has automatic margins. AutoRightMargin // The NoEscCtlc [no_esc_ctlc, xsb] bool capability indicates beehive (f1=escape, f2=ctrl C). NoEscCtlc // The CeolStandoutGlitch [ceol_standout_glitch, xhp] bool capability indicates standout not erased by overwriting (hp). CeolStandoutGlitch // The EatNewlineGlitch [eat_newline_glitch, xenl] bool capability indicates newline ignored after 80 cols (concept). EatNewlineGlitch // The EraseOverstrike [erase_overstrike, eo] bool capability indicates can erase overstrikes with a blank. EraseOverstrike // The GenericType [generic_type, gn] bool capability indicates generic line type. GenericType // The HardCopy [hard_copy, hc] bool capability indicates hardcopy terminal. HardCopy // The HasMetaKey [has_meta_key, km] bool capability indicates Has a meta key (i.e., sets 8th-bit). HasMetaKey // The HasStatusLine [has_status_line, hs] bool capability indicates has extra status line. HasStatusLine // The InsertNullGlitch [insert_null_glitch, in] bool capability indicates insert mode distinguishes nulls. InsertNullGlitch // The MemoryAbove [memory_above, da] bool capability indicates display may be retained above the screen. MemoryAbove // The MemoryBelow [memory_below, db] bool capability indicates display may be retained below the screen. MemoryBelow // The MoveInsertMode [move_insert_mode, mir] bool capability indicates safe to move while in insert mode. MoveInsertMode // The MoveStandoutMode [move_standout_mode, msgr] bool capability indicates safe to move while in standout mode. MoveStandoutMode // The OverStrike [over_strike, os] bool capability indicates terminal can overstrike. OverStrike // The StatusLineEscOk [status_line_esc_ok, eslok] bool capability indicates escape can be used on the status line. StatusLineEscOk // The DestTabsMagicSmso [dest_tabs_magic_smso, xt] bool capability indicates tabs destructive, magic so char (t1061). DestTabsMagicSmso // The TildeGlitch [tilde_glitch, hz] bool capability indicates cannot print ~'s (Hazeltine). TildeGlitch // The TransparentUnderline [transparent_underline, ul] bool capability indicates underline character overstrikes. TransparentUnderline // The XonXoff [xon_xoff, xon] bool capability indicates terminal uses xon/xoff handshaking. XonXoff // The NeedsXonXoff [needs_xon_xoff, nxon] bool capability indicates padding will not work, xon/xoff required. NeedsXonXoff // The PrtrSilent [prtr_silent, mc5i] bool capability indicates printer will not echo on screen. PrtrSilent // The HardCursor [hard_cursor, chts] bool capability indicates cursor is hard to see. HardCursor // The NonRevRmcup [non_rev_rmcup, nrrmc] bool capability indicates smcup does not reverse rmcup. NonRevRmcup // The NoPadChar [no_pad_char, npc] bool capability indicates pad character does not exist. NoPadChar // The NonDestScrollRegion [non_dest_scroll_region, ndscr] bool capability indicates scrolling region is non-destructive. NonDestScrollRegion // The CanChange [can_change, ccc] bool capability indicates terminal can re-define existing colors. CanChange // The BackColorErase [back_color_erase, bce] bool capability indicates screen erased with background color. BackColorErase // The HueLightnessSaturation [hue_lightness_saturation, hls] bool capability indicates terminal uses only HLS color notation (Tektronix). HueLightnessSaturation // The ColAddrGlitch [col_addr_glitch, xhpa] bool capability indicates only positive motion for hpa/mhpa caps. ColAddrGlitch // The CrCancelsMicroMode [cr_cancels_micro_mode, crxm] bool capability indicates using cr turns off micro mode. CrCancelsMicroMode // The HasPrintWheel [has_print_wheel, daisy] bool capability indicates printer needs operator to change character set. HasPrintWheel // The RowAddrGlitch [row_addr_glitch, xvpa] bool capability indicates only positive motion for vpa/mvpa caps. RowAddrGlitch // The SemiAutoRightMargin [semi_auto_right_margin, sam] bool capability indicates printing in last column causes cr. SemiAutoRightMargin // The CpiChangesRes [cpi_changes_res, cpix] bool capability indicates changing character pitch changes resolution. CpiChangesRes // The LpiChangesRes [lpi_changes_res, lpix] bool capability indicates changing line pitch changes resolution. LpiChangesRes // The BackspacesWithBs [backspaces_with_bs, OTbs] bool capability indicates uses ^H to move left. BackspacesWithBs // The CrtNoScrolling [crt_no_scrolling, OTns] bool capability indicates crt cannot scroll. CrtNoScrolling // The NoCorrectlyWorkingCr [no_correctly_working_cr, OTnc] bool capability indicates no way to go to start of line. NoCorrectlyWorkingCr // The GnuHasMetaKey [gnu_has_meta_key, OTMT] bool capability indicates has meta key. GnuHasMetaKey // The LinefeedIsNewline [linefeed_is_newline, OTNL] bool capability indicates move down with \n. LinefeedIsNewline // The HasHardwareTabs [has_hardware_tabs, OTpt] bool capability indicates has 8-char tabs invoked with ^I. HasHardwareTabs // The ReturnDoesClrEol [return_does_clr_eol, OTxr] bool capability indicates return clears the line. ReturnDoesClrEol ) // Num capabilities. const ( // The Columns [columns, cols] num capability is number of columns in a line. Columns = iota // The InitTabs [init_tabs, it] num capability is tabs initially every # spaces. InitTabs // The Lines [lines, lines] num capability is number of lines on screen or page. Lines // The LinesOfMemory [lines_of_memory, lm] num capability is lines of memory if > line. 0 means varies. LinesOfMemory // The MagicCookieGlitch [magic_cookie_glitch, xmc] num capability is number of blank characters left by smso or rmso. MagicCookieGlitch // The PaddingBaudRate [padding_baud_rate, pb] num capability is lowest baud rate where padding needed. PaddingBaudRate // The VirtualTerminal [virtual_terminal, vt] num capability is virtual terminal number (CB/unix). VirtualTerminal // The WidthStatusLine [width_status_line, wsl] num capability is number of columns in status line. WidthStatusLine // The NumLabels [num_labels, nlab] num capability is number of labels on screen. NumLabels // The LabelHeight [label_height, lh] num capability is rows in each label. LabelHeight // The LabelWidth [label_width, lw] num capability is columns in each label. LabelWidth // The MaxAttributes [max_attributes, ma] num capability is maximum combined attributes terminal can handle. MaxAttributes // The MaximumWindows [maximum_windows, wnum] num capability is maximum number of definable windows. MaximumWindows // The MaxColors [max_colors, colors] num capability is maximum number of colors on screen. MaxColors // The MaxPairs [max_pairs, pairs] num capability is maximum number of color-pairs on the screen. MaxPairs // The NoColorVideo [no_color_video, ncv] num capability is video attributes that cannot be used with colors. NoColorVideo // The BufferCapacity [buffer_capacity, bufsz] num capability is numbers of bytes buffered before printing. BufferCapacity // The DotVertSpacing [dot_vert_spacing, spinv] num capability is spacing of pins vertically in pins per inch. DotVertSpacing // The DotHorzSpacing [dot_horz_spacing, spinh] num capability is spacing of dots horizontally in dots per inch. DotHorzSpacing // The MaxMicroAddress [max_micro_address, maddr] num capability is maximum value in micro_..._address. MaxMicroAddress // The MaxMicroJump [max_micro_jump, mjump] num capability is maximum value in parm_..._micro. MaxMicroJump // The MicroColSize [micro_col_size, mcs] num capability is character step size when in micro mode. MicroColSize // The MicroLineSize [micro_line_size, mls] num capability is line step size when in micro mode. MicroLineSize // The NumberOfPins [number_of_pins, npins] num capability is numbers of pins in print-head. NumberOfPins // The OutputResChar [output_res_char, orc] num capability is horizontal resolution in units per line. OutputResChar // The OutputResLine [output_res_line, orl] num capability is vertical resolution in units per line. OutputResLine // The OutputResHorzInch [output_res_horz_inch, orhi] num capability is horizontal resolution in units per inch. OutputResHorzInch // The OutputResVertInch [output_res_vert_inch, orvi] num capability is vertical resolution in units per inch. OutputResVertInch // The PrintRate [print_rate, cps] num capability is print rate in characters per second. PrintRate // The WideCharSize [wide_char_size, widcs] num capability is character step size when in double wide mode. WideCharSize // The Buttons [buttons, btns] num capability is number of buttons on mouse. Buttons // The BitImageEntwining [bit_image_entwining, bitwin] num capability is number of passes for each bit-image row. BitImageEntwining // The BitImageType [bit_image_type, bitype] num capability is type of bit-image device. BitImageType // The MagicCookieGlitchUl [magic_cookie_glitch_ul, OTug] num capability is number of blanks left by ul. MagicCookieGlitchUl // The CarriageReturnDelay [carriage_return_delay, OTdC] num capability is pad needed for CR. CarriageReturnDelay // The NewLineDelay [new_line_delay, OTdN] num capability is pad needed for LF. NewLineDelay // The BackspaceDelay [backspace_delay, OTdB] num capability is padding required for ^H. BackspaceDelay // The HorizontalTabDelay [horizontal_tab_delay, OTdT] num capability is padding required for ^I. HorizontalTabDelay // The NumberOfFunctionKeys [number_of_function_keys, OTkn] num capability is count of function keys. NumberOfFunctionKeys ) // String capabilities. const ( // The BackTab [back_tab, cbt] string capability is the back tab (P). BackTab = iota // The Bell [bell, bel] string capability is the audible signal (bell) (P). Bell // The CarriageReturn [carriage_return, cr] string capability is the carriage return (P*) (P*). CarriageReturn // The ChangeScrollRegion [change_scroll_region, csr] string capability is the change region to line #1 to line #2 (P). ChangeScrollRegion // The ClearAllTabs [clear_all_tabs, tbc] string capability is the clear all tab stops (P). ClearAllTabs // The ClearScreen [clear_screen, clear] string capability is the clear screen and home cursor (P*). ClearScreen // The ClrEol [clr_eol, el] string capability is the clear to end of line (P). ClrEol // The ClrEos [clr_eos, ed] string capability is the clear to end of screen (P*). ClrEos // The ColumnAddress [column_address, hpa] string capability is the horizontal position #1, absolute (P). ColumnAddress // The CommandCharacter [command_character, cmdch] string capability is the terminal settable cmd character in prototype !?. CommandCharacter // The CursorAddress [cursor_address, cup] string capability is the move to row #1 columns #2. CursorAddress // The CursorDown [cursor_down, cud1] string capability is the down one line. CursorDown // The CursorHome [cursor_home, home] string capability is the home cursor (if no cup). CursorHome // The CursorInvisible [cursor_invisible, civis] string capability is the make cursor invisible. CursorInvisible // The CursorLeft [cursor_left, cub1] string capability is the move left one space. CursorLeft // The CursorMemAddress [cursor_mem_address, mrcup] string capability is the memory relative cursor addressing, move to row #1 columns #2. CursorMemAddress // The CursorNormal [cursor_normal, cnorm] string capability is the make cursor appear normal (undo civis/cvvis). CursorNormal // The CursorRight [cursor_right, cuf1] string capability is the non-destructive space (move right one space). CursorRight // The CursorToLl [cursor_to_ll, ll] string capability is the last line, first column (if no cup). CursorToLl // The CursorUp [cursor_up, cuu1] string capability is the up one line. CursorUp // The CursorVisible [cursor_visible, cvvis] string capability is the make cursor very visible. CursorVisible // The DeleteCharacter [delete_character, dch1] string capability is the delete character (P*). DeleteCharacter // The DeleteLine [delete_line, dl1] string capability is the delete line (P*). DeleteLine // The DisStatusLine [dis_status_line, dsl] string capability is the disable status line. DisStatusLine // The DownHalfLine [down_half_line, hd] string capability is the half a line down. DownHalfLine // The EnterAltCharsetMode [enter_alt_charset_mode, smacs] string capability is the start alternate character set (P). EnterAltCharsetMode // The EnterBlinkMode [enter_blink_mode, blink] string capability is the turn on blinking. EnterBlinkMode // The EnterBoldMode [enter_bold_mode, bold] string capability is the turn on bold (extra bright) mode. EnterBoldMode // The EnterCaMode [enter_ca_mode, smcup] string capability is the string to start programs using cup. EnterCaMode // The EnterDeleteMode [enter_delete_mode, smdc] string capability is the enter delete mode. EnterDeleteMode // The EnterDimMode [enter_dim_mode, dim] string capability is the turn on half-bright mode. EnterDimMode // The EnterInsertMode [enter_insert_mode, smir] string capability is the enter insert mode. EnterInsertMode // The EnterSecureMode [enter_secure_mode, invis] string capability is the turn on blank mode (characters invisible). EnterSecureMode // The EnterProtectedMode [enter_protected_mode, prot] string capability is the turn on protected mode. EnterProtectedMode // The EnterReverseMode [enter_reverse_mode, rev] string capability is the turn on reverse video mode. EnterReverseMode // The EnterStandoutMode [enter_standout_mode, smso] string capability is the begin standout mode. EnterStandoutMode // The EnterUnderlineMode [enter_underline_mode, smul] string capability is the begin underline mode. EnterUnderlineMode // The EraseChars [erase_chars, ech] string capability is the erase #1 characters (P). EraseChars // The ExitAltCharsetMode [exit_alt_charset_mode, rmacs] string capability is the end alternate character set (P). ExitAltCharsetMode // The ExitAttributeMode [exit_attribute_mode, sgr0] string capability is the turn off all attributes. ExitAttributeMode // The ExitCaMode [exit_ca_mode, rmcup] string capability is the strings to end programs using cup. ExitCaMode // The ExitDeleteMode [exit_delete_mode, rmdc] string capability is the end delete mode. ExitDeleteMode // The ExitInsertMode [exit_insert_mode, rmir] string capability is the exit insert mode. ExitInsertMode // The ExitStandoutMode [exit_standout_mode, rmso] string capability is the exit standout mode. ExitStandoutMode // The ExitUnderlineMode [exit_underline_mode, rmul] string capability is the exit underline mode. ExitUnderlineMode // The FlashScreen [flash_screen, flash] string capability is the visible bell (may not move cursor). FlashScreen // The FormFeed [form_feed, ff] string capability is the hardcopy terminal page eject (P*). FormFeed // The FromStatusLine [from_status_line, fsl] string capability is the return from status line. FromStatusLine // The Init1string [init_1string, is1] string capability is the initialization string. Init1string // The Init2string [init_2string, is2] string capability is the initialization string. Init2string // The Init3string [init_3string, is3] string capability is the initialization string. Init3string // The InitFile [init_file, if] string capability is the name of initialization file. InitFile // The InsertCharacter [insert_character, ich1] string capability is the insert character (P). InsertCharacter // The InsertLine [insert_line, il1] string capability is the insert line (P*). InsertLine // The InsertPadding [insert_padding, ip] string capability is the insert padding after inserted character. InsertPadding // The KeyBackspace [key_backspace, kbs] string capability is the backspace key. KeyBackspace // The KeyCatab [key_catab, ktbc] string capability is the clear-all-tabs key. KeyCatab // The KeyClear [key_clear, kclr] string capability is the clear-screen or erase key. KeyClear // The KeyCtab [key_ctab, kctab] string capability is the clear-tab key. KeyCtab // The KeyDc [key_dc, kdch1] string capability is the delete-character key. KeyDc // The KeyDl [key_dl, kdl1] string capability is the delete-line key. KeyDl // The KeyDown [key_down, kcud1] string capability is the down-arrow key. KeyDown // The KeyEic [key_eic, krmir] string capability is the sent by rmir or smir in insert mode. KeyEic // The KeyEol [key_eol, kel] string capability is the clear-to-end-of-line key. KeyEol // The KeyEos [key_eos, ked] string capability is the clear-to-end-of-screen key. KeyEos // The KeyF0 [key_f0, kf0] string capability is the F0 function key. KeyF0 // The KeyF1 [key_f1, kf1] string capability is the F1 function key. KeyF1 // The KeyF10 [key_f10, kf10] string capability is the F10 function key. KeyF10 // The KeyF2 [key_f2, kf2] string capability is the F2 function key. KeyF2 // The KeyF3 [key_f3, kf3] string capability is the F3 function key. KeyF3 // The KeyF4 [key_f4, kf4] string capability is the F4 function key. KeyF4 // The KeyF5 [key_f5, kf5] string capability is the F5 function key. KeyF5 // The KeyF6 [key_f6, kf6] string capability is the F6 function key. KeyF6 // The KeyF7 [key_f7, kf7] string capability is the F7 function key. KeyF7 // The KeyF8 [key_f8, kf8] string capability is the F8 function key. KeyF8 // The KeyF9 [key_f9, kf9] string capability is the F9 function key. KeyF9 // The KeyHome [key_home, khome] string capability is the home key. KeyHome // The KeyIc [key_ic, kich1] string capability is the insert-character key. KeyIc // The KeyIl [key_il, kil1] string capability is the insert-line key. KeyIl // The KeyLeft [key_left, kcub1] string capability is the left-arrow key. KeyLeft // The KeyLl [key_ll, kll] string capability is the lower-left key (home down). KeyLl // The KeyNpage [key_npage, knp] string capability is the next-page key. KeyNpage // The KeyPpage [key_ppage, kpp] string capability is the previous-page key. KeyPpage // The KeyRight [key_right, kcuf1] string capability is the right-arrow key. KeyRight // The KeySf [key_sf, kind] string capability is the scroll-forward key. KeySf // The KeySr [key_sr, kri] string capability is the scroll-backward key. KeySr // The KeyStab [key_stab, khts] string capability is the set-tab key. KeyStab // The KeyUp [key_up, kcuu1] string capability is the up-arrow key. KeyUp // The KeypadLocal [keypad_local, rmkx] string capability is the leave 'keyboard_transmit' mode. KeypadLocal // The KeypadXmit [keypad_xmit, smkx] string capability is the enter 'keyboard_transmit' mode. KeypadXmit // The LabF0 [lab_f0, lf0] string capability is the label on function key f0 if not f0. LabF0 // The LabF1 [lab_f1, lf1] string capability is the label on function key f1 if not f1. LabF1 // The LabF10 [lab_f10, lf10] string capability is the label on function key f10 if not f10. LabF10 // The LabF2 [lab_f2, lf2] string capability is the label on function key f2 if not f2. LabF2 // The LabF3 [lab_f3, lf3] string capability is the label on function key f3 if not f3. LabF3 // The LabF4 [lab_f4, lf4] string capability is the label on function key f4 if not f4. LabF4 // The LabF5 [lab_f5, lf5] string capability is the label on function key f5 if not f5. LabF5 // The LabF6 [lab_f6, lf6] string capability is the label on function key f6 if not f6. LabF6 // The LabF7 [lab_f7, lf7] string capability is the label on function key f7 if not f7. LabF7 // The LabF8 [lab_f8, lf8] string capability is the label on function key f8 if not f8. LabF8 // The LabF9 [lab_f9, lf9] string capability is the label on function key f9 if not f9. LabF9 // The MetaOff [meta_off, rmm] string capability is the turn off meta mode. MetaOff // The MetaOn [meta_on, smm] string capability is the turn on meta mode (8th-bit on). MetaOn // The Newline [newline, nel] string capability is the newline (behave like cr followed by lf). Newline // The PadChar [pad_char, pad] string capability is the padding char (instead of null). PadChar // The ParmDch [parm_dch, dch] string capability is the delete #1 characters (P*). ParmDch // The ParmDeleteLine [parm_delete_line, dl] string capability is the delete #1 lines (P*). ParmDeleteLine // The ParmDownCursor [parm_down_cursor, cud] string capability is the down #1 lines (P*). ParmDownCursor // The ParmIch [parm_ich, ich] string capability is the insert #1 characters (P*). ParmIch // The ParmIndex [parm_index, indn] string capability is the scroll forward #1 lines (P). ParmIndex // The ParmInsertLine [parm_insert_line, il] string capability is the insert #1 lines (P*). ParmInsertLine // The ParmLeftCursor [parm_left_cursor, cub] string capability is the move #1 characters to the left (P). ParmLeftCursor // The ParmRightCursor [parm_right_cursor, cuf] string capability is the move #1 characters to the right (P*). ParmRightCursor // The ParmRindex [parm_rindex, rin] string capability is the scroll back #1 lines (P). ParmRindex // The ParmUpCursor [parm_up_cursor, cuu] string capability is the up #1 lines (P*). ParmUpCursor // The PkeyKey [pkey_key, pfkey] string capability is the program function key #1 to type string #2. PkeyKey // The PkeyLocal [pkey_local, pfloc] string capability is the program function key #1 to execute string #2. PkeyLocal // The PkeyXmit [pkey_xmit, pfx] string capability is the program function key #1 to transmit string #2. PkeyXmit // The PrintScreen [print_screen, mc0] string capability is the print contents of screen. PrintScreen // The PrtrOff [prtr_off, mc4] string capability is the turn off printer. PrtrOff // The PrtrOn [prtr_on, mc5] string capability is the turn on printer. PrtrOn // The RepeatChar [repeat_char, rep] string capability is the repeat char #1 #2 times (P*). RepeatChar // The Reset1string [reset_1string, rs1] string capability is the reset string. Reset1string // The Reset2string [reset_2string, rs2] string capability is the reset string. Reset2string // The Reset3string [reset_3string, rs3] string capability is the reset string. Reset3string // The ResetFile [reset_file, rf] string capability is the name of reset file. ResetFile // The RestoreCursor [restore_cursor, rc] string capability is the restore cursor to position of last save_cursor. RestoreCursor // The RowAddress [row_address, vpa] string capability is the vertical position #1 absolute (P). RowAddress // The SaveCursor [save_cursor, sc] string capability is the save current cursor position (P). SaveCursor // The ScrollForward [scroll_forward, ind] string capability is the scroll text up (P). ScrollForward // The ScrollReverse [scroll_reverse, ri] string capability is the scroll text down (P). ScrollReverse // The SetAttributes [set_attributes, sgr] string capability is the define video attributes #1-#9 (PG9). SetAttributes // The SetTab [set_tab, hts] string capability is the set a tab in every row, current columns. SetTab // The SetWindow [set_window, wind] string capability is the current window is lines #1-#2 cols #3-#4. SetWindow // The Tab [tab, ht] string capability is the tab to next 8-space hardware tab stop. Tab // The ToStatusLine [to_status_line, tsl] string capability is the move to status line, column #1. ToStatusLine // The UnderlineChar [underline_char, uc] string capability is the underline char and move past it. UnderlineChar // The UpHalfLine [up_half_line, hu] string capability is the half a line up. UpHalfLine // The InitProg [init_prog, iprog] string capability is the path name of program for initialization. InitProg // The KeyA1 [key_a1, ka1] string capability is the upper left of keypad. KeyA1 // The KeyA3 [key_a3, ka3] string capability is the upper right of keypad. KeyA3 // The KeyB2 [key_b2, kb2] string capability is the center of keypad. KeyB2 // The KeyC1 [key_c1, kc1] string capability is the lower left of keypad. KeyC1 // The KeyC3 [key_c3, kc3] string capability is the lower right of keypad. KeyC3 // The PrtrNon [prtr_non, mc5p] string capability is the turn on printer for #1 bytes. PrtrNon // The CharPadding [char_padding, rmp] string capability is the like ip but when in insert mode. CharPadding // The AcsChars [acs_chars, acsc] string capability is the graphics charset pairs, based on vt100. AcsChars // The PlabNorm [plab_norm, pln] string capability is the program label #1 to show string #2. PlabNorm // The KeyBtab [key_btab, kcbt] string capability is the back-tab key. KeyBtab // The EnterXonMode [enter_xon_mode, smxon] string capability is the turn on xon/xoff handshaking. EnterXonMode // The ExitXonMode [exit_xon_mode, rmxon] string capability is the turn off xon/xoff handshaking. ExitXonMode // The EnterAmMode [enter_am_mode, smam] string capability is the turn on automatic margins. EnterAmMode // The ExitAmMode [exit_am_mode, rmam] string capability is the turn off automatic margins. ExitAmMode // The XonCharacter [xon_character, xonc] string capability is the XON character. XonCharacter // The XoffCharacter [xoff_character, xoffc] string capability is the XOFF character. XoffCharacter // The EnaAcs [ena_acs, enacs] string capability is the enable alternate char set. EnaAcs // The LabelOn [label_on, smln] string capability is the turn on soft labels. LabelOn // The LabelOff [label_off, rmln] string capability is the turn off soft labels. LabelOff // The KeyBeg [key_beg, kbeg] string capability is the begin key. KeyBeg // The KeyCancel [key_cancel, kcan] string capability is the cancel key. KeyCancel // The KeyClose [key_close, kclo] string capability is the close key. KeyClose // The KeyCommand [key_command, kcmd] string capability is the command key. KeyCommand // The KeyCopy [key_copy, kcpy] string capability is the copy key. KeyCopy // The KeyCreate [key_create, kcrt] string capability is the create key. KeyCreate // The KeyEnd [key_end, kend] string capability is the end key. KeyEnd // The KeyEnter [key_enter, kent] string capability is the enter/send key. KeyEnter // The KeyExit [key_exit, kext] string capability is the exit key. KeyExit // The KeyFind [key_find, kfnd] string capability is the find key. KeyFind // The KeyHelp [key_help, khlp] string capability is the help key. KeyHelp // The KeyMark [key_mark, kmrk] string capability is the mark key. KeyMark // The KeyMessage [key_message, kmsg] string capability is the message key. KeyMessage // The KeyMove [key_move, kmov] string capability is the move key. KeyMove // The KeyNext [key_next, knxt] string capability is the next key. KeyNext // The KeyOpen [key_open, kopn] string capability is the open key. KeyOpen // The KeyOptions [key_options, kopt] string capability is the options key. KeyOptions // The KeyPrevious [key_previous, kprv] string capability is the previous key. KeyPrevious // The KeyPrint [key_print, kprt] string capability is the print key. KeyPrint // The KeyRedo [key_redo, krdo] string capability is the redo key. KeyRedo // The KeyReference [key_reference, kref] string capability is the reference key. KeyReference // The KeyRefresh [key_refresh, krfr] string capability is the refresh key. KeyRefresh // The KeyReplace [key_replace, krpl] string capability is the replace key. KeyReplace // The KeyRestart [key_restart, krst] string capability is the restart key. KeyRestart // The KeyResume [key_resume, kres] string capability is the resume key. KeyResume // The KeySave [key_save, ksav] string capability is the save key. KeySave // The KeySuspend [key_suspend, kspd] string capability is the suspend key. KeySuspend // The KeyUndo [key_undo, kund] string capability is the undo key. KeyUndo // The KeySbeg [key_sbeg, kBEG] string capability is the shifted begin key. KeySbeg // The KeyScancel [key_scancel, kCAN] string capability is the shifted cancel key. KeyScancel // The KeyScommand [key_scommand, kCMD] string capability is the shifted command key. KeyScommand // The KeyScopy [key_scopy, kCPY] string capability is the shifted copy key. KeyScopy // The KeyScreate [key_screate, kCRT] string capability is the shifted create key. KeyScreate // The KeySdc [key_sdc, kDC] string capability is the shifted delete-character key. KeySdc // The KeySdl [key_sdl, kDL] string capability is the shifted delete-line key. KeySdl // The KeySelect [key_select, kslt] string capability is the select key. KeySelect // The KeySend [key_send, kEND] string capability is the shifted end key. KeySend // The KeySeol [key_seol, kEOL] string capability is the shifted clear-to-end-of-line key. KeySeol // The KeySexit [key_sexit, kEXT] string capability is the shifted exit key. KeySexit // The KeySfind [key_sfind, kFND] string capability is the shifted find key. KeySfind // The KeyShelp [key_shelp, kHLP] string capability is the shifted help key. KeyShelp // The KeyShome [key_shome, kHOM] string capability is the shifted home key. KeyShome // The KeySic [key_sic, kIC] string capability is the shifted insert-character key. KeySic // The KeySleft [key_sleft, kLFT] string capability is the shifted left-arrow key. KeySleft // The KeySmessage [key_smessage, kMSG] string capability is the shifted message key. KeySmessage // The KeySmove [key_smove, kMOV] string capability is the shifted move key. KeySmove // The KeySnext [key_snext, kNXT] string capability is the shifted next key. KeySnext // The KeySoptions [key_soptions, kOPT] string capability is the shifted options key. KeySoptions // The KeySprevious [key_sprevious, kPRV] string capability is the shifted previous key. KeySprevious // The KeySprint [key_sprint, kPRT] string capability is the shifted print key. KeySprint // The KeySredo [key_sredo, kRDO] string capability is the shifted redo key. KeySredo // The KeySreplace [key_sreplace, kRPL] string capability is the shifted replace key. KeySreplace // The KeySright [key_sright, kRIT] string capability is the shifted right-arrow key. KeySright // The KeySrsume [key_srsume, kRES] string capability is the shifted resume key. KeySrsume // The KeySsave [key_ssave, kSAV] string capability is the shifted save key. KeySsave // The KeySsuspend [key_ssuspend, kSPD] string capability is the shifted suspend key. KeySsuspend // The KeySundo [key_sundo, kUND] string capability is the shifted undo key. KeySundo // The ReqForInput [req_for_input, rfi] string capability is the send next input char (for ptys). ReqForInput // The KeyF11 [key_f11, kf11] string capability is the F11 function key. KeyF11 // The KeyF12 [key_f12, kf12] string capability is the F12 function key. KeyF12 // The KeyF13 [key_f13, kf13] string capability is the F13 function key. KeyF13 // The KeyF14 [key_f14, kf14] string capability is the F14 function key. KeyF14 // The KeyF15 [key_f15, kf15] string capability is the F15 function key. KeyF15 // The KeyF16 [key_f16, kf16] string capability is the F16 function key. KeyF16 // The KeyF17 [key_f17, kf17] string capability is the F17 function key. KeyF17 // The KeyF18 [key_f18, kf18] string capability is the F18 function key. KeyF18 // The KeyF19 [key_f19, kf19] string capability is the F19 function key. KeyF19 // The KeyF20 [key_f20, kf20] string capability is the F20 function key. KeyF20 // The KeyF21 [key_f21, kf21] string capability is the F21 function key. KeyF21 // The KeyF22 [key_f22, kf22] string capability is the F22 function key. KeyF22 // The KeyF23 [key_f23, kf23] string capability is the F23 function key. KeyF23 // The KeyF24 [key_f24, kf24] string capability is the F24 function key. KeyF24 // The KeyF25 [key_f25, kf25] string capability is the F25 function key. KeyF25 // The KeyF26 [key_f26, kf26] string capability is the F26 function key. KeyF26 // The KeyF27 [key_f27, kf27] string capability is the F27 function key. KeyF27
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
true
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/xo/terminfo/util.go
vendor/github.com/xo/terminfo/util.go
package terminfo import ( "sort" ) const ( // maxFileLength is the max file length. maxFileLength = 4096 // magic is the file magic for terminfo files. magic = 0432 // magicExtended is the file magic for terminfo files with the extended number format. magicExtended = 01036 ) // header fields. const ( fieldMagic = iota fieldNameSize fieldBoolCount fieldNumCount fieldStringCount fieldTableSize ) // header extended fields. const ( fieldExtBoolCount = iota fieldExtNumCount fieldExtStringCount fieldExtOffsetCount fieldExtTableSize ) // hasInvalidCaps determines if the capabilities in h are invalid. func hasInvalidCaps(h []int) bool { return h[fieldBoolCount] > CapCountBool || h[fieldNumCount] > CapCountNum || h[fieldStringCount] > CapCountString } // capLength returns the total length of the capabilities in bytes. func capLength(h []int) int { return h[fieldNameSize] + h[fieldBoolCount] + (h[fieldNameSize]+h[fieldBoolCount])%2 + // account for word align h[fieldNumCount]*2 + h[fieldStringCount]*2 + h[fieldTableSize] } // hasInvalidExtOffset determines if the extended offset field is valid. func hasInvalidExtOffset(h []int) bool { return h[fieldExtBoolCount]+ h[fieldExtNumCount]+ h[fieldExtStringCount]*2 != h[fieldExtOffsetCount] } // extCapLength returns the total length of extended capabilities in bytes. func extCapLength(h []int, numWidth int) int { return h[fieldExtBoolCount] + h[fieldExtBoolCount]%2 + // account for word align h[fieldExtNumCount]*(numWidth/8) + h[fieldExtOffsetCount]*2 + h[fieldExtTableSize] } // findNull finds the position of null in buf. func findNull(buf []byte, i int) int { for ; i < len(buf); i++ { if buf[i] == 0 { return i } } return -1 } // readStrings decodes n strings from string data table buf using the indexes in idx. func readStrings(idx []int, buf []byte, n int) (map[int][]byte, int, error) { var last int m := make(map[int][]byte) for i := 0; i < n; i++ { start := idx[i] if start < 0 { continue } if end := findNull(buf, start); end != -1 { m[i], last = buf[start:end], end+1 } else { return nil, 0, ErrInvalidStringTable } } return m, last, nil } // decoder holds state info while decoding a terminfo file. type decoder struct { buf []byte pos int len int } // readBytes reads the next n bytes of buf, incrementing pos by n. func (d *decoder) readBytes(n int) ([]byte, error) { if d.len < d.pos+n { return nil, ErrUnexpectedFileEnd } n, d.pos = d.pos, d.pos+n return d.buf[n:d.pos], nil } // readInts reads n number of ints with width w. func (d *decoder) readInts(n, w int) ([]int, error) { w /= 8 l := n * w buf, err := d.readBytes(l) if err != nil { return nil, err } // align d.pos += d.pos % 2 z := make([]int, n) for i, j := 0, 0; i < l; i, j = i+w, j+1 { switch w { case 1: z[i] = int(buf[i]) case 2: z[j] = int(int16(buf[i+1])<<8 | int16(buf[i])) case 4: z[j] = int(buf[i+3])<<24 | int(buf[i+2])<<16 | int(buf[i+1])<<8 | int(buf[i]) } } return z, nil } // readBools reads the next n bools. func (d *decoder) readBools(n int) (map[int]bool, map[int]bool, error) { buf, err := d.readInts(n, 8) if err != nil { return nil, nil, err } // process bools, boolsM := make(map[int]bool), make(map[int]bool) for i, b := range buf { bools[i] = b == 1 if int8(b) == -2 { boolsM[i] = true } } return bools, boolsM, nil } // readNums reads the next n nums. func (d *decoder) readNums(n, w int) (map[int]int, map[int]bool, error) { buf, err := d.readInts(n, w) if err != nil { return nil, nil, err } // process nums, numsM := make(map[int]int), make(map[int]bool) for i := 0; i < n; i++ { nums[i] = buf[i] if buf[i] == -2 { numsM[i] = true } } return nums, numsM, nil } // readStringTable reads the string data for n strings and the accompanying data // table of length sz. func (d *decoder) readStringTable(n, sz int) ([][]byte, []int, error) { buf, err := d.readInts(n, 16) if err != nil { return nil, nil, err } // read string data table data, err := d.readBytes(sz) if err != nil { return nil, nil, err } // align d.pos += d.pos % 2 // process s := make([][]byte, n) var m []int for i := 0; i < n; i++ { start := buf[i] if start == -2 { m = append(m, i) } else if start >= 0 { if end := findNull(data, start); end != -1 { s[i] = data[start:end] } else { return nil, nil, ErrInvalidStringTable } } } return s, m, nil } // readStrings reads the next n strings and processes the string data table of // length sz. func (d *decoder) readStrings(n, sz int) (map[int][]byte, map[int]bool, error) { s, m, err := d.readStringTable(n, sz) if err != nil { return nil, nil, err } strs := make(map[int][]byte) for k, v := range s { if k == AcsChars { v = canonicalizeAscChars(v) } strs[k] = v } strsM := make(map[int]bool, len(m)) for _, k := range m { strsM[k] = true } return strs, strsM, nil } // canonicalizeAscChars reorders chars to be unique, in order. // // see repair_ascc in ncurses-6.0/progs/dump_entry.c func canonicalizeAscChars(z []byte) []byte { var c chars enc := make(map[byte]byte, len(z)/2) for i := 0; i < len(z); i += 2 { if _, ok := enc[z[i]]; !ok { a, b := z[i], z[i+1] //log.Printf(">>> a: %d %c, b: %d %c", a, a, b, b) c, enc[a] = append(c, b), b } } sort.Sort(c) r := make([]byte, 2*len(c)) for i := 0; i < len(c); i++ { r[i*2], r[i*2+1] = c[i], enc[c[i]] } return r } type chars []byte func (c chars) Len() int { return len(c) } func (c chars) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c chars) Less(i, j int) bool { return c[i] < c[j] }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/xo/terminfo/load.go
vendor/github.com/xo/terminfo/load.go
package terminfo import ( "os" "os/user" "path" "strings" "sync" ) // termCache is the terminfo cache. var termCache = struct { db map[string]*Terminfo sync.RWMutex }{ db: make(map[string]*Terminfo), } // Load follows the behavior described in terminfo(5) to find correct the // terminfo file using the name, reads the file and then returns a Terminfo // struct that describes the file. func Load(name string) (*Terminfo, error) { if name == "" { return nil, ErrEmptyTermName } termCache.RLock() ti, ok := termCache.db[name] termCache.RUnlock() if ok { return ti, nil } var checkDirs []string // check $TERMINFO if dir := os.Getenv("TERMINFO"); dir != "" { checkDirs = append(checkDirs, dir) } // check $HOME/.terminfo u, err := user.Current() if err != nil { return nil, err } checkDirs = append(checkDirs, path.Join(u.HomeDir, ".terminfo")) // check $TERMINFO_DIRS if dirs := os.Getenv("TERMINFO_DIRS"); dirs != "" { checkDirs = append(checkDirs, strings.Split(dirs, ":")...) } // check fallback directories checkDirs = append(checkDirs, "/etc/terminfo", "/lib/terminfo", "/usr/share/terminfo") for _, dir := range checkDirs { ti, err = Open(dir, name) if err != nil && err != ErrFileNotFound && !os.IsNotExist(err) { return nil, err } else if err == nil { return ti, nil } } return nil, ErrDatabaseDirectoryNotFound } // LoadFromEnv loads the terminal info based on the name contained in // environment variable TERM. func LoadFromEnv() (*Terminfo, error) { return Load(os.Getenv("TERM")) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/xo/terminfo/stack.go
vendor/github.com/xo/terminfo/stack.go
package terminfo type stack []interface{} func (s *stack) push(v interface{}) { *s = append(*s, v) } func (s *stack) pop() interface{} { if len(*s) == 0 { return nil } v := (*s)[len(*s)-1] *s = (*s)[:len(*s)-1] return v } func (s *stack) popInt() int { if i, ok := s.pop().(int); ok { return i } return 0 } func (s *stack) popBool() bool { if b, ok := s.pop().(bool); ok { return b } return false } func (s *stack) popByte() byte { if b, ok := s.pop().(byte); ok { return b } return 0 } func (s *stack) popString() string { if a, ok := s.pop().(string); ok { return a } return "" } func (s *stack) reset() { *s = (*s)[:0] }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/xo/terminfo/color.go
vendor/github.com/xo/terminfo/color.go
package terminfo import ( "os" "strconv" "strings" ) // ColorLevel is the color level supported by a terminal. type ColorLevel uint // ColorLevel values. const ( ColorLevelNone ColorLevel = iota ColorLevelBasic ColorLevelHundreds ColorLevelMillions ) // String satisfies the Stringer interface. func (c ColorLevel) String() string { switch c { case ColorLevelBasic: return "basic" case ColorLevelHundreds: return "hundreds" case ColorLevelMillions: return "millions" } return "none" } // ChromaFormatterName returns the github.com/alecthomas/chroma compatible // formatter name for the color level. func (c ColorLevel) ChromaFormatterName() string { switch c { case ColorLevelBasic: return "terminal" case ColorLevelHundreds: return "terminal256" case ColorLevelMillions: return "terminal16m" } return "noop" } // ColorLevelFromEnv returns the color level COLORTERM, FORCE_COLOR, // TERM_PROGRAM, or determined from the TERM environment variable. func ColorLevelFromEnv() (ColorLevel, error) { // check for overriding environment variables colorTerm, termProg, forceColor := os.Getenv("COLORTERM"), os.Getenv("TERM_PROGRAM"), os.Getenv("FORCE_COLOR") switch { case strings.Contains(colorTerm, "truecolor") || strings.Contains(colorTerm, "24bit") || termProg == "Hyper": return ColorLevelMillions, nil case colorTerm != "" || forceColor != "": return ColorLevelBasic, nil case termProg == "Apple_Terminal": return ColorLevelHundreds, nil case termProg == "iTerm.app": ver := os.Getenv("TERM_PROGRAM_VERSION") if ver == "" { return ColorLevelHundreds, nil } i, err := strconv.Atoi(strings.Split(ver, ".")[0]) if err != nil { return ColorLevelNone, ErrInvalidTermProgramVersion } if i == 3 { return ColorLevelMillions, nil } return ColorLevelHundreds, nil } // otherwise determine from TERM's max_colors capability if term := os.Getenv("TERM"); term != "" { ti, err := Load(term) if err != nil { return ColorLevelNone, err } v, ok := ti.Nums[MaxColors] switch { case !ok || v <= 16: return ColorLevelNone, nil case ok && v >= 256: return ColorLevelHundreds, nil } } return ColorLevelBasic, nil }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/xo/terminfo/param.go
vendor/github.com/xo/terminfo/param.go
package terminfo import ( "bytes" "fmt" "io" "strconv" "strings" "sync" ) // parametizer represents the a scan state for a parameterized string. type parametizer struct { // z is the string to parameterize z []byte // pos is the current position in s. pos int // nest is the current nest level. nest int // s is the variable stack. s stack // skipElse keeps the state of skipping else. skipElse bool // buf is the result buffer. buf *bytes.Buffer // params are the parameters to interpolate. params [9]interface{} // vars are dynamic variables. vars [26]interface{} } // staticVars are the static, global variables. var staticVars = struct { vars [26]interface{} sync.Mutex }{} var parametizerPool = sync.Pool{ New: func() interface{} { p := new(parametizer) p.buf = bytes.NewBuffer(make([]byte, 0, 45)) return p }, } // newParametizer returns a new initialized parametizer from the pool. func newParametizer(z []byte) *parametizer { p := parametizerPool.Get().(*parametizer) p.z = z return p } // reset resets the parametizer. func (p *parametizer) reset() { p.pos, p.nest = 0, 0 p.s.reset() p.buf.Reset() p.params, p.vars = [9]interface{}{}, [26]interface{}{} parametizerPool.Put(p) } // stateFn represents the state of the scanner as a function that returns the // next state. type stateFn func() stateFn // exec executes the parameterizer, interpolating the supplied parameters. func (p *parametizer) exec() string { for state := p.scanTextFn; state != nil; { state = state() } return p.buf.String() } // peek returns the next byte. func (p *parametizer) peek() (byte, error) { if p.pos >= len(p.z) { return 0, io.EOF } return p.z[p.pos], nil } // writeFrom writes the characters from ppos to pos to the buffer. func (p *parametizer) writeFrom(ppos int) { if p.pos > ppos { // append remaining characters. p.buf.Write(p.z[ppos:p.pos]) } } func (p *parametizer) scanTextFn() stateFn { ppos := p.pos for { ch, err := p.peek() if err != nil { p.writeFrom(ppos) return nil } if ch == '%' { p.writeFrom(ppos) p.pos++ return p.scanCodeFn } p.pos++ } } func (p *parametizer) scanCodeFn() stateFn { ch, err := p.peek() if err != nil { return nil } switch ch { case '%': p.buf.WriteByte('%') case ':': // this character is used to avoid interpreting "%-" and "%+" as operators. // the next character is where the format really begins. p.pos++ _, err = p.peek() if err != nil { return nil } return p.scanFormatFn case '#', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.': return p.scanFormatFn case 'o': p.buf.WriteString(strconv.FormatInt(int64(p.s.popInt()), 8)) case 'd': p.buf.WriteString(strconv.Itoa(p.s.popInt())) case 'x': p.buf.WriteString(strconv.FormatInt(int64(p.s.popInt()), 16)) case 'X': p.buf.WriteString(strings.ToUpper(strconv.FormatInt(int64(p.s.popInt()), 16))) case 's': p.buf.WriteString(p.s.popString()) case 'c': p.buf.WriteByte(p.s.popByte()) case 'p': p.pos++ return p.pushParamFn case 'P': p.pos++ return p.setDsVarFn case 'g': p.pos++ return p.getDsVarFn case '\'': p.pos++ ch, err = p.peek() if err != nil { return nil } p.s.push(ch) // skip the '\'' p.pos++ case '{': p.pos++ return p.pushIntfn case 'l': p.s.push(len(p.s.popString())) case '+': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai + bi) case '-': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai - bi) case '*': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai * bi) case '/': bi, ai := p.s.popInt(), p.s.popInt() if bi != 0 { p.s.push(ai / bi) } else { p.s.push(0) } case 'm': bi, ai := p.s.popInt(), p.s.popInt() if bi != 0 { p.s.push(ai % bi) } else { p.s.push(0) } case '&': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai & bi) case '|': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai | bi) case '^': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai ^ bi) case '=': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai == bi) case '>': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai > bi) case '<': bi, ai := p.s.popInt(), p.s.popInt() p.s.push(ai < bi) case 'A': bi, ai := p.s.popBool(), p.s.popBool() p.s.push(ai && bi) case 'O': bi, ai := p.s.popBool(), p.s.popBool() p.s.push(ai || bi) case '!': p.s.push(!p.s.popBool()) case '~': p.s.push(^p.s.popInt()) case 'i': for i := range p.params[:2] { if n, ok := p.params[i].(int); ok { p.params[i] = n + 1 } } case '?', ';': case 't': return p.scanThenFn case 'e': p.skipElse = true return p.skipTextFn } p.pos++ return p.scanTextFn } func (p *parametizer) scanFormatFn() stateFn { // the character was already read, so no need to check the error. ch, _ := p.peek() // 6 should be the maximum length of a format string, for example "%:-9.9d". f := []byte{'%', ch, 0, 0, 0, 0} var err error for { p.pos++ ch, err = p.peek() if err != nil { return nil } f = append(f, ch) switch ch { case 'o', 'd', 'x', 'X': fmt.Fprintf(p.buf, string(f), p.s.popInt()) break case 's': fmt.Fprintf(p.buf, string(f), p.s.popString()) break case 'c': fmt.Fprintf(p.buf, string(f), p.s.popByte()) break } } p.pos++ return p.scanTextFn } func (p *parametizer) pushParamFn() stateFn { ch, err := p.peek() if err != nil { return nil } if ai := int(ch - '1'); ai >= 0 && ai < len(p.params) { p.s.push(p.params[ai]) } else { p.s.push(0) } // skip the '}' p.pos++ return p.scanTextFn } func (p *parametizer) setDsVarFn() stateFn { ch, err := p.peek() if err != nil { return nil } if ch >= 'A' && ch <= 'Z' { staticVars.Lock() staticVars.vars[int(ch-'A')] = p.s.pop() staticVars.Unlock() } else if ch >= 'a' && ch <= 'z' { p.vars[int(ch-'a')] = p.s.pop() } p.pos++ return p.scanTextFn } func (p *parametizer) getDsVarFn() stateFn { ch, err := p.peek() if err != nil { return nil } var a byte if ch >= 'A' && ch <= 'Z' { a = 'A' } else if ch >= 'a' && ch <= 'z' { a = 'a' } staticVars.Lock() p.s.push(staticVars.vars[int(ch-a)]) staticVars.Unlock() p.pos++ return p.scanTextFn } func (p *parametizer) pushIntfn() stateFn { var ai int for { ch, err := p.peek() if err != nil { return nil } p.pos++ if ch < '0' || ch > '9' { p.s.push(ai) return p.scanTextFn } ai = (ai * 10) + int(ch-'0') } } func (p *parametizer) scanThenFn() stateFn { p.pos++ if p.s.popBool() { return p.scanTextFn } p.skipElse = false return p.skipTextFn } func (p *parametizer) skipTextFn() stateFn { for { ch, err := p.peek() if err != nil { return nil } p.pos++ if ch == '%' { break } } if p.skipElse { return p.skipElseFn } return p.skipThenFn } func (p *parametizer) skipThenFn() stateFn { ch, err := p.peek() if err != nil { return nil } p.pos++ switch ch { case ';': if p.nest == 0 { return p.scanTextFn } p.nest-- case '?': p.nest++ case 'e': if p.nest == 0 { return p.scanTextFn } } return p.skipTextFn } func (p *parametizer) skipElseFn() stateFn { ch, err := p.peek() if err != nil { return nil } p.pos++ switch ch { case ';': if p.nest == 0 { return p.scanTextFn } p.nest-- case '?': p.nest++ } return p.skipTextFn } // Printf evaluates a parameterized terminfo value z, interpolating params. func Printf(z []byte, params ...interface{}) string { p := newParametizer(z) defer p.reset() // make sure we always have 9 parameters -- makes it easier // later to skip checks and its faster for i := 0; i < len(p.params) && i < len(params); i++ { p.params[i] = params[i] } return p.exec() } // Fprintf evaluates a parameterized terminfo value z, interpolating params and // writing to w. func Fprintf(w io.Writer, z []byte, params ...interface{}) { w.Write([]byte(Printf(z, params...))) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/xo/terminfo/caps.go
vendor/github.com/xo/terminfo/caps.go
package terminfo //go:generate go run gen.go // BoolCapName returns the bool capability name. func BoolCapName(i int) string { return boolCapNames[2*i] } // BoolCapNameShort returns the short bool capability name. func BoolCapNameShort(i int) string { return boolCapNames[2*i+1] } // NumCapName returns the num capability name. func NumCapName(i int) string { return numCapNames[2*i] } // NumCapNameShort returns the short num capability name. func NumCapNameShort(i int) string { return numCapNames[2*i+1] } // StringCapName returns the string capability name. func StringCapName(i int) string { return stringCapNames[2*i] } // StringCapNameShort returns the short string capability name. func StringCapNameShort(i int) string { return stringCapNames[2*i+1] }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/go-logfmt/logfmt/jsonstring.go
vendor/github.com/go-logfmt/logfmt/jsonstring.go
package logfmt import ( "bytes" "io" "strconv" "sync" "unicode" "unicode/utf16" "unicode/utf8" ) // Taken from Go's encoding/json and modified for use here. // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. var hex = "0123456789abcdef" var bufferPool = sync.Pool{ New: func() interface{} { return &bytes.Buffer{} }, } func getBuffer() *bytes.Buffer { return bufferPool.Get().(*bytes.Buffer) } func poolBuffer(buf *bytes.Buffer) { buf.Reset() bufferPool.Put(buf) } // NOTE: keep in sync with writeQuotedBytes below. func writeQuotedString(w io.Writer, s string) (int, error) { buf := getBuffer() buf.WriteByte('"') start := 0 for i := 0; i < len(s); { if b := s[i]; b < utf8.RuneSelf { if 0x20 <= b && b != '\\' && b != '"' { i++ continue } if start < i { buf.WriteString(s[start:i]) } switch b { case '\\', '"': buf.WriteByte('\\') buf.WriteByte(b) case '\n': buf.WriteByte('\\') buf.WriteByte('n') case '\r': buf.WriteByte('\\') buf.WriteByte('r') case '\t': buf.WriteByte('\\') buf.WriteByte('t') default: // This encodes bytes < 0x20 except for \n, \r, and \t. buf.WriteString(`\u00`) buf.WriteByte(hex[b>>4]) buf.WriteByte(hex[b&0xF]) } i++ start = i continue } c, size := utf8.DecodeRuneInString(s[i:]) if c == utf8.RuneError { if start < i { buf.WriteString(s[start:i]) } buf.WriteString(`\ufffd`) i += size start = i continue } i += size } if start < len(s) { buf.WriteString(s[start:]) } buf.WriteByte('"') n, err := w.Write(buf.Bytes()) poolBuffer(buf) return n, err } // NOTE: keep in sync with writeQuoteString above. func writeQuotedBytes(w io.Writer, s []byte) (int, error) { buf := getBuffer() buf.WriteByte('"') start := 0 for i := 0; i < len(s); { if b := s[i]; b < utf8.RuneSelf { if 0x20 <= b && b != '\\' && b != '"' { i++ continue } if start < i { buf.Write(s[start:i]) } switch b { case '\\', '"': buf.WriteByte('\\') buf.WriteByte(b) case '\n': buf.WriteByte('\\') buf.WriteByte('n') case '\r': buf.WriteByte('\\') buf.WriteByte('r') case '\t': buf.WriteByte('\\') buf.WriteByte('t') default: // This encodes bytes < 0x20 except for \n, \r, and \t. buf.WriteString(`\u00`) buf.WriteByte(hex[b>>4]) buf.WriteByte(hex[b&0xF]) } i++ start = i continue } c, size := utf8.DecodeRune(s[i:]) if c == utf8.RuneError { if start < i { buf.Write(s[start:i]) } buf.WriteString(`\ufffd`) i += size start = i continue } i += size } if start < len(s) { buf.Write(s[start:]) } buf.WriteByte('"') n, err := w.Write(buf.Bytes()) poolBuffer(buf) return n, err } // getu4 decodes \uXXXX from the beginning of s, returning the hex value, // or it returns -1. func getu4(s []byte) rune { if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { return -1 } r, err := strconv.ParseUint(string(s[2:6]), 16, 64) if err != nil { return -1 } return rune(r) } func unquoteBytes(s []byte) (t []byte, ok bool) { if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { return } s = s[1 : len(s)-1] // Check for unusual characters. If there are none, // then no unquoting is needed, so return a slice of the // original bytes. r := 0 for r < len(s) { c := s[r] if c == '\\' || c == '"' || c < ' ' { break } if c < utf8.RuneSelf { r++ continue } rr, size := utf8.DecodeRune(s[r:]) if rr == utf8.RuneError { break } r += size } if r == len(s) { return s, true } b := make([]byte, len(s)+2*utf8.UTFMax) w := copy(b, s[0:r]) for r < len(s) { // Out of room? Can only happen if s is full of // malformed UTF-8 and we're replacing each // byte with RuneError. if w >= len(b)-2*utf8.UTFMax { nb := make([]byte, (len(b)+utf8.UTFMax)*2) copy(nb, b[0:w]) b = nb } switch c := s[r]; { case c == '\\': r++ if r >= len(s) { return } switch s[r] { default: return case '"', '\\', '/', '\'': b[w] = s[r] r++ w++ case 'b': b[w] = '\b' r++ w++ case 'f': b[w] = '\f' r++ w++ case 'n': b[w] = '\n' r++ w++ case 'r': b[w] = '\r' r++ w++ case 't': b[w] = '\t' r++ w++ case 'u': r-- rr := getu4(s[r:]) if rr < 0 { return } r += 6 if utf16.IsSurrogate(rr) { rr1 := getu4(s[r:]) if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { // A valid pair; consume. r += 6 w += utf8.EncodeRune(b[w:], dec) break } // Invalid surrogate; fall back to replacement rune. rr = unicode.ReplacementChar } w += utf8.EncodeRune(b[w:], rr) } // Quote, control characters are invalid. case c == '"', c < ' ': return // ASCII case c < utf8.RuneSelf: b[w] = c r++ w++ // Coerce to well-formed UTF-8. default: rr, size := utf8.DecodeRune(s[r:]) r += size w += utf8.EncodeRune(b[w:], rr) } } return b[0:w], true }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/go-logfmt/logfmt/encode.go
vendor/github.com/go-logfmt/logfmt/encode.go
package logfmt import ( "bytes" "encoding" "errors" "fmt" "io" "reflect" "strings" "unicode/utf8" ) // MarshalKeyvals returns the logfmt encoding of keyvals, a variadic sequence // of alternating keys and values. func MarshalKeyvals(keyvals ...interface{}) ([]byte, error) { buf := &bytes.Buffer{} if err := NewEncoder(buf).EncodeKeyvals(keyvals...); err != nil { return nil, err } return buf.Bytes(), nil } // An Encoder writes logfmt data to an output stream. type Encoder struct { w io.Writer scratch bytes.Buffer needSep bool } // NewEncoder returns a new encoder that writes to w. func NewEncoder(w io.Writer) *Encoder { return &Encoder{ w: w, } } var ( space = []byte(" ") equals = []byte("=") newline = []byte("\n") null = []byte("null") ) // EncodeKeyval writes the logfmt encoding of key and value to the stream. A // single space is written before the second and subsequent keys in a record. // Nothing is written if a non-nil error is returned. func (enc *Encoder) EncodeKeyval(key, value interface{}) error { enc.scratch.Reset() if enc.needSep { if _, err := enc.scratch.Write(space); err != nil { return err } } if err := writeKey(&enc.scratch, key); err != nil { return err } if _, err := enc.scratch.Write(equals); err != nil { return err } if err := writeValue(&enc.scratch, value); err != nil { return err } _, err := enc.w.Write(enc.scratch.Bytes()) enc.needSep = true return err } // EncodeKeyvals writes the logfmt encoding of keyvals to the stream. Keyvals // is a variadic sequence of alternating keys and values. Keys of unsupported // type are skipped along with their corresponding value. Values of // unsupported type or that cause a MarshalerError are replaced by their error // but do not cause EncodeKeyvals to return an error. If a non-nil error is // returned some key/value pairs may not have be written. func (enc *Encoder) EncodeKeyvals(keyvals ...interface{}) error { if len(keyvals) == 0 { return nil } if len(keyvals)%2 == 1 { keyvals = append(keyvals, nil) } for i := 0; i < len(keyvals); i += 2 { k, v := keyvals[i], keyvals[i+1] err := enc.EncodeKeyval(k, v) if err == ErrUnsupportedKeyType { continue } if _, ok := err.(*MarshalerError); ok || err == ErrUnsupportedValueType { v = err err = enc.EncodeKeyval(k, v) } if err != nil { return err } } return nil } // MarshalerError represents an error encountered while marshaling a value. type MarshalerError struct { Type reflect.Type Err error } func (e *MarshalerError) Error() string { return "error marshaling value of type " + e.Type.String() + ": " + e.Err.Error() } // ErrNilKey is returned by Marshal functions and Encoder methods if a key is // a nil interface or pointer value. var ErrNilKey = errors.New("nil key") // ErrInvalidKey is returned by Marshal functions and Encoder methods if, after // dropping invalid runes, a key is empty. var ErrInvalidKey = errors.New("invalid key") // ErrUnsupportedKeyType is returned by Encoder methods if a key has an // unsupported type. var ErrUnsupportedKeyType = errors.New("unsupported key type") // ErrUnsupportedValueType is returned by Encoder methods if a value has an // unsupported type. var ErrUnsupportedValueType = errors.New("unsupported value type") func writeKey(w io.Writer, key interface{}) error { if key == nil { return ErrNilKey } switch k := key.(type) { case string: return writeStringKey(w, k) case []byte: if k == nil { return ErrNilKey } return writeBytesKey(w, k) case encoding.TextMarshaler: kb, err := safeMarshal(k) if err != nil { return err } if kb == nil { return ErrNilKey } return writeBytesKey(w, kb) case fmt.Stringer: ks, ok := safeString(k) if !ok { return ErrNilKey } return writeStringKey(w, ks) default: rkey := reflect.ValueOf(key) switch rkey.Kind() { case reflect.Array, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Struct: return ErrUnsupportedKeyType case reflect.Ptr: if rkey.IsNil() { return ErrNilKey } return writeKey(w, rkey.Elem().Interface()) } return writeStringKey(w, fmt.Sprint(k)) } } // keyRuneFilter returns r for all valid key runes, and -1 for all invalid key // runes. When used as the mapping function for strings.Map and bytes.Map // functions it causes them to remove invalid key runes from strings or byte // slices respectively. func keyRuneFilter(r rune) rune { if r <= ' ' || r == '=' || r == '"' || r == utf8.RuneError { return -1 } return r } func writeStringKey(w io.Writer, key string) error { k := strings.Map(keyRuneFilter, key) if k == "" { return ErrInvalidKey } _, err := io.WriteString(w, k) return err } func writeBytesKey(w io.Writer, key []byte) error { k := bytes.Map(keyRuneFilter, key) if len(k) == 0 { return ErrInvalidKey } _, err := w.Write(k) return err } func writeValue(w io.Writer, value interface{}) error { switch v := value.(type) { case nil: return writeBytesValue(w, null) case string: return writeStringValue(w, v, true) case []byte: return writeBytesValue(w, v) case encoding.TextMarshaler: vb, err := safeMarshal(v) if err != nil { return err } if vb == nil { vb = null } return writeBytesValue(w, vb) case error: se, ok := safeError(v) return writeStringValue(w, se, ok) case fmt.Stringer: ss, ok := safeString(v) return writeStringValue(w, ss, ok) default: rvalue := reflect.ValueOf(value) switch rvalue.Kind() { case reflect.Array, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Struct: return ErrUnsupportedValueType case reflect.Ptr: if rvalue.IsNil() { return writeBytesValue(w, null) } return writeValue(w, rvalue.Elem().Interface()) } return writeStringValue(w, fmt.Sprint(v), true) } } func needsQuotedValueRune(r rune) bool { return r <= ' ' || r == '=' || r == '"' || r == utf8.RuneError } func writeStringValue(w io.Writer, value string, ok bool) error { var err error if ok && value == "null" { _, err = io.WriteString(w, `"null"`) } else if strings.IndexFunc(value, needsQuotedValueRune) != -1 { _, err = writeQuotedString(w, value) } else { _, err = io.WriteString(w, value) } return err } func writeBytesValue(w io.Writer, value []byte) error { var err error if bytes.IndexFunc(value, needsQuotedValueRune) != -1 { _, err = writeQuotedBytes(w, value) } else { _, err = w.Write(value) } return err } // EndRecord writes a newline character to the stream and resets the encoder // to the beginning of a new record. func (enc *Encoder) EndRecord() error { _, err := enc.w.Write(newline) if err == nil { enc.needSep = false } return err } // Reset resets the encoder to the beginning of a new record. func (enc *Encoder) Reset() { enc.needSep = false } func safeError(err error) (s string, ok bool) { defer func() { if panicVal := recover(); panicVal != nil { if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() { s, ok = "null", false } else { s, ok = fmt.Sprintf("PANIC:%v", panicVal), false } } }() s, ok = err.Error(), true return } func safeString(str fmt.Stringer) (s string, ok bool) { defer func() { if panicVal := recover(); panicVal != nil { if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() { s, ok = "null", false } else { s, ok = fmt.Sprintf("PANIC:%v", panicVal), true } } }() s, ok = str.String(), true return } func safeMarshal(tm encoding.TextMarshaler) (b []byte, err error) { defer func() { if panicVal := recover(); panicVal != nil { if v := reflect.ValueOf(tm); v.Kind() == reflect.Ptr && v.IsNil() { b, err = nil, nil } else { b, err = nil, fmt.Errorf("panic when marshalling: %s", panicVal) } } }() b, err = tm.MarshalText() if err != nil { return nil, &MarshalerError{ Type: reflect.TypeOf(tm), Err: err, } } return }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/go-logfmt/logfmt/doc.go
vendor/github.com/go-logfmt/logfmt/doc.go
// Package logfmt implements utilities to marshal and unmarshal data in the // logfmt format. The logfmt format records key/value pairs in a way that // balances readability for humans and simplicity of computer parsing. It is // most commonly used as a more human friendly alternative to JSON for // structured logging. package logfmt
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/go-logfmt/logfmt/decode.go
vendor/github.com/go-logfmt/logfmt/decode.go
package logfmt import ( "bufio" "bytes" "fmt" "io" "unicode/utf8" ) // A Decoder reads and decodes logfmt records from an input stream. type Decoder struct { pos int key []byte value []byte lineNum int s *bufio.Scanner err error } // NewDecoder returns a new decoder that reads from r. // // The decoder introduces its own buffering and may read data from r beyond // the logfmt records requested. func NewDecoder(r io.Reader) *Decoder { dec := &Decoder{ s: bufio.NewScanner(r), } return dec } // ScanRecord advances the Decoder to the next record, which can then be // parsed with the ScanKeyval method. It returns false when decoding stops, // either by reaching the end of the input or an error. After ScanRecord // returns false, the Err method will return any error that occurred during // decoding, except that if it was io.EOF, Err will return nil. func (dec *Decoder) ScanRecord() bool { if dec.err != nil { return false } if !dec.s.Scan() { dec.err = dec.s.Err() return false } dec.lineNum++ dec.pos = 0 return true } // ScanKeyval advances the Decoder to the next key/value pair of the current // record, which can then be retrieved with the Key and Value methods. It // returns false when decoding stops, either by reaching the end of the // current record or an error. func (dec *Decoder) ScanKeyval() bool { dec.key, dec.value = nil, nil if dec.err != nil { return false } line := dec.s.Bytes() // garbage for p, c := range line[dec.pos:] { if c > ' ' { dec.pos += p goto key } } dec.pos = len(line) return false key: const invalidKeyError = "invalid key" start, multibyte := dec.pos, false for p, c := range line[dec.pos:] { switch { case c == '=': dec.pos += p if dec.pos > start { dec.key = line[start:dec.pos] if multibyte && bytes.ContainsRune(dec.key, utf8.RuneError) { dec.syntaxError(invalidKeyError) return false } } if dec.key == nil { dec.unexpectedByte(c) return false } goto equal case c == '"': dec.pos += p dec.unexpectedByte(c) return false case c <= ' ': dec.pos += p if dec.pos > start { dec.key = line[start:dec.pos] if multibyte && bytes.ContainsRune(dec.key, utf8.RuneError) { dec.syntaxError(invalidKeyError) return false } } return true case c >= utf8.RuneSelf: multibyte = true } } dec.pos = len(line) if dec.pos > start { dec.key = line[start:dec.pos] if multibyte && bytes.ContainsRune(dec.key, utf8.RuneError) { dec.syntaxError(invalidKeyError) return false } } return true equal: dec.pos++ if dec.pos >= len(line) { return true } switch c := line[dec.pos]; { case c <= ' ': return true case c == '"': goto qvalue } // value start = dec.pos for p, c := range line[dec.pos:] { switch { case c == '=' || c == '"': dec.pos += p dec.unexpectedByte(c) return false case c <= ' ': dec.pos += p if dec.pos > start { dec.value = line[start:dec.pos] } return true } } dec.pos = len(line) if dec.pos > start { dec.value = line[start:dec.pos] } return true qvalue: const ( untermQuote = "unterminated quoted value" invalidQuote = "invalid quoted value" ) hasEsc, esc := false, false start = dec.pos for p, c := range line[dec.pos+1:] { switch { case esc: esc = false case c == '\\': hasEsc, esc = true, true case c == '"': dec.pos += p + 2 if hasEsc { v, ok := unquoteBytes(line[start:dec.pos]) if !ok { dec.syntaxError(invalidQuote) return false } dec.value = v } else { start++ end := dec.pos - 1 if end > start { dec.value = line[start:end] } } return true } } dec.pos = len(line) dec.syntaxError(untermQuote) return false } // Key returns the most recent key found by a call to ScanKeyval. The returned // slice may point to internal buffers and is only valid until the next call // to ScanRecord. It does no allocation. func (dec *Decoder) Key() []byte { return dec.key } // Value returns the most recent value found by a call to ScanKeyval. The // returned slice may point to internal buffers and is only valid until the // next call to ScanRecord. It does no allocation when the value has no // escape sequences. func (dec *Decoder) Value() []byte { return dec.value } // Err returns the first non-EOF error that was encountered by the Scanner. func (dec *Decoder) Err() error { return dec.err } func (dec *Decoder) syntaxError(msg string) { dec.err = &SyntaxError{ Msg: msg, Line: dec.lineNum, Pos: dec.pos + 1, } } func (dec *Decoder) unexpectedByte(c byte) { dec.err = &SyntaxError{ Msg: fmt.Sprintf("unexpected %q", c), Line: dec.lineNum, Pos: dec.pos + 1, } } // A SyntaxError represents a syntax error in the logfmt input stream. type SyntaxError struct { Msg string Line int Pos int } func (e *SyntaxError) Error() string { return fmt.Sprintf("logfmt syntax error at pos %d on line %d: %s", e.Pos, e.Line, e.Msg) }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/mailru/easyjson/jwriter/writer.go
vendor/github.com/mailru/easyjson/jwriter/writer.go
// Package jwriter contains a JSON writer. package jwriter import ( "io" "strconv" "unicode/utf8" "github.com/mailru/easyjson/buffer" ) // Flags describe various encoding options. The behavior may be actually implemented in the encoder, but // Flags field in Writer is used to set and pass them around. type Flags int const ( NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. ) // Writer is a JSON writer. type Writer struct { Flags Flags Error error Buffer buffer.Buffer NoEscapeHTML bool } // Size returns the size of the data that was written out. func (w *Writer) Size() int { return w.Buffer.Size() } // DumpTo outputs the data to given io.Writer, resetting the buffer. func (w *Writer) DumpTo(out io.Writer) (written int, err error) { return w.Buffer.DumpTo(out) } // BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice // as argument that it will try to reuse. func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { if w.Error != nil { return nil, w.Error } return w.Buffer.BuildBytes(reuse...), nil } // ReadCloser returns an io.ReadCloser that can be used to read the data. // ReadCloser also resets the buffer. func (w *Writer) ReadCloser() (io.ReadCloser, error) { if w.Error != nil { return nil, w.Error } return w.Buffer.ReadCloser(), nil } // RawByte appends raw binary data to the buffer. func (w *Writer) RawByte(c byte) { w.Buffer.AppendByte(c) } // RawByte appends raw binary data to the buffer. func (w *Writer) RawString(s string) { w.Buffer.AppendString(s) } // Raw appends raw binary data to the buffer or sets the error if it is given. Useful for // calling with results of MarshalJSON-like functions. func (w *Writer) Raw(data []byte, err error) { switch { case w.Error != nil: return case err != nil: w.Error = err case len(data) > 0: w.Buffer.AppendBytes(data) default: w.RawString("null") } } // RawText encloses raw binary data in quotes and appends in to the buffer. // Useful for calling with results of MarshalText-like functions. func (w *Writer) RawText(data []byte, err error) { switch { case w.Error != nil: return case err != nil: w.Error = err case len(data) > 0: w.String(string(data)) default: w.RawString("null") } } // Base64Bytes appends data to the buffer after base64 encoding it func (w *Writer) Base64Bytes(data []byte) { if data == nil { w.Buffer.AppendString("null") return } w.Buffer.AppendByte('"') w.base64(data) w.Buffer.AppendByte('"') } func (w *Writer) Uint8(n uint8) { w.Buffer.EnsureSpace(3) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) } func (w *Writer) Uint16(n uint16) { w.Buffer.EnsureSpace(5) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) } func (w *Writer) Uint32(n uint32) { w.Buffer.EnsureSpace(10) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) } func (w *Writer) Uint(n uint) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) } func (w *Writer) Uint64(n uint64) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) } func (w *Writer) Int8(n int8) { w.Buffer.EnsureSpace(4) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) } func (w *Writer) Int16(n int16) { w.Buffer.EnsureSpace(6) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) } func (w *Writer) Int32(n int32) { w.Buffer.EnsureSpace(11) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) } func (w *Writer) Int(n int) { w.Buffer.EnsureSpace(21) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) } func (w *Writer) Int64(n int64) { w.Buffer.EnsureSpace(21) w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) } func (w *Writer) Uint8Str(n uint8) { w.Buffer.EnsureSpace(3) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Uint16Str(n uint16) { w.Buffer.EnsureSpace(5) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Uint32Str(n uint32) { w.Buffer.EnsureSpace(10) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) UintStr(n uint) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Uint64Str(n uint64) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) UintptrStr(n uintptr) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Int8Str(n int8) { w.Buffer.EnsureSpace(4) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Int16Str(n int16) { w.Buffer.EnsureSpace(6) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Int32Str(n int32) { w.Buffer.EnsureSpace(11) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) IntStr(n int) { w.Buffer.EnsureSpace(21) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Int64Str(n int64) { w.Buffer.EnsureSpace(21) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Float32(n float32) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) } func (w *Writer) Float32Str(n float32) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Float64(n float64) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) } func (w *Writer) Float64Str(n float64) { w.Buffer.EnsureSpace(20) w.Buffer.Buf = append(w.Buffer.Buf, '"') w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 64) w.Buffer.Buf = append(w.Buffer.Buf, '"') } func (w *Writer) Bool(v bool) { w.Buffer.EnsureSpace(5) if v { w.Buffer.Buf = append(w.Buffer.Buf, "true"...) } else { w.Buffer.Buf = append(w.Buffer.Buf, "false"...) } } const chars = "0123456789abcdef" func getTable(falseValues ...int) [128]bool { table := [128]bool{} for i := 0; i < 128; i++ { table[i] = true } for _, v := range falseValues { table[v] = false } return table } var ( htmlEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '&', '<', '>', '\\') htmlNoEscapeTable = getTable(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '\\') ) func (w *Writer) String(s string) { w.Buffer.AppendByte('"') // Portions of the string that contain no escapes are appended as // byte slices. p := 0 // last non-escape symbol escapeTable := &htmlEscapeTable if w.NoEscapeHTML { escapeTable = &htmlNoEscapeTable } for i := 0; i < len(s); { c := s[i] if c < utf8.RuneSelf { if escapeTable[c] { // single-width character, no escaping is required i++ continue } w.Buffer.AppendString(s[p:i]) switch c { case '\t': w.Buffer.AppendString(`\t`) case '\r': w.Buffer.AppendString(`\r`) case '\n': w.Buffer.AppendString(`\n`) case '\\': w.Buffer.AppendString(`\\`) case '"': w.Buffer.AppendString(`\"`) default: w.Buffer.AppendString(`\u00`) w.Buffer.AppendByte(chars[c>>4]) w.Buffer.AppendByte(chars[c&0xf]) } i++ p = i continue } // broken utf runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) if runeValue == utf8.RuneError && runeWidth == 1 { w.Buffer.AppendString(s[p:i]) w.Buffer.AppendString(`\ufffd`) i++ p = i continue } // jsonp stuff - tab separator and line separator if runeValue == '\u2028' || runeValue == '\u2029' { w.Buffer.AppendString(s[p:i]) w.Buffer.AppendString(`\u202`) w.Buffer.AppendByte(chars[runeValue&0xf]) i += runeWidth p = i continue } i += runeWidth } w.Buffer.AppendString(s[p:]) w.Buffer.AppendByte('"') } const encode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" const padChar = '=' func (w *Writer) base64(in []byte) { if len(in) == 0 { return } w.Buffer.EnsureSpace(((len(in)-1)/3 + 1) * 4) si := 0 n := (len(in) / 3) * 3 for si < n { // Convert 3x 8bit source bytes into 4 bytes val := uint(in[si+0])<<16 | uint(in[si+1])<<8 | uint(in[si+2]) w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F], encode[val>>6&0x3F], encode[val&0x3F]) si += 3 } remain := len(in) - si if remain == 0 { return } // Add the remaining small block val := uint(in[si+0]) << 16 if remain == 2 { val |= uint(in[si+1]) << 8 } w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>18&0x3F], encode[val>>12&0x3F]) switch remain { case 2: w.Buffer.Buf = append(w.Buffer.Buf, encode[val>>6&0x3F], byte(padChar)) case 1: w.Buffer.Buf = append(w.Buffer.Buf, byte(padChar), byte(padChar)) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/mailru/easyjson/buffer/pool.go
vendor/github.com/mailru/easyjson/buffer/pool.go
// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to // reduce copying and to allow reuse of individual chunks. package buffer import ( "io" "net" "sync" ) // PoolConfig contains configuration for the allocation and reuse strategy. type PoolConfig struct { StartSize int // Minimum chunk size that is allocated. PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. MaxSize int // Maximum chunk size that will be allocated. } var config = PoolConfig{ StartSize: 128, PooledSize: 512, MaxSize: 32768, } // Reuse pool: chunk size -> pool. var buffers = map[int]*sync.Pool{} func initBuffers() { for l := config.PooledSize; l <= config.MaxSize; l *= 2 { buffers[l] = new(sync.Pool) } } func init() { initBuffers() } // Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. func Init(cfg PoolConfig) { config = cfg initBuffers() } // putBuf puts a chunk to reuse pool if it can be reused. func putBuf(buf []byte) { size := cap(buf) if size < config.PooledSize { return } if c := buffers[size]; c != nil { c.Put(buf[:0]) } } // getBuf gets a chunk from reuse pool or creates a new one if reuse failed. func getBuf(size int) []byte { if size >= config.PooledSize { if c := buffers[size]; c != nil { v := c.Get() if v != nil { return v.([]byte) } } } return make([]byte, 0, size) } // Buffer is a buffer optimized for serialization without extra copying. type Buffer struct { // Buf is the current chunk that can be used for serialization. Buf []byte toPool []byte bufs [][]byte } // EnsureSpace makes sure that the current chunk contains at least s free bytes, // possibly creating a new chunk. func (b *Buffer) EnsureSpace(s int) { if cap(b.Buf)-len(b.Buf) < s { b.ensureSpaceSlow(s) } } func (b *Buffer) ensureSpaceSlow(s int) { l := len(b.Buf) if l > 0 { if cap(b.toPool) != cap(b.Buf) { // Chunk was reallocated, toPool can be pooled. putBuf(b.toPool) } if cap(b.bufs) == 0 { b.bufs = make([][]byte, 0, 8) } b.bufs = append(b.bufs, b.Buf) l = cap(b.toPool) * 2 } else { l = config.StartSize } if l > config.MaxSize { l = config.MaxSize } b.Buf = getBuf(l) b.toPool = b.Buf } // AppendByte appends a single byte to buffer. func (b *Buffer) AppendByte(data byte) { b.EnsureSpace(1) b.Buf = append(b.Buf, data) } // AppendBytes appends a byte slice to buffer. func (b *Buffer) AppendBytes(data []byte) { if len(data) <= cap(b.Buf)-len(b.Buf) { b.Buf = append(b.Buf, data...) // fast path } else { b.appendBytesSlow(data) } } func (b *Buffer) appendBytesSlow(data []byte) { for len(data) > 0 { b.EnsureSpace(1) sz := cap(b.Buf) - len(b.Buf) if sz > len(data) { sz = len(data) } b.Buf = append(b.Buf, data[:sz]...) data = data[sz:] } } // AppendString appends a string to buffer. func (b *Buffer) AppendString(data string) { if len(data) <= cap(b.Buf)-len(b.Buf) { b.Buf = append(b.Buf, data...) // fast path } else { b.appendStringSlow(data) } } func (b *Buffer) appendStringSlow(data string) { for len(data) > 0 { b.EnsureSpace(1) sz := cap(b.Buf) - len(b.Buf) if sz > len(data) { sz = len(data) } b.Buf = append(b.Buf, data[:sz]...) data = data[sz:] } } // Size computes the size of a buffer by adding sizes of every chunk. func (b *Buffer) Size() int { size := len(b.Buf) for _, buf := range b.bufs { size += len(buf) } return size } // DumpTo outputs the contents of a buffer to a writer and resets the buffer. func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { bufs := net.Buffers(b.bufs) if len(b.Buf) > 0 { bufs = append(bufs, b.Buf) } n, err := bufs.WriteTo(w) for _, buf := range b.bufs { putBuf(buf) } putBuf(b.toPool) b.bufs = nil b.Buf = nil b.toPool = nil return int(n), err } // BuildBytes creates a single byte slice with all the contents of the buffer. Data is // copied if it does not fit in a single chunk. You can optionally provide one byte // slice as argument that it will try to reuse. func (b *Buffer) BuildBytes(reuse ...[]byte) []byte { if len(b.bufs) == 0 { ret := b.Buf b.toPool = nil b.Buf = nil return ret } var ret []byte size := b.Size() // If we got a buffer as argument and it is big enough, reuse it. if len(reuse) == 1 && cap(reuse[0]) >= size { ret = reuse[0][:0] } else { ret = make([]byte, 0, size) } for _, buf := range b.bufs { ret = append(ret, buf...) putBuf(buf) } ret = append(ret, b.Buf...) putBuf(b.toPool) b.bufs = nil b.toPool = nil b.Buf = nil return ret } type readCloser struct { offset int bufs [][]byte } func (r *readCloser) Read(p []byte) (n int, err error) { for _, buf := range r.bufs { // Copy as much as we can. x := copy(p[n:], buf[r.offset:]) n += x // Increment how much we filled. // Did we empty the whole buffer? if r.offset+x == len(buf) { // On to the next buffer. r.offset = 0 r.bufs = r.bufs[1:] // We can release this buffer. putBuf(buf) } else { r.offset += x } if n == len(p) { break } } // No buffers left or nothing read? if len(r.bufs) == 0 { err = io.EOF } return } func (r *readCloser) Close() error { // Release all remaining buffers. for _, buf := range r.bufs { putBuf(buf) } // In case Close gets called multiple times. r.bufs = nil return nil } // ReadCloser creates an io.ReadCloser with all the contents of the buffer. func (b *Buffer) ReadCloser() io.ReadCloser { ret := &readCloser{0, append(b.bufs, b.Buf)} b.bufs = nil b.toPool = nil b.Buf = nil return ret }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/kevinburke/ssh_config/parser.go
vendor/github.com/kevinburke/ssh_config/parser.go
package ssh_config import ( "fmt" "strings" "unicode" ) type sshParser struct { flow chan token config *Config tokensBuffer []token currentTable []string seenTableKeys []string // /etc/ssh parser or local parser - used to find the default for relative // filepaths in the Include directive system bool depth uint8 } type sshParserStateFn func() sshParserStateFn // Formats and panics an error message based on a token func (p *sshParser) raiseErrorf(tok *token, msg string, args ...interface{}) { // TODO this format is ugly panic(tok.Position.String() + ": " + fmt.Sprintf(msg, args...)) } func (p *sshParser) raiseError(tok *token, err error) { if err == ErrDepthExceeded { panic(err) } // TODO this format is ugly panic(tok.Position.String() + ": " + err.Error()) } func (p *sshParser) run() { for state := p.parseStart; state != nil; { state = state() } } func (p *sshParser) peek() *token { if len(p.tokensBuffer) != 0 { return &(p.tokensBuffer[0]) } tok, ok := <-p.flow if !ok { return nil } p.tokensBuffer = append(p.tokensBuffer, tok) return &tok } func (p *sshParser) getToken() *token { if len(p.tokensBuffer) != 0 { tok := p.tokensBuffer[0] p.tokensBuffer = p.tokensBuffer[1:] return &tok } tok, ok := <-p.flow if !ok { return nil } return &tok } func (p *sshParser) parseStart() sshParserStateFn { tok := p.peek() // end of stream, parsing is finished if tok == nil { return nil } switch tok.typ { case tokenComment, tokenEmptyLine: return p.parseComment case tokenKey: return p.parseKV case tokenEOF: return nil default: p.raiseErrorf(tok, fmt.Sprintf("unexpected token %q\n", tok)) } return nil } func (p *sshParser) parseKV() sshParserStateFn { key := p.getToken() hasEquals := false val := p.getToken() if val.typ == tokenEquals { hasEquals = true val = p.getToken() } comment := "" tok := p.peek() if tok == nil { tok = &token{typ: tokenEOF} } if tok.typ == tokenComment && tok.Position.Line == val.Position.Line { tok = p.getToken() comment = tok.val } if strings.ToLower(key.val) == "match" { // https://github.com/kevinburke/ssh_config/issues/6 p.raiseErrorf(val, "ssh_config: Match directive parsing is unsupported") return nil } if strings.ToLower(key.val) == "host" { strPatterns := strings.Split(val.val, " ") patterns := make([]*Pattern, 0) for i := range strPatterns { if strPatterns[i] == "" { continue } pat, err := NewPattern(strPatterns[i]) if err != nil { p.raiseErrorf(val, "Invalid host pattern: %v", err) return nil } patterns = append(patterns, pat) } // val.val at this point could be e.g. "example.com " hostval := strings.TrimRightFunc(val.val, unicode.IsSpace) spaceBeforeComment := val.val[len(hostval):] val.val = hostval p.config.Hosts = append(p.config.Hosts, &Host{ Patterns: patterns, Nodes: make([]Node, 0), EOLComment: comment, spaceBeforeComment: spaceBeforeComment, hasEquals: hasEquals, }) return p.parseStart } lastHost := p.config.Hosts[len(p.config.Hosts)-1] if strings.ToLower(key.val) == "include" { inc, err := NewInclude(strings.Split(val.val, " "), hasEquals, key.Position, comment, p.system, p.depth+1) if err == ErrDepthExceeded { p.raiseError(val, err) return nil } if err != nil { p.raiseErrorf(val, "Error parsing Include directive: %v", err) return nil } lastHost.Nodes = append(lastHost.Nodes, inc) return p.parseStart } shortval := strings.TrimRightFunc(val.val, unicode.IsSpace) spaceAfterValue := val.val[len(shortval):] kv := &KV{ Key: key.val, Value: shortval, spaceAfterValue: spaceAfterValue, Comment: comment, hasEquals: hasEquals, leadingSpace: key.Position.Col - 1, position: key.Position, } lastHost.Nodes = append(lastHost.Nodes, kv) return p.parseStart } func (p *sshParser) parseComment() sshParserStateFn { comment := p.getToken() lastHost := p.config.Hosts[len(p.config.Hosts)-1] lastHost.Nodes = append(lastHost.Nodes, &Empty{ Comment: comment.val, // account for the "#" as well leadingSpace: comment.Position.Col - 2, position: comment.Position, }) return p.parseStart } func parseSSH(flow chan token, system bool, depth uint8) *Config { // Ensure we consume tokens to completion even if parser exits early defer func() { for range flow { } }() result := newConfig() result.position = Position{1, 1} parser := &sshParser{ flow: flow, config: result, tokensBuffer: make([]token, 0), currentTable: make([]string, 0), seenTableKeys: make([]string, 0), system: system, depth: depth, } parser.run() return result }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/kevinburke/ssh_config/lexer.go
vendor/github.com/kevinburke/ssh_config/lexer.go
package ssh_config import ( "bytes" ) // Define state functions type sshLexStateFn func() sshLexStateFn type sshLexer struct { inputIdx int input []rune // Textual source buffer []rune // Runes composing the current token tokens chan token line int col int endbufferLine int endbufferCol int } func (s *sshLexer) lexComment(previousState sshLexStateFn) sshLexStateFn { return func() sshLexStateFn { growingString := "" for next := s.peek(); next != '\n' && next != eof; next = s.peek() { if next == '\r' && s.follow("\r\n") { break } growingString += string(next) s.next() } s.emitWithValue(tokenComment, growingString) s.skip() return previousState } } // lex the space after an equals sign in a function func (s *sshLexer) lexRspace() sshLexStateFn { for { next := s.peek() if !isSpace(next) { break } s.skip() } return s.lexRvalue } func (s *sshLexer) lexEquals() sshLexStateFn { for { next := s.peek() if next == '=' { s.emit(tokenEquals) s.skip() return s.lexRspace } // TODO error handling here; newline eof etc. if !isSpace(next) { break } s.skip() } return s.lexRvalue } func (s *sshLexer) lexKey() sshLexStateFn { growingString := "" for r := s.peek(); isKeyChar(r); r = s.peek() { // simplified a lot here if isSpace(r) || r == '=' { s.emitWithValue(tokenKey, growingString) s.skip() return s.lexEquals } growingString += string(r) s.next() } s.emitWithValue(tokenKey, growingString) return s.lexEquals } func (s *sshLexer) lexRvalue() sshLexStateFn { growingString := "" for { next := s.peek() switch next { case '\r': if s.follow("\r\n") { s.emitWithValue(tokenString, growingString) s.skip() return s.lexVoid } case '\n': s.emitWithValue(tokenString, growingString) s.skip() return s.lexVoid case '#': s.emitWithValue(tokenString, growingString) s.skip() return s.lexComment(s.lexVoid) case eof: s.next() } if next == eof { break } growingString += string(next) s.next() } s.emit(tokenEOF) return nil } func (s *sshLexer) read() rune { r := s.peek() if r == '\n' { s.endbufferLine++ s.endbufferCol = 1 } else { s.endbufferCol++ } s.inputIdx++ return r } func (s *sshLexer) next() rune { r := s.read() if r != eof { s.buffer = append(s.buffer, r) } return r } func (s *sshLexer) lexVoid() sshLexStateFn { for { next := s.peek() switch next { case '#': s.skip() return s.lexComment(s.lexVoid) case '\r': fallthrough case '\n': s.emit(tokenEmptyLine) s.skip() continue } if isSpace(next) { s.skip() } if isKeyStartChar(next) { return s.lexKey } // removed IsKeyStartChar and lexKey. probably will need to readd if next == eof { s.next() break } } s.emit(tokenEOF) return nil } func (s *sshLexer) ignore() { s.buffer = make([]rune, 0) s.line = s.endbufferLine s.col = s.endbufferCol } func (s *sshLexer) skip() { s.next() s.ignore() } func (s *sshLexer) emit(t tokenType) { s.emitWithValue(t, string(s.buffer)) } func (s *sshLexer) emitWithValue(t tokenType, value string) { tok := token{ Position: Position{s.line, s.col}, typ: t, val: value, } s.tokens <- tok s.ignore() } func (s *sshLexer) peek() rune { if s.inputIdx >= len(s.input) { return eof } r := s.input[s.inputIdx] return r } func (s *sshLexer) follow(next string) bool { inputIdx := s.inputIdx for _, expectedRune := range next { if inputIdx >= len(s.input) { return false } r := s.input[inputIdx] inputIdx++ if expectedRune != r { return false } } return true } func (s *sshLexer) run() { for state := s.lexVoid; state != nil; { state = state() } close(s.tokens) } func lexSSH(input []byte) chan token { runes := bytes.Runes(input) l := &sshLexer{ input: runes, tokens: make(chan token), line: 1, col: 1, endbufferLine: 1, endbufferCol: 1, } go l.run() return l.tokens }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/kevinburke/ssh_config/validators.go
vendor/github.com/kevinburke/ssh_config/validators.go
package ssh_config import ( "fmt" "strconv" "strings" ) // Default returns the default value for the given keyword, for example "22" if // the keyword is "Port". Default returns the empty string if the keyword has no // default, or if the keyword is unknown. Keyword matching is case-insensitive. // // Default values are provided by OpenSSH_7.4p1 on a Mac. func Default(keyword string) string { return defaults[strings.ToLower(keyword)] } // Arguments where the value must be "yes" or "no" and *only* yes or no. var yesnos = map[string]bool{ strings.ToLower("BatchMode"): true, strings.ToLower("CanonicalizeFallbackLocal"): true, strings.ToLower("ChallengeResponseAuthentication"): true, strings.ToLower("CheckHostIP"): true, strings.ToLower("ClearAllForwardings"): true, strings.ToLower("Compression"): true, strings.ToLower("EnableSSHKeysign"): true, strings.ToLower("ExitOnForwardFailure"): true, strings.ToLower("ForwardAgent"): true, strings.ToLower("ForwardX11"): true, strings.ToLower("ForwardX11Trusted"): true, strings.ToLower("GatewayPorts"): true, strings.ToLower("GSSAPIAuthentication"): true, strings.ToLower("GSSAPIDelegateCredentials"): true, strings.ToLower("HostbasedAuthentication"): true, strings.ToLower("IdentitiesOnly"): true, strings.ToLower("KbdInteractiveAuthentication"): true, strings.ToLower("NoHostAuthenticationForLocalhost"): true, strings.ToLower("PasswordAuthentication"): true, strings.ToLower("PermitLocalCommand"): true, strings.ToLower("PubkeyAuthentication"): true, strings.ToLower("RhostsRSAAuthentication"): true, strings.ToLower("RSAAuthentication"): true, strings.ToLower("StreamLocalBindUnlink"): true, strings.ToLower("TCPKeepAlive"): true, strings.ToLower("UseKeychain"): true, strings.ToLower("UsePrivilegedPort"): true, strings.ToLower("VisualHostKey"): true, } var uints = map[string]bool{ strings.ToLower("CanonicalizeMaxDots"): true, strings.ToLower("CompressionLevel"): true, // 1 to 9 strings.ToLower("ConnectionAttempts"): true, strings.ToLower("ConnectTimeout"): true, strings.ToLower("NumberOfPasswordPrompts"): true, strings.ToLower("Port"): true, strings.ToLower("ServerAliveCountMax"): true, strings.ToLower("ServerAliveInterval"): true, } func mustBeYesOrNo(lkey string) bool { return yesnos[lkey] } func mustBeUint(lkey string) bool { return uints[lkey] } func validate(key, val string) error { lkey := strings.ToLower(key) if mustBeYesOrNo(lkey) && (val != "yes" && val != "no") { return fmt.Errorf("ssh_config: value for key %q must be 'yes' or 'no', got %q", key, val) } if mustBeUint(lkey) { _, err := strconv.ParseUint(val, 10, 64) if err != nil { return fmt.Errorf("ssh_config: %v", err) } } return nil } var defaults = map[string]string{ strings.ToLower("AddKeysToAgent"): "no", strings.ToLower("AddressFamily"): "any", strings.ToLower("BatchMode"): "no", strings.ToLower("CanonicalizeFallbackLocal"): "yes", strings.ToLower("CanonicalizeHostname"): "no", strings.ToLower("CanonicalizeMaxDots"): "1", strings.ToLower("ChallengeResponseAuthentication"): "yes", strings.ToLower("CheckHostIP"): "yes", // TODO is this still the correct cipher strings.ToLower("Cipher"): "3des", strings.ToLower("Ciphers"): "chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc", strings.ToLower("ClearAllForwardings"): "no", strings.ToLower("Compression"): "no", strings.ToLower("CompressionLevel"): "6", strings.ToLower("ConnectionAttempts"): "1", strings.ToLower("ControlMaster"): "no", strings.ToLower("EnableSSHKeysign"): "no", strings.ToLower("EscapeChar"): "~", strings.ToLower("ExitOnForwardFailure"): "no", strings.ToLower("FingerprintHash"): "sha256", strings.ToLower("ForwardAgent"): "no", strings.ToLower("ForwardX11"): "no", strings.ToLower("ForwardX11Timeout"): "20m", strings.ToLower("ForwardX11Trusted"): "no", strings.ToLower("GatewayPorts"): "no", strings.ToLower("GlobalKnownHostsFile"): "/etc/ssh/ssh_known_hosts /etc/ssh/ssh_known_hosts2", strings.ToLower("GSSAPIAuthentication"): "no", strings.ToLower("GSSAPIDelegateCredentials"): "no", strings.ToLower("HashKnownHosts"): "no", strings.ToLower("HostbasedAuthentication"): "no", strings.ToLower("HostbasedKeyTypes"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", strings.ToLower("HostKeyAlgorithms"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", // HostName has a dynamic default (the value passed at the command line). strings.ToLower("IdentitiesOnly"): "no", strings.ToLower("IdentityFile"): "~/.ssh/identity", // IPQoS has a dynamic default based on interactive or non-interactive // sessions. strings.ToLower("KbdInteractiveAuthentication"): "yes", strings.ToLower("KexAlgorithms"): "curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1", strings.ToLower("LogLevel"): "INFO", strings.ToLower("MACs"): "umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1", strings.ToLower("NoHostAuthenticationForLocalhost"): "no", strings.ToLower("NumberOfPasswordPrompts"): "3", strings.ToLower("PasswordAuthentication"): "yes", strings.ToLower("PermitLocalCommand"): "no", strings.ToLower("Port"): "22", strings.ToLower("PreferredAuthentications"): "gssapi-with-mic,hostbased,publickey,keyboard-interactive,password", strings.ToLower("Protocol"): "2", strings.ToLower("ProxyUseFdpass"): "no", strings.ToLower("PubkeyAcceptedKeyTypes"): "ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-rsa", strings.ToLower("PubkeyAuthentication"): "yes", strings.ToLower("RekeyLimit"): "default none", strings.ToLower("RhostsRSAAuthentication"): "no", strings.ToLower("RSAAuthentication"): "yes", strings.ToLower("ServerAliveCountMax"): "3", strings.ToLower("ServerAliveInterval"): "0", strings.ToLower("StreamLocalBindMask"): "0177", strings.ToLower("StreamLocalBindUnlink"): "no", strings.ToLower("StrictHostKeyChecking"): "ask", strings.ToLower("TCPKeepAlive"): "yes", strings.ToLower("Tunnel"): "no", strings.ToLower("TunnelDevice"): "any:any", strings.ToLower("UpdateHostKeys"): "no", strings.ToLower("UseKeychain"): "no", strings.ToLower("UsePrivilegedPort"): "no", strings.ToLower("UserKnownHostsFile"): "~/.ssh/known_hosts ~/.ssh/known_hosts2", strings.ToLower("VerifyHostKeyDNS"): "no", strings.ToLower("VisualHostKey"): "no", strings.ToLower("XAuthLocation"): "/usr/X11R6/bin/xauth", } // these identities are used for SSH protocol 2 var defaultProtocol2Identities = []string{ "~/.ssh/id_dsa", "~/.ssh/id_ecdsa", "~/.ssh/id_ed25519", "~/.ssh/id_rsa", } // these directives support multiple items that can be collected // across multiple files var pluralDirectives = map[string]bool{ "CertificateFile": true, "IdentityFile": true, "DynamicForward": true, "RemoteForward": true, "SendEnv": true, "SetEnv": true, } // SupportsMultiple reports whether a directive can be specified multiple times. func SupportsMultiple(key string) bool { return pluralDirectives[strings.ToLower(key)] }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/kevinburke/ssh_config/token.go
vendor/github.com/kevinburke/ssh_config/token.go
package ssh_config import "fmt" type token struct { Position typ tokenType val string } func (t token) String() string { switch t.typ { case tokenEOF: return "EOF" } return fmt.Sprintf("%q", t.val) } type tokenType int const ( eof = -(iota + 1) ) const ( tokenError tokenType = iota tokenEOF tokenEmptyLine tokenComment tokenKey tokenEquals tokenString ) func isSpace(r rune) bool { return r == ' ' || r == '\t' } func isKeyStartChar(r rune) bool { return !(isSpace(r) || r == '\r' || r == '\n' || r == eof) } // I'm not sure that this is correct func isKeyChar(r rune) bool { // Keys start with the first character that isn't whitespace or [ and end // with the last non-whitespace character before the equals sign. Keys // cannot contain a # character." return !(r == '\r' || r == '\n' || r == eof || r == '=') }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/kevinburke/ssh_config/config.go
vendor/github.com/kevinburke/ssh_config/config.go
// Package ssh_config provides tools for manipulating SSH config files. // // Importantly, this parser attempts to preserve comments in a given file, so // you can manipulate a `ssh_config` file from a program, if your heart desires. // // The Get() and GetStrict() functions will attempt to read values from // $HOME/.ssh/config, falling back to /etc/ssh/ssh_config. The first argument is // the host name to match on ("example.com"), and the second argument is the key // you want to retrieve ("Port"). The keywords are case insensitive. // // port := ssh_config.Get("myhost", "Port") // // You can also manipulate an SSH config file and then print it or write it back // to disk. // // f, _ := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "config")) // cfg, _ := ssh_config.Decode(f) // for _, host := range cfg.Hosts { // fmt.Println("patterns:", host.Patterns) // for _, node := range host.Nodes { // fmt.Println(node.String()) // } // } // // // Write the cfg back to disk: // fmt.Println(cfg.String()) // // BUG: the Match directive is currently unsupported; parsing a config with // a Match directive will trigger an error. package ssh_config import ( "bytes" "errors" "fmt" "io" "os" osuser "os/user" "path/filepath" "regexp" "runtime" "strings" "sync" ) const version = "1.2" var _ = version type configFinder func() string // UserSettings checks ~/.ssh and /etc/ssh for configuration files. The config // files are parsed and cached the first time Get() or GetStrict() is called. type UserSettings struct { IgnoreErrors bool systemConfig *Config systemConfigFinder configFinder userConfig *Config userConfigFinder configFinder loadConfigs sync.Once onceErr error } func homedir() string { user, err := osuser.Current() if err == nil { return user.HomeDir } else { return os.Getenv("HOME") } } func userConfigFinder() string { return filepath.Join(homedir(), ".ssh", "config") } // DefaultUserSettings is the default UserSettings and is used by Get and // GetStrict. It checks both $HOME/.ssh/config and /etc/ssh/ssh_config for keys, // and it will return parse errors (if any) instead of swallowing them. var DefaultUserSettings = &UserSettings{ IgnoreErrors: false, systemConfigFinder: systemConfigFinder, userConfigFinder: userConfigFinder, } func systemConfigFinder() string { return filepath.Join("/", "etc", "ssh", "ssh_config") } func findVal(c *Config, alias, key string) (string, error) { if c == nil { return "", nil } val, err := c.Get(alias, key) if err != nil || val == "" { return "", err } if err := validate(key, val); err != nil { return "", err } return val, nil } func findAll(c *Config, alias, key string) ([]string, error) { if c == nil { return nil, nil } return c.GetAll(alias, key) } // Get finds the first value for key within a declaration that matches the // alias. Get returns the empty string if no value was found, or if IgnoreErrors // is false and we could not parse the configuration file. Use GetStrict to // disambiguate the latter cases. // // The match for key is case insensitive. // // Get is a wrapper around DefaultUserSettings.Get. func Get(alias, key string) string { return DefaultUserSettings.Get(alias, key) } // GetAll retrieves zero or more directives for key for the given alias. GetAll // returns nil if no value was found, or if IgnoreErrors is false and we could // not parse the configuration file. Use GetAllStrict to disambiguate the // latter cases. // // In most cases you want to use Get or GetStrict, which returns a single value. // However, a subset of ssh configuration values (IdentityFile, for example) // allow you to specify multiple directives. // // The match for key is case insensitive. // // GetAll is a wrapper around DefaultUserSettings.GetAll. func GetAll(alias, key string) []string { return DefaultUserSettings.GetAll(alias, key) } // GetStrict finds the first value for key within a declaration that matches the // alias. If key has a default value and no matching configuration is found, the // default will be returned. For more information on default values and the way // patterns are matched, see the manpage for ssh_config. // // The returned error will be non-nil if and only if a user's configuration file // or the system configuration file could not be parsed, and u.IgnoreErrors is // false. // // GetStrict is a wrapper around DefaultUserSettings.GetStrict. func GetStrict(alias, key string) (string, error) { return DefaultUserSettings.GetStrict(alias, key) } // GetAllStrict retrieves zero or more directives for key for the given alias. // // In most cases you want to use Get or GetStrict, which returns a single value. // However, a subset of ssh configuration values (IdentityFile, for example) // allow you to specify multiple directives. // // The returned error will be non-nil if and only if a user's configuration file // or the system configuration file could not be parsed, and u.IgnoreErrors is // false. // // GetAllStrict is a wrapper around DefaultUserSettings.GetAllStrict. func GetAllStrict(alias, key string) ([]string, error) { return DefaultUserSettings.GetAllStrict(alias, key) } // Get finds the first value for key within a declaration that matches the // alias. Get returns the empty string if no value was found, or if IgnoreErrors // is false and we could not parse the configuration file. Use GetStrict to // disambiguate the latter cases. // // The match for key is case insensitive. func (u *UserSettings) Get(alias, key string) string { val, err := u.GetStrict(alias, key) if err != nil { return "" } return val } // GetAll retrieves zero or more directives for key for the given alias. GetAll // returns nil if no value was found, or if IgnoreErrors is false and we could // not parse the configuration file. Use GetStrict to disambiguate the latter // cases. // // The match for key is case insensitive. func (u *UserSettings) GetAll(alias, key string) []string { val, _ := u.GetAllStrict(alias, key) return val } // GetStrict finds the first value for key within a declaration that matches the // alias. If key has a default value and no matching configuration is found, the // default will be returned. For more information on default values and the way // patterns are matched, see the manpage for ssh_config. // // error will be non-nil if and only if a user's configuration file or the // system configuration file could not be parsed, and u.IgnoreErrors is false. func (u *UserSettings) GetStrict(alias, key string) (string, error) { u.doLoadConfigs() //lint:ignore S1002 I prefer it this way if u.onceErr != nil && u.IgnoreErrors == false { return "", u.onceErr } val, err := findVal(u.userConfig, alias, key) if err != nil || val != "" { return val, err } val2, err2 := findVal(u.systemConfig, alias, key) if err2 != nil || val2 != "" { return val2, err2 } return Default(key), nil } // GetAllStrict retrieves zero or more directives for key for the given alias. // If key has a default value and no matching configuration is found, the // default will be returned. For more information on default values and the way // patterns are matched, see the manpage for ssh_config. // // The returned error will be non-nil if and only if a user's configuration file // or the system configuration file could not be parsed, and u.IgnoreErrors is // false. func (u *UserSettings) GetAllStrict(alias, key string) ([]string, error) { u.doLoadConfigs() //lint:ignore S1002 I prefer it this way if u.onceErr != nil && u.IgnoreErrors == false { return nil, u.onceErr } val, err := findAll(u.userConfig, alias, key) if err != nil || val != nil { return val, err } val2, err2 := findAll(u.systemConfig, alias, key) if err2 != nil || val2 != nil { return val2, err2 } // TODO: IdentityFile has multiple default values that we should return. if def := Default(key); def != "" { return []string{def}, nil } return []string{}, nil } func (u *UserSettings) doLoadConfigs() { u.loadConfigs.Do(func() { // can't parse user file, that's ok. var filename string if u.userConfigFinder == nil { filename = userConfigFinder() } else { filename = u.userConfigFinder() } var err error u.userConfig, err = parseFile(filename) //lint:ignore S1002 I prefer it this way if err != nil && os.IsNotExist(err) == false { u.onceErr = err return } if u.systemConfigFinder == nil { filename = systemConfigFinder() } else { filename = u.systemConfigFinder() } u.systemConfig, err = parseFile(filename) //lint:ignore S1002 I prefer it this way if err != nil && os.IsNotExist(err) == false { u.onceErr = err return } }) } func parseFile(filename string) (*Config, error) { return parseWithDepth(filename, 0) } func parseWithDepth(filename string, depth uint8) (*Config, error) { b, err := os.ReadFile(filename) if err != nil { return nil, err } return decodeBytes(b, isSystem(filename), depth) } func isSystem(filename string) bool { // TODO: not sure this is the best way to detect a system repo return strings.HasPrefix(filepath.Clean(filename), "/etc/ssh") } // Decode reads r into a Config, or returns an error if r could not be parsed as // an SSH config file. func Decode(r io.Reader) (*Config, error) { b, err := io.ReadAll(r) if err != nil { return nil, err } return decodeBytes(b, false, 0) } // DecodeBytes reads b into a Config, or returns an error if r could not be // parsed as an SSH config file. func DecodeBytes(b []byte) (*Config, error) { return decodeBytes(b, false, 0) } func decodeBytes(b []byte, system bool, depth uint8) (c *Config, err error) { defer func() { if r := recover(); r != nil { if _, ok := r.(runtime.Error); ok { panic(r) } if e, ok := r.(error); ok && e == ErrDepthExceeded { err = e return } err = errors.New(r.(string)) } }() c = parseSSH(lexSSH(b), system, depth) return c, err } // Config represents an SSH config file. type Config struct { // A list of hosts to match against. The file begins with an implicit // "Host *" declaration matching all hosts. Hosts []*Host depth uint8 position Position } // Get finds the first value in the configuration that matches the alias and // contains key. Get returns the empty string if no value was found, or if the // Config contains an invalid conditional Include value. // // The match for key is case insensitive. func (c *Config) Get(alias, key string) (string, error) { lowerKey := strings.ToLower(key) for _, host := range c.Hosts { if !host.Matches(alias) { continue } for _, node := range host.Nodes { switch t := node.(type) { case *Empty: continue case *KV: // "keys are case insensitive" per the spec lkey := strings.ToLower(t.Key) if lkey == "match" { panic("can't handle Match directives") } if lkey == lowerKey { return t.Value, nil } case *Include: val := t.Get(alias, key) if val != "" { return val, nil } default: return "", fmt.Errorf("unknown Node type %v", t) } } } return "", nil } // GetAll returns all values in the configuration that match the alias and // contains key, or nil if none are present. func (c *Config) GetAll(alias, key string) ([]string, error) { lowerKey := strings.ToLower(key) all := []string(nil) for _, host := range c.Hosts { if !host.Matches(alias) { continue } for _, node := range host.Nodes { switch t := node.(type) { case *Empty: continue case *KV: // "keys are case insensitive" per the spec lkey := strings.ToLower(t.Key) if lkey == "match" { panic("can't handle Match directives") } if lkey == lowerKey { all = append(all, t.Value) } case *Include: val, _ := t.GetAll(alias, key) if len(val) > 0 { all = append(all, val...) } default: return nil, fmt.Errorf("unknown Node type %v", t) } } } return all, nil } // String returns a string representation of the Config file. func (c Config) String() string { return marshal(c).String() } func (c Config) MarshalText() ([]byte, error) { return marshal(c).Bytes(), nil } func marshal(c Config) *bytes.Buffer { var buf bytes.Buffer for i := range c.Hosts { buf.WriteString(c.Hosts[i].String()) } return &buf } // Pattern is a pattern in a Host declaration. Patterns are read-only values; // create a new one with NewPattern(). type Pattern struct { str string // Its appearance in the file, not the value that gets compiled. regex *regexp.Regexp not bool // True if this is a negated match } // String prints the string representation of the pattern. func (p Pattern) String() string { return p.str } // Copied from regexp.go with * and ? removed. var specialBytes = []byte(`\.+()|[]{}^$`) func special(b byte) bool { return bytes.IndexByte(specialBytes, b) >= 0 } // NewPattern creates a new Pattern for matching hosts. NewPattern("*") creates // a Pattern that matches all hosts. // // From the manpage, a pattern consists of zero or more non-whitespace // characters, `*' (a wildcard that matches zero or more characters), or `?' (a // wildcard that matches exactly one character). For example, to specify a set // of declarations for any host in the ".co.uk" set of domains, the following // pattern could be used: // // Host *.co.uk // // The following pattern would match any host in the 192.168.0.[0-9] network range: // // Host 192.168.0.? func NewPattern(s string) (*Pattern, error) { if s == "" { return nil, errors.New("ssh_config: empty pattern") } negated := false if s[0] == '!' { negated = true s = s[1:] } var buf bytes.Buffer buf.WriteByte('^') for i := 0; i < len(s); i++ { // A byte loop is correct because all metacharacters are ASCII. switch b := s[i]; b { case '*': buf.WriteString(".*") case '?': buf.WriteString(".?") default: // borrowing from QuoteMeta here. if special(b) { buf.WriteByte('\\') } buf.WriteByte(b) } } buf.WriteByte('$') r, err := regexp.Compile(buf.String()) if err != nil { return nil, err } return &Pattern{str: s, regex: r, not: negated}, nil } // Host describes a Host directive and the keywords that follow it. type Host struct { // A list of host patterns that should match this host. Patterns []*Pattern // A Node is either a key/value pair or a comment line. Nodes []Node // EOLComment is the comment (if any) terminating the Host line. EOLComment string // Whitespace if any between the Host declaration and a trailing comment. spaceBeforeComment string hasEquals bool leadingSpace int // TODO: handle spaces vs tabs here. // The file starts with an implicit "Host *" declaration. implicit bool } // Matches returns true if the Host matches for the given alias. For // a description of the rules that provide a match, see the manpage for // ssh_config. func (h *Host) Matches(alias string) bool { found := false for i := range h.Patterns { if h.Patterns[i].regex.MatchString(alias) { if h.Patterns[i].not { // Negated match. "A pattern entry may be negated by prefixing // it with an exclamation mark (`!'). If a negated entry is // matched, then the Host entry is ignored, regardless of // whether any other patterns on the line match. Negated matches // are therefore useful to provide exceptions for wildcard // matches." return false } found = true } } return found } // String prints h as it would appear in a config file. Minor tweaks may be // present in the whitespace in the printed file. func (h *Host) String() string { var buf strings.Builder //lint:ignore S1002 I prefer to write it this way if h.implicit == false { buf.WriteString(strings.Repeat(" ", int(h.leadingSpace))) buf.WriteString("Host") if h.hasEquals { buf.WriteString(" = ") } else { buf.WriteString(" ") } for i, pat := range h.Patterns { buf.WriteString(pat.String()) if i < len(h.Patterns)-1 { buf.WriteString(" ") } } buf.WriteString(h.spaceBeforeComment) if h.EOLComment != "" { buf.WriteByte('#') buf.WriteString(h.EOLComment) } buf.WriteByte('\n') } for i := range h.Nodes { buf.WriteString(h.Nodes[i].String()) buf.WriteByte('\n') } return buf.String() } // Node represents a line in a Config. type Node interface { Pos() Position String() string } // KV is a line in the config file that contains a key, a value, and possibly // a comment. type KV struct { Key string Value string // Whitespace after the value but before any comment spaceAfterValue string Comment string hasEquals bool leadingSpace int // Space before the key. TODO handle spaces vs tabs. position Position } // Pos returns k's Position. func (k *KV) Pos() Position { return k.position } // String prints k as it was parsed in the config file. func (k *KV) String() string { if k == nil { return "" } equals := " " if k.hasEquals { equals = " = " } line := strings.Repeat(" ", int(k.leadingSpace)) + k.Key + equals + k.Value + k.spaceAfterValue if k.Comment != "" { line += "#" + k.Comment } return line } // Empty is a line in the config file that contains only whitespace or comments. type Empty struct { Comment string leadingSpace int // TODO handle spaces vs tabs. position Position } // Pos returns e's Position. func (e *Empty) Pos() Position { return e.position } // String prints e as it was parsed in the config file. func (e *Empty) String() string { if e == nil { return "" } if e.Comment == "" { return "" } return fmt.Sprintf("%s#%s", strings.Repeat(" ", int(e.leadingSpace)), e.Comment) } // Include holds the result of an Include directive, including the config files // that have been parsed as part of that directive. At most 5 levels of Include // statements will be parsed. type Include struct { // Comment is the contents of any comment at the end of the Include // statement. Comment string // an include directive can include several different files, and wildcards directives []string mu sync.Mutex // 1:1 mapping between matches and keys in files array; matches preserves // ordering matches []string // actual filenames are listed here files map[string]*Config leadingSpace int position Position depth uint8 hasEquals bool } const maxRecurseDepth = 5 // ErrDepthExceeded is returned if too many Include directives are parsed. // Usually this indicates a recursive loop (an Include directive pointing to the // file it contains). var ErrDepthExceeded = errors.New("ssh_config: max recurse depth exceeded") func removeDups(arr []string) []string { // Use map to record duplicates as we find them. encountered := make(map[string]bool, len(arr)) result := make([]string, 0) for v := range arr { //lint:ignore S1002 I prefer it this way if encountered[arr[v]] == false { encountered[arr[v]] = true result = append(result, arr[v]) } } return result } // NewInclude creates a new Include with a list of file globs to include. // Configuration files are parsed greedily (e.g. as soon as this function runs). // Any error encountered while parsing nested configuration files will be // returned. func NewInclude(directives []string, hasEquals bool, pos Position, comment string, system bool, depth uint8) (*Include, error) { if depth > maxRecurseDepth { return nil, ErrDepthExceeded } inc := &Include{ Comment: comment, directives: directives, files: make(map[string]*Config), position: pos, leadingSpace: pos.Col - 1, depth: depth, hasEquals: hasEquals, } // no need for inc.mu.Lock() since nothing else can access this inc matches := make([]string, 0) for i := range directives { var path string if filepath.IsAbs(directives[i]) { path = directives[i] } else if system { path = filepath.Join("/etc/ssh", directives[i]) } else { path = filepath.Join(homedir(), ".ssh", directives[i]) } theseMatches, err := filepath.Glob(path) if err != nil { return nil, err } matches = append(matches, theseMatches...) } matches = removeDups(matches) inc.matches = matches for i := range matches { config, err := parseWithDepth(matches[i], depth) if err != nil { return nil, err } inc.files[matches[i]] = config } return inc, nil } // Pos returns the position of the Include directive in the larger file. func (i *Include) Pos() Position { return i.position } // Get finds the first value in the Include statement matching the alias and the // given key. func (inc *Include) Get(alias, key string) string { inc.mu.Lock() defer inc.mu.Unlock() // TODO: we search files in any order which is not correct for i := range inc.matches { cfg := inc.files[inc.matches[i]] if cfg == nil { panic("nil cfg") } val, err := cfg.Get(alias, key) if err == nil && val != "" { return val } } return "" } // GetAll finds all values in the Include statement matching the alias and the // given key. func (inc *Include) GetAll(alias, key string) ([]string, error) { inc.mu.Lock() defer inc.mu.Unlock() var vals []string // TODO: we search files in any order which is not correct for i := range inc.matches { cfg := inc.files[inc.matches[i]] if cfg == nil { panic("nil cfg") } val, err := cfg.GetAll(alias, key) if err == nil && len(val) != 0 { // In theory if SupportsMultiple was false for this key we could // stop looking here. But the caller has asked us to find all // instances of the keyword (and could use Get() if they wanted) so // let's keep looking. vals = append(vals, val...) } } return vals, nil } // String prints out a string representation of this Include directive. Note // included Config files are not printed as part of this representation. func (inc *Include) String() string { equals := " " if inc.hasEquals { equals = " = " } line := fmt.Sprintf("%sInclude%s%s", strings.Repeat(" ", int(inc.leadingSpace)), equals, strings.Join(inc.directives, " ")) if inc.Comment != "" { line += " #" + inc.Comment } return line } var matchAll *Pattern func init() { var err error matchAll, err = NewPattern("*") if err != nil { panic(err) } } func newConfig() *Config { return &Config{ Hosts: []*Host{ &Host{ implicit: true, Patterns: []*Pattern{matchAll}, Nodes: make([]Node, 0), }, }, depth: 0, } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/kevinburke/ssh_config/position.go
vendor/github.com/kevinburke/ssh_config/position.go
package ssh_config import "fmt" // Position of a document element within a SSH document. // // Line and Col are both 1-indexed positions for the element's line number and // column number, respectively. Values of zero or less will cause Invalid(), // to return true. type Position struct { Line int // line within the document Col int // column within the line } // String representation of the position. // Displays 1-indexed line and column numbers. func (p Position) String() string { return fmt.Sprintf("(%d, %d)", p.Line, p.Col) } // Invalid returns whether or not the position is valid (i.e. with negative or // null values) func (p Position) Invalid() bool { return p.Line <= 0 || p.Col <= 0 }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/integrii/flaggy/flag.go
vendor/github.com/integrii/flaggy/flag.go
package flaggy import ( "errors" "fmt" "net" "reflect" "strconv" "strings" "time" ) // Flag holds the base methods for all flag types type Flag struct { ShortName string LongName string Description string rawValue string // the value as a string before being parsed Hidden bool // indicates this flag should be hidden from help and suggestions AssignmentVar interface{} defaultValue string // the value (as a string), that was set by default before any parsing and assignment parsed bool // indicates that this flag has already been parsed } // HasName indicates that this flag's short or long name matches the // supplied name string func (f *Flag) HasName(name string) bool { name = strings.TrimSpace(name) if f.ShortName == name || f.LongName == name { return true } return false } // identifyAndAssignValue identifies the type of the incoming value // and assigns it to the AssignmentVar pointer's target value. If // the value is a type that needs parsing, that is performed as well. func (f *Flag) identifyAndAssignValue(value string) error { var err error // Only parse this flag default value once. This keeps us from // overwriting the default value in help output if !f.parsed { f.parsed = true // parse the default value as a string and remember it for help output f.defaultValue, err = f.returnAssignmentVarValueAsString() if err != nil { return err } } debugPrint("attempting to assign value", value, "to flag", f.LongName) f.rawValue = value // remember the raw value // depending on the type of the assignment variable, we convert the // incoming string and assign it. We only use pointers to variables // in flagy. No returning vars by value. switch f.AssignmentVar.(type) { case *string: v, _ := (f.AssignmentVar).(*string) *v = value case *[]string: v := f.AssignmentVar.(*[]string) splitString := strings.Split(value, ",") new := append(*v, splitString...) *v = new case *bool: v, err := strconv.ParseBool(value) if err != nil { return err } a, _ := (f.AssignmentVar).(*bool) *a = v case *[]bool: // parse the incoming bool b, err := strconv.ParseBool(value) if err != nil { return err } // cast the assignment var existing := f.AssignmentVar.(*[]bool) // deref the assignment var and append to it v := append(*existing, b) // pointer the new value and assign it a, _ := (f.AssignmentVar).(*[]bool) *a = v case *time.Duration: v, err := time.ParseDuration(value) if err != nil { return err } a, _ := (f.AssignmentVar).(*time.Duration) *a = v case *[]time.Duration: t, err := time.ParseDuration(value) if err != nil { return err } existing := f.AssignmentVar.(*[]time.Duration) // deref the assignment var and append to it v := append(*existing, t) // pointer the new value and assign it a, _ := (f.AssignmentVar).(*[]time.Duration) *a = v case *float32: v, err := strconv.ParseFloat(value, 32) if err != nil { return err } float := float32(v) a, _ := (f.AssignmentVar).(*float32) *a = float case *[]float32: v, err := strconv.ParseFloat(value, 32) if err != nil { return err } float := float32(v) existing := f.AssignmentVar.(*[]float32) new := append(*existing, float) *existing = new case *float64: v, err := strconv.ParseFloat(value, 64) if err != nil { return err } a, _ := (f.AssignmentVar).(*float64) *a = v case *[]float64: v, err := strconv.ParseFloat(value, 64) if err != nil { return err } existing := f.AssignmentVar.(*[]float64) new := append(*existing, v) *existing = new case *int: v, err := strconv.Atoi(value) if err != nil { return err } e := f.AssignmentVar.(*int) *e = v case *[]int: v, err := strconv.Atoi(value) if err != nil { return err } existing := f.AssignmentVar.(*[]int) new := append(*existing, v) *existing = new case *uint: v, err := strconv.ParseUint(value, 10, 64) if err != nil { return err } existing := f.AssignmentVar.(*uint) *existing = uint(v) case *[]uint: v, err := strconv.ParseUint(value, 10, 64) if err != nil { return err } existing := f.AssignmentVar.(*[]uint) new := append(*existing, uint(v)) *existing = new case *uint64: v, err := strconv.ParseUint(value, 10, 64) if err != nil { return err } existing := f.AssignmentVar.(*uint64) *existing = v case *[]uint64: v, err := strconv.ParseUint(value, 10, 64) if err != nil { return err } existing := f.AssignmentVar.(*[]uint64) new := append(*existing, v) *existing = new case *uint32: v, err := strconv.ParseUint(value, 10, 32) if err != nil { return err } existing := f.AssignmentVar.(*uint32) *existing = uint32(v) case *[]uint32: v, err := strconv.ParseUint(value, 10, 32) if err != nil { return err } existing := f.AssignmentVar.(*[]uint32) new := append(*existing, uint32(v)) *existing = new case *uint16: v, err := strconv.ParseUint(value, 10, 16) if err != nil { return err } val := uint16(v) existing := f.AssignmentVar.(*uint16) *existing = val case *[]uint16: v, err := strconv.ParseUint(value, 10, 16) if err != nil { return err } existing := f.AssignmentVar.(*[]uint16) new := append(*existing, uint16(v)) *existing = new case *uint8: v, err := strconv.ParseUint(value, 10, 8) if err != nil { return err } val := uint8(v) existing := f.AssignmentVar.(*uint8) *existing = val case *[]uint8: var newSlice []uint8 v, err := strconv.ParseUint(value, 10, 8) if err != nil { return err } newV := uint8(v) existing := f.AssignmentVar.(*[]uint8) newSlice = append(*existing, newV) *existing = newSlice case *int64: v, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } existing := f.AssignmentVar.(*int64) *existing = v case *[]int64: v, err := strconv.ParseInt(value, 10, 64) if err != nil { return err } existingSlice := f.AssignmentVar.(*[]int64) newSlice := append(*existingSlice, v) *existingSlice = newSlice case *int32: v, err := strconv.ParseInt(value, 10, 32) if err != nil { return err } converted := int32(v) existing := f.AssignmentVar.(*int32) *existing = converted case *[]int32: v, err := strconv.ParseInt(value, 10, 32) if err != nil { return err } existingSlice := f.AssignmentVar.(*[]int32) newSlice := append(*existingSlice, int32(v)) *existingSlice = newSlice case *int16: v, err := strconv.ParseInt(value, 10, 16) if err != nil { return err } converted := int16(v) existing := f.AssignmentVar.(*int16) *existing = converted case *[]int16: v, err := strconv.ParseInt(value, 10, 16) if err != nil { return err } existingSlice := f.AssignmentVar.(*[]int16) newSlice := append(*existingSlice, int16(v)) *existingSlice = newSlice case *int8: v, err := strconv.ParseInt(value, 10, 8) if err != nil { return err } converted := int8(v) existing := f.AssignmentVar.(*int8) *existing = converted case *[]int8: v, err := strconv.ParseInt(value, 10, 8) if err != nil { return err } existingSlice := f.AssignmentVar.(*[]int8) newSlice := append(*existingSlice, int8(v)) *existingSlice = newSlice case *net.IP: v := net.ParseIP(value) existing := f.AssignmentVar.(*net.IP) *existing = v case *[]net.IP: v := net.ParseIP(value) existing := f.AssignmentVar.(*[]net.IP) new := append(*existing, v) *existing = new case *net.HardwareAddr: v, err := net.ParseMAC(value) if err != nil { return err } existing := f.AssignmentVar.(*net.HardwareAddr) *existing = v case *[]net.HardwareAddr: v, err := net.ParseMAC(value) if err != nil { return err } existing := f.AssignmentVar.(*[]net.HardwareAddr) new := append(*existing, v) *existing = new case *net.IPMask: v := net.IPMask(net.ParseIP(value).To4()) existing := f.AssignmentVar.(*net.IPMask) *existing = v case *[]net.IPMask: v := net.IPMask(net.ParseIP(value).To4()) existing := f.AssignmentVar.(*[]net.IPMask) new := append(*existing, v) *existing = new default: return errors.New("Unknown flag assignmentVar supplied in flag " + f.LongName + " " + f.ShortName) } return err } const argIsPositional = "positional" // subcommand or positional value const argIsFlagWithSpace = "flagWithSpace" // -f path or --file path const argIsFlagWithValue = "flagWithValue" // -f=path or --file=path const argIsFinal = "final" // the final argument only '--' // determineArgType determines if the specified arg is a flag with space // separated value, a flag with a connected value, or neither (positional) func determineArgType(arg string) string { // if the arg is --, then its the final arg if arg == "--" { return argIsFinal } // if it has the prefix --, then its a long flag if strings.HasPrefix(arg, "--") { // if it contains an equals, it is a joined value if strings.Contains(arg, "=") { return argIsFlagWithValue } return argIsFlagWithSpace } // if it has the prefix -, then its a short flag if strings.HasPrefix(arg, "-") { // if it contains an equals, it is a joined value if strings.Contains(arg, "=") { return argIsFlagWithValue } return argIsFlagWithSpace } return argIsPositional } // parseArgWithValue parses a key=value concatenated argument into a key and // value func parseArgWithValue(arg string) (key string, value string) { // remove up to two minuses from start of flag arg = strings.TrimPrefix(arg, "-") arg = strings.TrimPrefix(arg, "-") // debugPrint("parseArgWithValue parsing", arg) // break at the equals args := strings.SplitN(arg, "=", 2) // if its a bool arg, with no explicit value, we return a blank if len(args) == 1 { return args[0], "" } // if its a key and value pair, we return those if len(args) == 2 { // debugPrint("parseArgWithValue parsed", args[0], args[1]) return args[0], args[1] } fmt.Println("Warning: attempted to parseArgWithValue but did not have correct parameter count.", arg, "->", args) return "", "" } // parseFlagToName parses a flag with space value down to a key name: // --path -> path // -p -> p func parseFlagToName(arg string) string { // remove minus from start arg = strings.TrimLeft(arg, "-") arg = strings.TrimLeft(arg, "-") return arg } // flagIsBool determines if the flag is a bool within the specified parser // and subcommand's context func flagIsBool(sc *Subcommand, p *Parser, key string) bool { for _, f := range append(sc.Flags, p.Flags...) { if f.HasName(key) { _, isBool := f.AssignmentVar.(*bool) _, isBoolSlice := f.AssignmentVar.(*[]bool) if isBool || isBoolSlice { return true } } } // by default, the answer is false return false } // returnAssignmentVarValueAsString returns the value of the flag's // assignment variable as a string. This is used to display the // default value of flags before they are assigned (like when help is output). func (f *Flag) returnAssignmentVarValueAsString() (string, error) { debugPrint("returning current value of assignment var of flag", f.LongName) var err error // depending on the type of the assignment variable, we convert the // incoming string and assign it. We only use pointers to variables // in flagy. No returning vars by value. switch f.AssignmentVar.(type) { case *string: v, _ := (f.AssignmentVar).(*string) return *v, err case *[]string: v := f.AssignmentVar.(*[]string) return strings.Join(*v, ","), err case *bool: a, _ := (f.AssignmentVar).(*bool) return strconv.FormatBool(*a), err case *[]bool: value := f.AssignmentVar.(*[]bool) var ss []string for _, b := range *value { ss = append(ss, strconv.FormatBool(b)) } return strings.Join(ss, ","), err case *time.Duration: a := f.AssignmentVar.(*time.Duration) return (*a).String(), err case *[]time.Duration: tds := f.AssignmentVar.(*[]time.Duration) var asSlice []string for _, td := range *tds { asSlice = append(asSlice, td.String()) } return strings.Join(asSlice, ","), err case *float32: a := f.AssignmentVar.(*float32) return strconv.FormatFloat(float64(*a), 'f', 2, 32), err case *[]float32: v := f.AssignmentVar.(*[]float32) var strSlice []string for _, f := range *v { formatted := strconv.FormatFloat(float64(f), 'f', 2, 32) strSlice = append(strSlice, formatted) } return strings.Join(strSlice, ","), err case *float64: a := f.AssignmentVar.(*float64) return strconv.FormatFloat(float64(*a), 'f', 2, 64), err case *[]float64: v := f.AssignmentVar.(*[]float64) var strSlice []string for _, f := range *v { formatted := strconv.FormatFloat(float64(f), 'f', 2, 64) strSlice = append(strSlice, formatted) } return strings.Join(strSlice, ","), err case *int: a := f.AssignmentVar.(*int) return strconv.Itoa(*a), err case *[]int: val := f.AssignmentVar.(*[]int) var strSlice []string for _, i := range *val { str := strconv.Itoa(i) strSlice = append(strSlice, str) } return strings.Join(strSlice, ","), err case *uint: v := f.AssignmentVar.(*uint) return strconv.FormatUint(uint64(*v), 10), err case *[]uint: values := f.AssignmentVar.(*[]uint) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatUint(uint64(i), 10)) } return strings.Join(strVars, ","), err case *uint64: v := f.AssignmentVar.(*uint64) return strconv.FormatUint(*v, 10), err case *[]uint64: values := f.AssignmentVar.(*[]uint64) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatUint(i, 10)) } return strings.Join(strVars, ","), err case *uint32: v := f.AssignmentVar.(*uint32) return strconv.FormatUint(uint64(*v), 10), err case *[]uint32: values := f.AssignmentVar.(*[]uint32) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatUint(uint64(i), 10)) } return strings.Join(strVars, ","), err case *uint16: v := f.AssignmentVar.(*uint16) return strconv.FormatUint(uint64(*v), 10), err case *[]uint16: values := f.AssignmentVar.(*[]uint16) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatUint(uint64(i), 10)) } return strings.Join(strVars, ","), err case *uint8: v := f.AssignmentVar.(*uint8) return strconv.FormatUint(uint64(*v), 10), err case *[]uint8: values := f.AssignmentVar.(*[]uint8) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatUint(uint64(i), 10)) } return strings.Join(strVars, ","), err case *int64: v := f.AssignmentVar.(*int64) return strconv.FormatInt(int64(*v), 10), err case *[]int64: values := f.AssignmentVar.(*[]int64) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatInt(i, 10)) } return strings.Join(strVars, ","), err case *int32: v := f.AssignmentVar.(*int32) return strconv.FormatInt(int64(*v), 10), err case *[]int32: values := f.AssignmentVar.(*[]int32) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatInt(int64(i), 10)) } return strings.Join(strVars, ","), err case *int16: v := f.AssignmentVar.(*int16) return strconv.FormatInt(int64(*v), 10), err case *[]int16: values := f.AssignmentVar.(*[]int16) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatInt(int64(i), 10)) } return strings.Join(strVars, ","), err case *int8: v := f.AssignmentVar.(*int8) return strconv.FormatInt(int64(*v), 10), err case *[]int8: values := f.AssignmentVar.(*[]int8) var strVars []string for _, i := range *values { strVars = append(strVars, strconv.FormatInt(int64(i), 10)) } return strings.Join(strVars, ","), err case *net.IP: val := f.AssignmentVar.(*net.IP) return val.String(), err case *[]net.IP: val := f.AssignmentVar.(*[]net.IP) var strSlice []string for _, ip := range *val { strSlice = append(strSlice, ip.String()) } return strings.Join(strSlice, ","), err case *net.HardwareAddr: val := f.AssignmentVar.(*net.HardwareAddr) return val.String(), err case *[]net.HardwareAddr: val := f.AssignmentVar.(*[]net.HardwareAddr) var strSlice []string for _, mac := range *val { strSlice = append(strSlice, mac.String()) } return strings.Join(strSlice, ","), err case *net.IPMask: val := f.AssignmentVar.(*net.IPMask) return val.String(), err case *[]net.IPMask: val := f.AssignmentVar.(*[]net.IPMask) var strSlice []string for _, m := range *val { strSlice = append(strSlice, m.String()) } return strings.Join(strSlice, ","), err default: return "", errors.New("Unknown flag assignmentVar found in flag " + f.LongName + " " + f.ShortName + ". Type not supported: " + reflect.TypeOf(f.AssignmentVar).String()) } }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false
jesseduffield/lazygit
https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/github.com/integrii/flaggy/parser.go
vendor/github.com/integrii/flaggy/parser.go
package flaggy import ( "errors" "fmt" "os" "strconv" "text/template" ) // Parser represents the set of flags and subcommands we are expecting // from our input arguments. Parser is the top level struct responsible for // parsing an entire set of subcommands and flags. type Parser struct { Subcommand Version string // the optional version of the parser. ShowHelpWithHFlag bool // display help when -h or --help passed ShowVersionWithVersionFlag bool // display the version when --version passed ShowHelpOnUnexpected bool // display help when an unexpected flag or subcommand is passed TrailingArguments []string // everything after a -- is placed here HelpTemplate *template.Template // template for Help output trailingArgumentsExtracted bool // indicates that trailing args have been parsed and should not be appended again parsed bool // indicates this parser has parsed subcommandContext *Subcommand // points to the most specific subcommand being used } // NewParser creates a new ArgumentParser ready to parse inputs func NewParser(name string) *Parser { // this can not be done inline because of struct embedding p := &Parser{} p.Name = name p.Version = defaultVersion p.ShowHelpOnUnexpected = true p.ShowHelpWithHFlag = true p.ShowVersionWithVersionFlag = true p.SetHelpTemplate(DefaultHelpTemplate) p.subcommandContext = &Subcommand{} return p } // ParseArgs parses as if the passed args were the os.Args, but without the // binary at the 0 position in the array. An error is returned if there // is a low level issue converting flags to their proper type. No error // is returned for invalid arguments or missing require subcommands. func (p *Parser) ParseArgs(args []string) error { if p.parsed { return errors.New("Parser.Parse() called twice on parser with name: " + " " + p.Name + " " + p.ShortName) } p.parsed = true debugPrint("Kicking off parsing with args:", args) err := p.parse(p, args, 0) if err != nil { return err } // if we are set to crash on unexpected args, look for those here TODO if p.ShowHelpOnUnexpected { parsedValues := p.findAllParsedValues() debugPrint("parsedValues:", parsedValues) argsNotParsed := findArgsNotInParsedValues(args, parsedValues) if len(argsNotParsed) > 0 { // flatten out unused args for our error message var argsNotParsedFlat string for _, a := range argsNotParsed { argsNotParsedFlat = argsNotParsedFlat + " " + a } p.ShowHelpAndExit("Unknown arguments supplied: " + argsNotParsedFlat) } } return nil } // findArgsNotInParsedValues finds arguments not used in parsed values. The // incoming args should be in the order supplied by the user and should not // include the invoked binary, which is normally the first thing in os.Args. func findArgsNotInParsedValues(args []string, parsedValues []parsedValue) []string { var argsNotUsed []string var skipNext bool for _, a := range args { // if the final argument (--) is seen, then we stop checking because all // further values are trailing arguments. if determineArgType(a) == argIsFinal { return argsNotUsed } // allow for skipping the next arg when needed if skipNext { skipNext = false continue } // strip flag slashes from incoming arguments so they match up with the // keys from parsedValues. arg := parseFlagToName(a) // indicates that we found this arg used in one of the parsed values. Used // to indicate which values should be added to argsNotUsed. var foundArgUsed bool // search all args for a corresponding parsed value for _, pv := range parsedValues { // this argumenet was a key // debugPrint(pv.Key, "==", arg) debugPrint(pv.Key + "==" + arg + " || (" + strconv.FormatBool(pv.IsPositional) + " && " + pv.Value + " == " + arg + ")") if pv.Key == arg || (pv.IsPositional && pv.Value == arg) { debugPrint("Found matching parsed arg for " + pv.Key) foundArgUsed = true // the arg was used in this parsedValues set // if the value is not a positional value and the parsed value had a // value that was not blank, we skip the next value in the argument list if !pv.IsPositional && len(pv.Value) > 0 { skipNext = true break } } // this prevents excessive parsed values from being checked after we find // the arg used for the first time if foundArgUsed { break } } // if the arg was not used in any parsed values, then we add it to the slice // of arguments not used if !foundArgUsed { argsNotUsed = append(argsNotUsed, arg) } } return argsNotUsed } // ShowVersionAndExit shows the version of this parser func (p *Parser) ShowVersionAndExit() { fmt.Println("Version:", p.Version) exitOrPanic(0) } // SetHelpTemplate sets the go template this parser will use when rendering // Help. func (p *Parser) SetHelpTemplate(tmpl string) error { var err error p.HelpTemplate = template.New(helpFlagLongName) p.HelpTemplate, err = p.HelpTemplate.Parse(tmpl) if err != nil { return err } return nil } // Parse calculates all flags and subcommands func (p *Parser) Parse() error { err := p.ParseArgs(os.Args[1:]) if err != nil { return err } return nil } // ShowHelp shows Help without an error message func (p *Parser) ShowHelp() { debugPrint("showing help for", p.subcommandContext.Name) p.ShowHelpWithMessage("") } // ShowHelpAndExit shows parser help and exits with status code 2 func (p *Parser) ShowHelpAndExit(message string) { p.ShowHelpWithMessage(message) exitOrPanic(2) } // ShowHelpWithMessage shows the Help for this parser with an optional string error // message as a header. The supplied subcommand will be the context of Help // displayed to the user. func (p *Parser) ShowHelpWithMessage(message string) { // create a new Help values template and extract values into it help := Help{} help.ExtractValues(p, message) err := p.HelpTemplate.Execute(os.Stderr, help) if err != nil { fmt.Fprintln(os.Stderr, "Error rendering Help template:", err) } } // DisableShowVersionWithVersion disables the showing of version information // with --version. It is enabled by default. func (p *Parser) DisableShowVersionWithVersion() { p.ShowVersionWithVersionFlag = false }
go
MIT
80dd695d7a8d32714603f5a6307f26f589802b1d
2026-01-07T08:35:43.445894Z
false