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	"mvdan.cc/sh/v3/syntax"
 34)
 35
 36type Editor interface {
 37	util.Model
 38	layout.Sizeable
 39	layout.Focusable
 40	layout.Help
 41	layout.Positional
 42
 43	SetSession(session session.Session) tea.Cmd
 44	IsCompletionsOpen() bool
 45	HasAttachments() 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
117	// Parse the EDITOR parts to separate the executable from its arguments.
118	// This properly handles EDITORs with args like `zed --wait`.
119	parsed, err := syntax.NewParser().Parse(strings.NewReader(editor), "")
120	if err != nil {
121		return util.ReportError(fmt.Errorf("failed to parse editor command: %w", err))
122	}
123
124	var cmdName string
125	var cmdArgs []string
126	if len(parsed.Stmts) > 0 && parsed.Stmts[0].Cmd != nil {
127		if callExpr, ok := parsed.Stmts[0].Cmd.(*syntax.CallExpr); ok && len(callExpr.Args) > 0 {
128			for i, arg := range callExpr.Args {
129				var argStr string
130				for _, part := range arg.Parts {
131					if lit, ok := part.(*syntax.Lit); ok {
132						argStr += lit.Value
133					}
134				}
135				if i == 0 {
136					cmdName = argStr
137				} else {
138					cmdArgs = append(cmdArgs, argStr)
139				}
140			}
141		}
142	}
143
144	// Fallback if parsing borked
145	if cmdName == "" {
146		cmdName = editor
147	}
148
149	cmdArgs = append(cmdArgs, tmpfile.Name())
150	c := exec.CommandContext(context.TODO(), cmdName, cmdArgs...)
151	c.Stdin = os.Stdin
152	c.Stdout = os.Stdout
153	c.Stderr = os.Stderr
154	return tea.ExecProcess(c, func(err error) tea.Msg {
155		if err != nil {
156			return util.ReportError(err)
157		}
158		content, err := os.ReadFile(tmpfile.Name())
159		if err != nil {
160			return util.ReportError(err)
161		}
162		if len(content) == 0 {
163			return util.ReportWarn("Message is empty")
164		}
165		os.Remove(tmpfile.Name())
166		return OpenEditorMsg{
167			Text: strings.TrimSpace(string(content)),
168		}
169	})
170}
171
172func (m *editorCmp) Init() tea.Cmd {
173	return nil
174}
175
176func (m *editorCmp) send() tea.Cmd {
177	value := m.textarea.Value()
178	value = strings.TrimSpace(value)
179
180	switch value {
181	case "exit", "quit":
182		m.textarea.Reset()
183		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
184	}
185
186	m.textarea.Reset()
187	attachments := m.attachments
188
189	m.attachments = nil
190	if value == "" {
191		return nil
192	}
193
194	// Change the placeholder when sending a new message.
195	m.randomizePlaceholders()
196
197	return tea.Batch(
198		util.CmdHandler(chat.SendMsg{
199			Text:        value,
200			Attachments: attachments,
201		}),
202	)
203}
204
205func (m *editorCmp) repositionCompletions() tea.Msg {
206	x, y := m.completionsPosition()
207	return completions.RepositionCompletionsMsg{X: x, Y: y}
208}
209
210func (m *editorCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
211	var cmd tea.Cmd
212	var cmds []tea.Cmd
213	switch msg := msg.(type) {
214	case tea.WindowSizeMsg:
215		return m, m.repositionCompletions
216	case filepicker.FilePickedMsg:
217		if len(m.attachments) >= maxAttachments {
218			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
219		}
220		m.attachments = append(m.attachments, msg.Attachment)
221		return m, nil
222	case completions.CompletionsOpenedMsg:
223		m.isCompletionsOpen = true
224	case completions.CompletionsClosedMsg:
225		m.isCompletionsOpen = false
226		m.currentQuery = ""
227		m.completionsStartIndex = 0
228	case completions.SelectCompletionMsg:
229		if !m.isCompletionsOpen {
230			return m, nil
231		}
232		if item, ok := msg.Value.(FileCompletionItem); ok {
233			word := m.textarea.Word()
234			// If the selected item is a file, insert its path into the textarea
235			value := m.textarea.Value()
236			value = value[:m.completionsStartIndex] + // Remove the current query
237				item.Path + // Insert the file path
238				value[m.completionsStartIndex+len(word):] // Append the rest of the value
239			// XXX: This will always move the cursor to the end of the textarea.
240			m.textarea.SetValue(value)
241			m.textarea.MoveToEnd()
242			if !msg.Insert {
243				m.isCompletionsOpen = false
244				m.currentQuery = ""
245				m.completionsStartIndex = 0
246			}
247		}
248
249	case commands.OpenExternalEditorMsg:
250		if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
251			return m, util.ReportWarn("Agent is working, please wait...")
252		}
253		if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.HasPendingCompletionNotification(m.session.ID) {
254			m.app.AgentCoordinator.CancelCompletionNotification(m.session.ID)
255		}
256		return m, m.openEditor(m.textarea.Value())
257	case OpenEditorMsg:
258		m.textarea.SetValue(msg.Text)
259		m.textarea.MoveToEnd()
260	case tea.PasteMsg:
261		// Interaction: cancel any pending turn-end notification for this session.
262		if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.HasPendingCompletionNotification(m.session.ID) {
263			m.app.AgentCoordinator.CancelCompletionNotification(m.session.ID)
264		}
265		path := strings.ReplaceAll(msg.Content, "\\ ", " ")
266		// try to get an image
267		path, err := filepath.Abs(strings.TrimSpace(path))
268		if err != nil {
269			m.textarea, cmd = m.textarea.Update(msg)
270			return m, cmd
271		}
272		isAllowedType := false
273		for _, ext := range filepicker.AllowedTypes {
274			if strings.HasSuffix(path, ext) {
275				isAllowedType = true
276				break
277			}
278		}
279		if !isAllowedType {
280			m.textarea, cmd = m.textarea.Update(msg)
281			return m, cmd
282		}
283		tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
284		if tooBig {
285			m.textarea, cmd = m.textarea.Update(msg)
286			return m, cmd
287		}
288
289		content, err := os.ReadFile(path)
290		if err != nil {
291			m.textarea, cmd = m.textarea.Update(msg)
292			return m, cmd
293		}
294		mimeBufferSize := min(512, len(content))
295		mimeType := http.DetectContentType(content[:mimeBufferSize])
296		fileName := filepath.Base(path)
297		attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
298		return m, util.CmdHandler(filepicker.FilePickedMsg{
299			Attachment: attachment,
300		})
301
302	case commands.ToggleYoloModeMsg:
303		m.setEditorPrompt()
304		return m, nil
305	case tea.KeyPressMsg:
306		// Interaction: cancel any pending turn-end notification for this session.
307		if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.HasPendingCompletionNotification(m.session.ID) {
308			m.app.AgentCoordinator.CancelCompletionNotification(m.session.ID)
309		}
310		cur := m.textarea.Cursor()
311		curIdx := m.textarea.Width()*cur.Y + cur.X
312		switch {
313		// Open command palette when "/" is pressed on empty prompt
314		case msg.String() == "/" && len(strings.TrimSpace(m.textarea.Value())) == 0:
315			return m, util.CmdHandler(dialogs.OpenDialogMsg{
316				Model: commands.NewCommandDialog(m.session.ID),
317			})
318		// Completions
319		case msg.String() == "@" && !m.isCompletionsOpen &&
320			// only show if beginning of prompt, or if previous char is a space or newline:
321			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
322			m.isCompletionsOpen = true
323			m.currentQuery = ""
324			m.completionsStartIndex = curIdx
325			cmds = append(cmds, m.startCompletions)
326		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
327			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
328		}
329		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
330			m.deleteMode = true
331			return m, nil
332		}
333		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
334			m.deleteMode = false
335			m.attachments = nil
336			return m, nil
337		}
338		rune := msg.Code
339		if m.deleteMode && unicode.IsDigit(rune) {
340			num := int(rune - '0')
341			m.deleteMode = false
342			if num < 10 && len(m.attachments) > num {
343				if num == 0 {
344					m.attachments = m.attachments[num+1:]
345				} else {
346					m.attachments = slices.Delete(m.attachments, num, num+1)
347				}
348				return m, nil
349			}
350		}
351		if key.Matches(msg, m.keyMap.OpenEditor) {
352			if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
353				return m, util.ReportWarn("Agent is working, please wait...")
354			}
355			return m, m.openEditor(m.textarea.Value())
356		}
357		if key.Matches(msg, DeleteKeyMaps.Escape) {
358			m.deleteMode = false
359			return m, nil
360		}
361		if key.Matches(msg, m.keyMap.Newline) {
362			m.textarea.InsertRune('\n')
363			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
364		}
365		// Handle Enter key
366		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
367			value := m.textarea.Value()
368			if strings.HasSuffix(value, "\\") {
369				// If the last character is a backslash, remove it and add a newline.
370				m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
371			} else {
372				// Otherwise, send the message
373				return m, m.send()
374			}
375		}
376	}
377
378	m.textarea, cmd = m.textarea.Update(msg)
379	cmds = append(cmds, cmd)
380
381	if m.textarea.Focused() {
382		kp, ok := msg.(tea.KeyPressMsg)
383		if ok {
384			if kp.String() == "space" || m.textarea.Value() == "" {
385				m.isCompletionsOpen = false
386				m.currentQuery = ""
387				m.completionsStartIndex = 0
388				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
389			} else {
390				word := m.textarea.Word()
391				if strings.HasPrefix(word, "@") {
392					// XXX: wont' work if editing in the middle of the field.
393					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
394					m.currentQuery = word[1:]
395					x, y := m.completionsPosition()
396					x -= len(m.currentQuery)
397					m.isCompletionsOpen = true
398					cmds = append(cmds,
399						util.CmdHandler(completions.FilterCompletionsMsg{
400							Query:  m.currentQuery,
401							Reopen: m.isCompletionsOpen,
402							X:      x,
403							Y:      y,
404						}),
405					)
406				} else if m.isCompletionsOpen {
407					m.isCompletionsOpen = false
408					m.currentQuery = ""
409					m.completionsStartIndex = 0
410					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
411				}
412			}
413		}
414	}
415
416	return m, tea.Batch(cmds...)
417}
418
419func (m *editorCmp) setEditorPrompt() {
420	if m.app.Permissions.SkipRequests() {
421		m.textarea.SetPromptFunc(4, yoloPromptFunc)
422		return
423	}
424	m.textarea.SetPromptFunc(4, normalPromptFunc)
425}
426
427func (m *editorCmp) completionsPosition() (int, int) {
428	cur := m.textarea.Cursor()
429	if cur == nil {
430		return m.x, m.y + 1 // adjust for padding
431	}
432	x := cur.X + m.x
433	y := cur.Y + m.y + 1 // adjust for padding
434	return x, y
435}
436
437func (m *editorCmp) Cursor() *tea.Cursor {
438	cursor := m.textarea.Cursor()
439	if cursor != nil {
440		cursor.X = cursor.X + m.x + 1
441		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
442	}
443	return cursor
444}
445
446var readyPlaceholders = [...]string{
447	"Ready!",
448	"Ready...",
449	"Ready?",
450	"Ready for instructions",
451}
452
453var workingPlaceholders = [...]string{
454	"Working!",
455	"Working...",
456	"Brrrrr...",
457	"Prrrrrrrr...",
458	"Processing...",
459	"Thinking...",
460}
461
462func (m *editorCmp) randomizePlaceholders() {
463	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
464	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
465}
466
467func (m *editorCmp) View() string {
468	t := styles.CurrentTheme()
469	// Update placeholder
470	if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
471		m.textarea.Placeholder = m.workingPlaceholder
472	} else {
473		m.textarea.Placeholder = m.readyPlaceholder
474	}
475	if m.app.Permissions.SkipRequests() {
476		m.textarea.Placeholder = "Yolo mode!"
477	}
478	if len(m.attachments) == 0 {
479		content := t.S().Base.Padding(1).Render(
480			m.textarea.View(),
481		)
482		return content
483	}
484	content := t.S().Base.Padding(0, 1, 1, 1).Render(
485		lipgloss.JoinVertical(lipgloss.Top,
486			m.attachmentsContent(),
487			m.textarea.View(),
488		),
489	)
490	return content
491}
492
493func (m *editorCmp) SetSize(width, height int) tea.Cmd {
494	m.width = width
495	m.height = height
496	m.textarea.SetWidth(width - 2)   // adjust for padding
497	m.textarea.SetHeight(height - 2) // adjust for padding
498	return nil
499}
500
501func (m *editorCmp) GetSize() (int, int) {
502	return m.textarea.Width(), m.textarea.Height()
503}
504
505func (m *editorCmp) attachmentsContent() string {
506	var styledAttachments []string
507	t := styles.CurrentTheme()
508	attachmentStyles := t.S().Base.
509		MarginLeft(1).
510		Background(t.FgMuted).
511		Foreground(t.FgBase)
512	for i, attachment := range m.attachments {
513		var filename string
514		if len(attachment.FileName) > 10 {
515			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
516		} else {
517			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
518		}
519		if m.deleteMode {
520			filename = fmt.Sprintf("%d%s", i, filename)
521		}
522		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
523	}
524	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
525	return content
526}
527
528func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
529	m.x = x
530	m.y = y
531	return nil
532}
533
534func (m *editorCmp) startCompletions() tea.Msg {
535	ls := m.app.Config().Options.TUI.Completions
536	depth, limit := ls.Limits()
537	files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
538	slices.Sort(files)
539	completionItems := make([]completions.Completion, 0, len(files))
540	for _, file := range files {
541		file = strings.TrimPrefix(file, "./")
542		completionItems = append(completionItems, completions.Completion{
543			Title: file,
544			Value: FileCompletionItem{
545				Path: file,
546			},
547		})
548	}
549
550	x, y := m.completionsPosition()
551	return completions.OpenCompletionsMsg{
552		Completions: completionItems,
553		X:           x,
554		Y:           y,
555		MaxResults:  maxFileResults,
556	}
557}
558
559// Blur implements Container.
560func (c *editorCmp) Blur() tea.Cmd {
561	c.textarea.Blur()
562	return nil
563}
564
565// Focus implements Container.
566func (c *editorCmp) Focus() tea.Cmd {
567	return c.textarea.Focus()
568}
569
570// IsFocused implements Container.
571func (c *editorCmp) IsFocused() bool {
572	return c.textarea.Focused()
573}
574
575// Bindings implements Container.
576func (c *editorCmp) Bindings() []key.Binding {
577	return c.keyMap.KeyBindings()
578}
579
580// TODO: most likely we do not need to have the session here
581// we need to move some functionality to the page level
582func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
583	c.session = session
584	return nil
585}
586
587func (c *editorCmp) IsCompletionsOpen() bool {
588	return c.isCompletionsOpen
589}
590
591func (c *editorCmp) HasAttachments() bool {
592	return len(c.attachments) > 0
593}
594
595func normalPromptFunc(info textarea.PromptInfo) string {
596	t := styles.CurrentTheme()
597	if info.LineNumber == 0 {
598		return "  > "
599	}
600	if info.Focused {
601		return t.S().Base.Foreground(t.GreenDark).Render("::: ")
602	}
603	return t.S().Muted.Render("::: ")
604}
605
606func yoloPromptFunc(info textarea.PromptInfo) string {
607	t := styles.CurrentTheme()
608	if info.LineNumber == 0 {
609		if info.Focused {
610			return fmt.Sprintf("%s ", t.YoloIconFocused)
611		} else {
612			return fmt.Sprintf("%s ", t.YoloIconBlurred)
613		}
614	}
615	if info.Focused {
616		return fmt.Sprintf("%s ", t.YoloDotsFocused)
617	}
618	return fmt.Sprintf("%s ", t.YoloDotsBlurred)
619}
620
621func New(app *app.App) Editor {
622	t := styles.CurrentTheme()
623	ta := textarea.New()
624	ta.SetStyles(t.S().TextArea)
625	ta.ShowLineNumbers = false
626	ta.CharLimit = -1
627	ta.SetVirtualCursor(false)
628	ta.Focus()
629	e := &editorCmp{
630		// TODO: remove the app instance from here
631		app:      app,
632		textarea: ta,
633		keyMap:   DefaultEditorKeyMap(),
634	}
635	e.setEditorPrompt()
636
637	e.randomizePlaceholders()
638	e.textarea.Placeholder = e.readyPlaceholder
639
640	return e
641}