Skip to content

Commit 502f8d7

Browse files
committed
syntax highlightling
1 parent 53d2d76 commit 502f8d7

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

httpmdhtml/md_to_html.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22
just convert a markdown file to HTML and write it out to a file
33
"""
44
import os
5-
import sys
65
import base64
76
from pathlib import Path
87
import argparse
98
import re
109
from markdown_it import MarkdownIt
11-
from bs4 import BeautifulSoup, element
10+
from bs4 import BeautifulSoup
1211

1312

1413
def markdown_to_html(
@@ -26,9 +25,17 @@ def markdown_to_html(
2625
soup = BeautifulSoup(html_text, "html5lib") # adds <html>, <head>, <body>
2726
soup.select_one("head").append(soup.new_tag("meta"))
2827
soup.select_one("meta").attrs["charset"] = "UTF-8"
29-
# if lots of images, caching is preferable more often than not
30-
# soup.select_one('meta').attrs['http-equiv'] = "Cache-control"
31-
# soup.select_one('meta').attrs['content'] = "no-cache"
28+
29+
# syntax highlighting
30+
soup.select_one('head').append(soup.new_tag('link'))
31+
soup.select_one("link").attrs["rel"] = "stylesheet"
32+
soup.select_one("link").attrs["href"] = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/monokai.min.css"
33+
34+
soup.select_one('head').append(soup.new_tag('script'))
35+
soup.select("script")[0].attrs['src'] ='https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js'
36+
soup.select_one('head').append(soup.new_tag('script'))
37+
soup.select("script")[1].string = 'hljs.highlightAll();'
38+
3239
soup.select_one("head").append(soup.new_tag("style"))
3340
if css_file:
3441
if css_file == "none":
@@ -52,7 +59,7 @@ def markdown_to_html(
5259
f"setTimeout(function(){{ document.location.reload(); }}, {live_md_rr});"
5360
)
5461
soup.select_one("head").append(soup.new_tag("script"))
55-
soup.select_one("script").string = script
62+
soup.select("script")[-1].string = script
5663
if encode_local_images:
5764
img_elems = soup.select("img")
5865
url_pattern = "^https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$"
@@ -77,7 +84,7 @@ def markdown_to_html(
7784
parser.add_argument(
7885
"--out_file_path",
7986
"-o",
80-
default="tmp.html",
87+
default=None,
8188
help="out-file-path; your HTML file to be created",
8289
)
8390
parser.add_argument(
@@ -93,6 +100,9 @@ def markdown_to_html(
93100
)
94101
args = parser.parse_args()
95102

103+
if not args.out_file_path:
104+
args.out_file_path = str(Path(args.in_file_path).with_suffix('.html'))
105+
96106
markdown_to_html(
97107
MarkdownIt_obj=MarkdownIt_obj,
98108
in_file_path=args.in_file_path,

0 commit comments

Comments
 (0)