Cross-Platform Document Editor: Engineering Decisions for a Clean-Room Rewrite in Rust and WebAssembly
This article breaks down the engineering practice behind building a cross-platform word processor from the ground up. It covers why a system-level language plus WebAssembly is a viable foundation, how to layer a shared kernel against platform-specific hosts, how the document model and layout engine fit together, what it takes to open and save office formats without losing information, how complex features such as tables, revisions, spell check and mail merge are implemented, how AI-assisted development is scoped safely, and how layered testing and a restrained release cadence protect quality. It is written for engineers and teams considering entry into document processing who care more about transferable method than about any specific product.
1. Introduction: Why Rebuild a Document Editor at All
A word processor looks like a simple “type text, adjust layout” tool. In reality, it is one of the most complex categories of desktop software. It has to solve three layers of problems at once:
- Document model: paragraphs, character styles, style inheritance, pagination, tables, headers and footers — all interrelated, forming a tree that must be maintained for the long term.
- Layout computation: line breaking, inline alignment, baseline alignment, widow and orphan control, float wrapping. Every step directly affects the reading experience.
- Format compatibility: the documents users bring in come from many different office applications with different internal structures and rules. The editor has to balance “opens and is immediately usable” against “saves without losing anything.”
In recent years, more and more projects have rewritten this kind of foundational software in system-level languages. One representative example is a free, cross-platform word processor built by an individual developer with the help of AI coding tools, implemented as a clean-room rewrite (referred to below as the “reference implementation”). Its approach can be summarized as follows:
- Written in Rust, a language known for memory safety, no garbage collection pauses, and cross-platform compilation.
- The core compiles both into native programs for each desktop operating system and into a WebAssembly module that runs in the browser.
- The UI uses a ribbon-style design covering document styles, tables, revisions, comments, spell and grammar checking, and mail merge.
- On the format side it can open and save the standard office document format, is compatible with the Open Document Format, Rich Text Format, web markup, lightweight markup and plain text, and can export to the Portable Document Format (PDF).
Worth noting: the same developer built spreadsheet and presentation components with the same approach, forming a three-piece suite covering mainstream office scenarios. That suggests the same architectural method can be reused across document types.
This article strips out the specific product and distills the practice into seven key engineering questions, examining the design tradeoffs and implementation points of each:
- Technology selection;
- Architectural layering;
- Document model and layout;
- Format compatibility;
- Complex feature modules;
- AI-assisted development;
- Testing, delivery and release cadence.
2. Technology Selection: Why a System Language and WebAssembly
2.1 Writing the Kernel in a System-Level Language
The kernel of a document editor involves a large amount of tree manipulation, text slicing and string processing, with high demands on performance and predictability. A system-level language such as Rust offers three main advantages in this scenario:
- Memory safety: null pointers, data races, and use-after-free are ruled out at compile time. A document processor loads untrusted external files, so these guarantees directly shrink the attack surface.
- Predictable latency: with no garbage collector, layout and rendering do not suffer indeterminate pauses, which makes scrolling long documents noticeably smoother.
- One codebase, multiple targets: the same kernel compiles to a native program or to WebAssembly, and is reused across every platform.
2.2 Extending to the Browser with WebAssembly
WebAssembly is a binary instruction format that runs in the browser at close to native speed. Once the kernel is compiled to WebAssembly, the browser build and the desktop build share the same model and layout code; the only difference is the display and system capabilities the host provides.
That said, the browser sandbox imposes clear limits: file access generally requires explicit user permission, clipboard and printing behavior are constrained by permissions, and the set of available system fonts is limited. So the browser version is better positioned as a lightweight companion than as a full replacement for the desktop version.
2.3 Dividing Labor Between the UI Layer and the Kernel Layer
Judging by the shape of the reference implementation, desktop and browser share one kernel, and the UI very likely uses either a cross-platform GUI toolkit or a web technology stack. Whatever the concrete implementation, the UI layer should do only four things: render layout results, translate input into editing commands, present menus and dialogs, and provide status feedback. The moment UI logic leaks into the kernel, cross-platform reuse breaks down quickly.
3. Overall Architecture: One Kernel, Many Hosts
3.1 Layer Responsibilities
| Layer | Main responsibilities | Key constraints |
|---|---|---|
| Kernel | Document model, style system, layout engine, editing commands, undo/redo | No dependency on a windowing system, font files or the filesystem; can run standalone in tests |
| Format layer | Parsing and serialization of the standard office format, plus Open Document, rich text, web markup, lightweight markup and plain text | Input and output are byte streams or streaming interfaces; can be fuzz-tested on its own |
| Service layer | Spell and grammar checking, mail merge, auto-update, anonymous crash reporting (optional) | Decoupled from the UI; can run on background threads or in a separate process |
| Host layer | The desktop native host creates windows, opens file dialogs, and calls system font and printing interfaces; the browser host handles WebAssembly loading and page integration | Implements only platform differences; all business logic is pushed down |
The direct benefits of this layering are:
- The kernel can be tested without a GUI, so unit tests run extremely fast.
- The kernel can be reused server-side, for example to provide a document conversion service.
- The format layer is isolated from itself and from the kernel: adding a new format requires no kernel changes.
3.2 Command-Based Editing: Every Modification Follows the Same Path
All editing operations are uniformly wrapped as “commands,” and every command must supply two sets of logic — forward apply and reverse revert. Schematically:
/// Unified interface for editing commandspub trait EditCommand {/// Apply forward, returning a document snapshot or change setfn apply(&self, doc: &mut Document) -> Result<ChangeSet, EditError>;/// Revert backward; undo must return to exactly the pre-execution statefn revert(&self, doc: &mut Document, change: &ChangeSet) -> Result<(), EditError>;}/// Intermediate state during input (such as IME composition) must collapse into a single undo steppub struct Transaction {commands: Vec<Box<dyn EditCommand>>,}impl Transaction {pub fn commit(self) -> Vec<ChangeSet> {self.commands.into_iter().filter_map(|cmd| cmd.apply(/* … */).ok()).collect()}}
The value of this approach:
- Undo and redo come for free; no per-operation undo logic is needed.
- The command log can be persisted, so unsaved edits can be recovered after a crash.
- Consistency checks can be run before and after each command, for example verifying that style references are still valid.
4. Document Model and Layout Engine
4.1 A Layered Document Model
A practical document model usually has four layers:
- Document: holds global information such as the style table, numbering definitions and page setup.
- Section: carries page-level information — paper size, margins, headers and footers. A document may contain multiple sections.
- Block-level content: paragraphs, tables, images, lists and so on, determining how content stacks vertically.
- Inline content: text runs, links, comment and revision anchors — carrying character-level formatting.
/// Simplified sketch of the document modelpub struct Document {pub sections: Vec<Section>, // Sections: page setup, headers and footerspub styles: StyleTable, // Style table: built-in and user-defined stylespub numbering: NumberingTable, // Numbering definitions: multilevel lists, bullets}pub struct Section {pub page_setup: PageSetup, // Paper size, margins, columnspub blocks: Vec<Block>, // Block-level content such as paragraphs and tables}pub enum Block {Paragraph(Paragraph),Table(Table),}pub struct Paragraph {pub ppr: ParaProperties, // Paragraph properties: style reference, alignment, indentspub runs: Vec<Run>, // Inline content}pub struct Run {pub rpr: RunProperties, // Character properties: font, size, boldpub content: RunContent, // Text, symbols, image references}
4.2 Style Inheritance and Property Overrides
One of the hardest problems in a document editor is that property values come from too many places: paragraph style, character style, numbering style, direct formatting and theme fonts can all affect the final result. The usual engineering solution is to define a property resolution order for each element type, with priority roughly: document defaults < table/list styles < paragraph style < character style < direct formatting. Resolution merges level by level into the “effective properties,” which are then handed to the layout engine.
Style references must also handle two kinds of anomalies:
- Missing styles: the document references a style that does not exist locally. Fall back to the semantically closest built-in style rather than erroring out.
- Circular inheritance: when style A is based on style B and B is based on A, the cycle must be detected and broken during resolution; otherwise you get infinite recursion.
4.3 Core Stages of the Layout Engine
Layout is fundamentally the process of “placing” inline content onto a page, in roughly four steps:
- Text shaping: generate a glyph sequence and positions according to language and font, handling ligatures, kerning, and contextual forms in complex scripts. For complex scripts represented by Arabic and Devanagari, letter shapes change with position, so you must rely on a mature shaping library.
- Line breaking: break text at semantically permitted positions according to the Unicode line breaking algorithm, while avoiding problems such as punctuation at the start of a line or improper hanging punctuation at the end.
- Inline and paragraph layout: determine line height and baseline, handle alignment of super/subscripts and images with text, then stack the lines into a paragraph.
- Page layout: decide pagination points, follow widow and orphan rules (avoiding a paragraph’s first or last line sitting alone at the bottom or top of a page), then handle headers, footers and page numbers.
4.4 Incremental Layout and Long Documents
Re-laying out the whole document on every keystroke is unacceptable. Common optimizations include:
- Dirty-region marking: only the paragraphs whose content changed, and the content after them, need reflow.
- Lazy pagination: compute subsequent page numbers only when the user scrolls nearby.
- Line-level caching: record how many pages each paragraph occupies to avoid repeated computation.
- Virtualized rendering: render only the paragraphs and pages near the viewport.
5. Format Compatibility: Closing the Open-Edit-Save Loop
5.1 The Parsing Pipeline
Most mainstream office document formats are built on a “compressed archive + XML parts” structure: the archive contains several parts — the main document body, style sheet, relationship files, media assets — and the parts reference each other through relationship files. A robust parsing pipeline usually has four steps:
- Verify the file signature to decide whether it is a supported format.
- Extract into memory or a temporary directory, capping individual part size and total extracted size to prevent a “zip bomb” from exhausting memory.
- Parse the body and style parts and build the internal model.
- Validate cross-references — for example, whether style IDs, numbering IDs and relationship IDs all resolve to definitions.
5.2 A Normalization Layer and a Fidelity Strategy
Different formats model the same concept very differently. For example:
- One format expresses columns with a section; another may use consecutive section-break markers.
- One format expresses lists through numbering definitions; another may write the numbers directly into the text.
If the parser maps external structures straight onto the internal model, the code spirals out of control quickly. A more robust approach is a normalization layer: every format first converts into a unified intermediate representation, and the internal model is generated from that layer. The kernel then needs to know nothing about the details of any external format.
For content that cannot be expressed losslessly, the conversion layer should classify fidelity explicitly:
| Fidelity level | Handling | What the user sees |
|---|---|---|
| Fully supported | One-to-one structural mapping | No difference |
| Approximate | Substitute the semantically closest internal properties and record the discrepancy | Appearance is broadly the same; details may differ |
| Unsupported | Kept as a non-editable placeholder object or dropped, with a notice | Clearly told which content was not preserved |
5.3 The “Minimal Rewrite” Principle at Save Time
Many compatibility problems appear during saving, not during loading. The ideal strategy is:
- Record the original bytes of each part when the document is loaded.
- On save, re-serialize only the parts that were modified.
- Write unmodified parts back verbatim.
This significantly reduces information loss from a simple “open and save” cycle.
5.4 A Test Matrix Across Formats
Format compatibility cannot be verified by clicking through the UI. Build a structured corpus of test documents covering:
- Multilingual text, including bidirectional and complex scripts;
- Merged cells and tables spanning pages;
- Documents containing revisions and comments;
- Embedded images, charts and formula objects;
- Multilevel numbering and cross-references;
- Headers, footers and sections.
Every document defines two sets of fields: “expected to be preserved” and “allowed to be lost.” Each commit runs the conversions automatically and compares against a baseline, so compatibility does not silently regress as features iterate.
6. Implementation Points for Complex Feature Modules
6.1 Tables
The difficulty in tables is not the cell itself but:
- Merged cells: you must maintain both a grid model and a display model, and it must be traceable which grid positions are covered after a merge.
- Page spanning: when a row does not fit entirely on the current page, whether to move the whole row or allow the row to split internally should be configurable.
- Nested tables: the width calculation of an inner table depends on the outer cell’s width, creating a risk of circular dependency, so a calculation order must be defined.
6.2 Revisions and Comments
A revision is essentially “an edit with metadata”: who inserted or deleted what, and when. Key implementation points:
- Revision metadata hangs on text runs rather than storing a separate copy of the document.
- Accepting a revision is equivalent to solidifying insertions into ordinary text and truly removing deletions.
- Rejecting a revision requires the reverse operation, so revisions naturally fit the command pattern.
- Comment anchors may become invalid after text changes, so anchor migration rules must be defined — for example, when the anchor is deleted, the comment points to the enclosing paragraph.
6.3 Spell and Grammar Checking
A checking engine generally has three parts:
- Language detection: pick a dictionary based on the language tag of a paragraph or run; when the tag is missing, a simple inference can be made from the character set and word frequency.
- Spell checking: the core is dictionary lookup plus edit-distance computation, typically using data structures such as a trie or a finite-state transducer that support fuzzy matching.
- Grammar and style checking: rule-based plus lightweight statistical models, covering common issues such as repeated words, missing spaces between CJK and Latin text, mixed full-width and half-width punctuation, long sentences and passive voice.
For performance, checking should run incrementally — only on changed paragraphs — and on a background thread so it never blocks typing.
6.4 Mail Merge
Mail merge is essentially batch generation from “template + data source”:
- Insert placeholders in the template that point to columns of the data source.
- Support conditional blocks, for example “do not show a paragraph when the amount is empty.”
- Support repeating blocks, used to generate table rows that vary with each data record.
- Validate fields before batch generation: a missing field should produce a clear message rather than blank output.
7. Practical Approach to AI-Assisted Development
7.1 Dividing the Work
The reference implementation illustrates a typical AI-assisted development model. Tasks can be grouped into three classes:
| Task type | Suited to AI | Human responsibility |
|---|---|---|
| Well-specified implementation | Data structure definitions, boilerplate, first drafts of unit tests | Interface design, confirming edge cases |
| Cross-format conversion | Generating parser skeletons from public specifications | Validating semantic correctness against real samples |
| Defect fixing | Reproduction cases, candidate root causes, draft patches | Reviewing patches, confirming no regressions |
7.2 The Engineering Value of a Clean-Room Rewrite
Implementing features from scratch without touching or copying any proprietary source code — relying only on public format specifications and the externally observable behavior of software — is a compliance-oriented practice worth borrowing. It avoids copyright disputes at the source, but it also imposes higher demands:
- Every implementation step must be grounded in evidence; ideally the prompt or comment should cite the corresponding clause of the public specification.
- Functional acceptance should be based on “behavioral equivalence,” meaning the same input produces the same visible result, not a comparison of implementation details.
- The license provenance of generated code must be traceable, to avoid pulling in snippets incompatible with the project’s license.
7.3 Risks and Boundaries
AI-assisted development is not risk-free:
- Hallucination: a model may generate interfaces or parameters that look plausible but do not exist, so all generated code must be validated by compilation and tests.
- Prompt injection: when document content or specification text is fed to the model, it may carry “instruction-like” text that nudges the model into off-target changes, so external content must be treated as untrusted data.
- Responsibility boundaries: AI can accelerate implementation, but it cannot replace architecture decisions, security review or performance validation.
8. Testing, Delivery and Release Cadence
8.1 A Layered Testing Strategy
| Test layer | Test target | Purpose |
|---|---|---|
| Unit tests | Command apply/revert, property resolution | Guarantee reversible logic and correct property computation |
| Property-based tests | Generate random documents for arbitrary input and verify invariants, e.g. “the document matches its initial state after undo” | Surface boundary defects |
| Format round-trip tests | Round-trip conversion among multiple formats | Prevent compatibility regressions |
| Fuzzing | Feed the parser random or malformed byte streams | Guarantee no crashes and no out-of-bounds access |
| End-to-end tests | Launch the UI, open a file, edit, save | Verify the complete user path |
8.2 Release Cadence
The reference implementation is still at the RC (release candidate) stage, with an English-only UI. From an engineering standpoint this is a fairly restrained approach: a candidate version means features are essentially frozen and the focus shifts to defect fixes and compatibility verification. A sensible release cadence can be divided into:
- Early development builds: incomplete features, frequently changing interfaces, for developers only.
- Beta: main features usable, opened up to early users for feedback.
- Release candidate: features frozen, defects and compatibility issues addressed in a concentrated push.
- General availability: released after validation across multiple platforms and formats.
In addition, the project source is published on a code hosting platform, so users can fetch and test it themselves. This openness helps broaden test coverage and lets the community find platform-specific issues earlier.
8.3 Recommendations for Users
For users, a candidate build is better suited to evaluation and testing than to important commercial documents. The guidance from the reference implementation’s maintainers is pragmatic:
- Keep a backup of the original file for important documents.
- When something must be delivered externally, export to PDF first to guarantee consistent layout.
- If you hit a compatibility problem, keep the original file and submit feedback rather than continuing to edit the converted copy.
9. Conclusion
A document editor with a Rust kernel and WebAssembly as the bridge shows one viable path for modern foundational software: use a system-level language to guarantee safety and performance, one unified kernel to cover multiple platforms, public specifications to achieve format compatibility, AI assistance to accelerate development, and rigorous testing plus a restrained release cadence to hold the quality line.
For teams or individual developers planning to enter document processing, what is truly worth borrowing is not a specific product but this method: layer first, model next, then compatibility — and treat compatibility as an engineering problem of continuous verification, not a one-time feature.
