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