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 // Hanlde Enter key
249 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
250 value := m.textarea.Value()
251 if len(value) > 0 && value[len(value)-1] == '\\' {
252 // If the last character is a backslash, remove it and add a newline
253 m.textarea.SetValue(value[:len(value)-1] + "\n")
254 return m, nil
255 } else {
256 // Otherwise, send the message
257 return m, m.send()
258 }
259 }
260 }
261 m.textarea, cmd = m.textarea.Update(msg)
262 cmds = append(cmds, cmd)
263 return m, tea.Batch(cmds...)
264}
265
266func (m *editorCmp) Cursor() *tea.Cursor {
267 cursor := m.textarea.Cursor()
268 if cursor != nil {
269 cursor.X = cursor.X + m.x + 1
270 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
271 }
272 return cursor
273}
274
275func (m *editorCmp) View() string {
276 t := styles.CurrentTheme()
277 if len(m.attachments) == 0 {
278 content := t.S().Base.Padding(1).Render(
279 m.textarea.View(),
280 )
281 return content
282 }
283 content := t.S().Base.Padding(0, 1, 1, 1).Render(
284 lipgloss.JoinVertical(lipgloss.Top,
285 m.attachmentsContent(),
286 m.textarea.View(),
287 ),
288 )
289 return content
290}
291
292func (m *editorCmp) SetSize(width, height int) tea.Cmd {
293 m.width = width
294 m.height = height
295 m.textarea.SetWidth(width - 2) // adjust for padding
296 m.textarea.SetHeight(height - 2) // adjust for padding
297 return nil
298}
299
300func (m *editorCmp) GetSize() (int, int) {
301 return m.textarea.Width(), m.textarea.Height()
302}
303
304func (m *editorCmp) attachmentsContent() string {
305 var styledAttachments []string
306 t := styles.CurrentTheme()
307 attachmentStyles := t.S().Base.
308 MarginLeft(1).
309 Background(t.FgMuted).
310 Foreground(t.FgBase)
311 for i, attachment := range m.attachments {
312 var filename string
313 if len(attachment.FileName) > 10 {
314 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
315 } else {
316 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
317 }
318 if m.deleteMode {
319 filename = fmt.Sprintf("%d%s", i, filename)
320 }
321 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
322 }
323 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
324 return content
325}
326
327func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
328 m.x = x
329 m.y = y
330 return nil
331}
332
333func (m *editorCmp) startCompletions() tea.Msg {
334 files, _, _ := fsext.ListDirectory(".", []string{}, 0)
335 completionItems := make([]completions.Completion, 0, len(files))
336 for _, file := range files {
337 file = strings.TrimPrefix(file, "./")
338 completionItems = append(completionItems, completions.Completion{
339 Title: file,
340 Value: FileCompletionItem{
341 Path: file,
342 },
343 })
344 }
345
346 x := m.textarea.Cursor().X + m.x + 1
347 y := m.textarea.Cursor().Y + m.y + 1
348 return completions.OpenCompletionsMsg{
349 Completions: completionItems,
350 X: x,
351 Y: y,
352 }
353}
354
355// Blur implements Container.
356func (c *editorCmp) Blur() tea.Cmd {
357 c.textarea.Blur()
358 return nil
359}
360
361// Focus implements Container.
362func (c *editorCmp) Focus() tea.Cmd {
363 return c.textarea.Focus()
364}
365
366// IsFocused implements Container.
367func (c *editorCmp) IsFocused() bool {
368 return c.textarea.Focused()
369}
370
371func (c *editorCmp) Bindings() []key.Binding {
372 return c.keyMap.KeyBindings()
373}
374
375func NewEditorCmp(app *app.App) util.Model {
376 t := styles.CurrentTheme()
377 ta := textarea.New()
378 ta.SetStyles(t.S().TextArea)
379 ta.SetPromptFunc(4, func(lineIndex int, focused bool) string {
380 if lineIndex == 0 {
381 return " > "
382 }
383 if focused {
384 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
385 } else {
386 return t.S().Muted.Render("::: ")
387 }
388 })
389 ta.ShowLineNumbers = false
390 ta.CharLimit = -1
391 ta.Placeholder = "Tell me more about this project..."
392 ta.SetVirtualCursor(false)
393 ta.Focus()
394
395 return &editorCmp{
396 app: app,
397 textarea: ta,
398 keyMap: DefaultEditorKeyMap(),
399 }
400}