Tracked changes

Create tracked edits, inspect revisions by story, accept or reject changes, and change their author.

Set Document.changeTrackingMode to create tracked edits, and use RevisionCollection to review them. Create a runtime with Runtime and setup, and use document proxies inside runtime.run().

Create a tracked replacement

Set TrackMineOnly, then use an ordinary range edit:

await runtime.run(async (context) => {
  const matches = context.document.body.search('within 7 days', {
    matchCase: true,
  });
  matches.load('items');
  await context.sync();
  if (matches.items.length !== 1) throw new Error('Choose one deadline');

  context.document.changeTrackingMode = 'TrackMineOnly';
  matches.items[0]!.insertText('within 30 days', 'Replace');
  await context.sync();
});

Use insertText(text, 'Before' | 'After') to propose an insertion, and range.delete() or range.clear() to propose a deletion. The mode assignment and the edits commit together. A failed batch keeps the previous mode and document.

RequirementDetail
AuthorPass a nonempty author when you create the runtime.
Browser runtimeInstall the Pro review module on an editable editor.
Mode lifetimeThe mode persists across runs on that runtime. Load changeTrackingMode before you read it.
ScopeThe mode does not change the editor UI mode, peers' tracking settings, or a saved document policy.
ChangeTrackingModeBehavior
OffInitial mode. The runtime does not track its edits. If the browser editor is in suggesting mode, supported edits still become suggestions by the editor's author.
TrackMineOnlyRecords text and property changes by this runtime's author.
TrackAllFails with NotSupported.

Never turn tracking off automatically to make a refused edit succeed. Report the limit, or let your application choose a separately authorized permanent edit. Each successful sync is a separate suggestion, and a later refusal does not roll back earlier ones.

Supported tracked edits

EditBehavior with TrackMineOnly
Range textInsert, replace, or delete. Deletions can span adjacent sibling paragraphs. Replacements across paragraphs work outside collaboration.
Paragraph deletionParagraph.delete() proposes deleting the text and the paragraph mark.
Font and paragraph formattingRecords property revisions, including paragraph styles.
Paragraph insertion and splitTracks text and each new paragraph mark. Reject removes or joins them.
BreaksRange.insertBreak() tracks line, page, and next-page section breaks.
ListsTracks creation, membership, and level changes. You can configure newly proposed definitions.
TablesTracks complete insertion, cell values, row additions, and partial row deletions. See Tables and cells.
Content controlsWraps nonempty ordinary text in PlainText, RichText, or DatePicker controls, outside collaboration. The author can set the pending control's tag and title.
FieldsInserts an inert field as one tracked insertion. See Fields and pagination.
EquationsInserts one inline equation with insertOoxml() as one tracked insertion. A tracked deletion that covers an equation strikes the whole equation.

Your edits can go inside or beside another author's pending text insertion or deletion. Each author's change stays a separate decision. New text inside their insertion splits it into two revisions with the same identity, so decide both, or pass both to resolve().

These tracked edits fail with NotImplemented. debugInfo.innerError.code names the rule:

EditinnerError.code
A deletion or replacement that covers only deleted text and no paragraph markedit.tracked-deleted-text-only
An edit that touches another author's paragraph mark, formatting, move, or structural changeedit.tracked-foreign-revision-unsupported
New text inside a link or content control within another author's insertionedit.tracked-foreign-revision-unsupported
An edit that covers or borders your own pending change, such as a range that a tracked write returnededit.tracked-own-pending-change

These tracked edits also refuse:

  • Table and wrapper boundaries inside a tracked range.
  • A replacement that spans paragraphs in collaboration.
  • A deletion beside your own pending deletion, or directly before your own insertion. An append after your pending deletion at the paragraph tail works.
  • Text edits in a row with a pending row insertion or deletion.
  • Established list definitions, existing table properties and columns, pictures, page setup, and other structural edits.
  • Tracked table and cell value replacement in collaboration.

Propose structural edits

Propose a paragraph split

insertText() treats \n, \r, and \r\n as paragraph breaks. Replace only the gap between two sentences:

await runtime.run(async (context) => {
  context.document.changeTrackingMode = 'TrackMineOnly';
  const body = context.document.body;
  const first = body.search('the goods.').getFirst();
  const second = body.search('The buyer').getFirst();
  first.getRange('End').expandTo(second.getRange('Start')).insertText('\n', 'Replace');
  await context.sync();
});

The proposal strikes the space as a Delete and adds the paragraph mark as an Insert. Accept keeps the new paragraph, and reject joins them again. For break rules and refusals, see Split a paragraph.

Propose a field

Call Range.insertField() with TrackMineOnly. Reject removes the whole field. For the sample and result writes, see Propose a field as a tracked change.

Propose an equation

Call Range.insertOoxml() with TrackMineOnly. The equation and its plain runs form one tracked insertion. For the accepted package, see Insert an equation.

Propose removing paragraphs

Call Paragraph.delete() with TrackMineOnly. Delete adjacent paragraphs in one sync:

await runtime.run(async (context) => {
  const paragraphs = context.document.body.paragraphs;
  paragraphs.load('items/text');
  await context.sync();

  context.document.changeTrackingMode = 'TrackMineOnly';
  for (const paragraph of paragraphs.items) {
    if (paragraph.text.startsWith('Draft note:')) paragraph.delete();
  }
  await context.sync();
});

Accept removes the text and marks. Reject restores them.

One refused paragraph cancels every write in the sync. A range.delete() that covers one of these paragraph marks refuses with the same code:

ParagraphError code
The last paragraph of a story, table cell, or content controlNotSupported
A paragraph directly before a table or block content controlNotSupported
A paragraph whose mark ends a sectionNotSupported
A paragraph with an inline content controlNotSupported
A paragraph with a complex field boundary whose match is in another paragraphNotSupported
A paragraph that nests inline content more than 64 levels deepNotSupported
A paragraph with your own pending changeNotImplemented
A paragraph with another author's paragraph mark, formatting, move, or structural changeNotImplemented
A paragraph whose next paragraph starts with a pending changeNotImplemented
A paragraph whose previous mark you already proposed deletingNotImplemented

Propose several structural edits in one run

Each sync is one transaction. These rules decide which structural edits share a sync:

RuleResult
Edits in different paragraphsShare a sync. They commit together or not at all.
Two structural edits in one paragraphRefuse with ConflictingChanges. Sync after the first, read the range again, then make the second.
An object that a write returnsCan load in the same sync. Editing it before the sync fails with InvalidObjectPath.
insertBreak() other than a line breakRuns alone in its sync.

This sample proposes a split, a field, and an equation in three paragraphs. Search hits take edits in the sync that reads them, and ooxml holds an equation package from Insert an equation:

await runtime.run(async (context) => {
  context.document.changeTrackingMode = 'TrackMineOnly';
  const body = context.document.body;
  const one = body.search('One.').getFirst();
  const two = body.search('Two.').getFirst();
  one.getRange('End').expandTo(two.getRange('Start')).insertText('\n', 'Replace');
  body.search('Field here').getFirst().insertField('Before', 'Seq', 'Figure');
  body.search('Math here').getFirst().insertOoxml(ooxml, 'Before');
  await context.sync();
});

On refusal, error.debugInfo.errorLocation names the refused call, such as document.body.search.getFirst().insertOoxml. For conflicts, it names the later call. For more information, see Batching, loading, and errors.

To preview a tracked replacement before you commit it, use runtime.preview(). For more information, see Preview other wording before you write it.

Choose a text view

Option or memberReads
revisionTextView: 'allMarkup'Default runtime option. Text loads and search include insertions and deletions.
revisionTextView: 'original'Text loads and search keep pending deletions and hide pending insertions.
getReviewedText('Current')One paragraph or range as if every change were accepted. This is the default.
getReviewedText('Original')One paragraph or range as if every change were rejected.

revisionTextView is a DocxEditor host option, not an Office.js property. Neither member accepts or rejects revisions. Pass plain text, not live proxies, to a model.

Inspect changes

Load collection membership and the properties you need in one sync:

const pending = await runtime.run(async (context) => {
  const revisions = context.document.revisions;
  revisions.load('items/author,items/date,items/type');
  await context.sync();
  return revisions.items.map((revision) => ({
    author: revision.author,
    date: revision.date?.toISOString() ?? null,
    type: revision.type,
  }));
});

Revision.date is Date | null. Revision.type uses RevisionType, including Insert, Delete, CellInsertion, CellDeletion, CellMerge, and ParagraphNumber. Resolve Revision.range before you read it.

CollectionScope
Document.revisionsThe main story only. acceptAll() leaves header, footer, note, and text box changes pending.
Body.revisionsThat body's story, such as a header, footer, note, or text box.
Range.revisionsChanges the range overlaps, in document order, within its story.
Style definition changesNo collection. The editor's unfiltered Accept All and Reject All resolve them.
Comment text changesNo collection. Editor review actions resolve them.
Legacy w:numberingChange recordsNot revisions. Unfiltered bulk accept or reject removes them and keeps list membership.

RevisionCollection exposes items, resolve(), setAuthor(), acceptAll(), and rejectAll(). It has no first-item accessor.

Membership ruleDetail
Omitted historyitems omits formatting changes that leave resolved formatting unchanged, and history with no single type, such as a table grid change. Story-wide acceptAll(), rejectAll(), and resolve() still decide them.
Partial coverRange.revisions lists a change whole when the range covers part of it.
Collapsed rangeRange.revisions lists the changes that touch its position.
Paragraph marksRange.revisions lists a mark change only when the range continues into the next paragraph.
ReplacementsA replacement lists two members.
Text viewMembership uses document positions, so revisionTextView does not change it.

Accept or reject changes

Choose a decision call:

CallBehavior
Revision.accept(), Revision.reject()Decides one supported revision.
RevisionCollection.acceptAll(), rejectAll()Strict. Any unsupported change fails the whole sync and changes nothing.
RevisionCollection.resolve(action, revisions?)Partial. Decides supported changes and reports skipped ones.

A strict story-wide batch takes one call:

await runtime.run(async (context) => {
  context.document.revisions.acceptAll();
  await context.sync();
});

Strict calls follow these rules:

  • They ignore editor filters and include history that items omits.
  • An empty collection succeeds.
  • A row kept for a nested table fails them with review.retained-structure.
  • On a range collection, they resolve every change the range overlaps, including characters outside the range.

Resolve a batch of changes

Pass 'accept' or 'reject', and optionally revision objects from the same context and story:

await runtime.run(async (context) => {
  const revisions = context.document.revisions;
  revisions.load('items/author');
  await context.sync();

  const selected = revisions.items.filter((revision) => revision.author === 'Ada');
  const result = revisions.resolve('accept', selected);
  await context.sync();

  const { resolved, skipped, remaining } = result.value;
  console.log(resolved.length, skipped, remaining);
});

Omit the selection to process the whole story, including history that items omits. An empty array selects nothing. Duplicates resolve once.

RuleDetail
BatchKeep resolve() as the only write in its sync. Reads can share it. Use one sync for each story.
ResultRead result.value after the sync. A failed transaction commits nothing and leaves the result unloaded.
UndoChanges commit in one transaction and one undo step.
FiltersAPI batches do not inherit editor filters.
BrowserRequires the Pro review module and an editable document.
PermissionsProtection, content control locks, and collaboration permissions apply. Tracked-changes protection refuses every decision and author change.
Range collectionsresolve() and setAuthor() refuse with NotSupported. Use the story's collection.

Interpret skipped decisions

Result fieldMeaning
resolvedDecisions applied, with key, author, part name, and revision kind.
skippedDecisions left pending, with key, reason, revision metadata when known, and an optional detail.
remainingPending decisions in the story, including excluded and unsupported changes.
Skip reasonNext step
unsupported-revisionKeep the change, or edit the content directly with tracking off. With detail locked-content, remove the content lock first. With bound-content, a data binding keeps it.
incomplete-groupThe change resolves only with another change the selection leaves out, often a deleted row. Decide both in one call, or clear the filter that hides the other.
retained-structureA row stays to keep nested table content. Other selected changes may have applied.
unknown-revisionThe target no longer exists. Load the collection again.

Tracked-changes protection

If the document enforces tracked-changes protection (w:documentProtection with w:edit="trackedChanges"), reviewers can make tracked edits and comments only. Every decision call, resolve(), and setAuthor() then fails the sync with GeneralException and debugInfo.innerError.code edit.protected-content, and nothing changes. The live editor refuses the same decisions.

try {
  await runtime.run(async (context) => {
    context.document.revisions.acceptAll();
    await context.sync();
  });
} catch (error) {
  if (error.debugInfo?.innerError?.code === 'edit.protected-content') {
    // Leave the changes pending, or ask the document owner to lift the protection.
  }
}

If a strict batch fails with NotImplemented, or with GeneralException and review.locked-content or review.bound-content, use resolve() and report what remains. For StaleDocument, start a fresh run and load the revisions again.

Existing acceptAll() and rejectAll() calls keep their behavior. Use resolve() for partial batches and explicit selections.

Work with review items

A review panel lists cards from useReview().items or editor.getReviewItems(). These DocxEditor functions map a card key to the object model:

FunctionReturnsStale key
getReviewItemRevisions(context, key)The card's revision, or both halves of a replacementEmpty collection. acceptAll() fails with InvalidObjectPath.
getReviewItemRange(context, key)The range a revision or comment card coversFails the sync with ItemNotFound. So does a comment with no document anchor.
getReviewItemRangeOrNullObject(context, key)Same as getReviewItemRangeRange with isNullObject true.

The following sample accepts the change that a card shows:

import {
  getReviewItemRevisions,
  type DocxEditorRuntime,
} from '@docx-editor.dev/editor-api/browser';

function AcceptButton(props: { runtime: DocxEditorRuntime; item: { readonly key: string } }) {
  const { runtime, item } = props;
  const accept = () =>
    runtime.run(async (context) => {
      getReviewItemRevisions(context, item.key).acceptAll();
      await context.sync();
    });
  return <button onClick={accept}>Accept</button>;
}
  • The collection from getReviewItemRevisions refuses resolve() and setAuthor() with NotSupported.
  • A comment key refuses in getReviewItemRevisions, and a custom node key refuses in both functions.
  • Use getReviewItemRevisions() for the card's changes. The range's revisions can also include nested or overlapping changes by other authors.
  • Read keys immediately before use, because edits change them.

Office.js has no review queue, so these functions are not members of Office.js-shaped classes.

Change the author of tracked changes

RevisionCollection.setAuthor(author, selection?, options?) changes w:author on changes in one story. The changes stay pending:

await runtime.run(async (context) => {
  const result = context.document.revisions.setAuthor(
    'Ada Lovelace',
    { authors: ['Contract agent'] },
    { date: new Date() }
  );
  await context.sync();
  console.log(result.value.updated.length, result.value.skipped);
});
selectionSelects
{ authors }Every change by those authors
Revision[]Those changes. An empty array selects nothing.
OmittedEvery change in the story by every author, including history items omits
  • Without options.date, each change keeps its date.
  • Keep setAuthor() as the only write in its sync.
  • Revision objects stay valid; load author again to read the new value.
  • Browser writes require the Pro review module and an editable document.
Error codeCause
InvalidArgumentBlank author, invalid date or selection, or an object from another context. Thrown before anything queues.
ConflictingChangesAnother write shares the sync.
GeneralExceptionDocument protection refuses it, including tracked-changes, read-only, and comments-only protection.
NotSupportedA browser runtime has no Pro review module.
Result fieldMeaning
updatedChanged revisions, with key, author, previousKey, and previousAuthor.
skippedChanges that kept their author: unknown-revision or unsupported-revision, such as a table grid record.

Change authors in the editor

Run the setReviewChangesAuthor command. It runs in one undo step:

const result = editor.exec({
  type: 'setReviewChangesAuthor',
  authors: ['Contract agent'],
  date: new Date().toISOString(),
});
if (result.ok) console.log(result.revisionAuthors);
FieldBehavior
authorNew author. Defaults to the editor's author.
keysExact review item keys. Excludes scope and authors.
scope'visible' (default) uses active filters. 'document' includes hidden authors.
authorsNarrows the scope by exact w:author.
dateISO 8601 string. setAuthor() and adopt() take a Date.
unsupported'skip' (default) or 'fail'.

Review keys include author and date, so an updated change gets a new key. Map revisionAuthors.updated from previousKey to key. If nothing changes, the command returns changed: false and adds no undo step.

In React and Vue, useReview().adopt(items) runs this command. For more information, see Adopt suggestions as your own.

Refusal codeCause
invalidArgsBlank or missing author, invalid date or selection, or keys with scope or authors.
lockedThe document is open for viewing, or protection refuses the change.
notFoundNo selected change exists.
unsupportedNo Pro review module, only records with no author, or a skip with unsupported: 'fail'.

Resolve changes shown in the editor

The resolveAllReviewChanges command honors author visibility and the tracked-changes filter, including offscreen changes:

editor.setTrackedChangesFilter((revision) => revision.author === 'Ada');
const result = editor.exec({ type: 'resolveAllReviewChanges', action: 'accept' });
if (result.ok) console.log(result.revisions);
FieldBehavior
action'accept' or 'reject'.
keysKeys from editor.getReviewItems(). Overrides the filter.
scope'visible' (default) or 'document' for all authors in supported stories.
unsupported'skip' (default) or 'fail'. Pass scope: 'document' and unsupported: 'fail' for the earlier strict behavior.

The result has the same fields as resolve(), and remaining counts pending decisions across the document.

SelectionBehavior
No keysA filtered decision skips a change that would also resolve a hidden change.
KeysDecides as a card would.
RefusalWhen
notFoundNo listed change matches the scope or filter.
unsupportedNothing applies, unsupported: 'fail' meets a skip, or the keys name no pending change.
lockedThe document is open for viewing, protected, or locked by a content control.
boundA data-bound content control holds every selected change.

reviewCodeOfRefusal(result.reason) and reviewCodeOfSkip(skip) from @docx-editor.dev/core give review codes, such as review.locked-content. The reviewChangesResolved event reports action, resolvedCount, and skipped. For review controls and filters, see the Pro Tracked changes guide.

Compare two documents

document.compareFromBase64(base64File, options) records the differences from a revised copy as tracked changes. It requires reviewModule() from @docx-editor.dev/pro:

import { DocxEditor } from '@docx-editor.dev/editor-api';
import { reviewModule } from '@docx-editor.dev/pro';

const runtime = await DocxEditor.createServer(originalBytes, {
  modules: [reviewModule()],
});
await runtime.run(async (context) => {
  context.document.compareFromBase64(revisedBase64, { authorName: 'Legal' });
  await context.sync();
});
const redline = await runtime.save();
  • The compare first accepts existing tracked changes in both documents.
  • It replaces content in one edit and one undo step. Keep it as the only write in its sync.
  • It returns nothing. Load document.revisions afterward to count changes.
OptionSupport
authorNameDefault: the revised document's last author, then its creator, then Comparison. The editor command uses the editor's author first.
detectFormatChangesRecords character, paragraph, table, and section formatting. Default true.
removeDateAndTimeWrites revisions without dates.
compareTargetCompareTargetCurrent only. CompareTargetNew and CompareTargetSelected refuse.
removePersonalInformationtrue refuses with NotSupported.
addToRecentFiles, ignoreAllComparisonWarningsNo effect.
CauseError codeinnerError.code
No review moduleNotSupportededit.review-module-required
A collaborative sessionNotSupportededit.operation-unsupported
Decoded revised DOCX over 128 MiB, or over block and text limitsNotSupportededit.resource-limit
Empty base64, or an option of the wrong typeInvalidArgumentNone
Invalid base64, or not a DOCX packageInvalidArgumentedit.invalid-argument
Refused compareTarget or removePersonalInformationNotSupportedNone
Protection the compare would breakNotImplementededit.protected-content
Differences no tracked change can recordNotImplementededit.unsupported-content

document.compare(filePath) always refuses with NotSupported. For the editor workflow, see Compare documents.

Limits

Decisions can change more than the named revision:

SituationResult
A decision removes contentChanges inside it resolve too, including other authors' changes.
A change in text that another decision in the sync removesGoes with that text. Its own decision skips.
Rejecting a formatting changeRestores earlier properties. Another author's change inside them resolves and appears in resolved.
One half of a move or cell mergeResolves both halves. The other object then fails with InvalidObjectPath.
Nested text changesResolve alone. A range that overlaps part of a group resolves only the overlapped changes.
Run formatting inside a text changeResolves independently of the text change, unless the decision removes the formatted content.
Two decisions reach one change in a syncThe later one skips. Contrary decisions fail with ConflictingChanges.
Content-locked controlOnly decisions that keep the content apply. Others skip with locked-content, or fail with GeneralException and review.locked-content. Set ContentControl.cannotEdit to false to decide them.
Data-bound controlChanges stay pending, except paragraph formatting. Others fail with GeneralException and review.bound-content.
A decision empties a control or cellAn inline control gets a five-space placeholder. A block control and comment keep their last paragraph. A fully emptied block control moves inline to the next paragraph's start and gets the placeholder. A control with sdtLocked stays as an empty shell. Accepting the deletion of every paragraph in a cell, marks included, removes the cell. A row with no cells left, and a table with no rows left, go too.
Malformed w:ins or w:del wrappers holding paragraphsRefuse resolution and keep their content.
A decision removes paragraph marksRemoves an emptied paragraph before a block control or at a text box's end. Removes an emptied custom XML block when a following paragraph remains.
A decision removes all equation contentRemoves the equation.
A decision leaves two tables side by sideJoins them when their properties and grids match.
Bookmark, comment, or permission markers between deleted paragraphsDo not split the decision. Accept moves them to the join; reject keeps them.
Accepting a merge head whose continuation is in a deleted rowThe continuation stays pending until the row decision.
Rejecting an inserted cellAlso resolves its neighboring width change. A direct same-author width decision also resolves the cell. Other-author or indirect width decisions leave the cell pending.
Rejecting an alignment-only table changeRestores alignment only in rows with row or cell formatting history.
Removing a rowCan resolve a whole table formatting change, even when part of it lies outside the row.

How changes group into decisions:

ContentGrouping
Deletion or replacement right after your own pending insertionAllowed in one paragraph. It stays a separate decision.
Moved paragraph marksSeparate decisions. A complete paragraph move can take three calls.
Move with no sourceA mark outside the move range can group with its paragraph's moved text. Reject removes that mark and keeps the text.
Same-author cell insertions or deletionsGroup down one column across adjacent rows. Side-by-side cells stay separate.
Alignment-only table changeGroups with row or cell formatting history and takes that author's name. Without that history, no alignment revision appears.
Content control, hyperlink, simple field, or w:dir edgesSplit a change. Unchanged field characters also split it.
Final paragraph mark of a block controlSeparate, unless the control ends a cell.
Tracked row inside a row-level content controlOne revision.
EquationIts tracked content can join the surrounding text change. A deleted paragraph that holds an equation is one decision.

Identity and collaboration limits:

  • Use revision objects or review keys, not OOXML w:id values, which can repeat. Treat keys as opaque, and load them again after save and reopen.
  • If a new author would collide with another change, the editor gives the change a new w:id. Both stay separate decisions.
  • In collaboration, tracked replacements stay within one paragraph, and content control and table value proposals refuse.
  • Text a participant types into your proposed deletion joins it. A concurrent decision on another author's change applies to that change only.
  • For rendering and save detail, see DOCX fidelity.

See also