1package editor
2
3import (
4 "fmt"
5 "math/rand"
6 "net/http"
7 "os"
8 "path/filepath"
9 "regexp"
10 "slices"
11 "strconv"
12 "strings"
13 "unicode"
14
15 "charm.land/bubbles/v2/key"
16 "charm.land/bubbles/v2/textarea"
17 tea "charm.land/bubbletea/v2"
18 "charm.land/lipgloss/v2"
19 "github.com/charmbracelet/crush/internal/app"
20 "github.com/charmbracelet/crush/internal/filetracker"
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/x/ansi"
34 "github.com/charmbracelet/x/editor"
35)
36
37type Editor interface {
38 util.Model
39 layout.Sizeable
40 layout.Focusable
41 layout.Help
42 layout.Positional
43
44 SetSession(session session.Session) tea.Cmd
45 IsCompletionsOpen() bool
46 HasAttachments() bool
47 IsEmpty() 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 // 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", "alt+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 maxFileResults = 25
91
92type OpenEditorMsg struct {
93 Text string
94}
95
96func (m *editorCmp) openEditor(value string) tea.Cmd {
97 tmpfile, err := os.CreateTemp("", "msg_*.md")
98 if err != nil {
99 return util.ReportError(err)
100 }
101 defer tmpfile.Close() //nolint:errcheck
102 if _, err := tmpfile.WriteString(value); err != nil {
103 return util.ReportError(err)
104 }
105 cmd, err := editor.Command(
106 "crush",
107 tmpfile.Name(),
108 editor.AtPosition(
109 m.textarea.Line()+1,
110 m.textarea.Column()+1,
111 ),
112 )
113 if err != nil {
114 return util.ReportError(err)
115 }
116 return tea.ExecProcess(cmd, func(err error) tea.Msg {
117 if err != nil {
118 return util.ReportError(err)
119 }
120 content, err := os.ReadFile(tmpfile.Name())
121 if err != nil {
122 return util.ReportError(err)
123 }
124 if len(content) == 0 {
125 return util.ReportWarn("Message is empty")
126 }
127 os.Remove(tmpfile.Name())
128 return OpenEditorMsg{
129 Text: strings.TrimSpace(string(content)),
130 }
131 })
132}
133
134func (m *editorCmp) Init() tea.Cmd {
135 return nil
136}
137
138func (m *editorCmp) send() tea.Cmd {
139 value := m.textarea.Value()
140 value = strings.TrimSpace(value)
141
142 switch value {
143 case "exit", "quit":
144 m.textarea.Reset()
145 return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
146 }
147
148 attachments := m.attachments
149
150 if value == "" && !message.ContainsTextAttachment(attachments) {
151 return nil
152 }
153
154 m.textarea.Reset()
155 m.attachments = nil
156 // Change the placeholder when sending a new message.
157 m.randomizePlaceholders()
158
159 return tea.Batch(
160 util.CmdHandler(chat.SendMsg{
161 Text: value,
162 Attachments: attachments,
163 }),
164 )
165}
166
167func (m *editorCmp) repositionCompletions() tea.Msg {
168 x, y := m.completionsPosition()
169 return completions.RepositionCompletionsMsg{X: x, Y: y}
170}
171
172func (m *editorCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
173 var cmd tea.Cmd
174 var cmds []tea.Cmd
175 switch msg := msg.(type) {
176 case tea.WindowSizeMsg:
177 return m, m.repositionCompletions
178 case filepicker.FilePickedMsg:
179 m.attachments = append(m.attachments, msg.Attachment)
180 return m, nil
181 case completions.CompletionsOpenedMsg:
182 m.isCompletionsOpen = true
183 case completions.CompletionsClosedMsg:
184 m.isCompletionsOpen = false
185 m.currentQuery = ""
186 m.completionsStartIndex = 0
187 case completions.SelectCompletionMsg:
188 if !m.isCompletionsOpen {
189 return m, nil
190 }
191 if item, ok := msg.Value.(FileCompletionItem); ok {
192 word := m.textarea.Word()
193 // If the selected item is a file, insert its path into the textarea
194 value := m.textarea.Value()
195 value = value[:m.completionsStartIndex] + // Remove the current query
196 item.Path + // Insert the file path
197 value[m.completionsStartIndex+len(word):] // Append the rest of the value
198 // XXX: This will always move the cursor to the end of the textarea.
199 m.textarea.SetValue(value)
200 m.textarea.MoveToEnd()
201 if !msg.Insert {
202 m.isCompletionsOpen = false
203 m.currentQuery = ""
204 m.completionsStartIndex = 0
205 }
206 absPath, _ := filepath.Abs(item.Path)
207 // Skip attachment if file was already read and hasn't been modified.
208 lastRead := filetracker.LastReadTime(absPath)
209 if !lastRead.IsZero() {
210 if info, err := os.Stat(item.Path); err == nil && !info.ModTime().After(lastRead) {
211 return m, nil
212 }
213 }
214 content, err := os.ReadFile(item.Path)
215 if err != nil {
216 // if it fails, let the LLM handle it later.
217 return m, nil
218 }
219 filetracker.RecordRead(absPath)
220 m.attachments = append(m.attachments, message.Attachment{
221 FilePath: item.Path,
222 FileName: filepath.Base(item.Path),
223 MimeType: mimeOf(content),
224 Content: content,
225 })
226 }
227
228 case commands.OpenExternalEditorMsg:
229 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
230 return m, util.ReportWarn("Agent is working, please wait...")
231 }
232 return m, m.openEditor(m.textarea.Value())
233 case OpenEditorMsg:
234 m.textarea.SetValue(msg.Text)
235 m.textarea.MoveToEnd()
236 case tea.PasteMsg:
237 // If pasted text has more than 2 newlines, treat it as a file attachment.
238 if strings.Count(msg.Content, "\n") > 2 {
239 content := []byte(msg.Content)
240 if len(content) > maxAttachmentSize {
241 return m, util.ReportWarn("Paste is too big (>5mb)")
242 }
243 name := fmt.Sprintf("paste_%d.txt", m.pasteIdx())
244 mimeType := mimeOf(content)
245 attachment := message.Attachment{
246 FileName: name,
247 FilePath: name,
248 MimeType: mimeType,
249 Content: content,
250 }
251 return m, util.CmdHandler(filepicker.FilePickedMsg{
252 Attachment: attachment,
253 })
254 }
255
256 // Try to parse as a file path.
257 content, path, err := filepathToFile(msg.Content)
258 if err != nil {
259 // Not a file path, just update the textarea normally.
260 m.textarea, cmd = m.textarea.Update(msg)
261 return m, cmd
262 }
263
264 if len(content) > maxAttachmentSize {
265 return m, util.ReportWarn("File is too big (>5mb)")
266 }
267
268 mimeType := mimeOf(content)
269 attachment := message.Attachment{
270 FilePath: path,
271 FileName: filepath.Base(path),
272 MimeType: mimeType,
273 Content: content,
274 }
275 if !attachment.IsText() && !attachment.IsImage() {
276 return m, util.ReportWarn("Invalid file content type: " + mimeType)
277 }
278 return m, util.CmdHandler(filepicker.FilePickedMsg{
279 Attachment: attachment,
280 })
281
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 // Open command palette when "/" is pressed on empty prompt
290 case msg.String() == "/" && m.IsEmpty():
291 return m, util.CmdHandler(dialogs.OpenDialogMsg{
292 Model: commands.NewCommandDialog(m.session.ID),
293 })
294 // Completions
295 case msg.String() == "@" && !m.isCompletionsOpen &&
296 // only show if beginning of prompt, or if previous char is a space or newline:
297 (len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
298 m.isCompletionsOpen = true
299 m.currentQuery = ""
300 m.completionsStartIndex = curIdx
301 cmds = append(cmds, m.startCompletions)
302 case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
303 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
304 }
305 if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
306 m.deleteMode = true
307 return m, nil
308 }
309 if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
310 m.deleteMode = false
311 m.attachments = nil
312 return m, nil
313 }
314 rune := msg.Code
315 if m.deleteMode && unicode.IsDigit(rune) {
316 num := int(rune - '0')
317 m.deleteMode = false
318 if num < 10 && len(m.attachments) > num {
319 if num == 0 {
320 m.attachments = m.attachments[num+1:]
321 } else {
322 m.attachments = slices.Delete(m.attachments, num, num+1)
323 }
324 return m, nil
325 }
326 }
327 if key.Matches(msg, m.keyMap.OpenEditor) {
328 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
329 return m, util.ReportWarn("Agent is working, please wait...")
330 }
331 return m, m.openEditor(m.textarea.Value())
332 }
333 if key.Matches(msg, DeleteKeyMaps.Escape) {
334 m.deleteMode = false
335 return m, nil
336 }
337 if key.Matches(msg, m.keyMap.Newline) {
338 m.textarea.InsertRune('\n')
339 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
340 }
341 // Handle Enter key
342 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
343 value := m.textarea.Value()
344 if strings.HasSuffix(value, "\\") {
345 // If the last character is a backslash, remove it and add a newline.
346 m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
347 } else {
348 // Otherwise, send the message
349 return m, m.send()
350 }
351 }
352 }
353
354 m.textarea, cmd = m.textarea.Update(msg)
355 cmds = append(cmds, cmd)
356
357 if m.textarea.Focused() {
358 kp, ok := msg.(tea.KeyPressMsg)
359 if ok {
360 if kp.String() == "space" || m.textarea.Value() == "" {
361 m.isCompletionsOpen = false
362 m.currentQuery = ""
363 m.completionsStartIndex = 0
364 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
365 } else {
366 word := m.textarea.Word()
367 if strings.HasPrefix(word, "@") {
368 // XXX: wont' work if editing in the middle of the field.
369 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
370 m.currentQuery = word[1:]
371 x, y := m.completionsPosition()
372 x -= len(m.currentQuery)
373 m.isCompletionsOpen = true
374 cmds = append(cmds,
375 util.CmdHandler(completions.FilterCompletionsMsg{
376 Query: m.currentQuery,
377 Reopen: m.isCompletionsOpen,
378 X: x,
379 Y: y,
380 }),
381 )
382 } else if m.isCompletionsOpen {
383 m.isCompletionsOpen = false
384 m.currentQuery = ""
385 m.completionsStartIndex = 0
386 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
387 }
388 }
389 }
390 }
391
392 return m, tea.Batch(cmds...)
393}
394
395func (m *editorCmp) setEditorPrompt() {
396 if m.app.Permissions.SkipRequests() {
397 m.textarea.SetPromptFunc(4, yoloPromptFunc)
398 return
399 }
400 m.textarea.SetPromptFunc(4, normalPromptFunc)
401}
402
403func (m *editorCmp) completionsPosition() (int, int) {
404 cur := m.textarea.Cursor()
405 if cur == nil {
406 return m.x, m.y + 1 // adjust for padding
407 }
408 x := cur.X + m.x
409 y := cur.Y + m.y + 1 // adjust for padding
410 return x, y
411}
412
413func (m *editorCmp) Cursor() *tea.Cursor {
414 cursor := m.textarea.Cursor()
415 if cursor != nil {
416 cursor.X = cursor.X + m.x + 1
417 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
418 }
419 return cursor
420}
421
422var readyPlaceholders = [...]string{
423 "Ready!",
424 "Ready...",
425 "Ready?",
426 "Ready for instructions",
427}
428
429var workingPlaceholders = [...]string{
430 "Working!",
431 "Working...",
432 "Brrrrr...",
433 "Prrrrrrrr...",
434 "Processing...",
435 "Thinking...",
436}
437
438func (m *editorCmp) randomizePlaceholders() {
439 m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
440 m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
441}
442
443func (m *editorCmp) View() string {
444 t := styles.CurrentTheme()
445 // Update placeholder
446 if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
447 m.textarea.Placeholder = m.workingPlaceholder
448 } else {
449 m.textarea.Placeholder = m.readyPlaceholder
450 }
451 if m.app.Permissions.SkipRequests() {
452 m.textarea.Placeholder = "Yolo mode!"
453 }
454 if len(m.attachments) == 0 {
455 return t.S().Base.Padding(1).Render(
456 m.textarea.View(),
457 )
458 }
459 return t.S().Base.Padding(0, 1, 1, 1).Render(
460 lipgloss.JoinVertical(
461 lipgloss.Top,
462 m.attachmentsContent(),
463 m.textarea.View(),
464 ),
465 )
466}
467
468func (m *editorCmp) SetSize(width, height int) tea.Cmd {
469 m.width = width
470 m.height = height
471 m.textarea.SetWidth(width - 2) // adjust for padding
472 m.textarea.SetHeight(height - 2) // adjust for padding
473 return nil
474}
475
476func (m *editorCmp) GetSize() (int, int) {
477 return m.textarea.Width(), m.textarea.Height()
478}
479
480func (m *editorCmp) attachmentsContent() string {
481 var styledAttachments []string
482 t := styles.CurrentTheme()
483 attachmentStyle := t.S().Base.
484 Padding(0, 1).
485 MarginRight(1).
486 Background(t.FgMuted).
487 Foreground(t.FgBase).
488 Render
489 iconStyle := t.S().Base.
490 Foreground(t.BgSubtle).
491 Background(t.Green).
492 Padding(0, 1).
493 Bold(true).
494 Render
495 rmStyle := t.S().Base.
496 Padding(0, 1).
497 Bold(true).
498 Background(t.Red).
499 Foreground(t.FgBase).
500 Render
501 for i, attachment := range m.attachments {
502 filename := ansi.Truncate(filepath.Base(attachment.FileName), 10, "...")
503 icon := styles.ImageIcon
504 if attachment.IsText() {
505 icon = styles.TextIcon
506 }
507 if m.deleteMode {
508 styledAttachments = append(
509 styledAttachments,
510 rmStyle(fmt.Sprintf("%d", i)),
511 attachmentStyle(filename),
512 )
513 continue
514 }
515 styledAttachments = append(
516 styledAttachments,
517 iconStyle(icon),
518 attachmentStyle(filename),
519 )
520 }
521 return lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
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 ls := m.app.Config().Options.TUI.Completions
532 depth, limit := ls.Limits()
533 files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
534 slices.Sort(files)
535 completionItems := make([]completions.Completion, 0, len(files))
536 for _, file := range files {
537 file = strings.TrimPrefix(file, "./")
538 completionItems = append(completionItems, completions.Completion{
539 Title: file,
540 Value: FileCompletionItem{
541 Path: file,
542 },
543 })
544 }
545
546 x, y := m.completionsPosition()
547 return completions.OpenCompletionsMsg{
548 Completions: completionItems,
549 X: x,
550 Y: y,
551 MaxResults: maxFileResults,
552 }
553}
554
555// Blur implements Container.
556func (c *editorCmp) Blur() tea.Cmd {
557 c.textarea.Blur()
558 return nil
559}
560
561// Focus implements Container.
562func (c *editorCmp) Focus() tea.Cmd {
563 return c.textarea.Focus()
564}
565
566// IsFocused implements Container.
567func (c *editorCmp) IsFocused() bool {
568 return c.textarea.Focused()
569}
570
571// Bindings implements Container.
572func (c *editorCmp) Bindings() []key.Binding {
573 return c.keyMap.KeyBindings()
574}
575
576// TODO: most likely we do not need to have the session here
577// we need to move some functionality to the page level
578func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
579 c.session = session
580 return nil
581}
582
583func (c *editorCmp) IsCompletionsOpen() bool {
584 return c.isCompletionsOpen
585}
586
587func (c *editorCmp) HasAttachments() bool {
588 return len(c.attachments) > 0
589}
590
591func (c *editorCmp) IsEmpty() bool {
592 return strings.TrimSpace(c.textarea.Value()) == ""
593}
594
595func normalPromptFunc(info textarea.PromptInfo) string {
596 t := styles.CurrentTheme()
597 if info.LineNumber == 0 {
598 if info.Focused {
599 return " > "
600 }
601 return "::: "
602 }
603 if info.Focused {
604 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
605 }
606 return t.S().Muted.Render("::: ")
607}
608
609func yoloPromptFunc(info textarea.PromptInfo) string {
610 t := styles.CurrentTheme()
611 if info.LineNumber == 0 {
612 if info.Focused {
613 return fmt.Sprintf("%s ", t.YoloIconFocused)
614 } else {
615 return fmt.Sprintf("%s ", t.YoloIconBlurred)
616 }
617 }
618 if info.Focused {
619 return fmt.Sprintf("%s ", t.YoloDotsFocused)
620 }
621 return fmt.Sprintf("%s ", t.YoloDotsBlurred)
622}
623
624func New(app *app.App) Editor {
625 t := styles.CurrentTheme()
626 ta := textarea.New()
627 ta.SetStyles(t.S().TextArea)
628 ta.ShowLineNumbers = false
629 ta.CharLimit = -1
630 ta.SetVirtualCursor(false)
631 ta.Focus()
632 e := &editorCmp{
633 // TODO: remove the app instance from here
634 app: app,
635 textarea: ta,
636 keyMap: DefaultEditorKeyMap(),
637 }
638 e.setEditorPrompt()
639
640 e.randomizePlaceholders()
641 e.textarea.Placeholder = e.readyPlaceholder
642
643 return e
644}
645
646var maxAttachmentSize = 5 * 1024 * 1024 // 5MB
647
648var pasteRE = regexp.MustCompile(`paste_(\d+).txt`)
649
650func (m *editorCmp) pasteIdx() int {
651 result := 0
652 for _, at := range m.attachments {
653 found := pasteRE.FindStringSubmatch(at.FileName)
654 if len(found) == 0 {
655 continue
656 }
657 idx, err := strconv.Atoi(found[1])
658 if err == nil {
659 result = max(result, idx)
660 }
661 }
662 return result + 1
663}
664
665func filepathToFile(name string) ([]byte, string, error) {
666 path, err := filepath.Abs(strings.TrimSpace(strings.ReplaceAll(name, "\\", "")))
667 if err != nil {
668 return nil, "", err
669 }
670 content, err := os.ReadFile(path)
671 if err != nil {
672 return nil, "", err
673 }
674 return content, path, nil
675}
676
677func mimeOf(content []byte) string {
678 mimeBufferSize := min(512, len(content))
679 return http.DetectContentType(content[:mimeBufferSize])
680}