editor.go

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