html.go

  1package view
  2
  3import (
  4	"encoding/base64"
  5	"fmt"
  6	"io"
  7	"mime/quotedprintable"
  8	"net/http"
  9	"os"
 10	"regexp"
 11	"strings"
 12	"sync"
 13	"time"
 14
 15	"charm.land/lipgloss/v2"
 16	"github.com/floatpane/matcha/clib"
 17	"github.com/floatpane/matcha/theme"
 18)
 19
 20func linkStyle() lipgloss.Style {
 21	return lipgloss.NewStyle().Foreground(theme.ActiveTheme.Link)
 22}
 23
 24// getTerminalCellSize returns the height of a terminal cell in pixels.
 25// It queries the terminal using TIOCGWINSZ to get both character and pixel dimensions.
 26// Falls back to a default of 18 pixels if the query fails.
 27func getTerminalCellSize() int {
 28	const defaultCellHeight = 18
 29
 30	// Try stdout, stdin, stderr, then /dev/tty as last resort
 31	fds := []int{int(os.Stdout.Fd()), int(os.Stdin.Fd()), int(os.Stderr.Fd())}
 32
 33	for _, fd := range fds {
 34		if cellHeight := getCellHeightFromFd(fd); cellHeight > 0 {
 35			return cellHeight
 36		}
 37	}
 38
 39	// Try /dev/tty directly - this works even when stdio is redirected (e.g., in Bubble Tea)
 40	if tty, err := os.Open("/dev/tty"); err == nil {
 41		defer tty.Close()
 42		if cellHeight := getCellHeightFromFd(int(tty.Fd())); cellHeight > 0 {
 43			return cellHeight
 44		}
 45	}
 46
 47	debugImageProtocol("using default cell height: %d pixels", defaultCellHeight)
 48	return defaultCellHeight
 49}
 50
 51// hyperlinkSupported checks if the terminal supports OSC 8 hyperlinks.
 52func hyperlinkSupported() bool {
 53	term := strings.ToLower(os.Getenv("TERM"))
 54
 55	// Terminals known to support OSC 8 hyperlinks
 56	supportedTerms := []string{
 57		"kitty",
 58		"ghostty",
 59		"wezterm",
 60		"alacritty",
 61		"foot",
 62		"tmux",
 63		"screen",
 64	}
 65
 66	for _, supported := range supportedTerms {
 67		if strings.Contains(term, supported) {
 68			return true
 69		}
 70	}
 71
 72	// Check for specific terminal programs
 73	termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
 74	supportedPrograms := []string{
 75		"iterm.app",
 76		"hyper",
 77		"vscode",
 78		"ghostty",
 79		"wezterm",
 80	}
 81
 82	for _, supported := range supportedPrograms {
 83		if strings.Contains(termProgram, supported) {
 84			return true
 85		}
 86	}
 87
 88	// Check for VTE-based terminals (GNOME Terminal, etc.)
 89	if os.Getenv("VTE_VERSION") != "" {
 90		return true
 91	}
 92
 93	// Check for specific environment variables that indicate hyperlink support
 94	if os.Getenv("KITTY_WINDOW_ID") != "" ||
 95		os.Getenv("GHOSTTY_RESOURCES_DIR") != "" ||
 96		os.Getenv("WEZTERM_EXECUTABLE") != "" ||
 97		os.Getenv("WT_SESSION") != "" {
 98		return true
 99	}
100
101	return false
102}
103
104// hyperlink formats a string as either a terminal-clickable hyperlink or plain text with URL.
105func hyperlink(url, text string) string {
106	if text == "" {
107		text = url
108	}
109
110	supported := hyperlinkSupported()
111
112	if supported {
113		// Use OSC 8 hyperlink sequence for supported terminals
114		return fmt.Sprintf("\x1b]8;;%s\x07%s\x1b]8;;\x07", url, linkStyle().Render(text))
115	} else {
116		// Fallback to plain text format for unsupported terminals
117		if text == url {
118			return fmt.Sprintf("<%s>", linkStyle().Render(url))
119		}
120		return fmt.Sprintf("%s <%s>", linkStyle().Render(text), linkStyle().Render(url))
121	}
122}
123
124func decodeQuotedPrintable(s string) (string, error) {
125	reader := quotedprintable.NewReader(strings.NewReader(s))
126	body, err := io.ReadAll(reader)
127	if err != nil {
128		return "", err
129	}
130	return string(body), nil
131}
132
133// markdownToHTML converts a Markdown string to an HTML string using md4c (C).
134func markdownToHTML(md []byte) []byte {
135	return clib.MarkdownToHTML(md)
136}
137
138func kittySupported() bool {
139	term := strings.ToLower(os.Getenv("TERM"))
140	if strings.Contains(term, "kitty") {
141		return true
142	}
143	return os.Getenv("KITTY_WINDOW_ID") != ""
144}
145
146func ghosttySupported() bool {
147	// Check for TERM containing ghostty
148	term := strings.ToLower(os.Getenv("TERM"))
149	if strings.Contains(term, "ghostty") {
150		return true
151	}
152
153	// Check for Ghostty-specific environment variables
154	if os.Getenv("TERM_PROGRAM") == "ghostty" {
155		return true
156	}
157
158	// Check for GHOSTTY_RESOURCES_DIR which Ghostty sets
159	return os.Getenv("GHOSTTY_RESOURCES_DIR") != ""
160}
161
162func iterm2Supported() bool {
163	termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
164	if termProgram == "iterm.app" {
165		return true
166	}
167
168	// Check for iTerm2-specific environment variables
169	if os.Getenv("ITERM_SESSION_ID") != "" || os.Getenv("ITERM_PROFILE") != "" {
170		return true
171	}
172
173	return false
174}
175
176func weztermSupported() bool {
177	// Check for WezTerm-specific environment variables
178	if os.Getenv("WEZTERM_EXECUTABLE") != "" || os.Getenv("WEZTERM_CONFIG_FILE") != "" {
179		return true
180	}
181
182	termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
183	if termProgram == "wezterm" {
184		return true
185	}
186
187	term := strings.ToLower(os.Getenv("TERM"))
188	if strings.Contains(term, "wezterm") {
189		return true
190	}
191
192	return false
193}
194
195func waystSupported() bool {
196	term := strings.ToLower(os.Getenv("TERM"))
197	if strings.Contains(term, "wayst") {
198		return true
199	}
200
201	termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
202	if termProgram == "wayst" {
203		return true
204	}
205
206	return false
207}
208
209func warpSupported() bool {
210	termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
211	if termProgram == "warp" {
212		return true
213	}
214
215	// Check for Warp-specific environment variables
216	if os.Getenv("WARP_IS_LOCAL_SHELL_SESSION") != "" || os.Getenv("WARP_COMBINED_PROMPT_COMMAND_FINISHED") != "" {
217		return true
218	}
219
220	return false
221}
222
223func konsoleSupported() bool {
224	// Check for Konsole-specific environment variables
225	if os.Getenv("KONSOLE_DBUS_SESSION") != "" || os.Getenv("KONSOLE_VERSION") != "" {
226		return true
227	}
228
229	termProgram := strings.ToLower(os.Getenv("TERM_PROGRAM"))
230	if termProgram == "konsole" {
231		return true
232	}
233
234	return false
235}
236
237// ImageProtocolSupported checks if any supported image protocol terminal is detected.
238func ImageProtocolSupported() bool {
239	return imageProtocolSupported()
240}
241
242// imageProtocolSupported checks if any supported image protocol terminal is detected.
243func imageProtocolSupported() bool {
244	return kittySupported() || ghosttySupported() || iterm2Supported() ||
245		weztermSupported() || waystSupported() || warpSupported() || konsoleSupported()
246}
247
248func debugImageProtocol(format string, args ...interface{}) {
249	if os.Getenv("DEBUG_IMAGE_PROTOCOL") == "" && os.Getenv("DEBUG_KITTY_IMAGES") == "" {
250		return
251	}
252	msg := fmt.Sprintf("[img-protocol] "+format+"\n", args...)
253	fmt.Print(msg)
254	if path := os.Getenv("DEBUG_IMAGE_PROTOCOL_LOG"); path != "" {
255		if f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
256			_, _ = f.WriteString(msg)
257			_ = f.Close()
258		}
259	} else if path := os.Getenv("DEBUG_KITTY_LOG"); path != "" {
260		if f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644); err == nil {
261			_, _ = f.WriteString(msg)
262			_ = f.Close()
263		}
264	}
265}
266
267// remoteImageCache caches fetched remote images (URL -> base64 PNG string).
268var remoteImageCache sync.Map
269
270// nextImageID is an auto-incrementing counter for Kitty image IDs.
271var nextImageID uint32 = 1000
272
273// allocImageID returns a unique Kitty image ID.
274func allocImageID() uint32 {
275	id := nextImageID
276	nextImageID++
277	return id
278}
279
280func fetchRemoteBase64(url string) string {
281	if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
282		return ""
283	}
284
285	// Check cache first
286	if cached, ok := remoteImageCache.Load(url); ok {
287		debugImageProtocol("remote cache hit url=%s", url)
288		return cached.(string)
289	}
290
291	client := &http.Client{Timeout: 5 * time.Second}
292	resp, err := client.Get(url)
293	if err != nil {
294		debugImageProtocol("remote fetch failed url=%s err=%v", url, err)
295		return ""
296	}
297	defer resp.Body.Close()
298	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
299		debugImageProtocol("remote fetch non-200 url=%s status=%d", url, resp.StatusCode)
300		return ""
301	}
302	data, err := io.ReadAll(resp.Body)
303	if err != nil {
304		debugImageProtocol("remote fetch read error url=%s err=%v", url, err)
305		return ""
306	}
307
308	result, ok := clib.DecodeToPNG(data)
309	if !ok {
310		debugImageProtocol("remote decode failed url=%s", url)
311		return ""
312	}
313
314	encoded := base64.StdEncoding.EncodeToString(result.PNGData)
315	debugImageProtocol("remote fetch ok url=%s len=%d", url, len(encoded))
316	remoteImageCache.Store(url, encoded)
317	return encoded
318}
319
320func dataURIBase64(uri string) string {
321	if !strings.HasPrefix(uri, "data:") {
322		return ""
323	}
324	comma := strings.Index(uri, ",")
325	if comma == -1 || comma+1 >= len(uri) {
326		return ""
327	}
328	return uri[comma+1:]
329}
330
331// imageRowPlaceholderPrefix is used to mark where image row spacing should be inserted.
332// This prevents the newline-collapsing regex from removing intentional spacing.
333// Uses brackets instead of angle brackets to avoid being interpreted as HTML tags.
334const imageRowPlaceholderPrefix = "[[MATCHA_IMG_ROWS:"
335const imageRowPlaceholderSuffix = "]]"
336
337func kittyInlineImage(payload string) string {
338	if payload == "" {
339		return ""
340	}
341
342	const chunkSize = 4096
343	var b strings.Builder
344
345	// Calculate how many terminal rows the image occupies to advance text after it.
346	rows := 1
347	if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
348		if _, h, ok := clib.ImageDimensions(data); ok {
349			cellHeight := getTerminalCellSize()
350			rows = (h + cellHeight - 1) / cellHeight
351			if rows < 1 {
352				rows = 1
353			}
354			debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
355		}
356	}
357
358	for offset := 0; offset < len(payload); offset += chunkSize {
359		end := offset + chunkSize
360		if end > len(payload) {
361			end = len(payload)
362		}
363		more := "0"
364		if end < len(payload) {
365			more = "1"
366		}
367
368		chunk := payload[offset:end]
369		if offset == 0 {
370			// C=1 means cursor does NOT move after image render (stays at top-left of image position)
371			// This is needed for proper TUI rendering, but we must add newlines to push text below
372			b.WriteString(fmt.Sprintf("\x1b_Gf=100,a=T,q=2,C=1,m=%s;%s\x1b\\", more, chunk))
373		} else {
374			b.WriteString(fmt.Sprintf("\x1b_Gm=%s;%s\x1b\\", more, chunk))
375		}
376	}
377
378	// Add newlines to push cursor below the image.
379	// Use a placeholder that won't be collapsed by the newline regex.
380	b.WriteString(fmt.Sprintf("\n%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix))
381
382	return b.String()
383}
384
385// iterm2InlineImage renders an image using iTerm2's image protocol
386func iterm2InlineImage(payload string) string {
387	if payload == "" {
388		return ""
389	}
390
391	// Calculate rows for cursor positioning
392	rows := 1
393	if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
394		if _, h, ok := clib.ImageDimensions(data); ok {
395			cellHeight := getTerminalCellSize()
396			rows = (h + cellHeight - 1) / cellHeight
397			if rows < 1 {
398				rows = 1
399			}
400			debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
401		}
402	}
403
404	// iTerm2 image protocol: ESC]1337;File=inline=1:<base64_data>BEL
405	result := fmt.Sprintf("\x1b]1337;File=inline=1:%s\x07\n", payload)
406
407	// Add placeholder for row spacing
408	result += fmt.Sprintf("%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix)
409
410	return result
411}
412
413// renderInlineImage renders an image using the appropriate protocol for the detected terminal
414func renderInlineImage(payload string) string {
415	if payload == "" {
416		return ""
417	}
418
419	if kittySupported() || ghosttySupported() || weztermSupported() || waystSupported() || konsoleSupported() {
420		// These terminals use the Kitty graphics protocol
421		return kittyInlineImage(payload)
422	} else if iterm2Supported() || warpSupported() {
423		// iTerm2 and Warp use the iTerm2 image protocol
424		return iterm2InlineImage(payload)
425	}
426
427	return ""
428}
429
430// imageRows calculates the number of terminal rows an image occupies.
431func imageRows(payload string) int {
432	rows := 1
433	if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
434		if _, h, ok := clib.ImageDimensions(data); ok {
435			cellHeight := getTerminalCellSize()
436			rows = (h + cellHeight - 1) / cellHeight
437			if rows < 1 {
438				rows = 1
439			}
440			debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
441		}
442	}
443	return rows
444}
445
446// kittyUploadImage uploads image data to the terminal with a unique ID using
447// the Kitty graphics protocol transmit action (a=t). The image is stored in
448// the terminal's memory and can be displayed later by ID without re-sending data.
449func kittyUploadImage(payload string, id uint32) {
450	if payload == "" {
451		return
452	}
453
454	const chunkSize = 4096
455	for offset := 0; offset < len(payload); offset += chunkSize {
456		end := offset + chunkSize
457		if end > len(payload) {
458			end = len(payload)
459		}
460		more := "0"
461		if end < len(payload) {
462			more = "1"
463		}
464
465		chunk := payload[offset:end]
466		if offset == 0 {
467			// a=t: transmit (upload) only, don't display yet
468			// i=ID: assign this image ID
469			fmt.Fprintf(os.Stdout, "\x1b_Gf=100,a=t,i=%d,q=2,m=%s;%s\x1b\\", id, more, chunk)
470		} else {
471			fmt.Fprintf(os.Stdout, "\x1b_Gm=%s;%s\x1b\\", more, chunk)
472		}
473	}
474	os.Stdout.Sync()
475}
476
477// kittyDisplayImage displays a previously uploaded image by its ID at the
478// current cursor position. This is very fast since no image data is transmitted.
479func kittyDisplayImage(id uint32) string {
480	// a=p: put (display) an already-uploaded image by ID
481	// C=1: cursor does not move
482	return fmt.Sprintf("\x1b_Ga=p,i=%d,q=2,C=1\x1b\\", id)
483}
484
485// iterm2ImageEscapeOnly returns only the iTerm2 image protocol escape sequence
486// without any row placeholders. Used for out-of-band rendering to stdout.
487func iterm2ImageEscapeOnly(payload string) string {
488	if payload == "" {
489		return ""
490	}
491	return fmt.Sprintf("\x1b]1337;File=inline=1:%s\x07", payload)
492}
493
494// RenderImageToStdout writes an image directly to stdout at the given screen
495// row using cursor positioning. This bypasses bubbletea's cell-based renderer
496// which cannot handle graphics protocol escape sequences.
497//
498// For Kitty-protocol terminals, images are uploaded once and then displayed by
499// ID on subsequent calls, making scroll rendering nearly instant.
500func RenderImageToStdout(placement *ImagePlacement, screenRow int) {
501	if placement.Base64 == "" {
502		return
503	}
504
505	useKitty := kittySupported() || ghosttySupported() || weztermSupported() || waystSupported() || konsoleSupported()
506	useIterm2 := iterm2Supported() || warpSupported()
507
508	if useKitty {
509		// Upload once, display by ID on subsequent renders
510		if !placement.Uploaded {
511			placement.ID = allocImageID()
512			kittyUploadImage(placement.Base64, placement.ID)
513			placement.Uploaded = true
514		}
515		seq := kittyDisplayImage(placement.ID)
516		fmt.Fprintf(os.Stdout, "\x1b[s\x1b[%d;1H%s\x1b[u", screenRow+1, seq)
517		os.Stdout.Sync()
518	} else if useIterm2 {
519		seq := iterm2ImageEscapeOnly(placement.Base64)
520		fmt.Fprintf(os.Stdout, "\x1b[s\x1b[%d;1H%s\x1b[u", screenRow+1, seq)
521		os.Stdout.Sync()
522	}
523}
524
525// expandImageRowPlaceholders replaces image row placeholders with actual newlines.
526func expandImageRowPlaceholders(text string) string {
527	re := regexp.MustCompile(regexp.QuoteMeta(imageRowPlaceholderPrefix) + `(\d+)` + regexp.QuoteMeta(imageRowPlaceholderSuffix))
528	return re.ReplaceAllStringFunc(text, func(match string) string {
529		// Extract the number of rows from the placeholder
530		numStr := strings.TrimPrefix(match, imageRowPlaceholderPrefix)
531		numStr = strings.TrimSuffix(numStr, imageRowPlaceholderSuffix)
532		rows := 1
533		if _, err := fmt.Sscanf(numStr, "%d", &rows); err != nil || rows < 1 {
534			rows = 1
535		}
536		// Return the newlines needed to push content below the image
537		return strings.Repeat("\n", rows)
538	})
539}
540
541type InlineImage struct {
542	CID    string
543	Base64 string
544}
545
546// ImagePlacement holds the data needed to render an image at a specific
547// line in the email body. Images are rendered directly to stdout (bypassing
548// bubbletea's cell-based renderer which cannot handle graphics protocols).
549type ImagePlacement struct {
550	Line     int    // Line number in the processed body text where the image starts
551	Base64   string // Base64-encoded image data (PNG)
552	Rows     int    // Number of terminal rows the image occupies
553	Uploaded bool   // Whether the image has been uploaded to the terminal via Kitty ID
554	ID       uint32 // Kitty image ID for display-by-reference
555}
556
557// ProcessBodyWithInline renders the body and resolves CID inline images when provided.
558// Returns the rendered body text, image placements for out-of-band rendering, and any error.
559func ProcessBodyWithInline(rawBody string, inline []InlineImage, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
560	inlineMap := make(map[string]string, len(inline))
561	for _, img := range inline {
562		cid := strings.TrimSpace(img.CID)
563		cid = strings.TrimPrefix(cid, "<")
564		cid = strings.TrimSuffix(cid, ">")
565		cid = strings.TrimPrefix(cid, "cid:")
566		if cid == "" || img.Base64 == "" {
567			continue
568		}
569		inlineMap[cid] = img.Base64
570	}
571	return processBody(rawBody, inlineMap, h1Style, h2Style, bodyStyle, disableImages)
572}
573
574// ProcessBody takes a raw email body, decodes it, and formats it as plain
575// text with terminal hyperlinks.
576func ProcessBody(rawBody string, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
577	return processBody(rawBody, nil, h1Style, h2Style, bodyStyle, disableImages)
578}
579
580func processBody(rawBody string, inline map[string]string, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
581	decodedBody, err := decodeQuotedPrintable(rawBody)
582	if err != nil {
583		decodedBody = rawBody
584	}
585
586	htmlBody := markdownToHTML([]byte(decodedBody))
587
588	// Parse HTML into structured elements using C parser.
589	elements, ok := clib.HTMLToElements(string(htmlBody))
590	if !ok {
591		return "", nil, fmt.Errorf("could not parse email body")
592	}
593
594	// Process elements: apply styles and collect image placements.
595	var text strings.Builder
596	var imgIndex int
597	var pendingImages []struct {
598		index   int
599		payload string
600		rows    int
601	}
602
603	onWroteRegex := regexp.MustCompile(`On\s+(.+?),\s+(.+?)\s+wrote:`)
604
605	for _, elem := range elements {
606		switch elem.Type {
607		case clib.HElemText:
608			text.WriteString(elem.Text)
609
610		case clib.HElemH1:
611			text.WriteString(h1Style.Render(elem.Text))
612			text.WriteString("\n\n")
613
614		case clib.HElemH2:
615			text.WriteString(h2Style.Render(elem.Text))
616			text.WriteString("\n\n")
617
618		case clib.HElemLink:
619			text.WriteString(hyperlink(elem.Attr1, elem.Text))
620
621		case clib.HElemImage:
622			src := elem.Attr1
623			alt := elem.Attr2
624
625			if !disableImages && imageProtocolSupported() {
626				var payload string
627				if strings.HasPrefix(src, "data:image/") {
628					payload = dataURIBase64(src)
629				} else if strings.HasPrefix(src, "cid:") {
630					cid := strings.TrimPrefix(src, "cid:")
631					cid = strings.Trim(cid, "<>")
632					if inline != nil {
633						payload = inline[cid]
634						debugImageProtocol("cid lookup for %s found=%t len=%d", cid, payload != "", len(payload))
635					} else {
636						debugImageProtocol("cid lookup skipped inline map nil for %s", cid)
637					}
638				} else if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") {
639					payload = fetchRemoteBase64(src)
640				}
641
642				if payload != "" {
643					rows := imageRows(payload)
644					debugImageProtocol("collected image placement src=%s rows=%d", src, rows)
645
646					idx := imgIndex
647					imgIndex++
648					pendingImages = append(pendingImages, struct {
649						index   int
650						payload string
651						rows    int
652					}{idx, payload, rows})
653
654					text.WriteString(fmt.Sprintf("\n[[MATCHA_IMG:%d]]", idx))
655					text.WriteString(fmt.Sprintf("\n%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix))
656					continue
657				}
658				debugImageProtocol("no payload for src=%s", src)
659			}
660			if hyperlinkSupported() {
661				text.WriteString(hyperlink(src, fmt.Sprintf("\n [Click here to view image: %s] \n", alt)))
662			} else {
663				text.WriteString(fmt.Sprintf("\n %s \n", linkStyle().Render(fmt.Sprintf("[Image: %s, %s]", alt, src))))
664			}
665
666		case clib.HElemBlockquote:
667			var from, date string
668			prevText := elem.Attr2
669			cite := elem.Attr1
670
671			if matches := onWroteRegex.FindStringSubmatch(prevText); matches != nil {
672				date = parseDateForDisplay(matches[1])
673				from = matches[2]
674			} else if matches := onWroteRegex.FindStringSubmatch(cite); matches != nil {
675				date = parseDateForDisplay(matches[1])
676				from = matches[2]
677			}
678
679			text.WriteString(renderQuoteBox(from, date, strings.Split(elem.Text, "\n")))
680		}
681	}
682
683	result := text.String()
684
685	// Collapse excessive newlines, but not the image row placeholders
686	re := regexp.MustCompile(`\n{3,}`)
687	result = re.ReplaceAllString(result, "\n\n")
688
689	// Now expand the image row placeholders to actual newlines
690	result = expandImageRowPlaceholders(result)
691
692	// Build image placements by finding the line numbers of image markers.
693	var placements []ImagePlacement
694	if len(pendingImages) > 0 {
695		lines := strings.Split(result, "\n")
696		imgMarkerRegex := regexp.MustCompile(`\[\[MATCHA_IMG:(\d+)\]\]`)
697		for lineNum, line := range lines {
698			if matches := imgMarkerRegex.FindStringSubmatch(line); matches != nil {
699				var idx int
700				fmt.Sscanf(matches[1], "%d", &idx)
701				for _, pi := range pendingImages {
702					if pi.index == idx {
703						placements = append(placements, ImagePlacement{
704							Line:   lineNum,
705							Base64: pi.payload,
706							Rows:   pi.rows,
707						})
708						break
709					}
710				}
711			}
712		}
713
714		// Remove the image markers from the text (leave the spacing)
715		result = imgMarkerRegex.ReplaceAllString(result, "")
716	}
717
718	// Style quoted reply sections (for plain text > quotes)
719	result = styleQuotedReplies(result)
720
721	return bodyStyle.Render(result), placements, nil
722}
723
724func quoteBoxStyle() lipgloss.Style {
725	return lipgloss.NewStyle().
726		Border(lipgloss.RoundedBorder()).
727		BorderForeground(theme.ActiveTheme.Secondary).
728		Padding(0, 1).
729		Foreground(theme.ActiveTheme.Secondary)
730}
731
732func quoteHeaderStyle() lipgloss.Style {
733	return lipgloss.NewStyle().
734		Foreground(theme.ActiveTheme.Secondary)
735}
736
737// styleQuotedReplies detects quoted reply sections and styles them in a box
738func styleQuotedReplies(text string) string {
739	lines := strings.Split(text, "\n")
740	var result []string
741	var quoteBlock []string
742	var quoteFrom, quoteDate string
743	inQuote := false
744
745	// Regex to match "On DATE, EMAIL wrote:" pattern
746	// Matches various date formats
747	onWroteRegex := regexp.MustCompile(`^On\s+(.+?),\s+(.+?)\s+wrote:$`)
748
749	for i := 0; i < len(lines); i++ {
750		line := lines[i]
751		trimmedLine := strings.TrimSpace(line)
752
753		// Check for "On DATE, EMAIL wrote:" header
754		if matches := onWroteRegex.FindStringSubmatch(trimmedLine); matches != nil {
755			// If we were already in a quote block, render it first
756			if inQuote && len(quoteBlock) > 0 {
757				result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
758				quoteBlock = nil
759			}
760
761			// Parse the date and email from the match
762			dateStr := matches[1]
763			quoteFrom = matches[2]
764			quoteDate = parseDateForDisplay(dateStr)
765			inQuote = true
766			continue
767		}
768
769		// Check if line starts with ">" (quoted text)
770		if strings.HasPrefix(trimmedLine, ">") {
771			if !inQuote {
772				// Start a new quote block without header info
773				inQuote = true
774				quoteFrom = ""
775				quoteDate = ""
776			}
777			// Remove the leading "> " and add to quote block
778			quotedContent := strings.TrimPrefix(trimmedLine, ">")
779			quotedContent = strings.TrimPrefix(quotedContent, " ")
780			quoteBlock = append(quoteBlock, quotedContent)
781		} else if inQuote {
782			// End of quote block - check if it's just whitespace
783			if trimmedLine == "" && i+1 < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i+1]), ">") {
784				// Empty line within quote block, keep it
785				quoteBlock = append(quoteBlock, "")
786			} else if trimmedLine == "" && len(quoteBlock) == 0 {
787				// Empty line before any quoted content, skip
788				continue
789			} else {
790				// End of quote block
791				if len(quoteBlock) > 0 {
792					result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
793					quoteBlock = nil
794				}
795				inQuote = false
796				quoteFrom = ""
797				quoteDate = ""
798				result = append(result, line)
799			}
800		} else {
801			result = append(result, line)
802		}
803	}
804
805	// Handle any remaining quote block
806	if inQuote && len(quoteBlock) > 0 {
807		result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
808	}
809
810	return strings.Join(result, "\n")
811}
812
813// parseDateForDisplay converts various date formats to DD:MM:YY HH:MM
814func parseDateForDisplay(dateStr string) string {
815	// Common date formats to try
816	formats := []string{
817		"Jan 2, 2006 at 3:04 PM",
818		"02:01:06 15:04",
819		"2006-01-02 15:04:05",
820		"Mon, 02 Jan 2006 15:04:05 -0700",
821		"Mon, 2 Jan 2006 15:04:05 -0700",
822		"2 Jan 2006 15:04:05",
823		"January 2, 2006 at 3:04 PM",
824		"Jan 2, 2006 3:04 PM",
825		time.RFC1123Z,
826		time.RFC1123,
827		time.RFC822Z,
828		time.RFC822,
829	}
830
831	for _, format := range formats {
832		if t, err := time.Parse(format, dateStr); err == nil {
833			return t.Format("02:01:06 15:04")
834		}
835	}
836
837	// Return original if parsing fails
838	return dateStr
839}
840
841// renderQuoteBox renders a quoted section in a styled box
842func renderQuoteBox(from, date string, lines []string) string {
843	// Build header with email on left and date on right
844	var header string
845	if from != "" || date != "" {
846		if from != "" && date != "" {
847			header = quoteHeaderStyle().Render(from + "  " + date)
848		} else if from != "" {
849			header = quoteHeaderStyle().Render(from)
850		} else {
851			header = quoteHeaderStyle().Render(date)
852		}
853	}
854
855	// Join the quoted content
856	content := strings.Join(lines, "\n")
857
858	// Build the box content
859	var boxContent string
860	if header != "" {
861		boxContent = header + "\n\n" + content
862	} else {
863		boxContent = content
864	}
865
866	return quoteBoxStyle().Render(boxContent)
867}