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