fix: stop an index entry field scrambling the document in Word (#1546) (#3792)

This commit is contained in:
Dolan
2026-10-19 12:23:45 +01:00
committed by GitHub
parent ea08b9677c
commit 69fc2da10d
4 changed files with 117 additions and 3 deletions
+25
View File
@@ -82,6 +82,31 @@ const doc = new Document({
});
```
### Index entries
An index entry (`XE`) marks a place in the document for an `INDEX` field to list, with its page number. The entry shows nothing itself. Word builds the index when its fields are updated, so give the `INDEX` field a cached value to show until then:
```ts live
import { Document, HeadingLevel, Paragraph, SimpleField, TextRun } from "docx";
const doc = new Document({
sections: [
{
children: [
new Paragraph({
children: [new TextRun("Apples are red"), new SimpleField('XE "Apples"'), new TextRun(", and pears are green.")],
}),
new Paragraph({ children: [new TextRun("Bananas are yellow."), new SimpleField('XE "Bananas"')] }),
new Paragraph({ text: "Index", heading: HeadingLevel.HEADING_1 }),
new Paragraph({ children: [new SimpleField("INDEX", "Apples, 1")] }),
],
},
],
});
```
Table of contents entries (`TC`) and table of authorities entries (`TA`) are added the same way. These fields have no result, so a cached value given to one isn't written.
### Mail merge fields
Fields are often used in a mail merge where a template document is created and data from another source (Excel or a database) is inserted in the document.
+9 -2
View File
@@ -25,6 +25,7 @@ const FieldCharacterType = {
type IFieldCharAttributes = {
readonly type: (typeof FieldCharacterType)[keyof typeof FieldCharacterType];
readonly dirty?: boolean;
readonly locked?: boolean;
};
/**
@@ -45,12 +46,17 @@ type IFieldCharAttributes = {
* ```
* @internal
*/
const createFieldChar = (type: (typeof FieldCharacterType)[keyof typeof FieldCharacterType], dirty?: boolean): XmlComponent =>
const createFieldChar = (
type: (typeof FieldCharacterType)[keyof typeof FieldCharacterType],
dirty?: boolean,
locked?: boolean,
): XmlComponent =>
new BuilderElement<IFieldCharAttributes>({
name: "w:fldChar",
attributes: {
type: { key: "w:fldCharType", value: type },
dirty: { key: "w:dirty", value: dirty },
locked: { key: "w:fldLock", value: locked },
},
});
@@ -59,8 +65,9 @@ const createFieldChar = (type: (typeof FieldCharacterType)[keyof typeof FieldCha
*
* The Begin element marks the start of a field. A field consists of a begin character,
* field instructions, an optional separate character, field result, and an end character.
* A locked field (`w:fldLock`) is not updated by Word.
*/
export const createBegin = (dirty?: boolean): XmlComponent => createFieldChar(FieldCharacterType.BEGIN, dirty);
export const createBegin = (dirty?: boolean, locked?: boolean): XmlComponent => createFieldChar(FieldCharacterType.BEGIN, dirty, locked);
/** The formatted begin characters of the fields that are dirty only when the document isn't given page numbers */
const dirtyWithoutPageNumbers = new WeakSet<object>();
@@ -37,6 +37,53 @@ describe("SimpleField", () => {
expect(unset).to.deep.equal({ "w:fldSimple": { _attr: { "w:instr": "DATE" } } });
expect(unlocked).to.deep.equal({ "w:fldSimple": { _attr: { "w:instr": "DATE" } } });
});
it("writes an index entry as a complex field in a run, because Word moves the text around a w:fldSimple one", () => {
const tree = new Formatter().format(new SimpleField('XE "test"'));
expect(tree).to.deep.equal({
"w:r": [
{ "w:fldChar": { _attr: { "w:fldCharType": "begin" } } },
{ "w:instrText": [{ _attr: { "xml:space": "preserve" } }, 'XE "test"'] },
{ "w:fldChar": { _attr: { "w:fldCharType": "end" } } },
],
});
});
it.each([
["a table of contents entry", 'TC "Apples" \\l 2'],
["a table of authorities entry", 'TA \\l "Smith v. Jones"'],
["a referenced document", 'RD "chapter-2.docx"'],
["private data", "PRIVATE data"],
["an index entry in lower case with spaces around it", ' xe "test" '],
])("writes %s as a complex field, as it has no result either", (_, instruction) => {
const tree = new Formatter().format(new SimpleField(instruction));
expect(tree).to.deep.equal({
"w:r": [
{ "w:fldChar": { _attr: { "w:fldCharType": "begin" } } },
{ "w:instrText": [{ _attr: { "xml:space": "preserve" } }, instruction] },
{ "w:fldChar": { _attr: { "w:fldCharType": "end" } } },
],
});
});
it("doesn't write a cached value for a field with no result, and locks it on its beginning", () => {
const tree = new Formatter().format(new SimpleField('XE "test"', "ignored", { locked: true }));
expect(tree).to.deep.equal({
"w:r": [
{ "w:fldChar": { _attr: { "w:fldCharType": "begin", "w:fldLock": true } } },
{ "w:instrText": [{ _attr: { "xml:space": "preserve" } }, 'XE "test"'] },
{ "w:fldChar": { _attr: { "w:fldCharType": "end" } } },
],
});
});
it.each(["TOC \\o", "TIME", "RDX", "SET bookmark text", "ADVANCE \\r 10"])(
"keeps %s as a w:fldSimple, as only the fields with no result are misread",
(instruction) => {
const tree = new Formatter().format(new SimpleField(instruction));
expect(tree).to.deep.equal({ "w:fldSimple": { _attr: { "w:instr": instruction } } });
},
);
});
});
+36 -1
View File
@@ -9,10 +9,31 @@
*
* @module
*/
import { SpaceType } from "@file/shared";
import { XmlAttributeComponent, XmlComponent } from "@file/xml-components";
import { createBegin, createEnd } from "./field";
import { TextAttributes } from "./text-attributes";
import { TextRun } from "./text-run";
/**
* The fields that mark a place in the document and have no result: index entries (`XE`), table of contents entries
* (`TC`), table of authorities entries (`TA`), referenced documents (`RD`) and `PRIVATE`. Word misreads them as a
* `w:fldSimple`, moving the text around them to other places in the document, so they are written as a complex field.
*/
const MARKER_FIELD = /^\s*(?:XE|TC|TA|RD|PRIVATE)\b/i;
/**
* @internal
*/
class FieldInstructionText extends XmlComponent {
public constructor(instruction: string) {
super("w:instrText");
this.root.push(new TextAttributes({ space: SpaceType.PRESERVE }));
this.root.push(instruction);
}
}
/**
* @internal
*/
@@ -35,6 +56,10 @@ export type ISimpleFieldOptions = {
* in a single element, unlike complex fields which use separate begin/end markers.
* Simple fields are typically used for fields that don't require complex nesting.
*
* Fields that mark a place and have no result, such as an index entry (`XE`) or a table of contents entry (`TC`), are
* written as a complex field in a run (`w:r`), as Word writes them, because Word moves the text around them when it
* reads them as a `w:fldSimple`. They have no cached value, so one given isn't written.
*
* Reference: http://www.datypic.com/sc/ooxml/e-w_fldSimple-1.html
*
* @publicApi
@@ -61,6 +86,9 @@ export type ISimpleFieldOptions = {
*
* // Locked field, Word keeps the cached value when fields are updated
* new SimpleField("DATE", "2024-01-01", { locked: true });
*
* // Index entry, for an INDEX field to list
* new SimpleField('XE "Apples"');
* ```
*/
export class SimpleField extends XmlComponent {
@@ -68,7 +96,14 @@ export class SimpleField extends XmlComponent {
declare private readonly brand: "SimpleField";
public constructor(instruction: string, cachedValue?: string, options: ISimpleFieldOptions = {}) {
super("w:fldSimple");
const marker = MARKER_FIELD.test(instruction);
super(marker ? "w:r" : "w:fldSimple");
if (marker) {
this.root.push(createBegin(undefined, options.locked ? true : undefined));
this.root.push(new FieldInstructionText(instruction));
this.root.push(createEnd());
return;
}
this.root.push(new FldSimpleAttrs({ instr: instruction, fldLock: options.locked ? true : undefined }));
if (cachedValue !== undefined) {
this.root.push(new TextRun(cachedValue));