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/client"
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 *client.Client
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", "alt+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
174func (m *editorCmp) Update(msg tea.Msg) (tea.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 info, err := m.app.GetAgentSessionInfo(context.TODO(), m.session.ID)
215 if err == nil && info.IsBusy {
216 return m, util.ReportWarn("Agent is working, please wait...")
217 }
218 return m, m.openEditor(m.textarea.Value())
219 case OpenEditorMsg:
220 m.textarea.SetValue(msg.Text)
221 m.textarea.MoveToEnd()
222 case tea.PasteMsg:
223 path := strings.ReplaceAll(string(msg), "\\ ", " ")
224 // try to get an image
225 path, err := filepath.Abs(strings.TrimSpace(path))
226 if err != nil {
227 m.textarea, cmd = m.textarea.Update(msg)
228 return m, cmd
229 }
230 isAllowedType := false
231 for _, ext := range filepicker.AllowedTypes {
232 if strings.HasSuffix(path, ext) {
233 isAllowedType = true
234 break
235 }
236 }
237 if !isAllowedType {
238 m.textarea, cmd = m.textarea.Update(msg)
239 return m, cmd
240 }
241 tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
242 if tooBig {
243 m.textarea, cmd = m.textarea.Update(msg)
244 return m, cmd
245 }
246
247 content, err := os.ReadFile(path)
248 if err != nil {
249 m.textarea, cmd = m.textarea.Update(msg)
250 return m, cmd
251 }
252 mimeBufferSize := min(512, len(content))
253 mimeType := http.DetectContentType(content[:mimeBufferSize])
254 fileName := filepath.Base(path)
255 attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
256 return m, util.CmdHandler(filepicker.FilePickedMsg{
257 Attachment: attachment,
258 })
259
260 case commands.ToggleYoloModeMsg:
261 m.setEditorPrompt()
262 return m, nil
263 case tea.KeyPressMsg:
264 cur := m.textarea.Cursor()
265 curIdx := m.textarea.Width()*cur.Y + cur.X
266 switch {
267 // Completions
268 case msg.String() == "/" && !m.isCompletionsOpen &&
269 // only show if beginning of prompt, or if previous char is a space or newline:
270 (len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
271 m.isCompletionsOpen = true
272 m.currentQuery = ""
273 m.completionsStartIndex = curIdx
274 cmds = append(cmds, m.startCompletions)
275 case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
276 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
277 }
278 if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
279 m.deleteMode = true
280 return m, nil
281 }
282 if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
283 m.deleteMode = false
284 m.attachments = nil
285 return m, nil
286 }
287 rune := msg.Code
288 if m.deleteMode && unicode.IsDigit(rune) {
289 num := int(rune - '0')
290 m.deleteMode = false
291 if num < 10 && len(m.attachments) > num {
292 if num == 0 {
293 m.attachments = m.attachments[num+1:]
294 } else {
295 m.attachments = slices.Delete(m.attachments, num, num+1)
296 }
297 return m, nil
298 }
299 }
300 if key.Matches(msg, m.keyMap.OpenEditor) {
301 info, err := m.app.GetAgentSessionInfo(context.TODO(), m.session.ID)
302 if err == nil && info.IsBusy {
303 return m, util.ReportWarn("Agent is working, please wait...")
304 }
305 return m, m.openEditor(m.textarea.Value())
306 }
307 if key.Matches(msg, DeleteKeyMaps.Escape) {
308 m.deleteMode = false
309 return m, nil
310 }
311 if key.Matches(msg, m.keyMap.Newline) {
312 m.textarea.InsertRune('\n')
313 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
314 }
315 // Handle Enter key
316 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
317 value := m.textarea.Value()
318 if strings.HasSuffix(value, "\\") {
319 // If the last character is a backslash, remove it and add a newline.
320 m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
321 } else {
322 // Otherwise, send the message
323 return m, m.send()
324 }
325 }
326 }
327
328 m.textarea, cmd = m.textarea.Update(msg)
329 cmds = append(cmds, cmd)
330
331 if m.textarea.Focused() {
332 kp, ok := msg.(tea.KeyPressMsg)
333 if ok {
334 if kp.String() == "space" || m.textarea.Value() == "" {
335 m.isCompletionsOpen = false
336 m.currentQuery = ""
337 m.completionsStartIndex = 0
338 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
339 } else {
340 word := m.textarea.Word()
341 if strings.HasPrefix(word, "/") {
342 // XXX: wont' work if editing in the middle of the field.
343 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
344 m.currentQuery = word[1:]
345 x, y := m.completionsPosition()
346 x -= len(m.currentQuery)
347 m.isCompletionsOpen = true
348 cmds = append(cmds,
349 util.CmdHandler(completions.FilterCompletionsMsg{
350 Query: m.currentQuery,
351 Reopen: m.isCompletionsOpen,
352 X: x,
353 Y: y,
354 }),
355 )
356 } else if m.isCompletionsOpen {
357 m.isCompletionsOpen = false
358 m.currentQuery = ""
359 m.completionsStartIndex = 0
360 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
361 }
362 }
363 }
364 }
365
366 return m, tea.Batch(cmds...)
367}
368
369func (m *editorCmp) setEditorPrompt() {
370 skip, err := m.app.GetPermissionsSkipRequests(context.TODO())
371 if err == nil && skip {
372 m.textarea.SetPromptFunc(4, yoloPromptFunc)
373 return
374 }
375 m.textarea.SetPromptFunc(4, normalPromptFunc)
376}
377
378func (m *editorCmp) completionsPosition() (int, int) {
379 cur := m.textarea.Cursor()
380 if cur == nil {
381 return m.x, m.y + 1 // adjust for padding
382 }
383 x := cur.X + m.x
384 y := cur.Y + m.y + 1 // adjust for padding
385 return x, y
386}
387
388func (m *editorCmp) Cursor() *tea.Cursor {
389 cursor := m.textarea.Cursor()
390 if cursor != nil {
391 cursor.X = cursor.X + m.x + 1
392 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
393 }
394 return cursor
395}
396
397var readyPlaceholders = [...]string{
398 "Ready!",
399 "Ready...",
400 "Ready?",
401 "Ready for instructions",
402}
403
404var workingPlaceholders = [...]string{
405 "Working!",
406 "Working...",
407 "Brrrrr...",
408 "Prrrrrrrr...",
409 "Processing...",
410 "Thinking...",
411}
412
413func (m *editorCmp) randomizePlaceholders() {
414 m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
415 m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
416}
417
418func (m *editorCmp) View() string {
419 t := styles.CurrentTheme()
420 // Update placeholder
421 info, err := m.app.GetAgentInfo(context.TODO())
422 if err == nil && info.IsBusy {
423 m.textarea.Placeholder = m.workingPlaceholder
424 } else {
425 m.textarea.Placeholder = m.readyPlaceholder
426 }
427 skip, err := m.app.GetPermissionsSkipRequests(context.TODO())
428 if err == nil && skip {
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 files, _, _ := fsext.ListDirectory(".", nil, 0)
489 slices.Sort(files)
490 completionItems := make([]completions.Completion, 0, len(files))
491 for _, file := range files {
492 file = strings.TrimPrefix(file, "./")
493 completionItems = append(completionItems, completions.Completion{
494 Title: file,
495 Value: FileCompletionItem{
496 Path: file,
497 },
498 })
499 }
500
501 x, y := m.completionsPosition()
502 return completions.OpenCompletionsMsg{
503 Completions: completionItems,
504 X: x,
505 Y: y,
506 }
507}
508
509// Blur implements Container.
510func (c *editorCmp) Blur() tea.Cmd {
511 c.textarea.Blur()
512 return nil
513}
514
515// Focus implements Container.
516func (c *editorCmp) Focus() tea.Cmd {
517 return c.textarea.Focus()
518}
519
520// IsFocused implements Container.
521func (c *editorCmp) IsFocused() bool {
522 return c.textarea.Focused()
523}
524
525// Bindings implements Container.
526func (c *editorCmp) Bindings() []key.Binding {
527 return c.keyMap.KeyBindings()
528}
529
530// TODO: most likely we do not need to have the session here
531// we need to move some functionality to the page level
532func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
533 c.session = session
534 return nil
535}
536
537func (c *editorCmp) IsCompletionsOpen() bool {
538 return c.isCompletionsOpen
539}
540
541func (c *editorCmp) HasAttachments() bool {
542 return len(c.attachments) > 0
543}
544
545func normalPromptFunc(info textarea.PromptInfo) string {
546 t := styles.CurrentTheme()
547 if info.LineNumber == 0 {
548 return " > "
549 }
550 if info.Focused {
551 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
552 }
553 return t.S().Muted.Render("::: ")
554}
555
556func yoloPromptFunc(info textarea.PromptInfo) string {
557 t := styles.CurrentTheme()
558 if info.LineNumber == 0 {
559 if info.Focused {
560 return fmt.Sprintf("%s ", t.YoloIconFocused)
561 } else {
562 return fmt.Sprintf("%s ", t.YoloIconBlurred)
563 }
564 }
565 if info.Focused {
566 return fmt.Sprintf("%s ", t.YoloDotsFocused)
567 }
568 return fmt.Sprintf("%s ", t.YoloDotsBlurred)
569}
570
571func New(app *client.Client) Editor {
572 t := styles.CurrentTheme()
573 ta := textarea.New()
574 ta.SetStyles(t.S().TextArea)
575 ta.ShowLineNumbers = false
576 ta.CharLimit = -1
577 ta.SetVirtualCursor(false)
578 ta.Focus()
579 e := &editorCmp{
580 // TODO: remove the app instance from here
581 app: app,
582 textarea: ta,
583 keyMap: DefaultEditorKeyMap(),
584 }
585 e.setEditorPrompt()
586
587 e.randomizePlaceholders()
588 e.textarea.Placeholder = e.readyPlaceholder
589
590 return e
591}