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.HElemTable:
667 headerRows := 0
668 if elem.Attr1 != "" {
669 fmt.Sscanf(elem.Attr1, "%d", &headerRows)
670 }
671 text.WriteString("\n")
672 text.WriteString(renderTable(elem.Text, headerRows))
673 text.WriteString("\n")
674
675 case clib.HElemBlockquote:
676 var from, date string
677 prevText := elem.Attr2
678 cite := elem.Attr1
679
680 if matches := onWroteRegex.FindStringSubmatch(prevText); matches != nil {
681 date = parseDateForDisplay(matches[1])
682 from = matches[2]
683 } else if matches := onWroteRegex.FindStringSubmatch(cite); matches != nil {
684 date = parseDateForDisplay(matches[1])
685 from = matches[2]
686 }
687
688 text.WriteString(renderQuoteBox(from, date, strings.Split(elem.Text, "\n")))
689 }
690 }
691
692 result := text.String()
693
694 // Collapse excessive newlines, but not the image row placeholders
695 re := regexp.MustCompile(`\n{3,}`)
696 result = re.ReplaceAllString(result, "\n\n")
697
698 // Now expand the image row placeholders to actual newlines
699 result = expandImageRowPlaceholders(result)
700
701 // Build image placements by finding the line numbers of image markers.
702 var placements []ImagePlacement
703 if len(pendingImages) > 0 {
704 lines := strings.Split(result, "\n")
705 imgMarkerRegex := regexp.MustCompile(`\[\[MATCHA_IMG:(\d+)\]\]`)
706 for lineNum, line := range lines {
707 if matches := imgMarkerRegex.FindStringSubmatch(line); matches != nil {
708 var idx int
709 fmt.Sscanf(matches[1], "%d", &idx)
710 for _, pi := range pendingImages {
711 if pi.index == idx {
712 placements = append(placements, ImagePlacement{
713 Line: lineNum,
714 Base64: pi.payload,
715 Rows: pi.rows,
716 })
717 break
718 }
719 }
720 }
721 }
722
723 // Remove the image markers from the text (leave the spacing)
724 result = imgMarkerRegex.ReplaceAllString(result, "")
725 }
726
727 // Style quoted reply sections (for plain text > quotes)
728 result = styleQuotedReplies(result)
729
730 return bodyStyle.Render(result), placements, nil
731}
732
733func tableHeaderStyle() lipgloss.Style {
734 return lipgloss.NewStyle().Bold(true).Foreground(theme.ActiveTheme.Accent)
735}
736
737func tableBorderStyle() lipgloss.Style {
738 return lipgloss.NewStyle().Foreground(theme.ActiveTheme.Secondary)
739}
740
741// renderTable renders table data as a Unicode box-drawing table.
742// data is tab-separated cells, newline-separated rows.
743// headerRows is the number of header rows.
744func renderTable(data string, headerRows int) string {
745 rows := strings.Split(data, "\n")
746 if len(rows) == 0 {
747 return ""
748 }
749
750 // Parse into 2D grid and trim cell whitespace
751 var grid [][]string
752 maxCols := 0
753 for _, row := range rows {
754 cells := strings.Split(row, "\t")
755 trimmed := make([]string, len(cells))
756 for i, c := range cells {
757 trimmed[i] = strings.TrimSpace(c)
758 }
759 grid = append(grid, trimmed)
760 if len(trimmed) > maxCols {
761 maxCols = len(trimmed)
762 }
763 }
764
765 // Normalize: ensure all rows have the same number of columns
766 for i := range grid {
767 for len(grid[i]) < maxCols {
768 grid[i] = append(grid[i], "")
769 }
770 }
771
772 // Calculate column widths
773 colWidths := make([]int, maxCols)
774 for _, row := range grid {
775 for j, cell := range row {
776 if len(cell) > colWidths[j] {
777 colWidths[j] = len(cell)
778 }
779 }
780 }
781
782 // Minimum width per column
783 for i := range colWidths {
784 if colWidths[i] < 3 {
785 colWidths[i] = 3
786 }
787 }
788
789 bs := tableBorderStyle()
790 hs := tableHeaderStyle()
791
792 // Build horizontal borders
793 buildBorder := func(left, mid, right, fill string) string {
794 var b strings.Builder
795 b.WriteString(bs.Render(left))
796 for j, w := range colWidths {
797 b.WriteString(bs.Render(strings.Repeat(fill, w+2)))
798 if j < len(colWidths)-1 {
799 b.WriteString(bs.Render(mid))
800 }
801 }
802 b.WriteString(bs.Render(right))
803 return b.String()
804 }
805
806 topBorder := buildBorder("┌", "┬", "┐", "─")
807 midBorder := buildBorder("├", "┼", "┤", "─")
808 botBorder := buildBorder("└", "┴", "┘", "─")
809
810 var out strings.Builder
811 out.WriteString(topBorder)
812 out.WriteString("\n")
813
814 for i, row := range grid {
815 out.WriteString(bs.Render("│"))
816 for j, cell := range row {
817 padded := cell + strings.Repeat(" ", colWidths[j]-len(cell))
818 if i < headerRows {
819 out.WriteString(" " + hs.Render(padded) + " ")
820 } else {
821 out.WriteString(" " + padded + " ")
822 }
823 out.WriteString(bs.Render("│"))
824 }
825 out.WriteString("\n")
826
827 if i < headerRows && (i+1 == headerRows || i+1 == len(grid)) {
828 out.WriteString(midBorder)
829 out.WriteString("\n")
830 }
831 }
832
833 out.WriteString(botBorder)
834 return out.String()
835}
836
837func quoteBoxStyle() lipgloss.Style {
838 return lipgloss.NewStyle().
839 Border(lipgloss.RoundedBorder()).
840 BorderForeground(theme.ActiveTheme.Secondary).
841 Padding(0, 1).
842 Foreground(theme.ActiveTheme.Secondary)
843}
844
845func quoteHeaderStyle() lipgloss.Style {
846 return lipgloss.NewStyle().
847 Foreground(theme.ActiveTheme.Secondary)
848}
849
850// styleQuotedReplies detects quoted reply sections and styles them in a box
851func styleQuotedReplies(text string) string {
852 lines := strings.Split(text, "\n")
853 var result []string
854 var quoteBlock []string
855 var quoteFrom, quoteDate string
856 inQuote := false
857
858 // Regex to match "On DATE, EMAIL wrote:" pattern
859 // Matches various date formats
860 onWroteRegex := regexp.MustCompile(`^On\s+(.+?),\s+(.+?)\s+wrote:$`)
861
862 for i := 0; i < len(lines); i++ {
863 line := lines[i]
864 trimmedLine := strings.TrimSpace(line)
865
866 // Check for "On DATE, EMAIL wrote:" header
867 if matches := onWroteRegex.FindStringSubmatch(trimmedLine); matches != nil {
868 // If we were already in a quote block, render it first
869 if inQuote && len(quoteBlock) > 0 {
870 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
871 quoteBlock = nil
872 }
873
874 // Parse the date and email from the match
875 dateStr := matches[1]
876 quoteFrom = matches[2]
877 quoteDate = parseDateForDisplay(dateStr)
878 inQuote = true
879 continue
880 }
881
882 // Check if line starts with ">" (quoted text)
883 if strings.HasPrefix(trimmedLine, ">") {
884 if !inQuote {
885 // Start a new quote block without header info
886 inQuote = true
887 quoteFrom = ""
888 quoteDate = ""
889 }
890 // Remove the leading "> " and add to quote block
891 quotedContent := strings.TrimPrefix(trimmedLine, ">")
892 quotedContent = strings.TrimPrefix(quotedContent, " ")
893 quoteBlock = append(quoteBlock, quotedContent)
894 } else if inQuote {
895 // End of quote block - check if it's just whitespace
896 if trimmedLine == "" && i+1 < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i+1]), ">") {
897 // Empty line within quote block, keep it
898 quoteBlock = append(quoteBlock, "")
899 } else if trimmedLine == "" && len(quoteBlock) == 0 {
900 // Empty line before any quoted content, skip
901 continue
902 } else {
903 // End of quote block
904 if len(quoteBlock) > 0 {
905 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
906 quoteBlock = nil
907 }
908 inQuote = false
909 quoteFrom = ""
910 quoteDate = ""
911 result = append(result, line)
912 }
913 } else {
914 result = append(result, line)
915 }
916 }
917
918 // Handle any remaining quote block
919 if inQuote && len(quoteBlock) > 0 {
920 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
921 }
922
923 return strings.Join(result, "\n")
924}
925
926// parseDateForDisplay converts various date formats to DD:MM:YY HH:MM
927func parseDateForDisplay(dateStr string) string {
928 // Common date formats to try
929 formats := []string{
930 "Jan 2, 2006 at 3:04 PM",
931 "02:01:06 15:04",
932 "2006-01-02 15:04:05",
933 "Mon, 02 Jan 2006 15:04:05 -0700",
934 "Mon, 2 Jan 2006 15:04:05 -0700",
935 "2 Jan 2006 15:04:05",
936 "January 2, 2006 at 3:04 PM",
937 "Jan 2, 2006 3:04 PM",
938 time.RFC1123Z,
939 time.RFC1123,
940 time.RFC822Z,
941 time.RFC822,
942 }
943
944 for _, format := range formats {
945 if t, err := time.Parse(format, dateStr); err == nil {
946 return t.Format("02:01:06 15:04")
947 }
948 }
949
950 // Return original if parsing fails
951 return dateStr
952}
953
954// renderQuoteBox renders a quoted section in a styled box
955func renderQuoteBox(from, date string, lines []string) string {
956 // Build header with email on left and date on right
957 var header string
958 if from != "" || date != "" {
959 if from != "" && date != "" {
960 header = quoteHeaderStyle().Render(from + " " + date)
961 } else if from != "" {
962 header = quoteHeaderStyle().Render(from)
963 } else {
964 header = quoteHeaderStyle().Render(date)
965 }
966 }
967
968 // Join the quoted content
969 content := strings.Join(lines, "\n")
970
971 // Build the box content
972 var boxContent string
973 if header != "" {
974 boxContent = header + "\n\n" + content
975 } else {
976 boxContent = content
977 }
978
979 return quoteBoxStyle().Render(boxContent)
980}