RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(agent): Render Markdown tables in DOCX exports (#21274)
Sbaaoui Idrissb6252efd5806
diff --git a/internal/agent/component/io/docx_writer.go b/internal/agent/component/io/docx_writer.goindex c70ce50adf..0eec48c52c 100644--- a/internal/agent/component/io/docx_writer.go+++ b/internal/agent/component/io/docx_writer.go@@ -26,10 +26,7 @@// - //go:embed — the static XML parts (Content_Types, _rels, styles)//// The output is a Word-compatible .docx. The XML is intentionally-// minimal: a single font, a single style, and a flat list of-// paragraphs. Tables / images / lists are future polish items; the-// test suite (see docx_writer_test.go) verifies the ZIP magic, the-// embedded document.xml content, and the XML-escape+// minimal: a single font, a single style, paragraphs, and native tables.package ioimport (@@ -40,6 +37,12 @@ import ("html""strings""text/template"++ "github.com/yuin/goldmark"+ "github.com/yuin/goldmark/ast"+ "github.com/yuin/goldmark/extension"+ tableast "github.com/yuin/goldmark/extension/ast"+ gmtext "github.com/yuin/goldmark/text")//go:embed templates/content_types.xml@@ -71,7 +74,7 @@ type DOCXOptions struct {// DOCXOptions and Document flatten into this when the writer is// invoked.type docModel struct {- Paragraphs []string+ Blocks []docxBlockHeaderText stringFooterText stringWatermarkText string@@ -85,6 +88,11 @@ type docModel struct {Timestamp string}+type docxBlock struct {+ Text string+ Rows [][]string+}+// tmplFuncs registers the {{xml}} helper used to escape user content// before it lands in the document body. text/template doesn't have a// template.HTML type, so we return a string and rely on the template@@ -100,9 +108,7 @@ var tmplFuncs = template.FuncMap{//// Layout strategy (P4)://-// - One paragraph per non-empty line in content.-// - Empty lines are preserved as empty paragraphs (so the document's-// vertical rhythm matches the source).+// - Paragraphs and Markdown tables retain their source order.// - The header carries a centered title and (optionally) a VML// watermark shape.// - The footer carries the footer text and (optionally) a page-number@@ -118,7 +124,7 @@ func WriteDOCX(content string, opts DOCXOptions) ([]byte, error) {}model := docModel{- Paragraphs: splitParagraphs(content),+ Blocks: markdownDOCXBlocks(content),HeaderText: opts.HeaderText,FooterText: opts.FooterText,WatermarkText: opts.WatermarkText,@@ -197,6 +203,46 @@ func WriteDOCX(content string, opts DOCXOptions) ([]byte, error) {return buf.Bytes(), nil}+func markdownDOCXBlocks(content string) []docxBlock {+ content = normalizeMarkdownTableSeparators(content)+ source := []byte(content)+ document := goldmark.New(goldmark.WithExtensions(extension.Table)).Parser().Parse(gmtext.NewReader(source))+ blocks := make([]docxBlock, 0, document.ChildCount())+ for node := document.FirstChild(); node != nil; node = node.NextSibling() {+ switch n := node.(type) {+ case *ast.FencedCodeBlock:+ text := rawPDFBlockText(n, source)+ if strings.EqualFold(string(n.Language(source)), "markdown") || strings.EqualFold(string(n.Language(source)), "md") {+ blocks = append(blocks, markdownDOCXBlocks(text)...)+ } else {+ info := ""+ if n.Info != nil {+ info = string(n.Info.Text(source))+ }+ blocks = append(blocks, docxBlock{Text: "```" + info + "\n" + text + "\n```"})+ }+ case *tableast.Table:+ rows := make([][]string, 0, n.ChildCount())+ for row := n.FirstChild(); row != nil; row = row.NextSibling() {+ cells := make([]string, 0, row.ChildCount())+ for cell := row.FirstChild(); cell != nil; cell = cell.NextSibling() {+ cells = append(cells, inlinePDFText(cell, source))+ }+ rows = append(rows, cells)+ }+ blocks = append(blocks, docxBlock{Rows: rows})+ default:+ if text := rawPDFBlockText(n, source); text != "" || node == document.FirstChild() {+ blocks = append(blocks, docxBlock{Text: text})+ }+ }+ }+ if len(blocks) == 0 {+ return []docxBlock{{}}+ }+ return blocks+}+// writeZipFile writes a static []byte payload as a file inside the zip.func writeZipFile(zw *zip.Writer, name string, data []byte) error {w, err := zw.Create(name)@@ -222,22 +268,6 @@ func writeZipTmpl(zw *zip.Writer, name string, tmpl *template.Template, model anreturn nil}-// splitParagraphs turns the source content into a list of paragraph-// strings. Empty lines are preserved as empty strings so the rendered-// document's vertical rhythm matches the source.-func splitParagraphs(content string) []string {- if content == "" {- return []string{""}- }- lines := strings.Split(content, "\n")- out := make([]string, 0, len(lines))- for _, l := range lines {- // Strip trailing \r for CRLF inputs.- out = append(out, strings.TrimRight(l, "\r"))- }- return out-}-// nowUTC returns a stable timestamp string for footer / watermark// metadata. Format: "2026-06-03T14:45:06Z" (RFC3339 in UTC).// The var is package-scoped so tests can override it.diff --git a/internal/agent/component/io/docx_writer_test.go b/internal/agent/component/io/docx_writer_test.goindex 76694fdf79..48921c6235 100644--- a/internal/agent/component/io/docx_writer_test.go+++ b/internal/agent/component/io/docx_writer_test.go@@ -19,6 +19,7 @@ package ioimport ("archive/zip""bytes"+ "encoding/xml""io""strings""testing"@@ -153,6 +154,71 @@ func TestDOCXWriter_EmptyContent(t *testing.T) {}}+func TestDOCXWriter_MarkdownTables(t *testing.T) {+ content := "Before table\n\n| A | B | C |\n| --- | --- | --- |\n| one | two | three |\n| 1 | 2 | 3 |\n\n" ++ "```markdown\n| X | Y | Z |\n| --- | --- | --- |\n| α & < | 二 | 3 |\n| x | y | z |\n```\n\n" ++ "| L | M | N |\n| --- | --- |\n| four | five | six |\n| 4 | 5 | 6 |\n\n" ++ "```text\n| not | a | table |\n| --- | --- | --- |\n```\nAfter table"+ doc, err := WriteDOCX(content, DOCXOptions{})+ if err != nil {+ t.Fatalf("WriteDOCX: %v", err)+ }+ zr, err := zip.NewReader(bytes.NewReader(doc), int64(len(doc)))+ if err != nil {+ t.Fatalf("zip.NewReader: %v", err)+ }+ body, ok := readZipFile(t, zr, "word/document.xml")+ if !ok {+ t.Fatal("word/document.xml missing")+ }+ decoder := xml.NewDecoder(strings.NewReader(body))+ var tables, rows, cells int+ var inCell bool+ var values []string+ for {+ tok, err := decoder.Token()+ if err != nil {+ if err == io.EOF {+ break+ }+ t.Fatalf("decode document.xml: %v", err)+ }+ switch token := tok.(type) {+ case xml.StartElement:+ switch token.Name.Local {+ case "tbl":+ tables+++ case "tr":+ rows+++ case "tc":+ cells+++ inCell = true+ }+ case xml.EndElement:+ if token.Name.Local == "tc" {+ inCell = false+ }+ case xml.CharData:+ if inCell && strings.TrimSpace(string(token)) != "" {+ values = append(values, strings.TrimSpace(string(token)))+ }+ }+ }+ if tables != 3 || rows != 9 || cells != 27 {+ t.Fatalf("DOCX table structure = %d tables, %d rows, %d cells; want 3, 9, 27", tables, rows, cells)+ }+ wantValues := []string{"A", "B", "C", "one", "two", "three", "1", "2", "3", "X", "Y", "Z", "α & <", "二", "3", "x", "y", "z", "L", "M", "N", "four", "five", "six", "4", "5", "6"}+ if strings.Join(values, "\x00") != strings.Join(wantValues, "\x00") {+ t.Errorf("table cells = %q, want %q", values, wantValues)+ }+ if strings.Index(body, "Before table") > strings.Index(body, "<w:tbl>") || strings.Index(body, "<w:tbl>") > strings.Index(body, "After table") {+ t.Error("table changed its order relative to surrounding paragraphs")+ }+ if !strings.Contains(body, "Before table") || !strings.Contains(body, "After table") || !strings.Contains(body, "```text\n| not | a | table |\n| --- | --- | --- |\n```") {+ t.Errorf("paragraph or non-Markdown code content changed: %s", truncate(body, 1200))+ }+}+// readZipFile returns the file body as a string, or ("", false) if the// file is not present.func readZipFile(t *testing.T, zr *zip.Reader, name string) (string, bool) {diff --git a/internal/agent/component/io/templates/document.xml.tmpl b/internal/agent/component/io/templates/document.xml.tmplindex 50ba528561..a7397243e0 100644--- a/internal/agent/component/io/templates/document.xml.tmpl+++ b/internal/agent/component/io/templates/document.xml.tmpl@@ -1,7 +1,7 @@<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>-{{range .Paragraphs}}<w:p><w:r><w:rPr><w:sz w:val="{{pt $.FontSize}}"/><w:szCs w:val="{{pt $.FontSize}}"/><w:rFonts w:ascii="{{$.FontFamily}}" w:eastAsia="{{$.FontFamily}}" w:hAnsi="{{$.FontFamily}}"/></w:rPr><w:t xml:space="preserve">{{xml .}}</w:t></w:r></w:p>+{{range .Blocks}}{{if .Rows}}<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/></w:tblPr>{{range .Rows}}<w:tr>{{range .}}<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr><w:p><w:r><w:rPr><w:sz w:val="{{pt $.FontSize}}"/><w:szCs w:val="{{pt $.FontSize}}"/><w:rFonts w:ascii="{{$.FontFamily}}" w:eastAsia="{{$.FontFamily}}" w:hAnsi="{{$.FontFamily}}"/></w:rPr><w:t xml:space="preserve">{{xml .}}</w:t></w:r></w:p></w:tc>{{end}}</w:tr>{{end}}</w:tbl>{{else}}<w:p><w:r><w:rPr><w:sz w:val="{{pt $.FontSize}}"/><w:szCs w:val="{{pt $.FontSize}}"/><w:rFonts w:ascii="{{$.FontFamily}}" w:eastAsia="{{$.FontFamily}}" w:hAnsi="{{$.FontFamily}}"/></w:rPr><w:t xml:space="preserve">{{xml .Text}}</w:t></w:r></w:p>{{end}}{{end}}<w:sectPr>{{if .HasHeader}}<w:headerReference w:type="default" r:id="rIdHeader1"/>{{end}}{{if .HasFooter}}<w:footerReference w:type="default" r:id="rIdFooter1"/>{{end}}