Tutorials

Exec Commands

Run external commands and editors from your TUI.

Launch editors and external programs from your TUI!

The Code

package main

import (
    "os"
    "os/exec"
    tea "github.com/charmbracelet/bubbletea/v2"
)

type model struct {
    editing bool
}

type editorFinishedMsg struct{ err error }

func openEditor() tea.Cmd {
    editor := os.Getenv("EDITOR")
    if editor == "" {
        editor = "vim"
    }
    c := exec.Command(editor, "test.txt")
    return tea.ExecProcess(c, func(err error) tea.Msg {
        return editorFinishedMsg{err}
    })
}

func (m model) Init() tea.Cmd { return nil }

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
    switch msg := msg.(type) {
    case tea.KeyPressMsg:
        switch msg.String() {
        case "e":
            m.editing = true
            return m, openEditor()
        case "q":
            return m, tea.Quit
        }
    case editorFinishedMsg:
        m.editing = false
        if msg.err != nil {
            // Handle error
        }
    }
    return m, nil
}

func (m model) View() string {
    if m.editing {
        return "Editing..."
    }
    return "Press e to edit, q to quit"
}

func main() {
    tea.NewProgram(model{}).Run()
}

Key Function

tea.ExecProcess(cmd, func(err error) tea.Msg {
    return someMsg{err}
})

Suspends the TUI, runs the command, then resumes!