diff options
author | gbrandl <devnull@localhost> | 2007-09-12 22:22:44 +0200 |
---|---|---|
committer | gbrandl <devnull@localhost> | 2007-09-12 22:22:44 +0200 |
commit | 7c0271f06490b6dc42381f3679f8c79813f326c1 (patch) | |
tree | 697b7ca1323a1eccec6b30212caf03d2c0dc9483 /external/markdown-processor.py | |
parent | e85745364b2f6760dd65ca088c3b9030bbe79b04 (diff) | |
download | pygments-7c0271f06490b6dc42381f3679f8c79813f326c1.tar.gz |
Add externals for Markdown and ReST. (Ticket #268).
Diffstat (limited to 'external/markdown-processor.py')
-rw-r--r-- | external/markdown-processor.py | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/external/markdown-processor.py b/external/markdown-processor.py new file mode 100644 index 00000000..d4cbe61c --- /dev/null +++ b/external/markdown-processor.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +""" + The Pygments Markdown Preprocessor + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + This fragment is a Markdown_ preprocessor that renders source code + to HTML via Pygments. To use it, invoke Markdown like so:: + + from markdown import Markdown + + md = Markdown() + md.preprocessors.insert(0, CodeBlockPreprocessor()) + markdown = md.__str__ + + markdown is then a callable that can be passed to the context of + a template and used in that template, for example. + + This uses CSS classes by default, so use + ``pygmentize -S <some style> -f html > pygments.css`` + to create a stylesheet to be added to the website. + + You can then highlight source code in your markdown markup:: + + [sourcecode:lexer] + some code + [/sourcecode] + + .. _Markdown: http://www.freewisdom.org/projects/python-markdown/ + + :copyright: 2007 by Jochen Kupperschmidt. + :license: BSD, see LICENSE for more details. +""" + +# Options +# ~~~~~~~ + +# Set to True if you want inline CSS styles instead of classes +INLINESTYLES = False + + +import re + +from markdown import Preprocessor + +from pygments import highlight +from pygments.formatters import HtmlFormatter +from pygments.lexers import get_lexer_by_name, TextLexer + + +class CodeBlockPreprocessor(Preprocessor): + + pattern = re.compile( + r'\[sourcecode:(.+?)\](.+?)\[/sourcecode\]', re.S) + + formatter = HtmlFormatter(noclasses=INLINESTYLES) + + def run(self, lines): + def repl(m): + try: + lexer = get_lexer_by_name(m.group(1)) + except ValueError: + lexer = TextLexer() + code = highlight(m.group(2), lexer, formatter) + code = code.replace('\n\n', '\n \n') + return '\n\n<div class="code">%s</div>\n\n' % code + return self.pattern.sub( + repl, '\n'.join(lines)).split('\n') + |