Skip to content

Instantly share code, notes, and snippets.

@yangg
Created July 27, 2012 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yangg/3186215 to your computer and use it in GitHub Desktop.
Save yangg/3186215 to your computer and use it in GitHub Desktop.
Markdown & syntax highlighter
<?php
namespace Sundown\Render;
class Colorful extends HTML {
public function blockCode($code, $lang) {
if($lang) {
return self::renderCode($code, $lang);
}
return parent::blockCode($code, $lang);
}
public static function renderCode($code, $lang) {
$tmp = tmpfile();
fwrite($tmp, $code);
$meta_data = stream_get_meta_data($tmp);
$cmd = "pygmentize -f html -l $lang -P encoding=utf-8 {$meta_data['uri']}";
$output = shell_exec($cmd);
fclose($tmp);
return $output;
}
}
#!/usr/bin/env python
import sys
import misaka as m
from misaka import HtmlRenderer, Markdown
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
# https://github.com/FSX/misaka
# http://pygments.org/
class ColorRenderer(HtmlRenderer):
def block_code(self, text, lang):
if not lang:
return '<pre><code>%s</code></pre>' % text.strip()
lexer = get_lexer_by_name(lang, stripall = True)
return highlight(text, lexer, HtmlFormatter())
if __name__ == '__main__':
if len(sys.argv) > 1:
with open(sys.argv[1], 'r') as fd:
text = fd.read()
else:
text = sys.stdin.read()
text = text.decode('utf-8')
flags = m.HTML_HARD_WRAP
exts = m.EXT_FENCED_CODE | m.EXT_AUTOLINK | m.EXT_NO_INTRA_EMPHASIS | m.EXT_SUPERSCRIPT | m.EXT_TABLES
md = Markdown(ColorRenderer(flags), exts)
print md.render(text).encode('utf-8')
<?php
function Markdown($text) {
$desc = array( array('pipe', 'r'), array('pipe', 'w'));
$process = proc_open(__DIR__.'/markdown', $desc, $pipes);
fwrite($pipes[0], $text);
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
return $output;
}
/*
* https://github.com/chobie/php-sundown
*/
function Markdown1($text) {
exec('pygmentize', $output, $status);
if($status === 0) {
include_once 'Colorful.php';
}
$flags = array("hard_wrap" => true);
$extensions = array(
"hard_wrap" => true,
"fenced_code_blocks" => true,
"autolink" => true,
);
$renderClass = 'Sundown\Render'. (class_exists('Sundown\Render\Colorful') ? '\Colorful' : '\HTML');
$sundown = new Sundown\Markdown(new $renderClass($flags), $extensions);
return $sundown->render($text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment