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/core/layout"
 22	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 23	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 24	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 25	"github.com/charmbracelet/crush/internal/tui/styles"
 26	"github.com/charmbracelet/crush/internal/tui/util"
 27	"github.com/charmbracelet/lipgloss/v2"
 28)
 29
 30type Editor interface {
 31	util.Model
 32	layout.Sizeable
 33	layout.Focusable
 34	layout.Help
 35	layout.Positional
 36
 37	SetSession(session session.Session) tea.Cmd
 38	IsCompletionsOpen() bool
 39	Cursor() *tea.Cursor
 40	SendMessage() tea.Cmd
 41}
 42
 43type FileCompletionItem struct {
 44	Path string // The file path
 45}
 46
 47type editorCmp struct {
 48	width       int
 49	height      int
 50	x, y        int
 51	app         *app.App
 52	session     session.Session
 53	textarea    textarea.Model
 54	attachments []message.Attachment
 55	deleteMode  bool
 56
 57	keyMap EditorKeyMap
 58
 59	// File path completions
 60	currentQuery          string
 61	completionsStartIndex int
 62	isCompletionsOpen     bool
 63}
 64
 65var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 66	AttachmentDeleteMode: key.NewBinding(
 67		key.WithKeys("ctrl+r"),
 68		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 69	),
 70	Escape: key.NewBinding(
 71		key.WithKeys("esc"),
 72		key.WithHelp("esc", "cancel delete mode"),
 73	),
 74	DeleteAllAttachments: key.NewBinding(
 75		key.WithKeys("r"),
 76		key.WithHelp("ctrl+r+r", "delete all attachments"),
 77	),
 78}
 79
 80const (
 81	maxAttachments = 5
 82)
 83
 84type openEditorMsg struct {
 85	Text string
 86}
 87
 88func (m *editorCmp) openEditor(value string) tea.Cmd {
 89	editor := os.Getenv("EDITOR")
 90	if editor == "" {
 91		// Use platform-appropriate default editor
 92		if runtime.GOOS == "windows" {
 93			editor = "notepad"
 94		} else {
 95			editor = "nvim"
 96		}
 97	}
 98
 99	tmpfile, err := os.CreateTemp("", "msg_*.md")
100	if err != nil {
101		return util.ReportError(err)
102	}
103	defer tmpfile.Close() //nolint:errcheck
104	if _, err := tmpfile.WriteString(value); err != nil {
105		return util.ReportError(err)
106	}
107	c := exec.Command(editor, tmpfile.Name())
108	c.Stdin = os.Stdin
109	c.Stdout = os.Stdout
110	c.Stderr = os.Stderr
111	return tea.ExecProcess(c, func(err error) tea.Msg {
112		if err != nil {
113			return util.ReportError(err)
114		}
115		content, err := os.ReadFile(tmpfile.Name())
116		if err != nil {
117			return util.ReportError(err)
118		}
119		if len(content) == 0 {
120			return util.ReportWarn("Message is empty")
121		}
122		os.Remove(tmpfile.Name())
123		return openEditorMsg{
124			Text: strings.TrimSpace(string(content)),
125		}
126	})
127}
128
129func (m *editorCmp) Init() tea.Cmd {
130	return nil
131}
132
133func (m *editorCmp) send() tea.Cmd {
134	if m.app.CoderAgent == nil {
135		return util.ReportError(fmt.Errorf("coder agent is not initialized"))
136	}
137	if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
138		return util.ReportWarn("Agent is working, please wait...")
139	}
140
141	value := m.textarea.Value()
142	value = strings.TrimSpace(value)
143
144	switch value {
145	case "exit", "quit":
146		m.textarea.Reset()
147		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
148	}
149
150	m.textarea.Reset()
151	attachments := m.attachments
152
153	m.attachments = nil
154	if value == "" {
155		return nil
156	}
157	return tea.Batch(
158		util.CmdHandler(chat.SendMsg{
159			Text:        value,
160			Attachments: attachments,
161		}),
162	)
163}
164
165func (m *editorCmp) repositionCompletions() tea.Msg {
166	x, y := m.completionsPosition()
167	return completions.RepositionCompletionsMsg{X: x, Y: y}
168}
169
170func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
171	var cmd tea.Cmd
172	var cmds []tea.Cmd
173	switch msg := msg.(type) {
174	case tea.WindowSizeMsg:
175		return m, m.repositionCompletions
176	case filepicker.FilePickedMsg:
177		if len(m.attachments) >= maxAttachments {
178			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
179		}
180		m.attachments = append(m.attachments, msg.Attachment)
181		return m, nil
182	case completions.CompletionsOpenedMsg:
183		m.isCompletionsOpen = true
184	case completions.CompletionsClosedMsg:
185		m.isCompletionsOpen = false
186		m.currentQuery = ""
187		m.completionsStartIndex = 0
188	case completions.SelectCompletionMsg:
189		if !m.isCompletionsOpen {
190			return m, nil
191		}
192		if item, ok := msg.Value.(FileCompletionItem); ok {
193			word := m.textarea.Word()
194			// If the selected item is a file, insert its path into the textarea
195			value := m.textarea.Value()
196			value = value[:m.completionsStartIndex] + // Remove the current query
197				item.Path + // Insert the file path
198				value[m.completionsStartIndex+len(word):] // Append the rest of the value
199			// XXX: This will always move the cursor to the end of the textarea.
200			m.textarea.SetValue(value)
201			m.textarea.MoveToEnd()
202			if !msg.Insert {
203				m.isCompletionsOpen = false
204				m.currentQuery = ""
205				m.completionsStartIndex = 0
206			}
207		}
208	case openEditorMsg:
209		m.textarea.SetValue(msg.Text)
210		m.textarea.MoveToEnd()
211	case tea.KeyPressMsg:
212		cur := m.textarea.Cursor()
213		curIdx := m.textarea.Width()*cur.Y + cur.X
214		switch {
215		// Completions
216		case msg.String() == "/" && !m.isCompletionsOpen &&
217			// only show if beginning of prompt, or if previous char is a space or newline:
218			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
219			m.isCompletionsOpen = true
220			m.currentQuery = ""
221			m.completionsStartIndex = curIdx
222			cmds = append(cmds, m.startCompletions)
223		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
224			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
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			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
261		}
262		// Handle Enter key
263		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
264			value := m.textarea.Value()
265			if len(value) > 0 && value[len(value)-1] == '\\' {
266				// If the last character is a backslash, remove it and add a newline
267				m.textarea.SetValue(value[:len(value)-1])
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
278	if m.textarea.Focused() {
279		kp, ok := msg.(tea.KeyPressMsg)
280		if ok {
281			if kp.String() == "space" || m.textarea.Value() == "" {
282				m.isCompletionsOpen = false
283				m.currentQuery = ""
284				m.completionsStartIndex = 0
285				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
286			} else {
287				word := m.textarea.Word()
288				if strings.HasPrefix(word, "/") {
289					// XXX: wont' work if editing in the middle of the field.
290					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
291					m.currentQuery = word[1:]
292					x, y := m.completionsPosition()
293					x -= len(m.currentQuery)
294					m.isCompletionsOpen = true
295					cmds = append(cmds,
296						util.CmdHandler(completions.FilterCompletionsMsg{
297							Query:  m.currentQuery,
298							Reopen: m.isCompletionsOpen,
299							X:      x,
300							Y:      y,
301						}),
302					)
303				} else if m.isCompletionsOpen {
304					m.isCompletionsOpen = false
305					m.currentQuery = ""
306					m.completionsStartIndex = 0
307					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
308				}
309			}
310		}
311	}
312
313	return m, tea.Batch(cmds...)
314}
315
316func (m *editorCmp) completionsPosition() (int, int) {
317	cur := m.textarea.Cursor()
318	if cur == nil {
319		return m.x, m.y + 1 // adjust for padding
320	}
321	x := cur.X + m.x
322	y := cur.Y + m.y + 1 // adjust for padding
323	return x, y
324}
325
326func (m *editorCmp) Cursor() *tea.Cursor {
327	cursor := m.textarea.Cursor()
328	if cursor != nil {
329		cursor.X = cursor.X + m.x + 1
330		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
331	}
332	return cursor
333}
334
335func (m *editorCmp) View() string {
336	t := styles.CurrentTheme()
337	if len(m.attachments) == 0 {
338		content := t.S().Base.Padding(1).Render(
339			m.textarea.View(),
340		)
341		return content
342	}
343	content := t.S().Base.Padding(0, 1, 1, 1).Render(
344		lipgloss.JoinVertical(lipgloss.Top,
345			m.attachmentsContent(),
346			m.textarea.View(),
347		),
348	)
349	return content
350}
351
352func (m *editorCmp) SetSize(width, height int) tea.Cmd {
353	m.width = width
354	m.height = height
355	m.textarea.SetWidth(width - 2)   // adjust for padding
356	m.textarea.SetHeight(height - 2) // adjust for padding
357	return nil
358}
359
360func (m *editorCmp) GetSize() (int, int) {
361	return m.textarea.Width(), m.textarea.Height()
362}
363
364func (m *editorCmp) attachmentsContent() string {
365	var styledAttachments []string
366	t := styles.CurrentTheme()
367	attachmentStyles := t.S().Base.
368		MarginLeft(1).
369		Background(t.FgMuted).
370		Foreground(t.FgBase)
371	for i, attachment := range m.attachments {
372		var filename string
373		if len(attachment.FileName) > 10 {
374			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
375		} else {
376			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
377		}
378		if m.deleteMode {
379			filename = fmt.Sprintf("%d%s", i, filename)
380		}
381		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
382	}
383	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
384	return content
385}
386
387func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
388	m.x = x
389	m.y = y
390	return nil
391}
392
393func (m *editorCmp) startCompletions() tea.Msg {
394	files, _, _ := fsext.ListDirectory(".", []string{}, 0)
395	completionItems := make([]completions.Completion, 0, len(files))
396	for _, file := range files {
397		file = strings.TrimPrefix(file, "./")
398		completionItems = append(completionItems, completions.Completion{
399			Title: file,
400			Value: FileCompletionItem{
401				Path: file,
402			},
403		})
404	}
405
406	x, y := m.completionsPosition()
407	return completions.OpenCompletionsMsg{
408		Completions: completionItems,
409		X:           x,
410		Y:           y,
411	}
412}
413
414// Blur implements Container.
415func (c *editorCmp) Blur() tea.Cmd {
416	c.textarea.Blur()
417	return nil
418}
419
420// Focus implements Container.
421func (c *editorCmp) Focus() tea.Cmd {
422	return c.textarea.Focus()
423}
424
425// IsFocused implements Container.
426func (c *editorCmp) IsFocused() bool {
427	return c.textarea.Focused()
428}
429
430// Bindings implements Container.
431func (c *editorCmp) Bindings() []key.Binding {
432	return c.keyMap.KeyBindings()
433}
434
435// TODO: most likely we do not need to have the session here
436// we need to move some functionality to the page level
437func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
438	c.session = session
439	return nil
440}
441
442func (c *editorCmp) IsCompletionsOpen() bool {
443	return c.isCompletionsOpen
444}
445
446func (c *editorCmp) SendMessage() tea.Cmd {
447	return c.send()
448}
449
450func New(app *app.App, initialPrompt string) Editor {
451	t := styles.CurrentTheme()
452	ta := textarea.New()
453	ta.SetStyles(t.S().TextArea)
454	ta.SetPromptFunc(4, func(info textarea.PromptInfo) string {
455		if info.LineNumber == 0 {
456			return "  > "
457		}
458		if info.Focused {
459			return t.S().Base.Foreground(t.GreenDark).Render("::: ")
460		} else {
461			return t.S().Muted.Render("::: ")
462		}
463	})
464	ta.ShowLineNumbers = false
465	ta.CharLimit = -1
466	ta.Placeholder = "Tell me more about this project..."
467	ta.SetVirtualCursor(false)
468	ta.Focus()
469
470	// Set initial prompt if provided
471	if initialPrompt != "" {
472		ta.SetValue(initialPrompt)
473		ta.MoveToEnd()
474	}
475
476	return &editorCmp{
477		// TODO: remove the app instance from here
478		app:      app,
479		textarea: ta,
480		keyMap:   DefaultEditorKeyMap(),
481	}
482}