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 activeModelHasImageSupport() (bool, string) {
244	agentCfg := config.Get().Agents["coder"]
245	model := config.Get().GetModelByType(agentCfg.Model)
246	return model.SupportsImages, model.Name
247}
248
249func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
250	var cmd tea.Cmd
251	var cmds []tea.Cmd
252	switch msg := msg.(type) {
253	case tea.WindowSizeMsg:
254		return m, m.repositionCompletions
255	case filepicker.FilePickedMsg:
256		if len(m.attachments) >= maxAttachments {
257			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
258		}
259		m.attachments = append(m.attachments, msg.Attachment)
260		return m, nil
261	case completions.CompletionsOpenedMsg:
262		m.isCompletionsOpen = true
263	case completions.CompletionsClosedMsg:
264		m.isCompletionsOpen = false
265		m.currentQuery = ""
266		m.completionsStartIndex = 0
267	case completions.SelectCompletionMsg:
268		if !m.isCompletionsOpen {
269			return m, nil
270		}
271		if item, ok := msg.Value.(FileCompletionItem); ok {
272			return onCompletionItemSelect(os.DirFS("."), activeModelHasImageSupport, item, msg.Insert, m)
273		}
274	case commands.OpenExternalEditorMsg:
275		if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
276			return m, util.ReportWarn("Agent is working, please wait...")
277		}
278		return m, m.openEditor(m.textarea.Value())
279	case OpenEditorMsg:
280		m.textarea.SetValue(msg.Text)
281		m.textarea.MoveToEnd()
282	case tea.PasteMsg:
283		agentCfg := config.Get().Agents["coder"]
284		model := config.Get().GetModelByType(agentCfg.Model)
285		if !model.SupportsImages {
286			return m, util.ReportWarn("File attachments are not supported by the current model: " + model.Name)
287		}
288        return m, filepicker.OnPaste(filepicker.ResolveFS, string(msg)) // inject fsys accessibly from PWD
289
290	case commands.ToggleYoloModeMsg:
291		m.setEditorPrompt()
292		return m, nil
293	case tea.KeyPressMsg:
294		cur := m.textarea.Cursor()
295		curIdx := m.textarea.Width()*cur.Y + cur.X
296		switch {
297		// Completions
298		case msg.String() == "/" && !m.isCompletionsOpen &&
299			// only show if beginning of prompt, or if previous char is a space or newline:
300			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
301			m.isCompletionsOpen = true
302			m.currentQuery = ""
303			m.completionsStartIndex = curIdx
304
305			cmds = append(cmds, m.startCompletions())
306		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
307			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
308		}
309		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
310			m.deleteMode = true
311			return m, nil
312		}
313		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
314			m.deleteMode = false
315			m.attachments = nil
316			return m, nil
317		}
318		rune := msg.Code
319		if m.deleteMode && unicode.IsDigit(rune) {
320			num := int(rune - '0')
321			m.deleteMode = false
322			if num < 10 && len(m.attachments) > num {
323				if num == 0 {
324					m.attachments = m.attachments[num+1:]
325				} else {
326					m.attachments = slices.Delete(m.attachments, num, num+1)
327				}
328				return m, nil
329			}
330		}
331		if key.Matches(msg, m.keyMap.OpenEditor) {
332			if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
333				return m, util.ReportWarn("Agent is working, please wait...")
334			}
335			return m, m.openEditor(m.textarea.Value())
336		}
337		if key.Matches(msg, DeleteKeyMaps.Escape) {
338			m.deleteMode = false
339			return m, nil
340		}
341		if key.Matches(msg, m.keyMap.Newline) {
342			m.textarea.InsertRune('\n')
343			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
344		}
345		// Handle Enter key
346		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
347			value := m.textarea.Value()
348			if strings.HasSuffix(value, "\\") {
349				// If the last character is a backslash, remove it and add a newline.
350				m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
351			} else {
352				// Otherwise, send the message
353				return m, m.send()
354			}
355		}
356	}
357
358	m.textarea, cmd = m.textarea.Update(msg)
359	cmds = append(cmds, cmd)
360
361	if m.textarea.Focused() {
362		kp, ok := msg.(tea.KeyPressMsg)
363		if ok {
364			if kp.String() == "space" || m.textarea.Value() == "" {
365				m.isCompletionsOpen = false
366				m.currentQuery = ""
367				m.completionsStartIndex = 0
368				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
369			} else {
370				word := m.textarea.Word()
371				if strings.HasPrefix(word, "/") {
372					// XXX: wont' work if editing in the middle of the field.
373					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
374					m.currentQuery = word[1:]
375					x, y := m.completionsPosition()
376					x -= len(m.currentQuery)
377					m.isCompletionsOpen = true
378					cmds = append(cmds,
379						util.CmdHandler(completions.FilterCompletionsMsg{
380							Query:  m.currentQuery,
381							Reopen: m.isCompletionsOpen,
382							X:      x,
383							Y:      y,
384						}),
385					)
386				} else if m.isCompletionsOpen {
387					m.isCompletionsOpen = false
388					m.currentQuery = ""
389					m.completionsStartIndex = 0
390					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
391				}
392			}
393		}
394	}
395
396	return m, tea.Batch(cmds...)
397}
398
399func (m *editorCmp) setEditorPrompt() {
400	if perm := m.app.Permissions; perm != nil {
401		if perm.SkipRequests() {
402			m.textarea.SetPromptFunc(4, yoloPromptFunc)
403			return
404		}
405	}
406	m.textarea.SetPromptFunc(4, normalPromptFunc)
407}
408
409func (m *editorCmp) completionsPosition() (int, int) {
410	cur := m.textarea.Cursor()
411	if cur == nil {
412		return m.x, m.y + 1 // adjust for padding
413	}
414	x := cur.X + m.x
415	y := cur.Y + m.y + 1 // adjust for padding
416	return x, y
417}
418
419func (m *editorCmp) Cursor() *tea.Cursor {
420	cursor := m.textarea.Cursor()
421	if cursor != nil {
422		cursor.X = cursor.X + m.x + 1
423		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
424	}
425	return cursor
426}
427
428var readyPlaceholders = [...]string{
429	"Ready!",
430	"Ready...",
431	"Ready?",
432	"Ready for instructions",
433}
434
435var workingPlaceholders = [...]string{
436	"Working!",
437	"Working...",
438	"Brrrrr...",
439	"Prrrrrrrr...",
440	"Processing...",
441	"Thinking...",
442}
443
444func (m *editorCmp) randomizePlaceholders() {
445	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
446	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
447}
448
449func (m *editorCmp) View() string {
450	t := styles.CurrentTheme()
451	// Update placeholder
452	if m.app.CoderAgent != nil && m.app.CoderAgent.IsBusy() {
453		m.textarea.Placeholder = m.workingPlaceholder
454	} else {
455		m.textarea.Placeholder = m.readyPlaceholder
456	}
457	if m.app.Permissions.SkipRequests() {
458		m.textarea.Placeholder = "Yolo mode!"
459	}
460	if len(m.attachments) == 0 {
461		content := t.S().Base.Padding(1).Render(
462			m.textarea.View(),
463		)
464		return content
465	}
466	content := t.S().Base.Padding(0, 1, 1, 1).Render(
467		lipgloss.JoinVertical(lipgloss.Top,
468			m.attachmentsContent(),
469			m.textarea.View(),
470		),
471	)
472	return content
473}
474
475func (m *editorCmp) SetSize(width, height int) tea.Cmd {
476	m.width = width
477	m.height = height
478	m.textarea.SetWidth(width - 2)   // adjust for padding
479	m.textarea.SetHeight(height - 2) // adjust for padding
480	return nil
481}
482
483func (m *editorCmp) GetSize() (int, int) {
484	return m.textarea.Width(), m.textarea.Height()
485}
486
487func (m *editorCmp) attachmentsContent() string {
488	var styledAttachments []string
489	t := styles.CurrentTheme()
490	attachmentStyles := t.S().Base.
491		MarginLeft(1).
492		Background(t.FgMuted).
493		Foreground(t.FgBase)
494	for i, attachment := range m.attachments {
495		var filename string
496		if len(attachment.FileName) > 10 {
497			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
498		} else {
499			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
500		}
501		if m.deleteMode {
502			filename = fmt.Sprintf("%d%s", i, filename)
503		}
504		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
505	}
506	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
507	return content
508}
509
510func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
511	m.x = x
512	m.y = y
513	return nil
514}
515
516func (m *editorCmp) startCompletions() func() tea.Msg {
517	return func() tea.Msg {
518		files, _, _ := m.listDirResolver()(".", nil)
519		slices.Sort(files)
520		completionItems := make([]completions.Completion, 0, len(files))
521		for _, file := range files {
522			file = strings.TrimPrefix(file, "./")
523			completionItems = append(completionItems, completions.Completion{
524				Title: file,
525				Value: FileCompletionItem{
526					Path: file,
527				},
528			})
529		}
530
531		x, y := m.completionsPosition()
532		return completions.OpenCompletionsMsg{
533			Completions: completionItems,
534			X:           x,
535			Y:           y,
536		}
537	}
538}
539
540// Blur implements Container.
541func (c *editorCmp) Blur() tea.Cmd {
542	c.textarea.Blur()
543	return nil
544}
545
546// Focus implements Container.
547func (c *editorCmp) Focus() tea.Cmd {
548	return c.textarea.Focus()
549}
550
551// IsFocused implements Container.
552func (c *editorCmp) IsFocused() bool {
553	return c.textarea.Focused()
554}
555
556// Bindings implements Container.
557func (c *editorCmp) Bindings() []key.Binding {
558	return c.keyMap.KeyBindings()
559}
560
561// TODO: most likely we do not need to have the session here
562// we need to move some functionality to the page level
563func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
564	c.session = session
565	return nil
566}
567
568func (c *editorCmp) IsCompletionsOpen() bool {
569	return c.isCompletionsOpen
570}
571
572func (c *editorCmp) HasAttachments() bool {
573	return len(c.attachments) > 0
574}
575
576func normalPromptFunc(info textarea.PromptInfo) string {
577	t := styles.CurrentTheme()
578	if info.LineNumber == 0 {
579		return "  > "
580	}
581	if info.Focused {
582		return t.S().Base.Foreground(t.GreenDark).Render("::: ")
583	}
584	return t.S().Muted.Render("::: ")
585}
586
587func yoloPromptFunc(info textarea.PromptInfo) string {
588	t := styles.CurrentTheme()
589	if info.LineNumber == 0 {
590		if info.Focused {
591			return fmt.Sprintf("%s ", t.YoloIconFocused)
592		} else {
593			return fmt.Sprintf("%s ", t.YoloIconBlurred)
594		}
595	}
596	if info.Focused {
597		return fmt.Sprintf("%s ", t.YoloDotsFocused)
598	}
599	return fmt.Sprintf("%s ", t.YoloDotsBlurred)
600}
601
602func newTextArea() *textarea.Model {
603	t := styles.CurrentTheme()
604	ta := textarea.New()
605	ta.SetStyles(t.S().TextArea)
606	ta.ShowLineNumbers = false
607	ta.CharLimit = -1
608	ta.SetVirtualCursor(false)
609	ta.Focus()
610	return ta
611}
612
613func newEditor(app *app.App, resolveDirLister fsext.DirectoryListerResolver) *editorCmp {
614	e := editorCmp{
615		// TODO: remove the app instance from here
616		app:             app,
617		textarea:        newTextArea(),
618		keyMap:          DefaultEditorKeyMap(),
619		listDirResolver: resolveDirLister,
620	}
621	e.setEditorPrompt()
622
623	e.randomizePlaceholders()
624	e.textarea.Placeholder = e.readyPlaceholder
625
626	return &e
627}
628
629func New(app *app.App) Editor {
630	ls := app.Config().Options.TUI.Completions.Limits
631	return newEditor(app, fsext.ResolveDirectoryLister(ls()))
632}