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