### Key String Representation Example Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Demonstrates how to get a user-friendly string representation of a Key, useful for comparisons. ```go k := Key{Type: KeyEnter} fmt.Println(k) // Output: enter ``` -------------------------------- ### KeyType String Representation Example Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Shows how to use the String() method on a KeyType to get its string representation, and how to check for KeyRunes and access modifier information like Alt. ```go k := Key{Type: KeyRunes, Runes: []rune{'a'}, Alt: true} if k.Type == KeyRunes { fmt.Println(k.Runes) // Output: a fmt.Println(k.String()) // Output: alt+a } ``` -------------------------------- ### Start Program with Alternate Screen Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the program with the alternate screen buffer enabled for full window mode. The alternate screen is automatically exited when the program quits. ```go p := tea.NewProgram(Model{}, tea.WithAltScreen()) if _, err := p.Run(); err != nil { fmt.Println("Error running program:", err) os.Exit(1) } ``` -------------------------------- ### Bubble Tea Initial Model Setup Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Initializes the application's state with a sample grocery list and an empty map for selected items. ```go func initialModel() model { return model{ // Our to-do list is a grocery list choices: []string{"Buy carrots", "Buy celery", "Buy kohlrabi"}, // A map which indicates which choices are selected. We're using // the map like a mathematical set. The keys refer to the indexes // of the `choices` slice, above. selected: make(map[int]struct{}), } } ``` -------------------------------- ### Handling KeyMsgs with KeyType Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea This example demonstrates a more robust method of handling KeyMsgs by switching on the KeyType, which is considered more foolproof than relying on string representations. ```go // Switch on the key type (more foolproof) switch msg := msg.(type) { case KeyMsg: switch msg.Type { case KeyEnter: fmt.Println("you pressed enter!") case KeyRunes: switch string(msg.Runes) { case "a": fmt.Println("you pressed a!") } } } ``` -------------------------------- ### Start Bubble Tea Program (Deprecated) Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Initializes and runs the program's event loops, blocking until termination. Use Program.Run instead. ```go func (p *Program) Start() error ``` -------------------------------- ### Program.Start Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the Bubble Tea program. Deprecated. ```APIDOC ## func (p *Program) Start() error ### Description Starts the Bubble Tea program. Deprecated. ### Returns - **error** - An error if the program failed to start. ``` -------------------------------- ### Start Program and Return Model (Deprecated) Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Initializes and runs the program's event loops, blocking until termination. Returns the final model. Use Program.Run instead. ```go func (p *Program) StartReturningModel() (Model, error) ``` -------------------------------- ### Program.StartReturningModel Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the Bubble Tea program and returns the final model. Deprecated. ```APIDOC ## func (p *Program) StartReturningModel() (Model, error) ### Description Starts the Bubble Tea program and returns the final model. Deprecated. ### Returns - **(Model, error)** - The final model and any error encountered. ``` -------------------------------- ### WithAltScreen Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the program with the alternate screen buffer enabled, allowing the program to run in full window mode. The alternate screen is automatically exited when the program quits. ```APIDOC ## func WithAltScreen ### Description Starts the program with the alternate screen buffer enabled (i.e. the program starts in full window mode). Note that the altscreen will be automatically exited when the program quits. ### Method N/A (ProgramOption configuration function) ### Endpoint N/A ### Parameters N/A ### Request Example ```go p := tea.NewProgram(Model{}, tea.WithAltScreen()) if _, err := p.Run(); err != nil { fmt.Println("Error running program:", err) os.Exit(1) } ``` ### Response N/A ``` -------------------------------- ### Handling KeyMsgs with String Representation Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea This example shows how to use the String() method of KeyMsg to switch on different keypresses, offering a concise way to check for specific keys like 'enter' or 'a'. ```go // Switch on the string representation of the key (shorter) switch msg := msg.(type) { case KeyMsg: switch msg.String() { case "enter": fmt.Println("you pressed enter!") case "a": fmt.Println("you pressed a!") } } ``` -------------------------------- ### WithMouseCellMotion Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the program with the mouse enabled in "cell motion" mode, capturing click, release, and wheel events, as well as drag events. It attempts to enable extended mode (SGR) and falls back to normal mode (X10) if unsupported. ```APIDOC ## func WithMouseCellMotion ### Description Starts the program with the mouse enabled in "cell motion" mode. Cell motion mode enables mouse click, release, and wheel events. Mouse movement events are also captured if a mouse button is pressed (i.e., drag events). Cell motion mode is better supported than all motion mode. This will try to enable the mouse in extended mode (SGR), if that is not supported by the terminal it will fall back to normal mode (X10). ### Method func WithMouseCellMotion() ProgramOption ``` -------------------------------- ### Enable Mouse Events in All Motion Mode Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the program with the mouse enabled in "all motion" mode, supporting click, release, wheel, and motion events regardless of button press, enabling hover interactions. It attempts to use SGR mode and falls back to X10 if unsupported. ```go func WithMouseAllMotion() ProgramOption ``` -------------------------------- ### WithoutBracketedPaste Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the program with bracketed paste disabled. ```APIDOC ## func WithoutBracketedPaste ### Description Starts the program with bracketed paste disabled. ### Method func WithoutBracketedPaste() ProgramOption ``` -------------------------------- ### WithMouseAllMotion Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the program with the mouse enabled in "all motion" mode. This enables mouse click, release, wheel, and motion events, regardless of whether a mouse button is pressed, effectively enabling support for hover interactions. ```APIDOC ## func WithMouseAllMotion ### Description Starts the program with the mouse enabled in "all motion" mode. EnableMouseAllMotion is a special command that enables mouse click, release, wheel, and motion events, which are delivered regardless of whether a mouse button is pressed, effectively enabling support for hover interactions. This will try to enable the mouse in extended mode (SGR), if that is not supported by the terminal it will fall back to normal mode (X10). Many modern terminals support this, but not all. If in doubt, use EnableMouseCellMotion instead. To enable the mouse once the program has already started running use the EnableMouseAllMotion command. To disable the mouse when the program is running use the DisableMouse command. The mouse will be automatically disabled when the program exits. ### Method N/A (ProgramOption configuration function) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Program.RestoreTerminal Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Restores the terminal to its state before the program started. ```APIDOC ## func (p *Program) RestoreTerminal() error ### Description Restores the terminal to its state before the program started. ### Returns - **error** - An error if the terminal could not be restored. ``` -------------------------------- ### Send Message to Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sends a message to the main update function for external injection. Blocks if the program hasn't started; no-op if terminated. ```go func (p *Program) Send(msg Msg) ``` -------------------------------- ### WithContext Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Lets you specify a context in which to run the Program. This is useful if you want to cancel the execution from outside. When a Program gets cancelled it will exit with an error ErrProgramKilled. ```APIDOC ## func WithContext ### Description Lets you specify a context in which to run the Program. This is useful if you want to cancel the execution from outside. When a Program gets cancelled it will exit with an error ErrProgramKilled. ### Method N/A (ProgramOption configuration function) ### Endpoint N/A ### Parameters - **ctx** (context.Context) - Required - The context to run the program with. ### Request Example N/A ### Response N/A ``` -------------------------------- ### WindowSize Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Queries the terminal for its current size, delivering the results via a WindowSizeMsg. WindowSizeMsgs are automatically delivered on Program start and when window dimensions change, so explicit invocation is often unnecessary. ```APIDOC ## WindowSize ### Description Queries the terminal for its current size, delivering the results via a WindowSizeMsg. WindowSizeMsgs are automatically delivered on Program start and when window dimensions change, so explicit invocation is often unnecessary. ### Function Signature ``` func WindowSize() Cmd ``` ``` -------------------------------- ### Disable Bracketed Paste - Bubble Tea Option Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the program with bracketed paste mode disabled. ```go func WithoutBracketedPaste() ProgramOption ``` -------------------------------- ### Enable Mouse Cell Motion - Bubble Tea Option Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Starts the program with mouse events enabled in cell motion mode. This mode supports click, release, and wheel events, and drag events. It attempts to use SGR mode and falls back to X10 mode if unsupported. ```go func WithMouseCellMotion() ProgramOption ``` -------------------------------- ### Program.Send Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sends a message to the main update function for interoperability. Blocks if the program hasn't started; is a no-op if terminated. ```APIDOC ## Program.Send ### Description Sends a message to the main update function, effectively allowing messages to be injected from outside the program for interoperability purposes. If the program hasn't started yet this will be a blocking operation. If the program has already been terminated this will be a no-op, so it's safe to send messages after the program has exited. ### Parameters - **msg** (Msg) - The message to send. ### Method Signature ``` func (p *Program) Send(msg Msg) ``` ``` -------------------------------- ### Debugging Bubble Tea with Delve Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea These shell commands demonstrate how to start the Delve debugger in headless mode and connect to it from another terminal for debugging Bubble Tea applications. ```shell # Start the debugger $ dlv debug --headless --api-version=2 --listen=127.0.0.1:43000 . API server listening at: 127.0.0.1:43000 # Connect to it from another terminal $ dlv connect 127.0.0.1:43000 ``` -------------------------------- ### Log to File in Bubble Tea Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Include this code before starting your Bubble Tea program to log debug information to a file named 'debug.log'. Ensure the DEBUG environment variable is set to enable logging. ```go if len(os.Getenv("DEBUG")) > 0 { f, err := tea.LogToFile("debug.log", "debug") if err != nil { fmt.Println("fatal:", err) os.Exit(1) } defer f.Close() } ``` -------------------------------- ### Log to File with Default Options Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sets up default logging to a file. The file will be created if it doesn't exist. Remember to close the file when done. ```go f, err := LogToFile("debug.log", "debug") if err != nil { fmt.Println("fatal:", err) os.Exit(1) } defer f.Close() ``` -------------------------------- ### LogToFile Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sets up default logging to a file. Creates the file if it doesn't exist. Remember to close the file when done. ```APIDOC ## func LogToFile ### Description Sets up default logging to a file. This is helpful as we can't print to the terminal since our TUI is occupying it. If the file doesn't exist it will be created. ### Function Signature ```go func LogToFile(path string, prefix string) (*os.File, error) ``` ### Parameters #### Path Parameters - **path** (string) - The path to the log file. - **prefix** (string) - The prefix for log messages. ### Returns - **(*os.File, error)** - A pointer to the opened log file and an error if any occurred. ### Example ```go f, err := LogToFile("debug.log", "debug") if err != nil { fmt.Println("fatal:", err) os.Exit(1) } defer f.Close() ``` ``` -------------------------------- ### Bubble Tea Init Method (No Command) Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Implements the Init method for the Bubble Tea model. Returns nil, indicating no initial I/O command is needed. ```go func (m model) Init() tea.Cmd { // Just return `nil`, which means "no I/O right now, please." return nil } ``` -------------------------------- ### Program.StartReturningModel Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Initializes and runs the program's event loops, blocking until termination. Returns the final model. Deprecated: Use Program.Run instead. ```APIDOC ## Program.StartReturningModel ### Description Initializes the program and runs its event loops, blocking until it gets terminated by either Program.Quit, Program.Kill, or its signal handler. Returns the final model. ### Deprecated please use Program.Run instead. ### Returns - **Model**: The final model of the program. - **error**: An error if the program terminated with an error. ### Method Signature ``` func (p *Program) StartReturningModel() (Model, error) ``` ``` -------------------------------- ### Create New Bubble Tea Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Initializes a new Bubble Tea Program with a given model and optional program options. ```go func NewProgram(model Model, opts ...ProgramOption) *Program ``` -------------------------------- ### ProgramOption.WithEnvironment Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Configures the program with a specific environment. ```APIDOC ## func ProgramOption.WithEnvironment(env []string) ProgramOption ### Description Configures the program with a specific environment. ### Parameters #### Path Parameters - **env** ([]string) - Required - The environment variables to set. ### Returns - **ProgramOption** - The option to set the environment. ``` -------------------------------- ### LogToFileWith Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Logs all output to a specified file with a given prefix and custom log options. Returns the file handle and any error encountered. ```APIDOC ## func LogToFileWith(path string, prefix string, log LogOptionsSetter) (*os.File, error) ### Description Logs all output to a specified file with a given prefix and custom log options. Returns the file handle and any error encountered. ### Parameters #### Path Parameters - **path** (string) - Required - The file path for logging. - **prefix** (string) - Required - The prefix for log entries. - **log** (LogOptionsSetter) - Required - Custom options for logging. ### Returns - **(*os.File, error)** - The opened log file and any error that occurred. ``` -------------------------------- ### Suspend Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Tells the Bubble Tea program to suspend. This command can be used to temporarily pause the program's execution, for example, to allow the user to interact with the underlying terminal. ```APIDOC ## Suspend ### Description Suspends the Bubble Tea program. This command tells the Bubble Tea program to suspend. ### Method Command ### Endpoint N/A ### Parameters None ### Request Example ```go Msg = Suspend() ``` ### Response #### Success Response - **Msg**: A message type indicating the command to suspend the program. ``` -------------------------------- ### Program.Println Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints above the Program. This output is unmanaged and persists across renders. It does not output if the altscreen is active. ```APIDOC ## Program.Println ### Description Prints above the Program. This output is unmanaged by the program and will persist across renders by the Program. If the altscreen is active no output will be printed. ### Method Signature ``` func (p *Program) Println(args ...interface{}) ``` ``` -------------------------------- ### ProgramOption.WithContext Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Configures the program with a specific context. ```APIDOC ## func ProgramOption.WithContext(ctx context.Context) ProgramOption ### Description Configures the program with a specific context. ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - The context to use. ### Returns - **ProgramOption** - The option to set the context. ``` -------------------------------- ### Every Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command that ticks in sync with the system clock at a specified interval. Useful for periodic actions. ```APIDOC ## func Every ### Description Creates a command that ticks in sync with the system clock. If you want to tick every second, minute, or hour, you can use this. It's also handy for having different things tick in sync. Because we're ticking with the system clock the tick will likely not run for the entire specified duration. For example, if we're ticking for one minute and the clock is at 12:34:20 then the next tick will happen at 12:35:00, 40 seconds later. ### Function Signature ```go func Every(duration time.Duration, fn func(time.Time) Msg) Cmd ``` ### Parameters #### Path Parameters - **duration** (time.Duration) - The interval for the ticks. - **fn** (func(time.Time) Msg) - A function that returns a message containing the time at which the tick occurred. ### Returns - **Cmd** - A command that triggers ticks at the specified interval. ### Example ```go type TickMsg time.Time cmd := Every(time.Second, func(t time.Time) Msg { return TickMsg(t) }) ``` ### Note Every sends a single message and won't automatically dispatch messages at an interval. To do that, you'll want to return another Every command after receiving your tick message. For example: ```go type TickMsg time.Time // Send a message every second. func tickEvery() Cmd { return Every(time.Second, func(t time.Time) Msg { return TickMsg(t) }) } func (m model) Init() Cmd { // Start ticking. return tickEvery() } func (m model) Update(msg Msg) (Model, Cmd) { switch msg.(type) { case TickMsg: // Return your Every command again to loop. return m, tickEvery() } return m, nil } ``` Every is analogous to Tick in the Elm Architecture. ``` -------------------------------- ### Program.Start Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Initializes and runs the program's event loops, blocking until termination. Deprecated: Use Program.Run instead. ```APIDOC ## Program.Start ### Description Initializes the program and runs its event loops, blocking until it gets terminated by either Program.Quit, Program.Kill, or its signal handler. ### Deprecated please use Program.Run instead. ### Returns An error if the program failed to start or run. ### Method Signature ``` func (p *Program) Start() error ``` ``` -------------------------------- ### Show Cursor Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Manually instructs Bubble Tea to show the cursor. ```go func ShowCursor() Msg ``` -------------------------------- ### WithFilter Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Supplies an event filter that will be invoked before Bubble Tea processes a tea.Msg. The event filter can return any tea.Msg which will then get handled by Bubble Tea instead of the original event. If the event filter returns nil, the event will be ignored and Bubble Tea will not process it. ```APIDOC ## func WithFilter ### Description Supplies an event filter that will be invoked before Bubble Tea processes a tea.Msg. The event filter can return any tea.Msg which will then get handled by Bubble Tea instead of the original event. If the event filter returns nil, the event will be ignored and Bubble Tea will not process it. ### Method N/A (ProgramOption configuration function) ### Endpoint N/A ### Parameters - **filter** (func(Model, Msg) Msg) - Required - The event filter function. ### Request Example ```go func filter(m tea.Model, msg tea.Msg) tea.Msg { if _, ok := msg.(tea.QuitMsg); !ok { return msg } model := m.(myModel) if model.hasChanges { return nil } return msg } p := tea.NewProgram(Model{}, tea.WithFilter(filter)); if _,err := p.Run(); err != nil { fmt.Println("Error running program:", err) os.Exit(1) } ``` ### Response N/A ``` -------------------------------- ### ProgramOption.WithAltScreen Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Configures the program to use an alternate screen buffer. ```APIDOC ## func ProgramOption.WithAltScreen() ProgramOption ### Description Configures the program to use an alternate screen buffer. ### Returns - **ProgramOption** - The option to use an alternate screen. ``` -------------------------------- ### Execute Commands Sequentially (Deprecated) Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sequentially executes commands in order and returns the first non-nil message. Use Sequence instead. ```go func Sequentially(cmds ...Cmd) Cmd ``` ```go func saveStateCmd() Msg { if err := save(); err != nil { return errMsg{err} } return nil } cmd := Sequentially(saveStateCmd, Quit) ``` -------------------------------- ### Print Output Above Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints output above the Program, persisting across renders. Output is unmanaged. No output if altscreen is active. ```go func (p *Program) Println(args ...interface{}) ``` -------------------------------- ### Execute Commands Sequentially Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sequence runs multiple commands one after another in the order they are provided. This is useful for tasks that must be performed in a specific order. ```go func Sequence(cmds ...Cmd) Cmd ``` -------------------------------- ### Run Bubble Tea Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Initializes and runs the program's event loops, blocking until termination. Returns the final model. ```go func (p *Program) Run() (returnModel Model, returnErr error) ``` -------------------------------- ### Program.Println Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints arguments to the terminal. ```APIDOC ## func (p *Program) Println(args ...interface{}) ### Description Prints arguments to the terminal. ### Parameters #### Path Parameters - **args** (...interface{}) - Required - The arguments to print. ``` -------------------------------- ### Cmd.Println Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command that prints arguments to the terminal. ```APIDOC ## func (Cmd) Println(args ...interface{}) Cmd ### Description Creates a command that prints arguments to the terminal. ### Parameters #### Path Parameters - **args** (...interface{}) - Required - The arguments to print. ### Returns - **Cmd** - A command that prints the provided arguments. ``` -------------------------------- ### NewProgram Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a new Bubble Tea Program instance. This is the entry point for initializing and running a Bubble Tea application. ```APIDOC ## NewProgram ### Description Creates a new Program instance. This function creates a new Program with the given model and program options. ### Method Constructor ### Endpoint N/A ### Parameters - **model** (Model) - Required - The initial model for the program. - **opts** (...ProgramOption) - Optional - A variadic list of program options to configure the program. ### Request Example ```go program := NewProgram(myModel, WithAltScreen(), WithMouseAllMotion()) ``` ### Response #### Success Response - **(*Program)**: A pointer to the newly created Program instance. ``` -------------------------------- ### Running a Bubble Tea Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea This Go function initializes and runs a Bubble Tea program with a given initial model. It handles potential errors during program execution. ```go func main() { p := tea.NewProgram(initialModel()) if _, err := p.Run(); err != nil { fmt.Printf("Alas, there's been an error: %v", err) os.Exit(1) } } ``` -------------------------------- ### Cmd.Every Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command that executes a function at a regular interval. ```APIDOC ## func (Cmd) Every(duration time.Duration, fn func(time.Time) Msg) Cmd ### Description Creates a command that executes a function at a regular interval. ### Parameters #### Path Parameters - **duration** (time.Duration) - Required - The interval duration. - **fn** (func(time.Time) Msg) - Required - The function to execute at each interval. ### Returns - **Cmd** - A command that triggers the function periodically. ``` -------------------------------- ### Looping Periodic Command Execution Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Demonstrates how to create a continuously ticking command that dispatches messages at a set interval. This is achieved by returning the 'Every' command again after receiving a tick message. ```go type TickMsg time.Time // Send a message every second. func tickEvery() Cmd { return Every(time.Second, func(t time.Time) Msg { return TickMsg(t) }) } func (m model) Init() Cmd { // Start ticking. return tickEvery() } func (m model) Update(msg Msg) (Model, Cmd) { switch msg.(type) { case TickMsg: // Return your Every command again to loop. return m, tickEvery() } return m, nil } ``` -------------------------------- ### Print Formatted Output Above Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints formatted output above the Program, persisting across renders. Output is unmanaged and appears on its own line. No output if altscreen is active. ```go func (p *Program) Printf(template string, args ...interface{}) ``` -------------------------------- ### Enter Alternate Screen Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea This command tells the Bubble Tea program to enter the alternate screen buffer. Use the WithAltScreen ProgramOption for initialization. ```go func EnterAltScreen() Msg ``` -------------------------------- ### ProgramOption.WithFPS Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Configures the program's target frames per second. ```APIDOC ## func ProgramOption.WithFPS(fps int) ProgramOption ### Description Configures the program's target frames per second. ### Parameters #### Path Parameters - **fps** (int) - Required - The target FPS. ### Returns - **ProgramOption** - The option to set the FPS. ``` -------------------------------- ### Cmd.Sequence Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command that executes multiple commands in sequence. ```APIDOC ## func (Cmd) Sequence(cmds ...Cmd) Cmd ### Description Creates a command that executes multiple commands in sequence. ### Parameters #### Path Parameters - **cmds** (...Cmd) - Required - A variadic list of commands to execute. ### Returns - **Cmd** - A command that runs the provided commands sequentially. ``` -------------------------------- ### Set Window Title Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sets the terminal window title. Use the SetWindowTitle command instead. ```go func (p *Program) SetWindowTitle(title string) ``` -------------------------------- ### Program.NewProgram Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a new Bubble Tea program. ```APIDOC ## func Program.NewProgram(model Model, opts ...ProgramOption) *Program ### Description Creates a new Bubble Tea program. ### Parameters #### Path Parameters - **model** (Model) - Required - The initial model for the program. - **opts** (...ProgramOption) - Optional - Options to configure the program. ### Returns - **(*Program)** - A pointer to the newly created program. ``` -------------------------------- ### Cmd.WindowSize Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command to retrieve the current terminal window size. ```APIDOC ## func (Cmd) WindowSize() Cmd ### Description Creates a command to retrieve the current terminal window size. ### Returns - **Cmd** - A command that requests the window size. ``` -------------------------------- ### Print to Terminal Above Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Use Println to display unmanaged output above the program's rendering area. This output persists across renders and is not affected by the program's state. It will not print if the altscreen is active. ```go func Println(args ...interface{}) Cmd ``` -------------------------------- ### Program.Printf Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints above the Program using a format template, similar to fmt.Printf. This output is unmanaged and persists across renders. It prints on its own line and does not output if the altscreen is active. ```APIDOC ## Program.Printf ### Description Prints above the Program. It takes a format template followed by values similar to fmt.Printf. This output is unmanaged by the program and will persist across renders by the Program. Unlike fmt.Printf (but similar to log.Printf) the message will be print on its own line. If the altscreen is active no output will be printed. ### Method Signature ``` func (p *Program) Printf(template string, args ...interface{}) ``` ``` -------------------------------- ### Open TTY for Input Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Opens a new TTY for input, which corresponds to the console input device on Windows. ```go func WithInputTTY() ProgramOption ``` -------------------------------- ### Bubble Tea View Method Implementation Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea This Go function renders the application's user interface as a string based on the current state of the model. It displays a list of choices with indicators for the cursor position and selection status. ```go func (m model) View() string { // The header s := "What should we buy at the market?\n\n" // Iterate over our choices for i, choice := range m.choices { // Is the cursor pointing at this choice? cursor := " " // no cursor if m.cursor == i { cursor = ">" // cursor! } // Is this choice selected? checked := " " // not selected if _, ok := m.selected[i]; ok { checked = "x" // selected! } // Render the row s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice) } // The footer s += "\nPress q to quit.\n" // Send the UI for rendering return s } ``` -------------------------------- ### Program.Run Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Initializes and runs the program's event loops, blocking until termination. Returns the final model. ```APIDOC ## Program.Run ### Description Initializes the program and runs its event loops, blocking until it gets terminated by either Program.Quit, Program.Kill, or its signal handler. Returns the final model. ### Returns - **Model**: The final model of the program. - **error**: An error if the program terminated with an error. ### Method Signature ``` func (p *Program) Run() (returnModel Model, returnErr error) ``` ``` -------------------------------- ### Enter Alternate Screen Buffer Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Enters the alternate screen buffer, consuming the entire terminal. Use WithAltScreen ProgramOption instead. ```go func (p *Program) EnterAltScreen() ``` -------------------------------- ### Program.Run Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Runs the Bubble Tea program until it quits. ```APIDOC ## func (p *Program) Run() (returnModel Model, returnErr error) ### Description Runs the Bubble Tea program until it quits. ### Returns - **(Model, error)** - The final model and any error encountered during execution. ``` -------------------------------- ### Println Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints unmanaged output above the Program. This output persists across renders and appears on its own line. It does not print if the alt-screen is active. ```APIDOC ## Println ### Description Prints unmanaged output above the Program. This output persists across renders and appears on its own line. It does not print if the alt-screen is active. ### Function Signature ``` func Println(args ...interface{}) Cmd ``` ``` -------------------------------- ### ShowCursor Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Manually instructs Bubble Tea to show the cursor. This command can be used if the cursor was hidden and needs to be made visible again during program execution. ```APIDOC ## ShowCursor ### Description Shows the cursor. This is a special command for manually instructing Bubble Tea to show the cursor. ### Method Command ### Endpoint N/A ### Parameters None ### Request Example ```go Msg = ShowCursor() ``` ### Response #### Success Response - **Msg**: A message type indicating the command to show the cursor. ``` -------------------------------- ### Cmd.Exec Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command to execute an external process and receive callbacks. ```APIDOC ## func (Cmd) Exec(c ExecCommand, fn ExecCallback) Cmd ### Description Creates a command to execute an external process and receive callbacks. ### Parameters #### Path Parameters - **c** (ExecCommand) - Required - The command to execute. - **fn** (ExecCallback) - Required - The callback function to handle process output and events. ### Returns - **Cmd** - A command that executes the external process. ``` -------------------------------- ### LogToFile Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Logs all output to a specified file with a given prefix. Returns the file handle and any error encountered. ```APIDOC ## func LogToFile(path string, prefix string) (*os.File, error) ### Description Logs all output to a specified file with a given prefix. Returns the file handle and any error encountered. ### Parameters #### Path Parameters - **path** (string) - Required - The file path for logging. - **prefix** (string) - Required - The prefix for log entries. ### Returns - **(*os.File, error)** - The opened log file and any error that occurred. ``` -------------------------------- ### Specify Program Context Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Lets you specify a context to run the Program in, useful for cancelling execution from outside. A cancelled program exits with ErrProgramKilled. ```go func WithContext(ctx context.Context) ProgramOption ``` -------------------------------- ### Sequence Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Runs the given commands one at a time, in order. This contrasts with Batch, which runs commands concurrently. ```APIDOC ## Sequence ### Description Runs the given commands one at a time, in order. This contrasts with Batch, which runs commands concurrently. ### Function Signature ``` func Sequence(cmds ...Cmd) Cmd ``` ``` -------------------------------- ### Execute a Command Periodically with System Clock Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command that ticks in sync with the system clock at a specified interval. The actual tick may not run for the exact duration due to clock synchronization. Use this for periodic tasks that need to align with system time. ```go type TickMsg time.Time cmd := Every(time.Second, func(t time.Time) Msg { return TickMsg(t) }) ``` -------------------------------- ### LogToFileWith Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Allows logging to a file with a custom LogOptionsSetter. ```APIDOC ## func LogToFileWith ### Description Allows logging to a file with a custom LogOptionsSetter. This function is available from v0.24.0 onwards. ### Function Signature ```go func LogToFileWith(path string, prefix string, log LogOptionsSetter) (*os.File, error) ``` ### Parameters #### Path Parameters - **path** (string) - The path to the log file. - **prefix** (string) - The prefix for log messages. - **log** (LogOptionsSetter) - A custom setter for log options. ### Returns - **(*os.File, error)** - A pointer to the opened log file and an error if any occurred. ``` -------------------------------- ### Enable Focus Reporting Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Use this command to enable the reporting of focus events to the Bubble Tea program. ```go func EnableReportFocus() Msg ``` -------------------------------- ### Print Output Above Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints formatted text above the main program output. This output is unmanaged by the program and persists across renders. It will not print if the alternate screen is active. ```go Printf("Processing item %d...", itemID) ``` -------------------------------- ### ProgramOption.WithInput Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Configures the program's input source. ```APIDOC ## func ProgramOption.WithInput(input io.Reader) ProgramOption ### Description Configures the program's input source. ### Parameters #### Path Parameters - **input** (io.Reader) - Required - The input reader. ### Returns - **ProgramOption** - The option to set the input source. ``` -------------------------------- ### Bubble Tea Package Import Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Imports the Bubble Tea library for use in a Go program. Ensure you run `go mod tidy` to download dependencies. ```go package main // These imports will be used later on the tutorial. If you save the file // now, Go might complain they are unused, but that's fine. // You may also need to run `go mod tidy` to download bubbletea and its // dependencies. import ( "fmt" "os" tea "github.com/charmbracelet/bubbletea" ) ``` -------------------------------- ### Cmd.Printf Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command that prints formatted output to the terminal. ```APIDOC ## func (Cmd) Printf(template string, args ...interface{}) Cmd ### Description Creates a command that prints formatted output to the terminal. ### Parameters #### Path Parameters - **template** (string) - Required - The format string. - **args** (...interface{}) - Optional - Arguments for the format string. ### Returns - **Cmd** - A command that prints formatted output. ``` -------------------------------- ### WithFPS Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sets a custom maximum FPS at which the renderer should run. If less than 1, the default value of 60 will be used. If over 120, the FPS will be capped at 120. ```APIDOC ## func WithFPS ### Description Sets a custom maximum FPS at which the renderer should run. If less than 1, the default value of 60 will be used. If over 120, the FPS will be capped at 120. ### Method N/A (ProgramOption configuration function) ### Endpoint N/A ### Parameters - **fps** (int) - Required - The desired maximum frames per second. ### Request Example N/A ### Response N/A ``` -------------------------------- ### ProgramOption.WithReportFocus Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Enables reporting of focus events. ```APIDOC ## func ProgramOption.WithReportFocus() ProgramOption ### Description Enables reporting of focus events. ### Returns - **ProgramOption** - The option to enable focus reporting. ``` -------------------------------- ### Printf Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints output above the Program. Takes a format template and arguments similar to fmt.Printf. This output is unmanaged by the program and will persist across renders. ```APIDOC ## func Printf ### Description Printf prints above the Program. It takes a format template followed by values similar to fmt.Printf. This output is unmanaged by the program and will persist across renders by the Program. Unlike fmt.Printf (but similar to log.Printf) the message will be print on its own line. If the altscreen is active no output will be printed. This function is available from v0.22.0 onwards. ### Function Signature ```go func Printf(template string, args ...interface{}) Cmd ``` ### Parameters #### Path Parameters - **template** (string) - The format template string. - **args** (...interface{}) - The arguments to format. ### Returns - **Cmd** - A command that prints the formatted string. ``` -------------------------------- ### MouseMsg String Method Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Returns a string representation of a MouseMsg. ```go func (m MouseMsg) String() string ``` -------------------------------- ### ProgramOption.WithMouseAllMotion Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Enables reporting of all mouse motion events. ```APIDOC ## func ProgramOption.WithMouseAllMotion() ProgramOption ### Description Enables reporting of all mouse motion events. ### Returns - **ProgramOption** - The option to enable all mouse motion events. ``` -------------------------------- ### Cmd.Sequentially Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command that executes multiple commands sequentially. Deprecated. ```APIDOC ## func (Cmd) Sequentially(cmds ...Cmd) Cmd ### Description Creates a command that executes multiple commands sequentially. Deprecated. ### Parameters #### Path Parameters - **cmds** (...Cmd) - Required - A variadic list of commands to execute. ### Returns - **Cmd** - A command that runs the provided commands sequentially. ``` -------------------------------- ### ClearScreen Command Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea A command to clear the screen before the next update. Use for clearing clutter when the alt screen is not in use; not for regular redraws. ```go func ClearScreen() Msg ``` -------------------------------- ### WithInputTTY Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Opens a new TTY for input (or console input device on Windows). ```APIDOC ## func WithInputTTY ### Description Opens a new TTY for input (or console input device on Windows). ### Method N/A (ProgramOption configuration function) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Execute External Process and Handle Completion Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Runs an external command (like 'vim') in a blocking fashion, pausing the program until completion. It allows you to specify a callback function to handle the result or error after the process finishes. ```go type VimFinishedMsg struct { err error } c := exec.Command("vim", "file.txt") cmd := ExecProcess(c, func(err error) Msg { return VimFinishedMsg{err: err} }) ``` -------------------------------- ### Set Program Output - Bubble Tea Option Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sets the output writer for the program. Defaults to stdout. Typically not needed unless redirecting output. ```go func WithOutput(output io.Writer) ProgramOption ``` -------------------------------- ### Cmd.ExecProcess Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command to execute an external process from an exec.Cmd and receive callbacks. ```APIDOC ## func (Cmd) ExecProcess(c *exec.Cmd, fn ExecCallback) Cmd ### Description Creates a command to execute an external process from an exec.Cmd and receive callbacks. ### Parameters #### Path Parameters - **c** (*exec.Cmd) - Required - The exec.Cmd to execute. - **fn** (ExecCallback) - Required - The callback function to handle process output and events. ### Returns - **Cmd** - A command that executes the external process. ``` -------------------------------- ### Bubble Tea Update Method Implementation Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea This Go function handles incoming messages, such as key presses, to update the application's model. It supports quitting the application, moving a cursor, and toggling selection states for list items. ```go func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { // Is it a key press? case tea.KeyMsg: // Cool, what was the actual key pressed? switch msg.String() { // These keys should exit the program. case "ctrl+c", "q": return m, tea.Quit // The "up" and "k" keys move the cursor up case "up", "k": if m.cursor > 0 { m.cursor-- } // The "down" and "j" keys move the cursor down case "down", "j": if m.cursor < len(m.choices)-1 { m.cursor++ } // The "enter" key and the spacebar (a literal space) toggle // the selected state for the item that the cursor is pointing at. case "enter", " ": _, ok := m.selected[m.cursor] if ok { delete(m.selected, m.cursor) } else { m.selected[m.cursor] = struct{}{} } } } // Return the updated model to the Bubble Tea runtime for processing. // Note that we're not returning a command. return m, nil } ``` -------------------------------- ### WithEnvironment Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sets the environment variables that the program will use. This is useful when the program is running in a remote session (e.g. SSH) and you want to pass the environment variables from the remote session to the program. ```APIDOC ## func WithEnvironment ### Description Sets the environment variables that the program will use. This useful when the program is running in a remote session (e.g. SSH) and you want to pass the environment variables from the remote session to the program. ### Method N/A (ProgramOption configuration function) ### Endpoint N/A ### Parameters - **env** ([]string) - Required - A slice of strings representing environment variables. ### Request Example ```go var sess ssh.Session // ssh.Session is a type from the github.com/charmbracelet/ssh package pty, _, _ := sess.Pty() equals := append(sess.Environ(), "TERM="+pty.Term) p := tea.NewProgram(model, tea.WithEnvironment(environ)) ``` ### Response N/A ``` -------------------------------- ### Enable All Mouse Events Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Enables mouse click, release, wheel, and motion events for hover interactions. Not all terminals support this; consider EnableMouseCellMotion if in doubt. Do not use in Init; use WithMouseAllMotion ProgramOption instead. ```go func EnableMouseAllMotion() Msg ``` -------------------------------- ### Quit Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sends a command to exit the Bubble Tea program. ```go func Quit() Msg ``` -------------------------------- ### ProgramOption.WithInputTTY Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Configures the program to use the TTY as its input source. ```APIDOC ## func ProgramOption.WithInputTTY() ProgramOption ### Description Configures the program to use the TTY as its input source. ### Returns - **ProgramOption** - The option to use TTY input. ``` -------------------------------- ### Suspend Program Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Sends a command to suspend the Bubble Tea program. ```go func Suspend() Msg ``` -------------------------------- ### Query Terminal Window Size Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea WindowSize is a command that retrieves the current dimensions of the terminal. The results are delivered as a WindowSizeMsg. This command is often implicitly handled by the framework on startup and resize. ```go func WindowSize() Cmd ``` -------------------------------- ### Program.EnterAltScreen Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Enters the alternate screen buffer, consuming the entire terminal window. Deprecated: Use the WithAltScreen ProgramOption instead. ```APIDOC ## Program.EnterAltScreen ### Description Enters the alternate screen buffer, which consumes the entire terminal window. ExitAltScreen will return the terminal to its former state. ### Deprecated Use the WithAltScreen ProgramOption instead. ### Method Signature ``` func (p *Program) EnterAltScreen() ``` ``` -------------------------------- ### Immediately Stop Program Execution Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Signals the program to stop immediately and restore the terminal state, skipping the final render. Returns ErrProgramKilled. ```go func (p *Program) Kill() ``` -------------------------------- ### Msg.ShowCursor Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Returns a message to show the cursor. ```APIDOC ## func Msg.ShowCursor() Msg ### Description Returns a message to show the cursor. ### Returns - **Msg** - The message to show the cursor. ``` -------------------------------- ### Cmd.Batch Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Creates a command that executes multiple commands in parallel. ```APIDOC ## func (Cmd) Batch(cmds ...Cmd) Cmd ### Description Creates a command that executes multiple commands in parallel. ### Parameters #### Path Parameters - **cmds** (...Cmd) - Required - A variadic list of commands to execute. ### Returns - **Cmd** - A command that runs the provided commands concurrently. ``` -------------------------------- ### ProgramOption.WithMouseCellMotion Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Enables reporting of mouse motion events within cells. ```APIDOC ## func ProgramOption.WithMouseCellMotion() ProgramOption ### Description Enables reporting of mouse motion events within cells. ### Returns - **ProgramOption** - The option to enable cell motion mouse events. ``` -------------------------------- ### Program.Printf Source: https://pkg.go.dev/github.com/charmbracelet/bubbletea Prints formatted output to the terminal. ```APIDOC ## func (p *Program) Printf(template string, args ...interface{}) ### Description Prints formatted output to the terminal. ### Parameters #### Path Parameters - **template** (string) - Required - The format string. - **args** (...interface{}) - Optional - Arguments for the format string. ```