root/trunk/plugins/SyntaxHighlight.py

Revision 215 (checked in by llimllib, 10 months ago)

need to import the exception

Line 
1 """Prerequisites: pygments (http://pygments.org)
2
3 To get code highlighting, you'll need to generate a CSS file from your
4 favorite Pygments theme and include it in your header; see an example css
5 file at http://billmill.org:9561/cherry_blossom/browser/trunk/static/code.css
6 . If you want to generate the CSS on the fly, check out this earlier revision
7 of SyntaxHighlighter which did so:
8 http://billmill.org:9561/cherry_blossom/browser/trunk/plugins/SyntaxHighlight.py?rev=197
9
10
11 Configuration for SyntaxHighlight module should be in a [SyntaxHighlight]
12     secion of your cherryblossom.conf file.
13
14 options:
15 syntax_style (string): Style to use for highlighting text. Check out the style
16     documentation at http://pygments.org/docs/styles/ and take the styles out
17     for a test drive at http://pygments.org/demo/
18 """
19
20 import cherrypy as cpy
21 import re
22 import pygments
23 from cgi import escape
24 from pygments.lexers import get_lexer_by_name
25 from pygments.formatters import HtmlFormatter
26 from pygments.util import ClassNotFound
27 from utils import config
28
29 CODE_RE = re.compile("<code (?:\s*lang=(.*?))*>(.*?)<(?#)/code>", re.S)
30
31 class SyntaxHighlight(object):
32     def __init__(self, parent): pass
33
34     def highlight_code(self, textstr, font_tags=False):
35         for lang, code in CODE_RE.findall(textstr):
36             if not lang: lang = "python"
37
38             try:
39                 lexer = get_lexer_by_name(lang.strip('"'))
40             except ClassNotFound:
41                 return
42             formatter = HtmlFormatter(style=config("syntax_style", "default",
43                 "SyntaxHighlight"), noclasses=font_tags)
44             code = pygments.highlight(code, lexer, formatter)
45
46             textstr = CODE_RE.sub(code, textstr, 1)
47         return textstr
48
49     #story is an Entry object
50     def cb_feed_story(self, story):
51         #de-lazify the object
52         story.text
53         story._text = self.highlight_code(story._text, font_tags=True)
54        
55     #story is an Entry object
56     def cb_story(self, story):
57         #de-lazify the object
58         story.text
59         story._text = self.highlight_code(story._text)
Note: See TracBrowser for help on using the browser.