oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1// Package docx is the font half of Docs' Word files: how a document's
2// families are written into a .docx and read back out of one.
3//
4// Paul's default 5 (2026-10-24): Carlito is written as Calibri and
5// Caladea as Cambria, the Office faces they are metric twins of, so a
6// document breaks its lines in Word where it does here; every other
7// family is named, not embedded; and on the way in Calibri becomes
8// Carlito and Cambria Caladea. The names are internal/fonts' manifest
9// (Docx.Name, and ByDocxName for the way back).
10//
11// Write is deliberately only what the font rulings need: paragraphs and
12// headings, runs with their family, weight, slope and size, the document
13// default in w:docDefaults and every family named in fontTable.xml.
14// Lists, tables, images and links are not written yet, and nothing routes
15// to Write. Import (read.go) is the reading half, used by the import page
16// (spec §11.2 and implementation/google-drive-import.md).
17package docx
18
19import (
20 "archive/zip"
21 "bytes"
22 "encoding/xml"
23 "fmt"
24 "io"
25 "sort"
26 "strings"
27
28 "github.com/carlosframework/docs/internal/export"
29 "github.com/carlosframework/docs/internal/fonts"
30)
31
32// Write writes doc as a .docx.
33func Write(doc export.Document) ([]byte, error) {
34 used := map[*fonts.Family]bool{fonts.Default: true}
35 var body strings.Builder
36 var walk func(nodes []export.Node)
37 walk = func(nodes []export.Node) {
38 for _, n := range nodes {
39 switch n.Type {
40 case "paragraph", "heading":
41 body.WriteString("<w:p>")
42 if n.Type == "heading" {
43 level := n.Attrs.Level
44 if level < 1 || level > 6 {
45 level = 1
46 }
47 fmt.Fprintf(&body, `<w:pPr><w:pStyle w:val="Heading%d"/></w:pPr>`, level)
48 }
49 for _, run := range n.Content {
50 if run.IsText() && run.Text != "" {
51 writeRun(&body, run, used)
52 }
53 }
54 body.WriteString("</w:p>")
55 default:
56 walk(n.Content)
57 }
58 }
59 }
60 walk(doc.Root.Content)
61
62 families := make([]*fonts.Family, 0, len(used))
63 for f := range used {
64 families = append(families, f)
65 }
66 sort.Slice(families, func(i, j int) bool { return families[i].Index < families[j].Index })
67
68 var buf bytes.Buffer
69 z := zip.NewWriter(&buf)
70 files := []struct{ name, body string }{
71 {"[Content_Types].xml", contentTypes},
72 {"_rels/.rels", rootRels},
73 {"word/_rels/document.xml.rels", documentRels},
74 {"word/document.xml", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
75 `<w:document xmlns:w="` + wNS + `"><w:body>` + body.String() + `</w:body></w:document>`},
76 {"word/styles.xml", styles()},
77 {"word/fontTable.xml", fontTable(families)},
78 }
79 for _, f := range files {
80 w, err := z.Create(f.name)
81 if err != nil {
82 return nil, err
83 }
84 if _, err := io.WriteString(w, f.body); err != nil {
85 return nil, err
86 }
87 }
88 if err := z.Close(); err != nil {
89 return nil, err
90 }
91 return buf.Bytes(), nil
92}
93
94func writeRun(b *strings.Builder, run export.Node, used map[*fonts.Family]bool) {
95 names := make([]string, len(run.Marks))
96 for i, m := range run.Marks {
97 names[i] = m.Type
98 }
99 family := fonts.ForMarks(names)
100 if run.Has("code") {
101 family = fonts.Code
102 }
103 used[family] = true
104 var props strings.Builder
105 if family != fonts.Default {
106 n := xmlAttr(family.Docx.Name)
107 fmt.Fprintf(&props, `<w:rFonts w:ascii="%s" w:hAnsi="%s" w:cs="%s" w:eastAsia="%s"/>`, n, n, n, n)
108 }
109 if run.Has("strong") {
110 props.WriteString("<w:b/>")
111 }
112 if run.Has("em") {
113 props.WriteString("<w:i/>")
114 }
115 for _, mark := range export.SizeMarks() {
116 if run.Has(mark) {
117 if pt, ok := export.SizePt(mark); ok {
118 fmt.Fprintf(&props, `<w:sz w:val="%d"/>`, int(pt*2))
119 }
120 break
121 }
122 }
123 b.WriteString("<w:r>")
124 if props.Len() > 0 {
125 b.WriteString("<w:rPr>" + props.String() + "</w:rPr>")
126 }
127 b.WriteString(`<w:t xml:space="preserve">` + xmlText(run.Text) + "</w:t></w:r>")
128}
129
130// styles puts the default family in w:docDefaults, where Word and an
131// importer read a document's own default from, at Docs' 12pt body.
132func styles() string {
133 n := xmlAttr(fonts.Default.Docx.Name)
134 var b strings.Builder
135 b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="` + wNS + `">`)
136 fmt.Fprintf(&b, `<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="%s" w:hAnsi="%s" w:cs="%s" w:eastAsia="%s"/>`+
137 `<w:sz w:val="%d"/><w:szCs w:val="%d"/></w:rPr></w:rPrDefault></w:docDefaults>`, n, n, n, n, int(export.BodySizePt*2), int(export.BodySizePt*2))
138 b.WriteString(`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>`)
139 for level := 1; level <= 6; level++ {
140 fmt.Fprintf(&b, `<w:style w:type="paragraph" w:styleId="Heading%d"><w:name w:val="heading %d"/><w:basedOn w:val="Normal"/>`+
141 `<w:next w:val="Normal"/><w:qFormat/><w:rPr><w:b/></w:rPr></w:style>`, level, level)
142 }
143 b.WriteString(`</w:styles>`)
144 return b.String()
145}
146
147// fontTable names every family the document uses, with what Word needs
148// to substitute sensibly when it does not have one: its generic family,
149// pitch, panose and nearest Office face.
150func fontTable(families []*fonts.Family) string {
151 var b strings.Builder
152 b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:fonts xmlns:w="` + wNS + `">`)
153 for _, f := range families {
154 fmt.Fprintf(&b, `<w:font w:name="%s">`, xmlAttr(f.Docx.Name))
155 if f.Docx.AltName != "" {
156 fmt.Fprintf(&b, `<w:altName w:val="%s"/>`, xmlAttr(f.Docx.AltName))
157 }
158 if f.Docx.Panose != "" {
159 fmt.Fprintf(&b, `<w:panose1 w:val="%s"/>`, xmlAttr(f.Docx.Panose))
160 }
161 fmt.Fprintf(&b, `<w:family w:val="%s"/><w:pitch w:val="%s"/></w:font>`, xmlAttr(f.Docx.Family), xmlAttr(f.Docx.Pitch))
162 }
163 b.WriteString(`</w:fonts>`)
164 return b.String()
165}
166
167func xmlText(s string) string {
168 var b bytes.Buffer
169 _ = xml.EscapeText(&b, []byte(s))
170 return b.String()
171}
172
173func xmlAttr(s string) string { return strings.ReplaceAll(xmlText(s), `"`, "&quot;") }
174
175const contentTypes = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
176 `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
177 `<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
178 `<Default Extension="xml" ContentType="application/xml"/>` +
179 `<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>` +
180 `<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>` +
181 `<Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/>` +
182 `</Types>`
183
184const rootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
185 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
186 `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>` +
187 `</Relationships>`
188
189const documentRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
190 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
191 `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
192 `<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/>` +
193 `</Relationships>`
194