Change pre code css in markdown

This commit is contained in:
cuom1999 2024-01-18 19:46:41 -06:00
parent d75a498d18
commit aef795b40c
24 changed files with 200 additions and 397 deletions

View file

@ -1,44 +1,13 @@
from django.utils.html import escape, mark_safe
from judge.markdown import markdown
__all__ = ["highlight_code"]
def _make_pre_code(code):
return mark_safe("<pre>" + escape(code) + "</pre>")
def highlight_code(code, language, linenos=True, title=None):
linenos_option = 'linenums="1"' if linenos else ""
title_option = f'title="{title}"' if title else ""
options = f"{{.{language} {linenos_option} {title_option}}}"
try:
import pygments
import pygments.lexers
import pygments.formatters
import pygments.util
except ImportError:
def highlight_code(code, language, cssclass=None):
return _make_pre_code(code)
else:
def highlight_code(code, language, cssclass="codehilite", linenos=True):
try:
lexer = pygments.lexers.get_lexer_by_name(language)
except pygments.util.ClassNotFound:
return _make_pre_code(code)
if linenos:
return mark_safe(
pygments.highlight(
code,
lexer,
pygments.formatters.HtmlFormatter(
cssclass=cssclass, linenos="table", wrapcode=True
),
)
)
return mark_safe(
pygments.highlight(
code,
lexer,
pygments.formatters.HtmlFormatter(cssclass=cssclass, wrapcode=True),
)
)
value = f"```{options}\n{code}\n```\n"
return mark_safe(markdown(value))

View file

@ -1,112 +1,7 @@
from .. import registry
import markdown as _markdown
import bleach
from django.utils.html import escape
from bs4 import BeautifulSoup
from pymdownx import superfences
EXTENSIONS = [
"pymdownx.arithmatex",
"pymdownx.magiclink",
"pymdownx.betterem",
"pymdownx.details",
"pymdownx.emoji",
"pymdownx.inlinehilite",
"pymdownx.superfences",
"pymdownx.tasklist",
"markdown.extensions.footnotes",
"markdown.extensions.attr_list",
"markdown.extensions.def_list",
"markdown.extensions.tables",
"markdown.extensions.admonition",
"nl2br",
"mdx_breakless_lists",
]
EXTENSION_CONFIGS = {
"pymdownx.superfences": {
"custom_fences": [
{
"name": "sample",
"class": "no-border",
"format": superfences.fence_code_format,
}
]
},
}
ALLOWED_TAGS = list(bleach.sanitizer.ALLOWED_TAGS) + [
"img",
"center",
"iframe",
"div",
"span",
"table",
"tr",
"td",
"th",
"tr",
"pre",
"code",
"p",
"hr",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"thead",
"tbody",
"sup",
"dl",
"dt",
"dd",
"br",
"details",
"summary",
]
ALLOWED_ATTRS = ["src", "width", "height", "href", "class", "open"]
from judge.markdown import markdown as _markdown
@registry.filter
def markdown(value, lazy_load=False):
extensions = EXTENSIONS
html = _markdown.markdown(
value, extensions=extensions, extension_configs=EXTENSION_CONFIGS
)
# Don't clean mathjax
hash_script_tag = {}
soup = BeautifulSoup(html, "html.parser")
for script_tag in soup.find_all("script"):
allow_math_types = ["math/tex", "math/tex; mode=display"]
if script_tag.attrs.get("type", False) in allow_math_types:
hash_script_tag[str(hash(str(script_tag)))] = str(script_tag)
for hashed_tag in hash_script_tag:
tag = hash_script_tag[hashed_tag]
html = html.replace(tag, hashed_tag)
html = bleach.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS)
for hashed_tag in hash_script_tag:
tag = hash_script_tag[hashed_tag]
html = html.replace(hashed_tag, tag)
if not html:
html = escape(value)
if lazy_load:
soup = BeautifulSoup(html, features="html.parser")
for img in soup.findAll("img"):
if img.get("src"):
img["data-src"] = img["src"]
img["src"] = ""
for img in soup.findAll("iframe"):
if img.get("src"):
img["data-src"] = img["src"]
img["src"] = ""
html = str(soup)
return '<div class="md-typeset">%s</div>' % html
return _markdown(value, lazy_load)

View file

@ -96,7 +96,7 @@ class Command(BaseCommand):
.replace("'//", "'https://")
)
maker.title = problem_name
for file in ("style.css", "pygment-github.css", "mathjax3_config.js"):
for file in ("style.css", "mathjax3_config.js"):
maker.load(file, os.path.join(settings.DMOJ_RESOURCES, file))
maker.make(debug=True)
if not maker.success:

117
judge/markdown.py Normal file
View file

@ -0,0 +1,117 @@
import markdown as _markdown
import bleach
from django.utils.html import escape
from bs4 import BeautifulSoup
from pymdownx import superfences
EXTENSIONS = [
"pymdownx.arithmatex",
"pymdownx.magiclink",
"pymdownx.betterem",
"pymdownx.details",
"pymdownx.emoji",
"pymdownx.inlinehilite",
"pymdownx.superfences",
"pymdownx.highlight",
"pymdownx.tasklist",
"markdown.extensions.footnotes",
"markdown.extensions.attr_list",
"markdown.extensions.def_list",
"markdown.extensions.tables",
"markdown.extensions.admonition",
"nl2br",
"mdx_breakless_lists",
]
EXTENSION_CONFIGS = {
"pymdownx.superfences": {
"custom_fences": [
{
"name": "sample",
"class": "no-border",
"format": superfences.fence_code_format,
}
],
},
"pymdownx.highlight": {
"auto_title": True,
"auto_title_map": {
"Text Only": "",
},
},
}
ALLOWED_TAGS = list(bleach.sanitizer.ALLOWED_TAGS) + [
"img",
"center",
"iframe",
"div",
"span",
"table",
"tr",
"td",
"th",
"tr",
"pre",
"code",
"p",
"hr",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"thead",
"tbody",
"sup",
"dl",
"dt",
"dd",
"br",
"details",
"summary",
]
ALLOWED_ATTRS = ["src", "width", "height", "href", "class", "open"]
def markdown(value, lazy_load=False):
extensions = EXTENSIONS
html = _markdown.markdown(
value, extensions=extensions, extension_configs=EXTENSION_CONFIGS
)
# Don't clean mathjax
hash_script_tag = {}
soup = BeautifulSoup(html, "html.parser")
for script_tag in soup.find_all("script"):
allow_math_types = ["math/tex", "math/tex; mode=display"]
if script_tag.attrs.get("type", False) in allow_math_types:
hash_script_tag[str(hash(str(script_tag)))] = str(script_tag)
for hashed_tag in hash_script_tag:
tag = hash_script_tag[hashed_tag]
html = html.replace(tag, hashed_tag)
html = bleach.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRS)
for hashed_tag in hash_script_tag:
tag = hash_script_tag[hashed_tag]
html = html.replace(hashed_tag, tag)
if not html:
html = escape(value)
if lazy_load:
soup = BeautifulSoup(html, features="html.parser")
for img in soup.findAll("img"):
if img.get("src"):
img["data-src"] = img["src"]
img["src"] = ""
for img in soup.findAll("iframe"):
if img.get("src"):
img["data-src"] = img["src"]
img["src"] = ""
html = str(soup)
return '<div class="md-typeset content-description">%s</div>' % html

View file

@ -24,7 +24,6 @@ def get_resource(request):
scheme = "http"
return {
"PYGMENT_THEME": settings.PYGMENT_THEME,
"INLINE_JQUERY": settings.INLINE_JQUERY,
"INLINE_FONTAWESOME": settings.INLINE_FONTAWESOME,
"JQUERY_JS": settings.JQUERY_JS,

View file

@ -406,7 +406,7 @@ class ProblemPdfView(ProblemMixin, SingleObjectMixin, View):
.replace("'//", "'https://")
)
maker.title = problem_name
assets = ["style.css", "pygment-github.css"]
assets = ["style.css"]
if maker.math_engine == "jax":
assets.append("mathjax3_config.js")
for file in assets:

View file

@ -344,7 +344,7 @@ def problem_init_view(request, problem):
"problem/yaml.html",
{
"raw_source": data,
"highlighted_source": highlight_code(data, "yaml", linenos=False),
"highlighted_source": highlight_code(data, "yaml", linenos=True),
"title": _("Generated init.yml for %s") % problem.name,
"content_title": mark_safe(
escape(_("Generated init.yml for %s"))

View file

@ -113,22 +113,6 @@ class SubmissionDetailBase(LoginRequiredMixin, TitleMixin, SubmissionMixin, Deta
)
class SubmissionSource(SubmissionDetailBase):
template_name = "submission/source.html"
def get_queryset(self):
return super().get_queryset().select_related("source")
def get_context_data(self, **kwargs):
context = super(SubmissionSource, self).get_context_data(**kwargs)
submission = self.object
context["raw_source"] = submission.source.source.rstrip("\n")
context["highlighted_source"] = highlight_code(
submission.source.source, submission.language.pygments, linenos=False
)
return context
def get_hidden_subtasks(request, submission):
contest = submission.contest_object
if contest and contest.is_editable_by(request.user):
@ -227,9 +211,11 @@ class SubmissionStatus(SubmissionDetailBase):
)
context["time_limit"] = submission.problem.time_limit
context["can_see_testcases"] = False
context["raw_source"] = submission.source.source.rstrip("\n")
context["highlighted_source"] = highlight_code(
submission.source.source, submission.language.pygments, linenos=False
submission.source.source,
submission.language.pygments,
linenos=True,
title=submission.language,
)
contest = submission.contest_or_none
@ -265,7 +251,7 @@ class SubmissionTestCaseQuery(SubmissionStatus):
return super(SubmissionTestCaseQuery, self).get(request, *args, **kwargs)
class SubmissionSourceRaw(SubmissionSource):
class SubmissionSourceRaw(SubmissionDetailBase):
def get(self, request, *args, **kwargs):
submission = self.get_object()
return HttpResponse(submission.source.source, content_type="text/plain")

View file

@ -117,7 +117,6 @@ else:
class Media:
css = {
"all": [
"pygment-github.css",
"table.css",
"ranks.css",
"dmmd-preview.css",