comparison pylons_app/lib/helpers.py @ 165:ea893ffb7f00

implemented pygmentize codes into webhelpers. Together with color_dict caching into pylons globals
author Marcin Kuzminski <marcin@python-works.com>
date Fri, 21 May 2010 02:07:49 +0200
parents 4cea52709743
children be4621c6de58
comparison
equal deleted inserted replaced
164:1231bbe1ab36 165:ea893ffb7f00
1 """Helper functions 1 """Helper functions
2 2
3 Consists of functions to typically be used within templates, but also 3 Consists of functions to typically be used within templates, but also
4 available to Controllers. This module is available to both as 'h'. 4 available to Controllers. This module is available to both as 'h'.
5 """ 5 """
6 from pylons import url 6 from pylons import url, app_globals as g
7 from pylons.i18n.translation import _, ungettext 7 from pylons.i18n.translation import _, ungettext
8 from webhelpers.html import (literal, HTML, escape) 8 from webhelpers.html import (literal, HTML, escape)
9 from webhelpers.html.builder import make_tag 9 from webhelpers.html.builder import make_tag
10 from webhelpers.html.tools import (auto_link, button_to, highlight, js_obfuscate 10 from webhelpers.html.tools import (auto_link, button_to, highlight, js_obfuscate
11 , mail_to, strip_links, strip_tags, tag_re) 11 , mail_to, strip_links, strip_tags, tag_re)
17 submit, text, password, textarea, title, 17 submit, text, password, textarea, title,
18 ul, xml_declaration) 18 ul, xml_declaration)
19 from webhelpers.text import (chop_at, collapse, convert_accented_entities, 19 from webhelpers.text import (chop_at, collapse, convert_accented_entities,
20 convert_misc_entities, lchop, plural, rchop, 20 convert_misc_entities, lchop, plural, rchop,
21 remove_formatting, replace_whitespace, urlify) 21 remove_formatting, replace_whitespace, urlify)
22 22 from webhelpers.number import (format_byte_size, format_bit_size)
23 from webhelpers.pylonslib import Flash as _Flash 23 from webhelpers.pylonslib import Flash as _Flash
24 from webhelpers.pylonslib.secure_form import secure_form 24 from webhelpers.pylonslib.secure_form import secure_form
25 25
26 from pygments import highlight 26 from pygments import highlight
27 from pygments.formatters import HtmlFormatter 27 from pygments.formatters import HtmlFormatter
48 def __call__(self, field_name, form_errors): 48 def __call__(self, field_name, form_errors):
49 tmpl = """<span class="error_msg">%s</span>""" 49 tmpl = """<span class="error_msg">%s</span>"""
50 if form_errors and form_errors.has_key(field_name): 50 if form_errors and form_errors.has_key(field_name):
51 return literal(tmpl % form_errors.get(field_name)) 51 return literal(tmpl % form_errors.get(field_name))
52 52
53 class _FileSizeFormat(object):
54 """
55 Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
56 102 bytes, etc).
57 """
58 def __call__(self, bytes):
59 try:
60 bytes = float(bytes)
61 except TypeError:
62 return u"0 bytes"
63
64 if bytes < 1024:
65 return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
66 if bytes < 1024 * 1024:
67 return _("%.1f KB") % (bytes / 1024)
68 if bytes < 1024 * 1024 * 1024:
69 return _("%.1f MB") % (bytes / (1024 * 1024))
70 return _("%.1f GB") % (bytes / (1024 * 1024 * 1024))
71
72 class _FilesBreadCrumbs(object): 53 class _FilesBreadCrumbs(object):
73 54
74 def __call__(self, repo_name, rev, paths): 55 def __call__(self, repo_name, rev, paths):
75 url_l = [link_to(repo_name, url('files_home', repo_name=repo_name, revision=rev, f_path=''))] 56 url_l = [link_to(repo_name, url('files_home', repo_name=repo_name, revision=rev, f_path=''))]
76 paths_l = paths.split('/') 57 paths_l = paths.split('/')
80 url_l.append(link_to(p, url('files_home', repo_name=repo_name, revision=rev, f_path='/'.join(paths_l[:cnt])))) 61 url_l.append(link_to(p, url('files_home', repo_name=repo_name, revision=rev, f_path='/'.join(paths_l[:cnt]))))
81 62
82 return literal(' / '.join(url_l)) 63 return literal(' / '.join(url_l))
83 64
84 def pygmentize(code, **kwargs): 65 def pygmentize(code, **kwargs):
85 ''' 66 """
86 Filter for chunks of html to replace code tags with pygmented code 67 Filter for chunks of html to replace code tags with pygmented code
87 ''' 68 """
88 return literal(highlight(code, guess_lexer(code), HtmlFormatter(**kwargs))) 69 code = code.splitlines()
70 _html, _html2 = [], []
71 _html.append("""<table class="code-highlighttable">""")
72 _html.append("""<tr>""")
73 _html.append("""<td class="linenos">""")
74 _html.append("""<div class="linenodiv">""")
75 _html.append("""<pre>""")
76 for cnt, code in enumerate(code, 1):
77 #generete lines nos
78 _html.append("""<a id="A%s" href="#A%s">%s</a>\n""" \
79 % (cnt, cnt, cnt))
80 #propagate second list with code
81 _html2.append("""%s""" % (highlight(code, get_lexer_by_name('python'),
82 HtmlFormatter(nowrap=True))))
83 _html.append("""</pre>""")
84 _html.append("""</div>""")
85 _html.append("""</td>""")
86 _html.append("""<td class="code">""")
87 _html.append("""<div class="code-highlight">""")
88 _html.append("""<pre>""")
89 _html.extend(_html2)
90 _html.append("""</pre>""")
91 _html.append("""</div>""")
92 _html.append("""</td>""")
93 _html.append("""</tr>""")
94 _html.append("""</table>""")
95 return literal(''.join(_html))
96 #return literal(highlight(code, get_lexer_by_name('python'), HtmlFormatter(**kwargs)))
97
98 def pygmentize_annotation(annotate_list, repo_name):
99 """
100 Generate a dict of
101 @param annotate_lists:
102 """
103 import random
104 color_dict = g.changeset_annotation_colors
105 def gen_color():
106 return [str(random.randrange(0, 255)) for _ in xrange(3)]
107 def get_color_string(cs):
108 if color_dict.has_key(cs):
109 col = color_dict[cs]
110 else:
111 color_dict[cs] = gen_color()
112 col = color_dict[cs]
113 return "color: rgb(%s) ! important;" % (','.join(col))
114 _html, _html2, _html3 = [], [], []
115 _html.append("""<table class="code-highlighttable">""")
116 _html.append("""<tr>""")
117 _html.append("""<td class="linenos">""")
118 _html.append("""<div class="linenodiv">""")
119 _html.append("""<pre>""")
120 for line in annotate_list:
121 #lines
122 _html.append("""<a id="A%s" href="#S%s">%s</a>\n""" \
123 % (line[0], line[0], line[0]))
124 #annotation tags
125 _html2.append("""%s\n""" % link_to(line[1].raw_id,
126 url('changeset_home', repo_name=repo_name, revision=line[1].raw_id),
127 title=_('author') + ':%s rev:%s %s' % (line[1].author, line[1].revision,
128 line[1].message,),
129 style=get_color_string(line[1].raw_id)))
130 #code formated with pygments
131 _html3.append("""%s""" % (highlight(line[2], get_lexer_by_name('python')
132 , HtmlFormatter(nowrap=True))))
133 _html.append("""</pre>""")
134 _html.append("""</div>""")
135 _html.append("""</td>""")
136 _html.append("""<td class="linenos">""")
137 _html.append("""<div class="linenodiv">""")
138 _html.append("""<pre>""")
139 _html.extend(_html2)
140 _html.append("""</pre>""")
141 _html.append("""</div>""")
142 _html.append("""</td>""")
143 _html.append("""<td class="code">""")
144 _html.append("""<div class="code-highlight">""")
145 _html.append("""<pre>""")
146 _html.extend(_html3)
147 _html.append("""</pre>""")
148 _html.append("""</div>""")
149 _html.append("""</td>""")
150 _html.append("""</tr>""")
151 _html.append("""</table>""")
152 return literal(''.join(_html))
89 153
90 154
91 files_breadcrumbs = _FilesBreadCrumbs() 155 files_breadcrumbs = _FilesBreadCrumbs()
92 filesizeformat = _FileSizeFormat()
93 link = _Link() 156 link = _Link()
94 flash = _Flash() 157 flash = _Flash()
95 get_error = _GetError() 158 get_error = _GetError()