Debian Codegraph @

external/markdown-processor.py

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