editor.go

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