- code_element = next(pre_element.children)
-
- # FIXME: this method sucks, but can we do better?
- fixed_pre = (
- str(code_element)
- .replace(" ", '.')
- .replace("\n", "
")
- )
+ code_element = pre_element.find("code")
+ if code_element is None: continue
+
+ # Keep syntax-highlighting tags intact: only rewrite text nodes.
+ for text_node in list(code_element.find_all(string=True)):
+ lines = str(text_node).split("\n")
+
+ # minihtml ignores normal spaces/newlines in , so preserve them.
+ for index, line in enumerate(lines):
+ if index: text_node.insert_before(soup.new_tag("br"))
+
+ if line: text_node.insert_before(
+ bs4.NavigableString(line.replace(" ", "\xa0"))
+ )
- code_element.replace_with(bs4.BeautifulSoup(fixed_pre, "html.parser"))
+ text_node.extract()
+
+ # FIXME: highlight the code using Sublime's syntax if needed
+ # currently using pygments codehilite stylesheet (not that good looking)
+
+ # Reuse markdown2.py Pygments HTML classes by injecting matching CSS
+ try:
+ from pygments.formatters import HtmlFormatter
+ except ImportError:
+ # Fallback: keep preview working without token colors.
+ pygments_stylesheet = ""
+ else:
+ pygments_stylesheet = HtmlFormatter(cssclass="codehilite").get_style_defs(
+ ".codehilite"
+ )
- # FIXME: highlight the code using Sublime's syntax
+ # add the pygments stylesheet to the end of the existing stylesheet
+ stylesheet = resources["stylesheet"] + "\n\n" + pygments_stylesheet
# FIXME: report that ST doesn't support
but does work with
... WTF?
- return "\n\n{}".format(resources["stylesheet"], soup).replace(
+ return "\n\n{}".format(stylesheet, soup).replace(
"
", "
"
)