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