Code highlighting

This commit is contained in:
Thomas Sileo
2019-08-25 00:16:39 +02:00
parent 14e5e6b7e7
commit 562aae86f3
6 changed files with 42 additions and 2 deletions

30
utils/highlight.py Normal file
View File

@@ -0,0 +1,30 @@
from functools import lru_cache
from bs4 import BeautifulSoup
from pygments import highlight as phighlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer
from config import THEME_STYLE
from config import ThemeStyle
_FORMATTER = HtmlFormatter(
style="default" if THEME_STYLE == ThemeStyle.LIGHT else "vim"
)
HIGHLIGHT_CSS = _FORMATTER.get_style_defs()
@lru_cache(512)
def highlight(html: str) -> str:
soup = BeautifulSoup(html, "html5lib")
for code in soup.find_all("code"):
if not code.parent.name == "pre":
continue
lexer = guess_lexer(code.text)
tag = BeautifulSoup(phighlight(code.text, lexer, _FORMATTER)).body.next
pre = code.parent
pre.replaceWith(tag)
out = soup.body
out.name = "div"
return str(out)

View File

@@ -21,6 +21,7 @@ from config import ID
from config import MEDIA_CACHE
from core.activitypub import _answer_key
from utils import parse_datetime
from utils.highlight import highlight
from utils.media import Kind
from utils.media import _is_img
@@ -47,6 +48,11 @@ def visibility_is_public(v: str) -> bool:
return v in [ap.Visibility.PUBLIC.name, ap.Visibility.UNLISTED.name]
@filters.app_template_filter()
def code_highlight(content):
return highlight(content)
@filters.app_template_filter()
def emojify(text):
return emoji_unicode.replace(