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 // Limit response body to 10 MB to prevent memory exhaustion from
303 // malicious or very large images.
304 const maxImageSize = 10 << 20 // 10 MB
305 data, err := io.ReadAll(io.LimitReader(resp.Body, maxImageSize))
306 if err != nil {
307 debugImageProtocol("remote fetch read error url=%s err=%v", url, err)
308 return ""
309 }
310
311 result, ok := clib.DecodeToPNG(data)
312 if !ok {
313 debugImageProtocol("remote decode failed url=%s", url)
314 return ""
315 }
316
317 encoded := base64.StdEncoding.EncodeToString(result.PNGData)
318 debugImageProtocol("remote fetch ok url=%s len=%d", url, len(encoded))
319 remoteImageCache.Store(url, encoded)
320 return encoded
321}
322
323func dataURIBase64(uri string) string {
324 if !strings.HasPrefix(uri, "data:") {
325 return ""
326 }
327 comma := strings.Index(uri, ",")
328 if comma == -1 || comma+1 >= len(uri) {
329 return ""
330 }
331 return uri[comma+1:]
332}
333
334// imageRowPlaceholderPrefix is used to mark where image row spacing should be inserted.
335// This prevents the newline-collapsing regex from removing intentional spacing.
336// Uses brackets instead of angle brackets to avoid being interpreted as HTML tags.
337const imageRowPlaceholderPrefix = "[[MATCHA_IMG_ROWS:"
338const imageRowPlaceholderSuffix = "]]"
339
340func kittyInlineImage(payload string) string {
341 if payload == "" {
342 return ""
343 }
344
345 const chunkSize = 4096
346 var b strings.Builder
347
348 // Calculate how many terminal rows the image occupies to advance text after it.
349 rows := 1
350 if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
351 if _, h, ok := clib.ImageDimensions(data); ok {
352 cellHeight := getTerminalCellSize()
353 rows = (h + cellHeight - 1) / cellHeight
354 if rows < 1 {
355 rows = 1
356 }
357 debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
358 }
359 }
360
361 for offset := 0; offset < len(payload); offset += chunkSize {
362 end := offset + chunkSize
363 if end > len(payload) {
364 end = len(payload)
365 }
366 more := "0"
367 if end < len(payload) {
368 more = "1"
369 }
370
371 chunk := payload[offset:end]
372 if offset == 0 {
373 // C=1 means cursor does NOT move after image render (stays at top-left of image position)
374 // This is needed for proper TUI rendering, but we must add newlines to push text below
375 b.WriteString(fmt.Sprintf("\x1b_Gf=100,a=T,q=2,C=1,m=%s;%s\x1b\\", more, chunk))
376 } else {
377 b.WriteString(fmt.Sprintf("\x1b_Gm=%s;%s\x1b\\", more, chunk))
378 }
379 }
380
381 // Add newlines to push cursor below the image.
382 // Use a placeholder that won't be collapsed by the newline regex.
383 b.WriteString(fmt.Sprintf("\n%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix))
384
385 return b.String()
386}
387
388// iterm2InlineImage renders an image using iTerm2's image protocol
389func iterm2InlineImage(payload string) string {
390 if payload == "" {
391 return ""
392 }
393
394 // Calculate rows for cursor positioning
395 rows := 1
396 if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
397 if _, h, ok := clib.ImageDimensions(data); ok {
398 cellHeight := getTerminalCellSize()
399 rows = (h + cellHeight - 1) / cellHeight
400 if rows < 1 {
401 rows = 1
402 }
403 debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
404 }
405 }
406
407 // iTerm2 image protocol: ESC]1337;File=inline=1:<base64_data>BEL
408 result := fmt.Sprintf("\x1b]1337;File=inline=1:%s\x07\n", payload)
409
410 // Add placeholder for row spacing
411 result += fmt.Sprintf("%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix)
412
413 return result
414}
415
416// renderInlineImage renders an image using the appropriate protocol for the detected terminal
417func renderInlineImage(payload string) string {
418 if payload == "" {
419 return ""
420 }
421
422 if kittySupported() || ghosttySupported() || weztermSupported() || waystSupported() || konsoleSupported() {
423 // These terminals use the Kitty graphics protocol
424 return kittyInlineImage(payload)
425 } else if iterm2Supported() || warpSupported() {
426 // iTerm2 and Warp use the iTerm2 image protocol
427 return iterm2InlineImage(payload)
428 }
429
430 return ""
431}
432
433// imageRows calculates the number of terminal rows an image occupies.
434func imageRows(payload string) int {
435 rows := 1
436 if data, err := base64.StdEncoding.DecodeString(payload); err == nil {
437 if _, h, ok := clib.ImageDimensions(data); ok {
438 cellHeight := getTerminalCellSize()
439 rows = (h + cellHeight - 1) / cellHeight
440 if rows < 1 {
441 rows = 1
442 }
443 debugImageProtocol("image height: %d pixels, cell height: %d pixels, rows needed: %d", h, cellHeight, rows)
444 }
445 }
446 return rows
447}
448
449// kittyUploadImage uploads image data to the terminal with a unique ID using
450// the Kitty graphics protocol transmit action (a=t). The image is stored in
451// the terminal's memory and can be displayed later by ID without re-sending data.
452func kittyUploadImage(payload string, id uint32) {
453 if payload == "" {
454 return
455 }
456
457 const chunkSize = 4096
458 for offset := 0; offset < len(payload); offset += chunkSize {
459 end := offset + chunkSize
460 if end > len(payload) {
461 end = len(payload)
462 }
463 more := "0"
464 if end < len(payload) {
465 more = "1"
466 }
467
468 chunk := payload[offset:end]
469 if offset == 0 {
470 // a=t: transmit (upload) only, don't display yet
471 // i=ID: assign this image ID
472 fmt.Fprintf(os.Stdout, "\x1b_Gf=100,a=t,i=%d,q=2,m=%s;%s\x1b\\", id, more, chunk)
473 } else {
474 fmt.Fprintf(os.Stdout, "\x1b_Gm=%s;%s\x1b\\", more, chunk)
475 }
476 }
477 os.Stdout.Sync()
478}
479
480// kittyDisplayImage displays a previously uploaded image by its ID at the
481// current cursor position. This is very fast since no image data is transmitted.
482func kittyDisplayImage(id uint32) string {
483 // a=p: put (display) an already-uploaded image by ID
484 // C=1: cursor does not move
485 return fmt.Sprintf("\x1b_Ga=p,i=%d,q=2,C=1\x1b\\", id)
486}
487
488// iterm2ImageEscapeOnly returns only the iTerm2 image protocol escape sequence
489// without any row placeholders. Used for out-of-band rendering to stdout.
490func iterm2ImageEscapeOnly(payload string) string {
491 if payload == "" {
492 return ""
493 }
494 return fmt.Sprintf("\x1b]1337;File=inline=1:%s\x07", payload)
495}
496
497// RenderImageToStdout writes an image directly to stdout at the given screen
498// row using cursor positioning. This bypasses bubbletea's cell-based renderer
499// which cannot handle graphics protocol escape sequences.
500//
501// For Kitty-protocol terminals, images are uploaded once and then displayed by
502// ID on subsequent calls, making scroll rendering nearly instant.
503func RenderImageToStdout(placement *ImagePlacement, screenRow int) {
504 if placement.Base64 == "" {
505 return
506 }
507
508 useKitty := kittySupported() || ghosttySupported() || weztermSupported() || waystSupported() || konsoleSupported()
509 useIterm2 := iterm2Supported() || warpSupported()
510
511 if useKitty {
512 // Upload once, display by ID on subsequent renders
513 if !placement.Uploaded {
514 placement.ID = allocImageID()
515 kittyUploadImage(placement.Base64, placement.ID)
516 placement.Uploaded = true
517 }
518 seq := kittyDisplayImage(placement.ID)
519 fmt.Fprintf(os.Stdout, "\x1b[s\x1b[%d;1H%s\x1b[u", screenRow+1, seq)
520 os.Stdout.Sync()
521 } else if useIterm2 {
522 seq := iterm2ImageEscapeOnly(placement.Base64)
523 fmt.Fprintf(os.Stdout, "\x1b[s\x1b[%d;1H%s\x1b[u", screenRow+1, seq)
524 os.Stdout.Sync()
525 }
526}
527
528// expandImageRowPlaceholders replaces image row placeholders with actual newlines.
529func expandImageRowPlaceholders(text string) string {
530 re := regexp.MustCompile(regexp.QuoteMeta(imageRowPlaceholderPrefix) + `(\d+)` + regexp.QuoteMeta(imageRowPlaceholderSuffix))
531 return re.ReplaceAllStringFunc(text, func(match string) string {
532 // Extract the number of rows from the placeholder
533 numStr := strings.TrimPrefix(match, imageRowPlaceholderPrefix)
534 numStr = strings.TrimSuffix(numStr, imageRowPlaceholderSuffix)
535 rows := 1
536 if _, err := fmt.Sscanf(numStr, "%d", &rows); err != nil || rows < 1 {
537 rows = 1
538 }
539 // Return the newlines needed to push content below the image
540 return strings.Repeat("\n", rows)
541 })
542}
543
544type InlineImage struct {
545 CID string
546 Base64 string
547}
548
549// ImagePlacement holds the data needed to render an image at a specific
550// line in the email body. Images are rendered directly to stdout (bypassing
551// bubbletea's cell-based renderer which cannot handle graphics protocols).
552type ImagePlacement struct {
553 Line int // Line number in the processed body text where the image starts
554 Base64 string // Base64-encoded image data (PNG)
555 Rows int // Number of terminal rows the image occupies
556 Uploaded bool // Whether the image has been uploaded to the terminal via Kitty ID
557 ID uint32 // Kitty image ID for display-by-reference
558}
559
560// ProcessBodyWithInline renders the body and resolves CID inline images when provided.
561// Returns the rendered body text, image placements for out-of-band rendering, and any error.
562func ProcessBodyWithInline(rawBody string, inline []InlineImage, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
563 inlineMap := make(map[string]string, len(inline))
564 for _, img := range inline {
565 cid := strings.TrimSpace(img.CID)
566 cid = strings.TrimPrefix(cid, "<")
567 cid = strings.TrimSuffix(cid, ">")
568 cid = strings.TrimPrefix(cid, "cid:")
569 if cid == "" || img.Base64 == "" {
570 continue
571 }
572 inlineMap[cid] = img.Base64
573 }
574 return processBody(rawBody, inlineMap, h1Style, h2Style, bodyStyle, disableImages)
575}
576
577// ProcessBody takes a raw email body, decodes it, and formats it as plain
578// text with terminal hyperlinks.
579func ProcessBody(rawBody string, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
580 return processBody(rawBody, nil, h1Style, h2Style, bodyStyle, disableImages)
581}
582
583func processBody(rawBody string, inline map[string]string, h1Style, h2Style, bodyStyle lipgloss.Style, disableImages bool) (string, []ImagePlacement, error) {
584 decodedBody, err := decodeQuotedPrintable(rawBody)
585 if err != nil {
586 decodedBody = rawBody
587 }
588
589 htmlBody := markdownToHTML([]byte(decodedBody))
590
591 // Parse HTML into structured elements using C parser.
592 elements, ok := clib.HTMLToElements(string(htmlBody))
593 if !ok {
594 return "", nil, fmt.Errorf("could not parse email body")
595 }
596
597 // Process elements: apply styles and collect image placements.
598 var text strings.Builder
599 var imgIndex int
600 var pendingImages []struct {
601 index int
602 payload string
603 rows int
604 }
605
606 onWroteRegex := regexp.MustCompile(`On\s+(.+?),\s+(.+?)\s+wrote:`)
607
608 for _, elem := range elements {
609 switch elem.Type {
610 case clib.HElemText:
611 text.WriteString(elem.Text)
612
613 case clib.HElemH1:
614 text.WriteString(h1Style.Render(elem.Text))
615 text.WriteString("\n\n")
616
617 case clib.HElemH2:
618 text.WriteString(h2Style.Render(elem.Text))
619 text.WriteString("\n\n")
620
621 case clib.HElemLink:
622 text.WriteString(hyperlink(elem.Attr1, elem.Text))
623
624 case clib.HElemImage:
625 src := elem.Attr1
626 alt := elem.Attr2
627
628 if !disableImages && imageProtocolSupported() {
629 var payload string
630 if strings.HasPrefix(src, "data:image/") {
631 payload = dataURIBase64(src)
632 } else if strings.HasPrefix(src, "cid:") {
633 cid := strings.TrimPrefix(src, "cid:")
634 cid = strings.Trim(cid, "<>")
635 if inline != nil {
636 payload = inline[cid]
637 debugImageProtocol("cid lookup for %s found=%t len=%d", cid, payload != "", len(payload))
638 } else {
639 debugImageProtocol("cid lookup skipped inline map nil for %s", cid)
640 }
641 } else if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") {
642 payload = fetchRemoteBase64(src)
643 }
644
645 if payload != "" {
646 rows := imageRows(payload)
647 debugImageProtocol("collected image placement src=%s rows=%d", src, rows)
648
649 idx := imgIndex
650 imgIndex++
651 pendingImages = append(pendingImages, struct {
652 index int
653 payload string
654 rows int
655 }{idx, payload, rows})
656
657 text.WriteString(fmt.Sprintf("\n[[MATCHA_IMG:%d]]", idx))
658 text.WriteString(fmt.Sprintf("\n%s%d%s\n", imageRowPlaceholderPrefix, rows, imageRowPlaceholderSuffix))
659 continue
660 }
661 debugImageProtocol("no payload for src=%s", src)
662 }
663 if hyperlinkSupported() {
664 text.WriteString(hyperlink(src, fmt.Sprintf("\n [Click here to view image: %s] \n", alt)))
665 } else {
666 text.WriteString(fmt.Sprintf("\n %s \n", linkStyle().Render(fmt.Sprintf("[Image: %s, %s]", alt, src))))
667 }
668
669 case clib.HElemTable:
670 headerRows := 0
671 if elem.Attr1 != "" {
672 fmt.Sscanf(elem.Attr1, "%d", &headerRows)
673 }
674 text.WriteString("\n")
675 text.WriteString(renderTable(elem.Text, headerRows))
676 text.WriteString("\n")
677
678 case clib.HElemBlockquote:
679 var from, date string
680 prevText := elem.Attr2
681 cite := elem.Attr1
682
683 if matches := onWroteRegex.FindStringSubmatch(prevText); matches != nil {
684 date = parseDateForDisplay(matches[1])
685 from = matches[2]
686 } else if matches := onWroteRegex.FindStringSubmatch(cite); matches != nil {
687 date = parseDateForDisplay(matches[1])
688 from = matches[2]
689 }
690
691 text.WriteString(renderQuoteBox(from, date, strings.Split(elem.Text, "\n")))
692 }
693 }
694
695 result := text.String()
696
697 // Collapse excessive newlines, but not the image row placeholders
698 re := regexp.MustCompile(`\n{3,}`)
699 result = re.ReplaceAllString(result, "\n\n")
700
701 // Now expand the image row placeholders to actual newlines
702 result = expandImageRowPlaceholders(result)
703
704 // Build image placements by finding the line numbers of image markers.
705 var placements []ImagePlacement
706 if len(pendingImages) > 0 {
707 lines := strings.Split(result, "\n")
708 imgMarkerRegex := regexp.MustCompile(`\[\[MATCHA_IMG:(\d+)\]\]`)
709 for lineNum, line := range lines {
710 if matches := imgMarkerRegex.FindStringSubmatch(line); matches != nil {
711 var idx int
712 fmt.Sscanf(matches[1], "%d", &idx)
713 for _, pi := range pendingImages {
714 if pi.index == idx {
715 placements = append(placements, ImagePlacement{
716 Line: lineNum,
717 Base64: pi.payload,
718 Rows: pi.rows,
719 })
720 break
721 }
722 }
723 }
724 }
725
726 // Remove the image markers from the text (leave the spacing)
727 result = imgMarkerRegex.ReplaceAllString(result, "")
728 }
729
730 // Style quoted reply sections (for plain text > quotes)
731 result = styleQuotedReplies(result)
732
733 return bodyStyle.Render(result), placements, nil
734}
735
736func tableHeaderStyle() lipgloss.Style {
737 return lipgloss.NewStyle().Bold(true).Foreground(theme.ActiveTheme.Accent)
738}
739
740func tableBorderStyle() lipgloss.Style {
741 return lipgloss.NewStyle().Foreground(theme.ActiveTheme.Secondary)
742}
743
744// renderTable renders table data as a Unicode box-drawing table.
745// data is tab-separated cells, newline-separated rows.
746// headerRows is the number of header rows.
747func renderTable(data string, headerRows int) string {
748 rows := strings.Split(data, "\n")
749 if len(rows) == 0 {
750 return ""
751 }
752
753 // Parse into 2D grid and trim cell whitespace
754 var grid [][]string
755 maxCols := 0
756 for _, row := range rows {
757 cells := strings.Split(row, "\t")
758 trimmed := make([]string, len(cells))
759 for i, c := range cells {
760 trimmed[i] = strings.TrimSpace(c)
761 }
762 grid = append(grid, trimmed)
763 if len(trimmed) > maxCols {
764 maxCols = len(trimmed)
765 }
766 }
767
768 // Normalize: ensure all rows have the same number of columns
769 for i := range grid {
770 for len(grid[i]) < maxCols {
771 grid[i] = append(grid[i], "")
772 }
773 }
774
775 // Calculate column widths
776 colWidths := make([]int, maxCols)
777 for _, row := range grid {
778 for j, cell := range row {
779 if len(cell) > colWidths[j] {
780 colWidths[j] = len(cell)
781 }
782 }
783 }
784
785 // Minimum width per column
786 for i := range colWidths {
787 if colWidths[i] < 3 {
788 colWidths[i] = 3
789 }
790 }
791
792 bs := tableBorderStyle()
793 hs := tableHeaderStyle()
794
795 // Build horizontal borders
796 buildBorder := func(left, mid, right, fill string) string {
797 var b strings.Builder
798 b.WriteString(bs.Render(left))
799 for j, w := range colWidths {
800 b.WriteString(bs.Render(strings.Repeat(fill, w+2)))
801 if j < len(colWidths)-1 {
802 b.WriteString(bs.Render(mid))
803 }
804 }
805 b.WriteString(bs.Render(right))
806 return b.String()
807 }
808
809 topBorder := buildBorder("┌", "┬", "┐", "─")
810 midBorder := buildBorder("├", "┼", "┤", "─")
811 botBorder := buildBorder("└", "┴", "┘", "─")
812
813 var out strings.Builder
814 out.WriteString(topBorder)
815 out.WriteString("\n")
816
817 for i, row := range grid {
818 out.WriteString(bs.Render("│"))
819 for j, cell := range row {
820 padded := cell + strings.Repeat(" ", colWidths[j]-len(cell))
821 if i < headerRows {
822 out.WriteString(" " + hs.Render(padded) + " ")
823 } else {
824 out.WriteString(" " + padded + " ")
825 }
826 out.WriteString(bs.Render("│"))
827 }
828 out.WriteString("\n")
829
830 if i < headerRows && (i+1 == headerRows || i+1 == len(grid)) {
831 out.WriteString(midBorder)
832 out.WriteString("\n")
833 }
834 }
835
836 out.WriteString(botBorder)
837 return out.String()
838}
839
840func quoteBoxStyle() lipgloss.Style {
841 return lipgloss.NewStyle().
842 Border(lipgloss.RoundedBorder()).
843 BorderForeground(theme.ActiveTheme.Secondary).
844 Padding(0, 1).
845 Foreground(theme.ActiveTheme.Secondary)
846}
847
848func quoteHeaderStyle() lipgloss.Style {
849 return lipgloss.NewStyle().
850 Foreground(theme.ActiveTheme.Secondary)
851}
852
853// styleQuotedReplies detects quoted reply sections and styles them in a box
854func styleQuotedReplies(text string) string {
855 lines := strings.Split(text, "\n")
856 var result []string
857 var quoteBlock []string
858 var quoteFrom, quoteDate string
859 inQuote := false
860
861 // Regex to match "On DATE, EMAIL wrote:" pattern
862 // Matches various date formats
863 onWroteRegex := regexp.MustCompile(`^On\s+(.+?),\s+(.+?)\s+wrote:$`)
864
865 for i := 0; i < len(lines); i++ {
866 line := lines[i]
867 trimmedLine := strings.TrimSpace(line)
868
869 // Check for "On DATE, EMAIL wrote:" header
870 if matches := onWroteRegex.FindStringSubmatch(trimmedLine); matches != nil {
871 // If we were already in a quote block, render it first
872 if inQuote && len(quoteBlock) > 0 {
873 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
874 quoteBlock = nil
875 }
876
877 // Parse the date and email from the match
878 dateStr := matches[1]
879 quoteFrom = matches[2]
880 quoteDate = parseDateForDisplay(dateStr)
881 inQuote = true
882 continue
883 }
884
885 // Check if line starts with ">" (quoted text)
886 if strings.HasPrefix(trimmedLine, ">") {
887 if !inQuote {
888 // Start a new quote block without header info
889 inQuote = true
890 quoteFrom = ""
891 quoteDate = ""
892 }
893 // Remove the leading "> " and add to quote block
894 quotedContent := strings.TrimPrefix(trimmedLine, ">")
895 quotedContent = strings.TrimPrefix(quotedContent, " ")
896 quoteBlock = append(quoteBlock, quotedContent)
897 } else if inQuote {
898 // End of quote block - check if it's just whitespace
899 if trimmedLine == "" && i+1 < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i+1]), ">") {
900 // Empty line within quote block, keep it
901 quoteBlock = append(quoteBlock, "")
902 } else if trimmedLine == "" && len(quoteBlock) == 0 {
903 // Empty line before any quoted content, skip
904 continue
905 } else {
906 // End of quote block
907 if len(quoteBlock) > 0 {
908 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
909 quoteBlock = nil
910 }
911 inQuote = false
912 quoteFrom = ""
913 quoteDate = ""
914 result = append(result, line)
915 }
916 } else {
917 result = append(result, line)
918 }
919 }
920
921 // Handle any remaining quote block
922 if inQuote && len(quoteBlock) > 0 {
923 result = append(result, renderQuoteBox(quoteFrom, quoteDate, quoteBlock))
924 }
925
926 return strings.Join(result, "\n")
927}
928
929// parseDateForDisplay converts various date formats to DD:MM:YY HH:MM
930func parseDateForDisplay(dateStr string) string {
931 // Common date formats to try
932 formats := []string{
933 "Jan 2, 2006 at 3:04 PM",
934 "02:01:06 15:04",
935 "2006-01-02 15:04:05",
936 "Mon, 02 Jan 2006 15:04:05 -0700",
937 "Mon, 2 Jan 2006 15:04:05 -0700",
938 "2 Jan 2006 15:04:05",
939 "January 2, 2006 at 3:04 PM",
940 "Jan 2, 2006 3:04 PM",
941 time.RFC1123Z,
942 time.RFC1123,
943 time.RFC822Z,
944 time.RFC822,
945 }
946
947 for _, format := range formats {
948 if t, err := time.Parse(format, dateStr); err == nil {
949 return t.Format("02:01:06 15:04")
950 }
951 }
952
953 // Return original if parsing fails
954 return dateStr
955}
956
957// renderQuoteBox renders a quoted section in a styled box
958func renderQuoteBox(from, date string, lines []string) string {
959 // Build header with email on left and date on right
960 var header string
961 if from != "" || date != "" {
962 if from != "" && date != "" {
963 header = quoteHeaderStyle().Render(from + " " + date)
964 } else if from != "" {
965 header = quoteHeaderStyle().Render(from)
966 } else {
967 header = quoteHeaderStyle().Render(date)
968 }
969 }
970
971 // Join the quoted content
972 content := strings.Join(lines, "\n")
973
974 // Build the box content
975 var boxContent string
976 if header != "" {
977 boxContent = header + "\n\n" + content
978 } else {
979 boxContent = content
980 }
981
982 return quoteBoxStyle().Render(boxContent)
983}