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 "git.secluded.site/crush/internal/app"
21 "git.secluded.site/crush/internal/fsext"
22 "git.secluded.site/crush/internal/message"
23 "git.secluded.site/crush/internal/session"
24 "git.secluded.site/crush/internal/shell"
25 "git.secluded.site/crush/internal/tui/components/chat"
26 "git.secluded.site/crush/internal/tui/components/completions"
27 "git.secluded.site/crush/internal/tui/components/core/layout"
28 "git.secluded.site/crush/internal/tui/components/dialogs"
29 "git.secluded.site/crush/internal/tui/components/dialogs/commands"
30 "git.secluded.site/crush/internal/tui/components/dialogs/filepicker"
31 "git.secluded.site/crush/internal/tui/components/dialogs/quit"
32 "git.secluded.site/crush/internal/tui/styles"
33 "git.secluded.site/crush/internal/tui/util"
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 cmdName, cmdArgs, err := shell.ParseCommand(editor)
120 if err != nil {
121 return util.ReportError(err)
122 }
123
124 cmdArgs = append(cmdArgs, tmpfile.Name())
125 c := exec.CommandContext(context.TODO(), cmdName, cmdArgs...)
126 c.Stdin = os.Stdin
127 c.Stdout = os.Stdout
128 c.Stderr = os.Stderr
129 return tea.ExecProcess(c, func(err error) tea.Msg {
130 if err != nil {
131 return util.ReportError(err)
132 }
133 content, err := os.ReadFile(tmpfile.Name())
134 if err != nil {
135 return util.ReportError(err)
136 }
137 if len(content) == 0 {
138 return util.ReportWarn("Message is empty")
139 }
140 os.Remove(tmpfile.Name())
141 return OpenEditorMsg{
142 Text: strings.TrimSpace(string(content)),
143 }
144 })
145}
146
147func (m *editorCmp) openWorkingDir() tea.Cmd {
148 editor := os.Getenv("EDITOR")
149 if editor == "" {
150 // Use platform-appropriate default editor
151 if runtime.GOOS == "windows" {
152 editor = "notepad"
153 } else {
154 editor = "nvim"
155 }
156 }
157
158 // Parse the EDITOR parts to separate the executable from its arguments.
159 // This properly handles EDITORs with args like `zed --wait`.
160 cmdName, cmdArgs, err := shell.ParseCommand(editor)
161 if err != nil {
162 return util.ReportError(err)
163 }
164
165 cmdArgs = append(cmdArgs, ".")
166 c := exec.CommandContext(context.TODO(), cmdName, cmdArgs...)
167 c.Stdin = os.Stdin
168 c.Stdout = os.Stdout
169 c.Stderr = os.Stderr
170 return tea.ExecProcess(c, func(err error) tea.Msg {
171 if err != nil {
172 return util.ReportError(err)
173 }
174 return nil
175 })
176}
177
178func (m *editorCmp) Init() tea.Cmd {
179 return nil
180}
181
182func (m *editorCmp) send() tea.Cmd {
183 value := m.textarea.Value()
184 value = strings.TrimSpace(value)
185
186 switch value {
187 case "exit", "quit":
188 m.textarea.Reset()
189 return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
190 }
191
192 m.textarea.Reset()
193 attachments := m.attachments
194
195 m.attachments = nil
196 if value == "" {
197 return nil
198 }
199
200 // Change the placeholder when sending a new message.
201 m.randomizePlaceholders()
202
203 return tea.Batch(
204 util.CmdHandler(chat.SendMsg{
205 Text: value,
206 Attachments: attachments,
207 }),
208 )
209}
210
211func (m *editorCmp) repositionCompletions() tea.Msg {
212 x, y := m.completionsPosition()
213 return completions.RepositionCompletionsMsg{X: x, Y: y}
214}
215
216func (m *editorCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
217 var cmd tea.Cmd
218 var cmds []tea.Cmd
219 switch msg := msg.(type) {
220 case tea.WindowSizeMsg:
221 return m, m.repositionCompletions
222 case filepicker.FilePickedMsg:
223 if len(m.attachments) >= maxAttachments {
224 return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
225 }
226 m.attachments = append(m.attachments, msg.Attachment)
227 return m, nil
228 case completions.CompletionsOpenedMsg:
229 m.isCompletionsOpen = true
230 case completions.CompletionsClosedMsg:
231 m.isCompletionsOpen = false
232 m.currentQuery = ""
233 m.completionsStartIndex = 0
234 case completions.SelectCompletionMsg:
235 if !m.isCompletionsOpen {
236 return m, nil
237 }
238 if item, ok := msg.Value.(FileCompletionItem); ok {
239 word := m.textarea.Word()
240 // If the selected item is a file, insert its path into the textarea
241 value := m.textarea.Value()
242 value = value[:m.completionsStartIndex] + // Remove the current query
243 item.Path + // Insert the file path
244 value[m.completionsStartIndex+len(word):] // Append the rest of the value
245 // XXX: This will always move the cursor to the end of the textarea.
246 m.textarea.SetValue(value)
247 m.textarea.MoveToEnd()
248 if !msg.Insert {
249 m.isCompletionsOpen = false
250 m.currentQuery = ""
251 m.completionsStartIndex = 0
252 }
253 }
254
255 case commands.OpenExternalEditorMsg:
256 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
257 return m, util.ReportWarn("Agent is working, please wait...")
258 }
259 return m, m.openEditor(m.textarea.Value())
260 case OpenEditorMsg:
261 m.textarea.SetValue(msg.Text)
262 m.textarea.MoveToEnd()
263 case tea.PasteMsg:
264 path := strings.ReplaceAll(msg.Content, "\\ ", " ")
265 // try to get an image
266 path, err := filepath.Abs(strings.TrimSpace(path))
267 if err != nil {
268 m.textarea, cmd = m.textarea.Update(msg)
269 return m, cmd
270 }
271 isAllowedType := false
272 for _, ext := range filepicker.AllowedTypes {
273 if strings.HasSuffix(path, ext) {
274 isAllowedType = true
275 break
276 }
277 }
278 if !isAllowedType {
279 m.textarea, cmd = m.textarea.Update(msg)
280 return m, cmd
281 }
282 tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
283 if tooBig {
284 m.textarea, cmd = m.textarea.Update(msg)
285 return m, cmd
286 }
287
288 content, err := os.ReadFile(path)
289 if err != nil {
290 m.textarea, cmd = m.textarea.Update(msg)
291 return m, cmd
292 }
293 mimeBufferSize := min(512, len(content))
294 mimeType := http.DetectContentType(content[:mimeBufferSize])
295 fileName := filepath.Base(path)
296 attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
297 return m, util.CmdHandler(filepicker.FilePickedMsg{
298 Attachment: attachment,
299 })
300
301 case commands.ToggleYoloModeMsg:
302 m.setEditorPrompt()
303 return m, nil
304 case tea.KeyPressMsg:
305 cur := m.textarea.Cursor()
306 curIdx := m.textarea.Width()*cur.Y + cur.X
307 switch {
308 // Open command palette when "/" is pressed on empty prompt
309 case msg.String() == "/" && len(strings.TrimSpace(m.textarea.Value())) == 0:
310 return m, util.CmdHandler(dialogs.OpenDialogMsg{
311 Model: commands.NewCommandDialog(m.session.ID),
312 })
313 // Completions
314 case msg.String() == "@" && !m.isCompletionsOpen &&
315 // only show if beginning of prompt, or if previous char is a space or newline:
316 (len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
317 m.isCompletionsOpen = true
318 m.currentQuery = ""
319 m.completionsStartIndex = curIdx
320 cmds = append(cmds, m.startCompletions)
321 case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
322 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
323 }
324 if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
325 m.deleteMode = true
326 return m, nil
327 }
328 if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
329 m.deleteMode = false
330 m.attachments = nil
331 return m, nil
332 }
333 rune := msg.Code
334 if m.deleteMode && unicode.IsDigit(rune) {
335 num := int(rune - '0')
336 m.deleteMode = false
337 if num < 10 && len(m.attachments) > num {
338 if num == 0 {
339 m.attachments = m.attachments[num+1:]
340 } else {
341 m.attachments = slices.Delete(m.attachments, num, num+1)
342 }
343 return m, nil
344 }
345 }
346 if key.Matches(msg, m.keyMap.OpenEditor) {
347 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
348 return m, util.ReportWarn("Agent is working, please wait...")
349 }
350 return m, m.openEditor(m.textarea.Value())
351 }
352 if key.Matches(msg, m.keyMap.OpenWorkingDir) {
353 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
354 return m, util.ReportWarn("Agent is working, please wait...")
355 }
356 return m, m.openWorkingDir()
357 }
358 if key.Matches(msg, DeleteKeyMaps.Escape) {
359 m.deleteMode = false
360 return m, nil
361 }
362 if key.Matches(msg, m.keyMap.Newline) {
363 m.textarea.InsertRune('\n')
364 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
365 }
366 // Handle Enter key
367 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
368 value := m.textarea.Value()
369 if strings.HasSuffix(value, "\\") {
370 // If the last character is a backslash, remove it and add a newline.
371 m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
372 } else {
373 // Otherwise, send the message
374 return m, m.send()
375 }
376 }
377 }
378
379 m.textarea, cmd = m.textarea.Update(msg)
380 cmds = append(cmds, cmd)
381
382 if m.textarea.Focused() {
383 kp, ok := msg.(tea.KeyPressMsg)
384 if ok {
385 if kp.String() == "space" || m.textarea.Value() == "" {
386 m.isCompletionsOpen = false
387 m.currentQuery = ""
388 m.completionsStartIndex = 0
389 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
390 } else {
391 word := m.textarea.Word()
392 if strings.HasPrefix(word, "@") {
393 // XXX: wont' work if editing in the middle of the field.
394 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
395 m.currentQuery = word[1:]
396 x, y := m.completionsPosition()
397 x -= len(m.currentQuery)
398 m.isCompletionsOpen = true
399 cmds = append(cmds,
400 util.CmdHandler(completions.FilterCompletionsMsg{
401 Query: m.currentQuery,
402 Reopen: m.isCompletionsOpen,
403 X: x,
404 Y: y,
405 }),
406 )
407 } else if m.isCompletionsOpen {
408 m.isCompletionsOpen = false
409 m.currentQuery = ""
410 m.completionsStartIndex = 0
411 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
412 }
413 }
414 }
415 }
416
417 return m, tea.Batch(cmds...)
418}
419
420func (m *editorCmp) setEditorPrompt() {
421 if m.app.Permissions.SkipRequests() {
422 m.textarea.SetPromptFunc(4, yoloPromptFunc)
423 return
424 }
425 m.textarea.SetPromptFunc(4, normalPromptFunc)
426}
427
428func (m *editorCmp) completionsPosition() (int, int) {
429 cur := m.textarea.Cursor()
430 if cur == nil {
431 return m.x, m.y + 1 // adjust for padding
432 }
433 x := cur.X + m.x
434 y := cur.Y + m.y + 1 // adjust for padding
435 return x, y
436}
437
438func (m *editorCmp) Cursor() *tea.Cursor {
439 cursor := m.textarea.Cursor()
440 if cursor != nil {
441 cursor.X = cursor.X + m.x + 1
442 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
443 }
444 return cursor
445}
446
447var readyPlaceholders = [...]string{
448 "Ready!",
449 "Ready...",
450 "Ready?",
451 "Ready for instructions",
452}
453
454var workingPlaceholders = [...]string{
455 "Working!",
456 "Working...",
457 "Brrrrr...",
458 "Prrrrrrrr...",
459 "Processing...",
460 "Thinking...",
461}
462
463func (m *editorCmp) randomizePlaceholders() {
464 m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
465 m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
466}
467
468func (m *editorCmp) View() string {
469 t := styles.CurrentTheme()
470 // Update placeholder
471 if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
472 m.textarea.Placeholder = m.workingPlaceholder
473 } else {
474 m.textarea.Placeholder = m.readyPlaceholder
475 }
476 if m.app.Permissions.SkipRequests() {
477 m.textarea.Placeholder = "Yolo mode!"
478 }
479 if len(m.attachments) == 0 {
480 content := t.S().Base.Padding(1).Render(
481 m.textarea.View(),
482 )
483 return content
484 }
485 content := t.S().Base.Padding(0, 1, 1, 1).Render(
486 lipgloss.JoinVertical(lipgloss.Top,
487 m.attachmentsContent(),
488 m.textarea.View(),
489 ),
490 )
491 return content
492}
493
494func (m *editorCmp) SetSize(width, height int) tea.Cmd {
495 m.width = width
496 m.height = height
497 m.textarea.SetWidth(width - 2) // adjust for padding
498 m.textarea.SetHeight(height - 2) // adjust for padding
499 return nil
500}
501
502func (m *editorCmp) GetSize() (int, int) {
503 return m.textarea.Width(), m.textarea.Height()
504}
505
506func (m *editorCmp) attachmentsContent() string {
507 var styledAttachments []string
508 t := styles.CurrentTheme()
509 attachmentStyles := t.S().Base.
510 MarginLeft(1).
511 Background(t.FgMuted).
512 Foreground(t.FgBase)
513 for i, attachment := range m.attachments {
514 var filename string
515 if len(attachment.FileName) > 10 {
516 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
517 } else {
518 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
519 }
520 if m.deleteMode {
521 filename = fmt.Sprintf("%d%s", i, filename)
522 }
523 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
524 }
525 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
526 return content
527}
528
529func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
530 m.x = x
531 m.y = y
532 return nil
533}
534
535func (m *editorCmp) startCompletions() tea.Msg {
536 ls := m.app.Config().Options.TUI.Completions
537 depth, limit := ls.Limits()
538 files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
539 slices.Sort(files)
540 completionItems := make([]completions.Completion, 0, len(files))
541 for _, file := range files {
542 file = strings.TrimPrefix(file, "./")
543 completionItems = append(completionItems, completions.Completion{
544 Title: file,
545 Value: FileCompletionItem{
546 Path: file,
547 },
548 })
549 }
550
551 x, y := m.completionsPosition()
552 return completions.OpenCompletionsMsg{
553 Completions: completionItems,
554 X: x,
555 Y: y,
556 MaxResults: maxFileResults,
557 }
558}
559
560// Blur implements Container.
561func (c *editorCmp) Blur() tea.Cmd {
562 c.textarea.Blur()
563 return nil
564}
565
566// Focus implements Container.
567func (c *editorCmp) Focus() tea.Cmd {
568 return c.textarea.Focus()
569}
570
571// IsFocused implements Container.
572func (c *editorCmp) IsFocused() bool {
573 return c.textarea.Focused()
574}
575
576// Bindings implements Container.
577func (c *editorCmp) Bindings() []key.Binding {
578 return c.keyMap.KeyBindings()
579}
580
581// TODO: most likely we do not need to have the session here
582// we need to move some functionality to the page level
583func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
584 c.session = session
585 return nil
586}
587
588func (c *editorCmp) IsCompletionsOpen() bool {
589 return c.isCompletionsOpen
590}
591
592func (c *editorCmp) HasAttachments() bool {
593 return len(c.attachments) > 0
594}
595
596func normalPromptFunc(info textarea.PromptInfo) string {
597 t := styles.CurrentTheme()
598 if info.LineNumber == 0 {
599 return " > "
600 }
601 if info.Focused {
602 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
603 }
604 return t.S().Muted.Render("::: ")
605}
606
607func yoloPromptFunc(info textarea.PromptInfo) string {
608 t := styles.CurrentTheme()
609 if info.LineNumber == 0 {
610 if info.Focused {
611 return fmt.Sprintf("%s ", t.YoloIconFocused)
612 } else {
613 return fmt.Sprintf("%s ", t.YoloIconBlurred)
614 }
615 }
616 if info.Focused {
617 return fmt.Sprintf("%s ", t.YoloDotsFocused)
618 }
619 return fmt.Sprintf("%s ", t.YoloDotsBlurred)
620}
621
622func New(app *app.App) Editor {
623 t := styles.CurrentTheme()
624 ta := textarea.New()
625 ta.SetStyles(t.S().TextArea)
626 ta.ShowLineNumbers = false
627 ta.CharLimit = -1
628 ta.SetVirtualCursor(false)
629 ta.Focus()
630 e := &editorCmp{
631 // TODO: remove the app instance from here
632 app: app,
633 textarea: ta,
634 keyMap: DefaultEditorKeyMap(),
635 }
636 e.setEditorPrompt()
637
638 e.randomizePlaceholders()
639 e.textarea.Placeholder = e.readyPlaceholder
640
641 return e
642}