diff --git a/AUTHORS b/AUTHORS index d773b8f17..aef4410be 100644 --- a/AUTHORS +++ b/AUTHORS @@ -81,6 +81,7 @@ Other contributors, listed alphabetically, are: * Hong Xu -- svg support in imgmath extension and various bug fixes * Stephen Finucane -- setup command improvements and documentation * Daniel Pizetta -- inheritance diagram improvements +* KINEBUCHI Tomohiko -- typing Sphinx as well as docutils Many thanks for all contributions! diff --git a/CHANGES b/CHANGES index 664b6e38f..851ac61ad 100644 --- a/CHANGES +++ b/CHANGES @@ -26,11 +26,14 @@ Incompatible changes * LaTeX: Move message resources to ``sphinxmessage.sty`` * LaTeX: Stop using ``\captions`` macro for some labels * LaTeX: for ``'xelatex'`` and ``'lualatex'``, use the ``FreeFont`` OpenType - fonts as default choice (refs #5645) + fonts as default choice (refs: #5645) * LaTeX: Greek letters in text are not escaped to math mode mark-up, and they will use the text font not the math font. The ``LGR`` font encoding must be added to the ``'fontenc'`` key of :confval:`latex_elements` for this to work (only if it is needed by the document, of course). +* LaTeX: setting the :confval:`language` to ``'en'`` triggered ``Sonny`` option + of ``fncychap``, now it is ``Bjarne`` to match case of no language specified. + (refs: #5772) * #5770: doctest: Follow :confval:`highlight_language` on highlighting doctest block. As a result, they are highlighted as python3 by default. @@ -48,6 +51,7 @@ Deprecated is_meta_keywords()`` * The ``suffix`` argument of ``env.doc2path()`` is deprecated. * The string style ``base`` argument of ``env.doc2path()`` is deprecated. +* ``sphinx.addnodes.abbreviation`` * ``sphinx.application.Sphinx._setting_up_extension`` * ``sphinx.config.check_unicode()`` * ``sphinx.ext.autodoc.importer._MockImporter`` @@ -60,7 +64,8 @@ Deprecated * ``sphinx.testing.util.remove_unicode_literal()`` * ``sphinx.util.attrdict`` * ``sphinx.util.force_decode()`` -* ``sphinx.util.get_matching_docs()`` is deprecated +* ``sphinx.util.get_matching_docs()`` +* ``sphinx.util.inspect.Parameter`` * ``sphinx.util.osutil.walk()`` * ``sphinx.util.PeekableIterator`` * ``sphinx.util.pycompat.u`` @@ -103,6 +108,8 @@ Bugs fixed language and ``'xelatex'`` or ``'lualatex'`` as :confval:`latex_engine` (refs: #5251) * #5248: LaTeX: Greek letters in section titles disappear from PDF bookmarks +* #5772: LaTeX: should the Bjarne style of fncychap be used for English also + if passed as language option? Testing -------- diff --git a/doc/extdev/index.rst b/doc/extdev/index.rst index f15f92790..003666217 100644 --- a/doc/extdev/index.rst +++ b/doc/extdev/index.rst @@ -147,6 +147,11 @@ The following is a list of deprecated interfaces. - 4.0 - ``os.path.join()`` + * - ``sphinx.addnodes.abbreviation`` + - 2.0 + - 4.0 + - ``docutils.nodes.abbreviation`` + * - ``sphinx.config.check_unicode()`` - 2.0 - 4.0 @@ -197,6 +202,11 @@ The following is a list of deprecated interfaces. - 4.0 - ``sphinx.util.get_matching_files()`` + * - ``sphinx.util.inspect.Parameter`` + - 2.0 + - 3.0 + - N/A + * - ``sphinx.util.osutil.walk()`` - 2.0 - 4.0 diff --git a/doc/usage/configuration.rst b/doc/usage/configuration.rst index e175c6f44..b20219fcd 100644 --- a/doc/usage/configuration.rst +++ b/doc/usage/configuration.rst @@ -2094,6 +2094,8 @@ information. "fncychap" styles you can try are "Lenny", "Glenn", "Conny", "Rejne" and "Bjornstrup". You can also set this to ``''`` to disable fncychap. + The default is ``''`` for Japanese documents. + ``'preamble'`` Additional preamble content, default empty. See :doc:`/latex`. diff --git a/sphinx/__init__.py b/sphinx/__init__.py index eb05bcd83..ac5a91a97 100644 --- a/sphinx/__init__.py +++ b/sphinx/__init__.py @@ -22,7 +22,6 @@ from .deprecation import RemovedInNextVersionWarning if False: # For type annotation - # note: Don't use typing.TYPE_CHECK here (for py27 and py34). from typing import Any # NOQA diff --git a/sphinx/addnodes.py b/sphinx/addnodes.py index d907f617a..7c8f2c9d0 100644 --- a/sphinx/addnodes.py +++ b/sphinx/addnodes.py @@ -13,13 +13,12 @@ import warnings from docutils import nodes -from sphinx.deprecation import RemovedInSphinx30Warning +from sphinx.deprecation import RemovedInSphinx30Warning, RemovedInSphinx40Warning if False: # For type annotation from typing import Any, Dict, List, Sequence # NOQA from sphinx.application import Sphinx # NOQA - from sphinx.util.typing import unicode # NOQA class translatable(nodes.Node): @@ -42,12 +41,12 @@ class translatable(nodes.Node): raise NotImplementedError def apply_translated_message(self, original_message, translated_message): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Apply translated message.""" raise NotImplementedError def extract_original_messages(self): - # type: () -> Sequence[unicode] + # type: () -> Sequence[str] """Extract translation messages. :returns: list of extracted messages or messages generator @@ -69,12 +68,12 @@ class toctree(nodes.General, nodes.Element, translatable): self['rawcaption'] = self['caption'] def apply_translated_message(self, original_message, translated_message): - # type: (unicode, unicode) -> None + # type: (str, str) -> None if self.get('rawcaption') == original_message: self['caption'] = translated_message def extract_original_messages(self): - # type: () -> List[unicode] + # type: () -> List[str] if 'rawcaption' in self: return [self['rawcaption']] else: @@ -128,7 +127,7 @@ class desc_type(nodes.Part, nodes.Inline, nodes.FixedTextElement): class desc_returns(desc_type): """Node for a "returns" annotation (a la -> in Python).""" def astext(self): - # type: () -> unicode + # type: () -> str return ' -> ' + super(desc_returns, self).astext() @@ -150,7 +149,7 @@ class desc_optional(nodes.Part, nodes.Inline, nodes.FixedTextElement): child_text_separator = ', ' def astext(self): - # type: () -> unicode + # type: () -> str return '[' + super(desc_optional, self).astext() + ']' @@ -344,8 +343,18 @@ class literal_strong(nodes.strong, not_smartquotable): """ -class abbreviation(nodes.Inline, nodes.TextElement): - """Node for abbreviations with explanations.""" +class abbreviation(nodes.abbreviation): + """Node for abbreviations with explanations. + + .. deprecated:: 2.0 + """ + + def __init__(self, rawsource='', text='', *children, **attributes): + # type: (str, str, *nodes.Node, **Any) -> None + warnings.warn("abbrevition node for Sphinx was replaced by docutils'.", + RemovedInSphinx40Warning, stacklevel=2) + + super(abbreviation, self).__init__(rawsource, text, *children, **attributes) class manpage(nodes.Inline, nodes.FixedTextElement): @@ -353,7 +362,7 @@ class manpage(nodes.Inline, nodes.FixedTextElement): def setup(app): - # type: (Sphinx) -> Dict[unicode, Any] + # type: (Sphinx) -> Dict[str, Any] app.add_node(toctree) app.add_node(desc) app.add_node(desc_signature) @@ -389,7 +398,6 @@ def setup(app): app.add_node(download_reference) app.add_node(literal_emphasis) app.add_node(literal_strong) - app.add_node(abbreviation, override=True) app.add_node(manpage) return { diff --git a/sphinx/application.py b/sphinx/application.py index 984b2b6af..5f06bfc70 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -10,7 +10,6 @@ :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ -from __future__ import print_function import os import pickle @@ -60,7 +59,7 @@ if False: from sphinx.extension import Extension # NOQA from sphinx.roles import XRefRole # NOQA from sphinx.theming import Theme # NOQA - from sphinx.util.typing import RoleFunction, TitleGetter, unicode # NOQA + from sphinx.util.typing import RoleFunction, TitleGetter # NOQA builtin_extensions = ( 'sphinx.addnodes', @@ -113,7 +112,7 @@ builtin_extensions = ( # Strictly, alabaster theme is not a builtin extension, # but it is loaded automatically to use it as default theme. 'alabaster', -) # type: Tuple[unicode, ...] +) ENV_PICKLE_FILENAME = 'environment.pickle' @@ -133,20 +132,20 @@ class Sphinx: confoverrides=None, status=sys.stdout, warning=sys.stderr, freshenv=False, warningiserror=False, tags=None, verbosity=0, parallel=0, keep_going=False): - # type: (unicode, unicode, unicode, unicode, unicode, Dict, IO, IO, bool, bool, List[unicode], int, int, bool) -> None # NOQA + # type: (str, str, str, str, str, Dict, IO, IO, bool, bool, List[str], int, int, bool) -> None # NOQA self.phase = BuildPhase.INITIALIZATION self.verbosity = verbosity - self.extensions = {} # type: Dict[unicode, Extension] + self.extensions = {} # type: Dict[str, Extension] self.builder = None # type: Builder self.env = None # type: BuildEnvironment self.project = None # type: Project self.registry = SphinxComponentRegistry() - self.html_themes = {} # type: Dict[unicode, unicode] + self.html_themes = {} # type: Dict[str, str] # validate provided directories - self.srcdir = abspath(srcdir) # type: unicode - self.outdir = abspath(outdir) # type: unicode - self.doctreedir = abspath(doctreedir) # type: unicode + self.srcdir = abspath(srcdir) + self.outdir = abspath(outdir) + self.doctreedir = abspath(doctreedir) self.confdir = confdir if self.confdir: # confdir is optional self.confdir = abspath(self.confdir) @@ -306,11 +305,11 @@ class Sphinx: self._init_env(freshenv=True) def preload_builder(self, name): - # type: (unicode) -> None + # type: (str) -> None self.registry.preload_builder(self, name) def create_builder(self, name): - # type: (unicode) -> Builder + # type: (str) -> Builder if name is None: logger.info(__('No builder selected, using default: html')) name = 'html' @@ -326,7 +325,7 @@ class Sphinx: # ---- main "build" method ------------------------------------------------- def build(self, force_all=False, filenames=None): - # type: (bool, List[unicode]) -> None + # type: (bool, List[str]) -> None self.phase = BuildPhase.READING try: if force_all: @@ -371,7 +370,7 @@ class Sphinx: # ---- general extensibility interface ------------------------------------- def setup_extension(self, extname): - # type: (unicode) -> None + # type: (str) -> None """Import and setup a Sphinx extension module. Load the extension given by the module *name*. Use this if your @@ -382,7 +381,7 @@ class Sphinx: self.registry.load_extension(self, extname) def require_sphinx(self, version): - # type: (unicode) -> None + # type: (str) -> None """Check the Sphinx version if requested. Compare *version* (which must be a ``major.minor`` version string, e.g. @@ -395,7 +394,7 @@ class Sphinx: raise VersionRequirementError(version) def import_object(self, objname, source=None): - # type: (str, unicode) -> Any + # type: (str, str) -> Any """Import an object from a ``module.name`` string. .. deprecated:: 1.8 @@ -408,7 +407,7 @@ class Sphinx: # event interface def connect(self, event, callback): - # type: (unicode, Callable) -> int + # type: (str, Callable) -> int """Register *callback* to be called when *event* is emitted. For details on available core events and the arguments of callback @@ -428,7 +427,7 @@ class Sphinx: self.events.disconnect(listener_id) def emit(self, event, *args): - # type: (unicode, Any) -> List + # type: (str, Any) -> List """Emit *event* and pass *arguments* to the callback functions. Return the return values of all callbacks as a list. Do not emit core @@ -443,7 +442,7 @@ class Sphinx: return self.events.emit(event, self, *args) def emit_firstresult(self, event, *args): - # type: (unicode, Any) -> Any + # type: (str, Any) -> Any """Emit *event* and pass *arguments* to the callback functions. Return the result of the first callback that doesn't return ``None``. @@ -468,7 +467,7 @@ class Sphinx: # TODO(stephenfin): Describe 'types' parameter def add_config_value(self, name, default, rebuild, types=()): - # type: (unicode, Any, Union[bool, unicode], Any) -> None + # type: (str, Any, Union[bool, str], Any) -> None """Register a configuration value. This is necessary for Sphinx to recognize new values and set default @@ -501,7 +500,7 @@ class Sphinx: self.config.add(name, default, rebuild, types) def add_event(self, name): - # type: (unicode) -> None + # type: (str) -> None """Register an event called *name*. This is needed to be able to emit it. @@ -510,7 +509,7 @@ class Sphinx: self.events.add(name) def set_translator(self, name, translator_class, override=False): - # type: (unicode, Type[nodes.NodeVisitor], bool) -> None + # type: (str, Type[nodes.NodeVisitor], bool) -> None """Register or override a Docutils translator class. This is used to register a custom output translator or to replace a @@ -563,7 +562,7 @@ class Sphinx: self.registry.add_translation_handlers(node, **kwds) def add_enumerable_node(self, node, figtype, title_getter=None, override=False, **kwds): - # type: (Type[nodes.Element], unicode, TitleGetter, bool, Any) -> None + # type: (Type[nodes.Element], str, TitleGetter, bool, Any) -> None """Register a Docutils node class as a numfig target. Sphinx numbers the node automatically. And then the users can refer it @@ -592,14 +591,14 @@ class Sphinx: @property def enumerable_nodes(self): - # type: () -> Dict[Type[nodes.Node], Tuple[unicode, TitleGetter]] + # type: () -> Dict[Type[nodes.Node], Tuple[str, TitleGetter]] warnings.warn('app.enumerable_nodes() is deprecated. ' 'Use app.get_domain("std").enumerable_nodes instead.', RemovedInSphinx30Warning, stacklevel=2) return self.registry.enumerable_nodes def add_directive(self, name, obj, content=None, arguments=None, override=False, **options): # NOQA - # type: (unicode, Any, bool, Tuple[int, int, bool], bool, Any) -> None + # type: (str, Any, bool, Tuple[int, int, bool], bool, Any) -> None """Register a Docutils directive. *name* must be the prospective directive name. There are two possible @@ -663,7 +662,7 @@ class Sphinx: docutils.register_directive(name, obj) def add_role(self, name, role, override=False): - # type: (unicode, Any, bool) -> None + # type: (str, Any, bool) -> None """Register a Docutils role. *name* must be the role name that occurs in the source, *role* the role @@ -681,7 +680,7 @@ class Sphinx: docutils.register_role(name, role) def add_generic_role(self, name, nodeclass, override=False): - # type: (unicode, Any, bool) -> None + # type: (str, Any, bool) -> None """Register a generic Docutils role. Register a Docutils role that does nothing but wrap its contents in the @@ -732,7 +731,7 @@ class Sphinx: def add_directive_to_domain(self, domain, name, obj, has_content=None, argument_spec=None, override=False, **option_spec): - # type: (unicode, unicode, Any, bool, Any, bool, Any) -> None + # type: (str, str, Any, bool, Any, bool, Any) -> None """Register a Docutils directive in a domain. Like :meth:`add_directive`, but the directive is added to the domain @@ -747,7 +746,7 @@ class Sphinx: **option_spec) def add_role_to_domain(self, domain, name, role, override=False): - # type: (unicode, unicode, Union[RoleFunction, XRefRole], bool) -> None + # type: (str, str, Union[RoleFunction, XRefRole], bool) -> None """Register a Docutils role in a domain. Like :meth:`add_role`, but the role is added to the domain named @@ -760,7 +759,7 @@ class Sphinx: self.registry.add_role_to_domain(domain, name, role, override=override) def add_index_to_domain(self, domain, index, override=False): - # type: (unicode, Type[Index], bool) -> None + # type: (str, Type[Index], bool) -> None """Register a custom index for a domain. Add a custom *index* class to the domain named *domain*. *index* must @@ -775,7 +774,7 @@ class Sphinx: def add_object_type(self, directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', doc_field_types=[], override=False): - # type: (unicode, unicode, unicode, Callable, Type[nodes.TextElement], unicode, List, bool) -> None # NOQA + # type: (str, str, str, Callable, Type[nodes.TextElement], str, List, bool) -> None """Register a new object type. This method is a very convenient way to add a new :term:`object` type @@ -841,7 +840,7 @@ class Sphinx: def add_crossref_type(self, directivename, rolename, indextemplate='', ref_nodeclass=None, objname='', override=False): - # type: (unicode, unicode, unicode, Type[nodes.TextElement], unicode, bool) -> None + # type: (str, str, str, Type[nodes.TextElement], str, bool) -> None """Register a new crossref object type. This method is very similar to :meth:`add_object_type` except that the @@ -920,7 +919,7 @@ class Sphinx: self.registry.add_post_transform(transform) def add_javascript(self, filename, **kwargs): - # type: (unicode, **unicode) -> None + # type: (str, **str) -> None """An alias of :meth:`add_js_file`.""" warnings.warn('The app.add_javascript() is deprecated. ' 'Please use app.add_js_file() instead.', @@ -928,7 +927,7 @@ class Sphinx: self.add_js_file(filename, **kwargs) def add_js_file(self, filename, **kwargs): - # type: (unicode, **unicode) -> None + # type: (str, **str) -> None """Register a JavaScript file to include in the HTML output. Add *filename* to the list of JavaScript files that the default HTML @@ -955,7 +954,7 @@ class Sphinx: self.builder.add_js_file(filename, **kwargs) # type: ignore def add_css_file(self, filename, **kwargs): - # type: (unicode, **unicode) -> None + # type: (str, **str) -> None """Register a stylesheet to include in the HTML output. Add *filename* to the list of CSS files that the default HTML template @@ -995,13 +994,13 @@ class Sphinx: self.builder.add_css_file(filename, **kwargs) # type: ignore def add_stylesheet(self, filename, alternate=False, title=None): - # type: (unicode, bool, unicode) -> None + # type: (str, bool, str) -> None """An alias of :meth:`add_css_file`.""" warnings.warn('The app.add_stylesheet() is deprecated. ' 'Please use app.add_css_file() instead.', RemovedInSphinx40Warning, stacklevel=2) - attributes = {} # type: Dict[unicode, unicode] + attributes = {} # type: Dict[str, str] if alternate: attributes['rel'] = 'alternate stylesheet' else: @@ -1013,7 +1012,7 @@ class Sphinx: self.add_css_file(filename, **attributes) def add_latex_package(self, packagename, options=None): - # type: (unicode, unicode) -> None + # type: (str, str) -> None r"""Register a package to include in the LaTeX source code. Add *packagename* to the list of packages that LaTeX source code will @@ -1032,7 +1031,7 @@ class Sphinx: self.registry.add_latex_package(packagename, options) def add_lexer(self, alias, lexer): - # type: (unicode, Any) -> None + # type: (str, Any) -> None """Register a new lexer for source code. Use *lexer*, which must be an instance of a Pygments lexer class, to @@ -1066,7 +1065,7 @@ class Sphinx: self.add_directive('auto' + cls.objtype, AutodocDirective) def add_autodoc_attrgetter(self, typ, getter): - # type: (Type, Callable[[Any, unicode, Any], Any]) -> None + # type: (Type, Callable[[Any, str, Any], Any]) -> None """Register a new ``getattr``-like function for the autodoc extension. Add *getter*, which must be a function with an interface compatible to @@ -1098,7 +1097,7 @@ class Sphinx: languages[cls.lang] = cls def add_source_suffix(self, suffix, filetype, override=False): - # type: (unicode, unicode, bool) -> None + # type: (str, str, bool) -> None """Register a suffix of source files. Same as :confval:`source_suffix`. The users can override this @@ -1133,7 +1132,7 @@ class Sphinx: collector().enable(self) def add_html_theme(self, name, theme_path): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Register a HTML Theme. The *name* is a name of theme, and *path* is a full path to the theme @@ -1145,7 +1144,7 @@ class Sphinx: self.html_themes[name] = theme_path def add_html_math_renderer(self, name, inline_renderers=None, block_renderers=None): - # type: (unicode, Tuple[Callable, Callable], Tuple[Callable, Callable]) -> None + # type: (str, Tuple[Callable, Callable], Tuple[Callable, Callable]) -> None """Register a math renderer for HTML. The *name* is a name of the math renderer. Both *inline_renderers* and @@ -1159,7 +1158,7 @@ class Sphinx: self.registry.add_html_math_renderer(name, inline_renderers, block_renderers) def add_message_catalog(self, catalog, locale_dir): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Register a message catalog. The *catalog* is a name of catalog, and *locale_dir* is a base path @@ -1173,7 +1172,7 @@ class Sphinx: # ---- other methods ------------------------------------------------- def is_parallel_allowed(self, typ): - # type: (unicode) -> bool + # type: (str) -> bool """Check parallel processing is allowed or not. ``typ`` is a type of processing; ``'read'`` or ``'write'``. @@ -1206,7 +1205,7 @@ class Sphinx: @property def _setting_up_extension(self): - # type: () -> List[unicode] + # type: () -> List[str] warnings.warn('app._setting_up_extension is deprecated.', RemovedInSphinx30Warning) return ['?'] @@ -1219,7 +1218,7 @@ class TemplateBridge: """ def init(self, builder, theme=None, dirs=None): - # type: (Builder, Theme, List[unicode]) -> None + # type: (Builder, Theme, List[str]) -> None """Called by the builder to initialize the template system. *builder* is the builder object; you'll probably want to look at the @@ -1239,14 +1238,14 @@ class TemplateBridge: return 0 def render(self, template, context): - # type: (unicode, Dict) -> None + # type: (str, Dict) -> None """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): - # type: (unicode, Dict) -> unicode + # type: (str, Dict) -> str """Called by the builder to render a template given as a string with a specified context (a Python dictionary). """ diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py index 94ec3b4ee..40944fcf1 100644 --- a/sphinx/builders/__init__.py +++ b/sphinx/builders/__init__.py @@ -47,7 +47,6 @@ if False: from sphinx.environment import BuildEnvironment # NOQA from sphinx.util.i18n import CatalogInfo # NOQA from sphinx.util.tags import Tags # NOQA - from sphinx.util.typing import unicode # NOQA logger = logging.getLogger(__name__) @@ -59,19 +58,19 @@ class Builder: """ #: The builder's name, for the -b command line option. - name = '' # type: unicode + name = '' #: The builder's output format, or '' if no document output is produced. - format = '' # type: unicode + format = '' #: The message emitted upon successful build completion. This can be a #: printf-style template string with the following keys: ``outdir``, #: ``project`` - epilog = '' # type: unicode + epilog = '' #: default translator class for the builder. This can be overrided by #: :py:meth:`app.set_translator()`. default_translator_class = None # type: Type[nodes.NodeVisitor] # doctree versioning method - versioning_method = 'none' # type: unicode + versioning_method = 'none' versioning_compare = False # allow parallel write_doc() calls allow_parallel = False @@ -80,7 +79,7 @@ class Builder: #: The list of MIME types of image formats supported by the builder. #: Image files are searched in the order in which they appear here. - supported_image_types = [] # type: List[unicode] + supported_image_types = [] # type: List[str] #: The builder supports remote images or not. supported_remote_images = False #: The builder supports data URIs or not. @@ -104,11 +103,11 @@ class Builder: self.tags.add("builder_%s" % self.name) # images that need to be copied over (source -> dest) - self.images = {} # type: Dict[unicode, unicode] + self.images = {} # type: Dict[str, str] # basename of images directory self.imagedir = "" # relative path to image directory from current docname (used at writing docs) - self.imgpath = "" # type: unicode + self.imgpath = "" # these get set later self.parallel_ok = False @@ -154,7 +153,7 @@ class Builder: self.templates = BuiltinTemplateLoader() def get_target_uri(self, docname, typ=None): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str """Return the target URI for a document name. *typ* can be used to qualify the link characteristic for individual @@ -163,7 +162,7 @@ class Builder: raise NotImplementedError def get_relative_uri(self, from_, to, typ=None): - # type: (unicode, unicode, unicode) -> unicode + # type: (str, str, str) -> str """Return a relative URI between two source filenames. May raise environment.NoUri if there's no way to return a sensible URI. @@ -172,7 +171,7 @@ class Builder: self.get_target_uri(to, typ)) def get_outdated_docs(self): - # type: () -> Union[unicode, Iterable[unicode]] + # type: () -> Union[str, Iterable[str]] """Return an iterable of output files that are outdated, or a string describing what an update build will build. @@ -183,7 +182,7 @@ class Builder: raise NotImplementedError def get_asset_paths(self): - # type: () -> List[unicode] + # type: () -> List[str] """Return list of paths for assets (ex. templates, CSS, etc.).""" return [] @@ -222,12 +221,12 @@ class Builder: # compile po methods def compile_catalogs(self, catalogs, message): - # type: (Set[CatalogInfo], unicode) -> None + # type: (Set[CatalogInfo], str) -> None if not self.config.gettext_auto_build: return def cat2relpath(cat): - # type: (CatalogInfo) -> unicode + # type: (CatalogInfo) -> str return relpath(cat.mo_path, self.env.srcdir).replace(path.sep, SEP) logger.info(bold(__('building [mo]: ')) + message) @@ -248,9 +247,9 @@ class Builder: self.compile_catalogs(catalogs, message) def compile_specific_catalogs(self, specified_files): - # type: (List[unicode]) -> None + # type: (List[str]) -> None def to_domain(fpath): - # type: (unicode) -> unicode + # type: (str) -> str docname = self.env.path2doc(path.abspath(fpath)) if docname: return find_catalog(docname, self.config.gettext_compact) @@ -286,13 +285,13 @@ class Builder: self.build(None, summary=__('all source files'), method='all') def build_specific(self, filenames): - # type: (List[unicode]) -> None + # type: (List[str]) -> None """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 = [] - suffixes = None # type: Tuple[unicode] + suffixes = None # type: Tuple[str] suffixes = tuple(self.config.source_suffix) # type: ignore for filename in filenames: filename = path.normpath(path.abspath(filename)) @@ -328,7 +327,7 @@ class Builder: len(to_build)) def build(self, docnames, summary=None, method='update'): - # type: (Iterable[unicode], unicode, unicode) -> None + # type: (Iterable[str], str, str) -> None """Main build method. First updates the environment, and then calls :meth:`write`. @@ -399,7 +398,7 @@ class Builder: self.finish_tasks.join() def read(self): - # type: () -> List[unicode] + # type: () -> List[str] """(Re-)read all files new or changed since last update. Store all environment docnames in the canonical format (ie using SEP as @@ -462,7 +461,7 @@ class Builder: return sorted(docnames) def _read_serial(self, docnames): - # type: (List[unicode]) -> None + # type: (List[str]) -> None for docname in status_iterator(docnames, 'reading sources... ', "purple", len(docnames), self.app.verbosity): # remove all inventory entries for that file @@ -471,14 +470,14 @@ class Builder: self.read_doc(docname) def _read_parallel(self, docnames, nproc): - # type: (List[unicode], int) -> None + # type: (List[str], int) -> None # clear all outdated docs at once for docname in docnames: self.app.emit('env-purge-doc', self.env, docname) self.env.clear_doc(docname) def read_process(docs): - # type: (List[unicode]) -> bytes + # type: (List[str]) -> bytes self.env.app = self.app for docname in docs: self.read_doc(docname) @@ -486,7 +485,7 @@ class Builder: return pickle.dumps(self.env, pickle.HIGHEST_PROTOCOL) def merge(docs, otherenv): - # type: (List[unicode], bytes) -> None + # type: (List[str], bytes) -> None env = pickle.loads(otherenv) self.env.merge_info_from(docs, env, self.app) @@ -502,7 +501,7 @@ class Builder: tasks.join() def read_doc(self, docname): - # type: (unicode) -> None + # type: (str) -> None """Parse a file and add/update inventory entries for the doctree.""" self.env.prepare_settings(docname) @@ -528,7 +527,7 @@ class Builder: self.write_doctree(docname, doctree) def write_doctree(self, docname, doctree): - # type: (unicode, nodes.document) -> None + # type: (str, nodes.document) -> None """Write the doctree to a file.""" # make it picklable doctree.reporter = None @@ -543,7 +542,7 @@ class Builder: pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) def write(self, build_docnames, updated_docnames, method='update'): - # type: (Iterable[unicode], Sequence[unicode], unicode) -> None + # type: (Iterable[str], Sequence[str], str) -> None if build_docnames is None or build_docnames == ['__all__']: # build_all build_docnames = self.env.found_docs @@ -574,7 +573,7 @@ class Builder: self._write_serial(sorted(docnames)) def _write_serial(self, docnames): - # type: (Sequence[unicode]) -> None + # type: (Sequence[str]) -> None with logging.pending_warnings(): for docname in status_iterator(docnames, __('writing output... '), "darkgreen", len(docnames), self.app.verbosity): @@ -585,9 +584,9 @@ class Builder: self.write_doc(docname, doctree) def _write_parallel(self, docnames, nproc): - # type: (Sequence[unicode], int) -> None + # type: (Sequence[str], int) -> None def write_process(docs): - # type: (List[Tuple[unicode, nodes.document]]) -> None + # type: (List[Tuple[str, nodes.document]]) -> None self.app.phase = BuildPhase.WRITING for docname, doctree in docs: self.write_doc(docname, doctree) @@ -618,17 +617,17 @@ class Builder: tasks.join() def prepare_writing(self, docnames): - # type: (Set[unicode]) -> None + # type: (Set[str]) -> None """A place where you can add logic before :meth:`write_doc` is run""" raise NotImplementedError def write_doc(self, docname, doctree): - # type: (unicode, nodes.document) -> None + # type: (str, nodes.document) -> None """Where you actually write something to the filesystem.""" raise NotImplementedError def write_doc_serialized(self, docname, doctree): - # type: (unicode, nodes.document) -> None + # type: (str, nodes.document) -> None """Handle parts of write_doc that must be called in the main process if parallel build is active. """ @@ -651,7 +650,7 @@ class Builder: pass def get_builder_config(self, option, default): - # type: (unicode, unicode) -> Any + # type: (str, str) -> Any """Return a builder specific option. This method allows customization of common builder settings by diff --git a/sphinx/builders/_epub_base.py b/sphinx/builders/_epub_base.py index 80277431b..4e1794179 100644 --- a/sphinx/builders/_epub_base.py +++ b/sphinx/builders/_epub_base.py @@ -39,7 +39,6 @@ if False: # For type annotation from typing import Any, Dict, List, Tuple # NOQA from sphinx.application import Sphinx # NOQA - from sphinx.util.typing import unicode # NOQA logger = logging.getLogger(__name__) @@ -80,7 +79,7 @@ MEDIA_TYPES = { '.otf': 'application/x-font-otf', '.ttf': 'application/x-font-ttf', '.woff': 'application/font-woff', -} # type: Dict[unicode, unicode] +} VECTOR_GRAPHICS_EXTENSIONS = ('.svg',) @@ -97,7 +96,7 @@ NavPoint = namedtuple('NavPoint', ['navpoint', 'playorder', 'text', 'refuri', 'c def sphinx_smarty_pants(t, language='en'): - # type: (unicode, str) -> unicode + # type: (str, str) -> str t = t.replace('"', '"') t = smartquotes.educateDashesOldSchool(t) t = smartquotes.educateQuotes(t, language) @@ -158,21 +157,21 @@ class EpubBuilder(StandaloneHTMLBuilder): self.link_suffix = '.xhtml' self.playorder = 0 self.tocid = 0 - self.id_cache = {} # type: Dict[unicode, unicode] + self.id_cache = {} # type: Dict[str, str] self.use_index = self.get_builder_config('use_index', 'epub') - self.refnodes = [] # type: List[Dict[unicode, Any]] + self.refnodes = [] # type: List[Dict[str, Any]] def create_build_info(self): # type: () -> BuildInfo return BuildInfo(self.config, self.tags, ['html', 'epub']) def get_theme_config(self): - # type: () -> Tuple[unicode, Dict] + # type: () -> Tuple[str, Dict] return self.config.epub_theme, self.config.epub_theme_options # generic support functions def make_id(self, name): - # type: (unicode) -> unicode + # type: (str) -> str # id_cache is intentionally mutable """Return a unique id for name.""" id = self.id_cache.get(name) @@ -182,7 +181,7 @@ class EpubBuilder(StandaloneHTMLBuilder): return id def esc(self, name): - # type: (unicode) -> unicode + # type: (str) -> str """Replace all characters not allowed in text an attribute values.""" # Like cgi.escape, but also replace apostrophe name = name.replace('&', '&') @@ -193,7 +192,7 @@ class EpubBuilder(StandaloneHTMLBuilder): return name def get_refnodes(self, doctree, result): - # type: (nodes.Node, List[Dict[unicode, Any]]) -> List[Dict[unicode, Any]] + # type: (nodes.Node, List[Dict[str, Any]]) -> List[Dict[str, Any]] """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? @@ -233,7 +232,7 @@ class EpubBuilder(StandaloneHTMLBuilder): self.toc_add_files(self.refnodes) def toc_add_files(self, refnodes): - # type: (List[Dict[unicode, Any]]) -> None + # type: (List[Dict[str, Any]]) -> None """Add the master_doc, pre and post files to a list of refnodes. """ refnodes.insert(0, { @@ -256,7 +255,7 @@ class EpubBuilder(StandaloneHTMLBuilder): }) def fix_fragment(self, prefix, fragment): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str """Return a href/id attribute with colons replaced by hyphens.""" return prefix + fragment.replace(':', '-') @@ -294,11 +293,11 @@ class EpubBuilder(StandaloneHTMLBuilder): desc_signature.attributes['ids'] = newids def add_visible_links(self, tree, show_urls='inline'): - # type: (nodes.document, unicode) -> None + # type: (nodes.document, str) -> None """Add visible link targets for external links""" def make_footnote_ref(doc, label): - # type: (nodes.document, unicode) -> nodes.footnote_reference + # type: (nodes.document, str) -> nodes.footnote_reference """Create a footnote_reference node with children""" footnote_ref = nodes.footnote_reference('[#]_') footnote_ref.append(nodes.Text(label)) @@ -306,7 +305,7 @@ class EpubBuilder(StandaloneHTMLBuilder): return footnote_ref def make_footnote(doc, label, uri): - # type: (nodes.document, unicode, unicode) -> nodes.footnote + # type: (nodes.document, str, str) -> nodes.footnote """Create a footnote node with children""" footnote = nodes.footnote(uri) para = nodes.paragraph() @@ -366,7 +365,7 @@ class EpubBuilder(StandaloneHTMLBuilder): fn_idx += 1 def write_doc(self, docname, doctree): - # type: (unicode, nodes.document) -> None + # type: (str, nodes.document) -> None """Write one document file. This method is overwritten in order to fix fragment identifiers @@ -377,7 +376,7 @@ class EpubBuilder(StandaloneHTMLBuilder): super(EpubBuilder, self).write_doc(docname, doctree) def fix_genindex(self, tree): - # type: (List[Tuple[unicode, List[Tuple[unicode, Any]]]]) -> None + # type: (List[Tuple[str, List[Tuple[str, Any]]]]) -> None """Fix href attributes for genindex pages.""" # XXX: modifies tree inline # Logic modeled from themes/basic/genindex.html @@ -396,7 +395,7 @@ class EpubBuilder(StandaloneHTMLBuilder): self.fix_fragment(m.group(1), m.group(2))) def is_vector_graphics(self, filename): - # type: (unicode) -> bool + # type: (str) -> bool """Does the filename extension indicate a vector graphic format?""" ext = path.splitext(filename)[-1] return ext in VECTOR_GRAPHICS_EXTENSIONS @@ -461,7 +460,7 @@ class EpubBuilder(StandaloneHTMLBuilder): def handle_page(self, pagename, addctx, templatename='page.html', outfilename=None, event_arg=None): - # type: (unicode, Dict, unicode, unicode, Any) -> None + # type: (str, Dict, str, str, Any) -> None """Create a rendered page. This method is overwritten for genindex pages in order to fix href link @@ -476,14 +475,14 @@ class EpubBuilder(StandaloneHTMLBuilder): outfilename, event_arg) def build_mimetype(self, outdir, outname): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Write the metainfo file mimetype.""" logger.info(__('writing %s file...'), outname) copy_asset_file(path.join(self.template_dir, 'mimetype'), path.join(outdir, outname)) def build_container(self, outdir, outname): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Write the metainfo file META-INF/container.xml.""" logger.info(__('writing %s file...'), outname) filename = path.join(outdir, outname) @@ -491,11 +490,11 @@ class EpubBuilder(StandaloneHTMLBuilder): copy_asset_file(path.join(self.template_dir, 'container.xml'), filename) def content_metadata(self): - # type: () -> Dict[unicode, Any] + # type: () -> Dict[str, Any] """Create a dictionary with all metadata for the content.opf file properly escaped. """ - metadata = {} # type: Dict[unicode, Any] + metadata = {} # type: Dict[str, Any] metadata['title'] = self.esc(self.config.epub_title) metadata['author'] = self.esc(self.config.epub_author) metadata['uid'] = self.esc(self.config.epub_uid) @@ -511,7 +510,7 @@ class EpubBuilder(StandaloneHTMLBuilder): return metadata def build_content(self, outdir, outname): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Write the metainfo file content.opf It contains bibliographic data, a file list and the spine (the reading order). """ @@ -522,7 +521,7 @@ class EpubBuilder(StandaloneHTMLBuilder): if not outdir.endswith(os.sep): outdir += os.sep olen = len(outdir) - self.files = [] # type: List[unicode] + self.files = [] # type: List[str] self.ignored_files = ['.buildinfo', 'mimetype', 'content.opf', 'toc.ncx', 'META-INF/container.xml', 'Thumbs.db', 'ehthumbs.db', '.DS_Store', @@ -625,7 +624,7 @@ class EpubBuilder(StandaloneHTMLBuilder): metadata) def new_navpoint(self, node, level, incr=True): - # type: (Dict[unicode, Any], int, bool) -> NavPoint + # type: (Dict[str, Any], int, bool) -> NavPoint """Create a new entry in the toc from the node at given level.""" # XXX Modifies the node if incr: @@ -635,7 +634,7 @@ class EpubBuilder(StandaloneHTMLBuilder): node['text'], node['refuri'], []) def build_navpoints(self, nodes): - # type: (List[Dict[unicode, Any]]) -> List[NavPoint] + # type: (List[Dict[str, Any]]) -> List[NavPoint] """Create the toc navigation structure. Subelements of a node are nested inside the navpoint. For nested nodes @@ -680,11 +679,11 @@ class EpubBuilder(StandaloneHTMLBuilder): return navstack[0].children def toc_metadata(self, level, navpoints): - # type: (int, List[NavPoint]) -> Dict[unicode, Any] + # type: (int, List[NavPoint]) -> Dict[str, Any] """Create a dictionary with all metadata for the toc.ncx file properly escaped. """ - metadata = {} # type: Dict[unicode, Any] + metadata = {} # type: Dict[str, Any] metadata['uid'] = self.config.epub_uid metadata['title'] = self.esc(self.config.epub_title) metadata['level'] = level @@ -692,7 +691,7 @@ class EpubBuilder(StandaloneHTMLBuilder): return metadata def build_toc(self, outdir, outname): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Write the metainfo file toc.ncx.""" logger.info(__('writing %s file...'), outname) @@ -713,7 +712,7 @@ class EpubBuilder(StandaloneHTMLBuilder): self.toc_metadata(level, navpoints)) def build_epub(self, outdir, outname): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Write the epub file. It is a zip file with the mimetype file stored uncompressed as the first diff --git a/sphinx/builders/applehelp.py b/sphinx/builders/applehelp.py index 74f8fcfc6..f7379e1ba 100644 --- a/sphinx/builders/applehelp.py +++ b/sphinx/builders/applehelp.py @@ -8,7 +8,6 @@ :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ -from __future__ import print_function import pipes import plistlib @@ -31,7 +30,6 @@ if False: # For type annotation from typing import Any, Dict # NOQA from sphinx.application import Sphinx # NOQA - from sphinx.util.typing import unicode # NOQA logger = logging.getLogger(__name__) @@ -270,7 +268,7 @@ class AppleHelpBuilder(StandaloneHTMLBuilder): def setup(app): - # type: (Sphinx) -> Dict[unicode, Any] + # type: (Sphinx) -> Dict[str, Any] app.setup_extension('sphinx.builders.html') app.add_builder(AppleHelpBuilder) diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py index 5f1999003..5b934fb3e 100644 --- a/sphinx/builders/changes.py +++ b/sphinx/builders/changes.py @@ -27,7 +27,6 @@ if False: # For type annotation from typing import Any, Dict, List, Tuple # NOQA from sphinx.application import Sphinx # NOQA - from sphinx.util.typing import unicode # NOQA logger = logging.getLogger(__name__) @@ -48,22 +47,22 @@ class ChangesBuilder(Builder): self.templates.init(self, self.theme) def get_outdated_docs(self): - # type: () -> unicode + # type: () -> str return self.outdir typemap = { 'versionadded': 'added', 'versionchanged': 'changed', 'deprecated': 'deprecated', - } # type: Dict[unicode, unicode] + } def write(self, *ignored): # type: (Any) -> None version = self.config.version domain = cast(ChangeSetDomain, self.env.get_domain('changeset')) - libchanges = {} # type: Dict[unicode, List[Tuple[unicode, unicode, int]]] - apichanges = [] # type: List[Tuple[unicode, unicode, int]] - otherchanges = {} # type: Dict[Tuple[unicode, unicode], List[Tuple[unicode, unicode, int]]] # NOQA + libchanges = {} # type: Dict[str, List[Tuple[str, str, int]]] + apichanges = [] # type: List[Tuple[str, str, int]] + otherchanges = {} # type: Dict[Tuple[str, str], List[Tuple[str, str, int]]] if version not in self.env.versionchanges: logger.info(bold(__('no changes in version %s.') % version)) return @@ -123,7 +122,7 @@ class ChangesBuilder(Builder): '.. deprecated:: %s' % version] def hl(no, line): - # type: (int, unicode) -> unicode + # type: (int, str) -> str line = ' ' % no + htmlescape(line) for x in hltext: if x in line: @@ -157,7 +156,7 @@ class ChangesBuilder(Builder): self.outdir) def hl(self, text, version): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str text = htmlescape(text) for directive in ['versionchanged', 'versionadded', 'deprecated']: text = text.replace('.. %s:: %s' % (directive, version), @@ -170,7 +169,7 @@ class ChangesBuilder(Builder): def setup(app): - # type: (Sphinx) -> Dict[unicode, Any] + # type: (Sphinx) -> Dict[str, Any] app.add_builder(ChangesBuilder) return { diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py index 901fb5560..cb01667b9 100644 --- a/sphinx/builders/devhelp.py +++ b/sphinx/builders/devhelp.py @@ -36,7 +36,6 @@ if False: # For type annotation from typing import Dict, List # NOQA from sphinx.application import Sphinx # NOQA - from sphinx.util.typing import unicode # NOQA logger = logging.getLogger(__name__) @@ -72,7 +71,7 @@ class DevhelpBuilder(StandaloneHTMLBuilder): self.build_devhelp(self.outdir, self.config.devhelp_basename) def build_devhelp(self, outdir, outname): - # type: (unicode, unicode) -> None + # type: (str, str) -> None logger.info(__('dumping devhelp index...')) # Basic info @@ -112,7 +111,7 @@ class DevhelpBuilder(StandaloneHTMLBuilder): index = IndexEntries(self.env).create_index(self) def write_index(title, refs, subitems): - # type: (unicode, List[Any], Any) -> None + # type: (str, List[Any], Any) -> None if len(refs) == 0: pass elif len(refs) == 1: @@ -141,7 +140,7 @@ class DevhelpBuilder(StandaloneHTMLBuilder): def setup(app): - # type: (Sphinx) -> Dict[unicode, Any] + # type: (Sphinx) -> Dict[str, Any] app.setup_extension('sphinx.builders.html') app.add_builder(DevhelpBuilder) diff --git a/sphinx/builders/dummy.py b/sphinx/builders/dummy.py index 9ab1ad155..d20a5ab09 100644 --- a/sphinx/builders/dummy.py +++ b/sphinx/builders/dummy.py @@ -18,7 +18,6 @@ if False: from typing import Any, Dict, Set # NOQA from docutils import nodes # NOQA from sphinx.application import Sphinx # NOQA - from sphinx.util.typing import unicode # NOQA class DummyBuilder(Builder): @@ -32,19 +31,19 @@ class DummyBuilder(Builder): pass def get_outdated_docs(self): - # type: () -> Set[unicode] + # type: () -> Set[str] return self.env.found_docs def get_target_uri(self, docname, typ=None): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str return '' def prepare_writing(self, docnames): - # type: (Set[unicode]) -> None + # type: (Set[str]) -> None pass def write_doc(self, docname, doctree): - # type: (unicode, nodes.Node) -> None + # type: (str, nodes.Node) -> None pass def finish(self): @@ -53,7 +52,7 @@ class DummyBuilder(Builder): def setup(app): - # type: (Sphinx) -> Dict[unicode, Any] + # type: (Sphinx) -> Dict[str, Any] app.add_builder(DummyBuilder) return { diff --git a/sphinx/builders/epub3.py b/sphinx/builders/epub3.py index 312098098..a378bd981 100644 --- a/sphinx/builders/epub3.py +++ b/sphinx/builders/epub3.py @@ -28,7 +28,6 @@ if False: from docutils import nodes # NOQA from sphinx.application import Sphinx # NOQA from sphinx.config import Config # NOQA - from sphinx.util.typing import unicode # NOQA logger = logging.getLogger(__name__) @@ -141,7 +140,7 @@ class Epub3Builder(_epub_base.EpubBuilder): return metadata def prepare_writing(self, docnames): - # type: (Set[unicode]) -> None + # type: (Set[str]) -> None super(Epub3Builder, self).prepare_writing(docnames) writing_mode = self.config.epub_writing_mode @@ -151,7 +150,7 @@ class Epub3Builder(_epub_base.EpubBuilder): self.globalcontext['skip_ua_compatible'] = True def build_navlist(self, navnodes): - # type: (List[Dict[unicode, Any]]) -> List[NavPoint] + # type: (List[Dict[str, Any]]) -> List[NavPoint] """Create the toc navigation structure. This method is almost same as build_navpoints method in epub.py. @@ -205,7 +204,7 @@ class Epub3Builder(_epub_base.EpubBuilder): return metadata def build_navigation_doc(self, outdir, outname): - # type: (unicode, unicode) -> None + # type: (str, str) -> None """Write the metainfo file nav.xhtml.""" logger.info(__('writing %s file...'), outname) @@ -231,7 +230,7 @@ class Epub3Builder(_epub_base.EpubBuilder): def convert_epub_css_files(app, config): # type: (Sphinx, Config) -> None """This converts string styled epub_css_files to tuple styled one.""" - epub_css_files = [] # type: List[Tuple[unicode, Dict]] + epub_css_files = [] # type: List[Tuple[str, Dict]] for entry in config.epub_css_files: if isinstance(entry, str): epub_css_files.append((entry, {})) @@ -247,7 +246,7 @@ def convert_epub_css_files(app, config): def setup(app): - # type: (Sphinx) -> Dict[unicode, Any] + # type: (Sphinx) -> Dict[str, Any] app.add_builder(Epub3Builder) # config values diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py index 684013d11..7ff8d0d53 100644 --- a/sphinx/builders/gettext.py +++ b/sphinx/builders/gettext.py @@ -14,12 +14,11 @@ from __future__ import unicode_literals from codecs import open from collections import defaultdict, OrderedDict from datetime import datetime, tzinfo, timedelta +from io import StringIO from os import path, walk, getenv from time import time from uuid import uuid4 -from six import StringIO - from sphinx.builders import Builder from sphinx.domains.python import pairindextypes from sphinx.errors import ThemeError @@ -37,7 +36,6 @@ if False: from docutils import nodes # NOQA from sphinx.application import Sphinx # NOQA from sphinx.util.i18n import CatalogInfo # NOQA - from sphinx.util.typing import unicode # NOQA logger = logging.getLogger(__name__) @@ -69,13 +67,13 @@ class Catalog: def __init__(self): # type: () -> None - self.messages = [] # type: List[unicode] + self.messages = [] # type: List[str] # retain insertion order, a la OrderedDict - self.metadata = OrderedDict() # type: Dict[unicode, List[Tuple[unicode, int, unicode]]] # NOQA + self.metadata = OrderedDict() # type: Dict[str, List[Tuple[str, int, str]]] # msgid -> file, line, uid def add(self, msg, origin): - # type: (unicode, Union[nodes.Element, MsgOrigin]) -> None + # type: (str, Union[nodes.Element, MsgOrigin]) -> None if not hasattr(origin, 'uid'): # Nodes that are replicated like todo don't have a uid, # however i18n is also unnecessary. @@ -92,7 +90,7 @@ class MsgOrigin: """ def __init__(self, source, line): - # type: (unicode, int) -> None + # type: (str, int) -> None self.source = source self.line = line self.uid = uuid4().hex @@ -125,26 +123,26 @@ class I18nBuilder(Builder): self.env.set_versioning_method(self.versioning_method, self.env.config.gettext_uuid) self.tags = I18nTags() - self.catalogs = defaultdict(Catalog) # type: DefaultDict[unicode, Catalog] + self.catalogs = defaultdict(Catalog) # type: DefaultDict[str, Catalog] def get_target_uri(self, docname, typ=None): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str return '' def get_outdated_docs(self): - # type: () -> Set[unicode] + # type: () -> Set[str] return self.env.found_docs def prepare_writing(self, docnames): - # type: (Set[unicode]) -> None + # type: (Set[str]) -> None return def compile_catalogs(self, catalogs, message): - # type: (Set[CatalogInfo], unicode) -> None + # type: (Set[CatalogInfo], str) -> None return def write_doc(self, docname, doctree): - # type: (unicode, nodes.document) -> None + # type: (str, nodes.document) -> None catalog = self.catalogs[find_catalog(docname, self.config.gettext_compact)] for node, msg in extract_messages(doctree): @@ -194,7 +192,7 @@ ltz = LocalTimeZone() def should_write(filepath, new_content): - # type: (unicode, unicode) -> bool + # type: (str, str) -> bool if not path.exists(filepath): return True try: @@ -226,7 +224,7 @@ class MessageCatalogBuilder(I18nBuilder): self.templates.init(self) def _collect_templates(self): - # type: () -> Set[unicode] + # type: () -> Set[str] template_files = set() for template_path in self.config.templates_path: tmpl_abs_path = path.join(self.app.srcdir, template_path) @@ -258,7 +256,7 @@ class MessageCatalogBuilder(I18nBuilder): raise ThemeError('%s: %r' % (template, exc)) def build(self, docnames, summary=None, method='update'): - # type: (Iterable[unicode], unicode, unicode) -> None + # type: (Iterable[str], str, str) -> None self._extract_from_template() super(MessageCatalogBuilder, self).build(docnames, summary, method) @@ -310,7 +308,7 @@ class MessageCatalogBuilder(I18nBuilder): def setup(app): - # type: (Sphinx) -> Dict[unicode, Any] + # type: (Sphinx) -> Dict[str, Any] app.add_builder(MessageCatalogBuilder) app.add_config_value('gettext_compact', True, 'gettext') diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py index f9a28933d..10a6498e2 100644 --- a/sphinx/builders/html.py +++ b/sphinx/builders/html.py @@ -60,7 +60,6 @@ if False: from sphinx.config import Config # NOQA from sphinx.domains import Domain, Index, IndexEntry # NOQA from sphinx.util.tags import Tags # NOQA - from sphinx.util.typing import unicode # NOQA # Experimental HTML5 Writer if is_html5_writer_available(): @@ -79,7 +78,7 @@ return_codes_re = re.compile('[\r\n]+') def get_stable_hash(obj): - # type: (Any) -> unicode + # type: (Any) -> str """ Return a stable hash for a Python data structure. We can't just use the md5 of str(obj) since for example dictionary items are enumerated @@ -99,11 +98,11 @@ class Stylesheet(text_type): its filename (str). """ - attributes = None # type: Dict[unicode, unicode] - filename = None # type: unicode + attributes = None # type: Dict[str, str] + filename = None # type: str def __new__(cls, filename, *args, **attributes): - # type: (unicode, unicode, unicode) -> None + # type: (str, str, str) -> None self = text_type.__new__(cls, filename) # type: ignore self.filename = filename self.attributes = attributes @@ -119,14 +118,14 @@ class Stylesheet(text_type): class JSContainer(list): """The container for JavaScript scripts.""" def insert(self, index, obj): - # type: (int, unicode) -> None + # type: (int, str) -> None warnings.warn('builder.script_files is deprecated. ' 'Please use app.add_js_file() instead.', RemovedInSphinx30Warning, stacklevel=2) super(JSContainer, self).insert(index, obj) def extend(self, other): # type: ignore - # type: (List[unicode]) -> None + # type: (List[str]) -> None warnings.warn('builder.script_files is deprecated. ' 'Please use app.add_js_file() instead.', RemovedInSphinx30Warning, stacklevel=2) @@ -134,7 +133,7 @@ class JSContainer(list): self.append(item) def __iadd__(self, other): # type: ignore - # type: (List[unicode]) -> JSContainer + # type: (List[str]) -> JSContainer warnings.warn('builder.script_files is deprecated. ' 'Please use app.add_js_file() instead.', RemovedInSphinx30Warning, stacklevel=2) @@ -143,7 +142,7 @@ class JSContainer(list): return self def __add__(self, other): - # type: (List[unicode]) -> JSContainer + # type: (List[str]) -> JSContainer ret = JSContainer(self) ret += other return ret @@ -156,11 +155,11 @@ class JavaScript(text_type): its filename (str). """ - attributes = None # type: Dict[unicode, unicode] - filename = None # type: unicode + attributes = None # type: Dict[str, str] + filename = None # type: str def __new__(cls, filename, **attributes): - # type: (unicode, **unicode) -> None + # type: (str, **str) -> None self = text_type.__new__(cls, filename) # type: ignore self.filename = filename self.attributes = attributes @@ -193,7 +192,7 @@ class BuildInfo: raise ValueError(__('build info file is broken: %r') % exc) def __init__(self, config=None, tags=None, config_categories=[]): - # type: (Config, Tags, List[unicode]) -> None + # type: (Config, Tags, List[str]) -> None self.config_hash = u'' self.tags_hash = u'' @@ -249,8 +248,8 @@ class StandaloneHTMLBuilder(Builder): # use html5 translator by default default_html5_translator = False - imgpath = None # type: unicode - domain_indices = [] # type: List[Tuple[unicode, Type[Index], List[Tuple[unicode, List[IndexEntry]]], bool]] # NOQA + imgpath = None # type: str + domain_indices = [] # type: List[Tuple[str, Type[Index], List[Tuple[str, List[IndexEntry]]], bool]] # NOQA # cached publisher object for snippets _publisher = None @@ -260,7 +259,7 @@ class StandaloneHTMLBuilder(Builder): super(StandaloneHTMLBuilder, self).__init__(app) # CSS files - self.css_files = [] # type: List[Dict[unicode, unicode]] + self.css_files = [] # type: List[Dict[str, str]] # JS files self.script_files = JSContainer() # type: List[JavaScript] @@ -271,9 +270,9 @@ class StandaloneHTMLBuilder(Builder): # basename of images directory self.imagedir = '_images' # section numbers for headings in the currently visited document - self.secnumbers = {} # type: Dict[unicode, Tuple[int, ...]] + self.secnumbers = {} # type: Dict[str, Tuple[int, ...]] # currently written docname - self.current_docname = None # type: unicode + self.current_docname = None # type: str self.init_templates() self.init_highlighter() @@ -302,7 +301,7 @@ class StandaloneHTMLBuilder(Builder): return BuildInfo(self.config, self.tags, ['html']) def _get_translations_js(self): - # type: () -> unicode + # type: () -> str candidates = [path.join(dir, self.config.language, 'LC_MESSAGES', 'sphinx.js') for dir in self.config.locale_dirs] + \ @@ -317,7 +316,7 @@ class StandaloneHTMLBuilder(Builder): return None def get_theme_config(self): - # type: () -> Tuple[unicode, Dict] + # type: () -> Tuple[str, Dict] return self.config.html_theme, self.config.html_theme_options def init_templates(self): @@ -349,7 +348,7 @@ class StandaloneHTMLBuilder(Builder): self.add_css_file(filename, **attrs) def add_css_file(self, filename, **kwargs): - # type: (unicode, **unicode) -> None + # type: (str, **str) -> None if '://' not in filename: filename = posixpath.join('_static', filename) @@ -372,7 +371,7 @@ class StandaloneHTMLBuilder(Builder): self.add_js_file('translations.js') def add_js_file(self, filename, **kwargs): - # type: (unicode, **unicode) -> None + # type: (str, **str) -> None if filename and '://' not in filename: filename = posixpath.join('_static', filename) @@ -392,7 +391,7 @@ class StandaloneHTMLBuilder(Builder): @property def math_renderer_name(self): - # type: () -> unicode + # type: () -> str name = self.get_builder_config('math_renderer', 'html') if name is not None: # use given name @@ -412,14 +411,13 @@ class StandaloneHTMLBuilder(Builder): return None def get_outdated_docs(self): - # type: () -> Iterator[unicode] + # type: () -> Iterator[str] try: with open(path.join(self.outdir, '.buildinfo')) as fp: buildinfo = BuildInfo.load(fp) if self.build_info != buildinfo: - for docname in self.env.found_docs: - yield docname + yield from self.env.found_docs return except ValueError as exc: logger.warning(__('Failed to read build info file: %r'), exc) @@ -450,11 +448,11 @@ class StandaloneHTMLBuilder(Builder): pass def get_asset_paths(self): - # type: () -> List[unicode] + # type: () -> List[str] return self.config.html_extra_path + self.config.html_static_path def render_partial(self, node): - # type: (nodes.Node) -> Dict[unicode, unicode] + # type: (nodes.Node) -> Dict[str, str] """Utility: Render a lone doctree node.""" if node is None: return {'fragment': ''} @@ -480,7 +478,7 @@ class StandaloneHTMLBuilder(Builder): return pub.writer.parts def prepare_writing(self, docnames): - # type: (Set[unicode]) -> None + # type: (Set[str]) -> None # create the search indexer self.indexer = None if self.search: @@ -509,7 +507,7 @@ class StandaloneHTMLBuilder(Builder): domain = None # type: Domain domain = self.env.domains[domain_name] for indexcls in domain.indices: - indexname = '%s-%s' % (domain.name, indexcls.name) # type: unicode + indexname = '%s-%s' % (domain.name, indexcls.name) if isinstance(indices_config, list): if indexname not in indices_config: continue @@ -538,7 +536,7 @@ class StandaloneHTMLBuilder(Builder): self.relations = self.env.collect_relations() - rellinks = [] # type: List[Tuple[unicode, unicode, unicode, unicode]] + rellinks = [] # type: List[Tuple[str, str, str, str]] if self.use_index: rellinks.append(('genindex', _('General Index'), 'I', _('index'))) for indexname, indexcls, content, collapse in self.domain_indices: @@ -582,7 +580,7 @@ class StandaloneHTMLBuilder(Builder): 'logo': logo, 'favicon': favicon, 'html5_doctype': self.config.html_experimental_html5_writer and html5_ready, - } # type: Dict[unicode, Any] + } if self.theme: self.globalcontext.update( ('theme_' + key, val) for (key, val) in @@ -590,7 +588,7 @@ class StandaloneHTMLBuilder(Builder): self.globalcontext.update(self.config.html_context) def get_doc_context(self, docname, body, metatags): - # type: (unicode, unicode, unicode) -> Dict[unicode, Any] + # type: (str, str, str) -> Dict[str, Any] """Collect items for the template context of a page.""" # find out relations prev = next = None @@ -671,14 +669,14 @@ class StandaloneHTMLBuilder(Builder): } def write_doc(self, docname, doctree): - # type: (unicode, nodes.document) -> None + # type: (str, nodes.document) -> None destination = StringOutput(encoding='utf-8') doctree.settings = self.docsettings self.secnumbers = self.env.toc_secnumbers.get(docname, {}) self.fignumbers = self.env.toc_fignumbers.get(docname, {}) self.imgpath = relative_uri(self.get_target_uri(docname), '_images') - self.dlpath = relative_uri(self.get_target_uri(docname), '_downloads') # type: unicode + self.dlpath = relative_uri(self.get_target_uri(docname), '_downloads') self.current_docname = docname self.docwriter.write(doctree, destination) self.docwriter.assemble_parts() @@ -689,7 +687,7 @@ class StandaloneHTMLBuilder(Builder): self.handle_page(docname, ctx, event_arg=doctree) def write_doc_serialized(self, docname, doctree): - # type: (unicode, nodes.document) -> None + # type: (str, nodes.document) -> None self.imgpath = relative_uri(self.get_target_uri(docname), self.imagedir) self.post_process_images(doctree) title_node = self.env.longtitles.get(docname) @@ -809,7 +807,7 @@ class StandaloneHTMLBuilder(Builder): def copy_download_files(self): # type: () -> None def to_relpath(f): - # type: (unicode) -> unicode + # type: (str) -> str return relative_path(self.srcdir, f) # copy downloadable files if self.env.dlfiles: @@ -951,7 +949,7 @@ class StandaloneHTMLBuilder(Builder): reference.append(node) def load_indexer(self, docnames): - # type: (Iterable[unicode]) -> None + # type: (Iterable[str]) -> None keep = set(self.env.all_docs) - set(docnames) try: searchindexfn = path.join(self.outdir, self.searchindex_filename) @@ -970,7 +968,7 @@ class StandaloneHTMLBuilder(Builder): self.indexer.prune(keep) def index_page(self, pagename, doctree, title): - # type: (unicode, nodes.document, unicode) -> None + # type: (str, nodes.document, str) -> None # only index pages with title if self.indexer is not None and title: filename = self.env.doc2path(pagename, base=None) @@ -981,20 +979,20 @@ class StandaloneHTMLBuilder(Builder): self.indexer.feed(pagename, title, doctree) # type: ignore def _get_local_toctree(self, docname, collapse=True, **kwds): - # type: (unicode, bool, Any) -> unicode + # type: (str, bool, Any) -> str if 'includehidden' not in kwds: kwds['includehidden'] = False return self.render_partial(TocTree(self.env).get_toctree_for( docname, self, collapse, **kwds))['fragment'] def get_outfilename(self, pagename): - # type: (unicode) -> unicode + # type: (str) -> str return path.join(self.outdir, os_path(pagename) + self.out_suffix) def add_sidebars(self, pagename, ctx): - # type: (unicode, Dict) -> None + # type: (str, Dict) -> None def has_wildcard(pattern): - # type: (unicode) -> bool + # type: (str) -> bool return any(char in pattern for char in '*?[') sidebars = None matched = None @@ -1045,12 +1043,12 @@ class StandaloneHTMLBuilder(Builder): # --------- these are overwritten by the serialization builder def get_target_uri(self, docname, typ=None): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str return docname + self.link_suffix def handle_page(self, pagename, addctx, templatename='page.html', outfilename=None, event_arg=None): - # type: (unicode, Dict, unicode, unicode, Any) -> None + # type: (str, Dict, str, str, Any) -> None ctx = self.globalcontext.copy() # current_page_name is backwards compatibility ctx['pagename'] = ctx['current_page_name'] = pagename @@ -1067,7 +1065,7 @@ class StandaloneHTMLBuilder(Builder): ctx['pageurl'] = None def pathto(otheruri, resource=False, baseuri=default_baseuri): - # type: (unicode, bool, unicode) -> unicode + # type: (str, bool, str) -> str if resource and '://' in otheruri: # allow non-local resources given by scheme return otheruri @@ -1080,7 +1078,7 @@ class StandaloneHTMLBuilder(Builder): ctx['pathto'] = pathto def css_tag(css): - # type: (Stylesheet) -> unicode + # type: (Stylesheet) -> str attrs = [] for key in sorted(css.attributes): value = css.attributes[key] @@ -1091,7 +1089,7 @@ class StandaloneHTMLBuilder(Builder): ctx['css_tag'] = css_tag def hasdoc(name): - # type: (unicode) -> bool + # type: (str) -> bool if name in self.env.all_docs: return True elif name == 'search' and self.search: @@ -1102,7 +1100,7 @@ class StandaloneHTMLBuilder(Builder): ctx['hasdoc'] = hasdoc def warn(*args, **kwargs): - # type: (Any, Any) -> unicode + # type: (Any, Any) -> str """Simple warn() wrapper for themes.""" warnings.warn('The template function warn() was deprecated. ' 'Use warning() instead.', @@ -1150,7 +1148,7 @@ class StandaloneHTMLBuilder(Builder): copyfile(self.env.doc2path(pagename), source_name) def update_page_context(self, pagename, templatename, ctx, event_arg): - # type: (unicode, unicode, Dict, Any) -> None + # type: (str, str, Dict, Any) -> None pass def handle_finish(self): @@ -1193,7 +1191,7 @@ class DirectoryHTMLBuilder(StandaloneHTMLBuilder): name = 'dirhtml' def get_target_uri(self, docname, typ=None): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str if docname == 'index': return '' if docname.endswith(SEP + 'index'): @@ -1201,7 +1199,7 @@ class DirectoryHTMLBuilder(StandaloneHTMLBuilder): return docname + SEP def get_outfilename(self, pagename): - # type: (unicode) -> unicode + # type: (str) -> str if pagename == 'index' or pagename.endswith(SEP + 'index'): outfilename = path.join(self.outdir, os_path(pagename) + self.out_suffix) @@ -1212,7 +1210,7 @@ class DirectoryHTMLBuilder(StandaloneHTMLBuilder): return outfilename def prepare_writing(self, docnames): - # type: (Set[unicode]) -> None + # type: (Set[str]) -> None super(DirectoryHTMLBuilder, self).prepare_writing(docnames) self.globalcontext['no_search_suffix'] = True @@ -1228,11 +1226,11 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): copysource = False def get_outdated_docs(self): # type: ignore - # type: () -> Union[unicode, List[unicode]] + # type: () -> Union[str, List[str]] return 'all documents' def get_target_uri(self, docname, typ=None): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str if docname in self.env.all_docs: # all references are on the same page... return self.config.master_doc + self.out_suffix + \ @@ -1242,7 +1240,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): return docname + self.out_suffix def get_relative_uri(self, from_, to, typ=None): - # type: (unicode, unicode, unicode) -> unicode + # type: (str, str, str) -> str # ignore source return self.get_target_uri(to, typ) @@ -1262,7 +1260,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): refnode['refuri'] = fname + refuri[hashindex:] def _get_local_toctree(self, docname, collapse=True, **kwds): - # type: (unicode, bool, Any) -> unicode + # type: (str, bool, Any) -> str if 'includehidden' not in kwds: kwds['includehidden'] = False toctree = TocTree(self.env).get_toctree_for(docname, self, collapse, **kwds) @@ -1281,7 +1279,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): return tree def assemble_toc_secnumbers(self): - # type: () -> Dict[unicode, Dict[unicode, Tuple[int, ...]]] + # type: () -> Dict[str, Dict[str, Tuple[int, ...]]] # Assemble toc_secnumbers to resolve section numbers on SingleHTML. # Merge all secnumbers to single secnumber. # @@ -1291,7 +1289,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): # # There are related codes in inline_all_toctres() and # HTMLTranslter#add_secnumber(). - new_secnumbers = {} # type: Dict[unicode, Tuple[int, ...]] + new_secnumbers = {} # type: Dict[str, Tuple[int, ...]] for docname, secnums in self.env.toc_secnumbers.items(): for id, secnum in secnums.items(): alias = "%s/%s" % (docname, id) @@ -1300,7 +1298,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): return {self.config.master_doc: new_secnumbers} def assemble_toc_fignumbers(self): - # type: () -> Dict[unicode, Dict[unicode, Dict[unicode, Tuple[int, ...]]]] # NOQA + # type: () -> Dict[str, Dict[str, Dict[str, Tuple[int, ...]]]] # Assemble toc_fignumbers to resolve figure numbers on SingleHTML. # Merge all fignumbers to single fignumber. # @@ -1310,7 +1308,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): # # There are related codes in inline_all_toctres() and # HTMLTranslter#add_fignumber(). - new_fignumbers = {} # type: Dict[unicode, Dict[unicode, Tuple[int, ...]]] + new_fignumbers = {} # type: Dict[str, Dict[str, Tuple[int, ...]]] # {u'foo': {'figure': {'id2': (2,), 'id1': (1,)}}, u'bar': {'figure': {'id1': (3,)}}} for docname, fignumlist in self.env.toc_fignumbers.items(): for figtype, fignums in fignumlist.items(): @@ -1322,7 +1320,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder): return {self.config.master_doc: new_fignumbers} def get_doc_context(self, docname, body, metatags): - # type: (unicode, unicode, unicode) -> Dict + # type: (str, str, str) -> Dict # no relation links... toctree = TocTree(self.env).get_toctree_for(self.config.master_doc, self, False) # if there is no toctree, toc is None @@ -1404,7 +1402,7 @@ class SerializingHTMLBuilder(StandaloneHTMLBuilder): additional_dump_args = () # type: Tuple #: the filename for the global context file - globalcontext_filename = None # type: unicode + globalcontext_filename = None # type: str supported_image_types = ['image/svg+xml', 'image/png', 'image/gif', 'image/jpeg'] @@ -1423,7 +1421,7 @@ class SerializingHTMLBuilder(StandaloneHTMLBuilder): self.use_index = self.get_builder_config('use_index', 'html') def get_target_uri(self, docname, typ=None): - # type: (unicode, unicode) -> unicode + # type: (str, str) -> str if docname == 'index': return '' if docname.endswith(SEP + 'index'): @@ -1431,7 +1429,7 @@ class SerializingHTMLBuilder(StandaloneHTMLBuilder): return docname + SEP def dump_context(self, context, filename): - # type: (Dict, unicode) -> None + # type: (Dict, str) -> None if self.implementation_dumps_unicode: with open(filename, 'w', encoding='utf-8') as ft: self.implementation.dump(context, ft, *self.additional_dump_args) @@ -1441,7 +1439,7 @@ class SerializingHTMLBuilder(StandaloneHTMLBuilder): def handle_page(self, pagename, ctx, templatename='page.html', outfilename=None, event_arg=None): - # type: (unicode, Dict, unicode, unicode, Any) -> None + # type: (str, Dict, str, str, Any) -> None ctx['current_page_name'] = pagename self.add_sidebars(pagename, ctx) @@ -1528,7 +1526,7 @@ class JSONHTMLBuilder(SerializingHTMLBuilder): def convert_html_css_files(app, config): # type: (Sphinx, Config) -> None """This converts string styled html_css_files to tuple styled one.""" - html_css_files = [] # type: List[Tuple[unicode, Dict]] + html_css_files = [] # type: List[Tuple[str, Dict]] for entry in config.html_css_files: if isinstance(entry, str): html_css_files.append((entry, {})) @@ -1546,7 +1544,7 @@ def convert_html_css_files(app, config): def convert_html_js_files(app, config): # type: (Sphinx, Config) -> None """This converts string styled html_js_files to tuple styled one.""" - html_js_files = [] # type: List[Tuple[unicode, Dict]] + html_js_files = [] # type: List[Tuple[str, Dict]] for entry in config.html_js_files: if isinstance(entry, str): html_js_files.append((entry, {})) @@ -1562,7 +1560,7 @@ def convert_html_js_files(app, config): def setup_js_tag_helper(app, pagename, templatexname, context, doctree): - # type: (Sphinx, unicode, unicode, Dict, nodes.Node) -> None + # type: (Sphinx, str, str, Dict, nodes.Node) -> None """Set up js_tag() template helper. .. note:: This set up function is added to keep compatibility with webhelper. @@ -1570,9 +1568,9 @@ def setup_js_tag_helper(app, pagename, templatexname, context, doctree): pathto = context.get('pathto') def js_tag(js): - # type: (JavaScript) -> unicode + # type: (JavaScript) -> str attrs = [] - body = '' # type: unicode + body = '' if isinstance(js, JavaScript): for key in sorted(js.attributes): value = js.attributes[key] @@ -1606,7 +1604,7 @@ def validate_math_renderer(app): def setup(app): - # type: (Sphinx) -> Dict[unicode, Any] + # type: (Sphinx) -> Dict[str, Any] # builders app.add_builder(StandaloneHTMLBuilder) app.add_builder(DirectoryHTMLBuilder) diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py index 55bff842b..24f3ab2c4 100644 --- a/sphinx/builders/htmlhelp.py +++ b/sphinx/builders/htmlhelp.py @@ -9,7 +9,6 @@ :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ -from __future__ import print_function import os from os import path @@ -31,7 +30,6 @@ if False: from typing import Any, Dict, IO, List, Tuple # NOQA from sphinx.application import Sphinx # NOQA from sphinx.config import Config # NOQA - from sphinx.util.typing import unicode # NOQA logger = logging.getLogger(__name__) @@ -209,13 +207,13 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder): self.lcid, self.encoding = locale def open_file(self, outdir, basename, mode='w'): - # type: (unicode, unicode, unicode) -> IO + # type: (str, str, str) -> IO # open a file with the correct encoding for the selected language return open(path.join(outdir, basename), mode, encoding=self.encoding, errors='xmlcharrefreplace') def update_page_context(self, pagename, templatename, ctx, event_arg): - # type: (unicode, unicode, Dict, unicode) -> None + # type: (str, str, Dict, str) -> None ctx['encoding'] = self.encoding def handle_finish(self): @@ -223,7 +221,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder): self.build_hhx(self.outdir, self.config.htmlhelp_basename) def write_doc(self, docname, doctree): - # type: (unicode, nodes.document) -> None + # type: (str, nodes.document) -> None for node in doctree.traverse(nodes.reference): # add ``target=_blank`` attributes to external links if node.get('internal') is None and 'refuri' in node: @@ -232,7 +230,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder): super(HTMLHelpBuilder, self).write_doc(docname, doctree) def build_hhx(self, outdir, outname): - # type: (unicode, unicode) -> None + # type: (str, str) -> None logger.info(__('dumping stopword list...')) with self.open_file(outdir, outname + '.stp') as f: for word in sorted(stopwords): @@ -306,9 +304,9 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder): f.write('