| 1 | package tui |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "os/exec" |
| 6 | |
| 7 | tea "charm.land/bubbletea/v2" |
| 8 | ) |
| 9 | |
| 10 | // SpawnEditor opens the user's $EDITOR on a temp file seeded with content. |
| 11 | // pattern is the os.CreateTemp pattern (e.g. "jotts-*.md"); empty falls back |
| 12 | // to a generic ".txt" pattern. tag is echoed in the resulting message so |
| 13 | // callers can correlate the result with the record being edited. |
| 14 | func SpawnEditor(tag, pattern, content string) tea.Cmd { |
| 15 | editor := os.Getenv("EDITOR") |
| 16 | if editor == "" { |
| 17 | return func() tea.Msg { |
| 18 | return StatusMsg{Text: "$EDITOR not set"} |
| 19 | } |
| 20 | } |
| 21 | if pattern == "" { |
| 22 | pattern = "editor-*.txt" |
| 23 | } |
| 24 | |
| 25 | tmp, err := os.CreateTemp("", pattern) |
| 26 | if err != nil { |
| 27 | return func() tea.Msg { |
| 28 | return StatusMsg{Text: "tempfile: " + err.Error()} |
| 29 | } |
| 30 | } |
| 31 | path := tmp.Name() |
| 32 | if _, err := tmp.WriteString(content); err != nil { |
| 33 | _ = tmp.Close() |
| 34 | _ = os.Remove(path) |
| 35 | return func() tea.Msg { |
| 36 | return StatusMsg{Text: "tempfile: " + err.Error()} |
| 37 | } |
| 38 | } |
| 39 | _ = tmp.Close() |
| 40 | |
| 41 | cmd := exec.Command(editor, path) |
| 42 | return tea.ExecProcess(cmd, func(err error) tea.Msg { |
| 43 | defer os.Remove(path) |
| 44 | if err != nil { |
| 45 | return EditorFinishedMsg{Tag: tag, Err: err} |
| 46 | } |
| 47 | b, rerr := os.ReadFile(path) |
| 48 | if rerr != nil { |
| 49 | return EditorFinishedMsg{Tag: tag, Err: rerr} |
| 50 | } |
| 51 | return EditorFinishedMsg{Tag: tag, Content: string(b)} |
| 52 | }) |
| 53 | } |