Skip to content
Myr

Merge branch 'main' into fix-nested-cmd-order

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Ayman Bagabas · committed by GitHub · parents 0290af4, 21eecd5 · Browse files · 80 files+4039 added−1269 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

80 files+4039 added−1269 removed

  • other:+4039 added−1269 removed

80 files+4039 added−1269 removed

modified:.github/workflows/build.yml+12 added-34 removed
modified:.github/workflows/coverage.yml+8 added-7 removed
added:.github/workflows/dependabot-sync.yml+17 added
modified:.github/workflows/examples.yml+3 added-3 removed
deleted:.github/workflows/lint-soft.yml-28 removed
added:.github/workflows/lint-sync.yml+14 added
modified:.github/workflows/lint.yml+2 added-22 removed
added:.github/workflows/release.yml+29 added
added:.github/CODEOWNERS+1 added
1* @meowgorithm @aymanbagabas
modified:.github/dependabot.yml+59 added-10 removed
1version: 223updates:4 - package-ecosystem: "gomod"5 directory: "/"6 schedule:6 interval: "daily"7 interval: "weekly"8 day: "monday"9 time: "05:00"10 timezone: "America/New_York"11 labels:12 - "dependencies"13 commit-message:10 prefix: "feat"14 prefix: "chore"15 include: "scope"16 groups:17 all:18 patterns:19 - "*"2012 - package-ecosystem: "gomod"13 directory: "/examples"21 - package-ecosystem: "github-actions"22 directory: "/"23 schedule:15 interval: "daily"24 interval: "weekly"25 day: "monday"26 time: "05:00"27 timezone: "America/New_York"28 labels:29 - "dependencies"30 commit-message:31 prefix: "chore"32 include: "scope"33 groups:34 all:35 patterns:36 - "*"3738 - package-ecosystem: "docker"39 directory: "/"40 schedule:41 interval: "weekly"42 day: "monday"43 time: "05:00"44 timezone: "America/New_York"45 labels:46 - "dependencies"47 commit-message:48 prefix: "chore"49 include: "scope"50 groups:51 all:52 patterns:53 - "*"5455 - package-ecosystem: "gomod"22 directory: "/tutorials"56 directory: "/examples"57 schedule:24 interval: "daily"58 interval: "weekly"59 day: "monday"60 time: "05:00"61 timezone: "America/New_York"62 labels:63 - "dependencies"64 commit-message:65 prefix: "chore"66 include: "scope"67 groups:68 all:69 patterns:70 - "*"7130 - package-ecosystem: "github-actions"31 directory: "/"72 - package-ecosystem: "gomod"73 directory: "/tutorials"74 schedule:33 interval: "daily"75 interval: "weekly"76 day: "monday"77 time: "05:00"78 timezone: "America/New_York"79 labels:80 - "dependencies"81 commit-message:82 prefix: "chore"83 include: "scope"84 groups:85 all:86 patterns:87 - "*"
modified:examples/altscreen-toggle/main.go+18 added-8 removed
3 unmodified lines
4 "fmt"5 "os"67 tea "github.com/charmbracelet/bubbletea"8 "github.com/muesli/termenv"8 "github.com/charmbracelet/lipgloss"9)1011var (12 color = termenv.EnvColorProfile().Color13 keyword = termenv.Style{}.Foreground(color("204")).Background(color("235")).Styled14 help = termenv.Style{}.Foreground(color("241")).Styled12 keywordStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("204")).Background(lipgloss.Color("235"))13 helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))14)1516type model struct {18 altscreen bool19 quitting bool17 altscreen bool18 quitting bool19 suspending bool20}2122func (m model) Init() tea.Cmd {23 return nil24}2526func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {27 switch msg := msg.(type) {28 case tea.ResumeMsg:29 m.suspending = false30 return m, nil31 case tea.KeyMsg:32 switch msg.String() {33 case "q", "ctrl+c", "esc":34 m.quitting = true35 return m, tea.Quit36 case "ctrl+z":37 m.suspending = true38 return m, tea.Suspend39 case " ":40 var cmd tea.Cmd41 if m.altscreen {42 cmd = tea.ExitAltScreen
7 unmodified lines
50 return m, nil51}5253func (m model) View() string {54 if m.suspending {55 return ""56 }5758 if m.quitting {59 return "Bye!\n"60 }61
8 unmodified lines
70 } else {71 mode = inlineMode72 }7364 return fmt.Sprintf("\n\n You're in %s\n\n\n", keyword(mode)) +65 help(" space: switch modes • q: exit\n")74 return fmt.Sprintf("\n\n You're in %s\n\n\n", keywordStyle.Render(mode)) +75 helpStyle.Render(" space: switch modes • ctrl-z: suspend • q: exit\n")76}7778func main() {79 if _, err := tea.NewProgram(model{}).Run(); err != nil {
4 unmodified lines
modified:examples/autocomplete/main.go+28 added-4 removed
5 unmodified lines
6 "io"7 "log"8 "net/http"910 "github.com/charmbracelet/bubbles/help"11 "github.com/charmbracelet/bubbles/key"12 "github.com/charmbracelet/bubbles/textinput"13 tea "github.com/charmbracelet/bubbletea"14 "github.com/charmbracelet/lipgloss"15)
45 unmodified lines
61}6263type model struct {64 textInput textinput.Model65 help help.Model66 keymap keymap67}6869type keymap struct{}7071func (k keymap) ShortHelp() []key.Binding {72 return []key.Binding{73 key.NewBinding(key.WithKeys("tab"), key.WithHelp("tab", "complete")),74 key.NewBinding(key.WithKeys("ctrl+n"), key.WithHelp("ctrl+n", "next")),75 key.NewBinding(key.WithKeys("ctrl+p"), key.WithHelp("ctrl+p", "prev")),76 key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "quit")),77 }78}79func (k keymap) FullHelp() [][]key.Binding {80 return [][]key.Binding{k.ShortHelp()}81}8283func initialModel() model {84 ti := textinput.New()85 ti.Placeholder = "repository"86 ti.Prompt = "charmbracelet/"68 ti.Placeholder = "repo..."87 ti.PromptStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))88 ti.Cursor.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))89 ti.Focus()90 ti.CharLimit = 5091 ti.Width = 2092 ti.ShowSuggestions = true9394 h := help.New()9596 km := keymap{}9774 return model{textInput: ti}98 return model{textInput: ti, help: h, keymap: km}99}100101func (m model) Init() tea.Cmd {102 return tea.Batch(getRepos, textinput.Blink)
20 unmodified lines
123}124125func (m model) View() string {126 return fmt.Sprintf(103 "What’s your favorite Charm repository?\n\n%s\n\n%s\n",127 "Pick a Charm™ repo:\n\n %s\n\n%s\n\n",128 m.textInput.View(),105 "(tab to complete, ctrl+n/ctrl+p to cycle through suggestions, esc to quit)",129 m.help.View(m.keymap),130 )131}
modified:examples/chat/main.go+16 added-3 removed
12 unmodified lines
13 tea "github.com/charmbracelet/bubbletea"14 "github.com/charmbracelet/lipgloss"15)1617const gap = "\n\n"1819func main() {20 p := tea.NewProgram(initialModel())2122 if _, err := p.Run(); err != nil {
57 unmodified lines
80 m.textarea, tiCmd = m.textarea.Update(msg)81 m.viewport, vpCmd = m.viewport.Update(msg)8283 switch msg := msg.(type) {84 case tea.WindowSizeMsg:85 m.viewport.Width = msg.Width86 m.textarea.SetWidth(msg.Width)87 m.viewport.Height = msg.Height - m.textarea.Height() - lipgloss.Height(gap)8889 if len(m.messages) > 0 {90 // Wrap content before setting it.91 m.viewport.SetContent(lipgloss.NewStyle().Width(m.viewport.Width).Render(strings.Join(m.messages, "\n")))92 }93 m.viewport.GotoBottom()94 case tea.KeyMsg:95 switch msg.Type {96 case tea.KeyCtrlC, tea.KeyEsc:97 fmt.Println(m.textarea.Value())98 return m, tea.Quit99 case tea.KeyEnter:100 m.messages = append(m.messages, m.senderStyle.Render("You: ")+m.textarea.Value())89 m.viewport.SetContent(strings.Join(m.messages, "\n"))101 m.viewport.SetContent(lipgloss.NewStyle().Width(m.viewport.Width).Render(strings.Join(m.messages, "\n")))102 m.textarea.Reset()103 m.viewport.GotoBottom()104 }105
7 unmodified lines
113}114115func (m model) View() string {116 return fmt.Sprintf(105 "%s\n\n%s",117 "%s%s%s",118 m.viewport.View(),119 gap,120 m.textarea.View(),108 ) + "\n\n"121 )122}
modified:examples/file-picker/main.go+1 added-1 removed
86 unmodified lines
8788 m := model{89 filepicker: fp,90 }91 tm, _ := tea.NewProgram(&m, tea.WithOutput(os.Stderr)).Run()91 tm, _ := tea.NewProgram(&m).Run()92 mm := tm.(model)93 fmt.Println("\n You selected: " + m.filepicker.Styles.Selected.Render(mm.selectedFile) + "\n")94}
added:examples/focus-blur/main.go+66 added
1package main23// A simple program that handled losing and acquiring focus.45import (6 "log"78 tea "github.com/charmbracelet/bubbletea"9)1011func main() {12 p := tea.NewProgram(model{13 // assume we start focused...14 focused: true,15 reporting: true,16 }, tea.WithReportFocus())17 if _, err := p.Run(); err != nil {18 log.Fatal(err)19 }20}2122type model struct {23 focused bool24 reporting bool25}2627func (m model) Init() tea.Cmd {28 return nil29}3031func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {32 switch msg := msg.(type) {33 case tea.FocusMsg:34 m.focused = true35 case tea.BlurMsg:36 m.focused = false37 case tea.KeyMsg:38 switch msg.String() {39 case "t":40 m.reporting = !m.reporting41 case "ctrl+c", "q":42 return m, tea.Quit43 }44 }4546 return m, nil47}4849func (m model) View() string {50 s := "Hi. Focus report is currently "51 if m.reporting {52 s += "enabled"53 } else {54 s += "disabled"55 }56 s += ".\n\n"5758 if m.reporting {59 if m.focused {60 s += "This program is currently focused!"61 } else {62 s += "This program is currently blurred!"63 }64 }65 return s + "\n\nTo quit sooner press ctrl-c, or t to toggle focus reporting...\n"66}
modified:examples/fullscreen/main.go+1 added-1 removed
21 unmodified lines
22 }23}2425func (m model) Init() tea.Cmd {26 return tea.Batch(tick(), tea.EnterAltScreen)26 return tick()27}2829func (m model) Update(message tea.Msg) (tea.Model, tea.Cmd) {30 switch msg := message.(type) {
26 unmodified lines
modified:examples/glamour/main.go+12 added-1 removed
63 unmodified lines
64 BorderStyle(lipgloss.RoundedBorder()).65 BorderForeground(lipgloss.Color("62")).66 PaddingRight(2)6768 // We need to adjust the width of the glamour render from our main width69 // to account for a few things:70 //71 // * The viewport border width72 // * The viewport padding73 // * The viewport margins74 // * The gutter glamour applies to the left side of the content75 //76 const glamourGutter = 277 glamourRenderWidth := width - vp.Style.GetHorizontalFrameSize() - glamourGutter7879 renderer, err := glamour.NewTermRenderer(80 glamour.WithAutoStyle(),70 glamour.WithWordWrap(width),81 glamour.WithWordWrap(glamourRenderWidth),82 )83 if err != nil {84 return nil, err85 }
53 unmodified lines
modified:examples/list-fancy/main.go+2 added-2 removed
116 unmodified lines
117 }118}119120func (m model) Init() tea.Cmd {121 return tea.EnterAltScreen121 return nil122}123124func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {125 var cmds []tea.Cmd
56 unmodified lines
182183func main() {184 rand.Seed(time.Now().UTC().UnixNano())185186 if _, err := tea.NewProgram(newModel()).Run(); err != nil {186 if _, err := tea.NewProgram(newModel(), tea.WithAltScreen()).Run(); err != nil {187 fmt.Println("Error running program:", err)188 os.Exit(1)189 }190}
modified:examples/list-simple/main.go+1 added-1 removed
65 unmodified lines
66 return m, nil6768 case tea.KeyMsg:69 switch keypress := msg.String(); keypress {70 case "ctrl+c":70 case "q", "ctrl+c":71 m.quitting = true72 return m, tea.Quit7374 case "enter":
54 unmodified lines
modified:examples/mouse/main.go+3 added-11 removed
2 unmodified lines
3// A simple program that opens the alternate screen buffer and displays mouse4// coordinates and events.56import (7 "fmt"7 "log"89 tea "github.com/charmbracelet/bubbletea"10)1112func main() {14 p := tea.NewProgram(model{}, tea.WithAltScreen(), tea.WithMouseAllMotion())13 p := tea.NewProgram(model{}, tea.WithMouseAllMotion())14 if _, err := p.Run(); err != nil {15 log.Fatal(err)16 }17}1819type model struct {21 init bool20 mouseEvent tea.MouseEvent21}2223func (m model) Init() tea.Cmd {
7 unmodified lines
31 return m, tea.Quit32 }3334 case tea.MouseMsg:37 m.init = true38 m.mouseEvent = tea.MouseEvent(msg)35 return m, tea.Printf("(X: %d, Y: %d) %s", msg.X, msg.Y, tea.MouseEvent(msg))36 }3738 return m, nil39}4041func (m model) View() string {45 s := "Do mouse stuff. When you're done press q to quit.\n\n"42 s := "Do mouse stuff. When you're done press q to quit.\n"4347 if m.init {48 e := m.mouseEvent49 s += fmt.Sprintf("(X: %d, Y: %d) %s", e.X, e.Y, e)50 }5144 return s45}
modified:examples/package-manager/main.go+10 added-6 removed
56 unmodified lines
57 case "ctrl+c", "esc", "q":58 return m, tea.Quit59 }60 case installedPkgMsg:61 pkg := m.packages[m.index]62 if m.index >= len(m.packages)-1 {63 // Everything's been installed. We're done!64 m.done = true64 return m, tea.Quit65 return m, tea.Sequence(66 tea.Printf("%s %s", checkMark, pkg), // print the last success message67 tea.Quit, // exit the program68 )69 }7071 // Update progress bar68 progressCmd := m.progress.SetPercent(float64(m.index) / float64(len(m.packages)-1))6972 m.index++73 progressCmd := m.progress.SetPercent(float64(m.index) / float64(len(m.packages)))7475 return m, tea.Batch(76 progressCmd,73 tea.Printf("%s %s", checkMark, m.packages[m.index]), // print success message above our program74 downloadAndInstall(m.packages[m.index]), // download the next package77 tea.Printf("%s %s", checkMark, pkg), // print success message above our program78 downloadAndInstall(m.packages[m.index]), // download the next package79 )80 case spinner.TickMsg:81 var cmd tea.Cmd82 m.spinner, cmd = m.spinner.Update(msg)
15 unmodified lines
98 if m.done {99 return doneStyle.Render(fmt.Sprintf("Done! Installed %d packages.\n", n))100 }10198 pkgCount := fmt.Sprintf(" %*d/%*d", w, m.index, w, n-1)102 pkgCount := fmt.Sprintf(" %*d/%*d", w, m.index, w, n)103104 spin := m.spinner.View() + " "105 prog := m.progress.View()106 cellsAvail := max(0, m.width-lipgloss.Width(spin+prog+pkgCount))
34 unmodified lines
modified:examples/pager/main.go+1 added-24 removed
11 unmodified lines
12 tea "github.com/charmbracelet/bubbletea"13 "github.com/charmbracelet/lipgloss"14)1516// You generally won't need this unless you're processing stuff with17// complicated ANSI escape sequences. Turn it on if you notice flickering.18//19// Also keep in mind that high performance rendering only works for programs20// that use the full size of the terminal. We're enabling that below with21// tea.EnterAltScreen().22const useHighPerformanceRenderer = false2316var (17 titleStyle = func() lipgloss.Style {18 b := lipgloss.RoundedBorder()19 b.Right = "├"
2 unmodified lines
2223 infoStyle = func() lipgloss.Style {24 b := lipgloss.RoundedBorder()25 b.Left = "┤"34 return titleStyle.Copy().BorderStyle(b)26 return titleStyle.BorderStyle(b)27 }()28)2930type model struct {
30 unmodified lines
61 // quickly, though asynchronously, which is why we wait for them62 // here.63 m.viewport = viewport.New(msg.Width, msg.Height-verticalMarginHeight)64 m.viewport.YPosition = headerHeight73 m.viewport.HighPerformanceRendering = useHighPerformanceRenderer65 m.viewport.SetContent(m.content)66 m.ready = true7677 // This is only necessary for high performance rendering, which in78 // most cases you won't need.79 //80 // Render the viewport one line below the header.81 m.viewport.YPosition = headerHeight + 167 } else {68 m.viewport.Width = msg.Width69 m.viewport.Height = msg.Height - verticalMarginHeight70 }8687 if useHighPerformanceRenderer {88 // Render (or re-render) the whole viewport. Necessary both to89 // initialize the viewport and when the window is resized.90 //91 // This is needed for high-performance rendering only.92 cmds = append(cmds, viewport.Sync(m.viewport))93 }71 }7273 // Handle keyboard and mouse events in the viewport74 m.viewport, cmd = m.viewport.Update(msg)
50 unmodified lines
modified:examples/send-msg/main.go+2 added-2 removed
16 unmodified lines
1718var (19 spinnerStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))20 helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Margin(1, 0)21 dotStyle = helpStyle.Copy().UnsetMargins()22 durationStyle = dotStyle.Copy()21 dotStyle = helpStyle.UnsetMargins()22 durationStyle = dotStyle23 appStyle = lipgloss.NewStyle().Margin(1, 2, 0, 2)24)2526type resultMsg struct {
105 unmodified lines
added:examples/set-window-title/main.go+35 added
1package main23// A simple example illustrating how to set a window title.45import (6 "fmt"7 "os"89 tea "github.com/charmbracelet/bubbletea"10)1112type model struct{}1314func (m model) Init() tea.Cmd {15 return tea.SetWindowTitle("Bubble Tea Example")16}1718func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {19 switch msg.(type) {20 case tea.KeyMsg:21 return m, tea.Quit22 }23 return m, nil24}2526func (m model) View() string {27 return "\nPress any key to quit."28}2930func main() {31 if _, err := tea.NewProgram(model{}).Run(); err != nil {32 fmt.Println("Uh oh:", err)33 os.Exit(1)34 }35}
modified:examples/simple/testdata/TestApp.golden+7 added-3 removed
1[?25lHi. This program will exit in 10 seconds. To quit sooner press any key2Hi. This program will exit in 9 seconds. To quit sooner press any key.3[?25h[?1002l[?1003l1[?25l[?2004h Hi. This program will exit in 10 seconds.23To quit sooner press ctrl-c, or press ctrl-z to suspend...4 Hi. This program will exit in 9 seconds.567  [?2004l[?25h[?1002l[?1003l[?1006l
modified:examples/simple/main_test.go-6 removed
6 unmodified lines
7 "testing"8 "time"910 tea "github.com/charmbracelet/bubbletea"11 "github.com/charmbracelet/lipgloss"11 "github.com/charmbracelet/x/exp/teatest"13 "github.com/muesli/termenv"12)1316func init() {17 lipgloss.SetColorProfile(termenv.Ascii)18}1914func TestApp(t *testing.T) {15 m := model(10)16 tm := teatest.NewTestModel(17 t, m,
69 unmodified lines
modified:examples/simple/main.go+9 added-3 removed
41 unmodified lines
42// Update is called when messages are received. The idea is that you inspect the43// message and send back an updated model accordingly. You can also return44// a command, which is a function that performs I/O and returns a message.45func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {46 switch msg.(type) {46 switch msg := msg.(type) {47 case tea.KeyMsg:48 switch msg.String() {49 case "ctrl+c", "q":48 return m, tea.Quit50 return m, tea.Quit51 case "ctrl+z":52 return m, tea.Suspend53 }5455 case tickMsg:56 m--57 if m <= 0 {58 return m, tea.Quit
5 unmodified lines
6465// View returns a string based on data in the model. That string which will be66// rendered to the terminal.67func (m model) View() string {62 return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.\n", m)68 return fmt.Sprintf("Hi. This program will exit in %d seconds.\n\nTo quit sooner press ctrl-c, or press ctrl-z to suspend...\n", m)69}7071// Messages are events that we respond to in our Update function. This72// particular one indicates that the timer has ticked.
6 unmodified lines
added:examples/suspend/main.go+57 added
1package main23import (4 "errors"5 "fmt"6 "os"78 tea "github.com/charmbracelet/bubbletea"9)1011type model struct {12 quitting bool13 suspending bool14}1516func (m model) Init() tea.Cmd {17 return nil18}1920func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {21 switch msg := msg.(type) {22 case tea.ResumeMsg:23 m.suspending = false24 return m, nil25 case tea.KeyMsg:26 switch msg.String() {27 case "q", "esc":28 m.quitting = true29 return m, tea.Quit30 case "ctrl+c":31 m.quitting = true32 return m, tea.Interrupt33 case "ctrl+z":34 m.suspending = true35 return m, tea.Suspend36 }37 }38 return m, nil39}4041func (m model) View() string {42 if m.suspending || m.quitting {43 return ""44 }4546 return "\nPress ctrl-z to suspend, ctrl+c to interrupt, q, or esc to exit\n"47}4849func main() {50 if _, err := tea.NewProgram(model{}).Run(); err != nil {51 fmt.Println("Error running program:", err)52 if errors.Is(err, tea.ErrInterrupted) {53 os.Exit(130)54 }55 os.Exit(1)56 }57}
added:examples/table-resize/main.go+148 added
1package main23import (4 "fmt"5 "os"67 tea "github.com/charmbracelet/bubbletea"8 "github.com/charmbracelet/lipgloss"9 "github.com/charmbracelet/lipgloss/table"10)1112type model struct {13 table *table.Table14}1516func (m model) Init() tea.Cmd { return nil }1718func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {19 var cmd tea.Cmd20 switch msg := msg.(type) {21 case tea.WindowSizeMsg:22 m.table = m.table.Width(msg.Width)23 m.table = m.table.Height(msg.Height)24 case tea.KeyMsg:25 switch msg.String() {26 case "q", "ctrl+c":27 return m, tea.Quit28 case "enter":29 }30 }31 return m, cmd32}3334func (m model) View() string {35 return "\n" + m.table.String() + "\n"36}3738func main() {39 re := lipgloss.NewRenderer(os.Stdout)40 baseStyle := re.NewStyle().Padding(0, 1)41 headerStyle := baseStyle.Foreground(lipgloss.Color("252")).Bold(true)42 selectedStyle := baseStyle.Foreground(lipgloss.Color("#01BE85")).Background(lipgloss.Color("#00432F"))43 typeColors := map[string]lipgloss.Color{44 "Bug": lipgloss.Color("#D7FF87"),45 "Electric": lipgloss.Color("#FDFF90"),46 "Fire": lipgloss.Color("#FF7698"),47 "Flying": lipgloss.Color("#FF87D7"),48 "Grass": lipgloss.Color("#75FBAB"),49 "Ground": lipgloss.Color("#FF875F"),50 "Normal": lipgloss.Color("#929292"),51 "Poison": lipgloss.Color("#7D5AFC"),52 "Water": lipgloss.Color("#00E2C7"),53 }54 dimTypeColors := map[string]lipgloss.Color{55 "Bug": lipgloss.Color("#97AD64"),56 "Electric": lipgloss.Color("#FCFF5F"),57 "Fire": lipgloss.Color("#BA5F75"),58 "Flying": lipgloss.Color("#C97AB2"),59 "Grass": lipgloss.Color("#59B980"),60 "Ground": lipgloss.Color("#C77252"),61 "Normal": lipgloss.Color("#727272"),62 "Poison": lipgloss.Color("#634BD0"),63 "Water": lipgloss.Color("#439F8E"),64 }65 headers := []string{"#", "NAME", "TYPE 1", "TYPE 2", "JAPANESE", "OFFICIAL ROM."}66 rows := [][]string{67 {"1", "Bulbasaur", "Grass", "Poison", "フシギダネ", "Bulbasaur"},68 {"2", "Ivysaur", "Grass", "Poison", "フシギソウ", "Ivysaur"},69 {"3", "Venusaur", "Grass", "Poison", "フシギバナ", "Venusaur"},70 {"4", "Charmander", "Fire", "", "ヒトカゲ", "Hitokage"},71 {"5", "Charmeleon", "Fire", "", "リザード", "Lizardo"},72 {"6", "Charizard", "Fire", "Flying", "リザードン", "Lizardon"},73 {"7", "Squirtle", "Water", "", "ゼニガメ", "Zenigame"},74 {"8", "Wartortle", "Water", "", "カメール", "Kameil"},75 {"9", "Blastoise", "Water", "", "カメックス", "Kamex"},76 {"10", "Caterpie", "Bug", "", "キャタピー", "Caterpie"},77 {"11", "Metapod", "Bug", "", "トランセル", "Trancell"},78 {"12", "Butterfree", "Bug", "Flying", "バタフリー", "Butterfree"},79 {"13", "Weedle", "Bug", "Poison", "ビードル", "Beedle"},80 {"14", "Kakuna", "Bug", "Poison", "コクーン", "Cocoon"},81 {"15", "Beedrill", "Bug", "Poison", "スピアー", "Spear"},82 {"16", "Pidgey", "Normal", "Flying", "ポッポ", "Poppo"},83 {"17", "Pidgeotto", "Normal", "Flying", "ピジョン", "Pigeon"},84 {"18", "Pidgeot", "Normal", "Flying", "ピジョット", "Pigeot"},85 {"19", "Rattata", "Normal", "", "コラッタ", "Koratta"},86 {"20", "Raticate", "Normal", "", "ラッタ", "Ratta"},87 {"21", "Spearow", "Normal", "Flying", "オニスズメ", "Onisuzume"},88 {"22", "Fearow", "Normal", "Flying", "オニドリル", "Onidrill"},89 {"23", "Ekans", "Poison", "", "アーボ", "Arbo"},90 {"24", "Arbok", "Poison", "", "アーボック", "Arbok"},91 {"25", "Pikachu", "Electric", "", "ピカチュウ", "Pikachu"},92 {"26", "Raichu", "Electric", "", "ライチュウ", "Raichu"},93 {"27", "Sandshrew", "Ground", "", "サンド", "Sand"},94 {"28", "Sandslash", "Ground", "", "サンドパン", "Sandpan"},95 }9697 t := table.New().98 Headers(headers...).99 Rows(rows...).100 Border(lipgloss.NormalBorder()).101 BorderStyle(re.NewStyle().Foreground(lipgloss.Color("238"))).102 StyleFunc(func(row, col int) lipgloss.Style {103 if row == 0 {104 return headerStyle105 }106107 rowIndex := row - 1108 if rowIndex < 0 || rowIndex >= len(rows) {109 return baseStyle110 }111112 if rows[rowIndex][1] == "Pikachu" {113 return selectedStyle114 }115116 even := row%2 == 0117118 switch col {119 case 2, 3: // Type 1 + 2120 c := typeColors121 if even {122 c = dimTypeColors123 }124125 if col >= len(rows[rowIndex]) {126 return baseStyle127 }128129 color, ok := c[rows[rowIndex][col]]130 if !ok {131 return baseStyle132 }133 return baseStyle.Foreground(color)134 }135136 if even {137 return baseStyle.Foreground(lipgloss.Color("245"))138 }139 return baseStyle.Foreground(lipgloss.Color("252"))140 }).141 Border(lipgloss.ThickBorder())142143 m := model{t}144 if _, err := tea.NewProgram(m, tea.WithAltScreen()).Run(); err != nil {145 fmt.Println("Error running program:", err)146 os.Exit(1)147 }148}
modified:examples/tabs/main.go+3 added-3 removed
49 unmodified lines
50 activeTabBorder = tabBorderWithBottom("┘", " ", "└")51 docStyle = lipgloss.NewStyle().Padding(1, 2, 1, 2)52 highlightColor = lipgloss.AdaptiveColor{Light: "#874BFD", Dark: "#7D56F4"}53 inactiveTabStyle = lipgloss.NewStyle().Border(inactiveTabBorder, true).BorderForeground(highlightColor).Padding(0, 1)54 activeTabStyle = inactiveTabStyle.Copy().Border(activeTabBorder, true)54 activeTabStyle = inactiveTabStyle.Border(activeTabBorder, true)55 windowStyle = lipgloss.NewStyle().BorderForeground(highlightColor).Padding(2, 0).Align(lipgloss.Center).Border(lipgloss.NormalBorder()).UnsetBorderTop()56)5758func (m model) View() string {
4 unmodified lines
63 for i, t := range m.Tabs {64 var style lipgloss.Style65 isFirst, isLast, isActive := i == 0, i == len(m.Tabs)-1, i == m.activeTab66 if isActive {67 style = activeTabStyle.Copy()67 style = activeTabStyle68 } else {69 style = inactiveTabStyle.Copy()69 style = inactiveTabStyle70 }71 border, _, _, _, _ := style.GetBorder()72 if isFirst && isActive {73 border.BottomLeft = "│"
41 unmodified lines
modified:examples/textinputs/main.go+3 added-3 removed
15 unmodified lines
1617var (18 focusedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))19 blurredStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))20 cursorStyle = focusedStyle.Copy()20 cursorStyle = focusedStyle21 noStyle = lipgloss.NewStyle()22 helpStyle = blurredStyle.Copy()22 helpStyle = blurredStyle23 cursorModeHelpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))2425 focusedButton = focusedStyle.Copy().Render("[ Submit ]")25 focusedButton = focusedStyle.Render("[ Submit ]")26 blurredButton = fmt.Sprintf("[ %s ]", blurredStyle.Render("Submit"))27)2829type model struct {
149 unmodified lines
modified:examples/tui-daemon-combo/main.go+5 added-3 removed
11 unmodified lines
12 "github.com/charmbracelet/bubbles/spinner"13 tea "github.com/charmbracelet/bubbletea"14 "github.com/charmbracelet/lipgloss"15 "github.com/mattn/go-isatty"16 "github.com/muesli/reflow/indent"16)1718var (19var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Render19 helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Render20 mainStyle = lipgloss.NewStyle().MarginLeft(1)21)2223func main() {24 var (25 daemonMode bool
93 unmodified lines
119 if m.quitting {120 s += "\n"121 }122121 return indent.String(s, 1)123 return mainStyle.Render(s)124}125126// processFinishedMsg is sent when a pretend process completes.127type processFinishedMsg time.Duration
12 unmodified lines
modified:examples/views/main.go+25 added-31 removed
12 unmodified lines
13 "strings"14 "time"1516 tea "github.com/charmbracelet/bubbletea"17 "github.com/charmbracelet/lipgloss"18 "github.com/fogleman/ease"19 "github.com/lucasb-eyer/go-colorful"19 "github.com/muesli/reflow/indent"20 "github.com/muesli/termenv"20)2122const (23 progressBarWidth = 7124 progressFullChar = "█"25 progressEmptyChar = "░"26 dotChar = " • "27)2829// General stuff for styling the view30var (31 term = termenv.EnvColorProfile()32 keyword = makeFgStyle("211")33 subtle = makeFgStyle("241")34 progressEmpty = subtle(progressEmptyChar)35 dot = colorFg(" • ", "236")31 keywordStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("211"))32 subtleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))33 ticksStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("79"))34 checkboxStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212"))35 progressEmpty = subtleStyle.Render(progressEmptyChar)36 dotStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("236")).Render(dotChar)37 mainStyle = lipgloss.NewStyle().MarginLeft(2)3839 // Gradient colors we'll use for the progress bar38 ramp = makeRamp("#B14FFF", "#00FFA3", progressBarWidth)40 ramp = makeRampStyles("#B14FFF", "#00FFA3", progressBarWidth)41)4243func main() {44 initialModel := model{0, false, 10, 0, 0, false, false}
63 unmodified lines
108 s = choicesView(m)109 } else {110 s = chosenView(m)111 }110 return indent.String("\n"+s+"\n\n", 2)112 return mainStyle.Render("\n" + s + "\n\n")113}114115// Sub-update functions116
67 unmodified lines
184185 tpl := "What to do today?\n\n"186 tpl += "%s\n\n"187 tpl += "Program quits in %s seconds\n\n"186 tpl += subtle("j/k, up/down: select") + dot + subtle("enter: choose") + dot + subtle("q, esc: quit")188 tpl += subtleStyle.Render("j/k, up/down: select") + dotStyle +189 subtleStyle.Render("enter: choose") + dotStyle +190 subtleStyle.Render("q, esc: quit")191192 choices := fmt.Sprintf(193 "%s\n%s\n%s\n%s",194 checkbox("Plant carrots", c == 0),
1 unmodified line
196 checkbox("Read something", c == 2),197 checkbox("See friends", c == 3),198 )199196 return fmt.Sprintf(tpl, choices, colorFg(strconv.Itoa(m.Ticks), "79"))200 return fmt.Sprintf(tpl, choices, ticksStyle.Render(strconv.Itoa(m.Ticks)))201}202203// The second view, after a task has been chosen204func chosenView(m model) string {205 var msg string206207 switch m.Choice {208 case 0:205 msg = fmt.Sprintf("Carrot planting?\n\nCool, we'll need %s and %s...", keyword("libgarden"), keyword("vegeutils"))209 msg = fmt.Sprintf("Carrot planting?\n\nCool, we'll need %s and %s...", keywordStyle.Render("libgarden"), keywordStyle.Render("vegeutils"))210 case 1:207 msg = fmt.Sprintf("A trip to the market?\n\nOkay, then we should install %s and %s...", keyword("marketkit"), keyword("libshopping"))211 msg = fmt.Sprintf("A trip to the market?\n\nOkay, then we should install %s and %s...", keywordStyle.Render("marketkit"), keywordStyle.Render("libshopping"))212 case 2:209 msg = fmt.Sprintf("Reading time?\n\nOkay, cool, then we’ll need a library. Yes, an %s.", keyword("actual library"))213 msg = fmt.Sprintf("Reading time?\n\nOkay, cool, then we’ll need a library. Yes, an %s.", keywordStyle.Render("actual library"))214 default:211 msg = fmt.Sprintf("It’s always good to see friends.\n\nFetching %s and %s...", keyword("social-skills"), keyword("conversationutils"))215 msg = fmt.Sprintf("It’s always good to see friends.\n\nFetching %s and %s...", keywordStyle.Render("social-skills"), keywordStyle.Render("conversationutils"))216 }217218 label := "Downloading..."219 if m.Loaded {216 label = fmt.Sprintf("Downloaded. Exiting in %s seconds...", colorFg(strconv.Itoa(m.Ticks), "79"))220 label = fmt.Sprintf("Downloaded. Exiting in %s seconds...", ticksStyle.Render(strconv.Itoa(m.Ticks)))221 }222223 return msg + "\n\n" + label + "\n" + progressbar(m.Progress) + "%"224}225226func checkbox(label string, checked bool) string {227 if checked {224 return colorFg("[x] "+label, "212")228 return checkboxStyle.Render("[x] " + label)229 }230 return fmt.Sprintf("[ ] %s", label)231}232
2 unmodified lines
235236 fullSize := int(math.Round(w * percent))237 var fullCells string238 for i := 0; i < fullSize; i++ {235 fullCells += termenv.String(progressFullChar).Foreground(term.Color(ramp[i])).String()239 fullCells += ramp[i].Render(progressFullChar)240 }241242 emptySize := int(w) - fullSize243 emptyCells := strings.Repeat(progressEmpty, emptySize)
2 unmodified lines
246}247248// Utils249246// Color a string's foreground with the given value.247func colorFg(val, color string) string {248 return termenv.String(val).Foreground(term.Color(color)).String()249}250251// Return a function that will colorize the foreground of a given string.252func makeFgStyle(color string) func(string) string {253 return termenv.Style{}.Foreground(term.Color(color)).Styled254}255250// Generate a blend of colors.257func makeRamp(colorA, colorB string, steps float64) (s []string) {251func makeRampStyles(colorA, colorB string, steps float64) (s []lipgloss.Style) {252 cA, _ := colorful.Hex(colorA)253 cB, _ := colorful.Hex(colorB)254255 for i := 0.0; i < steps; i++ {256 c := cA.BlendLuv(cB, i/steps)263 s = append(s, colorToHex(c))257 s = append(s, lipgloss.NewStyle().Foreground(lipgloss.Color(colorToHex(c))))258 }259 return260}261268// Convert a colorful.Color to a hexadecimal format compatible with termenv.262// Convert a colorful.Color to a hexadecimal format.263func colorToHex(c colorful.Color) string {264 return fmt.Sprintf("#%s%s%s", colorFloatToHex(c.R), colorFloatToHex(c.G), colorFloatToHex(c.B))265}266
9 unmodified lines
added:examples/window-size/main.go+44 added
1package main23// A simple program that queries and displays the window-size.45import (6 "log"78 tea "github.com/charmbracelet/bubbletea"9)1011func main() {12 p := tea.NewProgram(model{})13 if _, err := p.Run(); err != nil {14 log.Fatal(err)15 }16}1718type model struct{}1920func (m model) Init() tea.Cmd {21 return nil22}2324func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {25 switch msg := msg.(type) {26 case tea.KeyMsg:27 if s := msg.String(); s == "ctrl+c" || s == "q" || s == "esc" {28 return m, tea.Quit29 }3031 return m, tea.WindowSize()3233 case tea.WindowSizeMsg:34 return m, tea.Printf("%dx%d", msg.Width, msg.Height)35 }3637 return m, nil38}3940func (m model) View() string {41 s := "When you're done press q to quit. Press any other key to query the window-size.\n"4243 return s44}
modified:examples/go.mod+34 added-27 removed
1module examples23go 1.173go 1.24.045toolchain go1.24.567require (6 github.com/charmbracelet/bubbles v0.16.2-0.20230821152602-eda891258c027 github.com/charmbracelet/bubbletea v0.24.28 github.com/charmbracelet/glamour v0.6.08 github.com/charmbracelet/bubbles v0.21.09 github.com/charmbracelet/bubbletea v1.3.410 github.com/charmbracelet/glamour v0.10.011 github.com/charmbracelet/harmonica v0.2.010 github.com/charmbracelet/lipgloss v0.9.111 github.com/charmbracelet/x/exp/teatest v0.0.0-20230508155401-2bd6fa14c46a12 github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c66083413 github.com/charmbracelet/x/exp/teatest v0.0.0-20240521184646-23081fb03b2814 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf177615 github.com/lucasb-eyer/go-colorful v1.2.014 github.com/mattn/go-isatty v0.0.1815 github.com/muesli/reflow v0.3.016 github.com/muesli/termenv v0.15.216 github.com/mattn/go-isatty v0.0.2017)1819require (20 github.com/alecthomas/chroma v0.10.0 // indirect20 github.com/alecthomas/chroma/v2 v2.14.0 // indirect21 github.com/atotto/clipboard v0.1.4 // indirect22 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect23 github.com/aymanbagabas/go-udiff v0.1.0 // indirect23 github.com/aymanbagabas/go-udiff v0.2.0 // indirect24 github.com/aymerick/douceur v0.2.0 // indirect25 github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect26 github.com/dlclark/regexp2 v1.4.0 // indirect25 github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect26 github.com/charmbracelet/x/ansi v0.10.1 // indirect27 github.com/charmbracelet/x/cellbuf v0.0.13 // indirect28 github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 // indirect29 github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect30 github.com/charmbracelet/x/term v0.2.1 // indirect31 github.com/dlclark/regexp2 v1.11.0 // indirect32 github.com/dustin/go-humanize v1.0.1 // indirect33 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect28 github.com/gorilla/css v1.0.0 // indirect34 github.com/gorilla/css v1.0.1 // indirect35 github.com/mattn/go-localereader v0.0.1 // indirect30 github.com/mattn/go-runewidth v0.0.15 // indirect31 github.com/microcosm-cc/bluemonday v1.0.21 // indirect32 github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect36 github.com/mattn/go-runewidth v0.0.16 // indirect37 github.com/microcosm-cc/bluemonday v1.0.27 // indirect38 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect39 github.com/muesli/cancelreader v0.2.2 // indirect34 github.com/olekukonko/tablewriter v0.0.5 // indirect35 github.com/rivo/uniseg v0.2.0 // indirect36 github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f // indirect37 github.com/yuin/goldmark v1.5.2 // indirect38 github.com/yuin/goldmark-emoji v1.0.1 // indirect39 golang.org/x/net v0.17.0 // indirect40 golang.org/x/sync v0.1.0 // indirect41 golang.org/x/sys v0.13.0 // indirect42 golang.org/x/term v0.13.0 // indirect43 golang.org/x/text v0.13.0 // indirect40 github.com/muesli/reflow v0.3.0 // indirect41 github.com/muesli/termenv v0.16.0 // indirect42 github.com/rivo/uniseg v0.4.7 // indirect43 github.com/sahilm/fuzzy v0.1.1 // indirect44 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect45 github.com/yuin/goldmark v1.7.8 // indirect46 github.com/yuin/goldmark-emoji v1.0.5 // indirect47 golang.org/x/net v0.38.0 // indirect48 golang.org/x/sys v0.36.0 // indirect49 golang.org/x/term v0.31.0 // indirect50 golang.org/x/text v0.24.0 // indirect51)5253replace github.com/charmbracelet/bubbletea => ../
modified:examples/go.sum+70 added-113 removed
1github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek=2github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s=1github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=2github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=3github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE=4github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=5github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E=6github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I=7github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=8github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=9github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=10github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=5github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4=6github.com/aymanbagabas/go-osc52 v1.2.1 h1:q2sWUyDcozPLcLabEMd+a+7Ea2DitxZVN9hTxab9L4E=7github.com/aymanbagabas/go-osc52 v1.2.1/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4=11github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=12github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=10github.com/aymanbagabas/go-udiff v0.1.0 h1:9Dpklm2oBBhMxIFbMffmPvDaF7vOYfv9B5HXVr42KMU=11github.com/aymanbagabas/go-udiff v0.1.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=13github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=14github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=15github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=16github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=14github.com/charmbracelet/bubbles v0.16.2-0.20230821152602-eda891258c02 h1:MruS04uPbUJHF0MQzwOlh9yco1pHwPDLI7qGMu25IME=15github.com/charmbracelet/bubbles v0.16.2-0.20230821152602-eda891258c02/go.mod h1:XUdibuVUiMfcfKTRla58bmY3TWsdjgF+Rp8pvimQLck=16github.com/charmbracelet/glamour v0.6.0 h1:wi8fse3Y7nfcabbbDuwolqTqMQPMnVPeZhDM273bISc=17github.com/charmbracelet/glamour v0.6.0/go.mod h1:taqWV4swIMMbWALc0m7AfE9JkPSU8om2538k9ITBxOc=17github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=18github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=19github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=20github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=21github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY=22github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk=23github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=24github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=20github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNWpFujkNawKNhE2c=21github.com/charmbracelet/lipgloss v0.9.1 h1:PNyd3jvaJbg4jRHKWXnCj1akQm4rh8dbEzN1p/u1KWg=22github.com/charmbracelet/lipgloss v0.9.1/go.mod h1:1mPmG4cxScwUQALAAnacHaigiiHB9Pmr+v1VEawJl6I=23github.com/charmbracelet/x/exp/teatest v0.0.0-20230508155401-2bd6fa14c46a h1:GpNt24LKE8sH5G0SZUpu4Tg15sP5XSt1mnfIqE7fW34=24github.com/charmbracelet/x/exp/teatest v0.0.0-20230508155401-2bd6fa14c46a/go.mod h1:dpMo6PfGlhavn+ofggWhfFQmK9sZB2Ewljiz9bZtKVI=25github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=26github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=27github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=28github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=29github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=30github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E=31github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=25github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE=26github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA=27github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=28github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=29github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k=30github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=31github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=32github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=33github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI=34github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU=35github.com/charmbracelet/x/exp/teatest v0.0.0-20240521184646-23081fb03b28 h1:sOWKNRjt8uOEVgPiJVIJCse1+mUDM2F/vYY6W0Go640=36github.com/charmbracelet/x/exp/teatest v0.0.0-20240521184646-23081fb03b28/go.mod h1:l1w+LTJZCCozeGzMEWGxRw6Mo2DfcZUvupz8HGubdes=37github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=38github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=39github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=40github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=41github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=42github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=43github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=44github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=45github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776 h1:VRIbnDWRmAh5yBdz+J6yFMF5vso1It6vn+WmM/5l7MA=46github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776/go.mod h1:9wvnDu3YOfxzWM9Cst40msBF1C2UdQgDv962oTxSuMs=36github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=37github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=47github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=48github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=49github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=50github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=51github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=52github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=53github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=54github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=42github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=43github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=44github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=45github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=55github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=56github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=57github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=58github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=48github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=59github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=50github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=51github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=52github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=53github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=54github.com/microcosm-cc/bluemonday v1.0.21 h1:dNH3e4PSyE4vNX+KlRGHT5KrSvjeUkoNPwEORjffHJg=55github.com/microcosm-cc/bluemonday v1.0.21/go.mod h1:ytNkv4RrDrLJ2pqlsSI46O6IVXmZOBBD4SaJyDwwTkM=56github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=57github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=60github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=61github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=62github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=63github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=64github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=65github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=66github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=67github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=68github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=69github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=62github.com/muesli/termenv v0.13.0/go.mod h1:sP1+uffeLaEYpyOTb8pLCUctGcGLnoFjSn4YJK5e2bc=63github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ=64github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=65github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=66github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=67github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=68github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=69github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=70github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=71github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=72github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=71github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=73github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=73github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f h1:MvTmaQdww/z0Q4wrYjDSCcZ78NoftLQyHBSLW/Cx79Y=74github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=75github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=76github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=77github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=78github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=79github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=80github.com/yuin/goldmark v1.5.2 h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU=81github.com/yuin/goldmark v1.5.2/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=82github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os=83github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ=84golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=85golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=86golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=87golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=88golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=89golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=90golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=91golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=92golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=93golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=94golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=95golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=96golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=97golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=98golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=99golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=100golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=101golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=102golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=103golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=104golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=105golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=106golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=107golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=108golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=109golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=110golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=74github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=75github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=76github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=77github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=78github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=79github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=80github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=81github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=82github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=83github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk=84github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=85golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=86golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=87golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=88golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=89golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=90golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=112golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=113golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=114golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=115golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=116golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=117golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=118golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=119golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=120golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=121golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=122golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek=123golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=124golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=125golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=126golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=127golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=128golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=129golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=130golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=131golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=132golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=133golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=134golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=135golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=136golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=137gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=138gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=139gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=91golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=92golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=93golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=94golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=95golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=96golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
modified:examples/README.md+1 added-1 removed
28 unmodified lines
2930### Credit Card Form3132The `credit-card-form` example demonstrates how to build a multi-step form with33`textinput`s bubbles and validation on the inputs.33`textinputs` bubbles and validation on the inputs.3435<a href="./credit-card-form/main.go">36 <img width="750" src="./credit-card-form/credit-card-form.gif" />37</a>
291 unmodified lines
modified:tutorials/basics/main.go+1 added-1 removed
23 unmodified lines
24 }25}2627func (m model) Init() tea.Cmd {28 return nil28 return tea.SetWindowTitle("Grocery List")29}3031func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {32 switch msg := msg.(type) {
54 unmodified lines
modified:tutorials/commands/README.md+1 added-1 removed
163 unmodified lines
164## Run the program165166The only thing left to do is run the program, so let's do that! Our initial167model doesn't need any data at all in this case, we just initialize it with168as a `struct` with defaults.168a `model` struct with default values.169170```go171func main() {172 if _, err := tea.NewProgram(model{}).Run(); err != nil {
75 unmodified lines
modified:tutorials/go.mod+13 added-12 removed
1module tutorial23go 1.173go 1.1845require github.com/charmbracelet/bubbletea v0.23.25require github.com/charmbracelet/bubbletea v0.25.067require (8 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect9 github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect9 github.com/charmbracelet/lipgloss v0.13.1 // indirect10 github.com/charmbracelet/x/ansi v0.4.0 // indirect11 github.com/charmbracelet/x/term v0.2.0 // indirect12 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect13 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect11 github.com/mattn/go-isatty v0.0.18 // indirect14 github.com/mattn/go-isatty v0.0.20 // indirect15 github.com/mattn/go-localereader v0.0.1 // indirect13 github.com/mattn/go-runewidth v0.0.14 // indirect14 github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect16 github.com/mattn/go-runewidth v0.0.15 // indirect17 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect18 github.com/muesli/cancelreader v0.2.2 // indirect16 github.com/muesli/reflow v0.3.0 // indirect19 github.com/muesli/termenv v0.15.2 // indirect18 github.com/rivo/uniseg v0.2.0 // indirect19 golang.org/x/sync v0.1.0 // indirect20 golang.org/x/sys v0.7.0 // indirect21 golang.org/x/term v0.6.0 // indirect22 golang.org/x/text v0.3.8 // indirect20 github.com/rivo/uniseg v0.4.7 // indirect21 golang.org/x/sync v0.8.0 // indirect22 golang.org/x/sys v0.26.0 // indirect23 golang.org/x/text v0.13.0 // indirect24)2526replace github.com/charmbracelet/bubbletea => ../
modified:tutorials/go.sum+23 added-47 removed
1github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=2github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=3github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=4github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=3github.com/charmbracelet/lipgloss v0.13.1 h1:Oik/oqDTMVA01GetT4JdEC033dNzWoQHdWnHnQmXE2A=4github.com/charmbracelet/lipgloss v0.13.1/go.mod h1:zaYVJ2xKSKEnTEEbX6uAHabh2d975RJ+0yfkFpRBz5U=5github.com/charmbracelet/x/ansi v0.4.0 h1:NqwHA4B23VwsDn4H3VcNX1W1tOmgnvY1NDx5tOXdnOU=6github.com/charmbracelet/x/ansi v0.4.0/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=7github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0=8github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=9github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=10github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=11github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=12github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=7github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=8github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=13github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=14github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=15github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=16github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=11github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=12github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=13github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=14github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=15github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=16github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=17github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=18github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=19github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=20github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=21github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=22github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=19github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=20github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=23github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=24github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=23github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=24github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=25github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=26github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=27golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=28golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=29golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=30golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=31golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=32golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=33golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=34golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=35golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=36golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=37golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=38golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=39golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=40golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=41golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=42golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=43golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=26github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=27github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=28golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=29golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=30golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=31golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=45golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=46golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=47golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=48golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=49golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=50golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=51golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=52golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=53golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=54golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=55golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=56golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=57golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=58golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=59golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=32golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=33golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=34golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=35golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
modified:.gitignore+1 added
18 unmodified lines
19tutorials/basics/basics20tutorials/commands/commands21.idea22coverage.txt23dist/
deleted:.golangci-soft.yml-47 removed
1run:2 tests: false34issues:5 include:6 - EXC00017 - EXC00058 - EXC00119 - EXC001210 - EXC00131112 max-issues-per-linter: 013 max-same-issues: 01415linters:16 enable:17 # - dupl18 - exhaustive19 # - exhaustivestruct20 - goconst21 - godot22 - godox23 - gomnd24 - gomoddirectives25 - goprintffuncname26 - ifshort27 # - lll28 - misspell29 - nakedret30 - nestif31 - noctx32 - nolintlint33 - prealloc34 - wrapcheck3536 # disable default linters, they are already enabled in .golangci.yml37 disable:38 - deadcode39 - errcheck40 - gosimple41 - govet42 - ineffassign43 - staticcheck44 - structcheck45 - typecheck46 - unused47 - varcheck
modified:.golangci.yml+30 added-15 removed
1version: "2"2run:3 tests: false34issues:5 include:6 - EXC00017 - EXC00058 - EXC00119 - EXC001210 - EXC00131112 max-issues-per-linter: 013 max-same-issues: 0144linters:5 enable:6 - bodyclose18 - exportloopref19 - goimports7 - exhaustive8 - goconst9 - godot10 - gomoddirectives11 - goprintffuncname12 - gosec13 - misspell14 - nakedret15 - nestif16 - nilerr22 - predeclared17 - noctx18 - nolintlint19 - prealloc20 - revive21 - rowserrcheck22 - sqlclosecheck23 - tparallel24 - unconvert25 - unparam26 - whitespace27 - wrapcheck28 exclusions:29 rules:30 - text: '(slog|log)\.\w+'31 linters:32 - noctx33 generated: lax34 presets:35 - common-false-positives36issues:37 max-issues-per-linter: 038 max-same-issues: 039formatters:40 enable:41 - gofumpt42 - goimports43 exclusions:44 generated: lax
added:.goreleaser.yml+5 added
1# yaml-language-server: $schema=https://goreleaser.com/static/schema-pro.json2version: 23includes:4 - from_url:5 url: charmbracelet/meta/main/goreleaser-lib.yaml
modified:commands_test.go+15 added-7 removed
80 unmodified lines
81 }82}8384func TestBatch(t *testing.T) {85 testMultipleCommands[BatchMsg](t, Batch)86}8788func TestSequence(t *testing.T) {89 testMultipleCommands[sequenceMsg](t, Sequence)90}9192func testMultipleCommands[T ~[]Cmd](t *testing.T, createFn func(cmd ...Cmd) Cmd) {93 t.Run("nil cmd", func(t *testing.T) {86 if b := Batch(nil); b != nil {94 if b := createFn(nil); b != nil {95 t.Fatalf("expected nil, got %+v", b)96 }97 })98 t.Run("empty cmd", func(t *testing.T) {91 if b := Batch(); b != nil {99 if b := createFn(); b != nil {100 t.Fatalf("expected nil, got %+v", b)101 }102 })103 t.Run("single cmd", func(t *testing.T) {96 b := Batch(Quit)()97 if l := len(b.(BatchMsg)); l != 1 {98 t.Fatalf("expected a []Cmd with len 1, got %d", l)104 b := createFn(Quit)()105 if _, ok := b.(QuitMsg); !ok {106 t.Fatalf("expected a QuitMsg, got %T", b)107 }108 })109 t.Run("mixed nil cmds", func(t *testing.T) {102 b := Batch(nil, Quit, nil, Quit, nil, nil)()103 if l := len(b.(BatchMsg)); l != 2 {110 b := createFn(nil, Quit, nil, Quit, nil, nil)()111 if l := len(b.(T)); l != 2 {112 t.Fatalf("expected a []Cmd with len 2, got %d", l)113 }114 })115}
modified:commands.go+72 added-22 removed
11 unmodified lines
12// func (m model) Init() Cmd {13// return tea.Batch(someCommand, someOtherCommand)14// }15func Batch(cmds ...Cmd) Cmd {16 var validCmds []Cmd //nolint:prealloc17 for _, c := range cmds {18 if c == nil {19 continue20 }21 validCmds = append(validCmds, c)22 }23 if len(validCmds) == 0 {24 return nil25 }26 return func() Msg {27 return BatchMsg(validCmds)28 }16 return compactCmds[BatchMsg](cmds)17}1819// BatchMsg is a message used to perform a bunch of commands concurrently with20// no ordering guarantees. You can send a BatchMsg with Batch.
1 unmodified line
2223// Sequence runs the given commands one at a time, in order. Contrast this with24// Batch, which runs commands concurrently.25func Sequence(cmds ...Cmd) Cmd {38 return func() Msg {39 return sequenceMsg(cmds)40 }26 return compactCmds[sequenceMsg](cmds)27}2829// sequenceMsg is used internally to run the given commands in order.30type sequenceMsg []Cmd3132// compactCmds ignores any nil commands in cmds, and returns the most direct33// command possible. That is, considering the non-nil commands, if there are34// none it returns nil, if there is exactly one it returns that command35// directly, else it returns the non-nil commands as type T.36func compactCmds[T ~[]Cmd](cmds []Cmd) Cmd {37 var validCmds []Cmd //nolint:prealloc38 for _, c := range cmds {39 if c == nil {40 continue41 }42 validCmds = append(validCmds, c)43 }44 switch len(validCmds) {45 case 0:46 return nil47 case 1:48 return validCmds[0]49 default:50 return func() Msg {51 return T(validCmds)52 }53 }54}5556// Every is a command that ticks in sync with the system clock. So, if you57// wanted to tick with the system clock every second, minute or hour you58// could use this. It's also handy for having different things tick in sync.59//
39 unmodified lines
99// }100//101// Every is analogous to Tick in the Elm Architecture.102func Every(duration time.Duration, fn func(time.Time) Msg) Cmd {103 n := time.Now()104 d := n.Truncate(duration).Add(duration).Sub(n)105 t := time.NewTimer(d)106 return func() Msg {94 n := time.Now()95 d := n.Truncate(duration).Add(duration).Sub(n)96 t := time.NewTimer(d)97 return fn(<-t.C)107 ts := <-t.C108 t.Stop()109 for len(t.C) > 0 {110 <-t.C111 }112 return fn(ts)113 }114}115116// Tick produces a command at an interval independent of the system clock at
34 unmodified lines
151// }152// return m, nil153// }154func Tick(d time.Duration, fn func(time.Time) Msg) Cmd {155 t := time.NewTimer(d)156 return func() Msg {141 t := time.NewTimer(d)142 return fn(<-t.C)157 ts := <-t.C158 t.Stop()159 for len(t.C) > 0 {160 <-t.C161 }162 return fn(ts)163 }164}165166// Sequentially produces a command that sequentially executes the given
22 unmodified lines
189 }190 return nil191 }192}193194// setWindowTitleMsg is an internal message used to set the window title.195type setWindowTitleMsg string196197// SetWindowTitle produces a command that sets the terminal title.198//199// For example:200//201// func (m model) Init() Cmd {202// // Set title.203// return tea.SetWindowTitle("My App")204// }205func SetWindowTitle(title string) Cmd {206 return func() Msg {207 return setWindowTitleMsg(title)208 }209}210211type windowSizeMsg struct{}212213// WindowSize is a command that queries the terminal for its current size. It214// delivers the results to Update via a [WindowSizeMsg]. Keep in mind that215// WindowSizeMsgs will automatically be delivered to Update when the [Program]216// starts and when the window dimensions change so in many cases you will not217// need to explicitly invoke this command.218func WindowSize() Cmd {219 return func() Msg {220 return windowSizeMsg{}221 }222}
deleted:CONTRIBUTING.md-13 removed
1# Contributing23Pull requests are welcome for any changes.45Consider opening an issue for larger changes to get feedback on the idea from the team.67If your change touches parts of the Bubble Tea renderer or internals, make sure8that all the examples in the `examples/` folder continue to run correctly.910For commit messages, please use conventional commits[^1] to make it easier to11generate release notes.1213[^1]: https://www.conventionalcommits.org/en/v1.0.0
modified:exec_test.go+34 added-12 removed
1 unmodified line
23import (4 "bytes"5 "os/exec"6 "runtime"7 "testing"8)910type execFinishedMsg struct{ err error }
25 unmodified lines
36func (m *testExecModel) View() string {37 return "\n"38}3940type spyRenderer struct {41 renderer42 calledReset bool43}4445func (r *spyRenderer) resetLinesRendered() {46 r.calledReset = true47 r.renderer.resetLinesRendered()48}4950func TestTeaExec(t *testing.T) {40 tests := []struct {51 type test struct {52 name string53 cmd string54 expectErr bool44 }{55 }56 tests := []test{57 {46 name: "true",47 cmd: "true",48 expectErr: false,49 },50 {51 name: "false",52 cmd: "false",53 expectErr: true,54 },55 {58 name: "invalid command",59 cmd: "invalid",60 expectErr: true,61 },62 }6364 if runtime.GOOS != "windows" {65 tests = append(tests, []test{66 {67 name: "true",68 cmd: "true",69 expectErr: false,70 },71 {72 name: "false",73 cmd: "false",74 expectErr: true,75 },76 }...)77 }7879 for _, test := range tests {80 t.Run(test.name, func(t *testing.T) {81 var buf bytes.Buffer82 var in bytes.Buffer
2 unmodified lines
85 p := NewProgram(m, WithInput(&in), WithOutput(&buf))86 if _, err := p.Run(); err != nil {87 t.Error(err)88 }89 p.renderer = &spyRenderer{renderer: p.renderer}9091 if m.err != nil && !test.expectErr {92 t.Errorf("expected no error, got %v", m.err)9394 if !p.renderer.(*spyRenderer).calledReset {95 t.Error("expected renderer to be reset")96 }97 }98 if m.err == nil && test.expectErr {99 t.Error("expected error, got nil")100 }
3 unmodified lines
modified:exec.go+5 added-1 removed
107 unmodified lines
108 return109 }110111 c.SetStdin(p.input)112 c.SetStdout(p.output.TTY())112 c.SetStdout(p.output)113 c.SetStderr(os.Stderr)114115 // Execute system command.116 if err := c.Run(); err != nil {117 p.renderer.resetLinesRendered()118 _ = p.RestoreTerminal() // also try to restore the terminal.119 if fn != nil {120 go p.Send(fn(err))121 }122 return123 }124125 // Maintain the existing output from the command126 p.renderer.resetLinesRendered()127128 // Have the program re-capture input.129 err := p.RestoreTerminal()130 if fn != nil {131 go p.Send(fn(err))
2 unmodified lines
added:focus.go+9 added
1package tea23// FocusMsg represents a terminal focus message.4// This occurs when the terminal gains focus.5type FocusMsg struct{}67// BlurMsg represents a terminal blur message.8// This occurs when the terminal loses focus.9type BlurMsg struct{}
modified:go.mod+14 added-11 removed
1module github.com/charmbracelet/bubbletea23go 1.173go 1.24.045require (6 github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac817 github.com/mattn/go-isatty v0.0.186 github.com/charmbracelet/lipgloss v1.1.07 github.com/charmbracelet/x/ansi v0.10.18 github.com/charmbracelet/x/term v0.2.19 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f10 github.com/mattn/go-localereader v0.0.19 github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b11 github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f612 github.com/muesli/cancelreader v0.2.211 github.com/muesli/reflow v0.3.012 github.com/muesli/termenv v0.15.213 golang.org/x/sync v0.1.013 golang.org/x/sys v0.36.014 golang.org/x/term v0.6.014)1516require (17 github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect18 github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect19 github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect20 github.com/lucasb-eyer/go-colorful v1.2.0 // indirect20 github.com/mattn/go-runewidth v0.0.14 // indirect21 github.com/rivo/uniseg v0.2.0 // indirect22 golang.org/x/sys v0.7.0 // indirect21 github.com/mattn/go-isatty v0.0.20 // indirect22 github.com/mattn/go-runewidth v0.0.16 // indirect23 github.com/muesli/termenv v0.16.0 // indirect24 github.com/rivo/uniseg v0.4.7 // indirect25 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect26 golang.org/x/text v0.3.8 // indirect27)
modified:go.sum+29 added-47 removed
1github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=2github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=3github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=4github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=3github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=4github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=5github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=6github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=7github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=8github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=9github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=10github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=11github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=12github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=13github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=14github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=15github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=16github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=7github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=8github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=17github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=18github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=19github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=20github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=11github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=12github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=13github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=14github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=15github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=16github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=21github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=22github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=23github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=24github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=25github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=26github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=19github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=20github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=21github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=22github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=23github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=24github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=27github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=28github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=29github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=26github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=27golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=28golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=29golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=30golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=31golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=32golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=33golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=34golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=35golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=36golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=37golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=38golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=39golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=40golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=41golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=42golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=43golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=30github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=31github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=32github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=33github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=34golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=35golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=36golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=37golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=45golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=46golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=47golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=48golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=49golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=50golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=51golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=52golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=53golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=38golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=39golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=40golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=41golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=56golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=57golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=58golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=59golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
added:inputreader_other.go+19 added
1//go:build !windows2// +build !windows34package tea56import (7 "fmt"8 "io"910 "github.com/muesli/cancelreader"11)1213func newInputReader(r io.Reader, _ bool) (cancelreader.CancelReader, error) {14 cr, err := cancelreader.NewReader(r)15 if err != nil {16 return nil, fmt.Errorf("bubbletea: error creating cancel reader: %w", err)17 }18 return cr, nil19}
added:inputreader_windows.go+129 added
1//go:build windows2// +build windows34package tea56import (7 "fmt"8 "io"9 "os"10 "sync"1112 "github.com/charmbracelet/x/term"13 "github.com/erikgeiser/coninput"14 "github.com/muesli/cancelreader"15 "golang.org/x/sys/windows"16)1718type conInputReader struct {19 cancelMixin2021 conin windows.Handle2223 originalMode uint3224}2526var _ cancelreader.CancelReader = &conInputReader{}2728func newInputReader(r io.Reader, enableMouse bool) (cancelreader.CancelReader, error) {29 fallback := func(io.Reader) (cancelreader.CancelReader, error) {30 return cancelreader.NewReader(r)31 }32 if f, ok := r.(term.File); !ok || f.Fd() != os.Stdin.Fd() {33 return fallback(r)34 }3536 conin, err := coninput.NewStdinHandle()37 if err != nil {38 return fallback(r)39 }4041 modes := []uint32{42 windows.ENABLE_WINDOW_INPUT,43 windows.ENABLE_EXTENDED_FLAGS,44 }4546 // Since we have options to enable mouse events, [WithMouseCellMotion],47 // [WithMouseAllMotion], and [EnableMouseCellMotion],48 // [EnableMouseAllMotion], and [DisableMouse], we need to check if the user49 // has enabled mouse events and add the appropriate mode accordingly.50 // Otherwise, mouse events will be enabled all the time.51 if enableMouse {52 modes = append(modes, windows.ENABLE_MOUSE_INPUT)53 }5455 originalMode, err := prepareConsole(conin, modes...)56 if err != nil {57 return nil, fmt.Errorf("failed to prepare console input: %w", err)58 }5960 return &conInputReader{61 conin: conin,62 originalMode: originalMode,63 }, nil64}6566// Cancel implements cancelreader.CancelReader.67func (r *conInputReader) Cancel() bool {68 r.setCanceled()6970 // Warning: These cancel methods do not reliably work on console input71 // and should not be counted on.72 return windows.CancelIoEx(r.conin, nil) == nil || windows.CancelIo(r.conin) == nil73}7475// Close implements cancelreader.CancelReader.76func (r *conInputReader) Close() error {77 if r.originalMode != 0 {78 err := windows.SetConsoleMode(r.conin, r.originalMode)79 if err != nil {80 return fmt.Errorf("reset console mode: %w", err)81 }82 }8384 return nil85}8687// Read implements cancelreader.CancelReader.88func (r *conInputReader) Read(_ []byte) (n int, err error) {89 if r.isCanceled() {90 err = cancelreader.ErrCanceled91 }92 return93}9495func prepareConsole(input windows.Handle, modes ...uint32) (originalMode uint32, err error) {96 err = windows.GetConsoleMode(input, &originalMode)97 if err != nil {98 return 0, fmt.Errorf("get console mode: %w", err)99 }100101 newMode := coninput.AddInputModes(0, modes...)102103 err = windows.SetConsoleMode(input, newMode)104 if err != nil {105 return 0, fmt.Errorf("set console mode: %w", err)106 }107108 return originalMode, nil109}110111// cancelMixin represents a goroutine-safe cancellation status.112type cancelMixin struct {113 unsafeCanceled bool114 lock sync.Mutex115}116117func (c *cancelMixin) setCanceled() {118 c.lock.Lock()119 defer c.lock.Unlock()120121 c.unsafeCanceled = true122}123124func (c *cancelMixin) isCanceled() bool {125 c.lock.Lock()126 defer c.lock.Unlock()127128 return c.unsafeCanceled129}
added:key_other.go+13 added
1//go:build !windows2// +build !windows34package tea56import (7 "context"8 "io"9)1011func readInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {12 return readAnsiInputs(ctx, msgs, input)13}
modified:key_sequences.go+60 added-1 removed
1package tea23import "sort"3import (4 "bytes"5 "sort"6 "unicode/utf8"7)89// extSequences is used by the map-based algorithm below. It contains10// the sequences plus their alternatives with an escape character11// prefixed, plus the control chars, plus the space.
60 unmodified lines
72 }7374 return false, 0, nil75}7677// detectBracketedPaste detects an input pasted while bracketed78// paste mode was enabled.79//80// Note: this function is a no-op if bracketed paste was not enabled81// on the terminal, since in that case we'd never see this82// particular escape sequence.83func detectBracketedPaste(input []byte) (hasBp bool, width int, msg Msg) {84 // Detect the start sequence.85 const bpStart = "\x1b[200~"86 if len(input) < len(bpStart) || string(input[:len(bpStart)]) != bpStart {87 return false, 0, nil88 }8990 // Skip over the start sequence.91 input = input[len(bpStart):]9293 // If we saw the start sequence, then we must have an end sequence94 // as well. Find it.95 const bpEnd = "\x1b[201~"96 idx := bytes.Index(input, []byte(bpEnd))97 inputLen := len(bpStart) + idx + len(bpEnd)98 if idx == -1 {99 // We have encountered the end of the input buffer without seeing100 // the marker for the end of the bracketed paste.101 // Tell the outer loop we have done a short read and we want more.102 return true, 0, nil103 }104105 // The paste is everything in-between.106 paste := input[:idx]107108 // All there is in-between is runes, not to be interpreted further.109 k := Key{Type: KeyRunes, Paste: true}110 for len(paste) > 0 {111 r, w := utf8.DecodeRune(paste)112 if r != utf8.RuneError {113 k.Runes = append(k.Runes, r)114 }115 paste = paste[w:]116 }117118 return true, inputLen, KeyMsg(k)119}120121// detectReportFocus detects a focus report sequence.122func detectReportFocus(input []byte) (hasRF bool, width int, msg Msg) {123 switch {124 case bytes.Equal(input, []byte("\x1b[I")):125 return true, 3, FocusMsg{} //nolint:mnd126 case bytes.Equal(input, []byte("\x1b[O")):127 return true, 3, BlurMsg{} //nolint:mnd128 }129 return false, 0, nil130}
modified:key_test.go+108 added-54 removed
132 unmodified lines
133 td := buildBaseSeqTests()134 // Add tests for the inputs that detectOneMsg() can parse, but135 // detectSequence() cannot.136 td = append(td,137 // focus/blur138 seqTest{139 []byte{'\x1b', '[', 'I'},140 FocusMsg{},141 },142 seqTest{143 []byte{'\x1b', '[', 'O'},144 BlurMsg{},145 },146 // Mouse event.147 seqTest{148 []byte{'\x1b', '[', 'M', byte(32) + 0b0100_0000, byte(65), byte(49)},140 MouseMsg{X: 32, Y: 16, Type: MouseWheelUp},149 MouseMsg{X: 32, Y: 16, Type: MouseWheelUp, Button: MouseButtonWheelUp, Action: MouseActionPress},150 },151 // SGR Mouse event.152 seqTest{153 []byte("\x1b[<0;33;17M"),154 MouseMsg{X: 32, Y: 16, Type: MouseLeft, Button: MouseButtonLeft, Action: MouseActionPress},155 },156 // Runes.157 seqTest{158 []byte{'a'},159 KeyMsg{Type: KeyRunes, Runes: []rune("a")},
90 unmodified lines
250 in []byte251 out []Msg252 }253 testData := []test{254 {240 {"a",255 "a",256 []byte{'a'},257 []Msg{258 KeyMsg{259 Type: KeyRunes,260 Runes: []rune{'a'},261 },262 },263 },249 {" ",264 {265 " ",266 []byte{' '},267 []Msg{268 KeyMsg{269 Type: KeySpace,270 Runes: []rune{' '},271 },272 },273 },274 {258 {"a alt+a",275 "a alt+a",276 []byte{'a', '\x1b', 'a'},277 []Msg{278 KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},279 KeyMsg{Type: KeyRunes, Runes: []rune{'a'}, Alt: true},280 },281 },282 {265 {"a alt+a a",283 "a alt+a a",284 []byte{'a', '\x1b', 'a', 'a'},285 []Msg{286 KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},287 KeyMsg{Type: KeyRunes, Runes: []rune{'a'}, Alt: true},288 KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},289 },290 },291 {273 {"ctrl+a",292 "ctrl+a",293 []byte{byte(keySOH)},294 []Msg{295 KeyMsg{296 Type: KeyCtrlA,297 },298 },299 },300 {281 {"ctrl+a ctrl+b",301 "ctrl+a ctrl+b",302 []byte{byte(keySOH), byte(keySTX)},303 []Msg{304 KeyMsg{Type: KeyCtrlA},305 KeyMsg{Type: KeyCtrlB},306 },307 },308 {288 {"alt+a",309 "alt+a",310 []byte{byte(0x1b), 'a'},311 []Msg{312 KeyMsg{313 Type: KeyRunes,
1 unmodified line
315 Runes: []rune{'a'},316 },317 },318 },319 {298 {"abcd",320 "abcd",321 []byte{'a', 'b', 'c', 'd'},322 []Msg{323 KeyMsg{324 Type: KeyRunes,325 Runes: []rune{'a', 'b', 'c', 'd'},326 },327 },328 },329 {307 {"up",330 "up",331 []byte("\x1b[A"),332 []Msg{333 KeyMsg{334 Type: KeyUp,335 },336 },337 },338 {315 {"wheel up",339 "wheel up",340 []byte{'\x1b', '[', 'M', byte(32) + 0b0100_0000, byte(65), byte(49)},341 []Msg{342 MouseMsg{319 X: 32,320 Y: 16,321 Type: MouseWheelUp,343 X: 32,344 Y: 16,345 Type: MouseWheelUp,346 Button: MouseButtonWheelUp,347 Action: MouseActionPress,348 },349 },350 },325 {"left release",351 {352 "left motion release",353 []byte{354 '\x1b', '[', 'M', byte(32) + 0b0010_0000, byte(32 + 33), byte(16 + 33),355 '\x1b', '[', 'M', byte(32) + 0b0000_0011, byte(64 + 33), byte(32 + 33),356 },357 []Msg{358 MouseMsg(MouseEvent{332 X: 32,333 Y: 16,334 Type: MouseLeft,359 X: 32,360 Y: 16,361 Type: MouseLeft,362 Button: MouseButtonLeft,363 Action: MouseActionMotion,364 }),365 MouseMsg(MouseEvent{337 X: 64,338 Y: 32,339 Type: MouseRelease,366 X: 64,367 Y: 32,368 Type: MouseRelease,369 Button: MouseButtonNone,370 Action: MouseActionRelease,371 }),372 },373 },374 {343 {"shift+tab",375 "shift+tab",376 []byte{'\x1b', '[', 'Z'},377 []Msg{378 KeyMsg{379 Type: KeyShiftTab,380 },381 },382 },383 {351 {"enter",384 "enter",385 []byte{'\r'},386 []Msg{KeyMsg{Type: KeyEnter}},387 },388 {355 {"alt+enter",389 "alt+enter",390 []byte{'\x1b', '\r'},391 []Msg{392 KeyMsg{393 Type: KeyEnter,394 Alt: true,395 },396 },397 },398 {364 {"insert",399 "insert",400 []byte{'\x1b', '[', '2', '~'},401 []Msg{402 KeyMsg{403 Type: KeyInsert,404 },405 },406 },407 {372 {"alt+ctrl+a",408 "alt+ctrl+a",409 []byte{'\x1b', byte(keySOH)},410 []Msg{411 KeyMsg{412 Type: KeyCtrlA,413 Alt: true,414 },415 },416 },417 {381 {"?CSI[45 45 45 45 88]?",418 "?CSI[45 45 45 45 88]?",419 []byte{'\x1b', '[', '-', '-', '-', '-', 'X'},420 []Msg{unknownCSISequenceMsg([]byte{'\x1b', '[', '-', '-', '-', '-', 'X'})},421 },422 // Powershell sequences.423 {386 {"up",424 "up",425 []byte{'\x1b', 'O', 'A'},426 []Msg{KeyMsg{Type: KeyUp}},427 },428 {390 {"down",429 "down",430 []byte{'\x1b', 'O', 'B'},431 []Msg{KeyMsg{Type: KeyDown}},432 },433 {394 {"right",434 "right",435 []byte{'\x1b', 'O', 'C'},436 []Msg{KeyMsg{Type: KeyRight}},437 },438 {398 {"left",439 "left",440 []byte{'\x1b', 'O', 'D'},441 []Msg{KeyMsg{Type: KeyLeft}},442 },443 {402 {"alt+enter",444 "alt+enter",445 []byte{'\x1b', '\x0d'},446 []Msg{KeyMsg{Type: KeyEnter, Alt: true}},447 },448 {406 {"alt+backspace",449 "alt+backspace",450 []byte{'\x1b', '\x7f'},451 []Msg{KeyMsg{Type: KeyBackspace, Alt: true}},452 },453 {410 {"ctrl+@",454 "ctrl+@",455 []byte{'\x00'},456 []Msg{KeyMsg{Type: KeyCtrlAt}},457 },458 {414 {"alt+ctrl+@",459 "alt+ctrl+@",460 []byte{'\x1b', '\x00'},461 []Msg{KeyMsg{Type: KeyCtrlAt, Alt: true}},462 },463 {418 {"esc",464 "esc",465 []byte{'\x1b'},466 []Msg{KeyMsg{Type: KeyEsc}},467 },468 {422 {"alt+esc",469 "alt+esc",470 []byte{'\x1b', '\x1b'},471 []Msg{KeyMsg{Type: KeyEsc, Alt: true}},472 },426 // Bracketed paste does not work yet.427 {"?CSI[50 48 48 126]? a b ?CSI[50 48 49 126]?",473 {474 "[a b] o",475 []byte{476 '\x1b', '[', '2', '0', '0', '~',477 'a', ' ', 'b',431 '\x1b', '[', '2', '0', '1', '~'},478 '\x1b', '[', '2', '0', '1', '~',479 'o',480 },481 []Msg{433 // What we expect once bracketed paste is recognized properly:434 //435 // KeyMsg{Type: KeyRunes, Runes: []rune("a b")},436 //437 // What we get instead (for now):438 unknownCSISequenceMsg{0x1b, 0x5b, 0x32, 0x30, 0x30, 0x7e},439 KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},440 KeyMsg{Type: KeySpace, Runes: []rune{' '}},441 KeyMsg{Type: KeyRunes, Runes: []rune{'b'}},482 KeyMsg{Type: KeyRunes, Runes: []rune("a b"), Paste: true},483 KeyMsg{Type: KeyRunes, Runes: []rune("o")},442 unknownCSISequenceMsg{0x1b, 0x5b, 0x32, 0x30, 0x31, 0x7e},484 },485 },486 {487 "[a\x03\nb]",488 []byte{489 '\x1b', '[', '2', '0', '0', '~',490 'a', '\x03', '\n', 'b',491 '\x1b', '[', '2', '0', '1', '~',492 },493 []Msg{494 KeyMsg{Type: KeyRunes, Runes: []rune("a\x03\nb"), Paste: true},495 },496 },497 }498 if runtime.GOOS != "windows" {499 // Sadly, utf8.DecodeRune([]byte(0xfe)) returns a valid rune on windows.500 // This is incorrect, but it makes our test fail if we try it out.501 testData = append(testData,450 test{"?0xfe?",502 test{503 "?0xfe?",504 []byte{'\xfe'},505 []Msg{unknownInputByteMsg(0xfe)},506 },454 test{"a ?0xfe? b",507 test{508 "a ?0xfe? b",509 []byte{'a', '\xfe', ' ', 'b'},510 []Msg{511 KeyMsg{Type: KeyRunes, Runes: []rune{'a'}},512 unknownInputByteMsg(0xfe),
55 unmodified lines
568 // Start the reader in the background.569 wg.Add(1)570 go func() {571 defer wg.Done()518 inputErr = readInputs(ctx, msgsC, input)572 inputErr = readAnsiInputs(ctx, msgsC, input)573 msgsC <- nil574 }()575576 var msgs []Msg
139 unmodified lines
716 })717 }718}719666// TestDetectRandomSequencesLex checks that the map-based sequence720// TestDetectRandomSequencesMap checks that the map-based sequence721// detector works over concatenations of random sequences.722func TestDetectRandomSequencesMap(t *testing.T) {723 runTestDetectSequence(t, detectSequence)724}
11 unmodified lines
added:key_windows.go+441 added
1//go:build windows2// +build windows34package tea56import (7 "context"8 "fmt"9 "io"10 "time"1112 "github.com/erikgeiser/coninput"13 localereader "github.com/mattn/go-localereader"14 "github.com/muesli/cancelreader"15)1617func readInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {18 if coninReader, ok := input.(*conInputReader); ok {19 return readConInputs(ctx, msgs, coninReader)20 }2122 return readAnsiInputs(ctx, msgs, localereader.NewReader(input))23}2425func readConInputs(ctx context.Context, msgsch chan<- Msg, con *conInputReader) error {26 var ps coninput.ButtonState // keep track of previous mouse state27 var ws coninput.WindowBufferSizeEventRecord // keep track of the last window size event28 for {29 events, err := peekAndReadConsInput(con)30 if err != nil {31 return err32 }33 for _, event := range events {34 var msgs []Msg35 switch e := event.Unwrap().(type) {36 case coninput.KeyEventRecord:37 if !e.KeyDown || e.VirtualKeyCode == coninput.VK_SHIFT {38 continue39 }4041 for i := 0; i < int(e.RepeatCount); i++ {42 eventKeyType := keyType(e)43 var runes []rune4445 // Add the character only if the key type is an actual character and not a control sequence.46 // This mimics the behavior in readAnsiInputs where the character is also removed.47 // We don't need to handle KeySpace here. See the comment in keyType().48 if eventKeyType == KeyRunes {49 runes = []rune{e.Char}50 }5152 msgs = append(msgs, KeyMsg{53 Type: eventKeyType,54 Runes: runes,55 Alt: e.ControlKeyState.Contains(coninput.LEFT_ALT_PRESSED | coninput.RIGHT_ALT_PRESSED),56 })57 }58 case coninput.WindowBufferSizeEventRecord:59 if e != ws {60 ws = e61 msgs = append(msgs, WindowSizeMsg{62 Width: int(e.Size.X),63 Height: int(e.Size.Y),64 })65 }66 case coninput.MouseEventRecord:67 event := mouseEvent(ps, e)68 if event.Type != MouseUnknown {69 msgs = append(msgs, event)70 }71 ps = e.ButtonState72 case coninput.FocusEventRecord, coninput.MenuEventRecord:73 // ignore74 default: // unknown event75 continue76 }7778 // Send all messages to the channel79 for _, msg := range msgs {80 select {81 case msgsch <- msg:82 case <-ctx.Done():83 err := ctx.Err()84 if err != nil {85 return fmt.Errorf("coninput context error: %w", err)86 }87 return nil88 }89 }90 }91 }92}9394// Peek for new input in a tight loop and then read the input.95// windows.CancelIo* does not work reliably so peek first and only use the data if96// the console input is not cancelled.97func peekAndReadConsInput(con *conInputReader) ([]coninput.InputRecord, error) {98 events, err := peekConsInput(con)99 if err != nil {100 return events, err101 }102 events, err = coninput.ReadNConsoleInputs(con.conin, intToUint32OrDie(len(events)))103 if con.isCanceled() {104 return events, cancelreader.ErrCanceled105 }106 if err != nil {107 return events, fmt.Errorf("read coninput events: %w", err)108 }109 return events, nil110}111112// Convert i to unit32 or panic if it cannot be converted. Check satisfies lint G115.113func intToUint32OrDie(i int) uint32 {114 if i < 0 {115 panic("cannot convert numEvents " + fmt.Sprint(i) + " to uint32")116 }117 return uint32(i) //nolint:gosec118}119120// Keeps peeking until there is data or the input is cancelled.121func peekConsInput(con *conInputReader) ([]coninput.InputRecord, error) {122 for {123 events, err := coninput.PeekNConsoleInputs(con.conin, 16)124 if con.isCanceled() {125 return events, cancelreader.ErrCanceled126 }127 if err != nil {128 return events, fmt.Errorf("peek coninput events: %w", err)129 }130 if len(events) > 0 {131 return events, nil132 }133 // Sleep for a bit to avoid busy waiting.134 time.Sleep(16 * time.Millisecond)135 }136}137138func mouseEventButton(p, s coninput.ButtonState) (button MouseButton, action MouseAction) {139 btn := p ^ s140 action = MouseActionPress141 if btn&s == 0 {142 action = MouseActionRelease143 }144145 if btn == 0 {146 switch {147 case s&coninput.FROM_LEFT_1ST_BUTTON_PRESSED > 0:148 button = MouseButtonLeft149 case s&coninput.FROM_LEFT_2ND_BUTTON_PRESSED > 0:150 button = MouseButtonMiddle151 case s&coninput.RIGHTMOST_BUTTON_PRESSED > 0:152 button = MouseButtonRight153 case s&coninput.FROM_LEFT_3RD_BUTTON_PRESSED > 0:154 button = MouseButtonBackward155 case s&coninput.FROM_LEFT_4TH_BUTTON_PRESSED > 0:156 button = MouseButtonForward157 }158 return button, action159 }160161 switch btn {162 case coninput.FROM_LEFT_1ST_BUTTON_PRESSED: // left button163 button = MouseButtonLeft164 case coninput.RIGHTMOST_BUTTON_PRESSED: // right button165 button = MouseButtonRight166 case coninput.FROM_LEFT_2ND_BUTTON_PRESSED: // middle button167 button = MouseButtonMiddle168 case coninput.FROM_LEFT_3RD_BUTTON_PRESSED: // unknown (possibly mouse backward)169 button = MouseButtonBackward170 case coninput.FROM_LEFT_4TH_BUTTON_PRESSED: // unknown (possibly mouse forward)171 button = MouseButtonForward172 }173174 return button, action175}176177func mouseEvent(p coninput.ButtonState, e coninput.MouseEventRecord) MouseMsg {178 ev := MouseMsg{179 X: int(e.MousePositon.X),180 Y: int(e.MousePositon.Y),181 Alt: e.ControlKeyState.Contains(coninput.LEFT_ALT_PRESSED | coninput.RIGHT_ALT_PRESSED),182 Ctrl: e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED | coninput.RIGHT_CTRL_PRESSED),183 Shift: e.ControlKeyState.Contains(coninput.SHIFT_PRESSED),184 }185 switch e.EventFlags {186 case coninput.CLICK, coninput.DOUBLE_CLICK:187 ev.Button, ev.Action = mouseEventButton(p, e.ButtonState)188 if ev.Action == MouseActionRelease {189 ev.Type = MouseRelease190 }191 switch ev.Button { //nolint:exhaustive192 case MouseButtonLeft:193 ev.Type = MouseLeft194 case MouseButtonMiddle:195 ev.Type = MouseMiddle196 case MouseButtonRight:197 ev.Type = MouseRight198 case MouseButtonBackward:199 ev.Type = MouseBackward200 case MouseButtonForward:201 ev.Type = MouseForward202 }203 case coninput.MOUSE_WHEELED:204 if e.WheelDirection > 0 {205 ev.Button = MouseButtonWheelUp206 ev.Type = MouseWheelUp207 } else {208 ev.Button = MouseButtonWheelDown209 ev.Type = MouseWheelDown210 }211 case coninput.MOUSE_HWHEELED:212 if e.WheelDirection > 0 {213 ev.Button = MouseButtonWheelRight214 ev.Type = MouseWheelRight215 } else {216 ev.Button = MouseButtonWheelLeft217 ev.Type = MouseWheelLeft218 }219 case coninput.MOUSE_MOVED:220 ev.Button, _ = mouseEventButton(p, e.ButtonState)221 ev.Action = MouseActionMotion222 ev.Type = MouseMotion223 }224225 return ev226}227228func keyType(e coninput.KeyEventRecord) KeyType {229 code := e.VirtualKeyCode230231 shiftPressed := e.ControlKeyState.Contains(coninput.SHIFT_PRESSED)232 ctrlPressed := e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED | coninput.RIGHT_CTRL_PRESSED)233234 switch code { //nolint:exhaustive235 case coninput.VK_RETURN:236 return KeyEnter237 case coninput.VK_BACK:238 return KeyBackspace239 case coninput.VK_TAB:240 if shiftPressed {241 return KeyShiftTab242 }243 return KeyTab244 case coninput.VK_SPACE:245 return KeyRunes // this could be KeySpace but on unix space also produces KeyRunes246 case coninput.VK_ESCAPE:247 return KeyEscape248 case coninput.VK_UP:249 switch {250 case shiftPressed && ctrlPressed:251 return KeyCtrlShiftUp252 case shiftPressed:253 return KeyShiftUp254 case ctrlPressed:255 return KeyCtrlUp256 default:257 return KeyUp258 }259 case coninput.VK_DOWN:260 switch {261 case shiftPressed && ctrlPressed:262 return KeyCtrlShiftDown263 case shiftPressed:264 return KeyShiftDown265 case ctrlPressed:266 return KeyCtrlDown267 default:268 return KeyDown269 }270 case coninput.VK_RIGHT:271 switch {272 case shiftPressed && ctrlPressed:273 return KeyCtrlShiftRight274 case shiftPressed:275 return KeyShiftRight276 case ctrlPressed:277 return KeyCtrlRight278 default:279 return KeyRight280 }281 case coninput.VK_LEFT:282 switch {283 case shiftPressed && ctrlPressed:284 return KeyCtrlShiftLeft285 case shiftPressed:286 return KeyShiftLeft287 case ctrlPressed:288 return KeyCtrlLeft289 default:290 return KeyLeft291 }292 case coninput.VK_HOME:293 switch {294 case shiftPressed && ctrlPressed:295 return KeyCtrlShiftHome296 case shiftPressed:297 return KeyShiftHome298 case ctrlPressed:299 return KeyCtrlHome300 default:301 return KeyHome302 }303 case coninput.VK_END:304 switch {305 case shiftPressed && ctrlPressed:306 return KeyCtrlShiftEnd307 case shiftPressed:308 return KeyShiftEnd309 case ctrlPressed:310 return KeyCtrlEnd311 default:312 return KeyEnd313 }314 case coninput.VK_PRIOR:315 return KeyPgUp316 case coninput.VK_NEXT:317 return KeyPgDown318 case coninput.VK_DELETE:319 return KeyDelete320 case coninput.VK_F1:321 return KeyF1322 case coninput.VK_F2:323 return KeyF2324 case coninput.VK_F3:325 return KeyF3326 case coninput.VK_F4:327 return KeyF4328 case coninput.VK_F5:329 return KeyF5330 case coninput.VK_F6:331 return KeyF6332 case coninput.VK_F7:333 return KeyF7334 case coninput.VK_F8:335 return KeyF8336 case coninput.VK_F9:337 return KeyF9338 case coninput.VK_F10:339 return KeyF10340 case coninput.VK_F11:341 return KeyF11342 case coninput.VK_F12:343 return KeyF12344 case coninput.VK_F13:345 return KeyF13346 case coninput.VK_F14:347 return KeyF14348 case coninput.VK_F15:349 return KeyF15350 case coninput.VK_F16:351 return KeyF16352 case coninput.VK_F17:353 return KeyF17354 case coninput.VK_F18:355 return KeyF18356 case coninput.VK_F19:357 return KeyF19358 case coninput.VK_F20:359 return KeyF20360 default:361 switch {362 case e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED) && e.ControlKeyState.Contains(coninput.RIGHT_ALT_PRESSED):363 // AltGr is pressed, then it's a rune.364 fallthrough365 case !e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED) && !e.ControlKeyState.Contains(coninput.RIGHT_CTRL_PRESSED):366 return KeyRunes367 }368369 switch e.Char {370 case '@':371 return KeyCtrlAt372 case '\x01':373 return KeyCtrlA374 case '\x02':375 return KeyCtrlB376 case '\x03':377 return KeyCtrlC378 case '\x04':379 return KeyCtrlD380 case '\x05':381 return KeyCtrlE382 case '\x06':383 return KeyCtrlF384 case '\a':385 return KeyCtrlG386 case '\b':387 return KeyCtrlH388 case '\t':389 return KeyCtrlI390 case '\n':391 return KeyCtrlJ392 case '\v':393 return KeyCtrlK394 case '\f':395 return KeyCtrlL396 case '\r':397 return KeyCtrlM398 case '\x0e':399 return KeyCtrlN400 case '\x0f':401 return KeyCtrlO402 case '\x10':403 return KeyCtrlP404 case '\x11':405 return KeyCtrlQ406 case '\x12':407 return KeyCtrlR408 case '\x13':409 return KeyCtrlS410 case '\x14':411 return KeyCtrlT412 case '\x15':413 return KeyCtrlU414 case '\x16':415 return KeyCtrlV416 case '\x17':417 return KeyCtrlW418 case '\x18':419 return KeyCtrlX420 case '\x19':421 return KeyCtrlY422 case '\x1a':423 return KeyCtrlZ424 case '\x1b':425 return KeyCtrlOpenBracket // KeyEscape426 case '\x1c':427 return KeyCtrlBackslash428 case '\x1f':429 return KeyCtrlUnderscore430 }431432 switch code { //nolint:exhaustive433 case coninput.VK_OEM_4:434 return KeyCtrlOpenBracket435 case coninput.VK_OEM_6:436 return KeyCtrlCloseBracket437 }438439 return KeyRunes440 }441}
modified:key.go+54 added-12 removed
3 unmodified lines
4 "context"5 "fmt"6 "io"7 "regexp"8 "strings"9 "unicode/utf8"10)1112// KeyMsg contains information about a keypress. KeyMsgs are always sent to
41 unmodified lines
54type Key struct {55 Type KeyType56 Runes []rune57 Alt bool58 Paste bool59}6061// String returns a friendly string representation for a key. It's safe (and62// encouraged) for use in key comparison.
1 unmodified line
64// k := Key{Type: KeyEnter}65// fmt.Println(k)66// // Output: enter67func (k Key) String() (str string) {68 var buf strings.Builder69 if k.Alt {67 str += "alt+"70 buf.WriteString("alt+")71 }72 if k.Type == KeyRunes {70 str += string(k.Runes)71 return str73 if k.Paste {74 // Note: bubbles/keys bindings currently do string compares to75 // recognize shortcuts. Since pasted text should never activate76 // shortcuts, we need to ensure that the binding code doesn't77 // match Key events that result from pastes. We achieve this78 // here by enclosing pastes in '[...]' so that the string79 // comparison in Matches() fails in that case.80 buf.WriteByte('[')81 }82 buf.WriteString(string(k.Runes))83 if k.Paste {84 buf.WriteByte(']')85 }86 return buf.String()87 } else if s, ok := keyNames[k.Type]; ok {73 str += s74 return str88 buf.WriteString(s)89 return buf.String()90 }91 return ""92}93
458 unmodified lines
552}553554var spaceRunes = []rune{' '}555541// readInputs reads keypress and mouse inputs from a TTY and produces messages556// readAnsiInputs reads keypress and mouse inputs from a TTY and produces messages557// containing information about the key or mouse events accordingly.543func readInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {558func readAnsiInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {559 var buf [256]byte560561 var leftOverFromPrevIteration []byte562loop:
42 unmodified lines
605 leftOverFromPrevIteration = nil606 }607}608609var (594var unknownCSIRe = regexp.MustCompile(`^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]`)610 unknownCSIRe = regexp.MustCompile(`^\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]`)611 mouseSGRRegex = regexp.MustCompile(`(\d+);(\d+);(\d+)([Mm])`)612)613614func detectOneMsg(b []byte, canHaveMoreData bool) (w int, msg Msg) {615 // Detect mouse events.598 const mouseEventLen = 6599 if len(b) >= mouseEventLen && b[0] == '\x1b' && b[1] == '[' && b[2] == 'M' {600 return mouseEventLen, MouseMsg(parseX10MouseEvent(b))616 // X10 mouse events have a length of 6 bytes617 const mouseEventX10Len = 6618 if len(b) >= mouseEventX10Len && b[0] == '\x1b' && b[1] == '[' {619 switch b[2] {620 case 'M':621 return mouseEventX10Len, MouseMsg(parseX10MouseEvent(b))622 case '<':623 if matchIndices := mouseSGRRegex.FindSubmatchIndex(b[3:]); matchIndices != nil {624 // SGR mouse events length is the length of the match plus the length of the escape sequence625 mouseEventSGRLen := matchIndices[1] + 3 //nolint:mnd626 return mouseEventSGRLen, MouseMsg(parseSGRMouseEvent(b))627 }628 }629 }630631 // Detect focus events.632 var foundRF bool633 foundRF, w, msg = detectReportFocus(b)634 if foundRF {635 return w, msg636 }637638 // Detect bracketed paste.639 var foundbp bool640 foundbp, w, msg = detectBracketedPaste(b)641 if foundbp {642 return w, msg643 }644645 // Detect escape sequence and control characters other than NUL,646 // possibly with an escape character in front to mark the Alt647 // modifier.648 var foundSeq bool649 foundSeq, w, msg = detectSequence(b)650 if foundSeq {609 return651 return w, msg652 }653654 // No non-NUL control character or escape sequence.655 // If we are seeing at least an escape character, remember it for later below.
60 unmodified lines
modified:LICENSE+1 added-1 removed
1MIT License23Copyright (c) 2020-2023 Charmbracelet, Inc3Copyright (c) 2020-2025 Charmbracelet, Inc45Permission is hereby granted, free of charge, to any person obtaining a copy6of this software and associated documentation files (the "Software"), to deal7in the Software without restriction, including without limitation the rights
14 unmodified lines
modified:logging.go+1 added-1 removed
31 unmodified lines
32}3334// LogToFileWith does allows to call LogToFile with a custom LogOptionsSetter.35func LogToFileWith(path string, prefix string, log LogOptionsSetter) (*os.File, error) {36 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) //nolint:gomnd36 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) //nolint:mnd37 if err != nil {38 return nil, fmt.Errorf("error opening file for logging: %w", err)39 }40 log.SetOutput(f)
13 unmodified lines
modified:mouse_test.go+717 added-124 removed
1package tea23import "testing"3import (4 "fmt"5 "testing"6)78func TestMouseEvent_String(t *testing.T) {9 tt := []struct {10 name string11 event MouseEvent12 expected string13 }{14 {12 name: "unknown",13 event: MouseEvent{Type: MouseUnknown},15 name: "unknown",16 event: MouseEvent{17 Action: MouseActionPress,18 Button: MouseButtonNone,19 Type: MouseUnknown,20 },21 expected: "unknown",22 },23 {17 name: "left",18 event: MouseEvent{Type: MouseLeft},19 expected: "left",24 name: "left",25 event: MouseEvent{26 Action: MouseActionPress,27 Button: MouseButtonLeft,28 Type: MouseLeft,29 },30 expected: "left press",31 },32 {22 name: "right",23 event: MouseEvent{Type: MouseRight},24 expected: "right",33 name: "right",34 event: MouseEvent{35 Action: MouseActionPress,36 Button: MouseButtonRight,37 Type: MouseRight,38 },39 expected: "right press",40 },41 {27 name: "middle",28 event: MouseEvent{Type: MouseMiddle},29 expected: "middle",42 name: "middle",43 event: MouseEvent{44 Action: MouseActionPress,45 Button: MouseButtonMiddle,46 Type: MouseMiddle,47 },48 expected: "middle press",49 },50 {32 name: "release",33 event: MouseEvent{Type: MouseRelease},51 name: "release",52 event: MouseEvent{53 Action: MouseActionRelease,54 Button: MouseButtonNone,55 Type: MouseRelease,56 },57 expected: "release",58 },59 {37 name: "wheel up",38 event: MouseEvent{Type: MouseWheelUp},60 name: "wheel up",61 event: MouseEvent{62 Action: MouseActionPress,63 Button: MouseButtonWheelUp,64 Type: MouseWheelUp,65 },66 expected: "wheel up",67 },68 {42 name: "wheel down",43 event: MouseEvent{Type: MouseWheelDown},69 name: "wheel down",70 event: MouseEvent{71 Action: MouseActionPress,72 Button: MouseButtonWheelDown,73 Type: MouseWheelDown,74 },75 expected: "wheel down",76 },77 {47 name: "motion",48 event: MouseEvent{Type: MouseMotion},78 name: "wheel left",79 event: MouseEvent{80 Action: MouseActionPress,81 Button: MouseButtonWheelLeft,82 Type: MouseWheelLeft,83 },84 expected: "wheel left",85 },86 {87 name: "wheel right",88 event: MouseEvent{89 Action: MouseActionPress,90 Button: MouseButtonWheelRight,91 Type: MouseWheelRight,92 },93 expected: "wheel right",94 },95 {96 name: "motion",97 event: MouseEvent{98 Action: MouseActionMotion,99 Button: MouseButtonNone,100 Type: MouseMotion,101 },102 expected: "motion",103 },104 {105 name: "shift+left release",106 event: MouseEvent{107 Type: MouseLeft,108 Action: MouseActionRelease,109 Button: MouseButtonLeft,110 Shift: true,111 },112 expected: "shift+left release",113 },114 {115 name: "shift+left",116 event: MouseEvent{117 Type: MouseLeft,118 Action: MouseActionPress,119 Button: MouseButtonLeft,120 Shift: true,121 },122 expected: "shift+left press",123 },124 {125 name: "ctrl+shift+left",126 event: MouseEvent{127 Type: MouseLeft,128 Action: MouseActionPress,129 Button: MouseButtonLeft,130 Shift: true,131 Ctrl: true,132 },133 expected: "ctrl+shift+left press",134 },135 {136 name: "alt+left",137 event: MouseEvent{54 Type: MouseLeft,55 Alt: true,138 Type: MouseLeft,139 Action: MouseActionPress,140 Button: MouseButtonLeft,141 Alt: true,142 },57 expected: "alt+left",143 expected: "alt+left press",144 },145 {146 name: "ctrl+left",147 event: MouseEvent{62 Type: MouseLeft,63 Ctrl: true,148 Type: MouseLeft,149 Action: MouseActionPress,150 Button: MouseButtonLeft,151 Ctrl: true,152 },65 expected: "ctrl+left",153 expected: "ctrl+left press",154 },155 {156 name: "ctrl+alt+left",157 event: MouseEvent{70 Type: MouseLeft,71 Alt: true,72 Ctrl: true,158 Type: MouseLeft,159 Action: MouseActionPress,160 Button: MouseButtonLeft,161 Alt: true,162 Ctrl: true,163 },74 expected: "ctrl+alt+left",164 expected: "ctrl+alt+left press",165 },166 {167 name: "ctrl+alt+shift+left",168 event: MouseEvent{169 Type: MouseLeft,170 Action: MouseActionPress,171 Button: MouseButtonLeft,172 Alt: true,173 Ctrl: true,174 Shift: true,175 },176 expected: "ctrl+alt+shift+left press",177 },178 {179 name: "ignore coordinates",180 event: MouseEvent{79 X: 100,80 Y: 200,81 Type: MouseLeft,181 X: 100,182 Y: 200,183 Type: MouseLeft,184 Action: MouseActionPress,185 Button: MouseButtonLeft,186 },83 expected: "left",187 expected: "left press",188 },189 {190 name: "broken type",191 event: MouseEvent{88 Type: MouseEventType(-1000),192 Type: MouseEventType(-100),193 Action: MouseAction(-110),194 Button: MouseButton(-120),195 },196 expected: "",197 },198 }
33 unmodified lines
232 }{233 // Position.234 {235 name: "zero position",130 buf: encode(0b0010_0000, 0, 0),236 buf: encode(0b0000_0000, 0, 0),237 expected: MouseEvent{132 X: 0,133 Y: 0,134 Type: MouseLeft,238 X: 0,239 Y: 0,240 Type: MouseLeft,241 Action: MouseActionPress,242 Button: MouseButtonLeft,243 },244 },245 {246 name: "max position",139 buf: encode(0b0010_0000, 222, 222), // Because 255 (max int8) - 32 - 1.247 buf: encode(0b0000_0000, 222, 222), // Because 255 (max int8) - 32 - 1.248 expected: MouseEvent{141 X: 222,142 Y: 222,143 Type: MouseLeft,249 X: 222,250 Y: 222,251 Type: MouseLeft,252 Action: MouseActionPress,253 Button: MouseButtonLeft,254 },255 },256 // Simple.257 {258 name: "left",259 buf: encode(0b0000_0000, 32, 16),260 expected: MouseEvent{151 X: 32,152 Y: 16,153 Type: MouseLeft,261 X: 32,262 Y: 16,263 Type: MouseLeft,264 Action: MouseActionPress,265 Button: MouseButtonLeft,266 },267 },268 {269 name: "left in motion",270 buf: encode(0b0010_0000, 32, 16),271 expected: MouseEvent{160 X: 32,161 Y: 16,162 Type: MouseLeft,272 X: 32,273 Y: 16,274 Type: MouseLeft,275 Action: MouseActionMotion,276 Button: MouseButtonLeft,277 },278 },279 {280 name: "middle",281 buf: encode(0b0000_0001, 32, 16),282 expected: MouseEvent{169 X: 32,170 Y: 16,171 Type: MouseMiddle,283 X: 32,284 Y: 16,285 Type: MouseMiddle,286 Action: MouseActionPress,287 Button: MouseButtonMiddle,288 },289 },290 {291 name: "middle in motion",292 buf: encode(0b0010_0001, 32, 16),293 expected: MouseEvent{178 X: 32,179 Y: 16,180 Type: MouseMiddle,294 X: 32,295 Y: 16,296 Type: MouseMiddle,297 Action: MouseActionMotion,298 Button: MouseButtonMiddle,299 },300 },301 {302 name: "right",303 buf: encode(0b0000_0010, 32, 16),304 expected: MouseEvent{187 X: 32,188 Y: 16,189 Type: MouseRight,305 X: 32,306 Y: 16,307 Type: MouseRight,308 Action: MouseActionPress,309 Button: MouseButtonRight,310 },311 },312 {313 name: "right in motion",314 buf: encode(0b0010_0010, 32, 16),315 expected: MouseEvent{196 X: 32,197 Y: 16,198 Type: MouseRight,316 X: 32,317 Y: 16,318 Type: MouseRight,319 Action: MouseActionMotion,320 Button: MouseButtonRight,321 },322 },323 {324 name: "motion",325 buf: encode(0b0010_0011, 32, 16),326 expected: MouseEvent{205 X: 32,206 Y: 16,207 Type: MouseMotion,327 X: 32,328 Y: 16,329 Type: MouseMotion,330 Action: MouseActionMotion,331 Button: MouseButtonNone,332 },333 },334 {335 name: "wheel up",336 buf: encode(0b0100_0000, 32, 16),337 expected: MouseEvent{214 X: 32,215 Y: 16,216 Type: MouseWheelUp,338 X: 32,339 Y: 16,340 Type: MouseWheelUp,341 Action: MouseActionPress,342 Button: MouseButtonWheelUp,343 },344 },345 {346 name: "wheel down",347 buf: encode(0b0100_0001, 32, 16),348 expected: MouseEvent{223 X: 32,224 Y: 16,225 Type: MouseWheelDown,349 X: 32,350 Y: 16,351 Type: MouseWheelDown,352 Action: MouseActionPress,353 Button: MouseButtonWheelDown,354 },355 },356 {357 name: "wheel left",358 buf: encode(0b0100_0010, 32, 16),359 expected: MouseEvent{360 X: 32,361 Y: 16,362 Type: MouseWheelLeft,363 Action: MouseActionPress,364 Button: MouseButtonWheelLeft,365 },366 },367 {368 name: "wheel right",369 buf: encode(0b0100_0011, 32, 16),370 expected: MouseEvent{371 X: 32,372 Y: 16,373 Type: MouseWheelRight,374 Action: MouseActionPress,375 Button: MouseButtonWheelRight,376 },377 },378 {379 name: "release",380 buf: encode(0b0000_0011, 32, 16),381 expected: MouseEvent{232 X: 32,233 Y: 16,234 Type: MouseRelease,382 X: 32,383 Y: 16,384 Type: MouseRelease,385 Action: MouseActionRelease,386 Button: MouseButtonNone,387 },388 },389 {390 name: "backward",391 buf: encode(0b1000_0000, 32, 16),392 expected: MouseEvent{393 X: 32,394 Y: 16,395 Type: MouseBackward,396 Action: MouseActionPress,397 Button: MouseButtonBackward,398 },399 },400 {401 name: "forward",402 buf: encode(0b1000_0001, 32, 16),403 expected: MouseEvent{404 X: 32,405 Y: 16,406 Type: MouseForward,407 Action: MouseActionPress,408 Button: MouseButtonForward,409 },410 },411 {412 name: "button 10",413 buf: encode(0b1000_0010, 32, 16),414 expected: MouseEvent{415 X: 32,416 Y: 16,417 Type: MouseUnknown,418 Action: MouseActionPress,419 Button: MouseButton10,420 },421 },422 {423 name: "button 11",424 buf: encode(0b1000_0011, 32, 16),425 expected: MouseEvent{426 X: 32,427 Y: 16,428 Type: MouseUnknown,429 Action: MouseActionPress,430 Button: MouseButton11,431 },432 },433 // Combinations.434 {435 name: "alt+right",240 buf: encode(0b0010_1010, 32, 16),436 buf: encode(0b0000_1010, 32, 16),437 expected: MouseEvent{242 X: 32,243 Y: 16,244 Type: MouseRight,245 Alt: true,438 X: 32,439 Y: 16,440 Alt: true,441 Type: MouseRight,442 Action: MouseActionPress,443 Button: MouseButtonRight,444 },445 },446 {447 name: "ctrl+right",250 buf: encode(0b0011_0010, 32, 16),448 buf: encode(0b0001_0010, 32, 16),449 expected: MouseEvent{252 X: 32,253 Y: 16,254 Type: MouseRight,255 Ctrl: true,450 X: 32,451 Y: 16,452 Ctrl: true,453 Type: MouseRight,454 Action: MouseActionPress,455 Button: MouseButtonRight,456 },457 },458 {259 name: "ctrl+alt+right",260 buf: encode(0b0011_1010, 32, 16),459 name: "left in motion",460 buf: encode(0b0010_0000, 32, 16),461 expected: MouseEvent{262 X: 32,263 Y: 16,264 Type: MouseRight,265 Alt: true,266 Ctrl: true,462 X: 32,463 Y: 16,464 Alt: false,465 Type: MouseLeft,466 Action: MouseActionMotion,467 Button: MouseButtonLeft,468 },469 },470 {270 name: "alt+wheel down",271 buf: encode(0b0100_1001, 32, 16),471 name: "alt+right in motion",472 buf: encode(0b0010_1010, 32, 16),473 expected: MouseEvent{273 X: 32,274 Y: 16,275 Type: MouseWheelDown,276 Alt: true,474 X: 32,475 Y: 16,476 Alt: true,477 Type: MouseRight,478 Action: MouseActionMotion,479 Button: MouseButtonRight,480 },481 },482 {280 name: "ctrl+wheel down",281 buf: encode(0b0101_0001, 32, 16),483 name: "ctrl+right in motion",484 buf: encode(0b0011_0010, 32, 16),485 expected: MouseEvent{283 X: 32,284 Y: 16,285 Type: MouseWheelDown,286 Ctrl: true,486 X: 32,487 Y: 16,488 Ctrl: true,489 Type: MouseRight,490 Action: MouseActionMotion,491 Button: MouseButtonRight,492 },493 },494 {290 name: "ctrl+alt+wheel down",291 buf: encode(0b0101_1001, 32, 16),495 name: "ctrl+alt+right",496 buf: encode(0b0001_1010, 32, 16),497 expected: MouseEvent{293 X: 32,294 Y: 16,295 Type: MouseWheelDown,296 Alt: true,297 Ctrl: true,498 X: 32,499 Y: 16,500 Alt: true,501 Ctrl: true,502 Type: MouseRight,503 Action: MouseActionPress,504 Button: MouseButtonRight,505 },506 },300 // Unknown.507 {302 name: "wheel with unknown bit",303 buf: encode(0b0100_0010, 32, 16),508 name: "ctrl+wheel up",509 buf: encode(0b0101_0000, 32, 16),510 expected: MouseEvent{305 X: 32,306 Y: 16,307 Type: MouseUnknown,511 X: 32,512 Y: 16,513 Ctrl: true,514 Type: MouseWheelUp,515 Action: MouseActionPress,516 Button: MouseButtonWheelUp,517 },518 },519 {311 name: "unknown with modifier",312 buf: encode(0b0100_1010, 32, 16),520 name: "alt+wheel down",521 buf: encode(0b0100_1001, 32, 16),522 expected: MouseEvent{314 X: 32,315 Y: 16,316 Type: MouseUnknown,317 Alt: true,523 X: 32,524 Y: 16,525 Alt: true,526 Type: MouseWheelDown,527 Action: MouseActionPress,528 Button: MouseButtonWheelDown,529 },530 },531 {532 name: "ctrl+alt+wheel down",533 buf: encode(0b0101_1001, 32, 16),534 expected: MouseEvent{535 X: 32,536 Y: 16,537 Alt: true,538 Ctrl: true,539 Type: MouseWheelDown,540 Action: MouseActionPress,541 Button: MouseButtonWheelDown,542 },543 },544 // Overflow position.545 {546 name: "overflow position",547 buf: encode(0b0010_0000, 250, 223), // Because 255 (max int8) - 32 - 1.548 expected: MouseEvent{325 X: -6,326 Y: -33,327 Type: MouseLeft,549 X: -6,550 Y: -33,551 Type: MouseLeft,552 Action: MouseActionMotion,553 Button: MouseButtonLeft,554 },555 },556 }557
11 unmodified lines
569 }570 })571 }572}573574// func TestParseX10MouseEvent_error(t *testing.T) {575// tt := []struct {576// name string577// buf []byte578// }{579// {580// name: "empty buf",581// buf: nil,582// },583// {584// name: "wrong high bit",585// buf: []byte("\x1a[M@A1"),586// },587// {588// name: "short buf",589// buf: []byte("\x1b[M@A"),590// },591// {592// name: "long buf",593// buf: []byte("\x1b[M@A11"),594// },595// }596//597// for i := range tt {598// tc := tt[i]599//600// t.Run(tc.name, func(t *testing.T) {601// _, err := parseX10MouseEvent(tc.buf)602//603// if err == nil {604// t.Fatalf("expected error but got nil")605// }606// })607// }608// }609610func TestParseSGRMouseEvent(t *testing.T) {611 encode := func(b, x, y int, r bool) []byte {612 re := 'M'613 if r {614 re = 'm'615 }616 return []byte(fmt.Sprintf("\x1b[<%d;%d;%d%c", b, x+1, y+1, re))617 }618619 tt := []struct {620 name string621 buf []byte622 expected MouseEvent623 }{624 // Position.625 {626 name: "zero position",627 buf: encode(0, 0, 0, false),628 expected: MouseEvent{629 X: 0,630 Y: 0,631 Type: MouseLeft,632 Action: MouseActionPress,633 Button: MouseButtonLeft,634 },635 },636 {637 name: "225 position",638 buf: encode(0, 225, 225, false),639 expected: MouseEvent{640 X: 225,641 Y: 225,642 Type: MouseLeft,643 Action: MouseActionPress,644 Button: MouseButtonLeft,645 },646 },647 // Simple.648 {649 name: "left",650 buf: encode(0, 32, 16, false),651 expected: MouseEvent{652 X: 32,653 Y: 16,654 Type: MouseLeft,655 Action: MouseActionPress,656 Button: MouseButtonLeft,657 },658 },659 {660 name: "left in motion",661 buf: encode(32, 32, 16, false),662 expected: MouseEvent{663 X: 32,664 Y: 16,665 Type: MouseLeft,666 Action: MouseActionMotion,667 Button: MouseButtonLeft,668 },669 },670 {671 name: "left release",672 buf: encode(0, 32, 16, true),673 expected: MouseEvent{674 X: 32,675 Y: 16,676 Type: MouseRelease,677 Action: MouseActionRelease,678 Button: MouseButtonLeft,679 },680 },681 {682 name: "middle",683 buf: encode(1, 32, 16, false),684 expected: MouseEvent{685 X: 32,686 Y: 16,687 Type: MouseMiddle,688 Action: MouseActionPress,689 Button: MouseButtonMiddle,690 },691 },692 {693 name: "middle in motion",694 buf: encode(33, 32, 16, false),695 expected: MouseEvent{696 X: 32,697 Y: 16,698 Type: MouseMiddle,699 Action: MouseActionMotion,700 Button: MouseButtonMiddle,701 },702 },703 {704 name: "middle release",705 buf: encode(1, 32, 16, true),706 expected: MouseEvent{707 X: 32,708 Y: 16,709 Type: MouseRelease,710 Action: MouseActionRelease,711 Button: MouseButtonMiddle,712 },713 },714 {715 name: "right",716 buf: encode(2, 32, 16, false),717 expected: MouseEvent{718 X: 32,719 Y: 16,720 Type: MouseRight,721 Action: MouseActionPress,722 Button: MouseButtonRight,723 },724 },725 {726 name: "right release",727 buf: encode(2, 32, 16, true),728 expected: MouseEvent{729 X: 32,730 Y: 16,731 Type: MouseRelease,732 Action: MouseActionRelease,733 Button: MouseButtonRight,734 },735 },736 {737 name: "motion",738 buf: encode(35, 32, 16, false),739 expected: MouseEvent{740 X: 32,741 Y: 16,742 Type: MouseMotion,743 Action: MouseActionMotion,744 Button: MouseButtonNone,745 },746 },747 {748 name: "wheel up",749 buf: encode(64, 32, 16, false),750 expected: MouseEvent{751 X: 32,752 Y: 16,753 Type: MouseWheelUp,754 Action: MouseActionPress,755 Button: MouseButtonWheelUp,756 },757 },758 {759 name: "wheel down",760 buf: encode(65, 32, 16, false),761 expected: MouseEvent{762 X: 32,763 Y: 16,764 Type: MouseWheelDown,765 Action: MouseActionPress,766 Button: MouseButtonWheelDown,767 },768 },769 {770 name: "wheel left",771 buf: encode(66, 32, 16, false),772 expected: MouseEvent{773 X: 32,774 Y: 16,775 Type: MouseWheelLeft,776 Action: MouseActionPress,777 Button: MouseButtonWheelLeft,778 },779 },780 {781 name: "wheel right",782 buf: encode(67, 32, 16, false),783 expected: MouseEvent{784 X: 32,785 Y: 16,786 Type: MouseWheelRight,787 Action: MouseActionPress,788 Button: MouseButtonWheelRight,789 },790 },791 {792 name: "backward",793 buf: encode(128, 32, 16, false),794 expected: MouseEvent{795 X: 32,796 Y: 16,797 Type: MouseBackward,798 Action: MouseActionPress,799 Button: MouseButtonBackward,800 },801 },802 {803 name: "backward in motion",804 buf: encode(160, 32, 16, false),805 expected: MouseEvent{806 X: 32,807 Y: 16,808 Type: MouseBackward,809 Action: MouseActionMotion,810 Button: MouseButtonBackward,811 },812 },813 {814 name: "forward",815 buf: encode(129, 32, 16, false),816 expected: MouseEvent{817 X: 32,818 Y: 16,819 Type: MouseForward,820 Action: MouseActionPress,821 Button: MouseButtonForward,822 },823 },824 {825 name: "forward in motion",826 buf: encode(161, 32, 16, false),827 expected: MouseEvent{828 X: 32,829 Y: 16,830 Type: MouseForward,831 Action: MouseActionMotion,832 Button: MouseButtonForward,833 },834 },835 // Combinations.836 {837 name: "alt+right",838 buf: encode(10, 32, 16, false),839 expected: MouseEvent{840 X: 32,841 Y: 16,842 Alt: true,843 Type: MouseRight,844 Action: MouseActionPress,845 Button: MouseButtonRight,846 },847 },848 {849 name: "ctrl+right",850 buf: encode(18, 32, 16, false),851 expected: MouseEvent{852 X: 32,853 Y: 16,854 Ctrl: true,855 Type: MouseRight,856 Action: MouseActionPress,857 Button: MouseButtonRight,858 },859 },860 {861 name: "ctrl+alt+right",862 buf: encode(26, 32, 16, false),863 expected: MouseEvent{864 X: 32,865 Y: 16,866 Alt: true,867 Ctrl: true,868 Type: MouseRight,869 Action: MouseActionPress,870 Button: MouseButtonRight,871 },872 },873 {874 name: "alt+wheel press",875 buf: encode(73, 32, 16, false),876 expected: MouseEvent{877 X: 32,878 Y: 16,879 Alt: true,880 Type: MouseWheelDown,881 Action: MouseActionPress,882 Button: MouseButtonWheelDown,883 },884 },885 {886 name: "ctrl+wheel press",887 buf: encode(81, 32, 16, false),888 expected: MouseEvent{889 X: 32,890 Y: 16,891 Ctrl: true,892 Type: MouseWheelDown,893 Action: MouseActionPress,894 Button: MouseButtonWheelDown,895 },896 },897 {898 name: "ctrl+alt+wheel press",899 buf: encode(89, 32, 16, false),900 expected: MouseEvent{901 X: 32,902 Y: 16,903 Alt: true,904 Ctrl: true,905 Type: MouseWheelDown,906 Action: MouseActionPress,907 Button: MouseButtonWheelDown,908 },909 },910 {911 name: "ctrl+alt+shift+wheel press",912 buf: encode(93, 32, 16, false),913 expected: MouseEvent{914 X: 32,915 Y: 16,916 Shift: true,917 Alt: true,918 Ctrl: true,919 Type: MouseWheelDown,920 Action: MouseActionPress,921 Button: MouseButtonWheelDown,922 },923 },924 }925926 for i := range tt {927 tc := tt[i]928929 t.Run(tc.name, func(t *testing.T) {930 actual := parseSGRMouseEvent(tc.buf)931 if tc.expected != actual {932 t.Fatalf("expected %#v but got %#v",933 tc.expected,934 actual,935 )936 }937 })938 }939}
modified:mouse.go+233 added-57 removed
1package tea23import "strconv"45// MouseMsg contains information about a mouse event and are sent to a programs6// update function when mouse activity occurs. Note that the mouse must first7// be enabled in order for the mouse events to be received.8type MouseMsg MouseEvent
5 unmodified lines
1415// MouseEvent represents a mouse event, which could be a click, a scroll wheel16// movement, a cursor movement, or a combination.17type MouseEvent struct {16 X int17 Y int18 X int19 Y int20 Shift bool21 Alt bool22 Ctrl bool23 Action MouseAction24 Button MouseButton2526 // Deprecated: Use MouseAction & MouseButton instead.27 Type MouseEventType19 Alt bool20 Ctrl bool28}2930// IsWheel returns true if the mouse event is a wheel event.31func (m MouseEvent) IsWheel() bool {32 return m.Button == MouseButtonWheelUp || m.Button == MouseButtonWheelDown ||33 m.Button == MouseButtonWheelLeft || m.Button == MouseButtonWheelRight34}3536// String returns a string representation of a mouse event.37func (m MouseEvent) String() (s string) {38 if m.Ctrl {39 s += "ctrl+"40 }41 if m.Alt {42 s += "alt+"43 }31 s += mouseEventTypes[m.Type]44 if m.Shift {45 s += "shift+"46 }4748 if m.Button == MouseButtonNone { //nolint:nestif49 if m.Action == MouseActionMotion || m.Action == MouseActionRelease {50 s += mouseActions[m.Action]51 } else {52 s += "unknown"53 }54 } else if m.IsWheel() {55 s += mouseButtons[m.Button]56 } else {57 btn := mouseButtons[m.Button]58 if btn != "" {59 s += btn60 }61 act := mouseActions[m.Action]62 if act != "" {63 s += " " + act64 }65 }6667 return s68}6970// MouseAction represents the action that occurred during a mouse event.71type MouseAction int7273// Mouse event actions.74const (75 MouseActionPress MouseAction = iota76 MouseActionRelease77 MouseActionMotion78)7980var mouseActions = map[MouseAction]string{81 MouseActionPress: "press",82 MouseActionRelease: "release",83 MouseActionMotion: "motion",84}8586// MouseButton represents the button that was pressed during a mouse event.87type MouseButton int8889// Mouse event buttons90//91// This is based on X11 mouse button codes.92//93// 1 = left button94// 2 = middle button (pressing the scroll wheel)95// 3 = right button96// 4 = turn scroll wheel up97// 5 = turn scroll wheel down98// 6 = push scroll wheel left99// 7 = push scroll wheel right100// 8 = 4th button (aka browser backward button)101// 9 = 5th button (aka browser forward button)102// 10103// 11104//105// Other buttons are not supported.106const (107 MouseButtonNone MouseButton = iota108 MouseButtonLeft109 MouseButtonMiddle110 MouseButtonRight111 MouseButtonWheelUp112 MouseButtonWheelDown113 MouseButtonWheelLeft114 MouseButtonWheelRight115 MouseButtonBackward116 MouseButtonForward117 MouseButton10118 MouseButton11119)120121var mouseButtons = map[MouseButton]string{122 MouseButtonNone: "none",123 MouseButtonLeft: "left",124 MouseButtonMiddle: "middle",125 MouseButtonRight: "right",126 MouseButtonWheelUp: "wheel up",127 MouseButtonWheelDown: "wheel down",128 MouseButtonWheelLeft: "wheel left",129 MouseButtonWheelRight: "wheel right",130 MouseButtonBackward: "backward",131 MouseButtonForward: "forward",132 MouseButton10: "button 10",133 MouseButton11: "button 11",134}135136// MouseEventType indicates the type of mouse event occurring.137//138// Deprecated: Use MouseAction & MouseButton instead.139type MouseEventType int140141// Mouse event types.142//143// Deprecated: Use MouseAction & MouseButton instead.144const (145 MouseUnknown MouseEventType = iota146 MouseLeft147 MouseRight148 MouseMiddle44 MouseRelease149 MouseRelease // mouse button release (X10 only)150 MouseWheelUp151 MouseWheelDown152 MouseWheelLeft153 MouseWheelRight154 MouseBackward155 MouseForward156 MouseMotion157)15850var mouseEventTypes = map[MouseEventType]string{51 MouseUnknown: "unknown",52 MouseLeft: "left",53 MouseRight: "right",54 MouseMiddle: "middle",55 MouseRelease: "release",56 MouseWheelUp: "wheel up",57 MouseWheelDown: "wheel down",58 MouseMotion: "motion",159// Parse SGR-encoded mouse events; SGR extended mouse events. SGR mouse events160// look like:161//162// ESC [ < Cb ; Cx ; Cy (M or m)163//164// where:165//166// Cb is the encoded button code167// Cx is the x-coordinate of the mouse168// Cy is the y-coordinate of the mouse169// M is for button press, m is for button release170//171// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates172func parseSGRMouseEvent(buf []byte) MouseEvent {173 str := string(buf[3:])174 matches := mouseSGRRegex.FindStringSubmatch(str)175 if len(matches) != 5 { //nolint:mnd176 // Unreachable, we already checked the regex in `detectOneMsg`.177 panic("invalid mouse event")178 }179180 b, _ := strconv.Atoi(matches[1])181 px := matches[2]182 py := matches[3]183 release := matches[4] == "m"184 m := parseMouseButton(b, true)185186 // Wheel buttons don't have release events187 // Motion can be reported as a release event in some terminals (Windows Terminal)188 if m.Action != MouseActionMotion && !m.IsWheel() && release {189 m.Action = MouseActionRelease190 m.Type = MouseRelease191 }192193 x, _ := strconv.Atoi(px)194 y, _ := strconv.Atoi(py)195196 // (1,1) is the upper left. We subtract 1 to normalize it to (0,0).197 m.X = x - 1198 m.Y = y - 1199200 return m201}202203const x10MouseByteOffset = 32204205// Parse X10-encoded mouse events; the simplest kind. The last release of X1062// was December 1986, by the way.206// was December 1986, by the way. The original X10 mouse protocol limits the Cx207// and Cy coordinates to 223 (=255-032).208//209// X10 mouse events look like:210//211// ESC [M Cb Cx Cy212//213// See: http://www.xfree86.org/current/ctlseqs.html#Mouse%20Tracking214func parseX10MouseEvent(buf []byte) MouseEvent {215 v := buf[3:6]216 m := parseMouseButton(int(v[0]), false)217218 // (1,1) is the upper left. We subtract 1 to normalize it to (0,0).219 m.X = int(v[1]) - x10MouseByteOffset - 1220 m.Y = int(v[2]) - x10MouseByteOffset - 1221222 return m223}224225// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates226func parseMouseButton(b int, isSGR bool) MouseEvent {227 var m MouseEvent72 const byteOffset = 3273 e := v[0] - byteOffset228 e := b229 if !isSGR {230 e -= x10MouseByteOffset231 }232233 const (234 bitShift = 0b0000_0100235 bitAlt = 0b0000_1000236 bitCtrl = 0b0001_0000237 bitMotion = 0b0010_0000238 bitWheel = 0b0100_0000239 bitAdd = 0b1000_0000 // additional buttons 8-11240241 bitsMask = 0b0000_00118384 bitsLeft = 0b0000_000085 bitsMiddle = 0b0000_000186 bitsRight = 0b0000_001087 bitsRelease = 0b0000_00118889 bitsWheelUp = 0b0000_000090 bitsWheelDown = 0b0000_0001242 )24393 if e&bitWheel != 0 {94 // Check the low two bits.95 switch e & bitsMask {96 case bitsWheelUp:97 m.Type = MouseWheelUp98 case bitsWheelDown:99 m.Type = MouseWheelDown100 }244 if e&bitAdd != 0 {245 m.Button = MouseButtonBackward + MouseButton(e&bitsMask)246 } else if e&bitWheel != 0 {247 m.Button = MouseButtonWheelUp + MouseButton(e&bitsMask)248 } else {102 // Check the low two bits.103 // We do not separate clicking and dragging.104 switch e & bitsMask {105 case bitsLeft:106 m.Type = MouseLeft107 case bitsMiddle:108 m.Type = MouseMiddle109 case bitsRight:110 m.Type = MouseRight111 case bitsRelease:112 if e&bitMotion != 0 {113 m.Type = MouseMotion114 } else {115 m.Type = MouseRelease116 }249 m.Button = MouseButtonLeft + MouseButton(e&bitsMask)250 // X10 reports a button release as 0b0000_0011 (3)251 if e&bitsMask == bitsMask {252 m.Action = MouseActionRelease253 m.Button = MouseButtonNone254 }255 }256120 if e&bitAlt != 0 {121 m.Alt = true257 // Motion bit doesn't get reported for wheel events.258 if e&bitMotion != 0 && !m.IsWheel() {259 m.Action = MouseActionMotion260 }123 if e&bitCtrl != 0 {124 m.Ctrl = true125 }261127 // (1,1) is the upper left. We subtract 1 to normalize it to (0,0).128 m.X = int(v[1]) - byteOffset - 1129 m.Y = int(v[2]) - byteOffset - 1262 // Modifiers263 m.Alt = e&bitAlt != 0264 m.Ctrl = e&bitCtrl != 0265 m.Shift = e&bitShift != 0266267 // backward compatibility268 switch {269 case m.Button == MouseButtonLeft && m.Action == MouseActionPress:270 m.Type = MouseLeft271 case m.Button == MouseButtonMiddle && m.Action == MouseActionPress:272 m.Type = MouseMiddle273 case m.Button == MouseButtonRight && m.Action == MouseActionPress:274 m.Type = MouseRight275 case m.Button == MouseButtonNone && m.Action == MouseActionRelease:276 m.Type = MouseRelease277 case m.Button == MouseButtonWheelUp && m.Action == MouseActionPress:278 m.Type = MouseWheelUp279 case m.Button == MouseButtonWheelDown && m.Action == MouseActionPress:280 m.Type = MouseWheelDown281 case m.Button == MouseButtonWheelLeft && m.Action == MouseActionPress:282 m.Type = MouseWheelLeft283 case m.Button == MouseButtonWheelRight && m.Action == MouseActionPress:284 m.Type = MouseWheelRight285 case m.Button == MouseButtonBackward && m.Action == MouseActionPress:286 m.Type = MouseBackward287 case m.Button == MouseButtonForward && m.Action == MouseActionPress:288 m.Type = MouseForward289 case m.Action == MouseActionMotion:290 m.Type = MouseMotion291 switch m.Button { //nolint:exhaustive292 case MouseButtonLeft:293 m.Type = MouseLeft294 case MouseButtonMiddle:295 m.Type = MouseMiddle296 case MouseButtonRight:297 m.Type = MouseRight298 case MouseButtonBackward:299 m.Type = MouseBackward300 case MouseButtonForward:301 m.Type = MouseForward302 }303 default:304 m.Type = MouseUnknown305 }306307 return m308}
modified:nil_renderer.go+25 added-15 removed
1package tea23type nilRenderer struct{}45func (n nilRenderer) start() {}6func (n nilRenderer) stop() {}7func (n nilRenderer) kill() {}8func (n nilRenderer) write(_ string) {}9func (n nilRenderer) repaint() {}10func (n nilRenderer) clearScreen() {}11func (n nilRenderer) altScreen() bool { return false }12func (n nilRenderer) enterAltScreen() {}13func (n nilRenderer) exitAltScreen() {}14func (n nilRenderer) showCursor() {}15func (n nilRenderer) hideCursor() {}16func (n nilRenderer) enableMouseCellMotion() {}17func (n nilRenderer) disableMouseCellMotion() {}18func (n nilRenderer) enableMouseAllMotion() {}19func (n nilRenderer) disableMouseAllMotion() {}5func (n nilRenderer) start() {}6func (n nilRenderer) stop() {}7func (n nilRenderer) kill() {}8func (n nilRenderer) write(_ string) {}9func (n nilRenderer) repaint() {}10func (n nilRenderer) clearScreen() {}11func (n nilRenderer) altScreen() bool { return false }12func (n nilRenderer) enterAltScreen() {}13func (n nilRenderer) exitAltScreen() {}14func (n nilRenderer) showCursor() {}15func (n nilRenderer) hideCursor() {}16func (n nilRenderer) enableMouseCellMotion() {}17func (n nilRenderer) disableMouseCellMotion() {}18func (n nilRenderer) enableMouseAllMotion() {}19func (n nilRenderer) disableMouseAllMotion() {}20func (n nilRenderer) enableBracketedPaste() {}21func (n nilRenderer) disableBracketedPaste() {}22func (n nilRenderer) enableMouseSGRMode() {}23func (n nilRenderer) disableMouseSGRMode() {}24func (n nilRenderer) bracketedPasteActive() bool { return false }25func (n nilRenderer) setWindowTitle(_ string) {}26func (n nilRenderer) reportFocus() bool { return false }27func (n nilRenderer) enableReportFocus() {}28func (n nilRenderer) disableReportFocus() {}29func (n nilRenderer) resetLinesRendered() {}
modified:options_test.go+22 added-6 removed
1package tea23import (4 "bytes"5 "context"6 "os"7 "sync/atomic"8 "testing"9)1011func TestOptions(t *testing.T) {12 t.Run("output", func(t *testing.T) {13 var b bytes.Buffer14 p := NewProgram(nil, WithOutput(&b))12 if p.output.TTY() != nil {13 t.Errorf("expected output to custom, got %v", p.output.TTY().Fd())15 if f, ok := p.output.(*os.File); ok {16 t.Errorf("expected output to custom, got %v", f.Fd())17 }18 })1920 t.Run("custom input", func(t *testing.T) {
18 unmodified lines
39 })4041 t.Run("without signals", func(t *testing.T) {42 p := NewProgram(nil, WithoutSignals())40 if !p.ignoreSignals {43 if atomic.LoadUint32(&p.ignoreSignals) == 0 {44 t.Errorf("ignore signals should have been set")45 }46 })47
3 unmodified lines
51 t.Errorf("expected filter to be set")52 }53 })5455 t.Run("external context", func(t *testing.T) {56 extCtx, extCancel := context.WithCancel(context.Background())57 defer extCancel()5859 p := NewProgram(nil, WithContext(extCtx))60 if p.externalCtx != extCtx || p.externalCtx == context.Background() {61 t.Errorf("expected passed in external context, got default (nil)")62 }63 })6465 t.Run("input options", func(t *testing.T) {66 exercise := func(t *testing.T, opt ProgramOption, expect inputType) {67 p := NewProgram(nil, opt)68 if p.inputType != expect {
8 unmodified lines
77 t.Run("custom input", func(t *testing.T) {78 var b bytes.Buffer79 exercise(t, WithInput(&b), customInput)80 })6881 })8283 t.Run("startup options", func(t *testing.T) {84 exercise := func(t *testing.T, opt ProgramOption, expect startupOptions) {
6 unmodified lines
91 t.Run("alt screen", func(t *testing.T) {92 exercise(t, WithAltScreen(), withAltScreen)93 })9495 t.Run("bracketed paste disabled", func(t *testing.T) {96 exercise(t, WithoutBracketedPaste(), withoutBracketedPaste)97 })9899 t.Run("ansi compression", func(t *testing.T) {100 exercise(t, WithANSICompressor(), withANSICompressor)101 })102
26 unmodified lines
129 })130 })131132 t.Run("multiple", func(t *testing.T) {117 p := NewProgram(nil, WithMouseAllMotion(), WithAltScreen(), WithInputTTY())118 for _, opt := range []startupOptions{withMouseAllMotion, withAltScreen} {133 p := NewProgram(nil, WithMouseAllMotion(), WithoutBracketedPaste(), WithAltScreen(), WithInputTTY())134 for _, opt := range []startupOptions{withMouseAllMotion, withoutBracketedPaste, withAltScreen} {135 if !p.startupOptions.has(opt) {136 t.Errorf("expected startup options have %v, got %v", opt, p.startupOptions)137 }138 if p.inputType != ttyInput {
5 unmodified lines
modified:options.go+50 added-9 removed
1 unmodified line
23import (4 "context"5 "io"67 "github.com/muesli/termenv"6 "sync/atomic"7)89// ProgramOption is used to set options when initializing a Program. Program can10// accept a variable number of options.
7 unmodified lines
18// useful if you want to cancel the execution from outside. When a Program gets19// cancelled it will exit with an error ErrProgramKilled.20func WithContext(ctx context.Context) ProgramOption {21 return func(p *Program) {23 p.ctx = ctx22 p.externalCtx = ctx23 }24}2526// WithOutput sets the output which, by default, is stdout. In most cases you27// won't need to use this.28func WithOutput(output io.Writer) ProgramOption {29 return func(p *Program) {31 if o, ok := output.(*termenv.Output); ok {32 p.output = o30 p.output = output33 } else {34 p.output = termenv.NewOutput(output, termenv.WithColorCache(true))35 }31 }32}3334// WithInput sets the input which, by default, is stdin. In most cases you
13 unmodified lines
48 p.inputType = ttyInput49 }50}5152// WithEnvironment sets the environment variables that the program will use.53// This useful when the program is running in a remote session (e.g. SSH) and54// you want to pass the environment variables from the remote session to the55// program.56//57// Example:58//59// var sess ssh.Session // ssh.Session is a type from the github.com/charmbracelet/ssh package60// pty, _, _ := sess.Pty()61// environ := append(sess.Environ(), "TERM="+pty.Term)62// p := tea.NewProgram(model, tea.WithEnvironment(environ)63func WithEnvironment(env []string) ProgramOption {64 return func(p *Program) {65 p.environ = env66 }67}6869// WithoutSignalHandler disables the signal handler that Bubble Tea sets up for70// Programs. This is useful if you want to handle signals yourself.71func WithoutSignalHandler() ProgramOption {72 return func(p *Program) {
14 unmodified lines
87// WithoutSignals will ignore OS signals.88// This is mainly useful for testing.89func WithoutSignals() ProgramOption {90 return func(p *Program) {79 p.ignoreSignals = true91 atomic.StoreUint32(&p.ignoreSignals, 1)92 }93}9495// WithAltScreen starts the program with the alternate screen buffer enabled
15 unmodified lines
111 p.startupOptions |= withAltScreen112 }113}114115// WithoutBracketedPaste starts the program with bracketed paste disabled.116func WithoutBracketedPaste() ProgramOption {117 return func(p *Program) {118 p.startupOptions |= withoutBracketedPaste119 }120}121122// WithMouseCellMotion starts the program with the mouse enabled in "cell123// motion" mode.124//125// Cell motion mode enables mouse click, release, and wheel events. Mouse126// movement events are also captured if a mouse button is pressed (i.e., drag127// events). Cell motion mode is better supported than all motion mode.128//129// This will try to enable the mouse in extended mode (SGR), if that is not130// supported by the terminal it will fall back to normal mode (X10).131//132// To enable mouse cell motion once the program has already started running use133// the EnableMouseCellMotion command. To disable the mouse when the program is134// running use the DisableMouse command.135//
11 unmodified lines
147// EnableMouseAllMotion is a special command that enables mouse click, release,148// wheel, and motion events, which are delivered regardless of whether a mouse149// button is pressed, effectively enabling support for hover interactions.150//151// This will try to enable the mouse in extended mode (SGR), if that is not152// supported by the terminal it will fall back to normal mode (X10).153//154// Many modern terminals support this, but not all. If in doubt, use155// EnableMouseCellMotion instead.156//157// To enable the mouse once the program has already started running use the
26 unmodified lines
184// smaller output, at the cost of some processing overhead.185//186// This feature is provisional, and may be changed or removed in a future version187// of this package.188//189// Deprecated: this incurs a noticeable performance hit. A future release will190// optimize ANSI automatically without the performance penalty.191func WithANSICompressor() ProgramOption {192 return func(p *Program) {193 p.startupOptions |= withANSICompressor194 }
41 unmodified lines
236 return func(p *Program) {237 p.fps = fps238 }239}240241// WithReportFocus enables reporting when the terminal gains and loses242// focus. When this is enabled [FocusMsg] and [BlurMsg] messages will be sent243// to your Update method.244//245// Note that while most terminals and multiplexers support focus reporting,246// some do not. Also note that tmux needs to be configured to report focus247// events.248func WithReportFocus() ProgramOption {249 return func(p *Program) {250 p.startupOptions |= withReportFocus251 }252}
modified:README.md+85 added-95 removed
1# Bubble Tea23<p>4 <img src="https://stuff.charm.sh/bubbletea/bubbletea-github-header-simple.png" width="313" alt="Bubble Tea Title Treatment"><br>4 <picture>5 <source media="(prefers-color-scheme: light)" srcset="https://stuff.charm.sh/bubbletea/bubble-tea-v2-light.png" width="308">6 <source media="(prefers-color-scheme: dark)" srcset="https://stuff.charm.sh/bubbletea/bubble-tea-v2-dark.png" width="312">7 <img src="https://stuff.charm.sh/bubbletea/bubble-tea-v2-light.png" width="308" />8 </picture>9 <br>10 <a href="https://github.com/charmbracelet/bubbletea/releases"><img src="https://img.shields.io/github/release/charmbracelet/bubbletea.svg" alt="Latest Release"></a>6 <a href="https://pkg.go.dev/github.com/charmbracelet/bubbletea?tab=doc"><img src="https://godoc.org/github.com/golang/gddo?status.svg" alt="GoDoc"></a>7 <a href="https://github.com/charmbracelet/bubbletea/actions"><img src="https://github.com/charmbracelet/bubbletea/workflows/build/badge.svg" alt="Build Status"></a>11 <a href="https://pkg.go.dev/github.com/charmbracelet/bubbletea?tab=doc"><img src="https://godoc.org/github.com/charmbracelet/bubbletea?status.svg" alt="GoDoc"></a>12 <a href="https://github.com/charmbracelet/bubbletea/actions"><img src="https://github.com/charmbracelet/bubbletea/actions/workflows/build.yml/badge.svg?branch=main" alt="Build Status"></a>13</p>1415The fun, functional and stateful way to build terminal apps. A Go framework16based on [The Elm Architecture][elm]. Bubble Tea is well-suited for simple and
3 unmodified lines
20 <img src="https://stuff.charm.sh/bubbletea/bubbletea-example.gif" width="100%" alt="Bubble Tea Example">21</p>2223Bubble Tea is in use in production and includes a number of features and19performance optimizations we’ve added along the way. Among those is a standard20framerate-based renderer, a renderer for high-performance scrollable21regions which works alongside the main renderer, and mouse support.24performance optimizations we’ve added along the way. Among those is25a framerate-based renderer, mouse support, focus reporting and more.2627To get started, see the tutorial below, the [examples][examples], the28[docs][docs], the [video tutorials][youtube] and some common [resources](#libraries-we-use-with-bubble-tea).29
7 unmodified lines
37 <a href="https://github.com/charmbracelet/bubbles"><img src="https://stuff.charm.sh/bubbles/bubbles-badge.png" width="174" alt="Bubbles Badge"></a>&nbsp;&nbsp;38 <a href="https://github.com/charmbracelet/bubbles"><img src="https://stuff.charm.sh/bubbles-examples/textinput.gif" width="400" alt="Text Input Example from Bubbles"></a>39</p>4037***41---4243## Tutorial4445Bubble Tea is based on the functional design paradigms of [The Elm
5 unmodified lines
51By the way, the non-annotated source code for this program is available52[on GitHub][tut-source].5354[elm]: https://guide.elm-lang.org/architecture/51[tut-source]:https://github.com/charmbracelet/bubbletea/tree/master/tutorials/basics55[tut-source]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/basics5657### Enough! Let's get to it.5859For this tutorial, we're making a shopping list.
3 unmodified lines
6364```go65package main6667// These imports will be used later on the tutorial. If you save the file68// now, Go might complain they are unused, but that's fine.69// You may also need to run `go mod tidy` to download bubbletea and its70// dependencies.71import (72 "fmt"73 "os"74
3 unmodified lines
7879Bubble Tea programs are comprised of a **model** that describes the application80state and three simple methods on that model:8174* **Init**, a function that returns an initial command for the application to run.75* **Update**, a function that handles incoming events and updates the model accordingly.76* **View**, a function that renders the UI based on the data in the model.82- **Init**, a function that returns an initial command for the application to run.83- **Update**, a function that handles incoming events and updates the model accordingly.84- **View**, a function that renders the UI based on the data in the model.8586### The Model8788So let's start by defining our model which will store our application's state.
171 unmodified lines
260261There are also several [Bubble Tea examples][examples] available and, of course,262there are [Go Docs][docs].263256[cmd]: http://github.com/charmbracelet/bubbletea/tree/master/tutorials/commands/257[examples]: http://github.com/charmbracelet/bubbletea/tree/master/examples264[cmd]: https://github.com/charmbracelet/bubbletea/tree/main/tutorials/commands/265[examples]: https://github.com/charmbracelet/bubbletea/tree/main/examples266[docs]: https://pkg.go.dev/github.com/charmbracelet/bubbletea?tab=doc267268## Debugging269
3 unmodified lines
273delve in headless mode and then connect to it:274275```bash276# Start the debugger269$ dlv debug --headless .270API server listening at: 127.0.0.1:34241277$ dlv debug --headless --api-version=2 --listen=127.0.0.1:43000 .278API server listening at: 127.0.0.1:43000279280# Connect to it from another terminal273$ dlv connect 127.0.0.1:34241281$ dlv connect 127.0.0.1:43000282```283276Note that the default port used will vary on your system and per run, so277actually watch out what address the first `dlv` run tells you to connect to.284If you do not explicitly supply the `--listen` flag, the port used will vary285per run, so passing this in makes the debugger easier to use from a script286or your IDE of choice.287288Additionally, we pass in `--api-version=2` because delve defaults to version 1289for backwards compatibility reasons. However, delve recommends using version 2290for all new development and some clients may no longer work with version 1.291For more information, see the [Delve documentation](https://github.com/go-delve/delve/tree/master/Documentation/api).292293### Logging Stuff294295You can’t really log to stdout with Bubble Tea because your TUI is busy296occupying that! You can, however, log to a file by including something like
14 unmodified lines
311your program in another window.312313## Libraries we use with Bubble Tea314301* [Bubbles][bubbles]: Common Bubble Tea components such as text inputs, viewports, spinners and so on302* [Lip Gloss][lipgloss]: Style, format and layout tools for terminal applications303* [Harmonica][harmonica]: A spring animation library for smooth, natural motion304* [BubbleZone][bubblezone]: Easy mouse event tracking for Bubble Tea components305* [Termenv][termenv]: Advanced ANSI styling for terminal applications306* [Reflow][reflow]: Advanced ANSI-aware methods for working with text315- [Bubbles][bubbles]: Common Bubble Tea components such as text inputs, viewports, spinners and so on316- [Lip Gloss][lipgloss]: Style, format and layout tools for terminal applications317- [Harmonica][harmonica]: A spring animation library for smooth, natural motion318- [BubbleZone][bubblezone]: Easy mouse event tracking for Bubble Tea components319- [ntcharts][ntcharts]: A terminal charting library built for Bubble Tea and [Lip Gloss][lipgloss]320321[bubbles]: https://github.com/charmbracelet/bubbles322[lipgloss]: https://github.com/charmbracelet/lipgloss323[harmonica]: https://github.com/charmbracelet/harmonica324[bubblezone]: https://github.com/lrstanley/bubblezone312[termenv]: https://github.com/muesli/termenv313[reflow]: https://github.com/muesli/reflow325[ntcharts]: https://github.com/NimbleMarkets/ntcharts326327## Bubble Tea in the Wild328317For some Bubble Tea programs in production, see:329There are over [10,000 applications](https://github.com/charmbracelet/bubbletea/network/dependents) built with Bubble Tea! Here are a handful of ’em.330319* [AT CLI](https://github.com/daskycodes/at_cli): execute AT Commands via serial port connections320* [Aztify](https://github.com/Azure/aztfy): bring Microsoft Azure resources under Terraform321* [brows](https://github.com/rubysolo/brows): a GitHub release browser322* [Canard](https://github.com/mrusme/canard): an RSS client323* [charm](https://github.com/charmbracelet/charm): the official Charm user account manager324* [chezmoi](https://github.com/twpayne/chezmoi): securely manage your dotfiles across multiple machines325* [chtop](https://github.com/chhetripradeep/chtop): monitor your ClickHouse node without leaving terminal326* [circumflex](https://github.com/bensadeh/circumflex): read Hacker News in the terminal327* [clidle](https://github.com/ajeetdsouza/clidle): a Wordle clone328* [cLive](https://github.com/koki-develop/clive): automate terminal operations and view them live in a browser329* [container-canary](https://github.com/NVIDIA/container-canary): a container validator330* [countdown](https://github.com/aldernero/countdown): a multi-event countdown timer331* [dns53](https://github.com/purpleclay/dns53): dynamic DNS with Amazon Route53. Expose your EC2 quickly, securely and privately332* [eks-node-viewer](https://github.com/awslabs/eks-node-viewer): a tool for visualizing dynamic node usage within an eks cluster333* [enola](https://github.com/sherlock-project/enola): hunt down social media accounts by username across social networks334* [flapioca](https://github.com/kbrgl/flapioca): Flappy Bird on the CLI!335* [fm](https://github.com/knipferrc/fm): a terminal-based file manager336* [fork-cleaner](https://github.com/caarlos0/fork-cleaner): clean up old and inactive forks in your GitHub account337* [fztea](https://github.com/jon4hz/fztea): a Flipper Zero TUI338* [gambit](https://github.com/maaslalani/gambit): chess in the terminal339* [gembro](https://git.sr.ht/~rafael/gembro): a mouse-driven Gemini browser340* [gh-b](https://github.com/joaom00/gh-b): a GitHub CLI extension for managing branches341* [gh-dash](https://www.github.com/dlvhdr/gh-dash): a GitHub CLI extension for PRs and issues342* [gitflow-toolkit](https://github.com/mritd/gitflow-toolkit): a GitFlow submission tool343* [Glow](https://github.com/charmbracelet/glow): a markdown reader, browser, and online markdown stash344* [gocovsh](https://github.com/orlangure/gocovsh): explore Go coverage reports from the CLI345* [got](https://github.com/fedeztk/got): a simple translator and text-to-speech app build on top of simplytranslate's APIs346* [hiSHtory](https://github.com/ddworken/hishtory): your shell history in context, synced, and queryable347* [httpit](https://github.com/gonetx/httpit): a rapid http(s) benchmark tool348* [IDNT](https://github.com/r-darwish/idnt): a batch software uninstaller349* [kboard](https://github.com/CamiloGarciaLaRotta/kboard): a typing game350* [mandelbrot-cli](https://github.com/MicheleFiladelfia/mandelbrot-cli): a multiplatform terminal mandelbrot set explorer351* [mc](https://github.com/minio/mc): the official [MinIO](https://min.io) client352* [mergestat](https://github.com/mergestat/mergestat): run SQL queries on git repositories353* [Neon Modem Overdrive](https://github.com/mrusme/neonmodem): a BBS-style TUI client for Discourse, Lemmy, Lobste.rs and Hacker News354* [Noted](https://github.com/torbratsberg/noted): a note viewer and manager355* [pathos](https://github.com/chip/pathos): a PATH env variable editor356* [portal](https://github.com/ZinoKader/portal): secure transfers between computers357* [redis-viewer](https://github.com/SaltFishPr/redis-viewer): a Redis databases browser358* [scrabbler](https://github.com/wI2L/scrabbler): Automatic draw TUI for your duplicate Scrabble games359* [sku](https://github.com/fedeztk/sku): Sudoku on the CLI360* [Slides](https://github.com/maaslalani/slides): a markdown-based presentation tool361* [SlurmCommander](https://github.com/CLIP-HPC/SlurmCommander): a Slurm workload manager TUI362* [Soft Serve](https://github.com/charmbracelet/soft-serve): a command-line-first Git server that runs a TUI over SSH363* [solitaire-tui](https://github.com/brianstrauch/solitaire-tui): Klondike Solitaire for the terminal364* [StormForge Optimize Controller](https://github.com/thestormforge/optimize-controller): a tool for experimenting with application configurations in Kubernetes365* [Storydb](https://github.com/grrlopes/storydb): a bash/zsh ctrl+r improved command history finder.366* [STTG](https://github.com/wille1101/sttg): a teletext client for SVT, Sweden’s national public television station367* [sttr](https://github.com/abhimanyu003/sttr): a general-purpose text transformer368* [tasktimer](https://github.com/caarlos0/tasktimer): a dead-simple task timer369* [termdbms](https://github.com/mathaou/termdbms): a keyboard and mouse driven database browser370* [ticker](https://github.com/achannarasappa/ticker): a terminal stock viewer and stock position tracker371* [tran](https://github.com/abdfnx/tran): securely transfer stuff between computers (based on [portal](https://github.com/ZinoKader/portal))372* [Typer](https://github.com/maaslalani/typer): a typing test373* [typioca](https://github.com/bloznelis/typioca): Cozy typing speed tester in terminal 374* [tz](https://github.com/oz/tz): an aid for scheduling across multiple time zones375* [ugm](https://github.com/ariasmn/ugm): a unix user and group browser376* [walk](https://github.com/antonmedv/walk): a terminal navigator377* [wander](https://github.com/robinovitch61/wander): a HashiCorp Nomad terminal client378* [WG Commander](https://github.com/AndrianBdn/wg-cmd): a TUI for a simple WireGuard VPN setup 379* [wishlist](https://github.com/charmbracelet/wishlist): an SSH directory331### Staff favourites332333- [chezmoi](https://github.com/twpayne/chezmoi): securely manage your dotfiles across multiple machines334- [circumflex](https://github.com/bensadeh/circumflex): read Hacker News in the terminal335- [gh-dash](https://www.github.com/dlvhdr/gh-dash): a GitHub CLI extension for PRs and issues336- [Tetrigo](https://github.com/Broderick-Westrope/tetrigo): Tetris in the terminal337- [Signls](https://github.com/emprcl/signls): a generative midi sequencer designed for composition and live performance338- [Superfile](https://github.com/yorukot/superfile): a super file manager339340### In Industry341342- Microsoft Azure – [Aztify](https://github.com/Azure/aztfy): bring Microsoft Azure resources under Terraform343- Daytona – [Daytona](https://github.com/daytonaio/daytona): open source dev environment manager344- Cockroach Labs – [CockroachDB](https://github.com/cockroachdb/cockroach): a cloud-native, high-availability distributed SQL database345- Truffle Security Co. – [Trufflehog](https://github.com/trufflesecurity/trufflehog): find leaked credentials346- NVIDIA – [container-canary](https://github.com/NVIDIA/container-canary): a container validator347- AWS – [eks-node-viewer](https://github.com/awslabs/eks-node-viewer): a tool for visualizing dynamic node usage within an EKS cluster348- MinIO – [mc](https://github.com/minio/mc): the official [MinIO](https://min.io) client349- Ubuntu – [Authd](https://github.com/ubuntu/authd): an authentication daemon for cloud-based identity providers350351### Charm stuff352353- [Glow](https://github.com/charmbracelet/glow): a markdown reader, browser, and online markdown stash354- [Huh?](https://github.com/charmbracelet/huh): an interactive prompt and form toolkit355- [Mods](https://github.com/charmbracelet/mods): AI on the CLI, built for pipelines356- [Wishlist](https://github.com/charmbracelet/wishlist): an SSH directory (and bastion!)357358### There’s so much more where that came from359360For more applications built with Bubble Tea see [Charm & Friends][community].361Is there something cool you made with Bubble Tea you want to share? [PRs][community] are362welcome!363364## Contributing365366See [contributing][contribute].367368[contribute]: https://github.com/charmbracelet/bubbletea/contribute369370## Feedback371383We'd love to hear your thoughts on this project. Feel free to drop us a note!372We’d love to hear your thoughts on this project. Feel free to drop us a note!373385* [Twitter](https://twitter.com/charmcli)386* [The Fediverse](https://mastodon.social/@charmcli)387* [Discord](https://charm.sh/chat)374- [Twitter](https://twitter.com/charmcli)375- [The Fediverse](https://mastodon.social/@charmcli)376- [Discord](https://charm.sh/chat)377378## Acknowledgments379380Bubble Tea is based on the paradigms of [The Elm Architecture][elm] by Evan
3 unmodified lines
384385[elm]: https://guide.elm-lang.org/architecture/386[gotea]: https://github.com/tj/go-tea387[zb]: https://de.wikipedia.org/wiki/Zeichenorientierte_Benutzerschnittstelle388[community]: https://github.com/charm-and-friends/charm-in-the-wild389390## License391402[MIT](https://github.com/charmbracelet/bubbletea/raw/master/LICENSE)392[MIT](https://github.com/charmbracelet/bubbletea/raw/main/LICENSE)393404***394---395396Part of [Charm](https://charm.sh).397408<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>398<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-banner-next.jpg" width="400"></a>399400Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة
modified:renderer.go+35 added-3 removed
38 unmodified lines
39 // enableMouseCellMotion enables mouse click, release, wheel and motion40 // events if a mouse button is pressed (i.e., drag events).41 enableMouseCellMotion()4243 // DisableMouseCellMotion disables Mouse Cell Motion tracking.43 // disableMouseCellMotion disables Mouse Cell Motion tracking.44 disableMouseCellMotion()4546 // EnableMouseAllMotion enables mouse click, release, wheel and motion46 // enableMouseAllMotion enables mouse click, release, wheel and motion47 // events, regardless of whether a mouse button is pressed. Many modern48 // terminals support this, but not all.49 enableMouseAllMotion()5051 // DisableMouseAllMotion disables All Motion mouse tracking.51 // disableMouseAllMotion disables All Motion mouse tracking.52 disableMouseAllMotion()5354 // enableMouseSGRMode enables mouse extended mode (SGR).55 enableMouseSGRMode()5657 // disableMouseSGRMode disables mouse extended mode (SGR).58 disableMouseSGRMode()5960 // enableBracketedPaste enables bracketed paste, where characters61 // inside the input are not interpreted when pasted as a whole.62 enableBracketedPaste()6364 // disableBracketedPaste disables bracketed paste.65 disableBracketedPaste()6667 // bracketedPasteActive reports whether bracketed paste mode is68 // currently enabled.69 bracketedPasteActive() bool7071 // setWindowTitle sets the terminal window title.72 setWindowTitle(string)7374 // reportFocus returns whether reporting focus events is enabled.75 reportFocus() bool7677 // enableReportFocus reports focus events to the program.78 enableReportFocus()7980 // disableReportFocus stops reporting focus events to the program.81 disableReportFocus()8283 // resetLinesRendered ensures exec output remains on screen on exit84 resetLinesRendered()85}8687// repaintMsg forces a full repaint.88type repaintMsg struct{}
modified:screen_test.go+15 added-9 removed
12 unmodified lines
13 }{14 {15 name: "clear_screen",16 cmds: []Cmd{ClearScreen},17 expected: "\x1b[?25l\x1b[2J\x1b[1;1H\x1b[1;1Hsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l",17 expected: "\x1b[?25l\x1b[?2004h\x1b[2J\x1b[H\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",18 },19 {20 name: "altscreen",21 cmds: []Cmd{EnterAltScreen, ExitAltScreen},22 expected: "\x1b[?25l\x1b[?1049h\x1b[2J\x1b[1;1H\x1b[1;1H\x1b[?25l\x1b[?1049l\x1b[?25lsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l",22 expected: "\x1b[?25l\x1b[?2004h\x1b[?1049h\x1b[2J\x1b[H\x1b[?25l\x1b[?1049l\x1b[?25l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",23 },24 {25 name: "altscreen_autoexit",26 cmds: []Cmd{EnterAltScreen},27 expected: "\x1b[?25l\x1b[?1049h\x1b[2J\x1b[1;1H\x1b[1;1H\x1b[?25lsuccess\r\n\x1b[2;0H\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1049l\x1b[?25h",27 expected: "\x1b[?25l\x1b[?2004h\x1b[?1049h\x1b[2J\x1b[H\x1b[?25l\x1b[H\rsuccess\x1b[K\r\n\x1b[K\x1b[2;H\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h",28 },29 {30 name: "mouse_cellmotion",31 cmds: []Cmd{EnableMouseCellMotion},32 expected: "\x1b[?25l\x1b[?1002hsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l",32 expected: "\x1b[?25l\x1b[?2004h\x1b[?1002h\x1b[?1006h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",33 },34 {35 name: "mouse_allmotion",36 cmds: []Cmd{EnableMouseAllMotion},37 expected: "\x1b[?25l\x1b[?1003hsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l",37 expected: "\x1b[?25l\x1b[?2004h\x1b[?1003h\x1b[?1006h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",38 },39 {40 name: "mouse_disable",41 cmds: []Cmd{EnableMouseAllMotion, DisableMouse},42 expected: "\x1b[?25l\x1b[?1003h\x1b[?1002l\x1b[?1003lsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l",42 expected: "\x1b[?25l\x1b[?2004h\x1b[?1003h\x1b[?1006h\x1b[?1002l\x1b[?1003l\x1b[?1006l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",43 },44 {45 name: "cursor_hide",46 cmds: []Cmd{HideCursor},47 expected: "\x1b[?25l\x1b[?25lsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l",47 expected: "\x1b[?25l\x1b[?2004h\x1b[?25l\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",48 },49 {50 name: "cursor_hideshow",51 cmds: []Cmd{HideCursor, ShowCursor},52 expected: "\x1b[?25l\x1b[?25l\x1b[?25hsuccess\r\n\x1b[0D\x1b[2K\x1b[?25h\x1b[?1002l\x1b[?1003l",52 expected: "\x1b[?25l\x1b[?2004h\x1b[?25l\x1b[?25h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",53 },54 {55 name: "bp_stop_start",56 cmds: []Cmd{DisableBracketedPaste, EnableBracketedPaste},57 expected: "\x1b[?25l\x1b[?2004h\x1b[?2004l\x1b[?2004h\rsuccess\x1b[K\r\n\x1b[K\r\x1b[2K\r\x1b[?2004l\x1b[?25h\x1b[?1002l\x1b[?1003l\x1b[?1006l",58 },59 }6061 for _, test := range tests {62 t.Run(test.name, func(t *testing.T) {
2 unmodified lines
6566 m := &testModel{}67 p := NewProgram(m, WithInput(&in), WithOutput(&buf))6869 test.cmds = append([]Cmd{func() Msg { return WindowSizeMsg{80, 24} }}, test.cmds...)70 test.cmds = append(test.cmds, Quit)71 go p.Send(test.cmds)7273 if _, err := p.Run(); err != nil {74 t.Fatal(err)75 }7677 if buf.String() != test.expected {72 t.Errorf("expected embedded sequence, got %q", buf.String())78 t.Errorf("expected embedded sequence:\n%q\ngot:\n%q", test.expected, buf.String())79 }80 })81 }82}
modified:screen.go+83 added-4 removed
114 unmodified lines
115// showCursorMsg is an internal command used to show the cursor. You can send116// this message with ShowCursor.117type showCursorMsg struct{}118119// EnableBracketedPaste is a special command that tells the Bubble Tea program120// to accept bracketed paste input.121//122// Note that bracketed paste will be automatically disabled when the123// program quits.124func EnableBracketedPaste() Msg {125 return enableBracketedPasteMsg{}126}127128// enableBracketedPasteMsg in an internal message signals that129// bracketed paste should be enabled. You can send an130// enableBracketedPasteMsg with EnableBracketedPaste.131type enableBracketedPasteMsg struct{}132133// DisableBracketedPaste is a special command that tells the Bubble Tea program134// to stop processing bracketed paste input.135//136// Note that bracketed paste will be automatically disabled when the137// program quits.138func DisableBracketedPaste() Msg {139 return disableBracketedPasteMsg{}140}141142// disableBracketedPasteMsg in an internal message signals that143// bracketed paste should be disabled. You can send an144// disableBracketedPasteMsg with DisableBracketedPaste.145type disableBracketedPasteMsg struct{}146147// enableReportFocusMsg is an internal message that signals to enable focus148// reporting. You can send an enableReportFocusMsg with EnableReportFocus.149type enableReportFocusMsg struct{}150151// EnableReportFocus is a special command that tells the Bubble Tea program to152// report focus events to the program.153func EnableReportFocus() Msg {154 return enableReportFocusMsg{}155}156157// disableReportFocusMsg is an internal message that signals to disable focus158// reporting. You can send an disableReportFocusMsg with DisableReportFocus.159type disableReportFocusMsg struct{}160161// DisableReportFocus is a special command that tells the Bubble Tea program to162// stop reporting focus events to the program.163func DisableReportFocus() Msg {164 return disableReportFocusMsg{}165}166167// EnterAltScreen enters the alternate screen buffer, which consumes the entire168// terminal window. ExitAltScreen will return the terminal to its former state.169//170// Deprecated: Use the WithAltScreen ProgramOption instead.171func (p *Program) EnterAltScreen() {172 if p.renderer != nil {173 p.renderer.enterAltScreen()174 } else {175 p.startupOptions |= withAltScreen176 }177}178179// ExitAltScreen exits the alternate screen buffer.
1 unmodified line
181// Deprecated: The altscreen will exited automatically when the program exits.182func (p *Program) ExitAltScreen() {183 if p.renderer != nil {184 p.renderer.exitAltScreen()185 } else {186 p.startupOptions &^= withAltScreen187 }188}189190// EnableMouseCellMotion enables mouse click, release, wheel and motion events191// if a mouse button is pressed (i.e., drag events).192//193// Deprecated: Use the WithMouseCellMotion ProgramOption instead.194func (p *Program) EnableMouseCellMotion() {195 if p.renderer != nil {143 p.renderer.enableMouseCellMotion()196 p.renderer.enableMouseCellMotion()197 } else {198 p.startupOptions |= withMouseCellMotion199 }200}201202// DisableMouseCellMotion disables Mouse Cell Motion tracking. This will be203// called automatically when exiting a Bubble Tea program.204//205// Deprecated: The mouse will automatically be disabled when the program exits.206func (p *Program) DisableMouseCellMotion() {207 if p.renderer != nil {151 p.renderer.disableMouseCellMotion()208 p.renderer.disableMouseCellMotion()209 } else {210 p.startupOptions &^= withMouseCellMotion211 }212}213214// EnableMouseAllMotion enables mouse click, release, wheel and motion events,215// regardless of whether a mouse button is pressed. Many modern terminals216// support this, but not all.217//218// Deprecated: Use the WithMouseAllMotion ProgramOption instead.219func (p *Program) EnableMouseAllMotion() {220 if p.renderer != nil {160 p.renderer.enableMouseAllMotion()221 p.renderer.enableMouseAllMotion()222 } else {223 p.startupOptions |= withMouseAllMotion224 }225}226227// DisableMouseAllMotion disables All Motion mouse tracking. This will be228// called automatically when exiting a Bubble Tea program.229//230// Deprecated: The mouse will automatically be disabled when the program exits.231func (p *Program) DisableMouseAllMotion() {232 if p.renderer != nil {168 p.renderer.disableMouseAllMotion()233 p.renderer.disableMouseAllMotion()234 } else {235 p.startupOptions &^= withMouseAllMotion236 }237}238239// SetWindowTitle sets the terminal window title.240//241// Deprecated: Use the SetWindowTitle command instead.242func (p *Program) SetWindowTitle(title string) {243 if p.renderer != nil {244 p.renderer.setWindowTitle(title)245 } else {246 p.startupTitle = title247 }248}
modified:signals_unix.go+2 added-2 removed
1//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || aix2// +build darwin dragonfly freebsd linux netbsd openbsd solaris aix1//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || aix || zos2// +build darwin dragonfly freebsd linux netbsd openbsd solaris aix zos34package tea56import (
27 unmodified lines
modified:standard_renderer.go+232 added-107 removed
6 unmodified lines
7 "strings"8 "sync"9 "time"1011 "github.com/charmbracelet/x/ansi"12 "github.com/muesli/ansi/compressor"12 "github.com/muesli/reflow/truncate"13 "github.com/muesli/termenv"13)1415const (16 // defaultFramerate specifies the maximum interval at which we should
8 unmodified lines
25// In cases where very high performance is needed the renderer can be told26// to exclude ranges of lines, allowing them to be written to directly.27type standardRenderer struct {28 mtx *sync.Mutex30 out *termenv.Output29 out io.Writer3031 buf bytes.Buffer32 queuedMessageLines []string33 framerate time.Duration34 ticker *time.Ticker35 done chan struct{}36 lastRender string37 lastRenderedLines []string38 linesRendered int39 altLinesRendered int40 useANSICompressor bool41 once sync.Once4243 // cursor visibility state
1 unmodified line
4546 // essentially whether or not we're using the full size of the terminal47 altScreenActive bool4849 // whether or not we're currently using bracketed paste50 bpActive bool5152 // reportingFocus whether reporting focus events is enabled53 reportingFocus bool5455 // renderer dimensions; usually the size of the window56 width int57 height int58
2 unmodified lines
61}6263// newRenderer creates a new renderer. Normally you'll want to initialize it64// with os.Stdout as the first argument.58func newRenderer(out *termenv.Output, useANSICompressor bool, fps int) renderer {65func newRenderer(out io.Writer, useANSICompressor bool, fps int) renderer {66 if fps < 1 {67 fps = defaultFPS68 } else if fps > maxFPS {69 fps = maxFPS
6 unmodified lines
76 useANSICompressor: useANSICompressor,77 queuedMessageLines: []string{},78 }79 if r.useANSICompressor {73 r.out = termenv.NewOutput(&compressor.Writer{Forward: out})80 r.out = &compressor.Writer{Forward: out}81 }82 return r83}84
26 unmodified lines
111112 r.mtx.Lock()113 defer r.mtx.Unlock()114108 r.out.ClearLine()115 r.execute(ansi.EraseEntireLine)116 // Move the cursor back to the beginning of the line117 r.execute("\r")118119 if r.useANSICompressor {111 if w, ok := r.out.TTY().(io.WriteCloser); ok {120 if w, ok := r.out.(io.WriteCloser); ok {121 _ = w.Close()122 }123 }124}125126// execute writes a sequence to the terminal.127func (r *standardRenderer) execute(seq string) {128 _, _ = io.WriteString(r.out, seq)129}130131// kill halts the renderer. The final frame will not be rendered.132func (r *standardRenderer) kill() {133 // Stop the renderer before acquiring the mutex to avoid a deadlock.134 r.once.Do(func() {
2 unmodified lines
137138 r.mtx.Lock()139 defer r.mtx.Unlock()140127 r.out.ClearLine()141 r.execute(ansi.EraseEntireLine)142 // Move the cursor back to the beginning of the line143 r.execute("\r")144}145146// listen waits for ticks on the ticker, or a signal to stop the renderer.147func (r *standardRenderer) listen() {
14 unmodified lines
162 r.mtx.Lock()163 defer r.mtx.Unlock()164165 if r.buf.Len() == 0 || r.buf.String() == r.lastRender {150 // Nothing to do166 // Nothing to do.167 return168 }169154 // Output buffer170 // Output buffer.171 buf := &bytes.Buffer{}156 out := termenv.NewOutput(buf)172173 // Moving to the beginning of the section, that we rendered.174 if r.altScreenActive {175 buf.WriteString(ansi.CursorHomePosition)176 } else if r.linesRendered > 1 {177 buf.WriteString(ansi.CursorUp(r.linesRendered - 1))178 }179180 newLines := strings.Split(r.buf.String(), "\n")181182 // If we know the output's height, we can use it to determine how many183 // lines we can render. We drop lines from the top of the render buffer if
2 unmodified lines
186 if r.height > 0 && len(newLines) > r.height {187 newLines = newLines[len(newLines)-r.height:]188 }189168 numLinesThisFlush := len(newLines)169 oldLines := strings.Split(r.lastRender, "\n")170 skipLines := make(map[int]struct{})190 flushQueuedMessages := len(r.queuedMessageLines) > 0 && !r.altScreenActive191173 // Add any queued messages to this render192 if flushQueuedMessages {175 newLines = append(r.queuedMessageLines, newLines...)176 r.queuedMessageLines = []string{}177 }193 // Dump the lines we've queued up for printing.194 for _, line := range r.queuedMessageLines {195 if ansi.StringWidth(line) < r.width {196 // We only erase the rest of the line when the line is shorter than197 // the width of the terminal. When the cursor reaches the end of198 // the line, any escape sequences that follow will only affect the199 // last cell of the line.200179 // Clear any lines we painted in the last render.180 if r.linesRendered > 0 {181 for i := r.linesRendered - 1; i > 0; i-- {182 // If the number of lines we want to render hasn't increased and183 // new line is the same as the old line we can skip rendering for184 // this line as a performance optimization.185 if (len(newLines) <= len(oldLines)) && (len(newLines) > i && len(oldLines) > i) && (newLines[i] == oldLines[i]) {186 skipLines[i] = struct{}{}187 } else if _, exists := r.ignoreLines[i]; !exists {188 out.ClearLine()201 // Removing previously rendered content at the end of line.202 line = line + ansi.EraseLineRight203 }204191 out.CursorUp(1)205 _, _ = buf.WriteString(line)206 _, _ = buf.WriteString("\r\n")207 }193194 if _, exists := r.ignoreLines[0]; !exists {195 // We need to return to the start of the line here to properly196 // erase it. Going back the entire width of the terminal will197 // usually be farther than we need to go, but terminal emulators198 // will stop the cursor at the start of the line as a rule.199 //200 // We use this sequence in particular because it's part of the ANSI201 // standard (whereas others are proprietary to, say, VT100/VT52).202 // If cursor previous line (ESC[ + <n> + F) were better supported203 // we could use that above to eliminate this step.204 out.CursorBack(r.width)205 out.ClearLine()206 }208 // Clear the queued message lines.209 r.queuedMessageLines = []string{}210 }211209 // Merge the set of lines we're skipping as a rendering optimization with210 // the set of lines we've explicitly asked the renderer to ignore.211 for k, v := range r.ignoreLines {212 skipLines[k] = v213 }214215 // Paint new lines212 // Paint new lines.213 for i := 0; i < len(newLines); i++ {217 if _, skip := skipLines[i]; skip {214 canSkip := !flushQueuedMessages && // Queuing messages triggers repaint -> we don't have access to previous frame content.215 len(r.lastRenderedLines) > i && r.lastRenderedLines[i] == newLines[i] // Previously rendered line is the same.216217 if _, ignore := r.ignoreLines[i]; ignore || canSkip {218 // Unless this is the last line, move the cursor down.219 if i < len(newLines)-1 {220 out.CursorDown(1)220 buf.WriteByte('\n')221 }222 } else {223 line := newLines[i]222 continue223 }224225 // Truncate lines wider than the width of the window to avoid226 // wrapping, which will mess up rendering. If we don't have the227 // width of the window this will be ignored.228 //229 // Note that on Windows we only get the width of the window on230 // program initialization, so after a resize this won't perform231 // correctly (signal SIGWINCH is not supported on Windows).232 if r.width > 0 {233 line = truncate.String(line, uint(r.width))234 }225 if i == 0 && r.lastRender == "" {226 // On first render, reset the cursor to the start of the line227 // before writing anything.228 buf.WriteByte('\r')229 }230236 _, _ = out.WriteString(line)231 line := newLines[i]232238 if i < len(newLines)-1 {239 _, _ = out.WriteString("\r\n")240 }233 // Truncate lines wider than the width of the window to avoid234 // wrapping, which will mess up rendering. If we don't have the235 // width of the window this will be ignored.236 //237 // Note that on Windows we only get the width of the window on238 // program initialization, so after a resize this won't perform239 // correctly (signal SIGWINCH is not supported on Windows).240 if r.width > 0 {241 line = ansi.Truncate(line, r.width, "")242 }243244 if ansi.StringWidth(line) < r.width {245 // We only erase the rest of the line when the line is shorter than246 // the width of the terminal. When the cursor reaches the end of247 // the line, any escape sequences that follow will only affect the248 // last cell of the line.249250 // Removing previously rendered content at the end of line.251 line = line + ansi.EraseLineRight252 }253254 _, _ = buf.WriteString(line)255256 if i < len(newLines)-1 {257 _, _ = buf.WriteString("\r\n")258 }259 }243 r.linesRendered = numLinesThisFlush260261 // Clearing left over content from last render.262 if r.lastLinesRendered() > len(newLines) {263 buf.WriteString(ansi.EraseScreenBelow)264 }265266 if r.altScreenActive {267 r.altLinesRendered = len(newLines)268 } else {269 r.linesRendered = len(newLines)270 }271272 // Make sure the cursor is at the start of the last line to keep rendering273 // behavior consistent.274 if r.altScreenActive {275 // This case fixes a bug in macOS terminal. In other terminals the276 // other case seems to do the job regardless of whether or not we're277 // using the full terminal window.251 out.MoveCursor(r.linesRendered, 0)278 buf.WriteString(ansi.CursorPosition(0, len(newLines)))279 } else {253 out.CursorBack(r.width)280 buf.WriteByte('\r')281 }282283 _, _ = r.out.Write(buf.Bytes())284 r.lastRender = r.buf.String()285286 // Save previously rendered lines for comparison in the next render. If we287 // don't do this, we can't skip rendering lines that haven't changed.288 // See https://github.com/charmbracelet/bubbletea/pull/1233289 r.lastRenderedLines = newLines290 r.buf.Reset()291}292293// lastLinesRendered returns the number of lines rendered lastly.294func (r *standardRenderer) lastLinesRendered() int {295 if r.altScreenActive {296 return r.altLinesRendered297 }298 return r.linesRendered299}300301// write writes to the internal buffer. The buffer will be outputted via the302// ticker which calls flush().303func (r *standardRenderer) write(s string) {304 r.mtx.Lock()
12 unmodified lines
317}318319func (r *standardRenderer) repaint() {320 r.lastRender = ""321 r.lastRenderedLines = nil322}323324func (r *standardRenderer) clearScreen() {325 r.mtx.Lock()326 defer r.mtx.Unlock()327287 r.out.ClearScreen()288 r.out.MoveCursor(1, 1)328 r.execute(ansi.EraseEntireScreen)329 r.execute(ansi.CursorHomePosition)330331 r.repaint()332}333
12 unmodified lines
346 return347 }348349 r.altScreenActive = true309 r.out.AltScreen()350 r.execute(ansi.SetAltScreenSaveCursorMode)351352 // Ensure that the terminal is cleared, even when it doesn't support353 // alt screen (or alt screen support is disabled, like GNU screen by354 // default).355 //356 // Note: we can't use r.clearScreen() here because the mutex is already357 // locked.317 r.out.ClearScreen()318 r.out.MoveCursor(1, 1)358 r.execute(ansi.EraseEntireScreen)359 r.execute(ansi.CursorHomePosition)360361 // cmd.exe and other terminals keep separate cursor states for the AltScreen362 // and the main buffer. We have to explicitly reset the cursor visibility363 // whenever we enter AltScreen.364 if r.cursorHidden {324 r.out.HideCursor()365 r.execute(ansi.HideCursor)366 } else {326 r.out.ShowCursor()367 r.execute(ansi.ShowCursor)368 }369370 // Entering the alt screen resets the lines rendered count.371 r.altLinesRendered = 0372373 r.repaint()374}375376func (r *standardRenderer) exitAltScreen() {
4 unmodified lines
381 return382 }383384 r.altScreenActive = false341 r.out.ExitAltScreen()385 r.execute(ansi.ResetAltScreenSaveCursorMode)386387 // cmd.exe and other terminals keep separate cursor states for the AltScreen388 // and the main buffer. We have to explicitly reset the cursor visibility389 // whenever we exit AltScreen.390 if r.cursorHidden {347 r.out.HideCursor()391 r.execute(ansi.HideCursor)392 } else {349 r.out.ShowCursor()393 r.execute(ansi.ShowCursor)394 }395396 r.repaint()397}
2 unmodified lines
400 r.mtx.Lock()401 defer r.mtx.Unlock()402403 r.cursorHidden = false360 r.out.ShowCursor()404 r.execute(ansi.ShowCursor)405}406407func (r *standardRenderer) hideCursor() {408 r.mtx.Lock()409 defer r.mtx.Unlock()410411 r.cursorHidden = true368 r.out.HideCursor()412 r.execute(ansi.HideCursor)413}414415func (r *standardRenderer) enableMouseCellMotion() {416 r.mtx.Lock()417 defer r.mtx.Unlock()418375 r.out.EnableMouseCellMotion()419 r.execute(ansi.SetButtonEventMouseMode)420}421422func (r *standardRenderer) disableMouseCellMotion() {423 r.mtx.Lock()424 defer r.mtx.Unlock()425382 r.out.DisableMouseCellMotion()426 r.execute(ansi.ResetButtonEventMouseMode)427}428429func (r *standardRenderer) enableMouseAllMotion() {430 r.mtx.Lock()431 defer r.mtx.Unlock()432389 r.out.EnableMouseAllMotion()433 r.execute(ansi.SetAnyEventMouseMode)434}435436func (r *standardRenderer) disableMouseAllMotion() {437 r.mtx.Lock()438 defer r.mtx.Unlock()439396 r.out.DisableMouseAllMotion()440 r.execute(ansi.ResetAnyEventMouseMode)441}442443func (r *standardRenderer) enableMouseSGRMode() {444 r.mtx.Lock()445 defer r.mtx.Unlock()446447 r.execute(ansi.SetSgrExtMouseMode)448}449450func (r *standardRenderer) disableMouseSGRMode() {451 r.mtx.Lock()452 defer r.mtx.Unlock()453454 r.execute(ansi.ResetSgrExtMouseMode)455}456457func (r *standardRenderer) enableBracketedPaste() {458 r.mtx.Lock()459 defer r.mtx.Unlock()460461 r.execute(ansi.SetBracketedPasteMode)462 r.bpActive = true463}464465func (r *standardRenderer) disableBracketedPaste() {466 r.mtx.Lock()467 defer r.mtx.Unlock()468469 r.execute(ansi.ResetBracketedPasteMode)470 r.bpActive = false471}472473func (r *standardRenderer) bracketedPasteActive() bool {474 r.mtx.Lock()475 defer r.mtx.Unlock()476477 return r.bpActive478}479480func (r *standardRenderer) enableReportFocus() {481 r.mtx.Lock()482 defer r.mtx.Unlock()483484 r.execute(ansi.SetFocusEventMode)485 r.reportingFocus = true486}487488func (r *standardRenderer) disableReportFocus() {489 r.mtx.Lock()490 defer r.mtx.Unlock()491492 r.execute(ansi.ResetFocusEventMode)493 r.reportingFocus = false494}495496func (r *standardRenderer) reportFocus() bool {497 r.mtx.Lock()498 defer r.mtx.Unlock()499500 return r.reportingFocus501}502503// setWindowTitle sets the terminal window title.504func (r *standardRenderer) setWindowTitle(title string) {505 r.execute(ansi.SetWindowTitle(title))506}507508// setIgnoredLines specifies lines not to be touched by the standard Bubble Tea509// renderer.510func (r *standardRenderer) setIgnoredLines(from int, to int) {511 // Lock if we're going to be clearing some lines since we don't want512 // anything jacking our cursor.404 if r.linesRendered > 0 {513 if r.lastLinesRendered() > 0 {514 r.mtx.Lock()515 defer r.mtx.Unlock()516 }517
4 unmodified lines
522 r.ignoreLines[i] = struct{}{}523 }524525 // Erase ignored lines526 lastLinesRendered := r.lastLinesRendered()417 if r.linesRendered > 0 {527 if lastLinesRendered > 0 {528 buf := &bytes.Buffer{}419 out := termenv.NewOutput(buf)529421 for i := r.linesRendered - 1; i >= 0; i-- {530 for i := lastLinesRendered - 1; i >= 0; i-- {531 if _, exists := r.ignoreLines[i]; exists {423 out.ClearLine()532 buf.WriteString(ansi.EraseEntireLine)533 }425 out.CursorUp(1)534 buf.WriteString(ansi.CUU1)535 }427 out.MoveCursor(r.linesRendered, 0) // put cursor back536 buf.WriteString(ansi.CursorPosition(0, lastLinesRendered)) // put cursor back537 _, _ = r.out.Write(buf.Bytes())538 }539}540
3 unmodified lines
544func (r *standardRenderer) clearIgnoredLines() {545 r.ignoreLines = nil546}547548func (r *standardRenderer) resetLinesRendered() {549 r.linesRendered = 0550}551552// insertTop effectively scrolls up. It inserts lines at the top of a given553// area designated to be a scrollable region, pushing everything else down.554// This is roughly how ncurses does it.555//
10 unmodified lines
566// different than the normal way we approach rendering in Bubble Tea. It's for567// use in high-performance rendering, such as a pager that could potentially568// be rendering very complicated ansi. In cases where the content is simpler569// standard Bubble Tea rendering should suffice.570//571// Deprecated: This option is deprecated and will be removed in a future572// version of this package.573func (r *standardRenderer) insertTop(lines []string, topBoundary, bottomBoundary int) {574 r.mtx.Lock()575 defer r.mtx.Unlock()576577 buf := &bytes.Buffer{}462 out := termenv.NewOutput(buf)578464 out.ChangeScrollingRegion(topBoundary, bottomBoundary)465 out.MoveCursor(topBoundary, 0)466 out.InsertLines(len(lines))467 _, _ = out.WriteString(strings.Join(lines, "\r\n"))468 out.ChangeScrollingRegion(0, r.height)579 buf.WriteString(ansi.SetTopBottomMargins(topBoundary, bottomBoundary))580 buf.WriteString(ansi.CursorPosition(0, topBoundary))581 buf.WriteString(ansi.InsertLine(len(lines)))582 _, _ = buf.WriteString(strings.Join(lines, "\r\n"))583 buf.WriteString(ansi.SetTopBottomMargins(0, r.height))584585 // Move cursor back to where the main rendering routine expects it to be471 out.MoveCursor(r.linesRendered, 0)586 buf.WriteString(ansi.CursorPosition(0, r.lastLinesRendered()))587588 _, _ = r.out.Write(buf.Bytes())589}590
5 unmodified lines
596//597// See note in insertTop() for caveats, how this function only makes sense for598// full-window applications, and how it differs from the normal way we do599// rendering in Bubble Tea.600//601// Deprecated: This option is deprecated and will be removed in a future602// version of this package.603func (r *standardRenderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {604 r.mtx.Lock()605 defer r.mtx.Unlock()606607 buf := &bytes.Buffer{}490 out := termenv.NewOutput(buf)608492 out.ChangeScrollingRegion(topBoundary, bottomBoundary)493 out.MoveCursor(bottomBoundary, 0)494 _, _ = out.WriteString("\r\n" + strings.Join(lines, "\r\n"))495 out.ChangeScrollingRegion(0, r.height)609 buf.WriteString(ansi.SetTopBottomMargins(topBoundary, bottomBoundary))610 buf.WriteString(ansi.CursorPosition(0, bottomBoundary))611 _, _ = buf.WriteString("\r\n" + strings.Join(lines, "\r\n"))612 buf.WriteString(ansi.SetTopBottomMargins(0, r.height))613614 // Move cursor back to where the main rendering routine expects it to be498 out.MoveCursor(r.linesRendered, 0)615 buf.WriteString(ansi.CursorPosition(0, r.lastLinesRendered()))616617 _, _ = r.out.Write(buf.Bytes())618}619
63 unmodified lines
683// scrollable area. This is required to initialize the scrollable region and684// should also be called on resize (WindowSizeMsg).685//686// For high-performance, scroll-based rendering only.687//688// Deprecated: This option will be removed in a future version of this package.689func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd {690 return func() Msg {691 return syncScrollAreaMsg{692 lines: lines,
8 unmodified lines
701// ClearScrollArea deallocates the scrollable region and returns the control of702// those lines to the main rendering routine.703//704// For high-performance, scroll-based rendering only.705//706// Deprecated: This option will be removed in a future version of this package.707func ClearScrollArea() Msg {708 return clearScrollAreaMsg{}709}710
7 unmodified lines
718// lines below down. Lines that are pushed out the scrollable region disappear719// from view.720//721// For high-performance, scroll-based rendering only.722//723// Deprecated: This option will be removed in a future version of this package.724func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd {725 return func() Msg {726 return scrollUpMsg{727 lines: newLines,
13 unmodified lines
741// existing lines above up. Lines that are pushed out of the scrollable region742// disappear from view.743//744// For high-performance, scroll-based rendering only.745//746// Deprecated: This option will be removed in a future version of this package.747func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd {748 return func() Msg {749 return scrollDownMsg{750 lines: newLines,
40 unmodified lines
added:Taskfile.yaml+14 added
1# https://taskfile.dev23version: '3'45tasks:6 lint:7 desc: Run lint8 cmds:9 - golangci-lint run1011 test:12 desc: Run tests13 cmds:14 - go test ./... {{.CLI_ARGS}}
added:tea_init.go+22 added
1package tea23import (4 "github.com/charmbracelet/lipgloss"5)67func init() {8 // XXX: This is a workaround to make assure that Lip Gloss and Termenv9 // query the terminal before any Bubble Tea Program runs and acquires the10 // terminal. Without this, Programs that use Lip Gloss/Termenv might hang11 // while waiting for a a [termenv.OSCTimeout] while querying the terminal12 // for its background/foreground colors.13 //14 // This happens because Bubble Tea acquires the terminal before termenv15 // reads any responses.16 //17 // Note that this will only affect programs running on the default IO i.e.18 // [os.Stdout] and [os.Stdin].19 //20 // This workaround will be removed in v2.21 _ = lipgloss.HasDarkBackground()22}
modified:tea_test.go+273 added-4 removed
1 unmodified line
23import (4 "bytes"5 "context"6 "errors"7 "sync"8 "sync/atomic"9 "testing"10 "time"11)1213type ctxImplodeMsg struct {14 cancel context.CancelFunc15}1617type incrementMsg struct{}1819type panicMsg struct{}2021type testModel struct {22 executed atomic.Value23 counter atomic.Value24}
2 unmodified lines
27 return nil28}2930func (m *testModel) Update(msg Msg) (Model, Cmd) {23 switch msg.(type) {31 switch msg := msg.(type) {32 case ctxImplodeMsg:33 msg.cancel()34 time.Sleep(100 * time.Millisecond)3536 case incrementMsg:37 i := m.counter.Load()38 if i == nil {39 m.counter.Store(1)
2 unmodified lines
42 }4344 case KeyMsg:45 return m, Quit4647 case panicMsg:48 panic("testing panic behavior")49 }5051 return m, nil52}
7 unmodified lines
60 var buf bytes.Buffer61 var in bytes.Buffer62 in.Write([]byte("q"))6364 ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second)65 defer cancel()6649 p := NewProgram(&testModel{}, WithInput(&in), WithOutput(&buf))67 p := NewProgram(&testModel{}, WithInput(&in), WithOutput(&buf), WithContext(ctx))68 if _, err := p.Run(); err != nil {69 t.Fatal(err)70 }71
22 unmodified lines
94 t.Fatal(err)95 }96}9798func TestTeaWaitQuit(t *testing.T) {99 var buf bytes.Buffer100 var in bytes.Buffer101102 progStarted := make(chan struct{})103 waitStarted := make(chan struct{})104 errChan := make(chan error, 1)105106 m := &testModel{}107 p := NewProgram(m, WithInput(&in), WithOutput(&buf))108109 go func() {110 _, err := p.Run()111 errChan <- err112 }()113114 go func() {115 for {116 time.Sleep(time.Millisecond)117 if m.executed.Load() != nil {118 close(progStarted)119120 <-waitStarted121 time.Sleep(50 * time.Millisecond)122 p.Quit()123124 return125 }126 }127 }()128129 <-progStarted130131 var wg sync.WaitGroup132 for i := 0; i < 5; i++ {133 wg.Add(1)134 go func() {135 p.Wait()136 wg.Done()137 }()138 }139 close(waitStarted)140 wg.Wait()141142 err := <-errChan143 if err != nil {144 t.Fatalf("Expected nil, got %v", err)145 }146}147148func TestTeaWaitKill(t *testing.T) {149 var buf bytes.Buffer150 var in bytes.Buffer151152 progStarted := make(chan struct{})153 waitStarted := make(chan struct{})154 errChan := make(chan error, 1)155156 m := &testModel{}157 p := NewProgram(m, WithInput(&in), WithOutput(&buf))158159 go func() {160 _, err := p.Run()161 errChan <- err162 }()163164 go func() {165 for {166 time.Sleep(time.Millisecond)167 if m.executed.Load() != nil {168 close(progStarted)169170 <-waitStarted171 time.Sleep(50 * time.Millisecond)172 p.Kill()173174 return175 }176 }177 }()178179 <-progStarted180181 var wg sync.WaitGroup182 for i := 0; i < 5; i++ {183 wg.Add(1)184 go func() {185 p.Wait()186 wg.Done()187 }()188 }189 close(waitStarted)190 wg.Wait()191192 err := <-errChan193 if !errors.Is(err, ErrProgramKilled) {194 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)195 }196}197198func TestTeaWithFilter(t *testing.T) {199 testTeaWithFilter(t, 0)200 testTeaWithFilter(t, 1)201 testTeaWithFilter(t, 2)
49 unmodified lines
251 }252 }253 }()254137 if _, err := p.Run(); err != ErrProgramKilled {255 _, err := p.Run()256257 if !errors.Is(err, ErrProgramKilled) {258 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)259 }260261 if errors.Is(err, context.Canceled) {262 // The end user should not know about the program's internal context state.263 // The program should only report external context cancellation as a context error.264 t.Fatalf("Internal context cancellation was reported as context error!")265 }266}267268func TestTeaContext(t *testing.T) {269 ctx, cancel := context.WithCancel(context.Background())
11 unmodified lines
281 }282 }283 }()284159 if _, err := p.Run(); err != ErrProgramKilled {285 _, err := p.Run()286287 if !errors.Is(err, ErrProgramKilled) {288 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)289 }290291 if !errors.Is(err, context.Canceled) {292 // The end user should know that their passed in context caused the kill.293 t.Fatalf("Expected %v, got %v", context.Canceled, err)294 }295}296297func TestTeaContextImplodeDeadlock(t *testing.T) {298 ctx, cancel := context.WithCancel(context.Background())299 var buf bytes.Buffer300 var in bytes.Buffer301302 m := &testModel{}303 p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))304 go func() {305 for {306 time.Sleep(time.Millisecond)307 if m.executed.Load() != nil {308 p.Send(ctxImplodeMsg{cancel: cancel})309 return310 }311 }312 }()313314 if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {315 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)316 }317}318319func TestTeaContextBatchDeadlock(t *testing.T) {320 ctx, cancel := context.WithCancel(context.Background())321 var buf bytes.Buffer322 var in bytes.Buffer323324 inc := func() Msg {325 cancel()326 return incrementMsg{}327 }328329 m := &testModel{}330 p := NewProgram(m, WithContext(ctx), WithInput(&in), WithOutput(&buf))331 go func() {332 for {333 time.Sleep(time.Millisecond)334 if m.executed.Load() != nil {335 batch := make(BatchMsg, 100)336 for i := range batch {337 batch[i] = inc338 }339 p.Send(batch)340 return341 }342 }343 }()344345 if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {346 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)347 }348}349350func TestTeaBatchMsg(t *testing.T) {351 var buf bytes.Buffer352 var in bytes.Buffer353
69 unmodified lines
423 t.Fatalf("counter should be 3, got %d", m.counter.Load())424 }425}426427func TestTeaNestedSequenceMsg(t *testing.T) {428 var buf bytes.Buffer429 var in bytes.Buffer430431 inc := func() Msg {432 return incrementMsg{}433 }434435 m := &testModel{}436 p := NewProgram(m, WithInput(&in), WithOutput(&buf))437 go p.Send(sequenceMsg{inc, Sequence(inc, inc), Quit})438439 if _, err := p.Run(); err != nil {440 t.Fatal(err)441 }442443 if m.counter.Load() != 3 {444 t.Fatalf("counter should be 3, got %d", m.counter.Load())445 }446}447448func TestTeaSend(t *testing.T) {449 var buf bytes.Buffer450 var in bytes.Buffer451
17 unmodified lines
469470 m := &testModel{}471 NewProgram(m, WithInput(&in), WithOutput(&buf))472}473474func TestTeaPanic(t *testing.T) {475 var buf bytes.Buffer476 var in bytes.Buffer477478 m := &testModel{}479 p := NewProgram(m, WithInput(&in), WithOutput(&buf))480 go func() {481 for {482 time.Sleep(time.Millisecond)483 if m.executed.Load() != nil {484 p.Send(panicMsg{})485 return486 }487 }488 }()489490 _, err := p.Run()491492 if !errors.Is(err, ErrProgramPanic) {493 t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)494 }495496 if !errors.Is(err, ErrProgramKilled) {497 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)498 }499}500501func TestTeaGoroutinePanic(t *testing.T) {502 var buf bytes.Buffer503 var in bytes.Buffer504505 panicCmd := func() Msg {506 panic("testing goroutine panic behavior")507 }508509 m := &testModel{}510 p := NewProgram(m, WithInput(&in), WithOutput(&buf))511 go func() {512 for {513 time.Sleep(time.Millisecond)514 if m.executed.Load() != nil {515 batch := make(BatchMsg, 10)516 for i := range batch {517 batch[i] = panicCmd518 }519 p.Send(batch)520 return521 }522 }523 }()524525 _, err := p.Run()526527 if !errors.Is(err, ErrProgramPanic) {528 t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)529 }530531 if !errors.Is(err, ErrProgramKilled) {532 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)533 }534}
modified:tea.go+288 added-96 removed
14 unmodified lines
15 "fmt"16 "io"17 "os"18 "os/signal"19 "runtime"20 "runtime/debug"21 "sync"22 "sync/atomic"23 "syscall"2423 "github.com/containerd/console"24 isatty "github.com/mattn/go-isatty"25 "github.com/charmbracelet/x/term"26 "github.com/muesli/cancelreader"26 "github.com/muesli/termenv"27 "golang.org/x/sync/errgroup"27)2829// ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic.30var ErrProgramPanic = errors.New("program experienced a panic")3130// ErrProgramKilled is returned by [Program.Run] when the program got killed.32// ErrProgramKilled is returned by [Program.Run] when the program gets killed.33var ErrProgramKilled = errors.New("program was killed")3435// ErrInterrupted is returned by [Program.Run] when the program get a SIGINT36// signal, or when it receives a [InterruptMsg].37var ErrInterrupted = errors.New("program was interrupted")3839// Msg contain data from the result of a IO operation. Msgs trigger the update40// function and, henceforth, the UI.41type Msg interface{}42
28 unmodified lines
71 ttyInput72 customInput73)7469// String implements the stringer interface for [inputType]. It is inteded to75// String implements the stringer interface for [inputType]. It is intended to76// be used in testing.77func (i inputType) String() string {78 return [...]string{79 "default input",
5 unmodified lines
85// Options to customize the program during its initialization. These are86// generally set with ProgramOptions.87//88// The options here are treated as bits.83type startupOptions byte89type startupOptions int169091func (s startupOptions) has(option startupOptions) bool {92 return s&option != 093}
3 unmodified lines
97 withMouseCellMotion98 withMouseAllMotion99 withANSICompressor100 withoutSignalHandler95101 // Catching panics is incredibly useful for restoring the terminal to a102 // usable state after a panic occurs. When this is set, Bubble Tea will103 // recover from panics, print the stack trace, and disable raw mode. This104 // feature is on by default.105 withoutCatchPanics106 withoutBracketedPaste107 withReportFocus108)109103// handlers manages series of channels returned by various processes. It allows104// us to wait for those processes to terminate before exiting the program.105type handlers []chan struct{}110// channelHandlers manages the series of channels returned by various processes.111// It allows us to wait for those processes to terminate before exiting the112// program.113type channelHandlers []chan struct{}114115// Adds a channel to the list of handlers. We wait for all handlers to terminate116// gracefully on shutdown.109func (h *handlers) add(ch chan struct{}) {117func (h *channelHandlers) add(ch chan struct{}) {118 *h = append(*h, ch)119}120121// shutdown waits for all handlers to terminate.114func (h handlers) shutdown() {122func (h channelHandlers) shutdown() {123 var wg sync.WaitGroup124 for _, ch := range h {125 wg.Add(1)126 go func(ch chan struct{}) {
7 unmodified lines
134// Program is a terminal user interface.135type Program struct {136 initialModel Model137138 // handlers is a list of channels that need to be waited on before the139 // program can exit.140 handlers channelHandlers141142 // Configuration options that will set as the program is initializing,143 // treated as bits. These options can be set via various ProgramOptions.144 startupOptions startupOptions145146 // startupTitle is the title that will be set on the terminal when the147 // program starts.148 startupTitle string149150 inputType inputType151152 // externalCtx is a context that was passed in via WithContext, otherwise defaulting153 // to ctx.Background() (in case it was not), the internal context is derived from it.154 externalCtx context.Context155156 // ctx is the programs's internal context for signalling internal teardown.157 // It is built and derived from the externalCtx in NewProgram().158 ctx context.Context159 cancel context.CancelFunc160161 msgs chan Msg162 errs chan error163 finished chan struct{}164165 // where to send output, this will usually be os.Stdout.144 output *termenv.Output145 restoreOutput func() error146 renderer renderer166 output io.Writer167 // ttyOutput is null if output is not a TTY.168 ttyOutput term.File169 previousOutputState *term.State170 renderer renderer171172 // the environment variables for the program, defaults to os.Environ().173 environ []string174175 // where to read inputs from, this will usually be os.Stdin.149 input io.Reader150 cancelReader cancelreader.CancelReader151 readLoopDone chan struct{}152 console console.Console176 input io.Reader177 // ttyInput is null if input is not a TTY.178 ttyInput term.File179 previousTtyInputState *term.State180 cancelReader cancelreader.CancelReader181 readLoopDone chan struct{}182183 // was the altscreen active before releasing the terminal?184 altScreenWasActive bool156 ignoreSignals bool185 ignoreSignals uint32186158 // Stores the original reference to stdin for cases where input is not a159 // TTY on windows and we've automatically opened CONIN$ to receive input.160 // When the program exits this will be restored.161 //162 // Lint ignore note: the linter will find false positive on unix systems163 // as this value only comes into play on Windows, hence the ignore comment164 // below.165 windowsStdin *os.File //nolint:golint,structcheck,unused187 bpWasActive bool // was the bracketed paste mode active before releasing the terminal?188 reportFocus bool // was focus reporting active before releasing the terminal?189190 filter func(Model, Msg) Msg191192 // fps is the frames per second we should set on the renderer, if193 // applicable,194 fps int195196 // mouseMode is true if the program should enable mouse mode on Windows.197 mouseMode bool198}199200// Quit is a special command that tells the Bubble Tea program to exit.201func Quit() Msg {202 return QuitMsg{}203}204179// QuitMsg signals that the program should quit. You can send a QuitMsg with180// Quit.205// QuitMsg signals that the program should quit. You can send a [QuitMsg] with206// [Quit].207type QuitMsg struct{}208209// Suspend is a special command that tells the Bubble Tea program to suspend.210func Suspend() Msg {211 return SuspendMsg{}212}213214// SuspendMsg signals the program should suspend.215// This usually happens when ctrl+z is pressed on common programs, but since216// bubbletea puts the terminal in raw mode, we need to handle it in a217// per-program basis.218//219// You can send this message with [Suspend()].220type SuspendMsg struct{}221222// ResumeMsg can be listen to do something once a program is resumed back223// from a suspend state.224type ResumeMsg struct{}225226// InterruptMsg signals the program should suspend.227// This usually happens when ctrl+c is pressed on common programs, but since228// bubbletea puts the terminal in raw mode, we need to handle it in a229// per-program basis.230//231// You can send this message with [Interrupt()].232type InterruptMsg struct{}233234// Interrupt is a special command that tells the Bubble Tea program to235// interrupt.236func Interrupt() Msg {237 return InterruptMsg{}238}239240// NewProgram creates a new Program.241func NewProgram(model Model, opts ...ProgramOption) *Program {242 p := &Program{243 initialModel: model,
6 unmodified lines
250 }251252 // A context can be provided with a ProgramOption, but if none was provided253 // we'll use the default background context.197 if p.ctx == nil {198 p.ctx = context.Background()254 if p.externalCtx == nil {255 p.externalCtx = context.Background()256 }257 // Initialize context and teardown channel.201 p.ctx, p.cancel = context.WithCancel(p.ctx)258 p.ctx, p.cancel = context.WithCancel(p.externalCtx)259260 // if no output was set, set it to stdout261 if p.output == nil {205 p.output = termenv.DefaultOutput()262 p.output = os.Stdout263 }264207 // cache detected color values208 termenv.WithColorCache(true)(p.output)265 // if no environment was set, set it to os.Environ()266 if p.environ == nil {267 p.environ = os.Environ()268 }269211 p.restoreOutput, _ = termenv.EnableVirtualTerminalProcessing(p.output)212270 return p271}272273func (p *Program) handleSignals() chan struct{} {
19 unmodified lines
293 select {294 case <-p.ctx.Done():295 return296240 case <-sig:241 if !p.ignoreSignals {242 p.msgs <- QuitMsg{}297 case s := <-sig:298 if atomic.LoadUint32(&p.ignoreSignals) == 0 {299 switch s {300 case syscall.SIGINT:301 p.msgs <- InterruptMsg{}302 default:303 p.msgs <- QuitMsg{}304 }305 return306 }307 }308 }
5 unmodified lines
314// handleResize handles terminal resize events.315func (p *Program) handleResize() chan struct{} {316 ch := make(chan struct{})317256 if f, ok := p.output.TTY().(*os.File); ok && isatty.IsTerminal(f.Fd()) {318 if p.ttyOutput != nil {319 // Get the initial terminal size and send it to the program.320 go p.checkResize()321322 // Listen for window resizes.
28 unmodified lines
351 // (e.g. tick commands that sleep for half a second). It's not352 // possible to cancel them so we'll have to leak the goroutine353 // until Cmd returns.354 go func() {355 // Recover from panics.356 if !p.startupOptions.has(withoutCatchPanics) {357 defer func() {358 if r := recover(); r != nil {359 p.recoverFromGoPanic(r)360 }361 }()362 }363364 msg := cmd() // this can be long.365 p.Send(msg)366 }()367 }
2 unmodified lines
370371 return ch372}373374func (p *Program) disableMouse() {375 p.renderer.disableMouseCellMotion()376 p.renderer.disableMouseAllMotion()377 p.renderer.disableMouseSGRMode()378}379380// eventLoop is the central message loop. It receives and handles the default381// Bubble Tea messages, update the model and triggers redraws.382func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {383 for {
17 unmodified lines
401 switch msg := msg.(type) {402 case QuitMsg:403 return model, nil404405 case InterruptMsg:406 return model, ErrInterrupted407408 case SuspendMsg:409 if suspendSupported {410 p.suspend()411 }412413 case clearScreenMsg:414 p.renderer.clearScreen()415416 case enterAltScreenMsg:
1 unmodified line
418419 case exitAltScreenMsg:420 p.renderer.exitAltScreen()421422 case enableMouseCellMotionMsg, enableMouseAllMotionMsg:423 switch msg.(type) {337 case enableMouseCellMotionMsg:338 p.renderer.enableMouseCellMotion()424 case enableMouseCellMotionMsg:425 p.renderer.enableMouseCellMotion()426 case enableMouseAllMotionMsg:427 p.renderer.enableMouseAllMotion()428 }429 // mouse mode (1006) is a no-op if the terminal doesn't support it.430 p.renderer.enableMouseSGRMode()431340 case enableMouseAllMotionMsg:341 p.renderer.enableMouseAllMotion()432 // XXX: This is used to enable mouse mode on Windows. We need433 // to reinitialize the cancel reader to get the mouse events to434 // work.435 if runtime.GOOS == "windows" && !p.mouseMode {436 p.mouseMode = true437 p.initCancelReader(true) //nolint:errcheck,gosec438 }439440 case disableMouseMsg:344 p.renderer.disableMouseCellMotion()345 p.renderer.disableMouseAllMotion()441 p.disableMouse()442443 // XXX: On Windows, mouse mode is enabled on the input reader444 // level. We need to instruct the input reader to stop reading445 // mouse events.446 if runtime.GOOS == "windows" && p.mouseMode {447 p.mouseMode = false448 p.initCancelReader(true) //nolint:errcheck,gosec449 }450451 case showCursorMsg:452 p.renderer.showCursor()453454 case hideCursorMsg:455 p.renderer.hideCursor()456457 case enableBracketedPasteMsg:458 p.renderer.enableBracketedPaste()459460 case disableBracketedPasteMsg:461 p.renderer.disableBracketedPaste()462463 case enableReportFocusMsg:464 p.renderer.enableReportFocus()465466 case disableReportFocusMsg:467 p.renderer.disableReportFocus()468469 case execMsg:470 // NB: this blocks.471 p.exec(msg.cmd, msg.fn)472
12 unmodified lines
485 }486487 var cmd Cmd488 model, cmd = model.Update(msg) // run update489490 select {491 case <-p.ctx.Done():492 return model, nil373 cmds <- cmd // process command (if any)493 case cmds <- cmd: // process command (if any)494 }495496 p.renderer.write(model.View()) // send view to renderer497 }498 }499}
44 unmodified lines
544545// Run initializes the program and runs its event loops, blocking until it gets546// terminated by either [Program.Quit], [Program.Kill], or its signal handler.547// Returns the final model.426func (p *Program) Run() (Model, error) {427 handlers := handlers{}548func (p *Program) Run() (returnModel Model, returnErr error) {549 p.handlers = channelHandlers{}550 cmds := make(chan Cmd)429 p.errs = make(chan error)430 p.finished = make(chan struct{}, 1)551 p.errs = make(chan error, 1)552553 p.finished = make(chan struct{})554 defer func() {555 close(p.finished)556 }()557558 defer p.cancel()559560 switch p.inputType {561 case defaultInput:
4 unmodified lines
566 // input. This will allow things to "just work" in cases where data was567 // piped in or redirected to the application.568 //569 // To disable input entirely pass nil to the [WithInput] program option.444 f, isFile := p.input.(*os.File)570 f, isFile := p.input.(term.File)571 if !isFile {572 break573 }448 if isatty.IsTerminal(f.Fd()) {574 if term.IsTerminal(f.Fd()) {575 break576 }577578 f, err := openInputTTY()
17 unmodified lines
596 }597598 // Handle signals.599 if !p.startupOptions.has(withoutSignalHandler) {474 handlers.add(p.handleSignals())600 p.handlers.add(p.handleSignals())601 }602603 // Recover from panics.604 if !p.startupOptions.has(withoutCatchPanics) {605 defer func() {606 if r := recover(); r != nil {481 p.shutdown(true)482 fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)483 debug.PrintStack()484 return607 returnErr = fmt.Errorf("%w: %w", ErrProgramKilled, ErrProgramPanic)608 p.recoverFromPanic(r)609 }610 }()611 }612
8 unmodified lines
621 return p.initialModel, err622 }623624 // Honor program startup options.625 if p.startupTitle != "" {626 p.renderer.setWindowTitle(p.startupTitle)627 }628 if p.startupOptions&withAltScreen != 0 {629 p.renderer.enterAltScreen()630 }631 if p.startupOptions&withoutBracketedPaste == 0 {632 p.renderer.enableBracketedPaste()633 }634 if p.startupOptions&withMouseCellMotion != 0 {635 p.renderer.enableMouseCellMotion()636 p.renderer.enableMouseSGRMode()637 } else if p.startupOptions&withMouseAllMotion != 0 {638 p.renderer.enableMouseAllMotion()639 p.renderer.enableMouseSGRMode()640 }641642 // XXX: Should we enable mouse mode on Windows?643 // This needs to happen before initializing the cancel and input reader.644 p.mouseMode = p.startupOptions&withMouseCellMotion != 0 || p.startupOptions&withMouseAllMotion != 0645646 if p.startupOptions&withReportFocus != 0 {647 p.renderer.enableReportFocus()648 }649650 // Start the renderer.651 p.renderer.start()652653 // Initialize the program.654 model := p.initialModel655 if initCmd := model.Init(); initCmd != nil {656 ch := make(chan struct{})514 handlers.add(ch)657 p.handlers.add(ch)658659 go func() {660 defer close(ch)661
3 unmodified lines
665 }666 }()667 }668526 // Start the renderer.527 p.renderer.start()528669 // Render the initial view.670 p.renderer.write(model.View())671672 // Subscribe to user input.673 if p.input != nil {534 if err := p.initCancelReader(); err != nil {674 if err := p.initCancelReader(false); err != nil {675 return model, err676 }677 }678679 // Handle resize events.540 handlers.add(p.handleResize())680 p.handlers.add(p.handleResize())681682 // Process commands.543 handlers.add(p.handleCommands(cmds))683 p.handlers.add(p.handleCommands(cmds))684685 // Run event loop, handle updates and draw.686 model, err := p.eventLoop(model, cmds)547 killed := p.ctx.Err() != nil687688 if err == nil && len(p.errs) > 0 {689 err = <-p.errs // Drain a leftover error in case eventLoop crashed690 }691692 killed := p.externalCtx.Err() != nil || p.ctx.Err() != nil || err != nil693 if killed {694 if err == nil && p.externalCtx.Err() != nil {695 // Return also as context error the cancellation of an external context.696 // This is the context the user knows about and should be able to act on.697 err = fmt.Errorf("%w: %w", ErrProgramKilled, p.externalCtx.Err())698 } else if err == nil && p.ctx.Err() != nil {699 // Return only that the program was killed (not the internal mechanism).700 // The user does not know or need to care about the internal program context.549 err = ErrProgramKilled701 err = ErrProgramKilled702 } else {703 // Return that the program was killed and also the error that caused it.704 err = fmt.Errorf("%w: %w", ErrProgramKilled, err)705 }706 } else {707 // Graceful shutdown of the program (not killed):708 // Ensure we rendered the final state of the model.709 p.renderer.write(model.View())710 }711555 // Tear down.556 p.cancel()557558 // Check if the cancel reader has been setup before waiting and closing.559 if p.cancelReader != nil {560 // Wait for input loop to finish.561 if p.cancelReader.Cancel() {562 p.waitForReadLoop()563 }564 _ = p.cancelReader.Close()565 }566567 // Wait for all handlers to finish.568 handlers.shutdown()569712 // Restore terminal state.713 p.shutdown(killed)714715 return model, err
42 unmodified lines
758func (p *Program) Quit() {759 p.Send(Quit())760}761620// Kill stops the program immediately and restores the former terminal state.762// Kill signals the program to stop immediately and restore the former terminal state.763// The final render that you would normally see when quitting will be skipped.764// [program.Run] returns a [ErrProgramKilled] error.765func (p *Program) Kill() {766 p.cancel()
4 unmodified lines
771 <-p.finished772}773774// shutdown performs operations to free up resources and restore the terminal633// to its original state.775// to its original state. It is called once at the end of the program's lifetime.776//777// This method should not be called to signal the program to be killed/shutdown.778// Doing so can lead to race conditions with the eventual call at the program's end.779// As alternatives, the [Quit] or [Kill] convenience methods should be used instead.780func (p *Program) shutdown(kill bool) {781 p.cancel()782783 // Wait for all handlers to finish.784 p.handlers.shutdown()785786 // Check if the cancel reader has been setup before waiting and closing.787 if p.cancelReader != nil {788 // Wait for input loop to finish.789 if p.cancelReader.Cancel() {790 if !kill {791 p.waitForReadLoop()792 }793 }794 _ = p.cancelReader.Close()795 }796797 if p.renderer != nil {798 if kill {799 p.renderer.kill()800 } else {
1 unmodified line
802 }803 }804805 _ = p.restoreTerminalState()644 if p.restoreOutput != nil {645 _ = p.restoreOutput()806}807808// recoverFromPanic recovers from a panic, prints the stack trace, and restores809// the terminal to a usable state.810func (p *Program) recoverFromPanic(r interface{}) {811 select {812 case p.errs <- ErrProgramPanic:813 default:814 }647 p.finished <- struct{}{}815 p.shutdown(true) // Ok to call here, p.Run() cannot do it anymore.816 fmt.Printf("Caught panic:\n\n%s\n\nRestoring terminal...\n\n", r)817 debug.PrintStack()818}819820// recoverFromGoPanic recovers from a goroutine panic, prints a stack trace and821// signals for the program to be killed and terminal restored to a usable state.822func (p *Program) recoverFromGoPanic(r interface{}) {823 select {824 case p.errs <- ErrProgramPanic:825 default:826 }827 p.cancel()828 fmt.Printf("Caught goroutine panic:\n\n%s\n\nRestoring terminal...\n\n", r)829 debug.PrintStack()830}831832// ReleaseTerminal restores the original terminal state and cancels the input833// reader. You can return control to the Program with RestoreTerminal.834func (p *Program) ReleaseTerminal() error {653 p.ignoreSignals = true654 p.cancelReader.Cancel()835 atomic.StoreUint32(&p.ignoreSignals, 1)836 if p.cancelReader != nil {837 p.cancelReader.Cancel()838 }839840 p.waitForReadLoop()841842 if p.renderer != nil {843 p.renderer.stop()844 p.altScreenWasActive = p.renderer.altScreen()845 p.bpWasActive = p.renderer.bracketedPasteActive()846 p.reportFocus = p.renderer.reportFocus()847 }848661 p.altScreenWasActive = p.renderer.altScreen()849 return p.restoreTerminalState()850}851852// RestoreTerminal reinitializes the Program's input reader, restores the853// terminal to the former state when the program was running, and repaints.854// Use it to reinitialize a Program after running ReleaseTerminal.855func (p *Program) RestoreTerminal() error {669 p.ignoreSignals = false856 atomic.StoreUint32(&p.ignoreSignals, 0)857858 if err := p.initTerminal(); err != nil {859 return err860 }674 if err := p.initCancelReader(); err != nil {861 if err := p.initCancelReader(false); err != nil {862 return err863 }677864 if p.altScreenWasActive {865 p.renderer.enterAltScreen()866 } else {867 // entering alt screen already causes a repaint.
1 unmodified line
869 }870 if p.renderer != nil {871 p.renderer.start()872 }873 if p.bpWasActive {874 p.renderer.enableBracketedPaste()875 }876 if p.reportFocus {877 p.renderer.enableReportFocus()878 }879880 // If the output is a terminal, it may have been resized while another881 // process was at the foreground, in which case we may not have received882 // SIGWINCH. Detect any size change now and propagate the new size as
29 unmodified lines
modified:tty_unix.go+25 added-21 removed
1//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || aix2// +build darwin dragonfly freebsd linux netbsd openbsd solaris aix1//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || aix || zos2// +build darwin dragonfly freebsd linux netbsd openbsd solaris aix zos34package tea56import (7 "fmt"8 "os"9 "os/signal"10 "syscall"1110 "github.com/containerd/console"12 "github.com/charmbracelet/x/term"13)1413func (p *Program) initInput() error {14 // If input's a file, use console to manage it15 if f, ok := p.input.(*os.File); ok {16 c, err := console.ConsoleFromFile(f)15func (p *Program) initInput() (err error) {16 // Check if input is a terminal17 if f, ok := p.input.(term.File); ok && term.IsTerminal(f.Fd()) {18 p.ttyInput = f19 p.previousTtyInputState, err = term.MakeRaw(p.ttyInput.Fd())20 if err != nil {18 return nil //nolint:nilerr // ignore error, this was just a test21 return fmt.Errorf("error entering raw mode: %w", err)22 }20 p.console = c23 }2423 return nil24}2526// On unix systems, RestoreInput closes any TTYs we opened for input. Note that27// we don't do this on Windows as it causes the prompt to not be drawn until28// the terminal receives a keypress rather than appearing promptly after the29// program exits.30func (p *Program) restoreInput() error {31 if p.console != nil {32 if err := p.console.Reset(); err != nil {33 return fmt.Errorf("error restoring console: %w", err)34 }25 if f, ok := p.output.(term.File); ok && term.IsTerminal(f.Fd()) {26 p.ttyOutput = f27 }2829 return nil30}3132func openInputTTY() (*os.File, error) {
2 unmodified lines
35 return nil, fmt.Errorf("could not open a new TTY: %w", err)36 }37 return f, nil38}3940const suspendSupported = true4142// Send SIGTSTP to the entire process group.43func suspendProcess() {44 c := make(chan os.Signal, 1)45 signal.Notify(c, syscall.SIGCONT)46 _ = syscall.Kill(0, syscall.SIGTSTP)47 // blocks until a CONT happens...48 <-c49}
modified:tty_windows.go+43 added-22 removed
2 unmodified lines
34package tea56import (7 "fmt"8 "os"99 "github.com/containerd/console"10 "github.com/charmbracelet/x/term"11 "golang.org/x/sys/windows"12)1312func (p *Program) initInput() error {13 // If input's a file, use console to manage it14 if f, ok := p.input.(*os.File); ok {15 // Save a reference to the current stdin then replace stdin with our16 // input. We do this so we can hand input off to containerd/console to17 // set raw mode, and do it in this fashion because the method18 // console.ConsoleFromFile isn't supported on Windows.19 p.windowsStdin = os.Stdin20 os.Stdin = f14func (p *Program) initInput() (err error) {15 // Save stdin state and enable VT input16 // We also need to enable VT17 // input here.18 if f, ok := p.input.(term.File); ok && term.IsTerminal(f.Fd()) {19 p.ttyInput = f20 p.previousTtyInputState, err = term.MakeRaw(p.ttyInput.Fd())21 if err != nil {22 return fmt.Errorf("error making raw: %w", err)23 }2422 // Note: this will panic if it fails.23 c := console.Current()24 p.console = c25 // Enable VT input26 var mode uint3227 if err := windows.GetConsoleMode(windows.Handle(p.ttyInput.Fd()), &mode); err != nil {28 return fmt.Errorf("error getting console mode: %w", err)29 }3031 if err := windows.SetConsoleMode(windows.Handle(p.ttyInput.Fd()), mode|windows.ENABLE_VIRTUAL_TERMINAL_INPUT); err != nil {32 return fmt.Errorf("error setting console mode: %w", err)33 }34 }3536 // Save output screen buffer state and enable VT processing.37 if f, ok := p.output.(term.File); ok && term.IsTerminal(f.Fd()) {38 p.ttyOutput = f39 p.previousOutputState, err = term.GetState(f.Fd())40 if err != nil {27 return nil28}41 return fmt.Errorf("error getting state: %w", err)42 }4330// restoreInput restores stdout in the event that we placed it aside to handle31// input with CONIN$, above.32func (p *Program) restoreInput() error {33 if p.windowsStdin != nil {34 os.Stdin = p.windowsStdin44 var mode uint3245 if err := windows.GetConsoleMode(windows.Handle(p.ttyOutput.Fd()), &mode); err != nil {46 return fmt.Errorf("error getting console mode: %w", err)47 }4849 if err := windows.SetConsoleMode(windows.Handle(p.ttyOutput.Fd()), mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err != nil {50 return fmt.Errorf("error setting console mode: %w", err)51 }52 }5354 return nil55}5657// Open the Windows equivalent of a TTY.58func openInputTTY() (*os.File, error) {42 f, err := os.OpenFile("CONIN$", os.O_RDWR, 0644)59 f, err := os.OpenFile("CONIN$", os.O_RDWR, 0o644) //nolint:gosec60 if err != nil {44 return nil, err61 return nil, fmt.Errorf("error opening file: %w", err)62 }63 return f, nil64}6566const suspendSupported = false6768func suspendProcess() {}
modified:tty.go+50 added-29 removed
2 unmodified lines
3import (4 "errors"5 "fmt"6 "io"7 "os"7 "time"810 isatty "github.com/mattn/go-isatty"11 localereader "github.com/mattn/go-localereader"9 "github.com/charmbracelet/x/term"10 "github.com/muesli/cancelreader"13 "golang.org/x/term"11)1213func (p *Program) suspend() {14 if err := p.ReleaseTerminal(); err != nil {15 // If we can't release input, abort.16 return17 }1819 suspendProcess()2021 _ = p.RestoreTerminal()22 go p.Send(ResumeMsg{})23}2425func (p *Program) initTerminal() error {17 err := p.initInput()18 if err != nil {19 return err26 if _, ok := p.renderer.(*nilRenderer); ok {27 // No need to initialize the terminal if we're not rendering28 return nil29 }3022 if p.console != nil {23 err = p.console.SetRaw()24 if err != nil {25 return fmt.Errorf("error entering raw mode: %w", err)26 }31 if err := p.initInput(); err != nil {32 return err33 }3435 p.renderer.hideCursor()36 return nil
2 unmodified lines
39// restoreTerminalState restores the terminal to the state prior to running the40// Bubble Tea program.41func (p *Program) restoreTerminalState() error {42 if p.renderer != nil {43 p.renderer.disableBracketedPaste()44 p.renderer.showCursor()38 p.renderer.disableMouseCellMotion()39 p.renderer.disableMouseAllMotion()45 p.disableMouse()4647 if p.renderer.reportFocus() {48 p.renderer.disableReportFocus()49 }5051 if p.renderer.altScreen() {52 p.renderer.exitAltScreen()5354 // give the terminal a moment to catch up45 time.Sleep(time.Millisecond * 10) //nolint:gomnd55 time.Sleep(time.Millisecond * 10) //nolint:mnd56 }57 }5849 if p.console != nil {50 err := p.console.Reset()51 if err != nil {52 return fmt.Errorf("error restoring terminal state: %w", err)59 return p.restoreInput()60}6162// restoreInput restores the tty input to its original state.63func (p *Program) restoreInput() error {64 if p.ttyInput != nil && p.previousTtyInputState != nil {65 if err := term.Restore(p.ttyInput.Fd(), p.previousTtyInputState); err != nil {66 return fmt.Errorf("error restoring console: %w", err)67 }68 }5556 return p.restoreInput()69 if p.ttyOutput != nil && p.previousOutputState != nil {70 if err := term.Restore(p.ttyOutput.Fd(), p.previousOutputState); err != nil {71 return fmt.Errorf("error restoring console: %w", err)72 }73 }74 return nil75}7677// initCancelReader (re)commences reading inputs.60func (p *Program) initCancelReader() error {78func (p *Program) initCancelReader(cancel bool) error {79 if cancel && p.cancelReader != nil {80 p.cancelReader.Cancel()81 p.waitForReadLoop()82 }8384 var err error62 p.cancelReader, err = cancelreader.NewReader(p.input)85 p.cancelReader, err = newInputReader(p.input, p.mouseMode)86 if err != nil {87 return fmt.Errorf("error creating cancelreader: %w", err)88 }89
5 unmodified lines
9596func (p *Program) readLoop() {97 defer close(p.readLoopDone)9876 input := localereader.NewReader(p.cancelReader)77 err := readInputs(p.ctx, p.msgs, input)99 err := readInputs(p.ctx, p.msgs, p.cancelReader)100 if !errors.Is(err, io.EOF) && !errors.Is(err, cancelreader.ErrCanceled) {101 select {102 case <-p.ctx.Done():103 case p.errs <- err:
4 unmodified lines
108// waitForReadLoop waits for the cancelReader to finish its read loop.109func (p *Program) waitForReadLoop() {110 select {111 case <-p.readLoopDone:90 case <-time.After(500 * time.Millisecond): //nolint:gomnd112 case <-time.After(500 * time.Millisecond): //nolint:mnd113 // The read loop hangs, which means the input114 // cancelReader's cancel function has returned true even115 // though it was not able to cancel the read.116 }
1 unmodified line
118119// checkResize detects the current size of the output and informs the program120// via a WindowSizeMsg.121func (p *Program) checkResize() {100 f, ok := p.output.TTY().(*os.File)101 if !ok || !isatty.IsTerminal(f.Fd()) {122 if p.ttyOutput == nil {123 // can't query window size124 return125 }126106 w, h, err := term.GetSize(int(f.Fd()))127 w, h, err := term.GetSize(p.ttyOutput.Fd())128 if err != nil {129 select {130 case <-p.ctx.Done():131 case p.errs <- err:
10 unmodified lines