15 "charm.land/bubbles/v2/key"
16 "charm.land/bubbles/v2/textarea"
17 tea "charm.land/bubbletea/v2"
18 "charm.land/lipgloss/v2"
19 "github.com/charmbracelet/crush/internal/app"
20 "github.com/charmbracelet/crush/internal/fsext"
21 "github.com/charmbracelet/crush/internal/message"
22 "github.com/charmbracelet/crush/internal/session"
23 "github.com/charmbracelet/crush/internal/tui/components/chat"
24 "github.com/charmbracelet/crush/internal/tui/components/completions"
25 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
26 "github.com/charmbracelet/crush/internal/tui/components/dialogs"
27 "github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
28 "github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
29 "github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
30 "github.com/charmbracelet/crush/internal/tui/styles"
31 "github.com/charmbracelet/crush/internal/tui/util"
34type Editor interface {
41 SetSession(session session.Session) tea.Cmd
42 IsCompletionsOpen() bool
47type FileCompletionItem struct {
48 Path string // The file path
51type editorCmp struct {
56 session session.Session
57 textarea textarea.Model
58 attachments []message.Attachment
60 readyPlaceholder string
61 workingPlaceholder string
65 // File path completions
67 completionsStartIndex int
68 isCompletionsOpen bool
71var DeleteKeyMaps = DeleteAttachmentKeyMaps{
72 AttachmentDeleteMode: key.NewBinding(
73 key.WithKeys("ctrl+r"),
74 key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
76 Escape: key.NewBinding(
77 key.WithKeys("esc", "alt+esc"),
78 key.WithHelp("esc", "cancel delete mode"),
80 DeleteAllAttachments: key.NewBinding(
82 key.WithHelp("ctrl+r+r", "delete all attachments"),
91type OpenEditorMsg struct {
95func (m *editorCmp) openEditor(value string) tea.Cmd {
96 editor := os.Getenv("EDITOR")
98 // Use platform-appropriate default editor
99 if runtime.GOOS == "windows" {
106 tmpfile, err := os.CreateTemp("", "msg_*.md")
108 return util.ReportError(err)
110 defer tmpfile.Close() //nolint:errcheck
111 if _, err := tmpfile.WriteString(value); err != nil {
112 return util.ReportError(err)
114 cmdStr := editor + " " + tmpfile.Name()
115 return util.ExecShell(context.TODO(), cmdStr, func(err error) tea.Msg {
117 return util.ReportError(err)
119 content, err := os.ReadFile(tmpfile.Name())
121 return util.ReportError(err)
123 if len(content) == 0 {
124 return util.ReportWarn("Message is empty")
126 os.Remove(tmpfile.Name())
127 return OpenEditorMsg{
128 Text: strings.TrimSpace(string(content)),
133func (m *editorCmp) Init() tea.Cmd {
137func (m *editorCmp) send() tea.Cmd {
138 value := m.textarea.Value()
139 value = strings.TrimSpace(value)
144 return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
148 attachments := m.attachments
155 // Change the placeholder when sending a new message.
156 m.randomizePlaceholders()
159 util.CmdHandler(chat.SendMsg{
161 Attachments: attachments,
166func (m *editorCmp) repositionCompletions() tea.Msg {
167 x, y := m.completionsPosition()
168 return completions.RepositionCompletionsMsg{X: x, Y: y}
171func (m *editorCmp) Update(msg tea.Msg) (util.Model, 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))
181 m.attachments = append(m.attachments, msg.Attachment)
183 case completions.CompletionsOpenedMsg:
184 m.isCompletionsOpen = true
185 case completions.CompletionsClosedMsg:
186 m.isCompletionsOpen = false
188 m.completionsStartIndex = 0
189 case completions.SelectCompletionMsg:
190 if !m.isCompletionsOpen {
193 if item, ok := msg.Value.(FileCompletionItem); ok {
194 word := m.textarea.Word()
195 // If the selected item is a file, insert its path into the textarea
196 value := m.textarea.Value()
197 value = value[:m.completionsStartIndex] + // Remove the current query
198 item.Path + // Insert the file path
199 value[m.completionsStartIndex+len(word):] // Append the rest of the value
200 // XXX: This will always move the cursor to the end of the textarea.
201 m.textarea.SetValue(value)
202 m.textarea.MoveToEnd()
204 m.isCompletionsOpen = false
206 m.completionsStartIndex = 0
210 case commands.OpenExternalEditorMsg:
211 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
212 return m, util.ReportWarn("Agent is working, please wait...")
214 return m, m.openEditor(m.textarea.Value())
216 m.textarea.SetValue(msg.Text)
217 m.textarea.MoveToEnd()
219 path := strings.ReplaceAll(msg.Content, "\\ ", " ")
220 // try to get an image
221 path, err := filepath.Abs(strings.TrimSpace(path))
223 m.textarea, cmd = m.textarea.Update(msg)
226 isAllowedType := false
227 for _, ext := range filepicker.AllowedTypes {
228 if strings.HasSuffix(path, ext) {
234 m.textarea, cmd = m.textarea.Update(msg)
237 tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
239 m.textarea, cmd = m.textarea.Update(msg)
243 content, err := os.ReadFile(path)
245 m.textarea, cmd = m.textarea.Update(msg)
248 mimeBufferSize := min(512, len(content))
249 mimeType := http.DetectContentType(content[:mimeBufferSize])
250 fileName := filepath.Base(path)
251 attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
252 return m, util.CmdHandler(filepicker.FilePickedMsg{
253 Attachment: attachment,
256 case commands.ToggleYoloModeMsg:
259 case tea.KeyPressMsg:
260 cur := m.textarea.Cursor()
261 curIdx := m.textarea.Width()*cur.Y + cur.X
263 // Open command palette when "/" is pressed on empty prompt
264 case msg.String() == "/" && len(strings.TrimSpace(m.textarea.Value())) == 0:
265 return m, util.CmdHandler(dialogs.OpenDialogMsg{
266 Model: commands.NewCommandDialog(m.session.ID),
269 case msg.String() == "@" && !m.isCompletionsOpen &&
270 // only show if beginning of prompt, or if previous char is a space or newline:
271 (len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
272 m.isCompletionsOpen = true
274 m.completionsStartIndex = curIdx
275 cmds = append(cmds, m.startCompletions)
276 case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
277 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
279 if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
283 if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
289 if m.deleteMode && unicode.IsDigit(rune) {
290 num := int(rune - '0')
292 if num < 10 && len(m.attachments) > num {
294 m.attachments = m.attachments[num+1:]
296 m.attachments = slices.Delete(m.attachments, num, num+1)
301 if key.Matches(msg, m.keyMap.OpenEditor) {
302 if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
303 return m, util.ReportWarn("Agent is working, please wait...")
305 return m, m.openEditor(m.textarea.Value())
307 if key.Matches(msg, DeleteKeyMaps.Escape) {
311 if key.Matches(msg, m.keyMap.Newline) {
312 m.textarea.InsertRune('\n')
313 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
316 if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
317 value := m.textarea.Value()
318 if strings.HasSuffix(value, "\\") {
319 // If the last character is a backslash, remove it and add a newline.
320 m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
322 // Otherwise, send the message
328 m.textarea, cmd = m.textarea.Update(msg)
329 cmds = append(cmds, cmd)
331 if m.textarea.Focused() {
332 kp, ok := msg.(tea.KeyPressMsg)
334 if kp.String() == "space" || m.textarea.Value() == "" {
335 m.isCompletionsOpen = false
337 m.completionsStartIndex = 0
338 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
340 word := m.textarea.Word()
341 if strings.HasPrefix(word, "@") {
342 // XXX: wont' work if editing in the middle of the field.
343 m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
344 m.currentQuery = word[1:]
345 x, y := m.completionsPosition()
346 x -= len(m.currentQuery)
347 m.isCompletionsOpen = true
349 util.CmdHandler(completions.FilterCompletionsMsg{
350 Query: m.currentQuery,
351 Reopen: m.isCompletionsOpen,
356 } else if m.isCompletionsOpen {
357 m.isCompletionsOpen = false
359 m.completionsStartIndex = 0
360 cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
366 return m, tea.Batch(cmds...)
369func (m *editorCmp) setEditorPrompt() {
370 if m.app.Permissions.SkipRequests() {
371 m.textarea.SetPromptFunc(4, yoloPromptFunc)
374 m.textarea.SetPromptFunc(4, normalPromptFunc)
377func (m *editorCmp) completionsPosition() (int, int) {
378 cur := m.textarea.Cursor()
380 return m.x, m.y + 1 // adjust for padding
383 y := cur.Y + m.y + 1 // adjust for padding
387func (m *editorCmp) Cursor() *tea.Cursor {
388 cursor := m.textarea.Cursor()
390 cursor.X = cursor.X + m.x + 1
391 cursor.Y = cursor.Y + m.y + 1 // adjust for padding
396var readyPlaceholders = [...]string{
400 "Ready for instructions",
403var workingPlaceholders = [...]string{
412func (m *editorCmp) randomizePlaceholders() {
413 m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
414 m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
417func (m *editorCmp) View() string {
418 t := styles.CurrentTheme()
419 // Update placeholder
420 if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
421 m.textarea.Placeholder = m.workingPlaceholder
423 m.textarea.Placeholder = m.readyPlaceholder
425 if m.app.Permissions.SkipRequests() {
426 m.textarea.Placeholder = "Yolo mode!"
428 if len(m.attachments) == 0 {
429 content := t.S().Base.Padding(1).Render(
434 content := t.S().Base.Padding(0, 1, 1, 1).Render(
435 lipgloss.JoinVertical(lipgloss.Top,
436 m.attachmentsContent(),
443func (m *editorCmp) SetSize(width, height int) tea.Cmd {
446 m.textarea.SetWidth(width - 2) // adjust for padding
447 m.textarea.SetHeight(height - 2) // adjust for padding
451func (m *editorCmp) GetSize() (int, int) {
452 return m.textarea.Width(), m.textarea.Height()
455func (m *editorCmp) attachmentsContent() string {
456 var styledAttachments []string
457 t := styles.CurrentTheme()
458 attachmentStyles := t.S().Base.
460 Background(t.FgMuted).
462 for i, attachment := range m.attachments {
464 if len(attachment.FileName) > 10 {
465 filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
467 filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
470 filename = fmt.Sprintf("%d%s", i, filename)
472 styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
474 content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
478func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
484func (m *editorCmp) startCompletions() tea.Msg {
485 ls := m.app.Config().Options.TUI.Completions
486 depth, limit := ls.Limits()
487 files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
489 completionItems := make([]completions.Completion, 0, len(files))
490 for _, file := range files {
491 file = strings.TrimPrefix(file, "./")
492 completionItems = append(completionItems, completions.Completion{
494 Value: FileCompletionItem{
500 x, y := m.completionsPosition()
501 return completions.OpenCompletionsMsg{
502 Completions: completionItems,
505 MaxResults: maxFileResults,
509// Blur implements Container.
510func (c *editorCmp) Blur() tea.Cmd {
515// Focus implements Container.
516func (c *editorCmp) Focus() tea.Cmd {
517 return c.textarea.Focus()
520// IsFocused implements Container.
521func (c *editorCmp) IsFocused() bool {
522 return c.textarea.Focused()
525// Bindings implements Container.
526func (c *editorCmp) Bindings() []key.Binding {
527 return c.keyMap.KeyBindings()
530// TODO: most likely we do not need to have the session here
531// we need to move some functionality to the page level
532func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
537func (c *editorCmp) IsCompletionsOpen() bool {
538 return c.isCompletionsOpen
541func (c *editorCmp) HasAttachments() bool {
542 return len(c.attachments) > 0
545func normalPromptFunc(info textarea.PromptInfo) string {
546 t := styles.CurrentTheme()
547 if info.LineNumber == 0 {
551 return t.S().Base.Foreground(t.GreenDark).Render("::: ")
553 return t.S().Muted.Render("::: ")
556func yoloPromptFunc(info textarea.PromptInfo) string {
557 t := styles.CurrentTheme()
558 if info.LineNumber == 0 {
560 return fmt.Sprintf("%s ", t.YoloIconFocused)
562 return fmt.Sprintf("%s ", t.YoloIconBlurred)
566 return fmt.Sprintf("%s ", t.YoloDotsFocused)
568 return fmt.Sprintf("%s ", t.YoloDotsBlurred)
571func New(app *app.App) Editor {
572 t := styles.CurrentTheme()
574 ta.SetStyles(t.S().TextArea)
575 ta.ShowLineNumbers = false
577 ta.SetVirtualCursor(false)
580 // TODO: remove the app instance from here
583 keyMap: DefaultEditorKeyMap(),
587 e.randomizePlaceholders()
588 e.textarea.Placeholder = e.readyPlaceholder
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list