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