Fields and cross-references

Configure field results, legacy form fields, and table of contents removal in the DOCX editor.

A DOCX field stores an instruction and an optional saved result. The editor preserves both through open and save. It evaluates a defined set of display-only fields.

Field instructions stay inert. The editor never runs macros, DDE instructions, OLE content, or external include instructions such as INCLUDETEXT and INCLUDEPICTURE. External image links never fetch content.

Supported fields

FieldBehavior
PAGE, NUMPAGES, SECTIONPAGESUpdate in headers, footers, and the body. A hidden saved result stays hidden. An = formula over these fields, such as { = { PAGE } } or { = { NUMPAGES } - { PAGE } }, updates the same way. See Page number formulas. These fields and formulas also update inside another field's result, such as { QUOTE "x" { PAGE } }. In the body, that result keeps its saved text when it holds a space or more than 32 characters. A PAGE field that is a tracked deletion shows the live value. A page field whose instruction alone is a tracked deletion shows nothing. In the original view, such a field shows its value when it has no live instruction element. Otherwise it keeps its saved result.
STYLEREFUpdates supported character-style and paragraph-style references in headers. A paragraph without a paragraph style matches the default paragraph style. A paragraph style outranks a character style with the same name. Supports \l and \* MERGEFORMAT. With \n or \w, shows the list number of a paragraph-style match: \n shows only the number text of the paragraph's own level, and \w adds the higher levels. A match without a number shows 0.
REFResolves bookmark text or numbering in the body and notes.
NOTEREFResolves a bookmarked footnote or endnote reference number.
AUTONUM, AUTONUMLGL, AUTONUMOUTGenerate separate number sequences in document order.
LISTNUMNumbers from the document's list definitions in the body. Without a name, uses the list of its paragraph or of the last numbered paragraph before it, else the built-in list. Without \l, a field in a numbered paragraph uses the next level down. In the built-in list, the level is the paragraph's outline level, else the level below the last heading.
SYMBOLRenders the requested character, font, and size.
Selected metadata fieldsRender sanitized values from document properties.
DATE, TIMEShow the saved result. With fieldDate, fields with a \@ picture show that date.
FILENAME, SEQ, EQ, CITATION, BIBLIOGRAPHYShow the saved result. No new value is calculated.

Other fields show their saved result. REF, PAGEREF, and NOTEREF with \h link to their bookmark. For switch support, wrapping, and header pagination, see DOCX fidelity.

Page number formulas

An = formula updates on each page when its operands are PAGE, NUMPAGES, or SECTIONPAGES fields and numbers, such as { = { PAGE } + 1 }.

  • The operators are unary minus, ^, *, /, +, -, and the comparisons =, <>, <, <=, >, and >=. Parentheses group terms. A comparison shows 1 or 0.
  • The result shows as many decimal places as its most precise number, and at least two after a division. Trailing zeros are removed: { = { PAGE } / 3 } shows 0.33 on page 1 and 1 on page 3.
  • A \# picture without a decimal point rounds the result to a whole number. A negative result shows only through a picture of 0 digits, such as 00.
  • A \* number format, such as \* roman, shows only whole results of zero or more.
  • An operand can have the \* Arabic switch. Any other operand switch keeps the saved result.
  • A formula keeps its saved result on a page where it has no value, such as after a division by zero, or a result its switches cannot show.
  • A formula keeps its saved result when it uses functions, bookmarks, table cells, %, a repeated ^, a negative exponent, a formula as an operand, or a picture with a decimal point.
  • A formula over a bare PAGE keeps its saved result in a section whose page numbers are not digits, such as roman numerals. Use { PAGE \* Arabic } as the operand there.
  • A formula without a page field, and a formula that is a tracked deletion, keep their saved results. A formula whose = alone is a tracked deletion shows nothing.

Show the current date

The value of a DATE or TIME field is the current date and time, so its saved result shows the date of the last update. By default, the editor shows saved results. Set fieldDate when you create the editor to show a date instead:

import { createDocxEditor } from '@docx-editor.dev/core';

const editor = createDocxEditor({
  container,
  document: bytes,
  fieldDate: new Date(),
});
  • Only fields with a \@ date-time picture show the date. A field without a picture, or with \l, \h, \s, or a casing switch, shows its saved result.
  • Pictures support d, dd, ddd, dddd, M, MM, MMM, MMMM, y, yy, yyyy, Y, YY, YYYY, h, hh, H, HH, m, mm, ss, AM/PM, am/pm, and quoted text. Both AM/PM and am/pm show AM or PM. A code repeated beyond these lengths, such as yyy or ddddd, another letter, a Thai picture item, or a backquoted SEQ name keeps the saved result. Inside quotes, \\ is a backslash and \" is a double quote.
  • Month and day names are English. A picture with a name keeps its saved result when the language of the field instruction is not English.
  • A complex field takes the language of the run that holds its instruction. A simple field (w:fldSimple) takes the language set by the document defaults, table style, or paragraph style. The result run's language applies only when none of them sets one.
  • The date shows in the local time zone.
  • The date is display-only. Saved files and collaboration sessions keep the saved results.
  • CREATEDATE, SAVEDATE, and PRINTDATE always show their saved results.
  • File > Print and File > Export > PDF pass the date to your PDF handler as ChromeExportView.fieldDate. Forward it to exportPdf as fieldDate, and the PDF shows the same dates. Fields show the date in the local time of the converter, so send the browser's wall-clock time to a server. See Convert PDF on the server.
  • exportPdf and exportMarkdown take a fieldDate option for conversions outside the editor. Without it, they show saved results. File > Export > Markdown does not pass the date. In your Markdown handler, pass the same Date that you gave the editor to exportMarkdown.
  • An invalid Date, or fieldDate with fieldResults: 'editable', throws a TypeError. The option applies only at creation.
  • The React and Vue components take the same fieldDate prop. They read it once, when they create the editor. To show another date, remount the component.

Edit saved field results

Set fieldResults to 'editable' when you create the editor to let users edit saved results:

import { createDocxEditor } from '@docx-editor.dev/core';

const editor = createDocxEditor({
  container,
  document: bytes,
  fieldResults: 'editable',
});

The packaged editor and DocxEditor.Root accept the same prop:

import { DocxEditor } from '@docx-editor.dev/react';

export function FieldEditor({ bytes }: { bytes: Uint8Array }) {
  return <DocxEditor document={bytes} fieldResults="editable" />;
}

The option applies only at creation. Later prop changes have no effect and log a development warning. By default, each field behaves as one unit.

Field kindIn editable mode
DATE, TIME, CREATEDATE, SAVEDATE, PRINTDATE, MERGEFIELD, HYPERLINK, QUOTE, FILENAME, FILLIN, SEQThe saved result is editable text.
Computed fields, such as PAGE, NUMPAGES, REF, PAGEREF, DOCPROPERTYStay one atomic unit.
A simple field (w:fldSimple) inside a complex field resultNot supported. Do not enable editable mode for these documents.
  • Manual edits save as result text. The editor does not calculate the field or set w:dirty.
  • An application that updates fields later can replace manual edits, except HYPERLINK display text and locked fields.
  • Suggesting mode tracks edits inside the result.
  • Text typed at either edge of a result stays outside the field.
  • Deleting only the result text leaves an empty field that acts as one unit. Typing goes beside it, and an adjacent Backspace or Delete removes it.
  • Editing the result of a w:fldSimple field converts it to an equivalent complex field.
  • If you set fieldResults: 'editable' and register a collaboration module, createDocxEditor throws a TypeError.
  • For a custom core integration, pass the same FieldResultsMode to layout, paragraphTextOf(), and each edit. The modes produce different text offsets.

Insert and update fields from code

The automation API inserts fields with the Office.js-shaped Range.insertField():

await runtime.run(async (context) => {
  const hit = context.document.body.search('see section ').getFirst();
  hit.insertField('After', 'Ref', '_Ref123456 \\h');
  await context.sync();
});

Insertion writes the instruction as text and never evaluates it. For field types, tracked insertion, and updateResult(), see Fields and pagination.

Refresh results on save

save() updates calibrated, writable REF and NOTEREF results in the body, footnotes, and endnotes. The refresh can add one undo step for all updated parts.

  • Locked fields, revision markup, nested or unsafe results, and protected content controls keep their saved result.
  • View mode, read-only sessions, and collaborative sessions do not rewrite results.
  • REF updates only when its saved result at open matches the computed value or is empty. Otherwise the saved result stays.

Legacy text form fields

Legacy FORMTEXT fields open the Field Options popup on double-click. Configure the popups and date parsing with these props:

PropPurpose
popups.textFormFieldReplaces the Field Options popup (default value, type, maximum length, format, fill-in).
popups.invalidTextFormFieldReplaces the alert for an invalid number or date.
localeParses date input. Defaults to en-US.
i18nSets interface strings. Independent of locale.

This example accepts Polish dates with the default English interface:

<DocxEditor document={bytes} locale="pl-PL" />

With pl-PL, 01.02.2030 means February 1. ISO input (2030-02-01) works in every locale. For popup composition, see Customize popups.

  • Unprotected fields: partial edits keep the field definition. Replacing the whole result removes the field definition.
  • Protected fields: with forms protection, filling keeps the definition and Tab moves between fields.
  • Protected input validates and formats when the user leaves the field.
  • Invalid pending protected input makes save() reject with code invalidArgs. The input stays for correction.
  • Date input supports Gregorian numeric dates and full English month names only.
  • A maximum length of 0 sets no length limit.

FORMCHECKBOX and FORMDROPDOWN fields toggle or select in one undo step. Disabled fields and viewing mode refuse changes. Suggesting mode also refuses them, because the value has no tracked form. Entry and exit macros never run.

Remove a table of contents

Run the removeToc command to remove a generated table of contents (TOC):

const tocId = editor.snapshot().tocContext?.id;
editor.exec({ type: 'removeToc', ...(tocId ? { tocId } : {}) });

Without tocId, the command targets the last right-clicked TOC, the TOC at the selection, or the only TOC. The removal is one undo step and synchronizes in collaboration sessions. The context menu offers Remove table of contents.

The command refuses and leaves the document unchanged in these cases:

  • Suggesting mode. A removal has no tracked form.
  • Locked or data-bound TOC content.
  • A section break before the end of the field, or a table or content control inside the field.

A successful removal handles nearby content as follows:

ContentAfter removal
Text before and after the fieldStays, joined into one paragraph.
A section break at the end of the TOCStays, in the joined paragraph or in an empty paragraph.
Comments and footnotes anchored wholly inside the TOCRemoved.
Bookmark and comment ranges that partly overlap the TOCStay. Their removed ends move to the deletion point.
A wrapper control locked only against deletionStays with its heading. The command removes only the field.

Generated TOC rows are read-only. Delete and Backspace do not remove them. Content that you insert right before a TOC, or right after its end mark, goes outside the field, so a refresh keeps it. This covers text, links, bookmarks, comments, notes, content controls, pictures, and charts. A table or a new TOC on a closing line goes after that line. The same placement applies to any field whose characters span paragraphs. When a tracked change or link holds a field character and text past it, it divides at that edge, and the insert goes between the two parts. An untracked insert at that edge keeps a tracked insertion one change, as typing inside it does.

Limits

  • Keyboard navigation does not stop before a TOC that starts its story, such as the first block of the body or of a table cell.
  • Computed fields stay atomic in every mode.
  • The editor refuses to insert an empty content control at a field edge inside a tracked change, link, or smart tag.
  • An inline content control that holds a field character never divides at the field edge.
  • Field instructions stay inert. Macros, DDE, OLE, and external include instructions never execute.
  • Saved results inside another field's instruction do not display, also when the instruction holds paragraph marks.
  • A paragraph inside a field instruction that holds plain text outside a nested field still displays. The text before the field and the text after its instruction then keep their own lines.
  • Paragraphs inside a field instruction do not display and do not advance list numbers. This also applies in table cells and content controls. Showing field instructions changes only table of contents fields, so these paragraphs stay hidden and other fields keep their saved results.
  • The text before a field and the text after its instruction share one line when the instruction holds paragraph marks. The line uses the first paragraph's formatting and the last paragraph's space after. The paragraphs stay separate in the document.
  • On that shared line, text, paragraph breaks, line breaks, and section breaks inserted at the start of the result go before the field instead. This includes composed text, tracked insertions, and formatting armed there. A table goes before the whole line. Text typed there takes the formatting of the text before the field, unless you arm a format.
  • The caret has one stop where the two sides meet. When the result starts a new line, or runs in the other direction, each side keeps its own stop. The editor state can report a caret at that stop as the start of the result paragraph.
  • Backspace, Delete, and the mergeParagraphs command do not join across a paragraph mark inside a field instruction. mergeParagraphs refuses with the unsupported code.
  • Enter, the splitParagraph command, and section breaks refuse to add a paragraph mark inside a field instruction. This includes the start of the field result when the two sides do not share one line, for example when the first paragraph ends a section. A table or a table of contents inserted in the field result goes before the paragraph that holds the start of the field. A rich paste there falls back to plain text, and the editor state reports a field-code-mark rejection.
  • Automation writes refuse to add or remove a paragraph mark inside a field instruction. An untracked range delete that covers the whole field, from its start through the end of its result, removes the field instead.
  • LISTNUM and REF in headers, footers, and text boxes keep their saved result.
  • NOTEREF with \p or \f keeps its saved result.
  • STYLEREF results longer than 4,096 characters keep their saved result.
  • STYLEREF with \r, \t, or \p, with \n or \w on a character style, or with \n or \w on a bullet or none number format match, keeps its saved result. In a document without a numbering part, \n and \w keep their saved results.
  • Header STYLEREF fields keep their saved results when the body exceeds the scan limits.
  • Header STYLEREF pagination stops with an error if it does not settle within its pass limit.
  • Option+F9 (macOS) or Alt+F9 (Windows) shows field instructions without changing the document.

See also