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