📜 ⬆️ ⬇️

Source Code Highlighting

It so happened that it was decided to highlight code in Habré using 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 for Habra, as you know, you need a special approach, and htr does not skip the html output. In this regard, I wrote a small class for the pygments, which corrects this annoying misunderstanding. You can use the web version at paste.ly .

# -*- coding: utf-8 -*-

from pygments.formatter import Formatter

class HabrFormatter (Formatter):

_html_escape_table = (( '&' , '&' ),
( '<' , '&lt;' ),
( '>' , '&gt;' ),
( '"' , '&quot;' ),
( "'" , '&#39;' ),
( ' ' , '&nbsp;' ),
( ' \t ' , '&nbsp;' *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( '<blockquote><code>' )
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 += '<font color="# %s ">' % style[ 'color' ]
end = '</font>' + end
if style[ 'bold' ]:
start += '<strong>'
end = '</strong>' + end
if style[ 'italic' ]:
start += '<em>'
end = '</em>' + end
if style[ 'underline' ]:
start += '<u>'
end = '</u>' + end
if last_start != start:
outfile . write(last_end)
outfile . write(start)
outfile . write(value)
last_start, last_end = start, end
outfile . write( '</code></blockquote>' )

The only trouble is that it is impossible to change the background color on the habr, which makes not all pygments color styles suitable for use.

')

Source: https://habr.com/ru/post/75349/


All Articles