editor.go

  1package editor
  2
  3import (
  4	"fmt"
  5	"math/rand"
  6	"net/http"
  7	"os"
  8	"path/filepath"
  9	"regexp"
 10	"slices"
 11	"strconv"
 12	"strings"
 13	"unicode"
 14
 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/filetracker"
 21	"github.com/charmbracelet/crush/internal/fsext"
 22	"github.com/charmbracelet/crush/internal/message"
 23	"github.com/charmbracelet/crush/internal/session"
 24	"github.com/charmbracelet/crush/internal/tui/components/chat"
 25	"github.com/charmbracelet/crush/internal/tui/components/completions"
 26	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 27	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 28	"github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
 29	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 30	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 31	"github.com/charmbracelet/crush/internal/tui/styles"
 32	"github.com/charmbracelet/crush/internal/tui/util"
 33	"github.com/charmbracelet/x/ansi"
 34	"github.com/charmbracelet/x/editor"
 35)
 36
 37var (
 38	errClipboardPlatformUnsupported = fmt.Errorf("clipboard operations are not supported on this platform")
 39	errClipboardUnknownFormat       = fmt.Errorf("unknown clipboard format")
 40)
 41
 42type Editor interface {
 43	util.Model
 44	layout.Sizeable
 45	layout.Focusable
 46	layout.Help
 47	layout.Positional
 48
 49	SetSession(session session.Session) tea.Cmd
 50	IsCompletionsOpen() bool
 51	HasAttachments() bool
 52	IsEmpty() bool
 53	Cursor() *tea.Cursor
 54}
 55
 56type FileCompletionItem struct {
 57	Path string // The file path
 58}
 59
 60type editorCmp struct {
 61	width              int
 62	height             int
 63	x, y               int
 64	app                *app.App
 65	session            session.Session
 66	textarea           textarea.Model
 67	attachments        []message.Attachment
 68	deleteMode         bool
 69	readyPlaceholder   string
 70	workingPlaceholder string
 71
 72	keyMap EditorKeyMap
 73
 74	// File path completions
 75	currentQuery          string
 76	completionsStartIndex int
 77	isCompletionsOpen     bool
 78}
 79
 80var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 81	AttachmentDeleteMode: key.NewBinding(
 82		key.WithKeys("ctrl+r"),
 83		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 84	),
 85	Escape: key.NewBinding(
 86		key.WithKeys("esc", "alt+esc"),
 87		key.WithHelp("esc", "cancel delete mode"),
 88	),
 89	DeleteAllAttachments: key.NewBinding(
 90		key.WithKeys("r"),
 91		key.WithHelp("ctrl+r+r", "delete all attachments"),
 92	),
 93}
 94
 95const maxFileResults = 25
 96
 97type OpenEditorMsg struct {
 98	Text string
 99}
100
101func (m *editorCmp) openEditor(value string) tea.Cmd {
102	tmpfile, err := os.CreateTemp("", "msg_*.md")
103	if err != nil {
104		return util.ReportError(err)
105	}
106	defer tmpfile.Close() //nolint:errcheck
107	if _, err := tmpfile.WriteString(value); err != nil {
108		return util.ReportError(err)
109	}
110	cmd, err := editor.Command(
111		"crush",
112		tmpfile.Name(),
113		editor.AtPosition(
114			m.textarea.Line()+1,
115			m.textarea.Column()+1,
116		),
117	)
118	if err != nil {
119		return util.ReportError(err)
120	}
121	return tea.ExecProcess(cmd, func(err error) tea.Msg {
122		if err != nil {
123			return util.ReportError(err)
124		}
125		content, err := os.ReadFile(tmpfile.Name())
126		if err != nil {
127			return util.ReportError(err)
128		}
129		if len(content) == 0 {
130			return util.ReportWarn("Message is empty")
131		}
132		os.Remove(tmpfile.Name())
133		return OpenEditorMsg{
134			Text: strings.TrimSpace(string(content)),
135		}
136	})
137}
138
139func (m *editorCmp) Init() tea.Cmd {
140	return nil
141}
142
143func (m *editorCmp) send() tea.Cmd {
144	value := m.textarea.Value()
145	value = strings.TrimSpace(value)
146
147	switch value {
148	case "exit", "quit":
149		m.textarea.Reset()
150		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
151	}
152
153	attachments := m.attachments
154
155	if value == "" && !message.ContainsTextAttachment(attachments) {
156		return nil
157	}
158
159	m.textarea.Reset()
160	m.attachments = nil
161	// Change the placeholder when sending a new message.
162	m.randomizePlaceholders()
163
164	return tea.Batch(
165		util.CmdHandler(chat.SendMsg{
166			Text:        value,
167			Attachments: attachments,
168		}),
169	)
170}
171
172func (m *editorCmp) repositionCompletions() tea.Msg {
173	x, y := m.completionsPosition()
174	return completions.RepositionCompletionsMsg{X: x, Y: y}
175}
176
177func (m *editorCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
178	var cmd tea.Cmd
179	var cmds []tea.Cmd
180	switch msg := msg.(type) {
181	case tea.WindowSizeMsg:
182		return m, m.repositionCompletions
183	case filepicker.FilePickedMsg:
184		m.attachments = append(m.attachments, msg.Attachment)
185		return m, nil
186	case completions.CompletionsOpenedMsg:
187		m.isCompletionsOpen = true
188	case completions.CompletionsClosedMsg:
189		m.isCompletionsOpen = false
190		m.currentQuery = ""
191		m.completionsStartIndex = 0
192	case completions.SelectCompletionMsg:
193		if !m.isCompletionsOpen {
194			return m, nil
195		}
196		if item, ok := msg.Value.(FileCompletionItem); ok {
197			word := m.textarea.Word()
198			// If the selected item is a file, insert its path into the textarea
199			value := m.textarea.Value()
200			value = value[:m.completionsStartIndex] + // Remove the current query
201				item.Path + // Insert the file path
202				value[m.completionsStartIndex+len(word):] // Append the rest of the value
203			// XXX: This will always move the cursor to the end of the textarea.
204			m.textarea.SetValue(value)
205			m.textarea.MoveToEnd()
206			if !msg.Insert {
207				m.isCompletionsOpen = false
208				m.currentQuery = ""
209				m.completionsStartIndex = 0
210			}
211			absPath, _ := filepath.Abs(item.Path)
212			// Skip attachment if file was already read and hasn't been modified.
213			lastRead := filetracker.LastReadTime(absPath)
214			if !lastRead.IsZero() {
215				if info, err := os.Stat(item.Path); err == nil && !info.ModTime().After(lastRead) {
216					return m, nil
217				}
218			}
219			content, err := os.ReadFile(item.Path)
220			if err != nil {
221				// if it fails, let the LLM handle it later.
222				return m, nil
223			}
224			filetracker.RecordRead(absPath)
225			m.attachments = append(m.attachments, message.Attachment{
226				FilePath: item.Path,
227				FileName: filepath.Base(item.Path),
228				MimeType: mimeOf(content),
229				Content:  content,
230			})
231		}
232
233	case commands.OpenExternalEditorMsg:
234		if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
235			return m, util.ReportWarn("Agent is working, please wait...")
236		}
237		return m, m.openEditor(m.textarea.Value())
238	case OpenEditorMsg:
239		m.textarea.SetValue(msg.Text)
240		m.textarea.MoveToEnd()
241	case tea.PasteMsg:
242		// If pasted text has more than 2 newlines, treat it as a file attachment.
243		if strings.Count(msg.Content, "\n") > 2 {
244			content := []byte(msg.Content)
245			if len(content) > maxAttachmentSize {
246				return m, util.ReportWarn("Paste is too big (>5mb)")
247			}
248			name := fmt.Sprintf("paste_%d.txt", m.pasteIdx())
249			mimeType := mimeOf(content)
250			attachment := message.Attachment{
251				FileName: name,
252				FilePath: name,
253				MimeType: mimeType,
254				Content:  content,
255			}
256			return m, util.CmdHandler(filepicker.FilePickedMsg{
257				Attachment: attachment,
258			})
259		}
260
261		// Try to parse as a file path.
262		content, path, err := filepathToFile(msg.Content)
263		if err != nil {
264			// Not a file path, just update the textarea normally.
265			m.textarea, cmd = m.textarea.Update(msg)
266			return m, cmd
267		}
268
269		if len(content) > maxAttachmentSize {
270			return m, util.ReportWarn("File is too big (>5mb)")
271		}
272
273		mimeType := mimeOf(content)
274		attachment := message.Attachment{
275			FilePath: path,
276			FileName: filepath.Base(path),
277			MimeType: mimeType,
278			Content:  content,
279		}
280		if !attachment.IsText() && !attachment.IsImage() {
281			return m, util.ReportWarn("Invalid file content type: " + mimeType)
282		}
283		return m, util.CmdHandler(filepicker.FilePickedMsg{
284			Attachment: attachment,
285		})
286
287	case commands.ToggleYoloModeMsg:
288		m.setEditorPrompt()
289		return m, nil
290	case tea.KeyPressMsg:
291		cur := m.textarea.Cursor()
292		curIdx := m.textarea.Width()*cur.Y + cur.X
293		switch {
294		// Open command palette when "/" is pressed on empty prompt
295		case msg.String() == "/" && m.IsEmpty():
296			return m, util.CmdHandler(dialogs.OpenDialogMsg{
297				Model: commands.NewCommandDialog(m.session.ID),
298			})
299		// Completions
300		case msg.String() == "@" && !m.isCompletionsOpen &&
301			// only show if beginning of prompt, or if previous char is a space or newline:
302			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
303			m.isCompletionsOpen = true
304			m.currentQuery = ""
305			m.completionsStartIndex = curIdx
306			cmds = append(cmds, m.startCompletions)
307		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
308			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
309		}
310		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
311			m.deleteMode = true
312			return m, nil
313		}
314		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
315			m.deleteMode = false
316			m.attachments = nil
317			return m, nil
318		}
319		rune := msg.Code
320		if m.deleteMode && unicode.IsDigit(rune) {
321			num := int(rune - '0')
322			m.deleteMode = false
323			if num < 10 && len(m.attachments) > num {
324				if num == 0 {
325					m.attachments = m.attachments[num+1:]
326				} else {
327					m.attachments = slices.Delete(m.attachments, num, num+1)
328				}
329				return m, nil
330			}
331		}
332		if key.Matches(msg, m.keyMap.OpenEditor) {
333			if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
334				return m, util.ReportWarn("Agent is working, please wait...")
335			}
336			return m, m.openEditor(m.textarea.Value())
337		}
338		if key.Matches(msg, DeleteKeyMaps.Escape) {
339			m.deleteMode = false
340			return m, nil
341		}
342		if key.Matches(msg, m.keyMap.Newline) {
343			m.textarea.InsertRune('\n')
344			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
345		}
346		// Handle image paste from clipboard
347		if key.Matches(msg, m.keyMap.PasteImage) {
348			imageData, err := readClipboard(clipboardFormatImage)
349
350			if err != nil || len(imageData) == 0 {
351				// If no image data found, try to get text data (could be file path)
352				var textData []byte
353				textData, err = readClipboard(clipboardFormatText)
354				if err != nil || len(textData) == 0 {
355					// If clipboard is empty, show a warning
356					return m, util.ReportWarn("No data found in clipboard. Note: Some terminals may not support reading image data from clipboard directly.")
357				}
358
359				// Check if the text data is a file path
360				textStr := string(textData)
361				// First, try to interpret as a file path (existing functionality)
362				path := strings.ReplaceAll(textStr, "\\ ", " ")
363				path, err = filepath.Abs(strings.TrimSpace(path))
364				if err == nil {
365					isAllowedType := false
366					for _, ext := range filepicker.AllowedTypes {
367						if strings.HasSuffix(path, ext) {
368							isAllowedType = true
369							break
370						}
371					}
372					if isAllowedType {
373						tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
374						if !tooBig {
375							content, err := os.ReadFile(path)
376							if err == nil {
377								mimeBufferSize := min(512, len(content))
378								mimeType := http.DetectContentType(content[:mimeBufferSize])
379								fileName := filepath.Base(path)
380								attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
381								return m, util.CmdHandler(filepicker.FilePickedMsg{
382									Attachment: attachment,
383								})
384							}
385						}
386					}
387				}
388
389				// If not a valid file path, show a warning
390				return m, util.ReportWarn("No image found in clipboard")
391			} else {
392				// We have image data from the clipboard
393				// Create a temporary file to store the clipboard image data
394				tempFile, err := os.CreateTemp("", "clipboard_image_crush_*")
395				if err != nil {
396					return m, util.ReportError(err)
397				}
398				defer tempFile.Close()
399
400				// Write clipboard content to the temporary file
401				_, err = tempFile.Write(imageData)
402				if err != nil {
403					return m, util.ReportError(err)
404				}
405
406				// Determine the file extension based on the image data
407				mimeBufferSize := min(512, len(imageData))
408				mimeType := http.DetectContentType(imageData[:mimeBufferSize])
409
410				// Create an attachment from the temporary file
411				fileName := filepath.Base(tempFile.Name())
412				attachment := message.Attachment{
413					FilePath: tempFile.Name(),
414					FileName: fileName,
415					MimeType: mimeType,
416					Content:  imageData,
417				}
418
419				return m, util.CmdHandler(filepicker.FilePickedMsg{
420					Attachment: attachment,
421				})
422			}
423		}
424		// Handle Enter key
425		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
426			value := m.textarea.Value()
427			if strings.HasSuffix(value, "\\") {
428				// If the last character is a backslash, remove it and add a newline.
429				m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
430			} else {
431				// Otherwise, send the message
432				return m, m.send()
433			}
434		}
435	}
436
437	m.textarea, cmd = m.textarea.Update(msg)
438	cmds = append(cmds, cmd)
439
440	if m.textarea.Focused() {
441		kp, ok := msg.(tea.KeyPressMsg)
442		if ok {
443			if kp.String() == "space" || m.textarea.Value() == "" {
444				m.isCompletionsOpen = false
445				m.currentQuery = ""
446				m.completionsStartIndex = 0
447				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
448			} else {
449				word := m.textarea.Word()
450				if strings.HasPrefix(word, "@") {
451					// XXX: wont' work if editing in the middle of the field.
452					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
453					m.currentQuery = word[1:]
454					x, y := m.completionsPosition()
455					x -= len(m.currentQuery)
456					m.isCompletionsOpen = true
457					cmds = append(cmds,
458						util.CmdHandler(completions.FilterCompletionsMsg{
459							Query:  m.currentQuery,
460							Reopen: m.isCompletionsOpen,
461							X:      x,
462							Y:      y,
463						}),
464					)
465				} else if m.isCompletionsOpen {
466					m.isCompletionsOpen = false
467					m.currentQuery = ""
468					m.completionsStartIndex = 0
469					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
470				}
471			}
472		}
473	}
474
475	return m, tea.Batch(cmds...)
476}
477
478func (m *editorCmp) setEditorPrompt() {
479	if m.app.Permissions.SkipRequests() {
480		m.textarea.SetPromptFunc(4, yoloPromptFunc)
481		return
482	}
483	m.textarea.SetPromptFunc(4, normalPromptFunc)
484}
485
486func (m *editorCmp) completionsPosition() (int, int) {
487	cur := m.textarea.Cursor()
488	if cur == nil {
489		return m.x, m.y + 1 // adjust for padding
490	}
491	x := cur.X + m.x
492	y := cur.Y + m.y + 1 // adjust for padding
493	return x, y
494}
495
496func (m *editorCmp) Cursor() *tea.Cursor {
497	cursor := m.textarea.Cursor()
498	if cursor != nil {
499		cursor.X = cursor.X + m.x + 1
500		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
501	}
502	return cursor
503}
504
505var readyPlaceholders = [...]string{
506	"Ready!",
507	"Ready...",
508	"Ready?",
509	"Ready for instructions",
510}
511
512var workingPlaceholders = [...]string{
513	"Working!",
514	"Working...",
515	"Brrrrr...",
516	"Prrrrrrrr...",
517	"Processing...",
518	"Thinking...",
519}
520
521func (m *editorCmp) randomizePlaceholders() {
522	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
523	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
524}
525
526func (m *editorCmp) View() string {
527	t := styles.CurrentTheme()
528	// Update placeholder
529	if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
530		m.textarea.Placeholder = m.workingPlaceholder
531	} else {
532		m.textarea.Placeholder = m.readyPlaceholder
533	}
534	if m.app.Permissions.SkipRequests() {
535		m.textarea.Placeholder = "Yolo mode!"
536	}
537	if len(m.attachments) == 0 {
538		return t.S().Base.Padding(1).Render(
539			m.textarea.View(),
540		)
541	}
542	return t.S().Base.Padding(0, 1, 1, 1).Render(
543		lipgloss.JoinVertical(
544			lipgloss.Top,
545			m.attachmentsContent(),
546			m.textarea.View(),
547		),
548	)
549}
550
551func (m *editorCmp) SetSize(width, height int) tea.Cmd {
552	m.width = width
553	m.height = height
554	m.textarea.SetWidth(width - 2)   // adjust for padding
555	m.textarea.SetHeight(height - 2) // adjust for padding
556	return nil
557}
558
559func (m *editorCmp) GetSize() (int, int) {
560	return m.textarea.Width(), m.textarea.Height()
561}
562
563func (m *editorCmp) attachmentsContent() string {
564	var styledAttachments []string
565	t := styles.CurrentTheme()
566	attachmentStyle := t.S().Base.
567		Padding(0, 1).
568		MarginRight(1).
569		Background(t.FgMuted).
570		Foreground(t.FgBase).
571		Render
572	iconStyle := t.S().Base.
573		Foreground(t.BgSubtle).
574		Background(t.Green).
575		Padding(0, 1).
576		Bold(true).
577		Render
578	rmStyle := t.S().Base.
579		Padding(0, 1).
580		Bold(true).
581		Background(t.Red).
582		Foreground(t.FgBase).
583		Render
584	for i, attachment := range m.attachments {
585		filename := ansi.Truncate(filepath.Base(attachment.FileName), 10, "...")
586		icon := styles.ImageIcon
587		if attachment.IsText() {
588			icon = styles.TextIcon
589		}
590		if m.deleteMode {
591			styledAttachments = append(
592				styledAttachments,
593				rmStyle(fmt.Sprintf("%d", i)),
594				attachmentStyle(filename),
595			)
596			continue
597		}
598		styledAttachments = append(
599			styledAttachments,
600			iconStyle(icon),
601			attachmentStyle(filename),
602		)
603	}
604	return lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
605}
606
607func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
608	m.x = x
609	m.y = y
610	return nil
611}
612
613func (m *editorCmp) startCompletions() tea.Msg {
614	ls := m.app.Config().Options.TUI.Completions
615	depth, limit := ls.Limits()
616	files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
617	slices.Sort(files)
618	completionItems := make([]completions.Completion, 0, len(files))
619	for _, file := range files {
620		file = strings.TrimPrefix(file, "./")
621		completionItems = append(completionItems, completions.Completion{
622			Title: file,
623			Value: FileCompletionItem{
624				Path: file,
625			},
626		})
627	}
628
629	x, y := m.completionsPosition()
630	return completions.OpenCompletionsMsg{
631		Completions: completionItems,
632		X:           x,
633		Y:           y,
634		MaxResults:  maxFileResults,
635	}
636}
637
638// Blur implements Container.
639func (c *editorCmp) Blur() tea.Cmd {
640	c.textarea.Blur()
641	return nil
642}
643
644// Focus implements Container.
645func (c *editorCmp) Focus() tea.Cmd {
646	return c.textarea.Focus()
647}
648
649// IsFocused implements Container.
650func (c *editorCmp) IsFocused() bool {
651	return c.textarea.Focused()
652}
653
654// Bindings implements Container.
655func (c *editorCmp) Bindings() []key.Binding {
656	return c.keyMap.KeyBindings()
657}
658
659// TODO: most likely we do not need to have the session here
660// we need to move some functionality to the page level
661func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
662	c.session = session
663	return nil
664}
665
666func (c *editorCmp) IsCompletionsOpen() bool {
667	return c.isCompletionsOpen
668}
669
670func (c *editorCmp) HasAttachments() bool {
671	return len(c.attachments) > 0
672}
673
674func (c *editorCmp) IsEmpty() bool {
675	return strings.TrimSpace(c.textarea.Value()) == ""
676}
677
678func normalPromptFunc(info textarea.PromptInfo) string {
679	t := styles.CurrentTheme()
680	if info.LineNumber == 0 {
681		if info.Focused {
682			return "  > "
683		}
684		return "::: "
685	}
686	if info.Focused {
687		return t.S().Base.Foreground(t.GreenDark).Render("::: ")
688	}
689	return t.S().Muted.Render("::: ")
690}
691
692func yoloPromptFunc(info textarea.PromptInfo) string {
693	t := styles.CurrentTheme()
694	if info.LineNumber == 0 {
695		if info.Focused {
696			return fmt.Sprintf("%s ", t.YoloIconFocused)
697		} else {
698			return fmt.Sprintf("%s ", t.YoloIconBlurred)
699		}
700	}
701	if info.Focused {
702		return fmt.Sprintf("%s ", t.YoloDotsFocused)
703	}
704	return fmt.Sprintf("%s ", t.YoloDotsBlurred)
705}
706
707func New(app *app.App) Editor {
708	t := styles.CurrentTheme()
709	ta := textarea.New()
710	ta.SetStyles(t.S().TextArea)
711	ta.ShowLineNumbers = false
712	ta.CharLimit = -1
713	ta.SetVirtualCursor(false)
714	ta.Focus()
715	e := &editorCmp{
716		// TODO: remove the app instance from here
717		app:      app,
718		textarea: ta,
719		keyMap:   DefaultEditorKeyMap(),
720	}
721	e.setEditorPrompt()
722
723	e.randomizePlaceholders()
724	e.textarea.Placeholder = e.readyPlaceholder
725
726	return e
727}
728
729var maxAttachmentSize = 5 * 1024 * 1024 // 5MB
730
731var pasteRE = regexp.MustCompile(`paste_(\d+).txt`)
732
733func (m *editorCmp) pasteIdx() int {
734	result := 0
735	for _, at := range m.attachments {
736		found := pasteRE.FindStringSubmatch(at.FileName)
737		if len(found) == 0 {
738			continue
739		}
740		idx, err := strconv.Atoi(found[1])
741		if err == nil {
742			result = max(result, idx)
743		}
744	}
745	return result + 1
746}
747
748func filepathToFile(name string) ([]byte, string, error) {
749	path, err := filepath.Abs(strings.TrimSpace(strings.ReplaceAll(name, "\\", "")))
750	if err != nil {
751		return nil, "", err
752	}
753	content, err := os.ReadFile(path)
754	if err != nil {
755		return nil, "", err
756	}
757	return content, path, nil
758}
759
760func mimeOf(content []byte) string {
761	mimeBufferSize := min(512, len(content))
762	return http.DetectContentType(content[:mimeBufferSize])
763}