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