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.
| Requirement | Detail |
|---|---|
| Author | Pass a nonempty author when you create the runtime. |
| Browser runtime | Install the Pro review module on an editable editor. |
| Mode lifetime | The mode persists across runs on that runtime. Load changeTrackingMode before you read it. |
| Scope | The mode does not change the editor UI mode, peers' tracking settings, or a saved document policy. |
ChangeTrackingMode | Behavior |
|---|---|
Off | Initial 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. |
TrackMineOnly | Records text and property changes by this runtime's author. |
TrackAll | Fails 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
| Edit | Behavior with TrackMineOnly |
|---|---|
| Range text | Insert, replace, or delete. Deletions can span adjacent sibling paragraphs. Replacements across paragraphs work outside collaboration. |
| Paragraph deletion | Paragraph.delete() proposes deleting the text and the paragraph mark. |
| Font and paragraph formatting | Records property revisions, including paragraph styles. |
| Paragraph insertion and split | Tracks text and each new paragraph mark. Reject removes or joins them. |
| Breaks | Range.insertBreak() tracks line, page, and next-page section breaks. |
| Lists | Tracks creation, membership, and level changes. You can configure newly proposed definitions. |
| Tables | Tracks complete insertion, cell values, row additions, and partial row deletions. See Tables and cells. |
| Content controls | Wraps nonempty ordinary text in PlainText, RichText, or DatePicker controls, outside collaboration. The author can set the pending control's tag and title. |
| Fields | Inserts an inert field as one tracked insertion. See Fields and pagination. |
| Equations | Inserts 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:
| Edit | innerError.code |
|---|---|
| A deletion or replacement that covers only deleted text and no paragraph mark | edit.tracked-deleted-text-only |
| An edit that touches another author's paragraph mark, formatting, move, or structural change | edit.tracked-foreign-revision-unsupported |
| New text inside a link or content control within another author's insertion | edit.tracked-foreign-revision-unsupported |
| An edit that covers or borders your own pending change, such as a range that a tracked write returned | edit.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:
| Paragraph | Error code |
|---|---|
| The last paragraph of a story, table cell, or content control | NotSupported |
| A paragraph directly before a table or block content control | NotSupported |
| A paragraph whose mark ends a section | NotSupported |
| A paragraph with an inline content control | NotSupported |
| A paragraph with a complex field boundary whose match is in another paragraph | NotSupported |
| A paragraph that nests inline content more than 64 levels deep | NotSupported |
| A paragraph with your own pending change | NotImplemented |
| A paragraph with another author's paragraph mark, formatting, move, or structural change | NotImplemented |
| A paragraph whose next paragraph starts with a pending change | NotImplemented |
| A paragraph whose previous mark you already proposed deleting | NotImplemented |
Propose several structural edits in one run
Each sync is one transaction. These rules decide which structural edits share a sync:
| Rule | Result |
|---|---|
| Edits in different paragraphs | Share a sync. They commit together or not at all. |
| Two structural edits in one paragraph | Refuse with ConflictingChanges. Sync after the first, read the range again, then make the second. |
| An object that a write returns | Can load in the same sync. Editing it before the sync fails with InvalidObjectPath. |
insertBreak() other than a line break | Runs 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 member | Reads |
|---|---|
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.
| Collection | Scope |
|---|---|
Document.revisions | The main story only. acceptAll() leaves header, footer, note, and text box changes pending. |
Body.revisions | That body's story, such as a header, footer, note, or text box. |
Range.revisions | Changes the range overlaps, in document order, within its story. |
| Style definition changes | No collection. The editor's unfiltered Accept All and Reject All resolve them. |
| Comment text changes | No collection. Editor review actions resolve them. |
Legacy w:numberingChange records | Not 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 rule | Detail |
|---|---|
| Omitted history | items 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 cover | Range.revisions lists a change whole when the range covers part of it. |
| Collapsed range | Range.revisions lists the changes that touch its position. |
| Paragraph marks | Range.revisions lists a mark change only when the range continues into the next paragraph. |
| Replacements | A replacement lists two members. |
| Text view | Membership uses document positions, so revisionTextView does not change it. |
Accept or reject changes
Choose a decision call:
| Call | Behavior |
|---|---|
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
itemsomits. - 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.
| Rule | Detail |
|---|---|
| Batch | Keep resolve() as the only write in its sync. Reads can share it. Use one sync for each story. |
| Result | Read result.value after the sync. A failed transaction commits nothing and leaves the result unloaded. |
| Undo | Changes commit in one transaction and one undo step. |
| Filters | API batches do not inherit editor filters. |
| Browser | Requires the Pro review module and an editable document. |
| Permissions | Protection, content control locks, and collaboration permissions apply. Tracked-changes protection refuses every decision and author change. |
| Range collections | resolve() and setAuthor() refuse with NotSupported. Use the story's collection. |
Interpret skipped decisions
| Result field | Meaning |
|---|---|
resolved | Decisions applied, with key, author, part name, and revision kind. |
skipped | Decisions left pending, with key, reason, revision metadata when known, and an optional detail. |
remaining | Pending decisions in the story, including excluded and unsupported changes. |
| Skip reason | Next step |
|---|---|
unsupported-revision | Keep 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-group | The 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-structure | A row stays to keep nested table content. Other selected changes may have applied. |
unknown-revision | The 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:
| Function | Returns | Stale key |
|---|---|---|
getReviewItemRevisions(context, key) | The card's revision, or both halves of a replacement | Empty collection. acceptAll() fails with InvalidObjectPath. |
getReviewItemRange(context, key) | The range a revision or comment card covers | Fails the sync with ItemNotFound. So does a comment with no document anchor. |
getReviewItemRangeOrNullObject(context, key) | Same as getReviewItemRange | Range 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
getReviewItemRevisionsrefusesresolve()andsetAuthor()withNotSupported. - A comment key refuses in
getReviewItemRevisions, and a custom node key refuses in both functions. - Use
getReviewItemRevisions()for the card's changes. The range'srevisionscan 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);
});selection | Selects |
|---|---|
{ authors } | Every change by those authors |
Revision[] | Those changes. An empty array selects nothing. |
| Omitted | Every 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
authoragain to read the new value. - Browser writes require the Pro review module and an editable document.
| Error code | Cause |
|---|---|
InvalidArgument | Blank author, invalid date or selection, or an object from another context. Thrown before anything queues. |
ConflictingChanges | Another write shares the sync. |
GeneralException | Document protection refuses it, including tracked-changes, read-only, and comments-only protection. |
NotSupported | A browser runtime has no Pro review module. |
| Result field | Meaning |
|---|---|
updated | Changed revisions, with key, author, previousKey, and previousAuthor. |
skipped | Changes 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);| Field | Behavior |
|---|---|
author | New author. Defaults to the editor's author. |
keys | Exact review item keys. Excludes scope and authors. |
scope | 'visible' (default) uses active filters. 'document' includes hidden authors. |
authors | Narrows the scope by exact w:author. |
date | ISO 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 code | Cause |
|---|---|
invalidArgs | Blank or missing author, invalid date or selection, or keys with scope or authors. |
locked | The document is open for viewing, or protection refuses the change. |
notFound | No selected change exists. |
unsupported | No 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);| Field | Behavior |
|---|---|
action | 'accept' or 'reject'. |
keys | Keys 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.
| Selection | Behavior |
|---|---|
| No keys | A filtered decision skips a change that would also resolve a hidden change. |
| Keys | Decides as a card would. |
| Refusal | When |
|---|---|
notFound | No listed change matches the scope or filter. |
unsupported | Nothing applies, unsupported: 'fail' meets a skip, or the keys name no pending change. |
locked | The document is open for viewing, protected, or locked by a content control. |
bound | A 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.revisionsafterward to count changes.
| Option | Support |
|---|---|
authorName | Default: the revised document's last author, then its creator, then Comparison. The editor command uses the editor's author first. |
detectFormatChanges | Records character, paragraph, table, and section formatting. Default true. |
removeDateAndTime | Writes revisions without dates. |
compareTarget | CompareTargetCurrent only. CompareTargetNew and CompareTargetSelected refuse. |
removePersonalInformation | true refuses with NotSupported. |
addToRecentFiles, ignoreAllComparisonWarnings | No effect. |
| Cause | Error code | innerError.code |
|---|---|---|
| No review module | NotSupported | edit.review-module-required |
| A collaborative session | NotSupported | edit.operation-unsupported |
| Decoded revised DOCX over 128 MiB, or over block and text limits | NotSupported | edit.resource-limit |
| Empty base64, or an option of the wrong type | InvalidArgument | None |
| Invalid base64, or not a DOCX package | InvalidArgument | edit.invalid-argument |
Refused compareTarget or removePersonalInformation | NotSupported | None |
| Protection the compare would break | NotImplemented | edit.protected-content |
| Differences no tracked change can record | NotImplemented | edit.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:
| Situation | Result |
|---|---|
| A decision removes content | Changes inside it resolve too, including other authors' changes. |
| A change in text that another decision in the sync removes | Goes with that text. Its own decision skips. |
| Rejecting a formatting change | Restores earlier properties. Another author's change inside them resolves and appears in resolved. |
| One half of a move or cell merge | Resolves both halves. The other object then fails with InvalidObjectPath. |
| Nested text changes | Resolve alone. A range that overlaps part of a group resolves only the overlapped changes. |
| Run formatting inside a text change | Resolves independently of the text change, unless the decision removes the formatted content. |
| Two decisions reach one change in a sync | The later one skips. Contrary decisions fail with ConflictingChanges. |
| Content-locked control | Only 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 control | Changes stay pending, except paragraph formatting. Others fail with GeneralException and review.bound-content. |
| A decision empties a control or cell | An 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 paragraphs | Refuse resolution and keep their content. |
| A decision removes paragraph marks | Removes 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 content | Removes the equation. |
| A decision leaves two tables side by side | Joins them when their properties and grids match. |
| Bookmark, comment, or permission markers between deleted paragraphs | Do not split the decision. Accept moves them to the join; reject keeps them. |
| Accepting a merge head whose continuation is in a deleted row | The continuation stays pending until the row decision. |
| Rejecting an inserted cell | Also 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 change | Restores alignment only in rows with row or cell formatting history. |
| Removing a row | Can resolve a whole table formatting change, even when part of it lies outside the row. |
How changes group into decisions:
| Content | Grouping |
|---|---|
| Deletion or replacement right after your own pending insertion | Allowed in one paragraph. It stays a separate decision. |
| Moved paragraph marks | Separate decisions. A complete paragraph move can take three calls. |
| Move with no source | A 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 deletions | Group down one column across adjacent rows. Side-by-side cells stay separate. |
| Alignment-only table change | Groups 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 edges | Split a change. Unchanged field characters also split it. |
| Final paragraph mark of a block control | Separate, unless the control ends a cell. |
| Tracked row inside a row-level content control | One revision. |
| Equation | Its 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:idvalues, 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.