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