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