Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions src/cli/styles/set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ export async function runStylesSet(args: string[]): Promise<number> {
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)",
Expand All @@ -116,18 +116,20 @@ export async function runStylesSet(args: string[]): Promise<number> {
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
Expand Down
2 changes: 1 addition & 1 deletion src/core/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<w:style>`, 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 `<w:rPrChange>`/`<w:pPrChange>`/`<w:ins>`): [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.

Expand Down
64 changes: 55 additions & 9 deletions src/core/ast/document/styles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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");
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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: `<w:docDefaults>/<w:rPrDefault>/<w:rPr>/
Expand Down Expand Up @@ -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 `<w:style>` with the given metadata + formatting (the
Expand Down Expand Up @@ -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;
}
}

Expand Down Expand Up @@ -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<string, string> = new Map([
["Normal", "paragraph"],
["DefaultParagraphFont", "character"],
]);

/** The baseline style catalog: id → a builder that emits the `<w:style>`
* definition. Each builder renders one of the style components below. */
const BASELINE: Record<BaselineStyleId, () => XmlNode> = {
Expand Down
81 changes: 81 additions & 0 deletions tests/cli/styles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('<w:basedOn w:val="Absatz-Standardschriftart"/>');
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('<w:basedOn w:val="Standard"/>');
expect(styles).toContain('<w:next w:val="Standard"/>');
});

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">.*<w:sz w:val="24"\/>/);
});

test("styles set --at Normal --based-on <its local id> 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(
'<w:basedOn w:val="Standard"/>',
);
});
});

const GERMAN_STYLES = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:default="1" w:styleId="Standard"><w:name w:val="Normal"/><w:qFormat/></w:style><w:style w:type="character" w:default="1" w:styleId="Absatz-Standardschriftart"><w:name w:val="Default Paragraph Font"/><w:uiPriority w:val="1"/><w:semiHidden/><w:unhideWhenUsed/></w:style></w:styles>`;

/** A one-paragraph doc whose styles.xml holds only German Word's two defaults. */
async function germanStylesDoc(label: string): Promise<string> {
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;
}
32 changes: 32 additions & 0 deletions tests/fixtures/setup/style-defs.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
* <w:docDefaults> AND repointing word/theme/theme1.xml's font scheme. The
* theme-following headings (Heading1/Title/Subtitle reference the theme
Expand Down Expand Up @@ -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(
Expand All @@ -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.
Expand Down Expand Up @@ -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<void> {
const pkg = await Pkg.open(out);
const styles = (await pkg.readText("word/styles.xml"))
.replace('w:styleId="Normal"', 'w:styleId="Standard"')
.replace(
"</w:styles>",
'<w:style w:type="character" w:default="1" w:styleId="Absatz-Standardschriftart"><w:name w:val="Default Paragraph Font"/><w:uiPriority w:val="1"/><w:semiHidden/><w:unhideWhenUsed/></w:style></w:styles>',
);
pkg.writeText("word/styles.xml", styles);
await pkg.save();
}

// Verify and report.
const used = await cli("styles", out, "--used");
console.log(`Wrote ${out}`);
Expand Down
Binary file modified tests/fixtures/style-defs.docx
Binary file not shown.
Loading