editor.go

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