editor.go

  1package editor
  2
  3import (
  4	"context"
  5	"fmt"
  6	"math/rand"
  7	"net/http"
  8	"os"
  9	"path/filepath"
 10	"runtime"
 11	"slices"
 12	"strings"
 13	"unicode"
 14
 15	"charm.land/bubbles/v2/key"
 16	"charm.land/bubbles/v2/textarea"
 17	tea "charm.land/bubbletea/v2"
 18	"charm.land/lipgloss/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	tuieditor "github.com/charmbracelet/crush/internal/tui/components/dialogs/tui_editor"
 31	"github.com/charmbracelet/crush/internal/tui/styles"
 32	"github.com/charmbracelet/crush/internal/tui/util"
 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	IsEmpty() bool
 46	Cursor() *tea.Cursor
 47}
 48
 49type FileCompletionItem struct {
 50	Path string // The file path
 51}
 52
 53type editorCmp struct {
 54	width              int
 55	height             int
 56	x, y               int
 57	app                *app.App
 58	session            session.Session
 59	textarea           textarea.Model
 60	attachments        []message.Attachment
 61	deleteMode         bool
 62	readyPlaceholder   string
 63	workingPlaceholder string
 64
 65	keyMap EditorKeyMap
 66
 67	// File path completions
 68	currentQuery          string
 69	completionsStartIndex int
 70	isCompletionsOpen     bool
 71}
 72
 73var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 74	AttachmentDeleteMode: key.NewBinding(
 75		key.WithKeys("ctrl+r"),
 76		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 77	),
 78	Escape: key.NewBinding(
 79		key.WithKeys("esc", "alt+esc"),
 80		key.WithHelp("esc", "cancel delete mode"),
 81	),
 82	DeleteAllAttachments: key.NewBinding(
 83		key.WithKeys("r"),
 84		key.WithHelp("ctrl+r+r", "delete all attachments"),
 85	),
 86}
 87
 88const (
 89	maxAttachments = 5
 90	maxFileResults = 25
 91)
 92
 93type OpenEditorMsg struct {
 94	Text string
 95}
 96
 97func (m *editorCmp) openEditor(value string) tea.Cmd {
 98	editor := os.Getenv("EDITOR")
 99	if editor == "" {
100		// Use platform-appropriate default editor.
101		if runtime.GOOS == "windows" {
102			editor = "notepad"
103		} else {
104			editor = "nvim"
105		}
106	}
107
108	tmpfile, err := os.CreateTemp("", "msg_*.md")
109	if err != nil {
110		return util.ReportError(err)
111	}
112	defer tmpfile.Close() //nolint:errcheck
113	if _, err := tmpfile.WriteString(value); err != nil {
114		return util.ReportError(err)
115	}
116
117	if tuieditor.IsTUIEditor(editor) {
118		return util.CmdHandler(commands.OpenEmbeddedEditorMsg{
119			FilePath: tmpfile.Name(),
120			Editor:   editor,
121		})
122	}
123
124	cmdStr := editor + " " + tmpfile.Name()
125	return util.ExecShell(context.TODO(), cmdStr, func(err error) tea.Msg {
126		if err != nil {
127			return util.ReportError(err)
128		}
129		content, err := os.ReadFile(tmpfile.Name())
130		if err != nil {
131			return util.ReportError(err)
132		}
133		if len(content) == 0 {
134			return util.ReportWarn("Message is empty")
135		}
136		os.Remove(tmpfile.Name())
137		return OpenEditorMsg{
138			Text: strings.TrimSpace(string(content)),
139		}
140	})
141}
142
143func (m *editorCmp) Init() tea.Cmd {
144	return nil
145}
146
147func (m *editorCmp) send() tea.Cmd {
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) (util.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.AgentCoordinator.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(msg.Content, "\\ ", " ")
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		// Open command palette when "/" is pressed on empty prompt
274		case msg.String() == "/" && m.IsEmpty():
275			return m, util.CmdHandler(dialogs.OpenDialogMsg{
276				Model: commands.NewCommandDialog(m.app.Context(), m.session.ID),
277			})
278		// Completions
279		case msg.String() == "@" && !m.isCompletionsOpen &&
280			// only show if beginning of prompt, or if previous char is a space or newline:
281			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
282			m.isCompletionsOpen = true
283			m.currentQuery = ""
284			m.completionsStartIndex = curIdx
285			cmds = append(cmds, m.startCompletions)
286		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
287			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
288		}
289		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
290			m.deleteMode = true
291			return m, nil
292		}
293		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
294			m.deleteMode = false
295			m.attachments = nil
296			return m, nil
297		}
298		rune := msg.Code
299		if m.deleteMode && unicode.IsDigit(rune) {
300			num := int(rune - '0')
301			m.deleteMode = false
302			if num < 10 && len(m.attachments) > num {
303				if num == 0 {
304					m.attachments = m.attachments[num+1:]
305				} else {
306					m.attachments = slices.Delete(m.attachments, num, num+1)
307				}
308				return m, nil
309			}
310		}
311		if key.Matches(msg, m.keyMap.OpenEditor) {
312			if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
313				return m, util.ReportWarn("Agent is working, please wait...")
314			}
315			return m, m.openEditor(m.textarea.Value())
316		}
317		if key.Matches(msg, DeleteKeyMaps.Escape) {
318			m.deleteMode = false
319			return m, nil
320		}
321		if key.Matches(msg, m.keyMap.Newline) {
322			m.textarea.InsertRune('\n')
323			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
324		}
325		// Handle Enter key
326		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
327			value := m.textarea.Value()
328			if strings.HasSuffix(value, "\\") {
329				// If the last character is a backslash, remove it and add a newline.
330				m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
331			} else {
332				// Otherwise, send the message
333				return m, m.send()
334			}
335		}
336	}
337
338	m.textarea, cmd = m.textarea.Update(msg)
339	cmds = append(cmds, cmd)
340
341	if m.textarea.Focused() {
342		kp, ok := msg.(tea.KeyPressMsg)
343		if ok {
344			if kp.String() == "space" || m.textarea.Value() == "" {
345				m.isCompletionsOpen = false
346				m.currentQuery = ""
347				m.completionsStartIndex = 0
348				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
349			} else {
350				word := m.textarea.Word()
351				if strings.HasPrefix(word, "@") {
352					// XXX: wont' work if editing in the middle of the field.
353					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
354					m.currentQuery = word[1:]
355					x, y := m.completionsPosition()
356					x -= len(m.currentQuery)
357					m.isCompletionsOpen = true
358					cmds = append(cmds,
359						util.CmdHandler(completions.FilterCompletionsMsg{
360							Query:  m.currentQuery,
361							Reopen: m.isCompletionsOpen,
362							X:      x,
363							Y:      y,
364						}),
365					)
366				} else if m.isCompletionsOpen {
367					m.isCompletionsOpen = false
368					m.currentQuery = ""
369					m.completionsStartIndex = 0
370					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
371				}
372			}
373		}
374	}
375
376	return m, tea.Batch(cmds...)
377}
378
379func (m *editorCmp) setEditorPrompt() {
380	if m.app.Permissions.SkipRequests() {
381		m.textarea.SetPromptFunc(4, yoloPromptFunc)
382		return
383	}
384	m.textarea.SetPromptFunc(4, normalPromptFunc)
385}
386
387func (m *editorCmp) completionsPosition() (int, int) {
388	cur := m.textarea.Cursor()
389	if cur == nil {
390		return m.x, m.y + 1 // adjust for padding
391	}
392	x := cur.X + m.x
393	y := cur.Y + m.y + 1 // adjust for padding
394	return x, y
395}
396
397func (m *editorCmp) Cursor() *tea.Cursor {
398	cursor := m.textarea.Cursor()
399	if cursor != nil {
400		cursor.X = cursor.X + m.x + 1
401		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
402	}
403	return cursor
404}
405
406var readyPlaceholders = [...]string{
407	"Ready!",
408	"Ready...",
409	"Ready?",
410	"Ready for instructions",
411}
412
413var workingPlaceholders = [...]string{
414	"Working!",
415	"Working...",
416	"Brrrrr...",
417	"Prrrrrrrr...",
418	"Processing...",
419	"Thinking...",
420}
421
422func (m *editorCmp) randomizePlaceholders() {
423	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
424	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
425}
426
427func (m *editorCmp) View() string {
428	t := styles.CurrentTheme()
429	// Update placeholder
430	if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
431		m.textarea.Placeholder = m.workingPlaceholder
432	} else {
433		m.textarea.Placeholder = m.readyPlaceholder
434	}
435	if m.app.Permissions.SkipRequests() {
436		m.textarea.Placeholder = "Yolo mode!"
437	}
438	if len(m.attachments) == 0 {
439		content := t.S().Base.Padding(1).Render(
440			m.textarea.View(),
441		)
442		return content
443	}
444	content := t.S().Base.Padding(0, 1, 1, 1).Render(
445		lipgloss.JoinVertical(lipgloss.Top,
446			m.attachmentsContent(),
447			m.textarea.View(),
448		),
449	)
450	return content
451}
452
453func (m *editorCmp) SetSize(width, height int) tea.Cmd {
454	m.width = width
455	m.height = height
456	m.textarea.SetWidth(width - 2)   // adjust for padding
457	m.textarea.SetHeight(height - 2) // adjust for padding
458	return nil
459}
460
461func (m *editorCmp) GetSize() (int, int) {
462	return m.textarea.Width(), m.textarea.Height()
463}
464
465func (m *editorCmp) attachmentsContent() string {
466	var styledAttachments []string
467	t := styles.CurrentTheme()
468	attachmentStyles := t.S().Base.
469		MarginLeft(1).
470		Background(t.FgMuted).
471		Foreground(t.FgBase)
472	for i, attachment := range m.attachments {
473		var filename string
474		if len(attachment.FileName) > 10 {
475			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
476		} else {
477			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
478		}
479		if m.deleteMode {
480			filename = fmt.Sprintf("%d%s", i, filename)
481		}
482		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
483	}
484	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
485	return content
486}
487
488func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
489	m.x = x
490	m.y = y
491	return nil
492}
493
494func (m *editorCmp) startCompletions() tea.Msg {
495	ls := m.app.Config().Options.TUI.Completions
496	depth, limit := ls.Limits()
497	files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
498	slices.Sort(files)
499	completionItems := make([]completions.Completion, 0, len(files))
500	for _, file := range files {
501		file = strings.TrimPrefix(file, "./")
502		completionItems = append(completionItems, completions.Completion{
503			Title: file,
504			Value: FileCompletionItem{
505				Path: file,
506			},
507		})
508	}
509
510	x, y := m.completionsPosition()
511	return completions.OpenCompletionsMsg{
512		Completions: completionItems,
513		X:           x,
514		Y:           y,
515		MaxResults:  maxFileResults,
516	}
517}
518
519// Blur implements Container.
520func (c *editorCmp) Blur() tea.Cmd {
521	c.textarea.Blur()
522	return nil
523}
524
525// Focus implements Container.
526func (c *editorCmp) Focus() tea.Cmd {
527	return c.textarea.Focus()
528}
529
530// IsFocused implements Container.
531func (c *editorCmp) IsFocused() bool {
532	return c.textarea.Focused()
533}
534
535// Bindings implements Container.
536func (c *editorCmp) Bindings() []key.Binding {
537	return c.keyMap.KeyBindings()
538}
539
540// TODO: most likely we do not need to have the session here
541// we need to move some functionality to the page level
542func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
543	c.session = session
544	return nil
545}
546
547func (c *editorCmp) IsCompletionsOpen() bool {
548	return c.isCompletionsOpen
549}
550
551func (c *editorCmp) HasAttachments() bool {
552	return len(c.attachments) > 0
553}
554
555func (c *editorCmp) IsEmpty() bool {
556	return strings.TrimSpace(c.textarea.Value()) == ""
557}
558
559func normalPromptFunc(info textarea.PromptInfo) string {
560	t := styles.CurrentTheme()
561	if info.LineNumber == 0 {
562		return "  > "
563	}
564	if info.Focused {
565		return t.S().Base.Foreground(t.GreenDark).Render("::: ")
566	}
567	return t.S().Muted.Render("::: ")
568}
569
570func yoloPromptFunc(info textarea.PromptInfo) string {
571	t := styles.CurrentTheme()
572	if info.LineNumber == 0 {
573		if info.Focused {
574			return fmt.Sprintf("%s ", t.YoloIconFocused)
575		} else {
576			return fmt.Sprintf("%s ", t.YoloIconBlurred)
577		}
578	}
579	if info.Focused {
580		return fmt.Sprintf("%s ", t.YoloDotsFocused)
581	}
582	return fmt.Sprintf("%s ", t.YoloDotsBlurred)
583}
584
585func New(app *app.App) Editor {
586	t := styles.CurrentTheme()
587	ta := textarea.New()
588	ta.SetStyles(t.S().TextArea)
589	ta.ShowLineNumbers = false
590	ta.CharLimit = -1
591	ta.SetVirtualCursor(false)
592	ta.Focus()
593	e := &editorCmp{
594		// TODO: remove the app instance from here
595		app:      app,
596		textarea: ta,
597		keyMap:   DefaultEditorKeyMap(),
598	}
599	e.setEditorPrompt()
600
601	e.randomizePlaceholders()
602	e.textarea.Placeholder = e.readyPlaceholder
603
604	return e
605}