Docx
"Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
Source: Content adapted from anthropics/skills (MIT).
Overview
A user may ask you to create, edit, or analyze the contents of a .docx file. A .docx file is essentially a ZIP archive containing XML files and other resources that you can read or edit. You have different tools and workflows available for different tasks.
Workflow Decision Tree
Reading/Analyzing Content
Use "Text extraction" or "Raw XML access" sections below
Creating New Document
Use "Creating a new Word document" workflow
Editing Existing Document
-
Your own document + simple changes Use "Basic OOXML editing" workflow
-
Someone else's document Use "Redlining workflow" (recommended default)
-
Legal, academic, business, or government docs Use "Redlining workflow" (required)
Reading and analyzing content
Text extraction
If you just need to read the text contents of a document, you should convert the document to markdown using pandoc. Pandoc provides excellent support for preserving document structure and can show tracked changes:
# Convert document to markdown with tracked changes
pandoc --track-changes=all path-to-file.docx -o output.md
# Options: --track-changes=accept/reject/allRaw XML access
You need raw XML access for: comments, complex formatting, document structure, embedded media, and metadata. For any of these features, you'll need to unpack a document and read its raw XML contents.
Unpacking a file
python ooxml/scripts/unpack.py <office_file> <output_directory>
Key file structures
word/document.xml- Main document contentsword/comments.xml- Comments referenced in document.xmlword/media/- Embedded images and media files- Tracked changes use
<w:ins>(insertions) and<w:del>(deletions) tags
Creating a new Word document
When creating a new Word document from scratch, use docx-js, which allows you to create Word documents using JavaScript/TypeScript.
Workflow
- MANDATORY - READ ENTIRE FILE: Read
docx-js.md(~500 lines) completely from start to finish. NEVER set any range limits when reading this file. Read the full file content for detailed syntax, critical formatting rules, and best practices before proceeding with document creation. - Create a JavaScript/TypeScript file using Document, Paragraph, TextRun components (You can assume all dependencies are installed, but if not, refer to the dependencies section below)
- Export as .docx using Packer.toBuffer()
Editing an existing Word document
When editing an existing Word document, use the Document library (a Python library for OOXML manipulation). The library automatically handles infrastructure setup and provides methods for document manipulation. For complex scenarios, you can access the underlying DOM directly through the library.
Workflow
- MANDATORY - READ ENTIRE FILE: Read
ooxml.md(~600 lines) completely from start to finish. NEVER set any range limits when reading this file. Read the full file content for the Document library API and XML patterns for directly editing document files. - Unpack the document:
python ooxml/scripts/unpack.py <office_file> <output_directory> - Create and run a Python script using the Document library (see "Document Library" section in ooxml.md)
- Pack the final document:
python ooxml/scripts/pack.py <input_directory> <office_file>
The Document library provides both high-level methods for common operations and direct DOM access for complex scenarios.
Redlining workflow for document review
This workflow allows you to plan comprehensive tracked changes using markdown before implementing them in OOXML. CRITICAL: For complete tracked changes, you must implement ALL changes systematically.
Batching Strategy: Group related changes into batches of 3-10 changes. This makes debugging manageable while maintaining efficiency. Test each batch before moving to the next.
Principle: Minimal, Precise Edits
When implementing tracked changes, only mark text that actually changes. Repeating unchanged text makes edits harder to review and appears unprofessional. Break replacements into: [unchanged text] + [deletion] + [insertion] + [unchanged text]. Preserve the original run's RSID for unchanged text by extracting the <w:r> element from the original and reusing it.
Example - Changing "30 days" to "60 days" in a sentence:
# BAD - Replaces entire sentence
'<w:del><w:r><w:delText>The term is 30 days.</w:delText></w:r></w:del><w:ins><w:r><w:t>The term is 60 days.</w:t></w:r></w:ins>'
# GOOD - Only marks what changed, preserves original <w:r> for unchanged text
'<w:r w:rsidR="00AB12CD"><w:t>The term is </w:t></w:r><w:del><w:r><w:delText>30</w:delText></w:r></w:del><w:ins><w:r><w:t>60</w:t></w:r></w:ins><w:r w:rsidR="00AB12CD"><w:t> days.</w:t></w:r>'Tracked changes workflow
-
Get markdown representation: Convert document to markdown with tracked changes preserved:
pandoc --track-changes=all path-to-file.docx -o current.md -
Identify and group changes: Review the document and identify ALL changes needed, organizing them into logical batches:
Location methods (for finding changes in XML):
- Section/heading numbers (e.g., "Section 3.2", "Article IV")
- Paragraph identifiers if numbered
- Grep patterns with unique surrounding text
- Document structure (e.g., "first paragraph", "signature block")
- DO NOT use markdown line numbers - they don't map to XML structure
Batch organization (group 3-10 related changes per batch):
- By section: "Batch 1: Section 2 amendments", "Batch 2: Section 5 updates"
- By type: "Batch 1: Date corrections", "Batch 2: Party name changes"
- By complexity: Start with simple text replacements, then tackle complex structural changes
- Sequential: "Batch 1: Pages 1-3", "Batch 2: Pages 4-6"
-
Read documentation and unpack:
- MANDATORY - READ ENTIRE FILE: Read
ooxml.md(~600 lines) completely from start to finish. NEVER set any range limits when reading this file. Pay special attention to the "Document Library" and "Tracked Change Patterns" sections. - Unpack the document:
python ooxml/scripts/unpack.py <file.docx> <dir> - Note the suggested RSID: The unpack script will suggest an RSID to use for your tracked changes. Copy this RSID for use in step 4b.
- MANDATORY - READ ENTIRE FILE: Read
-
Implement changes in batches: Group changes logically (by section, by type, or by proximity) and implement them together in a single script. This approach:
- Makes debugging easier (smaller batch = easier to isolate errors)
- Allows incremental progress
- Maintains efficiency (batch size of 3-10 changes works well)
Suggested batch groupings:
- By document section (e.g., "Section 3 changes", "Definitions", "Termination clause")
- By change type (e.g., "Date changes", "Party name updates", "Legal term replacements")
- By proximity (e.g., "Changes on pages 1-3", "Changes in first half of document")
For each batch of related changes:
a. Map text to XML: Grep for text in
word/document.xmlto verify how text is split across<w:r>elements.b. Create and run script: Use
get_nodeto find nodes, implement changes, thendoc.save(). See "Document Library" section in ooxml.md for patterns.Note: Always grep
word/document.xmlimmediately before writing a script to get current line numbers and verify text content. Line numbers change after each script run. -
Pack the document: After all batches are complete, convert the unpacked directory back to .docx:
python ooxml/scripts/pack.py unpacked reviewed-document.docx -
Final verification: Do a comprehensive check of the complete document:
- Convert final document to markdown:
pandoc --track-changes=all reviewed-document.docx -o verification.md - Verify ALL changes were applied correctly:
grep "original phrase" verification.md # Should NOT find it grep "replacement phrase" verification.md # Should find it - Check that no unintended changes were introduced
- Convert final document to markdown:
Converting Documents to Images
To visually analyze Word documents, convert them to images using a two-step process:
-
Convert DOCX to PDF:
soffice --headless --convert-to pdf document.docx -
Convert PDF pages to JPEG images:
pdftoppm -jpeg -r 150 document.pdf pageThis creates files like
page-1.jpg,page-2.jpg, etc.
Options:
-r 150: Sets resolution to 150 DPI (adjust for quality/size balance)-jpeg: Output JPEG format (use-pngfor PNG if preferred)-f N: First page to convert (e.g.,-f 2starts from page 2)-l N: Last page to convert (e.g.,-l 5stops at page 5)page: Prefix for output files
Example for specific range:
pdftoppm -jpeg -r 150 -f 2 -l 5 document.pdf page # Converts only pages 2-5Code Style Guidelines
IMPORTANT: When generating code for DOCX operations:
- Write concise code
- Avoid verbose variable names and redundant operations
- Avoid unnecessary print statements
Dependencies
Required dependencies (install if not available):
- pandoc:
sudo apt-get install pandoc(for text extraction) - docx:
npm install -g docx(for creating new documents) - LibreOffice:
sudo apt-get install libreoffice(for PDF conversion) - Poppler:
sudo apt-get install poppler-utils(for pdftoppm to convert PDF to images) - defusedxml:
pip install defusedxml(for secure XML parsing)
Resource Files
LICENSE.txt
Binary resource
docx-js.md
Binary resource
ooxml.md
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd
Binary resource
ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd
Download ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd
Binary resource
ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd
Download ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd
Binary resource
ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd
Download ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd
Binary resource
ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd
Download ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd
Binary resource
ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd
Download ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd
Binary resource
ooxml/schemas/mce/mc.xsd
Download ooxml/schemas/mce/mc.xsd
Binary resource
ooxml/schemas/microsoft/wml-2010.xsd
Download ooxml/schemas/microsoft/wml-2010.xsd
Binary resource
ooxml/schemas/microsoft/wml-2012.xsd
Download ooxml/schemas/microsoft/wml-2012.xsd
Binary resource
ooxml/schemas/microsoft/wml-2018.xsd
Download ooxml/schemas/microsoft/wml-2018.xsd
Binary resource
ooxml/schemas/microsoft/wml-cex-2018.xsd
Download ooxml/schemas/microsoft/wml-cex-2018.xsd
Binary resource
ooxml/schemas/microsoft/wml-cid-2016.xsd
Download ooxml/schemas/microsoft/wml-cid-2016.xsd
Binary resource
ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd
Download ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd
Binary resource
ooxml/schemas/microsoft/wml-symex-2015.xsd
Download ooxml/schemas/microsoft/wml-symex-2015.xsd
Binary resource
ooxml/scripts/pack.py
Download ooxml/scripts/pack.py
#!/usr/bin/env python3
"""
Tool to pack a directory into a .docx, .pptx, or .xlsx file with XML formatting undone.
Example usage:
python pack.py <input_directory> <office_file> [--force]
"""
import argparse
import shutil
import subprocess
import sys
import tempfile
import defusedxml.minidom
import zipfile
from pathlib import Path
def main():
parser = argparse.ArgumentParser(description="Pack a directory into an Office file")
parser.add_argument("input_directory", help="Unpacked Office document directory")
parser.add_argument("output_file", help="Output Office file (.docx/.pptx/.xlsx)")
parser.add_argument("--force", action="store_true", help="Skip validation")
args = parser.parse_args()
try:
success = pack_document(
args.input_directory, args.output_file, validate=not args.force
)
# Show warning if validation was skipped
if args.force:
print("Warning: Skipped validation, file may be corrupt", file=sys.stderr)
# Exit with error if validation failed
elif not success:
print("Contents would produce a corrupt file.", file=sys.stderr)
print("Please validate XML before repacking.", file=sys.stderr)
print("Use --force to skip validation and pack anyway.", file=sys.stderr)
sys.exit(1)
except ValueError as e:
sys.exit(f"Error: {e}")
def pack_document(input_dir, output_file, validate=False):
"""Pack a directory into an Office file (.docx/.pptx/.xlsx).
Args:
input_dir: Path to unpacked Office document directory
output_file: Path to output Office file
validate: If True, validates with soffice (default: False)
Returns:
bool: True if successful, False if validation failed
"""
input_dir = Path(input_dir)
output_file = Path(output_file)
if not input_dir.is_dir():
raise ValueError(f"{input_dir} is not a directory")
if output_file.suffix.lower() not in {".docx", ".pptx", ".xlsx"}:
raise ValueError(f"{output_file} must be a .docx, .pptx, or .xlsx file")
# Work in temporary directory to avoid modifying original
with tempfile.TemporaryDirectory() as temp_dir:
temp_content_dir = Path(temp_dir) / "content"
shutil.copytree(input_dir, temp_content_dir)
# Process XML files to remove pretty-printing whitespace
for pattern in ["*.xml", "*.rels"]:
for xml_file in temp_content_dir.rglob(pattern):
condense_xml(xml_file)
# Create final Office file as zip archive
output_file.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(output_file, "w", zipfile.ZIP_DEFLATED) as zf:
for f in temp_content_dir.rglob("*"):
if f.is_file():
zf.write(f, f.relative_to(temp_content_dir))
# Validate if requested
if validate:
if not validate_document(output_file):
output_file.unlink() # Delete the corrupt file
return False
return True
def validate_document(doc_path):
"""Validate document by converting to HTML with soffice."""
# Determine the correct filter based on file extension
match doc_path.suffix.lower():
case ".docx":
filter_name = "html:HTML"
case ".pptx":
filter_name = "html:impress_html_Export"
case ".xlsx":
filter_name = "html:HTML (StarCalc)"
with tempfile.TemporaryDirectory() as temp_dir:
try:
result = subprocess.run(
[
"soffice",
"--headless",
"--convert-to",
filter_name,
"--outdir",
temp_dir,
str(doc_path),
],
capture_output=True,
timeout=10,
text=True,
)
if not (Path(temp_dir) / f"{doc_path.stem}.html").exists():
error_msg = result.stderr.strip() or "Document validation failed"
print(f"Validation error: {error_msg}", file=sys.stderr)
return False
return True
except FileNotFoundError:
print("Warning: soffice not found. Skipping validation.", file=sys.stderr)
return True
except subprocess.TimeoutExpired:
print("Validation error: Timeout during conversion", file=sys.stderr)
return False
except Exception as e:
print(f"Validation error: {e}", file=sys.stderr)
return False
def condense_xml(xml_file):
"""Strip unnecessary whitespace and remove comments."""
with open(xml_file, "r", encoding="utf-8") as f:
dom = defusedxml.minidom.parse(f)
# Process each element to remove whitespace and comments
for element in dom.getElementsByTagName("*"):
# Skip w:t elements and their processing
if element.tagName.endswith(":t"):
continue
# Remove whitespace-only text nodes and comment nodes
for child in list(element.childNodes):
if (
child.nodeType == child.TEXT_NODE
and child.nodeValue
and child.nodeValue.strip() == ""
) or child.nodeType == child.COMMENT_NODE:
element.removeChild(child)
# Write back the condensed XML
with open(xml_file, "wb") as f:
f.write(dom.toxml(encoding="UTF-8"))
if __name__ == "__main__":
main()ooxml/scripts/unpack.py
Download ooxml/scripts/unpack.py
#!/usr/bin/env python3
"""Unpack and format XML contents of Office files (.docx, .pptx, .xlsx)"""
import random
import sys
import defusedxml.minidom
import zipfile
from pathlib import Path
# Get command line arguments
assert len(sys.argv) == 3, "Usage: python unpack.py <office_file> <output_dir>"
input_file, output_dir = sys.argv[1], sys.argv[2]
# Extract and format
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
zipfile.ZipFile(input_file).extractall(output_path)
# Pretty print all XML files
xml_files = list(output_path.rglob("*.xml")) + list(output_path.rglob("*.rels"))
for xml_file in xml_files:
content = xml_file.read_text(encoding="utf-8")
dom = defusedxml.minidom.parseString(content)
xml_file.write_bytes(dom.toprettyxml(indent=" ", encoding="ascii"))
# For .docx files, suggest an RSID for tracked changes
if input_file.endswith(".docx"):
suggested_rsid = "".join(random.choices("0123456789ABCDEF", k=8))
print(f"Suggested RSID for edit session: {suggested_rsid}")ooxml/scripts/validate.py
Download ooxml/scripts/validate.py
#!/usr/bin/env python3
"""
Command line tool to validate Office document XML files against XSD schemas and tracked changes.
Usage:
python validate.py <dir> --original <original_file>
"""
import argparse
import sys
from pathlib import Path
from validation import DOCXSchemaValidator, PPTXSchemaValidator, RedliningValidator
def main():
parser = argparse.ArgumentParser(description="Validate Office document XML files")
parser.add_argument(
"unpacked_dir",
help="Path to unpacked Office document directory",
)
parser.add_argument(
"--original",
required=True,
help="Path to original file (.docx/.pptx/.xlsx)",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="Enable verbose output",
)
args = parser.parse_args()
# Validate paths
unpacked_dir = Path(args.unpacked_dir)
original_file = Path(args.original)
file_extension = original_file.suffix.lower()
assert unpacked_dir.is_dir(), f"Error: {unpacked_dir} is not a directory"
assert original_file.is_file(), f"Error: {original_file} is not a file"
assert file_extension in [".docx", ".pptx", ".xlsx"], (
f"Error: {original_file} must be a .docx, .pptx, or .xlsx file"
)
# Run validations
match file_extension:
case ".docx":
validators = [DOCXSchemaValidator, RedliningValidator]
case ".pptx":
validators = [PPTXSchemaValidator]
case _:
print(f"Error: Validation not supported for file type {file_extension}")
sys.exit(1)
# Run validators
success = True
for V in validators:
validator = V(unpacked_dir, original_file, verbose=args.verbose)
if not validator.validate():
success = False
if success:
print("All validations PASSED!")
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()ooxml/scripts/validation/init.py
Download ooxml/scripts/validation/init.py
"""
Validation modules for Word document processing.
"""
from .base import BaseSchemaValidator
from .docx import DOCXSchemaValidator
from .pptx import PPTXSchemaValidator
from .redlining import RedliningValidator
__all__ = [
"BaseSchemaValidator",
"DOCXSchemaValidator",
"PPTXSchemaValidator",
"RedliningValidator",
]ooxml/scripts/validation/base.py
Download ooxml/scripts/validation/base.py
Binary resource
ooxml/scripts/validation/docx.py
Download ooxml/scripts/validation/docx.py
Binary resource
ooxml/scripts/validation/pptx.py
Download ooxml/scripts/validation/pptx.py
Binary resource
ooxml/scripts/validation/redlining.py
Download ooxml/scripts/validation/redlining.py
Binary resource
scripts/init.py
# Make scripts directory a package for relative imports in testsscripts/document.py
Binary resource
scripts/templates/comments.xml
Download scripts/templates/comments.xml
Binary resource
scripts/templates/commentsExtended.xml
Download scripts/templates/commentsExtended.xml
Binary resource
scripts/templates/commentsExtensible.xml
Download scripts/templates/commentsExtensible.xml
Binary resource
scripts/templates/commentsIds.xml
Download scripts/templates/commentsIds.xml
Binary resource
scripts/templates/people.xml
Download scripts/templates/people.xml
Binary resource
scripts/utilities.py
Binary resource
claudeskills Docs