1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# -*- coding: utf-8 -*-
"""
sphinx.highlighting
~~~~~~~~~~~~~~~~~~~
Highlight code blocks using Pygments.
:copyright: 2007 by Georg Brandl.
:license: Python license.
"""
import cgi
from collections import defaultdict
try:
import pygments
from pygments import highlight
from pygments.lexers import PythonLexer, PythonConsoleLexer, CLexer, \
TextLexer, RstLexer
from pygments.formatters import HtmlFormatter
from pygments.filters import ErrorToken
from pygments.style import Style
from pygments.styles.friendly import FriendlyStyle
from pygments.token import Generic, Comment
except ImportError:
pygments = None
else:
class PythonDocStyle(Style):
"""
Like friendly, but a bit darker to enhance contrast on the green background.
"""
background_color = '#eeffcc'
default_style = ''
styles = FriendlyStyle.styles
styles.update({
Generic.Output: 'italic #333',
Comment: 'italic #408090',
})
lexers = defaultdict(TextLexer,
none = TextLexer(),
python = PythonLexer(),
pycon = PythonConsoleLexer(),
rest = RstLexer(),
c = CLexer(),
)
for _lexer in lexers.values():
_lexer.add_filter('raiseonerror')
fmter = HtmlFormatter(style=PythonDocStyle)
def highlight_block(source, lang):
if not pygments:
return '<pre>' + cgi.escape(source) + '</pre>\n'
if lang == 'python':
if source.startswith('>>>'):
lexer = lexers['pycon']
else:
lexer = lexers['python']
else:
lexer = lexers[lang]
try:
return highlight(source, lexer, fmter)
except ErrorToken:
# this is most probably not Python, so let it pass textonly
return '<pre>' + cgi.escape(source) + '</pre>\n'
def get_stylesheet():
return fmter.get_style_defs()
|