> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reducto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Concepts

`WordDocument` is an OfficeJS-like API. It follows the names and shapes of the [Word JavaScript API](https://learn.microsoft.com/en-us/javascript/api/word), so if you know `Word.run`, you know most of it.

It is **not** OfficeJS-compatible. It is not a drop-in replacement for Office.js, and add-in code does not run on it without changes. There is no `Word.run`, no request context and no `load`/`sync`. Some members are missing, some have a different shape, and some are extensions that Office.js does not have. The differences are below.

## Try it

Edit the script. The pages on the right show the result when you stop typing. Click a block on a page to go to the line that made it.

```ts theme={null}
// Pages 4–5 of "Attention Is All You Need"; the text, diagrams and equations are editable.
import { type WordDocument, type Paragraph } from "@reductoai/docx/officejs";

declare const doc: WordDocument;

type MathText = { tex: string };
type Content = string | MathText;
const math = (tex: string): MathText => ({ tex });
const dk = String.raw`d_k`;
const dv = String.raw`d_v`;
const dm = String.raw`d_{\mathrm{model}}`;
const inverseScale = String.raw`\frac{1}{\sqrt{d_k}}`;

function append(p: Paragraph, content: Content[]): void {
  for (const item of content) {
    if (typeof item === "string") p.insertText(item, "End");
    else p.insertMath(item.tex, "End");
  }
}

function style(p: Paragraph, size = 9.5): Paragraph {
  p.font.set({ name: "Times New Roman", size, color: "#000000", bold: false, italic: false });
  p.set({ alignment: "Justified", spaceBefore: 0, spaceAfter: 3 });
  p.format({
    keepNext: false,
    tabStops: null,
    leftIndentPt: 0,
    rightIndentPt: 0,
    firstLineIndentPt: 0,
  });
  p.setLineSpacing({ rule: "AtLeast", points: 10.5 });
  return p;
}

function paragraph(content: Content[]): Paragraph {
  const p = doc.body.insertParagraph("", "End");
  if (p.isListItem) p.detachFromList();
  append(p, content);
  return style(p);
}

function heading(number: string, text: string): void {
  const p = paragraph([`${number}    ${text}`]);
  p.font.bold = true;
  p.set({ spaceBefore: 6, spaceAfter: 5, alignment: "Left" });
  p.format({ keepNext: true });
}

function equation(tex: string, number?: string): void {
  const p = paragraph(["\t", math(tex), ...(number ? ["\t" + number] : [])]);
  p.set({ alignment: "Left", spaceBefore: 6, spaceAfter: 6 });
  p.tabStops = [
    { position: 198, alignment: "Center" },
    { position: 396, alignment: "Right" },
  ];
}

doc.setDefaultFont("Times New Roman");
doc.getStyles().getByName("Normal").font.set({ name: "Times New Roman", size: 9.5 });
const figure = style(doc.body.paragraphs.getFirst());
figure.spaceAfter = 0;
figure.setLineSpacing({ rule: "Exactly", points: 186 });

// Figure 2 is a native grouped drawing, with editable labels and connectors.
type Scene = Parameters<Paragraph["insertScene"]>[0];
const shapes: NonNullable<Scene["shapes"]>[number][] = [];
const lines: NonNullable<Scene["lines"]>[number][] = [];
function box(
  id: string,
  text: string,
  left: number,
  top: number,
  width: number,
  height: number,
  fill?: string,
): void {
  shapes.push({
    id,
    geometricShapeType: fill ? "RoundRectangle" : "Rectangle",
    left,
    top,
    width,
    height,
    text,
    textAnchor: "Middle",
    textAlign: "Center",
    // Word's default insets and spacing do not fit the small diagram labels.
    textMargins: 0,
    textSpacing: { spaceBefore: 0, spaceAfter: 0, lineSpacing: { rule: "Exactly", points: 10 } },
    ...(fill ? { fillColor: fill, lineColor: "000000", lineWeight: 1 } : {}),
    font: { name: fill ? "Arial" : "Times New Roman", sizePt: fill ? 7.5 : 10 },
  });
}
type Point = readonly [number, number];
function arrow(points: readonly Point[]): void {
  lines.push({ points, arrow: "End", lineColor: "000000", lineWeight: 0.7 });
}
box("left-title", "Scaled Dot-Product Attention", 20, 0, 158, 17);
box("right-title", "Multi-Head Attention", 240, 0, 135, 17);
box("q", "Q", 57, 143, 14, 14);
box("k", "K", 81, 143, 14, 14);
box("v", "V", 104, 143, 14, 14);
box("scores", "MatMul", 57, 124, 45, 13, "CCC5DF");
box("scale", "Scale", 63, 103, 31, 13, "FFFACB");
box("mask", "Mask (opt.)", 55, 82, 47, 13, "F8D0E5");
box("softmax", "SoftMax", 57, 61, 43, 13, "D3E9D7");
box("weighted", "MatMul", 73, 40, 46, 13, "CCC5DF");
arrow([
  [64, 143],
  [64, 137],
]);
arrow([
  [88, 143],
  [88, 137],
]);
arrow([
  [79.5, 124],
  [79.5, 116],
]);
arrow([
  [79.5, 103],
  [79.5, 95],
]);
arrow([
  [79.5, 82],
  [79.5, 74],
]);
arrow([
  [79.5, 61],
  [79.5, 53],
]);
arrow([
  [111, 143],
  [132, 143],
  [132, 46.5],
  [119, 46.5],
]);
arrow([
  [96, 40],
  [96, 27],
]);
for (const depth of [2, 1, 0]) {
  const offset = depth * 4;
  const suffix = String(depth);
  box("attention" + suffix, "", 248 + offset, 82 - offset, 103, 24, depth ? "EBEBEB" : "CCC5DF");
  for (const [index, label] of ["V", "K", "Q"].entries()) {
    box(
      "linear" + label + suffix,
      depth ? "" : "Linear",
      248 + index * 35 + offset,
      121 - offset,
      28,
      14,
      "E5EFEC",
    );
  }
}
shapes.find((s) => s.id === "attention0")!.text = "Scaled Dot-Product\nAttention";
for (const [index, label] of ["V", "K", "Q"].entries()) {
  box("input" + label, label, 253 + index * 35, 163, 17, 13);
  const x = 262 + index * 35;
  arrow([
    [x, 163],
    [x, 135],
  ]);
  arrow([
    [x, 121],
    [x, 106],
  ]);
}
box("concat", "Concat", 280, 52, 35, 14, "FFFACB");
box("output-linear", "Linear", 284, 27, 28, 14, "E5EFEC");
box("heads", "h", 359, 86, 12, 15);
arrow([
  [299.5, 74],
  [299.5, 66],
]);
arrow([
  [298, 52],
  [298, 41],
]);
arrow([
  [298, 27],
  [298, 18],
]);
figure.insertScene({
  shapes,
  lines,
  left: 20,
  top: 0,
  relativeFromH: "column",
  relativeFromV: "paragraph",
  name: "Figure 2 — attention mechanisms",
}).wrap = "None";
const caption = paragraph([
  "Figure 2: (left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.",
]);
caption.spaceAfter = 12;
paragraph([
  "of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.",
]);
heading("3.2.1", "Scaled Dot-Product Attention");
paragraph([
  'We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of dimension ',
  math(dk),
  ", and values of dimension ",
  math(dv),
  ". We compute the dot products of the query with all keys, divide each by ",
  math(String.raw`\sqrt{d_k}`),
  ", and apply a softmax function to obtain the weights on the values.",
]);
paragraph([
  "In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix ",
  math("Q"),
  ". The keys and values are also packed together into matrices ",
  math("K"),
  " and ",
  math("V"),
  ". We compute the matrix of outputs as:",
]);
equation(
  String.raw`\operatorname{Attention}(Q,K,V) = \operatorname{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V`,
  "(1)",
);
paragraph([
  "The two most commonly used attention functions are additive attention [2], and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of ",
  math(inverseScale),
  ". Additive attention computes the compatibility function using a feed-forward network with a single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.",
]);
const gradients = paragraph([
  "While for small values of ",
  math(dk),
  " the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of ",
  math(dk),
  " [3]. We suspect that for large values of ",
  math(dk),
  ", the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients",
  ". To counteract this effect, we scale the dot products by ",
  math(inverseScale),
  ".",
]);
// The mark goes mid-paragraph; text typed after it would take its superscript style.
const note = gradients.search("small gradients").getFirst().insertFootnote();
const noteText = [
  "To illustrate why the dot products get large, assume that the components of ",
  math("q"),
  " and ",
  math("k"),
  " are independent random variables with mean 0 and variance 1. Then their dot product, ",
  math(String.raw`q \cdot k = \sum_{i=1}^{d_k} q_i k_i`),
  ", has mean 0 and variance ",
  math(dk),
  ".",
];
// Keep the native footnote marker and append its editable text and equation.
doc.getStyles().getByName("Footnote Text").font.set({ name: "Times New Roman", size: 9 });
const noteParagraph = note.body.paragraphs.getFirst();
append(noteParagraph, [" ", ...noteText]);
for (const p of note.body.paragraphs.items) {
  style(p, 9);
  p.spaceAfter = 0;
  p.setLineSpacing({ rule: "AtLeast", points: 10 });
}
heading("3.2.2", "Multi-Head Attention");
paragraph([
  "Instead of performing a single attention function with ",
  math(dm),
  "-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values ",
  math("h"),
  " times with different, learned linear projections to ",
  math(dk),
  ", ",
  math(dk),
  " and ",
  math(dv),
  " dimensions, respectively. On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding ",
  math(dv),
  "-dimensional",
]).insertBreak("SectionNext", "After");

paragraph([
  "output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure 2.",
]);
paragraph([
  "Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.",
]);
equation(
  String.raw`\operatorname{MultiHead}(Q,K,V) = \operatorname{Concat}(\mathrm{head}_1,\ldots,\mathrm{head}_h)W^O`,
);
equation(
  String.raw`\text{where } \mathrm{head}_i = \operatorname{Attention}(QW_i^Q,KW_i^K,VW_i^V)`,
);
paragraph([
  "Where the projections are parameter matrices ",
  math(String.raw`W_i^Q \in \mathbb{R}^{d_{\mathrm{model}} \times d_k}`),
  ", ",
  math(String.raw`W_i^K \in \mathbb{R}^{d_{\mathrm{model}} \times d_k}`),
  ", ",
  math(String.raw`W_i^V \in \mathbb{R}^{d_{\mathrm{model}} \times d_v}`),
  " and ",
  math(String.raw`W^O \in \mathbb{R}^{h d_v \times d_{\mathrm{model}}}`),
  ".",
]);
paragraph([
  "In this work we employ ",
  math("h=8"),
  " parallel attention layers, or heads. For each of these we use ",
  math(String.raw`d_k = d_v = d_{\mathrm{model}}/h = 64`),
  ". Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.",
]);
heading("3.2.3", "Applications of Attention in our Model");
let bullets: number | undefined;
paragraph(["The Transformer uses multi-head attention in three different ways:"]);
for (const text of [
  'In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as [38, 2, 9].',
  "The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.",
  "Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to −∞) all values in the input of the softmax which correspond to illegal connections. See Figure 2.",
]) {
  const p = paragraph([text]);
  if (bullets === undefined) bullets = p.startNewList("bullet").id;
  else p.attachToList(bullets);
  p.set({ leftIndent: 36, firstLineIndent: -10, spaceAfter: 5 });
}
heading("3.3", "Position-wise Feed-Forward Networks");
paragraph([
  "In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.",
]);
equation(String.raw`\operatorname{FFN}(x) = \max(0,xW_1+b_1)W_2+b_2`, "(2)");
paragraph([
  "While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is ",
  math(String.raw`d_{\mathrm{model}} = 512`),
  ", and the inner-layer has dimensionality ",
  math(String.raw`d_{\mathrm{ff}} = 2048`),
  ".",
]);
heading("3.4", "Embeddings and Softmax");
paragraph([
  "Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension ",
  math(dm),
  ". We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to [30]. In the embedding layers, we multiply those weights by ",
  math(String.raw`\sqrt{d_{\mathrm{model}}}`),
  ".",
]);

for (const [index, section] of doc.sections.items.entries()) {
  section.pageSetup.set({
    pageWidth: 612,
    pageHeight: 792,
    leftMargin: 108,
    rightMargin: 108,
    topMargin: 72,
    bottomMargin: 56,
    headerDistance: 30,
    footerDistance: 39,
    pageNumberStart: 4 + index,
  });
}
// The excerpt starts at footnote 4.
doc.sections.getFirst().pageSetup.footnoteNumberStart = 4;
const footer = doc.sections.getFirst().getFooter("Primary");
footer.insertPageNumber({ template: "{page}", alignment: "center" });
for (const p of footer.paragraphs.items) {
  style(p);
  p.set({ alignment: "Centered", spaceAfter: 0 });
}
```

Live example

## No `run`, `load` or `sync`

Office.js sends a batch of commands to Word and waits. Here the document is in memory, so every property reads at once and every edit applies at once.

```ts theme={null}
// Office.js in Word
await Word.run(async (context) => {
  const paragraphs = context.document.body.paragraphs;
  paragraphs.load("items/text");
  await context.sync();
  paragraphs.items[0].insertText("Hello", "Start");
  await context.sync();
});

// @reductoai/docx
const paragraphs = doc.body.paragraphs;
paragraphs.items[0].insertText("Hello", "Start");
```

There is no `load()` and no `sync()`. Remove them when you port add-in code. Values that Office.js wraps in a `ClientResult` (for example `getReviewedText()`) have a `.value` that is ready at once.

## Handles and collections

* A collection (`paragraphs`, `tables`, `revisions`, `comments`) has `.items`, `.getFirst()`, `.getFirstOrNullObject()` and `.length`.
* Collections are **live**. Read them again after an edit that adds or removes items.
* A handle points into the document. When its content is removed (for example, a rejected revision), the handle throws `no longer part of the document`.
* Re-query ranges after you replace their text or change their container.

## Paragraph ids (`w14:paraId`)

Word gives each paragraph and table row a `w14:paraId`. Word keeps these ids on save only when every paragraph and row has a valid, unique id. If one id is missing, Word makes new ids for all of them.

A file with missing ids:

* Every paragraph and row gets an id, as Word does when it saves. When a file has no paraIds, or some are missing, the open fills them from the file's own text and order.
* Each open of the same file fills the same ids, and every copy in a live session fills them alike. Two different files get different ids.
* The filled ids go into the next save once you read a `uniqueLocalId` or make an edit. After that the ids come from the file, so a later text change, by us or by another tool, does not move them.
* A document whose ids nobody read and that nobody edited saves byte for byte. If you change only its properties (for example a custom property), the body, headers, footers and notes save as they were, with no filled ids.

Edits:

* Each paragraph and row that you add gets a new id. This applies to the facade, the editor and accepted suggestion cards.
* An edited paragraph keeps its id.
* A split follows Word: Enter at the end of a paragraph keeps the id on the first part, and Enter at any other position moves it to the second part.
* When two paragraphs join, the paragraph whose mark stays keeps its id.
* `insertParagraph` keeps the id on the paragraph you call it on. Word gives the id to the new paragraph instead. Both files are valid; only which paragraph holds the id differs.
* Word keeps all of these ids when it saves the file, and an edit in Word keeps a paragraph's id.

### `uniqueLocalId`

`Paragraph.uniqueLocalId` is a GUID built from the paragraph's paraId. Its first eight digits are the paraId. It stays the same after a save, a reload, a server restart and a round trip through Word. `doc.getParagraphByUniqueLocalId(id)` finds the paragraph in the body, a header, a footer or a note, and throws `ItemNotFound` when no paragraph has that id (for example, after you delete it).

```ts theme={null}
const id = doc.body.paragraphs.items[3].uniqueLocalId; // keep it in your own store
// ... later, in another session, after a reload ...
const again = await WordDocument.fromBytes(bytes);
again.getParagraphByUniqueLocalId(id).insertText(" (reviewed)", "End");
```

* This goes further than Word. Word makes a new `uniqueLocalId` for every paragraph each time Word starts, so add-in code written for Word must not expect it to last.
* The id is unique in one document only. A copy of a file, or a document made from one template, can have the same ids, so key your store by document and id.
* A split in the middle of a paragraph moves the id to the second part, as described above. The text after the split point keeps the id.
* Save the document after you read ids from a file that had none. If you do not save, the ids you read are not in the file, and an edit by another tool before the next open can change them.
* Reading every id costs time in proportion to the number of paragraphs: about 30 ms for 40,000 paragraphs. A lookup by id in the body takes about 1 ms at that size.

## Locations

Insert methods take an Office.js location. The values are case-sensitive.

| Location | Use with |
| - | - |
| `"Start"`, `"End"`, `"Replace"` | Text and content inside a paragraph, range or body |
| `"Before"`, `"After"` | A new sibling paragraph or table |
| `"Whole"` | `getRange("Whole")` |

## Units

Sizes are in **points** (72 per inch), as in Office.js. Table, row and column indexes start at 0.

## Extensions

Some members do not exist in Office.js but exist in Word's VBA object model (for example `setLineSpacing`, `documentDefaults`, `insertMath`). They have the VBA name, and the type docs mark them as extensions. Where Office.js has a member, OfficeJS follows its name and behavior.

## Layout-backed members

A few members need laid-out pages: `readPage()`, `getRects()`-style geometry, `updateFields()` (page numbers, TOC) and `toPdf()`. They need a **layout host**:

* In Node, `@reductoai/docx/node` installs one when you import it.
* In a page, call `browserLayoutHost({ fonts })` once. See [Office.js in the browser](https://docs.reducto.ai/office/docx/js-api/browser.md).
* With `@reductoai/docx/officejs` alone there is no host. Pure edits work; layout-backed members throw `No layout host`.

## Coverage

OfficeJS covers most of `Word.Document`, `Body`, `Paragraph`, `Range`, `Table`, `List`, `ContentControl`, `Comment`, `TrackedChange`, sections, headers and footers, styles, fields and pictures. The [API reference](https://docs.reducto.ai/office/docx/api/word-document.md) lists every member, and the members that throw because they are not implemented. A value that OfficeJS cannot write throws an error that tells you why; it does not fail silently.
