2017-03-20 16:56:39 +01:00
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
import subprocess
|
|
|
|
from django.conf import settings
|
2018-05-10 19:13:36 +02:00
|
|
|
from typing import Optional
|
2019-07-17 02:29:08 +02:00
|
|
|
from zerver.lib.storage import static_path
|
2017-03-20 16:56:39 +01:00
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def render_tex(tex: str, is_inline: bool=True) -> Optional[str]:
|
2018-07-02 00:05:24 +02:00
|
|
|
r"""Render a TeX string into HTML using KaTeX
|
2017-03-20 16:56:39 +01:00
|
|
|
|
|
|
|
Returns the HTML string, or None if there was some error in the TeX syntax
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
tex -- Text string with the TeX to render
|
|
|
|
Don't include delimiters ('$$', '\[ \]', etc.)
|
|
|
|
is_inline -- Boolean setting that indicates whether the render should be
|
|
|
|
inline (i.e. for embedding it in text) or not. The latter
|
|
|
|
will show the content centered, and in the "expanded" form
|
|
|
|
(default True)
|
|
|
|
"""
|
|
|
|
|
2019-06-29 10:13:08 +02:00
|
|
|
katex_path = (
|
2019-07-17 02:29:08 +02:00
|
|
|
static_path("webpack-bundles/katex-cli.js")
|
2019-06-29 10:13:08 +02:00
|
|
|
if settings.PRODUCTION
|
|
|
|
else os.path.join(settings.DEPLOY_ROOT, "node_modules/katex/cli.js")
|
|
|
|
)
|
2017-03-20 16:56:39 +01:00
|
|
|
if not os.path.isfile(katex_path):
|
|
|
|
logging.error("Cannot find KaTeX for latex rendering!")
|
|
|
|
return None
|
|
|
|
command = ['node', katex_path]
|
|
|
|
if not is_inline:
|
2019-06-29 10:13:08 +02:00
|
|
|
command.extend(['--display-mode'])
|
2017-03-20 16:56:39 +01:00
|
|
|
katex = subprocess.Popen(command,
|
|
|
|
stdin=subprocess.PIPE,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.PIPE)
|
2017-11-04 17:01:28 +01:00
|
|
|
stdout = katex.communicate(input=tex.encode())[0]
|
2017-03-20 16:56:39 +01:00
|
|
|
if katex.returncode == 0:
|
|
|
|
# stdout contains a newline at the end
|
2017-03-23 23:49:08 +01:00
|
|
|
assert stdout is not None
|
2017-03-20 16:56:39 +01:00
|
|
|
return stdout.decode('utf-8').strip()
|
|
|
|
else:
|
|
|
|
return None
|