summaryrefslogtreecommitdiff
path: root/sphinx/ext
diff options
context:
space:
mode:
Diffstat (limited to 'sphinx/ext')
-rw-r--r--sphinx/ext/apidoc.py71
-rw-r--r--sphinx/ext/autodoc/__init__.py42
-rw-r--r--sphinx/ext/autodoc/directive.py23
-rw-r--r--sphinx/ext/autodoc/importer.py23
-rw-r--r--sphinx/ext/autodoc/mock.py6
-rw-r--r--sphinx/ext/autosummary/__init__.py60
-rw-r--r--sphinx/ext/autosummary/generate.py37
-rw-r--r--sphinx/ext/doctest.py15
-rw-r--r--sphinx/ext/imgmath.py45
-rw-r--r--sphinx/ext/jsmath.py36
-rw-r--r--sphinx/ext/napoleon/docstring.py6
-rw-r--r--sphinx/ext/todo.py106
12 files changed, 44 insertions, 426 deletions
diff --git a/sphinx/ext/apidoc.py b/sphinx/ext/apidoc.py
index b01604617..8e3fbd7d0 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 e247d3bd2..083f2aaa7 100644
--- a/sphinx/ext/autodoc/__init__.py
+++ b/sphinx/ext/autodoc/__init__.py
@@ -18,13 +18,14 @@ from types import ModuleType
from typing import (
Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, Union
)
+from typing import TYPE_CHECKING
from docutils.statemachine import StringList
import sphinx
from sphinx.application import Sphinx
from sphinx.config import Config, ENUM
-from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.environment import BuildEnvironment
from sphinx.ext.autodoc.importer import import_object, get_module_members, get_object_members
from sphinx.ext.autodoc.mock import mock
@@ -37,9 +38,7 @@ from sphinx.util.docstrings import extract_metadata, prepare_docstring
from sphinx.util.inspect import getdoc, object_description, safe_getattr, stringify_signature
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
@@ -276,7 +275,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
@@ -460,12 +459,8 @@ 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) -> List[List[str]]:
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
"""Decode and return lines of the docstring(s) for the 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__,
@@ -787,7 +782,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:
@@ -1039,12 +1034,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):
@@ -1103,14 +1093,10 @@ class DocstringSignatureMixin:
return result
- def get_doc(self, encoding: str = None, ignore: int = None) -> 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.env.config.autodoc_docstring_signature: # type: ignore
@@ -1394,11 +1380,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
self.add_line(' ' + _('Bases: %s') % ', '.join(bases),
sourcename)
- def get_doc(self, encoding: str = None, ignore: int = None) -> 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]]:
lines = getattr(self, '_new_docstrings', None)
if lines is not None:
return lines
@@ -1918,7 +1900,7 @@ class SlotsAttributeDocumenter(AttributeDocumenter):
self.env.note_reread()
return False
- def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]:
+ def get_doc(self, ignore: int = None) -> List[List[str]]:
"""Decode and return lines of the docstring(s) for the object."""
if ignore is not None:
warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated."
@@ -1933,7 +1915,7 @@ class SlotsAttributeDocumenter(AttributeDocumenter):
return []
-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 9a3428f5d..5543059cb 100644
--- a/sphinx/ext/autodoc/directive.py
+++ b/sphinx/ext/autodoc/directive.py
@@ -6,27 +6,21 @@
:license: BSD, see LICENSE for details.
"""
-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
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 +47,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 cdccf710d..cb06edbac 100644
--- a/sphinx/ext/autodoc/importer.py
+++ b/sphinx/ext/autodoc/importer.py
@@ -13,7 +13,6 @@ import traceback
import warnings
from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Tuple
-from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.pycode import ModuleAnalyzer
from sphinx.util import logging
from sphinx.util.inspect import isclass, isenumclass, safe_getattr
@@ -122,9 +121,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)])
+class Attribute(NamedTuple):
+ name: str
+ directly_defined: bool
+ value: Any
def get_object_members(subject: Any, objpath: List[str], attrgetter: Callable,
@@ -180,18 +180,3 @@ def get_object_members(subject: Any, objpath: List[str], attrgetter: Callable,
members[name] = Attribute(name, True, INSTANCEATTR)
return members
-
-
-from sphinx.ext.autodoc.mock import ( # NOQA
- _MockModule, _MockObject, MockFinder, MockLoader, mock
-)
-
-deprecated_alias('sphinx.ext.autodoc.importer',
- {
- '_MockModule': _MockModule,
- '_MockObject': _MockObject,
- 'MockFinder': MockFinder,
- 'MockLoader': MockLoader,
- 'mock': mock,
- },
- RemovedInSphinx40Warning)
diff --git a/sphinx/ext/autodoc/mock.py b/sphinx/ext/autodoc/mock.py
index 98a3a3a96..f2ed89712 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
@@ -117,8 +117,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 162b6868c..bc8319a20 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
+from typing import Any, Dict, List, Tuple, Type
from typing import 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.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 Documenter
@@ -88,10 +88,6 @@ from sphinx.util.docutils import (
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__)
@@ -409,29 +405,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."""
@@ -652,33 +625,6 @@ def _import_by_name(name: str) -> Tuple[Any, Any, str]:
# -- :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 fe7daf214..cccbd1487 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
@@ -39,7 +39,7 @@ 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, RemovedInSphinx50Warning
+from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.ext.autodoc import Documenter
from sphinx.ext.autosummary import import_by_name, get_documenter
from sphinx.locale import __
@@ -52,10 +52,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__)
@@ -343,25 +339,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) -> 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)
@@ -373,11 +354,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]
@@ -403,7 +384,7 @@ def generate_autosummary_docs(sources: List[str], output_dir: str = None,
try:
name, obj, parent, mod_name = import_by_name(entry.name)
except ImportError as e:
- _warn(__('[autosummary] failed to import %r: %s') % (entry.name, e))
+ logger.warning(__('[autosummary] failed to import %r: %s') % (entry.name, e))
continue
context = {}
@@ -432,8 +413,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 26966016d..48ebcd34e 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 Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple, Type
+from typing import TYPE_CHECKING
from docutils import nodes
from docutils.nodes import Element, Node, TextElement
@@ -26,16 +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
@@ -45,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 2050e470e..65f281223 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)
-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:
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 75369a5ca..000000000
--- a/sphinx/ext/jsmath.py
+++ /dev/null
@@ -1,36 +0,0 @@
-"""
- sphinx.ext.jsmath
- ~~~~~~~~~~~~~~~~~
-
- Set up everything for use of JSMath to display math in HTML
- via JavaScript.
-
- :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import warnings
-from typing import Any, Dict
-
-from sphinxcontrib.jsmath import ( # NOQA
- html_visit_math,
- html_visit_displaymath,
- 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/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py
index 32edd7f8f..ea26d76bb 100644
--- a/sphinx/ext/napoleon/docstring.py
+++ b/sphinx/ext/napoleon/docstring.py
@@ -13,17 +13,13 @@
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
from sphinx.ext.napoleon.iterators import modify_iter
from sphinx.locale import _
-if False:
- # For type annotation
- from typing import Type # for python3.5.1
-
_directive_regex = re.compile(r'\.\. \S+::')
_google_section_regex = re.compile(r'^(\s|\w)+:\s*$')
diff --git a/sphinx/ext/todo.py b/sphinx/ext/todo.py
index bfb46903f..44b6acabc 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
+from typing import Any, Dict, List, Tuple
from typing import cast
from docutils import nodes
@@ -22,14 +21,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
@@ -104,33 +101,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.
@@ -217,80 +187,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)