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) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
165 var cmd tea.Cmd
166 var cmds []tea.Cmd
167 switch msg := msg.(type) {
168 case filepicker.FilePickedMsg:
169 if len(m.attachments) >= maxAttachments {
170 return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
171 }
172 m.attachments = append(m.attachments, msg.Attachment)
173 return m, nil
174 case completions.CompletionsOpenedMsg:
175 m.isCompletionsOpen = true
176 case completions.CompletionsClosedMsg:
177 m.isCompletionsOpen = false
178 m.currentQuery = ""
179 m.completionsStartIndex = 0
180 case completions.SelectCompletionMsg:
181 if !m.isCompletionsOpen {
182 return m, nil
183 }
184 if item, ok := msg.Value.(FileCompletionItem); ok {
185 // If the selected item is a file, insert its path into the textarea
186 value := m.textarea.Value()
187 value = value[:m.completionsStartIndex]
188 value += item.Path
189 m.textarea.SetValue(value)
190 m.isCompletionsOpen = false
191 m.currentQuery = ""
192 m.completionsStartIndex = 0
193 return m, nil
194 }
195 case openEditorMsg:
196 m.textarea.SetValue(msg.Text)
197 m.textarea.MoveToEnd()
198 case tea.KeyPressMsg:
199 switch {
200 // Completions
201 case msg.String() == "/" && !m.isCompletionsOpen &&
202 // only show if beginning of prompt, or if previous char is a space:
203 (len(m.textarea.Value()) == 0 || m.textarea.Value()[len(m.textarea.Value())-1] == ' '):
204 m.isCompletionsOpen = true
205 m.currentQuery = ""
206 m.completionsStartIndex = len(m.textarea.Value())
207 cmds = append(cmds, m.startCompletions)
208 case m.isCompletionsOpen && m.textarea.Cursor().X <= m.completionsStartIndex:
209 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
210 }
211 if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
212 m.deleteMode = true
213 return m, nil
214 }
215 if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
216 m.deleteMode = false
217 m.attachments = nil
218 return m, nil
219 }
220 rune := msg.Code
221 if m.deleteMode && unicode.IsDigit(rune) {
222 num := int(rune - '0')
223 m.deleteMode = false
224 if num < 10 && len(m.attachments) > num {
225 if num == 0 {
226 m.attachments = m.attachments[num+1:]
227 } else {
228 m.attachments = slices.Delete(m.attachments, num, num+1)
229 }
230 return m, nil
231 }
232 }
233 if key.Matches(msg, m.keyMap.OpenEditor) {
234 if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
235 return m, util.ReportWarn("Agent is working, please wait...")
236 }
237 return m, m.openEditor(m.textarea.Value())
238 }
239 if key.Matches(msg, DeleteKeyMaps.Escape) {
240 m.deleteMode = false
241 return m, nil
242 }
243 if key.Matches(msg, m.keyMap.Newline) {
244 m.textarea.InsertRune('\n')
245 }
246 // Handle Enter key
247 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
248 value := m.textarea.Value()
249 if len(value) > 0 && value[len(value)-1] == '\\' {
250 // If the last character is a backslash, remove it and add a newline
251 m.textarea.SetValue(value[:len(value)-1])
252 } else {
253 // Otherwise, send the message
254 return m, m.send()
255 }
256 }
257 }
258
259 m.textarea, cmd = m.textarea.Update(msg)
260 cmds = append(cmds, cmd)
261
262 if m.textarea.Focused() {
263 kp, ok := msg.(tea.KeyPressMsg)
264 if ok {
265 if kp.String() == "space" || m.textarea.Value() == "" {
266 m.isCompletionsOpen = false
267 m.currentQuery = ""
268 m.completionsStartIndex = 0
269 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
270 } else {
271 word := m.textarea.Word()
272 if strings.HasPrefix(word, "/") {
273 // XXX: wont' work if editing in the middle of the field.
274 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
275 m.currentQuery = word[1:]
276 m.isCompletionsOpen = true
277 cmds = append(cmds, util.CmdHandler(completions.FilterCompletionsMsg{
278 Query: m.currentQuery,
279 Reopen: m.isCompletionsOpen,
280 }))
281 } else {
282 m.isCompletionsOpen = false
283 m.currentQuery = ""
284 m.completionsStartIndex = 0
285 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
286 }
287 }
288 }
289 }
290
291 return m, tea.Batch(cmds...)
292}
293
294func (m *editorCmp) Cursor() *tea.Cursor {
295 cursor := m.textarea.Cursor()
296 if cursor != nil {
297 cursor.X = cursor.X + m.x + 1
298 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
299 }
300 return cursor
301}
302
303func (m *editorCmp) View() string {
304 t := styles.CurrentTheme()
305 if len(m.attachments) == 0 {
306 content := t.S().Base.Padding(1).Render(
307 m.textarea.View(),
308 )
309 return content
310 }
311 content := t.S().Base.Padding(0, 1, 1, 1).Render(
312 lipgloss.JoinVertical(lipgloss.Top,
313 m.attachmentsContent(),
314 m.textarea.View(),
315 ),
316 )
317 return content
318}
319
320func (m *editorCmp) SetSize(width, height int) tea.Cmd {
321 m.width = width
322 m.height = height
323 m.textarea.SetWidth(width - 2) // adjust for padding
324 m.textarea.SetHeight(height - 2) // adjust for padding
325 return nil
326}
327
328func (m *editorCmp) GetSize() (int, int) {
329 return m.textarea.Width(), m.textarea.Height()
330}
331
332func (m *editorCmp) attachmentsContent() string {
333 var styledAttachments []string
334 t := styles.CurrentTheme()
335 attachmentStyles := t.S().Base.
336 MarginLeft(1).
337 Background(t.FgMuted).
338 Foreground(t.FgBase)
339 for i, attachment := range m.attachments {
340 var filename string
341 if len(attachment.FileName) > 10 {
342 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
343 } else {
344 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
345 }
346 if m.deleteMode {
347 filename = fmt.Sprintf("%d%s", i, filename)
348 }
349 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
350 }
351 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
352 return content
353}
354
355func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
356 m.x = x
357 m.y = y
358 return nil
359}
360
361func (m *editorCmp) startCompletions() tea.Msg {
362 files, _, _ := fsext.ListDirectory(".", []string{}, 0)
363 completionItems := make([]completions.Completion, 0, len(files))
364 for _, file := range files {
365 file = strings.TrimPrefix(file, "./")
366 completionItems = append(completionItems, completions.Completion{
367 Title: file,
368 Value: FileCompletionItem{
369 Path: file,
370 },
371 })
372 }
373
374 cur := m.textarea.Cursor()
375 x := cur.X + m.x // adjust for padding
376 y := cur.Y + m.y + 1
377 return completions.OpenCompletionsMsg{
378 Completions: completionItems,
379 X: x,
380 Y: y,
381 }
382}
383
384// Blur implements Container.
385func (c *editorCmp) Blur() tea.Cmd {
386 c.textarea.Blur()
387 return nil
388}
389
390// Focus implements Container.
391func (c *editorCmp) Focus() tea.Cmd {
392 return c.textarea.Focus()
393}
394
395// IsFocused implements Container.
396func (c *editorCmp) IsFocused() bool {
397 return c.textarea.Focused()
398}
399
400// Bindings implements Container.
401func (c *editorCmp) Bindings() []key.Binding {
402 return c.keyMap.KeyBindings()
403}
404
405// TODO: most likely we do not need to have the session here
406// we need to move some functionality to the page level
407func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
408 c.session = session
409 return nil
410}
411
412func (c *editorCmp) IsCompletionsOpen() bool {
413 return c.isCompletionsOpen
414}
415
416func New(app *app.App) Editor {
417 t := styles.CurrentTheme()
418 ta := textarea.New()
419 ta.SetStyles(t.S().TextArea)
420 ta.SetPromptFunc(4, func(info textarea.PromptInfo) string {
421 if info.LineNumber == 0 {
422 return " > "
423 }
424 if info.Focused {
425 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
426 } else {
427 return t.S().Muted.Render("::: ")
428 }
429 })
430 ta.ShowLineNumbers = false
431 ta.CharLimit = -1
432 ta.Placeholder = "Tell me more about this project..."
433 ta.SetVirtualCursor(false)
434 ta.Focus()
435
436 return &editorCmp{
437 // TODO: remove the app instance from here
438 app: app,
439 textarea: ta,
440 keyMap: DefaultEditorKeyMap(),
441 }
442}