github.com/hoffmann Peter Hoffmann on Stackoverflow @peterhoffmann on twitter Peter Hoffmann on Facebook Contact me per email Subscribe to Atom Feed

Peter Hoffmann

Software Engineer
prev page next page

Python markdown with github flavored code blocks

Posted on May 28, 2012
#python

Fenced code blocks are a github extension to markdown:

```python
print "hello world"
```

will render as:

<pre><code class="python">
print "hello world"
</code></pre>

The advantages are that you don't have to indent the code (which is useful when you copy and paste python code) and that you can add a language identifier which can be used to highlight the code with tools like highlight.js.

Adding github flavored markdown code blocks to python markdown is really easy. There is already the fenced code blocks extension. All you have to do is to customize the regular expression in markdown/extensions/fenced_code.py:

67c67
<     r'(?P<fence>^~{3,})[ ]*(\{?\.(?P<lang>[a-zA-Z0-9_-]*)\}?)?[ ]*\n(?P<code>.*?)(?P=fence)[ ]*$', 
---
>     r'(?P<fence>^`{3,})[ ]*(?P<lang>[a-zA-Z0-9_-]*)[ ]*\n(?P<code>.*?)(?P=fence)[ ]*$',