Skip to content

Commit cceb8a7

Browse files
committed
Read tables back as Markdown instead of smearing their cells
HTMLToMarkdown had no table handling: <table> markup survived every pass untouched until the final tag-stripping regex deleted the tags and ran the cell text together. Display of any table-bearing message, comment, or to-do description came out as one smeared line, and the TUI in-place editors had to refuse table-bearing content wholesale to avoid destroying it on resubmit. Convert tables to GFM pipe tables instead. A new pass runs while row and cell tags are still intact: each <table> block is extracted (BC3 rich text is sanitized editor output — always flat editor-authored grids, so a non-greedy block match is safe), rows and cells are pulled out by regex, and the block is emitted as a pipe table. The first row is the header whether its cells are <th> or <td> (GFM has no headerless tables); align attributes — exactly what MarkdownToHTML emits for GFM column alignment — map back to :--- / :---: / ---: markers; the widest row sizes the table, with narrower rows padded, so no row is ever truncated. Cell content runs through the same inline conversions as body text (bold, italic, code, links, strikethrough, mentions, attachments) and block boundaries collapse to spaces. Escaping is GFM-exact: pipes escape as \| and literal backslashes double — GFM processes escapes left to right, so a lone \ before an escaped pipe would swallow its backslash and turn the pipe back into a delimiter. Code spans pass through as placeholders since backslashes are literal inside code; only their pipes are escaped. Cell entities are fully decoded before escaping — an encoded pipe is still a pipe, and goldmark would decode &#124; on the next render — and the emitted tables are parked behind placeholders until HTMLToMarkdown's document-level unescape pass has run, so nothing double-decodes. A goldmark-backed test proves the parsed cell content survives the full HTML → Markdown → HTML cycle (backslash-pipe text, code spans with pipes and backslashes, entity-encoded pipes and backslashes in text and code, pipes in link destinations, adjacent tables), and pipe tables round-trip byte-identical through MarkdownToHTML → HTMLToMarkdown, alignment and the #648 blank-line separator included. Shapes GFM can't represent still display, best-effort — colspan/rowspan cells emit as ordinary cells, a merged grid displaying better flattened than smeared — but editing them stays blocked: the blanket HasTableHTML gate on the three TUI in-place editors is replaced by HasComplexTableHTML, which fails closed on merged cells, captions, nested tables, attachments/images or block elements inside the table, cells spanning multiple paragraphs or lines, a table nested in a blockquote or list, unclosed tables, and tables the converter can't extract a grid from (they'd otherwise vanish with their content) — checking every table in the content, not just the first. Mentions are the one rich element cells may keep: they convert to **@name** exactly as they do in body text. Simple grids open for editing like any other content. The mention-conversion closure moves to a named mentionMarkdown function so cell conversion can reuse it; behavior is unchanged. Editing simple tables in the todos view requires the composer Reset fix (previous commit): without it, Reset dropped the description composer to single-line mode and SetValue flattened the freshly-converted pipe table. The todos test asserts the exact multiline table to prove the pairing.
1 parent f23a178 commit cceb8a7

7 files changed

Lines changed: 608 additions & 69 deletions

File tree

‎internal/richtext/richtext.go‎

Lines changed: 276 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,23 @@ func HTMLToMarkdown(html string) string {
707707
return convertCodeBlockHTML(s) + "\n\n"
708708
})
709709

710+
// Tables — convert to GFM pipe tables while row and cell tags are still
711+
// intact. Must run before the paragraph, line-break, and tag-stripping
712+
// passes below, which would otherwise smear cell text together. The
713+
// emitted Markdown is parked behind placeholders until every later pass
714+
// has run: cell text is fully entity-decoded and escaped, so the
715+
// document-level unescape would double-decode it (and could conjure
716+
// unescaped pipes out of encoded ones).
717+
var tables []string
718+
html = reTableBlock.ReplaceAllStringFunc(html, func(s string) string {
719+
md := convertTableHTML(s)
720+
if md == "" {
721+
return "\n\n"
722+
}
723+
tables = append(tables, md)
724+
return "\x00tbl" + strconv.Itoa(len(tables)-1) + "\x00\n\n"
725+
})
726+
710727
// Lists — use balanced-tag replacement to handle nesting correctly.
711728
html = replaceBalancedListBlocks(html)
712729

@@ -745,32 +762,7 @@ func HTMLToMarkdown(html string) string {
745762
html = reHTMLStrike.ReplaceAllString(html, "~~$1~~")
746763

747764
// @-mentions: extract display text, render as bold (must fire before general attachment regex)
748-
html = reMentionAttachment.ReplaceAllStringFunc(html, func(s string) string {
749-
inner := ""
750-
if match := reMentionAttachment.FindStringSubmatch(s); len(match) >= 2 {
751-
inner = match[1]
752-
}
753-
754-
name := ""
755-
if match := reMentionFigcaption.FindStringSubmatch(inner); len(match) >= 2 {
756-
name = strings.TrimSpace(unescapeHTML(reStripTags.ReplaceAllString(match[1], "")))
757-
}
758-
if name == "" {
759-
if match := reMentionImgAlt.FindStringSubmatch(inner); len(match) >= 2 {
760-
name = strings.TrimSpace(unescapeHTML(match[1]))
761-
}
762-
}
763-
if name == "" {
764-
name = strings.TrimSpace(unescapeHTML(reStripTags.ReplaceAllString(inner, "")))
765-
}
766-
if name == "" {
767-
name = "mention"
768-
}
769-
if !strings.HasPrefix(name, "@") {
770-
name = "@" + name
771-
}
772-
return "**" + name + "**"
773-
})
765+
html = reMentionAttachment.ReplaceAllStringFunc(html, mentionMarkdown)
774766

775767
// Basecamp attachments: <bc-attachment ... filename="report.pdf"> → 📎 report.pdf
776768
html = reAttachment.ReplaceAllString(html, "\n📎 $1\n")
@@ -788,9 +780,179 @@ func HTMLToMarkdown(html string) string {
788780
// Clean up multiple newlines
789781
html = reMultiNewline.ReplaceAllString(html, "\n\n")
790782

783+
// Restore the parked tables now that no pass can touch their content.
784+
for i, table := range tables {
785+
html = strings.Replace(html, "\x00tbl"+strconv.Itoa(i)+"\x00", table, 1)
786+
}
787+
791788
return strings.TrimSpace(html)
792789
}
793790

791+
// mentionMarkdown converts one <bc-attachment> mention element to bold
792+
// Markdown, extracting the display name from the figcaption, the image alt,
793+
// or the remaining text, in that order.
794+
func mentionMarkdown(s string) string {
795+
inner := ""
796+
if match := reMentionAttachment.FindStringSubmatch(s); len(match) >= 2 {
797+
inner = match[1]
798+
}
799+
800+
name := ""
801+
if match := reMentionFigcaption.FindStringSubmatch(inner); len(match) >= 2 {
802+
name = strings.TrimSpace(unescapeHTML(reStripTags.ReplaceAllString(match[1], "")))
803+
}
804+
if name == "" {
805+
if match := reMentionImgAlt.FindStringSubmatch(inner); len(match) >= 2 {
806+
name = strings.TrimSpace(unescapeHTML(match[1]))
807+
}
808+
}
809+
if name == "" {
810+
name = strings.TrimSpace(unescapeHTML(reStripTags.ReplaceAllString(inner, "")))
811+
}
812+
if name == "" {
813+
name = "mention"
814+
}
815+
if !strings.HasPrefix(name, "@") {
816+
name = "@" + name
817+
}
818+
return "**" + name + "**"
819+
}
820+
821+
// Pre-compiled regexes for HTML table conversion. BC3 rich text is sanitized
822+
// editor output, not arbitrary email HTML: tables are always flat
823+
// editor-authored grids (no nesting, no layout tables), so a non-greedy block
824+
// match is safe and every <table> converts — none are skipped.
825+
var (
826+
reTableBlock = regexp.MustCompile(`(?is)<table(?:\s[^>]*)?>.*?</table\s*>`)
827+
reTableRowHTML = regexp.MustCompile(`(?is)<tr(?:\s[^>]*)?>(.*?)</tr\s*>`)
828+
reTableCellHTML = regexp.MustCompile(`(?is)<t[hd]((?:\s[^>]*)?)>(.*?)</t[hd]\s*>`)
829+
reTableCellAlign = regexp.MustCompile(`(?i)\balign="(left|center|right)"`)
830+
reWhitespaceRun = regexp.MustCompile(`\s+`)
831+
)
832+
833+
// convertTableHTML converts one <table> block to a GFM pipe table. The first
834+
// row is the header whether its cells are <th> or <td> (GFM has no headerless
835+
// tables), with its align attributes — what MarkdownToHTML emits for GFM
836+
// column alignment — mapped back to :--- / :---: / ---: markers. The widest
837+
// row sizes the table and narrower rows are padded with empty cells. Cells
838+
// carrying colspan/rowspan emit as ordinary cells: a merged grid displays
839+
// better flattened than smeared, and editing such tables stays guarded by
840+
// HasComplexTableHTML.
841+
func convertTableHTML(table string) string {
842+
var rows [][]string
843+
var aligns []string
844+
for _, row := range reTableRowHTML.FindAllStringSubmatch(table, -1) {
845+
cells := reTableCellHTML.FindAllStringSubmatch(row[1], -1)
846+
if len(cells) == 0 {
847+
continue
848+
}
849+
texts := make([]string, 0, len(cells))
850+
for _, cell := range cells {
851+
texts = append(texts, cellMarkdown(cell[2]))
852+
}
853+
if rows == nil {
854+
aligns = make([]string, 0, len(cells))
855+
for _, cell := range cells {
856+
align := ""
857+
if m := reTableCellAlign.FindStringSubmatch(cell[1]); m != nil {
858+
align = strings.ToLower(m[1])
859+
}
860+
aligns = append(aligns, align)
861+
}
862+
}
863+
rows = append(rows, texts)
864+
}
865+
if rows == nil {
866+
return ""
867+
}
868+
869+
// Size the table to its widest row, not just the header: truncating a
870+
// wider later row would silently drop cell data.
871+
width := 0
872+
for _, row := range rows {
873+
width = max(width, len(row))
874+
}
875+
separators := make([]string, width)
876+
for i := range separators {
877+
switch {
878+
case i < len(aligns) && aligns[i] == "left":
879+
separators[i] = ":---"
880+
case i < len(aligns) && aligns[i] == "center":
881+
separators[i] = ":---:"
882+
case i < len(aligns) && aligns[i] == "right":
883+
separators[i] = "---:"
884+
default:
885+
separators[i] = "---"
886+
}
887+
}
888+
889+
pipeRow := func(cells []string) string {
890+
for len(cells) < width {
891+
cells = append(cells, "")
892+
}
893+
return "| " + strings.Join(cells, " | ") + " |"
894+
}
895+
lines := make([]string, 0, len(rows)+1)
896+
lines = append(lines, pipeRow(rows[0]), pipeRow(separators))
897+
for _, row := range rows[1:] {
898+
lines = append(lines, pipeRow(row))
899+
}
900+
return strings.Join(lines, "\n")
901+
}
902+
903+
// reCellEscape matches the characters that must be backslash-escaped in cell
904+
// text. Pipes would split the row. Backslashes must double: GFM processes
905+
// escapes left to right, so a lone literal `\` before an escaped pipe would
906+
// swallow its backslash and turn the pipe back into a delimiter.
907+
var reCellEscape = regexp.MustCompile(`[\\|]`)
908+
909+
// cellMarkdown converts a table cell's inner HTML to single-line Markdown:
910+
// inline elements convert as usual, block boundaries (<p>, <br>, and any
911+
// other leftover tag) collapse to spaces, and backslashes and pipes are
912+
// escaped so cell text can't break the row. Code spans pass through as
913+
// placeholders: backslashes are literal inside code, so only their pipes are
914+
// escaped (GFM's row splitting honors `\|` inside code spans). Entities are
915+
// fully decoded here, after tags are gone and before escaping — escaping
916+
// must see the real characters (an encoded pipe is still a pipe, and
917+
// goldmark would decode it on the next render) — which is why HTMLToMarkdown
918+
// parks the emitted table out of reach of its document-level unescape pass.
919+
func cellMarkdown(inner string) string {
920+
s := reMentionAttachment.ReplaceAllStringFunc(inner, mentionMarkdown)
921+
922+
var codes []string
923+
s = reHTMLCode.ReplaceAllStringFunc(s, func(m string) string {
924+
codes = append(codes, reHTMLCode.FindStringSubmatch(m)[1])
925+
return "\x00" + strconv.Itoa(len(codes)-1) + "\x00"
926+
})
927+
928+
s = reHTMLStrong.ReplaceAllString(s, "**$1**")
929+
s = reHTMLB.ReplaceAllString(s, "**$1**")
930+
s = reHTMLEm.ReplaceAllString(s, "*$1*")
931+
s = reHTMLI.ReplaceAllString(s, "*$1*")
932+
s = reHTMLLink.ReplaceAllString(s, "[$2]($1)")
933+
s = reHTMLImgSA.ReplaceAllString(s, "![$2]($1)")
934+
s = reHTMLImgAS.ReplaceAllString(s, "![$1]($2)")
935+
s = reHTMLImgS.ReplaceAllString(s, "![]($1)")
936+
s = reHTMLDel.ReplaceAllString(s, "~~$1~~")
937+
s = reHTMLS.ReplaceAllString(s, "~~$1~~")
938+
s = reHTMLStrike.ReplaceAllString(s, "~~$1~~")
939+
s = reAttachment.ReplaceAllString(s, "📎 $1")
940+
s = reAttachClose.ReplaceAllString(s, "")
941+
s = reAttachNoFile.ReplaceAllString(s, "📎 attachment")
942+
s = reStripTags.ReplaceAllString(s, " ")
943+
s = strings.ReplaceAll(html.UnescapeString(s), "\u00a0", " ")
944+
s = reCellEscape.ReplaceAllString(s, `\${0}`)
945+
s = strings.TrimSpace(reWhitespaceRun.ReplaceAllString(s, " "))
946+
947+
for i, code := range codes {
948+
code = reWhitespaceRun.ReplaceAllString(strings.TrimSpace(code), " ")
949+
code = html.UnescapeString(code)
950+
code = strings.ReplaceAll(code, "|", `\|`)
951+
s = strings.Replace(s, "\x00"+strconv.Itoa(i)+"\x00", "`"+code+"`", 1)
952+
}
953+
return s
954+
}
955+
794956
// reBRLine matches a <br> tag followed by an optional newline, collapsing
795957
// the pair to a single \n. goldmark's hard-break output is <br>\n; Trix API
796958
// content may have standalone <br>.
@@ -1506,15 +1668,96 @@ func IsHTML(s string) bool {
15061668
// reTableHTML matches a real <table> tag — with attributes (`<table …>`), bare
15071669
// (`<table>`), or self-closing (`<table/>`) — distinct from the Markdown table
15081670
// detector. The trailing class requires a boundary after the name so longer
1509-
// tags like <tablefoo> don't match. Used to gate the fail-closed TUI edit paths.
1671+
// tags like <tablefoo> don't match.
15101672
var reTableHTML = regexp.MustCompile(`(?i)<table[\s/>]`)
15111673

1512-
// HasTableHTML reports whether s contains an HTML table element. The TUI in-place
1513-
// editors use this to refuse table-bearing content: HTMLToMarkdown has no table
1514-
// handling and would strip the structure, so those edits fail closed rather than
1515-
// silently flatten the table on resubmit.
1516-
func HasTableHTML(s string) bool {
1517-
return reTableHTML.MatchString(s)
1674+
// reTableClose matches a closing </table> tag.
1675+
var reTableClose = regexp.MustCompile(`(?i)</table\s*>`)
1676+
1677+
// Complexity markers within a table block: merged cells; block elements,
1678+
// captions, attachments, and images anywhere inside the table; and cells
1679+
// whose content spans multiple paragraphs or lines. All are shapes a GFM pipe
1680+
// table cannot represent — cellMarkdown flattens them to single-line text for
1681+
// display, so resubmitting that text would lose the structure.
1682+
var (
1683+
reTableMergedCell = regexp.MustCompile(`(?i)\b(?:colspan|rowspan)\s*=`)
1684+
reTableComplexInner = regexp.MustCompile(`(?i)<(?:ul|ol|pre|blockquote|h[1-6]|caption|figure|img|bc-attachment)[\s/>]`)
1685+
)
1686+
1687+
// reTableContext matches the tags whose nesting decides whether a table sits
1688+
// inside another block container (a blockquote or a list item). GFM pipe
1689+
// tables are top-level only, so a table nested in either cannot round-trip.
1690+
var reTableContext = regexp.MustCompile(`(?i)<(/?)(blockquote|li|table)[\s/>]`)
1691+
1692+
// tableHasGrid reports whether a table block contains at least one row with
1693+
// at least one cell — the minimum structure convertTableHTML can emit.
1694+
func tableHasGrid(block string) bool {
1695+
for _, row := range reTableRowHTML.FindAllStringSubmatch(block, -1) {
1696+
if reTableCellHTML.MatchString(row[1]) {
1697+
return true
1698+
}
1699+
}
1700+
return false
1701+
}
1702+
1703+
// HasComplexTableHTML reports whether s contains a table that HTMLToMarkdown
1704+
// cannot round-trip as a GFM pipe table: merged cells (colspan/rowspan), a
1705+
// nested table, block content inside a cell, or the table itself nested in a
1706+
// blockquote or list. The TUI in-place editors use this to gate edits —
1707+
// HTMLToMarkdown still converts such tables for display, best-effort, but an
1708+
// edit-and-resubmit would flatten the structure, so those edits fail closed.
1709+
// Simple grids round-trip cleanly and stay editable.
1710+
func HasComplexTableHTML(s string) bool {
1711+
depth := 0
1712+
for _, m := range reTableContext.FindAllStringSubmatch(s, -1) {
1713+
closing := m[1] == "/"
1714+
if strings.EqualFold(m[2], "table") {
1715+
if !closing && depth > 0 {
1716+
return true
1717+
}
1718+
} else if closing {
1719+
if depth > 0 {
1720+
depth--
1721+
}
1722+
} else {
1723+
depth++
1724+
}
1725+
}
1726+
1727+
for {
1728+
open := reTableHTML.FindStringIndex(s)
1729+
if open == nil {
1730+
return false
1731+
}
1732+
rest := s[open[1]:]
1733+
closeTag := reTableClose.FindStringIndex(rest)
1734+
// No closing tag: the converter can't parse the table, so nothing
1735+
// about the edit loop is safe. Fail closed.
1736+
if closeTag == nil {
1737+
return true
1738+
}
1739+
block := rest[:closeTag[0]]
1740+
if reTableHTML.MatchString(block) || reTableMergedCell.MatchString(block) {
1741+
return true
1742+
}
1743+
// A table the converter can't extract a grid from vanishes from the
1744+
// Markdown; if it holds any text, that vanishing is data loss.
1745+
if !tableHasGrid(block) && strings.TrimSpace(reStripTags.ReplaceAllString(block, "")) != "" {
1746+
return true
1747+
}
1748+
// Mentions are the one rich element cells may keep: they convert to
1749+
// **@Name** exactly as they do in body text. Strip them before
1750+
// scanning for content the conversion would lose.
1751+
if reTableComplexInner.MatchString(reMentionAttachment.ReplaceAllString(block, "")) {
1752+
return true
1753+
}
1754+
for _, cell := range reTableCellHTML.FindAllStringSubmatch(block, -1) {
1755+
if reBR.MatchString(cell[2]) || len(reOpeningP.FindAllString(cell[2], -1)) > 1 {
1756+
return true
1757+
}
1758+
}
1759+
s = rest[closeTag[1]:]
1760+
}
15181761
}
15191762

15201763
func isEscapedAt(s string, pos int) bool {

0 commit comments

Comments
 (0)