editor.go

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