Skip to content

Instantly share code, notes, and snippets.

@MagerValp
Created September 25, 2017 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MagerValp/36e35384cba152fafae97dca865742f0 to your computer and use it in GitHub Desktop.
Save MagerValp/36e35384cba152fafae97dca865742f0 to your computer and use it in GitHub Desktop.
Convert markdown to html in a shell script using Xcode's CommonMark framework
#!/bin/bash
cat <<__MARKDOWN__ |
# Title ÅÄÖ
* list
__MARKDOWN__
/usr/bin/python <( cat <<__EOF__
#!/usr/bin/python
# -*- coding: utf-8 -*-
# https://gist.github.com/pudquick/03e454f4d2ad3ebe09216b78559c0541
import os
import sys
import ctypes
import subprocess
def save_stderr():
oldstderr = os.dup(2)
os.dup2(os.open("/dev/null", os.O_WRONLY), 2)
return oldstderr
def restore_stderr(oldstderr):
sys.stderr = os.fdopen(oldstderr, "w")
def open_commonmark():
oldstderr = save_stderr()
dev_path = subprocess.check_output(["xcode-select", "-p"]).rstrip()
xcode_path = dev_path.partition(".app/")[0] + ".app"
dtvmarkup_path = os.path.join(xcode_path, "Contents/SharedFrameworks/DVTMarkup.framework")
commonmark_path = os.path.join(dtvmarkup_path, "Versions/A/Frameworks/CommonMark.framework")
CM = ctypes.CDLL(os.path.join(commonmark_path, "CommonMark"))
restore_stderr(oldstderr)
return CM
CM = open_commonmark()
cmark_markdown_to_html = CM.cmark_markdown_to_html
cmark_markdown_to_html.restype = ctypes.c_char_p
def markdown_to_html(markdown):
mc = ctypes.create_string_buffer(markdown.encode("utf-8"))
return cmark_markdown_to_html(mc, len(mc)-1, 0).decode("utf-8")
sys.stdout.write(markdown_to_html(sys.stdin.read().decode("utf-8")).encode("utf-8"))
__EOF__
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment