1package editor
2
3import (
4 "fmt"
5 "net/http"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "runtime"
10 "slices"
11 "strings"
12 "unicode"
13
14 "github.com/charmbracelet/bubbles/v2/key"
15 "github.com/charmbracelet/bubbles/v2/textarea"
16 tea "github.com/charmbracelet/bubbletea/v2"
17 "github.com/charmbracelet/crush/internal/app"
18 "github.com/charmbracelet/crush/internal/fsext"
19 "github.com/charmbracelet/crush/internal/message"
20 "github.com/charmbracelet/crush/internal/session"
21 "github.com/charmbracelet/crush/internal/tui/components/chat"
22 "github.com/charmbracelet/crush/internal/tui/components/completions"
23 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
24 "github.com/charmbracelet/crush/internal/tui/components/dialogs"
25 "github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
26 "github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
27 "github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
28 "github.com/charmbracelet/crush/internal/tui/styles"
29 "github.com/charmbracelet/crush/internal/tui/util"
30 "github.com/charmbracelet/lipgloss/v2"
31)
32
33type Editor interface {
34 util.Model
35 layout.Sizeable
36 layout.Focusable
37 layout.Help
38 layout.Positional
39
40 SetSession(session session.Session) tea.Cmd
41 IsCompletionsOpen() bool
42 HasAttachments() bool
43 Cursor() *tea.Cursor
44}
45
46type FileCompletionItem struct {
47 Path string // The file path
48}
49
50type editorCmp struct {
51 width int
52 height int
53 x, y int
54 app *app.App
55 session session.Session
56 textarea textarea.Model
57 attachments []message.Attachment
58 deleteMode bool
59
60 keyMap EditorKeyMap
61
62 // File path completions
63 currentQuery string
64 completionsStartIndex int
65 isCompletionsOpen bool
66}
67
68var DeleteKeyMaps = DeleteAttachmentKeyMaps{
69 AttachmentDeleteMode: key.NewBinding(
70 key.WithKeys("ctrl+r"),
71 key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
72 ),
73 Escape: key.NewBinding(
74 key.WithKeys("esc"),
75 key.WithHelp("esc", "cancel delete mode"),
76 ),
77 DeleteAllAttachments: key.NewBinding(
78 key.WithKeys("r"),
79 key.WithHelp("ctrl+r+r", "delete all attachments"),
80 ),
81}
82
83const (
84 maxAttachments = 5
85)
86
87type OpenEditorMsg struct {
88 Text string
89}
90
91func (m *editorCmp) openEditor(value string) tea.Cmd {
92 editor := os.Getenv("EDITOR")
93 if editor == "" {
94 // Use platform-appropriate default editor
95 if runtime.GOOS == "windows" {
96 editor = "notepad"
97 } else {
98 editor = "nvim"
99 }
100 }
101
102 tmpfile, err := os.CreateTemp("", "msg_*.md")
103 if err != nil {
104 return util.ReportError(err)
105 }
106 defer tmpfile.Close() //nolint:errcheck
107 if _, err := tmpfile.WriteString(value); err != nil {
108 return util.ReportError(err)
109 }
110 c := exec.Command(editor, tmpfile.Name())
111 c.Stdin = os.Stdin
112 c.Stdout = os.Stdout
113 c.Stderr = os.Stderr
114 return tea.ExecProcess(c, func(err error) tea.Msg {
115 if err != nil {
116 return util.ReportError(err)
117 }
118 content, err := os.ReadFile(tmpfile.Name())
119 if err != nil {
120 return util.ReportError(err)
121 }
122 if len(content) == 0 {
123 return util.ReportWarn("Message is empty")
124 }
125 os.Remove(tmpfile.Name())
126 return OpenEditorMsg{
127 Text: strings.TrimSpace(string(content)),
128 }
129 })
130}
131
132func (m *editorCmp) Init() tea.Cmd {
133 return nil
134}
135
136func (m *editorCmp) send() tea.Cmd {
137 if m.app.CoderAgent == nil {
138 return util.ReportError(fmt.Errorf("coder agent is not initialized"))
139 }
140 if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
141 return util.ReportWarn("Agent is working, please wait...")
142 }
143
144 value := m.textarea.Value()
145 value = strings.TrimSpace(value)
146
147 switch value {
148 case "exit", "quit":
149 m.textarea.Reset()
150 return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
151 }
152
153 m.textarea.Reset()
154 attachments := m.attachments
155
156 m.attachments = nil
157 if value == "" {
158 return nil
159 }
160 return tea.Batch(
161 util.CmdHandler(chat.SendMsg{
162 Text: value,
163 Attachments: attachments,
164 }),
165 )
166}
167
168func (m *editorCmp) repositionCompletions() tea.Msg {
169 x, y := m.completionsPosition()
170 return completions.RepositionCompletionsMsg{X: x, Y: y}
171}
172
173func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
174 var cmd tea.Cmd
175 var cmds []tea.Cmd
176 switch msg := msg.(type) {
177 case tea.WindowSizeMsg:
178 return m, m.repositionCompletions
179 case filepicker.FilePickedMsg:
180 if len(m.attachments) >= maxAttachments {
181 return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
182 }
183 m.attachments = append(m.attachments, msg.Attachment)
184 return m, nil
185 case completions.CompletionsOpenedMsg:
186 m.isCompletionsOpen = true
187 case completions.CompletionsClosedMsg:
188 m.isCompletionsOpen = false
189 m.currentQuery = ""
190 m.completionsStartIndex = 0
191 case completions.SelectCompletionMsg:
192 if !m.isCompletionsOpen {
193 return m, nil
194 }
195 if item, ok := msg.Value.(FileCompletionItem); ok {
196 word := m.textarea.Word()
197 // If the selected item is a file, insert its path into the textarea
198 value := m.textarea.Value()
199 value = value[:m.completionsStartIndex] + // Remove the current query
200 item.Path + // Insert the file path
201 value[m.completionsStartIndex+len(word):] // Append the rest of the value
202 // XXX: This will always move the cursor to the end of the textarea.
203 m.textarea.SetValue(value)
204 m.textarea.MoveToEnd()
205 if !msg.Insert {
206 m.isCompletionsOpen = false
207 m.currentQuery = ""
208 m.completionsStartIndex = 0
209 }
210 }
211
212 case commands.OpenExternalEditorMsg:
213 if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
214 return m, util.ReportWarn("Agent is working, please wait...")
215 }
216 return m, m.openEditor(m.textarea.Value())
217 case OpenEditorMsg:
218 m.textarea.SetValue(msg.Text)
219 m.textarea.MoveToEnd()
220 case tea.PasteMsg:
221 path := strings.ReplaceAll(string(msg), "\\ ", " ")
222 // try to get an image
223 path, err := filepath.Abs(path)
224 if err != nil {
225 m.textarea, cmd = m.textarea.Update(msg)
226 return m, cmd
227 }
228 isAllowedType := false
229 for _, ext := range filepicker.AllowedTypes {
230 if strings.HasSuffix(path, ext) {
231 isAllowedType = true
232 break
233 }
234 }
235 if !isAllowedType {
236 m.textarea, cmd = m.textarea.Update(msg)
237 return m, cmd
238 }
239 tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
240 if tooBig {
241 m.textarea, cmd = m.textarea.Update(msg)
242 return m, cmd
243 }
244
245 content, err := os.ReadFile(path)
246 if err != nil {
247 m.textarea, cmd = m.textarea.Update(msg)
248 return m, cmd
249 }
250 mimeBufferSize := min(512, len(content))
251 mimeType := http.DetectContentType(content[:mimeBufferSize])
252 fileName := filepath.Base(path)
253 attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
254 return m, util.CmdHandler(filepicker.FilePickedMsg{
255 Attachment: attachment,
256 })
257
258 case tea.KeyPressMsg:
259 cur := m.textarea.Cursor()
260 curIdx := m.textarea.Width()*cur.Y + cur.X
261 switch {
262 // Completions
263 case msg.String() == "/" && !m.isCompletionsOpen &&
264 // only show if beginning of prompt, or if previous char is a space or newline:
265 (len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
266 m.isCompletionsOpen = true
267 m.currentQuery = ""
268 m.completionsStartIndex = curIdx
269 cmds = append(cmds, m.startCompletions)
270 case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
271 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
272 }
273 if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
274 m.deleteMode = true
275 return m, nil
276 }
277 if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
278 m.deleteMode = false
279 m.attachments = nil
280 return m, nil
281 }
282 rune := msg.Code
283 if m.deleteMode && unicode.IsDigit(rune) {
284 num := int(rune - '0')
285 m.deleteMode = false
286 if num < 10 && len(m.attachments) > num {
287 if num == 0 {
288 m.attachments = m.attachments[num+1:]
289 } else {
290 m.attachments = slices.Delete(m.attachments, num, num+1)
291 }
292 return m, nil
293 }
294 }
295 if key.Matches(msg, m.keyMap.OpenEditor) {
296 if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
297 return m, util.ReportWarn("Agent is working, please wait...")
298 }
299 return m, m.openEditor(m.textarea.Value())
300 }
301 if key.Matches(msg, DeleteKeyMaps.Escape) {
302 m.deleteMode = false
303 return m, nil
304 }
305 if key.Matches(msg, m.keyMap.Newline) {
306 m.textarea.InsertRune('\n')
307 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
308 }
309 // Handle Enter key
310 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
311 value := m.textarea.Value()
312 if len(value) > 0 && value[len(value)-1] == '\\' {
313 // If the last character is a backslash, remove it and add a newline
314 m.textarea.SetValue(value[:len(value)-1])
315 } else {
316 // Otherwise, send the message
317 return m, m.send()
318 }
319 }
320 }
321
322 m.textarea, cmd = m.textarea.Update(msg)
323 cmds = append(cmds, cmd)
324
325 if m.textarea.Focused() {
326 kp, ok := msg.(tea.KeyPressMsg)
327 if ok {
328 if kp.String() == "space" || m.textarea.Value() == "" {
329 m.isCompletionsOpen = false
330 m.currentQuery = ""
331 m.completionsStartIndex = 0
332 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
333 } else {
334 word := m.textarea.Word()
335 if strings.HasPrefix(word, "/") {
336 // XXX: wont' work if editing in the middle of the field.
337 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
338 m.currentQuery = word[1:]
339 x, y := m.completionsPosition()
340 x -= len(m.currentQuery)
341 m.isCompletionsOpen = true
342 cmds = append(cmds,
343 util.CmdHandler(completions.FilterCompletionsMsg{
344 Query: m.currentQuery,
345 Reopen: m.isCompletionsOpen,
346 X: x,
347 Y: y,
348 }),
349 )
350 } else if m.isCompletionsOpen {
351 m.isCompletionsOpen = false
352 m.currentQuery = ""
353 m.completionsStartIndex = 0
354 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
355 }
356 }
357 }
358 }
359
360 return m, tea.Batch(cmds...)
361}
362
363func (m *editorCmp) completionsPosition() (int, int) {
364 cur := m.textarea.Cursor()
365 if cur == nil {
366 return m.x, m.y + 1 // adjust for padding
367 }
368 x := cur.X + m.x
369 y := cur.Y + m.y + 1 // adjust for padding
370 return x, y
371}
372
373func (m *editorCmp) Cursor() *tea.Cursor {
374 cursor := m.textarea.Cursor()
375 if cursor != nil {
376 cursor.X = cursor.X + m.x + 1
377 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
378 }
379 return cursor
380}
381
382func (m *editorCmp) View() string {
383 t := styles.CurrentTheme()
384 if len(m.attachments) == 0 {
385 content := t.S().Base.Padding(1).Render(
386 m.textarea.View(),
387 )
388 return content
389 }
390 content := t.S().Base.Padding(0, 1, 1, 1).Render(
391 lipgloss.JoinVertical(lipgloss.Top,
392 m.attachmentsContent(),
393 m.textarea.View(),
394 ),
395 )
396 return content
397}
398
399func (m *editorCmp) SetSize(width, height int) tea.Cmd {
400 m.width = width
401 m.height = height
402 m.textarea.SetWidth(width - 2) // adjust for padding
403 m.textarea.SetHeight(height - 2) // adjust for padding
404 return nil
405}
406
407func (m *editorCmp) GetSize() (int, int) {
408 return m.textarea.Width(), m.textarea.Height()
409}
410
411func (m *editorCmp) attachmentsContent() string {
412 var styledAttachments []string
413 t := styles.CurrentTheme()
414 attachmentStyles := t.S().Base.
415 MarginLeft(1).
416 Background(t.FgMuted).
417 Foreground(t.FgBase)
418 for i, attachment := range m.attachments {
419 var filename string
420 if len(attachment.FileName) > 10 {
421 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
422 } else {
423 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
424 }
425 if m.deleteMode {
426 filename = fmt.Sprintf("%d%s", i, filename)
427 }
428 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
429 }
430 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
431 return content
432}
433
434func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
435 m.x = x
436 m.y = y
437 return nil
438}
439
440func (m *editorCmp) startCompletions() tea.Msg {
441 files, _, _ := fsext.ListDirectory(".", []string{}, 0)
442 completionItems := make([]completions.Completion, 0, len(files))
443 for _, file := range files {
444 file = strings.TrimPrefix(file, "./")
445 completionItems = append(completionItems, completions.Completion{
446 Title: file,
447 Value: FileCompletionItem{
448 Path: file,
449 },
450 })
451 }
452
453 x, y := m.completionsPosition()
454 return completions.OpenCompletionsMsg{
455 Completions: completionItems,
456 X: x,
457 Y: y,
458 }
459}
460
461// Blur implements Container.
462func (c *editorCmp) Blur() tea.Cmd {
463 c.textarea.Blur()
464 return nil
465}
466
467// Focus implements Container.
468func (c *editorCmp) Focus() tea.Cmd {
469 return c.textarea.Focus()
470}
471
472// IsFocused implements Container.
473func (c *editorCmp) IsFocused() bool {
474 return c.textarea.Focused()
475}
476
477// Bindings implements Container.
478func (c *editorCmp) Bindings() []key.Binding {
479 return c.keyMap.KeyBindings()
480}
481
482// TODO: most likely we do not need to have the session here
483// we need to move some functionality to the page level
484func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
485 c.session = session
486 return nil
487}
488
489func (c *editorCmp) IsCompletionsOpen() bool {
490 return c.isCompletionsOpen
491}
492
493func (c *editorCmp) HasAttachments() bool {
494 return len(c.attachments) > 0
495}
496
497func New(app *app.App) Editor {
498 t := styles.CurrentTheme()
499 ta := textarea.New()
500 ta.SetStyles(t.S().TextArea)
501 ta.SetPromptFunc(4, func(info textarea.PromptInfo) string {
502 if info.LineNumber == 0 {
503 return " > "
504 }
505 if info.Focused {
506 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
507 } else {
508 return t.S().Muted.Render("::: ")
509 }
510 })
511 ta.ShowLineNumbers = false
512 ta.CharLimit = -1
513 ta.Placeholder = "Tell me more about this project..."
514 ta.SetVirtualCursor(false)
515 ta.Focus()
516
517 return &editorCmp{
518 // TODO: remove the app instance from here
519 app: app,
520 textarea: ta,
521 keyMap: DefaultEditorKeyMap(),
522 }
523}