Code highlighting
This commit is contained in:
30
utils/highlight.py
Normal file
30
utils/highlight.py
Normal 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)
|
@@ -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(
|
||||
|
Reference in New Issue
Block a user