optional source headblob syntax highlighting using python-pygments
darcsweb.cgi
Thu Aug 7 05:31:41 UTC 2008 Alexandre Rossi <alexandre.rossi@gmail.com>
* optional source headblob syntax highlighting using python-pygments
--- old-darcsweb/darcsweb.cgi 2015-10-28 03:20:07.000000000 +0000
+++ new-darcsweb/darcsweb.cgi 2015-10-28 03:20:07.000000000 +0000
@@ -19,6 +19,13 @@
import urllib
import xml.sax
from xml.sax.saxutils import escape as xml_escape
+try:
+ import pygments
+ import pygments.lexers
+ import pygments.formatters
+except ImportError:
+ pygments = False
+
time_imports = time.time() - time_begin
iso_datetime = '%Y-%m-%dT%H:%M:%SZ'
@@ -1262,14 +1269,32 @@
def print_blob(fname):
print '<div class="page_path"><b>%s</b></div>' % escape(fname)
- print '<div class="page_body">'
if isbinary(fname):
print """
+<div class="page_body">
<i>This is a binary file and its contents will not be displayed.</i>
</div>
"""
return
+ if not pygments:
+ print_blob_simple(fname)
+ return
+ else:
+ try:
+ print_blob_highlighted(fname)
+ except ValueError:
+ # pygments couldn't guess a lexer to highlight the code, try
+ # another method with sampling the file contents.
+ try:
+ print_blob_highlighted(fname, sample_code=True)
+ except ValueError:
+ # pygments really could not find any lexer for this file.
+ print_blob_simple(fname)
+
+def print_blob_simple(fname):
+ print '<div class="page_body">'
+
f = open(realpath(fname), 'r')
count = 1
for l in f:
@@ -1289,6 +1314,18 @@
count += 1
print '</div>'
+def print_blob_highlighted(fname, sample_code=False):
+ code = open(realpath(fname), 'r').read()
+ if sample_code:
+ lexer = pygments.lexers.guess_lexer(code[:200],
+ encoding=config.repoencoding[0])
+ else:
+ lexer = pygments.lexers.guess_lexer_for_filename(fname, code[:200],
+ encoding=config.repoencoding[0])
+ formatter = pygments.formatters.HtmlFormatter(linenos=True,
+ cssclass='page_body')
+ print pygments.highlight(code, lexer, formatter)
+
def print_annotate(ann, style):
print '<div class="page_body">'
if isbinary(ann.fname):