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 cmds = append(cmds, m.startCompletions)
340 case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
341 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
342 }
343 if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
344 m.deleteMode = true
345 return m, nil
346 }
347 if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
348 m.deleteMode = false
349 m.attachments = nil
350 return m, nil
351 }
352 rune := msg.Code
353 if m.deleteMode && unicode.IsDigit(rune) {
354 num := int(rune - '0')
355 m.deleteMode = false
356 if num < 10 && len(m.attachments) > num {
357 if num == 0 {
358 m.attachments = m.attachments[num+1:]
359 } else {
360 m.attachments = slices.Delete(m.attachments, num, num+1)
361 }
362 return m, nil
363 }
364 }
365 if key.Matches(msg, m.keyMap.OpenEditor) {
366 if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
367 return m, util.ReportWarn("Agent is working, please wait...")
368 }
369 return m, m.openEditor(m.textarea.Value())
370 }
371 if key.Matches(msg, DeleteKeyMaps.Escape) {
372 m.deleteMode = false
373 return m, nil
374 }
375 if key.Matches(msg, m.keyMap.Newline) {
376 m.textarea.InsertRune('\n')
377 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
378 }
379 // Handle Enter key
380 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
381 value := m.textarea.Value()
382 if strings.HasSuffix(value, "\\") {
383 // If the last character is a backslash, remove it and add a newline.
384 m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
385 } else {
386 // Otherwise, send the message
387 return m, m.send()
388 }
389 }
390 }
391
392 m.textarea, cmd = m.textarea.Update(msg)
393 cmds = append(cmds, cmd)
394
395 if m.textarea.Focused() {
396 kp, ok := msg.(tea.KeyPressMsg)
397 if ok {
398 if kp.String() == "space" || m.textarea.Value() == "" {
399 m.isCompletionsOpen = false
400 m.currentQuery = ""
401 m.completionsStartIndex = 0
402 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
403 } else {
404 word := m.textarea.Word()
405 if strings.HasPrefix(word, "/") {
406 // XXX: wont' work if editing in the middle of the field.
407 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
408 m.currentQuery = word[1:]
409 x, y := m.completionsPosition()
410 x -= len(m.currentQuery)
411 m.isCompletionsOpen = true
412 cmds = append(cmds,
413 util.CmdHandler(completions.FilterCompletionsMsg{
414 Query: m.currentQuery,
415 Reopen: m.isCompletionsOpen,
416 X: x,
417 Y: y,
418 }),
419 )
420 } else if m.isCompletionsOpen {
421 m.isCompletionsOpen = false
422 m.currentQuery = ""
423 m.completionsStartIndex = 0
424 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
425 }
426 }
427 }
428 }
429
430 return m, tea.Batch(cmds...)
431}
432
433func (m *editorCmp) setEditorPrompt() {
434 if perm := m.app.Permissions; perm != nil {
435 if perm.SkipRequests() {
436 m.textarea.SetPromptFunc(4, yoloPromptFunc)
437 return
438 }
439 }
440 m.textarea.SetPromptFunc(4, normalPromptFunc)
441}
442
443func (m *editorCmp) completionsPosition() (int, int) {
444 cur := m.textarea.Cursor()
445 if cur == nil {
446 return m.x, m.y + 1 // adjust for padding
447 }
448 x := cur.X + m.x
449 y := cur.Y + m.y + 1 // adjust for padding
450 return x, y
451}
452
453func (m *editorCmp) Cursor() *tea.Cursor {
454 cursor := m.textarea.Cursor()
455 if cursor != nil {
456 cursor.X = cursor.X + m.x + 1
457 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
458 }
459 return cursor
460}
461
462var readyPlaceholders = [...]string{
463 "Ready!",
464 "Ready...",
465 "Ready?",
466 "Ready for instructions",
467}
468
469var workingPlaceholders = [...]string{
470 "Working!",
471 "Working...",
472 "Brrrrr...",
473 "Prrrrrrrr...",
474 "Processing...",
475 "Thinking...",
476}
477
478func (m *editorCmp) randomizePlaceholders() {
479 m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
480 m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
481}
482
483func (m *editorCmp) View() string {
484 t := styles.CurrentTheme()
485 // Update placeholder
486 if m.app.CoderAgent != nil && m.app.CoderAgent.IsBusy() {
487 m.textarea.Placeholder = m.workingPlaceholder
488 } else {
489 m.textarea.Placeholder = m.readyPlaceholder
490 }
491 if m.app.Permissions.SkipRequests() {
492 m.textarea.Placeholder = "Yolo mode!"
493 }
494 if len(m.attachments) == 0 {
495 content := t.S().Base.Padding(1).Render(
496 m.textarea.View(),
497 )
498 return content
499 }
500 content := t.S().Base.Padding(0, 1, 1, 1).Render(
501 lipgloss.JoinVertical(lipgloss.Top,
502 m.attachmentsContent(),
503 m.textarea.View(),
504 ),
505 )
506 return content
507}
508
509func (m *editorCmp) SetSize(width, height int) tea.Cmd {
510 m.width = width
511 m.height = height
512 m.textarea.SetWidth(width - 2) // adjust for padding
513 m.textarea.SetHeight(height - 2) // adjust for padding
514 return nil
515}
516
517func (m *editorCmp) GetSize() (int, int) {
518 return m.textarea.Width(), m.textarea.Height()
519}
520
521func (m *editorCmp) attachmentsContent() string {
522 var styledAttachments []string
523 t := styles.CurrentTheme()
524 attachmentStyles := t.S().Base.
525 MarginLeft(1).
526 Background(t.FgMuted).
527 Foreground(t.FgBase)
528 for i, attachment := range m.attachments {
529 var filename string
530 if len(attachment.FileName) > 10 {
531 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
532 } else {
533 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
534 }
535 if m.deleteMode {
536 filename = fmt.Sprintf("%d%s", i, filename)
537 }
538 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
539 }
540 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
541 return content
542}
543
544func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
545 m.x = x
546 m.y = y
547 return nil
548}
549
550func (m *editorCmp) startCompletions() tea.Msg {
551 ls := m.app.Config().Options.TUI.Completions
552 depth, limit := ls.Limits()
553 files, _, _ := m.listDirResolver()(".", nil, depth, limit)
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// Blur implements Container.
575func (c *editorCmp) Blur() tea.Cmd {
576 c.textarea.Blur()
577 return nil
578}
579
580// Focus implements Container.
581func (c *editorCmp) Focus() tea.Cmd {
582 return c.textarea.Focus()
583}
584
585// IsFocused implements Container.
586func (c *editorCmp) IsFocused() bool {
587 return c.textarea.Focused()
588}
589
590// Bindings implements Container.
591func (c *editorCmp) Bindings() []key.Binding {
592 return c.keyMap.KeyBindings()
593}
594
595// TODO: most likely we do not need to have the session here
596// we need to move some functionality to the page level
597func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
598 c.session = session
599 return nil
600}
601
602func (c *editorCmp) IsCompletionsOpen() bool {
603 return c.isCompletionsOpen
604}
605
606func (c *editorCmp) HasAttachments() bool {
607 return len(c.attachments) > 0
608}
609
610func normalPromptFunc(info textarea.PromptInfo) string {
611 t := styles.CurrentTheme()
612 if info.LineNumber == 0 {
613 return " > "
614 }
615 if info.Focused {
616 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
617 }
618 return t.S().Muted.Render("::: ")
619}
620
621func yoloPromptFunc(info textarea.PromptInfo) string {
622 t := styles.CurrentTheme()
623 if info.LineNumber == 0 {
624 if info.Focused {
625 return fmt.Sprintf("%s ", t.YoloIconFocused)
626 } else {
627 return fmt.Sprintf("%s ", t.YoloIconBlurred)
628 }
629 }
630 if info.Focused {
631 return fmt.Sprintf("%s ", t.YoloDotsFocused)
632 }
633 return fmt.Sprintf("%s ", t.YoloDotsBlurred)
634}
635
636func newTextArea() *textarea.Model {
637 t := styles.CurrentTheme()
638 ta := textarea.New()
639 ta.SetStyles(t.S().TextArea)
640 ta.ShowLineNumbers = false
641 ta.CharLimit = -1
642 ta.SetVirtualCursor(false)
643 ta.Focus()
644 return ta
645}
646
647func newEditor(app *app.App, resolveDirLister fsext.DirectoryListerResolver) *editorCmp {
648 e := editorCmp{
649 // TODO: remove the app instance from here
650 app: app,
651 textarea: newTextArea(),
652 keyMap: DefaultEditorKeyMap(),
653 listDirResolver: resolveDirLister,
654 }
655 e.setEditorPrompt()
656
657 e.randomizePlaceholders()
658 e.textarea.Placeholder = e.readyPlaceholder
659
660 return &e
661}
662
663func New(app *app.App) Editor {
664 return newEditor(app, fsext.ResolveDirectoryLister)
665}