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