
Source code highlighting
It so happened that it is customary to highlight code on the hub with the help of Source Code Highlighter. The list of supported languages is not impressive, and I did not find the opportunity to choose a color scheme. There is a pygments library that understands most of the languages used, can output html, pictures, latex and more. But, as you know, a special approach is needed for the habra, and the html does not skip the html output of pygments. In this regard, I wrote a small class for pygments that corrects this annoying misunderstanding. You can use the web version at paste.ly .
The only trouble is that it’s impossible to change the background color on the hub, which doesn’t make all pygment color styles usable.
# -*- coding: utf-8 -*-
from pygments.formatter import Formatter
class HabrFormatter(Formatter):
_html_escape_table = (('&', '&'),
('<', '<'),
('>', '>'),
('"', '"'),
("'", '''),
(' ', ' '),
('\t', ' '*4))
def escape_html(self, value):
return reduce(lambda value, rep: value.replace(*rep),
self._html_escape_table, value)
def format_unencoded(self, tokensource, outfile):
outfile.write('')
last_start = last_end = ''
for token_type, value in tokensource:
value = self.escape_html(value)
style = self.style.style_for_token(token_type)
start = end = ''
if style['color']:
start += '%s">' % style['color']
end = '' + end
if style['bold']:
start += ''
end = '' + end
if style['italic']:
start += ''
end = '' + end
if style['underline']:
start += ''
end = '' + end
if last_start != start:
outfile.write(last_end)
outfile.write(start)
outfile.write(value)
last_start, last_end = start, end
outfile.write('
')
The only trouble is that it’s impossible to change the background color on the hub, which doesn’t make all pygment color styles usable.