Docutils | Overview | About | Users | Reference | Developers

The Docutils Publisher

Author:

David Goodger

Contact:
docutils-develop@lists.sourceforge.net
Date:
2024-08-21
Revision:
9913

The docutils.core.Publisher class is the core of Docutils, managing all the processing and relationships between components. [1]

The Publisher convenience functions are the normal entry points for using Docutils as a library. Entry point functions with pre-set components are provided for use in "console_scripts" entry points. Configuration is done via convenience function arguments and runtime settings assembled from several sources.

Publisher Convenience Functions

There are several convenience functions in the docutils.core module. Each of these functions sets up a docutils.core.Publisher object, then calls its publish() method which handles everything else. For details, see the argument reference, the function docstrings and the source file core.py.

publish_cmdline()

Function for custom command-line applications.

def publish_cmdline(reader=None, reader_name=None, [5]
                    parser=None, parser_name=None, [5]
                    writer=None, writer_name=None, [5]
                    settings=None, settings_spec=None,
                    settings_overrides=None, config_section=None,
                    enable_exit_status=False,
                    argv=None, usage=default_usage,
                    description=default_description) -> str | bytes

The function reads input from sys.stdin or a file specified on the command line, writes the output document to a file, and also returns it as str instance. [2]

See the entry point functions in core.py, the scripts in the tools/ directory, and Inside A Docutils Command-Line Front-End Tool for usage examples.

publish_file()

For programmatic use with file I/O.

def publish_file(source=None, source_path=None,
                 destination=None, destination_path=None,
                 reader=None, reader_name=None, [5]
                 parser=None, parser_name=None, [5]
                 writer=None, writer_name=None, [5]
                 settings=None, settings_spec=None,
                 settings_overrides=None, config_section=None,
                 enable_exit_status=False) -> str | bytes

Read input from a file-like object. Write the output document to a file-like object and also return it as str instance. [2]

publish_string()

For programmatic use with string I/O.

def publish_string(source, source_path=None,
                   destination_path=None,
                   reader=None, reader_name=None, [5]
                   parser=None, parser_name=None, [5]
                   writer=None, writer_name=None, [5]
                   settings=None, settings_spec=None,
                   settings_overrides=None, config_section=None,
                   enable_exit_status=False) -> bytes | str

Get the input from the source argument (a str or bytes instance). Return the output document as a bytes instance unless the output_encoding runtime setting has the special value "unicode". [3]

Example:

Return a Docutils XML version of the source as str instance:

publish_string(source, writer='xml',
    settings_overrides={'output_encoding': 'unicode'})

The publish_str() function is provisional because in Python 3 the name and default return type no longer match.

publish_doctree()

For programmatic use with string input. Parse input into a Docutils Document Tree data structure. Return a nodes.document instance.

publish_doctree(source, source_path=None,
                source_class=io.StringInput,
                reader=None, reader_name=None, [5]
                parser=None, parser_name=None, [5]
                settings=None, settings_spec=None,
                settings_overrides=None, config_section=None,
                enable_exit_status=False) -> nodes.document

The Document Tree can be modified, pickled & unpickled, etc., and then reprocessed with publish_from_doctree().

publish_from_doctree()

For programmatic use with string output. Render from an existing Document Tree data structure (nodes.document instance). Return the output document as a bytes or str instance (cf. publish_string()).

publish_from_doctree(document, destination_path=None,
                     writer=None, writer_name=None, [5]
                     settings=None, settings_spec=None,
                     settings_overrides=None, config_section=None,
                     enable_exit_status=False) -> bytes | str

The publish_from_doctree() function is provisional because in Python 3 the name and default return type of the string I/O interface no longer match.

publish_parts()

For programmatic use. With string input (default) or file input (depending on the value of the source_class argument). Returns a dictionary of document parts.

def publish_parts(source, source_path=None,
                  source_class=io.StringInput,
                  destination_path=None,
                  reader=None, reader_name=None, [5]
                  parser=None, parser_name=None, [5]
                  writer=None, writer_name=None, [5]
                  settings=None, settings_spec=None,
                  settings_overrides=None, config_section=None,
                  enable_exit_status=False) -> dict

Dictionary keys are the part names. Each Writer component may publish a different set of document parts:

Example:

post-process the output document with a custom function post_process() before encoding with user-customizable encoding and errors:

def publish_bytes_with_postprocessing(*args, **kwargs):
    parts = publish_parts(*args, **kwargs)
    out_str = post_process(parts['whole'])
    return out_str.encode(parts['encoding'], parts['errors'])

There are more usage examples in the docutils/examples.py module.

Parts Provided by All Writers

"encoding"str

The output_encoding setting.

"errors"str

The output_encoding_error_handler setting.

"version"str

The version of Docutils used.

"whole"str | bytes

The entire formatted document. [2]

Parts Provided by the HTML Writers

All parts returned by the HTML writers are of data type str.

HTML4 Writer
"body"

Equivalent to "fragment". It is not equivalent to "html_body".

"body_prefix"

Contains

</head>
<body>
<div class="document" ...>

and, if applicable

<div class="header">
...
</div>
"body_pre_docinfo"

Contains (as applicable):

<h1 class="title">...</h1>
<h2 class="subtitle" id="...">...</h2>
"body_suffix"

Contains

</div>

(the end-tag for <div class="document">), the footer division if applicable:

<div class="footer">
...
</div>

and

</body>
</html>
"docinfo"

Bibliographic data, i.e. the <docinfo> element's content, [4] rendered as a table.

"footer"

The document footer content, meant to appear at the bottom of a web page, or repeated at the bottom of every printed page.

"fragment"

The document body (not the HTML <body>). In other words, part['fragment'] contains the entire document, less the document "title", "subtitle", "docinfo", "header", and "footer". Equivalent to part "body".

"head"

Contains <meta ... /> tags and the document <title>...</title>. See also "html_head".

"head_prefix"

The XML declaration, the DOCTYPE declaration, the <html ...> start tag, and the <head> start tag.

"header"

The document header content, meant to appear at the top of a web page, or repeated at the top of every printed page.

"html_body"

The HTML <body> content, less the <body> and </body> tags themselves.

"html_head"

The HTML <head> content, less the "stylesheet" and the <head> and </head> tags themselves.

The "Content-Type" meta tag's "charset" value is left unresolved, as %s:

<meta http-equiv="Content-Type" content="text/html; charset=%s" />

The interpolation should be done by client code. Alternatively, use part "head" which interpolates the "charset" value with "encoding".

"html_prolog"

The XML declaration and the doctype declaration. The XML declaration's "encoding" attribute's value is left unresolved, as "%s":

<?xml version="1.0" encoding="%s" ?>

The interpolation should be done by client code.

"html_subtitle"

The document subtitle, including the enclosing <h2 class="subtitle"> and </h2> tags.

"html_title"

The document title, including the enclosing <h1 class="title"> and </h1> tags.

"meta"

Contains all <meta ... /> tags.

"stylesheet"

The embedded stylesheet or stylesheet link.

"subtitle"

The document subtitle text and any inline markup. It does not include the enclosing <h2> and </h2> tags.

"title"

The document title text and any inline markup. It does not include the enclosing <h1> and </h1> tags.

The default template joins "head_prefix", "head", "stylesheet", "body_prefix", "body_pre_docinfo", "docinfo", "body", and "body_suffix" to get part "whole".

PEP/HTML Writer

The PEP/HTML writer provides the same parts as the HTML4 writer, plus the following:

"pepnum"

The PEP number (extracted from the header preamble).

S5/HTML Writer

The S5/HTML writer provides the same parts as the HTML4 writer.

HTML5 Writer

The HTML5 writer provides the same parts as the HTML4 writer. However, it uses semantic HTML5 elements for the document, "header", and "footer" and a description list for the "docinfo" part.

Parts Provided by the (Xe)LaTeX Writers

All parts returned by the (Xe)LaTeX writers are of data type str.

"abstract"

Formatted content of the "abstract" bibliographic field.

"body"

The document's content. In other words, parts['body'] contains the entire document, except the document title, subtitle, and docinfo.

This part can be included into another LaTeX document body using the \input{} command.

"body_pre_docinfo"

The \maketitle command.

"dedication"

Formatted content of the "dedication" bibliographic field.

"docinfo"

Bibliographic data, i.e. the <docinfo> element's content, rendered as a table.

With --use-latex-docinfo the <author>, <organization>, <contact>, <address" and <date> are moved to "titledata".

"fallbacks"

Fallback definitions for Docutils-specific LaTeX commands and environments.

"head_prefix"

The declaration of documentclass and document options.

"latex_preamble"

The argument of the --latex-preamble option.

"pdfsetup"

PDF properties ("hyperref" package setup).

"requirements"

Required packages and setup before the stylesheet inclusion.

"stylesheet"

The embedded stylesheet(s) or stylesheet loading command(s).

"subtitle"

Document subtitle text and any inline markup.

"title"

Document title text and any inline markup.

"titledata"

The combined title data in \title, \author, and \date macros.

With --use-latex-docinfo, this includes the <author>, <organization>, <contact>, <address" and <date> docinfo items.

See the template files default.tex, titlepage.tex, titlingpage.tex, and xelatex.tex for examples how these parts are combined into a valid LaTeX document.

publish_programmatically()

Auxiliary function used by publish_file(), publish_string(), publish_doctree(), and publish_parts(). Applications should not need to call this function directly.

Entry Point Functions

The functions rst2html(), rst2html4(), rst2html5(), rst2latex(), rst2man(), rst2odt(), rst2pseudoxml(), rst2s5(), rst2xetex(), and rst2xml() are wrappers around publish_cmdline() used in "console_scripts" entry points for eponymous command-line applications.

Argument Reference

File I/O

The function publish_file() uses the file I/O interface; publish_parts() can be configured to use file input by setting the source_class argument to docutils.io.FileInput.

sourcefile-like

A file-like object holding the document source (must have read() and close() methods).

Default: None (open source_path or use sys.stdin).

source_pathstr | pathlib.Path

Path to the source file, opened if source is None.

Default: None (use source).

destinationfile-like

A file-like object that will receive the output document (must have write() and close() methods).

Default: None (open destination_path or use sys.stdout).

destination_pathstr | pathlib.Path

Path to the destination file, opened if destination is None.

Default: None (use destination).

String I/O

The functions publish_string(), publish_doctree(), publish_from_doctree(), and publish_parts() use the string I/O interface provided by the docutils.io.StringInput and docutils.io.StringOutput classes.

sourcestr | bytes

The document source. bytes are decoded with the encoding specified in the input_encoding setting.

Required.

source_pathstr

Path to the file or name of the object that produced source. Used as "source" attribute in diagnostic output.

Default: None.

source_classdocutils.io.Input

Change the semantics of the "source" and "source_path" arguments. The value docutils.io.FileInput lets "source" and "source_path" behave as described in file I/O.

Default: docutils.io.StringInput.

destination_pathstr

Path to the file or name of the object which will receive the output. Used for determining relative paths (stylesheets, source links, etc.)

Default: None.

Component Specification

readerstr | docutils.readers.Reader

Reader component name or instance. [5]

Default: "standalone".

parserstr | docutils.parsers.Parser

Parser component name or instance. [5]

Default: "restructuredtext".

writerstr | docutils.writers.Writer

Writer component name or instance. [5]

Default: "pseudoxml".

Settings Specification

See also Runtime Settings.

settingsdocutils.frontend.Values

Runtime settings object. If settings is passed, it's assumed to be the end result of runtime settings processing and no further setting/config/option processing is done.

Default: None.

settings_specdocutils.SettingsSpec

Application-specific settings definitions, independent of components. In other words, the application becomes a component, and its settings data is processed after the other components. Used only if settings is None.

Default: None.

settings_overridesdict

Application-specific settings defaults that override the defaults of other components. Used only if settings is None.

Default: None.

config_sectionstr

Name of the configuration file section for this application.

Can be specified instead of settings_spec (a new docutils.SettingsSpec will be created) or in addition to settings_spec (overriding its config_section attribute). Used only if settings is None.

Default: None.

enable_exit_statusbool

Set "system exit status" at end of processing?

Default: False.