1 # highlight.py - highlight extension implementation file
3 # Copyright 2007-2009 Adam Hupp <adam@hupp.org> and others
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2, incorporated herein by reference.
8 # The original module was split in an interface and an implementation
9 # file to defer pygments loading and speedup extension setup.
11 from mercurial import demandimport
12 demandimport.ignore.extend(['pkgutil', 'pkg_resources', '__main__',])
13 from mercurial import util, encoding
15 from pygments import highlight
16 from pygments.util import ClassNotFound
17 from pygments.lexers import guess_lexer, guess_lexer_for_filename, TextLexer
18 from pygments.formatters import HtmlFormatter
20 SYNTAX_CSS = ('\n<link rel="stylesheet" href="{url}highlightcss" '
23 def pygmentize(field, fctx, style, tmpl):
25 # append a <link ...> to the syntax highlighting css
26 old_header = ''.join(tmpl('header'))
27 if SYNTAX_CSS not in old_header:
28 new_header = old_header + SYNTAX_CSS
29 tmpl.cache['header'] = new_header
35 # avoid UnicodeDecodeError in pygments
36 text = encoding.tolocal(text)
38 # To get multi-line strings right, we can't format line-by-line
40 lexer = guess_lexer_for_filename(fctx.path(), text[:1024],
41 encoding=encoding.encoding)
42 except (ClassNotFound, ValueError):
44 lexer = guess_lexer(text[:1024], encoding=encoding.encoding)
45 except (ClassNotFound, ValueError):
46 lexer = TextLexer(encoding=encoding.encoding)
48 formatter = HtmlFormatter(style=style, encoding=encoding.encoding)
50 colorized = highlight(text, lexer, formatter)
52 colorized = colorized[:colorized.find('\n</pre>')]
53 colorized = colorized[colorized.find('<pre>')+5:]
54 coloriter = iter(colorized.splitlines())
56 tmpl.filters['colorize'] = lambda x: coloriter.next()
58 oldl = tmpl.cache[field]
59 newl = oldl.replace('line|escape', 'line|colorize')
60 tmpl.cache[field] = newl