diff src/tools/common/template.py @ 2454:06ff33052354

core, template (filters): added pygments as a dependency + new highlight filter to use it.
author Goffi <goffi@goffi.org>
date Thu, 30 Nov 2017 21:00:24 +0100
parents 84e84a46b014
children bb0bbcc80fc8
line wrap: on
line diff
--- a/src/tools/common/template.py	Thu Nov 30 20:59:24 2017 +0100
+++ b/src/tools/common/template.py	Thu Nov 30 21:00:24 2017 +0100
@@ -32,6 +32,9 @@
 from babel import Locale
 from babel.core import UnknownLocaleError
 from babel import dates
+import pygments
+from pygments import lexers
+from pygments import formatters
 try:
     import sat_templates
 except ImportError:
@@ -208,6 +211,7 @@
         self.env.filters['item_filter'] = self._item_filter
         self.env.filters['adv_format'] = self._adv_format
         self.env.filters['dict_ext'] = self._dict_ext
+        self.env.filters['highlight'] = self.highlight
         # custom tests
         self.env.tests['in_the_past'] = self._in_the_past
 
@@ -511,6 +515,27 @@
         ret.update(extra_dict)
         return ret
 
+    def highlight(self, code, lexer_name=None, lexer_opts=None, html_fmt_opts=None):
+        """Do syntax highlighting on code
+
+        under the hood, pygments is used, check its documentation for options possible values
+        @param code(unicode): code or markup to highlight
+        @param lexer_name(unicode, None): name of the lexer to use
+            None to autodetect it
+        @param html_fmt_opts(dict, None): kword arguments to use for HtmlFormatter
+        @return (unicode): HTML markup with highlight classes
+        """
+        if lexer_opts is None:
+            lexer_opts = {}
+        if html_fmt_opts is None:
+            html_fmt_opts = {}
+        if lexer_name is None:
+            lexer = lexers.guess_lexer(code, **lexer_opts)
+        else:
+            lexer = lexers.get_lexer_by_name(lexer_name, **lexer_opts)
+        formatter = formatters.HtmlFormatter(**html_fmt_opts)
+        return safe(pygments.highlight(code, lexer, formatter))
+
     ## custom tests ##
 
     def _in_the_past(self, timestamp):