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