From 89425349e0f8162d7ec59d995a26a7d798533e90 Mon Sep 17 00:00:00 2001 From: Waylan Limberg Date: Thu, 7 Apr 2011 03:13:52 -0400 Subject: Factored out the importing of pygments in CodeHilite Extension so it doesn;t happen every time a block is highlighted. Not sure why I didn't do it this way to begin with. --- markdown/extensions/codehilite.py | 51 ++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/markdown/extensions/codehilite.py b/markdown/extensions/codehilite.py index f7a9b8c..4be1ad5 100644 --- a/markdown/extensions/codehilite.py +++ b/markdown/extensions/codehilite.py @@ -21,6 +21,13 @@ Dependencies: """ import markdown +try: + from pygments import highlight + from pygments.lexers import get_lexer_by_name, guess_lexer, TextLexer + from pygments.formatters import HtmlFormatter + pygments = True +except ImportError: + pygments = False # ------------------ The Main CodeHilite Class ---------------------- class CodeHilite: @@ -71,25 +78,7 @@ class CodeHilite: if self.lang == None: self._getLang() - try: - from pygments import highlight - from pygments.lexers import get_lexer_by_name, guess_lexer, \ - TextLexer - from pygments.formatters import HtmlFormatter - except ImportError: - # just escape and build markup usable by JS highlighting libs - txt = self._escape(self.src) - classes = [] - if self.lang: - classes.append('language-%s' % self.lang) - if self.linenos: - classes.append('linenums') - class_str = '' - if classes: - class_str = ' class="%s"' % ' '.join(classes) - return '
%s
\n'% \ - (self.css_class, class_str, txt) - else: + if pygments: try: lexer = get_lexer_by_name(self.lang) except ValueError: @@ -102,14 +91,22 @@ class CodeHilite: style=self.style, noclasses=self.noclasses) return highlight(self.src, lexer, formatter) - - def _escape(self, txt): - """ basic html escaping """ - txt = txt.replace('&', '&') - txt = txt.replace('<', '<') - txt = txt.replace('>', '>') - txt = txt.replace('"', '"') - return txt + else: + # just escape and build markup usable by JS highlighting libs + txt = self.src.replace('&', '&') + txt = txt.replace('<', '<') + txt = txt.replace('>', '>') + txt = txt.replace('"', '"') + classes = [] + if self.lang: + classes.append('language-%s' % self.lang) + if self.linenos: + classes.append('linenums') + class_str = '' + if classes: + class_str = ' class="%s"' % ' '.join(classes) + return '
%s
\n'% \ + (self.css_class, class_str, txt) def _getLang(self): """ -- cgit v1.2.3