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
Provenance
- Commit
0966c3a- Tree
9d21e03- Author
Ayman Bagabas <ayman.bagabas@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
0290af4- Parent 2
21eecd5
80 files changed+4039 added−1269 removed
modified:.github/workflows/build.yml+12 added-34 removed
123456789101112131415161767192089101112132223242526272829303132333435363738394041141516171819name: buildon: [push, pull_request]
jobs: build: strategy: matrix: go-version: [~1.17, ^1] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} env: GO111MODULE: "on" steps: - name: Install Go uses: actions/setup-go@v4 with: go-version: ${{ matrix.go-version }} uses: charmbracelet/meta/.github/workflows/build.yml@main
- name: Checkout code uses: actions/checkout@v4 build-go-mod: uses: charmbracelet/meta/.github/workflows/build.yml@main with: go-version: "" go-version-file: ./go.mod
- name: Download Go modules run: go mod download
- name: Build run: go build -v ./...
- name: Test run: go test ./...
- name: Build examples run: go build -v ./... working-directory: ./examples
- name: Test examples run: go test -v ./... working-directory: ./examples
- name: Build tutorials run: go build -v ./... working-directory: ./tutorials build-examples: uses: charmbracelet/meta/.github/workflows/build.yml@main with: go-version: "" go-version-file: ./examples/go.mod working-directory: ./examplesmodified:.github/workflows/coverage.yml+8 added-7 removed
10 unmodified lines111213141515161718192020212223242326272824252627282910 unmodified lines env: GO111MODULE: "on" steps: - name: Install Go uses: actions/setup-go@v4 uses: actions/setup-go@v6 with: go-version: ${{ matrix.go-version }}
- name: Checkout code uses: actions/checkout@v4 uses: actions/checkout@v5
- name: Coverage env: COVERALLS_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | go test -race -covermode atomic -coverprofile=profile.cov ./... GO111MODULE=off go get github.com/mattn/goveralls $(go env GOPATH)/bin/goveralls -coverprofile=profile.cov -service=github go test -race -covermode=atomic -coverprofile=coverage.txt ./...
- uses: codecov/codecov-action@v5 with: file: ./coverage.txt token: ${{ secrets.CODECOV_TOKEN }}added:.github/workflows/dependabot-sync.yml+17 added
1234567891011121314151617name: dependabot-syncon: schedule: - cron: "0 0 * * 0" # every Sunday at midnight workflow_dispatch: # allows manual triggering
permissions: contents: write pull-requests: write
jobs: dependabot-sync: uses: charmbracelet/meta/.github/workflows/dependabot-sync.yml@main with: repo_name: ${{ github.event.repository.name }} secrets: gh_token: ${{ secrets.PERSONAL_ACCESS_TOKEN }}modified:.github/workflows/examples.yml+3 added-3 removed
18 unmodified lines1920212223242324252627282930313232333435362 unmodified lines18 unmodified lines permissions: contents: write runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v4 - uses: actions/checkout@v5 - uses: actions/setup-go@v6 with: go-version: '^1' cache: true - shell: bash run: | (cd ./examples && go mod tidy) (cd ./tutorials && go mod tidy) - uses: stefanzweifel/git-auto-commit-action@v4 - uses: stefanzweifel/git-auto-commit-action@v6 with: commit_message: "chore: go mod tidy tutorials and examples" branch: master commit_user_name: actions-user2 unmodified linesdeleted:.github/workflows/lint-soft.yml-28 removed
12345678910111213141516171819202122232425262728name: lint-softon: push: pull_request:
permissions: contents: read # Optional: allow read access to pull request. Use with `only-new-issues` option. pull-requests: read
jobs: golangci: name: lint-soft runs-on: ubuntu-latest steps: - name: Install Go uses: actions/setup-go@v4 with: go-version: ^1
- uses: actions/checkout@v4 - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: # Optional: golangci-lint command line arguments. args: --config .golangci-soft.yml --issues-exit-code=0 # Optional: show only new issues if it's a pull request. The default value is `false`. only-new-issues: trueadded:.github/workflows/lint-sync.yml+14 added
1234567891011121314name: lint-syncon: schedule: # every Sunday at midnight - cron: "0 0 * * 0" workflow_dispatch: # allows manual triggering
permissions: contents: write pull-requests: write
jobs: lint: uses: charmbracelet/meta/.github/workflows/lint-sync.yml@mainmodified:.github/workflows/lint.yml+2 added-22 removed
123456789106121314151617181920212223242526272878name: linton: push: pull_request:
permissions: contents: read # Optional: allow read access to pull request. Use with `only-new-issues` option. pull-requests: read
jobs: golangci: name: lint runs-on: ubuntu-latest steps: - name: Install Go uses: actions/setup-go@v4 with: go-version: ^1
- uses: actions/checkout@v4 - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: # Optional: golangci-lint command line arguments. #args: # Optional: show only new issues if it's a pull request. The default value is `false`. only-new-issues: true lint: uses: charmbracelet/meta/.github/workflows/lint.yml@mainadded:.github/workflows/release.yml+29 added
1234567891011121314151617181920212223242526272829name: goreleaser
on: push: tags: - v*.*.*
concurrency: group: goreleaser cancel-in-progress: true
jobs: goreleaser: uses: charmbracelet/meta/.github/workflows/goreleaser.yml@main secrets: docker_username: ${{ secrets.DOCKERHUB_USERNAME }} docker_token: ${{ secrets.DOCKERHUB_TOKEN }} gh_pat: ${{ secrets.PERSONAL_ACCESS_TOKEN }} goreleaser_key: ${{ secrets.GORELEASER_KEY }} twitter_consumer_key: ${{ secrets.TWITTER_CONSUMER_KEY }} twitter_consumer_secret: ${{ secrets.TWITTER_CONSUMER_SECRET }} twitter_access_token: ${{ secrets.TWITTER_ACCESS_TOKEN }} twitter_access_token_secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} mastodon_client_id: ${{ secrets.MASTODON_CLIENT_ID }} mastodon_client_secret: ${{ secrets.MASTODON_CLIENT_SECRET }} mastodon_access_token: ${{ secrets.MASTODON_ACCESS_TOKEN }} discord_webhook_id: ${{ secrets.DISCORD_WEBHOOK_ID }} discord_webhook_token: ${{ secrets.DISCORD_WEBHOOK_TOKEN }}# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.jsonadded:.github/CODEOWNERS+1 added
1+* @meowgorithm @aymanbagabasmodified:.github/dependabot.yml+59 added-10 removed
1 version: 22+3 updates: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+ - "*"20+12- - 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+ - "*"37+38+ - 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+ - "*"54+55 - 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+ - "*"71+30- - 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 lines4 "fmt"5 "os"6 7 tea "github.com/charmbracelet/bubbletea"8- "github.com/muesli/termenv"8+ "github.com/charmbracelet/lipgloss"9 )10 11 var (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 )15 16 type model struct {18- altscreen bool19- quitting bool17+ altscreen bool18+ quitting bool19+ suspending bool20 }21 22 func (m model) Init() tea.Cmd {23 return nil24 }25 26 func (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.ExitAltScreen7 unmodified lines50 return m, nil51 }52 53 func (m model) View() string {54+ if m.suspending {55+ return ""56+ }57+58 if m.quitting {59 return "Bye!\n"60 }61 8 unmodified lines70 } else {71 mode = inlineMode72 }73 64- 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 }77 78 func main() {79 if _, err := tea.NewProgram(model{}).Run(); err != nil {4 unmodified linesmodified:examples/autocomplete/main.go+28 added-4 removed
5 unmodified lines6 "io"7 "log"8 "net/http"9 10+ "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 lines61 }62 63 type model struct {64 textInput textinput.Model65+ help help.Model66+ keymap keymap67 }68 69+type keymap struct{}70+71+func (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+}79+func (k keymap) FullHelp() [][]key.Binding {80+ return [][]key.Binding{k.ShortHelp()}81+}82+83 func 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 = true93+94+ h := help.New()95+96+ km := keymap{}97+74- return model{textInput: ti}98+ return model{textInput: ti, help: h, keymap: km}99 }100 101 func (m model) Init() tea.Cmd {102 return tea.Batch(getRepos, textinput.Blink)20 unmodified lines123 }124 125 func (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 lines13 tea "github.com/charmbracelet/bubbletea"14 "github.com/charmbracelet/lipgloss"15 )16 17+const gap = "\n\n"18+19 func main() {20 p := tea.NewProgram(initialModel())21 22 if _, err := p.Run(); err != nil {57 unmodified lines80 m.textarea, tiCmd = m.textarea.Update(msg)81 m.viewport, vpCmd = m.viewport.Update(msg)82 83 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)88+89+ 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 lines113 }114 115 func (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 lines87 88 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
1+package main2+3+// A simple program that handled losing and acquiring focus.4+5+import (6+ "log"7+8+ tea "github.com/charmbracelet/bubbletea"9+)10+11+func 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+}21+22+type model struct {23+ focused bool24+ reporting bool25+}26+27+func (m model) Init() tea.Cmd {28+ return nil29+}30+31+func (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+ }45+46+ return m, nil47+}48+49+func (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"57+58+ 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 lines22 }23 }24 25 func (m model) Init() tea.Cmd {26- return tea.Batch(tick(), tea.EnterAltScreen)26+ return tick()27 }28 29 func (m model) Update(message tea.Msg) (tea.Model, tea.Cmd) {30 switch msg := message.(type) {26 unmodified linesmodified:examples/glamour/main.go+12 added-1 removed
63 unmodified lines64 BorderStyle(lipgloss.RoundedBorder()).65 BorderForeground(lipgloss.Color("62")).66 PaddingRight(2)67 68+ // 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() - glamourGutter78+79 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 linesmodified:examples/list-fancy/main.go+2 added-2 removed
116 unmodified lines117 }118 }119 120 func (m model) Init() tea.Cmd {121- return tea.EnterAltScreen121+ return nil122 }123 124 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {125 var cmds []tea.Cmd56 unmodified lines182 183 func main() {184 rand.Seed(time.Now().UTC().UnixNano())185 186- 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 lines66 return m, nil67 68 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.Quit73 74 case "enter":54 unmodified linesmodified:examples/mouse/main.go+3 added-11 removed
2 unmodified lines3 // A simple program that opens the alternate screen buffer and displays mouse4 // coordinates and events.5 6 import (7- "fmt"7 "log"8 9 tea "github.com/charmbracelet/bubbletea"10 )11 12 func 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 }18 19 type model struct {21- init bool20 mouseEvent tea.MouseEvent21 }22 23 func (m model) Init() tea.Cmd {7 unmodified lines31 return m, tea.Quit32 }33 34 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 }37 38 return m, nil39 }40 41 func (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"43 47- if m.init {48- e := m.mouseEvent49- s += fmt.Sprintf("(X: %d, Y: %d) %s", e.X, e.Y, e)50- }51-44 return s45 }modified:examples/package-manager/main.go+10 added-6 removed
56 unmodified lines57 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 }70 71 // Update progress bar68- progressCmd := m.progress.SetPercent(float64(m.index) / float64(len(m.packages)-1))69-72 m.index++73+ progressCmd := m.progress.SetPercent(float64(m.index) / float64(len(m.packages)))74+75 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 lines98 if m.done {99 return doneStyle.Render(fmt.Sprintf("Done! Installed %d packages.\n", n))100 }101 98- pkgCount := fmt.Sprintf(" %*d/%*d", w, m.index, w, n-1)102+ pkgCount := fmt.Sprintf(" %*d/%*d", w, m.index, w, n)103 104 spin := m.spinner.View() + " "105 prog := m.progress.View()106 cellsAvail := max(0, m.width-lipgloss.Width(spin+prog+pkgCount))34 unmodified linesmodified:examples/pager/main.go+1 added-24 removed
11 unmodified lines12 tea "github.com/charmbracelet/bubbletea"13 "github.com/charmbracelet/lipgloss"14 )15 16-// 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().22-const useHighPerformanceRenderer = false23-16 var (17 titleStyle = func() lipgloss.Style {18 b := lipgloss.RoundedBorder()19 b.Right = "├"2 unmodified lines22 23 infoStyle = func() lipgloss.Style {24 b := lipgloss.RoundedBorder()25 b.Left = "┤"34- return titleStyle.Copy().BorderStyle(b)26+ return titleStyle.BorderStyle(b)27 }()28 )29 30 type model struct {30 unmodified lines61 // 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 = true76-77- // 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 }86-87- 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 }72 73 // Handle keyboard and mouse events in the viewport74 m.viewport, cmd = m.viewport.Update(msg)50 unmodified linesmodified:examples/send-msg/main.go+2 added-2 removed
16 unmodified lines17 18 var (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 )25 26 type resultMsg struct {105 unmodified linesadded:examples/set-window-title/main.go+35 added
1+package main2+3+// A simple example illustrating how to set a window title.4+5+import (6+ "fmt"7+ "os"8+9+ tea "github.com/charmbracelet/bubbletea"10+)11+12+type model struct{}13+14+func (m model) Init() tea.Cmd {15+ return tea.SetWindowTitle("Bubble Tea Example")16+}17+18+func (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+}25+26+func (m model) View() string {27+ return "\nPress any key to quit."28+}29+30+func 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 key2-[70D[1A[70D[2KHi. This program will exit in 9 seconds. To quit sooner press any key.3-[70D[2K[?25h[?1002l[?1003l1+[?25l[?2004h
Hi. This program will exit in 10 seconds.[K2+[K3+To quit sooner press ctrl-c, or press ctrl-z to suspend...[K4+[K
[3AHi. This program will exit in 9 seconds.[K5+6+7+
[2K
[?2004l[?25h[?1002l[?1003l[?1006lmodified:examples/simple/main_test.go-6 removed
6 unmodified lines7 "testing"8 "time"9 10 tea "github.com/charmbracelet/bubbletea"11- "github.com/charmbracelet/lipgloss"11 "github.com/charmbracelet/x/exp/teatest"13- "github.com/muesli/termenv"12 )13 16-func init() {17- lipgloss.SetColorProfile(termenv.Ascii)18-}19-14 func TestApp(t *testing.T) {15 m := model(10)16 tm := teatest.NewTestModel(17 t, m,69 unmodified linesmodified:examples/simple/main.go+9 added-3 removed
41 unmodified lines42 // 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.45 func (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+ }54+55 case tickMsg:56 m--57 if m <= 0 {58 return m, tea.Quit5 unmodified lines64 65 // View returns a string based on data in the model. That string which will be66 // rendered to the terminal.67 func (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 }70 71 // Messages are events that we respond to in our Update function. This72 // particular one indicates that the timer has ticked.6 unmodified linesadded:examples/suspend/main.go+57 added
1+package main2+3+import (4+ "errors"5+ "fmt"6+ "os"7+8+ tea "github.com/charmbracelet/bubbletea"9+)10+11+type model struct {12+ quitting bool13+ suspending bool14+}15+16+func (m model) Init() tea.Cmd {17+ return nil18+}19+20+func (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+}40+41+func (m model) View() string {42+ if m.suspending || m.quitting {43+ return ""44+ }45+46+ return "\nPress ctrl-z to suspend, ctrl+c to interrupt, q, or esc to exit\n"47+}48+49+func 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
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ tea "github.com/charmbracelet/bubbletea"8+ "github.com/charmbracelet/lipgloss"9+ "github.com/charmbracelet/lipgloss/table"10+)11+12+type model struct {13+ table *table.Table14+}15+16+func (m model) Init() tea.Cmd { return nil }17+18+func (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+}33+34+func (m model) View() string {35+ return "\n" + m.table.String() + "\n"36+}37+38+func 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+ }96+97+ 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+ }106+107+ rowIndex := row - 1108+ if rowIndex < 0 || rowIndex >= len(rows) {109+ return baseStyle110+ }111+112+ if rows[rowIndex][1] == "Pikachu" {113+ return selectedStyle114+ }115+116+ even := row%2 == 0117+118+ switch col {119+ case 2, 3: // Type 1 + 2120+ c := typeColors121+ if even {122+ c = dimTypeColors123+ }124+125+ if col >= len(rows[rowIndex]) {126+ return baseStyle127+ }128+129+ color, ok := c[rows[rowIndex][col]]130+ if !ok {131+ return baseStyle132+ }133+ return baseStyle.Foreground(color)134+ }135+136+ if even {137+ return baseStyle.Foreground(lipgloss.Color("245"))138+ }139+ return baseStyle.Foreground(lipgloss.Color("252"))140+ }).141+ Border(lipgloss.ThickBorder())142+143+ 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 lines50 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 )57 58 func (m model) View() string {4 unmodified lines63 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 linesmodified:examples/textinputs/main.go+3 added-3 removed
15 unmodified lines16 17 var (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"))24 25- focusedButton = focusedStyle.Copy().Render("[ Submit ]")25+ focusedButton = focusedStyle.Render("[ Submit ]")26 blurredButton = fmt.Sprintf("[ %s ]", blurredStyle.Render("Submit"))27 )28 29 type model struct {149 unmodified linesmodified:examples/tui-daemon-combo/main.go+5 added-3 removed
11 unmodified lines12 "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 )17 18+var (19-var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Render19+ helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241")).Render20+ mainStyle = lipgloss.NewStyle().MarginLeft(1)21+)22 23 func main() {24 var (25 daemonMode bool93 unmodified lines119 if m.quitting {120 s += "\n"121 }122 121- return indent.String(s, 1)123+ return mainStyle.Render(s)124 }125 126 // processFinishedMsg is sent when a pretend process completes.127 type processFinishedMsg time.Duration12 unmodified linesmodified:examples/views/main.go+25 added-31 removed
12 unmodified lines13 "strings"14 "time"15 16 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 )21 22 const (23 progressBarWidth = 7124 progressFullChar = "█"25 progressEmptyChar = "░"26+ dotChar = " • "27 )28 29 // General stuff for styling the view30 var (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)38 39 // Gradient colors we'll use for the progress bar38- ramp = makeRamp("#B14FFF", "#00FFA3", progressBarWidth)40+ ramp = makeRampStyles("#B14FFF", "#00FFA3", progressBarWidth)41 )42 43 func main() {44 initialModel := model{0, false, 10, 0, 0, false, false}63 unmodified lines108 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 }114 115 // Sub-update functions116 67 unmodified lines184 185 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")191 192 choices := fmt.Sprintf(193 "%s\n%s\n%s\n%s",194 checkbox("Plant carrots", c == 0),1 unmodified line196 checkbox("Read something", c == 2),197 checkbox("See friends", c == 3),198 )199 196- return fmt.Sprintf(tpl, choices, colorFg(strconv.Itoa(m.Ticks), "79"))200+ return fmt.Sprintf(tpl, choices, ticksStyle.Render(strconv.Itoa(m.Ticks)))201 }202 203 // The second view, after a task has been chosen204 func chosenView(m model) string {205 var msg string206 207 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 }217 218 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 }222 223 return msg + "\n\n" + label + "\n" + progressbar(m.Progress) + "%"224 }225 226 func 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 lines235 236 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 }241 242 emptySize := int(w) - fullSize243 emptyCells := strings.Repeat(progressEmpty, emptySize)2 unmodified lines246 }247 248 // Utils249 246-// Color a string's foreground with the given value.247-func colorFg(val, color string) string {248- return termenv.String(val).Foreground(term.Color(color)).String()249-}250-251-// Return a function that will colorize the foreground of a given string.252-func makeFgStyle(color string) func(string) string {253- return termenv.Style{}.Foreground(term.Color(color)).Styled254-}255-250 // Generate a blend of colors.257-func makeRamp(colorA, colorB string, steps float64) (s []string) {251+func makeRampStyles(colorA, colorB string, steps float64) (s []lipgloss.Style) {252 cA, _ := colorful.Hex(colorA)253 cB, _ := colorful.Hex(colorB)254 255 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 }261 268-// Convert a colorful.Color to a hexadecimal format compatible with termenv.262+// Convert a colorful.Color to a hexadecimal format.263 func 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 linesadded:examples/window-size/main.go+44 added
1+package main2+3+// A simple program that queries and displays the window-size.4+5+import (6+ "log"7+8+ tea "github.com/charmbracelet/bubbletea"9+)10+11+func main() {12+ p := tea.NewProgram(model{})13+ if _, err := p.Run(); err != nil {14+ log.Fatal(err)15+ }16+}17+18+type model struct{}19+20+func (m model) Init() tea.Cmd {21+ return nil22+}23+24+func (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+ }30+31+ return m, tea.WindowSize()32+33+ case tea.WindowSizeMsg:34+ return m, tea.Printf("%dx%d", msg.Width, msg.Height)35+ }36+37+ return m, nil38+}39+40+func (m model) View() string {41+ s := "When you're done press q to quit. Press any other key to query the window-size.\n"42+43+ return s44+}modified:examples/go.mod+34 added-27 removed
1 module examples2 3-go 1.173+go 1.24.04 5+toolchain go1.24.56+7 require (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 )18 19 require (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 )52 53 replace github.com/charmbracelet/bubbletea => ../modified:examples/go.sum+70 added-113 removed
1-github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek=2-github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s=1+github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=2+github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=3+github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE=4+github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=5+github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E=6+github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I=7+github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=8+github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=9 github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=10 github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=5-github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4=6-github.com/aymanbagabas/go-osc52 v1.2.1 h1:q2sWUyDcozPLcLabEMd+a+7Ea2DitxZVN9hTxab9L4E=7-github.com/aymanbagabas/go-osc52 v1.2.1/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4=11 github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=12 github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=10-github.com/aymanbagabas/go-udiff v0.1.0 h1:9Dpklm2oBBhMxIFbMffmPvDaF7vOYfv9B5HXVr42KMU=11-github.com/aymanbagabas/go-udiff v0.1.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=13+github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=14+github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=15 github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=16 github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=14-github.com/charmbracelet/bubbles v0.16.2-0.20230821152602-eda891258c02 h1:MruS04uPbUJHF0MQzwOlh9yco1pHwPDLI7qGMu25IME=15-github.com/charmbracelet/bubbles v0.16.2-0.20230821152602-eda891258c02/go.mod h1:XUdibuVUiMfcfKTRla58bmY3TWsdjgF+Rp8pvimQLck=16-github.com/charmbracelet/glamour v0.6.0 h1:wi8fse3Y7nfcabbbDuwolqTqMQPMnVPeZhDM273bISc=17-github.com/charmbracelet/glamour v0.6.0/go.mod h1:taqWV4swIMMbWALc0m7AfE9JkPSU8om2538k9ITBxOc=17+github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=18+github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=19+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=20+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=21+github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY=22+github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk=23 github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=24 github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=20-github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNWpFujkNawKNhE2c=21-github.com/charmbracelet/lipgloss v0.9.1 h1:PNyd3jvaJbg4jRHKWXnCj1akQm4rh8dbEzN1p/u1KWg=22-github.com/charmbracelet/lipgloss v0.9.1/go.mod h1:1mPmG4cxScwUQALAAnacHaigiiHB9Pmr+v1VEawJl6I=23-github.com/charmbracelet/x/exp/teatest v0.0.0-20230508155401-2bd6fa14c46a h1:GpNt24LKE8sH5G0SZUpu4Tg15sP5XSt1mnfIqE7fW34=24-github.com/charmbracelet/x/exp/teatest v0.0.0-20230508155401-2bd6fa14c46a/go.mod h1:dpMo6PfGlhavn+ofggWhfFQmK9sZB2Ewljiz9bZtKVI=25-github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=26-github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=27-github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=28-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=29-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=30-github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E=31-github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=25+github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE=26+github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA=27+github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=28+github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=29+github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ/IA3iR28k=30+github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=31+github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=32+github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=33+github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI=34+github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU=35+github.com/charmbracelet/x/exp/teatest v0.0.0-20240521184646-23081fb03b28 h1:sOWKNRjt8uOEVgPiJVIJCse1+mUDM2F/vYY6W0Go640=36+github.com/charmbracelet/x/exp/teatest v0.0.0-20240521184646-23081fb03b28/go.mod h1:l1w+LTJZCCozeGzMEWGxRw6Mo2DfcZUvupz8HGubdes=37+github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=38+github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=39+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=40+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=41 github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=42 github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=43+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=44+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=45 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776 h1:VRIbnDWRmAh5yBdz+J6yFMF5vso1It6vn+WmM/5l7MA=46 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776/go.mod h1:9wvnDu3YOfxzWM9Cst40msBF1C2UdQgDv962oTxSuMs=36-github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=37-github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=47+github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=48+github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=49+github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=50+github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=51 github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=52 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=53 github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=54 github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=42-github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=43-github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=44-github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=45-github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=55+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=56+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=57 github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=58 github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=48-github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=59 github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=50-github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=51-github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=52-github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=53-github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=54-github.com/microcosm-cc/bluemonday v1.0.21 h1:dNH3e4PSyE4vNX+KlRGHT5KrSvjeUkoNPwEORjffHJg=55-github.com/microcosm-cc/bluemonday v1.0.21/go.mod h1:ytNkv4RrDrLJ2pqlsSI46O6IVXmZOBBD4SaJyDwwTkM=56-github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=57-github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=60+github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=61+github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=62+github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=63+github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=64+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=65+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=66 github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=67 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=68 github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=69 github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=62-github.com/muesli/termenv v0.13.0/go.mod h1:sP1+uffeLaEYpyOTb8pLCUctGcGLnoFjSn4YJK5e2bc=63-github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ=64-github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=65-github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=66-github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=67-github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=68-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=69-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=70+github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=71+github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=72 github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=71-github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=73 github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=73-github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f h1:MvTmaQdww/z0Q4wrYjDSCcZ78NoftLQyHBSLW/Cx79Y=74-github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=75-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=76-github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=77-github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=78-github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=79-github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=80-github.com/yuin/goldmark v1.5.2 h1:ALmeCk/px5FSm1MAcFBAsVKZjDuMVj8Tm7FFIlMJnqU=81-github.com/yuin/goldmark v1.5.2/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=82-github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os=83-github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ=84-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=85-golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=86-golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=87-golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=88-golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=89-golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=90-golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=91-golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=92-golang.org/x/net v0.0.0-20221002022538-bcab6841153b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=93-golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=94-golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=95-golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=96-golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=97-golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=98-golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=99-golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=100-golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=101-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=102-golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=103-golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=104-golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=105-golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=106-golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=107-golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=108-golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=109-golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=110-golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=74+github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=75+github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=76+github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA=77+github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=78+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=79+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=80+github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=81+github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=82+github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=83+github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk=84+github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=85+golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=86+golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=87+golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=88+golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=89+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=90 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=112-golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=113-golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=114-golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=115-golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=116-golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=117-golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=118-golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=119-golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=120-golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=121-golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=122-golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek=123-golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=124-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=125-golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=126-golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=127-golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=128-golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=129-golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=130-golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=131-golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=132-golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=133-golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=134-golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=135-golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=136-golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=137-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=138-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=139-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=91+golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=92+golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=93+golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=94+golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=95+golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=96+golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=modified:examples/README.md+1 added-1 removed
28 unmodified lines29 30 ### Credit Card Form31 32 The `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.34 35 <a href="./credit-card-form/main.go">36 <img width="750" src="./credit-card-form/credit-card-form.gif" />37 </a>291 unmodified linesmodified:tutorials/basics/main.go+1 added-1 removed
23 unmodified lines24 }25 }26 27 func (m model) Init() tea.Cmd {28- return nil28+ return tea.SetWindowTitle("Grocery List")29 }30 31 func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {32 switch msg := msg.(type) {54 unmodified linesmodified:tutorials/commands/README.md+1 added-1 removed
163 unmodified lines164 ## Run the program165 166 The only thing left to do is run the program, so let's do that! Our initial167 model doesn't need any data at all in this case, we just initialize it with168-as a `struct` with defaults.168+a `model` struct with default values.169 170 ```go171 func main() {172 if _, err := tea.NewProgram(model{}).Run(); err != nil {75 unmodified linesmodified:tutorials/go.mod+13 added-12 removed
1 module tutorial2 3-go 1.173+go 1.184 5-require github.com/charmbracelet/bubbletea v0.23.25+require github.com/charmbracelet/bubbletea v0.25.06 7 require (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 )25 26 replace github.com/charmbracelet/bubbletea => ../modified:tutorials/go.sum+23 added-47 removed
1 github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=2 github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=3-github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=4-github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=3+github.com/charmbracelet/lipgloss v0.13.1 h1:Oik/oqDTMVA01GetT4JdEC033dNzWoQHdWnHnQmXE2A=4+github.com/charmbracelet/lipgloss v0.13.1/go.mod h1:zaYVJ2xKSKEnTEEbX6uAHabh2d975RJ+0yfkFpRBz5U=5+github.com/charmbracelet/x/ansi v0.4.0 h1:NqwHA4B23VwsDn4H3VcNX1W1tOmgnvY1NDx5tOXdnOU=6+github.com/charmbracelet/x/ansi v0.4.0/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=7+github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0=8+github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=9+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=10+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=11 github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=12 github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=7-github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=8-github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=13+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=14+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=15 github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=16 github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=11-github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=12-github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=13-github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=14-github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=15-github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=16-github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=17+github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=18+github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=19+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=20+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=21 github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=22 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=19-github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=20-github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=23 github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=24 github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=23-github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=24-github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=25 github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=26-github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=27-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=28-golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=29-golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=30-golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=31-golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=32-golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=33-golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=34-golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=35-golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=36-golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=37-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=38-golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=39-golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=40-golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=41-golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=42-golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=43-golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=26+github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=27+github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=28+golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=29+golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=30+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=31 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=45-golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=46-golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=47-golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=48-golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=49-golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=50-golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=51-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=52-golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=53-golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=54-golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=55-golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=56-golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=57-golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=58-golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=59-golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=32+golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=33+golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=34+golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=35+golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=modified:.gitignore+1 added
18 unmodified lines19 tutorials/basics/basics20 tutorials/commands/commands21 .idea22 coverage.txt23+dist/deleted:.golangci-soft.yml-47 removed
1-run:2- tests: false3-4-issues:5- include:6- - EXC00017- - EXC00058- - EXC00119- - EXC001210- - EXC001311-12- max-issues-per-linter: 013- max-same-issues: 014-15-linters:16- enable:17- # - dupl18- - exhaustive19- # - exhaustivestruct20- - goconst21- - godot22- - godox23- - gomnd24- - gomoddirectives25- - goprintffuncname26- - ifshort27- # - lll28- - misspell29- - nakedret30- - nestif31- - noctx32- - nolintlint33- - prealloc34- - wrapcheck35-36- # disable default linters, they are already enabled in .golangci.yml37- disable:38- - deadcode39- - errcheck40- - gosimple41- - govet42- - ineffassign43- - staticcheck44- - structcheck45- - typecheck46- - unused47- - varcheckmodified:.golangci.yml+30 added-15 removed
1+version: "2"2 run:3 tests: false3-4-issues:5- include:6- - EXC00017- - EXC00058- - EXC00119- - EXC001210- - EXC001311-12- max-issues-per-linter: 013- max-same-issues: 014-4 linters: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-positives36+issues:37+ max-issues-per-linter: 038+ max-same-issues: 039+formatters:40+ enable:41+ - gofumpt42+ - goimports43+ exclusions:44+ generated: laxadded:.goreleaser.yml+5 added
1+# yaml-language-server: $schema=https://goreleaser.com/static/schema-pro.json2+version: 23+includes:4+ - from_url:5+ url: charmbracelet/meta/main/goreleaser-lib.yamlmodified:commands_test.go+15 added-7 removed
80 unmodified lines81 }82 }83 84 func TestBatch(t *testing.T) {85+ testMultipleCommands[BatchMsg](t, Batch)86+}87+88+func TestSequence(t *testing.T) {89+ testMultipleCommands[sequenceMsg](t, Sequence)90+}91+92+func 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 lines12 // func (m model) Init() Cmd {13 // return tea.Batch(someCommand, someOtherCommand)14 // }15 func 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 }18 19 // 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 line22 23 // Sequence runs the given commands one at a time, in order. Contrast this with24 // Batch, which runs commands concurrently.25 func Sequence(cmds ...Cmd) Cmd {38- return func() Msg {39- return sequenceMsg(cmds)40- }26+ return compactCmds[sequenceMsg](cmds)27 }28 29 // sequenceMsg is used internally to run the given commands in order.30 type sequenceMsg []Cmd31 32+// 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.36+func 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+}55+56 // 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 lines99 // }100 //101 // Every is analogous to Tick in the Elm Architecture.102 func 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 }115 116 // Tick produces a command at an interval independent of the system clock at34 unmodified lines151 // }152 // return m, nil153 // }154 func 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 }165 166 // Sequentially produces a command that sequentially executes the given22 unmodified lines189 }190 return nil191 }192 }193+194+// setWindowTitleMsg is an internal message used to set the window title.195+type setWindowTitleMsg string196+197+// 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+// }205+func SetWindowTitle(title string) Cmd {206+ return func() Msg {207+ return setWindowTitleMsg(title)208+ }209+}210+211+type windowSizeMsg struct{}212+213+// 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.218+func WindowSize() Cmd {219+ return func() Msg {220+ return windowSizeMsg{}221+ }222+}deleted:CONTRIBUTING.md-13 removed
1-# Contributing2-3-Pull requests are welcome for any changes.4-5-Consider opening an issue for larger changes to get feedback on the idea from the team.6-7-If your change touches parts of the Bubble Tea renderer or internals, make sure8-that all the examples in the `examples/` folder continue to run correctly.9-10-For commit messages, please use conventional commits[^1] to make it easier to11-generate release notes.12-13-[^1]: https://www.conventionalcommits.org/en/v1.0.0modified:exec_test.go+34 added-12 removed
1 unmodified line2 3 import (4 "bytes"5 "os/exec"6+ "runtime"7 "testing"8 )9 10 type execFinishedMsg struct{ err error }25 unmodified lines36 func (m *testExecModel) View() string {37 return "\n"38 }39 40+type spyRenderer struct {41+ renderer42+ calledReset bool43+}44+45+func (r *spyRenderer) resetLinesRendered() {46+ r.calledReset = true47+ r.renderer.resetLinesRendered()48+}49+50 func 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 }63 64+ 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+ }78+79 for _, test := range tests {80 t.Run(test.name, func(t *testing.T) {81 var buf bytes.Buffer82 var in bytes.Buffer2 unmodified lines85 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}90 91 if m.err != nil && !test.expectErr {92 t.Errorf("expected no error, got %v", m.err)93+94+ 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 linesmodified:exec.go+5 added-1 removed
107 unmodified lines108 return109 }110 111 c.SetStdin(p.input)112- c.SetStdout(p.output.TTY())112+ c.SetStdout(p.output)113 c.SetStderr(os.Stderr)114 115 // 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 }124 125+ // Maintain the existing output from the command126+ p.renderer.resetLinesRendered()127+128 // Have the program re-capture input.129 err := p.RestoreTerminal()130 if fn != nil {131 go p.Send(fn(err))2 unmodified linesadded:focus.go+9 added
1+package tea2+3+// FocusMsg represents a terminal focus message.4+// This occurs when the terminal gains focus.5+type FocusMsg struct{}6+7+// BlurMsg represents a terminal blur message.8+// This occurs when the terminal loses focus.9+type BlurMsg struct{}modified:go.mod+14 added-11 removed
1 module github.com/charmbracelet/bubbletea2 3-go 1.173+go 1.24.04 5 require (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 )15 16 require (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
1 github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=2 github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=3-github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=4-github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=3+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=4+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=5+github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=6+github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=7+github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=8+github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=9+github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=10+github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=11+github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=12+github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=13+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=14+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=15 github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=16 github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=7-github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=8-github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=17+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=18+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=19 github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=20 github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=11-github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=12-github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=13-github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=14-github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=15-github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=16-github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=21+github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=22+github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=23+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=24+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=25 github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=26 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=19-github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=20-github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=21-github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=22-github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=23-github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=24-github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=27+github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=28+github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=29 github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=26-github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=27-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=28-golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=29-golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=30-golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=31-golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=32-golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=33-golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=34-golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=35-golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=36-golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=37-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=38-golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=39-golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=40-golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=41-golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=42-golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=43-golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=30+github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=31+github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=32+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=33+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=34+golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=35+golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=36+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=37 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=45-golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=46-golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=47-golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=48-golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=49-golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=50-golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=51-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=52-golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=53-golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=38+golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=39+golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=40 golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=41 golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=56-golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=57-golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=58-golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=59-golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=added:inputreader_other.go+19 added
1+//go:build !windows2+// +build !windows3+4+package tea5+6+import (7+ "fmt"8+ "io"9+10+ "github.com/muesli/cancelreader"11+)12+13+func 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 windows3+4+package tea5+6+import (7+ "fmt"8+ "io"9+ "os"10+ "sync"11+12+ "github.com/charmbracelet/x/term"13+ "github.com/erikgeiser/coninput"14+ "github.com/muesli/cancelreader"15+ "golang.org/x/sys/windows"16+)17+18+type conInputReader struct {19+ cancelMixin20+21+ conin windows.Handle22+23+ originalMode uint3224+}25+26+var _ cancelreader.CancelReader = &conInputReader{}27+28+func 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+ }35+36+ conin, err := coninput.NewStdinHandle()37+ if err != nil {38+ return fallback(r)39+ }40+41+ modes := []uint32{42+ windows.ENABLE_WINDOW_INPUT,43+ windows.ENABLE_EXTENDED_FLAGS,44+ }45+46+ // 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+ }54+55+ originalMode, err := prepareConsole(conin, modes...)56+ if err != nil {57+ return nil, fmt.Errorf("failed to prepare console input: %w", err)58+ }59+60+ return &conInputReader{61+ conin: conin,62+ originalMode: originalMode,63+ }, nil64+}65+66+// Cancel implements cancelreader.CancelReader.67+func (r *conInputReader) Cancel() bool {68+ r.setCanceled()69+70+ // 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+}74+75+// Close implements cancelreader.CancelReader.76+func (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+ }83+84+ return nil85+}86+87+// Read implements cancelreader.CancelReader.88+func (r *conInputReader) Read(_ []byte) (n int, err error) {89+ if r.isCanceled() {90+ err = cancelreader.ErrCanceled91+ }92+ return93+}94+95+func 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+ }100+101+ newMode := coninput.AddInputModes(0, modes...)102+103+ err = windows.SetConsoleMode(input, newMode)104+ if err != nil {105+ return 0, fmt.Errorf("set console mode: %w", err)106+ }107+108+ return originalMode, nil109+}110+111+// cancelMixin represents a goroutine-safe cancellation status.112+type cancelMixin struct {113+ unsafeCanceled bool114+ lock sync.Mutex115+}116+117+func (c *cancelMixin) setCanceled() {118+ c.lock.Lock()119+ defer c.lock.Unlock()120+121+ c.unsafeCanceled = true122+}123+124+func (c *cancelMixin) isCanceled() bool {125+ c.lock.Lock()126+ defer c.lock.Unlock()127+128+ return c.unsafeCanceled129+}added:key_other.go+13 added
1+//go:build !windows2+// +build !windows3+4+package tea5+6+import (7+ "context"8+ "io"9+)10+11+func 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
1 package tea2 3-import "sort"3+import (4+ "bytes"5+ "sort"6+ "unicode/utf8"7+)8 9 // 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 lines72 }73 74 return false, 0, nil75 }76+77+// 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.83+func 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+ }89+90+ // Skip over the start sequence.91+ input = input[len(bpStart):]92+93+ // 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+ }104+105+ // The paste is everything in-between.106+ paste := input[:idx]107+108+ // 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+ }117+118+ return true, inputLen, KeyMsg(k)119+}120+121+// detectReportFocus detects a focus report sequence.122+func 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 lines133 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 lines250 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 line315 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 lines568 // 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 }()575 576 var msgs []Msg139 unmodified lines716 })717 }718 }719 666-// TestDetectRandomSequencesLex checks that the map-based sequence720+// TestDetectRandomSequencesMap checks that the map-based sequence721 // detector works over concatenations of random sequences.722 func TestDetectRandomSequencesMap(t *testing.T) {723 runTestDetectSequence(t, detectSequence)724 }11 unmodified linesadded:key_windows.go+441 added
1+//go:build windows2+// +build windows3+4+package tea5+6+import (7+ "context"8+ "fmt"9+ "io"10+ "time"11+12+ "github.com/erikgeiser/coninput"13+ localereader "github.com/mattn/go-localereader"14+ "github.com/muesli/cancelreader"15+)16+17+func 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+ }21+22+ return readAnsiInputs(ctx, msgs, localereader.NewReader(input))23+}24+25+func 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+ }40+41+ for i := 0; i < int(e.RepeatCount); i++ {42+ eventKeyType := keyType(e)43+ var runes []rune44+45+ // 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+ }51+52+ 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+ }77+78+ // 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+}93+94+// 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.97+func 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+}111+112+// Convert i to unit32 or panic if it cannot be converted. Check satisfies lint G115.113+func 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+}119+120+// Keeps peeking until there is data or the input is cancelled.121+func 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+}137+138+func mouseEventButton(p, s coninput.ButtonState) (button MouseButton, action MouseAction) {139+ btn := p ^ s140+ action = MouseActionPress141+ if btn&s == 0 {142+ action = MouseActionRelease143+ }144+145+ 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+ }160+161+ 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+ }173+174+ return button, action175+}176+177+func 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+ }224+225+ return ev226+}227+228+func keyType(e coninput.KeyEventRecord) KeyType {229+ code := e.VirtualKeyCode230+231+ shiftPressed := e.ControlKeyState.Contains(coninput.SHIFT_PRESSED)232+ ctrlPressed := e.ControlKeyState.Contains(coninput.LEFT_CTRL_PRESSED | coninput.RIGHT_CTRL_PRESSED)233+234+ 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+ }368+369+ 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+ }431+432+ switch code { //nolint:exhaustive433+ case coninput.VK_OEM_4:434+ return KeyCtrlOpenBracket435+ case coninput.VK_OEM_6:436+ return KeyCtrlCloseBracket437+ }438+439+ return KeyRunes440+ }441+}modified:key.go+54 added-12 removed
3 unmodified lines4 "context"5 "fmt"6 "io"7 "regexp"8+ "strings"9 "unicode/utf8"10 )11 12 // KeyMsg contains information about a keypress. KeyMsgs are always sent to41 unmodified lines54 type Key struct {55 Type KeyType56 Runes []rune57 Alt bool58+ Paste bool59 }60 61 // String returns a friendly string representation for a key. It's safe (and62 // encouraged) for use in key comparison.1 unmodified line64 // k := Key{Type: KeyEnter}65 // fmt.Println(k)66 // // Output: enter67 func (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 lines552 }553 554 var spaceRunes = []rune{' '}555 541-// 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.543-func readInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {558+func readAnsiInputs(ctx context.Context, msgs chan<- Msg, input io.Reader) error {559 var buf [256]byte560 561 var leftOverFromPrevIteration []byte562 loop:42 unmodified lines605 leftOverFromPrevIteration = nil606 }607 }608 609+var (594-var 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+)613 614 func 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 }630 631+ // Detect focus events.632+ var foundRF bool633+ foundRF, w, msg = detectReportFocus(b)634+ if foundRF {635+ return w, msg636+ }637+638+ // Detect bracketed paste.639+ var foundbp bool640+ foundbp, w, msg = detectBracketedPaste(b)641+ if foundbp {642+ return w, msg643+ }644+645 // 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 }653 654 // 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 linesmodified:LICENSE+1 added-1 removed
1 MIT License2 3-Copyright (c) 2020-2023 Charmbracelet, Inc3+Copyright (c) 2020-2025 Charmbracelet, Inc4 5 Permission is hereby granted, free of charge, to any person obtaining a copy6 of this software and associated documentation files (the "Software"), to deal7 in the Software without restriction, including without limitation the rights14 unmodified linesmodified:logging.go+1 added-1 removed
31 unmodified lines32 }33 34 // LogToFileWith does allows to call LogToFile with a custom LogOptionsSetter.35 func 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 linesmodified:mouse_test.go+717 added-124 removed
1 package tea2 3-import "testing"3+import (4+ "fmt"5+ "testing"6+)7 8 func 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 lines232 }{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 lines569 }570 })571 }572 }573+574+// 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+// }609+610+func 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+ }618+619+ 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+ }925+926+ for i := range tt {927+ tc := tt[i]928+929+ 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
1 package tea2 3+import "strconv"4+5 // 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.8 type MouseMsg MouseEvent5 unmodified lines14 15 // MouseEvent represents a mouse event, which could be a click, a scroll wheel16 // movement, a cursor movement, or a combination.17 type MouseEvent struct {16- X int17- Y int18+ X int19+ Y int20+ Shift bool21+ Alt bool22+ Ctrl bool23+ Action MouseAction24+ Button MouseButton25+26+ // Deprecated: Use MouseAction & MouseButton instead.27 Type MouseEventType19- Alt bool20- Ctrl bool28 }29 30+// IsWheel returns true if the mouse event is a wheel event.31+func (m MouseEvent) IsWheel() bool {32+ return m.Button == MouseButtonWheelUp || m.Button == MouseButtonWheelDown ||33+ m.Button == MouseButtonWheelLeft || m.Button == MouseButtonWheelRight34+}35+36 // String returns a string representation of a mouse event.37 func (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+ }47+48+ 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+ }66+67 return s68 }69 70+// MouseAction represents the action that occurred during a mouse event.71+type MouseAction int72+73+// Mouse event actions.74+const (75+ MouseActionPress MouseAction = iota76+ MouseActionRelease77+ MouseActionMotion78+)79+80+var mouseActions = map[MouseAction]string{81+ MouseActionPress: "press",82+ MouseActionRelease: "release",83+ MouseActionMotion: "motion",84+}85+86+// MouseButton represents the button that was pressed during a mouse event.87+type MouseButton int88+89+// 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.106+const (107+ MouseButtonNone MouseButton = iota108+ MouseButtonLeft109+ MouseButtonMiddle110+ MouseButtonRight111+ MouseButtonWheelUp112+ MouseButtonWheelDown113+ MouseButtonWheelLeft114+ MouseButtonWheelRight115+ MouseButtonBackward116+ MouseButtonForward117+ MouseButton10118+ MouseButton11119+)120+121+var 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+}135+136 // MouseEventType indicates the type of mouse event occurring.137+//138+// Deprecated: Use MouseAction & MouseButton instead.139 type MouseEventType int140 141 // Mouse event types.142+//143+// Deprecated: Use MouseAction & MouseButton instead.144 const (145 MouseUnknown MouseEventType = iota146 MouseLeft147 MouseRight148 MouseMiddle44- MouseRelease149+ MouseRelease // mouse button release (X10 only)150 MouseWheelUp151 MouseWheelDown152+ MouseWheelLeft153+ MouseWheelRight154+ MouseBackward155+ MouseForward156 MouseMotion157 )158 50-var 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-coordinates172+func 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+ }179+180+ b, _ := strconv.Atoi(matches[1])181+ px := matches[2]182+ py := matches[3]183+ release := matches[4] == "m"184+ m := parseMouseButton(b, true)185+186+ // 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+ }192+193+ x, _ := strconv.Atoi(px)194+ y, _ := strconv.Atoi(py)195+196+ // (1,1) is the upper left. We subtract 1 to normalize it to (0,0).197+ m.X = x - 1198+ m.Y = y - 1199+200+ return m201 }202 203+const x10MouseByteOffset = 32204+205 // 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%20Tracking214 func parseX10MouseEvent(buf []byte) MouseEvent {215 v := buf[3:6]216+ m := parseMouseButton(int(v[0]), false)217+218+ // (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 - 1221+222+ return m223+}224+225+// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates226+func parseMouseButton(b int, isSGR bool) MouseEvent {227 var m MouseEvent72- const byteOffset = 3273- e := v[0] - byteOffset228+ e := b229+ if !isSGR {230+ e -= x10MouseByteOffset231+ }232 233 const (234 bitShift = 0b0000_0100235 bitAlt = 0b0000_1000236 bitCtrl = 0b0001_0000237 bitMotion = 0b0010_0000238 bitWheel = 0b0100_0000239+ bitAdd = 0b1000_0000 // additional buttons 8-11240 241 bitsMask = 0b0000_001183-84- bitsLeft = 0b0000_000085- bitsMiddle = 0b0000_000186- bitsRight = 0b0000_001087- bitsRelease = 0b0000_001188-89- bitsWheelUp = 0b0000_000090- bitsWheelDown = 0b0000_0001242 )243 93- 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 }256 120- 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- }261 127- // (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 != 0266 267+ // 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+ }306+307 return m308 }modified:nil_renderer.go+25 added-15 removed
1 package tea2 3 type nilRenderer struct{}4 5-func (n nilRenderer) start() {}6-func (n nilRenderer) stop() {}7-func (n nilRenderer) kill() {}8-func (n nilRenderer) write(_ string) {}9-func (n nilRenderer) repaint() {}10-func (n nilRenderer) clearScreen() {}11-func (n nilRenderer) altScreen() bool { return false }12-func (n nilRenderer) enterAltScreen() {}13-func (n nilRenderer) exitAltScreen() {}14-func (n nilRenderer) showCursor() {}15-func (n nilRenderer) hideCursor() {}16-func (n nilRenderer) enableMouseCellMotion() {}17-func (n nilRenderer) disableMouseCellMotion() {}18-func (n nilRenderer) enableMouseAllMotion() {}19-func (n nilRenderer) disableMouseAllMotion() {}5+func (n nilRenderer) start() {}6+func (n nilRenderer) stop() {}7+func (n nilRenderer) kill() {}8+func (n nilRenderer) write(_ string) {}9+func (n nilRenderer) repaint() {}10+func (n nilRenderer) clearScreen() {}11+func (n nilRenderer) altScreen() bool { return false }12+func (n nilRenderer) enterAltScreen() {}13+func (n nilRenderer) exitAltScreen() {}14+func (n nilRenderer) showCursor() {}15+func (n nilRenderer) hideCursor() {}16+func (n nilRenderer) enableMouseCellMotion() {}17+func (n nilRenderer) disableMouseCellMotion() {}18+func (n nilRenderer) enableMouseAllMotion() {}19+func (n nilRenderer) disableMouseAllMotion() {}20+func (n nilRenderer) enableBracketedPaste() {}21+func (n nilRenderer) disableBracketedPaste() {}22+func (n nilRenderer) enableMouseSGRMode() {}23+func (n nilRenderer) disableMouseSGRMode() {}24+func (n nilRenderer) bracketedPasteActive() bool { return false }25+func (n nilRenderer) setWindowTitle(_ string) {}26+func (n nilRenderer) reportFocus() bool { return false }27+func (n nilRenderer) enableReportFocus() {}28+func (n nilRenderer) disableReportFocus() {}29+func (n nilRenderer) resetLinesRendered() {}modified:options_test.go+22 added-6 removed
1 package tea2 3 import (4 "bytes"5+ "context"6+ "os"7+ "sync/atomic"8 "testing"9 )10 11 func 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 })19 20 t.Run("custom input", func(t *testing.T) {18 unmodified lines39 })40 41 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 lines51 t.Errorf("expected filter to be set")52 }53 })54 55+ t.Run("external context", func(t *testing.T) {56+ extCtx, extCancel := context.WithCancel(context.Background())57+ defer extCancel()58+59+ 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+ })64+65 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 lines77 t.Run("custom input", func(t *testing.T) {78 var b bytes.Buffer79 exercise(t, WithInput(&b), customInput)80 })68-81 })82 83 t.Run("startup options", func(t *testing.T) {84 exercise := func(t *testing.T, opt ProgramOption, expect startupOptions) {6 unmodified lines91 t.Run("alt screen", func(t *testing.T) {92 exercise(t, WithAltScreen(), withAltScreen)93 })94 95+ t.Run("bracketed paste disabled", func(t *testing.T) {96+ exercise(t, WithoutBracketedPaste(), withoutBracketedPaste)97+ })98+99 t.Run("ansi compression", func(t *testing.T) {100 exercise(t, WithANSICompressor(), withANSICompressor)101 })102 26 unmodified lines129 })130 })131 132 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 linesmodified:options.go+50 added-9 removed
1 unmodified line2 3 import (4 "context"5 "io"6-7- "github.com/muesli/termenv"6+ "sync/atomic"7 )8 9 // ProgramOption is used to set options when initializing a Program. Program can10 // accept a variable number of options.7 unmodified lines18 // useful if you want to cancel the execution from outside. When a Program gets19 // cancelled it will exit with an error ErrProgramKilled.20 func WithContext(ctx context.Context) ProgramOption {21 return func(p *Program) {23- p.ctx = ctx22+ p.externalCtx = ctx23 }24 }25 26 // WithOutput sets the output which, by default, is stdout. In most cases you27 // won't need to use this.28 func 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 }33 34 // WithInput sets the input which, by default, is stdin. In most cases you13 unmodified lines48 p.inputType = ttyInput49 }50 }51 52+// 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)63+func WithEnvironment(env []string) ProgramOption {64+ return func(p *Program) {65+ p.environ = env66+ }67+}68+69 // WithoutSignalHandler disables the signal handler that Bubble Tea sets up for70 // Programs. This is useful if you want to handle signals yourself.71 func WithoutSignalHandler() ProgramOption {72 return func(p *Program) {14 unmodified lines87 // WithoutSignals will ignore OS signals.88 // This is mainly useful for testing.89 func WithoutSignals() ProgramOption {90 return func(p *Program) {79- p.ignoreSignals = true91+ atomic.StoreUint32(&p.ignoreSignals, 1)92 }93 }94 95 // WithAltScreen starts the program with the alternate screen buffer enabled15 unmodified lines111 p.startupOptions |= withAltScreen112 }113 }114 115+// WithoutBracketedPaste starts the program with bracketed paste disabled.116+func WithoutBracketedPaste() ProgramOption {117+ return func(p *Program) {118+ p.startupOptions |= withoutBracketedPaste119+ }120+}121+122 // 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 lines147 // 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 the26 unmodified lines184 // 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.191 func WithANSICompressor() ProgramOption {192 return func(p *Program) {193 p.startupOptions |= withANSICompressor194 }41 unmodified lines236 return func(p *Program) {237 p.fps = fps238 }239 }240+241+// 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.248+func WithReportFocus() ProgramOption {249+ return func(p *Program) {250+ p.startupOptions |= withReportFocus251+ }252+}modified:README.md+85 added-95 removed
1 # Bubble Tea2 3 <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>14 15 The fun, functional and stateful way to build terminal apps. A Go framework16 based on [The Elm Architecture][elm]. Bubble Tea is well-suited for simple and3 unmodified lines20 <img src="https://stuff.charm.sh/bubbletea/bubbletea-example.gif" width="100%" alt="Bubble Tea Example">21 </p>22 23 Bubble Tea is in use in production and includes a number of features and19-performance optimizations we’ve added along the way. Among those is a standard20-framerate-based renderer, a renderer for high-performance scrollable21-regions which works alongside the main renderer, and mouse support.24+performance optimizations we’ve added along the way. Among those is25+a framerate-based renderer, mouse support, focus reporting and more.26 27 To 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 lines37 <a href="https://github.com/charmbracelet/bubbles"><img src="https://stuff.charm.sh/bubbles/bubbles-badge.png" width="174" alt="Bubbles Badge"></a> 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>40 37-***41+---42 43 ## Tutorial44 45 Bubble Tea is based on the functional design paradigms of [The Elm5 unmodified lines51 By the way, the non-annotated source code for this program is available52 [on GitHub][tut-source].53 54 [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/basics56 57 ### Enough! Let's get to it.58 59 For this tutorial, we're making a shopping list.3 unmodified lines63 64 ```go65 package main66 67+// 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.71 import (72 "fmt"73 "os"74 3 unmodified lines78 79 Bubble Tea programs are comprised of a **model** that describes the application80 state and three simple methods on that model:81 74-* **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.85 86 ### The Model87 88 So let's start by defining our model which will store our application's state.171 unmodified lines260 261 There are also several [Bubble Tea examples][examples] available and, of course,262 there are [Go Docs][docs].263 256-[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=doc267 268 ## Debugging269 3 unmodified lines273 delve in headless mode and then connect to it:274 275 ```bash276 # Start the debugger269-$ dlv debug --headless .270-API server listening at: 127.0.0.1:34241277+$ dlv debug --headless --api-version=2 --listen=127.0.0.1:43000 .278+API server listening at: 127.0.0.1:43000279 280 # Connect to it from another terminal273-$ dlv connect 127.0.0.1:34241281+$ dlv connect 127.0.0.1:43000282 ```283 276-Note that the default port used will vary on your system and per run, so277-actually watch out what address the first `dlv` run tells you to connect to.284+If you do not explicitly supply the `--listen` flag, the port used will vary285+per run, so passing this in makes the debugger easier to use from a script286+or your IDE of choice.287 288+Additionally, we pass in `--api-version=2` because delve defaults to version 1289+for backwards compatibility reasons. However, delve recommends using version 2290+for all new development and some clients may no longer work with version 1.291+For more information, see the [Delve documentation](https://github.com/go-delve/delve/tree/master/Documentation/api).292+293 ### Logging Stuff294 295 You can’t really log to stdout with Bubble Tea because your TUI is busy296 occupying that! You can, however, log to a file by including something like14 unmodified lines311 your program in another window.312 313 ## Libraries we use with Bubble Tea314 301-* [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]320 321 [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/ntcharts326 327 ## Bubble Tea in the Wild328 317-For some Bubble Tea programs in production, see:329+There are over [10,000 applications](https://github.com/charmbracelet/bubbletea/network/dependents) built with Bubble Tea! Here are a handful of ’em.330 319-* [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 favourites332 333+- [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 manager339+340+### In Industry341+342+- 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 providers350+351+### Charm stuff352+353+- [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!)357+358+### There’s so much more where that came from359+360+For more applications built with Bubble Tea see [Charm & Friends][community].361+Is there something cool you made with Bubble Tea you want to share? [PRs][community] are362+welcome!363+364+## Contributing365+366+See [contributing][contribute].367+368+[contribute]: https://github.com/charmbracelet/bubbletea/contribute369+370 ## Feedback371 383-We'd love to hear your thoughts on this project. Feel free to drop us a note!372+We’d love to hear your thoughts on this project. Feel free to drop us a note!373 385-* [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)377 378 ## Acknowledgments379 380 Bubble Tea is based on the paradigms of [The Elm Architecture][elm] by Evan3 unmodified lines384 385 [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-wild389 390 ## License391 402-[MIT](https://github.com/charmbracelet/bubbletea/raw/master/LICENSE)392+[MIT](https://github.com/charmbracelet/bubbletea/raw/main/LICENSE)393 404-***394+---395 396 Part of [Charm](https://charm.sh).397 408-<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>399 400 Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحةmodified:renderer.go+35 added-3 removed
38 unmodified lines39 // enableMouseCellMotion enables mouse click, release, wheel and motion40 // events if a mouse button is pressed (i.e., drag events).41 enableMouseCellMotion()42 43- // DisableMouseCellMotion disables Mouse Cell Motion tracking.43+ // disableMouseCellMotion disables Mouse Cell Motion tracking.44 disableMouseCellMotion()45 46- // 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()50 51- // DisableMouseAllMotion disables All Motion mouse tracking.51+ // disableMouseAllMotion disables All Motion mouse tracking.52 disableMouseAllMotion()53+54+ // enableMouseSGRMode enables mouse extended mode (SGR).55+ enableMouseSGRMode()56+57+ // disableMouseSGRMode disables mouse extended mode (SGR).58+ disableMouseSGRMode()59+60+ // enableBracketedPaste enables bracketed paste, where characters61+ // inside the input are not interpreted when pasted as a whole.62+ enableBracketedPaste()63+64+ // disableBracketedPaste disables bracketed paste.65+ disableBracketedPaste()66+67+ // bracketedPasteActive reports whether bracketed paste mode is68+ // currently enabled.69+ bracketedPasteActive() bool70+71+ // setWindowTitle sets the terminal window title.72+ setWindowTitle(string)73+74+ // reportFocus returns whether reporting focus events is enabled.75+ reportFocus() bool76+77+ // enableReportFocus reports focus events to the program.78+ enableReportFocus()79+80+ // disableReportFocus stops reporting focus events to the program.81+ disableReportFocus()82+83+ // resetLinesRendered ensures exec output remains on screen on exit84+ resetLinesRendered()85 }86 87 // repaintMsg forces a full repaint.88 type repaintMsg struct{}modified:screen_test.go+15 added-9 removed
12 unmodified lines13 }{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 }60 61 for _, test := range tests {62 t.Run(test.name, func(t *testing.T) {2 unmodified lines65 66 m := &testModel{}67 p := NewProgram(m, WithInput(&in), WithOutput(&buf))68 69+ 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)72 73 if _, err := p.Run(); err != nil {74 t.Fatal(err)75 }76 77 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 lines115 // showCursorMsg is an internal command used to show the cursor. You can send116 // this message with ShowCursor.117 type showCursorMsg struct{}118 119+// 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.124+func EnableBracketedPaste() Msg {125+ return enableBracketedPasteMsg{}126+}127+128+// enableBracketedPasteMsg in an internal message signals that129+// bracketed paste should be enabled. You can send an130+// enableBracketedPasteMsg with EnableBracketedPaste.131+type enableBracketedPasteMsg struct{}132+133+// 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.138+func DisableBracketedPaste() Msg {139+ return disableBracketedPasteMsg{}140+}141+142+// disableBracketedPasteMsg in an internal message signals that143+// bracketed paste should be disabled. You can send an144+// disableBracketedPasteMsg with DisableBracketedPaste.145+type disableBracketedPasteMsg struct{}146+147+// enableReportFocusMsg is an internal message that signals to enable focus148+// reporting. You can send an enableReportFocusMsg with EnableReportFocus.149+type enableReportFocusMsg struct{}150+151+// EnableReportFocus is a special command that tells the Bubble Tea program to152+// report focus events to the program.153+func EnableReportFocus() Msg {154+ return enableReportFocusMsg{}155+}156+157+// disableReportFocusMsg is an internal message that signals to disable focus158+// reporting. You can send an disableReportFocusMsg with DisableReportFocus.159+type disableReportFocusMsg struct{}160+161+// DisableReportFocus is a special command that tells the Bubble Tea program to162+// stop reporting focus events to the program.163+func DisableReportFocus() Msg {164+ return disableReportFocusMsg{}165+}166+167 // 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.171 func (p *Program) EnterAltScreen() {172 if p.renderer != nil {173 p.renderer.enterAltScreen()174+ } else {175+ p.startupOptions |= withAltScreen176 }177 }178 179 // ExitAltScreen exits the alternate screen buffer.1 unmodified line181 // Deprecated: The altscreen will exited automatically when the program exits.182 func (p *Program) ExitAltScreen() {183 if p.renderer != nil {184 p.renderer.exitAltScreen()185+ } else {186+ p.startupOptions &^= withAltScreen187 }188 }189 190 // 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.194 func (p *Program) EnableMouseCellMotion() {195+ if p.renderer != nil {143- p.renderer.enableMouseCellMotion()196+ p.renderer.enableMouseCellMotion()197+ } else {198+ p.startupOptions |= withMouseCellMotion199+ }200 }201 202 // 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.206 func (p *Program) DisableMouseCellMotion() {207+ if p.renderer != nil {151- p.renderer.disableMouseCellMotion()208+ p.renderer.disableMouseCellMotion()209+ } else {210+ p.startupOptions &^= withMouseCellMotion211+ }212 }213 214 // 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.219 func (p *Program) EnableMouseAllMotion() {220+ if p.renderer != nil {160- p.renderer.enableMouseAllMotion()221+ p.renderer.enableMouseAllMotion()222+ } else {223+ p.startupOptions |= withMouseAllMotion224+ }225 }226 227 // 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.231 func (p *Program) DisableMouseAllMotion() {232+ if p.renderer != nil {168- p.renderer.disableMouseAllMotion()233+ p.renderer.disableMouseAllMotion()234+ } else {235+ p.startupOptions &^= withMouseAllMotion236+ }237 }238+239+// SetWindowTitle sets the terminal window title.240+//241+// Deprecated: Use the SetWindowTitle command instead.242+func (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 zos3 4 package tea5 6 import (27 unmodified linesmodified:standard_renderer.go+232 added-107 removed
6 unmodified lines7 "strings"8 "sync"9 "time"10 11+ "github.com/charmbracelet/x/ansi"12 "github.com/muesli/ansi/compressor"12- "github.com/muesli/reflow/truncate"13- "github.com/muesli/termenv"13 )14 15 const (16 // defaultFramerate specifies the maximum interval at which we should8 unmodified lines25 // 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.27 type standardRenderer struct {28 mtx *sync.Mutex30- out *termenv.Output29+ out io.Writer30 31 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.Once42 43 // cursor visibility state1 unmodified line45 46 // essentially whether or not we're using the full size of the terminal47 altScreenActive bool48 49+ // whether or not we're currently using bracketed paste50+ bpActive bool51+52+ // reportingFocus whether reporting focus events is enabled53+ reportingFocus bool54+55 // renderer dimensions; usually the size of the window56 width int57 height int58 2 unmodified lines61 }62 63 // newRenderer creates a new renderer. Normally you'll want to initialize it64 // with os.Stdout as the first argument.58-func newRenderer(out *termenv.Output, useANSICompressor bool, fps int) renderer {65+func newRenderer(out io.Writer, useANSICompressor bool, fps int) renderer {66 if fps < 1 {67 fps = defaultFPS68 } else if fps > maxFPS {69 fps = maxFPS6 unmodified lines76 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 lines111 112 r.mtx.Lock()113 defer r.mtx.Unlock()114 108- r.out.ClearLine()115+ r.execute(ansi.EraseEntireLine)116+ // Move the cursor back to the beginning of the line117+ r.execute("\r")118 119 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 }125 126+// execute writes a sequence to the terminal.127+func (r *standardRenderer) execute(seq string) {128+ _, _ = io.WriteString(r.out, seq)129+}130+131 // kill halts the renderer. The final frame will not be rendered.132 func (r *standardRenderer) kill() {133 // Stop the renderer before acquiring the mutex to avoid a deadlock.134 r.once.Do(func() {2 unmodified lines137 138 r.mtx.Lock()139 defer r.mtx.Unlock()140 127- r.out.ClearLine()141+ r.execute(ansi.EraseEntireLine)142+ // Move the cursor back to the beginning of the line143+ r.execute("\r")144 }145 146 // listen waits for ticks on the ticker, or a signal to stop the renderer.147 func (r *standardRenderer) listen() {14 unmodified lines162 r.mtx.Lock()163 defer r.mtx.Unlock()164 165 if r.buf.Len() == 0 || r.buf.String() == r.lastRender {150- // Nothing to do166+ // Nothing to do.167 return168 }169 154- // Output buffer170+ // Output buffer.171 buf := &bytes.Buffer{}156- out := termenv.NewOutput(buf)172 173+ // 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+ }179+180 newLines := strings.Split(r.buf.String(), "\n")181 182 // 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 if2 unmodified lines186 if r.height > 0 && len(newLines) > r.height {187 newLines = newLines[len(newLines)-r.height:]188 }189 168- numLinesThisFlush := len(newLines)169- oldLines := strings.Split(r.lastRender, "\n")170- skipLines := make(map[int]struct{})190 flushQueuedMessages := len(r.queuedMessageLines) > 0 && !r.altScreenActive191 173- // 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.200 179- // 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 }204 191- out.CursorUp(1)205+ _, _ = buf.WriteString(line)206+ _, _ = buf.WriteString("\r\n")207 }193-194- 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 }211 209- // 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- }214-215- // 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.216+217+ 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+ }224 225- // 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+ }230 236- _, _ = out.WriteString(line)231+ line := newLines[i]232 238- 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 }243+244+ 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.249+250+ // Removing previously rendered content at the end of line.251+ line = line + ansi.EraseLineRight252+ }253+254+ _, _ = buf.WriteString(line)255+256+ if i < len(newLines)-1 {257+ _, _ = buf.WriteString("\r\n")258+ }259 }243- r.linesRendered = numLinesThisFlush260 261+ // Clearing left over content from last render.262+ if r.lastLinesRendered() > len(newLines) {263+ buf.WriteString(ansi.EraseScreenBelow)264+ }265+266+ if r.altScreenActive {267+ r.altLinesRendered = len(newLines)268+ } else {269+ r.linesRendered = len(newLines)270+ }271+272 // 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 }282 283 _, _ = r.out.Write(buf.Bytes())284 r.lastRender = r.buf.String()285+286+ // 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 }292 293+// lastLinesRendered returns the number of lines rendered lastly.294+func (r *standardRenderer) lastLinesRendered() int {295+ if r.altScreenActive {296+ return r.altLinesRendered297+ }298+ return r.linesRendered299+}300+301 // write writes to the internal buffer. The buffer will be outputted via the302 // ticker which calls flush().303 func (r *standardRenderer) write(s string) {304 r.mtx.Lock()12 unmodified lines317 }318 319 func (r *standardRenderer) repaint() {320 r.lastRender = ""321+ r.lastRenderedLines = nil322 }323 324 func (r *standardRenderer) clearScreen() {325 r.mtx.Lock()326 defer r.mtx.Unlock()327 287- r.out.ClearScreen()288- r.out.MoveCursor(1, 1)328+ r.execute(ansi.EraseEntireScreen)329+ r.execute(ansi.CursorHomePosition)330 331 r.repaint()332 }333 12 unmodified lines346 return347 }348 349 r.altScreenActive = true309- r.out.AltScreen()350+ r.execute(ansi.SetAltScreenSaveCursorMode)351 352 // 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)360 361 // 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 }369 370+ // Entering the alt screen resets the lines rendered count.371+ r.altLinesRendered = 0372+373 r.repaint()374 }375 376 func (r *standardRenderer) exitAltScreen() {4 unmodified lines381 return382 }383 384 r.altScreenActive = false341- r.out.ExitAltScreen()385+ r.execute(ansi.ResetAltScreenSaveCursorMode)386 387 // 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 }395 396 r.repaint()397 }2 unmodified lines400 r.mtx.Lock()401 defer r.mtx.Unlock()402 403 r.cursorHidden = false360- r.out.ShowCursor()404+ r.execute(ansi.ShowCursor)405 }406 407 func (r *standardRenderer) hideCursor() {408 r.mtx.Lock()409 defer r.mtx.Unlock()410 411 r.cursorHidden = true368- r.out.HideCursor()412+ r.execute(ansi.HideCursor)413 }414 415 func (r *standardRenderer) enableMouseCellMotion() {416 r.mtx.Lock()417 defer r.mtx.Unlock()418 375- r.out.EnableMouseCellMotion()419+ r.execute(ansi.SetButtonEventMouseMode)420 }421 422 func (r *standardRenderer) disableMouseCellMotion() {423 r.mtx.Lock()424 defer r.mtx.Unlock()425 382- r.out.DisableMouseCellMotion()426+ r.execute(ansi.ResetButtonEventMouseMode)427 }428 429 func (r *standardRenderer) enableMouseAllMotion() {430 r.mtx.Lock()431 defer r.mtx.Unlock()432 389- r.out.EnableMouseAllMotion()433+ r.execute(ansi.SetAnyEventMouseMode)434 }435 436 func (r *standardRenderer) disableMouseAllMotion() {437 r.mtx.Lock()438 defer r.mtx.Unlock()439 396- r.out.DisableMouseAllMotion()440+ r.execute(ansi.ResetAnyEventMouseMode)441 }442 443+func (r *standardRenderer) enableMouseSGRMode() {444+ r.mtx.Lock()445+ defer r.mtx.Unlock()446+447+ r.execute(ansi.SetSgrExtMouseMode)448+}449+450+func (r *standardRenderer) disableMouseSGRMode() {451+ r.mtx.Lock()452+ defer r.mtx.Unlock()453+454+ r.execute(ansi.ResetSgrExtMouseMode)455+}456+457+func (r *standardRenderer) enableBracketedPaste() {458+ r.mtx.Lock()459+ defer r.mtx.Unlock()460+461+ r.execute(ansi.SetBracketedPasteMode)462+ r.bpActive = true463+}464+465+func (r *standardRenderer) disableBracketedPaste() {466+ r.mtx.Lock()467+ defer r.mtx.Unlock()468+469+ r.execute(ansi.ResetBracketedPasteMode)470+ r.bpActive = false471+}472+473+func (r *standardRenderer) bracketedPasteActive() bool {474+ r.mtx.Lock()475+ defer r.mtx.Unlock()476+477+ return r.bpActive478+}479+480+func (r *standardRenderer) enableReportFocus() {481+ r.mtx.Lock()482+ defer r.mtx.Unlock()483+484+ r.execute(ansi.SetFocusEventMode)485+ r.reportingFocus = true486+}487+488+func (r *standardRenderer) disableReportFocus() {489+ r.mtx.Lock()490+ defer r.mtx.Unlock()491+492+ r.execute(ansi.ResetFocusEventMode)493+ r.reportingFocus = false494+}495+496+func (r *standardRenderer) reportFocus() bool {497+ r.mtx.Lock()498+ defer r.mtx.Unlock()499+500+ return r.reportingFocus501+}502+503+// setWindowTitle sets the terminal window title.504+func (r *standardRenderer) setWindowTitle(title string) {505+ r.execute(ansi.SetWindowTitle(title))506+}507+508 // setIgnoredLines specifies lines not to be touched by the standard Bubble Tea509 // renderer.510 func (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 lines522 r.ignoreLines[i] = struct{}{}523 }524 525 // Erase ignored lines526+ lastLinesRendered := r.lastLinesRendered()417- if r.linesRendered > 0 {527+ if lastLinesRendered > 0 {528 buf := &bytes.Buffer{}419- out := termenv.NewOutput(buf)529 421- 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 lines544 func (r *standardRenderer) clearIgnoredLines() {545 r.ignoreLines = nil546 }547 548+func (r *standardRenderer) resetLinesRendered() {549+ r.linesRendered = 0550+}551+552 // 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 lines566 // 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.573 func (r *standardRenderer) insertTop(lines []string, topBoundary, bottomBoundary int) {574 r.mtx.Lock()575 defer r.mtx.Unlock()576 577 buf := &bytes.Buffer{}462- out := termenv.NewOutput(buf)578 464- 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))584 585 // 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()))587 588 _, _ = r.out.Write(buf.Bytes())589 }590 5 unmodified lines596 //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.603 func (r *standardRenderer) insertBottom(lines []string, topBoundary, bottomBoundary int) {604 r.mtx.Lock()605 defer r.mtx.Unlock()606 607 buf := &bytes.Buffer{}490- out := termenv.NewOutput(buf)608 492- 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))613 614 // 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()))616 617 _, _ = r.out.Write(buf.Bytes())618 }619 63 unmodified lines683 // 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.689 func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd {690 return func() Msg {691 return syncScrollAreaMsg{692 lines: lines,8 unmodified lines701 // 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.707 func ClearScrollArea() Msg {708 return clearScrollAreaMsg{}709 }710 7 unmodified lines718 // 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.724 func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd {725 return func() Msg {726 return scrollUpMsg{727 lines: newLines,13 unmodified lines741 // 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.747 func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd {748 return func() Msg {749 return scrollDownMsg{750 lines: newLines,40 unmodified linesadded:Taskfile.yaml+14 added
1+# https://taskfile.dev2+3+version: '3'4+5+tasks:6+ lint:7+ desc: Run lint8+ cmds:9+ - golangci-lint run10+11+ test:12+ desc: Run tests13+ cmds:14+ - go test ./... {{.CLI_ARGS}}added:tea_init.go+22 added
1+package tea2+3+import (4+ "github.com/charmbracelet/lipgloss"5+)6+7+func 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 line2 3 import (4 "bytes"5 "context"6+ "errors"7+ "sync"8 "sync/atomic"9 "testing"10 "time"11 )12 13+type ctxImplodeMsg struct {14+ cancel context.CancelFunc15+}16+17 type incrementMsg struct{}18 19+type panicMsg struct{}20+21 type testModel struct {22 executed atomic.Value23 counter atomic.Value24 }2 unmodified lines27 return nil28 }29 30 func (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)35+36 case incrementMsg:37 i := m.counter.Load()38 if i == nil {39 m.counter.Store(1)2 unmodified lines42 }43 44 case KeyMsg:45 return m, Quit46+47+ case panicMsg:48+ panic("testing panic behavior")49 }50 51 return m, nil52 }7 unmodified lines60 var buf bytes.Buffer61 var in bytes.Buffer62 in.Write([]byte("q"))63 64+ ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second)65+ defer cancel()66+49- 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 lines94 t.Fatal(err)95 }96 }97 98+func TestTeaWaitQuit(t *testing.T) {99+ var buf bytes.Buffer100+ var in bytes.Buffer101+102+ progStarted := make(chan struct{})103+ waitStarted := make(chan struct{})104+ errChan := make(chan error, 1)105+106+ m := &testModel{}107+ p := NewProgram(m, WithInput(&in), WithOutput(&buf))108+109+ go func() {110+ _, err := p.Run()111+ errChan <- err112+ }()113+114+ go func() {115+ for {116+ time.Sleep(time.Millisecond)117+ if m.executed.Load() != nil {118+ close(progStarted)119+120+ <-waitStarted121+ time.Sleep(50 * time.Millisecond)122+ p.Quit()123+124+ return125+ }126+ }127+ }()128+129+ <-progStarted130+131+ 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()141+142+ err := <-errChan143+ if err != nil {144+ t.Fatalf("Expected nil, got %v", err)145+ }146+}147+148+func TestTeaWaitKill(t *testing.T) {149+ var buf bytes.Buffer150+ var in bytes.Buffer151+152+ progStarted := make(chan struct{})153+ waitStarted := make(chan struct{})154+ errChan := make(chan error, 1)155+156+ m := &testModel{}157+ p := NewProgram(m, WithInput(&in), WithOutput(&buf))158+159+ go func() {160+ _, err := p.Run()161+ errChan <- err162+ }()163+164+ go func() {165+ for {166+ time.Sleep(time.Millisecond)167+ if m.executed.Load() != nil {168+ close(progStarted)169+170+ <-waitStarted171+ time.Sleep(50 * time.Millisecond)172+ p.Kill()173+174+ return175+ }176+ }177+ }()178+179+ <-progStarted180+181+ 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()191+192+ err := <-errChan193+ if !errors.Is(err, ErrProgramKilled) {194+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)195+ }196+}197+198 func TestTeaWithFilter(t *testing.T) {199 testTeaWithFilter(t, 0)200 testTeaWithFilter(t, 1)201 testTeaWithFilter(t, 2)49 unmodified lines251 }252 }253 }()254 137- if _, err := p.Run(); err != ErrProgramKilled {255+ _, err := p.Run()256+257+ if !errors.Is(err, ErrProgramKilled) {258 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)259 }260+261+ 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 }267 268 func TestTeaContext(t *testing.T) {269 ctx, cancel := context.WithCancel(context.Background())11 unmodified lines281 }282 }283 }()284 159- if _, err := p.Run(); err != ErrProgramKilled {285+ _, err := p.Run()286+287+ if !errors.Is(err, ErrProgramKilled) {288 t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)289 }290+291+ 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 }296 297+func TestTeaContextImplodeDeadlock(t *testing.T) {298+ ctx, cancel := context.WithCancel(context.Background())299+ var buf bytes.Buffer300+ var in bytes.Buffer301+302+ 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+ }()313+314+ if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {315+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)316+ }317+}318+319+func TestTeaContextBatchDeadlock(t *testing.T) {320+ ctx, cancel := context.WithCancel(context.Background())321+ var buf bytes.Buffer322+ var in bytes.Buffer323+324+ inc := func() Msg {325+ cancel()326+ return incrementMsg{}327+ }328+329+ 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+ }()344+345+ if _, err := p.Run(); !errors.Is(err, ErrProgramKilled) {346+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)347+ }348+}349+350 func TestTeaBatchMsg(t *testing.T) {351 var buf bytes.Buffer352 var in bytes.Buffer353 69 unmodified lines423 t.Fatalf("counter should be 3, got %d", m.counter.Load())424 }425 }426 427+func TestTeaNestedSequenceMsg(t *testing.T) {428+ var buf bytes.Buffer429+ var in bytes.Buffer430+431+ inc := func() Msg {432+ return incrementMsg{}433+ }434+435+ m := &testModel{}436+ p := NewProgram(m, WithInput(&in), WithOutput(&buf))437+ go p.Send(sequenceMsg{inc, Sequence(inc, inc), Quit})438+439+ if _, err := p.Run(); err != nil {440+ t.Fatal(err)441+ }442+443+ if m.counter.Load() != 3 {444+ t.Fatalf("counter should be 3, got %d", m.counter.Load())445+ }446+}447+448 func TestTeaSend(t *testing.T) {449 var buf bytes.Buffer450 var in bytes.Buffer451 17 unmodified lines469 470 m := &testModel{}471 NewProgram(m, WithInput(&in), WithOutput(&buf))472 }473+474+func TestTeaPanic(t *testing.T) {475+ var buf bytes.Buffer476+ var in bytes.Buffer477+478+ 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+ }()489+490+ _, err := p.Run()491+492+ if !errors.Is(err, ErrProgramPanic) {493+ t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)494+ }495+496+ if !errors.Is(err, ErrProgramKilled) {497+ t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)498+ }499+}500+501+func TestTeaGoroutinePanic(t *testing.T) {502+ var buf bytes.Buffer503+ var in bytes.Buffer504+505+ panicCmd := func() Msg {506+ panic("testing goroutine panic behavior")507+ }508+509+ 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+ }()524+525+ _, err := p.Run()526+527+ if !errors.Is(err, ErrProgramPanic) {528+ t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)529+ }530+531+ 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 lines15 "fmt"16 "io"17 "os"18 "os/signal"19+ "runtime"20 "runtime/debug"21 "sync"22+ "sync/atomic"23 "syscall"24 23- "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 )28 29+// ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic.30+var ErrProgramPanic = errors.New("program experienced a panic")31+30-// ErrProgramKilled is returned by [Program.Run] when the program got killed.32+// ErrProgramKilled is returned by [Program.Run] when the program gets killed.33 var ErrProgramKilled = errors.New("program was killed")34 35+// ErrInterrupted is returned by [Program.Run] when the program get a SIGINT36+// signal, or when it receives a [InterruptMsg].37+var ErrInterrupted = errors.New("program was interrupted")38+39 // Msg contain data from the result of a IO operation. Msgs trigger the update40 // function and, henceforth, the UI.41 type Msg interface{}42 28 unmodified lines71 ttyInput72 customInput73 )74 69-// 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.77 func (i inputType) String() string {78 return [...]string{79 "default input",5 unmodified lines85 // Options to customize the program during its initialization. These are86 // generally set with ProgramOptions.87 //88 // The options here are treated as bits.83-type startupOptions byte89+type startupOptions int1690 91 func (s startupOptions) has(option startupOptions) bool {92 return s&option != 093 }3 unmodified lines97 withMouseCellMotion98 withMouseAllMotion99 withANSICompressor100 withoutSignalHandler95-101 // 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 )109 103-// handlers manages series of channels returned by various processes. It allows104-// us to wait for those processes to terminate before exiting the program.105-type 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.113+type channelHandlers []chan struct{}114 115 // Adds a channel to the list of handlers. We wait for all handlers to terminate116 // gracefully on shutdown.109-func (h *handlers) add(ch chan struct{}) {117+func (h *channelHandlers) add(ch chan struct{}) {118 *h = append(*h, ch)119 }120 121 // shutdown waits for all handlers to terminate.114-func (h handlers) shutdown() {122+func (h channelHandlers) shutdown() {123 var wg sync.WaitGroup124 for _, ch := range h {125 wg.Add(1)126 go func(ch chan struct{}) {7 unmodified lines134 // Program is a terminal user interface.135 type Program struct {136 initialModel Model137 138+ // handlers is a list of channels that need to be waited on before the139+ // program can exit.140+ handlers channelHandlers141+142 // Configuration options that will set as the program is initializing,143 // treated as bits. These options can be set via various ProgramOptions.144 startupOptions startupOptions145 146+ // startupTitle is the title that will be set on the terminal when the147+ // program starts.148+ startupTitle string149+150 inputType inputType151 152+ // 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.Context155+156+ // 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.CancelFunc160 161 msgs chan Msg162 errs chan error163 finished chan struct{}164 165 // 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 renderer171 172+ // the environment variables for the program, defaults to os.Environ().173+ environ []string174+175 // 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{}182 183 // was the altscreen active before releasing the terminal?184 altScreenWasActive bool156- ignoreSignals bool185+ ignoreSignals uint32186 158- // 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?189 190 filter func(Model, Msg) Msg191 192 // fps is the frames per second we should set on the renderer, if193 // applicable,194 fps int195+196+ // mouseMode is true if the program should enable mouse mode on Windows.197+ mouseMode bool198 }199 200 // Quit is a special command that tells the Bubble Tea program to exit.201 func Quit() Msg {202 return QuitMsg{}203 }204 179-// 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].207 type QuitMsg struct{}208 209+// Suspend is a special command that tells the Bubble Tea program to suspend.210+func Suspend() Msg {211+ return SuspendMsg{}212+}213+214+// 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()].220+type SuspendMsg struct{}221+222+// ResumeMsg can be listen to do something once a program is resumed back223+// from a suspend state.224+type ResumeMsg struct{}225+226+// 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()].232+type InterruptMsg struct{}233+234+// Interrupt is a special command that tells the Bubble Tea program to235+// interrupt.236+func Interrupt() Msg {237+ return InterruptMsg{}238+}239+240 // NewProgram creates a new Program.241 func NewProgram(model Model, opts ...ProgramOption) *Program {242 p := &Program{243 initialModel: model,6 unmodified lines250 }251 252 // 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)259 260 // if no output was set, set it to stdout261 if p.output == nil {205- p.output = termenv.DefaultOutput()262+ p.output = os.Stdout263+ }264 207- // 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 }269 211- p.restoreOutput, _ = termenv.EnableVirtualTerminalProcessing(p.output)212-270 return p271 }272 273 func (p *Program) handleSignals() chan struct{} {19 unmodified lines293 select {294 case <-p.ctx.Done():295 return296 240- 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 lines314 // handleResize handles terminal resize events.315 func (p *Program) handleResize() chan struct{} {316 ch := make(chan struct{})317 256- 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()321 322 // Listen for window resizes.28 unmodified lines351 // (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+ }363+364 msg := cmd() // this can be long.365 p.Send(msg)366 }()367 }2 unmodified lines370 371 return ch372 }373 374+func (p *Program) disableMouse() {375+ p.renderer.disableMouseCellMotion()376+ p.renderer.disableMouseAllMotion()377+ p.renderer.disableMouseSGRMode()378+}379+380 // eventLoop is the central message loop. It receives and handles the default381 // Bubble Tea messages, update the model and triggers redraws.382 func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {383 for {17 unmodified lines401 switch msg := msg.(type) {402 case QuitMsg:403 return model, nil404 405+ case InterruptMsg:406+ return model, ErrInterrupted407+408+ case SuspendMsg:409+ if suspendSupported {410+ p.suspend()411+ }412+413 case clearScreenMsg:414 p.renderer.clearScreen()415 416 case enterAltScreenMsg:1 unmodified line418 419 case exitAltScreenMsg:420 p.renderer.exitAltScreen()421 422+ 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()431 340- 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+ }439 440 case disableMouseMsg:344- p.renderer.disableMouseCellMotion()345- p.renderer.disableMouseAllMotion()441+ p.disableMouse()442 443+ // 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+ }450+451 case showCursorMsg:452 p.renderer.showCursor()453 454 case hideCursorMsg:455 p.renderer.hideCursor()456 457+ case enableBracketedPasteMsg:458+ p.renderer.enableBracketedPaste()459+460+ case disableBracketedPasteMsg:461+ p.renderer.disableBracketedPaste()462+463+ case enableReportFocusMsg:464+ p.renderer.enableReportFocus()465+466+ case disableReportFocusMsg:467+ p.renderer.disableReportFocus()468+469 case execMsg:470 // NB: this blocks.471 p.exec(msg.cmd, msg.fn)472 12 unmodified lines485 }486 487 var cmd Cmd488 model, cmd = model.Update(msg) // run update489+490+ 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+ }495+496 p.renderer.write(model.View()) // send view to renderer497 }498 }499 }44 unmodified lines544 545 // 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.426-func (p *Program) Run() (Model, error) {427- handlers := handlers{}548+func (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)552 553+ p.finished = make(chan struct{})554+ defer func() {555+ close(p.finished)556+ }()557+558 defer p.cancel()559 560 switch p.inputType {561 case defaultInput:4 unmodified lines566 // 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 }577 578 f, err := openInputTTY()17 unmodified lines596 }597 598 // Handle signals.599 if !p.startupOptions.has(withoutSignalHandler) {474- handlers.add(p.handleSignals())600+ p.handlers.add(p.handleSignals())601 }602 603 // 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 lines621 return p.initialModel, err622 }623 624 // 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 }641 642+ // 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 != 0645+646+ if p.startupOptions&withReportFocus != 0 {647+ p.renderer.enableReportFocus()648+ }649+650+ // Start the renderer.651+ p.renderer.start()652+653 // 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)658 659 go func() {660 defer close(ch)661 3 unmodified lines665 }666 }()667 }668 526- // Start the renderer.527- p.renderer.start()528-669 // Render the initial view.670 p.renderer.write(model.View())671 672 // 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 }678 679 // Handle resize events.540- handlers.add(p.handleResize())680+ p.handlers.add(p.handleResize())681 682 // Process commands.543- handlers.add(p.handleCommands(cmds))683+ p.handlers.add(p.handleCommands(cmds))684 685 // Run event loop, handle updates and draw.686 model, err := p.eventLoop(model, cmds)547- killed := p.ctx.Err() != nil687+688+ if err == nil && len(p.errs) > 0 {689+ err = <-p.errs // Drain a leftover error in case eventLoop crashed690+ }691+692+ 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 }711 555- // Tear down.556- p.cancel()557-558- // 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- }566-567- // Wait for all handlers to finish.568- handlers.shutdown()569-712 // Restore terminal state.713 p.shutdown(killed)714 715 return model, err42 unmodified lines758 func (p *Program) Quit() {759 p.Send(Quit())760 }761 620-// 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.765 func (p *Program) Kill() {766 p.cancel()4 unmodified lines771 <-p.finished772 }773 774 // 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.780 func (p *Program) shutdown(kill bool) {781+ p.cancel()782+783+ // Wait for all handlers to finish.784+ p.handlers.shutdown()785+786+ // 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+ }796+797 if p.renderer != nil {798 if kill {799 p.renderer.kill()800 } else {1 unmodified line802 }803 }804 805 _ = p.restoreTerminalState()644- if p.restoreOutput != nil {645- _ = p.restoreOutput()806+}807+808+// recoverFromPanic recovers from a panic, prints the stack trace, and restores809+// the terminal to a usable state.810+func (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 }819 820+// 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.822+func (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+}831+832 // ReleaseTerminal restores the original terminal state and cancels the input833 // reader. You can return control to the Program with RestoreTerminal.834 func (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+ }839+840 p.waitForReadLoop()841 842 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 }848 661- p.altScreenWasActive = p.renderer.altScreen()849 return p.restoreTerminalState()850 }851 852 // 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.855 func (p *Program) RestoreTerminal() error {669- p.ignoreSignals = false856+ atomic.StoreUint32(&p.ignoreSignals, 0)857 858 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 }677-864 if p.altScreenWasActive {865 p.renderer.enterAltScreen()866 } else {867 // entering alt screen already causes a repaint.1 unmodified line869 }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+ }879 880 // 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 as29 unmodified linesmodified: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 zos3 4 package tea5 6 import (7 "fmt"8 "os"9+ "os/signal"10+ "syscall"11 10- "github.com/containerd/console"12+ "github.com/charmbracelet/x/term"13 )14 13-func (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)15+func (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 }24 23- return nil24-}25-26-// 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.30-func (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 }28+29 return nil30 }31 32 func openInputTTY() (*os.File, error) {2 unmodified lines35 return nil, fmt.Errorf("could not open a new TTY: %w", err)36 }37 return f, nil38 }39+40+const suspendSupported = true41+42+// Send SIGTSTP to the entire process group.43+func 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 lines3 4 package tea5 6 import (7+ "fmt"8 "os"9 9- "github.com/containerd/console"10+ "github.com/charmbracelet/x/term"11+ "golang.org/x/sys/windows"12 )13 12-func (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 = f14+func (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+ }24 22- // 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+ }30+31+ 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 }35 36+ // 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+ }43 30-// restoreInput restores stdout in the event that we placed it aside to handle31-// input with CONIN$, above.32-func (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+ }48+49+ 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 }53 54 return nil55 }56 57 // Open the Windows equivalent of a TTY.58 func 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 }65+66+const suspendSupported = false67+68+func suspendProcess() {}modified:tty.go+50 added-29 removed
2 unmodified lines3 import (4 "errors"5 "fmt"6 "io"7- "os"7 "time"8 10- 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 )12 13+func (p *Program) suspend() {14+ if err := p.ReleaseTerminal(); err != nil {15+ // If we can't release input, abort.16+ return17+ }18+19+ suspendProcess()20+21+ _ = p.RestoreTerminal()22+ go p.Send(ResumeMsg{})23+}24+25 func (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 }30 22- 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 }34 35 p.renderer.hideCursor()36 return nil2 unmodified lines39 // restoreTerminalState restores the terminal to the state prior to running the40 // Bubble Tea program.41 func (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()46 47+ if p.renderer.reportFocus() {48+ p.renderer.disableReportFocus()49+ }50+51 if p.renderer.altScreen() {52 p.renderer.exitAltScreen()53 54 // give the terminal a moment to catch up45- time.Sleep(time.Millisecond * 10) //nolint:gomnd55+ time.Sleep(time.Millisecond * 10) //nolint:mnd56 }57 }58 49- 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+}61+62+// restoreInput restores the tty input to its original state.63+func (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 }55-56- 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 }76 77 // initCancelReader (re)commences reading inputs.60-func (p *Program) initCancelReader() error {78+func (p *Program) initCancelReader(cancel bool) error {79+ if cancel && p.cancelReader != nil {80+ p.cancelReader.Cancel()81+ p.waitForReadLoop()82+ }83+84 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 lines95 96 func (p *Program) readLoop() {97 defer close(p.readLoopDone)98 76- 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 lines108 // waitForReadLoop waits for the cancelReader to finish its read loop.109 func (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 line118 119 // checkResize detects the current size of the output and informs the program120 // via a WindowSizeMsg.121 func (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 }126 106- 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