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", "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 maxFileResults = 25
90)
91
92type OpenEditorMsg struct {
93 Text string
94}
95
96func (m *editorCmp) openEditor(value string) tea.Cmd {
97 editor := os.Getenv("EDITOR")
98 if editor == "" {
99 // Use platform-appropriate default editor
100 if runtime.GOOS == "windows" {
101 editor = "notepad"
102 } else {
103 editor = "nvim"
104 }
105 }
106
107 tmpfile, err := os.CreateTemp("", "msg_*.md")
108 if err != nil {
109 return util.ReportError(err)
110 }
111 defer tmpfile.Close() //nolint:errcheck
112 if _, err := tmpfile.WriteString(value); err != nil {
113 return util.ReportError(err)
114 }
115 c := exec.CommandContext(context.TODO(), editor, tmpfile.Name())
116 c.Stdin = os.Stdin
117 c.Stdout = os.Stdout
118 c.Stderr = os.Stderr
119 return tea.ExecProcess(c, func(err error) tea.Msg {
120 if err != nil {
121 return util.ReportError(err)
122 }
123 content, err := os.ReadFile(tmpfile.Name())
124 if err != nil {
125 return util.ReportError(err)
126 }
127 if len(content) == 0 {
128 return util.ReportWarn("Message is empty")
129 }
130 os.Remove(tmpfile.Name())
131 return OpenEditorMsg{
132 Text: strings.TrimSpace(string(content)),
133 }
134 })
135}
136
137func (m *editorCmp) Init() tea.Cmd {
138 return nil
139}
140
141func (m *editorCmp) send() tea.Cmd {
142 value := m.textarea.Value()
143 value = strings.TrimSpace(value)
144
145 switch value {
146 case "exit", "quit":
147 m.textarea.Reset()
148 return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
149 }
150
151 m.textarea.Reset()
152 attachments := m.attachments
153
154 m.attachments = nil
155 if value == "" {
156 return nil
157 }
158
159 // Change the placeholder when sending a new message.
160 m.randomizePlaceholders()
161
162 return tea.Batch(
163 util.CmdHandler(chat.SendMsg{
164 Text: value,
165 Attachments: attachments,
166 }),
167 )
168}
169
170func (m *editorCmp) repositionCompletions() tea.Msg {
171 x, y := m.completionsPosition()
172 return completions.RepositionCompletionsMsg{X: x, Y: y}
173}
174
175func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
176 var cmd tea.Cmd
177 var cmds []tea.Cmd
178 switch msg := msg.(type) {
179 case tea.WindowSizeMsg:
180 return m, m.repositionCompletions
181 case filepicker.FilePickedMsg:
182 if len(m.attachments) >= maxAttachments {
183 return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
184 }
185 m.attachments = append(m.attachments, msg.Attachment)
186 return m, nil
187 case completions.CompletionsOpenedMsg:
188 m.isCompletionsOpen = true
189 case completions.CompletionsClosedMsg:
190 m.isCompletionsOpen = false
191 m.currentQuery = ""
192 m.completionsStartIndex = 0
193 case completions.SelectCompletionMsg:
194 if !m.isCompletionsOpen {
195 return m, nil
196 }
197 if item, ok := msg.Value.(FileCompletionItem); ok {
198 word := m.textarea.Word()
199 // If the selected item is a file, insert its path into the textarea
200 value := m.textarea.Value()
201 value = value[:m.completionsStartIndex] + // Remove the current query
202 item.Path + // Insert the file path
203 value[m.completionsStartIndex+len(word):] // Append the rest of the value
204 // XXX: This will always move the cursor to the end of the textarea.
205 m.textarea.SetValue(value)
206 m.textarea.MoveToEnd()
207 if !msg.Insert {
208 m.isCompletionsOpen = false
209 m.currentQuery = ""
210 m.completionsStartIndex = 0
211 }
212 }
213
214 case commands.OpenExternalEditorMsg:
215 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
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 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
302 return m, util.ReportWarn("Agent is working, please wait...")
303 }
304 return m, m.openEditor(m.textarea.Value())
305 }
306 if key.Matches(msg, DeleteKeyMaps.Escape) {
307 m.deleteMode = false
308 return m, nil
309 }
310 if key.Matches(msg, m.keyMap.Newline) {
311 m.textarea.InsertRune('\n')
312 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
313 }
314 // Handle Enter key
315 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
316 value := m.textarea.Value()
317 if strings.HasSuffix(value, "\\") {
318 // If the last character is a backslash, remove it and add a newline.
319 m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
320 } else {
321 // Otherwise, send the message
322 return m, m.send()
323 }
324 }
325 }
326
327 m.textarea, cmd = m.textarea.Update(msg)
328 cmds = append(cmds, cmd)
329
330 if m.textarea.Focused() {
331 kp, ok := msg.(tea.KeyPressMsg)
332 if ok {
333 if kp.String() == "space" || m.textarea.Value() == "" {
334 m.isCompletionsOpen = false
335 m.currentQuery = ""
336 m.completionsStartIndex = 0
337 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
338 } else {
339 word := m.textarea.Word()
340 if strings.HasPrefix(word, "/") {
341 // XXX: wont' work if editing in the middle of the field.
342 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
343 m.currentQuery = word[1:]
344 x, y := m.completionsPosition()
345 x -= len(m.currentQuery)
346 m.isCompletionsOpen = true
347 cmds = append(cmds,
348 util.CmdHandler(completions.FilterCompletionsMsg{
349 Query: m.currentQuery,
350 Reopen: m.isCompletionsOpen,
351 X: x,
352 Y: y,
353 }),
354 )
355 } else if m.isCompletionsOpen {
356 m.isCompletionsOpen = false
357 m.currentQuery = ""
358 m.completionsStartIndex = 0
359 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
360 }
361 }
362 }
363 }
364
365 return m, tea.Batch(cmds...)
366}
367
368func (m *editorCmp) setEditorPrompt() {
369 if m.app.Permissions.SkipRequests() {
370 m.textarea.SetPromptFunc(4, yoloPromptFunc)
371 return
372 }
373 m.textarea.SetPromptFunc(4, normalPromptFunc)
374}
375
376func (m *editorCmp) completionsPosition() (int, int) {
377 cur := m.textarea.Cursor()
378 if cur == nil {
379 return m.x, m.y + 1 // adjust for padding
380 }
381 x := cur.X + m.x
382 y := cur.Y + m.y + 1 // adjust for padding
383 return x, y
384}
385
386func (m *editorCmp) Cursor() *tea.Cursor {
387 cursor := m.textarea.Cursor()
388 if cursor != nil {
389 cursor.X = cursor.X + m.x + 1
390 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
391 }
392 return cursor
393}
394
395var readyPlaceholders = [...]string{
396 "Ready!",
397 "Ready...",
398 "Ready?",
399 "Ready for instructions",
400}
401
402var workingPlaceholders = [...]string{
403 "Working!",
404 "Working...",
405 "Brrrrr...",
406 "Prrrrrrrr...",
407 "Processing...",
408 "Thinking...",
409}
410
411func (m *editorCmp) randomizePlaceholders() {
412 m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
413 m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
414}
415
416func (m *editorCmp) View() string {
417 t := styles.CurrentTheme()
418 // Update placeholder
419 if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
420 m.textarea.Placeholder = m.workingPlaceholder
421 } else {
422 m.textarea.Placeholder = m.readyPlaceholder
423 }
424 if m.app.Permissions.SkipRequests() {
425 m.textarea.Placeholder = "Yolo mode!"
426 }
427 if len(m.attachments) == 0 {
428 content := t.S().Base.Padding(1).Render(
429 m.textarea.View(),
430 )
431 return content
432 }
433 content := t.S().Base.Padding(0, 1, 1, 1).Render(
434 lipgloss.JoinVertical(lipgloss.Top,
435 m.attachmentsContent(),
436 m.textarea.View(),
437 ),
438 )
439 return content
440}
441
442func (m *editorCmp) SetSize(width, height int) tea.Cmd {
443 m.width = width
444 m.height = height
445 m.textarea.SetWidth(width - 2) // adjust for padding
446 m.textarea.SetHeight(height - 2) // adjust for padding
447 return nil
448}
449
450func (m *editorCmp) GetSize() (int, int) {
451 return m.textarea.Width(), m.textarea.Height()
452}
453
454func (m *editorCmp) attachmentsContent() string {
455 var styledAttachments []string
456 t := styles.CurrentTheme()
457 attachmentStyles := t.S().Base.
458 MarginLeft(1).
459 Background(t.FgMuted).
460 Foreground(t.FgBase)
461 for i, attachment := range m.attachments {
462 var filename string
463 if len(attachment.FileName) > 10 {
464 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
465 } else {
466 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
467 }
468 if m.deleteMode {
469 filename = fmt.Sprintf("%d%s", i, filename)
470 }
471 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
472 }
473 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
474 return content
475}
476
477func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
478 m.x = x
479 m.y = y
480 return nil
481}
482
483func (m *editorCmp) startCompletions() tea.Msg {
484 ls := m.app.Config().Options.TUI.Completions
485 depth, limit := ls.Limits()
486 files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
487 slices.Sort(files)
488 completionItems := make([]completions.Completion, 0, len(files))
489 for _, file := range files {
490 file = strings.TrimPrefix(file, "./")
491 completionItems = append(completionItems, completions.Completion{
492 Title: file,
493 Value: FileCompletionItem{
494 Path: file,
495 },
496 })
497 }
498
499 x, y := m.completionsPosition()
500 return completions.OpenCompletionsMsg{
501 Completions: completionItems,
502 X: x,
503 Y: y,
504 MaxResults: maxFileResults,
505 }
506}
507
508// Blur implements Container.
509func (c *editorCmp) Blur() tea.Cmd {
510 c.textarea.Blur()
511 return nil
512}
513
514// Focus implements Container.
515func (c *editorCmp) Focus() tea.Cmd {
516 return c.textarea.Focus()
517}
518
519// IsFocused implements Container.
520func (c *editorCmp) IsFocused() bool {
521 return c.textarea.Focused()
522}
523
524// Bindings implements Container.
525func (c *editorCmp) Bindings() []key.Binding {
526 return c.keyMap.KeyBindings()
527}
528
529// TODO: most likely we do not need to have the session here
530// we need to move some functionality to the page level
531func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
532 c.session = session
533 return nil
534}
535
536func (c *editorCmp) IsCompletionsOpen() bool {
537 return c.isCompletionsOpen
538}
539
540func (c *editorCmp) HasAttachments() bool {
541 return len(c.attachments) > 0
542}
543
544func normalPromptFunc(info textarea.PromptInfo) string {
545 t := styles.CurrentTheme()
546 if info.LineNumber == 0 {
547 return " > "
548 }
549 if info.Focused {
550 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
551 }
552 return t.S().Muted.Render("::: ")
553}
554
555func yoloPromptFunc(info textarea.PromptInfo) string {
556 t := styles.CurrentTheme()
557 if info.LineNumber == 0 {
558 if info.Focused {
559 return fmt.Sprintf("%s ", t.YoloIconFocused)
560 } else {
561 return fmt.Sprintf("%s ", t.YoloIconBlurred)
562 }
563 }
564 if info.Focused {
565 return fmt.Sprintf("%s ", t.YoloDotsFocused)
566 }
567 return fmt.Sprintf("%s ", t.YoloDotsBlurred)
568}
569
570func New(app *app.App) Editor {
571 t := styles.CurrentTheme()
572 ta := textarea.New()
573 ta.SetStyles(t.S().TextArea)
574 ta.ShowLineNumbers = false
575 ta.CharLimit = -1
576 ta.SetVirtualCursor(false)
577 ta.Focus()
578 e := &editorCmp{
579 // TODO: remove the app instance from here
580 app: app,
581 textarea: ta,
582 keyMap: DefaultEditorKeyMap(),
583 }
584 e.setEditorPrompt()
585
586 e.randomizePlaceholders()
587 e.textarea.Placeholder = e.readyPlaceholder
588
589 return e
590}