# Utilities

List knowledge packages, count formula targets, and the exception classes.

https://texform.dev/api/python/utilities

The structured library exceptions derive from `TexformError`, so one `except texform.TexformError` catches them:

- `TexformError`
  - `ParseError` — an operation needed a complete tree but parsing produced none.
  - `EditError` — an invalid `Document` edit.
  - `ConfigError` — invalid construction or per-call configuration input.
  - `TransformError` — a transform-engine failure.

`Parser.parse` reports malformed LaTeX through its result dict rather than raising; invalid configuration still raises `ConfigError`. Two categories are easy to misattribute. Attaching a node that belongs to another document raises `EditError` (`node belongs to a different document`), rejected before either tree is touched, and passing `TransformEngine.transform` a document that `has_errors()` raises `TransformError` — the precondition belongs to the engine, not to the earlier parse.

## `list_packages`

Kind: function

```python
list_packages() -> list[PackageInfo]
```

List the built-in knowledge packages with their record counts.

The returned names are the package identifiers accepted by the ``packages``
argument of ``KnowledgeBase``.

**Returns** `list[PackageInfo]` A list of ``PackageInfo`` dicts, each ``{"name": str, "commands": int, "environments": int}``.

```python
texform.list_packages()  # [{'name': 'ams', 'commands': 35, 'environments': 28}, ...]
```

- [PackageInfo](https://texform.dev/api/python/utilities.md#PackageInfo)
- [Parser](https://texform.dev/api/python/parser.md#Parser)
- [TransformEngine](https://texform.dev/api/python/transform-engine.md#TransformEngine)

## `count_targets`

Kind: function

```python
count_targets(src: str, config: ParseConfig | None = None, knowledge_base: KnowledgeBase | None = None) -> dict[str, int]
```

Count command, environment, and character targets in a LaTeX formula.

This is a Python-only helper for corpus analysis. The JavaScript binding
does not provide an equivalent function. It parses the source and reports
aggregate counts rather than returning a tree, so it requires a complete
parse.

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `src` | str | — | The LaTeX source string. |
| `config` | ParseConfig | None | None | A ``ParseConfig``, or ``None`` for the defaults. |
| `knowledge_base` | KnowledgeBase | None | None | Shared knowledge, or ``None`` for the process-wide default. |

**Returns** `dict[str, int]` A dict mapping a prefixed target key to its occurrence count. Keys are prefixed by kind: ``cmd:`` for commands, ``env:`` for environments, and ``char:`` for named character commands such as ``\alpha``.

- `ParseError`: If the source does not parse into a complete tree.

```python
texform.count_targets(r"\frac{x}{y} + \alpha")  # {'cmd:frac': 1, 'char:alpha': 1}
```

- [list_packages](https://texform.dev/api/python/utilities.md#list_packages)

## `PackageInfo`

Kind: typedDict

Summary of one built-in knowledge package.

| Name | Type | Description |
| --- | --- | --- |
| `name` | str | The package identifier accepted by the ``packages`` argument of ``KnowledgeBase`` (such as ``"base"`` or ``"ams"``). |
| `commands` | int | The number of command records in the package. |
| `environments` | int | The number of environment records in the package. |

## `TexformError`

Kind: exception

Extends: Exception

Base class for every exception the library raises.

Catching ``TexformError`` catches all of them. Note that ``Parser.parse``
does not raise on malformed input; it reports failures through its result
dict instead.

- [ParseError](https://texform.dev/api/python/utilities.md#ParseError)
- [EditError](https://texform.dev/api/python/utilities.md#EditError)
- [ConfigError](https://texform.dev/api/python/utilities.md#ConfigError)
- [TransformError](https://texform.dev/api/python/utilities.md#TransformError)

## `ParseError`

Kind: exception

Extends: TexformError

Raised when source could not be parsed into a complete tree.

Besides the cases below, ``Document.create_*``, ``parse_fragment``, and the ``set_*`` editing methods raise it when a source string is invalid.

``TransformEngine.normalize`` raises this on input that cannot produce a
complete tree, and ``count_targets`` raises it when the source does not parse
into a complete tree. The exception then carries the diagnostics and the
partial document for inspection.

#### `diagnostics`

The diagnostics describing the parse failure.

#### `document`

The partial ``Document``, or ``None`` when no tree was produced.

## `EditError`

Kind: exception

Extends: TexformError

Raised by a ``Document`` editing method on an invalid edit.

Triggers include editing a read-only (error) tree, detaching or removing the
root node, an out-of-bounds index, a wrong container shape, and attaching a
node that belongs to another document. The edit is rejected before it can
corrupt the tree.

## `ConfigError`

Kind: exception

Extends: TexformError

Raised on invalid construction or per-call configuration input.

Triggers include an unknown knowledge package name or transform profile, a
``config`` argument that is not the matching complete-config class (including
a dict passed as ``config``), unknown override keys, wrong scalar types
(string or int instead of bool, float instead of int), a list where an object
is expected, and a config class instance used as a nested override value.

## `TransformError`

Kind: exception

Extends: TexformError

Raised on a transform-engine failure.

Triggers include an eliminated-form contract violation, passing
``TransformEngine.transform`` a document that ``has_errors()``, or one
bound to a different knowledge-base instance.

## `ConformanceError`

Kind: exception

Extends: EditError

Raised when a construction, edit, or syntax import violates the knowledge base or the document's structure.

#### `path`

The tree path where the violation was found.

#### `rule`

A stable machine-readable rule code.

## `list_rules`

Kind: function

```python
list_rules() -> list[RuleInfo]
```

List the built-in rewrite rules, sorted by key.

The returned keys are the rule identifiers accepted by the
``disable_rules`` argument of ``TransformEngine`` and reported in rewrite
statistics. A rule runs only when the engine's profile selects its level and
the knowledge base enables one of its packages.

**Returns** `list[RuleInfo]` A list of ``RuleInfo`` dicts, each ``{"key": str, "level": str, "fidelity": str, "summary": str, "enabled_by_packages": list[str]}``.

```python
[rule for rule in texform.list_rules() if rule["key"] == "base/over-to-frac"]
# [{'key': 'base/over-to-frac', 'level': 'authoring', 'fidelity': 'render', ...}]
```

- [RuleInfo](https://texform.dev/api/python/utilities.md#RuleInfo)
- [TransformEngine](https://texform.dev/api/python/transform-engine.md#TransformEngine)

## `RuleInfo`

Kind: typedDict

Summary of one built-in rewrite rule.

| Name | Type | Description |
| --- | --- | --- |
| `key` | str | The stable rule key, such as ``"base/over-to-frac"``, accepted by the ``disable_rules`` argument of ``TransformEngine``. |
| `level` | RuleLevel | The first profile that accepts the rule's output. |
| `fidelity` | RuleFidelity | The rule's worst-case equivalence guarantee. |
| `summary` | str | A one-line description of what the rule does. |
| `enabled_by_packages` | list[str] | Packages that make the rule loadable when any one of them is enabled. |

## `RuleFidelity`

Kind: typeAlias

```python
Literal['math', 'reading', 'render']
```

A 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).

## `RuleLevel`

Kind: typeAlias

```python
Literal['authoring', 'faithful', 'corpus', 'equiv']
```

The first profile that accepts a rewrite rule's output as a suitable product.

