added loader for pygments formatter and stub for the testcase

This commit is contained in:
Joey Curtin 2013-03-28 15:40:46 -04:00
commit 498e44f36c
5 changed files with 49 additions and 9 deletions

View file

@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from pelican.settings import conf as pelican_settings
from pelican.utils.importlib import import_class
from docutils import nodes, utils
from docutils.parsers.rst import directives, roles, Directive
from pygments.formatters import HtmlFormatter
@ -9,11 +11,7 @@ from pygments.lexers import get_lexer_by_name, TextLexer
import re
INLINESTYLES = False
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES, linenos=True)
VARIANTS = {
'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}
VARIANTS = {}
class Pygments(Directive):
""" Source code syntax hightlighting.
@ -32,8 +30,10 @@ class Pygments(Directive):
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
# take an arbitrary option if more than one is given
formatter = self.options and VARIANTS[self.options.keys()[0]] \
or DEFAULT
formatter = import_class(pelican_settings.PYGMENTS_FORMATTER)
formatter = formatter(noclasses=INLINESTYLES,
linenos=pelican_settings.PYGMENTS_FORMATTER_SHOW_LINENO)
parsed = highlight('\n'.join(self.content), lexer, formatter)
return [nodes.raw('', parsed, format='html')]

View file

@ -91,7 +91,12 @@ _DEFAULT_CONFIG = {'PATH': os.curdir,
'SUMMARY_MAX_LENGTH': 50,
'PLUGINS': [],
'TEMPLATE_PAGES': {},
'IGNORE_FILES': []
'IGNORE_FILES': [],
'PYGMENTS_FORMATTER_SHOW_LINENO': False,
# This will allow users to import formatters form
# outside the pelican source.
# pelicanconf.py : PYGMENTS_FORMATTER = "my.custom.formatter"
'PYGMENTS_FORMATTER': 'pygments.formatters.HtmlFormatter'
}

View file

@ -26,3 +26,4 @@ class TestImportLib(unittest.TestCase):
for key in _DEFAULT_CONFIG.keys():
assert hasattr(conf, key)

View file

@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import os
import unittest
import sys
import locale
from pelican.utils.importlib import import_module
from pelican.settings import read_settings
from pelican.settings.base import _DEFAULT_CONFIG
# runtest with:
# cd ~/pelican/pelican/tests && python -m unittest discover . 'test_pygments*' && cd -
class TestPygments(unittest.TestCase):
def test_formatter(self):
pass

View file

@ -36,4 +36,21 @@ def import_module(name, package=None):
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name)
return sys.modules[name]
return sys.modules[name]
def import_class(name, package=None):
"""
Imports just the class and not the module.
"""
if package is None:
package = '.'.join(name.split('.')[:-1])
name = ''.join(name.split('.')[-1:])
if package == '':
package = None
module = import_module(package)
if not hasattr(module, name):
raise AttributeError("%s is not part of %s" % (name, package))
return getattr(module, name)