package document
import (
"archive/zip"
"bytes"
"encoding/xml"
"fmt"
"strings"
"github.com/gomarkdown/markdown/ast"
)
const (
nsMain = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
nsRel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
nsPkg = "http://schemas.openxmlformats.org/package/2006/relationships"
relStyles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
relNumbering = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"
relHyperlink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
relDocument = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
bulletNumID = 1
maxListLvl = 8
)
// DOCX renders Markdown as a Word document (.docx). It is built directly as zipped OOXML.
func DOCX(md []byte) ([]byte, error) {
b := &docxBuilder{nextNum: bulletNumID + 1}
b.blocks(NewParser().Parse(md).GetChildren(), blockCtx{})
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
parts := []struct{ name, data string }{
{"[Content_Types].xml", contentTypesXML},
{"_rels/.rels", rootRelsXML},
{"word/document.xml", b.documentXML()},
{"word/styles.xml", stylesXML},
{"word/numbering.xml", b.numberingXML()},
{"word/_rels/document.xml.rels", b.documentRelsXML()},
}
for _, p := range parts {
w, err := zw.Create(p.name)
if err != nil {
return nil, fmt.Errorf("failed to write docx part %s: %w", p.name, err)
}
if _, err := w.Write([]byte(xml.Header + p.data)); err != nil {
return nil, fmt.Errorf("failed to write docx part %s: %w", p.name, err)
}
}
if err := zw.Close(); err != nil {
return nil, fmt.Errorf("failed to finish docx: %w", err)
}
return buf.Bytes(), nil
}
// blockCtx carries the list and quote nesting while walking block nodes.
type blockCtx struct {
listLevel int // 0 when not in a list, otherwise the nesting depth (1-based)
numID int // numbering instance of the enclosing list
quote bool
// bullet holds a list item's marker until the first paragraph consumes it.
bullet *bool
}
type docxBuilder struct {
body strings.Builder
links []string // hyperlink targets, relationship ids are rId10+index
ordered []int // numbering ids created for ordered lists
nextNum int
}
func (b *docxBuilder) blocks(nodes []ast.Node, ctx blockCtx) {
var inline []ast.Node
flush := func() {
if len(inline) > 0 {
b.paragraph(b.runs(inline, runStyle{}), ctx)
inline = nil
}
}
for _, n := range nodes {
switch n := n.(type) {
case *ast.Paragraph:
flush()
// gomarkdown nests fenced code blocks and lists inside paragraphs.
b.blocks(n.Children, ctx)
case *ast.Heading:
flush()
level := min(max(n.Level, 1), 6)
fmt.Fprintf(&b.body, `%s`,
level, b.runs(n.Children, runStyle{}))
case *ast.List:
flush()
b.list(n, ctx)
case *ast.CodeBlock:
flush()
b.codeBlock(string(n.Literal), ctx)
case *ast.BlockQuote:
flush()
q := ctx
q.quote = true
b.blocks(n.Children, q)
case *ast.HorizontalRule:
flush()
b.body.WriteString(``)
case *ast.Table:
flush()
b.table(n)
case *ast.HTMLBlock:
flush()
default:
inline = append(inline, n)
}
}
flush()
}
// paragraph writes runs as one paragraph, applying list and quote formatting from ctx.
func (b *docxBuilder) paragraph(runs string, ctx blockCtx) {
if runs == "" {
return
}
var ppr string
switch {
case ctx.listLevel > 0 && ctx.bullet != nil && *ctx.bullet:
*ctx.bullet = false
ppr = fmt.Sprintf(``,
min(ctx.listLevel-1, maxListLvl), ctx.numID)
case ctx.listLevel > 0:
ppr = fmt.Sprintf(``, 360*ctx.listLevel+360)
case ctx.quote:
ppr = ``
}
if ppr != "" {
ppr = "" + ppr + ""
}
b.body.WriteString("" + ppr + runs + "")
}
func (b *docxBuilder) list(l *ast.List, ctx blockCtx) {
numID := bulletNumID
if l.ListFlags&ast.ListTypeOrdered != 0 {
numID = b.nextNum
b.nextNum++
b.ordered = append(b.ordered, numID)
}
for _, item := range l.Children {
marker := true
inner := ctx
inner.listLevel++
inner.numID = numID
inner.bullet = &marker
b.blocks(item.GetChildren(), inner)
}
}
func (b *docxBuilder) codeBlock(code string, ctx blockCtx) {
indent := ""
if ctx.listLevel > 0 {
indent = fmt.Sprintf(``, 360*ctx.listLevel+360)
}
code = strings.Trim(code, "\n")
lines := strings.Split(code, "\n")
for i, line := range lines {
spacing := ""
if i == len(lines)-1 {
spacing = ``
}
b.body.WriteString(`` + spacing + indent + ``)
b.body.WriteString(`` + escape(strings.ReplaceAll(line, "\t", " ")) + ``)
}
}
func (b *docxBuilder) table(t *ast.Table) {
b.body.WriteString(``)
for _, edge := range []string{"top", "left", "bottom", "right", "insideH", "insideV"} {
fmt.Fprintf(&b.body, ``, edge)
}
b.body.WriteString(``)
var walk func(nodes []ast.Node, header bool)
walk = func(nodes []ast.Node, header bool) {
for _, n := range nodes {
switch n := n.(type) {
case *ast.TableHeader:
walk(n.Children, true)
case *ast.TableBody, *ast.TableFooter:
walk(n.GetChildren(), false)
case *ast.TableRow:
b.tableRow(n, header)
}
}
}
walk(t.Children, false)
// Word requires a paragraph after a table, and it also separates it from what follows.
b.body.WriteString(``)
}
func (b *docxBuilder) tableRow(row *ast.TableRow, header bool) {
b.body.WriteString("")
for _, cell := range row.Children {
tcPr := ""
if header {
tcPr = ``
}
runs := b.runs(cell.GetChildren(), runStyle{bold: header})
b.body.WriteString("" + tcPr + "" + runs + "")
}
b.body.WriteString("")
}
// runStyle describes the inline formatting in effect.
type runStyle struct {
bold, italic, code bool
link bool
}
func (b *docxBuilder) runs(nodes []ast.Node, st runStyle) string {
var out strings.Builder
for _, n := range nodes {
switch n := n.(type) {
case *ast.Text:
out.WriteString(textRun(string(n.Literal), st))
case *ast.Code:
s := st
s.code = true
out.WriteString(textRun(string(n.Literal), s))
case *ast.Emph:
s := st
s.italic = true
out.WriteString(b.runs(n.Children, s))
case *ast.Strong:
s := st
s.bold = true
out.WriteString(b.runs(n.Children, s))
case *ast.Del:
out.WriteString(b.runs(n.Children, st))
case *ast.Link:
s := st
s.link = true
inner := b.runs(n.Children, s)
if dest := string(n.Destination); dest != "" {
b.links = append(b.links, dest)
inner = fmt.Sprintf(`%s`, linkRelBase+len(b.links)-1, inner)
}
out.WriteString(inner)
case *ast.Image:
s := st
s.italic = true
out.WriteString(textRun("[image: ", s) + b.runs(n.Children, s) + textRun("]", s))
case *ast.Softbreak:
out.WriteString(textRun(" ", st))
case *ast.Hardbreak:
out.WriteString(``)
case *ast.HTMLSpan:
default:
out.WriteString(b.runs(n.GetChildren(), st))
}
}
return out.String()
}
func textRun(text string, st runStyle) string {
if text == "" {
return ""
}
var props string
if st.code {
props += ``
}
if st.bold {
props += ``
}
if st.italic {
props += ``
}
if st.link {
props += ``
}
if props != "" {
props = "" + props + ""
}
text = strings.NewReplacer("\r", "", "\n", " ").Replace(text)
return `` + props + `` + escape(text) + ``
}
func escape(s string) string {
var buf bytes.Buffer
_ = xml.EscapeText(&buf, []byte(s))
return buf.String()
}
// linkRelBase is the first relationship id used for hyperlinks; lower ids are fixed parts.
const linkRelBase = 10
func (b *docxBuilder) documentXML() string {
return fmt.Sprintf(`%s`+
``,
nsMain, nsRel, b.body.String())
}
func (b *docxBuilder) documentRelsXML() string {
var s strings.Builder
fmt.Fprintf(&s, ``, nsPkg)
fmt.Fprintf(&s, ``, relStyles)
fmt.Fprintf(&s, ``, relNumbering)
for i, target := range b.links {
fmt.Fprintf(&s, ``,
linkRelBase+i, relHyperlink, escape(target))
}
s.WriteString(``)
return s.String()
}
// numberingXML defines one bullet list and one decimal list, each with nine indent levels.
// Every ordered list gets its own instance so numbering restarts at 1.
func (b *docxBuilder) numberingXML() string {
level := func(i int, format, text string) string {
return fmt.Sprintf(``+
``,
i, format, text, 720*(i+1))
}
var bullets, decimals strings.Builder
for i := 0; i <= maxListLvl; i++ {
bullets.WriteString(level(i, "bullet", "•"))
decimals.WriteString(level(i, "decimal", fmt.Sprintf("%%%d.", i+1)))
}
var s strings.Builder
fmt.Fprintf(&s, ``, nsMain)
s.WriteString(`` + bullets.String() + ``)
s.WriteString(`` + decimals.String() + ``)
fmt.Fprintf(&s, ``, bulletNumID)
for _, id := range b.ordered {
fmt.Fprintf(&s, ``+
``, id)
}
s.WriteString(``)
return s.String()
}
const contentTypesXML = `` +
`` +
`` +
`` +
`` +
`` +
``
const rootRelsXML = `` +
`` +
``
func headingStyle(level, halfPoints int) string {
return fmt.Sprintf(``+
``+
``, level, level, level-1, halfPoints)
}
var stylesXML = `` +
`` +
`` +
`` +
headingStyle(1, 48) + headingStyle(2, 40) + headingStyle(3, 32) +
headingStyle(4, 28) + headingStyle(5, 24) + headingStyle(6, 22) +
`` +
`` +
`` +
`` +
`` +
`` +
`` +
`` +
``