Last active
August 25, 2022 20:42
-
-
Save bashbunni/e3306e8633512d8134012028288212db to your computer and use it in GitHub Desktop.
Exec example but using WithAltScreen() prints output to outside of the altscreen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"os/exec" | |
tea "github.com/charmbracelet/bubbletea" | |
) | |
type editorFinishedMsg struct{ err error } | |
func openEditor() tea.Cmd { | |
editor := os.Getenv("EDITOR") | |
if editor == "" { | |
editor = "vim" | |
} | |
c := exec.Command(editor) //nolint:gosec | |
return tea.ExecProcess(c, func(err error) tea.Msg { | |
return editorFinishedMsg{err} | |
}) | |
} | |
type model struct { | |
altscreenActive bool | |
err error | |
quitting bool | |
} | |
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.KeyMsg: | |
switch msg.String() { | |
case "a": | |
m.altscreenActive = !m.altscreenActive | |
cmd := tea.EnterAltScreen | |
if !m.altscreenActive { | |
cmd = tea.ExitAltScreen | |
} | |
return m, cmd | |
case "e": | |
// temporarily releasing the terminal to open the editor | |
m.quitting = true | |
return m, openEditor() | |
case "ctrl+c", "q": | |
m.quitting = true | |
return m, tea.Quit | |
} | |
case editorFinishedMsg: | |
m.quitting = false | |
if msg.err != nil { | |
m.err = msg.err | |
return m, tea.Quit | |
} | |
} | |
return m, nil | |
} | |
func (m model) View() string { | |
if m.err != nil { | |
return "Error: " + m.err.Error() + "\n" | |
} | |
if !m.quitting { | |
return "Press 'e' to open your EDITOR.\nPress 'a' to toggle the altscreen\nPress 'q' to quit.\n" | |
} | |
return "" | |
} | |
func main() { | |
m := model{altscreenActive: true} | |
p := tea.NewProgram(m, tea.WithAltScreen()) | |
if err := p.Start(); err != nil { | |
fmt.Println("Error running program:", err) | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment