MCPcopy Create free account
hub / github.com/DevExzh/litchi

github.com/DevExzh/litchi @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
13,239 symbols 35,730 edges 742 files ⚖ Apache-2.0 4,749 documented · 36% ● updated 12d ago★ 425 open issues

Browse by type

⨍ Functions 11,583◇ Types & classes 1,656
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Litchi

Litchi Logo

A high-performance Rust library for reading and writing Microsoft Office file formats (OLE2 and OOXML), OpenDocument formats (ODF), RTF, and Apple iWork files. Supports .doc, .docx, .xls, .xlsx, .xlsb, .ppt, .pptx, .rtf, .odt, .ods, .odp, .oth, .odm, .odg, .odc, .odi, .odb, .odf, .pages, .numbers, and .key files.

[!WARNING] ⚠️ Active Development: This library is under active development. The API may change without notice. Not recommended for production use yet.

[!NOTE] The current logo is generated by AI, we need someone to design a better logo. If you are interested, please contact me via email.

Features

  • Unified API - litchi::open opens every supported format into one File type, detecting the format from the content. Every format reads and writes through File: paths, queries and views; immutable set, add, remove, move_to and swap; transactions with exact inverse patches; batches; save, to_bytes and create. Errors are typed and carry a stable code and a suggestion, and capabilities() reports what each handle supports
  • Microsoft Office - .doc, .docx, .xls, .xlsx, .xlsb, .ppt, .pptx and .rtf files
  • OpenDocument - .odt, .ods, .odp, and the .oth, .odm, .odg, .odc, .odi, .odb and .odf formula formats
  • Apple iWork - .pages, .numbers, and .key packages and app-authored package directories
  • Per-format modules - each format crate is re-exported for format-specific reading and writing
  • Equation Conversion - Read MathType, Equation Editor and Office Math equations as LaTeX
  • Markdown Conversion - Convert documents and presentations to Markdown format
  • Memory Efficient - Direct byte buffer support with zero-copy parsing where possible
  • High Performance - SIMD optimizations, minimal allocations, efficient memory layout

OOXML ownership is split by responsibility: litchi-opc owns the package graph, litchi-ooxml-common owns shared OOXML vocabulary and package services, litchi-docx, litchi-pptx, litchi-xlsx, and litchi-xlsb own their format semantics, and litchi-fonts owns font discovery, subsetting, embedding, and obfuscation. The litchi facade exposes each namespace only when its matching opt-in feature is enabled.

OOXML ingestion is bounded by litchi_opc::SourceLimits. The standard profile is used by ordinary open methods; applications that receive untrusted or multi-tenant input can derive a tighter checked profile with SourceLimits::builder() and pass it through the format's OpenOptions to open_with_options or from_bytes_with_options (or through litchi::OpenOptions to litchi::open_with). The policy covers package input, ZIP members and metadata, materialized OPC parts, [Content_Types].xml, and relationship XML and graph traversal. It implements the defensive-consumer concerns in ECMA-376 Part 2 sections 7.3.6 and 10, together with MS-OI29500 sections 2.1.1749-1752; its ceilings are Litchi safety policy, not maxima prescribed by those specifications. Errors report OpcError::Limit { kind: SourceLimitKind, observed, maximum }; invalid profiles report InvalidLimit { kind, value, maximum }.

PPTX and XLSX custom document properties use the shared typed litchi_ooxml_common::custom::Props and Value model for parsing and writing, following vendored MS-OI29500 §3.11. A missing custom-properties part is an empty Props; mutations are transactional and invalidate package signatures. Property values are inert data: Litchi never executes macros, VBA, ActiveX, controls, OLE objects, embedded code, actions, formulas, or links. Macro, VBA, ActiveX, control, OLE, and embedded-code payloads are retained only as inert blobs when exposed or preserved; they are never executed or activated.

Quick Start

Unless a section says otherwise, its snippets run inside a function that returns litchi::Result<()>.

Open any document

litchi::open detects the format from the file's content and returns a File: an enum with one variant per format (File::Docx, File::Xls, File::Ppt, ...), plus File::Locked for an encrypted file and File::Signed for a signed one. The common case needs no options and no format knowledge.

let file = litchi::open("report.docx")?; // or .doc, .rtf, .odt, .xlsx, .pptx, ...
println!("format: {:?}, family: {:?}", file.format(), file.family());

// Reads that every format shares are methods on `File`.
println!("{}", file.text()?);
if let Some(metadata) = file.metadata()? {
    println!("title: {:?}", metadata.title);
}

// Family reads go through a view: `document()`, `presentation()` or
// `workbook()`. A view refuses a file of another family.
for paragraph in file.document()?.paragraphs()? {
    println!("{}", paragraph.text()?);
}

Presentations and workbooks work the same way:

let deck = litchi::open("slides.pptx")?; // or .ppt, .odp
let presentation = deck.presentation()?;
println!("{} slides", presentation.slide_count()?);
for slide in presentation.slides()? {
    println!("{}", slide.text()?);
}

let book = litchi::open("budget.xlsx")?; // or .xls, .xlsb, .ods
println!("sheets: {:?}", book.workbook()?.worksheet_names()?);

The workbook view also implements the generic litchi::sheet::WorkbookTrait by static dispatch, so litchi::sheet::FormulaEvaluator (eval feature) can evaluate formulas on it directly; see the sheet_eval_* examples.

Format-specific reads live on the handle that each variant carries:

use litchi::File;

match litchi::open("budget.xlsx")? {
    File::Xlsx(xlsx) => {
        // XLSX sheet names match case-insensitively, as in Excel.
        if let Some(sheet) = xlsx.sheet("data")? {
            println!("{}: A1 = {:?}", sheet.name(), sheet.cell("A1")?);
        }
    },
    File::Pptx(pptx) => println!("slide size: {:?} EMU", pptx.slide_size()?),
    other => println!("{:?}", other.format()),
}

With the markdown feature, documents and presentations convert to Markdown:

use litchi::markdown::ToMarkdown;

let file = litchi::open("report.docx")?;
println!("{}", file.to_markdown()?);

Encrypted and signed files

An encrypted file opens as File::Locked. Reading it fails with document_protected and a suggestion to unlock it. With the encryption feature, Locked::unlock consumes the handle and opens the content with its password; a password never passes through OpenOptions.

use litchi::{File, Password};

let file = match litchi::open("protected.doc")? {
    File::Locked(locked) => {
        println!("{:?} encrypted with {:?}", locked.format(), locked.encryption());
        locked.unlock(Password::new("password".to_owned()))?
    },
    file => file,
};
println!("{}", file.text()?);

A signed OOXML or legacy binary file opens as File::Signed. It reads like any other file, and nothing is verified when it opens. So that no edit can strip a signature silently, editing a signed file requires removing the signature explicitly first: Signed::unsign consumes the signature and returns the file.

use litchi::File;

let file = litchi::open("contract.docx")?;
println!("{}", file.text()?); // reads the signed content
if let File::Signed(signed) = file {
    println!("{:?} signature in the {:?} container", signed.format(), signed.origin());
    let unsigned: File = signed.unsign();
    assert!(!unsigned.is_signed());
}

Errors

Every failure of the unified API is one litchi::Error. It carries a stable Code (code().as_str() is the snake_case wire name), a message, an optional suggestion, the format involved, and the typed error of the format crate that failed, which std::error::Error::source returns.

use litchi::Code;

match litchi::open("notes.pages") {
    Ok(file) => println!("{}", file.text()?),
    Err(error) if error.code() == Code::UnsupportedFormat => {
        // `detected` names the format that was recognized: Some(Pages) in a
        // build without the `pages` feature.
        println!("{:?}", error.detected());
        // "enable the `pages` cargo feature"
        if let Some(suggestion) = error.suggestion() {
            println!("{suggestion}");
        }
    },
    Err(error) => return Err(error),
}

The codes that opening and reading report most often:

Code When
file_not_found The path does not exist.
unsupported_format The input is not an Office file (detected() is None), or its format feature is disabled (detected() names the format and the suggestion identifies the feature). A family view reports it too, for a file of another family.
corrupt_file A container, record, XML part, or payload is malformed.
limit_exceeded The input exceeds a read limit. The suggestion is to raise the matching limit in OpenOptions if the input is trusted.
document_protected A File::Locked was read. The suggestion names Locked::unlock.
invalid_argument Locked::unlock was given the wrong password. The suggestion is to check it.
io_error Reading failed, or a file opened from a path changed after it was opened.
unsupported_capability The format cannot do what was asked, such as Markdown output of a workbook or unlocking an encrypted XLSB package.
cancelled The execution context in OpenOptions was cancelled.

Editing through File

Every format writes through File. The verbs take &self and return a new File; the input never changes. Several edits form one transaction through File::edit, whose patch inverts exactly. A snapshot saves to its origin with save(), to another path with save_as, or to memory with to_bytes().

use litchi::{FileFormat, NewNode, props};

let file = litchi::open("report.docx")?;
let file = file.set("/body/p[1]", props! { "text" => "Revised text" })?;
let added = file.add("/body", NewNode::new("paragraph").prop("text", "Appendix"))?;
added.file.save_as("report-revised.docx")?;

// A new file starts from `create`.
let book = litchi::create(FileFormat::Xlsx)?;
let book = book.set("/Sheet1/A1", props! { "value" => 42 })?;
book.save_as("new.xlsx")?;

Not every element supports every verb in every format. file.capabilities() lists what the handle supports; anything else fails with unsupported_capability instead of writing part of a change.

Creating and Writing Documents

The per-format modules create and edit documents. They report their own error types, so the snippets in this section and the next run inside a function that returns Result<(), Box<dyn std::error::Error + Send + Sync>>.

use litchi::docx::Builder;
use litchi::pptx::builder::Builder as PptxBuilder;
use litchi::xlsx::Package as XlsxPackage;

// Create Word document
let mut builder = Builder::new()?;
let doc = builder.document()?;
doc.add_heading("My Document", 1)?;
doc.add_paragraph_with_text("Hello, World!");
builder.build()?.save("output.docx")?;

// Create Excel workbook: edits are transactions over an immutable package
let mut edit = XlsxPackage::new()?.edit()?;
edit.sheet("Sheet1")?
    .ok_or("missing worksheet")?
    .set("A1", "Hello")?
    .set("B1", "World")?;
edit.commit()?.into_package().save("output.xlsx")?;

// Create PowerPoint presentation
let mut builder = PptxBuilder::new()?;
builder.presentation()?
    .add_slide()?
    .add_text_box("My Presentation", 0, 0, 914_400, 914_400);
builder.build()?.save("output.pptx")?;

Additional Format Support

// Pages, Keynote, and Numbers documents (requires "iwork")
#[cfg(feature = "iwork")]
{
    let file = litchi::open("budget.numbers")?; // or .pages, .key, or a package directory
    println!("{}", file.view(litchi::view::Mode::Outline)?);
    let file = file.set("/sheet[1]/table[1]/B2", litchi::props! { "value" => 42 })?;
    file.save()?; // a package directory is written back as a directory
}

// Equation conversion (requires the "equation" feature)
#[cfg(feature = "equation")]
{
    use litchi::equation;
    let latex = equation::omml_to_latex(
        "<m:oMath><m:r><m:t>x</m:t></m:r></m:oMath>",
        &equation::Limits::DEFAULT,
    )?;
    println!("{latex}");
}

Installation

[!NOTE] The crates.io release may lag the focused edit and reversible-patch APIs in development. Use the development version when you need those newer transaction surfaces.

Add to your Cargo.toml:

[dependencies]
litchi = { version = "0", features = ["docx"] }

# Or use the development version
litchi = { git = "https://github.com/DevExzh/litchi.git", features = ["docx"] }

Optional Features

Default features are empty. Choose precisely the file formats and capabilities your application uses; default-features = false is therefore optional, but can make that intent explicit.

[dependencies]
# Legacy PowerPoint, OOXML PowerPoint, and signing support.
litchi = { version = "0", features = ["ppt", "pptx", "sign"] }

# A minimal spreadsheet reader/writer surface.
litchi = { version = "0", default-features = false, features = ["xlsx"] }

# Parse only Pages documents. `keynote` and `numbers` are independent leaves.
litchi = { version = "0", features = ["pages"] }

# Enable every iWork format as a convenience bundle.
litchi = { version = "0", features = ["iwork"] }

Formats never imply signing. Add sign only when your application needs signature support.

Note about iWork leaves: pages, keynote, and numbers parse serialized IWA Protocol Buffer messages. Enabling any one of them requires a system protoc installation (used by prost-build); iwork simply enables all three.

  • Linux (Debian/Ubuntu): install protobuf-compiler
  • macOS: install protobuf (e.g. via Homebrew)
  • Windows: install protobuf (e.g. via Winget)

Note about font-discovery: System font discovery depends on font-kit,

Extension points exported contracts — how you extend this code

browse all types & interfaces →

Core symbols most depended-on inside this repo

browse all functions →

Shape

Function 6,171
Method 5,412
Class 1,209
Enum 423
Interface 24

Languages

Rust100%

Modules by API surface

src/common/simd/cmp.rs224 symbols
src/ooxml/xlsx/writer/sheet.rs153 symbols
src/sheet/eval/engine/statistical/distributions.rs125 symbols
src/ole/xls/writer/biff.rs98 symbols
src/odf/elements/table.rs95 symbols
src/ole/xls/writer/core.rs91 symbols
src/ooxml/xlsx/worksheet.rs89 symbols
src/ole/ppt/writer/core.rs89 symbols
src/sheet/eval/engine/info/mod.rs85 symbols
src/ooxml/pptx/writer/slide.rs85 symbols
src/ooxml/xlsb/writer/worksheet.rs83 symbols
soapberry-zip/src/archive.rs83 symbols

For agents

$ claude mcp add litchi \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page