// Package docx is the font half of Docs' Word files: how a document's
// families are written into a .docx and read back out of one.
//
// Paul's default 5 (2026-10-24): Carlito is written as Calibri and
// Caladea as Cambria, the Office faces they are metric twins of, so a
// document breaks its lines in Word where it does here; every other
// family is named, not embedded; and on the way in Calibri becomes
// Carlito and Cambria Caladea. The names are internal/fonts' manifest
// (Docx.Name, and ByDocxName for the way back).
//
// Write is deliberately only what the font rulings need: paragraphs and
// headings, runs with their family, weight, slope and size, the document
// default in w:docDefaults and every family named in fontTable.xml.
// Lists, tables, images and links are not written yet, and nothing routes
// to Write. Import (read.go) is the reading half, used by the import page
// (spec ยง11.2 and implementation/google-drive-import.md).
package docx
import (
"archive/zip"
"bytes"
"encoding/xml"
"fmt"
"io"
"sort"
"strings"
"github.com/carlosframework/docs/internal/export"
"github.com/carlosframework/docs/internal/fonts"
)
// Write writes doc as a .docx.
func Write(doc export.Document) ([]byte, error) {
used := map[*fonts.Family]bool{fonts.Default: true}
var body strings.Builder
var walk func(nodes []export.Node)
walk = func(nodes []export.Node) {
for _, n := range nodes {
switch n.Type {
case "paragraph", "heading":
body.WriteString("")
if n.Type == "heading" {
level := n.Attrs.Level
if level < 1 || level > 6 {
level = 1
}
fmt.Fprintf(&body, ``, level)
}
for _, run := range n.Content {
if run.IsText() && run.Text != "" {
writeRun(&body, run, used)
}
}
body.WriteString("")
default:
walk(n.Content)
}
}
}
walk(doc.Root.Content)
families := make([]*fonts.Family, 0, len(used))
for f := range used {
families = append(families, f)
}
sort.Slice(families, func(i, j int) bool { return families[i].Index < families[j].Index })
var buf bytes.Buffer
z := zip.NewWriter(&buf)
files := []struct{ name, body string }{
{"[Content_Types].xml", contentTypes},
{"_rels/.rels", rootRels},
{"word/_rels/document.xml.rels", documentRels},
{"word/document.xml", `` +
`` + body.String() + ``},
{"word/styles.xml", styles()},
{"word/fontTable.xml", fontTable(families)},
}
for _, f := range files {
w, err := z.Create(f.name)
if err != nil {
return nil, err
}
if _, err := io.WriteString(w, f.body); err != nil {
return nil, err
}
}
if err := z.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func writeRun(b *strings.Builder, run export.Node, used map[*fonts.Family]bool) {
names := make([]string, len(run.Marks))
for i, m := range run.Marks {
names[i] = m.Type
}
family := fonts.ForMarks(names)
if run.Has("code") {
family = fonts.Code
}
used[family] = true
var props strings.Builder
if family != fonts.Default {
n := xmlAttr(family.Docx.Name)
fmt.Fprintf(&props, ``, n, n, n, n)
}
if run.Has("strong") {
props.WriteString("")
}
if run.Has("em") {
props.WriteString("")
}
for _, mark := range export.SizeMarks() {
if run.Has(mark) {
if pt, ok := export.SizePt(mark); ok {
fmt.Fprintf(&props, ``, int(pt*2))
}
break
}
}
b.WriteString("")
if props.Len() > 0 {
b.WriteString("" + props.String() + "")
}
b.WriteString(`` + xmlText(run.Text) + "")
}
// styles puts the default family in w:docDefaults, where Word and an
// importer read a document's own default from, at Docs' 12pt body.
func styles() string {
n := xmlAttr(fonts.Default.Docx.Name)
var b strings.Builder
b.WriteString(``)
fmt.Fprintf(&b, ``+
``, n, n, n, n, int(export.BodySizePt*2), int(export.BodySizePt*2))
b.WriteString(``)
for level := 1; level <= 6; level++ {
fmt.Fprintf(&b, ``+
``, level, level)
}
b.WriteString(``)
return b.String()
}
// fontTable names every family the document uses, with what Word needs
// to substitute sensibly when it does not have one: its generic family,
// pitch, panose and nearest Office face.
func fontTable(families []*fonts.Family) string {
var b strings.Builder
b.WriteString(``)
for _, f := range families {
fmt.Fprintf(&b, ``, xmlAttr(f.Docx.Name))
if f.Docx.AltName != "" {
fmt.Fprintf(&b, ``, xmlAttr(f.Docx.AltName))
}
if f.Docx.Panose != "" {
fmt.Fprintf(&b, ``, xmlAttr(f.Docx.Panose))
}
fmt.Fprintf(&b, ``, xmlAttr(f.Docx.Family), xmlAttr(f.Docx.Pitch))
}
b.WriteString(``)
return b.String()
}
func xmlText(s string) string {
var b bytes.Buffer
_ = xml.EscapeText(&b, []byte(s))
return b.String()
}
func xmlAttr(s string) string { return strings.ReplaceAll(xmlText(s), `"`, """) }
const contentTypes = `` +
`` +
`` +
`` +
`` +
`` +
`` +
``
const rootRels = `` +
`` +
`` +
``
const documentRels = `` +
`` +
`` +
`` +
``