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(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 tea.KeyPressMsg:
267		cur := m.textarea.Cursor()
268		curIdx := m.textarea.Width()*cur.Y + cur.X
269		switch {
270		// Completions
271		case msg.String() == "/" && !m.isCompletionsOpen &&
272			// only show if beginning of prompt, or if previous char is a space or newline:
273			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
274			m.isCompletionsOpen = true
275			m.currentQuery = ""
276			m.completionsStartIndex = curIdx
277			cmds = append(cmds, m.startCompletions)
278		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
279			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
280		}
281		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
282			m.deleteMode = true
283			return m, nil
284		}
285		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
286			m.deleteMode = false
287			m.attachments = nil
288			return m, nil
289		}
290		rune := msg.Code
291		if m.deleteMode && unicode.IsDigit(rune) {
292			num := int(rune - '0')
293			m.deleteMode = false
294			if num < 10 && len(m.attachments) > num {
295				if num == 0 {
296					m.attachments = m.attachments[num+1:]
297				} else {
298					m.attachments = slices.Delete(m.attachments, num, num+1)
299				}
300				return m, nil
301			}
302		}
303		if key.Matches(msg, m.keyMap.OpenEditor) {
304			if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
305				return m, util.ReportWarn("Agent is working, please wait...")
306			}
307			return m, m.openEditor(m.textarea.Value())
308		}
309		if key.Matches(msg, DeleteKeyMaps.Escape) {
310			m.deleteMode = false
311			return m, nil
312		}
313		if key.Matches(msg, m.keyMap.Newline) {
314			m.textarea.InsertRune('\n')
315			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
316		}
317		// Handle Enter key
318		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
319			value := m.textarea.Value()
320			if len(value) > 0 && value[len(value)-1] == '\\' {
321				// If the last character is a backslash, remove it and add a newline
322				m.textarea.SetValue(value[:len(value)-1])
323			} else {
324				// Otherwise, send the message
325				return m, m.send()
326			}
327		}
328	}
329
330	m.textarea, cmd = m.textarea.Update(msg)
331	cmds = append(cmds, cmd)
332
333	if m.textarea.Focused() {
334		kp, ok := msg.(tea.KeyPressMsg)
335		if ok {
336			if kp.String() == "space" || m.textarea.Value() == "" {
337				m.isCompletionsOpen = false
338				m.currentQuery = ""
339				m.completionsStartIndex = 0
340				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
341			} else {
342				word := m.textarea.Word()
343				if strings.HasPrefix(word, "/") {
344					// XXX: wont' work if editing in the middle of the field.
345					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
346					m.currentQuery = word[1:]
347					x, y := m.completionsPosition()
348					x -= len(m.currentQuery)
349					m.isCompletionsOpen = true
350					cmds = append(cmds,
351						util.CmdHandler(completions.FilterCompletionsMsg{
352							Query:  m.currentQuery,
353							Reopen: m.isCompletionsOpen,
354							X:      x,
355							Y:      y,
356						}),
357					)
358				} else if m.isCompletionsOpen {
359					m.isCompletionsOpen = false
360					m.currentQuery = ""
361					m.completionsStartIndex = 0
362					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
363				}
364			}
365		}
366	}
367
368	return m, tea.Batch(cmds...)
369}
370
371func (m *editorCmp) completionsPosition() (int, int) {
372	cur := m.textarea.Cursor()
373	if cur == nil {
374		return m.x, m.y + 1 // adjust for padding
375	}
376	x := cur.X + m.x
377	y := cur.Y + m.y + 1 // adjust for padding
378	return x, y
379}
380
381func (m *editorCmp) Cursor() *tea.Cursor {
382	cursor := m.textarea.Cursor()
383	if cursor != nil {
384		cursor.X = cursor.X + m.x + 1
385		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
386	}
387	return cursor
388}
389
390var readyPlaceholders = [...]string{
391	"Ready!",
392	"Ready...",
393	"Ready?",
394	"Ready for instructions",
395}
396
397var workingPlaceholders = [...]string{
398	"Working!",
399	"Working...",
400	"Brrrrr...",
401	"Prrrrrrrr...",
402	"Processing...",
403	"Thinking...",
404}
405
406func (m *editorCmp) randomizePlaceholders() {
407	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
408	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
409}
410
411func (m *editorCmp) View() string {
412	t := styles.CurrentTheme()
413	// Update placeholder
414	if m.app.CoderAgent != nil && m.app.CoderAgent.IsBusy() {
415		m.textarea.Placeholder = m.workingPlaceholder
416	} else {
417		m.textarea.Placeholder = m.readyPlaceholder
418	}
419	if len(m.attachments) == 0 {
420		content := t.S().Base.Padding(1).Render(
421			m.textarea.View(),
422		)
423		return content
424	}
425	content := t.S().Base.Padding(0, 1, 1, 1).Render(
426		lipgloss.JoinVertical(lipgloss.Top,
427			m.attachmentsContent(),
428			m.textarea.View(),
429		),
430	)
431	return content
432}
433
434func (m *editorCmp) SetSize(width, height int) tea.Cmd {
435	m.width = width
436	m.height = height
437	m.textarea.SetWidth(width - 2)   // adjust for padding
438	m.textarea.SetHeight(height - 2) // adjust for padding
439	return nil
440}
441
442func (m *editorCmp) GetSize() (int, int) {
443	return m.textarea.Width(), m.textarea.Height()
444}
445
446func (m *editorCmp) attachmentsContent() string {
447	var styledAttachments []string
448	t := styles.CurrentTheme()
449	attachmentStyles := t.S().Base.
450		MarginLeft(1).
451		Background(t.FgMuted).
452		Foreground(t.FgBase)
453	for i, attachment := range m.attachments {
454		var filename string
455		if len(attachment.FileName) > 10 {
456			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
457		} else {
458			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
459		}
460		if m.deleteMode {
461			filename = fmt.Sprintf("%d%s", i, filename)
462		}
463		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
464	}
465	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
466	return content
467}
468
469func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
470	m.x = x
471	m.y = y
472	return nil
473}
474
475func (m *editorCmp) startCompletions() tea.Msg {
476	files, _, _ := fsext.ListDirectory(".", nil, 0)
477	completionItems := make([]completions.Completion, 0, len(files))
478	for _, file := range files {
479		file = strings.TrimPrefix(file, "./")
480		completionItems = append(completionItems, completions.Completion{
481			Title: file,
482			Value: FileCompletionItem{
483				Path: file,
484			},
485		})
486	}
487
488	x, y := m.completionsPosition()
489	return completions.OpenCompletionsMsg{
490		Completions: completionItems,
491		X:           x,
492		Y:           y,
493	}
494}
495
496// Blur implements Container.
497func (c *editorCmp) Blur() tea.Cmd {
498	c.textarea.Blur()
499	return nil
500}
501
502// Focus implements Container.
503func (c *editorCmp) Focus() tea.Cmd {
504	return c.textarea.Focus()
505}
506
507// IsFocused implements Container.
508func (c *editorCmp) IsFocused() bool {
509	return c.textarea.Focused()
510}
511
512// Bindings implements Container.
513func (c *editorCmp) Bindings() []key.Binding {
514	return c.keyMap.KeyBindings()
515}
516
517// TODO: most likely we do not need to have the session here
518// we need to move some functionality to the page level
519func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
520	c.session = session
521	return nil
522}
523
524func (c *editorCmp) IsCompletionsOpen() bool {
525	return c.isCompletionsOpen
526}
527
528func (c *editorCmp) HasAttachments() bool {
529	return len(c.attachments) > 0
530}
531
532func New(app *app.App) Editor {
533	t := styles.CurrentTheme()
534	ta := textarea.New()
535	ta.SetStyles(t.S().TextArea)
536	ta.SetPromptFunc(4, func(info textarea.PromptInfo) string {
537		if info.LineNumber == 0 {
538			return "  > "
539		}
540		if info.Focused {
541			return t.S().Base.Foreground(t.GreenDark).Render("::: ")
542		} else {
543			return t.S().Muted.Render("::: ")
544		}
545	})
546	ta.ShowLineNumbers = false
547	ta.CharLimit = -1
548	ta.SetVirtualCursor(false)
549	ta.Focus()
550
551	e := &editorCmp{
552		// TODO: remove the app instance from here
553		app:      app,
554		textarea: ta,
555		keyMap:   DefaultEditorKeyMap(),
556	}
557
558	e.randomizePlaceholders()
559	e.textarea.Placeholder = e.readyPlaceholder
560
561	return e
562}