imgmath: Use template file for LaTeX

This commit is contained in:
Takeshi KOMIYA 2019-04-16 01:27:11 +09:00
parent d7025cd1a7
commit aabeb71123
6 changed files with 85 additions and 12 deletions

View File

@ -44,6 +44,9 @@ Deprecated
* ``sphinx.ext.autodoc.importer.MockLoader`` * ``sphinx.ext.autodoc.importer.MockLoader``
* ``sphinx.ext.autodoc.importer.mock()`` * ``sphinx.ext.autodoc.importer.mock()``
* ``sphinx.ext.autosummary.autolink_role()`` * ``sphinx.ext.autosummary.autolink_role()``
* ``sphinx.ext.imgmath.DOC_BODY``
* ``sphinx.ext.imgmath.DOC_BODY_PREVIEW``
* ``sphinx.ext.imgmath.DOC_HEAD``
* ``sphinx.transforms.CitationReferences`` * ``sphinx.transforms.CitationReferences``
* ``sphinx.transforms.SmartQuotesSkipper`` * ``sphinx.transforms.SmartQuotesSkipper``
* ``sphinx.util.docfields.DocFieldTransformer.preprocess_fieldtypes()`` * ``sphinx.util.docfields.DocFieldTransformer.preprocess_fieldtypes()``

View File

@ -177,6 +177,21 @@ The following is a list of deprecated interfaces.
- 4.0 - 4.0
- ``sphinx.ext.autosummary.AutoLink`` - ``sphinx.ext.autosummary.AutoLink``
* - ``sphinx.ext.imgmath.DOC_BODY``
- 2.1
- 4.0
- N/A
* - ``sphinx.ext.imgmath.DOC_BODY_PREVIEW``
- 2.1
- 4.0
- N/A
* - ``sphinx.ext.imgmath.DOC_HEAD``
- 2.1
- 4.0
- N/A
* - ``sphinx.transforms.CitationReferences`` * - ``sphinx.transforms.CitationReferences``
- 2.1 - 2.1
- 4.0 - 4.0

View File

@ -21,12 +21,15 @@ from subprocess import CalledProcessError, PIPE
from docutils import nodes from docutils import nodes
import sphinx import sphinx
from sphinx import package_dir
from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.errors import SphinxError from sphinx.errors import SphinxError
from sphinx.locale import _, __ from sphinx.locale import _, __
from sphinx.util import logging from sphinx.util import logging
from sphinx.util.math import get_node_equation_number, wrap_displaymath from sphinx.util.math import get_node_equation_number, wrap_displaymath
from sphinx.util.osutil import ensuredir from sphinx.util.osutil import ensuredir
from sphinx.util.png import read_png_depth, write_png_depth from sphinx.util.png import read_png_depth, write_png_depth
from sphinx.util.template import LaTeXRenderer
if False: if False:
# For type annotation # For type annotation
@ -38,6 +41,8 @@ if False:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
templates_path = path.join(package_dir, 'templates', 'imgmath')
class MathExtError(SphinxError): class MathExtError(SphinxError):
category = 'Math extension error' category = 'Math extension error'
@ -87,19 +92,27 @@ DOC_BODY_PREVIEW = r'''
depth_re = re.compile(br'\[\d+ depth=(-?\d+)\]') depth_re = re.compile(br'\[\d+ depth=(-?\d+)\]')
def generate_latex_macro(math, config): def generate_latex_macro(math, config, confdir=''):
# type: (str, Config) -> str # type: (str, Config, str) -> str
"""Generate LaTeX macro.""" """Generate LaTeX macro."""
fontsize = config.imgmath_font_size variables = {
baselineskip = int(round(fontsize * 1.2)) 'fontsize': config.imgmath_font_size,
'baselineskip': int(round(config.imgmath_font_size * 1.2)),
'preamble': config.imgmath_latex_preamble,
'math': math
}
latex = DOC_HEAD + config.imgmath_latex_preamble
if config.imgmath_use_preview: if config.imgmath_use_preview:
latex += DOC_BODY_PREVIEW % (fontsize, baselineskip, math) template_name = 'preview.tex_t'
else: else:
latex += DOC_BODY % (fontsize, baselineskip, math) template_name = 'template.tex_t'
return latex for template_dir in config.templates_path:
template = path.join(confdir, template_dir, template_name)
if path.exists(template):
return LaTeXRenderer().render(template, variables)
return LaTeXRenderer(templates_path).render(template_name, variables)
def ensure_tempdir(builder): def ensure_tempdir(builder):
@ -220,7 +233,7 @@ def render_math(self, math):
if image_format not in SUPPORT_FORMAT: if image_format not in SUPPORT_FORMAT:
raise MathExtError('imgmath_image_format must be either "png" or "svg"') raise MathExtError('imgmath_image_format must be either "png" or "svg"')
latex = generate_latex_macro(math, self.builder.config) latex = generate_latex_macro(math, self.builder.config, self.builder.confdir)
filename = "%s.%s" % (sha1(latex.encode()).hexdigest(), image_format) filename = "%s.%s" % (sha1(latex.encode()).hexdigest(), image_format)
relfn = posixpath.join(self.builder.imgpath, 'math', filename) relfn = posixpath.join(self.builder.imgpath, 'math', filename)
@ -332,6 +345,15 @@ def html_visit_displaymath(self, node):
raise nodes.SkipNode 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): def setup(app):
# type: (Sphinx) -> Dict[str, Any] # type: (Sphinx) -> Dict[str, Any]
app.add_html_math_renderer('imgmath', app.add_html_math_renderer('imgmath',

View File

@ -0,0 +1,18 @@
\documentclass[12pt]{article}
\usepackage[utf8x]{inputenc}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{anyfontsize}
\usepackage{bm}
\pagestyle{empty}
<%= preamble %>
\usepackage[active]{preview}
\begin{document}
\begin{preview}
\fontsize{<%= fontsize %>}{<%= baselineskip %}}\selectfont <%= math %>
\end{preview}
\end{document}

View File

@ -0,0 +1,14 @@
\documentclass[12pt]{article}
\usepackage[utf8x]{inputenc}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{anyfontsize}
\usepackage{bm}
\pagestyle{empty}
<%= preamble %>
\begin{document}
\fontsize{<%= fontsize %>}{<%= baselineskip %>}\selectfont <%= math %>
\end{document}

View File

@ -67,9 +67,10 @@ class SphinxRenderer(FileRenderer):
class LaTeXRenderer(SphinxRenderer): class LaTeXRenderer(SphinxRenderer):
def __init__(self): def __init__(self, template_path=None):
# type: () -> None # type: (str) -> None
template_path = os.path.join(package_dir, 'templates', 'latex') if template_path is None:
template_path = os.path.join(package_dir, 'templates', 'latex')
super().__init__(template_path) super().__init__(template_path)
# use texescape as escape filter # use texescape as escape filter