NDOJ/judge/highlight_code.py

48 lines
1.2 KiB
Python
Raw Permalink Normal View History

2020-01-21 06:35:58 +00:00
from django.utils.html import escape, mark_safe
2022-05-14 17:57:27 +00:00
__all__ = ["highlight_code"]
2020-01-21 06:35:58 +00:00
def _make_pre_code(code):
2022-05-14 17:57:27 +00:00
return mark_safe("<pre>" + escape(code) + "</pre>")
2020-01-21 06:35:58 +00:00
def _wrap_code(inner):
yield 0, "<code>"
for tup in inner:
yield tup
yield 0, "</code>"
try:
import pygments
import pygments.lexers
import pygments.formatters.html
import pygments.util
except ImportError:
2022-05-14 17:57:27 +00:00
2020-01-21 06:35:58 +00:00
def highlight_code(code, language, cssclass=None):
return _make_pre_code(code)
2022-05-14 17:57:27 +00:00
2020-01-21 06:35:58 +00:00
else:
2022-05-14 17:57:27 +00:00
2020-01-21 06:35:58 +00:00
class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
def wrap(self, source, outfile):
return self._wrap_div(self._wrap_pre(_wrap_code(source)))
2022-05-14 17:57:27 +00:00
def highlight_code(code, language, cssclass="codehilite", linenos=True):
2020-01-21 06:35:58 +00:00
try:
lexer = pygments.lexers.get_lexer_by_name(language)
except pygments.util.ClassNotFound:
return _make_pre_code(code)
2021-12-18 03:51:15 +00:00
if linenos:
2022-05-14 17:57:27 +00:00
return mark_safe(
pygments.highlight(
code, lexer, HtmlCodeFormatter(cssclass=cssclass, linenos="table")
)
)
return mark_safe(
pygments.highlight(code, lexer, HtmlCodeFormatter(cssclass=cssclass))
)