zulip/zerver/lib/tex.py
Anders Kaseorg fd7803e7f4 settings: Unset STATIC_ROOT in development.
Django’s default FileSystemFinder disallows STATICFILES_DIRS from
containing STATIC_ROOT (by raising an ImproperlyConfigured exception),
because STATIC_ROOT is supposed to be the result of collecting all the
static files in the project, not one of the potentially many sources
of static files.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-07-24 17:40:31 -07:00

45 lines
1.5 KiB
Python

import logging
import os
import subprocess
from django.conf import settings
from typing import Optional
from zerver.lib.storage import static_path
def render_tex(tex: str, is_inline: bool=True) -> Optional[str]:
r"""Render a TeX string into HTML using KaTeX
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)
"""
katex_path = (
static_path("webpack-bundles/katex-cli.js")
if settings.PRODUCTION
else os.path.join(settings.DEPLOY_ROOT, "node_modules/katex/cli.js")
)
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:
command.extend(['--display-mode'])
katex = subprocess.Popen(command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout = katex.communicate(input=tex.encode())[0]
if katex.returncode == 0:
# stdout contains a newline at the end
assert stdout is not None
return stdout.decode('utf-8').strip()
else:
return None