From f1765c25763743edb027abe2ed504ef4f8a48775 Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Fri, 1 Jan 2016 01:31:59 +0900 Subject: [PATCH] Add sphinx.parsers.Parser class; a base class for new parsers The class inherits ``docutils.parsers.Parser`` and implements ``set_application()`` in addition. It enables subclasses to read configurations, to access environments and to logging. --- sphinx/environment.py | 9 ++++++--- sphinx/parsers.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 sphinx/parsers.py diff --git a/sphinx/environment.py b/sphinx/environment.py index 58463cae8..60287031c 100644 --- a/sphinx/environment.py +++ b/sphinx/environment.py @@ -105,13 +105,16 @@ class SphinxStandaloneReader(standalone.Reader): DefaultSubstitutions, MoveModuleTargets, HandleCodeBlocks, AutoNumbering, SortIds, RemoveTranslatableInline] - def __init__(self, parsers={}, *args, **kwargs): + def __init__(self, app, parsers={}, *args, **kwargs): standalone.Reader.__init__(self, *args, **kwargs) self.parser_map = {} for suffix, parser_class in parsers.items(): if isinstance(parser_class, string_types): parser_class = import_object(parser_class, 'source parser') - self.parser_map[suffix] = parser_class() + parser = parser_class() + if hasattr(parser, 'set_application'): + parser.set_application(app) + self.parser_map[suffix] = parser def read(self, source, parser, settings): self.source = source @@ -776,7 +779,7 @@ class BuildEnvironment: codecs.register_error('sphinx', self.warn_and_replace) # publish manually - reader = SphinxStandaloneReader(parsers=self.config.source_parsers) + reader = SphinxStandaloneReader(self.app, parsers=self.config.source_parsers) pub = Publisher(reader=reader, writer=SphinxDummyWriter(), destination_class=NullOutput) diff --git a/sphinx/parsers.py b/sphinx/parsers.py new file mode 100644 index 000000000..b7ca89aa5 --- /dev/null +++ b/sphinx/parsers.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +""" + sphinx.parsers + ~~~~~~~~~~~~~~ + + A Base class for additional parsers. + + :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import docutils.parsers + + +class Parser(docutils.parsers.Parser): + """ + A base class of parsers. + """ + + def set_application(self, app): + """set_application will be called from Sphinx to set app and other instance variables + + :param sphinx.application.Sphinx app: Sphinx application object + """ + self.app = app + self.config = app.config + self.env = app.env + self.warn = app.warn + self.info = app.info