oficina / docs Public

Docx: closed report metadata, and the whole style cascade.

Review fixes. The import report no longer stores or quotes face names
(Item.Names is gone): font substitution is a code, a count and
paragraph numbers, like every other line, so nothing from the file is
ever persisted in a report. A test holds the report's JSON free of the
fixture's text and face names.

Bold and italic now come through document default, paragraph style
chain, character style (w:rStyle) and run, as tri-state toggles, so an
explicit off at a nearer level wins. Underline/strike/colour/highlight/
raise/caps carried by a paragraph or character style are reported as
formatting lost for the paragraphs they reach, and a paragraph style's
centre/right alignment as alignment lost unless the paragraph states
its own. A heading takes its level's look in Docs (its style's size,
weight, slope and colour are not carried or reported; the import page
says so); only its face and its runs' own properties come through.
Mutation-checked: letting an explicit off inherit reddens the test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev e877ead699b988dd0ca6adf56aa9132a7b5bf4bd parent 25fc493
3 files changed, +213 −112
  • internal/docx/docx_test.go +14 −17
  • internal/docx/read.go +129 −92
  • internal/docx/read_test.go +70 −3

CI passed — run details

diff --git a/internal/docx/docx_test.go b/internal/docx/docx_test.go
index 7c092eb..0be5df1 100644
--- a/internal/docx/docx_test.go
+++ b/internal/docx/docx_test.go
@@ -79,13 +79,10 @@ func TestCarlitoAndCaladeaRoundTripAsCalibriAndCambria(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- back, unknown := res.Document, unknownFaces(res.Report)
+ back := res.Document
if len(res.Report.Items) > 0 {
t.Errorf("a document Docs wrote imports with losses: %+v", res.Report.Items)
}
- if len(unknown) > 0 {
- t.Errorf("faces Docs ships came back unknown: %v", unknown)
- }
runs := back.Root.Content[1].Content
want := []struct {
text string
@@ -122,20 +119,20 @@ func TestImportingWordsDefaults(t *testing.T) {
for _, c := range []struct {
defaultFace, runFace string
marks string
- unknown string
+ unknown bool
}{
- {"Calibri", "", "", ""},
- {"Cambria", "", "font_caladea", ""},
- {"Calibri", "Cambria", "font_caladea", ""},
- {"Cambria", "Calibri", "", ""},
- {"Calibri", "Wingdings", "", "Wingdings"},
+ {"Calibri", "", "", false},
+ {"Cambria", "", "font_caladea", false},
+ {"Calibri", "Cambria", "font_caladea", false},
+ {"Cambria", "Calibri", "", false},
+ {"Calibri", "Wingdings", "", true},
} {
data := wordFile(t, c.defaultFace, c.runFace)
res, err := docx.Import(data)
if err != nil {
t.Fatal(err)
}
- doc, unknown := res.Document, unknownFaces(res.Report)
+ doc, unknown := res.Document, substituted(res.Report)
var marks []string
for _, m := range doc.Root.Content[0].Content[0].Marks {
marks = append(marks, m.Type)
@@ -143,8 +140,8 @@ func TestImportingWordsDefaults(t *testing.T) {
if strings.Join(marks, " ") != c.marks {
t.Errorf("default %s, run %q: marks %v, want [%s]", c.defaultFace, c.runFace, marks, c.marks)
}
- if strings.Join(unknown, ",") != c.unknown {
- t.Errorf("default %s, run %q: unknown %v, want %q", c.defaultFace, c.runFace, unknown, c.unknown)
+ if unknown != c.unknown {
+ t.Errorf("default %s, run %q: substitution reported %v, want %v", c.defaultFace, c.runFace, unknown, c.unknown)
}
}
}
@@ -167,12 +164,12 @@ func wordFile(t *testing.T, defaultFace, runFace string) []byte {
return buf.Bytes()
}
-// unknownFaces is the face names the report says were substituted.
-func unknownFaces(r docx.Report) []string {
+// substituted is whether the report says a face was substituted.
+func substituted(r docx.Report) bool {
for _, it := range r.Items {
if it.Code == docx.CodeFontSubstituted {
- return it.Names
+ return true
}
}
- return nil
+ return false
}
diff --git a/internal/docx/read.go b/internal/docx/read.go
index 83d76c5..a1d2562 100644
--- a/internal/docx/read.go
+++ b/internal/docx/read.go
@@ -11,7 +11,6 @@ import (
"strconv"
"strings"
"unicode"
- "unicode/utf8"
"github.com/carlosframework/docs/internal/export"
"github.com/carlosframework/docs/internal/fonts"
@@ -99,10 +98,6 @@ const (
// maxLocations is how many paragraph numbers one report item keeps;
// its Count is still exact.
maxLocations = 20
- // maxFontNames bounds the face names the report quotes, and
- // maxFontName each name's length in bytes.
- maxFontNames = 20
- maxFontName = 64
)
// Import's refusals. Each is a whole answer: none of them says anything
@@ -134,12 +129,12 @@ type Report struct {
// Item is one kind of loss: how many times it happened and, where it
// has one, the first maxLocations paragraphs (1-based, in the imported
-// document) it happened at.
+// document) it happened at. Closed metadata only: nothing from the file
+// is ever quoted, not even a face name, which is as arbitrary as text.
type Item struct {
- Code Code `json:"code"`
- Count int `json:"count"`
- Paragraphs []int `json:"paragraphs,omitempty"`
- Names []string `json:"names,omitempty"`
+ Code Code `json:"code"`
+ Count int `json:"count"`
+ Paragraphs []int `json:"paragraphs,omitempty"`
}
// Code names one kind of loss. The set is closed: Codes lists it.
@@ -198,11 +193,10 @@ func readPart(f *zip.File, budget *int) ([]byte, error) {
type reporter struct {
items map[Code]*Item
- fonts map[string]bool
}
func newReporter() *reporter {
- return &reporter{items: map[Code]*Item{}, fonts: map[string]bool{}}
+ return &reporter{items: map[Code]*Item{}}
}
// add counts one occurrence of code at paragraph (1-based; 0 for none).
@@ -218,26 +212,10 @@ func (r *reporter) add(code Code, paragraph int) {
}
}
-func (r *reporter) font(name string, paragraph int) {
- r.add(CodeFontSubstituted, paragraph)
- if len(r.fonts) < maxFontNames {
- if len(name) > maxFontName {
- name = truncate(name, maxFontName)
- }
- r.fonts[name] = true
- }
-}
-
func (r *reporter) report() Report {
var out Report
for _, c := range Codes {
if it := r.items[c]; it != nil {
- if c == CodeFontSubstituted {
- for n := range r.fonts {
- it.Names = append(it.Names, n)
- }
- sort.Strings(it.Names)
- }
sort.Ints(it.Paragraphs)
out.Items = append(out.Items, *it)
}
@@ -245,13 +223,6 @@ func (r *reporter) report() Report {
return out
}
-func truncate(s string, n int) string {
- for n > 0 && !utf8.RuneStart(s[n]) {
- n--
- }
- return s[:n]
-}
-
// ---- styles
const (
@@ -261,9 +232,9 @@ const (
type style struct {
name, basedOn string
- font string
- size int // half-points, 0 for unset
+ rp props // the style's own run properties
numbered bool
+ aligned bool // centred or right-aligned
}
// styleKind is what a paragraph style makes of a block.
@@ -280,21 +251,60 @@ type block struct {
runs []export.Node
}
+// tri is an OOXML toggle as stated somewhere in the cascade: unset,
+// on, or explicitly off. An explicit off stops inheritance.
+type tri int8
+
+const (
+ unset tri = iota
+ on
+ off
+)
+
+func triOf(b bool) tri {
+ if b {
+ return on
+ }
+ return off
+}
+
+// props are run properties at one level of the cascade: a run's own
+// w:rPr, a character style, a paragraph style, or the document default.
type props struct {
- bold, italic bool
- font string // a Word face name, "" for inherited
- size int // half-points, 0 for inherited
+ bold, italic tri
+ font string // a Word face name, "" for unset
+ size int // half-points, 0 for unset
lost bool // underline, strike, colour, highlight, raised, caps
+ rstyle string // a run's character style
+}
+
+// over is p with every property p leaves unset taken from base. Lost
+// formatting accumulates: a style's colour is as lost as a run's.
+func (p props) over(base props) props {
+ if p.bold == unset {
+ p.bold = base.bold
+ }
+ if p.italic == unset {
+ p.italic = base.italic
+ }
+ if p.font == "" {
+ p.font = base.font
+ }
+ if p.size == 0 {
+ p.size = base.size
+ }
+ p.lost = p.lost || base.lost
+ return p
}
type reader struct {
dec *xml.Decoder
depth int
- styles map[string]*style
+ styles map[string]*style // paragraph styles
+ charStyles map[string]*style
defaultStyle string
- baseFont string
- baseSize int
+ base props // w:docDefaults' run properties
blocks []block
runs, text int
rep *reporter
@@ -414,6 +424,7 @@ func (r *reader) readStyles(b []byte) error {
r.dec = newDecoder(b)
r.depth = 0
r.styles = map[string]*style{}
+ r.charStyles = map[string]*style{}
if err := r.root("styles"); err != nil {
return err
}
@@ -428,12 +439,7 @@ func (r *reader) readStyles(b []byte) error {
if !isW(e, "rPr") {
return r.skip()
}
- p := props{}
- if err := r.runProps(&p); err != nil {
- return err
- }
- r.baseFont, r.baseSize = p.font, p.size
- return nil
+ return r.runProps(&r.base)
}, nil)
}, nil)
case isW(e, "style"):
@@ -448,16 +454,14 @@ func (r *reader) readStyles(b []byte) error {
case isW(c, "basedOn"):
s.basedOn, _ = attr(c, "val")
case isW(c, "rPr"):
- p := props{}
- if err := r.runProps(&p); err != nil {
- return err
- }
- s.font, s.size = p.font, p.size
- return nil
+ return r.runProps(&s.rp)
case isW(c, "pPr"):
return r.children(func(p xml.StartElement) error {
- if isW(p, "numPr") {
+ switch {
+ case isW(p, "numPr"):
s.numbered = true
+ case isW(p, "jc"):
+ s.aligned = alignedValue(p)
}
return r.skip()
}, nil)
@@ -467,11 +471,15 @@ func (r *reader) readStyles(b []byte) error {
if err != nil {
return err
}
- if kind == "paragraph" && id != "" {
+ switch {
+ case id == "":
+ case kind == "paragraph":
r.styles[id] = s
if toggle1(def) {
r.defaultStyle = id
}
+ case kind == "character":
+ r.charStyles[id] = s
}
return nil
}
@@ -487,11 +495,15 @@ func toggle1(v string) bool {
// never revisiting one (a basedOn loop is a damaged file, read as far as
// it makes sense).
func (r *reader) chain(id string) []*style {
+ return chainIn(r.styles, id)
+}
+
+func chainIn(styles map[string]*style, id string) []*style {
var out []*style
seen := map[string]bool{}
for id != "" && !seen[id] && len(out) < 10 {
seen[id] = true
- s := r.styles[id]
+ s := styles[id]
if s == nil {
break
}
@@ -523,27 +535,50 @@ func (r *reader) kind(id string) styleKind {
return styleKind{}
}
-// inherited is the face and size a run in a paragraph of this style
-// inherits: the style chain's, then the document default's.
-func (r *reader) inherited(id string) (font string, size int) {
+// inherited is what a run in a paragraph of this style inherits: the
+// style chain's run properties, nearest first, then the document
+// default's.
+func (r *reader) inherited(id string) props {
if id == "" {
id = r.defaultStyle
}
+ var p props
for _, s := range r.chain(id) {
- if font == "" {
- font = s.font
- }
- if size == 0 {
- size = s.size
- }
+ p = p.over(s.rp)
}
- if font == "" {
- font = r.baseFont
+ return p.over(r.base)
+}
+
+// charInherited is a character style chain's run properties.
+func (r *reader) charInherited(id string) props {
+ var p props
+ for _, s := range chainIn(r.charStyles, id) {
+ p = p.over(s.rp)
}
- if size == 0 {
- size = r.baseSize
+ return p
+}
+
+func (r *reader) alignedStyle(id string) bool {
+ if id == "" {
+ id = r.defaultStyle
}
- return font, size
+ for _, s := range r.chain(id) {
+ if s.aligned {
+ return true
+ }
+ }
+ return false
+}
+
+// alignedValue is whether a w:jc is an alignment Docs does not import:
+// centred, right, or anything else that is not the start edge or
+// justification.
+func alignedValue(e xml.StartElement) bool {
+ switch v, _ := attr(e, "val"); v {
+ case "", "left", "start", "both", "distribute":
+ return false
+ }
+ return true
}
func (r *reader) numberedStyle(id string) bool {
@@ -661,9 +696,9 @@ func (r *reader) table() error {
type para struct {
style string
kind styleKind
- font string
- size int
+ inh props // what its runs inherit
listMarked bool
+ jcSet bool // the paragraph states its own alignment
}
func (r *reader) newBlock(p *para) error {
@@ -711,11 +746,15 @@ func (r *reader) paragraph() error {
// settle applies the paragraph's style once pPr has been read.
func (r *reader) settle(p *para) {
p.kind = r.kind(p.style)
- p.font, p.size = r.inherited(p.style)
+ p.inh = r.inherited(p.style)
if p.kind.heading > 0 {
- // A heading's size is its level's in Docs; only a size its runs
- // state themselves is carried.
- p.size = 0
+ // A heading looks like its level in Docs: the heading style's
+ // own size, weight, slope and colour are the level's here, and
+ // the import page says so. Only its face, and what its runs
+ // state themselves, are carried.
+ p.inh = props{font: p.inh.font}
+ } else if !p.jcSet && r.alignedStyle(p.style) {
+ r.rep.add(CodeAlignmentLost, r.here())
}
r.blocks[len(r.blocks)-1].heading = p.kind.heading
switch {
@@ -753,9 +792,8 @@ func (r *reader) paragraphProps(p *para) error {
}
return nil
case isW(e, "jc"):
- switch v, _ := attr(e, "val"); v {
- case "", "left", "start", "both", "distribute":
- default:
+ p.jcSet = true
+ if alignedValue(e) {
r.rep.add(CodeAlignmentLost, r.here())
}
case isW(e, "sectPr"):
@@ -846,9 +884,11 @@ func (r *reader) runProps(p *props) error {
return r.children(func(e xml.StartElement) error {
switch {
case isW(e, "b"):
- p.bold = toggle(e)
+ p.bold = triOf(toggle(e))
case isW(e, "i"):
- p.italic = toggle(e)
+ p.italic = triOf(toggle(e))
+ case isW(e, "rStyle"):
+ p.rstyle, _ = attr(e, "val")
case isW(e, "rFonts"):
if v, ok := attr(e, "ascii"); ok && v != "" {
p.font = v
@@ -921,23 +961,20 @@ func (r *reader) emit(p *para, rp props, s string) error {
}
run := export.Node{Type: "text", Text: s}
+ // The cascade: the run's own properties, its character style, its
+ // paragraph's style, the document default.
+ rp = rp.over(r.charInherited(rp.rstyle)).over(p.inh)
face := rp.font
- if face == "" {
- face = p.font
- }
if face != "" {
if f, ok := fonts.ByDocxName(face); ok {
if f != fonts.Default {
run.Marks = append(run.Marks, export.Mark{Type: f.Mark()})
}
} else {
- r.rep.font(face, r.here())
+ r.rep.add(CodeFontSubstituted, r.here())
}
}
size := rp.size
- if size == 0 {
- size = p.size
- }
if size != 0 && size != export.BodySizePt*2 {
if mark, ok := sizeMark(size); ok {
run.Marks = append(run.Marks, export.Mark{Type: mark})
@@ -945,10 +982,10 @@ func (r *reader) emit(p *para, rp props, s string) error {
r.rep.add(CodeSizeDropped, r.here())
}
}
- if rp.bold {
+ if rp.bold == on {
run.Marks = append(run.Marks, export.Mark{Type: "strong"})
}
- if rp.italic {
+ if rp.italic == on {
run.Marks = append(run.Marks, export.Mark{Type: "em"})
}
if rp.lost {
diff --git a/internal/docx/read_test.go b/internal/docx/read_test.go
index ef45bb6..16593b1 100644
--- a/internal/docx/read_test.go
+++ b/internal/docx/read_test.go
@@ -211,9 +211,9 @@ func TestImportReadsEveryContainerGoogleExportsTextIn(t *testing.T) {
docx.CodeHeadersOmitted: {1, "", ""},
docx.CodeTitleAsHeading: {1, "1", ""},
docx.CodeSubtitleAsParagraph: {1, "19", ""},
- docx.CodeFontSubstituted: {1, "17", "Comic Sans MS"},
+ docx.CodeFontSubstituted: {1, "17", ""},
docx.CodeSizeDropped: {2, "17,19", ""},
- docx.CodeFormattingLost: {1, "3", ""},
+ docx.CodeFormattingLost: {2, "3,19", ""},
docx.CodeAlignmentLost: {1, "18", ""},
docx.CodeTabAsSpace: {1, "14", ""},
docx.CodeLineBreakSplit: {1, "15", ""},
@@ -225,7 +225,7 @@ func TestImportReadsEveryContainerGoogleExportsTextIn(t *testing.T) {
for _, p := range it.Paragraphs {
where = append(where, fmt.Sprint(p))
}
- gotReport[it.Code] = line{it.Count, strings.Join(where, ","), strings.Join(it.Names, ",")}
+ gotReport[it.Code] = line{it.Count, strings.Join(where, ","), ""}
}
for code, w := range wantReport {
if g, ok := gotReport[code]; !ok {
@@ -291,6 +291,65 @@ func TestImportKeepsWhatTheOldReaderLost(t *testing.T) {
}
}
+// Bold and italic come through the whole cascade: document default,
+// paragraph style chain, character style, run, with an explicit off at
+// any nearer level winning. What a style carries that Docs cannot hold is
+// reported for the paragraphs it reaches, not dropped in silence.
+func TestImportFollowsTheStyleCascade(t *testing.T) {
+ styles := `<w:styles ` + docNS + `>` +
+ `<w:docDefaults><w:rPrDefault><w:rPr><w:i/></w:rPr></w:rPrDefault></w:docDefaults>` +
+ `<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Strong"><w:name w:val="Strong body"/><w:basedOn w:val="Normal"/><w:rPr><w:b/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="StrongChild"><w:name w:val="Strong child"/><w:basedOn w:val="Strong"/><w:rPr><w:i w:val="0"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Red"><w:name w:val="Red"/><w:rPr><w:color w:val="FF0000"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Centred"><w:name w:val="Centred"/><w:pPr><w:jc w:val="center"/></w:pPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:rPr><w:b/><w:color w:val="FF0000"/><w:sz w:val="40"/></w:rPr></w:style>` +
+ `<w:style w:type="character" w:styleId="Emph"><w:name w:val="Emph"/><w:rPr><w:i/><w:u w:val="single"/></w:rPr></w:style>` +
+ `</w:styles>`
+ body := para("", run("", "default italic")) +
+ para("Strong", run("", "style bold")+run(`<w:b w:val="0"/>`, "run says not bold")) +
+ para("StrongChild", run("", "inherited bold, italic off")) +
+ para("", run(`<w:rStyle w:val="Emph"/><w:i w:val="0"/>`, "character style, italic off")+run(`<w:rStyle w:val="Emph"/>`, "character style")) +
+ para("Red", run("", "red")) +
+ para("Centred", run("", "centred")) +
+ `<w:p><w:pPr><w:pStyle w:val="Centred"/><w:jc w:val="left"/></w:pPr>` + run("", "left after all") + `</w:p>` +
+ para("Heading1", run("", "heading"))
+ res, err := docx.Import(zipOf(t, map[string]string{
+ "word/styles.xml": styles,
+ "word/document.xml": `<w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`,
+ }))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{
+ "paragraph:default italic{em}|",
+ "paragraph:style bold{strong,em}|run says not bold{em}|",
+ "paragraph:inherited bold, italic off{strong}|",
+ "paragraph:character style, italic off|character style{em}|",
+ "paragraph:red{em}|",
+ "paragraph:centred{em}|",
+ "paragraph:left after all{em}|",
+ "heading1:heading|",
+ }
+ if got := strings.Join(shape(res.Document), "\n"); got != strings.Join(want, "\n") {
+ t.Errorf("document\n got:\n%s\nwant:\n%s", got, strings.Join(want, "\n"))
+ }
+ where := map[docx.Code]string{}
+ for _, it := range res.Report.Items {
+ var ps []string
+ for _, p := range it.Paragraphs {
+ ps = append(ps, fmt.Sprint(p))
+ }
+ where[it.Code] = strings.Join(ps, ",")
+ }
+ if where[docx.CodeFormattingLost] != "4,5" {
+ t.Errorf("formatting lost at %q, want the underlined character style (4) and the red paragraph style (5)", where[docx.CodeFormattingLost])
+ }
+ if where[docx.CodeAlignmentLost] != "6" {
+ t.Errorf("alignment lost at %q, want the centred style's paragraph only (6)", where[docx.CodeAlignmentLost])
+ }
+}
+
func TestImportNeverReadsALinkTarget(t *testing.T) {
res, err := docx.Import(googleShaped(t))
if err != nil {
@@ -302,6 +361,14 @@ func TestImportNeverReadsALinkTarget(t *testing.T) {
t.Errorf("the result carries %q from the file's metadata", s)
}
}
+ // The report is closed metadata: codes, counts and paragraph
+ // numbers. No text from the file, and no face name either.
+ rep, _ := json.Marshal(res.Report)
+ for _, s := range []string{"Comic", "Arial", "Quarterly", "Summary", "our site", "removed"} {
+ if strings.Contains(string(rep), s) {
+ t.Errorf("the report quotes %q from the file", s)
+ }
+ }
}
func TestImportDropsControlCharacters(t *testing.T) {