summaryrefslogtreecommitdiff
path: root/sphinx
diff options
context:
space:
mode:
Diffstat (limited to 'sphinx')
-rw-r--r--sphinx/__init__.py15
-rw-r--r--sphinx/addnodes.py24
-rw-r--r--sphinx/application.py48
-rw-r--r--sphinx/builders/__init__.py7
-rw-r--r--sphinx/builders/_epub_base.py129
-rw-r--r--sphinx/builders/applehelp.py45
-rw-r--r--sphinx/builders/devhelp.py40
-rw-r--r--sphinx/builders/epub3.py33
-rw-r--r--sphinx/builders/gettext.py27
-rw-r--r--sphinx/builders/html/__init__.py60
-rw-r--r--sphinx/builders/htmlhelp.py47
-rw-r--r--sphinx/builders/latex/__init__.py47
-rw-r--r--sphinx/builders/manpage.py2
-rw-r--r--sphinx/builders/qthelp.py42
-rw-r--r--sphinx/builders/xml.py7
-rw-r--r--sphinx/cmd/make_mode.py1
-rw-r--r--sphinx/cmd/quickstart.py41
-rw-r--r--sphinx/config.py45
-rw-r--r--sphinx/deprecation.py10
-rw-r--r--sphinx/directives/__init__.py54
-rw-r--r--sphinx/directives/code.py18
-rw-r--r--sphinx/directives/other.py27
-rw-r--r--sphinx/directives/patches.py25
-rw-r--r--sphinx/domains/__init__.py23
-rw-r--r--sphinx/domains/changeset.py16
-rw-r--r--sphinx/domains/citation.py5
-rw-r--r--sphinx/domains/index.py5
-rw-r--r--sphinx/domains/math.py25
-rw-r--r--sphinx/domains/python.py191
-rw-r--r--sphinx/domains/std.py48
-rw-r--r--sphinx/environment/__init__.py53
-rw-r--r--sphinx/environment/adapters/toctree.py5
-rw-r--r--sphinx/environment/collectors/__init__.py5
-rw-r--r--sphinx/environment/collectors/indexentries.py63
-rw-r--r--sphinx/environment/collectors/toctree.py7
-rw-r--r--sphinx/events.py32
-rw-r--r--sphinx/ext/apidoc.py71
-rw-r--r--sphinx/ext/autodoc/__init__.py75
-rw-r--r--sphinx/ext/autodoc/directive.py24
-rw-r--r--sphinx/ext/autodoc/importer.py45
-rw-r--r--sphinx/ext/autodoc/mock.py6
-rw-r--r--sphinx/ext/autosummary/__init__.py61
-rw-r--r--sphinx/ext/autosummary/generate.py47
-rw-r--r--sphinx/ext/doctest.py16
-rw-r--r--sphinx/ext/imgmath.py45
-rw-r--r--sphinx/ext/jsmath.py33
-rw-r--r--sphinx/ext/mathjax.py3
-rw-r--r--sphinx/ext/napoleon/docstring.py7
-rw-r--r--sphinx/ext/todo.py106
-rw-r--r--sphinx/extension.py5
-rw-r--r--sphinx/io.py34
-rw-r--r--sphinx/jinja2glue.py5
-rw-r--r--sphinx/parsers.py9
-rw-r--r--sphinx/project.py6
-rw-r--r--sphinx/pycode/__init__.py27
-rw-r--r--sphinx/pycode/ast.py35
-rw-r--r--sphinx/pycode/parser.py17
-rw-r--r--sphinx/registry.py7
-rw-r--r--sphinx/roles.py259
-rw-r--r--sphinx/search/__init__.py16
-rw-r--r--sphinx/setup_command.py6
-rw-r--r--sphinx/templates/quickstart/Makefile_t1
-rw-r--r--sphinx/templates/quickstart/make.bat_t1
-rw-r--r--sphinx/testing/fixtures.py7
-rw-r--r--sphinx/testing/util.py11
-rw-r--r--sphinx/themes/basic/layout.html2
-rw-r--r--sphinx/themes/basic/static/basic.css_t2
-rw-r--r--sphinx/themes/basic/static/searchtools.js2
-rw-r--r--sphinx/theming.py5
-rw-r--r--sphinx/transforms/__init__.py23
-rw-r--r--sphinx/transforms/i18n.py16
-rw-r--r--sphinx/transforms/post_transforms/code.py8
-rw-r--r--sphinx/transforms/references.py5
-rw-r--r--sphinx/util/__init__.py203
-rw-r--r--sphinx/util/cfamily.py23
-rw-r--r--sphinx/util/compat.py27
-rw-r--r--sphinx/util/docfields.py30
-rw-r--r--sphinx/util/docutils.py41
-rw-r--r--sphinx/util/fileutil.py5
-rw-r--r--sphinx/util/i18n.py91
-rw-r--r--sphinx/util/images.py8
-rw-r--r--sphinx/util/inspect.py173
-rw-r--r--sphinx/util/inventory.py5
-rw-r--r--sphinx/util/jsonimpl.py45
-rw-r--r--sphinx/util/logging.py7
-rw-r--r--sphinx/util/nodes.py39
-rw-r--r--sphinx/util/osutil.py28
-rw-r--r--sphinx/util/pycompat.py66
-rw-r--r--sphinx/util/smartypants.py5
-rw-r--r--sphinx/util/texescape.py10
-rw-r--r--sphinx/util/typing.py130
-rw-r--r--sphinx/versioning.py5
-rw-r--r--sphinx/writers/html.py16
-rw-r--r--sphinx/writers/html5.py46
-rw-r--r--sphinx/writers/latex.py122
-rw-r--r--sphinx/writers/manpage.py11
-rw-r--r--sphinx/writers/texinfo.py7
-rw-r--r--sphinx/writers/text.py6
98 files changed, 566 insertions, 2903 deletions
diff --git a/sphinx/__init__.py b/sphinx/__init__.py
index 23a867fa0..c44e7db13 100644
--- a/sphinx/__init__.py
+++ b/sphinx/__init__.py
@@ -19,11 +19,6 @@ from subprocess import PIPE
from .deprecation import RemovedInNextVersionWarning
-if False:
- # For type annotation
- from typing import Any # NOQA
-
-
# by default, all DeprecationWarning under sphinx package will be emit.
# Users can avoid this by using environment variable: PYTHONWARNINGS=
if 'PYTHONWARNINGS' not in os.environ:
@@ -32,8 +27,8 @@ if 'PYTHONWARNINGS' not in os.environ:
warnings.filterwarnings('ignore', "'U' mode is deprecated",
DeprecationWarning, module='docutils.io')
-__version__ = '3.5.0+'
-__released__ = '3.5.0' # used when Sphinx builds its own docs
+__version__ = '4.0.0+'
+__released__ = '4.0.0' # used when Sphinx builds its own docs
#: Version info for better programmatic use.
#:
@@ -43,7 +38,7 @@ __released__ = '3.5.0' # used when Sphinx builds its own docs
#:
#: .. versionadded:: 1.2
#: Before version 1.2, check the string ``sphinx.__version__``.
-version_info = (3, 5, 0, 'beta', 0)
+version_info = (4, 0, 0, 'beta', 0)
package_dir = path.abspath(path.dirname(__file__))
@@ -57,8 +52,8 @@ if __version__.endswith('+'):
try:
ret = subprocess.run(['git', 'show', '-s', '--pretty=format:%h'],
cwd=package_dir,
- stdout=PIPE, stderr=PIPE)
+ stdout=PIPE, stderr=PIPE, encoding='ascii')
if ret.stdout:
- __display_version__ += '/' + ret.stdout.decode('ascii').strip()
+ __display_version__ += '/' + ret.stdout.strip()
except Exception:
pass
diff --git a/sphinx/addnodes.py b/sphinx/addnodes.py
index 5f371e46b..9bcfaaabf 100644
--- a/sphinx/addnodes.py
+++ b/sphinx/addnodes.py
@@ -8,16 +8,12 @@
:license: BSD, see LICENSE for details.
"""
-import warnings
-from typing import Any, Dict, List, Sequence
+from typing import TYPE_CHECKING, Any, Dict, List, Sequence
from docutils import nodes
-from docutils.nodes import Element, Node
+from docutils.nodes import Element
-from sphinx.deprecation import RemovedInSphinx40Warning
-
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -362,20 +358,6 @@ class literal_strong(nodes.strong, not_smartquotable):
"""
-class abbreviation(nodes.abbreviation):
- """Node for abbreviations with explanations.
-
- .. deprecated:: 2.0
- """
-
- def __init__(self, rawsource: str = '', text: str = '',
- *children: Node, **attributes: Any) -> None:
- warnings.warn("abbrevition node for Sphinx was replaced by docutils'.",
- RemovedInSphinx40Warning, stacklevel=2)
-
- super().__init__(rawsource, text, *children, **attributes)
-
-
class manpage(nodes.Inline, nodes.FixedTextElement):
"""Node for references to manpages."""
diff --git a/sphinx/application.py b/sphinx/application.py
index 54a2603aa..710d7701a 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -14,11 +14,10 @@ import os
import pickle
import platform
import sys
-import warnings
from collections import deque
from io import StringIO
from os import path
-from typing import IO, Any, Callable, Dict, List, Optional, Tuple, Union
+from typing import IO, TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union
from docutils import nodes
from docutils.nodes import Element, TextElement
@@ -30,14 +29,13 @@ from pygments.lexer import Lexer
import sphinx
from sphinx import locale, package_dir
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.domains import Domain, Index
from sphinx.environment import BuildEnvironment
from sphinx.environment.collectors import EnvironmentCollector
from sphinx.errors import ApplicationError, ConfigError, VersionRequirementError
from sphinx.events import EventManager
from sphinx.extension import Extension
-from sphinx.highlighting import lexer_classes, lexers
+from sphinx.highlighting import lexer_classes
from sphinx.locale import __
from sphinx.project import Project
from sphinx.registry import SphinxComponentRegistry
@@ -52,10 +50,7 @@ from sphinx.util.osutil import abspath, ensuredir, relpath
from sphinx.util.tags import Tags
from sphinx.util.typing import RoleFunction, TitleGetter
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from docutils.nodes import Node # NOQA
from sphinx.builders import Builder
@@ -916,13 +911,6 @@ class Sphinx:
"""
self.registry.add_post_transform(transform)
- def add_javascript(self, filename: str, **kwargs: Any) -> None:
- """An alias of :meth:`add_js_file`."""
- warnings.warn('The app.add_javascript() is deprecated. '
- 'Please use app.add_js_file() instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- self.add_js_file(filename, **kwargs)
-
def add_js_file(self, filename: str, priority: int = 500, **kwargs: Any) -> None:
"""Register a JavaScript file to include in the HTML output.
@@ -1002,6 +990,8 @@ class Sphinx:
* - Priority
- Main purpose in Sphinx
+ * - 200
+ - default priority for built-in CSS files
* - 500
- default priority for extensions
* - 800
@@ -1031,24 +1021,6 @@ class Sphinx:
if hasattr(self.builder, 'add_css_file'):
self.builder.add_css_file(filename, priority=priority, **kwargs) # type: ignore
- def add_stylesheet(self, filename: str, alternate: bool = False, title: str = None
- ) -> 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[str, Any]
- if alternate:
- attributes['rel'] = 'alternate stylesheet'
- else:
- attributes['rel'] = 'stylesheet'
-
- if title:
- attributes['title'] = title
-
- self.add_css_file(filename, **attributes)
-
def add_latex_package(self, packagename: str, options: str = None,
after_hyperref: bool = False) -> None:
r"""Register a package to include in the LaTeX source code.
@@ -1072,7 +1044,7 @@ class Sphinx:
"""
self.registry.add_latex_package(packagename, options, after_hyperref)
- def add_lexer(self, alias: str, lexer: Union[Lexer, "Type[Lexer]"]) -> None:
+ def add_lexer(self, alias: str, lexer: Type[Lexer]) -> None:
"""Register a new lexer for source code.
Use *lexer* to highlight code blocks with the given language *alias*.
@@ -1083,13 +1055,7 @@ class Sphinx:
still supported until Sphinx-3.x.
"""
logger.debug('[app] adding lexer: %r', (alias, lexer))
- if isinstance(lexer, Lexer):
- warnings.warn('app.add_lexer() API changed; '
- 'Please give lexer class instead of instance',
- RemovedInSphinx40Warning, stacklevel=2)
- lexers[alias] = lexer
- else:
- lexer_classes[alias] = lexer
+ lexer_classes[alias] = lexer
def add_autodocumenter(self, cls: Any, override: bool = False) -> None:
"""Register a new documenter class for the autodoc extension.
diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py
index 58030bb6c..7e361652f 100644
--- a/sphinx/builders/__init__.py
+++ b/sphinx/builders/__init__.py
@@ -11,7 +11,7 @@
import pickle
import time
from os import path
-from typing import Any, Dict, Iterable, List, Sequence, Set, Tuple, Union
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence, Set, Tuple, Type, Union
from docutils import nodes
from docutils.nodes import Node
@@ -40,10 +40,7 @@ try:
except ImportError:
multiprocessing = None
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
diff --git a/sphinx/builders/_epub_base.py b/sphinx/builders/_epub_base.py
index 7df3f8df5..453474e09 100644
--- a/sphinx/builders/_epub_base.py
+++ b/sphinx/builders/_epub_base.py
@@ -11,10 +11,8 @@
import html
import os
import re
-import warnings
-from collections import namedtuple
from os import path
-from typing import Any, Dict, List, Set, Tuple
+from typing import Any, Dict, List, NamedTuple, Set, Tuple
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile
from docutils import nodes
@@ -23,7 +21,6 @@ from docutils.utils import smartquotes
from sphinx import addnodes
from sphinx.builders.html import BuildInfo, StandaloneHTMLBuilder
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import __
from sphinx.util import logging, status_iterator
from sphinx.util.fileutil import copy_asset_file
@@ -84,10 +81,30 @@ VECTOR_GRAPHICS_EXTENSIONS = ('.svg',)
REFURI_RE = re.compile("([^#:]*#)(.*)")
-ManifestItem = namedtuple('ManifestItem', ['href', 'id', 'media_type'])
-Spine = namedtuple('Spine', ['idref', 'linear'])
-Guide = namedtuple('Guide', ['type', 'title', 'uri'])
-NavPoint = namedtuple('NavPoint', ['navpoint', 'playorder', 'text', 'refuri', 'children'])
+class ManifestItem(NamedTuple):
+ href: str
+ id: str
+ media_type: str
+
+
+class Spine(NamedTuple):
+ idref: str
+ linear: bool
+
+
+class Guide(NamedTuple):
+ type: str
+ title: str
+ uri: str
+
+
+class NavPoint(NamedTuple):
+ navpoint: str
+ playorder: int
+ text: str
+ refuri: str
+ children: List[Any] # mypy does not support recursive types
+ # https://github.com/python/mypy/issues/7069
def sphinx_smarty_pants(t: str, language: str = 'en') -> str:
@@ -168,18 +185,6 @@ class EpubBuilder(StandaloneHTMLBuilder):
self.id_cache[name] = id
return id
- def esc(self, name: str) -> str:
- """Replace all characters not allowed in text an attribute values."""
- warnings.warn(
- '%s.esc() is deprecated. Use html.escape() instead.' % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
- name = name.replace('&', '&')
- name = name.replace('<', '&lt;')
- name = name.replace('>', '&gt;')
- name = name.replace('"', '&quot;')
- name = name.replace('\'', '&#39;')
- return name
-
def get_refnodes(self, doctree: Node, result: List[Dict[str, Any]]) -> List[Dict[str, Any]]: # NOQA
"""Collect section titles, their depth in the toc and the refuri."""
# XXX: is there a better way than checking the attribute
@@ -461,30 +466,17 @@ class EpubBuilder(StandaloneHTMLBuilder):
addctx['doctype'] = self.doctype
super().handle_page(pagename, addctx, templatename, outfilename, event_arg)
- def build_mimetype(self, outdir: str = None, outname: str = 'mimetype') -> None:
+ def build_mimetype(self) -> None:
"""Write the metainfo file mimetype."""
- if outdir:
- warnings.warn('The arguments of EpubBuilder.build_mimetype() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- else:
- outdir = self.outdir
+ logger.info(__('writing mimetype file...'))
+ copy_asset_file(path.join(self.template_dir, 'mimetype'), self.outdir)
- logger.info(__('writing %s file...'), outname)
- copy_asset_file(path.join(self.template_dir, 'mimetype'),
- path.join(outdir, outname))
-
- def build_container(self, outdir: str = None, outname: str = 'META-INF/container.xml') -> None: # NOQA
+ def build_container(self, outname: str = 'META-INF/container.xml') -> None: # NOQA
"""Write the metainfo file META-INF/container.xml."""
- if outdir:
- warnings.warn('The arguments of EpubBuilder.build_container() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- else:
- outdir = self.outdir
-
- logger.info(__('writing %s file...'), outname)
- filename = path.join(outdir, outname)
- ensuredir(path.dirname(filename))
- copy_asset_file(path.join(self.template_dir, 'container.xml'), filename)
+ logger.info(__('writing META-INF/container.xml file...'))
+ outdir = path.join(self.outdir, 'META-INF')
+ ensuredir(outdir)
+ copy_asset_file(path.join(self.template_dir, 'container.xml'), outdir)
def content_metadata(self) -> Dict[str, Any]:
"""Create a dictionary with all metadata for the content.opf
@@ -505,23 +497,17 @@ class EpubBuilder(StandaloneHTMLBuilder):
metadata['guides'] = []
return metadata
- def build_content(self, outdir: str = None, outname: str = 'content.opf') -> None:
+ def build_content(self) -> None:
"""Write the metainfo file content.opf It contains bibliographic data,
a file list and the spine (the reading order).
"""
- if outdir:
- warnings.warn('The arguments of EpubBuilder.build_content() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- else:
- outdir = self.outdir
-
- logger.info(__('writing %s file...'), outname)
+ logger.info(__('writing content.opf file...'))
metadata = self.content_metadata()
# files
- if not outdir.endswith(os.sep):
- outdir += os.sep
- olen = len(outdir)
+ if not self.outdir.endswith(os.sep):
+ self.outdir += os.sep
+ olen = len(self.outdir)
self.files = [] # type: List[str]
self.ignored_files = ['.buildinfo', 'mimetype', 'content.opf',
'toc.ncx', 'META-INF/container.xml',
@@ -530,7 +516,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
self.config.epub_exclude_files
if not self.use_index:
self.ignored_files.append('genindex' + self.out_suffix)
- for root, dirs, files in os.walk(outdir):
+ for root, dirs, files in os.walk(self.outdir):
dirs.sort()
for fn in sorted(files):
filename = path.join(root, fn)[olen:]
@@ -620,9 +606,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
html.escape(self.refnodes[0]['refuri'])))
# write the project file
- copy_asset_file(path.join(self.template_dir, 'content.opf_t'),
- path.join(outdir, outname),
- metadata)
+ copy_asset_file(path.join(self.template_dir, 'content.opf_t'), self.outdir, metadata)
def new_navpoint(self, node: Dict[str, Any], level: int, incr: bool = True) -> NavPoint:
"""Create a new entry in the toc from the node at given level."""
@@ -640,7 +624,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
the parent node is reinserted in the subnav.
"""
navstack = [] # type: List[NavPoint]
- navstack.append(NavPoint('dummy', '', '', '', []))
+ navstack.append(NavPoint('dummy', 0, '', '', []))
level = 0
lastnode = None
for node in nodes:
@@ -688,15 +672,9 @@ class EpubBuilder(StandaloneHTMLBuilder):
metadata['navpoints'] = navpoints
return metadata
- def build_toc(self, outdir: str = None, outname: str = 'toc.ncx') -> None:
+ def build_toc(self) -> None:
"""Write the metainfo file toc.ncx."""
- if outdir:
- warnings.warn('The arguments of EpubBuilder.build_toc() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- else:
- outdir = self.outdir
-
- logger.info(__('writing %s file...'), outname)
+ logger.info(__('writing toc.ncx file...'))
if self.config.epub_tocscope == 'default':
doctree = self.env.get_and_resolve_doctree(self.config.master_doc,
@@ -711,28 +689,21 @@ class EpubBuilder(StandaloneHTMLBuilder):
navpoints = self.build_navpoints(refnodes)
level = max(item['level'] for item in self.refnodes)
level = min(level, self.config.epub_tocdepth)
- copy_asset_file(path.join(self.template_dir, 'toc.ncx_t'),
- path.join(outdir, outname),
+ copy_asset_file(path.join(self.template_dir, 'toc.ncx_t'), self.outdir,
self.toc_metadata(level, navpoints))
- def build_epub(self, outdir: str = None, outname: str = None) -> None:
+ def build_epub(self) -> None:
"""Write the epub file.
It is a zip file with the mimetype file stored uncompressed as the first
entry.
"""
- if outdir:
- warnings.warn('The arguments of EpubBuilder.build_epub() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- else:
- outdir = self.outdir
- outname = self.config.epub_basename + '.epub'
-
+ outname = self.config.epub_basename + '.epub'
logger.info(__('writing %s file...'), outname)
- epub_filename = path.join(outdir, outname)
+ epub_filename = path.join(self.outdir, outname)
with ZipFile(epub_filename, 'w', ZIP_DEFLATED) as epub:
- epub.write(path.join(outdir, 'mimetype'), 'mimetype', ZIP_STORED)
+ epub.write(path.join(self.outdir, 'mimetype'), 'mimetype', ZIP_STORED)
for filename in ['META-INF/container.xml', 'content.opf', 'toc.ncx']:
- epub.write(path.join(outdir, filename), filename, ZIP_DEFLATED)
+ epub.write(path.join(self.outdir, filename), filename, ZIP_DEFLATED)
for filename in self.files:
- epub.write(path.join(outdir, filename), filename, ZIP_DEFLATED)
+ epub.write(path.join(self.outdir, filename), filename, ZIP_DEFLATED)
diff --git a/sphinx/builders/applehelp.py b/sphinx/builders/applehelp.py
deleted file mode 100644
index bfc8c8dc8..000000000
--- a/sphinx/builders/applehelp.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""
- sphinx.builders.applehelp
- ~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Build Apple help books.
-
- :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-from typing import Any, Dict
-
-from sphinxcontrib.applehelp import (AppleHelpBuilder, AppleHelpCodeSigningFailed,
- AppleHelpIndexerFailed)
-
-from sphinx.application import Sphinx
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
-
-deprecated_alias('sphinx.builders.applehelp',
- {
- 'AppleHelpCodeSigningFailed': AppleHelpCodeSigningFailed,
- 'AppleHelpIndexerFailed': AppleHelpIndexerFailed,
- 'AppleHelpBuilder': AppleHelpBuilder,
- },
- RemovedInSphinx40Warning,
- {
- 'AppleHelpCodeSigningFailed':
- 'sphinxcontrib.applehelp.AppleHelpCodeSigningFailed',
- 'AppleHelpIndexerFailed':
- 'sphinxcontrib.applehelp.AppleHelpIndexerFailed',
- 'AppleHelpBuilder': 'sphinxcontrib.applehelp.AppleHelpBuilder',
- })
-
-
-def setup(app: Sphinx) -> Dict[str, Any]:
- warnings.warn('sphinx.builders.applehelp has been moved to sphinxcontrib-applehelp.',
- RemovedInSphinx40Warning, stacklevel=2)
- app.setup_extension('sphinxcontrib.applehelp')
-
- return {
- 'version': 'builtin',
- 'parallel_read_safe': True,
- 'parallel_write_safe': True,
- }
diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py
deleted file mode 100644
index 9625b62f4..000000000
--- a/sphinx/builders/devhelp.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""
- sphinx.builders.devhelp
- ~~~~~~~~~~~~~~~~~~~~~~~
-
- Build HTML documentation and Devhelp_ support files.
-
- .. _Devhelp: https://wiki.gnome.org/Apps/Devhelp
-
- :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-from typing import Any, Dict
-
-from sphinxcontrib.devhelp import DevhelpBuilder
-
-from sphinx.application import Sphinx
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
-
-deprecated_alias('sphinx.builders.devhelp',
- {
- 'DevhelpBuilder': DevhelpBuilder,
- },
- RemovedInSphinx40Warning,
- {
- 'DevhelpBuilder': 'sphinxcontrib.devhelp.DevhelpBuilder'
- })
-
-
-def setup(app: Sphinx) -> Dict[str, Any]:
- warnings.warn('sphinx.builders.devhelp has been moved to sphinxcontrib-devhelp.',
- RemovedInSphinx40Warning)
- app.setup_extension('sphinxcontrib.devhelp')
-
- return {
- 'version': 'builtin',
- 'parallel_read_safe': True,
- 'parallel_write_safe': True,
- }
diff --git a/sphinx/builders/epub3.py b/sphinx/builders/epub3.py
index d1cf64eb3..8a0dab303 100644
--- a/sphinx/builders/epub3.py
+++ b/sphinx/builders/epub3.py
@@ -10,16 +10,13 @@
"""
import html
-import warnings
-from collections import namedtuple
from os import path
-from typing import Any, Dict, List, Set, Tuple
+from typing import Any, Dict, List, NamedTuple, Set, Tuple
from sphinx import package_dir
from sphinx.application import Sphinx
from sphinx.builders import _epub_base
from sphinx.config import ENUM, Config
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import __
from sphinx.util import logging, xmlname_checker
from sphinx.util.fileutil import copy_asset_file
@@ -29,7 +26,12 @@ from sphinx.util.osutil import make_filename
logger = logging.getLogger(__name__)
-NavPoint = namedtuple('NavPoint', ['text', 'refuri', 'children'])
+class NavPoint(NamedTuple):
+ text: str
+ refuri: str
+ children: List[Any] # mypy does not support recursive types
+ # https://github.com/python/mypy/issues/7069
+
# writing modes
PAGE_PROGRESSION_DIRECTIONS = {
@@ -81,10 +83,6 @@ class Epub3Builder(_epub_base.EpubBuilder):
self.build_toc()
self.build_epub()
- def validate_config_value(self) -> None:
- warnings.warn('Epub3Builder.validate_config_value() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
def content_metadata(self) -> Dict:
"""Create a dictionary with all metadata for the content.opf
file properly escaped.
@@ -162,15 +160,9 @@ class Epub3Builder(_epub_base.EpubBuilder):
metadata['navlist'] = navlist
return metadata
- def build_navigation_doc(self, outdir: str = None, outname: str = 'nav.xhtml') -> None:
+ def build_navigation_doc(self) -> None:
"""Write the metainfo file nav.xhtml."""
- if outdir:
- warnings.warn('The arguments of Epub3Builder.build_navigation_doc() '
- 'is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
- else:
- outdir = self.outdir
-
- logger.info(__('writing %s file...'), outname)
+ logger.info(__('writing nav.xhtml file...'))
if self.config.epub_tocscope == 'default':
doctree = self.env.get_and_resolve_doctree(
@@ -182,13 +174,12 @@ class Epub3Builder(_epub_base.EpubBuilder):
# 'includehidden'
refnodes = self.refnodes
navlist = self.build_navlist(refnodes)
- copy_asset_file(path.join(self.template_dir, 'nav.xhtml_t'),
- path.join(outdir, outname),
+ copy_asset_file(path.join(self.template_dir, 'nav.xhtml_t'), self.outdir,
self.navigation_doc_metadata(navlist))
# Add nav.xhtml to epub file
- if outname not in self.files:
- self.files.append(outname)
+ if 'nav.xhtml' not in self.files:
+ self.files.append('nav.xhtml')
def validate_config_values(app: Sphinx) -> None:
diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py
index 75c95c0bc..78ae06b74 100644
--- a/sphinx/builders/gettext.py
+++ b/sphinx/builders/gettext.py
@@ -13,7 +13,7 @@ from collections import OrderedDict, defaultdict
from datetime import datetime, timedelta, tzinfo
from os import getenv, path, walk
from time import time
-from typing import Any, Dict, Generator, Iterable, List, Set, Tuple, Union
+from typing import Any, DefaultDict, Dict, Generator, Iterable, List, Set, Tuple, Union
from uuid import uuid4
from docutils import nodes
@@ -33,33 +33,8 @@ from sphinx.util.osutil import canon_path, ensuredir, relpath
from sphinx.util.tags import Tags
from sphinx.util.template import SphinxRenderer
-if False:
- # For type annotation
- from typing import DefaultDict # for python3.5.1
-
logger = logging.getLogger(__name__)
-POHEADER = r"""
-# SOME DESCRIPTIVE TITLE.
-# Copyright (C) %(copyright)s
-# This file is distributed under the same license as the %(project)s package.
-# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
-#
-#, fuzzy
-msgid ""
-msgstr ""
-"Project-Id-Version: %(project)s %(version)s\n"
-"Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: %(ctime)s\n"
-"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
-"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
-"Language-Team: LANGUAGE <LL@li.org>\n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=UTF-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-
-"""[1:] # RemovedInSphinx40Warning
-
class Message:
"""An entry of translatable message."""
diff --git a/sphinx/builders/html/__init__.py b/sphinx/builders/html/__init__.py
index 4bb7ee510..faee0a976 100644
--- a/sphinx/builders/html/__init__.py
+++ b/sphinx/builders/html/__init__.py
@@ -13,9 +13,9 @@ import os
import posixpath
import re
import sys
-import warnings
+from datetime import datetime
from os import path
-from typing import IO, Any, Dict, Iterable, Iterator, List, Set, Tuple
+from typing import IO, Any, Dict, Iterable, Iterator, List, Set, Tuple, Type
from urllib.parse import quote
from docutils import nodes
@@ -29,7 +29,6 @@ from sphinx import __display_version__, package_dir
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.config import ENUM, Config
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.domains import Domain, Index, IndexEntry
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.environment.adapters.indexentries import IndexEntries
@@ -49,11 +48,6 @@ from sphinx.util.osutil import copyfile, ensuredir, os_path, relative_uri
from sphinx.util.tags import Tags
from sphinx.writers.html import HTMLTranslator, HTMLWriter
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-
# HTML5 Writer is available or not
if is_html5_writer_available():
from sphinx.writers.html5 import HTML5Translator
@@ -256,6 +250,14 @@ class StandaloneHTMLBuilder(Builder):
return jsfile
return None
+ def _get_style_filename(self) -> str:
+ if self.config.html_style is not None:
+ return self.config.html_style
+ elif self.theme:
+ return self.theme.get_config('theme', 'stylesheet')
+ else:
+ return 'default.css'
+
def get_theme_config(self) -> Tuple[str, Dict]:
return self.config.html_theme, self.config.html_theme_options
@@ -291,6 +293,9 @@ class StandaloneHTMLBuilder(Builder):
self.dark_highlighter = None
def init_css_files(self) -> None:
+ self.add_css_file('pygments.css', priority=200)
+ self.add_css_file(self._get_style_filename(), priority=200)
+
for filename, attrs in self.app.registry.css_files:
self.add_css_file(filename, **attrs)
@@ -358,6 +363,7 @@ class StandaloneHTMLBuilder(Builder):
buildinfo = BuildInfo.load(fp)
if self.build_info != buildinfo:
+ logger.debug('[build target] did not match: build_info ')
yield from self.env.found_docs
return
except ValueError as exc:
@@ -372,6 +378,7 @@ class StandaloneHTMLBuilder(Builder):
template_mtime = 0
for docname in self.env.found_docs:
if docname not in self.env.all_docs:
+ logger.debug('[build target] did not in env: %r', docname)
yield docname
continue
targetname = self.get_outfilename(docname)
@@ -383,6 +390,14 @@ class StandaloneHTMLBuilder(Builder):
srcmtime = max(path.getmtime(self.env.doc2path(docname)),
template_mtime)
if srcmtime > targetmtime:
+ logger.debug(
+ '[build target] targetname %r(%s), template(%s), docname %r(%s)',
+ targetname,
+ datetime.utcfromtimestamp(targetmtime),
+ datetime.utcfromtimestamp(template_mtime),
+ docname,
+ datetime.utcfromtimestamp(path.getmtime(self.env.doc2path(docname))),
+ )
yield docname
except OSError:
# source doesn't exist anymore
@@ -470,13 +485,6 @@ class StandaloneHTMLBuilder(Builder):
self._script_files = list(self.script_files)
self._css_files = list(self.css_files)
- if self.config.html_style is not None:
- stylename = self.config.html_style
- elif self.theme:
- stylename = self.theme.get_config('theme', 'stylesheet')
- else:
- stylename = 'default.css'
-
self.globalcontext = {
'embedded': self.embedded,
'project': self.config.project,
@@ -499,7 +507,7 @@ class StandaloneHTMLBuilder(Builder):
'language': self.config.language,
'css_files': self.css_files,
'sphinx_version': __display_version__,
- 'style': stylename,
+ 'style': self._get_style_filename(),
'rellinks': rellinks,
'builder': self.name,
'parents': [],
@@ -885,21 +893,11 @@ class StandaloneHTMLBuilder(Builder):
# only index pages with title
if self.indexer is not None and title:
filename = self.env.doc2path(pagename, base=None)
- try:
- metadata = self.env.metadata.get(pagename, {})
- if 'nosearch' in metadata:
- self.indexer.feed(pagename, filename, '', new_document(''))
- else:
- self.indexer.feed(pagename, filename, title, doctree)
- except TypeError:
- # fallback for old search-adapters
- self.indexer.feed(pagename, title, doctree) # type: ignore
- indexer_name = self.indexer.__class__.__name__
- warnings.warn(
- 'The %s.feed() method signature is deprecated. Update to '
- '%s.feed(docname, filename, title, doctree).' % (
- indexer_name, indexer_name),
- RemovedInSphinx40Warning, stacklevel=2)
+ metadata = self.env.metadata.get(pagename, {})
+ if 'nosearch' in metadata:
+ self.indexer.feed(pagename, filename, '', new_document(''))
+ else:
+ self.indexer.feed(pagename, filename, title, doctree)
def _get_local_toctree(self, docname: str, collapse: bool = True, **kwargs: Any) -> str:
if 'includehidden' not in kwargs:
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
deleted file mode 100644
index 08719712c..000000000
--- a/sphinx/builders/htmlhelp.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""
- sphinx.builders.htmlhelp
- ~~~~~~~~~~~~~~~~~~~~~~~~
-
- Build HTML help support files.
- Parts adapted from Python's Doc/tools/prechm.py.
-
- :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-from typing import Any, Dict
-
-from sphinxcontrib.htmlhelp import (HTMLHelpBuilder, chm_htmlescape, chm_locales,
- default_htmlhelp_basename)
-
-from sphinx.application import Sphinx
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
-
-deprecated_alias('sphinx.builders.htmlhelp',
- {
- 'chm_locales': chm_locales,
- 'chm_htmlescape': chm_htmlescape,
- 'HTMLHelpBuilder': HTMLHelpBuilder,
- 'default_htmlhelp_basename': default_htmlhelp_basename,
- },
- RemovedInSphinx40Warning,
- {
- 'chm_locales': 'sphinxcontrib.htmlhelp.chm_locales',
- 'chm_htmlescape': 'sphinxcontrib.htmlhelp.chm_htmlescape',
- 'HTMLHelpBuilder': 'sphinxcontrib.htmlhelp.HTMLHelpBuilder',
- 'default_htmlhelp_basename':
- 'sphinxcontrib.htmlhelp.default_htmlhelp_basename',
- })
-
-
-def setup(app: Sphinx) -> Dict[str, Any]:
- warnings.warn('sphinx.builders.htmlhelp has been moved to sphinxcontrib-htmlhelp.',
- RemovedInSphinx40Warning, stacklevel=2)
- app.setup_extension('sphinxcontrib.htmlhelp')
-
- return {
- 'version': 'builtin',
- 'parallel_read_safe': True,
- 'parallel_write_safe': True,
- }
diff --git a/sphinx/builders/latex/__init__.py b/sphinx/builders/latex/__init__.py
index 5c7a7412a..dc5b66518 100644
--- a/sphinx/builders/latex/__init__.py
+++ b/sphinx/builders/latex/__init__.py
@@ -24,7 +24,7 @@ from sphinx.builders.latex.constants import ADDITIONAL_SETTINGS, DEFAULT_SETTING
from sphinx.builders.latex.theming import Theme, ThemeFactory
from sphinx.builders.latex.util import ExtBabel
from sphinx.config import ENUM, Config
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.errors import NoUri, SphinxError
from sphinx.locale import _, __
@@ -261,7 +261,6 @@ class LaTeXBuilder(Builder):
defaults=self.env.settings,
components=(docwriter,),
read_config_files=True).get_default_values() # type: Any
- patch_settings(docsettings)
self.init_document_data()
self.write_stylesheet()
@@ -364,10 +363,6 @@ class LaTeXBuilder(Builder):
pendingnode.replace_self(newnodes)
return largetree
- def apply_transforms(self, doctree: nodes.document) -> None:
- warnings.warn('LaTeXBuilder.apply_transforms() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
def finish(self) -> None:
self.copy_image_files()
self.write_message_catalog()
@@ -462,44 +457,6 @@ class LaTeXBuilder(Builder):
return self.app.registry.latex_packages_after_hyperref
-def patch_settings(settings: Any) -> Any:
- """Make settings object to show deprecation messages."""
-
- class Values(type(settings)): # type: ignore
- @property
- def author(self) -> str:
- warnings.warn('settings.author is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return self._author
-
- @property
- def title(self) -> str:
- warnings.warn('settings.title is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return self._title
-
- @property
- def contentsname(self) -> str:
- warnings.warn('settings.contentsname is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return self._contentsname
-
- @property
- def docname(self) -> str:
- warnings.warn('settings.docname is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return self._docname
-
- @property
- def docclass(self) -> str:
- warnings.warn('settings.docclass is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return self._docclass
-
- # dynamic subclassing
- settings.__class__ = Values
-
-
def validate_config_values(app: Sphinx, config: Config) -> None:
for key in list(config.latex_elements):
if key not in DEFAULT_SETTINGS:
@@ -525,7 +482,7 @@ def install_packages_for_ja(app: Sphinx) -> None:
def default_latex_engine(config: Config) -> str:
""" Better default latex_engine settings for specific languages. """
if config.language == 'ja':
- return 'platex'
+ return 'uplatex'
elif (config.language or '').startswith('zh'):
return 'xelatex'
elif config.language == 'el':
diff --git a/sphinx/builders/manpage.py b/sphinx/builders/manpage.py
index 292f495de..e1e1b77f0 100644
--- a/sphinx/builders/manpage.py
+++ b/sphinx/builders/manpage.py
@@ -118,7 +118,7 @@ def setup(app: Sphinx) -> Dict[str, Any]:
app.add_config_value('man_pages', default_man_pages, None)
app.add_config_value('man_show_urls', False, None)
- app.add_config_value('man_make_section_directory', False, None)
+ app.add_config_value('man_make_section_directory', True, None)
return {
'version': 'builtin',
diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py
deleted file mode 100644
index c5219dd75..000000000
--- a/sphinx/builders/qthelp.py
+++ /dev/null
@@ -1,42 +0,0 @@
-"""
- sphinx.builders.qthelp
- ~~~~~~~~~~~~~~~~~~~~~~
-
- Build input files for the Qt collection generator.
-
- :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-from typing import Any, Dict
-
-from sphinxcontrib.qthelp import QtHelpBuilder, render_file
-
-import sphinx
-from sphinx.application import Sphinx
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
-
-deprecated_alias('sphinx.builders.qthelp',
- {
- 'render_file': render_file,
- 'QtHelpBuilder': QtHelpBuilder,
- },
- RemovedInSphinx40Warning,
- {
- 'render_file': 'sphinxcontrib.qthelp.render_file',
- 'QtHelpBuilder': 'sphinxcontrib.qthelp.QtHelpBuilder',
- })
-
-
-def setup(app: Sphinx) -> Dict[str, Any]:
- warnings.warn('sphinx.builders.qthelp has been moved to sphinxcontrib-qthelp.',
- RemovedInSphinx40Warning)
-
- app.setup_extension('sphinxcontrib.qthelp')
-
- return {
- 'version': sphinx.__display_version__,
- 'parallel_read_safe': True,
- 'parallel_write_safe': True,
- }
diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py
index 1b051119b..88dfe83a9 100644
--- a/sphinx/builders/xml.py
+++ b/sphinx/builders/xml.py
@@ -9,7 +9,7 @@
"""
from os import path
-from typing import Any, Dict, Iterator, Set, Union
+from typing import Any, Dict, Iterator, Set, Type, Union
from docutils import nodes
from docutils.io import StringOutput
@@ -23,11 +23,6 @@ from sphinx.util import logging
from sphinx.util.osutil import ensuredir, os_path
from sphinx.writers.xml import PseudoXMLWriter, XMLWriter
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-
logger = logging.getLogger(__name__)
diff --git a/sphinx/cmd/make_mode.py b/sphinx/cmd/make_mode.py
index aaa40fba0..242329ae0 100644
--- a/sphinx/cmd/make_mode.py
+++ b/sphinx/cmd/make_mode.py
@@ -50,6 +50,7 @@ BUILDERS = [
("", "doctest", "to run all doctests embedded in the documentation "
"(if enabled)"),
("", "coverage", "to run coverage check of the documentation (if enabled)"),
+ ("", "clean", "to remove everything in the build directory"),
]
diff --git a/sphinx/cmd/quickstart.py b/sphinx/cmd/quickstart.py
index 7d1c48f31..0972769ee 100644
--- a/sphinx/cmd/quickstart.py
+++ b/sphinx/cmd/quickstart.py
@@ -11,13 +11,11 @@
import argparse
import locale
import os
-import re
import sys
import time
-import warnings
from collections import OrderedDict
from os import path
-from typing import Any, Callable, Dict, List, Pattern, Union
+from typing import Any, Callable, Dict, List, Union
# try to import readline, unix specific enhancement
try:
@@ -35,15 +33,11 @@ from docutils.utils import column_width
import sphinx.locale
from sphinx import __display_version__, package_dir
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import __
-from sphinx.util.console import (bold, color_terminal, colorize, nocolor, red, # type: ignore
- turquoise)
+from sphinx.util.console import bold, color_terminal, colorize, nocolor, red # type: ignore
from sphinx.util.osutil import ensuredir
from sphinx.util.template import SphinxRenderer
-TERM_ENCODING = getattr(sys.stdin, 'encoding', None) # RemovedInSphinx40Warning
-
EXTENSIONS = OrderedDict([
('autodoc', __('automatically insert docstrings from modules')),
('doctest', __('automatically test code snippets in doctest blocks')),
@@ -134,30 +128,6 @@ def ok(x: str) -> str:
return x
-def term_decode(text: Union[bytes, str]) -> str:
- warnings.warn('term_decode() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- if isinstance(text, str):
- return text
-
- # Use the known encoding, if possible
- if TERM_ENCODING:
- return text.decode(TERM_ENCODING)
-
- # If ascii is safe, use it with no warning
- if text.decode('ascii', 'replace').encode('ascii', 'replace') == text:
- return text.decode('ascii')
-
- print(turquoise(__('* Note: non-ASCII characters entered '
- 'and terminal encoding unknown -- assuming '
- 'UTF-8 or Latin-1.')))
- try:
- return text.decode()
- except UnicodeDecodeError:
- return text.decode('latin1')
-
-
def do_prompt(text: str, default: str = None, validator: Callable[[str], Any] = nonempty) -> Union[str, bool]: # NOQA
while True:
if default is not None:
@@ -183,13 +153,6 @@ def do_prompt(text: str, default: str = None, validator: Callable[[str], Any] =
return x
-def convert_python_source(source: str, rex: Pattern = re.compile(r"[uU]('.*?')")) -> str:
- # remove Unicode literal prefixes
- warnings.warn('convert_python_source() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- return rex.sub('\\1', source)
-
-
class QuickstartRenderer(SphinxRenderer):
def __init__(self, templatedir: str) -> None:
self.templatedir = templatedir or ''
diff --git a/sphinx/config.py b/sphinx/config.py
index 4c038b061..735a3e0b3 100644
--- a/sphinx/config.py
+++ b/sphinx/config.py
@@ -11,24 +11,20 @@
import re
import traceback
import types
-import warnings
from collections import OrderedDict
from os import getenv, path
-from typing import (Any, Callable, Dict, Generator, Iterator, List, NamedTuple, Set, Tuple,
- Union)
+from typing import (TYPE_CHECKING, Any, Callable, Dict, Generator, Iterator, List, NamedTuple,
+ Set, Tuple, Union)
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.errors import ConfigError, ExtensionError
from sphinx.locale import _, __
from sphinx.util import logging
from sphinx.util.i18n import format_date
-from sphinx.util.osutil import cd
-from sphinx.util.pycompat import execfile_
+from sphinx.util.osutil import cd, fs_encoding
from sphinx.util.tags import Tags
from sphinx.util.typing import NoneType
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.environment import BuildEnvironment
@@ -38,9 +34,11 @@ CONFIG_FILENAME = 'conf.py'
UNSERIALIZABLE_TYPES = (type, types.ModuleType, types.FunctionType)
copyright_year_re = re.compile(r'^((\d{4}-)?)(\d{4})(?=[ ,])')
-ConfigValue = NamedTuple('ConfigValue', [('name', str),
- ('value', Any),
- ('rebuild', Union[bool, str])])
+
+class ConfigValue(NamedTuple):
+ name: str
+ value: Any
+ rebuild: Union[bool, str]
def is_serializable(obj: Any) -> bool:
@@ -73,10 +71,6 @@ class ENUM:
return value in self.candidates
-# RemovedInSphinx40Warning
-string_classes = [str] # type: List
-
-
class Config:
"""Configuration file abstraction.
@@ -113,7 +107,6 @@ class Config:
'master_doc': ('index', 'env', []),
'source_suffix': ({'.rst': 'restructuredtext'}, 'env', Any),
'source_encoding': ('utf-8-sig', 'env', []),
- 'source_parsers': ({}, 'env', []),
'exclude_patterns': ([], 'env', []),
'default_role': (None, 'env', [str]),
'add_function_parentheses': (True, 'env', []),
@@ -324,7 +317,9 @@ def eval_config_file(filename: str, tags: Tags) -> Dict[str, Any]:
with cd(path.dirname(filename)):
# during executing config file, current dir is changed to ``confdir``.
try:
- execfile_(filename, namespace)
+ with open(filename, 'rb') as f:
+ code = compile(f.read(), filename.encode(fs_encoding), 'exec')
+ exec(code, namespace)
except SyntaxError as err:
msg = __("There is a syntax error in your configuration file: %s\n")
raise ConfigError(msg % err) from err
@@ -459,22 +454,6 @@ def check_confval_types(app: "Sphinx", config: Config) -> None:
default=type(default)))
-def check_unicode(config: Config) -> None:
- """check all string values for non-ASCII characters in bytestrings,
- since that can result in UnicodeErrors all over the place
- """
- warnings.warn('sphinx.config.check_unicode() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- nonascii_re = re.compile(br'[\x80-\xff]')
-
- for name, value in config._raw_config.items():
- if isinstance(value, bytes) and nonascii_re.search(value):
- logger.warning(__('the config value %r is set to a string with non-ASCII '
- 'characters; this can lead to Unicode errors occurring. '
- 'Please use Unicode strings, e.g. %r.'), name, 'Content')
-
-
def check_primary_domain(app: "Sphinx", config: Config) -> None:
primary_domain = config.primary_domain
if primary_domain and not app.registry.has_domain(primary_domain):
diff --git a/sphinx/deprecation.py b/sphinx/deprecation.py
index 161d7bcac..1d602fa82 100644
--- a/sphinx/deprecation.py
+++ b/sphinx/deprecation.py
@@ -11,18 +11,14 @@
import sys
import warnings
from importlib import import_module
-from typing import Any, Dict
-
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
+from typing import Any, Dict, Type
class RemovedInSphinx40Warning(DeprecationWarning):
pass
-class RemovedInSphinx50Warning(PendingDeprecationWarning):
+class RemovedInSphinx50Warning(DeprecationWarning):
pass
@@ -30,7 +26,7 @@ class RemovedInSphinx60Warning(PendingDeprecationWarning):
pass
-RemovedInNextVersionWarning = RemovedInSphinx40Warning
+RemovedInNextVersionWarning = RemovedInSphinx50Warning
def deprecated_alias(modname: str, objects: Dict[str, object],
diff --git a/sphinx/directives/__init__.py b/sphinx/directives/__init__.py
index e386b3eaa..d4c82c9f3 100644
--- a/sphinx/directives/__init__.py
+++ b/sphinx/directives/__init__.py
@@ -9,7 +9,7 @@
"""
import re
-from typing import Any, Dict, Generic, List, Tuple, TypeVar, cast
+from typing import TYPE_CHECKING, Any, Dict, Generic, List, Tuple, TypeVar, cast
from docutils import nodes
from docutils.nodes import Node
@@ -17,15 +17,13 @@ from docutils.parsers.rst import directives, roles
from sphinx import addnodes
from sphinx.addnodes import desc_signature
-from sphinx.deprecation import (RemovedInSphinx40Warning, RemovedInSphinx50Warning,
- deprecated_alias)
+from sphinx.deprecation import RemovedInSphinx50Warning, deprecated_alias
from sphinx.util import docutils
from sphinx.util.docfields import DocFieldTransformer, Field, TypedField
from sphinx.util.docutils import SphinxDirective
from sphinx.util.typing import DirectiveOption
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -266,52 +264,6 @@ class DefaultDomain(SphinxDirective):
self.env.temp_data['default_domain'] = self.env.domains.get(domain_name)
return []
-from sphinx.directives.code import CodeBlock, Highlight, LiteralInclude # noqa
-from sphinx.directives.other import (Acks, Author, Centered, Class, HList, Include, # noqa
- Only, SeeAlso, TabularColumns, TocTree, VersionChange)
-from sphinx.directives.patches import Figure, Meta # noqa
-from sphinx.domains.index import IndexDirective # noqa
-
-deprecated_alias('sphinx.directives',
- {
- 'Highlight': Highlight,
- 'CodeBlock': CodeBlock,
- 'LiteralInclude': LiteralInclude,
- 'TocTree': TocTree,
- 'Author': Author,
- 'Index': IndexDirective,
- 'VersionChange': VersionChange,
- 'SeeAlso': SeeAlso,
- 'TabularColumns': TabularColumns,
- 'Centered': Centered,
- 'Acks': Acks,
- 'HList': HList,
- 'Only': Only,
- 'Include': Include,
- 'Class': Class,
- 'Figure': Figure,
- 'Meta': Meta,
- },
- RemovedInSphinx40Warning,
- {
- 'Highlight': 'sphinx.directives.code.Highlight',
- 'CodeBlock': 'sphinx.directives.code.CodeBlock',
- 'LiteralInclude': 'sphinx.directives.code.LiteralInclude',
- 'TocTree': 'sphinx.directives.other.TocTree',
- 'Author': 'sphinx.directives.other.Author',
- 'Index': 'sphinx.directives.other.IndexDirective',
- 'VersionChange': 'sphinx.directives.other.VersionChange',
- 'SeeAlso': 'sphinx.directives.other.SeeAlso',
- 'TabularColumns': 'sphinx.directives.other.TabularColumns',
- 'Centered': 'sphinx.directives.other.Centered',
- 'Acks': 'sphinx.directives.other.Acks',
- 'HList': 'sphinx.directives.other.HList',
- 'Only': 'sphinx.directives.other.Only',
- 'Include': 'sphinx.directives.other.Include',
- 'Class': 'sphinx.directives.other.Class',
- 'Figure': 'sphinx.directives.patches.Figure',
- 'Meta': 'sphinx.directives.patches.Meta',
- })
deprecated_alias('sphinx.directives',
{
diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py
index e01b8f9ec..f5cd92b82 100644
--- a/sphinx/directives/code.py
+++ b/sphinx/directives/code.py
@@ -8,9 +8,8 @@
import sys
import textwrap
-import warnings
from difflib import unified_diff
-from typing import Any, Dict, List, Tuple
+from typing import TYPE_CHECKING, Any, Dict, List, Tuple
from docutils import nodes
from docutils.nodes import Element, Node
@@ -19,14 +18,12 @@ from docutils.statemachine import StringList
from sphinx import addnodes
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.directives import optional_int
from sphinx.locale import __
from sphinx.util import logging, parselinenos
from sphinx.util.docutils import SphinxDirective
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
logger = logging.getLogger(__name__)
@@ -58,16 +55,6 @@ class Highlight(SphinxDirective):
linenothreshold=linenothreshold)]
-class HighlightLang(Highlight):
- """highlightlang directive (deprecated)"""
-
- def run(self) -> List[Node]:
- warnings.warn('highlightlang directive is deprecated. '
- 'Please use highlight directive instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- return super().run()
-
-
def dedent_lines(lines: List[str], dedent: int, location: Tuple[str, int] = None) -> List[str]:
if not dedent:
return textwrap.dedent(''.join(lines)).splitlines(True)
@@ -470,7 +457,6 @@ class LiteralInclude(SphinxDirective):
def setup(app: "Sphinx") -> Dict[str, Any]:
directives.register_directive('highlight', Highlight)
- directives.register_directive('highlightlang', HighlightLang)
directives.register_directive('code-block', CodeBlock)
directives.register_directive('sourcecode', CodeBlock)
directives.register_directive('literalinclude', LiteralInclude)
diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py
index 9325cbe4f..038da99e1 100644
--- a/sphinx/directives/other.py
+++ b/sphinx/directives/other.py
@@ -7,7 +7,7 @@
"""
import re
-from typing import Any, Dict, List, cast
+from typing import TYPE_CHECKING, Any, Dict, List, cast
from docutils import nodes
from docutils.nodes import Element, Node
@@ -17,7 +17,6 @@ from docutils.parsers.rst.directives.misc import Class
from docutils.parsers.rst.directives.misc import Include as BaseInclude
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.domains.changeset import VersionChange # NOQA # for compatibility
from sphinx.locale import _
from sphinx.util import docname_join, url_re
@@ -25,8 +24,7 @@ from sphinx.util.docutils import SphinxDirective
from sphinx.util.matching import Matcher, patfilter
from sphinx.util.nodes import explicit_title_re
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -137,7 +135,13 @@ class TocTree(SphinxDirective):
line=self.lineno))
self.env.note_reread()
else:
- all_docnames.discard(docname)
+ if docname in all_docnames:
+ all_docnames.remove(docname)
+ else:
+ message = 'duplicated entry found in toctree: %s'
+ ret.append(self.state.document.reporter.warning(message % docname,
+ line=self.lineno))
+
toctree['entries'].append((title, docname))
toctree['includefiles'].append(docname)
@@ -360,19 +364,6 @@ class Include(BaseInclude, SphinxDirective):
return super().run()
-# Import old modules here for compatibility
-from sphinx.domains.index import IndexDirective # NOQA
-
-deprecated_alias('sphinx.directives.other',
- {
- 'Index': IndexDirective,
- },
- RemovedInSphinx40Warning,
- {
- 'Index': 'sphinx.domains.index.IndexDirective',
- })
-
-
def setup(app: "Sphinx") -> Dict[str, Any]:
directives.register_directive('toctree', TocTree)
directives.register_directive('sectionauthor', Author)
diff --git a/sphinx/directives/patches.py b/sphinx/directives/patches.py
index 1eae6d0c8..5baa0994c 100644
--- a/sphinx/directives/patches.py
+++ b/sphinx/directives/patches.py
@@ -6,7 +6,8 @@
:license: BSD, see LICENSE for details.
"""
-from typing import Any, Dict, List, Tuple, cast
+import warnings
+from typing import TYPE_CHECKING, Any, Dict, List, Tuple, cast
from docutils import nodes
from docutils.nodes import Node, make_id, system_message
@@ -14,13 +15,13 @@ from docutils.parsers.rst import directives
from docutils.parsers.rst.directives import html, images, tables
from sphinx import addnodes
+from sphinx.deprecation import RemovedInSphinx60Warning
from sphinx.directives import optional_int
from sphinx.domains.math import MathDomain
from sphinx.util.docutils import SphinxDirective
from sphinx.util.nodes import set_source_info
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -72,6 +73,11 @@ class RSTTable(tables.RSTTable):
Only for docutils-0.13 or older version."""
+ def run(self) -> List[Node]:
+ warnings.warn('RSTTable is deprecated.',
+ RemovedInSphinx60Warning)
+ return super().run()
+
def make_title(self) -> Tuple[nodes.title, List[system_message]]:
title, message = super().make_title()
if title:
@@ -85,6 +91,11 @@ class CSVTable(tables.CSVTable):
Only for docutils-0.13 or older version."""
+ def run(self) -> List[Node]:
+ warnings.warn('RSTTable is deprecated.',
+ RemovedInSphinx60Warning)
+ return super().run()
+
def make_title(self) -> Tuple[nodes.title, List[system_message]]:
title, message = super().make_title()
if title:
@@ -98,6 +109,11 @@ class ListTable(tables.ListTable):
Only for docutils-0.13 or older version."""
+ def run(self) -> List[Node]:
+ warnings.warn('RSTTable is deprecated.',
+ RemovedInSphinx60Warning)
+ return super().run()
+
def make_title(self) -> Tuple[nodes.title, List[system_message]]:
title, message = super().make_title()
if title:
@@ -208,9 +224,6 @@ class MathDirective(SphinxDirective):
def setup(app: "Sphinx") -> Dict[str, Any]:
directives.register_directive('figure', Figure)
directives.register_directive('meta', Meta)
- directives.register_directive('table', RSTTable)
- directives.register_directive('csv-table', CSVTable)
- directives.register_directive('list-table', ListTable)
directives.register_directive('code', Code)
directives.register_directive('math', MathDirective)
diff --git a/sphinx/domains/__init__.py b/sphinx/domains/__init__.py
index 60142f584..3439ea93c 100644
--- a/sphinx/domains/__init__.py
+++ b/sphinx/domains/__init__.py
@@ -10,7 +10,8 @@
"""
import copy
-from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Tuple, Union, cast
+from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, List, NamedTuple, Tuple,
+ Type, Union, cast)
from docutils import nodes
from docutils.nodes import Element, Node, system_message
@@ -22,10 +23,7 @@ from sphinx.locale import _
from sphinx.roles import XRefRole
from sphinx.util.typing import RoleFunction
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment
@@ -56,13 +54,14 @@ class ObjType:
self.attrs.update(attrs)
-IndexEntry = NamedTuple('IndexEntry', [('name', str),
- ('subtype', int),
- ('docname', str),
- ('anchor', str),
- ('extra', str),
- ('qualifier', str),
- ('descr', str)])
+class IndexEntry(NamedTuple):
+ name: str
+ subtype: int
+ docname: str
+ anchor: str
+ extra: str
+ qualifier: str
+ descr: str
class Index:
diff --git a/sphinx/domains/changeset.py b/sphinx/domains/changeset.py
index ba323b729..33234d6e0 100644
--- a/sphinx/domains/changeset.py
+++ b/sphinx/domains/changeset.py
@@ -8,8 +8,7 @@
:license: BSD, see LICENSE for details.
"""
-from collections import namedtuple
-from typing import Any, Dict, List, cast
+from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, cast
from docutils import nodes
from docutils.nodes import Node
@@ -19,8 +18,7 @@ from sphinx.domains import Domain
from sphinx.locale import _
from sphinx.util.docutils import SphinxDirective
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.environment import BuildEnvironment
@@ -38,9 +36,13 @@ versionlabel_classes = {
}
-# TODO: move to typing.NamedTuple after dropping py35 support (see #5958)
-ChangeSet = namedtuple('ChangeSet',
- ['type', 'docname', 'lineno', 'module', 'descname', 'content'])
+class ChangeSet(NamedTuple):
+ type: str
+ docname: str
+ lineno: int
+ module: str
+ descname: str
+ content: str
class VersionChange(SphinxDirective):
diff --git a/sphinx/domains/citation.py b/sphinx/domains/citation.py
index 1ceb53037..772d486af 100644
--- a/sphinx/domains/citation.py
+++ b/sphinx/domains/citation.py
@@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
-from typing import Any, Dict, List, Set, Tuple, cast
+from typing import TYPE_CHECKING, Any, Dict, List, Set, Tuple, cast
from docutils import nodes
from docutils.nodes import Element
@@ -20,8 +20,7 @@ from sphinx.transforms import SphinxTransform
from sphinx.util import logging
from sphinx.util.nodes import copy_source_info, make_refnode
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment
diff --git a/sphinx/domains/index.py b/sphinx/domains/index.py
index 4a91d6ad1..fd1a76613 100644
--- a/sphinx/domains/index.py
+++ b/sphinx/domains/index.py
@@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
-from typing import Any, Dict, Iterable, List, Tuple
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Tuple
from docutils import nodes
from docutils.nodes import Node, system_message
@@ -21,8 +21,7 @@ from sphinx.util import logging, split_index_msg
from sphinx.util.docutils import ReferenceRole, SphinxDirective
from sphinx.util.nodes import process_index_entry
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
diff --git a/sphinx/domains/math.py b/sphinx/domains/math.py
index 248a7a2a6..70a27e642 100644
--- a/sphinx/domains/math.py
+++ b/sphinx/domains/math.py
@@ -8,14 +8,12 @@
:license: BSD, see LICENSE for details.
"""
-import warnings
-from typing import Any, Dict, Iterable, List, Tuple
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Tuple
from docutils import nodes
from docutils.nodes import Element, Node, make_id, system_message
from sphinx.addnodes import pending_xref
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.domains import Domain
from sphinx.environment import BuildEnvironment
from sphinx.locale import __
@@ -23,8 +21,7 @@ from sphinx.roles import XRefRole
from sphinx.util import logging
from sphinx.util.nodes import make_refnode
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.builders import Builder
@@ -139,24 +136,6 @@ class MathDomain(Domain):
def get_objects(self) -> List:
return []
- def add_equation(self, env: BuildEnvironment, docname: str, labelid: str) -> int:
- warnings.warn('MathDomain.add_equation() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- if labelid in self.equations:
- path = env.doc2path(self.equations[labelid][0])
- msg = __('duplicate label of equation %s, other instance in %s') % (labelid, path)
- raise UserWarning(msg)
- else:
- eqno = self.get_next_equation_number(docname)
- self.equations[labelid] = (docname, eqno)
- return eqno
-
- def get_next_equation_number(self, docname: str) -> int:
- warnings.warn('MathDomain.get_next_equation_number() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- targets = [eq for eq in self.equations.values() if eq[0] == docname]
- return len(targets) + 1
-
def has_equations(self, docname: str = None) -> bool:
if docname:
return self.data['has_equations'].get(docname, False)
diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py
index c2af9886f..c07c31e87 100644
--- a/sphinx/domains/python.py
+++ b/sphinx/domains/python.py
@@ -15,7 +15,7 @@ import sys
import typing
import warnings
from inspect import Parameter
-from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Tuple, cast
+from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Tuple, Type, cast
from docutils import nodes
from docutils.nodes import Element, Node
@@ -25,7 +25,7 @@ from sphinx import addnodes
from sphinx.addnodes import desc_signature, pending_xref
from sphinx.application import Sphinx
from sphinx.builders import Builder
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, Index, IndexEntry, ObjType
from sphinx.environment import BuildEnvironment
@@ -40,11 +40,6 @@ from sphinx.util.inspect import signature_from_str
from sphinx.util.nodes import make_id, make_refnode
from sphinx.util.typing import TextlikeNode
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-
logger = logging.getLogger(__name__)
@@ -68,14 +63,20 @@ pairindextypes = {
'builtin': _('built-in function'),
}
-ObjectEntry = NamedTuple('ObjectEntry', [('docname', str),
- ('node_id', str),
- ('objtype', str)])
-ModuleEntry = NamedTuple('ModuleEntry', [('docname', str),
- ('node_id', str),
- ('synopsis', str),
- ('platform', str),
- ('deprecated', bool)])
+
+class ObjectEntry(NamedTuple):
+ docname: str
+ node_id: str
+ objtype: str
+ canonical: bool
+
+
+class ModuleEntry(NamedTuple):
+ docname: str
+ node_id: str
+ synopsis: str
+ platform: str
+ deprecated: bool
def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xref:
@@ -100,6 +101,11 @@ def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Nod
def unparse(node: ast.AST) -> List[Node]:
if isinstance(node, ast.Attribute):
return [nodes.Text("%s.%s" % (unparse(node.value)[0], node.attr))]
+ elif isinstance(node, ast.Constant): # type: ignore
+ if node.value is Ellipsis:
+ return [addnodes.desc_sig_punctuation('', "...")]
+ else:
+ return [nodes.Text(node.value)]
elif isinstance(node, ast.Expr):
return unparse(node.value)
elif isinstance(node, ast.Index):
@@ -135,13 +141,6 @@ def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Nod
return result
else:
- if sys.version_info >= (3, 6):
- if isinstance(node, ast.Constant):
- if node.value is Ellipsis:
- return [addnodes.desc_sig_punctuation('', "...")]
- else:
- return [nodes.Text(node.value)]
-
if sys.version_info < (3, 8):
if isinstance(node, ast.Ellipsis):
return [addnodes.desc_sig_punctuation('', "...")]
@@ -267,7 +266,7 @@ def _pseudo_parse_arglist(signode: desc_signature, arglist: str) -> None:
# when it comes to handling "." and "~" prefixes.
class PyXrefMixin:
def make_xref(self, rolename: str, domain: str, target: str,
- innernode: "Type[TextlikeNode]" = nodes.emphasis,
+ innernode: Type[TextlikeNode] = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
result = super().make_xref(rolename, domain, target, # type: ignore
innernode, contnode, env)
@@ -286,7 +285,7 @@ class PyXrefMixin:
return result
def make_xrefs(self, rolename: str, domain: str, target: str,
- innernode: "Type[TextlikeNode]" = nodes.emphasis,
+ innernode: Type[TextlikeNode] = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> List[Node]:
delims = r'(\s*[\[\]\(\),](?:\s*or\s)?\s*|\s+or\s+)'
delims_re = re.compile(delims)
@@ -310,7 +309,7 @@ class PyXrefMixin:
class PyField(PyXrefMixin, Field):
def make_xref(self, rolename: str, domain: str, target: str,
- innernode: "Type[TextlikeNode]" = nodes.emphasis,
+ innernode: Type[TextlikeNode] = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
if rolename == 'class' and target == 'None':
# None is not a type, so use obj role instead.
@@ -325,7 +324,7 @@ class PyGroupedField(PyXrefMixin, GroupedField):
class PyTypedField(PyXrefMixin, TypedField):
def make_xref(self, rolename: str, domain: str, target: str,
- innernode: "Type[TextlikeNode]" = nodes.emphasis,
+ innernode: Type[TextlikeNode] = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
if rolename == 'class' and target == 'None':
# None is not a type, so use obj role instead.
@@ -345,6 +344,7 @@ class PyObject(ObjectDescription[Tuple[str, str]]):
'noindex': directives.flag,
'noindexentry': directives.flag,
'module': directives.unchanged,
+ 'canonical': directives.unchanged,
'annotation': directives.unchanged,
}
@@ -354,7 +354,7 @@ class PyObject(ObjectDescription[Tuple[str, str]]):
'keyword', 'kwarg', 'kwparam'),
typerolename='class', typenames=('paramtype', 'type'),
can_collapse=True),
- PyTypedField('variable', label=_('Variables'), rolename='obj',
+ PyTypedField('variable', label=_('Variables'),
names=('var', 'ivar', 'cvar'),
typerolename='class', typenames=('vartype',),
can_collapse=True),
@@ -486,6 +486,11 @@ class PyObject(ObjectDescription[Tuple[str, str]]):
domain = cast(PythonDomain, self.env.get_domain('py'))
domain.note_object(fullname, self.objtype, node_id, location=signode)
+ canonical_name = self.options.get('canonical')
+ if canonical_name:
+ domain.note_object(canonical_name, self.objtype, node_id, canonical=True,
+ location=signode)
+
if 'noindexentry' not in self.options:
indextext = self.get_index_text(modname, name_cls)
if indextext:
@@ -550,40 +555,6 @@ class PyObject(ObjectDescription[Tuple[str, str]]):
self.env.ref_context.pop('py:module')
-class PyModulelevel(PyObject):
- """
- Description of an object on module level (functions, data).
- """
-
- def run(self) -> List[Node]:
- for cls in self.__class__.__mro__:
- if cls.__name__ != 'DirectiveAdapter':
- warnings.warn('PyModulelevel is deprecated. '
- 'Please check the implementation of %s' % cls,
- RemovedInSphinx40Warning, stacklevel=2)
- break
- else:
- warnings.warn('PyModulelevel is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
-
- return super().run()
-
- def needs_arglist(self) -> bool:
- return self.objtype == 'function'
-
- def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str:
- if self.objtype == 'function':
- if not modname:
- return _('%s() (built-in function)') % name_cls[0]
- return _('%s() (in module %s)') % (name_cls[0], modname)
- elif self.objtype == 'data':
- if not modname:
- return _('%s (built-in variable)') % name_cls[0]
- return _('%s (in module %s)') % (name_cls[0], modname)
- else:
- return ''
-
-
class PyFunction(PyObject):
"""Description of a function."""
@@ -698,91 +669,6 @@ class PyClasslike(PyObject):
return ''
-class PyClassmember(PyObject):
- """
- Description of a class member (methods, attributes).
- """
-
- def run(self) -> List[Node]:
- for cls in self.__class__.__mro__:
- if cls.__name__ != 'DirectiveAdapter':
- warnings.warn('PyClassmember is deprecated. '
- 'Please check the implementation of %s' % cls,
- RemovedInSphinx40Warning, stacklevel=2)
- break
- else:
- warnings.warn('PyClassmember is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
-
- return super().run()
-
- def needs_arglist(self) -> bool:
- return self.objtype.endswith('method')
-
- def get_signature_prefix(self, sig: str) -> str:
- if self.objtype == 'staticmethod':
- return 'static '
- elif self.objtype == 'classmethod':
- return 'classmethod '
- return ''
-
- def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str:
- name, cls = name_cls
- add_modules = self.env.config.add_module_names
- if self.objtype == 'method':
- try:
- clsname, methname = name.rsplit('.', 1)
- except ValueError:
- if modname:
- return _('%s() (in module %s)') % (name, modname)
- else:
- return '%s()' % name
- if modname and add_modules:
- return _('%s() (%s.%s method)') % (methname, modname, clsname)
- else:
- return _('%s() (%s method)') % (methname, clsname)
- elif self.objtype == 'staticmethod':
- try:
- clsname, methname = name.rsplit('.', 1)
- except ValueError:
- if modname:
- return _('%s() (in module %s)') % (name, modname)
- else:
- return '%s()' % name
- if modname and add_modules:
- return _('%s() (%s.%s static method)') % (methname, modname,
- clsname)
- else:
- return _('%s() (%s static method)') % (methname, clsname)
- elif self.objtype == 'classmethod':
- try:
- clsname, methname = name.rsplit('.', 1)
- except ValueError:
- if modname:
- return _('%s() (in module %s)') % (name, modname)
- else:
- return '%s()' % name
- if modname:
- return _('%s() (%s.%s class method)') % (methname, modname,
- clsname)
- else:
- return _('%s() (%s class method)') % (methname, clsname)
- elif self.objtype == 'attribute':
- try:
- clsname, attrname = name.rsplit('.', 1)
- except ValueError:
- if modname:
- return _('%s (in module %s)') % (name, modname)
- else:
- return name
- if modname and add_modules:
- return _('%s (%s.%s attribute)') % (attrname, modname, clsname)
- else:
- return _('%s (%s attribute)') % (attrname, clsname)
- else:
- return ''
-
-
class PyMethod(PyObject):
"""Description of a method."""
@@ -1193,7 +1079,8 @@ class PythonDomain(Domain):
def objects(self) -> Dict[str, ObjectEntry]:
return self.data.setdefault('objects', {}) # fullname -> ObjectEntry
- def note_object(self, name: str, objtype: str, node_id: str, location: Any = None) -> None:
+ def note_object(self, name: str, objtype: str, node_id: str,
+ canonical: bool = False, location: Any = None) -> None:
"""Note a python object for cross reference.
.. versionadded:: 2.1
@@ -1203,7 +1090,7 @@ class PythonDomain(Domain):
logger.warning(__('duplicate object description of %s, '
'other instance in %s, use :noindex: for one of them'),
name, other.docname, location=location)
- self.objects[name] = ObjectEntry(self.env.docname, node_id, objtype)
+ self.objects[name] = ObjectEntry(self.env.docname, node_id, objtype, canonical)
@property
def modules(self) -> Dict[str, ModuleEntry]:
@@ -1356,7 +1243,11 @@ class PythonDomain(Domain):
yield (modname, modname, 'module', mod.docname, mod.node_id, 0)
for refname, obj in self.objects.items():
if obj.objtype != 'module': # modules are already handled
- yield (refname, refname, obj.objtype, obj.docname, obj.node_id, 1)
+ if obj.canonical:
+ # canonical names are not full-text searchable.
+ yield (refname, refname, obj.objtype, obj.docname, obj.node_id, -1)
+ else:
+ yield (refname, refname, obj.objtype, obj.docname, obj.node_id, 1)
def get_full_qualified_name(self, node: Element) -> str:
modname = node.get('py:module')
@@ -1402,7 +1293,7 @@ def setup(app: Sphinx) -> Dict[str, Any]:
return {
'version': 'builtin',
- 'env_version': 2,
+ 'env_version': 3,
'parallel_read_safe': True,
'parallel_write_safe': True,
}
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index b936a8d19..864c338f4 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -12,7 +12,8 @@ import re
import unicodedata
import warnings
from copy import copy
-from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast
+from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional,
+ Tuple, Type, Union, cast)
from docutils import nodes
from docutils.nodes import Element, Node, system_message
@@ -21,7 +22,7 @@ from docutils.statemachine import StringList
from sphinx import addnodes
from sphinx.addnodes import desc_signature, pending_xref
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.locale import _, __
@@ -31,10 +32,7 @@ from sphinx.util.docutils import SphinxDirective
from sphinx.util.nodes import clean_astext, make_id, make_refnode
from sphinx.util.typing import RoleFunction
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment
@@ -292,8 +290,8 @@ def split_term_classifiers(line: str) -> List[Optional[str]]:
def make_glossary_term(env: "BuildEnvironment", textnodes: Iterable[Node], index_key: str,
- source: str, lineno: int, node_id: str = None,
- document: nodes.document = None) -> nodes.term:
+ source: str, lineno: int, node_id: str, document: nodes.document
+ ) -> nodes.term:
# get a text-only representation of the term and register it
# as a cross-reference target
term = nodes.term('', '', *textnodes)
@@ -304,23 +302,10 @@ def make_glossary_term(env: "BuildEnvironment", textnodes: Iterable[Node], index
if node_id:
# node_id is given from outside (mainly i18n module), use it forcedly
term['ids'].append(node_id)
- elif document:
+ else:
node_id = make_id(env, document, 'term', termtext)
term['ids'].append(node_id)
document.note_explicit_target(term)
- else:
- warnings.warn('make_glossary_term() expects document is passed as an argument.',
- RemovedInSphinx40Warning, stacklevel=2)
- gloss_entries = env.temp_data.setdefault('gloss_entries', set())
- node_id = nodes.make_id('term-' + termtext)
- if node_id == 'term':
- # "term" is not good for node_id. Generate it by sequence number instead.
- node_id = 'term-%d' % env.new_serialno('glossary')
-
- while node_id in gloss_entries:
- node_id = 'term-%d' % env.new_serialno('glossary')
- gloss_entries.add(node_id)
- term['ids'].append(node_id)
std = cast(StandardDomain, env.get_domain('std'))
std.note_object('term', termtext, node_id, location=term)
@@ -428,7 +413,7 @@ class Glossary(SphinxDirective):
# use first classifier as a index key
term = make_glossary_term(self.env, textnodes, parts[1], source, lineno,
- document=self.state.document)
+ node_id=None, document=self.state.document)
term.rawsource = line
system_messages.extend(sysmsg)
termtexts.append(term.astext())
@@ -803,11 +788,6 @@ class StandardDomain(Domain):
resolver = self._resolve_doc_xref
elif typ == 'option':
resolver = self._resolve_option_xref
- elif typ == 'citation':
- warnings.warn('pending_xref(domain=std, type=citation) is deprecated: %r' % node,
- RemovedInSphinx40Warning, stacklevel=2)
- domain = env.get_domain('citation')
- return domain.resolve_xref(env, fromdocname, builder, typ, target, node, contnode)
elif typ == 'term':
resolver = self._resolve_term_xref
else:
@@ -1100,18 +1080,6 @@ class StandardDomain(Domain):
else:
return None
- def note_citations(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA
- warnings.warn('StandardDomain.note_citations() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- def note_citation_refs(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA
- warnings.warn('StandardDomain.note_citation_refs() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- def note_labels(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA
- warnings.warn('StandardDomain.note_labels() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
def warn_missing_reference(app: "Sphinx", domain: Domain, node: pending_xref) -> bool:
if (domain and domain.name != 'std') or node['reftype'] != 'ref':
diff --git a/sphinx/environment/__init__.py b/sphinx/environment/__init__.py
index be5e52f49..2121b3ee4 100644
--- a/sphinx/environment/__init__.py
+++ b/sphinx/environment/__init__.py
@@ -10,18 +10,18 @@
import os
import pickle
-import warnings
from collections import defaultdict
from copy import copy
+from datetime import datetime
from os import path
-from typing import Any, Callable, Dict, Generator, Iterator, List, Set, Tuple, Union, cast
+from typing import (TYPE_CHECKING, Any, Callable, Dict, Generator, Iterator, List, Set, Tuple,
+ Union)
from docutils import nodes
from docutils.nodes import Node
from sphinx import addnodes
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.domains import Domain
from sphinx.environment.adapters.toctree import TocTree
from sphinx.errors import BuildEnvironmentError, DocumentError, ExtensionError, SphinxError
@@ -34,8 +34,7 @@ from sphinx.util.docutils import LoggingReporter
from sphinx.util.i18n import CatalogRepository, docname_to_domain
from sphinx.util.nodes import is_translatable
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.builders import Builder
@@ -319,28 +318,13 @@ class BuildEnvironment:
"""
return self.project.path2doc(filename)
- def doc2path(self, docname: str, base: Union[bool, str] = True, suffix: str = None) -> str:
+ def doc2path(self, docname: str, base: bool = True) -> str:
"""Return the filename for the document name.
If *base* is True, return absolute path under self.srcdir.
- If *base* is None, return relative path to self.srcdir.
- If *base* is a path string, return absolute path under that.
- If *suffix* is not None, add it instead of config.source_suffix.
+ If *base* is False, return relative path to self.srcdir.
"""
- if suffix:
- warnings.warn('The suffix argument for doc2path() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- if base not in (True, False, None):
- warnings.warn('The string style base argument for doc2path() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- pathname = self.project.doc2path(docname, base is True)
- if suffix:
- filename, _ = path.splitext(pathname)
- pathname = filename + suffix
- if base and base is not True:
- pathname = path.join(base, pathname) # type: ignore
- return pathname
+ return self.project.doc2path(docname, base)
def relfn2path(self, filename: str, docname: str = None) -> Tuple[str, str]:
"""Return paths to a file referenced from a document, relative to
@@ -408,21 +392,28 @@ class BuildEnvironment:
else:
for docname in self.found_docs:
if docname not in self.all_docs:
+ logger.debug('[build target] added %r', docname)
added.add(docname)
continue
# if the doctree file is not there, rebuild
filename = path.join(self.doctreedir, docname + '.doctree')
if not path.isfile(filename):
+ logger.debug('[build target] changed %r', docname)
changed.add(docname)
continue
# check the "reread always" list
if docname in self.reread_always:
+ logger.debug('[build target] changed %r', docname)
changed.add(docname)
continue
# check the mtime of the document
mtime = self.all_docs[docname]
newmtime = path.getmtime(self.doc2path(docname))
if newmtime > mtime:
+ logger.debug('[build target] outdated %r: %s -> %s',
+ docname,
+ datetime.utcfromtimestamp(mtime),
+ datetime.utcfromtimestamp(newmtime))
changed.add(docname)
continue
# finally, check the mtime of dependencies
@@ -641,19 +632,3 @@ class BuildEnvironment:
for domain in self.domains.values():
domain.check_consistency()
self.events.emit('env-check-consistency', self)
-
- @property
- def indexentries(self) -> Dict[str, List[Tuple[str, str, str, str, str]]]:
- warnings.warn('env.indexentries() is deprecated. Please use IndexDomain instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- from sphinx.domains.index import IndexDomain
- domain = cast(IndexDomain, self.get_domain('index'))
- return domain.entries
-
- @indexentries.setter
- def indexentries(self, entries: Dict[str, List[Tuple[str, str, str, str, str]]]) -> None:
- warnings.warn('env.indexentries() is deprecated. Please use IndexDomain instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- from sphinx.domains.index import IndexDomain
- domain = cast(IndexDomain, self.get_domain('index'))
- domain.data['entries'] = entries
diff --git a/sphinx/environment/adapters/toctree.py b/sphinx/environment/adapters/toctree.py
index 93555d172..2e33cf702 100644
--- a/sphinx/environment/adapters/toctree.py
+++ b/sphinx/environment/adapters/toctree.py
@@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
-from typing import Any, Iterable, List, cast
+from typing import TYPE_CHECKING, Any, Iterable, List, cast
from docutils import nodes
from docutils.nodes import Element, Node
@@ -19,8 +19,7 @@ from sphinx.util import logging, url_re
from sphinx.util.matching import Matcher
from sphinx.util.nodes import clean_astext, process_only_nodes
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment
diff --git a/sphinx/environment/collectors/__init__.py b/sphinx/environment/collectors/__init__.py
index 4b7ac3472..aa254bd9a 100644
--- a/sphinx/environment/collectors/__init__.py
+++ b/sphinx/environment/collectors/__init__.py
@@ -8,14 +8,13 @@
:license: BSD, see LICENSE for details.
"""
-from typing import Dict, List, Set
+from typing import TYPE_CHECKING, Dict, List, Set
from docutils import nodes
from sphinx.environment import BuildEnvironment
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
diff --git a/sphinx/environment/collectors/indexentries.py b/sphinx/environment/collectors/indexentries.py
deleted file mode 100644
index 351cdc2de..000000000
--- a/sphinx/environment/collectors/indexentries.py
+++ /dev/null
@@ -1,63 +0,0 @@
-"""
- sphinx.environment.collectors.indexentries
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Index entries collector for sphinx.environment.
-
- :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-from typing import Any, Dict, Set
-
-from docutils import nodes
-
-from sphinx import addnodes
-from sphinx.application import Sphinx
-from sphinx.deprecation import RemovedInSphinx40Warning
-from sphinx.environment import BuildEnvironment
-from sphinx.environment.collectors import EnvironmentCollector
-from sphinx.util import logging, split_index_msg
-
-logger = logging.getLogger(__name__)
-
-
-class IndexEntriesCollector(EnvironmentCollector):
- name = 'indices'
-
- def __init__(self) -> None:
- warnings.warn('IndexEntriesCollector is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- def clear_doc(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None:
- env.indexentries.pop(docname, None)
-
- def merge_other(self, app: Sphinx, env: BuildEnvironment,
- docnames: Set[str], other: BuildEnvironment) -> None:
- for docname in docnames:
- env.indexentries[docname] = other.indexentries[docname]
-
- def process_doc(self, app: Sphinx, doctree: nodes.document) -> None:
- docname = app.env.docname
- entries = app.env.indexentries[docname] = []
- for node in doctree.traverse(addnodes.index):
- try:
- for entry in node['entries']:
- split_index_msg(entry[0], entry[1])
- except ValueError as exc:
- logger.warning(str(exc), location=node)
- node.parent.remove(node)
- else:
- for entry in node['entries']:
- entries.append(entry)
-
-
-def setup(app: Sphinx) -> Dict[str, Any]:
- app.add_env_collector(IndexEntriesCollector)
-
- return {
- 'version': 'builtin',
- 'parallel_read_safe': True,
- 'parallel_write_safe': True,
- }
diff --git a/sphinx/environment/collectors/toctree.py b/sphinx/environment/collectors/toctree.py
index 772451c56..da0b3fe6c 100644
--- a/sphinx/environment/collectors/toctree.py
+++ b/sphinx/environment/collectors/toctree.py
@@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
-from typing import Any, Dict, List, Set, Tuple, TypeVar, cast
+from typing import Any, Dict, List, Set, Tuple, Type, TypeVar, cast
from docutils import nodes
from docutils.nodes import Element, Node
@@ -22,11 +22,6 @@ from sphinx.locale import __
from sphinx.transforms import SphinxContentsFilter
from sphinx.util import logging, url_re
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-
N = TypeVar('N')
logger = logging.getLogger(__name__)
diff --git a/sphinx/events.py b/sphinx/events.py
index 806a6e55d..a29d551b7 100644
--- a/sphinx/events.py
+++ b/sphinx/events.py
@@ -10,28 +10,25 @@
:license: BSD, see LICENSE for details.
"""
-import warnings
from collections import defaultdict
from operator import attrgetter
-from typing import Any, Callable, Dict, List, NamedTuple, Tuple
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, NamedTuple, Tuple, Type
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.errors import ExtensionError, SphinxError
from sphinx.locale import __
from sphinx.util import logging
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
logger = logging.getLogger(__name__)
-EventListener = NamedTuple('EventListener', [('id', int),
- ('handler', Callable),
- ('priority', int)])
+
+class EventListener(NamedTuple):
+ id: int
+ handler: Callable
+ priority: int
# List of all known core events. Maps name to arguments description.
@@ -57,10 +54,7 @@ core_events = {
class EventManager:
"""Event manager for Sphinx."""
- def __init__(self, app: "Sphinx" = None) -> None:
- if app is None:
- warnings.warn('app argument is required for EventManager.',
- RemovedInSphinx40Warning)
+ def __init__(self, app: "Sphinx") -> None:
self.app = app
self.events = core_events.copy()
self.listeners = defaultdict(list) # type: Dict[str, List[EventListener]]
@@ -90,7 +84,7 @@ class EventManager:
listeners.remove(listener)
def emit(self, name: str, *args: Any,
- allowed_exceptions: Tuple["Type[Exception]", ...] = ()) -> List:
+ allowed_exceptions: Tuple[Type[Exception], ...] = ()) -> List:
"""Emit a Sphinx event."""
try:
logger.debug('[app] emitting event: %r%s', name, repr(args)[:100])
@@ -103,11 +97,7 @@ class EventManager:
listeners = sorted(self.listeners[name], key=attrgetter("priority"))
for listener in listeners:
try:
- if self.app is None:
- # for compatibility; RemovedInSphinx40Warning
- results.append(listener.handler(*args))
- else:
- results.append(listener.handler(self.app, *args))
+ results.append(listener.handler(self.app, *args))
except allowed_exceptions:
# pass through the errors specified as *allowed_exceptions*
raise
@@ -119,7 +109,7 @@ class EventManager:
return results
def emit_firstresult(self, name: str, *args: Any,
- allowed_exceptions: Tuple["Type[Exception]", ...] = ()) -> Any:
+ allowed_exceptions: Tuple[Type[Exception], ...] = ()) -> Any:
"""Emit a Sphinx event and returns first result.
This returns the result of the first handler that doesn't return ``None``.
diff --git a/sphinx/ext/apidoc.py b/sphinx/ext/apidoc.py
index 7f7d2848e..22d7212d9 100644
--- a/sphinx/ext/apidoc.py
+++ b/sphinx/ext/apidoc.py
@@ -19,7 +19,6 @@ import glob
import locale
import os
import sys
-import warnings
from copy import copy
from fnmatch import fnmatch
from importlib.machinery import EXTENSION_SUFFIXES
@@ -29,9 +28,7 @@ from typing import Any, List, Tuple
import sphinx.locale
from sphinx import __display_version__, package_dir
from sphinx.cmd.quickstart import EXTENSIONS
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.locale import __
-from sphinx.util import rst
from sphinx.util.osutil import FileAvoidWrite, ensuredir
from sphinx.util.template import ReSTRenderer
@@ -51,20 +48,6 @@ PY_SUFFIXES = ('.py', '.pyx') + tuple(EXTENSION_SUFFIXES)
template_dir = path.join(package_dir, 'templates', 'apidoc')
-def makename(package: str, module: str) -> str:
- """Join package and module with a dot."""
- warnings.warn('makename() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- # Both package and module can be None/empty.
- if package:
- name = package
- if module:
- name += '.' + module
- else:
- name = module
- return name
-
-
def is_initpy(filename: str) -> bool:
"""Check *filename* is __init__ file or not."""
basename = path.basename(filename)
@@ -109,26 +92,6 @@ def write_file(name: str, text: str, opts: Any) -> None:
f.write(text)
-def format_heading(level: int, text: str, escape: bool = True) -> str:
- """Create a heading of <level> [1, 2 or 3 supported]."""
- warnings.warn('format_warning() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- if escape:
- text = rst.escape(text)
- underlining = ['=', '-', '~', ][level - 1] * len(text)
- return '%s\n%s\n\n' % (text, underlining)
-
-
-def format_directive(module: str, package: str = None) -> str:
- """Create the automodule directive and add the options."""
- warnings.warn('format_directive() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- directive = '.. automodule:: %s\n' % module_join(package, module)
- for option in OPTIONS:
- directive += ' :%s:\n' % option
- return directive
-
-
def create_module_file(package: str, basename: str, opts: Any,
user_template_dir: str = None) -> None:
"""Build the text of the file and write the file."""
@@ -206,33 +169,6 @@ def create_modules_toc_file(modules: List[str], opts: Any, name: str = 'modules'
write_file(name, text, opts)
-def shall_skip(module: str, opts: Any, excludes: List[str] = []) -> bool:
- """Check if we want to skip this module."""
- warnings.warn('shall_skip() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- # skip if the file doesn't exist and not using implicit namespaces
- if not opts.implicit_namespaces and not path.exists(module):
- return True
-
- # Are we a package (here defined as __init__.py, not the folder in itself)
- if is_initpy(module):
- # Yes, check if we have any non-excluded modules at all here
- all_skipped = True
- basemodule = path.dirname(module)
- for submodule in glob.glob(path.join(basemodule, '*.py')):
- if not is_excluded(path.join(basemodule, submodule), excludes):
- # There's a non-excluded module here, we won't skip
- all_skipped = False
- if all_skipped:
- return True
-
- # skip if it has a "private" name and this is selected
- filename = path.basename(module)
- if is_initpy(filename) and filename.startswith('_') and not opts.includeprivate:
- return True
- return False
-
-
def is_skipped_package(dirname: str, opts: Any, excludes: List[str] = []) -> bool:
"""Check if we want to skip this module."""
if not path.isdir(dirname):
@@ -516,13 +452,6 @@ def main(argv: List[str] = sys.argv[1:]) -> int:
return 0
-deprecated_alias('sphinx.ext.apidoc',
- {
- 'INITPY': '__init__.py',
- },
- RemovedInSphinx40Warning)
-
-
# So program can be started with "python -m sphinx.apidoc ..."
if __name__ == "__main__":
main()
diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py
index bf80ef4a8..f66852a34 100644
--- a/sphinx/ext/autodoc/__init__.py
+++ b/sphinx/ext/autodoc/__init__.py
@@ -14,16 +14,15 @@ import re
import warnings
from inspect import Parameter, Signature
from types import ModuleType
-from typing import (Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type,
- TypeVar, Union)
+from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Sequence,
+ Set, Tuple, Type, TypeVar, Union)
from docutils.statemachine import StringList
import sphinx
from sphinx.application import Sphinx
from sphinx.config import ENUM, Config
-from sphinx.deprecation import (RemovedInSphinx40Warning, RemovedInSphinx50Warning,
- RemovedInSphinx60Warning)
+from sphinx.deprecation import RemovedInSphinx50Warning, RemovedInSphinx60Warning
from sphinx.environment import BuildEnvironment
from sphinx.ext.autodoc.importer import (get_class_members, get_object_members, import_module,
import_object)
@@ -37,10 +36,7 @@ from sphinx.util.inspect import (evaluate_signature, getdoc, object_description,
from sphinx.util.typing import get_type_hints, restify
from sphinx.util.typing import stringify as stringify_typehint
-if False:
- # For type annotation
- from typing import Type # NOQA # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.ext.autodoc.directive import DocumenterBridge
@@ -327,7 +323,7 @@ class Documenter:
def __init__(self, directive: "DocumenterBridge", name: str, indent: str = '') -> None:
self.directive = directive
- self.config = directive.env.config
+ self.config = directive.env.config # type: Config
self.env = directive.env # type: BuildEnvironment
self.options = directive.genopt
self.name = name
@@ -351,7 +347,7 @@ class Documenter:
self.analyzer = None # type: ModuleAnalyzer
@property
- def documenters(self) -> Dict[str, "Type[Documenter]"]:
+ def documenters(self) -> Dict[str, Type["Documenter"]]:
"""Returns registered Documenter classes"""
return self.env.app.registry.documenters
@@ -538,16 +534,12 @@ class Documenter:
# etc. don't support a prepended module name
self.add_line(' :module: %s' % self.modname, sourcename)
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
"""Decode and return lines of the docstring(s) for the object.
When it returns None value, autodoc-process-docstring will not be called for this
object.
"""
- if encoding is not None:
- warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
- % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
if ignore is not None:
warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated."
% self.__class__.__name__,
@@ -908,7 +900,7 @@ class Documenter:
# This is used for situations where you have a module that collects the
# functions and classes of internal submodules.
guess_modname = self.get_real_modname()
- self.real_modname = real_modname or guess_modname
+ self.real_modname = real_modname or guess_modname # type: str
# try to also get a source code analyzer for attribute docs
try:
@@ -1106,7 +1098,7 @@ class ModuleDocumenter(Documenter):
# Sort by __all__
def keyfunc(entry: Tuple[Documenter, bool]) -> int:
name = entry[0].name.split('::')[1]
- if name in self.__all__:
+ if self.__all__ and name in self.__all__:
return self.__all__.index(name)
else:
return len(self.__all__)
@@ -1179,12 +1171,7 @@ class DocstringSignatureMixin:
_new_docstrings = None # type: List[List[str]]
_signatures = None # type: List[str]
- def _find_signature(self, encoding: str = None) -> Tuple[str, str]:
- if encoding is not None:
- warnings.warn("The 'encoding' argument to autodoc.%s._find_signature() is "
- "deprecated." % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
-
+ def _find_signature(self) -> Tuple[str, str]:
# candidates of the object name
valid_names = [self.objpath[-1]] # type: ignore
if isinstance(self, ClassDocumenter):
@@ -1245,14 +1232,10 @@ class DocstringSignatureMixin:
return result
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
- if encoding is not None:
- warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
- % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
if self._new_docstrings is not None:
return self._new_docstrings
- return super().get_doc(None, ignore) # type: ignore
+ return super().get_doc(ignore) # type: ignore
def format_signature(self, **kwargs: Any) -> str:
if self.args is None and self.config.autodoc_docstring_signature: # type: ignore
@@ -1639,11 +1622,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
else:
return False, [m for m in members.values() if m.class_ == self.object]
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
- if encoding is not None:
- warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated."
- % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if self.doc_as_attr:
# Don't show the docstring of the class when it is an alias.
return None
@@ -1804,7 +1783,7 @@ class TypeVarMixin(DataDocumenterMixinBase):
return (isinstance(self.object, TypeVar) or
super().should_suppress_directive_header())
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if ignore is not None:
warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated."
% self.__class__.__name__,
@@ -1868,11 +1847,11 @@ class UninitializedGlobalVariableMixin(DataDocumenterMixinBase):
return (self.object is UNINITIALIZED_ATTR or
super().should_suppress_value_header())
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if self.object is UNINITIALIZED_ATTR:
return []
else:
- return super().get_doc(encoding, ignore) # type: ignore
+ return super().get_doc(ignore) # type: ignore
class DataDocumenter(GenericAliasMixin, NewTypeMixin, TypeVarMixin,
@@ -1967,13 +1946,13 @@ class DataDocumenter(GenericAliasMixin, NewTypeMixin, TypeVarMixin,
return None
- def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
# Check the variable has a docstring-comment
comment = self.get_module_comment(self.objpath[-1])
if comment:
return [comment]
else:
- return super().get_doc(encoding, ignore)
+ return super().get_doc(ignore)
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False
) -> None:
@@ -2176,13 +2155,13 @@ class NonDataDescriptorMixin(DataDocumenterMixinBase):
return (not getattr(self, 'non_data_descriptor', False) or
super().should_suppress_directive_header())
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if getattr(self, 'non_data_descriptor', False):
# the docstring of non datadescriptor is very probably the wrong thing
# to display
return None
else:
- return super().get_doc(encoding, ignore) # type: ignore
+ return super().get_doc(ignore) # type: ignore
class SlotsMixin(DataDocumenterMixinBase):
@@ -2215,7 +2194,7 @@ class SlotsMixin(DataDocumenterMixinBase):
else:
return super().should_suppress_directive_header()
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if self.object is SLOTSATTR:
try:
__slots__ = inspect.getslots(self.parent)
@@ -2229,7 +2208,7 @@ class SlotsMixin(DataDocumenterMixinBase):
(self.parent.__qualname__, exc), type='autodoc')
return []
else:
- return super().get_doc(encoding, ignore) # type: ignore
+ return super().get_doc(ignore) # type: ignore
class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase):
@@ -2333,11 +2312,11 @@ class UninitializedInstanceAttributeMixin(DataDocumenterMixinBase):
return (self.object is UNINITIALIZED_ATTR or
super().should_suppress_value_header())
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if self.object is UNINITIALIZED_ATTR:
return None
else:
- return super().get_doc(encoding, ignore) # type: ignore
+ return super().get_doc(ignore) # type: ignore
class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type: ignore
@@ -2489,7 +2468,7 @@ class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type:
return None
- def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]:
+ def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
# Check the attribute has a docstring-comment
comment = self.get_attribute_comment(self.parent, self.objpath[-1])
if comment:
@@ -2501,7 +2480,7 @@ class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type:
# ref: https://github.com/sphinx-doc/sphinx/issues/7805
orig = self.config.autodoc_inherit_docstrings
self.config.autodoc_inherit_docstrings = False # type: ignore
- return super().get_doc(encoding, ignore)
+ return super().get_doc(ignore)
finally:
self.config.autodoc_inherit_docstrings = orig # type: ignore
@@ -2566,7 +2545,7 @@ class NewTypeAttributeDocumenter(AttributeDocumenter):
return not isinstance(parent, ModuleDocumenter) and inspect.isNewType(member)
-def get_documenters(app: Sphinx) -> Dict[str, "Type[Documenter]"]:
+def get_documenters(app: Sphinx) -> Dict[str, Type[Documenter]]:
"""Returns registered Documenter classes"""
warnings.warn("get_documenters() is deprecated.", RemovedInSphinx50Warning, stacklevel=2)
return app.registry.documenters
diff --git a/sphinx/ext/autodoc/directive.py b/sphinx/ext/autodoc/directive.py
index b4c5fd28d..72407de35 100644
--- a/sphinx/ext/autodoc/directive.py
+++ b/sphinx/ext/autodoc/directive.py
@@ -7,27 +7,22 @@
"""
import warnings
-from typing import Any, Callable, Dict, List, Set
+from typing import Any, Callable, Dict, List, Set, Type
from docutils import nodes
from docutils.nodes import Element, Node
-from docutils.parsers.rst.states import RSTState, Struct
+from docutils.parsers.rst.states import RSTState
from docutils.statemachine import StringList
from docutils.utils import Reporter, assemble_option_dict
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.environment import BuildEnvironment
from sphinx.ext.autodoc import Documenter, Options
from sphinx.util import logging
from sphinx.util.docutils import SphinxDirective, switch_source_input
from sphinx.util.nodes import nested_parse_with_titles
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-
logger = logging.getLogger(__name__)
@@ -53,23 +48,14 @@ class DocumenterBridge:
"""A parameters container for Documenters."""
def __init__(self, env: BuildEnvironment, reporter: Reporter, options: Options,
- lineno: int, state: Any = None) -> None:
+ lineno: int, state: Any) -> None:
self.env = env
self._reporter = reporter
self.genopt = options
self.lineno = lineno
self.filename_set = set() # type: Set[str]
self.result = StringList()
-
- if state:
- self.state = state
- else:
- # create fake object for self.state.document.settings.tab_width
- warnings.warn('DocumenterBridge requires a state object on instantiation.',
- RemovedInSphinx40Warning, stacklevel=2)
- settings = Struct(tab_width=8)
- document = Struct(settings=settings)
- self.state = Struct(document=document)
+ self.state = state
def warn(self, msg: str) -> None:
logger.warning(msg, location=(self.env.docname, self.lineno))
diff --git a/sphinx/ext/autodoc/importer.py b/sphinx/ext/autodoc/importer.py
index ffcb27ecc..097dc6d07 100644
--- a/sphinx/ext/autodoc/importer.py
+++ b/sphinx/ext/autodoc/importer.py
@@ -11,10 +11,9 @@
import importlib
import traceback
import warnings
-from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Tuple
+from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple
-from sphinx.deprecation import (RemovedInSphinx40Warning, RemovedInSphinx50Warning,
- deprecated_alias)
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.util import logging
from sphinx.util.inspect import (getannotations, getmro, getslots, isclass, isenumclass,
@@ -166,21 +165,10 @@ def get_module_members(module: Any) -> List[Tuple[str, Any]]:
return sorted(list(members.values()))
-Attribute = NamedTuple('Attribute', [('name', str),
- ('directly_defined', bool),
- ('value', Any)])
-
-
-def _getmro(obj: Any) -> Tuple["Type", ...]:
- warnings.warn('sphinx.ext.autodoc.importer._getmro() is deprecated.',
- RemovedInSphinx40Warning)
- return getmro(obj)
-
-
-def _getannotations(obj: Any) -> Mapping[str, Any]:
- warnings.warn('sphinx.ext.autodoc.importer._getannotations() is deprecated.',
- RemovedInSphinx40Warning)
- return getannotations(obj)
+class Attribute(NamedTuple):
+ name: str
+ directly_defined: bool
+ value: Any
def get_object_members(subject: Any, objpath: List[str], attrgetter: Callable,
@@ -321,24 +309,3 @@ def get_class_members(subject: Any, objpath: List[str], attrgetter: Callable
pass
return members
-
-
-from sphinx.ext.autodoc.mock import (MockFinder, MockLoader, _MockModule, _MockObject, # NOQA
- mock)
-
-deprecated_alias('sphinx.ext.autodoc.importer',
- {
- '_MockModule': _MockModule,
- '_MockObject': _MockObject,
- 'MockFinder': MockFinder,
- 'MockLoader': MockLoader,
- 'mock': mock,
- },
- RemovedInSphinx40Warning,
- {
- '_MockModule': 'sphinx.ext.autodoc.mock._MockModule',
- '_MockObject': 'sphinx.ext.autodoc.mock._MockObject',
- 'MockFinder': 'sphinx.ext.autodoc.mock.MockFinder',
- 'MockLoader': 'sphinx.ext.autodoc.mock.MockLoader',
- 'mock': 'sphinx.ext.autodoc.mock.mock',
- })
diff --git a/sphinx/ext/autodoc/mock.py b/sphinx/ext/autodoc/mock.py
index 3d4f76410..513ce523f 100644
--- a/sphinx/ext/autodoc/mock.py
+++ b/sphinx/ext/autodoc/mock.py
@@ -14,7 +14,7 @@ import sys
from importlib.abc import Loader, MetaPathFinder
from importlib.machinery import ModuleSpec
from types import FunctionType, MethodType, ModuleType
-from typing import Any, Generator, Iterator, List, Sequence, Tuple, Union
+from typing import Any, Generator, Iterator, List, Optional, Sequence, Tuple, Union
from sphinx.util import logging
from sphinx.util.inspect import safe_getattr
@@ -118,8 +118,8 @@ class MockFinder(MetaPathFinder):
self.loader = MockLoader(self)
self.mocked_modules = [] # type: List[str]
- def find_spec(self, fullname: str, path: Sequence[Union[bytes, str]],
- target: ModuleType = None) -> ModuleSpec:
+ def find_spec(self, fullname: str, path: Optional[Sequence[Union[bytes, str]]],
+ target: ModuleType = None) -> Optional[ModuleSpec]:
for modname in self.modnames:
# check if fullname is (or is a descendant of) one of our targets
if modname == fullname or fullname.startswith(modname + '.'):
diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py
index b268127d0..7dbaaf686 100644
--- a/sphinx/ext/autosummary/__init__.py
+++ b/sphinx/ext/autosummary/__init__.py
@@ -60,19 +60,19 @@ import sys
import warnings
from os import path
from types import ModuleType
-from typing import Any, Dict, List, Tuple, cast
+from typing import Any, Dict, List, Tuple, Type, cast
from docutils import nodes
from docutils.nodes import Element, Node, system_message
from docutils.parsers.rst import directives
-from docutils.parsers.rst.states import Inliner, RSTStateMachine, Struct, state_classes
+from docutils.parsers.rst.states import RSTStateMachine, Struct, state_classes
from docutils.statemachine import StringList
import sphinx
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.environment import BuildEnvironment
from sphinx.environment.adapters.toctree import TocTree
from sphinx.ext.autodoc import INSTANCEATTR, Documenter
@@ -87,11 +87,6 @@ from sphinx.util.docutils import (NullReporter, SphinxDirective, SphinxRole, new
from sphinx.util.matching import Matcher
from sphinx.writers.html import HTMLTranslator
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-
logger = logging.getLogger(__name__)
@@ -435,29 +430,6 @@ class Autosummary(SphinxDirective):
return [table_spec, table]
- def warn(self, msg: str) -> None:
- warnings.warn('Autosummary.warn() is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- logger.warning(msg)
-
- @property
- def genopt(self) -> Options:
- warnings.warn('Autosummary.genopt is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return self.bridge.genopt
-
- @property
- def warnings(self) -> List[Node]:
- warnings.warn('Autosummary.warnings is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return []
-
- @property
- def result(self) -> StringList:
- warnings.warn('Autosummary.result is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return self.bridge.result
-
def strip_arg_typehint(s: str) -> str:
"""Strip a type hint from argument definition."""
@@ -700,33 +672,6 @@ def import_ivar_by_name(name: str, prefixes: List[str] = [None]) -> Tuple[str, A
# -- :autolink: (smart default role) -------------------------------------------
-def autolink_role(typ: str, rawtext: str, etext: str, lineno: int, inliner: Inliner,
- options: Dict = {}, content: List[str] = []
- ) -> Tuple[List[Node], List[system_message]]:
- """Smart linking role.
-
- Expands to ':obj:`text`' if `text` is an object that can be imported;
- otherwise expands to '*text*'.
- """
- warnings.warn('autolink_role() is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
- env = inliner.document.settings.env
- pyobj_role = env.get_domain('py').role('obj')
- objects, msg = pyobj_role('obj', rawtext, etext, lineno, inliner, options, content)
- if msg != []:
- return objects, msg
-
- assert len(objects) == 1
- pending_xref = cast(addnodes.pending_xref, objects[0])
- prefixes = get_import_prefixes_from_env(env)
- try:
- name, obj, parent, modname = import_by_name(pending_xref['reftarget'], prefixes)
- except ImportError:
- literal = cast(nodes.literal, pending_xref[0])
- objects[0] = nodes.emphasis(rawtext, literal.astext(), classes=literal['classes'])
-
- return objects, msg
-
-
class AutoLink(SphinxRole):
"""Smart linking role.
diff --git a/sphinx/ext/autosummary/generate.py b/sphinx/ext/autosummary/generate.py
index e21e1d94e..f972124dc 100644
--- a/sphinx/ext/autosummary/generate.py
+++ b/sphinx/ext/autosummary/generate.py
@@ -28,7 +28,7 @@ import sys
import warnings
from gettext import NullTranslations
from os import path
-from typing import Any, Callable, Dict, List, NamedTuple, Set, Tuple, Union
+from typing import Any, Dict, List, NamedTuple, Set, Tuple, Type, Union
from jinja2 import TemplateNotFound
from jinja2.sandbox import SandboxedEnvironment
@@ -38,7 +38,7 @@ from sphinx import __display_version__, package_dir
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.ext.autodoc import Documenter
from sphinx.ext.autodoc.importer import import_module
from sphinx.ext.autosummary import get_documenter, import_by_name, import_ivar_by_name
@@ -50,11 +50,6 @@ from sphinx.util.inspect import safe_getattr
from sphinx.util.osutil import ensuredir
from sphinx.util.template import SphinxTemplateLoader
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-
logger = logging.getLogger(__name__)
@@ -79,10 +74,11 @@ class DummyApplication:
pass
-AutosummaryEntry = NamedTuple('AutosummaryEntry', [('name', str),
- ('path', str),
- ('template', str),
- ('recursive', bool)])
+class AutosummaryEntry(NamedTuple):
+ name: str
+ path: str
+ template: str
+ recursive: bool
def setup_documenters(app: Any) -> None:
@@ -348,25 +344,10 @@ def generate_autosummary_content(name: str, obj: Any, parent: Any,
def generate_autosummary_docs(sources: List[str], output_dir: str = None,
- suffix: str = '.rst', warn: Callable = None,
- info: Callable = None, base_path: str = None,
+ suffix: str = '.rst', base_path: str = None,
builder: Builder = None, template_dir: str = None,
imported_members: bool = False, app: Any = None,
overwrite: bool = True, encoding: str = 'utf-8') -> None:
- if info:
- warnings.warn('info argument for generate_autosummary_docs() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- _info = info
- else:
- _info = logger.info
-
- if warn:
- warnings.warn('warn argument for generate_autosummary_docs() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- _warn = warn
- else:
- _warn = logger.warning
-
if builder:
warnings.warn('builder argument for generate_autosummary_docs() is deprecated.',
RemovedInSphinx50Warning, stacklevel=2)
@@ -378,11 +359,11 @@ def generate_autosummary_docs(sources: List[str], output_dir: str = None,
showed_sources = list(sorted(sources))
if len(showed_sources) > 20:
showed_sources = showed_sources[:10] + ['...'] + showed_sources[-10:]
- _info(__('[autosummary] generating autosummary for: %s') %
- ', '.join(showed_sources))
+ logger.info(__('[autosummary] generating autosummary for: %s') %
+ ', '.join(showed_sources))
if output_dir:
- _info(__('[autosummary] writing to %s') % output_dir)
+ logger.info(__('[autosummary] writing to %s') % output_dir)
if base_path is not None:
sources = [os.path.join(base_path, filename) for filename in sources]
@@ -419,7 +400,7 @@ def generate_autosummary_docs(sources: List[str], output_dir: str = None,
name, obj, parent, modname = import_ivar_by_name(entry.name)
qualname = name.replace(modname + ".", "")
except ImportError:
- _warn(__('[autosummary] failed to import %r: %s') % (entry.name, e))
+ logger.warning(__('[autosummary] failed to import %r: %s') % (entry.name, e))
continue
context = {}
@@ -449,8 +430,8 @@ def generate_autosummary_docs(sources: List[str], output_dir: str = None,
# descend recursively to new files
if new_files:
generate_autosummary_docs(new_files, output_dir=output_dir,
- suffix=suffix, warn=warn, info=info,
- base_path=base_path,
+ suffix=suffix, base_path=base_path,
+ builder=builder, template_dir=template_dir,
imported_members=imported_members, app=app,
overwrite=overwrite)
diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py
index 20afa2ec6..e48fca248 100644
--- a/sphinx/ext/doctest.py
+++ b/sphinx/ext/doctest.py
@@ -13,10 +13,10 @@ import doctest
import re
import sys
import time
-import warnings
from io import StringIO
from os import path
-from typing import Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple
+from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple,
+ Type)
from docutils import nodes
from docutils.nodes import Element, Node, TextElement
@@ -26,17 +26,13 @@ from packaging.version import Version
import sphinx
from sphinx.builders import Builder
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.console import bold # type: ignore
from sphinx.util.docutils import SphinxDirective
from sphinx.util.osutil import relpath
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -46,12 +42,6 @@ blankline_re = re.compile(r'^\s*<BLANKLINE>', re.MULTILINE)
doctestopt_re = re.compile(r'#\s*doctest:.+$', re.MULTILINE)
-def doctest_encode(text: str, encoding: str) -> str:
- warnings.warn('doctest_encode() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- return text
-
-
def is_allowed_version(spec: str, version: str) -> bool:
"""Check `spec` satisfies `version` or not.
diff --git a/sphinx/ext/imgmath.py b/sphinx/ext/imgmath.py
index cef50d548..a0f4ddcc3 100644
--- a/sphinx/ext/imgmath.py
+++ b/sphinx/ext/imgmath.py
@@ -26,7 +26,6 @@ from sphinx import package_dir
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.errors import SphinxError
from sphinx.locale import _, __
from sphinx.util import logging, sha1
@@ -58,35 +57,8 @@ class InvokeError(SphinxError):
SUPPORT_FORMAT = ('png', 'svg')
-DOC_HEAD = r'''
-\documentclass[12pt]{article}
-\usepackage[utf8x]{inputenc}
-\usepackage{amsmath}
-\usepackage{amsthm}
-\usepackage{amssymb}
-\usepackage{amsfonts}
-\usepackage{anyfontsize}
-\usepackage{bm}
-\pagestyle{empty}
-'''
-
-DOC_BODY = r'''
-\begin{document}
-\fontsize{%d}{%d}\selectfont %s
-\end{document}
-'''
-
-DOC_BODY_PREVIEW = r'''
-\usepackage[active]{preview}
-\begin{document}
-\begin{preview}
-\fontsize{%s}{%s}\selectfont %s
-\end{preview}
-\end{document}
-'''
-
-depth_re = re.compile(br'\[\d+ depth=(-?\d+)\]')
-depthsvg_re = re.compile(br'.*, depth=(.*)pt')
+depth_re = re.compile(r'\[\d+ depth=(-?\d+)\]')
+depthsvg_re = re.compile(r'.*, depth=(.*)pt')
depthsvgcomment_re = re.compile(r'<!-- DEPTH=(-?\d+) -->')
@@ -174,10 +146,10 @@ def compile_math(latex: str, builder: Builder) -> str:
raise MathExtError('latex exited with error', exc.stderr, exc.stdout) from exc
-def convert_dvi_to_image(command: List[str], name: str) -> Tuple[bytes, bytes]:
+def convert_dvi_to_image(command: List[str], name: str) -> Tuple[str, str]:
"""Convert DVI file to specific image format."""
try:
- ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True)
+ ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True, encoding='ascii')
return ret.stdout, ret.stderr
except OSError as exc:
logger.warning(__('%s command %r cannot be run (needed for math '
@@ -370,15 +342,6 @@ def html_visit_displaymath(self: HTMLTranslator, node: nodes.math_block) -> None
raise nodes.SkipNode
-deprecated_alias('sphinx.ext.imgmath',
- {
- 'DOC_BODY': DOC_BODY,
- 'DOC_BODY_PREVIEW': DOC_BODY_PREVIEW,
- 'DOC_HEAD': DOC_HEAD,
- },
- RemovedInSphinx40Warning)
-
-
def setup(app: Sphinx) -> Dict[str, Any]:
app.add_html_math_renderer('imgmath',
(html_visit_math, None),
diff --git a/sphinx/ext/jsmath.py b/sphinx/ext/jsmath.py
deleted file mode 100644
index cec40e224..000000000
--- a/sphinx/ext/jsmath.py
+++ /dev/null
@@ -1,33 +0,0 @@
-"""
- sphinx.ext.jsmath
- ~~~~~~~~~~~~~~~~~
-
- Set up everything for use of JSMath to display math in HTML
- via JavaScript.
-
- :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-from typing import Any, Dict
-
-from sphinxcontrib.jsmath import (html_visit_displaymath, html_visit_math, # NOQA
- install_jsmath)
-
-import sphinx
-from sphinx.application import Sphinx
-from sphinx.deprecation import RemovedInSphinx40Warning
-
-
-def setup(app: Sphinx) -> Dict[str, Any]:
- warnings.warn('sphinx.ext.jsmath has been moved to sphinxcontrib-jsmath.',
- RemovedInSphinx40Warning)
-
- app.setup_extension('sphinxcontrib.jsmath')
-
- return {
- 'version': sphinx.__display_version__,
- 'parallel_read_safe': True,
- 'parallel_write_safe': True,
- }
diff --git a/sphinx/ext/mathjax.py b/sphinx/ext/mathjax.py
index ff8ef3718..1cd2bd1cc 100644
--- a/sphinx/ext/mathjax.py
+++ b/sphinx/ext/mathjax.py
@@ -25,8 +25,7 @@ from sphinx.writers.html import HTMLTranslator
# more information for mathjax secure url is here:
# https://docs.mathjax.org/en/latest/start.html#secure-access-to-the-cdn
-MATHJAX_URL = ('https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?'
- 'config=TeX-AMS-MML_HTMLorMML')
+MATHJAX_URL = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
def html_visit_math(self: HTMLTranslator, node: nodes.math) -> None:
diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py
index 141be022e..755088ca5 100644
--- a/sphinx/ext/napoleon/docstring.py
+++ b/sphinx/ext/napoleon/docstring.py
@@ -14,7 +14,7 @@ import collections
import inspect
import re
from functools import partial
-from typing import Any, Callable, Dict, List, Tuple, Union
+from typing import Any, Callable, Dict, List, Tuple, Type, Union
from sphinx.application import Sphinx
from sphinx.config import Config as SphinxConfig
@@ -24,11 +24,6 @@ from sphinx.util import logging
from sphinx.util.inspect import stringify_annotation
from sphinx.util.typing import get_type_hints
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-
logger = logging.getLogger(__name__)
_directive_regex = re.compile(r'\.\. \S+::')
diff --git a/sphinx/ext/todo.py b/sphinx/ext/todo.py
index 640c93935..0c9a054f4 100644
--- a/sphinx/ext/todo.py
+++ b/sphinx/ext/todo.py
@@ -11,8 +11,7 @@
:license: BSD, see LICENSE for details.
"""
-import warnings
-from typing import Any, Dict, Iterable, List, Tuple, cast
+from typing import Any, Dict, List, Tuple, cast
from docutils import nodes
from docutils.nodes import Element, Node
@@ -21,14 +20,12 @@ from docutils.parsers.rst.directives.admonitions import BaseAdmonition
import sphinx
from sphinx.application import Sphinx
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.domains import Domain
from sphinx.environment import BuildEnvironment
from sphinx.errors import NoUri
from sphinx.locale import _, __
from sphinx.util import logging, texescape
from sphinx.util.docutils import SphinxDirective, new_document
-from sphinx.util.nodes import make_refnode
from sphinx.writers.html import HTMLTranslator
from sphinx.writers.latex import LaTeXTranslator
@@ -103,33 +100,6 @@ class TodoDomain(Domain):
location=todo)
-def process_todos(app: Sphinx, doctree: nodes.document) -> None:
- warnings.warn('process_todos() is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
- # collect all todos in the environment
- # this is not done in the directive itself because it some transformations
- # must have already been run, e.g. substitutions
- env = app.builder.env
- if not hasattr(env, 'todo_all_todos'):
- env.todo_all_todos = [] # type: ignore
- for node in doctree.traverse(todo_node):
- app.events.emit('todo-defined', node)
-
- newnode = node.deepcopy()
- newnode['ids'] = []
- env.todo_all_todos.append({ # type: ignore
- 'docname': env.docname,
- 'source': node.source or env.doc2path(env.docname),
- 'lineno': node.line,
- 'todo': newnode,
- 'target': node['ids'][0],
- })
-
- if env.config.todo_emit_warnings:
- label = cast(nodes.Element, node[1])
- logger.warning(__("TODO entry found: %s"), label.astext(),
- location=node)
-
-
class TodoList(SphinxDirective):
"""
A list of all todo entries.
@@ -216,80 +186,6 @@ class TodoListProcessor:
return para
-def process_todo_nodes(app: Sphinx, doctree: nodes.document, fromdocname: str) -> None:
- """Replace all todolist nodes with a list of the collected todos.
- Augment each todo with a backlink to the original location.
- """
- warnings.warn('process_todo_nodes() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- domain = cast(TodoDomain, app.env.get_domain('todo'))
- todos = sum(domain.todos.values(), []) # type: List[todo_node]
-
- for node in doctree.traverse(todolist):
- if node.get('ids'):
- content = [nodes.target()] # type: List[Element]
- else:
- content = []
-
- if not app.config['todo_include_todos']:
- node.replace_self(content)
- continue
-
- for todo_info in todos:
- para = nodes.paragraph(classes=['todo-source'])
- if app.config['todo_link_only']:
- description = _('<<original entry>>')
- else:
- description = (
- _('(The <<original entry>> is located in %s, line %d.)') %
- (todo_info.source, todo_info.line)
- )
- desc1 = description[:description.find('<<')]
- desc2 = description[description.find('>>') + 2:]
- para += nodes.Text(desc1, desc1)
-
- # Create a reference
- innernode = nodes.emphasis(_('original entry'), _('original entry'))
- try:
- para += make_refnode(app.builder, fromdocname, todo_info['docname'],
- todo_info['ids'][0], innernode)
- except NoUri:
- # ignore if no URI can be determined, e.g. for LaTeX output
- pass
- para += nodes.Text(desc2, desc2)
-
- todo_entry = todo_info.deepcopy()
- todo_entry['ids'].clear()
-
- # (Recursively) resolve references in the todo content
- app.env.resolve_references(todo_entry, todo_info['docname'], app.builder) # type: ignore # NOQA
-
- # Insert into the todolist
- content.append(todo_entry)
- content.append(para)
-
- node.replace_self(content)
-
-
-def purge_todos(app: Sphinx, env: BuildEnvironment, docname: str) -> None:
- warnings.warn('purge_todos() is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
- if not hasattr(env, 'todo_all_todos'):
- return
- env.todo_all_todos = [todo for todo in env.todo_all_todos # type: ignore
- if todo['docname'] != docname]
-
-
-def merge_info(app: Sphinx, env: BuildEnvironment, docnames: Iterable[str],
- other: BuildEnvironment) -> None:
- warnings.warn('merge_info() is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
- if not hasattr(other, 'todo_all_todos'):
- return
- if not hasattr(env, 'todo_all_todos'):
- env.todo_all_todos = [] # type: ignore
- env.todo_all_todos.extend(other.todo_all_todos) # type: ignore
-
-
def visit_todo_node(self: HTMLTranslator, node: todo_node) -> None:
if self.config.todo_include_todos:
self.visit_admonition(node)
diff --git a/sphinx/extension.py b/sphinx/extension.py
index 8129d89af..7ec6c8518 100644
--- a/sphinx/extension.py
+++ b/sphinx/extension.py
@@ -8,15 +8,14 @@
:license: BSD, see LICENSE for details.
"""
-from typing import Any, Dict
+from typing import TYPE_CHECKING, Any, Dict
from sphinx.config import Config
from sphinx.errors import VersionRequirementError
from sphinx.locale import __
from sphinx.util import logging
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
logger = logging.getLogger(__name__)
diff --git a/sphinx/io.py b/sphinx/io.py
index 3508dd58d..96f181184 100644
--- a/sphinx/io.py
+++ b/sphinx/io.py
@@ -8,8 +8,7 @@
:license: BSD, see LICENSE for details.
"""
import codecs
-import warnings
-from typing import Any, List
+from typing import TYPE_CHECKING, Any, List, Type
from docutils import nodes
from docutils.core import Publisher
@@ -23,9 +22,7 @@ from docutils.transforms.references import DanglingReferences
from docutils.writers import UnfilteredWriter
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.environment import BuildEnvironment
-from sphinx.errors import FiletypeNotFoundError
from sphinx.transforms import (AutoIndexUpgrader, DoctreeReadEvent, FigureAligner,
SphinxTransformer)
from sphinx.transforms.i18n import (Locale, PreserveTranslatableMessages,
@@ -35,10 +32,7 @@ from sphinx.util import UnicodeDecodeErrorHandler, get_filetype, logging
from sphinx.util.docutils import LoggingReporter
from sphinx.versioning import UIDTransform
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -63,18 +57,6 @@ class SphinxBaseReader(standalone.Reader):
super().__init__(*args, **kwargs)
- @property
- def app(self) -> "Sphinx":
- warnings.warn('SphinxBaseReader.app is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- return self._app
-
- @property
- def env(self) -> BuildEnvironment:
- warnings.warn('SphinxBaseReader.env is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- return self._env
-
def setup(self, app: "Sphinx") -> None:
self._app = app # hold application object only for compatibility
self._env = app.env
@@ -220,15 +202,3 @@ def read_doc(app: "Sphinx", env: BuildEnvironment, filename: str) -> nodes.docum
pub.publish()
return pub.document
-
-
-deprecated_alias('sphinx.io',
- {
- 'FiletypeNotFoundError': FiletypeNotFoundError,
- 'get_filetype': get_filetype,
- },
- RemovedInSphinx40Warning,
- {
- 'FiletypeNotFoundError': 'sphinx.errors.FiletypeNotFoundError',
- 'get_filetype': 'sphinx.util.get_filetype',
- })
diff --git a/sphinx/jinja2glue.py b/sphinx/jinja2glue.py
index c890455f3..c239f5a4a 100644
--- a/sphinx/jinja2glue.py
+++ b/sphinx/jinja2glue.py
@@ -10,7 +10,7 @@
from os import path
from pprint import pformat
-from typing import Any, Callable, Dict, Iterator, List, Tuple, Union
+from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Tuple, Union
from jinja2 import BaseLoader, FileSystemLoader, TemplateNotFound, contextfunction
from jinja2.environment import Environment
@@ -22,8 +22,7 @@ from sphinx.theming import Theme
from sphinx.util import logging
from sphinx.util.osutil import mtimes_of_files
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.builders import Builder
diff --git a/sphinx/parsers.py b/sphinx/parsers.py
index 17c291af7..2ca6ef111 100644
--- a/sphinx/parsers.py
+++ b/sphinx/parsers.py
@@ -9,7 +9,7 @@
"""
import warnings
-from typing import Any, Dict, List, Union
+from typing import TYPE_CHECKING, Any, Dict, List, Type, Union
import docutils.parsers
import docutils.parsers.rst
@@ -21,10 +21,7 @@ from docutils.transforms.universal import SmartQuotes
from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.util.rst import append_epilog, prepend_prolog
-if False:
- # For type annotation
- from typing import Type # NOQA # for python3.5.1
-
+if TYPE_CHECKING:
from docutils.transforms import Transform # NOQA
from sphinx.application import Sphinx
@@ -73,7 +70,7 @@ class Parser(docutils.parsers.Parser):
class RSTParser(docutils.parsers.rst.Parser, Parser):
"""A reST parser for Sphinx."""
- def get_transforms(self) -> List["Type[Transform]"]:
+ def get_transforms(self) -> List[Type["Transform"]]:
"""Sphinx's reST parser replaces a transform class for smart-quotes by own's
refs: sphinx.io.SphinxStandaloneReader
diff --git a/sphinx/project.py b/sphinx/project.py
index e5df4013f..258b8d4d6 100644
--- a/sphinx/project.py
+++ b/sphinx/project.py
@@ -10,15 +10,15 @@
import os
from glob import glob
+from typing import TYPE_CHECKING
from sphinx.locale import __
from sphinx.util import get_matching_files, logging, path_stabilize
from sphinx.util.matching import compile_matchers
from sphinx.util.osutil import SEP, relpath
-if False:
- # For type annotation
- from typing import Dict, List, Set # NOQA
+if TYPE_CHECKING:
+ from typing import Dict, List, Set
logger = logging.getLogger(__name__)
diff --git a/sphinx/pycode/__init__.py b/sphinx/pycode/__init__.py
index ab0dfdbf8..aaf748559 100644
--- a/sphinx/pycode/__init__.py
+++ b/sphinx/pycode/__init__.py
@@ -19,7 +19,7 @@ from os import path
from typing import IO, Any, Dict, List, Optional, Tuple
from zipfile import ZipFile
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.errors import PycodeError
from sphinx.pycode.parser import Parser
@@ -79,7 +79,7 @@ class ModuleAnalyzer:
@classmethod
def for_string(cls, string: str, modname: str, srcname: str = '<string>'
) -> "ModuleAnalyzer":
- return cls(StringIO(string), modname, srcname, decoded=True)
+ return cls(StringIO(string), modname, srcname)
@classmethod
def for_file(cls, filename: str, modname: str) -> "ModuleAnalyzer":
@@ -87,7 +87,7 @@ class ModuleAnalyzer:
return cls.cache['file', filename]
try:
with tokenize.open(filename) as f:
- obj = cls(f, modname, filename, decoded=True)
+ obj = cls(f, modname, filename)
cls.cache['file', filename] = obj
except Exception as err:
if '.egg' + path.sep in filename:
@@ -127,21 +127,12 @@ class ModuleAnalyzer:
cls.cache['module', modname] = obj
return obj
- def __init__(self, source: IO, modname: str, srcname: str, decoded: bool = False) -> None:
+ def __init__(self, source: IO, modname: str, srcname: str) -> None:
self.modname = modname # name of the module
self.srcname = srcname # name of the source file
# cache the source code as well
- pos = source.tell()
- if not decoded:
- warnings.warn('decode option for ModuleAnalyzer is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- self._encoding, _ = tokenize.detect_encoding(source.readline)
- source.seek(pos)
- self.code = source.read().decode(self._encoding)
- else:
- self._encoding = None
- self.code = source.read()
+ self.code = source.read()
# will be filled by analyze()
self.annotations = None # type: Dict[Tuple[str, str], str]
@@ -164,7 +155,7 @@ class ModuleAnalyzer:
return None
try:
- parser = Parser(self.code, self._encoding)
+ parser = Parser(self.code)
parser.parse()
self.attr_docs = OrderedDict()
@@ -192,9 +183,3 @@ class ModuleAnalyzer:
"""Find class, function and method definitions and their location."""
self.analyze()
return self.tags
-
- @property
- def encoding(self) -> str:
- warnings.warn('ModuleAnalyzer.encoding is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- return self._encoding
diff --git a/sphinx/pycode/ast.py b/sphinx/pycode/ast.py
index 65534f958..b9fbfc83d 100644
--- a/sphinx/pycode/ast.py
+++ b/sphinx/pycode/ast.py
@@ -9,7 +9,7 @@
"""
import sys
-from typing import Dict, List, Optional, Type
+from typing import Dict, List, Optional, Type, overload
if sys.version_info > (3, 8):
import ast
@@ -62,6 +62,16 @@ def parse(code: str, mode: str = 'exec') -> "ast.AST":
return ast.parse(code, mode=mode)
+@overload
+def unparse(node: None, code: str = '') -> None:
+ ...
+
+
+@overload
+def unparse(node: ast.AST, code: str = '') -> str:
+ ...
+
+
def unparse(node: Optional[ast.AST], code: str = '') -> Optional[str]:
"""Unparse an AST to string."""
if node is None:
@@ -150,6 +160,17 @@ class _UnparseVisitor(ast.NodeVisitor):
["%s=%s" % (k.arg, self.visit(k.value)) for k in node.keywords])
return "%s(%s)" % (self.visit(node.func), ", ".join(args))
+ def visit_Constant(self, node: ast.Constant) -> str: # type: ignore
+ if node.value is Ellipsis:
+ return "..."
+ elif isinstance(node.value, (int, float, complex)):
+ if self.code and sys.version_info > (3, 8):
+ return ast.get_source_segment(self.code, node) # type: ignore
+ else:
+ return repr(node.value)
+ else:
+ return repr(node.value)
+
def visit_Dict(self, node: ast.Dict) -> str:
keys = (self.visit(k) for k in node.keys)
values = (self.visit(v) for v in node.values)
@@ -197,18 +218,6 @@ class _UnparseVisitor(ast.NodeVisitor):
else:
return "()"
- if sys.version_info >= (3, 6):
- def visit_Constant(self, node: ast.Constant) -> str:
- if node.value is Ellipsis:
- return "..."
- elif isinstance(node.value, (int, float, complex)):
- if self.code and sys.version_info > (3, 8):
- return ast.get_source_segment(self.code, node)
- else:
- return repr(node.value)
- else:
- return repr(node.value)
-
if sys.version_info < (3, 8):
# these ast nodes were deprecated in python 3.8
def visit_Bytes(self, node: ast.Bytes) -> str:
diff --git a/sphinx/pycode/parser.py b/sphinx/pycode/parser.py
index dca59acd4..d157c7c1c 100644
--- a/sphinx/pycode/parser.py
+++ b/sphinx/pycode/parser.py
@@ -10,7 +10,6 @@
import inspect
import itertools
import re
-import sys
import tokenize
from collections import OrderedDict
from inspect import Signature
@@ -26,12 +25,6 @@ indent_re = re.compile('^\\s*$')
emptyline_re = re.compile('^\\s*(#.*)?$')
-if sys.version_info >= (3, 6):
- ASSIGN_NODES = (ast.Assign, ast.AnnAssign)
-else:
- ASSIGN_NODES = (ast.Assign)
-
-
def filter_whitespace(code: str) -> str:
return code.replace('\f', ' ') # replace FF (form feed) with whitespace
@@ -94,7 +87,10 @@ def dedent_docstring(s: str) -> str:
dummy.__doc__ = s
docstring = inspect.getdoc(dummy)
- return docstring.lstrip("\r\n").rstrip("\r\n")
+ if docstring:
+ return docstring.lstrip("\r\n").rstrip("\r\n")
+ else:
+ return ""
class Token:
@@ -398,13 +394,14 @@ class VariableCommentPicker(ast.NodeVisitor):
for varname in varnames:
self.add_entry(varname)
- def visit_AnnAssign(self, node: ast.AST) -> None: # Note: ast.AnnAssign not found in py35
+ def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
"""Handles AnnAssign node and pick up a variable comment."""
self.visit_Assign(node) # type: ignore
def visit_Expr(self, node: ast.Expr) -> None:
"""Handles Expr node and pick up a comment if string."""
- if (isinstance(self.previous, ASSIGN_NODES) and isinstance(node.value, ast.Str)):
+ if (isinstance(self.previous, (ast.Assign, ast.AnnAssign)) and
+ isinstance(node.value, ast.Str)):
try:
targets = get_assign_targets(self.previous)
varnames = get_lvar_names(targets[0], self.get_self())
diff --git a/sphinx/registry.py b/sphinx/registry.py
index c6a249e74..168583739 100644
--- a/sphinx/registry.py
+++ b/sphinx/registry.py
@@ -11,7 +11,7 @@
import traceback
from importlib import import_module
from types import MethodType
-from typing import Any, Callable, Dict, Iterator, List, Tuple, Union
+from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Tuple, Type, Union
from docutils import nodes
from docutils.io import Input
@@ -35,10 +35,7 @@ from sphinx.util import logging
from sphinx.util.logging import prefixed_warnings
from sphinx.util.typing import RoleFunction, TitleGetter
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.ext.autodoc import Documenter
diff --git a/sphinx/roles.py b/sphinx/roles.py
index 4f9261360..c3f594cbb 100644
--- a/sphinx/roles.py
+++ b/sphinx/roles.py
@@ -9,25 +9,18 @@
"""
import re
-import warnings
-from typing import Any, Dict, List, Tuple
+from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type
from docutils import nodes, utils
from docutils.nodes import Element, Node, TextElement, system_message
-from docutils.parsers.rst.states import Inliner
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import _
from sphinx.util import ws_re
from sphinx.util.docutils import ReferenceRole, SphinxRole
-from sphinx.util.nodes import process_index_entry, set_role_source_info, split_explicit_title
from sphinx.util.typing import RoleFunction
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.environment import BuildEnvironment
@@ -88,22 +81,6 @@ class XRefRole(ReferenceRole):
super().__init__()
- def _fix_parens(self, env: "BuildEnvironment", has_explicit_title: bool, title: str,
- target: str) -> Tuple[str, str]:
- warnings.warn('XRefRole._fix_parens() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- if not has_explicit_title:
- if title.endswith('()'):
- # remove parentheses
- title = title[:-2]
- if env.config.add_function_parentheses:
- # add them back to all occurrences if configured
- title += '()'
- # remove parentheses from the target too
- if target.endswith('()'):
- target = target[:-2]
- return title, target
-
def update_title_and_target(self, title: str, target: str) -> Tuple[str, str]:
if not self.has_explicit_title:
if title.endswith('()'):
@@ -194,75 +171,6 @@ class AnyXRefRole(XRefRole):
return result
-def indexmarkup_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner,
- options: Dict = {}, content: List[str] = []
- ) -> Tuple[List[Node], List[system_message]]:
- """Role for PEP/RFC references that generate an index entry."""
- warnings.warn('indexmarkup_role() is deprecated. Please use PEP or RFC class instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- env = inliner.document.settings.env
- if not typ:
- assert env.temp_data['default_role']
- typ = env.temp_data['default_role'].lower()
- else:
- typ = typ.lower()
-
- has_explicit_title, title, target = split_explicit_title(text)
- title = utils.unescape(title)
- target = utils.unescape(target)
- targetid = 'index-%s' % env.new_serialno('index')
- indexnode = addnodes.index()
- targetnode = nodes.target('', '', ids=[targetid])
- inliner.document.note_explicit_target(targetnode)
- if typ == 'pep':
- indexnode['entries'] = [
- ('single', _('Python Enhancement Proposals; PEP %s') % target,
- targetid, '', None)]
- anchor = ''
- anchorindex = target.find('#')
- if anchorindex > 0:
- target, anchor = target[:anchorindex], target[anchorindex:]
- if not has_explicit_title:
- title = "PEP " + utils.unescape(title)
- try:
- pepnum = int(target)
- except ValueError:
- msg = inliner.reporter.error('invalid PEP number %s' % target,
- line=lineno)
- prb = inliner.problematic(rawtext, rawtext, msg)
- return [prb], [msg]
- ref = inliner.document.settings.pep_base_url + 'pep-%04d' % pepnum
- sn = nodes.strong(title, title)
- rn = nodes.reference('', '', internal=False, refuri=ref + anchor,
- classes=[typ])
- rn += sn
- return [indexnode, targetnode, rn], []
- elif typ == 'rfc':
- indexnode['entries'] = [
- ('single', 'RFC; RFC %s' % target, targetid, '', None)]
- anchor = ''
- anchorindex = target.find('#')
- if anchorindex > 0:
- target, anchor = target[:anchorindex], target[anchorindex:]
- if not has_explicit_title:
- title = "RFC " + utils.unescape(title)
- try:
- rfcnum = int(target)
- except ValueError:
- msg = inliner.reporter.error('invalid RFC number %s' % target,
- line=lineno)
- prb = inliner.problematic(rawtext, rawtext, msg)
- return [prb], [msg]
- ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum
- sn = nodes.strong(title, title)
- rn = nodes.reference('', '', internal=False, refuri=ref + anchor,
- classes=[typ])
- rn += sn
- return [indexnode, targetnode, rn], []
- else:
- raise ValueError('unknown role type: %s' % typ)
-
-
class PEP(ReferenceRole):
def run(self) -> Tuple[List[Node], List[system_message]]:
target_id = 'index-%s' % self.env.new_serialno('index')
@@ -335,44 +243,6 @@ class RFC(ReferenceRole):
_amp_re = re.compile(r'(?<!&)&(?![&\s])')
-def menusel_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner,
- options: Dict = {}, content: List[str] = []
- ) -> Tuple[List[Node], List[system_message]]:
- warnings.warn('menusel_role() is deprecated. '
- 'Please use MenuSelection or GUILabel class instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- env = inliner.document.settings.env
- if not typ:
- assert env.temp_data['default_role']
- typ = env.temp_data['default_role'].lower()
- else:
- typ = typ.lower()
-
- text = utils.unescape(text)
- if typ == 'menuselection':
- text = text.replace('-->', '\N{TRIANGULAR BULLET}')
- spans = _amp_re.split(text)
-
- node = nodes.inline(rawtext=rawtext)
- for i, span in enumerate(spans):
- span = span.replace('&&', '&')
- if i == 0:
- if len(span) > 0:
- textnode = nodes.Text(span)
- node += textnode
- continue
- accel_node = nodes.inline()
- letter_node = nodes.Text(span[0])
- accel_node += letter_node
- accel_node['classes'].append('accelerator')
- node += accel_node
- textnode = nodes.Text(span[1:])
- node += textnode
-
- node['classes'].append(typ)
- return [node], []
-
-
class GUILabel(SphinxRole):
amp_re = re.compile(r'(?<!&)&(?![&\s])')
@@ -403,59 +273,6 @@ _litvar_re = re.compile('{([^}]+)}')
parens_re = re.compile(r'(\\*{|\\*})')
-def emph_literal_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner,
- options: Dict = {}, content: List[str] = []
- ) -> Tuple[List[Node], List[system_message]]:
- warnings.warn('emph_literal_role() is deprecated. '
- 'Please use EmphasizedLiteral class instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- env = inliner.document.settings.env
- if not typ:
- assert env.temp_data['default_role']
- typ = env.temp_data['default_role'].lower()
- else:
- typ = typ.lower()
-
- retnode = nodes.literal(role=typ.lower(), classes=[typ])
- parts = list(parens_re.split(utils.unescape(text)))
- stack = ['']
- for part in parts:
- matched = parens_re.match(part)
- if matched:
- backslashes = len(part) - 1
- if backslashes % 2 == 1: # escaped
- stack[-1] += "\\" * int((backslashes - 1) / 2) + part[-1]
- elif part[-1] == '{': # rparen
- stack[-1] += "\\" * int(backslashes / 2)
- if len(stack) >= 2 and stack[-2] == "{":
- # nested
- stack[-1] += "{"
- else:
- # start emphasis
- stack.append('{')
- stack.append('')
- else: # lparen
- stack[-1] += "\\" * int(backslashes / 2)
- if len(stack) == 3 and stack[1] == "{" and len(stack[2]) > 0:
- # emphasized word found
- if stack[0]:
- retnode += nodes.Text(stack[0], stack[0])
- retnode += nodes.emphasis(stack[2], stack[2])
- stack = ['']
- else:
- # emphasized word not found; the rparen is not a special symbol
- stack.append('}')
- stack = [''.join(stack)]
- else:
- stack[-1] += part
- if ''.join(stack):
- # remaining is treated as Text
- text = ''.join(stack)
- retnode += nodes.Text(text, text)
-
- return [retnode], []
-
-
class EmphasizedLiteral(SphinxRole):
parens_re = re.compile(r'(\\\\|\\{|\\}|{|})')
@@ -509,22 +326,6 @@ class EmphasizedLiteral(SphinxRole):
_abbr_re = re.compile(r'\((.*)\)$', re.S)
-def abbr_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner,
- options: Dict = {}, content: List[str] = []
- ) -> Tuple[List[Node], List[system_message]]:
- warnings.warn('abbr_role() is deprecated. Please use Abbrevation class instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- text = utils.unescape(text)
- m = _abbr_re.search(text)
- if m is None:
- return [nodes.abbreviation(text, text, **options)], []
- abbr = text[:m.start()].strip()
- expl = m.group(1)
- options = options.copy()
- options['explanation'] = expl
- return [nodes.abbreviation(abbr, abbr, **options)], []
-
-
class Abbreviation(SphinxRole):
abbr_re = re.compile(r'\((.*)\)$', re.S)
@@ -540,62 +341,6 @@ class Abbreviation(SphinxRole):
return [nodes.abbreviation(self.rawtext, text, **options)], []
-def index_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner,
- options: Dict = {}, content: List[str] = []
- ) -> Tuple[List[Node], List[system_message]]:
- warnings.warn('index_role() is deprecated. Please use Index class instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- # create new reference target
- env = inliner.document.settings.env
- targetid = 'index-%s' % env.new_serialno('index')
- targetnode = nodes.target('', '', ids=[targetid])
- # split text and target in role content
- has_explicit_title, title, target = split_explicit_title(text)
- title = utils.unescape(title)
- target = utils.unescape(target)
- # if an explicit target is given, we can process it as a full entry
- if has_explicit_title:
- entries = process_index_entry(target, targetid)
- # otherwise we just create a "single" entry
- else:
- # but allow giving main entry
- main = ''
- if target.startswith('!'):
- target = target[1:]
- title = title[1:]
- main = 'main'
- entries = [('single', target, targetid, main, None)]
- indexnode = addnodes.index()
- indexnode['entries'] = entries
- set_role_source_info(inliner, lineno, indexnode)
- textnode = nodes.Text(title, title)
- return [indexnode, targetnode, textnode], []
-
-
-class Index(ReferenceRole):
- def run(self) -> Tuple[List[Node], List[system_message]]:
- warnings.warn('Index role is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
- target_id = 'index-%s' % self.env.new_serialno('index')
- if self.has_explicit_title:
- # if an explicit target is given, process it as a full entry
- title = self.title
- entries = process_index_entry(self.target, target_id)
- else:
- # otherwise we just create a single entry
- if self.target.startswith('!'):
- title = self.title[1:]
- entries = [('single', self.target[1:], target_id, 'main', None)]
- else:
- title = self.title
- entries = [('single', self.target, target_id, '', None)]
-
- index = addnodes.index(entries=entries)
- target = nodes.target('', '', ids=[target_id])
- text = nodes.Text(title, title)
- self.set_source_info(index)
- return [index, target, text], []
-
-
specific_docroles = {
# links to download references
'download': XRefRole(nodeclass=addnodes.download_reference),
diff --git a/sphinx/search/__init__.py b/sphinx/search/__init__.py
index 6c748aed1..21c16e4d5 100644
--- a/sphinx/search/__init__.py
+++ b/sphinx/search/__init__.py
@@ -10,24 +10,18 @@
import html
import pickle
import re
-import warnings
from importlib import import_module
from os import path
-from typing import IO, Any, Dict, Iterable, List, Set, Tuple
+from typing import IO, Any, Dict, Iterable, List, Set, Tuple, Type
from docutils import nodes
from docutils.nodes import Node
from sphinx import addnodes, package_dir
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.environment import BuildEnvironment
from sphinx.search.jssplitter import splitter_code
from sphinx.util import jsdump
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
class SearchLanguage:
"""
@@ -116,7 +110,7 @@ var Stemmer = function() {
len(word) == 0 or not (
((len(word) < 3) and (12353 < ord(word[0]) < 12436)) or
(ord(word[0]) < 256 and (
- len(word) < 3 or word in self.stopwords
+ word in self.stopwords
))))
@@ -199,11 +193,7 @@ class WordCollector(nodes.NodeVisitor):
self.found_title_words = [] # type: List[str]
self.lang = lang
- def is_meta_keywords(self, node: addnodes.meta, nodetype: Any = None) -> bool:
- if nodetype is not None:
- warnings.warn('"nodetype" argument for WordCollector.is_meta_keywords() '
- 'is deprecated.', RemovedInSphinx40Warning, stacklevel=2)
-
+ def is_meta_keywords(self, node: addnodes.meta) -> bool:
if isinstance(node, addnodes.meta) and node.get('name') == 'keywords':
meta_lang = node.get('lang')
if meta_lang is None: # lang not specified
diff --git a/sphinx/setup_command.py b/sphinx/setup_command.py
index 0a30ff82f..dab19547e 100644
--- a/sphinx/setup_command.py
+++ b/sphinx/setup_command.py
@@ -16,6 +16,7 @@ import sys
from distutils.cmd import Command
from distutils.errors import DistutilsExecError
from io import StringIO
+from typing import TYPE_CHECKING
from sphinx.application import Sphinx
from sphinx.cmd.build import handle_exception
@@ -23,9 +24,8 @@ from sphinx.util.console import color_terminal, nocolor
from sphinx.util.docutils import docutils_namespace, patch_docutils
from sphinx.util.osutil import abspath
-if False:
- # For type annotation
- from typing import Any, Dict # NOQA
+if TYPE_CHECKING:
+ from typing import Any, Dict
class BuildDoc(Command):
diff --git a/sphinx/templates/quickstart/Makefile_t b/sphinx/templates/quickstart/Makefile_t
index af9c56304..14b2dc594 100644
--- a/sphinx/templates/quickstart/Makefile_t
+++ b/sphinx/templates/quickstart/Makefile_t
@@ -46,6 +46,7 @@ help:
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
@echo " dummy to check syntax errors of document sources"
+ @echo " clean to remove everything in the build directory"
.PHONY: clean
clean:
diff --git a/sphinx/templates/quickstart/make.bat_t b/sphinx/templates/quickstart/make.bat_t
index 830cf656e..e5d93d1ae 100644
--- a/sphinx/templates/quickstart/make.bat_t
+++ b/sphinx/templates/quickstart/make.bat_t
@@ -43,6 +43,7 @@ if "%1" == "help" (
echo. doctest to run all doctests embedded in the documentation if enabled
echo. coverage to run coverage check of the documentation if enabled
echo. dummy to check syntax errors of document sources
+ echo. clean to remove everything in the build directory
goto end
)
diff --git a/sphinx/testing/fixtures.py b/sphinx/testing/fixtures.py
index 1cf66283f..c284208ce 100644
--- a/sphinx/testing/fixtures.py
+++ b/sphinx/testing/fixtures.py
@@ -8,7 +8,6 @@
:license: BSD, see LICENSE for details.
"""
-import os
import subprocess
import sys
from collections import namedtuple
@@ -90,7 +89,6 @@ def app_params(request: Any, test_params: Dict, shared_result: SharedResult,
args = [pargs[i] for i in sorted(pargs.keys())]
# ##### process pytest.mark.test_params
-
if test_params['shared_result']:
if 'srcdir' in kwargs:
raise pytest.Exception('You can not specify shared_result and '
@@ -236,10 +234,7 @@ def sphinx_test_tempdir(tmpdir_factory: Any) -> "util.path":
"""
temporary directory that wrapped with `path` class.
"""
- tmpdir = os.environ.get('SPHINX_TEST_TEMPDIR') # RemovedInSphinx40Warning
- if tmpdir is None:
- tmpdir = tmpdir_factory.getbasetemp()
-
+ tmpdir = tmpdir_factory.getbasetemp()
return util.path(tmpdir).abspath()
diff --git a/sphinx/testing/util.py b/sphinx/testing/util.py
index 7d0cde143..7868f4d62 100644
--- a/sphinx/testing/util.py
+++ b/sphinx/testing/util.py
@@ -21,15 +21,12 @@ from docutils.nodes import Node
from docutils.parsers.rst import directives, roles
from sphinx import application, locale
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.pycode import ModuleAnalyzer
from sphinx.testing.path import path
from sphinx.util.osutil import relpath
__all__ = [
- 'Struct',
- 'SphinxTestApp', 'SphinxTestAppWrapperForSkipBuilding',
- 'remove_unicode_literals',
+ 'Struct', 'SphinxTestApp', 'SphinxTestAppWrapperForSkipBuilding',
]
@@ -177,12 +174,6 @@ class SphinxTestAppWrapperForSkipBuilding:
_unicode_literals_re = re.compile(r'u(".*?")|u(\'.*?\')')
-def remove_unicode_literals(s: str) -> str:
- warnings.warn('remove_unicode_literals() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- return _unicode_literals_re.sub(lambda x: x.group(1) or x.group(2), s)
-
-
def find_files(root: str, suffix: bool = None) -> Generator[str, None, None]:
for dirpath, dirs, files in os.walk(root, followlinks=True):
dirpath = path(dirpath)
diff --git a/sphinx/themes/basic/layout.html b/sphinx/themes/basic/layout.html
index bd56681c0..bae8ddd68 100644
--- a/sphinx/themes/basic/layout.html
+++ b/sphinx/themes/basic/layout.html
@@ -95,8 +95,6 @@
{%- endmacro %}
{%- macro css() %}
- <link rel="stylesheet" href="{{ pathto('_static/pygments.css', 1) }}" type="text/css" />
- <link rel="stylesheet" href="{{ pathto('_static/' + style, 1)|e }}" type="text/css" />
{%- for css in css_files %}
{%- if css|attr("filename") %}
{{ css_tag(css) }}
diff --git a/sphinx/themes/basic/static/basic.css_t b/sphinx/themes/basic/static/basic.css_t
index 3bb3ea705..c72d20eb6 100644
--- a/sphinx/themes/basic/static/basic.css_t
+++ b/sphinx/themes/basic/static/basic.css_t
@@ -130,7 +130,7 @@ ul.search li a {
font-weight: bold;
}
-ul.search li div.context {
+ul.search li p.context {
color: #888;
margin: 2px 0 0 30px;
text-align: left;
diff --git a/sphinx/themes/basic/static/searchtools.js b/sphinx/themes/basic/static/searchtools.js
index 6fc9e7f33..2cb28b330 100644
--- a/sphinx/themes/basic/static/searchtools.js
+++ b/sphinx/themes/basic/static/searchtools.js
@@ -501,7 +501,7 @@ var Search = {
var excerpt = ((start > 0) ? '...' : '') +
$.trim(text.substr(start, 240)) +
((start + 240 - text.length) ? '...' : '');
- var rv = $('<div class="context"></div>').text(excerpt);
+ var rv = $('<p class="context"></div>').text(excerpt);
$.each(hlwords, function() {
rv = rv.highlightText(this, 'highlighted');
});
diff --git a/sphinx/theming.py b/sphinx/theming.py
index 30e4dffdb..e84f5ae49 100644
--- a/sphinx/theming.py
+++ b/sphinx/theming.py
@@ -13,7 +13,7 @@ import os
import shutil
import tempfile
from os import path
-from typing import Any, Dict, List
+from typing import TYPE_CHECKING, Any, Dict, List
from zipfile import ZipFile
import pkg_resources
@@ -24,8 +24,7 @@ from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.osutil import ensuredir
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
diff --git a/sphinx/transforms/__init__.py b/sphinx/transforms/__init__.py
index 45640308f..8f8c5d0af 100644
--- a/sphinx/transforms/__init__.py
+++ b/sphinx/transforms/__init__.py
@@ -9,7 +9,7 @@
"""
import re
-from typing import Any, Dict, Generator, List, Tuple
+from typing import TYPE_CHECKING, Any, Dict, Generator, List, Tuple
from docutils import nodes
from docutils.nodes import Element, Node, Text
@@ -21,15 +21,13 @@ from docutils.utils.smartquotes import smartchars
from sphinx import addnodes
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.locale import _, __
from sphinx.util import docutils, logging
from sphinx.util.docutils import new_document
from sphinx.util.i18n import format_date
from sphinx.util.nodes import NodeMatcher, apply_source_workaround, is_smartquotable
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.domain.std import StandardDomain
from sphinx.environment import BuildEnvironment
@@ -400,23 +398,6 @@ class ManpageLink(SphinxTransform):
node.attributes.update(info)
-from sphinx.domains.citation import CitationDefinitionTransform # NOQA
-from sphinx.domains.citation import CitationReferenceTransform # NOQA
-
-deprecated_alias('sphinx.transforms',
- {
- 'CitationReferences': CitationReferenceTransform,
- 'SmartQuotesSkipper': CitationDefinitionTransform,
- },
- RemovedInSphinx40Warning,
- {
- 'CitationReferences':
- 'sphinx.domains.citation.CitationReferenceTransform',
- 'SmartQuotesSkipper':
- 'sphinx.domains.citation.CitationDefinitionTransform',
- })
-
-
def setup(app: "Sphinx") -> Dict[str, Any]:
app.add_transform(ApplySourceWorkaround)
app.add_transform(ExtraTranslatableNodes)
diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py
index 8520cfc69..d00c5a144 100644
--- a/sphinx/transforms/i18n.py
+++ b/sphinx/transforms/i18n.py
@@ -10,7 +10,7 @@
from os import path
from textwrap import indent
-from typing import Any, Dict, List, Tuple, TypeVar
+from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, TypeVar
from docutils import nodes
from docutils.io import StringInput
@@ -28,10 +28,7 @@ from sphinx.util.i18n import docname_to_domain
from sphinx.util.nodes import (IMAGE_TYPE_NODES, LITERAL_TYPE_NODES, NodeMatcher,
extract_messages, is_pending_meta, traverse_translatable_index)
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -245,6 +242,10 @@ class Locale(SphinxTransform):
node.details['nodes'][0]['content'] = msgstr
continue
+ if isinstance(node, nodes.image) and node.get('alt') == msg:
+ node['alt'] = msgstr
+ continue
+
# Avoid "Literal block expected; none found." warnings.
# If msgstr ends with '::' then it cause warning message at
# parser.parse() processing.
@@ -445,8 +446,9 @@ class Locale(SphinxTransform):
if isinstance(node, LITERAL_TYPE_NODES):
node.rawsource = node.astext()
- if isinstance(node, IMAGE_TYPE_NODES):
- node.update_all_atts(patch)
+ if isinstance(node, nodes.image) and node.get('alt') != msg:
+ node['uri'] = patch['uri']
+ continue # do not mark translated
node['translated'] = True # to avoid double translation
diff --git a/sphinx/transforms/post_transforms/code.py b/sphinx/transforms/post_transforms/code.py
index 20df1db3c..a880c4cd4 100644
--- a/sphinx/transforms/post_transforms/code.py
+++ b/sphinx/transforms/post_transforms/code.py
@@ -20,9 +20,11 @@ from sphinx.application import Sphinx
from sphinx.ext import doctest
from sphinx.transforms import SphinxTransform
-HighlightSetting = NamedTuple('HighlightSetting', [('language', str),
- ('force', bool),
- ('lineno_threshold', int)])
+
+class HighlightSetting(NamedTuple):
+ language: str
+ force: bool
+ lineno_threshold: int
class HighlightLanguageTransform(SphinxTransform):
diff --git a/sphinx/transforms/references.py b/sphinx/transforms/references.py
index cd564d9eb..c1afd0a2f 100644
--- a/sphinx/transforms/references.py
+++ b/sphinx/transforms/references.py
@@ -8,14 +8,13 @@
:license: BSD, see LICENSE for details.
"""
-from typing import Any, Dict
+from typing import TYPE_CHECKING, Any, Dict
from docutils.transforms.references import DanglingReferences
from sphinx.transforms import SphinxTransform
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py
index 2fbc182e5..3f1f2a95d 100644
--- a/sphinx/util/__init__.py
+++ b/sphinx/util/__init__.py
@@ -8,7 +8,6 @@
:license: BSD, see LICENSE for details.
"""
-import fnmatch
import functools
import hashlib
import os
@@ -19,20 +18,17 @@ import tempfile
import traceback
import unicodedata
import warnings
-from codecs import BOM_UTF8
-from collections import deque
from datetime import datetime
from importlib import import_module
from os import path
from time import mktime, strptime
-from typing import IO, Any, Callable, Dict, Iterable, Iterator, List, Pattern, Set, Tuple
+from typing import (IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Pattern,
+ Set, Tuple, Type)
from urllib.parse import parse_qsl, quote_plus, urlencode, urlsplit, urlunsplit
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
-from sphinx.errors import (ExtensionError, FiletypeNotFoundError, PycodeError,
- SphinxParallelError)
+from sphinx.deprecation import RemovedInSphinx50Warning
+from sphinx.errors import ExtensionError, FiletypeNotFoundError, SphinxParallelError
from sphinx.locale import __
-from sphinx.util import smartypants # noqa
from sphinx.util import logging
from sphinx.util.console import bold, colorize, strip_colors, term_width_line # type: ignore
from sphinx.util.matching import patfilter # noqa
@@ -41,13 +37,10 @@ from sphinx.util.nodes import (caption_ref_re, explicit_title_re, # noqa
# import other utilities; partly for backwards compatibility, so don't
# prune unused ones indiscriminately
from sphinx.util.osutil import (SEP, copyfile, copytimes, ensuredir, make_filename, # noqa
- movefile, mtimes_of_files, os_path, relative_uri, walk)
+ movefile, mtimes_of_files, os_path, relative_uri)
from sphinx.util.typing import PathMatcher
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -98,23 +91,6 @@ def get_matching_files(dirname: str,
yield filename
-def get_matching_docs(dirname: str, suffixes: List[str],
- exclude_matchers: Tuple[PathMatcher, ...] = ()) -> Iterable[str]:
- """Get all file names (without suffixes) matching a suffix in a directory,
- recursively.
-
- Exclude files and dirs matching a pattern in *exclude_patterns*.
- """
- warnings.warn('get_matching_docs() is now deprecated. Use get_matching_files() instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- suffixpatterns = ['*' + s for s in suffixes]
- for filename in get_matching_files(dirname, exclude_matchers):
- for suffixpattern in suffixpatterns:
- if fnmatch.fnmatch(filename, suffixpattern):
- yield filename[:-len(suffixpattern) + 1]
- break
-
-
def get_filetype(source_suffix: Dict[str, str], filename: str) -> str:
for suffix, filetype in source_suffix.items():
if filename.endswith(suffix):
@@ -272,53 +248,6 @@ def save_traceback(app: "Sphinx") -> str:
return path
-def get_module_source(modname: str) -> Tuple[str, str]:
- """Try to find the source code for a module.
-
- Can return ('file', 'filename') in which case the source is in the given
- file, or ('string', 'source') which which case the source is the string.
- """
- warnings.warn('get_module_source() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- try:
- mod = import_module(modname)
- except Exception as err:
- raise PycodeError('error importing %r' % modname, err) from err
- filename = getattr(mod, '__file__', None)
- loader = getattr(mod, '__loader__', None)
- if loader and getattr(loader, 'get_filename', None):
- try:
- filename = loader.get_filename(modname)
- except Exception as err:
- raise PycodeError('error getting filename for %r' % filename, err) from err
- if filename is None and loader:
- try:
- filename = loader.get_source(modname)
- if filename:
- return 'string', filename
- except Exception as err:
- raise PycodeError('error getting source for %r' % modname, err) from err
- if filename is None:
- raise PycodeError('no source found for module %r' % modname)
- filename = path.normpath(path.abspath(filename))
- lfilename = filename.lower()
- if lfilename.endswith('.pyo') or lfilename.endswith('.pyc'):
- filename = filename[:-1]
- if not path.isfile(filename) and path.isfile(filename + 'w'):
- filename += 'w'
- elif not (lfilename.endswith('.py') or lfilename.endswith('.pyw')):
- raise PycodeError('source is not a .py file: %r' % filename)
- elif ('.egg' + os.path.sep) in filename:
- pat = '(?<=\\.egg)' + re.escape(os.path.sep)
- eggpath, _ = re.split(pat, filename, 1)
- if path.isfile(eggpath):
- return 'file', filename
-
- if not path.isfile(filename):
- raise PycodeError('source file is not present: %r' % filename)
- return 'file', filename
-
-
def get_full_modname(modname: str, attribute: str) -> str:
if modname is None:
# Prevents a TypeError: if the last getattr() call will return None
@@ -340,58 +269,6 @@ def get_full_modname(modname: str, attribute: str) -> str:
_coding_re = re.compile(r'coding[:=]\s*([-\w.]+)')
-def detect_encoding(readline: Callable[[], bytes]) -> str:
- """Like tokenize.detect_encoding() from Py3k, but a bit simplified."""
- warnings.warn('sphinx.util.detect_encoding() is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
-
- def read_or_stop() -> bytes:
- try:
- return readline()
- except StopIteration:
- return None
-
- def get_normal_name(orig_enc: str) -> str:
- """Imitates get_normal_name in tokenizer.c."""
- # Only care about the first 12 characters.
- enc = orig_enc[:12].lower().replace('_', '-')
- if enc == 'utf-8' or enc.startswith('utf-8-'):
- return 'utf-8'
- if enc in ('latin-1', 'iso-8859-1', 'iso-latin-1') or \
- enc.startswith(('latin-1-', 'iso-8859-1-', 'iso-latin-1-')):
- return 'iso-8859-1'
- return orig_enc
-
- def find_cookie(line: bytes) -> str:
- try:
- line_string = line.decode('ascii')
- except UnicodeDecodeError:
- return None
-
- matches = _coding_re.findall(line_string)
- if not matches:
- return None
- return get_normal_name(matches[0])
-
- default = sys.getdefaultencoding()
- first = read_or_stop()
- if first and first.startswith(BOM_UTF8):
- first = first[3:]
- default = 'utf-8-sig'
- if not first:
- return default
- encoding = find_cookie(first)
- if encoding:
- return encoding
- second = read_or_stop()
- if not second:
- return default
- encoding = find_cookie(second)
- if encoding:
- return encoding
- return default
-
-
class UnicodeDecodeErrorHandler:
"""Custom error handler for open() that warns and replaces."""
@@ -460,39 +337,6 @@ def parselinenos(spec: str, total: int) -> List[int]:
return items
-def force_decode(string: str, encoding: str) -> str:
- """Forcibly get a unicode string out of a bytestring."""
- warnings.warn('force_decode() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- if isinstance(string, bytes):
- try:
- if encoding:
- string = string.decode(encoding)
- else:
- # try decoding with utf-8, should only work for real UTF-8
- string = string.decode()
- except UnicodeError:
- # last resort -- can't fail
- string = string.decode('latin1')
- return string
-
-
-class attrdict(dict):
- def __init__(self, *args: Any, **kwargs: Any) -> None:
- super().__init__(*args, **kwargs)
- warnings.warn('The attrdict class is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- def __getattr__(self, key: str) -> str:
- return self[key]
-
- def __setattr__(self, key: str, val: str) -> None:
- self[key] = val
-
- def __delattr__(self, key: str) -> None:
- del self[key]
-
-
def rpartition(s: str, t: str) -> Tuple[str, str]:
"""Similar to str.rpartition from 2.5, but doesn't return the separator."""
warnings.warn('rpartition() is now deprecated.', RemovedInSphinx50Warning, stacklevel=2)
@@ -542,41 +386,6 @@ def format_exception_cut_frames(x: int = 1) -> str:
return ''.join(res)
-class PeekableIterator:
- """
- An iterator which wraps any iterable and makes it possible to peek to see
- what's the next item.
- """
- def __init__(self, iterable: Iterable) -> None:
- self.remaining = deque() # type: deque
- self._iterator = iter(iterable)
- warnings.warn('PeekableIterator is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- def __iter__(self) -> "PeekableIterator":
- return self
-
- def __next__(self) -> Any:
- """Return the next item from the iterator."""
- if self.remaining:
- return self.remaining.popleft()
- return next(self._iterator)
-
- next = __next__ # Python 2 compatibility
-
- def push(self, item: Any) -> None:
- """Push the `item` on the internal stack, it will be returned on the
- next :meth:`next` call.
- """
- self.remaining.append(item)
-
- def peek(self) -> Any:
- """Return the next item without changing the state of the iterator."""
- item = next(self)
- self.push(item)
- return item
-
-
def import_object(objname: str, source: str = None) -> Any:
"""Import python object by qualname."""
try:
diff --git a/sphinx/util/cfamily.py b/sphinx/util/cfamily.py
index 1549fbf75..31244852c 100644
--- a/sphinx/util/cfamily.py
+++ b/sphinx/util/cfamily.py
@@ -9,7 +9,6 @@
"""
import re
-import warnings
from copy import deepcopy
from typing import Any, Callable, List, Match, Optional, Pattern, Tuple, Union
@@ -17,7 +16,6 @@ from docutils import nodes
from docutils.nodes import TextElement
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.util import logging
logger = logging.getLogger(__name__)
@@ -85,12 +83,7 @@ def verify_description_mode(mode: str) -> None:
class NoOldIdError(Exception):
# Used to avoid implementing unneeded id generation for old id schemes.
- @property
- def description(self) -> str:
- warnings.warn('%s.description is deprecated. '
- 'Coerce the instance to a string instead.' % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
- return str(self)
+ pass
class ASTBaseBase:
@@ -213,21 +206,11 @@ class ASTBaseParenExprList(ASTBaseBase):
################################################################################
class UnsupportedMultiCharacterCharLiteral(Exception):
- @property
- def decoded(self) -> str:
- warnings.warn('%s.decoded is deprecated. '
- 'Coerce the instance to a string instead.' % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
- return str(self)
+ pass
class DefinitionError(Exception):
- @property
- def description(self) -> str:
- warnings.warn('%s.description is deprecated. '
- 'Coerce the instance to a string instead.' % self.__class__.__name__,
- RemovedInSphinx40Warning, stacklevel=2)
- return str(self)
+ pass
class BaseParser:
diff --git a/sphinx/util/compat.py b/sphinx/util/compat.py
index dbe902be7..9be80358e 100644
--- a/sphinx/util/compat.py
+++ b/sphinx/util/compat.py
@@ -9,17 +9,9 @@
"""
import sys
-import warnings
-from typing import Any, Dict
+from typing import TYPE_CHECKING, Any, Dict
-from docutils.utils import get_source_line
-
-from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx40Warning
-from sphinx.transforms import SphinxTransform
-
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
@@ -36,22 +28,7 @@ def register_application_for_autosummary(app: "Sphinx") -> None:
autosummary._app = app
-class IndexEntriesMigrator(SphinxTransform):
- """Migrating indexentries from old style (4columns) to new style (5columns)."""
- default_priority = 700
-
- def apply(self, **kwargs: Any) -> None:
- for node in self.document.traverse(addnodes.index):
- for i, entries in enumerate(node['entries']):
- if len(entries) == 4:
- source, line = get_source_line(node)
- warnings.warn('An old styled index node found: %r at (%s:%s)' %
- (node, source, line), RemovedInSphinx40Warning, stacklevel=2)
- node['entries'][i] = entries + (None,)
-
-
def setup(app: "Sphinx") -> Dict[str, Any]:
- app.add_transform(IndexEntriesMigrator)
app.connect('builder-inited', register_application_for_autosummary)
return {
diff --git a/sphinx/util/docfields.py b/sphinx/util/docfields.py
index 3fc72340a..79abfe14b 100644
--- a/sphinx/util/docfields.py
+++ b/sphinx/util/docfields.py
@@ -9,20 +9,15 @@
:license: BSD, see LICENSE for details.
"""
-import warnings
-from typing import Any, Dict, List, Tuple, Union, cast
+from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, Union, cast
from docutils import nodes
from docutils.nodes import Node
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.util.typing import TextlikeNode
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.directive import ObjectDescription
from sphinx.environment import BuildEnvironment
@@ -219,26 +214,7 @@ class DocFieldTransformer:
def __init__(self, directive: "ObjectDescription") -> None:
self.directive = directive
- try:
- self.typemap = directive.get_field_type_map()
- except Exception:
- # for 3rd party extensions directly calls this transformer.
- warnings.warn('DocFieldTransformer expects given directive object is a subclass '
- 'of ObjectDescription.', RemovedInSphinx40Warning, stacklevel=2)
- self.typemap = self.preprocess_fieldtypes(directive.__class__.doc_field_types)
-
- def preprocess_fieldtypes(self, types: List[Field]) -> Dict[str, Tuple[Field, bool]]:
- warnings.warn('DocFieldTransformer.preprocess_fieldtypes() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- typemap = {}
- for fieldtype in types:
- for name in fieldtype.names:
- typemap[name] = fieldtype, False
- if fieldtype.is_typed:
- typed_field = cast(TypedField, fieldtype)
- for name in typed_field.typenames:
- typemap[name] = typed_field, True
- return typemap
+ self.typemap = directive.get_field_type_map()
def transform_all(self, node: addnodes.desc_content) -> None:
"""Transform all field list children of a node."""
diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py
index ce50c7ab1..a3e49e6d7 100644
--- a/sphinx/util/docutils.py
+++ b/sphinx/util/docutils.py
@@ -15,7 +15,8 @@ from copy import copy
from distutils.version import LooseVersion
from os import path
from types import ModuleType
-from typing import IO, Any, Callable, Dict, Generator, List, Optional, Set, Tuple, cast
+from typing import (IO, TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Set,
+ Tuple, Type, cast)
import docutils
from docutils import nodes
@@ -27,16 +28,14 @@ from docutils.statemachine import State, StateMachine, StringList
from docutils.utils import Reporter, unescape
from sphinx.errors import SphinxError
+from sphinx.locale import _
from sphinx.util import logging
from sphinx.util.typing import RoleFunction
logger = logging.getLogger(__name__)
report_re = re.compile('^(.+?:(?:\\d+)?): \\((DEBUG|INFO|WARNING|ERROR|SEVERE)/(\\d+)?\\) ')
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.builders import Builder
from sphinx.config import Config
from sphinx.environment import BuildEnvironment
@@ -145,7 +144,7 @@ def patched_get_language() -> Generator[None, None, None]:
@contextmanager
-def using_user_docutils_conf(confdir: str) -> Generator[None, None, None]:
+def using_user_docutils_conf(confdir: Optional[str]) -> Generator[None, None, None]:
"""Let docutils know the location of ``docutils.conf`` for Sphinx."""
try:
docutilsconfig = os.environ.get('DOCUTILSCONFIG', None)
@@ -161,7 +160,7 @@ def using_user_docutils_conf(confdir: str) -> Generator[None, None, None]:
@contextmanager
-def patch_docutils(confdir: str = None) -> Generator[None, None, None]:
+def patch_docutils(confdir: Optional[str] = None) -> Generator[None, None, None]:
"""Patch to docutils temporarily."""
with patched_get_language(), using_user_docutils_conf(confdir):
yield
@@ -210,6 +209,8 @@ class sphinx_domains:
element = getattr(domain, type)(name)
if element is not None:
return element, []
+ else:
+ logger.warning(_('unknown directive or role name: %s:%s'), domain_name, name)
# else look in the default domain
else:
def_domain = self.env.temp_data.get('default_domain')
@@ -347,15 +348,15 @@ class SphinxRole:
.. note:: The subclasses of this class might not work with docutils.
This class is strongly coupled with Sphinx.
"""
- name = None #: The role name actually used in the document.
- rawtext = None #: A string containing the entire interpreted text input.
- text = None #: The interpreted text content.
- lineno = None #: The line number where the interpreted text begins.
- inliner = None #: The ``docutils.parsers.rst.states.Inliner`` object.
- options = None #: A dictionary of directive options for customization
- #: (from the "role" directive).
- content = None #: A list of strings, the directive content for customization
- #: (from the "role" directive).
+ name: str #: The role name actually used in the document.
+ rawtext: str #: A string containing the entire interpreted text input.
+ text: str #: The interpreted text content.
+ lineno: int #: The line number where the interpreted text begins.
+ inliner: Inliner #: The ``docutils.parsers.rst.states.Inliner`` object.
+ options: Dict #: A dictionary of directive options for customization
+ #: (from the "role" directive).
+ content: List[str] #: A list of strings, the directive content for customization
+ #: (from the "role" directive).
def __call__(self, name: str, rawtext: str, text: str, lineno: int,
inliner: Inliner, options: Dict = {}, content: List[str] = []
@@ -408,10 +409,10 @@ class ReferenceRole(SphinxRole):
the role. The parsed result; link title and target will be stored to
``self.title`` and ``self.target``.
"""
- has_explicit_title = None #: A boolean indicates the role has explicit title or not.
- disabled = False #: A boolean indicates the reference is disabled.
- title = None #: The link title for the interpreted text.
- target = None #: The link target for the interpreted text.
+ has_explicit_title: bool #: A boolean indicates the role has explicit title or not.
+ disabled: bool #: A boolean indicates the reference is disabled.
+ title: str #: The link title for the interpreted text.
+ target: str #: The link target for the interpreted text.
# \x00 means the "<" was backslash-escaped
explicit_title_re = re.compile(r'^(.+?)\s*(?<!\x00)<(.*?)>$', re.DOTALL)
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
index 466c28135..37c038855 100644
--- a/sphinx/util/fileutil.py
+++ b/sphinx/util/fileutil.py
@@ -10,15 +10,14 @@
import os
import posixpath
-from typing import Callable, Dict
+from typing import TYPE_CHECKING, Callable, Dict
from docutils.utils import relative_path
from sphinx.util.osutil import copyfile, ensuredir
from sphinx.util.typing import PathMatcher
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.util.template import BaseRenderer
diff --git a/sphinx/util/i18n.py b/sphinx/util/i18n.py
index 6ea004bb0..3a5aca58e 100644
--- a/sphinx/util/i18n.py
+++ b/sphinx/util/i18n.py
@@ -7,34 +7,33 @@
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-import gettext
+
import os
import re
-import warnings
-from collections import namedtuple
from datetime import datetime, timezone
from os import path
-from typing import Callable, Generator, List, Set, Tuple, Union
+from typing import TYPE_CHECKING, Callable, Generator, List, NamedTuple, Tuple, Union
import babel.dates
from babel.messages.mofile import write_mo
from babel.messages.pofile import read_po
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.errors import SphinxError
from sphinx.locale import __
from sphinx.util import logging
-from sphinx.util.matching import Matcher
from sphinx.util.osutil import SEP, canon_path, relpath
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.environment import BuildEnvironment
logger = logging.getLogger(__name__)
-LocaleFileInfoBase = namedtuple('CatalogInfo', 'base_dir,domain,charset')
+
+class LocaleFileInfoBase(NamedTuple):
+ base_dir: str
+ domain: str
+ charset: str
class CatalogInfo(LocaleFileInfoBase):
@@ -117,17 +116,6 @@ class CatalogRepository:
yield CatalogInfo(basedir, domain, self.encoding)
-def find_catalog(docname: str, compaction: bool) -> str:
- warnings.warn('find_catalog() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- if compaction:
- ret = docname.split(SEP, 1)[0]
- else:
- ret = docname
-
- return ret
-
-
def docname_to_domain(docname: str, compation: Union[bool, str]) -> str:
"""Convert docname to domain for catalogs."""
if isinstance(compation, str):
@@ -138,69 +126,6 @@ def docname_to_domain(docname: str, compation: Union[bool, str]) -> str:
return docname
-def find_catalog_files(docname: str, srcdir: str, locale_dirs: List[str],
- lang: str, compaction: bool) -> List[str]:
- warnings.warn('find_catalog_files() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- if not(lang and locale_dirs):
- return []
-
- domain = find_catalog(docname, compaction)
- files = [gettext.find(domain, path.join(srcdir, dir_), [lang])
- for dir_ in locale_dirs]
- files = [relpath(f, srcdir) for f in files if f]
- return files
-
-
-def find_catalog_source_files(locale_dirs: List[str], locale: str, domains: List[str] = None,
- charset: str = 'utf-8', force_all: bool = False,
- excluded: Matcher = Matcher([])) -> Set[CatalogInfo]:
- """
- :param list locale_dirs:
- list of path as `['locale_dir1', 'locale_dir2', ...]` to find
- translation catalogs. Each path contains a structure such as
- `<locale>/LC_MESSAGES/domain.po`.
- :param str locale: a language as `'en'`
- :param list domains: list of domain names to get. If empty list or None
- is specified, get all domain names. default is None.
- :param boolean force_all:
- Set True if you want to get all catalogs rather than updated catalogs.
- default is False.
- :return: [CatalogInfo(), ...]
- """
- warnings.warn('find_catalog_source_files() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- catalogs = set() # type: Set[CatalogInfo]
-
- if not locale:
- return catalogs # locale is not specified
-
- for locale_dir in locale_dirs:
- if not locale_dir:
- continue # skip system locale directory
-
- base_dir = path.join(locale_dir, locale, 'LC_MESSAGES')
-
- if not path.exists(base_dir):
- continue # locale path is not found
-
- for dirpath, dirnames, filenames in os.walk(base_dir, followlinks=True):
- filenames = [f for f in filenames if f.endswith('.po')]
- for filename in filenames:
- if excluded(path.join(relpath(dirpath, base_dir), filename)):
- continue
- base = path.splitext(filename)[0]
- domain = relpath(path.join(dirpath, base), base_dir).replace(path.sep, SEP)
- if domains and domain not in domains:
- continue
- cat = CatalogInfo(base_dir, domain, charset)
- if force_all or cat.is_outdated():
- catalogs.add(cat)
-
- return catalogs
-
-
# date_format mappings: ustrftime() to bable.dates.format_datetime()
date_format_mappings = {
'%a': 'EEE', # Weekday as locale’s abbreviated name.
diff --git a/sphinx/util/images.py b/sphinx/util/images.py
index 81a321818..8c32e3414 100644
--- a/sphinx/util/images.py
+++ b/sphinx/util/images.py
@@ -31,9 +31,11 @@ mime_suffixes = OrderedDict([
('.ai', 'application/illustrator'),
])
-DataURI = NamedTuple('DataURI', [('mimetype', str),
- ('charset', str),
- ('data', bytes)])
+
+class DataURI(NamedTuple):
+ mimetype: str
+ charset: str
+ data: bytes
def get_image_size(filename: str) -> Optional[Tuple[int, int]]:
diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py
index e91e5df96..85186cf0b 100644
--- a/sphinx/util/inspect.py
+++ b/sphinx/util/inspect.py
@@ -20,10 +20,10 @@ import warnings
from functools import partial, partialmethod
from inspect import Parameter, isclass, ismethod, ismethoddescriptor, ismodule # NOQA
from io import StringIO
-from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, cast
+from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, cast
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
-from sphinx.pycode.ast import ast # for py35-37
+from sphinx.deprecation import RemovedInSphinx50Warning
+from sphinx.pycode.ast import ast # for py36-37
from sphinx.pycode.ast import unparse as ast_unparse
from sphinx.util import logging
from sphinx.util.typing import ForwardRef
@@ -339,7 +339,7 @@ def is_singledispatch_method(obj: Any) -> bool:
try:
from functools import singledispatchmethod # type: ignore
return isinstance(obj, singledispatchmethod)
- except ImportError: # py35-37
+ except ImportError: # py36-37
return False
@@ -417,23 +417,6 @@ def safe_getattr(obj: Any, name: str, *defargs: Any) -> Any:
raise AttributeError(name) from exc
-def safe_getmembers(object: Any, predicate: Callable[[str], bool] = None,
- attr_getter: Callable = safe_getattr) -> List[Tuple[str, Any]]:
- """A version of inspect.getmembers() that uses safe_getattr()."""
- warnings.warn('safe_getmembers() is deprecated', RemovedInSphinx40Warning, stacklevel=2)
-
- results = [] # type: List[Tuple[str, Any]]
- for key in dir(object):
- try:
- value = attr_getter(object, key, None)
- except AttributeError:
- continue
- if not predicate or predicate(value):
- results.append((key, value))
- results.sort()
- return results
-
-
def object_description(object: Any) -> str:
"""A repr() implementation that returns text safe to use in reST context."""
if isinstance(object, dict):
@@ -741,154 +724,6 @@ def signature_from_ast(node: ast.FunctionDef, code: str = '') -> inspect.Signatu
return inspect.Signature(params, return_annotation=return_annotation)
-class Signature:
- """The Signature object represents the call signature of a callable object and
- its return annotation.
- """
-
- empty = inspect.Signature.empty
-
- def __init__(self, subject: Callable, bound_method: bool = False,
- has_retval: bool = True) -> None:
- warnings.warn('sphinx.util.inspect.Signature() is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
-
- # check subject is not a built-in class (ex. int, str)
- if (isinstance(subject, type) and
- is_builtin_class_method(subject, "__new__") and
- is_builtin_class_method(subject, "__init__")):
- raise TypeError("can't compute signature for built-in type {}".format(subject))
-
- self.subject = subject
- self.has_retval = has_retval
- self.partialmethod_with_noargs = False
-
- try:
- self.signature = inspect.signature(subject) # type: Optional[inspect.Signature]
- except IndexError:
- # Until python 3.6.4, cpython has been crashed on inspection for
- # partialmethods not having any arguments.
- # https://bugs.python.org/issue33009
- if hasattr(subject, '_partialmethod'):
- self.signature = None
- self.partialmethod_with_noargs = True
- else:
- raise
-
- try:
- self.annotations = typing.get_type_hints(subject)
- except Exception:
- # get_type_hints() does not support some kind of objects like partial,
- # ForwardRef and so on. For them, it raises an exception. In that case,
- # we try to build annotations from argspec.
- self.annotations = {}
-
- if bound_method:
- # client gives a hint that the subject is a bound method
-
- if inspect.ismethod(subject):
- # inspect.signature already considers the subject is bound method.
- # So it is not need to skip first argument.
- self.skip_first_argument = False
- else:
- self.skip_first_argument = True
- else:
- # inspect.signature recognizes type of method properly without any hints
- self.skip_first_argument = False
-
- @property
- def parameters(self) -> Mapping:
- if self.partialmethod_with_noargs:
- return {}
- else:
- return self.signature.parameters
-
- @property
- def return_annotation(self) -> Any:
- if self.signature:
- if self.has_retval:
- return self.signature.return_annotation
- else:
- return Parameter.empty
- else:
- return None
-
- def format_args(self, show_annotation: bool = True) -> str:
- def get_annotation(param: Parameter) -> Any:
- if isinstance(param.annotation, str) and param.name in self.annotations:
- return self.annotations[param.name]
- else:
- return param.annotation
-
- args = []
- last_kind = None
- for i, param in enumerate(self.parameters.values()):
- # skip first argument if subject is bound method
- if self.skip_first_argument and i == 0:
- continue
-
- arg = StringIO()
-
- # insert '*' between POSITIONAL args and KEYWORD_ONLY args::
- # func(a, b, *, c, d):
- if param.kind == param.KEYWORD_ONLY and last_kind in (param.POSITIONAL_OR_KEYWORD,
- param.POSITIONAL_ONLY,
- None):
- args.append('*')
-
- if param.kind in (param.POSITIONAL_ONLY,
- param.POSITIONAL_OR_KEYWORD,
- param.KEYWORD_ONLY):
- arg.write(param.name)
- if show_annotation and param.annotation is not param.empty:
- arg.write(': ')
- arg.write(stringify_annotation(get_annotation(param)))
- if param.default is not param.empty:
- if param.annotation is param.empty or show_annotation is False:
- arg.write('=')
- arg.write(object_description(param.default))
- else:
- arg.write(' = ')
- arg.write(object_description(param.default))
- elif param.kind == param.VAR_POSITIONAL:
- arg.write('*')
- arg.write(param.name)
- if show_annotation and param.annotation is not param.empty:
- arg.write(': ')
- arg.write(stringify_annotation(get_annotation(param)))
- elif param.kind == param.VAR_KEYWORD:
- arg.write('**')
- arg.write(param.name)
- if show_annotation and param.annotation is not param.empty:
- arg.write(': ')
- arg.write(stringify_annotation(get_annotation(param)))
-
- args.append(arg.getvalue())
- last_kind = param.kind
-
- if self.return_annotation is Parameter.empty or show_annotation is False:
- return '(%s)' % ', '.join(args)
- else:
- if 'return' in self.annotations:
- annotation = stringify_annotation(self.annotations['return'])
- else:
- annotation = stringify_annotation(self.return_annotation)
-
- return '(%s) -> %s' % (', '.join(args), annotation)
-
- def format_annotation(self, annotation: Any) -> str:
- """Return formatted representation of a type annotation."""
- return stringify_annotation(annotation)
-
- def format_annotation_new(self, annotation: Any) -> str:
- """format_annotation() for py37+"""
- return stringify_annotation(annotation)
-
- def format_annotation_old(self, annotation: Any) -> str:
- """format_annotation() for py36 or below"""
- return stringify_annotation(annotation)
-
-
def getdoc(obj: Any, attrgetter: Callable = safe_getattr,
allow_inherited: bool = False, cls: Any = None, name: str = None) -> str:
"""Get the docstring for the object.
diff --git a/sphinx/util/inventory.py b/sphinx/util/inventory.py
index b1af1bfb9..40ac87997 100644
--- a/sphinx/util/inventory.py
+++ b/sphinx/util/inventory.py
@@ -10,7 +10,7 @@
import os
import re
import zlib
-from typing import IO, Callable, Iterator
+from typing import IO, TYPE_CHECKING, Callable, Iterator
from sphinx.util import logging
from sphinx.util.typing import Inventory
@@ -18,8 +18,7 @@ from sphinx.util.typing import Inventory
BUFSIZE = 16 * 1024
logger = logging.getLogger(__name__)
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment
diff --git a/sphinx/util/jsonimpl.py b/sphinx/util/jsonimpl.py
deleted file mode 100644
index b038fd4db..000000000
--- a/sphinx/util/jsonimpl.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""
- sphinx.util.jsonimpl
- ~~~~~~~~~~~~~~~~~~~~
-
- JSON serializer implementation wrapper.
-
- :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import json
-import warnings
-from collections import UserString
-from typing import IO, Any
-
-from sphinx.deprecation import RemovedInSphinx40Warning
-
-warnings.warn('sphinx.util.jsonimpl is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
-
-
-class SphinxJSONEncoder(json.JSONEncoder):
- """JSONEncoder subclass that forces translation proxies."""
- def default(self, obj: Any) -> str:
- if isinstance(obj, UserString):
- return str(obj)
- return super().default(obj)
-
-
-def dump(obj: Any, fp: IO, *args: Any, **kwargs: Any) -> None:
- kwargs['cls'] = SphinxJSONEncoder
- json.dump(obj, fp, *args, **kwargs)
-
-
-def dumps(obj: Any, *args: Any, **kwargs: Any) -> str:
- kwargs['cls'] = SphinxJSONEncoder
- return json.dumps(obj, *args, **kwargs)
-
-
-def load(*args: Any, **kwargs: Any) -> Any:
- return json.load(*args, **kwargs)
-
-
-def loads(*args: Any, **kwargs: Any) -> Any:
- return json.loads(*args, **kwargs)
diff --git a/sphinx/util/logging.py b/sphinx/util/logging.py
index 09780723a..1c480e017 100644
--- a/sphinx/util/logging.py
+++ b/sphinx/util/logging.py
@@ -12,7 +12,7 @@ import logging
import logging.handlers
from collections import defaultdict
from contextlib import contextmanager
-from typing import IO, Any, Dict, Generator, List, Tuple, Union
+from typing import IO, TYPE_CHECKING, Any, Dict, Generator, List, Tuple, Type, Union
from docutils import nodes
from docutils.nodes import Node
@@ -21,10 +21,7 @@ from docutils.utils import get_source_line
from sphinx.errors import SphinxWarning
from sphinx.util.console import colorize
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.application import Sphinx
diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py
index d5e43e716..944fd3ecb 100644
--- a/sphinx/util/nodes.py
+++ b/sphinx/util/nodes.py
@@ -10,8 +10,7 @@
import re
import unicodedata
-import warnings
-from typing import Any, Callable, Iterable, List, Set, Tuple, cast
+from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Set, Tuple, Type, cast
from docutils import nodes
from docutils.nodes import Element, Node
@@ -20,14 +19,10 @@ from docutils.parsers.rst.states import Inliner
from docutils.statemachine import StringList
from sphinx import addnodes
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import __
from sphinx.util import logging
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
+if TYPE_CHECKING:
from sphinx.builders import Builder
from sphinx.domain import IndexEntry
from sphinx.environment import BuildEnvironment
@@ -201,6 +196,10 @@ def is_translatable(node: Node) -> bool:
if isinstance(node, addnodes.translatable):
return True
+ # image node marked as translatable or having alt text
+ if isinstance(node, nodes.image) and (node.get('translatable') or node.get('alt')):
+ return True
+
if isinstance(node, nodes.Inline) and 'translatable' not in node: # type: ignore
# inline node must not be translated if 'translatable' is not set
return False
@@ -228,9 +227,6 @@ def is_translatable(node: Node) -> bool:
return False
return True
- if isinstance(node, nodes.image) and node.get('translatable'):
- return True
-
if isinstance(node, addnodes.meta):
return True
if is_pending_meta(node):
@@ -264,10 +260,13 @@ def extract_messages(doctree: Element) -> Iterable[Tuple[Element, str]]:
msg = node.rawsource
if not msg:
msg = node.astext()
- elif isinstance(node, IMAGE_TYPE_NODES):
- msg = '.. image:: %s' % node['uri']
+ elif isinstance(node, nodes.image):
if node.get('alt'):
- msg += '\n :alt: %s' % node['alt']
+ yield node, node['alt']
+ if node.get('translatable'):
+ msg = '.. image:: %s' % node['uri']
+ else:
+ msg = None
elif isinstance(node, META_TYPE_NODES):
msg = node.rawcontent
elif isinstance(node, nodes.pending) and is_pending_meta(node):
@@ -280,12 +279,6 @@ def extract_messages(doctree: Element) -> Iterable[Tuple[Element, str]]:
yield node, msg
-def find_source_node(node: Element) -> str:
- warnings.warn('find_source_node() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- return get_node_source(node)
-
-
def get_node_source(node: Element) -> str:
for pnode in traverse_parent(node):
if pnode.source:
@@ -613,10 +606,12 @@ def process_only_nodes(document: Node, tags: "Tags") -> None:
node.replace_self(nodes.comment())
-# monkey-patch Element.copy to copy the rawsource and line
-# for docutils-0.14 or older versions.
-
def _new_copy(self: Element) -> Element:
+ """monkey-patch Element.copy to copy the rawsource and line
+ for docutils-0.16 or older versions.
+
+ refs: https://sourceforge.net/p/docutils/patches/165/
+ """
newnode = self.__class__(self.rawsource, **self.attributes)
if isinstance(self, nodes.Element):
newnode.source = self.source
diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py
index 53bffd929..5ee2eccc8 100644
--- a/sphinx/util/osutil.py
+++ b/sphinx/util/osutil.py
@@ -9,7 +9,6 @@
"""
import contextlib
-import errno
import filecmp
import os
import re
@@ -18,9 +17,9 @@ import sys
import warnings
from io import StringIO
from os import path
-from typing import Any, Generator, Iterator, List, Optional, Tuple
+from typing import Any, Generator, Iterator, List, Optional, Type
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
try:
# for ALT Linux (#6712)
@@ -28,15 +27,6 @@ try:
except ImportError:
Path = None # type: ignore
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
-# Errnos that we need.
-EEXIST = getattr(errno, 'EEXIST', 0) # RemovedInSphinx40Warning
-ENOENT = getattr(errno, 'ENOENT', 0) # RemovedInSphinx40Warning
-EPIPE = getattr(errno, 'EPIPE', 0) # RemovedInSphinx40Warning
-EINVAL = getattr(errno, 'EINVAL', 0) # RemovedInSphinx40Warning
# SEP separates path elements in the canonical file names
#
@@ -83,13 +73,6 @@ def ensuredir(path: str) -> None:
os.makedirs(path, exist_ok=True)
-def walk(top: str, topdown: bool = True, followlinks: bool = False) -> Iterator[Tuple[str, List[str], List[str]]]: # NOQA
- warnings.warn('sphinx.util.osutil.walk() is deprecated for removal. '
- 'Please use os.walk() instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- return os.walk(top, topdown=topdown, followlinks=followlinks)
-
-
def mtimes_of_files(dirnames: List[str], suffix: str) -> Iterator[float]:
for dirname in dirnames:
for root, dirs, files in os.walk(dirname):
@@ -178,13 +161,6 @@ def abspath(pathdir: str) -> str:
return pathdir
-def getcwd() -> str:
- warnings.warn('sphinx.util.osutil.getcwd() is deprecated. '
- 'Please use os.getcwd() instead.',
- RemovedInSphinx40Warning, stacklevel=2)
- return os.getcwd()
-
-
@contextlib.contextmanager
def cd(target_dir: str) -> Generator[None, None, None]:
cwd = os.getcwd()
diff --git a/sphinx/util/pycompat.py b/sphinx/util/pycompat.py
index 87c38f72e..bb0c0b685 100644
--- a/sphinx/util/pycompat.py
+++ b/sphinx/util/pycompat.py
@@ -8,28 +8,21 @@
:license: BSD, see LICENSE for details.
"""
-import html
-import io
-import sys
-import textwrap
import warnings
from typing import Any, Callable
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
-from sphinx.locale import __
-from sphinx.util import logging
-from sphinx.util.console import terminal_safe
-from sphinx.util.typing import NoneType
-
-logger = logging.getLogger(__name__)
-
+from sphinx.deprecation import RemovedInSphinx60Warning
# ------------------------------------------------------------------------------
# Python 2/3 compatibility
+
# convert_with_2to3():
# support for running 2to3 over config files
def convert_with_2to3(filepath: str) -> str:
+ warnings.warn('convert_with_2to3() is deprecated',
+ RemovedInSphinx60Warning, stacklevel=2)
+
try:
from lib2to3.pgen2.parse import ParseError
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
@@ -53,57 +46,14 @@ def convert_with_2to3(filepath: str) -> str:
return str(tree)
-class UnicodeMixin:
- """Mixin class to handle defining the proper __str__/__unicode__
- methods in Python 2 or 3.
-
- .. deprecated:: 2.0
- """
- def __str__(self) -> str:
- warnings.warn('UnicodeMixin is deprecated',
- RemovedInSphinx40Warning, stacklevel=2)
- return self.__unicode__() # type: ignore
-
-
def execfile_(filepath: str, _globals: Any, open: Callable = open) -> None:
+ warnings.warn('execfile_() is deprecated',
+ RemovedInSphinx60Warning, stacklevel=2)
from sphinx.util.osutil import fs_encoding
with open(filepath, 'rb') as f:
source = f.read()
# compile to a code object, handle syntax errors
filepath_enc = filepath.encode(fs_encoding)
- try:
- code = compile(source, filepath_enc, 'exec')
- except SyntaxError:
- # maybe the file uses 2.x syntax; try to refactor to
- # 3.x syntax using 2to3
- source = convert_with_2to3(filepath)
- code = compile(source, filepath_enc, 'exec')
- # TODO: When support for evaluating Python 2 syntax is removed,
- # deprecate convert_with_2to3().
- logger.warning(__('Support for evaluating Python 2 syntax is deprecated '
- 'and will be removed in Sphinx 4.0. '
- 'Convert %s to Python 3 syntax.'),
- filepath)
+ code = compile(source, filepath_enc, 'exec')
exec(code, _globals)
-
-
-deprecated_alias('sphinx.util.pycompat',
- {
- 'NoneType': NoneType,
- 'TextIOWrapper': io.TextIOWrapper,
- 'htmlescape': html.escape,
- 'indent': textwrap.indent,
- 'terminal_safe': terminal_safe,
- 'sys_encoding': sys.getdefaultencoding(),
- 'u': '',
- },
- RemovedInSphinx40Warning,
- {
- 'NoneType': 'sphinx.util.typing.NoneType',
- 'TextIOWrapper': 'io.TextIOWrapper',
- 'htmlescape': 'html.escape',
- 'indent': 'textwrap.indent',
- 'terminal_safe': 'sphinx.util.console.terminal_safe',
- 'sys_encoding': 'sys.getdefaultencoding',
- })
diff --git a/sphinx/util/smartypants.py b/sphinx/util/smartypants.py
index ec6b2172c..ad13fcaad 100644
--- a/sphinx/util/smartypants.py
+++ b/sphinx/util/smartypants.py
@@ -26,12 +26,17 @@
"""
import re
+import warnings
from typing import Generator, Iterable, Tuple
from docutils.utils import smartquotes
+from sphinx.deprecation import RemovedInSphinx60Warning
from sphinx.util.docutils import __version_info__ as docutils_version
+warnings.warn('sphinx.util.smartypants is deprecated.',
+ RemovedInSphinx60Warning)
+
langquotes = {'af': '“”‘’',
'af-x-altquot': '„”‚’',
'bg': '„“‚‘', # Bulgarian, https://bg.wikipedia.org/wiki/Кавички
diff --git a/sphinx/util/texescape.py b/sphinx/util/texescape.py
index b67dcfe82..7323d2c27 100644
--- a/sphinx/util/texescape.py
+++ b/sphinx/util/texescape.py
@@ -11,8 +11,6 @@
import re
from typing import Dict
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
-
tex_replacements = [
# map TeX special chars
('$', r'\$'),
@@ -108,14 +106,6 @@ _tex_hlescape_map = {} # type: Dict[int, str]
_tex_hlescape_map_without_unicode = {} # type: Dict[int, str]
-deprecated_alias('sphinx.util.texescape',
- {
- 'tex_escape_map': _tex_escape_map,
- 'tex_hl_escape_map_new': _tex_hlescape_map,
- },
- RemovedInSphinx40Warning)
-
-
def escape(s: str, latex_engine: str = None) -> str:
"""Escape text for LaTeX output."""
if latex_engine in ('lualatex', 'xelatex'):
diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py
index e85c40cdf..ae9a3de28 100644
--- a/sphinx/util/typing.py
+++ b/sphinx/util/typing.py
@@ -22,7 +22,7 @@ else:
from typing import _ForwardRef # type: ignore
class ForwardRef:
- """A pseudo ForwardRef class for py35 and py36."""
+ """A pseudo ForwardRef class for py36."""
def __init__(self, arg: Any, is_argument: bool = True) -> None:
self.arg = arg
@@ -76,9 +76,6 @@ def get_type_hints(obj: Any, globalns: Dict = None, localns: Dict = None) -> Dic
except KeyError:
# a broken class found (refs: https://github.com/sphinx-doc/sphinx/issues/8084)
return {}
- except AttributeError:
- # AttributeError is raised on 3.5.2 (fixed by 3.5.3)
- return {}
def is_system_TypeVar(typ: Any) -> bool:
@@ -183,7 +180,7 @@ def _restify_py36(cls: Optional["Type"]) -> str:
qualname = repr(cls)
if (isinstance(cls, typing.TupleMeta) and # type: ignore
- not hasattr(cls, '__tuple_params__')): # for Python 3.6
+ not hasattr(cls, '__tuple_params__')):
params = cls.__args__
if params:
param_str = ', '.join(restify(p) for p in params)
@@ -191,40 +188,22 @@ def _restify_py36(cls: Optional["Type"]) -> str:
else:
return ':class:`%s`' % qualname
elif isinstance(cls, typing.GenericMeta):
- params = None
- if hasattr(cls, '__args__'):
- # for Python 3.5.2+
- if cls.__args__ is None or len(cls.__args__) <= 2: # type: ignore # NOQA
- params = cls.__args__ # type: ignore
- elif cls.__origin__ == Generator: # type: ignore
- params = cls.__args__ # type: ignore
- else: # typing.Callable
- args = ', '.join(restify(arg) for arg in cls.__args__[:-1]) # type: ignore
- result = restify(cls.__args__[-1]) # type: ignore
- return ':class:`%s`\\ [[%s], %s]' % (qualname, args, result)
- elif hasattr(cls, '__parameters__'):
- # for Python 3.5.0 and 3.5.1
- params = cls.__parameters__ # type: ignore
+ if cls.__args__ is None or len(cls.__args__) <= 2: # type: ignore # NOQA
+ params = cls.__args__ # type: ignore
+ elif cls.__origin__ == Generator: # type: ignore
+ params = cls.__args__ # type: ignore
+ else: # typing.Callable
+ args = ', '.join(restify(arg) for arg in cls.__args__[:-1]) # type: ignore
+ result = restify(cls.__args__[-1]) # type: ignore
+ return ':class:`%s`\\ [[%s], %s]' % (qualname, args, result)
if params:
param_str = ', '.join(restify(p) for p in params)
return ':class:`%s`\\ [%s]' % (qualname, param_str)
else:
return ':class:`%s`' % qualname
- elif (hasattr(typing, 'UnionMeta') and
- isinstance(cls, typing.UnionMeta) and # type: ignore
- hasattr(cls, '__union_params__')): # for Python 3.5
- params = cls.__union_params__
- if params is not None:
- if len(params) == 2 and params[1] is NoneType:
- return ':obj:`Optional`\\ [%s]' % restify(params[0])
- else:
- param_str = ', '.join(restify(p) for p in params)
- return ':obj:`%s`\\ [%s]' % (qualname, param_str)
- else:
- return ':obj:`%s`' % qualname
elif (hasattr(cls, '__origin__') and
- cls.__origin__ is typing.Union): # for Python 3.5.2+
+ cls.__origin__ is typing.Union):
params = cls.__args__
if params is not None:
if len(params) > 1 and params[-1] is NoneType:
@@ -238,31 +217,6 @@ def _restify_py36(cls: Optional["Type"]) -> str:
return ':obj:`Union`\\ [%s]' % param_str
else:
return ':obj:`Union`'
- elif (isinstance(cls, typing.CallableMeta) and # type: ignore
- getattr(cls, '__args__', None) is not None and
- hasattr(cls, '__result__')): # for Python 3.5
- # Skipped in the case of plain typing.Callable
- args = cls.__args__
- if args is None:
- return qualname
- elif args is Ellipsis:
- args_str = '...'
- else:
- formatted_args = (restify(a) for a in args) # type: ignore
- args_str = '[%s]' % ', '.join(formatted_args)
-
- return ':class:`%s`\\ [%s, %s]' % (qualname, args_str, stringify(cls.__result__))
- elif (isinstance(cls, typing.TupleMeta) and # type: ignore
- hasattr(cls, '__tuple_params__') and
- hasattr(cls, '__tuple_use_ellipsis__')): # for Python 3.5
- params = cls.__tuple_params__
- if params is not None:
- param_strings = [restify(p) for p in params]
- if cls.__tuple_use_ellipsis__:
- param_strings.append('...')
- return ':class:`%s`\\ [%s]' % (qualname, ', '.join(param_strings))
- else:
- return ':class:`%s`' % qualname
elif hasattr(cls, '__qualname__'):
if cls.__module__ == 'typing':
return ':class:`%s`' % cls.__qualname__
@@ -372,7 +326,7 @@ def _stringify_py37(annotation: Any) -> str:
def _stringify_py36(annotation: Any) -> str:
- """stringify() for py35 and py36."""
+ """stringify() for py36."""
module = getattr(annotation, '__module__', None)
if module == 'typing':
if getattr(annotation, '_name', None):
@@ -400,35 +354,20 @@ def _stringify_py36(annotation: Any) -> str:
return qualname
elif isinstance(annotation, typing.GenericMeta):
params = None
- if hasattr(annotation, '__args__'):
- # for Python 3.5.2+
- if annotation.__args__ is None or len(annotation.__args__) <= 2: # type: ignore # NOQA
- params = annotation.__args__ # type: ignore
- elif annotation.__origin__ == Generator: # type: ignore
- params = annotation.__args__ # type: ignore
- else: # typing.Callable
- args = ', '.join(stringify(arg) for arg
- in annotation.__args__[:-1]) # type: ignore
- result = stringify(annotation.__args__[-1]) # type: ignore
- return '%s[[%s], %s]' % (qualname, args, result)
- elif hasattr(annotation, '__parameters__'):
- # for Python 3.5.0 and 3.5.1
- params = annotation.__parameters__ # type: ignore
+ if annotation.__args__ is None or len(annotation.__args__) <= 2: # type: ignore # NOQA
+ params = annotation.__args__ # type: ignore
+ elif annotation.__origin__ == Generator: # type: ignore
+ params = annotation.__args__ # type: ignore
+ else: # typing.Callable
+ args = ', '.join(stringify(arg) for arg
+ in annotation.__args__[:-1]) # type: ignore
+ result = stringify(annotation.__args__[-1]) # type: ignore
+ return '%s[[%s], %s]' % (qualname, args, result)
if params is not None:
param_str = ', '.join(stringify(p) for p in params)
return '%s[%s]' % (qualname, param_str)
- elif (hasattr(typing, 'UnionMeta') and
- isinstance(annotation, typing.UnionMeta) and # type: ignore
- hasattr(annotation, '__union_params__')): # for Python 3.5
- params = annotation.__union_params__
- if params is not None:
- if len(params) == 2 and params[1] is NoneType:
- return 'Optional[%s]' % stringify(params[0])
- else:
- param_str = ', '.join(stringify(p) for p in params)
- return '%s[%s]' % (qualname, param_str)
elif (hasattr(annotation, '__origin__') and
- annotation.__origin__ is typing.Union): # for Python 3.5.2+
+ annotation.__origin__ is typing.Union):
params = annotation.__args__
if params is not None:
if len(params) > 1 and params[-1] is NoneType:
@@ -440,30 +379,5 @@ def _stringify_py36(annotation: Any) -> str:
else:
param_str = ', '.join(stringify(p) for p in params)
return 'Union[%s]' % param_str
- elif (isinstance(annotation, typing.CallableMeta) and # type: ignore
- getattr(annotation, '__args__', None) is not None and
- hasattr(annotation, '__result__')): # for Python 3.5
- # Skipped in the case of plain typing.Callable
- args = annotation.__args__
- if args is None:
- return qualname
- elif args is Ellipsis:
- args_str = '...'
- else:
- formatted_args = (stringify(a) for a in args)
- args_str = '[%s]' % ', '.join(formatted_args)
- return '%s[%s, %s]' % (qualname,
- args_str,
- stringify(annotation.__result__))
- elif (isinstance(annotation, typing.TupleMeta) and # type: ignore
- hasattr(annotation, '__tuple_params__') and
- hasattr(annotation, '__tuple_use_ellipsis__')): # for Python 3.5
- params = annotation.__tuple_params__
- if params is not None:
- param_strings = [stringify(p) for p in params]
- if annotation.__tuple_use_ellipsis__:
- param_strings.append('...')
- return '%s[%s]' % (qualname,
- ', '.join(param_strings))
return qualname
diff --git a/sphinx/versioning.py b/sphinx/versioning.py
index 6e5a9eb26..6824efe17 100644
--- a/sphinx/versioning.py
+++ b/sphinx/versioning.py
@@ -12,15 +12,14 @@ import pickle
from itertools import product, zip_longest
from operator import itemgetter
from os import path
-from typing import Any, Dict, Iterator
+from typing import TYPE_CHECKING, Any, Dict, Iterator
from uuid import uuid4
from docutils.nodes import Node
from sphinx.transforms import SphinxTransform
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.application import Sphinx
try:
diff --git a/sphinx/writers/html.py b/sphinx/writers/html.py
index 46e3e52e9..ca05b7e6d 100644
--- a/sphinx/writers/html.py
+++ b/sphinx/writers/html.py
@@ -12,8 +12,7 @@ import copy
import os
import posixpath
import re
-import warnings
-from typing import Any, Iterable, Tuple, cast
+from typing import TYPE_CHECKING, Iterable, Tuple, cast
from docutils import nodes
from docutils.nodes import Element, Node, Text
@@ -22,14 +21,12 @@ from docutils.writers.html4css1 import Writer
from sphinx import addnodes
from sphinx.builders import Builder
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import _, __, admonitionlabels
from sphinx.util import logging
from sphinx.util.docutils import SphinxTranslator
from sphinx.util.images import get_image_size
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.builders.html import StandaloneHTMLBuilder
@@ -86,14 +83,7 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
builder = None # type: StandaloneHTMLBuilder
- def __init__(self, *args: Any) -> None:
- if isinstance(args[0], nodes.document) and isinstance(args[1], Builder):
- document, builder = args
- else:
- warnings.warn('The order of arguments for HTMLTranslator has been changed. '
- 'Please give "document" as 1st and "builder" as 2nd.',
- RemovedInSphinx40Warning, stacklevel=2)
- builder, document = args
+ def __init__(self, document: nodes.document, builder: Builder) -> None:
super().__init__(document, builder)
self.highlighter = self.builder.highlighter
diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py
index d7c7b95e8..a08f62f73 100644
--- a/sphinx/writers/html5.py
+++ b/sphinx/writers/html5.py
@@ -12,7 +12,7 @@ import os
import posixpath
import re
import warnings
-from typing import Any, Iterable, Tuple, cast
+from typing import TYPE_CHECKING, Iterable, Tuple, cast
from docutils import nodes
from docutils.nodes import Element, Node, Text
@@ -20,14 +20,13 @@ from docutils.writers.html5_polyglot import HTMLTranslator as BaseTranslator
from sphinx import addnodes
from sphinx.builders import Builder
-from sphinx.deprecation import RemovedInSphinx40Warning
+from sphinx.deprecation import RemovedInSphinx60Warning
from sphinx.locale import _, __, admonitionlabels
from sphinx.util import logging
from sphinx.util.docutils import SphinxTranslator
from sphinx.util.images import get_image_size
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.builders.html import StandaloneHTMLBuilder
@@ -57,14 +56,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
builder = None # type: StandaloneHTMLBuilder
- def __init__(self, *args: Any) -> None:
- if isinstance(args[0], nodes.document) and isinstance(args[1], Builder):
- document, builder = args
- else:
- warnings.warn('The order of arguments for HTML5Translator has been changed. '
- 'Please give "document" as 1st and "builder" as 2nd.',
- RemovedInSphinx40Warning, stacklevel=2)
- builder, document = args
+ def __init__(self, document: nodes.document, builder: Builder) -> None:
super().__init__(document, builder)
self.highlighter = self.builder.highlighter
@@ -714,22 +706,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
# overwritten to add even/odd classes
- def generate_targets_for_table(self, node: Element) -> None:
- """Generate hyperlink targets for tables.
-
- Original visit_table() generates hyperlink targets inside table tags
- (<table>) if multiple IDs are assigned to listings.
- That is invalid DOM structure. (This is a bug of docutils <= 0.13.1)
-
- This exports hyperlink targets before tables to make valid DOM structure.
- """
- for id in node['ids'][1:]:
- self.body.append('<span id="%s"></span>' % id)
- node['ids'].remove(id)
-
def visit_table(self, node: Element) -> None:
- self.generate_targets_for_table(node)
-
self._table_row_index = 0
atts = {}
@@ -786,3 +763,18 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
def unknown_visit(self, node: Node) -> None:
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
+
+ def generate_targets_for_table(self, node: Element) -> None:
+ """Generate hyperlink targets for tables.
+
+ Original visit_table() generates hyperlink targets inside table tags
+ (<table>) if multiple IDs are assigned to listings.
+ That is invalid DOM structure. (This is a bug of docutils <= 0.13.1)
+
+ This exports hyperlink targets before tables to make valid DOM structure.
+ """
+ warnings.warn('generate_targets_for_table() is deprecated',
+ RemovedInSphinx60Warning, stacklevel=2)
+ for id in node['ids'][1:]:
+ self.body.append('<span id="%s"></span>' % id)
+ node['ids'].remove(id)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 1591b5056..56cc4bd7c 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -15,14 +15,13 @@ import re
import warnings
from collections import defaultdict
from os import path
-from typing import Any, Dict, Iterable, Iterator, List, Set, Tuple, Union, cast
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Set, Tuple, cast
from docutils import nodes, writers
from docutils.nodes import Element, Node, Text
from sphinx import addnodes, highlighting
-from sphinx.deprecation import (RemovedInSphinx40Warning, RemovedInSphinx50Warning,
- deprecated_alias)
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.domains import IndexEntry
from sphinx.domains.std import StandardDomain
from sphinx.errors import SphinxError
@@ -39,8 +38,7 @@ except ImportError:
# In Debain/Ubuntu, roman package is provided as roman, not as docutils.utils.roman
from roman import toRoman # type: ignore
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.builders.latex import LaTeXBuilder
from sphinx.builders.latex.theming import Theme
@@ -2036,120 +2034,6 @@ class LaTeXTranslator(SphinxTranslator):
def unknown_visit(self, node: Node) -> None:
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
- # --------- METHODS FOR COMPATIBILITY --------------------------------------
-
- def collect_footnotes(self, node: Element) -> Dict[str, List[Union["collected_footnote", bool]]]: # NOQA
- def footnotes_under(n: Element) -> Iterator[nodes.footnote]:
- if isinstance(n, nodes.footnote):
- yield n
- else:
- for c in n.children:
- if isinstance(c, addnodes.start_of_file):
- continue
- elif isinstance(c, nodes.Element):
- yield from footnotes_under(c)
-
- warnings.warn('LaTeXWriter.collected_footnote() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- fnotes = {} # type: Dict[str, List[Union[collected_footnote, bool]]]
- for fn in footnotes_under(node):
- label = cast(nodes.label, fn[0])
- num = label.astext().strip()
- newnode = collected_footnote('', *fn.children, number=num)
- fnotes[num] = [newnode, False]
- return fnotes
-
- @property
- def no_contractions(self) -> int:
- warnings.warn('LaTeXTranslator.no_contractions is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- return 0
-
- def babel_defmacro(self, name: str, definition: str) -> str:
- warnings.warn('babel_defmacro() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
-
- if self.elements['babel']:
- prefix = '\\addto\\extras%s{' % self.babel.get_language()
- suffix = '}'
- else: # babel is disabled (mainly for Japanese environment)
- prefix = ''
- suffix = ''
-
- return ('%s\\def%s{%s}%s\n' % (prefix, name, definition, suffix))
-
- def generate_numfig_format(self, builder: "LaTeXBuilder") -> str:
- warnings.warn('generate_numfig_format() is deprecated.',
- RemovedInSphinx40Warning, stacklevel=2)
- ret = [] # type: List[str]
- figure = self.config.numfig_format['figure'].split('%s', 1)
- if len(figure) == 1:
- ret.append('\\def\\fnum@figure{%s}\n' % self.escape(figure[0]).strip())
- else:
- definition = escape_abbr(self.escape(figure[0]))
- ret.append(self.babel_renewcommand('\\figurename', definition))
- ret.append('\\makeatletter\n')
- ret.append('\\def\\fnum@figure{\\figurename\\thefigure{}%s}\n' %
- self.escape(figure[1]))
- ret.append('\\makeatother\n')
-
- table = self.config.numfig_format['table'].split('%s', 1)
- if len(table) == 1:
- ret.append('\\def\\fnum@table{%s}\n' % self.escape(table[0]).strip())
- else:
- definition = escape_abbr(self.escape(table[0]))
- ret.append(self.babel_renewcommand('\\tablename', definition))
- ret.append('\\makeatletter\n')
- ret.append('\\def\\fnum@table{\\tablename\\thetable{}%s}\n' %
- self.escape(table[1]))
- ret.append('\\makeatother\n')
-
- codeblock = self.config.numfig_format['code-block'].split('%s', 1)
- if len(codeblock) == 1:
- pass # FIXME
- else:
- definition = self.escape(codeblock[0]).strip()
- ret.append(self.babel_renewcommand('\\literalblockname', definition))
- if codeblock[1]:
- pass # FIXME
-
- return ''.join(ret)
-
-
-# Import old modules here for compatibility
-from sphinx.builders.latex import constants # NOQA
-from sphinx.builders.latex.util import ExtBabel # NOQA
-
-deprecated_alias('sphinx.writers.latex',
- {
- 'ADDITIONAL_SETTINGS': constants.ADDITIONAL_SETTINGS,
- 'DEFAULT_SETTINGS': constants.DEFAULT_SETTINGS,
- 'LUALATEX_DEFAULT_FONTPKG': constants.LUALATEX_DEFAULT_FONTPKG,
- 'PDFLATEX_DEFAULT_FONTPKG': constants.PDFLATEX_DEFAULT_FONTPKG,
- 'SHORTHANDOFF': constants.SHORTHANDOFF,
- 'XELATEX_DEFAULT_FONTPKG': constants.XELATEX_DEFAULT_FONTPKG,
- 'XELATEX_GREEK_DEFAULT_FONTPKG': constants.XELATEX_GREEK_DEFAULT_FONTPKG,
- 'ExtBabel': ExtBabel,
- },
- RemovedInSphinx40Warning,
- {
- 'ADDITIONAL_SETTINGS':
- 'sphinx.builders.latex.constants.ADDITIONAL_SETTINGS',
- 'DEFAULT_SETTINGS':
- 'sphinx.builders.latex.constants.DEFAULT_SETTINGS',
- 'LUALATEX_DEFAULT_FONTPKG':
- 'sphinx.builders.latex.constants.LUALATEX_DEFAULT_FONTPKG',
- 'PDFLATEX_DEFAULT_FONTPKG':
- 'sphinx.builders.latex.constants.PDFLATEX_DEFAULT_FONTPKG',
- 'SHORTHANDOFF':
- 'sphinx.builders.latex.constants.SHORTHANDOFF',
- 'XELATEX_DEFAULT_FONTPKG':
- 'sphinx.builders.latex.constants.XELATEX_DEFAULT_FONTPKG',
- 'XELATEX_GREEK_DEFAULT_FONTPKG':
- 'sphinx.builders.latex.constants.XELATEX_GREEK_DEFAULT_FONTPKG',
- 'ExtBabel': 'sphinx.builders.latex.util.ExtBabel',
- })
# FIXME: Workaround to avoid circular import
# refs: https://github.com/sphinx-doc/sphinx/issues/5433
diff --git a/sphinx/writers/manpage.py b/sphinx/writers/manpage.py
index 9ef429ba3..917a71b3b 100644
--- a/sphinx/writers/manpage.py
+++ b/sphinx/writers/manpage.py
@@ -8,7 +8,6 @@
:license: BSD, see LICENSE for details.
"""
-import warnings
from typing import Any, Dict, Iterable, cast
from docutils import nodes
@@ -18,7 +17,6 @@ from docutils.writers.manpage import Writer
from sphinx import addnodes
from sphinx.builders import Builder
-from sphinx.deprecation import RemovedInSphinx40Warning
from sphinx.locale import _, admonitionlabels
from sphinx.util import logging
from sphinx.util.docutils import SphinxTranslator
@@ -77,14 +75,7 @@ class ManualPageTranslator(SphinxTranslator, BaseTranslator):
_docinfo = {} # type: Dict[str, Any]
- def __init__(self, *args: Any) -> None:
- if isinstance(args[0], nodes.document) and isinstance(args[1], Builder):
- document, builder = args
- else:
- warnings.warn('The order of arguments for ManualPageTranslator has been changed. '
- 'Please give "document" as 1st and "builder" as 2nd.',
- RemovedInSphinx40Warning, stacklevel=2)
- builder, document = args
+ def __init__(self, document: nodes.document, builder: Builder) -> None:
super().__init__(document, builder)
self.in_productionlist = 0
diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py
index 69c8b12a7..a70ffd5e4 100644
--- a/sphinx/writers/texinfo.py
+++ b/sphinx/writers/texinfo.py
@@ -12,8 +12,8 @@ import re
import textwrap
import warnings
from os import path
-from typing import (Any, Dict, Iterable, Iterator, List, Optional, Pattern, Set, Tuple, Union,
- cast)
+from typing import (TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Optional, Pattern, Set,
+ Tuple, Union, cast)
from docutils import nodes, writers
from docutils.nodes import Element, Node, Text
@@ -29,8 +29,7 @@ from sphinx.util.docutils import SphinxTranslator
from sphinx.util.i18n import format_date
from sphinx.writers.latex import collected_footnote
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.builders.texinfo import TexinfoBuilder
diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py
index c0ebe32a2..274a35d57 100644
--- a/sphinx/writers/text.py
+++ b/sphinx/writers/text.py
@@ -12,7 +12,8 @@ import os
import re
import textwrap
from itertools import chain, groupby
-from typing import Any, Dict, Generator, Iterable, List, Optional, Set, Tuple, Union, cast
+from typing import (TYPE_CHECKING, Any, Dict, Generator, Iterable, List, Optional, Set, Tuple,
+ Union, cast)
from docutils import nodes, writers
from docutils.nodes import Element, Node, Text
@@ -22,8 +23,7 @@ from sphinx import addnodes
from sphinx.locale import _, admonitionlabels
from sphinx.util.docutils import SphinxTranslator
-if False:
- # For type annotation
+if TYPE_CHECKING:
from sphinx.builders.text import TextBuilder