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