English | 简体中文
DocLaTeX is an experimental Rust command-line tool that converts LaTeX source for scholarly documents directly into Microsoft Word .docx files. It implements its own lexer, macro expander, document parser, bibliography processor, math-to-OMML converter, and OOXML writer. It does not invoke a TeX/LaTeX engine, BibTeX, or Biber.
The main goals are to preserve document semantics rather than approximate a PDF page: editable Word equations, working cross-references, automatic heading and equation numbering, citations, glossaries, and reusable Word styles.
Project status: DocLaTeX supports a substantial but incomplete LaTeX subset. It is not a complete TeX implementation or a drop-in replacement for every package and document class. Check the warnings printed during conversion and visually inspect important documents.
- TeX-aware, lazy tokenization with category-code changes such as
\makeatletterand\makeatother; category-code changes are restored at group boundaries. - Macro definitions using
\def,\gdef,\edef,\xdef,\let,\newcommand,\renewcommand,\providecommand, and\DeclareRobustCommand.\letaliases participate in\ifxcomparisons using their actual meanings. - A supported subset of
xparseargument specifications through\NewDocumentCommandand related commands, including mandatory and optional arguments. - User macro expansion in both text and mathematics, including custom math operators.
- Conditionals, counters, number formatting, user-defined environments, and theorem declarations.
- Recursive
\inputand\includeprocessing. filecontentsenvironments for generating local source/assets when required by a document.
- Parsing of
\documentclass,\LoadClass,\usepackage, and\RequirePackage. - Execution of local
.clsand.stysource, including files loaded from other class or package files. Definitions, conditionals, and supported primitives are processed during loading; non-semantic package output is kept out of the document. - Class/package option handling, including option declaration, processing, execution, and forwarding.
- A 100000-step expansion budget per class/package file. If it is exceeded, DocLaTeX restores the previous state, discards that file's output, and warns instead of hanging or leaking partial definitions. Internal package redefinitions do not displace commands handled natively by the parser, but subsequent user redefinitions in the document remain effective.
- File lookup relative to the current source file and project directory, with additional colon-separated search directories from
TEXINPUTS. - Built-in handling for common
article,report, andbookbehavior, selected font-size anda4paperoptions, and basic Chinese class/package behavior. - Recognition of common scholarly packages such as
amsmath,graphicx,hyperref,glossaries,natbib,cleveref,booktabs, andgeometry.
Class and package support is semantic but partial: recognizing a package name does not mean that every command provided by that package is implemented.
- Parts, chapters, sections, subsections, and lower heading levels, including starred headings and appendix lettering.
- Word heading styles with multilevel numbering lists.
\maketitlewith title, author, date, and\thankscontent.- A Word table-of-contents field for
\tableofcontents. - Paragraph alignment, indentation, explicit line breaks, page breaks, and basic vertical spacing.
- Bold, italic, slanted, small-caps, underlined, struck-through, monospaced, colored, highlighted, superscript, and subscript text.
- Itemized, enumerated, nested, custom-label, and description lists.
- Footnotes, external hyperlinks, verbatim text, and
lstlistingcontent. - Common text accents, using precomposed Unicode characters where available and combining marks otherwise.
- Context-sensitive
\xspacehandling for user macros, including suppression before punctuation and avoidance of duplicate explicit whitespace. abstract, quotation, alignment,minipage, theorem-like, and user-defined environments.- Generic paragraph-based environments receive their own Word paragraph style;
abstractuses the dedicatedAbstractstyle.
- Inline and display LaTeX mathematics converted directly to editable Office Math Markup Language (OMML), rather than embedded as screenshots. Delimiters remain upright, including inside italic math groups.
- Display mathematics shares its surrounding Word paragraph, using line breaks before and after the formula instead of introducing standalone equation paragraphs.
- Fractions, radicals, superscripts/subscripts, n-ary operators and limits, delimiters, accents, over/under braces, matrices, arrays, cases, boxed expressions, phantom content, and common Greek/symbol/operator commands.
- Math alphabets and text commands such as
\mathrm,\mathbf,\mathcal,\mathbb,\mathfrak, and\text; their arguments are recursively converted, preserving nested symbols and OMML structures rather than printing macro source. - Semantic handling for
\mathchoice, math style/version declarations, bold math,\operatorname,\overset/\underset, extensible arrows, and user-defined math macros. - Standard LaTeX/amsmath commands already supported by the OMML converter keep their mathematical meaning when class/package source is executed, rather than being expanded into unrelated spacing or internal control sequences.
equation,align,gather,multline,alignat,eqnarray, and related starred environments, plussubequationsand per-row\nonumber/\notaghandling.- Alignment at
&positions through Word's manual alignment markers. - Equation numbers generated with Word
SEQfields and placed using the professional-math#(number)convention. - Bookmarks at equation numbers and cached reference text for use before fields are updated.
\labeltargets on headings, figures, tables, equations, and theorem-like environments.\ref,\eqref,\pageref,\nameref,\autoref,\cref, and\Cref.- Word bookmarks and
REF/PAGEREFfields, with hyperlinks to reference targets. - Custom reference names through
\crefnameand\Crefname. - A two-pass compilation pipeline and a project-specific
.auxfile to carry labels and bibliography information between passes.
- Direct parsing of
.bibfiles and execution of\bibliographystyleprograms from local.bstfiles; no external BibTeX installation is required. Style lookup also searchesBSTINPUTS. - Multiple bibliography files, multiple citation keys, citation-ordering/compression behavior, and
\nocite{*}. \cite,\citet,\citep,\citealt,\citealp,\citeauthor,\citeyear,\citeyearpar, and\citeonline, including prenote/postnote optional arguments where applicable.- Entry ordering, author formatting, citation labels, and bibliography text controlled by the loaded
.bstprogram, with matching in-text author-year citations. - Built-in numeric, alphabetic, IEEE-like, and author-year fallbacks for recognized
plain,unsrt,alpha,abbrv,ieeetr/IEEEtran,apalike, and related styles when a.bstfile is unavailable or cannot be executed. - Manually written
thebibliographyenvironments and\bibitementries, with entries and numbering preserved across the second compilation pass. - Bibliography entries with internal links from citations.
The .bst interpreter supports the core stack language, entry iteration and sorting, name formatting, and common string operations. It is not a complete BibTeX implementation; unsupported styles produce a warning and use the built-in fallback.
\newacronymand\newglossaryentrydefinitions.- First-use expansion and subsequent short forms, capitalization, plural forms, and explicit short/long/full acronym commands.
- Common
\gls,\glspl,\acrshort,\acrlong,\acrfull, and acronym-package aliases. \printglossaries,\printglossary, and\printacronymsoutput without runningmakeindexorxindy.
- PNG, JPEG, and SVG images embedded directly in the DOCX package.
- PDF figures converted to SVG and embedded; only the first PDF page is used.
\graphicspath{{figures/}{...}}search directories for\includegraphics, with or without a filename extension.\includegraphicssizing throughwidth,height, andscale, including lengths relative to\textwidthwhile preserving aspect ratio when appropriate.- Centered images with a dedicated
Picturestyle that keeps the image with the following paragraph. - Figure/table captions, labels, and separate built-in
Captionand customTableCaptionstyles. - Centered
tabular,tabularx, andtabular*output with total-width handling,Xandp/m/bcolumns, repeated column specifications, explicit Word grid/cell widths, and horizontal/vertical alignment. booktabsrules, partial\cline/\cmidruleborders, row heights, cell/row colors,\makecellline breaks, and\multicolumn/\multirowspanning with Word vertical-merge continuation cells. Table formatting commands are consumed as formatting rather than emitted as cell text.- Table text uses the
TableTextstyle: single spacing and no first-line or hanging indentation.
- Native OOXML packaging for document content, styles, numbering, relationships, settings, properties, footnotes, and media.
- Built-in Word styles where appropriate, including body text, first-line-indented body text, headings, lists, captions, footnotes, and bibliography entries.
- Dedicated styles for pictures, table text, table captions, abstracts, verbatim content, and other parsed environments.
- Word fields marked for automatic update, with cached values so content remains visible before updating.
- A Rust toolchain with Cargo. The repository does not currently pin a specific Rust version.
- Optional, for PDF figures only: either
pdftocairoormutoolavailable onPATH.pdftocairo -svgis tried first, thenmutool draw.
Build the optimized executable:
cargo build --releaseThe executable is written to target/release/doclatex.
doclatex <input.tex> [-o <output.docx>] [-v]
doclatex --help
doclatex --version
For example, from this repository:
cargo run -- path/to/main.tex --output path/to/main.docxOr run the release binary directly:
target/release/doclatex path/to/main.tex -o path/to/main.docxIf -o/--output is omitted, the input extension is replaced with .docx. Use -v or --verbose to show progress inside each operation on standard error: source expansion reports token activity, parsing reports token percentages, bibliography resolution reports files, and DOCX generation reports blocks and package parts. In an interactive terminal, the current operation updates in place; redirected output uses throttled plain text lines without terminal control characters. By default, only warnings and the final output path are printed. Each compile automatically performs two expansion/parsing passes and writes an .aux file beside the input file. Existing output and .aux files are overwritten.
Relative input and output paths are resolved against the directory from which DocLaTeX is invoked. Included sources, classes, packages, graphics, and bibliographies should therefore remain available at their original project-relative paths.
examples/demo.tex is a compact demonstration of macros, references, equations, acronyms, tables, figures, verbatim text, and bibliographies. To try it without overwriting the checked-in example outputs:
tmpdir=$(mktemp -d)
cp examples/demo.tex examples/refs.bib examples/pixel.png examples/vector.pdf "$tmpdir"/
cargo run -- "$tmpdir/demo.tex" --output "$tmpdir/result.docx"examples/attention-is-all-you-need/ contains a larger, multi-file example based on the TeX source of Attention Is All You Need. It exercises recursive \input, a custom .sty file, mathematics, tables, and local graphics.
The generated document contains cached field results and requests field updates when opened. Depending on the Word-compatible editor and its security settings, you may still need to update fields manually. In Microsoft Word, select the document content and press F9; update the entire table of contents if prompted.
This is especially relevant for the table of contents, page references, equation sequence fields, and any numbering affected by later edits. Layout can differ between Microsoft Word, WPS Office, and other OOXML editors, so visual inspection is recommended.
- Complete TeX compatibility: Delimited macro corner cases, the full TeX programming model, every category-code/primitive behavior, and arbitrary third-party packages are not guaranteed to work.
- Exact class/package reproduction: DocLaTeX does not execute a full TeX installation. Page geometry, font selection, headers/footers, spacing, and class-specific layout are only partially reproduced.
- TeX-quality pagination: Floats are emitted in their source positions rather than managed by TeX's float placement algorithm. Placement options are accepted but do not control Word pagination. Line breaking, hyphenation, widow/orphan control, and page optimization are left largely to the editor.
- Graphics beyond basic images:
tikzpicturecontent is explicitly skipped. PGFPlots, TeX drawing code, EPS images, and conversion of arbitrary graphical environments are not currently rendered. - Lists and indexes:
\listoffiguresand\listoftablesare skipped. General index generation andmakeindex/xindyprocessing are not implemented. - Full bibliography engines:
biblatex, Biber, and CSL styles are unsupported. The.bstinterpreter covers core BibTeX operations but not every program or edge case; execution failures fall back to a built-in style with a warning, and complex field formatting may differ from TeX output. - Full glossary styles: Glossary entries are generated directly, without external indexing tools; advanced sorting, hierarchy, and custom glossary styles are not fully implemented.
- Every math construct: The OMML converter covers common scholarly notation, but uncommon symbols, complex alignment, custom spacing, and package-specific math commands may be missing or rendered differently.
- Advanced tables and floats:
longtable, complex multi-page tables, subfloat layouts, and allarray/package extensions are not fully reproduced. - Byte-for-byte visual equivalence: The output is a semantic Word document, not a replica of LaTeX-produced PDF pages.
Unsupported control sequences are generally discarded with a warning, while readable text in their groups is retained when possible; some unsupported environments are skipped as a whole. Class/package expansion-budget rollback and missing definitions can remove intended content. This best-effort behavior can therefore produce incomplete documents, and warnings should not be ignored for production use.
Run the 82 unit tests, two example-based integration tests, and formatting check from the repository root:
cargo test
cargo fmt --checkThe integration tests read only checked-in sources and assets from examples/. They compile both the demo and the multi-file Attention paper in temporary directories and verify expected document text and embedded graphics. Run them independently with:
cargo test --test examplesThe implementation is a single Rust binary crate. Its main stages are token.rs (lexing), engine.rs (macro expansion and class/package loading), parse.rs (document semantics), math.rs (OMML), bib.rs (bibliographies and style fallback), bst.rs (BibTeX style interpreter), aux.rs (two-pass data), and docx.rs (OOXML/DOCX output).
The checked-in .docx examples are illustrative outputs, not golden files compared by the test suite.
Conversion is not sandboxed. LaTeX input can read local files through includes, classes, packages, graphics, and bibliographies, and filecontents can write files. Review untrusted documents before compiling them, and use a temporary project copy when testing.