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