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
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ The agent never sees this file. It is the ground-truth definition of "correct" f
### Logo replaced
- The top-left image is the new mark sourced from `assets/logo.svg`.
- The document still contains **exactly two** embedded images (new logo + footer payment mark).
- The new logo is **not distorted**: its displayed box (`size=` in the `docx:image` read hint) has the same aspect ratio as `assets/logo.svg` (square, 256×256), give or take rounding.
- Verify via `docx images list FILE`: two entries, and the logo entry's dimensions / source match `assets/logo.svg`.
- Footer payment mark is preserved: the footer image relationship is still present and unreferenced relationships were not dropped.

Expand Down
2 changes: 1 addition & 1 deletion REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ docx footers clear FILE …
docx images add FILE (--after | --before) LOCATOR --image SRC [--alt T] [--width LENGTH] [--height LENGTH] [--caption "..."] # bare = inches; 5cm, 300px, … (see "Lengths and units")
docx images add FILE (--at-start | --at-end) --image SRC [options] # SRC = path, data: URI, or http(s) URL
docx images extract FILE --to DIR [--at imgN] # --to = output directory; --at picks one image
docx images replace FILE --at imgN --with ./new.png
docx images replace FILE --at imgN --with ./new.png [--width LENGTH | --height LENGTH | --keep-size] # keeps the displayed width, height follows the new aspect (fit to the text area); crop dropped; ack names the size
docx images delete FILE --at imgN

docx hyperlinks add FILE --at pN:S-E --url URL
Expand Down
16 changes: 13 additions & 3 deletions src/cli/images/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,17 +162,27 @@ async function parseImageFlags(values: RawValues): Promise<
const caption = decodeInlineEscapes(values.caption as string | undefined);
if (caption !== undefined) out.caption = caption;

const size = await parseImageSize(values);
if (typeof size === "number") return size;
return { ...out, ...size };
}

/** `--width`/`--height` through the shared length grammar (`IMAGE_LENGTH`),
* as inches. Shared with `images replace`, so both verbs size identically. */
export async function parseImageSize(
values: RawValues,
): Promise<{ widthInches?: number; heightInches?: number } | number> {
const size: { widthInches?: number; heightInches?: number } = {};
for (const flag of ["width", "height"] as const) {
const raw = values[flag] as string | undefined;
if (raw === undefined) continue;
const twips = parseLength(raw, flag, IMAGE_LENGTH);
if (typeof twips !== "number")
return fail("USAGE", twips.error, twips.hint);
out[flag === "width" ? "widthInches" : "heightInches"] =
size[flag === "width" ? "widthInches" : "heightInches"] =
twips / TWIPS_PER_INCH;
}

return out;
return size;
}

/** Image sizes: bare inches (the long-standing meaning), positive, and `px` at
Expand Down
160 changes: 127 additions & 33 deletions src/cli/images/replace.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { getPageContentHeightEmu, getPageContentWidthEmu } from "@core";
import { findContainingParagraph } from "@core/comments";
import {
applyReplacementExtent,
fitReplacementExtent,
type ImageSource,
ImageSourceError,
Images,
imageFormatForExtension,
loadImageSource,
type ReplacementSizing,
SUPPORTED_IMAGE_FORMATS,
} from "@core/image";
import { addAuditComment } from "../audit-comment";
import type { RawValues } from "../insert/index";
import { formatImageSize } from "../read/annotations";
import {
EXIT,
fail,
Expand All @@ -18,21 +25,33 @@ import {
tryParseArgs,
writeStdout,
} from "../respond";
import { parseImageSize } from "./add";

const HELP = `docx images replace — swap an image's bytes
const HELP = `docx images replace — swap an image's picture, refitting its frame

Usage:
docx images replace FILE --at imgN --with PATH [options]

Examples:
docx images replace doc.docx --at img2 --with ./new-photo.png
docx images replace doc.docx --at img0 --with ./diagram.jpg
docx images replace doc.docx --at img0 --with ./logo.png --width 1.5in

Required:
--at imgN image id to replace (e.g. img0)
--with PATH New image file (format keyed off the file extension:
png/jpg/gif/webp/bmp/tiff/svg/emf/wmf/ico)

Sizing (default: keep the displayed WIDTH, recompute the height from the new
image's aspect ratio, scaled down to fit the text area if needed — the new
picture is never stretched into the old one's box):
--width LENGTH Display width: bare inches (2) or in/cm/mm/pt/px/tw.
Alone, the height follows the new image's aspect ratio.
--height LENGTH Display height, same units. Alone, the width follows.
Both given: honored as-is.
--keep-size Keep the old box exactly (only when the new image has the
same shape)

Optional:
--author NAME Author for the audit comment when track-changes is on
(default: $DOCX_AUTHOR)
Expand All @@ -42,15 +61,20 @@ Optional:
-h, --help Show this help

The replacement may use a different format from the original — the embedded
part is renamed and re-registered automatically.
part is renamed and re-registered automatically. Any crop on the old picture
is dropped (it was cut for the old image). Every place that shows the same
picture (a shared media part) is refitted, each from its own width. A format
whose pixel size isn't read (emf/wmf/webp/bmp/tiff/ico) keeps the old box —
the confirmation says so; pass --width and --height to size it.

Image swaps can't be recorded as tracked changes, so when track-changes is on
an audit comment is anchored to each place the swapped image appears.

Output:
Prints a one-line confirmation on success (exit 0) — replace mints no new
id (the image keeps its imgN). --verbose prints {ok:true, operation, path,
imageId, partName, mimeType, bytes}. Errors print {code, error, hint?} with
Prints a one-line confirmation naming the new size on success (exit 0),
e.g. "images.replace img0 (1x4in)" — replace mints no new id (the image
keeps its imgN). --verbose prints {ok:true, operation, path, imageId, size,
partName, mimeType, bytes}. Errors print {code, error, hint?} with
a nonzero exit. Discover ids with \`docx images list FILE\`.
`;

Expand All @@ -60,6 +84,9 @@ export async function run(args: string[]): Promise<number> {
{
at: { type: "string" },
with: { type: "string" },
width: { type: "string" },
height: { type: "string" },
"keep-size": { type: "boolean" },
author: { type: "string" },
...SAVE_FLAGS,
},
Expand All @@ -83,6 +110,9 @@ export async function run(args: string[]): Promise<number> {
const sourcePath = parsed.values.with as string | undefined;
if (!sourcePath) return fail("USAGE", "Missing --with PATH", HELP);

const sizing = await parseSizing(parsed.values);
if (typeof sizing === "number") return sizing;

const sourceFile = Bun.file(sourcePath);
if (!(await sourceFile.exists())) {
return fail("FILE_NOT_FOUND", `Replacement file not found: ${sourcePath}`);
Expand All @@ -104,6 +134,22 @@ export async function run(args: string[]): Promise<number> {
const newMimeType = format.mimeType;
const newExtension = format.extension;

// Route the replacement through the shared resolver (same as `docx images add`)
// so it gets the same safety: SVG sanitization (scripts/handlers/animation
// stripped), HEIC→JPEG transcode, and the SSRF guard on remote srcs. We keep
// the extension/MIME resolved above for part naming; the bytes and pixel
// dimensions come back.
let source: ImageSource;
try {
source = await loadImageSource(sourcePath);
} catch (error) {
if (error instanceof ImageSourceError) {
return fail("IMAGE_SOURCE", error.message);
}
throw error;
}
const bytes = source.bytes;

const document = await openOrFail(path);
if (typeof document === "number") return document;

Expand All @@ -112,6 +158,44 @@ export async function run(args: string[]): Promise<number> {
return fail("IMAGE_NOT_FOUND", `Image not found: ${targetId}`);
}

// The bytes are shared by every drawing on this relationship, so every one
// of them is refitted (each from its own displayed width). Plan all fits
// BEFORE any mutation, so a sizing error writes nothing.
const occurrences = new Images(document).list();
const textArea = {
widthEmu: getPageContentWidthEmu(document),
heightEmu: getPageContentHeightEmu(document),
};
const fits = [];
for (const [index, occurrence] of occurrences.entries()) {
if (occurrence.relationshipId !== reference.relationshipId) continue;
const drawing = occurrence.run.findChild("w:drawing");
if (!drawing) continue;
const extent = fitReplacementExtent(drawing, source, sizing, textArea);
if (!extent) {
return fail(
"USAGE",
`Can't keep the aspect ratio: no pixel size could be read from .${sourceExtension}`,
"Pass both --width and --height to size it explicitly.",
);
}
fits.push({ id: `img${index}`, occurrence, drawing, extent });
}
const targetFit = fits.find((fit) => fit.id === targetId);
if (!targetFit) {
return fail(
"IMAGE_NOT_FOUND",
`Image reference is stale (no drawing for ${targetId})`,
);
}
const size = formatImageSize(
targetFit.extent.widthEmu,
targetFit.extent.heightEmu,
);
const sizeNote = targetFit.extent.sizeKnown
? undefined
: `kept ${size}: size unknown for .${sourceExtension} — pass --width and --height if it's a different shape`;

const originalPartName = reference.partName;
const newPartName = renameExtension(originalPartName, newExtension);
const outputPath = parsed.values.output as string | undefined;
Expand All @@ -122,26 +206,16 @@ export async function run(args: string[]): Promise<number> {
dryRun: true,
path,
imageId: targetId,
size,
from: { partName: originalPartName, mimeType: reference.contentType },
to: { partName: newPartName, mimeType: newMimeType },
...(outputPath ? { output: outputPath } : {}),
});
return EXIT.OK;
}

// Route the replacement through the shared resolver (same as `docx images add`)
// so it gets the same safety: SVG sanitization (scripts/handlers/animation
// stripped), HEIC→JPEG transcode, and the SSRF guard on remote srcs. We keep
// the extension/MIME resolved above for part naming; only the bytes come back.
let bytes: Uint8Array;
try {
bytes = (await loadImageSource(sourcePath)).bytes;
} catch (error) {
if (error instanceof ImageSourceError) {
return fail("IMAGE_SOURCE", error.message);
}
throw error;
}
for (const fit of fits) applyReplacementExtent(fit.drawing, fit.extent);

const originalMimeType = reference.contentType;

if (newPartName === originalPartName) {
Expand Down Expand Up @@ -171,12 +245,9 @@ export async function run(args: string[]): Promise<number> {

if (document.isTrackChangesEnabled()) {
const authorFlag = parsed.values.author as string | undefined;
const message = `image replaced: ${originalPartName} (${originalMimeType}) → ${newPartName} (${newMimeType}, ${bytes.length} bytes)`;
const drawingRuns = new Images(document)
.list()
.filter((hit) => hit.relationshipId === reference.relationshipId)
.map((hit) => hit.run);
for (const drawingRun of drawingRuns) {
const message = `image replaced: ${originalPartName} (${originalMimeType}) → ${newPartName} (${newMimeType}, ${bytes.length} bytes), now ${size}`;
for (const { occurrence } of fits) {
const drawingRun = occurrence.run;
const paragraph = findContainingParagraph(
document.documentTree,
drawingRun,
Expand All @@ -193,18 +264,41 @@ export async function run(args: string[]): Promise<number> {

await document.save(outputPath);

await respondAck({
ok: true,
operation: "images.replace",
path: outputPath ?? path,
imageId: targetId,
partName: newPartName,
mimeType: newMimeType,
bytes: bytes.length,
});
await respondAck(
{
ok: true,
operation: "images.replace",
path: outputPath ?? path,
imageId: targetId,
size,
...(sizeNote ? { note: sizeNote } : {}),
partName: newPartName,
mimeType: newMimeType,
bytes: bytes.length,
},
sizeNote && `↳ ${sizeNote}`,
);
return EXIT.OK;
}

/** `--width`/`--height` (shared grammar with `images add`) or `--keep-size`,
* which can't be combined — it would silently win over an explicit size. */
async function parseSizing(
values: RawValues,
): Promise<ReplacementSizing | number> {
const size = await parseImageSize(values);
if (typeof size === "number") return size;
if (!values["keep-size"]) return size;
if (size.widthInches !== undefined || size.heightInches !== undefined) {
return fail(
"USAGE",
"--keep-size can't be combined with --width/--height",
"Use --keep-size to keep the old box, or --width/--height to set a new one.",
);
}
return { keepSize: true };
}

function renameExtension(partName: string, newExtension: string): string {
const dotIndex = partName.lastIndexOf(".");
const slashIndex = partName.lastIndexOf("/");
Expand Down
6 changes: 6 additions & 0 deletions src/cli/read/annotations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ export function deviatingCellMargins(

/** Format an EMU count (914400 per inch) as inches, trimming trailing zeros.
* Image extents (`<wp:extent>`) are in EMU; `read --ast` carries the raw EMU. */
/** `WxHin` — the display-size form the `docx:image` hint and the
* `images replace` ack share, so an agent sees the same string in both. */
export function formatImageSize(widthEmu: number, heightEmu: number): string {
return `${emuToInches(widthEmu)}x${emuToInches(heightEmu)}in`;
}

export function emuToInches(emu: number): string {
return `${Number.parseFloat((emu / 914400).toFixed(2))}`;
}
7 changes: 2 additions & 5 deletions src/cli/read/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ import {
} from "@core/track-changes/revision-visibility";
import {
deviatingCellMargins,
emuToInches,
formatCellMargins,
formatImageSize,
formatNote,
htmlAttr,
type NotePair,
Expand Down Expand Up @@ -780,10 +780,7 @@ function contentWidthEmu(geometry: SectionBreak | undefined): number {
function formatImageNote(run: ImageRun, contentEmu: number): string {
const pairs: NotePair[] = [];
if (run.widthEmu && run.heightEmu) {
pairs.push([
"size",
`${emuToInches(run.widthEmu)}x${emuToInches(run.heightEmu)}in`,
]);
pairs.push(["size", formatImageSize(run.widthEmu, run.heightEmu)]);
}
if (run.floating) pairs.push(["float", "yes"]);
if (run.wrap) pairs.push(["wrap", run.wrap]);
Expand Down
5 changes: 4 additions & 1 deletion src/cli/respond.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,10 @@ function ackTarget(ack: Record<string, unknown>): string | null {
const to = str(ack.to);
return `${ack.hyperlinkId}${to ? ` → ${to}` : ""}`;
}
if (str(ack.imageId)) return str(ack.imageId);
if (str(ack.imageId)) {
const size = str(ack.size);
return size ? `${ack.imageId} (${size})` : str(ack.imageId);
}
if (str(ack.table)) {
const position = num(ack.position);
return position !== null ? `${ack.table} (${position})` : str(ack.table);
Expand Down
6 changes: 5 additions & 1 deletion src/core/image/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
# src/core/image — image emit, source resolution, formats

Three files reachable via the `@core/image` barrel ([index.ts](index.ts)): [formats.ts](formats.ts) (mime↔extension table), [source.ts](source.ts) (resolve an input reference to bytes), [drawing.tsx](drawing.tsx) (the `Images` lens + the `<Image>` emitter). A fourth file, [svg-sanitize.ts](svg-sanitize.ts), is internal to `source.ts` and not surfaced through the barrel.
Four files reachable via the `@core/image` barrel ([index.ts](index.ts)): [formats.ts](formats.ts) (mime↔extension table), [source.ts](source.ts) (resolve an input reference to bytes), [drawing.tsx](drawing.tsx) (the `Images` lens + the `<Image>` emitter), [refit.ts](refit.ts) (resize an existing drawing's frame for replacement bytes). A fifth file, [svg-sanitize.ts](svg-sanitize.ts), is internal to `source.ts` and not surfaced through the barrel.

## Emit + package ops

`loadImageSource(src)` in [source.ts](source.ts) resolves a path / `data:` URI / `http(s)` URL to `{bytes, extension, mimeType, pixelWidth?, pixelHeight?}` (header-parsed dims for png/jpeg/gif; other formats need explicit sizing). `computeExtentEmu` turns pixels + optional inch overrides into the `<wp:extent>` EMU pair. The `Images` lens in [drawing.tsx](drawing.tsx) carries `new Images(document).list()` (finds drawing runs in `imgN` order — shared by `images replace`/`delete`) and `new Images(document).add(source)` (writes `word/media/imageN.ext`, mints the `image` relationship, registers the content-type `<Default>`). `<Image>` is the pure emitter for the inline `<w:drawing>` run.

## Replace refits the frame

[refit.ts](refit.ts) sizes an EXISTING drawing for new bytes (`images replace`) so a differently-shaped picture is never stretched into the old box (issue #46). `fitReplacementExtent` is pure: keep the displayed width, recompute the height from the new pixel aspect, then scale down (aspect kept) to fit the text area; `--width`/`--height` go through `computeExtentEmu` exactly like `add`; `--keep-size` keeps the box; a format with no parsed pixel size keeps the box and reports `sizeKnown: false` (the CLI says so in the ack). `applyReplacementExtent` mutates in place: `<wp:extent>` AND `pic:spPr/a:xfrm/a:ext` (they must agree), drops `<a:srcRect>` (a crop in the OLD image's coordinates), and resets a tight/through `<wp:wrapPolygon>` to the full frame (polygon coordinates are a fixed 21600 space, so the rectangle needs no scaling). The bytes are per-relationship, so the CLI refits EVERY drawing on that rId — each from its own width — and plans all fits before mutating.

The `a:`/`pic:` namespaces are declared inline on `a:graphic`/`pic:pic` (matching Word) so the subtree validates regardless of the document root's declarations — `docx create`'s template declares `w/r/m/mc/wp/...` but **not** `a`/`pic`. Drawing object ids (`wp:docPr`/`pic:cNvPr` @id) must be unique per document, so `nextDrawingId` scans existing ids. `r:embed` is an *attribute*, so there's no `r` element namespace in `jsx/index.ts`. An image run inside `<w:ins>` surfaces `ImageRun.trackedChange` (populated in the `w:drawing` branch of `readRun` in `ast/read.ts`), same as a text run.

## One format table, keyed by extension
Expand Down
5 changes: 5 additions & 0 deletions src/core/image/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ export {
imageFormatForExtension,
SUPPORTED_IMAGE_FORMATS,
} from "./formats";
export {
applyReplacementExtent,
fitReplacementExtent,
type ReplacementSizing,
} from "./refit";
export {
computeExtentEmu,
type ImageSource,
Expand Down
Loading
Loading