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