| 1 | # -*- coding: utf-8 -*- |
|---|
| 2 | """ |
|---|
| 3 | The Pygments Markdown Preprocessor |
|---|
| 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|---|
| 5 | |
|---|
| 6 | This fragment is a Markdown_ preprocessor that renders source code |
|---|
| 7 | to HTML via Pygments. To use it, invoke Markdown like so:: |
|---|
| 8 | |
|---|
| 9 | from markdown import Markdown |
|---|
| 10 | |
|---|
| 11 | md = Markdown() |
|---|
| 12 | md.textPreprocessors.insert(0, CodeBlockPreprocessor()) |
|---|
| 13 | html = md.convert(someText) |
|---|
| 14 | |
|---|
| 15 | markdown is then a callable that can be passed to the context of |
|---|
| 16 | a template and used in that template, for example. |
|---|
| 17 | |
|---|
| 18 | This uses CSS classes by default, so use |
|---|
| 19 | ``pygmentize -S <some style> -f html > pygments.css`` |
|---|
| 20 | to create a stylesheet to be added to the website. |
|---|
| 21 | |
|---|
| 22 | You can then highlight source code in your markdown markup:: |
|---|
| 23 | |
|---|
| 24 | [sourcecode:lexer] |
|---|
| 25 | some code |
|---|
| 26 | [/sourcecode] |
|---|
| 27 | |
|---|
| 28 | .. _Markdown: http://www.freewisdom.org/projects/python-markdown/ |
|---|
| 29 | |
|---|
| 30 | :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. |
|---|
| 31 | :license: BSD, see LICENSE for details. |
|---|
| 32 | """ |
|---|
| 33 | |
|---|
| 34 | # Options |
|---|
| 35 | # ~~~~~~~ |
|---|
| 36 | |
|---|
| 37 | # Set to True if you want inline CSS styles instead of classes |
|---|
| 38 | INLINESTYLES = False |
|---|
| 39 | |
|---|
| 40 | |
|---|
| 41 | import re |
|---|
| 42 | |
|---|
| 43 | from markdown import TextPreprocessor |
|---|
| 44 | |
|---|
| 45 | from pygments import highlight |
|---|
| 46 | from pygments.formatters import HtmlFormatter |
|---|
| 47 | from pygments.lexers import get_lexer_by_name, TextLexer |
|---|
| 48 | |
|---|
| 49 | |
|---|
| 50 | class CodeBlockPreprocessor(TextPreprocessor): |
|---|
| 51 | |
|---|
| 52 | pattern = re.compile( |
|---|
| 53 | r'\[sourcecode:(.+?)\](.+?)\[/sourcecode\]', re.S) |
|---|
| 54 | |
|---|
| 55 | formatter = HtmlFormatter(noclasses=INLINESTYLES) |
|---|
| 56 | |
|---|
| 57 | def run(self, lines): |
|---|
| 58 | def repl(m): |
|---|
| 59 | try: |
|---|
| 60 | lexer = get_lexer_by_name(m.group(1)) |
|---|
| 61 | except ValueError: |
|---|
| 62 | lexer = TextLexer() |
|---|
| 63 | code = highlight(m.group(2), lexer, self.formatter) |
|---|
| 64 | code = code.replace('\n\n', '\n \n').replace('\n', '<br />') |
|---|
| 65 | return '\n\n<div class="code">%s</div>\n\n' % code |
|---|
| 66 | return self.pattern.sub( |
|---|
| 67 | repl, lines) |
|---|