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