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