editor.go

  1package editor
  2
  3import (
  4	"fmt"
  5	"os"
  6	"os/exec"
  7	"runtime"
  8	"slices"
  9	"strings"
 10	"unicode"
 11
 12	"github.com/charmbracelet/bubbles/v2/key"
 13	"github.com/charmbracelet/bubbles/v2/textarea"
 14	tea "github.com/charmbracelet/bubbletea/v2"
 15	"github.com/charmbracelet/crush/internal/app"
 16	"github.com/charmbracelet/crush/internal/fsext"
 17	"github.com/charmbracelet/crush/internal/message"
 18	"github.com/charmbracelet/crush/internal/session"
 19	"github.com/charmbracelet/crush/internal/tui/components/chat"
 20	"github.com/charmbracelet/crush/internal/tui/components/completions"
 21	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 22	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 23	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 24	"github.com/charmbracelet/crush/internal/tui/styles"
 25	"github.com/charmbracelet/crush/internal/tui/util"
 26	"github.com/charmbracelet/lipgloss/v2"
 27)
 28
 29type FileCompletionItem struct {
 30	Path string // The file path
 31}
 32
 33type editorCmp struct {
 34	width       int
 35	height      int
 36	x, y        int
 37	app         *app.App
 38	session     session.Session
 39	textarea    textarea.Model
 40	attachments []message.Attachment
 41	deleteMode  bool
 42
 43	keyMap EditorKeyMap
 44
 45	// File path completions
 46	currentQuery          string
 47	completionsStartIndex int
 48	isCompletionsOpen     bool
 49}
 50
 51var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 52	AttachmentDeleteMode: key.NewBinding(
 53		key.WithKeys("ctrl+r"),
 54		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 55	),
 56	Escape: key.NewBinding(
 57		key.WithKeys("esc"),
 58		key.WithHelp("esc", "cancel delete mode"),
 59	),
 60	DeleteAllAttachments: key.NewBinding(
 61		key.WithKeys("r"),
 62		key.WithHelp("ctrl+r+r", "delete all attchments"),
 63	),
 64}
 65
 66const (
 67	maxAttachments = 5
 68)
 69
 70type openEditorMsg struct {
 71	Text string
 72}
 73
 74func (m *editorCmp) openEditor(value string) tea.Cmd {
 75	editor := os.Getenv("EDITOR")
 76	if editor == "" {
 77		// Use platform-appropriate default editor
 78		if runtime.GOOS == "windows" {
 79			editor = "notepad"
 80		} else {
 81			editor = "nvim"
 82		}
 83	}
 84
 85	tmpfile, err := os.CreateTemp("", "msg_*.md")
 86	if err != nil {
 87		return util.ReportError(err)
 88	}
 89	defer tmpfile.Close() //nolint:errcheck
 90	if _, err := tmpfile.WriteString(value); err != nil {
 91		return util.ReportError(err)
 92	}
 93	c := exec.Command(editor, tmpfile.Name())
 94	c.Stdin = os.Stdin
 95	c.Stdout = os.Stdout
 96	c.Stderr = os.Stderr
 97	return tea.ExecProcess(c, func(err error) tea.Msg {
 98		if err != nil {
 99			return util.ReportError(err)
100		}
101		content, err := os.ReadFile(tmpfile.Name())
102		if err != nil {
103			return util.ReportError(err)
104		}
105		if len(content) == 0 {
106			return util.ReportWarn("Message is empty")
107		}
108		os.Remove(tmpfile.Name())
109		return openEditorMsg{
110			Text: strings.TrimSpace(string(content)),
111		}
112	})
113}
114
115func (m *editorCmp) Init() tea.Cmd {
116	return nil
117}
118
119func (m *editorCmp) send() tea.Cmd {
120	if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
121		return util.ReportWarn("Agent is working, please wait...")
122	}
123
124	value := m.textarea.Value()
125	value = strings.TrimSpace(value)
126
127	switch value {
128	case "exit", "quit":
129		m.textarea.Reset()
130		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
131	}
132
133	m.textarea.Reset()
134	attachments := m.attachments
135
136	m.attachments = nil
137	if value == "" {
138		return nil
139	}
140	return tea.Batch(
141		util.CmdHandler(chat.SendMsg{
142			Text:        value,
143			Attachments: attachments,
144		}),
145	)
146}
147
148func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
149	var cmd tea.Cmd
150	var cmds []tea.Cmd
151	switch msg := msg.(type) {
152	case tea.KeyboardEnhancementsMsg:
153		m.keyMap.keyboard = msg
154		return m, nil
155	case chat.SessionSelectedMsg:
156		if msg.ID != m.session.ID {
157			m.session = msg
158		}
159		return m, nil
160	case filepicker.FilePickedMsg:
161		if len(m.attachments) >= maxAttachments {
162			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
163		}
164		m.attachments = append(m.attachments, msg.Attachment)
165		return m, nil
166	case completions.CompletionsClosedMsg:
167		m.isCompletionsOpen = false
168		m.currentQuery = ""
169		m.completionsStartIndex = 0
170	case completions.SelectCompletionMsg:
171		if !m.isCompletionsOpen {
172			return m, nil
173		}
174		if item, ok := msg.Value.(FileCompletionItem); ok {
175			// If the selected item is a file, insert its path into the textarea
176			value := m.textarea.Value()
177			value = value[:m.completionsStartIndex]
178			if len(value) > 0 && value[len(value)-1] != ' ' {
179				value += " "
180			}
181			value += item.Path
182			m.textarea.SetValue(value)
183			m.isCompletionsOpen = false
184			m.currentQuery = ""
185			m.completionsStartIndex = 0
186			return m, nil
187		}
188	case openEditorMsg:
189		m.textarea.SetValue(msg.Text)
190		m.textarea.MoveToEnd()
191	case tea.KeyPressMsg:
192		switch {
193		// Completions
194		case msg.String() == "/" && !m.isCompletionsOpen:
195			m.isCompletionsOpen = true
196			m.currentQuery = ""
197			cmds = append(cmds, m.startCompletions)
198			m.completionsStartIndex = len(m.textarea.Value())
199		case msg.String() == "space" && m.isCompletionsOpen:
200			m.isCompletionsOpen = false
201			m.currentQuery = ""
202			m.completionsStartIndex = 0
203			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
204		case m.isCompletionsOpen && m.textarea.Cursor().X <= m.completionsStartIndex:
205			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
206		case msg.String() == "backspace" && m.isCompletionsOpen:
207			if len(m.currentQuery) > 0 {
208				m.currentQuery = m.currentQuery[:len(m.currentQuery)-1]
209				cmds = append(cmds, util.CmdHandler(completions.FilterCompletionsMsg{
210					Query: m.currentQuery,
211				}))
212			} else {
213				m.isCompletionsOpen = false
214				m.currentQuery = ""
215				m.completionsStartIndex = 0
216				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
217			}
218		default:
219			if m.isCompletionsOpen {
220				m.currentQuery += msg.String()
221				cmds = append(cmds, util.CmdHandler(completions.FilterCompletionsMsg{
222					Query: m.currentQuery,
223				}))
224			}
225		}
226		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
227			m.deleteMode = true
228			return m, nil
229		}
230		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
231			m.deleteMode = false
232			m.attachments = nil
233			return m, nil
234		}
235		rune := msg.Code
236		if m.deleteMode && unicode.IsDigit(rune) {
237			num := int(rune - '0')
238			m.deleteMode = false
239			if num < 10 && len(m.attachments) > num {
240				if num == 0 {
241					m.attachments = m.attachments[num+1:]
242				} else {
243					m.attachments = slices.Delete(m.attachments, num, num+1)
244				}
245				return m, nil
246			}
247		}
248		if key.Matches(msg, m.keyMap.OpenEditor) {
249			if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
250				return m, util.ReportWarn("Agent is working, please wait...")
251			}
252			return m, m.openEditor(m.textarea.Value())
253		}
254		if key.Matches(msg, DeleteKeyMaps.Escape) {
255			m.deleteMode = false
256			return m, nil
257		}
258		if key.Matches(msg, m.keyMap.Newline) {
259			m.textarea.InsertRune('\n')
260		}
261		// Handle Enter key
262		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
263			value := m.textarea.Value()
264			if len(value) > 0 && value[len(value)-1] == '\\' {
265				// If the last character is a backslash, remove it and add a newline
266				m.textarea.SetValue(value[:len(value)-1] + "\n")
267				return m, nil
268			} else {
269				// Otherwise, send the message
270				return m, m.send()
271			}
272		}
273	}
274
275	m.textarea, cmd = m.textarea.Update(msg)
276	cmds = append(cmds, cmd)
277	return m, tea.Batch(cmds...)
278}
279
280func (m *editorCmp) Cursor() *tea.Cursor {
281	cursor := m.textarea.Cursor()
282	if cursor != nil {
283		cursor.X = cursor.X + m.x + 1
284		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
285	}
286	return cursor
287}
288
289func (m *editorCmp) View() string {
290	t := styles.CurrentTheme()
291	if len(m.attachments) == 0 {
292		content := t.S().Base.Padding(1).Render(
293			m.textarea.View(),
294		)
295		return content
296	}
297	content := t.S().Base.Padding(0, 1, 1, 1).Render(
298		lipgloss.JoinVertical(lipgloss.Top,
299			m.attachmentsContent(),
300			m.textarea.View(),
301		),
302	)
303	return content
304}
305
306func (m *editorCmp) SetSize(width, height int) tea.Cmd {
307	m.width = width
308	m.height = height
309	m.textarea.SetWidth(width - 2)   // adjust for padding
310	m.textarea.SetHeight(height - 2) // adjust for padding
311	return nil
312}
313
314func (m *editorCmp) GetSize() (int, int) {
315	return m.textarea.Width(), m.textarea.Height()
316}
317
318func (m *editorCmp) attachmentsContent() string {
319	var styledAttachments []string
320	t := styles.CurrentTheme()
321	attachmentStyles := t.S().Base.
322		MarginLeft(1).
323		Background(t.FgMuted).
324		Foreground(t.FgBase)
325	for i, attachment := range m.attachments {
326		var filename string
327		if len(attachment.FileName) > 10 {
328			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
329		} else {
330			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
331		}
332		if m.deleteMode {
333			filename = fmt.Sprintf("%d%s", i, filename)
334		}
335		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
336	}
337	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
338	return content
339}
340
341func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
342	m.x = x
343	m.y = y
344	return nil
345}
346
347func (m *editorCmp) startCompletions() tea.Msg {
348	files, _, _ := fsext.ListDirectory(".", []string{}, 0)
349	completionItems := make([]completions.Completion, 0, len(files))
350	for _, file := range files {
351		file = strings.TrimPrefix(file, "./")
352		completionItems = append(completionItems, completions.Completion{
353			Title: file,
354			Value: FileCompletionItem{
355				Path: file,
356			},
357		})
358	}
359
360	x := m.textarea.Cursor().X + m.x + 1
361	y := m.textarea.Cursor().Y + m.y + 1
362	return completions.OpenCompletionsMsg{
363		Completions: completionItems,
364		X:           x,
365		Y:           y,
366	}
367}
368
369// Blur implements Container.
370func (c *editorCmp) Blur() tea.Cmd {
371	c.textarea.Blur()
372	return nil
373}
374
375// Focus implements Container.
376func (c *editorCmp) Focus() tea.Cmd {
377	return c.textarea.Focus()
378}
379
380// IsFocused implements Container.
381func (c *editorCmp) IsFocused() bool {
382	return c.textarea.Focused()
383}
384
385// Bindings implements Container.
386func (c *editorCmp) Bindings() []key.Binding {
387	return c.keyMap.KeyBindings()
388}
389
390func NewEditorCmp(app *app.App) util.Model {
391	t := styles.CurrentTheme()
392	ta := textarea.New()
393	ta.SetStyles(t.S().TextArea)
394	ta.SetPromptFunc(4, func(info textarea.PromptInfo) string {
395		if info.LineNumber == 0 {
396			return "  > "
397		}
398		if info.Focused {
399			return t.S().Base.Foreground(t.GreenDark).Render("::: ")
400		} else {
401			return t.S().Muted.Render("::: ")
402		}
403	})
404	ta.ShowLineNumbers = false
405	ta.CharLimit = -1
406	ta.Placeholder = "Tell me more about this project..."
407	ta.SetVirtualCursor(false)
408	ta.Focus()
409
410	return &editorCmp{
411		app:      app,
412		textarea: ta,
413		keyMap:   DefaultEditorKeyMap(),
414	}
415}