editor.go

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