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 cursor.X = cursor.X + m.x + 1
267 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
268 if len(m.attachments) == 0 {
269 content := t.S().Base.Padding(1).Render(
270 m.textarea.View(),
271 )
272 view := tea.NewView(content)
273 view.SetCursor(cursor)
274 return view
275 }
276 content := t.S().Base.Padding(0, 1, 1, 1).Render(
277 lipgloss.JoinVertical(lipgloss.Top,
278 m.attachmentsContent(),
279 m.textarea.View(),
280 ),
281 )
282 view := tea.NewView(content)
283 view.SetCursor(cursor)
284 return view
285}
286
287func (m *editorCmp) SetSize(width, height int) tea.Cmd {
288 m.width = width
289 m.height = height
290 m.textarea.SetWidth(width - 2) // adjust for padding
291 m.textarea.SetHeight(height - 2) // adjust for padding
292 return nil
293}
294
295func (m *editorCmp) GetSize() (int, int) {
296 return m.textarea.Width(), m.textarea.Height()
297}
298
299func (m *editorCmp) attachmentsContent() string {
300 var styledAttachments []string
301 t := theme.CurrentTheme()
302 attachmentStyles := styles.BaseStyle().
303 MarginLeft(1).
304 Background(t.TextMuted()).
305 Foreground(t.Text())
306 for i, attachment := range m.attachments {
307 var filename string
308 if len(attachment.FileName) > 10 {
309 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
310 } else {
311 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
312 }
313 if m.deleteMode {
314 filename = fmt.Sprintf("%d%s", i, filename)
315 }
316 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
317 }
318 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
319 return content
320}
321
322func (m *editorCmp) BindingKeys() []key.Binding {
323 bindings := []key.Binding{}
324 bindings = append(bindings, layout.KeyMapToSlice(m.keyMap)...)
325 bindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)
326 return bindings
327}
328
329func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
330 m.x = x
331 m.y = y
332 return nil
333}
334
335func (m *editorCmp) startCompletions() tea.Msg {
336 files, _, _ := fileutil.ListDirectory(".", []string{}, 0)
337 completionItems := make([]completions.Completion, 0, len(files))
338 for _, file := range files {
339 file = strings.TrimPrefix(file, "./")
340 completionItems = append(completionItems, completions.Completion{
341 Title: file,
342 Value: FileCompletionItem{
343 Path: file,
344 },
345 })
346 }
347
348 x := m.textarea.Cursor().X + m.x + 1
349 y := m.textarea.Cursor().Y + m.y + 1
350 return completions.OpenCompletionsMsg{
351 Completions: completionItems,
352 X: x,
353 Y: y,
354 }
355}
356
357func CreateTextArea(existing *textarea.Model) textarea.Model {
358 t := styles.CurrentTheme()
359 ta := textarea.New()
360 ta.SetStyles(t.S().TextArea)
361 ta.SetPromptFunc(4, func(lineIndex int) string {
362 if lineIndex == 0 {
363 return " > "
364 }
365 return t.S().Base.Foreground(t.Blue).Render("::: ")
366 })
367 ta.ShowLineNumbers = false
368 ta.CharLimit = -1
369 ta.Placeholder = "Tell me more about this project..."
370 ta.SetVirtualCursor(false)
371
372 if existing != nil {
373 ta.SetValue(existing.Value())
374 ta.SetWidth(existing.Width())
375 ta.SetHeight(existing.Height())
376 }
377
378 ta.Focus()
379 return ta
380}
381
382func NewEditorCmp(app *app.App) util.Model {
383 ta := CreateTextArea(nil)
384 return &editorCmp{
385 app: app,
386 textarea: ta,
387 keyMap: DefaultEditorKeyMap(),
388 }
389}