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

> Learn how the OfficeCLI refresh command recalculates document fields like page numbers and cross-references without altering content. Ensure your cached values are up-to-date.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: how-to-guide
- Published: 2026-08-08

---

**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](https://github.com/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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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.

```csharp
// 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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Refresh.cs) (lines 34-45), the backend selection follows this precedence:

```csharp
// 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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/ResidentServer.cs) (lines 28-33) handles refresh requests by:

```csharp
// 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:

```bash

# 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:

```bash

# 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:

```bash

# Ensure TOC page numbers match the rendered preview

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

```

## OfficeCLI Refresh Command Examples

### Basic Usage

```bash

# Recalculate all derived fields for a Word document

officecli refresh my-report.docx

```

### JSON Output for Scripting

```bash

# Parseable output for downstream automation

officecli refresh my-report.docx --json

```

Sample output structure:

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

```

### Pipeline Integration

```bash

# 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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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

- **Path:** [`src/officecli/Core/WordHtmlRefresh.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/WordHtmlRefresh.cs)
- **Role:** Cross-platform fallback using HTML rendering
- **Key methods:** `RefreshViaHtml`, `RegenerateAllTocs`, `ApplyPageNumbers` (lines 16-33)

### ResidentServer.cs

- **Path:** [`src/officecli/ResidentServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordPdfBackend.cs)) and cross-platform compatibility through HTML rendering ([`WordHtmlRefresh.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Refresh.cs) (lines 15-31), other Office formats like Excel or PowerPoint are not supported. The backend implementations—both [`WordPdfBackend.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordPdfBackend.cs) and [`WordHtmlRefresh.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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`](https://github.com/iOfficeAI/OfficeCLI/blob/main/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.