From 50339493c69e9b1b11212dc645162af81bb9e6cf Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Sun, 30 Nov 2008 19:58:29 +0100 Subject: [PATCH] Add Sphinx.add_lexer(). --- CHANGES | 4 ++++ doc/ext/appapi.rst | 7 +++++++ sphinx/application.py | 6 ++++++ sphinx/highlighting.py | 1 + tests/test_highlighting.py | 37 +++++++++++++++++++++++++++++++++++++ 5 files changed, 55 insertions(+) create mode 100644 tests/test_highlighting.py diff --git a/CHANGES b/CHANGES index 5d9bc20ca..b45ce66c9 100644 --- a/CHANGES +++ b/CHANGES @@ -4,6 +4,10 @@ Release 0.6 (in development) New features added ------------------ +* Extension API: + + - Add Sphinx.add_lexer() to add custom Pygments lexers. + * Other changes: - Allow giving config overrides for single dict keys on the command diff --git a/doc/ext/appapi.rst b/doc/ext/appapi.rst index 355e42bd0..3dd5282b1 100644 --- a/doc/ext/appapi.rst +++ b/doc/ext/appapi.rst @@ -167,6 +167,13 @@ the following public API: :confval:`the docs for the config value `. .. versionadded:: 0.5 + +.. method:: Sphinx.add_lexer(alias, lexer) + + Use *lexer*, which must be an instance of a Pygments lexer class, to + highlight code blocks with the given language *alias*. + + .. versionadded:: 0.6 .. method:: Sphinx.connect(event, callback) diff --git a/sphinx/application.py b/sphinx/application.py index 6c644bbea..f7c57592a 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -297,6 +297,12 @@ class Sphinx(object): StandaloneHTMLBuilder.script_files.append( posixpath.join('_static', filename)) + def add_lexer(self, alias, lexer): + from sphinx.highlighting import lexers + if lexers is None: + return + lexers[alias] = lexer + class TemplateBridge(object): """ diff --git a/sphinx/highlighting.py b/sphinx/highlighting.py index 3017133a5..d85aac237 100644 --- a/sphinx/highlighting.py +++ b/sphinx/highlighting.py @@ -30,6 +30,7 @@ try: from pygments.token import Generic, Comment, Number except ImportError: pygments = None + lexers = None else: class SphinxStyle(Style): """ diff --git a/tests/test_highlighting.py b/tests/test_highlighting.py new file mode 100644 index 000000000..5c3539468 --- /dev/null +++ b/tests/test_highlighting.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +""" + test_highlighting + ~~~~~~~~~~~~~~~~~ + + Test the Pygments highlighting bridge. + + :copyright: 2008 by Georg Brandl. + :license: BSD. +""" + +from util import * + +from pygments.lexer import RegexLexer +from pygments.token import Text, Name + +from sphinx.highlighting import PygmentsBridge + + +class MyLexer(RegexLexer): + name = 'testlexer' + + tokens = { + 'root': [ + ('a', Name), + ('b', Text), + ], + } + + +@with_app() +def test_add_lexer(app): + app.add_lexer('test', MyLexer()) + + bridge = PygmentsBridge('html') + ret = bridge.highlight_block('ab', 'test') + assert 'ab' in ret