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