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