commit f881337da725ec7cd871b45a0da59a13f38cdf45
parent 82fcd306c8eec1e3ff359584a7f6324a1475721f
Author: Sivaldo Davi <sivaldo@sivaldodavi>
Date: Sun, 11 Oct 2026 18:38:53 -0300
feat(musicas): edita letras no Vim
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Diffstat:
4 files changed, 162 insertions(+), 70 deletions(-)
diff --git a/README.md b/README.md
@@ -45,8 +45,8 @@ Sobrescritas específicas: `CULTO_BIBLE_FILE`, `CULTO_MUSIC_FILE`, `CULTO_PIX_FI
- **↑/↓** navega; **/** filtra; **Enter** seleciona.
- **Esc** volta; **q** volta ou sai do menu inicial.
-- Na visualização, **p** projeta; em músicas, **e** edita.
-- No editor, **Ctrl+S** salva e **Esc** descarta.
+- Na visualização, **p** projeta; em músicas, **e** abre o Vim/Neovim.
+- No editor, use `:wq` para salvar e sair; `:q!` para descartar.
- **Ctrl+C** encerra a interface.
Na visualização de uma música, cada parte é identificada com o número do slide e o número da estrofe. Se houver uma capa automática (hinos e salmos), ela aparece como slide 01 e a primeira estrofe como slide 02. Esses rótulos são apenas informativos e não aparecem na projeção.
diff --git a/internal/app/app.go b/internal/app/app.go
@@ -6,7 +6,6 @@ import (
"culto/internal/culto"
"github.com/charmbracelet/bubbles/list"
- "github.com/charmbracelet/bubbles/textarea"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
@@ -19,7 +18,6 @@ const (
menuScreen screen = iota
inputScreen
previewScreen
- editorScreen
)
type menuItem struct {
@@ -48,7 +46,6 @@ type model struct {
preview viewport.Model
content string
editSong string
- textarea textarea.Model
status string
width int
height int
@@ -140,29 +137,17 @@ func (m *model) ask(prompt, action string) {
m.status = ""
}
-func (m *model) edit(title, content string) {
- m.editSong = title
- m.textarea = textarea.New()
- m.textarea.Placeholder = "Separe as estrofes com uma linha em branco."
- m.textarea.SetValue(content)
- m.textarea.Focus()
- m.textarea.SetWidth(max(20, m.width-6))
- m.textarea.SetHeight(max(5, m.height-9))
- m.screen = editorScreen
-}
-
func (m *model) Init() tea.Cmd { return textinput.Blink }
func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ if finished, ok := msg.(editorFinishedMsg); ok {
+ return m, m.finishEditor(finished)
+ }
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
m.menu.SetSize(msg.Width, max(1, msg.Height-6))
m.preview.Width, m.preview.Height = max(1, msg.Width-4), max(1, msg.Height-8)
- if m.screen == editorScreen {
- m.textarea.SetWidth(max(20, msg.Width-6))
- m.textarea.SetHeight(max(5, msg.Height-9))
- }
return m, nil
case tea.KeyMsg:
if msg.String() == "ctrl+c" {
@@ -176,8 +161,6 @@ func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m.updateInput(msg)
case previewScreen:
return m.updatePreview(msg)
- case editorScreen:
- return m.updateEditor(msg)
default:
return m, nil
}
@@ -341,7 +324,8 @@ func (m *model) updateInput(msg tea.Msg) (tea.Model, tea.Cmd) {
case "search":
m.searchBible(value)
case "song:new":
- m.edit(value, "")
+ m.editSong = value
+ return m, m.openEditor(value, nil)
}
return m, nil
}
@@ -411,8 +395,7 @@ func (m *model) updatePreview(msg tea.Msg) (tea.Model, tea.Cmd) {
}
for _, category := range songs {
if stanzas, ok := category[m.editSong]; ok {
- m.edit(m.editSong, strings.Join(stanzas, "\n\n"))
- return m, nil
+ return m, m.openEditor(m.editSong, stanzas)
}
}
}
@@ -423,30 +406,6 @@ func (m *model) updatePreview(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, cmd
}
-func (m *model) updateEditor(msg tea.Msg) (tea.Model, tea.Cmd) {
- if key, ok := msg.(tea.KeyMsg); ok {
- switch key.String() {
- case "esc":
- m.editSong = ""
- m.popMenu()
- return m, nil
- case "ctrl+s":
- if err := culto.SaveSong(m.config.MusicFile, m.editSong, m.textarea.Value()); err != nil {
- m.status = "Erro ao salvar: " + err.Error()
- return m, nil
- }
- title := m.editSong
- m.editSong = ""
- m.popMenu()
- m.status = fmt.Sprintf("Música %q salva.", title)
- return m, nil
- }
- }
- var cmd tea.Cmd
- m.textarea, cmd = m.textarea.Update(msg)
- return m, cmd
-}
-
func (m *model) View() string {
header := heading.Render("CULTO") + " " + muted.Render("liturgia e projeção")
var body string
@@ -457,8 +416,6 @@ func (m *model) View() string {
body = "\n" + m.inputPrompt + "\n\n" + m.input.View()
case previewScreen:
body = m.preview.View()
- case editorScreen:
- body = fmt.Sprintf("Editando: %s\n\n%s", m.editSong, m.textarea.View())
}
if m.status != "" {
body += "\n" + problem.Render(m.status)
@@ -475,8 +432,6 @@ func (m *model) help() string {
return "Enter confirmar · Esc cancelar"
case previewScreen:
return "↑/↓ rolar · p projetar · e editar música · Esc voltar"
- case editorScreen:
- return "Ctrl+S salvar · Esc descartar"
default:
return ""
}
diff --git a/internal/app/app_test.go b/internal/app/app_test.go
@@ -1,6 +1,8 @@
package app
import (
+ "os"
+ "path/filepath"
"strings"
"testing"
@@ -32,30 +34,60 @@ func TestMainMenuAndLiturgiaNavigation(t *testing.T) {
}
}
-func TestCreateSongThroughEditor(t *testing.T) {
- musicFile := t.TempDir() + "/musicas.json"
+func TestSongEditorContentKeepsLyricsAndRemovesOnlyItsTitle(t *testing.T) {
+ title := "Cântico de teste"
+ original := songEditorText(title, []string{"Primeira estrofe", "Segunda estrofe"})
+ want := "Primeira estrofe\n\nSegunda estrofe"
+ if got := songEditorLyrics(original, title); got != want {
+ t.Fatalf("letra extraída = %q, esperado %q", got, want)
+ }
+
+ content := "# Cântico de teste\n\n# Cabeçalho da estrofe\nletra"
+ if got := songEditorLyrics(content, title); got != "# Cabeçalho da estrofe\nletra" {
+ t.Fatalf("cabeçalho Markdown da letra foi removido: %q", got)
+ }
+}
+
+func TestSongEditorStartsWithTitleAndEmptyLyrics(t *testing.T) {
+ if got, want := songEditorText("Nova música", nil), "# Nova música\n\n"; got != want {
+ t.Fatalf("conteúdo inicial = %q, esperado %q", got, want)
+ }
+}
+
+func TestFinishEditorSavesLyricsAndReturnsToSongList(t *testing.T) {
+ title := "Cântico existente"
+ musicFile := filepath.Join(t.TempDir(), "musicas.json")
+ if err := culto.SaveSong(musicFile, title, "Letra antiga"); err != nil {
+ t.Fatal(err)
+ }
+
m := New(culto.Config{MusicFile: musicFile}).(*model)
- m.activate("songs")
- m.activate("song:add")
- if m.screen != inputScreen {
- t.Fatal("formulário de título não abriu")
- }
- m.input.SetValue("Hino novo")
- m.updateInput(tea.KeyMsg{Type: tea.KeyEnter})
- if m.screen != editorScreen {
- t.Fatal("editor da música não abriu")
- }
- m.textarea.SetValue("Primeira estrofe\n\nSegunda estrofe")
- m.updateEditor(tea.KeyMsg{Type: tea.KeyCtrlS})
+ m.openSongs()
+ m.openSong(title)
+
+ original := songEditorText(title, []string{"Letra antiga"})
+ edited := songEditorText(title, []string{"Primeira estrofe", "Segunda estrofe"})
+ editFile := filepath.Join(t.TempDir(), "culto.md")
+ if err := os.WriteFile(editFile, []byte(edited), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ m.finishEditor(editorFinishedMsg{
+ title: title, path: editFile, original: original,
+ })
+
if m.screen != menuScreen || m.menu.Title != "Músicas · Esc volta" {
- t.Fatal("após salvar, a aplicação não voltou à lista de músicas")
+ t.Fatal("após editar, a aplicação não voltou à lista de músicas")
}
songs, err := culto.LoadSongs(musicFile)
if err != nil {
t.Fatal(err)
}
- if len(songs["Cânticos Espirituais"]["Hino novo"]) != 2 {
- t.Fatalf("estrofes não salvas: %#v", songs)
+ if got := songs["Cânticos Espirituais"][title]; len(got) != 2 ||
+ got[0] != "Primeira estrofe" || got[1] != "Segunda estrofe" {
+ t.Fatalf("letra editada não foi salva: %#v", got)
+ }
+ if _, err := os.Stat(editFile); !os.IsNotExist(err) {
+ t.Fatal("arquivo temporário do editor não foi removido")
}
}
diff --git a/internal/app/editor.go b/internal/app/editor.go
@@ -0,0 +1,105 @@
+package app
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+
+ "culto/internal/culto"
+ tea "github.com/charmbracelet/bubbletea"
+)
+
+type editorFinishedMsg struct {
+ title string
+ path string
+ original string
+ err error
+}
+
+func (m *model) openEditor(title string, stanzas []string) tea.Cmd {
+ editor, err := findEditor()
+ if err != nil {
+ m.status = err.Error()
+ return nil
+ }
+
+ file, err := os.CreateTemp("", "culto-*.md")
+ if err != nil {
+ m.status = fmt.Sprintf("não foi possível criar o arquivo temporário: %v", err)
+ return nil
+ }
+ path := file.Name()
+ original := songEditorText(title, stanzas)
+ if _, err := file.WriteString(original); err != nil {
+ file.Close()
+ os.Remove(path)
+ m.status = fmt.Sprintf("não foi possível preparar a letra para edição: %v", err)
+ return nil
+ }
+ if err := file.Close(); err != nil {
+ os.Remove(path)
+ m.status = fmt.Sprintf("não foi possível fechar o arquivo temporário: %v", err)
+ return nil
+ }
+
+ cmd := exec.Command(editor, path)
+ return tea.ExecProcess(cmd, func(err error) tea.Msg {
+ return editorFinishedMsg{title: title, path: path, original: original, err: err}
+ })
+}
+
+func findEditor() (string, error) {
+ for _, name := range []string{"nvim", "vim"} {
+ if path, err := exec.LookPath(name); err == nil {
+ return path, nil
+ }
+ }
+ return "", fmt.Errorf("não encontrei o Vim nem o Neovim no PATH")
+}
+
+func (m *model) finishEditor(msg editorFinishedMsg) tea.Cmd {
+ defer os.Remove(msg.path)
+ if msg.err != nil {
+ m.status = fmt.Sprintf("o editor foi encerrado com erro: %v", msg.err)
+ return nil
+ }
+ content, err := os.ReadFile(msg.path)
+ if err != nil {
+ m.status = fmt.Sprintf("não foi possível ler a letra editada: %v", err)
+ return nil
+ }
+ if string(content) == msg.original {
+ m.editSong = ""
+ m.popMenu()
+ m.status = "Edição cancelada ou sem alterações."
+ return nil
+ }
+ if err := culto.SaveSong(m.config.MusicFile, msg.title, songEditorLyrics(string(content), msg.title)); err != nil {
+ m.status = fmt.Sprintf("erro ao salvar a música: %v", err)
+ return nil
+ }
+ m.editSong = ""
+ m.popMenu()
+ m.status = fmt.Sprintf("Música %q salva.", msg.title)
+ return nil
+}
+
+func songEditorText(title string, stanzas []string) string {
+ var body string
+ if len(stanzas) > 0 {
+ body = strings.Join(stanzas, "\n\n")
+ }
+ return "# " + title + "\n\n" + body
+}
+
+func songEditorLyrics(content, title string) string {
+ lines := strings.SplitN(strings.ReplaceAll(content, "\r\n", "\n"), "\n", 2)
+ if len(lines) == 0 || lines[0] != "# "+title {
+ return content
+ }
+ if len(lines) == 1 {
+ return ""
+ }
+ return strings.TrimLeft(lines[1], "\n")
+}