Commits

Zoom Quiet  committed 304d0ae

make pure doc branch-clean others

  • Participants
  • Parent commits 2e5354c
  • Branches doc-zh

Comments (0)

Files changed (364)

File custom_fixers/__init__.py

Empty file removed.

File custom_fixers/fix_alt_unicode.py

-from lib2to3.fixer_base import BaseFix
-from lib2to3.fixer_util import Name
-
-class FixAltUnicode(BaseFix):
-    PATTERN = """
-    func=funcdef< 'def' name='__unicode__'
-                  parameters< '(' NAME ')' > any+ >
-    """
-
-    def transform(self, node, results):
-        name = results['name']
-        name.replace(Name('__str__', prefix=name.prefix))

File sphinx/__init__.py

-# -*- coding: utf-8 -*-
-"""
-    Sphinx
-    ~~~~~~
-
-    The Sphinx documentation toolchain.
-
-    :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-# Keep this file executable as-is in Python 3!
-# (Otherwise getting the version out of it from setup.py is impossible.)
-
-import sys
-from os import path
-
-__version__  = '1.1pre'
-__released__ = '1.1 (hg)'  # used when Sphinx builds its own docs
-
-package_dir = path.abspath(path.dirname(__file__))
-
-if '+' in __version__ or 'pre' in __version__:
-    # try to find out the changeset hash if checked out from hg, and append
-    # it to __version__ (since we use this value from setup.py, it gets
-    # automatically propagated to an installed copy as well)
-    try:
-        import subprocess
-        p = subprocess.Popen(['hg', 'id', '-i', '-R',
-                              path.join(package_dir, '..')],
-                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-        out, err = p.communicate()
-        if out:
-            __version__ += '/' + out.strip()
-    except Exception:
-        pass
-
-
-def main(argv=sys.argv):
-    """Sphinx build "main" command-line entry."""
-    if sys.version_info[:3] < (2, 4, 0):
-        sys.stderr.write('Error: Sphinx requires at least '
-                         'Python 2.4 to run.\n')
-        return 1
-
-    try:
-        from sphinx import cmdline
-    except ImportError:
-        err = sys.exc_info()[1]
-        errstr = str(err)
-        if errstr.lower().startswith('no module named'):
-            whichmod = errstr[16:]
-            hint = ''
-            if whichmod.startswith('docutils'):
-                whichmod = 'Docutils library'
-            elif whichmod.startswith('jinja'):
-                whichmod = 'Jinja2 library'
-            elif whichmod == 'roman':
-                whichmod = 'roman module (which is distributed with Docutils)'
-                hint = ('This can happen if you upgraded docutils using\n'
-                        'easy_install without uninstalling the old version'
-                        'first.\n')
-            else:
-                whichmod += ' module'
-            sys.stderr.write('Error: The %s cannot be found. '
-                             'Did you install Sphinx and its dependencies '
-                             'correctly?\n' % whichmod)
-            if hint:
-                sys.stderr.write(hint)
-            return 1
-        raise
-    return cmdline.main(argv)
-
-
-if __name__ == '__main__':
-    sys.exit(main(sys.argv))

File sphinx/addnodes.py

-# -*- coding: utf-8 -*-
-"""
-    sphinx.addnodes
-    ~~~~~~~~~~~~~~~
-
-    Additional docutils nodes.
-
-    :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-from docutils import nodes
-
-
-class toctree(nodes.General, nodes.Element):
-    """Node for inserting a "TOC tree"."""
-
-
-# domain-specific object descriptions (class, function etc.)
-
-class desc(nodes.Admonition, nodes.Element):
-    """Node for object descriptions.
-
-    This node is similar to a "definition list" with one definition.  It
-    contains one or more ``desc_signature`` and a ``desc_content``.
-    """
-
-class desc_signature(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for object signatures.
-
-    The "term" part of the custom Sphinx definition list.
-    """
-
-
-# nodes to use within a desc_signature
-
-class desc_addname(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for additional name parts (module name, class name)."""
-# compatibility alias
-desc_classname = desc_addname
-
-class desc_type(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for return types or object type names."""
-
-class desc_returns(desc_type):
-    """Node for a "returns" annotation (a la -> in Python)."""
-    def astext(self):
-        return ' -> ' + nodes.TextElement.astext(self)
-
-class desc_name(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for the main object name."""
-
-class desc_parameterlist(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for a general parameter list."""
-    child_text_separator = ', '
-
-class desc_parameter(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for a single parameter."""
-
-class desc_optional(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for marking optional parts of the parameter list."""
-    child_text_separator = ', '
-    def astext(self):
-        return '[' + nodes.TextElement.astext(self) + ']'
-
-class desc_annotation(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for signature annotations (not Python 3-style annotations)."""
-
-class desc_content(nodes.General, nodes.Element):
-    """Node for object description content.
-
-    This is the "definition" part of the custom Sphinx definition list.
-    """
-
-
-# new admonition-like constructs
-
-class versionmodified(nodes.Admonition, nodes.TextElement):
-    """Node for version change entries.
-
-    Currently used for "versionadded", "versionchanged" and "deprecated"
-    directives.
-    """
-
-class seealso(nodes.Admonition, nodes.Element):
-    """Custom "see also" admonition."""
-
-class productionlist(nodes.Admonition, nodes.Element):
-    """Node for grammar production lists.
-
-    Contains ``production`` nodes.
-    """
-
-class production(nodes.Part, nodes.Inline, nodes.TextElement):
-    """Node for a single grammar production rule."""
-
-
-# other directive-level nodes
-
-class index(nodes.Invisible, nodes.Inline, nodes.TextElement):
-    """Node for index entries.
-
-    This node is created by the ``index`` directive and has one attribute,
-    ``entries``.  Its value is a list of 4-tuples of ``(entrytype, entryname,
-    target, ignored)``.
-
-    *entrytype* is one of "single", "pair", "double", "triple".
-    """
-
-class centered(nodes.Part, nodes.Element):
-    """Deprecated."""
-
-class acks(nodes.Element):
-    """Special node for "acks" lists."""
-
-class hlist(nodes.Element):
-    """Node for "horizontal lists", i.e. lists that should be compressed to
-    take up less vertical space.
-    """
-
-class hlistcol(nodes.Element):
-    """Node for one column in a horizontal list."""
-
-class compact_paragraph(nodes.paragraph):
-    """Node for a compact paragraph (which never makes a <p> node)."""
-
-class glossary(nodes.Element):
-    """Node to insert a glossary."""
-
-class only(nodes.Element):
-    """Node for "only" directives (conditional inclusion based on tags)."""
-
-
-# meta-information nodes
-
-class start_of_file(nodes.Element):
-    """Node to mark start of a new file, used in the LaTeX builder only."""
-
-class highlightlang(nodes.Element):
-    """Inserted to set the highlight language and line number options for
-    subsequent code blocks.
-    """
-
-class tabular_col_spec(nodes.Element):
-    """Node for specifying tabular columns, used for LaTeX output."""
-
-class meta(nodes.Special, nodes.PreBibliographic, nodes.Element):
-    """Node for meta directive -- same as docutils' standard meta node,
-    but pickleable.
-    """
-
-
-# inline nodes
-
-class pending_xref(nodes.Inline, nodes.Element):
-    """Node for cross-references that cannot be resolved without complete
-    information about all documents.
-
-    These nodes are resolved before writing output, in
-    BuildEnvironment.resolve_references.
-    """
-
-class download_reference(nodes.reference):
-    """Node for download references, similar to pending_xref."""
-
-class literal_emphasis(nodes.emphasis):
-    """Node that behaves like `emphasis`, but further text processors are not
-    applied (e.g. smartypants for HTML output).
-    """
-
-class abbreviation(nodes.Inline, nodes.TextElement):
-    """Node for abbreviations with explanations."""
-
-
-# make the new nodes known to docutils; needed because the HTML writer will
-# choke at some point if these are not added
-nodes._add_node_class_names(k for k in globals().keys()
-                            if k != 'nodes' and k[0] != '_')

File sphinx/application.py

-# -*- coding: utf-8 -*-
-"""
-    sphinx.application
-    ~~~~~~~~~~~~~~~~~~
-
-    Sphinx application object.
-
-    Gracefully adapted from the TextPress system by Armin.
-
-    :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-import sys
-import types
-import posixpath
-from os import path
-from cStringIO import StringIO
-
-from docutils import nodes
-from docutils.parsers.rst import convert_directive_function, \
-     directives, roles
-
-import sphinx
-from sphinx import package_dir, locale
-from sphinx.roles import XRefRole
-from sphinx.config import Config
-from sphinx.errors import SphinxError, SphinxWarning, ExtensionError, \
-     VersionRequirementError
-from sphinx.domains import ObjType, BUILTIN_DOMAINS
-from sphinx.domains.std import GenericObject, Target, StandardDomain
-from sphinx.builders import BUILTIN_BUILDERS
-from sphinx.environment import BuildEnvironment, SphinxStandaloneReader
-from sphinx.util import pycompat  # imported for side-effects
-from sphinx.util.tags import Tags
-from sphinx.util.osutil import ENOENT
-from sphinx.util.console import bold
-
-
-# List of all known core events. Maps name to arguments description.
-events = {
-    'builder-inited': '',
-    'env-purge-doc': 'env, docname',
-    'source-read': 'docname, source text',
-    'doctree-read': 'the doctree before being pickled',
-    'missing-reference': 'env, node, contnode',
-    'doctree-resolved': 'doctree, docname',
-    'env-updated': 'env',
-    'html-collect-pages': 'builder',
-    'html-page-context': 'pagename, context, doctree or None',
-    'build-finished': 'exception',
-}
-
-CONFIG_FILENAME = 'conf.py'
-ENV_PICKLE_FILENAME = 'environment.pickle'
-
-
-class Sphinx(object):
-
-    def __init__(self, srcdir, confdir, outdir, doctreedir, buildername,
-                 confoverrides=None, status=sys.stdout, warning=sys.stderr,
-                 freshenv=False, warningiserror=False, tags=None):
-        self.next_listener_id = 0
-        self._extensions = {}
-        self._listeners = {}
-        self.domains = BUILTIN_DOMAINS.copy()
-        self.builderclasses = BUILTIN_BUILDERS.copy()
-        self.builder = None
-        self.env = None
-
-        self.srcdir = srcdir
-        self.confdir = confdir
-        self.outdir = outdir
-        self.doctreedir = doctreedir
-
-        if status is None:
-            self._status = StringIO()
-            self.quiet = True
-        else:
-            self._status = status
-            self.quiet = False
-
-        if warning is None:
-            self._warning = StringIO()
-        else:
-            self._warning = warning
-        self._warncount = 0
-        self.warningiserror = warningiserror
-
-        self._events = events.copy()
-
-        # say hello to the world
-        self.info(bold('Running Sphinx v%s' % sphinx.__version__))
-
-        # status code for command-line application
-        self.statuscode = 0
-
-        # read config
-        self.tags = Tags(tags)
-        self.config = Config(confdir, CONFIG_FILENAME,
-                             confoverrides or {}, self.tags)
-        self.config.check_unicode(self.warn)
-
-        # set confdir to srcdir if -C given (!= no confdir); a few pieces
-        # of code expect a confdir to be set
-        if self.confdir is None:
-            self.confdir = self.srcdir
-
-        # backwards compatibility: activate old C markup
-        self.setup_extension('sphinx.ext.oldcmarkup')
-        # load all user-given extension modules
-        for extension in self.config.extensions:
-            self.setup_extension(extension)
-        # the config file itself can be an extension
-        if self.config.setup:
-            self.config.setup(self)
-
-        # now that we know all config values, collect them from conf.py
-        self.config.init_values()
-
-        # check the Sphinx version if requested
-        if self.config.needs_sphinx and \
-           self.config.needs_sphinx > sphinx.__version__[:3]:
-            raise VersionRequirementError(
-                'This project needs at least Sphinx v%s and therefore cannot '
-                'be built with this version.' % self.config.needs_sphinx)
-
-        # set up translation infrastructure
-        self._init_i18n()
-        # set up the build environment
-        self._init_env(freshenv)
-        # set up the builder
-        self._init_builder(buildername)
-
-    def _init_i18n(self):
-        """Load translated strings from the configured localedirs if enabled in
-        the configuration.
-        """
-        if self.config.language is not None:
-            self.info(bold('loading translations [%s]... ' %
-                           self.config.language), nonl=True)
-            locale_dirs = [None, path.join(package_dir, 'locale')] + \
-                [path.join(self.srcdir, x) for x in self.config.locale_dirs]
-        else:
-            locale_dirs = []
-        self.translator, has_translation = locale.init(locale_dirs,
-                                                       self.config.language)
-        if self.config.language is not None:
-            if has_translation:
-                self.info('done')
-            else:
-                self.info('locale not available')
-
-    def _init_env(self, freshenv):
-        if freshenv:
-            self.env = BuildEnvironment(self.srcdir, self.doctreedir,
-                                        self.config)
-            self.env.find_files(self.config)
-            for domain in self.domains.keys():
-                self.env.domains[domain] = self.domains[domain](self.env)
-        else:
-            try:
-                self.info(bold('loading pickled environment... '), nonl=True)
-                self.env = BuildEnvironment.frompickle(self.config,
-                    path.join(self.doctreedir, ENV_PICKLE_FILENAME))
-                self.env.domains = {}
-                for domain in self.domains.keys():
-                    # this can raise if the data version doesn't fit
-                    self.env.domains[domain] = self.domains[domain](self.env)
-                self.info('done')
-            except Exception, err:
-                if type(err) is IOError and err.errno == ENOENT:
-                    self.info('not yet created')
-                else:
-                    self.info('failed: %s' % err)
-                return self._init_env(freshenv=True)
-
-        self.env.set_warnfunc(self.warn)
-
-    def _init_builder(self, buildername):
-        if buildername is None:
-            print >>self._status, 'No builder selected, using default: html'
-            buildername = 'html'
-        if buildername not in self.builderclasses:
-            raise SphinxError('Builder name %s not registered' % buildername)
-
-        builderclass = self.builderclasses[buildername]
-        if isinstance(builderclass, tuple):
-            # builtin builder
-            mod, cls = builderclass
-            builderclass = getattr(
-                __import__('sphinx.builders.' + mod, None, None, [cls]), cls)
-        self.builder = builderclass(self)
-        self.emit('builder-inited')
-
-    def build(self, force_all=False, filenames=None):
-        try:
-            if force_all:
-                self.builder.build_all()
-            elif filenames:
-                self.builder.build_specific(filenames)
-            else:
-                self.builder.build_update()
-        except Exception, err:
-            self.emit('build-finished', err)
-            raise
-        else:
-            self.emit('build-finished', None)
-        self.builder.cleanup()
-
-    def warn(self, message, location=None, prefix='WARNING: '):
-        if isinstance(location, tuple):
-            docname, lineno = location
-            if docname:
-                location = '%s:%s' % (self.env.doc2path(docname), lineno or '')
-            else:
-                location = None
-        warntext = location and '%s: %s%s\n' % (location, prefix, message) or \
-                   '%s%s\n' % (prefix, message)
-        if self.warningiserror:
-            raise SphinxWarning(warntext)
-        self._warncount += 1
-        try:
-            self._warning.write(warntext)
-        except UnicodeEncodeError:
-            encoding = getattr(self._warning, 'encoding', 'ascii') or 'ascii'
-            self._warning.write(warntext.encode(encoding, 'replace'))
-
-    def info(self, message='', nonl=False):
-        try:
-            self._status.write(message)
-        except UnicodeEncodeError:
-            encoding = getattr(self._status, 'encoding', 'ascii') or 'ascii'
-            self._status.write(message.encode(encoding, 'replace'))
-        if not nonl:
-            self._status.write('\n')
-        self._status.flush()
-
-    # general extensibility interface
-
-    def setup_extension(self, extension):
-        """Import and setup a Sphinx extension module. No-op if called twice."""
-        if extension in self._extensions:
-            return
-        try:
-            mod = __import__(extension, None, None, ['setup'])
-        except ImportError, err:
-            raise ExtensionError('Could not import extension %s' % extension,
-                                 err)
-        if not hasattr(mod, 'setup'):
-            self.warn('extension %r has no setup() function; is it really '
-                      'a Sphinx extension module?' % extension)
-        else:
-            try:
-                mod.setup(self)
-            except VersionRequirementError, err:
-                # add the extension name to the version required
-                raise VersionRequirementError(
-                    'The %s extension used by this project needs at least '
-                    'Sphinx v%s; it therefore cannot be built with this '
-                    'version.' % (extension, err))
-        self._extensions[extension] = mod
-
-    def require_sphinx(self, version):
-        # check the Sphinx version if requested
-        if version > sphinx.__version__[:3]:
-            raise VersionRequirementError(version)
-
-    def import_object(self, objname, source=None):
-        """Import an object from a 'module.name' string."""
-        try:
-            module, name = objname.rsplit('.', 1)
-        except ValueError, err:
-            raise ExtensionError('Invalid full object name %s' % objname +
-                                 (source and ' (needed for %s)' % source or ''),
-                                 err)
-        try:
-            return getattr(__import__(module, None, None, [name]), name)
-        except ImportError, err:
-            raise ExtensionError('Could not import %s' % module +
-                                 (source and ' (needed for %s)' % source or ''),
-                                 err)
-        except AttributeError, err:
-            raise ExtensionError('Could not find %s' % objname +
-                                 (source and ' (needed for %s)' % source or ''),
-                                 err)
-
-    # event interface
-
-    def _validate_event(self, event):
-        event = intern(event)
-        if event not in self._events:
-            raise ExtensionError('Unknown event name: %s' % event)
-
-    def connect(self, event, callback):
-        self._validate_event(event)
-        listener_id = self.next_listener_id
-        if event not in self._listeners:
-            self._listeners[event] = {listener_id: callback}
-        else:
-            self._listeners[event][listener_id] = callback
-        self.next_listener_id += 1
-        return listener_id
-
-    def disconnect(self, listener_id):
-        for event in self._listeners.itervalues():
-            event.pop(listener_id, None)
-
-    def emit(self, event, *args):
-        results = []
-        if event in self._listeners:
-            for _, callback in self._listeners[event].iteritems():
-                results.append(callback(self, *args))
-        return results
-
-    def emit_firstresult(self, event, *args):
-        for result in self.emit(event, *args):
-            if result is not None:
-                return result
-        return None
-
-    # registering addon parts
-
-    def add_builder(self, builder):
-        if not hasattr(builder, 'name'):
-            raise ExtensionError('Builder class %s has no "name" attribute'
-                                 % builder)
-        if builder.name in self.builderclasses:
-            if isinstance(self.builderclasses[builder.name], tuple):
-                raise ExtensionError('Builder %r is a builtin builder' %
-                                     builder.name)
-            else:
-                raise ExtensionError(
-                    'Builder %r already exists (in module %s)' % (
-                    builder.name, self.builderclasses[builder.name].__module__))
-        self.builderclasses[builder.name] = builder
-
-    def add_config_value(self, name, default, rebuild):
-        if name in self.config.values:
-            raise ExtensionError('Config value %r already present' % name)
-        if rebuild in (False, True):
-            rebuild = rebuild and 'env' or ''
-        self.config.values[name] = (default, rebuild)
-
-    def add_event(self, name):
-        if name in self._events:
-            raise ExtensionError('Event %r already present' % name)
-        self._events[name] = ''
-
-    def add_node(self, node, **kwds):
-        nodes._add_node_class_names([node.__name__])
-        for key, val in kwds.iteritems():
-            try:
-                visit, depart = val
-            except ValueError:
-                raise ExtensionError('Value for key %r must be a '
-                                     '(visit, depart) function tuple' % key)
-            if key == 'html':
-                from sphinx.writers.html import HTMLTranslator as translator
-            elif key == 'latex':
-                from sphinx.writers.latex import LaTeXTranslator as translator
-            elif key == 'text':
-                from sphinx.writers.text import TextTranslator as translator
-            elif key == 'man':
-                from sphinx.writers.manpage import ManualPageTranslator \
-                    as translator
-            elif key == 'texinfo':
-                from sphinx.writers.texinfo import TexinfoTranslator \
-                    as translator
-            else:
-                # ignore invalid keys for compatibility
-                continue
-            setattr(translator, 'visit_'+node.__name__, visit)
-            if depart:
-                setattr(translator, 'depart_'+node.__name__, depart)
-
-    def _directive_helper(self, obj, content=None, arguments=None, **options):
-        if isinstance(obj, (types.FunctionType, types.MethodType)):
-            obj.content = content
-            obj.arguments = arguments or (0, 0, False)
-            obj.options = options
-            return convert_directive_function(obj)
-        else:
-            if content or arguments or options:
-                raise ExtensionError('when adding directive classes, no '
-                                     'additional arguments may be given')
-            return obj
-
-    def add_directive(self, name, obj, content=None, arguments=None, **options):
-        directives.register_directive(
-            name, self._directive_helper(obj, content, arguments, **options))
-
-    def add_role(self, name, role):
-        roles.register_local_role(name, role)
-
-    def add_generic_role(self, name, nodeclass):
-        # don't use roles.register_generic_role because it uses
-        # register_canonical_role
-        role = roles.GenericRole(name, nodeclass)
-        roles.register_local_role(name, role)
-
-    def add_domain(self, domain):
-        if domain.name in self.domains:
-            raise ExtensionError('domain %s already registered' % domain.name)
-        self.domains[domain.name] = domain
-
-    def override_domain(self, domain):
-        if domain.name not in self.domains:
-            raise ExtensionError('domain %s not yet registered' % domain.name)
-        if not issubclass(domain, self.domains[domain.name]):
-            raise ExtensionError('new domain not a subclass of registered '
-                                 'domain' % domain.name)
-        self.domains[domain.name] = domain
-
-    def add_directive_to_domain(self, domain, name, obj,
-                                content=None, arguments=None, **options):
-        if domain not in self.domains:
-            raise ExtensionError('domain %s not yet registered' % domain)
-        self.domains[domain].directives[name] = \
-            self._directive_helper(obj, content, arguments, **options)
-
-    def add_role_to_domain(self, domain, name, role):
-        if domain not in self.domains:
-            raise ExtensionError('domain %s not yet registered' % domain)
-        self.domains[domain].roles[name] = role
-
-    def add_index_to_domain(self, domain, name, localname, shortname, func):
-        if domain not in self.domains:
-            raise ExtensionError('domain %s not yet registered' % domain)
-        self.domains[domain].indices.append((name, localname, shortname))
-        setattr(self.domains[domain], 'get_%s_index' % name, func)
-
-    def add_object_type(self, directivename, rolename, indextemplate='',
-                        parse_node=None, ref_nodeclass=None, objname=''):
-        StandardDomain.object_types[directivename] = \
-            ObjType(objname or directivename, rolename)
-        # create a subclass of GenericObject as the new directive
-        new_directive = type(directivename, (GenericObject, object),
-                             {'indextemplate': indextemplate,
-                              'parse_node': staticmethod(parse_node)})
-        StandardDomain.directives[directivename] = new_directive
-        # XXX support more options?
-        StandardDomain.roles[rolename] = XRefRole(innernodeclass=ref_nodeclass)
-
-    # backwards compatible alias
-    add_description_unit = add_object_type
-
-    def add_crossref_type(self, directivename, rolename, indextemplate='',
-                          ref_nodeclass=None, objname=''):
-        StandardDomain.object_types[directivename] = \
-            ObjType(objname or directivename, rolename)
-        # create a subclass of Target as the new directive
-        new_directive = type(directivename, (Target, object),
-                             {'indextemplate': indextemplate})
-        StandardDomain.directives[directivename] = new_directive
-        # XXX support more options?
-        StandardDomain.roles[rolename] = XRefRole(innernodeclass=ref_nodeclass)
-
-    def add_transform(self, transform):
-        SphinxStandaloneReader.transforms.append(transform)
-
-    def add_javascript(self, filename):
-        from sphinx.builders.html import StandaloneHTMLBuilder
-        if '://' in filename:
-            StandaloneHTMLBuilder.script_files.append(filename)
-        else:
-            StandaloneHTMLBuilder.script_files.append(
-                posixpath.join('_static', filename))
-
-    def add_stylesheet(self, filename):
-        from sphinx.builders.html import StandaloneHTMLBuilder
-        StandaloneHTMLBuilder.css_files.append(
-            posixpath.join('_static', filename))
-
-    def add_lexer(self, alias, lexer):
-        from sphinx.highlighting import lexers
-        if lexers is None:
-            return
-        lexers[alias] = lexer
-
-    def add_autodocumenter(self, cls):
-        from sphinx.ext import autodoc
-        autodoc.add_documenter(cls)
-        self.add_directive('auto' + cls.objtype, autodoc.AutoDirective)
-
-    def add_autodoc_attrgetter(self, type, getter):
-        from sphinx.ext import autodoc
-        autodoc.AutoDirective._special_attrgetters[type] = getter
-
-
-class TemplateBridge(object):
-    """
-    This class defines the interface for a "template bridge", that is, a class
-    that renders templates given a template name and a context.
-    """
-
-    def init(self, builder, theme=None, dirs=None):
-        """Called by the builder to initialize the template system.
-
-        *builder* is the builder object; you'll probably want to look at the
-        value of ``builder.config.templates_path``.
-
-        *theme* is a :class:`sphinx.theming.Theme` object or None; in the latter
-        case, *dirs* can be list of fixed directories to look for templates.
-        """
-        raise NotImplementedError('must be implemented in subclasses')
-
-    def newest_template_mtime(self):
-        """Called by the builder to determine if output files are outdated
-        because of template changes.  Return the mtime of the newest template
-        file that was changed.  The default implementation returns ``0``.
-        """
-        return 0
-
-    def render(self, template, context):
-        """Called by the builder to render a template given as a filename with
-        a specified context (a Python dictionary).
-        """
-        raise NotImplementedError('must be implemented in subclasses')
-
-    def render_string(self, template, context):
-        """Called by the builder to render a template given as a string with a
-        specified context (a Python dictionary).
-        """
-        raise NotImplementedError('must be implemented in subclasses')

File sphinx/builders/__init__.py

-# -*- coding: utf-8 -*-
-"""
-    sphinx.builders
-    ~~~~~~~~~~~~~~~
-
-    Builder superclass for all builders.
-
-    :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-import os
-from os import path
-
-from docutils import nodes
-
-from sphinx.util.osutil import SEP, relative_uri
-from sphinx.util.console import bold, purple, darkgreen, term_width_line
-
-# side effect: registers roles and directives
-from sphinx import roles
-from sphinx import directives
-
-
-class Builder(object):
-    """
-    Builds target formats from the reST sources.
-    """
-
-    # builder's name, for the -b command line options
-    name = ''
-    # builder's output format, or '' if no document output is produced
-    format = ''
-
-    def __init__(self, app):
-        self.env = app.env
-        self.srcdir = app.srcdir
-        self.confdir = app.confdir
-        self.outdir = app.outdir
-        self.doctreedir = app.doctreedir
-        if not path.isdir(self.doctreedir):
-            os.makedirs(self.doctreedir)
-
-        self.app = app
-        self.warn = app.warn
-        self.info = app.info
-        self.config = app.config
-        self.tags = app.tags
-        self.tags.add(self.format)
-
-        # images that need to be copied over (source -> dest)
-        self.images = {}
-
-        self.init()
-
-    # helper methods
-    def init(self):
-        """Load necessary templates and perform initialization.  The default
-        implementation does nothing.
-        """
-        pass
-
-    def create_template_bridge(self):
-        """Return the template bridge configured."""
-        if self.config.template_bridge:
-            self.templates = self.app.import_object(
-                self.config.template_bridge, 'template_bridge setting')()
-        else:
-            from sphinx.jinja2glue import BuiltinTemplateLoader
-            self.templates = BuiltinTemplateLoader()
-
-    def get_target_uri(self, docname, typ=None):
-        """Return the target URI for a document name.
-
-        *typ* can be used to qualify the link characteristic for individual
-        builders.
-        """
-        raise NotImplementedError
-
-    def get_relative_uri(self, from_, to, typ=None):
-        """Return a relative URI between two source filenames.
-
-        May raise environment.NoUri if there's no way to return a sensible URI.
-        """
-        return relative_uri(self.get_target_uri(from_),
-                            self.get_target_uri(to, typ))
-
-    def get_outdated_docs(self):
-        """Return an iterable of output files that are outdated, or a string
-        describing what an update build will build.
-
-        If the builder does not output individual files corresponding to
-        source files, return a string here.  If it does, return an iterable
-        of those files that need to be written.
-        """
-        raise NotImplementedError
-
-    def old_status_iterator(self, iterable, summary, colorfunc=darkgreen):
-        l = 0
-        for item in iterable:
-            if l == 0:
-                self.info(bold(summary), nonl=1)
-                l = 1
-            self.info(colorfunc(item) + ' ', nonl=1)
-            yield item
-        if l == 1:
-            self.info()
-
-    # new version with progress info
-    def status_iterator(self, iterable, summary, colorfunc=darkgreen, length=0):
-        if length == 0:
-            for item in self.old_status_iterator(iterable, summary, colorfunc):
-                yield item
-            return
-        l = 0
-        summary = bold(summary)
-        for item in iterable:
-            l += 1
-            self.info(term_width_line('%s[%3d%%] %s' %
-                                      (summary, 100*l/length,
-                                       colorfunc(item))), nonl=1)
-            yield item
-        if l > 0:
-            self.info()
-
-    supported_image_types = []
-
-    def post_process_images(self, doctree):
-        """Pick the best candidate for all image URIs."""
-        for node in doctree.traverse(nodes.image):
-            if '?' in node['candidates']:
-                # don't rewrite nonlocal image URIs
-                continue
-            if '*' not in node['candidates']:
-                for imgtype in self.supported_image_types:
-                    candidate = node['candidates'].get(imgtype, None)
-                    if candidate:
-                        break
-                else:
-                    self.warn(
-                        'no matching candidate for image URI %r' % node['uri'],
-                        '%s:%s' % (node.source, getattr(node, 'line', '')))
-                    continue
-                node['uri'] = candidate
-            else:
-                candidate = node['uri']
-            if candidate not in self.env.images:
-                # non-existing URI; let it alone
-                continue
-            self.images[candidate] = self.env.images[candidate][1]
-
-    # build methods
-
-    def build_all(self):
-        """Build all source files."""
-        self.build(None, summary='all source files', method='all')
-
-    def build_specific(self, filenames):
-        """Only rebuild as much as needed for changes in the *filenames*."""
-        # bring the filenames to the canonical format, that is,
-        # relative to the source directory and without source_suffix.
-        dirlen = len(self.srcdir) + 1
-        to_write = []
-        suffix = self.config.source_suffix
-        for filename in filenames:
-            filename = path.normpath(path.abspath(filename))
-            if not filename.startswith(self.srcdir):
-                self.warn('file %r given on command line is not under the '
-                          'source directory, ignoring' % filename)
-                continue
-            if not (path.isfile(filename) or path.isfile(filename + suffix)):
-                self.warn('file %r given on command line does not exist, '
-                          'ignoring' % filename)
-                continue
-            filename = filename[dirlen:]
-            if filename.endswith(suffix):
-                filename = filename[:-len(suffix)]
-            filename = filename.replace(path.sep, SEP)
-            to_write.append(filename)
-        self.build(to_write, method='specific',
-                   summary='%d source files given on command '
-                   'line' % len(to_write))
-
-    def build_update(self):
-        """Only rebuild what was changed or added since last build."""
-        to_build = self.get_outdated_docs()
-        if isinstance(to_build, str):
-            self.build(['__all__'], to_build)
-        else:
-            to_build = list(to_build)
-            self.build(to_build,
-                       summary='targets for %d source files that are '
-                       'out of date' % len(to_build))
-
-    def build(self, docnames, summary=None, method='update'):
-        """Main build method.
-
-        First updates the environment, and then calls :meth:`write`.
-        """
-        if summary:
-            self.info(bold('building [%s]: ' % self.name), nonl=1)
-            self.info(summary)
-
-        updated_docnames = set()
-        # while reading, collect all warnings from docutils
-        warnings = []
-        self.env.set_warnfunc(lambda *args: warnings.append(args))
-        self.info(bold('updating environment: '), nonl=1)
-        msg, length, iterator = self.env.update(self.config, self.srcdir,
-                                                self.doctreedir, self.app)
-        self.info(msg)
-        for docname in self.status_iterator(iterator, 'reading sources... ',
-                                            purple, length):
-            updated_docnames.add(docname)
-            # nothing further to do, the environment has already
-            # done the reading
-        for warning in warnings:
-            self.warn(*warning)
-        self.env.set_warnfunc(self.warn)
-
-        doccount = len(updated_docnames)
-        self.info(bold('looking for now-outdated files... '), nonl=1)
-        for docname in self.env.check_dependents(updated_docnames):
-            updated_docnames.add(docname)
-        outdated = len(updated_docnames) - doccount
-        if outdated:
-            self.info('%d found' % outdated)
-        else:
-            self.info('none found')
-
-        if updated_docnames:
-            # save the environment
-            from sphinx.application import ENV_PICKLE_FILENAME
-            self.info(bold('pickling environment... '), nonl=True)
-            self.env.topickle(path.join(self.doctreedir, ENV_PICKLE_FILENAME))
-            self.info('done')
-
-            # global actions
-            self.info(bold('checking consistency... '), nonl=True)
-            self.env.check_consistency()
-            self.info('done')
-        else:
-            if method == 'update' and not docnames:
-                self.info(bold('no targets are out of date.'))
-                return
-
-        # another indirection to support builders that don't build
-        # files individually
-        self.write(docnames, list(updated_docnames), method)
-
-        # finish (write static files etc.)
-        self.finish()
-        status = (self.app.statuscode == 0 and 'succeeded'
-                                           or 'finished with problems')
-        if self.app._warncount:
-            self.info(bold('build %s, %s warning%s.' %
-                           (status, self.app._warncount,
-                            self.app._warncount != 1 and 's' or '')))
-        else:
-            self.info(bold('build %s.' % status))
-
-    def write(self, build_docnames, updated_docnames, method='update'):
-        if build_docnames is None or build_docnames == ['__all__']:
-            # build_all
-            build_docnames = self.env.found_docs
-        if method == 'update':
-            # build updated ones as well
-            docnames = set(build_docnames) | set(updated_docnames)
-        else:
-            docnames = set(build_docnames)
-
-        # add all toctree-containing files that may have changed
-        for docname in list(docnames):
-            for tocdocname in self.env.files_to_rebuild.get(docname, []):
-                docnames.add(tocdocname)
-        docnames.add(self.config.master_doc)
-
-        self.info(bold('preparing documents... '), nonl=True)
-        self.prepare_writing(docnames)
-        self.info('done')
-
-        # write target files
-        warnings = []
-        self.env.set_warnfunc(lambda *args: warnings.append(args))
-        for docname in self.status_iterator(
-            sorted(docnames), 'writing output... ', darkgreen, len(docnames)):
-            doctree = self.env.get_and_resolve_doctree(docname, self)
-            self.write_doc(docname, doctree)
-        for warning in warnings:
-            self.warn(*warning)
-        self.env.set_warnfunc(self.warn)
-
-    def prepare_writing(self, docnames):
-        raise NotImplementedError
-
-    def write_doc(self, docname, doctree):
-        raise NotImplementedError
-
-    def finish(self):
-        """Finish the building process.
-
-        The default implementation does nothing.
-        """
-        pass
-
-    def cleanup(self):
-        """Cleanup any resources.
-
-        The default implementation does nothing.
-        """
-        pass
-
-
-BUILTIN_BUILDERS = {
-    'html':       ('html', 'StandaloneHTMLBuilder'),
-    'dirhtml':    ('html', 'DirectoryHTMLBuilder'),
-    'singlehtml': ('html', 'SingleFileHTMLBuilder'),
-    'pickle':     ('html', 'PickleHTMLBuilder'),
-    'json':       ('html', 'JSONHTMLBuilder'),
-    'web':        ('html', 'PickleHTMLBuilder'),
-    'htmlhelp':   ('htmlhelp', 'HTMLHelpBuilder'),
-    'devhelp':    ('devhelp', 'DevhelpBuilder'),
-    'qthelp':     ('qthelp', 'QtHelpBuilder'),
-    'epub':       ('epub', 'EpubBuilder'),
-    'latex':      ('latex', 'LaTeXBuilder'),
-    'text':       ('text', 'TextBuilder'),
-    'man':        ('manpage', 'ManualPageBuilder'),
-    'texinfo':    ('texinfo', 'TexinfoBuilder'),
-    'changes':    ('changes', 'ChangesBuilder'),
-    'linkcheck':  ('linkcheck', 'CheckExternalLinksBuilder'),
-    'websupport': ('websupport', 'WebSupportBuilder'),
-    'gettext':    ('intl', 'MessageCatalogBuilder'),
-}

File sphinx/builders/changes.py

-# -*- coding: utf-8 -*-
-"""
-    sphinx.builders.changes
-    ~~~~~~~~~~~~~~~~~~~~~~~
-
-    Changelog builder.
-
-    :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-import codecs
-from os import path
-from cgi import escape
-
-from sphinx import package_dir
-from sphinx.util import copy_static_entry
-from sphinx.locale import _
-from sphinx.theming import Theme
-from sphinx.builders import Builder
-from sphinx.util.osutil import ensuredir, os_path
-from sphinx.util.console import bold
-
-
-class ChangesBuilder(Builder):
-    """
-    Write a summary with all versionadded/changed directives.
-    """
-    name = 'changes'
-
-    def init(self):
-        self.create_template_bridge()
-        Theme.init_themes(self.confdir, self.config.html_theme_path,
-                          warn=self.warn)
-        self.theme = Theme('default')
-        self.templates.init(self, self.theme)
-
-    def get_outdated_docs(self):
-        return self.outdir
-
-    typemap = {
-        'versionadded': 'added',
-        'versionchanged': 'changed',
-        'deprecated': 'deprecated',
-    }
-
-    def write(self, *ignored):
-        version = self.config.version
-        libchanges = {}
-        apichanges = []
-        otherchanges = {}
-        if version not in self.env.versionchanges:
-            self.info(bold('no changes in version %s.' % version))
-            return
-        self.info(bold('writing summary file...'))
-        for type, docname, lineno, module, descname, content in \
-                self.env.versionchanges[version]:
-            if isinstance(descname, tuple):
-                descname = descname[0]
-            ttext = self.typemap[type]
-            context = content.replace('\n', ' ')
-            if descname and docname.startswith('c-api'):
-                if not descname:
-                    continue
-                if context:
-                    entry = '<b>%s</b>: <i>%s:</i> %s' % (descname, ttext,
-                                                          context)
-                else:
-                    entry = '<b>%s</b>: <i>%s</i>.' % (descname, ttext)
-                apichanges.append((entry, docname, lineno))
-            elif descname or module:
-                if not module:
-                    module = _('Builtins')
-                if not descname:
-                    descname = _('Module level')
-                if context:
-                    entry = '<b>%s</b>: <i>%s:</i> %s' % (descname, ttext,
-                                                          context)
-                else:
-                    entry = '<b>%s</b>: <i>%s</i>.' % (descname, ttext)
-                libchanges.setdefault(module, []).append((entry, docname,
-                                                          lineno))
-            else:
-                if not context:
-                    continue
-                entry = '<i>%s:</i> %s' % (ttext.capitalize(), context)
-                title = self.env.titles[docname].astext()
-                otherchanges.setdefault((docname, title), []).append(
-                    (entry, docname, lineno))
-
-        ctx = {
-            'project': self.config.project,
-            'version': version,
-            'docstitle': self.config.html_title,
-            'shorttitle': self.config.html_short_title,
-            'libchanges': sorted(libchanges.iteritems()),
-            'apichanges': sorted(apichanges),
-            'otherchanges': sorted(otherchanges.iteritems()),
-            'show_copyright': self.config.html_show_copyright,
-            'show_sphinx': self.config.html_show_sphinx,
-        }
-        f = codecs.open(path.join(self.outdir, 'index.html'), 'w', 'utf8')
-        try:
-            f.write(self.templates.render('changes/frameset.html', ctx))
-        finally:
-            f.close()
-        f = codecs.open(path.join(self.outdir, 'changes.html'), 'w', 'utf8')
-        try:
-            f.write(self.templates.render('changes/versionchanges.html', ctx))
-        finally:
-            f.close()
-
-        hltext = ['.. versionadded:: %s' % version,
-                  '.. versionchanged:: %s' % version,
-                  '.. deprecated:: %s' % version]
-
-        def hl(no, line):
-            line = '<a name="L%s"> </a>' % no + escape(line)
-            for x in hltext:
-                if x in line:
-                    line = '<span class="hl">%s</span>' % line
-                    break
-            return line
-
-        self.info(bold('copying source files...'))
-        for docname in self.env.all_docs:
-            f = codecs.open(self.env.doc2path(docname), 'r', 'latin1')
-            lines = f.readlines()
-            targetfn = path.join(self.outdir, 'rst', os_path(docname)) + '.html'
-            ensuredir(path.dirname(targetfn))
-            f = codecs.open(targetfn, 'w', 'latin1')
-            try:
-                text = ''.join(hl(i+1, line) for (i, line) in enumerate(lines))
-                ctx = {
-                    'filename': self.env.doc2path(docname, None),
-                    'text': text
-                }
-                f.write(self.templates.render('changes/rstsource.html', ctx))
-            finally:
-                f.close()
-        themectx = dict(('theme_' + key, val) for (key, val) in
-                        self.theme.get_options({}).iteritems())
-        copy_static_entry(path.join(package_dir, 'themes', 'default',
-                                    'static', 'default.css_t'),
-                          self.outdir, self, themectx)
-        copy_static_entry(path.join(package_dir, 'themes', 'basic',
-                                    'static', 'basic.css'),
-                          self.outdir, self)
-
-    def hl(self, text, version):
-        text = escape(text)
-        for directive in ['versionchanged', 'versionadded', 'deprecated']:
-            text = text.replace('.. %s:: %s' % (directive, version),
-                                '<b>.. %s:: %s</b>' % (directive, version))
-        return text
-
-    def finish(self):
-        pass

File sphinx/builders/devhelp.py

-# -*- coding: utf-8 -*-
-"""
-    sphinx.builders.devhelp
-    ~~~~~~~~~~~~~~~~~~~~~~~
-
-    Build HTML documentation and Devhelp_ support files.
-
-    .. _Devhelp: http://live.gnome.org/devhelp
-
-    :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-import re
-from os import path
-
-from docutils import nodes
-
-from sphinx import addnodes
-from sphinx.builders.html import StandaloneHTMLBuilder
-
-try:
-    import xml.etree.ElementTree as etree
-except ImportError:
-    try:
-        import lxml.etree as etree
-    except ImportError:
-        try:
-            import elementtree.ElementTree as etree
-        except ImportError:
-            import cElementTree as etree
-
-try:
-    import gzip
-    def comp_open(filename, mode='rb'):
-        return gzip.open(filename + '.gz', mode)
-except ImportError:
-    def comp_open(filename, mode='rb'):
-        return open(filename, mode)
-
-
-class DevhelpBuilder(StandaloneHTMLBuilder):
-    """
-    Builder that also outputs GNOME Devhelp file.
-    """
-    name = 'devhelp'
-
-    # don't copy the reST source
-    copysource = False
-    supported_image_types = ['image/png', 'image/gif', 'image/jpeg']
-
-    # don't add links
-    add_permalinks = False
-    # don't add sidebar etc.
-    embedded = True
-
-    def init(self):
-        StandaloneHTMLBuilder.init(self)
-        self.out_suffix = '.html'
-
-    def handle_finish(self):
-        self.build_devhelp(self.outdir, self.config.devhelp_basename)
-
-    def build_devhelp(self, outdir, outname):
-        self.info('dumping devhelp index...')
-
-        # Basic info
-        root = etree.Element('book',
-                             title=self.config.html_title,
-                             name=self.config.project,
-                             link="index.html",
-                             version=self.config.version)
-        tree = etree.ElementTree(root)
-
-        # TOC
-        chapters = etree.SubElement(root, 'chapters')
-
-        tocdoc = self.env.get_and_resolve_doctree(
-            self.config.master_doc, self, prune_toctrees=False)
-
-        def write_toc(node, parent):
-            if isinstance(node, addnodes.compact_paragraph) or \
-                   isinstance(node, nodes.bullet_list):
-                for subnode in node:
-                    write_toc(subnode, parent)
-            elif isinstance(node, nodes.list_item):
-                item = etree.SubElement(parent, 'sub')
-                for subnode in node:
-                    write_toc(subnode, item)
-            elif isinstance(node, nodes.reference):
-                parent.attrib['link'] = node['refuri']
-                parent.attrib['name'] = node.astext().encode('utf-8')
-
-        def istoctree(node):
-            return isinstance(node, addnodes.compact_paragraph) and \
-                   node.has_key('toctree')
-
-        for node in tocdoc.traverse(istoctree):
-            write_toc(node, chapters)
-
-        # Index
-        functions = etree.SubElement(root, 'functions')
-        index = self.env.create_index(self)
-
-        def write_index(title, refs, subitems):
-            if len(refs) == 0:
-                pass
-            elif len(refs) == 1:
-                etree.SubElement(functions, 'function',
-                                 name=title, link=refs[0])
-            else:
-                for i, ref in enumerate(refs):
-                    etree.SubElement(functions, 'function',
-                                     name="[%d] %s" % (i, title),
-                                     link=ref)
-
-            if subitems:
-                parent_title = re.sub(r'\s*\(.*\)\s*$', '', title)
-                for subitem in subitems:
-                    write_index("%s %s" % (parent_title, subitem[0]),
-                                subitem[1], [])
-
-        for (key, group) in index:
-            for title, (refs, subitems) in group:
-                write_index(title, refs, subitems)
-
-        # Dump the XML file
-        f = comp_open(path.join(outdir, outname + '.devhelp'), 'w')
-        try:
-            tree.write(f)
-        finally:
-            f.close()

File sphinx/builders/epub.py

-# -*- coding: utf-8 -*-
-"""
-    sphinx.builders.epub
-    ~~~~~~~~~~~~~~~~~~~~
-
-    Build epub files.
-    Originally derived from qthelp.py.
-
-    :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-import os
-import re
-import sys
-import time
-import codecs
-import zipfile
-from os import path
-
-from docutils import nodes
-
-from sphinx import addnodes
-from sphinx.builders.html import StandaloneHTMLBuilder
-from sphinx.util.osutil import EEXIST
-from sphinx.util.smartypants import sphinx_smarty_pants as ssp
-
-
-# (Fragment) templates from which the metainfo files content.opf, toc.ncx,
-# mimetype, and META-INF/container.xml are created.
-# This template section also defines strings that are embedded in the html
-# output but that may be customized by (re-)setting module attributes,
-# e.g. from conf.py.
-
-_mimetype_template = 'application/epub+zip' # no EOL!
-
-_container_template = u'''\
-<?xml version="1.0" encoding="UTF-8"?>
-<container version="1.0"
-      xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
-  <rootfiles>
-    <rootfile full-path="content.opf"
-        media-type="application/oebps-package+xml"/>
-  </rootfiles>
-</container>
-'''
-
-_toc_template = u'''\
-<?xml version="1.0"?>
-<ncx version="2005-1" xmlns="http://www.daisy.org/z3986/2005/ncx/">
-  <head>
-    <meta name="dtb:uid" content="%(uid)s"/>
-    <meta name="dtb:depth" content="%(level)d"/>
-    <meta name="dtb:totalPageCount" content="0"/>
-    <meta name="dtb:maxPageNumber" content="0"/>
-  </head>
-  <docTitle>
-    <text>%(title)s</text>
-  </docTitle>
-  <navMap>
-%(navpoints)s
-  </navMap>
-</ncx>
-'''
-
-_navpoint_template = u'''\
-%(indent)s  <navPoint id="%(navpoint)s" playOrder="%(playorder)d">
-%(indent)s    <navLabel>
-%(indent)s      <text>%(text)s</text>
-%(indent)s    </navLabel>
-%(indent)s    <content src="%(refuri)s" />
-%(indent)s  </navPoint>'''
-
-_navpoint_indent = '  '
-_navPoint_template = 'navPoint%d'
-
-_content_template = u'''\
-<?xml version="1.0" encoding="UTF-8"?>
-<package xmlns="http://www.idpf.org/2007/opf" version="2.0"
-      unique-identifier="%(uid)s">
-  <metadata xmlns:opf="http://www.idpf.org/2007/opf"
-        xmlns:dc="http://purl.org/dc/elements/1.1/">
-    <dc:language>%(lang)s</dc:language>
-    <dc:title>%(title)s</dc:title>
-    <dc:creator opf:role="aut">%(author)s</dc:creator>
-    <dc:publisher>%(publisher)s</dc:publisher>
-    <dc:rights>%(copyright)s</dc:rights>
-    <dc:identifier id="%(uid)s" opf:scheme="%(scheme)s">%(id)s</dc:identifier>
-    <dc:date>%(date)s</dc:date>
-  </metadata>
-  <manifest>
-    <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml" />
-%(files)s
-  </manifest>
-  <spine toc="ncx">
-%(spine)s
-  </spine>
-</package>
-'''
-
-_cover_template = u'''\
-    <meta name="cover" content="%(cover)s"/>
-'''
-
-_coverpage_name = u'epub-cover.html'
-
-_file_template = u'''\
-    <item id="%(id)s"
-          href="%(href)s"
-          media-type="%(media_type)s" />'''
-
-_spine_template = u'''\
-    <itemref idref="%(idref)s" />'''
-
-_toctree_template = u'toctree-l%d'
-
-_link_target_template = u' [%(uri)s]'
-
-_css_link_target_class = u'link-target'
-
-_media_types = {
-    '.html': 'application/xhtml+xml',
-    '.css': 'text/css',
-    '.png': 'image/png',
-    '.gif': 'image/gif',
-    '.svg': 'image/svg+xml',
-    '.jpg': 'image/jpeg',
-    '.jpeg': 'image/jpeg',
-    '.otf': 'application/x-font-otf',
-    '.ttf': 'application/x-font-ttf',
-}
-
-# Regular expression to match colons only in local fragment identifiers.
-# If the URI contains a colon before the #,
-# it is an external link that should not change.
-_refuri_re = re.compile("([^#:]*#)(.*)")
-
-
-# The epub publisher
-
-class EpubBuilder(StandaloneHTMLBuilder):
-    """
-    Builder that outputs epub files.
-
-    It creates the metainfo files container.opf, toc.ncx, mimetype, and
-    META-INF/container.xml.  Afterwards, all necessary files are zipped to an
-    epub file.
-    """
-    name = 'epub'
-
-    # don't copy the reST source
-    copysource = False
-    supported_image_types = ['image/svg+xml', 'image/png', 'image/gif',
-                             'image/jpeg']
-
-    # don't add links
-    add_permalinks = False
-    # don't add sidebar etc.
-    embedded = True
-
-    def init(self):
-        StandaloneHTMLBuilder.init(self)
-        # the output files for epub must be .html only
-        self.out_suffix = '.html'
-        self.playorder = 0
-
-    def get_theme_config(self):
-        return self.config.epub_theme, {}
-
-    # generic support functions
-    def make_id(self, name):
-        """Replace all characters not allowed for (X)HTML ids."""
-        return name.replace('/', '_').replace(' ', '')
-
-    def esc(self, name):
-        """Replace all characters not allowed in text an attribute values."""
-        # Like cgi.escape, but also replace apostrophe
-        name = name.replace('&', '&amp;')
-        name = name.replace('<', '&lt;')
-        name = name.replace('>', '&gt;')
-        name = name.replace('"', '&quot;')
-        name = name.replace('\'', '&apos;')
-        return name
-
-    def get_refnodes(self, doctree, result):
-        """Collect section titles, their depth in the toc and the refuri."""
-        # XXX: is there a better way than checking the attribute
-        # toctree-l[1-8] on the parent node?
-        if isinstance(doctree, nodes.reference) and doctree.has_key('refuri'):
-            refuri = doctree['refuri']
-            if refuri.startswith('http://') or refuri.startswith('https://') \
-                or refuri.startswith('irc:') or refuri.startswith('mailto:'):
-                return result
-            classes = doctree.parent.attributes['classes']
-            for level in range(8, 0, -1): # or range(1, 8)?