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