Migrate to py3 style type annotation: sphinx.ext.imgmath

This commit is contained in:
Takeshi KOMIYA committed 2019-07-04 01:10:15 +09:00
1 parent e25d77e999
commit 3a74ef89b3
1 file changed
+19 -34
+19 -34
View File
@@ -17,11 +17,16 @@ import tempfile
from hashlib import sha1
from os import path
from subprocess import CalledProcessError, PIPE
from typing import Any, Dict, List, Tuple
from docutils import nodes
from docutils.nodes import Element
import sphinx
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 _, __
@@ -30,14 +35,7 @@ from sphinx.util.math import get_node_equation_number, wrap_displaymath
from sphinx.util.osutil import ensuredir
from sphinx.util.png import read_png_depth, write_png_depth
from sphinx.util.template import LaTeXRenderer
if False:
# For type annotation
from typing import Any, Dict, List, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA
from sphinx.builders import Builder # NOQA
from sphinx.config import Config # NOQA
from sphinx.writers.html import HTMLTranslator # NOQA
from sphinx.writers.html import HTMLTranslator
logger = logging.getLogger(__name__)
@@ -47,8 +45,7 @@ templates_path = path.join(package_dir, 'templates', 'imgmath')
class MathExtError(SphinxError):
category = 'Math extension error'
def __init__(self, msg, stderr=None, stdout=None):
# type: (str, bytes, bytes) -> None
def __init__(self, msg: str, stderr: bytes = None, stdout: bytes = None) -> None:
if stderr:
msg += '\n[stderr]\n' + stderr.decode(sys.getdefaultencoding(), 'replace')
if stdout:
@@ -92,8 +89,7 @@ DOC_BODY_PREVIEW = r'''
depth_re = re.compile(br'\[\d+ depth=(-?\d+)\]')
def generate_latex_macro(math, config, confdir=''):
# type: (str, Config, str) -> str
def generate_latex_macro(math: str, config: Config, confdir: str = '') -> str:
"""Generate LaTeX macro."""
variables = {
'fontsize': config.imgmath_font_size,
@@ -115,8 +111,7 @@ def generate_latex_macro(math, config, confdir=''):
return LaTeXRenderer(templates_path).render(template_name, variables)
def ensure_tempdir(builder):
# type: (Builder) -> str
def ensure_tempdir(builder: Builder) -> str:
"""Create temporary directory.
use only one tempdir per build -- the use of a directory is cleaner
@@ -129,8 +124,7 @@ def ensure_tempdir(builder):
return builder._imgmath_tempdir # type: ignore
def compile_math(latex, builder):
# type: (str, Builder) -> str
def compile_math(latex: str, builder: Builder) -> str:
"""Compile LaTeX macros for math to DVI."""
tempdir = ensure_tempdir(builder)
filename = path.join(tempdir, 'math.tex')
@@ -157,8 +151,7 @@ def compile_math(latex, builder):
raise MathExtError('latex exited with error', exc.stderr, exc.stdout)
def convert_dvi_to_image(command, name):
# type: (List[str], str) -> Tuple[bytes, bytes]
def convert_dvi_to_image(command: List[str], name: str) -> Tuple[bytes, bytes]:
"""Convert DVI file to specific image format."""
try:
ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True)
@@ -172,8 +165,7 @@ def convert_dvi_to_image(command, name):
raise MathExtError('%s exited with error' % name, exc.stderr, exc.stdout)
def convert_dvi_to_png(dvipath, builder):
# type: (str, Builder) -> Tuple[str, int]
def convert_dvi_to_png(dvipath: str, builder: Builder) -> Tuple[str, int]:
"""Convert DVI file to PNG image."""
tempdir = ensure_tempdir(builder)
filename = path.join(tempdir, 'math.png')
@@ -199,8 +191,7 @@ def convert_dvi_to_png(dvipath, builder):
return filename, depth
def convert_dvi_to_svg(dvipath, builder):
# type: (str, Builder) -> Tuple[str, int]
def convert_dvi_to_svg(dvipath: str, builder: Builder) -> Tuple[str, int]:
"""Convert DVI file to SVG image."""
tempdir = ensure_tempdir(builder)
filename = path.join(tempdir, 'math.svg')
@@ -214,8 +205,7 @@ def convert_dvi_to_svg(dvipath, builder):
return filename, None
def render_math(self, math):
# type: (HTMLTranslator, str) -> Tuple[str, int]
def render_math(self: HTMLTranslator, math: str) -> Tuple[str, int]:
"""Render the LaTeX math expression *math* using latex and dvipng or
dvisvgm.
@@ -271,8 +261,7 @@ def render_math(self, math):
return relfn, depth
def cleanup_tempdir(app, exc):
# type: (Sphinx, Exception) -> None
def cleanup_tempdir(app: Sphinx, exc: Exception) -> None:
if exc:
return
if not hasattr(app.builder, '_imgmath_tempdir'):
@@ -283,15 +272,13 @@ def cleanup_tempdir(app, exc):
pass
def get_tooltip(self, node):
# type: (HTMLTranslator, Union[nodes.math, nodes.math_block]) -> str
def get_tooltip(self: HTMLTranslator, node: Element) -> str:
if self.builder.config.imgmath_add_tooltips:
return ' alt="%s"' % self.encode(node.astext()).strip()
return ''
def html_visit_math(self, node):
# type: (HTMLTranslator, nodes.math) -> None
def html_visit_math(self: HTMLTranslator, node: nodes.math) -> None:
try:
fname, depth = render_math(self, '$' + node.astext() + '$')
except MathExtError as exc:
@@ -313,8 +300,7 @@ def html_visit_math(self, node):
raise nodes.SkipNode
def html_visit_displaymath(self, node):
# type: (HTMLTranslator, nodes.math_block) -> None
def html_visit_displaymath(self: HTMLTranslator, node: nodes.math_block) -> None:
if node['nowrap']:
latex = node.astext()
else:
@@ -354,8 +340,7 @@ deprecated_alias('sphinx.ext.imgmath',
RemovedInSphinx40Warning)
def setup(app):
# type: (Sphinx) -> Dict[str, Any]
def setup(app: Sphinx) -> Dict[str, Any]:
app.add_html_math_renderer('imgmath',
(html_visit_math, None),
(html_visit_displaymath, None))