What Is the OfficeCLI 'refresh' Command and When to Use It for Reloading Document State

The OfficeCLI refresh command recalculates derived fields in Word documents—specifically Table-of-Contents page numbers, PAGE/NUMPAGES fields, and cross-references—without modifying visible content, ensuring cached values reflect the current document state.

The refresh command is a critical tool in the iOfficeAI/OfficeCLI toolkit for maintaining document accuracy. Whether you're automating document generation, integrating with CI pipelines, or using the live watch feature, understanding when and how to trigger a refresh prevents stale pagination and broken cross-references. This guide explains the command's internal architecture, dual-backend implementation, and precise usage scenarios based on the actual source code.

How the OfficeCLI Refresh Command Works

Command Architecture

The refresh functionality originates in src/officecli/CommandBuilder.Refresh.cs, where the command is registered with a clear description of its purpose: recalculating derived field values for Word .docx/.docm files.

// From CommandBuilder.Refresh.cs (lines 15-31)
new Command("refresh", "Recalculates derived field values (TOC page numbers, PAGE fields, cross-references) in a Word document")

The command builder handles three execution paths depending on runtime conditions:

  1. Resident server shortcut – If a officecli resident server already holds the target file in memory, the request forwards directly via req.Command = "refresh" (lines 23-28). This avoids disk reload and executes in-process.

  2. Word PDF backend – Primary path on Windows using COM automation.

  3. HTML fallback – Cross-platform alternative when Word is unavailable.

Backend Selection Logic

In CommandBuilder.Refresh.cs (lines 34-45), the backend selection follows this precedence:

// Pseudocode representing the selection logic
if (WordPdfBackend.IsAvailable && Platform.IsWindows) {
    await WordPdfBackend.RefreshFields(document);
} else {
    await WordHtmlRefresh.RefreshViaHtml(document);
}

The Word PDF backend (WordPdfBackend.cs, lines 14-18) carries the [SupportedOSPlatform("windows")] attribute, restricting it to Windows hosts with Microsoft Word installed. This backend produces pagination identical to pressing F9 in Word itself.

The HTML fallback (WordHtmlRefresh.cs, lines 16-33) executes a multi-step process when native Word automation is unavailable:

  • Regenerates all TOCs via WordTocBuilder.RegenerateAllTocs
  • Renders document to HTML using headless browser pagination
  • Updates PAGEREF fields in the OpenXML package through ApplyPageNumbers

Resident Server Integration

When running officecli watch, the resident server in ResidentServer.cs (lines 28-33) handles refresh requests by:

// From ResidentServer.cs
case "refresh":
    await ExecuteRefresh(document);
    NotifyWatchers(FullRefreshOccurred);
    break;

This ensures live preview sessions automatically reload the latest state after any refresh operation.

When to Use the OfficeCLI Refresh Command

Situation Why refresh Is Required
After programmatic edits using set, add, or remove commands that modify headings, bookmarks, or referenced elements Cached page numbers become stale; refresh recomputes them from the updated document structure
Before export or preview operations when generating HTML/PDF output Guarantees pagination in the exported artifact matches the current logical structure
During officecli watch sessions after external file modifications outside OfficeCLI The watch server triggers full refresh automatically, but manual invocation ensures immediate consistency
On Windows with Word installed when exact pagination fidelity is critical Word PDF backend provides pixel-perfect layout matching native Word behavior
On Linux/macOS or CI environments without Word but requiring TOC page numbers HTML fallback supplies best-effort pagination aligned with OfficeCLI's preview engine

Specific Use Cases

Document automation pipelines – When scripts insert content dynamically, page numbers shift. Refresh before final output:


# Insert content then immediately recalculate fields

officecli add my-report.docx --heading "New Section" "Content here"
officecli refresh my-report.docx
officecli export my-report.docx --pdf final-output.pdf

Cross-reference integrity – Bookmarks and their references require recalculation after structural changes:


# After adding a bookmarked section, refresh to update all REF fields

officecli add my-report.docx --bookmark "conclusion" "Conclusion content..."
officecli refresh my-report.docx

Preview accuracy – The HTML preview relies on current pagination data:


# Ensure TOC page numbers match the rendered preview

officecli refresh my-report.docx && officecli view my-report.docx

OfficeCLI Refresh Command Examples

Basic Usage


# Recalculate all derived fields for a Word document

officecli refresh my-report.docx

JSON Output for Scripting


# Parseable output for downstream automation

officecli refresh my-report.docx --json

Sample output structure:

{
  "success": true,
  "file": "my-report.docx",
  "backend": "WordPdf",
  "fieldsUpdated": 47,
  "tocsRegenerated": 2
}

Pipeline Integration


# Refresh then immediately open updated preview

officecli refresh my-report.docx && officecli view my-report.docx

# Full automation: refresh, verify, export

officecli refresh my-report.docx --json | jq -e '.success' && \
officecli export my-report.docx --pdf output.pdf

Implementation Details by Source File

CommandBuilder.Refresh.cs

  • Path: src/officecli/CommandBuilder.Refresh.cs
  • Role: Command definition, argument parsing, backend orchestration, result formatting
  • Key methods: Command constructor (lines 15-31), backend selection (lines 34-45)

WordPdfBackend.cs

  • Path: src/officecli/Core/WordPdfBackend.cs
  • Role: Windows-native COM interop with Microsoft Word
  • Platform constraint: [SupportedOSPlatform("windows")] (lines 14-18)
  • Key method: RefreshFields

WordHtmlRefresh.cs

ResidentServer.cs

  • Path: src/officecli/ResidentServer.cs
  • Role: In-process refresh handling for active watch sessions
  • Key integration: Notifies watchers of full refresh events (lines 28-33)

Summary

  • The refresh command recalculates derived fields—TOC page numbers, PAGE/NUMPAGES fields, and cross-references—in Word documents without modifying visible content.

  • Dual-backend architecture provides Windows-native accuracy via COM automation (WordPdfBackend.cs) and cross-platform compatibility through HTML rendering (WordHtmlRefresh.cs).

  • Resident server integration enables fast in-process refresh when officecli watch is active, with automatic notification to live watchers.

  • Invoke refresh after any programmatic edit affecting document structure, before export/preview operations, and whenever stale pagination would impact output quality.

Frequently Asked Questions

What file formats does the OfficeCLI refresh command support?

The refresh command currently supports Word .docx and .docm files only. According to the command definition in CommandBuilder.Refresh.cs (lines 15-31), other Office formats like Excel or PowerPoint are not supported. The backend implementations—both WordPdfBackend.cs and WordHtmlRefresh.cs—are Word-specific.

Does the refresh command work on Linux and macOS?

Yes, through the HTML fallback mechanism. When the Word PDF backend is unavailable (non-Windows platforms), WordHtmlRefresh.cs automatically provides best-effort pagination by rendering to HTML and extracting page numbers. However, this may not match Microsoft Word's exact layout. For identical pagination to Word, Windows with installed Office is required.

How does refresh differ from reopening the document in Word manually?

The refresh command automates what pressing F9 (Update Fields) does in Word—recalculating derived values without user interaction. The resident server capability also avoids the overhead of file reload from disk. When used in officecli watch mode, refresh propagates to live preview sessions automatically, something manual Word reopening cannot achieve.

Can I use refresh in CI/CD pipelines without Microsoft Office?

Yes. The HTML fallback in WordHtmlRefresh.cs executes on any platform with .NET runtime, using headless browser rendering to approximate pagination. While page numbers may differ slightly from Word's exact layout, they maintain consistency with OfficeCLI's own preview and export outputs, making this suitable for automated documentation workflows.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →