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