-
Notifications
You must be signed in to change notification settings - Fork 118
/
tools.py
57 lines (48 loc) · 2.16 KB
/
tools.py
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
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2011 Alexander Kojevnikov <[email protected]>
#
# hilite.me is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# hilite.me is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with hilite.me. If not, see <http://www.gnu.org/licenses/>.
import re
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
def hilite_me(code, lexer, options, style, linenos, divstyles):
lexer = lexer or 'python'
style = style or 'colorful'
defstyles = 'overflow:auto;width:auto;'
formatter = HtmlFormatter(style=style,
linenos=False,
noclasses=True,
cssclass='',
cssstyles=defstyles + divstyles,
prestyles='margin: 0')
html = highlight(code, get_lexer_by_name(lexer, **options), formatter)
if linenos:
html = insert_line_numbers(html)
html = "<!-- HTML generated using hilite.me -->" + html
return html
def get_default_style():
return 'border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;'
def insert_line_numbers(html):
match = re.search('(<pre[^>]*>)(.*)(</pre>)', html, re.DOTALL)
if not match: return html
pre_open = match.group(1)
pre = match.group(2)
pre_close = match.group(3)
html = html.replace(pre_close, '</pre></td></tr></table>')
numbers = range(1, pre.count('\n') + 1)
format = '%' + str(len(str(numbers[-1]))) + 'i'
lines = '\n'.join(format % i for i in numbers)
html = html.replace(pre_open, '<table><tr><td>' + pre_open + lines + '</pre></td><td>' + pre_open)
return html