editor.go

  1package editor
  2
  3import (
  4	"fmt"
  5	"os"
  6	"os/exec"
  7	"runtime"
  8	"slices"
  9	"strings"
 10	"unicode"
 11
 12	"github.com/charmbracelet/bubbles/v2/key"
 13	"github.com/charmbracelet/bubbles/v2/textarea"
 14	tea "github.com/charmbracelet/bubbletea/v2"
 15	"github.com/charmbracelet/crush/internal/app"
 16	"github.com/charmbracelet/crush/internal/fsext"
 17	"github.com/charmbracelet/crush/internal/message"
 18	"github.com/charmbracelet/crush/internal/session"
 19	"github.com/charmbracelet/crush/internal/tui/components/chat"
 20	"github.com/charmbracelet/crush/internal/tui/components/completions"
 21	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 22	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 23	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 24	"github.com/charmbracelet/crush/internal/tui/styles"
 25	"github.com/charmbracelet/crush/internal/tui/util"
 26	"github.com/charmbracelet/lipgloss/v2"
 27)
 28
 29type FileCompletionItem struct {
 30	Path string // The file path
 31}
 32
 33type editorCmp struct {
 34	width       int
 35	height      int
 36	x, y        int
 37	app         *app.App
 38	session     session.Session
 39	textarea    textarea.Model
 40	attachments []message.Attachment
 41	deleteMode  bool
 42
 43	keyMap EditorKeyMap
 44
 45	// File path completions
 46	currentQuery          string
 47	completionsStartIndex int
 48	isCompletionsOpen     bool
 49}
 50
 51var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 52	AttachmentDeleteMode: key.NewBinding(
 53		key.WithKeys("ctrl+r"),
 54		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 55	),
 56	Escape: key.NewBinding(
 57		key.WithKeys("esc"),
 58		key.WithHelp("esc", "cancel delete mode"),
 59	),
 60	DeleteAllAttachments: key.NewBinding(
 61		key.WithKeys("r"),
 62		key.WithHelp("ctrl+r+r", "delete all attchments"),
 63	),
 64}
 65
 66const (
 67	maxAttachments = 5
 68)
 69
 70func (m *editorCmp) openEditor() tea.Cmd {
 71	editor := os.Getenv("EDITOR")
 72	if editor == "" {
 73		// Use platform-appropriate default editor
 74		if runtime.GOOS == "windows" {
 75			editor = "notepad"
 76		} else {
 77			editor = "nvim"
 78		}
 79	}
 80
 81	tmpfile, err := os.CreateTemp("", "msg_*.md")
 82	if err != nil {
 83		return util.ReportError(err)
 84	}
 85	tmpfile.Close()
 86	c := exec.Command(editor, tmpfile.Name())
 87	c.Stdin = os.Stdin
 88	c.Stdout = os.Stdout
 89	c.Stderr = os.Stderr
 90	return tea.ExecProcess(c, func(err error) tea.Msg {
 91		if err != nil {
 92			return util.ReportError(err)
 93		}
 94		content, err := os.ReadFile(tmpfile.Name())
 95		if err != nil {
 96			return util.ReportError(err)
 97		}
 98		if len(content) == 0 {
 99			return util.ReportWarn("Message is empty")
100		}
101		os.Remove(tmpfile.Name())
102		attachments := m.attachments
103		m.attachments = nil
104		return chat.SendMsg{
105			Text:        string(content),
106			Attachments: attachments,
107		}
108	})
109}
110
111func (m *editorCmp) Init() tea.Cmd {
112	return nil
113}
114
115func (m *editorCmp) send() tea.Cmd {
116	if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
117		return util.ReportWarn("Agent is working, please wait...")
118	}
119
120	value := m.textarea.Value()
121	value = strings.TrimSpace(value)
122
123	switch value {
124	case "exit", "quit":
125		m.textarea.Reset()
126		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
127	}
128
129	m.textarea.Reset()
130	attachments := m.attachments
131
132	m.attachments = nil
133	if value == "" {
134		return nil
135	}
136	return tea.Batch(
137		util.CmdHandler(chat.SendMsg{
138			Text:        value,
139			Attachments: attachments,
140		}),
141	)
142}
143
144func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
145	var cmd tea.Cmd
146	var cmds []tea.Cmd
147	switch msg := msg.(type) {
148	case chat.SessionSelectedMsg:
149		if msg.ID != m.session.ID {
150			m.session = msg
151		}
152		return m, nil
153	case filepicker.FilePickedMsg:
154		if len(m.attachments) >= maxAttachments {
155			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
156		}
157		m.attachments = append(m.attachments, msg.Attachment)
158		return m, nil
159	case completions.CompletionsClosedMsg:
160		m.isCompletionsOpen = false
161		m.currentQuery = ""
162		m.completionsStartIndex = 0
163	case completions.SelectCompletionMsg:
164		if !m.isCompletionsOpen {
165			return m, nil
166		}
167		if item, ok := msg.Value.(FileCompletionItem); ok {
168			// If the selected item is a file, insert its path into the textarea
169			value := m.textarea.Value()
170			value = value[:m.completionsStartIndex]
171			if len(value) > 0 && value[len(value)-1] != ' ' {
172				value += " "
173			}
174			value += item.Path
175			m.textarea.SetValue(value)
176			m.isCompletionsOpen = false
177			m.currentQuery = ""
178			m.completionsStartIndex = 0
179			return m, nil
180		}
181	case tea.KeyPressMsg:
182		switch {
183		// Completions
184		case msg.String() == "/" && !m.isCompletionsOpen:
185			m.isCompletionsOpen = true
186			m.currentQuery = ""
187			cmds = append(cmds, m.startCompletions)
188			m.completionsStartIndex = len(m.textarea.Value())
189		case msg.String() == "space" && m.isCompletionsOpen:
190			m.isCompletionsOpen = false
191			m.currentQuery = ""
192			m.completionsStartIndex = 0
193			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
194		case m.isCompletionsOpen && m.textarea.Cursor().X <= m.completionsStartIndex:
195			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
196		case msg.String() == "backspace" && m.isCompletionsOpen:
197			if len(m.currentQuery) > 0 {
198				m.currentQuery = m.currentQuery[:len(m.currentQuery)-1]
199				cmds = append(cmds, util.CmdHandler(completions.FilterCompletionsMsg{
200					Query: m.currentQuery,
201				}))
202			} else {
203				m.isCompletionsOpen = false
204				m.currentQuery = ""
205				m.completionsStartIndex = 0
206				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
207			}
208		default:
209			if m.isCompletionsOpen {
210				m.currentQuery += msg.String()
211				cmds = append(cmds, util.CmdHandler(completions.FilterCompletionsMsg{
212					Query: m.currentQuery,
213				}))
214			}
215		}
216		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
217			m.deleteMode = true
218			return m, nil
219		}
220		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
221			m.deleteMode = false
222			m.attachments = nil
223			return m, nil
224		}
225		rune := msg.Code
226		if m.deleteMode && unicode.IsDigit(rune) {
227			num := int(rune - '0')
228			m.deleteMode = false
229			if num < 10 && len(m.attachments) > num {
230				if num == 0 {
231					m.attachments = m.attachments[num+1:]
232				} else {
233					m.attachments = slices.Delete(m.attachments, num, num+1)
234				}
235				return m, nil
236			}
237		}
238		if key.Matches(msg, m.keyMap.OpenEditor) {
239			if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
240				return m, util.ReportWarn("Agent is working, please wait...")
241			}
242			return m, m.openEditor()
243		}
244		if key.Matches(msg, DeleteKeyMaps.Escape) {
245			m.deleteMode = false
246			return m, nil
247		}
248		// Hanlde Enter key
249		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
250			value := m.textarea.Value()
251			if len(value) > 0 && value[len(value)-1] == '\\' {
252				// If the last character is a backslash, remove it and add a newline
253				m.textarea.SetValue(value[:len(value)-1] + "\n")
254				return m, nil
255			} else {
256				// Otherwise, send the message
257				return m, m.send()
258			}
259		}
260	}
261
262	m.textarea, cmd = m.textarea.Update(msg)
263	cmds = append(cmds, cmd)
264	return m, tea.Batch(cmds...)
265}
266
267func (m *editorCmp) Cursor() *tea.Cursor {
268	cursor := m.textarea.Cursor()
269	if cursor != nil {
270		cursor.X = cursor.X + m.x + 1
271		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
272	}
273	return cursor
274}
275
276func (m *editorCmp) View() string {
277	t := styles.CurrentTheme()
278	if len(m.attachments) == 0 {
279		content := t.S().Base.Padding(1).Render(
280			m.textarea.View(),
281		)
282		return content
283	}
284	content := t.S().Base.Padding(0, 1, 1, 1).Render(
285		lipgloss.JoinVertical(lipgloss.Top,
286			m.attachmentsContent(),
287			m.textarea.View(),
288		),
289	)
290	return content
291}
292
293func (m *editorCmp) SetSize(width, height int) tea.Cmd {
294	m.width = width
295	m.height = height
296	m.textarea.SetWidth(width - 2)   // adjust for padding
297	m.textarea.SetHeight(height - 2) // adjust for padding
298	return nil
299}
300
301func (m *editorCmp) GetSize() (int, int) {
302	return m.textarea.Width(), m.textarea.Height()
303}
304
305func (m *editorCmp) attachmentsContent() string {
306	var styledAttachments []string
307	t := styles.CurrentTheme()
308	attachmentStyles := t.S().Base.
309		MarginLeft(1).
310		Background(t.FgMuted).
311		Foreground(t.FgBase)
312	for i, attachment := range m.attachments {
313		var filename string
314		if len(attachment.FileName) > 10 {
315			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
316		} else {
317			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
318		}
319		if m.deleteMode {
320			filename = fmt.Sprintf("%d%s", i, filename)
321		}
322		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
323	}
324	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
325	return content
326}
327
328func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
329	m.x = x
330	m.y = y
331	return nil
332}
333
334func (m *editorCmp) startCompletions() tea.Msg {
335	files, _, _ := fsext.ListDirectory(".", []string{}, 0)
336	completionItems := make([]completions.Completion, 0, len(files))
337	for _, file := range files {
338		file = strings.TrimPrefix(file, "./")
339		completionItems = append(completionItems, completions.Completion{
340			Title: file,
341			Value: FileCompletionItem{
342				Path: file,
343			},
344		})
345	}
346
347	x := m.textarea.Cursor().X + m.x + 1
348	y := m.textarea.Cursor().Y + m.y + 1
349	return completions.OpenCompletionsMsg{
350		Completions: completionItems,
351		X:           x,
352		Y:           y,
353	}
354}
355
356// Blur implements Container.
357func (c *editorCmp) Blur() tea.Cmd {
358	c.textarea.Blur()
359	return nil
360}
361
362// Focus implements Container.
363func (c *editorCmp) Focus() tea.Cmd {
364	return c.textarea.Focus()
365}
366
367// IsFocused implements Container.
368func (c *editorCmp) IsFocused() bool {
369	return c.textarea.Focused()
370}
371
372func (c *editorCmp) Bindings() []key.Binding {
373	return c.keyMap.KeyBindings()
374}
375
376func NewEditorCmp(app *app.App) util.Model {
377	t := styles.CurrentTheme()
378	ta := textarea.New()
379	ta.SetStyles(t.S().TextArea)
380	ta.SetPromptFunc(4, func(lineIndex int, focused bool) string {
381		if lineIndex == 0 {
382			return "  > "
383		}
384		if focused {
385			return t.S().Base.Foreground(t.GreenDark).Render("::: ")
386		} else {
387			return t.S().Muted.Render("::: ")
388		}
389	})
390	ta.ShowLineNumbers = false
391	ta.CharLimit = -1
392	ta.Placeholder = "Tell me more about this project..."
393	ta.SetVirtualCursor(false)
394	ta.Focus()
395
396	return &editorCmp{
397		app:      app,
398		textarea: ta,
399		keyMap:   DefaultEditorKeyMap(),
400	}
401}