editor.go

  1package editor
  2
  3import (
  4	"context"
  5	"fmt"
  6	"math/rand"
  7	"net/http"
  8	"os"
  9	"os/exec"
 10	"path/filepath"
 11	"runtime"
 12	"slices"
 13	"strings"
 14	"unicode"
 15
 16	"github.com/charmbracelet/bubbles/v2/key"
 17	"github.com/charmbracelet/bubbles/v2/textarea"
 18	tea "github.com/charmbracelet/bubbletea/v2"
 19	"github.com/charmbracelet/crush/internal/app"
 20	"github.com/charmbracelet/crush/internal/fsext"
 21	"github.com/charmbracelet/crush/internal/message"
 22	"github.com/charmbracelet/crush/internal/session"
 23	"github.com/charmbracelet/crush/internal/tui/components/chat"
 24	"github.com/charmbracelet/crush/internal/tui/components/completions"
 25	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 26	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 27	"github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
 28	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 29	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 30	"github.com/charmbracelet/crush/internal/tui/styles"
 31	"github.com/charmbracelet/crush/internal/tui/util"
 32	"github.com/charmbracelet/lipgloss/v2"
 33)
 34
 35type Editor interface {
 36	util.Model
 37	layout.Sizeable
 38	layout.Focusable
 39	layout.Help
 40	layout.Positional
 41
 42	SetSession(session session.Session) tea.Cmd
 43	IsCompletionsOpen() bool
 44	HasAttachments() bool
 45	Cursor() *tea.Cursor
 46}
 47
 48type FileCompletionItem struct {
 49	Path string // The file path
 50}
 51
 52type editorCmp struct {
 53	width              int
 54	height             int
 55	x, y               int
 56	app                *app.App
 57	session            session.Session
 58	textarea           *textarea.Model
 59	attachments        []message.Attachment
 60	deleteMode         bool
 61	readyPlaceholder   string
 62	workingPlaceholder string
 63
 64	keyMap EditorKeyMap
 65
 66	// File path completions
 67	currentQuery          string
 68	completionsStartIndex int
 69	isCompletionsOpen     bool
 70}
 71
 72var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 73	AttachmentDeleteMode: key.NewBinding(
 74		key.WithKeys("ctrl+r"),
 75		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 76	),
 77	Escape: key.NewBinding(
 78		key.WithKeys("esc"),
 79		key.WithHelp("esc", "cancel delete mode"),
 80	),
 81	DeleteAllAttachments: key.NewBinding(
 82		key.WithKeys("r"),
 83		key.WithHelp("ctrl+r+r", "delete all attachments"),
 84	),
 85}
 86
 87const (
 88	maxAttachments = 5
 89)
 90
 91type OpenEditorMsg struct {
 92	Text string
 93}
 94
 95func (m *editorCmp) openEditor(value string) tea.Cmd {
 96	editor := os.Getenv("EDITOR")
 97	if editor == "" {
 98		// Use platform-appropriate default editor
 99		if runtime.GOOS == "windows" {
100			editor = "notepad"
101		} else {
102			editor = "nvim"
103		}
104	}
105
106	tmpfile, err := os.CreateTemp("", "msg_*.md")
107	if err != nil {
108		return util.ReportError(err)
109	}
110	defer tmpfile.Close() //nolint:errcheck
111	if _, err := tmpfile.WriteString(value); err != nil {
112		return util.ReportError(err)
113	}
114	c := exec.CommandContext(context.TODO(), editor, tmpfile.Name())
115	c.Stdin = os.Stdin
116	c.Stdout = os.Stdout
117	c.Stderr = os.Stderr
118	return tea.ExecProcess(c, func(err error) tea.Msg {
119		if err != nil {
120			return util.ReportError(err)
121		}
122		content, err := os.ReadFile(tmpfile.Name())
123		if err != nil {
124			return util.ReportError(err)
125		}
126		if len(content) == 0 {
127			return util.ReportWarn("Message is empty")
128		}
129		os.Remove(tmpfile.Name())
130		return OpenEditorMsg{
131			Text: strings.TrimSpace(string(content)),
132		}
133	})
134}
135
136func (m *editorCmp) Init() tea.Cmd {
137	return nil
138}
139
140func (m *editorCmp) send() tea.Cmd {
141	if m.app.CoderAgent == nil {
142		return util.ReportError(fmt.Errorf("coder agent is not initialized"))
143	}
144	if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
145		return util.ReportWarn("Agent is working, please wait...")
146	}
147
148	value := m.textarea.Value()
149	value = strings.TrimSpace(value)
150
151	switch value {
152	case "exit", "quit":
153		m.textarea.Reset()
154		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
155	}
156
157	m.textarea.Reset()
158	attachments := m.attachments
159
160	m.attachments = nil
161	if value == "" {
162		return nil
163	}
164
165	// Change the placeholder when sending a new message.
166	m.randomizePlaceholders()
167
168	return tea.Batch(
169		util.CmdHandler(chat.SendMsg{
170			Text:        value,
171			Attachments: attachments,
172		}),
173	)
174}
175
176func (m *editorCmp) repositionCompletions() tea.Msg {
177	x, y := m.completionsPosition()
178	return completions.RepositionCompletionsMsg{X: x, Y: y}
179}
180
181func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
182	var cmd tea.Cmd
183	var cmds []tea.Cmd
184	switch msg := msg.(type) {
185	case tea.WindowSizeMsg:
186		return m, m.repositionCompletions
187	case filepicker.FilePickedMsg:
188		if len(m.attachments) >= maxAttachments {
189			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
190		}
191		m.attachments = append(m.attachments, msg.Attachment)
192		return m, nil
193	case completions.CompletionsOpenedMsg:
194		m.isCompletionsOpen = true
195	case completions.CompletionsClosedMsg:
196		m.isCompletionsOpen = false
197		m.currentQuery = ""
198		m.completionsStartIndex = 0
199	case completions.SelectCompletionMsg:
200		if !m.isCompletionsOpen {
201			return m, nil
202		}
203		if item, ok := msg.Value.(FileCompletionItem); ok {
204			word := m.textarea.Word()
205			// If the selected item is a file, insert its path into the textarea
206			value := m.textarea.Value()
207			value = value[:m.completionsStartIndex] + // Remove the current query
208				item.Path + // Insert the file path
209				value[m.completionsStartIndex+len(word):] // Append the rest of the value
210			// XXX: This will always move the cursor to the end of the textarea.
211			m.textarea.SetValue(value)
212			m.textarea.MoveToEnd()
213			if !msg.Insert {
214				m.isCompletionsOpen = false
215				m.currentQuery = ""
216				m.completionsStartIndex = 0
217			}
218		}
219
220	case commands.OpenExternalEditorMsg:
221		if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
222			return m, util.ReportWarn("Agent is working, please wait...")
223		}
224		return m, m.openEditor(m.textarea.Value())
225	case OpenEditorMsg:
226		m.textarea.SetValue(msg.Text)
227		m.textarea.MoveToEnd()
228	case tea.PasteMsg:
229		path := strings.ReplaceAll(string(msg), "\\ ", " ")
230		// try to get an image
231		path, err := filepath.Abs(strings.TrimSpace(path))
232		if err != nil {
233			m.textarea, cmd = m.textarea.Update(msg)
234			return m, cmd
235		}
236		isAllowedType := false
237		for _, ext := range filepicker.AllowedTypes {
238			if strings.HasSuffix(path, ext) {
239				isAllowedType = true
240				break
241			}
242		}
243		if !isAllowedType {
244			m.textarea, cmd = m.textarea.Update(msg)
245			return m, cmd
246		}
247		tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
248		if tooBig {
249			m.textarea, cmd = m.textarea.Update(msg)
250			return m, cmd
251		}
252
253		content, err := os.ReadFile(path)
254		if err != nil {
255			m.textarea, cmd = m.textarea.Update(msg)
256			return m, cmd
257		}
258		mimeBufferSize := min(512, len(content))
259		mimeType := http.DetectContentType(content[:mimeBufferSize])
260		fileName := filepath.Base(path)
261		attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
262		return m, util.CmdHandler(filepicker.FilePickedMsg{
263			Attachment: attachment,
264		})
265
266	case commands.ToggleYoloModeMsg:
267		m.setEditorPrompt()
268		return m, nil
269	case tea.KeyPressMsg:
270		cur := m.textarea.Cursor()
271		curIdx := m.textarea.Width()*cur.Y + cur.X
272		switch {
273		// Completions
274		case msg.String() == "/" && !m.isCompletionsOpen &&
275			// only show if beginning of prompt, or if previous char is a space or newline:
276			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
277			m.isCompletionsOpen = true
278			m.currentQuery = ""
279			m.completionsStartIndex = curIdx
280			cmds = append(cmds, m.startCompletions)
281		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
282			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
283		}
284		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
285			m.deleteMode = true
286			return m, nil
287		}
288		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
289			m.deleteMode = false
290			m.attachments = nil
291			return m, nil
292		}
293		rune := msg.Code
294		if m.deleteMode && unicode.IsDigit(rune) {
295			num := int(rune - '0')
296			m.deleteMode = false
297			if num < 10 && len(m.attachments) > num {
298				if num == 0 {
299					m.attachments = m.attachments[num+1:]
300				} else {
301					m.attachments = slices.Delete(m.attachments, num, num+1)
302				}
303				return m, nil
304			}
305		}
306		if key.Matches(msg, m.keyMap.OpenEditor) {
307			if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
308				return m, util.ReportWarn("Agent is working, please wait...")
309			}
310			return m, m.openEditor(m.textarea.Value())
311		}
312		if key.Matches(msg, DeleteKeyMaps.Escape) {
313			m.deleteMode = false
314			return m, nil
315		}
316		if key.Matches(msg, m.keyMap.Newline) {
317			m.textarea.InsertRune('\n')
318			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
319		}
320		// Handle Enter key
321		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
322			value := m.textarea.Value()
323			if len(value) > 0 && value[len(value)-1] == '\\' {
324				// If the last character is a backslash, remove it and add a newline
325				m.textarea.SetValue(value[:len(value)-1])
326			} else {
327				// Otherwise, send the message
328				return m, m.send()
329			}
330		}
331	}
332
333	m.textarea, cmd = m.textarea.Update(msg)
334	cmds = append(cmds, cmd)
335
336	if m.textarea.Focused() {
337		kp, ok := msg.(tea.KeyPressMsg)
338		if ok {
339			if kp.String() == "space" || m.textarea.Value() == "" {
340				m.isCompletionsOpen = false
341				m.currentQuery = ""
342				m.completionsStartIndex = 0
343				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
344			} else {
345				word := m.textarea.Word()
346				if strings.HasPrefix(word, "/") {
347					// XXX: wont' work if editing in the middle of the field.
348					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
349					m.currentQuery = word[1:]
350					x, y := m.completionsPosition()
351					x -= len(m.currentQuery)
352					m.isCompletionsOpen = true
353					cmds = append(cmds,
354						util.CmdHandler(completions.FilterCompletionsMsg{
355							Query:  m.currentQuery,
356							Reopen: m.isCompletionsOpen,
357							X:      x,
358							Y:      y,
359						}),
360					)
361				} else if m.isCompletionsOpen {
362					m.isCompletionsOpen = false
363					m.currentQuery = ""
364					m.completionsStartIndex = 0
365					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
366				}
367			}
368		}
369	}
370
371	return m, tea.Batch(cmds...)
372}
373
374func (m *editorCmp) setEditorPrompt() {
375	if m.app.Permissions.SkipRequests() {
376		m.textarea.SetPromptFunc(4, yoloPromptFunc)
377		return
378	}
379	m.textarea.SetPromptFunc(4, normalPromptFunc)
380}
381
382func (m *editorCmp) completionsPosition() (int, int) {
383	cur := m.textarea.Cursor()
384	if cur == nil {
385		return m.x, m.y + 1 // adjust for padding
386	}
387	x := cur.X + m.x
388	y := cur.Y + m.y + 1 // adjust for padding
389	return x, y
390}
391
392func (m *editorCmp) Cursor() *tea.Cursor {
393	cursor := m.textarea.Cursor()
394	if cursor != nil {
395		cursor.X = cursor.X + m.x + 1
396		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
397	}
398	return cursor
399}
400
401var readyPlaceholders = [...]string{
402	"Ready!",
403	"Ready...",
404	"Ready?",
405	"Ready for instructions",
406}
407
408var workingPlaceholders = [...]string{
409	"Working!",
410	"Working...",
411	"Brrrrr...",
412	"Prrrrrrrr...",
413	"Processing...",
414	"Thinking...",
415}
416
417func (m *editorCmp) randomizePlaceholders() {
418	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
419	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
420}
421
422func (m *editorCmp) View() string {
423	t := styles.CurrentTheme()
424	// Update placeholder
425	if m.app.CoderAgent != nil && m.app.CoderAgent.IsBusy() {
426		m.textarea.Placeholder = m.workingPlaceholder
427	} else {
428		m.textarea.Placeholder = m.readyPlaceholder
429	}
430	if m.app.Permissions.SkipRequests() {
431		m.textarea.Placeholder = "Yolo mode!"
432	}
433	if len(m.attachments) == 0 {
434		content := t.S().Base.Padding(1).Render(
435			m.textarea.View(),
436		)
437		return content
438	}
439	content := t.S().Base.Padding(0, 1, 1, 1).Render(
440		lipgloss.JoinVertical(lipgloss.Top,
441			m.attachmentsContent(),
442			m.textarea.View(),
443		),
444	)
445	return content
446}
447
448func (m *editorCmp) SetSize(width, height int) tea.Cmd {
449	m.width = width
450	m.height = height
451	m.textarea.SetWidth(width - 2)   // adjust for padding
452	m.textarea.SetHeight(height - 2) // adjust for padding
453	return nil
454}
455
456func (m *editorCmp) GetSize() (int, int) {
457	return m.textarea.Width(), m.textarea.Height()
458}
459
460func (m *editorCmp) attachmentsContent() string {
461	var styledAttachments []string
462	t := styles.CurrentTheme()
463	attachmentStyles := t.S().Base.
464		MarginLeft(1).
465		Background(t.FgMuted).
466		Foreground(t.FgBase)
467	for i, attachment := range m.attachments {
468		var filename string
469		if len(attachment.FileName) > 10 {
470			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
471		} else {
472			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
473		}
474		if m.deleteMode {
475			filename = fmt.Sprintf("%d%s", i, filename)
476		}
477		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
478	}
479	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
480	return content
481}
482
483func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
484	m.x = x
485	m.y = y
486	return nil
487}
488
489func (m *editorCmp) startCompletions() tea.Msg {
490	files, _, _ := fsext.ListDirectory(".", nil, 0)
491	completionItems := make([]completions.Completion, 0, len(files))
492	for _, file := range files {
493		file = strings.TrimPrefix(file, "./")
494		completionItems = append(completionItems, completions.Completion{
495			Title: file,
496			Value: FileCompletionItem{
497				Path: file,
498			},
499		})
500	}
501
502	x, y := m.completionsPosition()
503	return completions.OpenCompletionsMsg{
504		Completions: completionItems,
505		X:           x,
506		Y:           y,
507	}
508}
509
510// Blur implements Container.
511func (c *editorCmp) Blur() tea.Cmd {
512	c.textarea.Blur()
513	return nil
514}
515
516// Focus implements Container.
517func (c *editorCmp) Focus() tea.Cmd {
518	return c.textarea.Focus()
519}
520
521// IsFocused implements Container.
522func (c *editorCmp) IsFocused() bool {
523	return c.textarea.Focused()
524}
525
526// Bindings implements Container.
527func (c *editorCmp) Bindings() []key.Binding {
528	return c.keyMap.KeyBindings()
529}
530
531// TODO: most likely we do not need to have the session here
532// we need to move some functionality to the page level
533func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
534	c.session = session
535	return nil
536}
537
538func (c *editorCmp) IsCompletionsOpen() bool {
539	return c.isCompletionsOpen
540}
541
542func (c *editorCmp) HasAttachments() bool {
543	return len(c.attachments) > 0
544}
545
546func normalPromptFunc(info textarea.PromptInfo) string {
547	t := styles.CurrentTheme()
548	if info.LineNumber == 0 {
549		return "  > "
550	}
551	if info.Focused {
552		return t.S().Base.Foreground(t.GreenDark).Render("::: ")
553	}
554	return t.S().Muted.Render("::: ")
555}
556
557func yoloPromptFunc(info textarea.PromptInfo) string {
558	t := styles.CurrentTheme()
559	if info.LineNumber == 0 {
560		if info.Focused {
561			return fmt.Sprintf("%s ", t.YoloIconFocused)
562		} else {
563			return fmt.Sprintf("%s ", t.YoloIconBlurred)
564		}
565	}
566	if info.Focused {
567		return fmt.Sprintf("%s ", t.YoloDotsFocused)
568	}
569	return fmt.Sprintf("%s ", t.YoloDotsBlurred)
570}
571
572func New(app *app.App) Editor {
573	t := styles.CurrentTheme()
574	ta := textarea.New()
575	ta.SetStyles(t.S().TextArea)
576	ta.ShowLineNumbers = false
577	ta.CharLimit = -1
578	ta.SetVirtualCursor(false)
579	ta.Focus()
580	e := &editorCmp{
581		// TODO: remove the app instance from here
582		app:      app,
583		textarea: ta,
584		keyMap:   DefaultEditorKeyMap(),
585	}
586	e.setEditorPrompt()
587
588	e.randomizePlaceholders()
589	e.textarea.Placeholder = e.readyPlaceholder
590
591	return e
592}