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