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) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
165	var cmd tea.Cmd
166	var cmds []tea.Cmd
167	switch msg := msg.(type) {
168	case filepicker.FilePickedMsg:
169		if len(m.attachments) >= maxAttachments {
170			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
171		}
172		m.attachments = append(m.attachments, msg.Attachment)
173		return m, nil
174	case completions.CompletionsOpenedMsg:
175		m.isCompletionsOpen = true
176	case completions.CompletionsClosedMsg:
177		m.isCompletionsOpen = false
178		m.currentQuery = ""
179		m.completionsStartIndex = 0
180	case completions.SelectCompletionMsg:
181		if !m.isCompletionsOpen {
182			return m, nil
183		}
184		if item, ok := msg.Value.(FileCompletionItem); ok {
185			// If the selected item is a file, insert its path into the textarea
186			value := m.textarea.Value()
187			value = value[:m.completionsStartIndex]
188			value += item.Path
189			m.textarea.SetValue(value)
190			if !msg.Insert {
191				m.isCompletionsOpen = false
192				m.currentQuery = ""
193				m.completionsStartIndex = 0
194			}
195			return m, nil
196		}
197	case openEditorMsg:
198		m.textarea.SetValue(msg.Text)
199		m.textarea.MoveToEnd()
200	case tea.KeyPressMsg:
201		switch {
202		// Completions
203		case msg.String() == "/" && !m.isCompletionsOpen &&
204			// only show if beginning of prompt, or if previous char is a space:
205			(len(m.textarea.Value()) == 0 || m.textarea.Value()[len(m.textarea.Value())-1] == ' '):
206			m.isCompletionsOpen = true
207			m.currentQuery = ""
208			m.completionsStartIndex = len(m.textarea.Value())
209			cmds = append(cmds, m.startCompletions)
210		case m.isCompletionsOpen && m.textarea.Cursor().X <= m.completionsStartIndex:
211			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
212		}
213		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
214			m.deleteMode = true
215			return m, nil
216		}
217		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
218			m.deleteMode = false
219			m.attachments = nil
220			return m, nil
221		}
222		rune := msg.Code
223		if m.deleteMode && unicode.IsDigit(rune) {
224			num := int(rune - '0')
225			m.deleteMode = false
226			if num < 10 && len(m.attachments) > num {
227				if num == 0 {
228					m.attachments = m.attachments[num+1:]
229				} else {
230					m.attachments = slices.Delete(m.attachments, num, num+1)
231				}
232				return m, nil
233			}
234		}
235		if key.Matches(msg, m.keyMap.OpenEditor) {
236			if m.app.CoderAgent.IsSessionBusy(m.session.ID) {
237				return m, util.ReportWarn("Agent is working, please wait...")
238			}
239			return m, m.openEditor(m.textarea.Value())
240		}
241		if key.Matches(msg, DeleteKeyMaps.Escape) {
242			m.deleteMode = false
243			return m, nil
244		}
245		if key.Matches(msg, m.keyMap.Newline) {
246			m.textarea.InsertRune('\n')
247		}
248		// Handle 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])
254			} else {
255				// Otherwise, send the message
256				return m, m.send()
257			}
258		}
259	}
260
261	m.textarea, cmd = m.textarea.Update(msg)
262	cmds = append(cmds, cmd)
263
264	if m.textarea.Focused() {
265		kp, ok := msg.(tea.KeyPressMsg)
266		if ok {
267			if kp.String() == "space" || m.textarea.Value() == "" {
268				m.isCompletionsOpen = false
269				m.currentQuery = ""
270				m.completionsStartIndex = 0
271				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
272			} else {
273				word := m.textarea.Word()
274				if strings.HasPrefix(word, "/") {
275					// XXX: wont' work if editing in the middle of the field.
276					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
277					m.currentQuery = word[1:]
278					m.isCompletionsOpen = true
279					cmds = append(cmds, util.CmdHandler(completions.FilterCompletionsMsg{
280						Query:  m.currentQuery,
281						Reopen: m.isCompletionsOpen,
282					}))
283				} else {
284					m.isCompletionsOpen = false
285					m.currentQuery = ""
286					m.completionsStartIndex = 0
287					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
288				}
289			}
290		}
291	}
292
293	return m, tea.Batch(cmds...)
294}
295
296func (m *editorCmp) Cursor() *tea.Cursor {
297	cursor := m.textarea.Cursor()
298	if cursor != nil {
299		cursor.X = cursor.X + m.x + 1
300		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
301	}
302	return cursor
303}
304
305func (m *editorCmp) View() string {
306	t := styles.CurrentTheme()
307	if len(m.attachments) == 0 {
308		content := t.S().Base.Padding(1).Render(
309			m.textarea.View(),
310		)
311		return content
312	}
313	content := t.S().Base.Padding(0, 1, 1, 1).Render(
314		lipgloss.JoinVertical(lipgloss.Top,
315			m.attachmentsContent(),
316			m.textarea.View(),
317		),
318	)
319	return content
320}
321
322func (m *editorCmp) SetSize(width, height int) tea.Cmd {
323	m.width = width
324	m.height = height
325	m.textarea.SetWidth(width - 2)   // adjust for padding
326	m.textarea.SetHeight(height - 2) // adjust for padding
327	return nil
328}
329
330func (m *editorCmp) GetSize() (int, int) {
331	return m.textarea.Width(), m.textarea.Height()
332}
333
334func (m *editorCmp) attachmentsContent() string {
335	var styledAttachments []string
336	t := styles.CurrentTheme()
337	attachmentStyles := t.S().Base.
338		MarginLeft(1).
339		Background(t.FgMuted).
340		Foreground(t.FgBase)
341	for i, attachment := range m.attachments {
342		var filename string
343		if len(attachment.FileName) > 10 {
344			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
345		} else {
346			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
347		}
348		if m.deleteMode {
349			filename = fmt.Sprintf("%d%s", i, filename)
350		}
351		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
352	}
353	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
354	return content
355}
356
357func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
358	m.x = x
359	m.y = y
360	return nil
361}
362
363func (m *editorCmp) startCompletions() tea.Msg {
364	files, _, _ := fsext.ListDirectory(".", []string{}, 0)
365	completionItems := make([]completions.Completion, 0, len(files))
366	for _, file := range files {
367		file = strings.TrimPrefix(file, "./")
368		completionItems = append(completionItems, completions.Completion{
369			Title: file,
370			Value: FileCompletionItem{
371				Path: file,
372			},
373		})
374	}
375
376	cur := m.textarea.Cursor()
377	x := cur.X + m.x // adjust for padding
378	y := cur.Y + m.y + 1
379	return completions.OpenCompletionsMsg{
380		Completions: completionItems,
381		X:           x,
382		Y:           y,
383	}
384}
385
386// Blur implements Container.
387func (c *editorCmp) Blur() tea.Cmd {
388	c.textarea.Blur()
389	return nil
390}
391
392// Focus implements Container.
393func (c *editorCmp) Focus() tea.Cmd {
394	return c.textarea.Focus()
395}
396
397// IsFocused implements Container.
398func (c *editorCmp) IsFocused() bool {
399	return c.textarea.Focused()
400}
401
402// Bindings implements Container.
403func (c *editorCmp) Bindings() []key.Binding {
404	return c.keyMap.KeyBindings()
405}
406
407// TODO: most likely we do not need to have the session here
408// we need to move some functionality to the page level
409func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
410	c.session = session
411	return nil
412}
413
414func (c *editorCmp) IsCompletionsOpen() bool {
415	return c.isCompletionsOpen
416}
417
418func New(app *app.App) Editor {
419	t := styles.CurrentTheme()
420	ta := textarea.New()
421	ta.SetStyles(t.S().TextArea)
422	ta.SetPromptFunc(4, func(info textarea.PromptInfo) string {
423		if info.LineNumber == 0 {
424			return "  > "
425		}
426		if info.Focused {
427			return t.S().Base.Foreground(t.GreenDark).Render("::: ")
428		} else {
429			return t.S().Muted.Render("::: ")
430		}
431	})
432	ta.ShowLineNumbers = false
433	ta.CharLimit = -1
434	ta.Placeholder = "Tell me more about this project..."
435	ta.SetVirtualCursor(false)
436	ta.Focus()
437
438	return &editorCmp{
439		// TODO: remove the app instance from here
440		app:      app,
441		textarea: ta,
442		keyMap:   DefaultEditorKeyMap(),
443	}
444}