1
0
mirror of https://github.com/gryf/vimblogger_ft.git synced 2025-12-18 03:50:21 +01:00

Pygments sourcecode directive improvements

This commit is contained in:
2010-12-25 15:19:08 +01:00
parent ceb2c3d308
commit 55e51cbe6f
7 changed files with 413 additions and 57 deletions

View File

@@ -17,6 +17,32 @@ try:
from pygments.lexers import get_lexer_by_name, TextLexer
from pygments.formatters import HtmlFormatter
def register(cssclass=None):
print "register"
if cssclass:
Pygments.cssclass = cssclass
directives.register_directive('sourcecode', Pygments)
def _positive_int_or_1(argument):
"""
Converts the argument into an integer. Returns positive integer. In
case of integers smaller than 1, returns 1. In case of None, returns
1.
"""
if argument is None:
return 1
retval = 1
try:
retval = int(argument)
except ValueError:
pass
if retval < 1:
return 1
return retval
class Pygments(Directive):
"""
Source code syntax highlighting.
@@ -24,7 +50,11 @@ try:
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'linenos': _positive_int_or_1,
'cssclass': directives.unchanged_required}
has_content = True
cssclass = None
def run(self):
self.assert_has_content()
@@ -33,12 +63,26 @@ try:
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
# take an arbitrary option if more than one is given
formatter = HtmlFormatter(noclasses=True)
kwargs = {'full': False,
'noclasses': False}
if self.options and 'linenos' in self.options:
kwargs['linenos'] = 'inline'
kwargs['linenostart'] = self.options['linenos']
if Pygments.cssclass:
kwargs['cssclass'] = Pygments.cssclass
if self.options and 'cssclass' in self.options:
kwargs['cssclass'] = self.options['cssclass']
formatter = HtmlFormatter(**kwargs)
parsed = highlight(u'\n'.join(self.content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]
directives.register_directive('sourcecode', Pygments)
register()
except ImportError:
pass