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