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