editor.go

  1package editor
  2
  3import (
  4	"context"
  5	"fmt"
  6	"math/rand"
  7	"net/http"
  8	"os"
  9	"os/exec"
 10	"path/filepath"
 11	"runtime"
 12	"slices"
 13	"strings"
 14	"unicode"
 15
 16	"charm.land/bubbles/v2/key"
 17	"charm.land/bubbles/v2/textarea"
 18	tea "charm.land/bubbletea/v2"
 19	"charm.land/lipgloss/v2"
 20	"github.com/charmbracelet/crush/internal/app"
 21	"github.com/charmbracelet/crush/internal/fsext"
 22	"github.com/charmbracelet/crush/internal/message"
 23	"github.com/charmbracelet/crush/internal/session"
 24	"github.com/charmbracelet/crush/internal/tui/components/chat"
 25	"github.com/charmbracelet/crush/internal/tui/components/completions"
 26	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 27	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 28	"github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
 29	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 30	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 31	"github.com/charmbracelet/crush/internal/tui/styles"
 32	"github.com/charmbracelet/crush/internal/tui/util"
 33)
 34
 35type Editor interface {
 36	util.Model
 37	layout.Sizeable
 38	layout.Focusable
 39	layout.Help
 40	layout.Positional
 41
 42	SetSession(session session.Session) tea.Cmd
 43	IsCompletionsOpen() bool
 44	HasAttachments() bool
 45	IsEmpty() bool
 46	Cursor() *tea.Cursor
 47}
 48
 49type FileCompletionItem struct {
 50	Path string // The file path
 51}
 52
 53type editorCmp struct {
 54	width              int
 55	height             int
 56	x, y               int
 57	app                *app.App
 58	session            session.Session
 59	textarea           textarea.Model
 60	attachments        []message.Attachment
 61	deleteMode         bool
 62	readyPlaceholder   string
 63	workingPlaceholder string
 64
 65	keyMap EditorKeyMap
 66
 67	// File path completions
 68	currentQuery          string
 69	completionsStartIndex int
 70	isCompletionsOpen     bool
 71}
 72
 73var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 74	AttachmentDeleteMode: key.NewBinding(
 75		key.WithKeys("ctrl+r"),
 76		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 77	),
 78	Escape: key.NewBinding(
 79		key.WithKeys("esc", "alt+esc"),
 80		key.WithHelp("esc", "cancel delete mode"),
 81	),
 82	DeleteAllAttachments: key.NewBinding(
 83		key.WithKeys("r"),
 84		key.WithHelp("ctrl+r+r", "delete all attachments"),
 85	),
 86}
 87
 88const (
 89	maxAttachments = 5
 90	maxFileResults = 25
 91)
 92
 93type OpenEditorMsg struct {
 94	Text string
 95}
 96
 97func (m *editorCmp) openEditor(value string) tea.Cmd {
 98	editor := os.Getenv("EDITOR")
 99	if editor == "" {
100		// Use platform-appropriate default editor
101		if runtime.GOOS == "windows" {
102			editor = "notepad"
103		} else {
104			editor = "nvim"
105		}
106	}
107
108	tmpfile, err := os.CreateTemp("", "msg_*.md")
109	if err != nil {
110		return util.ReportError(err)
111	}
112	defer tmpfile.Close() //nolint:errcheck
113	if _, err := tmpfile.WriteString(value); err != nil {
114		return util.ReportError(err)
115	}
116	c := exec.CommandContext(context.TODO(), editor, tmpfile.Name())
117	c.Stdin = os.Stdin
118	c.Stdout = os.Stdout
119	c.Stderr = os.Stderr
120	return tea.ExecProcess(c, func(err error) tea.Msg {
121		if err != nil {
122			return util.ReportError(err)
123		}
124		content, err := os.ReadFile(tmpfile.Name())
125		if err != nil {
126			return util.ReportError(err)
127		}
128		if len(content) == 0 {
129			return util.ReportWarn("Message is empty")
130		}
131		os.Remove(tmpfile.Name())
132		return OpenEditorMsg{
133			Text: strings.TrimSpace(string(content)),
134		}
135	})
136}
137
138func (m *editorCmp) Init() tea.Cmd {
139	return nil
140}
141
142func (m *editorCmp) send() tea.Cmd {
143	value := m.textarea.Value()
144	value = strings.TrimSpace(value)
145
146	switch value {
147	case "exit", "quit":
148		m.textarea.Reset()
149		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
150	}
151
152	m.textarea.Reset()
153	attachments := m.attachments
154
155	m.attachments = nil
156	if value == "" {
157		return nil
158	}
159
160	// Change the placeholder when sending a new message.
161	m.randomizePlaceholders()
162
163	return tea.Batch(
164		util.CmdHandler(chat.SendMsg{
165			Text:        value,
166			Attachments: attachments,
167		}),
168	)
169}
170
171func (m *editorCmp) repositionCompletions() tea.Msg {
172	x, y := m.completionsPosition()
173	return completions.RepositionCompletionsMsg{X: x, Y: y}
174}
175
176func (m *editorCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
177	var cmd tea.Cmd
178	var cmds []tea.Cmd
179	switch msg := msg.(type) {
180	case tea.WindowSizeMsg:
181		return m, m.repositionCompletions
182	case filepicker.FilePickedMsg:
183		if len(m.attachments) >= maxAttachments {
184			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
185		}
186		m.attachments = append(m.attachments, msg.Attachment)
187		return m, nil
188	case completions.CompletionsOpenedMsg:
189		m.isCompletionsOpen = true
190	case completions.CompletionsClosedMsg:
191		m.isCompletionsOpen = false
192		m.currentQuery = ""
193		m.completionsStartIndex = 0
194	case completions.SelectCompletionMsg:
195		if !m.isCompletionsOpen {
196			return m, nil
197		}
198		if item, ok := msg.Value.(FileCompletionItem); ok {
199			word := m.textarea.Word()
200			// If the selected item is a file, insert its path into the textarea
201			value := m.textarea.Value()
202			value = value[:m.completionsStartIndex] + // Remove the current query
203				item.Path + // Insert the file path
204				value[m.completionsStartIndex+len(word):] // Append the rest of the value
205			// XXX: This will always move the cursor to the end of the textarea.
206			m.textarea.SetValue(value)
207			m.textarea.MoveToEnd()
208			if !msg.Insert {
209				m.isCompletionsOpen = false
210				m.currentQuery = ""
211				m.completionsStartIndex = 0
212			}
213		}
214
215	case commands.OpenExternalEditorMsg:
216		if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
217			return m, util.ReportWarn("Agent is working, please wait...")
218		}
219		return m, m.openEditor(m.textarea.Value())
220	case OpenEditorMsg:
221		m.textarea.SetValue(msg.Text)
222		m.textarea.MoveToEnd()
223	case tea.PasteMsg:
224		path := strings.ReplaceAll(msg.Content, "\\ ", " ")
225		// try to get an image
226		path, err := filepath.Abs(strings.TrimSpace(path))
227		if err != nil {
228			m.textarea, cmd = m.textarea.Update(msg)
229			return m, cmd
230		}
231		isAllowedType := false
232		for _, ext := range filepicker.AllowedTypes {
233			if strings.HasSuffix(path, ext) {
234				isAllowedType = true
235				break
236			}
237		}
238		if !isAllowedType {
239			m.textarea, cmd = m.textarea.Update(msg)
240			return m, cmd
241		}
242		tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
243		if tooBig {
244			m.textarea, cmd = m.textarea.Update(msg)
245			return m, cmd
246		}
247
248		content, err := os.ReadFile(path)
249		if err != nil {
250			m.textarea, cmd = m.textarea.Update(msg)
251			return m, cmd
252		}
253		mimeBufferSize := min(512, len(content))
254		mimeType := http.DetectContentType(content[:mimeBufferSize])
255		fileName := filepath.Base(path)
256		attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
257		return m, util.CmdHandler(filepicker.FilePickedMsg{
258			Attachment: attachment,
259		})
260
261	case commands.ToggleYoloModeMsg:
262		m.setEditorPrompt()
263		return m, nil
264	case tea.KeyPressMsg:
265		cur := m.textarea.Cursor()
266		curIdx := m.textarea.Width()*cur.Y + cur.X
267		switch {
268		// Open command palette when "/" is pressed on empty prompt
269		case msg.String() == "/" && m.IsEmpty():
270			return m, util.CmdHandler(dialogs.OpenDialogMsg{
271				Model: commands.NewCommandDialog(m.session.ID),
272			})
273		// Completions
274		case msg.String() == "@" && !m.isCompletionsOpen &&
275			// only show if beginning of prompt, or if previous char is a space or newline:
276			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
277			m.isCompletionsOpen = true
278			m.currentQuery = ""
279			m.completionsStartIndex = curIdx
280			cmds = append(cmds, m.startCompletions)
281		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
282			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
283		}
284		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
285			m.deleteMode = true
286			return m, nil
287		}
288		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
289			m.deleteMode = false
290			m.attachments = nil
291			return m, nil
292		}
293		rune := msg.Code
294		if m.deleteMode && unicode.IsDigit(rune) {
295			num := int(rune - '0')
296			m.deleteMode = false
297			if num < 10 && len(m.attachments) > num {
298				if num == 0 {
299					m.attachments = m.attachments[num+1:]
300				} else {
301					m.attachments = slices.Delete(m.attachments, num, num+1)
302				}
303				return m, nil
304			}
305		}
306		if key.Matches(msg, m.keyMap.OpenEditor) {
307			if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
308				return m, util.ReportWarn("Agent is working, please wait...")
309			}
310			return m, m.openEditor(m.textarea.Value())
311		}
312		if key.Matches(msg, DeleteKeyMaps.Escape) {
313			m.deleteMode = false
314			return m, nil
315		}
316		if key.Matches(msg, m.keyMap.Newline) {
317			m.textarea.InsertRune('\n')
318			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
319		}
320		// Handle Enter key
321		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
322			value := m.textarea.Value()
323			if strings.HasSuffix(value, "\\") {
324				// If the last character is a backslash, remove it and add a newline.
325				m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
326			} else {
327				// Otherwise, send the message
328				return m, m.send()
329			}
330		}
331	}
332
333	m.textarea, cmd = m.textarea.Update(msg)
334	cmds = append(cmds, cmd)
335
336	if m.textarea.Focused() {
337		kp, ok := msg.(tea.KeyPressMsg)
338		if ok {
339			if kp.String() == "space" || m.textarea.Value() == "" {
340				m.isCompletionsOpen = false
341				m.currentQuery = ""
342				m.completionsStartIndex = 0
343				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
344			} else {
345				word := m.textarea.Word()
346				if strings.HasPrefix(word, "@") {
347					// XXX: wont' work if editing in the middle of the field.
348					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
349					m.currentQuery = word[1:]
350					x, y := m.completionsPosition()
351					x -= len(m.currentQuery)
352					m.isCompletionsOpen = true
353					cmds = append(cmds,
354						util.CmdHandler(completions.FilterCompletionsMsg{
355							Query:  m.currentQuery,
356							Reopen: m.isCompletionsOpen,
357							X:      x,
358							Y:      y,
359						}),
360					)
361				} else if m.isCompletionsOpen {
362					m.isCompletionsOpen = false
363					m.currentQuery = ""
364					m.completionsStartIndex = 0
365					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
366				}
367			}
368		}
369	}
370
371	return m, tea.Batch(cmds...)
372}
373
374func (m *editorCmp) setEditorPrompt() {
375	if m.app.Permissions.SkipRequests() {
376		m.textarea.SetPromptFunc(4, yoloPromptFunc)
377		return
378	}
379	m.textarea.SetPromptFunc(4, normalPromptFunc)
380}
381
382func (m *editorCmp) completionsPosition() (int, int) {
383	cur := m.textarea.Cursor()
384	if cur == nil {
385		return m.x, m.y + 1 // adjust for padding
386	}
387	x := cur.X + m.x
388	y := cur.Y + m.y + 1 // adjust for padding
389	return x, y
390}
391
392func (m *editorCmp) Cursor() *tea.Cursor {
393	cursor := m.textarea.Cursor()
394	if cursor != nil {
395		cursor.X = cursor.X + m.x + 1
396		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
397	}
398	return cursor
399}
400
401var readyPlaceholders = [...]string{
402	"Ready!",
403	"Ready...",
404	"Ready?",
405	"Ready for instructions",
406}
407
408var workingPlaceholders = [...]string{
409	"Working!",
410	"Working...",
411	"Brrrrr...",
412	"Prrrrrrrr...",
413	"Processing...",
414	"Thinking...",
415}
416
417func (m *editorCmp) randomizePlaceholders() {
418	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
419	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
420}
421
422func (m *editorCmp) View() string {
423	t := styles.CurrentTheme()
424	// Update placeholder
425	if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
426		m.textarea.Placeholder = m.workingPlaceholder
427	} else {
428		m.textarea.Placeholder = m.readyPlaceholder
429	}
430	if m.app.Permissions.SkipRequests() {
431		m.textarea.Placeholder = "Yolo mode!"
432	}
433	if len(m.attachments) == 0 {
434		content := t.S().Base.Padding(1).Render(
435			m.textarea.View(),
436		)
437		return content
438	}
439	content := t.S().Base.Padding(0, 1, 1, 1).Render(
440		lipgloss.JoinVertical(lipgloss.Top,
441			m.attachmentsContent(),
442			m.textarea.View(),
443		),
444	)
445	return content
446}
447
448func (m *editorCmp) SetSize(width, height int) tea.Cmd {
449	m.width = width
450	m.height = height
451	m.textarea.SetWidth(width - 2)   // adjust for padding
452	m.textarea.SetHeight(height - 2) // adjust for padding
453	return nil
454}
455
456func (m *editorCmp) GetSize() (int, int) {
457	return m.textarea.Width(), m.textarea.Height()
458}
459
460func (m *editorCmp) attachmentsContent() string {
461	var styledAttachments []string
462	t := styles.CurrentTheme()
463	attachmentStyles := t.S().Base.
464		MarginLeft(1).
465		Background(t.FgMuted).
466		Foreground(t.FgBase)
467	for i, attachment := range m.attachments {
468		var filename string
469		if len(attachment.FileName) > 10 {
470			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
471		} else {
472			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
473		}
474		if m.deleteMode {
475			filename = fmt.Sprintf("%d%s", i, filename)
476		}
477		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
478	}
479	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
480	return content
481}
482
483func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
484	m.x = x
485	m.y = y
486	return nil
487}
488
489func (m *editorCmp) startCompletions() tea.Msg {
490	ls := m.app.Config().Options.TUI.Completions
491	depth, limit := ls.Limits()
492	files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
493	slices.Sort(files)
494	completionItems := make([]completions.Completion, 0, len(files))
495	for _, file := range files {
496		file = strings.TrimPrefix(file, "./")
497		completionItems = append(completionItems, completions.Completion{
498			Title: file,
499			Value: FileCompletionItem{
500				Path: file,
501			},
502		})
503	}
504
505	x, y := m.completionsPosition()
506	return completions.OpenCompletionsMsg{
507		Completions: completionItems,
508		X:           x,
509		Y:           y,
510		MaxResults:  maxFileResults,
511	}
512}
513
514// Blur implements Container.
515func (c *editorCmp) Blur() tea.Cmd {
516	c.textarea.Blur()
517	return nil
518}
519
520// Focus implements Container.
521func (c *editorCmp) Focus() tea.Cmd {
522	return c.textarea.Focus()
523}
524
525// IsFocused implements Container.
526func (c *editorCmp) IsFocused() bool {
527	return c.textarea.Focused()
528}
529
530// Bindings implements Container.
531func (c *editorCmp) Bindings() []key.Binding {
532	return c.keyMap.KeyBindings()
533}
534
535// TODO: most likely we do not need to have the session here
536// we need to move some functionality to the page level
537func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
538	c.session = session
539	return nil
540}
541
542func (c *editorCmp) IsCompletionsOpen() bool {
543	return c.isCompletionsOpen
544}
545
546func (c *editorCmp) HasAttachments() bool {
547	return len(c.attachments) > 0
548}
549
550func (c *editorCmp) IsEmpty() bool {
551	return strings.TrimSpace(c.textarea.Value()) == ""
552}
553
554func normalPromptFunc(info textarea.PromptInfo) string {
555	t := styles.CurrentTheme()
556	if info.LineNumber == 0 {
557		return "  > "
558	}
559	if info.Focused {
560		return t.S().Base.Foreground(t.GreenDark).Render("::: ")
561	}
562	return t.S().Muted.Render("::: ")
563}
564
565func yoloPromptFunc(info textarea.PromptInfo) string {
566	t := styles.CurrentTheme()
567	if info.LineNumber == 0 {
568		if info.Focused {
569			return fmt.Sprintf("%s ", t.YoloIconFocused)
570		} else {
571			return fmt.Sprintf("%s ", t.YoloIconBlurred)
572		}
573	}
574	if info.Focused {
575		return fmt.Sprintf("%s ", t.YoloDotsFocused)
576	}
577	return fmt.Sprintf("%s ", t.YoloDotsBlurred)
578}
579
580func New(app *app.App) Editor {
581	t := styles.CurrentTheme()
582	ta := textarea.New()
583	ta.SetStyles(t.S().TextArea)
584	ta.ShowLineNumbers = false
585	ta.CharLimit = -1
586	ta.SetVirtualCursor(false)
587	ta.Focus()
588	e := &editorCmp{
589		// TODO: remove the app instance from here
590		app:      app,
591		textarea: ta,
592		keyMap:   DefaultEditorKeyMap(),
593	}
594	e.setEditorPrompt()
595
596	e.randomizePlaceholders()
597	e.textarea.Placeholder = e.readyPlaceholder
598
599	return e
600}