diff --git a/markdown2html.py b/markdown2html.py index 4e70cbd..2b55c83 100644 --- a/markdown2html.py +++ b/markdown2html.py @@ -69,22 +69,42 @@ def markdown2html(markdown, basepath, re_render, resources, viewport_width): # pre aren't handled by ST3. The require manual adjustment for pre_element in soup.find_all("pre"): - # select the first child, - 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( "
", "
" )