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
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
import pygments
|
|
|
|
import pygments.lexers
|
2022-09-15 17:01:29 +00:00
|
|
|
import pygments.formatters
|
2020-01-21 06:35:58 +00:00
|
|
|
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-09-15 18:26:07 +00:00
|
|
|
|
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(
|
2022-09-15 18:26:07 +00:00
|
|
|
code,
|
|
|
|
lexer,
|
|
|
|
pygments.formatters.HtmlFormatter(
|
|
|
|
cssclass=cssclass, linenos="table", wrapcode=True
|
|
|
|
),
|
2022-05-14 17:57:27 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
return mark_safe(
|
2022-09-15 18:26:07 +00:00
|
|
|
pygments.highlight(
|
|
|
|
code,
|
|
|
|
lexer,
|
|
|
|
pygments.formatters.HtmlFormatter(cssclass=cssclass, wrapcode=True),
|
|
|
|
)
|
2022-05-14 17:57:27 +00:00
|
|
|
)
|