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
2 changes: 1 addition & 1 deletion REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ docx track-changes apply doc.docx --accept rev0 --reject rev1 # finalize: acce

**Rich content.** Images insert from a path, `data:` URI, or `http(s)` URL (bounded fetch; SVG sanitized; non-public/metadata addresses refused at every redirect hop). HEIC/HEIF input is refused, by extension, MIME type, or file header, with an `IMAGE_SOURCE` error whose hint gives the conversion command (`sips` on macOS, `heif-convert` or ImageMagick on Linux): Word can't display HEIC, and docx-cli bundles no HEVC decoder. Equations round-trip OOXML `<m:oMath>` ↔ LaTeX (reconstructed, not legacy plaintext) — authored via temml (LaTeX→MathML) plus an in-house MathML→OMML adapter. Code blocks emit one `CodeBlock`-styled paragraph per line with optional lowlight syntax highlighting (37 bundled languages); they collapse back to a GFM fenced block on read. GFM task lists round-trip Word's checkbox content control (and the Word-for-Web Wingdings-glyph variant), surfacing as `taskState` in the AST. Tables operate on a merge-aware logical grid so `gridSpan`/`vMerge` cells map onto physical `<w:tc>`, and structural edits refuse to bisect an existing merge.

**Markdown dialect.** `create --from`, `insert/edit --markdown`, and the note bodies all parse the same GFM + math + CriticMarkup + inline-HTML-formatting dialect (remark + remark-gfm + remark-math + an in-house inline-surgery transform), composing the existing OOXML emitters. `read` emits a compatible dialect, so the read → edit → write loop round-trips (lossless for paragraphs, lists, and nested blockquotes; code/tables/math/headings inside a blockquote intentionally escape to top level on import). `read --ast` is the fully lossless JSON form. The `[^tcN]` and `[^cN]` labels `read --current` / `--comments` add (and their definition lines) are read-time hints like the `<!-- … -->` comments: the importer drops them, so pasting a `--current` line back applies its CriticMarkup exactly as if the labels weren't there, and never mints a footnote. Real footnotes read as `[^fnN]`/`[^enN]`; name your own anything but `tcN`/`cN`.
**Markdown dialect.** `create --from`, `insert/edit --markdown`, and the note bodies all parse the same GFM + math + CriticMarkup + inline-HTML-formatting dialect (remark + remark-gfm + remark-math + an in-house inline-surgery transform), composing the existing OOXML emitters. `read` emits a compatible dialect, so the read → edit → write loop round-trips (lossless for paragraphs, lists, and nested blockquotes; code/tables/math/headings inside a blockquote intentionally escape to top level on import). `read --ast` is the fully lossless JSON form. The `[^tcN]` and `[^cN]` labels `read --current` / `--comments` add (and their definition lines) are read-time hints like the `<!-- … -->` comments: the importer drops them, so pasting a `--current` line back applies its CriticMarkup exactly as if the labels weren't there, and never mints a footnote. Real footnotes read as `[^fnN]`/`[^enN]`; name your own anything but `tcN`/`cN`. Block-level HTML is NOT converted: a line that opens with a block tag (`<h1>`, `<p>`, `<div>`, `<table>`, …) swallows everything up to the next blank line, so a block that carries text is refused with a `USAGE` error (exit 2, nothing written) rather than silently dropped — an HTML file passed to `create --from` fails instead of producing an empty document. Tag-only wrappers (`<div align="center">` around real markdown) and `<!-- … -->` comments still drop silently; inline tags inside a paragraph are unaffected.

**Literal text — the parser-free channel.** When you want prose inserted _exactly_ — reviewer notes, quoted excerpts, anything where Markdown would misfire — use `create --text-file PATH` / `insert --text-file PATH` (or `-` for stdin). Every character lands verbatim and each newline starts a new paragraph; nothing is interpreted, so `3. note` stays `3.` (no ordered-list renumber), and `*x*`, `[t](u)`, bare URLs, and `{++x++}` are kept as written. This exists because GFM corruption isn't always escapable: bare URLs autolink with no escape sequence at all, and CriticMarkup eats `{++…++}` regardless of backslashes — so a literal path is the only safe way to author untouched prose.

Expand Down
117 changes: 43 additions & 74 deletions src/cli/create/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ Options:
stdin). One content source only. Uses the same markdown
dialect as 'docx insert --markdown'. This is the canonical
way to build a whole .docx from a markdown file.
HTML is not converted: block HTML that carries text
(an .html page, <div>/<table>/<h1> blocks) is refused
and nothing is written — rewrite it as markdown.
Footnote/endnote bodies keep bold/italic + hyperlinks;
footnote labels renumber to [^fnN] on import. (Under
track-changes, note bodies flatten to plain text.)
Expand Down Expand Up @@ -193,43 +196,45 @@ export async function run(args: string[]): Promise<number> {
(parsed.values.author as string | undefined) ?? Bun.env.DOCX_AUTHOR ?? "";
const title = (parsed.values.title as string | undefined) ?? "";

// Seed with --text (or empty) first. If --from was passed, we re-open the
// just-written package, replace the placeholder paragraph with parsed
// markdown blocks, and save again. We don't try to do the markdown parse
// inline against the raw template tree because MarkdownImport needs a
// full Document (relationships, content-types, lazy-provisioned views) to
// register footnote bodies / hyperlinks / images — all of which only come
// alive once the package is on disk and re-opened. We write the blank
// package straight to `destination` (the --output target if given, else
// FILE), then re-open and re-save that same file for the markdown pass.
// Build the blank package (seeded with --text, or empty) and run every
// content/geometry/marginals step against ONE in-memory Document over it,
// saving once at the end. `Document.fromPackage` gives MarkdownImport the
// full view set it needs (relationships, content-types, lazy-provisioned
// views) without a disk round-trip — and a refused source (bad image, block
// HTML that would drop text) writes NOTHING, so an existing FILE under
// --force survives a failed create.
const pkg = buildBlankPackage({ path: destination, title, author, text });
await pkg.save();
const document = await Document.fromPackage(pkg);

let blockCount = 1; // the seed paragraph buildBlankPackage emitted
if (fromPath !== undefined) {
const applied = await applyMarkdownToBody(destination, fromPath);
const applied = await applyMarkdownToBody(document, fromPath);
if (typeof applied === "number") return applied;
blockCount = applied.blockCount;
} else if (textFilePath !== undefined) {
const applied = await applyLiteralToBody(destination, textFilePath);
const applied = await applyLiteralToBody(document, textFilePath);
if (typeof applied === "number") return applied;
blockCount = applied.blockCount;
}

// Apply page geometry to the fresh doc's trailing <w:sectPr> by re-opening
// (same build → re-open → mutate → save pattern --from/--text-file use). No
// tracking: a brand-new document has no prior state to snapshot.
if (hasGeometry) {
const applied = await applyGeometryToBody(destination, geometry);
if (typeof applied === "number") return applied;
// No tracking for geometry: a brand-new document has no prior state to
// snapshot. Headers/footers follow geometry so the part lands on the final
// trailing sectPr.
if (hasGeometry || hasMarginals) {
const sectPr = document.body.body.children
.filter((child) => child.tag === "w:sectPr")
.pop();
if (!sectPr) {
return fail(
"USAGE",
"Internal: trailing <w:sectPr> not found in blank-package body",
);
}
if (hasGeometry) applyPageGeometry(sectPr, geometry);
if (hasMarginals) applyMarginals(document, sectPr, marginals);
}

// Headers/footers, applied after geometry so the part lands on the final
// trailing sectPr (same re-open-and-mutate pattern as the geometry step).
if (hasMarginals) {
const applied = await applyMarginalsToBody(destination, marginals);
if (typeof applied === "number") return applied;
}
await document.save();

await respondAck({
ok: true,
Expand All @@ -246,7 +251,7 @@ export async function run(args: string[]): Promise<number> {
* empty placeholder paragraph. Returns an exit code on failure, or the
* applied block count on success so the caller can report it in the ack. */
async function applyMarkdownToBody(
docxPath: string,
document: Document,
markdownPath: string,
): Promise<number | { blockCount: number }> {
let source: string;
Expand All @@ -263,7 +268,6 @@ async function applyMarkdownToBody(
);
}

const document = await Document.open(docxPath);
let blocks: XmlNode[];
try {
blocks = await new MarkdownImport(document).blocks(source);
Expand All @@ -274,15 +278,15 @@ async function applyMarkdownToBody(
throw error;
}

return replacePlaceholderAndSave(document, blocks);
return replacePlaceholder(document, blocks);
}

/** Read literal text from PATH (or stdin), split it into one paragraph per line
* (NO markdown parsing — every character lands verbatim), and splice the result
* over the seed paragraph. The `create` counterpart of `insert --text-file`,
* for building a doc from prose that GFM would corrupt. */
async function applyLiteralToBody(
docxPath: string,
document: Document,
textFilePath: string,
): Promise<number | { blockCount: number }> {
let source: string;
Expand All @@ -299,48 +303,16 @@ async function applyLiteralToBody(
);
}

const document = await Document.open(docxPath);
return replacePlaceholderAndSave(document, literalParagraphs(source));
return replacePlaceholder(document, literalParagraphs(source));
}

/** Re-open the freshly-written doc and apply page geometry to its trailing
* `<w:sectPr>` (the document-wide one buildBlankPackage emits). Returns an exit
* code on failure, or void on success. */
async function applyGeometryToBody(
docxPath: string,
geometry: PageGeometry,
): Promise<number | undefined> {
const document = await Document.open(docxPath);
const sectPr = document.body.body.children
.filter((child) => child.tag === "w:sectPr")
.pop();
if (!sectPr) {
return fail(
"USAGE",
"Internal: trailing <w:sectPr> not found in blank-package body",
);
}
applyPageGeometry(sectPr, geometry);
await document.save();
return undefined;
}

/** Re-open the freshly-written doc and apply create-time headers/footers to its
* trailing `<w:sectPr>` (document-wide) via the `Marginals` lens. */
async function applyMarginalsToBody(
docxPath: string,
/** Apply create-time headers/footers to the trailing (document-wide)
* `<w:sectPr>` via the `Marginals` lens. */
function applyMarginals(
document: Document,
sectPr: XmlNode,
marginals: { header?: string; footer?: string; pageNumbers: boolean },
): Promise<number | undefined> {
const document = await Document.open(docxPath);
const sectPr = document.body.body.children
.filter((child) => child.tag === "w:sectPr")
.pop();
if (!sectPr) {
return fail(
"USAGE",
"Internal: trailing <w:sectPr> not found in blank-package body",
);
}
): void {
const lens = new Marginals(document);
if (marginals.header !== undefined) {
lens.set([sectPr], "header", "default", { text: marginals.header });
Expand All @@ -354,24 +326,22 @@ async function applyMarginalsToBody(
align: "center",
});
}
await document.save();
return undefined;
}

/** Replace the blank package's single seed `<w:p>` with `blocks` and save.
* `buildBlankPackage` always emits exactly one placeholder `<w:p>` plus the
/** Replace the blank package's single seed `<w:p>` with `blocks` (the caller
* saves). `buildBlankPackage` always emits exactly one placeholder `<w:p>` plus the
* trailing `<w:sectPr>`; we swap the placeholder for the real content and leave
* the sectPr at the tail. An empty `blocks` (markdown source that walked to
* nothing) keeps the seed paragraph — splicing zero blocks would leave a bare
* `<w:sectPr>` as a direct `<w:body>` child, which ECMA-376 §17.2.2 frowns on
* and Word for Mac flags on save. */
async function replacePlaceholderAndSave(
async function replacePlaceholder(
document: Document,
blocks: XmlNode[],
): Promise<number | { blockCount: number }> {
if (blocks.length === 0) return { blockCount: 1 };

// `Document.open()` populated the embedded views; `document.body.body` is
// `Document.fromPackage()` populated the embedded views; `document.body.body` is
// the parsed `<w:body>` XmlNode. No need to re-walk the tree.
const body = document.body.body;
const placeholderIndex = body.children.findIndex(
Expand All @@ -384,6 +354,5 @@ async function replacePlaceholderAndSave(
);
}
body.children.splice(placeholderIndex, 1, ...blocks);
await document.save();
return { blockCount: blocks.length };
}
5 changes: 4 additions & 1 deletion src/core/markdown/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ itself round-trips through the ordinal).

**These are read-time VISIBILITY hints, not round-trip carriers — ONE contract.**
The importer DROPS every one: `walkBlock`'s `case "html"` returns `[]`, and the
inline walker drops inline comments. The structure survives normal edits via
inline walker drops inline comments. (One guard rides that drop: a block-HTML node whose
markup carries visible TEXT — `<p>Body</p>`, an `.html` page — is refused with
`USAGE` by `rejectTextBearingHtml` rather than dropped with its prose, issue #61;
comments and tag-only wrappers carry no text, so every `read` hint still drops.) The structure survives normal edits via
in-place XML mutation; `read --ast` is the lossless view; and the authoring verbs
(`docx sections`, `docx tables …`) manage it. So a from-scratch
`create` is deliberately lossy for non-Markdown structure (a section break read →
Expand Down
28 changes: 27 additions & 1 deletion src/core/markdown/walker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ function walkBlock(node: RootContent, ctx: WalkContext): XmlNode[] {
// `read` emits) — drop. These are read-time hints, not parse-back: the
// importer never reconstructs structure from them (`--ast` is the
// lossless view; edit-in-place + `docx sections`
// manage layout). Agents author through markdown features.
// manage layout). Agents author through markdown features. A block
// that would take TEXT with it is refused instead (issue #61).
rejectTextBearingHtml(node.value, node.position?.start.line);
return [];
case "footnoteDefinition":
// The lens pre-collects footnote definitions and registers their
Expand All @@ -88,6 +90,30 @@ function walkBlock(node: RootContent, ctx: WalkContext): XmlNode[] {
}
}

/** Refuse a raw block-HTML node whose markup carries visible text. CommonMark
* swallows a line that opens with a block tag (`<h1>`, `<p>`, `<div>`,
* `<table>`, …) — and everything up to the next blank line — into ONE opaque
* `html` node, so dropping it drops the prose inside: an HTML file passed to
* `create --from` used to become an empty document at exit 0. Tag-only blocks
* (a README's `<div align="center">` wrapper around real markdown) and comments
* (every `read` hint) carry no text and still drop silently. */
function rejectTextBearingHtml(html: string, line: number | undefined): void {
const text = html
.replace(/<!--[\s\S]*?(?:-->|$)/g, " ")
.replace(/<[^>]*>/g, " ")
.replace(/&(?:nbsp|#160|#x0*a0);/gi, " ")
.replace(/\s+/g, " ")
.trim();
if (text === "") return;
const where = line === undefined ? "" : ` at line ${line}`;
const preview = text.length > 60 ? `${text.slice(0, 57)}...` : text;
throw new MarkdownImportError(
"USAGE",
`Block-level HTML${where} would be dropped along with its text ("${preview}") — markdown input doesn't convert HTML blocks`,
"Rewrite it as markdown: `# Heading`, plain paragraphs, `| a | b |` tables, `**bold**`. Inline <u>/<sup>/<sub>/<mark>/<span> inside a paragraph are fine. To keep the text verbatim instead, strip the tags (or use --text-file where available).",
);
}

function paragraphBlock(
node: MdParagraph,
ctx: WalkContext,
Expand Down
62 changes: 62 additions & 0 deletions tests/cli/create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,3 +467,65 @@ describe("docx create — inline escape decoding (--text)", () => {
expect(paragraph?.runs).toEqual([{ type: "text", text: "Hello world" }]);
});
});

describe("docx create --from — block HTML (issue #61)", () => {
test("refuses an HTML file instead of writing an empty document", async () => {
const workspace = tempWorkspace("create-html");
const source = join(workspace, "page.html");
await Bun.write(source, "<h1>Title</h1><p>Body</p>");
const docPath = join(workspace, "out.docx");

const result = await runCli("create", docPath, "--from", source);
expect(result.exitCode).toBe(2);
const error = result.parsed as { code: string; error: string };
expect(error.code).toBe("USAGE");
expect(error.error).toContain("Title");
// Nothing is written when the content is refused.
expect(await Bun.file(docPath).exists()).toBe(false);
});

test("refuses block HTML with text inside otherwise-valid markdown", async () => {
const workspace = tempWorkspace("create-html-block");
const source = join(workspace, "draft.md");
await Bun.write(
source,
"Intro\n\n<table><tr><td>Cell text</td></tr></table>\n\nAfter\n",
);
const docPath = join(workspace, "out.docx");

const result = await runCli("create", docPath, "--from", source);
expect(result.exitCode).toBe(2);
expect((result.parsed as { error: string }).error).toContain("line 3");
expect(await Bun.file(docPath).exists()).toBe(false);
});

test("--force over an existing file leaves it untouched on refusal", async () => {
const workspace = tempWorkspace("create-html-force");
const docPath = join(workspace, "out.docx");
expect(
(await runCli("create", docPath, "--text", "Keep me")).exitCode,
).toBe(0);
const source = join(workspace, "page.html");
await Bun.write(source, "<div>Lost</div>");

const result = await runCli("create", docPath, "--from", source, "--force");
expect(result.exitCode).toBe(2);
expect((await runCli("read", docPath)).stdout).toContain("Keep me");
});

test("tag-only HTML and comments still pass (their content is markdown)", async () => {
const workspace = tempWorkspace("create-html-wrapper");
const source = join(workspace, "readme.md");
await Bun.write(
source,
'<div align="center">\n\n# Title\n\nBody text\n\n</div>\n\n<!-- p9 -->\n\n<p>&nbsp;</p>\n',
);
const docPath = join(workspace, "out.docx");

const result = await runCli("create", docPath, "--from", source);
expect(result.exitCode).toBe(0);
const markdown = (await runCli("read", docPath)).stdout;
expect(markdown).toContain("# Title");
expect(markdown).toContain("Body text");
});
});
9 changes: 3 additions & 6 deletions tests/cli/images.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1225,12 +1225,9 @@ describe("HEIC/HEIF input is refused on every image ingress", () => {
code: "IMAGE_SOURCE",
hint: expect.stringContaining("sips -s format jpeg"),
});
// `create` stages the blank package before its markdown pass (a
// pre-existing trait of every --from failure), so assert no image landed.
const pkg = await Pkg.open(docPath);
expect(pkg.listParts().some((part) => part.startsWith("word/media/"))).toBe(
false,
);
// `create` builds in memory and saves once, so a refused source writes
// nothing at all.
expect(await Bun.file(docPath).exists()).toBe(false);
});

test("images replace refuses a .heic file or HEIC behind a .jpg label", async () => {
Expand Down
Loading
Loading