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