summaryrefslogtreecommitdiff
path: root/sphinx/highlighting.py
diff options
context:
space:
mode:
Diffstat (limited to 'sphinx/highlighting.py')
-rw-r--r--sphinx/highlighting.py42
1 files changed, 27 insertions, 15 deletions
diff --git a/sphinx/highlighting.py b/sphinx/highlighting.py
index c194738f8..995ca65d3 100644
--- a/sphinx/highlighting.py
+++ b/sphinx/highlighting.py
@@ -27,6 +27,7 @@ if False:
# For type annotation
from typing import Any, Dict # NOQA
from pygments.formatter import Formatter # NOQA
+ from pygments.style import Style # NOQA
logger = logging.getLogger(__name__)
@@ -64,16 +65,8 @@ class PygmentsBridge:
def __init__(self, dest='html', stylename='sphinx'):
# type: (str, str) -> None
self.dest = dest
- if stylename is None or stylename == 'sphinx':
- style = SphinxStyle
- elif stylename == 'none':
- style = NoneStyle
- elif '.' in stylename:
- module, stylename = stylename.rsplit('.', 1)
- style = getattr(__import__(module, None, None, ['__name__']),
- stylename)
- else:
- style = get_style_by_name(stylename)
+
+ style = self.get_style(stylename)
self.formatter_args = {'style': style} # type: Dict[str, Any]
if dest == 'html':
self.formatter = self.html_formatter
@@ -81,16 +74,25 @@ class PygmentsBridge:
self.formatter = self.latex_formatter
self.formatter_args['commandprefix'] = 'PYG'
+ def get_style(self, stylename):
+ # type: (str) -> Style
+ if stylename is None or stylename == 'sphinx':
+ return SphinxStyle
+ elif stylename == 'none':
+ return NoneStyle
+ elif '.' in stylename:
+ module, stylename = stylename.rsplit('.', 1)
+ return getattr(__import__(module, None, None, ['__name__']), stylename)
+ else:
+ return get_style_by_name(stylename)
+
def get_formatter(self, **kwargs):
# type: (Any) -> Formatter
kwargs.update(self.formatter_args)
return self.formatter(**kwargs)
- def highlight_block(self, source, lang, opts=None, location=None, force=False, **kwargs):
- # type: (str, str, Any, Any, bool, Any) -> str
- if not isinstance(source, str):
- source = source.decode()
-
+ def get_lexer(self, source, lang, opts=None, location=None):
+ # type: (str, str, Any, Any) -> Lexer
# find out which lexer to use
if lang in ('py', 'python'):
if source.startswith('>>>'):
@@ -121,6 +123,15 @@ class PygmentsBridge:
else:
lexer.add_filter('raiseonerror')
+ return lexer
+
+ def highlight_block(self, source, lang, opts=None, location=None, force=False, **kwargs):
+ # type: (str, str, Any, Any, bool, Any) -> str
+ if not isinstance(source, str):
+ source = source.decode()
+
+ lexer = self.get_lexer(source, lang, opts, location)
+
# highlight via Pygments
formatter = self.get_formatter(**kwargs)
try:
@@ -136,6 +147,7 @@ class PygmentsBridge:
type='misc', subtype='highlighting_failure',
location=location)
hlsource = highlight(source, lexers['none'], formatter)
+
if self.dest == 'html':
return hlsource
else: