1package editor
2
3import (
4 "context"
5 "fmt"
6 "math/rand"
7 "net/http"
8 "os"
9 "path/filepath"
10 "runtime"
11 "slices"
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/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)
33
34type Editor interface {
35 util.Model
36 layout.Sizeable
37 layout.Focusable
38 layout.Help
39 layout.Positional
40
41 SetSession(session session.Session) tea.Cmd
42 IsCompletionsOpen() bool
43 HasAttachments() bool
44 Cursor() *tea.Cursor
45}
46
47type FileCompletionItem struct {
48 Path string // The file path
49}
50
51type editorCmp struct {
52 width int
53 height int
54 x, y int
55 app *app.App
56 session session.Session
57 textarea textarea.Model
58 attachments []message.Attachment
59 deleteMode bool
60 readyPlaceholder string
61 workingPlaceholder string
62
63 keyMap EditorKeyMap
64
65 // File path completions
66 currentQuery string
67 completionsStartIndex int
68 isCompletionsOpen bool
69}
70
71var DeleteKeyMaps = DeleteAttachmentKeyMaps{
72 AttachmentDeleteMode: key.NewBinding(
73 key.WithKeys("ctrl+r"),
74 key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
75 ),
76 Escape: key.NewBinding(
77 key.WithKeys("esc", "alt+esc"),
78 key.WithHelp("esc", "cancel delete mode"),
79 ),
80 DeleteAllAttachments: key.NewBinding(
81 key.WithKeys("r"),
82 key.WithHelp("ctrl+r+r", "delete all attachments"),
83 ),
84}
85
86const (
87 maxAttachments = 5
88 maxFileResults = 25
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
115 // Build the full shell command with the file argument.
116 cmdStr := fmt.Sprintf("%s %s", editor, tmpfile.Name())
117
118 return util.ExecShell(context.TODO(), cmdStr, 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
174func (m *editorCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
175 var cmd tea.Cmd
176 var cmds []tea.Cmd
177 switch msg := msg.(type) {
178 case tea.WindowSizeMsg:
179 return m, m.repositionCompletions
180 case filepicker.FilePickedMsg:
181 if len(m.attachments) >= maxAttachments {
182 return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
183 }
184 m.attachments = append(m.attachments, msg.Attachment)
185 return m, nil
186 case completions.CompletionsOpenedMsg:
187 m.isCompletionsOpen = true
188 case completions.CompletionsClosedMsg:
189 m.isCompletionsOpen = false
190 m.currentQuery = ""
191 m.completionsStartIndex = 0
192 case completions.SelectCompletionMsg:
193 if !m.isCompletionsOpen {
194 return m, nil
195 }
196 if item, ok := msg.Value.(FileCompletionItem); ok {
197 word := m.textarea.Word()
198 // If the selected item is a file, insert its path into the textarea
199 value := m.textarea.Value()
200 value = value[:m.completionsStartIndex] + // Remove the current query
201 item.Path + // Insert the file path
202 value[m.completionsStartIndex+len(word):] // Append the rest of the value
203 // XXX: This will always move the cursor to the end of the textarea.
204 m.textarea.SetValue(value)
205 m.textarea.MoveToEnd()
206 if !msg.Insert {
207 m.isCompletionsOpen = false
208 m.currentQuery = ""
209 m.completionsStartIndex = 0
210 }
211 }
212
213 case commands.OpenExternalEditorMsg:
214 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
215 return m, util.ReportWarn("Agent is working, please wait...")
216 }
217 return m, m.openEditor(m.textarea.Value())
218 case OpenEditorMsg:
219 m.textarea.SetValue(msg.Text)
220 m.textarea.MoveToEnd()
221 case tea.PasteMsg:
222 path := strings.ReplaceAll(msg.Content, "\\ ", " ")
223 // try to get an image
224 path, err := filepath.Abs(strings.TrimSpace(path))
225 if err != nil {
226 m.textarea, cmd = m.textarea.Update(msg)
227 return m, cmd
228 }
229 isAllowedType := false
230 for _, ext := range filepicker.AllowedTypes {
231 if strings.HasSuffix(path, ext) {
232 isAllowedType = true
233 break
234 }
235 }
236 if !isAllowedType {
237 m.textarea, cmd = m.textarea.Update(msg)
238 return m, cmd
239 }
240 tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
241 if tooBig {
242 m.textarea, cmd = m.textarea.Update(msg)
243 return m, cmd
244 }
245
246 content, err := os.ReadFile(path)
247 if err != nil {
248 m.textarea, cmd = m.textarea.Update(msg)
249 return m, cmd
250 }
251 mimeBufferSize := min(512, len(content))
252 mimeType := http.DetectContentType(content[:mimeBufferSize])
253 fileName := filepath.Base(path)
254 attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
255 return m, util.CmdHandler(filepicker.FilePickedMsg{
256 Attachment: attachment,
257 })
258
259 case commands.ToggleYoloModeMsg:
260 m.setEditorPrompt()
261 return m, nil
262 case tea.KeyPressMsg:
263 cur := m.textarea.Cursor()
264 curIdx := m.textarea.Width()*cur.Y + cur.X
265 switch {
266 // Open command palette when "/" is pressed on empty prompt
267 case msg.String() == "/" && len(strings.TrimSpace(m.textarea.Value())) == 0:
268 return m, util.CmdHandler(dialogs.OpenDialogMsg{
269 Model: commands.NewCommandDialog(m.session.ID),
270 })
271 // Completions
272 case msg.String() == "@" && !m.isCompletionsOpen &&
273 // only show if beginning of prompt, or if previous char is a space or newline:
274 (len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
275 m.isCompletionsOpen = true
276 m.currentQuery = ""
277 m.completionsStartIndex = curIdx
278 cmds = append(cmds, m.startCompletions)
279 case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
280 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
281 }
282 if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
283 m.deleteMode = true
284 return m, nil
285 }
286 if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
287 m.deleteMode = false
288 m.attachments = nil
289 return m, nil
290 }
291 rune := msg.Code
292 if m.deleteMode && unicode.IsDigit(rune) {
293 num := int(rune - '0')
294 m.deleteMode = false
295 if num < 10 && len(m.attachments) > num {
296 if num == 0 {
297 m.attachments = m.attachments[num+1:]
298 } else {
299 m.attachments = slices.Delete(m.attachments, num, num+1)
300 }
301 return m, nil
302 }
303 }
304 if key.Matches(msg, m.keyMap.OpenEditor) {
305 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
306 return m, util.ReportWarn("Agent is working, please wait...")
307 }
308 return m, m.openEditor(m.textarea.Value())
309 }
310 if key.Matches(msg, DeleteKeyMaps.Escape) {
311 m.deleteMode = false
312 return m, nil
313 }
314 if key.Matches(msg, m.keyMap.Newline) {
315 m.textarea.InsertRune('\n')
316 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
317 }
318 // Handle Enter key
319 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
320 value := m.textarea.Value()
321 if strings.HasSuffix(value, "\\") {
322 // If the last character is a backslash, remove it and add a newline.
323 m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
324 } else {
325 // Otherwise, send the message
326 return m, m.send()
327 }
328 }
329 }
330
331 m.textarea, cmd = m.textarea.Update(msg)
332 cmds = append(cmds, cmd)
333
334 if m.textarea.Focused() {
335 kp, ok := msg.(tea.KeyPressMsg)
336 if ok {
337 if kp.String() == "space" || m.textarea.Value() == "" {
338 m.isCompletionsOpen = false
339 m.currentQuery = ""
340 m.completionsStartIndex = 0
341 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
342 } else {
343 word := m.textarea.Word()
344 if strings.HasPrefix(word, "@") {
345 // XXX: wont' work if editing in the middle of the field.
346 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
347 m.currentQuery = word[1:]
348 x, y := m.completionsPosition()
349 x -= len(m.currentQuery)
350 m.isCompletionsOpen = true
351 cmds = append(cmds,
352 util.CmdHandler(completions.FilterCompletionsMsg{
353 Query: m.currentQuery,
354 Reopen: m.isCompletionsOpen,
355 X: x,
356 Y: y,
357 }),
358 )
359 } else if m.isCompletionsOpen {
360 m.isCompletionsOpen = false
361 m.currentQuery = ""
362 m.completionsStartIndex = 0
363 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
364 }
365 }
366 }
367 }
368
369 return m, tea.Batch(cmds...)
370}
371
372func (m *editorCmp) setEditorPrompt() {
373 if m.app.Permissions.SkipRequests() {
374 m.textarea.SetPromptFunc(4, yoloPromptFunc)
375 return
376 }
377 m.textarea.SetPromptFunc(4, normalPromptFunc)
378}
379
380func (m *editorCmp) completionsPosition() (int, int) {
381 cur := m.textarea.Cursor()
382 if cur == nil {
383 return m.x, m.y + 1 // adjust for padding
384 }
385 x := cur.X + m.x
386 y := cur.Y + m.y + 1 // adjust for padding
387 return x, y
388}
389
390func (m *editorCmp) Cursor() *tea.Cursor {
391 cursor := m.textarea.Cursor()
392 if cursor != nil {
393 cursor.X = cursor.X + m.x + 1
394 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
395 }
396 return cursor
397}
398
399var readyPlaceholders = [...]string{
400 "Ready!",
401 "Ready...",
402 "Ready?",
403 "Ready for instructions",
404}
405
406var workingPlaceholders = [...]string{
407 "Working!",
408 "Working...",
409 "Brrrrr...",
410 "Prrrrrrrr...",
411 "Processing...",
412 "Thinking...",
413}
414
415func (m *editorCmp) randomizePlaceholders() {
416 m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
417 m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
418}
419
420func (m *editorCmp) View() string {
421 t := styles.CurrentTheme()
422 // Update placeholder
423 if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
424 m.textarea.Placeholder = m.workingPlaceholder
425 } else {
426 m.textarea.Placeholder = m.readyPlaceholder
427 }
428 if m.app.Permissions.SkipRequests() {
429 m.textarea.Placeholder = "Yolo mode!"
430 }
431 if len(m.attachments) == 0 {
432 content := t.S().Base.Padding(1).Render(
433 m.textarea.View(),
434 )
435 return content
436 }
437 content := t.S().Base.Padding(0, 1, 1, 1).Render(
438 lipgloss.JoinVertical(lipgloss.Top,
439 m.attachmentsContent(),
440 m.textarea.View(),
441 ),
442 )
443 return content
444}
445
446func (m *editorCmp) SetSize(width, height int) tea.Cmd {
447 m.width = width
448 m.height = height
449 m.textarea.SetWidth(width - 2) // adjust for padding
450 m.textarea.SetHeight(height - 2) // adjust for padding
451 return nil
452}
453
454func (m *editorCmp) GetSize() (int, int) {
455 return m.textarea.Width(), m.textarea.Height()
456}
457
458func (m *editorCmp) attachmentsContent() string {
459 var styledAttachments []string
460 t := styles.CurrentTheme()
461 attachmentStyles := t.S().Base.
462 MarginLeft(1).
463 Background(t.FgMuted).
464 Foreground(t.FgBase)
465 for i, attachment := range m.attachments {
466 var filename string
467 if len(attachment.FileName) > 10 {
468 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
469 } else {
470 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
471 }
472 if m.deleteMode {
473 filename = fmt.Sprintf("%d%s", i, filename)
474 }
475 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
476 }
477 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
478 return content
479}
480
481func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
482 m.x = x
483 m.y = y
484 return nil
485}
486
487func (m *editorCmp) startCompletions() tea.Msg {
488 ls := m.app.Config().Options.TUI.Completions
489 depth, limit := ls.Limits()
490 files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
491 slices.Sort(files)
492 completionItems := make([]completions.Completion, 0, len(files))
493 for _, file := range files {
494 file = strings.TrimPrefix(file, "./")
495 completionItems = append(completionItems, completions.Completion{
496 Title: file,
497 Value: FileCompletionItem{
498 Path: file,
499 },
500 })
501 }
502
503 x, y := m.completionsPosition()
504 return completions.OpenCompletionsMsg{
505 Completions: completionItems,
506 X: x,
507 Y: y,
508 MaxResults: maxFileResults,
509 }
510}
511
512// Blur implements Container.
513func (c *editorCmp) Blur() tea.Cmd {
514 c.textarea.Blur()
515 return nil
516}
517
518// Focus implements Container.
519func (c *editorCmp) Focus() tea.Cmd {
520 return c.textarea.Focus()
521}
522
523// IsFocused implements Container.
524func (c *editorCmp) IsFocused() bool {
525 return c.textarea.Focused()
526}
527
528// Bindings implements Container.
529func (c *editorCmp) Bindings() []key.Binding {
530 return c.keyMap.KeyBindings()
531}
532
533// TODO: most likely we do not need to have the session here
534// we need to move some functionality to the page level
535func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
536 c.session = session
537 return nil
538}
539
540func (c *editorCmp) IsCompletionsOpen() bool {
541 return c.isCompletionsOpen
542}
543
544func (c *editorCmp) HasAttachments() bool {
545 return len(c.attachments) > 0
546}
547
548func normalPromptFunc(info textarea.PromptInfo) string {
549 t := styles.CurrentTheme()
550 if info.LineNumber == 0 {
551 return " > "
552 }
553 if info.Focused {
554 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
555 }
556 return t.S().Muted.Render("::: ")
557}
558
559func yoloPromptFunc(info textarea.PromptInfo) string {
560 t := styles.CurrentTheme()
561 if info.LineNumber == 0 {
562 if info.Focused {
563 return fmt.Sprintf("%s ", t.YoloIconFocused)
564 } else {
565 return fmt.Sprintf("%s ", t.YoloIconBlurred)
566 }
567 }
568 if info.Focused {
569 return fmt.Sprintf("%s ", t.YoloDotsFocused)
570 }
571 return fmt.Sprintf("%s ", t.YoloDotsBlurred)
572}
573
574func New(app *app.App) Editor {
575 t := styles.CurrentTheme()
576 ta := textarea.New()
577 ta.SetStyles(t.S().TextArea)
578 ta.ShowLineNumbers = false
579 ta.CharLimit = -1
580 ta.SetVirtualCursor(false)
581 ta.Focus()
582 e := &editorCmp{
583 // TODO: remove the app instance from here
584 app: app,
585 textarea: ta,
586 keyMap: DefaultEditorKeyMap(),
587 }
588 e.setEditorPrompt()
589
590 e.randomizePlaceholders()
591 e.textarea.Placeholder = e.readyPlaceholder
592
593 return e
594}