PythonPython API

Python API

Python conventions, the exception hierarchy, and a map of the texform module.

Conventions#

The texform Python package exposes the parser, document model, transform engine, and serializer from one Rust core. Install it with pip install texform; see Installation for supported Python versions and platforms. Methods and arguments use snake_case; the JavaScript binding uses camelCase. Both bindings share the parsing and transform core, but configuration interfaces and some exception types differ.

Structured data crosses the boundary as plain dicts, never custom wrapper classes: parse results, transform reports, diagnostics, and argspec results are all dicts, and option inputs are dicts too. The bundled type stubs (texform/__init__.pyi) describe those shapes as TypedDict types, so editors and type checkers see the exact keys. Document and Node are live handles into a Rust tree; a SyntaxNode is a plain dict snapshot.

Configuration is two-layered. A per-call config= argument must be a complete configuration class — ParseConfig or the phase-nested TransformConfig — and a dict there raises ConfigError. Partial adjustments go through keyword overlays instead (parse(src, reject_unknown=True), normalize(src, rewrite={"enabled": False})), where nested values are plain dicts, not phase-config instances. The parse baseline is lenient.

The structured library exceptions derive from TexformError, so a single except texform.TexformError catches them: ParseError (an operation needed a complete tree but parsing produced none), EditError (an invalid edit), ConfigError (invalid construction input), and TransformError (a transform-engine failure). Parser.parse returns malformed-input diagnostics and a document that may be None; invalid configuration still raises ConfigError.

Module map#

Parser#

SymbolKindDescription
ParserclassTurn LaTeX source into a parse result.
ParseConfigclassComplete parse configuration. The only accepted config= type for parse.
ParseOverridesdict typeKeyword overlays for parse. Omitted keys keep the baseline.
ParseResultdict typeThe result of Parser.parse: an optional document plus diagnostics.
ParseDiagnosticdict typeA single parse diagnostic emitted alongside a parse result.
ParseDiagnosticKindtypeCategory of a parse diagnostic, such as "unknown-command" or "argument-validation".
SpantypeHalf-open UTF-8 byte range {"start": int, "end": int} into the source.
SyntaxNodetypeLossless parse snapshot as a plain dict. The tagged-union shape is documented on the TypeScript SyntaxNode type; Python keeps this alias unexpanded.
ContextItemtypeA knowledge-injection item: a command, environment, or delimiter-control dict.
CommandItemdict typeA custom command injected into parser knowledge.
EnvironmentItemdict typeA custom environment injected into parser knowledge.
DelimiterItemdict typeA custom delimiter control injected into parser knowledge.

KnowledgeBase#

SymbolKindDescription
KnowledgeBaseclassImmutable knowledge shared by parsers, engines, and documents.
CommandItemdict typeA custom command injected into parser knowledge.
EnvironmentItemdict typeA custom environment injected into parser knowledge.
DelimiterItemdict typeA custom delimiter control injected into parser knowledge.

Document#

SymbolKindDescription
DocumentclassThe editable document tree — the working format you read, edit, and output.
NodeSpanEntrydict typeOne entry mapping a node identifier to its source byte span.
TokenizedLatexdict typeSerialized LaTeX and tokens produced by the same serializer traversal.
SerializationTokendict typeOne serialization fragment with UTF-8 byte offsets.
SerializationTokenKindtypeSemantic category of one serialization fragment.
NodeTabledict typePreorder node columns. Row indices are local to this snapshot.
ArgumentTabledict typeAll argument slots, ordered by owner row and slot index.
ColumnarTreedict typeTree columns for bulk structural analysis with Arrow or DataFrame tools.

Node#

SymbolKindDescription
NodeclassA read-only handle into a Document for navigation and reading.
NodeKindtypeNode kind as reported by Node.kind(). Python uses PascalCase ("Root", "Command", "ActiveSpace").
RuntimeContentModetypeRuntime content mode reported by the tree API: "math" or "text".
ErrorPartsdict typeThe decomposed content of an Error placeholder node.
GroupKindExplicitdict typeA group written with explicit braces { ... }.
GroupKindImplicitdict typeA group with no surrounding braces, inferred from structure.
GroupKindDelimiteddict typeA group bounded by a delimiter pair, such as \left( ... \right).
GroupKindInlineMathdict typeA group introduced by inline math shift, such as $ ... $ in text mode.
GroupKindReftypeThe kind of a Group node: explicit, implicit, delimited, or inline-math.
DelimiterValuetypeA delimiter string: a character, a backslash-prefixed control, or a dot.
MathArgdict typeA command argument carrying math-mode content.
TextArgdict typeA command argument carrying text-mode content.
DelimiterArgdict typeA command argument that is a single delimiter token.
CSNameArgdict typeA command argument that is a control-sequence name.
DimensionArgdict typeA command argument that is a TeX dimension, such as 2pt.
IntegerArgdict typeA command argument that is an integer literal.
KeyValArgdict typeA command argument that is a key=value list.
ColumnArgdict typeA command argument that is a tabular column specification.
BooleanArgdict typeA command argument that is a star flag, modeled as a boolean.
ArgReftypeA read command argument: one of the discriminated argument-value dicts.
ArgFormKindtype
NodeSlotKindtype
ArgFormdict type
OperatorNameArgdict type
PairedclassImmutable content and delimiter pair for an argspec Paired slot.
ArgtypeSlot input: source written inside the slot, a detached content node, a star flag, absence, or an explicit Paired delimiter pair.
NodeSlotdict type

TransformEngine#

SymbolKindDescription
TransformEngineclassNormalize a formula into the canonical form selected by a profile.
TransformConfigclassComplete transform configuration, nested by pipeline phase.
RewriteConfigclassComplete Rewrite phase configuration.
LowerAttributesConfigclassComplete LowerAttributes phase configuration.
FinalizeAstConfigclassComplete FinalizeAst phase configuration.
FlattenGroupsConfigclassComplete FlattenGroups phase configuration.
NormalizeOverridesclassFlat parse+transform overlays for normalize.
TransformOverridesdict typeKeyword overlays for transform.
RewriteOverridesdict typeKeyword overlays for the Rewrite phase.
LowerAttributesOverridesdict typeKeyword overlays for the LowerAttributes phase.
FinalizeAstOverridesdict typeKeyword overlays for the FinalizeAst phase.
FlattenGroupsOverridesdict typeKeyword overlays for the FlattenGroups phase.
NormalizeReportResultdict typeText plus the diagnostic report from one explicit normalize report call.
TransformReportdict typeDiagnostic report for one explicit report call.
TransformWarningdict typeAn unknown input name whose arguments or scope cannot be guaranteed.
LowerAttributesReportdict typeThe LowerAttributes phase report.
AttributeStatdict typeActivity for one (attr, value) pair in LowerAttributes.
AttributeFormCountsdict typeCounts of one attribute form, split by carrier.
RewriteReportdict typeThe Rewrite phase report.
RewriteRuleStatdict typeOne rewrite rule's outcome for a single call.
FinalizeAstReportdict typeThe FinalizeAst phase report.
FlattenGroupsReportdict typeThe FlattenGroups phase report.
FlattenGroupsActionCountsdict typeFlatten actions that changed the tree.
FlattenGroupsGuardCountsdict typePreserve-guard hits for one FlattenGroups run.
TransformProfiletypeNormalization profile name: "authoring", "faithful", "corpus", or "equiv".

serialize#

SymbolKindDescription
serializefunctionRender a SyntaxNode dict to LaTeX text.
SerializeOptionsdict typeOptions for Document.to_latex, Document.to_tokenized_latex, and serialize.
StyletypeSpaced output is byte-stable; compact preserves structure and text idempotency.

validate_argspec#

SymbolKindDescription
validate_argspecfunctionValidate an xparse-style argspec string and report its parsed slots.
ValidateArgspecResultdict typeThe outcome of validating an argspec string with validate_argspec.
ParsedArgSpecSlotdict typeOne parsed argument slot of an xparse-style specification.
ArgSpecKindTypetypeValue kind of one parsed argspec slot (content, delimiter, star, ...).
ArgSpecFormTypetypeSurface form of one parsed argspec slot (mandatory, optional group, paired, ...).

Utilities#

SymbolKindDescription
list_packagesfunctionList the built-in knowledge packages with their record counts.
count_targetsfunctionCount command, environment, and character targets in a LaTeX formula.
PackageInfodict typeSummary of one built-in knowledge package.
TexformErrorexceptionBase class for every exception the library raises.
ParseErrorexceptionRaised when source could not be parsed into a complete tree.
EditErrorexceptionRaised by a Document editing method on an invalid edit.
ConfigErrorexceptionRaised on invalid construction or per-call configuration input.
TransformErrorexceptionRaised on a transform-engine failure.
ConformanceErrorexceptionRaised when a construction, edit, or syntax import violates the knowledge base or the document's structure.
list_rulesfunctionList the built-in rewrite rules, sorted by key.
RuleInfodict typeSummary of one built-in rewrite rule.
RuleFidelitytypeA rewrite rule's worst-case equivalence guarantee, least to most faithful: "math" (meaning preserved, rendering may change), "reading" (notation content, reading order, and structural roles preserved), or "render" (rendering equivalent under the reference renderer).
RuleLeveltypeThe first profile that accepts a rewrite rule's output as a suitable product.