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