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