diff --git a/src/cli/styles/set.ts b/src/cli/styles/set.ts index 515aee0..c8cf8e1 100644 --- a/src/cli/styles/set.ts +++ b/src/cli/styles/set.ts @@ -92,8 +92,8 @@ export async function runStylesSet(args: string[]): Promise { const { values } = parsed; const filePath = parsed.positionals[0]; if (!filePath) return fail("USAGE", "Missing FILE argument", SET_HELP); - const styleId = values.at as string | undefined; - if (!styleId) { + const requestedStyleId = values.at as string | undefined; + if (!requestedStyleId) { return fail( "USAGE", "Missing --at STYLEID (the style to edit)", @@ -116,18 +116,20 @@ export async function runStylesSet(args: string[]): Promise { SET_HELP, ); } - if (basedOn === styleId) { + const document = await openOrFail(filePath); + if (typeof document === "number") return document; + + const styles = document.ensureStyles(); + // A localized Word names its default paragraph style `Standard`/`Normale`/…, + // so `--at Normal` targets whatever `w:default="1"` style plays that role. + const styleId = styles.localStyleId(requestedStyleId); + if (basedOn && styles.localStyleId(basedOn) === styleId) { return fail( "USAGE", `A style can't be based on itself ("${styleId}")`, "Point --based-on at a different (parent) style, or drop it.", ); } - - const document = await openOrFail(filePath); - if (typeof document === "number") return document; - - const styles = document.ensureStyles(); // Auto-provision an un-materialized baseline (e.g. `set --at Heading1` on a doc // that never used Heading1) so the agent's intent — "make Heading1 look like X" // — works regardless of whether the def already exists. A non-baseline unknown diff --git a/src/core/CLAUDE.md b/src/core/CLAUDE.md index 0877d2c..efe5671 100644 --- a/src/core/CLAUDE.md +++ b/src/core/CLAUDE.md @@ -62,7 +62,7 @@ Headers/footers are their own package — see [marginals/CLAUDE.md](marginals/CL ## Styles & numbering -`document.ensureStyles().ensureStyle(id)` ([ast/document/styles.tsx](ast/document/styles.tsx)) lazily provisions `word/styles.xml` from the `BASELINE` catalog if it isn't there yet. **Adding a baseline style:** extend the `BaselineStyleId` union and add a JSX-built definition to `BASELINE` — pStyle children must follow ECMA-376 §17.3.1.26 order (pStyle → keepNext → keepLines → numPr → pBdr → spacing → ind → jc). New tags go in `W_TAGS`. `insert --style`/`edit --style` auto-define baseline styles via `StylesView.ensureReferencedStyle`; custom values are referenced but left undefined. +`document.ensureStyles().ensureStyle(id)` ([ast/document/styles.tsx](ast/document/styles.tsx)) lazily provisions `word/styles.xml` from the `BASELINE` catalog if it isn't there yet. **Adding a baseline style:** extend the `BaselineStyleId` union and add a JSX-built definition to `BASELINE` — pStyle children must follow ECMA-376 §17.3.1.26 order (pStyle → keepNext → keepLines → numPr → pBdr → spacing → ind → jc). New tags go in `W_TAGS`. `insert --style`/`edit --style` auto-define baseline styles via `StylesView.ensureReferencedStyle`; custom values are referenced but left undefined. **Built-in defaults are found by `w:default="1"`, not by English id** (issue #59): a localized Word writes `Normal`/`DefaultParagraphFont` as e.g. German `Standard`/`Absatz-Standardschriftart`, so `StylesView.localStyleId` resolves those two ids to the document's own default of that type — provisioning never mints a second default `Normal`, and a provisioned style's `basedOn`/`next` are rewritten to the local ids (a `basedOn` naming a default the doc lacks entirely is dropped, not left dangling). Other baselines (`Heading1`, `Hyperlink`, `FootnoteText`, …) are still matched by English id. **Editing/creating a style definition** (`docx styles set`/`create`): `StylesView.setStyleFormatting(styleId, spec)` and `createStyle(spec)` apply a `StyleSpec` (run formatting + paragraph options + name/basedOn/next) onto a ``, splicing pPr/rPr at their CT_Style slots via `insertStyleChildInOrder` (the §17.7.4.17 analog of `insertPprChildInOrder`). They REUSE the body-edit appliers — `applyRunFormatToRpr` (extracted from `core/edit/set-formatting.ts`'s `setFormatting`) and `applyParagraphPropsToPPr` (extracted from `blocks.tsx`'s `applyParagraphOptionsInPlace`) — so a style's `--bold`/`--size`/`--space-before` behaves identically to a span edit. The methods live on the view (single part) rather than a lens; `Fonts` is a lens only because it ALSO spans the theme part. **Style edits are never tracked** (no ``/``/``): [verified empirically](../../README.md) that Word mutates `styles.xml` directly even under Track Changes — so the methods take no tracking arg and ignore the doc toggle. The CLI verbs ([cli/styles](../../cli/styles)) auto-provision an un-materialized baseline before `set`, reject pPr flags on character styles, and `styles --at` was widened to surface every settable property so the write-read loop holds. diff --git a/src/core/ast/document/styles.tsx b/src/core/ast/document/styles.tsx index c24b5b0..211df6d 100644 --- a/src/core/ast/document/styles.tsx +++ b/src/core/ast/document/styles.tsx @@ -182,7 +182,7 @@ export class StylesView { ?.findChild("w:sz") ?.getAttribute("w:val"); if (docDefault) return Number(docDefault); - const normal = this.getStyle("Normal") + const normal = this.getStyle(this.localStyleId("Normal")) ?.findChild("w:rPr") ?.findChild("w:sz") ?.getAttribute("w:val"); @@ -206,7 +206,7 @@ export class StylesView { ?.findChild("w:rFonts") ?.getAttribute("w:ascii"); if (docDefault) return docDefault; - return this.getStyle("Normal") + return this.getStyle(this.localStyleId("Normal")) ?.findChild("w:rPr") ?.findChild("w:rFonts") ?.getAttribute("w:ascii"); @@ -293,6 +293,18 @@ export class StylesView { this.#ensureStyleNode(root, styleId); } + /** The id this document uses for one of Word's built-in DEFAULT styles. A + * localized Word writes them under translated ids — German `Standard` / + * `Absatz-Standardschriftart` for `Normal` / `DefaultParagraphFont` — and + * only the `w:default="1"` flag identifies them (issue #59). Returns + * `styleId` unchanged when it's defined as-is, isn't one of those two, or + * the document declares no default of that type. */ + localStyleId(styleId: string): string { + if (this.hasStyle(styleId)) return styleId; + const type = BUILT_IN_DEFAULT_TYPE.get(styleId); + return (type && this.defaultStyleId(type)) || styleId; + } + /** Define a referenced paragraph/character style if it's a baseline we know * how to provision; no-op for undefined or custom styles. Convenience for * `insert --style` / `edit --style` so a `--style Heading2` reference also @@ -327,7 +339,7 @@ export class StylesView { const root = this.ensureStylesRoot(); this.#ensureStyleNode(root, "Normal"); if (this.hasStyle(styleId)) return; - root.children.push(build()); + root.children.push(this.#localizeDefaultReferences(build())); } /** Set the document default run font: `/// @@ -415,7 +427,11 @@ export class StylesView { setStyleFormatting(styleId: string, spec: StyleSpec): void { const style = this.getStyle(styleId); if (!style) return; - applyStyleSpec(style, spec); + applyStyleSpec(style, { + ...spec, + basedOn: spec.basedOn && this.localStyleId(spec.basedOn), + next: spec.next && this.localStyleId(spec.next), + }); } /** Provision a NEW custom `` with the given metadata + formatting (the @@ -479,11 +495,34 @@ export class StylesView { } #ensureStyleNode(stylesRoot: XmlNode, styleId: BaselineStyleId): void { - const exists = stylesRoot - .findChildren("w:style") - .some((child) => child.getAttribute("w:styleId") === styleId); - if (exists) return; - stylesRoot.children.push(BASELINE[styleId]()); + // `localStyleId` finds a localized default under its translated id, so a + // German doc's `Standard` satisfies `Normal` instead of gaining a SECOND + // `w:default="1"` paragraph style. + if (this.hasStyle(this.localStyleId(styleId))) return; + stylesRoot.children.push( + this.#localizeDefaultReferences(BASELINE[styleId]()), + ); + } + + /** Point a style's `basedOn`/`next` at the document's own default ids (see + * `localStyleId`) — the catalog names the English ones. A `basedOn` naming + * a built-in default the document doesn't define at all is dropped rather + * than left dangling: a style with no parent inherits the same defaults. */ + #localizeDefaultReferences(style: XmlNode): XmlNode { + for (const tag of ["w:basedOn", "w:next"]) { + const reference = style.findChild(tag); + const styleId = reference?.getAttribute("w:val"); + if (!reference || !styleId) continue; + const local = this.localStyleId(styleId); + const dangling = + BUILT_IN_DEFAULT_TYPE.has(styleId) && !this.hasStyle(local); + if (tag === "w:basedOn" && dangling) { + style.children.splice(style.children.indexOf(reference), 1); + continue; + } + reference.setAttribute("w:val", local); + } + return style; } } @@ -655,6 +694,13 @@ function insertStyleChildInOrder(style: XmlNode, child: XmlNode): void { else style.children.splice(at, 0, child); } +/** Word's built-in default styles by their English id → the `w:type` whose + * `w:default="1"` style plays that role in a localized document. */ +const BUILT_IN_DEFAULT_TYPE: ReadonlyMap = new Map([ + ["Normal", "paragraph"], + ["DefaultParagraphFont", "character"], +]); + /** The baseline style catalog: id → a builder that emits the `` * definition. Each builder renders one of the style components below. */ const BASELINE: Record XmlNode> = { diff --git a/tests/cli/styles.test.ts b/tests/cli/styles.test.ts index c573fe9..054e226 100644 --- a/tests/cli/styles.test.ts +++ b/tests/cli/styles.test.ts @@ -1016,3 +1016,84 @@ test("styles create/set independently expose complex-script font in JSON and tex "font-complex-script:", ); }); + +// Issue #59: a localized Word names its built-in defaults in its own language +// (German `Standard` / `Absatz-Standardschriftart`). Provisioning must find +// them by `w:default="1"`, never mint a second default `Normal`. +describe("localized default styles", () => { + test("a hyperlink edit reuses the German defaults instead of adding Normal", async () => { + const docPath = await germanStylesDoc("localized-link"); + const result = await runCli( + "edit", + docPath, + "--at", + "p0", + "See https://example.com", + ); + expect(result.exitCode).toBe(0); + const styles = await readStyles(docPath); + expect(styles).not.toContain('w:styleId="Normal"'); + expect(styles.match(/w:default="1"/g)).toHaveLength(2); + expect(styles).toContain('w:styleId="Hyperlink"'); + expect(styles).toContain(''); + expect(styles).not.toContain("DefaultParagraphFont"); + }); + + test("a heading's basedOn/next point at the localized default paragraph style", async () => { + const docPath = await germanStylesDoc("localized-heading"); + await runCli("edit", docPath, "--at", "p0", "# Title"); + const styles = await readStyles(docPath); + expect(styles).not.toContain('w:styleId="Normal"'); + expect(styles).toContain(''); + expect(styles).toContain(''); + }); + + test("styles set --at Normal edits the localized default paragraph style", async () => { + const docPath = await germanStylesDoc("localized-set"); + const result = await runCli( + "styles", + "set", + docPath, + "--at", + "Normal", + "--size", + "12", + "--verbose", + ); + expect(result.exitCode).toBe(0); + expect((result.parsed as { id: string }).id).toBe("Standard"); + const styles = await readStyles(docPath); + expect(styles).not.toContain('w:styleId="Normal"'); + expect(styles).toMatch(/w:styleId="Standard">.*/); + }); + + test("styles set --at Normal --based-on is refused as a self-reference", async () => { + const docPath = await germanStylesDoc("localized-cycle"); + const result = await runCli( + "styles", + "set", + docPath, + "--at", + "Normal", + "--based-on", + "Standard", + ); + expect(result.exitCode).toBe(2); + expect(await readStyles(docPath)).not.toContain( + '', + ); + }); +}); + +const GERMAN_STYLES = ` +`; + +/** A one-paragraph doc whose styles.xml holds only German Word's two defaults. */ +async function germanStylesDoc(label: string): Promise { + const docPath = join(tempWorkspace(label), "de.docx"); + await runCli("create", docPath, "--text", "Hallo"); + const pkg = await Pkg.open(docPath); + pkg.writeText("word/styles.xml", GERMAN_STYLES); + await pkg.save(); + return docPath; +} diff --git a/tests/fixtures/setup/style-defs.ts b/tests/fixtures/setup/style-defs.ts index e6949ff..c8beca5 100644 --- a/tests/fixtures/setup/style-defs.ts +++ b/tests/fixtures/setup/style-defs.ts @@ -1,5 +1,6 @@ import { mkdirSync } from "node:fs"; import { dirname, resolve } from "node:path"; +import { Pkg } from "@core/ast/document/package"; import { $ } from "bun"; // Pin core.xml timestamps so rebuilds are byte-deterministic. @@ -15,6 +16,11 @@ process.env.DOCX_CLI_NOW ??= "2026-05-22T00:00:00Z"; * spacing) and `docx styles create KbdKey --type character` a character style * (monospace + shaded background); * - `docx edit --style` applies a created style to a body paragraph; + * - the doc carries GERMAN Word's built-in default ids (`Standard` / + * `Absatz-Standardschriftart` — the one hand-rolled step, since the CLI + * never authors a localized template), so every provisioned baseline + * (Heading1, Hyperlink, the created styles) must base itself on those and + * never mint a second `w:default="1"` `Normal` (issue #59); * - `docx styles set-default-font` sets the document font (Garamond) — writing * AND repointing word/theme/theme1.xml's font scheme. The * theme-following headings (Heading1/Title/Subtitle reference the theme @@ -61,6 +67,7 @@ async function appendText( mkdirSync(dirname(out), { recursive: true }); await cli("create", out, "--title", "Style Definitions Demo", "--force"); +await localizeDefaultStyles(); // A heading (materializes Heading1) + body paragraphs that will adopt the styles. await cli( @@ -79,6 +86,16 @@ await appendText( await appendText("Key takeaway: editing a style updates everywhere at once."); await appendText("Press Enter to continue."); await appendText("Findings", { style: "Heading1" }); +// A bare URL autolinks: provisions the Hyperlink character style, which must +// base itself on the German default character style (issue #59). +await cli( + "insert", + out, + "--after", + `p${lastP}`, + "Reference: https://example.com", +); +lastP += 1; await appendText("A second section heading, sharing the Heading 1 style."); // Restyle the built-in Heading 1 definition — both headings update together. @@ -159,6 +176,21 @@ await cli( "Amiri", ); +/** Re-id the template's default paragraph style the way German Word writes it + * (`Standard`, display name still `Normal`) and add its default character + * style `Absatz-Standardschriftart`. */ +async function localizeDefaultStyles(): Promise { + const pkg = await Pkg.open(out); + const styles = (await pkg.readText("word/styles.xml")) + .replace('w:styleId="Normal"', 'w:styleId="Standard"') + .replace( + "", + '', + ); + pkg.writeText("word/styles.xml", styles); + await pkg.save(); +} + // Verify and report. const used = await cli("styles", out, "--used"); console.log(`Wrote ${out}`); diff --git a/tests/fixtures/style-defs.docx b/tests/fixtures/style-defs.docx index e7ade8b..3e0feb1 100644 Binary files a/tests/fixtures/style-defs.docx and b/tests/fixtures/style-defs.docx differ