Skip to content
lsdocs-rst API

lsdocs_rst #

A fast reStructuredText parser that builds docutils' document tree.

lsdocs-rst is a Rust port of docutils' parser and transforms. It builds the tree docutils builds (the same node kinds and attributes, printed as the same pseudo-XML) and records where in the source each node came from:

import lsdocs_rst

doc = lsdocs_rst.parse("Title\n=====\n\nHello, *world*.\n", transforms=True)
print(doc.pformat())
for emphasis in doc.findall("emphasis"):
    print(emphasis.astext(), emphasis.span)   # world (20, 27)

Settings are docutils' (tab_width, pep_references, ...), given as keyword arguments. Directives and roles can be written in Python (see Directive and Parser.role()), and directives such as include read files only through a loader you give (root= or files=). With docutils installed, Element.to_docutils() turns a tree into a docutils.nodes.document for docutils' writers.

class Text #

class Text(text: str, span: Span | None = None)

Text in the tree.

method astext #

astext(self) -> str

method to_dict #

to_dict(self) -> dict[str, Any]

method pformat #

pformat(self) -> str

class Element #

class Element(kind: str, attributes: dict[str, Any] | None = None, children: list[Node] | None = None, span: Span | None = None)

An element: a docutils node kind ("paragraph", "section", ...), attributes, children and a span.

Like a docutils node, element[i] is a child and element["ids"] an attribute.

property tagname #

property tagname: str

The kind, under docutils' name for it.

method from_dict #

classmethod from_dict(cls, data: Mapping[str, Any]) -> Element

An element from its dict form (see to_dict()).

method to_dict #

to_dict(self) -> dict[str, Any]

The dict form: kind, and attributes, children and span when present. Text is {"text": ..., "span": ...}. The same form as the Rust crate's serde feature, so it round-trips through JSON.

method pformat #

pformat(self) -> str

Pseudo-XML, exactly as docutils' pformat() prints it.

method to_xml #

to_xml(self, *, newlines: bool = False, indents: bool = False, xml_declaration: bool = True, doctype_declaration: bool = True) -> str

Docutils XML, as docutils --writer=xml writes it.

method to_docutils #

to_docutils(self, settings: Any = None) -> Any

The tree as docutils nodes (needs docutils). A document element becomes a docutils.nodes.document with settings (docutils' defaults if None), ready for docutils' writers.

method astext #

astext(self) -> str

The text of all descendants, concatenated.

method traverse #

traverse(self) -> Iterator[Element]

This element and its descendant elements, in document order.

method findall #

findall(self, kind: str | None = None) -> Iterator[Element]

This element and its descendants of kind (all if None), in document order, as docutils' findall.

method get #

get(self, name: str, default: Any = None) -> Any

variable Node #

Node = Union[Element, Text]

class DirectiveError #

class DirectiveError(message: str, level: int = ERROR)

Raised by a directive or role: reported in the document as a system message of level (1 info, 2 warning, 3 error, 4 severe), as docutils reports its own directives' errors.

class DirectiveContext #

class DirectiveContext(native: Any)

What a directive's Directive.run() gets: what was written, and access to the parser.

method parse_content #

parse_content(self, container: Element) -> Element

Parses the content as body elements into container.

method parse_inline #

parse_inline(self, text: str) -> tuple[list[Node], list[Element]]

Parses text as inline markup: the nodes, and messages to put after the element holding them.

method message #

message(self, level: int, text: str) -> Element

A system message (1 info to 4 severe) for the directive's line.

field name #

name: str = native.name

field arguments #

arguments: list[str] = native.arguments

field options #

options: dict[str, Any] = native.options

field content #

content: list[str] = native.content

field lineno #

lineno: int = native.lineno

field block_text #

block_text: str = native.block_text

field span #

span: Span | None = _span_from(native.span)

field in_substitution #

in_substitution: bool = native.in_substitution

class Directive #

class Directive

A directive: subclass it, set what it accepts, and implement run():

class Shout(lsdocs_rst.Directive):
    required_arguments = 1
    final_argument_whitespace = True

    def run(self, ctx):
        nodes, messages = ctx.parse_inline(ctx.arguments[0].upper())
        return [lsdocs_rst.Element("paragraph", children=nodes), *messages]

parser = lsdocs_rst.Parser().directive("shout", Shout)

option_spec maps option names to docutils' conversion functions, by name ("flag", "unchanged", "unchanged_required", "path", "uri", "int", "nonnegative_int", "percentage", "length_or_unitless", "length_or_percentage_or_unitless", "class_option"), by the functions themselves (docutils.parsers.rst.directives.flag, ...), or to a list of choices.

field required_arguments #

required_arguments: int = 0

field optional_arguments #

optional_arguments: int = 0

field final_argument_whitespace #

final_argument_whitespace: bool = False

field option_spec #

option_spec: Mapping[str, Any] = {}

field has_content #

has_content: bool = False

method run #

run(self, ctx: DirectiveContext) -> Sequence[Node | str]

The directive's nodes; raise DirectiveError to report a problem instead.

class RoleContext #

class RoleContext(data: Mapping[str, Any])

What a role function gets.

field name #

name: str = data["name"]

field text #

text: str = data["text"]

field raw_text #

raw_text: str = data["raw_text"]

field rawsource #

rawsource: str = data["rawsource"]

field options #

options: dict[str, Any] = data["options"]

field lineno #

lineno: int = data["lineno"]

field span #

span: Span | None = _span_from(data["span"])

class Parser #

class Parser(*, source: str | None = None, transforms: bool = False, keep_unknown_directives: bool = False, root: str | os.PathLike[str] | None = None, files: Loader | None = None, urls: Loader | None = None, **settings: Any)

A configured parser. Each method returns a new parser, so a parser can be shared and specialized:

parser = Parser(transforms=True, tab_width=4).role("shout", shout)
doc = parser.parse(text)

Keyword arguments: source (the document's name, used in messages), transforms (apply docutils' transforms, as publish_doctree does), keep_unknown_directives (keep them as directive elements instead of reporting them), root (let directives read files below this directory), files and urls (or read them with these functions, which return bytes or str and raise OSError), and any docutils setting the parser honors (tab_width, pep_references, id_prefix, ...; see default_settings()).

method directive #

directive(self, name: str, directive: type[Directive] | Directive) -> Parser

A parser with directive (a Directive subclass or instance) under name, before any standard one of that name.

method role #

role(self, name: str, role: Callable[[RoleContext], Sequence[Node | str]]) -> Parser

A parser with the role function role under name. It gets a RoleContext and returns inline nodes (or raises DirectiveError).

property settings #

property settings: dict[str, Any]

The docutils settings in use.

method parse #

parse(self, text: str) -> Element

Parses text into a document element. Problems are system_message elements in the tree; parsing itself only fails if a Python directive, role or loader raises (other than DirectiveError and OSError).

method parse_with_messages #

parse_with_messages(self, text: str) -> tuple[Element, list[Element]]

parse(), plus the messages docutils' transforms report without putting them in the tree (problematic elements refer to them by id).

function parse #

parse(text: str, **options: Any) -> Element

Parses text; the keyword arguments are Parser's.

function make_id #

make_id(name: str) -> str

name as docutils makes ids of names (docutils.nodes.make_id).

function default_settings #

default_settings() -> dict[str, Any]

The docutils settings the parser honors, with docutils' defaults.