Created
March 28, 2017 13:39
-
-
Save sbp/96c1fc6321ae06a978b88595722e88ec to your computer and use it in GitHub Desktop.
Literate Markdown comments in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import re | |
import subprocess | |
import sys | |
pattern = r'(?s)("[^"\\]*(?:\\.[^"\\]*)*")|/\*(.*?)\*/|([^"/]+)|(.)' | |
token = re.compile(pattern) | |
def put(text): | |
print(text, end="") | |
def escape(text): | |
text = text.replace("&", "&") | |
text = text.replace("<", "<") | |
return text.replace(">", ">") | |
def main(): | |
put('<meta charset="utf-8">\n') | |
put('<title>%s</title>\n' % escape(sys.argv[1])) | |
preformatted = False | |
with open(sys.argv[1], encoding="utf-8") as f: | |
text = f.read() | |
for string, comment, code1, code2 in token.findall(text): | |
code = string or code1 or code2 | |
if code: | |
if preformatted is False: | |
put("<pre>\n") | |
preformatted = True | |
code = code.lstrip() | |
put(escape(code)) | |
continue | |
comment = (comment.strip() + "\n").encode("utf-8") | |
if preformatted is True: | |
put("</pre>\n") | |
preformatted = False | |
try: | |
command = ["cmark", "/dev/stdin"] | |
html = subprocess.check_output(command, input=comment) | |
except subprocess.CalledProcessError as err: | |
put("<p>Markdown Error: %s</p>\n" % escape(str(err))) | |
else: | |
put(str(html, "utf-8")) | |
if preformatted is True: | |
put("</pre>\n") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment