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