# The Docutils Publisher

Author:

  David Goodger

Contact:
  docutils-develop@lists.sourceforge.net
Date:
  2025-12-01
Revision:
  10267
Copyright:
  This document has been placed in the public domain.

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.

[1]

See the Docutils Project Model in PEP 258 for an overview.

## 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.

[2] (1,2,3)

Documents in binary formats (currently only ODT) are returned as a bytes instance.

### 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'})

Caution!

The output_encoding and output_encoding_error_handler runtime settings may affect the content of the output document: Some document formats contain an encoding declaration, some formats use substitutions for non-encodable characters.

Use publish_parts() to get a str instance of the output document together with values of the "output_encoding" and "output_encoding_error_handler" settings.

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

[3]

similar to xml.etree.ElementTree.tostring()

### 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.

  [4]

  Abstract and dedication are included in the "body"/"fragment" part.

"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 LaTeX Writers

All parts returned by the LaTeX writers ("latex" writer and "xelatex" writer) 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 except "abstract" and "dedication" (i.e. the <docinfo> element's content), rendered as a table.

  If the use_latex_docinfo setting is True, <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 setting.

"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.

"template"

  Content of the template file. The output document (i.e. part "whole") is generated from the template by substituting placeholders with the corresponding parts using string.Template.substitute(). New in Docutils 0.22.

"title"

  Document title text and any inline markup.

"titledata"

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

  If use_latex_docinfo is True, "titledata" includes content from the <docinfo> elements <author>, <organization>, <contact>, <address>, and <date>.

### 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 or sys.stdin).

destination file-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 or sys.stdout).

### 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_class docutils.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

reader str | docutils.readers.Reader

  Reader component name or instance. [5]

  Default: "standalone".

parser str | docutils.parsers.Parser

  Parser component name or instance. [5]

  Default: "restructuredtext".

writer str | docutils.writers.Writer

  Writer component name or instance. [5]

  Default: "pseudoxml".

[5] (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18)

Up to Docutils 0.21, component names were specified with the "reader_name", "parser_name", and "writer_name" arguments. These arguments are deprecated and will be removed in Docutils 2.0.

### Settings Specification

See also Runtime Settings.

settings docutils.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_spec docutils.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_overrides dict

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

  Default: None.

config_section str

  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_status bool

  Set "system exit status" at end of processing?

  Default: False.