Hello, my name is Joshua Inkenbrandt and I live in Kansas City, Missouri with my wife and two kids. I'm a Mac guy. I'm a Python guy.

My goal is to make cool stuff that's fun and easy to use.

Only showing Posts with tag creole X

January 22, 2010

Creating A Pygments Macro for Creole.

When I created this site I decided to use Creole for my markup of choice. So far I really enjoy using it. One of the really nice things about Creole is that you can create macros that allow for custom markup. I've created one for use with Pygments.

import pygments
import pygments.lexers
import pygments.formatters
import genshi.core
import creoleparser
import creoleparser.core
import creoleparser.dialects as dialects

def highlight(text, lang=None):
    lexer = None
    if lang:
        lexer = pygments.lexers.get_lexer_by_name(lang, stripall=True)
    if not lexer:
        lexer = pygments.lexers.guess_lexer(text)
    if lexer:
        text = pygments.highlight(text, lexer, pygments.formatters.HtmlFormatter())
    return genshi.core.Markup(text)
    
def pygments_macro(macro_name, arg_string, body, isblock, environ):
    if macro_name == 'mycode':
        args, kwargs = creoleparser.parse_args(arg_string)
        lang = kwargs.get('lang', None)
        return highlight(body, lang)

test_str = """
Here's some code:
<<mycode lang='python'>>
def hello(who):
    print "Hello %s" % who

hello('world')
<</mycode>>"""        
        
def test_pygments_macro():
    dialect = dialects.create_dialect(dialects.creole11_base, macro_func=pygments_macro)
    parser = creoleparser.Parser(dialect=dialect)
    print parser(test_str)
    
if __name__ == "__main__":
    test_pygments_macro()

Most of it is self-explanatory. The only gotcha is when you need to return raw HTML, you have to wrap it in an instance of the Markup class (from genshi.core) otherwise the creoleparser will HTML escape your text. For more help with macros in Creole, try http://creoleparser.googlecode.com/svn/docs/macros.html