summaryrefslogtreecommitdiff
path: root/sphinx/directives/code.py
diff options
context:
space:
mode:
Diffstat (limited to 'sphinx/directives/code.py')
-rw-r--r--sphinx/directives/code.py76
1 files changed, 38 insertions, 38 deletions
diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py
index 30ded6dd4..c2acf8cca 100644
--- a/sphinx/directives/code.py
+++ b/sphinx/directives/code.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
sphinx.directives.code
~~~~~~~~~~~~~~~~~~~~~~
@@ -7,15 +6,13 @@
:license: BSD, see LICENSE for details.
"""
-import codecs
import sys
import warnings
from difflib import unified_diff
from docutils import nodes
from docutils.parsers.rst import directives
-from docutils.statemachine import ViewList
-from six import text_type
+from docutils.statemachine import StringList
from sphinx import addnodes
from sphinx.deprecation import RemovedInSphinx40Warning
@@ -63,11 +60,11 @@ class HighlightLang(Highlight):
warnings.warn('highlightlang directive is deprecated. '
'Please use highlight directive instead.',
RemovedInSphinx40Warning, stacklevel=2)
- return Highlight.run(self)
+ return super().run()
def dedent_lines(lines, dedent, location=None):
- # type: (List[unicode], int, Any) -> List[unicode]
+ # type: (List[str], int, Tuple[str, int]) -> List[str]
if not dedent:
return lines
@@ -85,22 +82,25 @@ def dedent_lines(lines, dedent, location=None):
def container_wrapper(directive, literal_node, caption):
- # type: (SphinxDirective, nodes.Node, unicode) -> nodes.container
+ # type: (SphinxDirective, nodes.Node, str) -> nodes.container
container_node = nodes.container('', literal_block=True,
classes=['literal-block-wrapper'])
parsed = nodes.Element()
- directive.state.nested_parse(ViewList([caption], source=''),
+ directive.state.nested_parse(StringList([caption], source=''),
directive.content_offset, parsed)
if isinstance(parsed[0], nodes.system_message):
msg = __('Invalid caption: %s' % parsed[0].astext())
raise ValueError(msg)
- caption_node = nodes.caption(parsed[0].rawsource, '',
- *parsed[0].children)
- caption_node.source = literal_node.source
- caption_node.line = literal_node.line
- container_node += caption_node
- container_node += literal_node
- return container_node
+ elif isinstance(parsed[0], nodes.Element):
+ caption_node = nodes.caption(parsed[0].rawsource, '',
+ *parsed[0].children)
+ caption_node.source = literal_node.source
+ caption_node.line = literal_node.line
+ container_node += caption_node
+ container_node += literal_node
+ return container_node
+ else:
+ raise RuntimeError # never reached
class CodeBlock(SphinxDirective):
@@ -126,7 +126,7 @@ class CodeBlock(SphinxDirective):
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
- code = u'\n'.join(self.content)
+ code = '\n'.join(self.content)
location = self.state_machine.get_source_and_line(self.lineno)
linespec = self.options.get('emphasize-lines')
@@ -141,7 +141,7 @@ class CodeBlock(SphinxDirective):
hl_lines = [x + 1 for x in hl_lines if x < nlines]
except ValueError as err:
- return [document.reporter.warning(str(err), line=self.lineno)]
+ return [document.reporter.warning(err, line=self.lineno)]
else:
hl_lines = None
@@ -151,7 +151,7 @@ class CodeBlock(SphinxDirective):
lines = dedent_lines(lines, self.options['dedent'], location=location)
code = '\n'.join(lines)
- literal = nodes.literal_block(code, code)
+ literal = nodes.literal_block(code, code) # type: nodes.Element
literal['language'] = self.arguments[0]
literal['linenos'] = 'linenos' in self.options or \
'lineno-start' in self.options
@@ -168,7 +168,7 @@ class CodeBlock(SphinxDirective):
try:
literal = container_wrapper(self, literal, caption)
except ValueError as exc:
- return [document.reporter.warning(text_type(exc), line=self.lineno)]
+ return [document.reporter.warning(exc, line=self.lineno)]
# literal will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
@@ -177,7 +177,7 @@ class CodeBlock(SphinxDirective):
return [literal]
-class LiteralIncludeReader(object):
+class LiteralIncludeReader:
INVALID_OPTIONS_PAIR = [
('lineno-match', 'lineno-start'),
('lineno-match', 'append'),
@@ -195,7 +195,7 @@ class LiteralIncludeReader(object):
]
def __init__(self, filename, options, config):
- # type: (unicode, Dict, Config) -> None
+ # type: (str, Dict, Config) -> None
self.filename = filename
self.options = options
self.encoding = options.get('encoding', config.source_encoding)
@@ -211,23 +211,23 @@ class LiteralIncludeReader(object):
(option1, option2))
def read_file(self, filename, location=None):
- # type: (unicode, Any) -> List[unicode]
+ # type: (str, Tuple[str, int]) -> List[str]
try:
- with codecs.open(filename, 'r', self.encoding, errors='strict') as f: # type: ignore # NOQA
- text = f.read() # type: unicode
+ with open(filename, encoding=self.encoding, errors='strict') as f:
+ text = f.read()
if 'tab-width' in self.options:
text = text.expandtabs(self.options['tab-width'])
return text.splitlines(True)
- except (IOError, OSError):
- raise IOError(__('Include file %r not found or reading it failed') % filename)
+ except OSError:
+ raise OSError(__('Include file %r not found or reading it failed') % filename)
except UnicodeError:
raise UnicodeError(__('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option') %
(self.encoding, filename))
def read(self, location=None):
- # type: (Any) -> Tuple[unicode, int]
+ # type: (Tuple[str, int]) -> Tuple[str, int]
if 'diff' in self.options:
lines = self.show_diff()
else:
@@ -245,7 +245,7 @@ class LiteralIncludeReader(object):
return ''.join(lines), len(lines)
def show_diff(self, location=None):
- # type: (Any) -> List[unicode]
+ # type: (Tuple[str, int]) -> List[str]
new_lines = self.read_file(self.filename)
old_filename = self.options.get('diff')
old_lines = self.read_file(old_filename)
@@ -253,7 +253,7 @@ class LiteralIncludeReader(object):
return list(diff)
def pyobject_filter(self, lines, location=None):
- # type: (List[unicode], Any) -> List[unicode]
+ # type: (List[str], Tuple[str, int]) -> List[str]
pyobject = self.options.get('pyobject')
if pyobject:
from sphinx.pycode import ModuleAnalyzer
@@ -272,7 +272,7 @@ class LiteralIncludeReader(object):
return lines
def lines_filter(self, lines, location=None):
- # type: (List[unicode], Any) -> List[unicode]
+ # type: (List[str], Tuple[str, int]) -> List[str]
linespec = self.options.get('lines')
if linespec:
linelist = parselinenos(linespec, len(lines))
@@ -297,7 +297,7 @@ class LiteralIncludeReader(object):
return lines
def start_filter(self, lines, location=None):
- # type: (List[unicode], Any) -> List[unicode]
+ # type: (List[str], Tuple[str, int]) -> List[str]
if 'start-at' in self.options:
start = self.options.get('start-at')
inclusive = False
@@ -329,7 +329,7 @@ class LiteralIncludeReader(object):
return lines
def end_filter(self, lines, location=None):
- # type: (List[unicode], Any) -> List[unicode]
+ # type: (List[str], Tuple[str, int]) -> List[str]
if 'end-at' in self.options:
end = self.options.get('end-at')
inclusive = True
@@ -357,7 +357,7 @@ class LiteralIncludeReader(object):
return lines
def prepend_filter(self, lines, location=None):
- # type: (List[unicode], Any) -> List[unicode]
+ # type: (List[str], Tuple[str, int]) -> List[str]
prepend = self.options.get('prepend')
if prepend:
lines.insert(0, prepend + '\n')
@@ -365,7 +365,7 @@ class LiteralIncludeReader(object):
return lines
def append_filter(self, lines, location=None):
- # type: (List[unicode], Any) -> List[unicode]
+ # type: (List[str], Tuple[str, int]) -> List[str]
append = self.options.get('append')
if append:
lines.append(append + '\n')
@@ -373,7 +373,7 @@ class LiteralIncludeReader(object):
return lines
def dedent_filter(self, lines, location=None):
- # type: (List[unicode], Any) -> List[unicode]
+ # type: (List[str], Tuple[str, int]) -> List[str]
if 'dedent' in self.options:
return dedent_lines(lines, self.options.get('dedent'), location=location)
else:
@@ -433,7 +433,7 @@ class LiteralInclude(SphinxDirective):
reader = LiteralIncludeReader(filename, self.options, self.config)
text, lines = reader.read(location=location)
- retnode = nodes.literal_block(text, text, source=filename)
+ retnode = nodes.literal_block(text, text, source=filename) # type: nodes.Element
set_source_info(self, retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
@@ -463,11 +463,11 @@ class LiteralInclude(SphinxDirective):
return [retnode]
except Exception as exc:
- return [document.reporter.warning(text_type(exc), line=self.lineno)]
+ return [document.reporter.warning(exc, line=self.lineno)]
def setup(app):
- # type: (Sphinx) -> Dict[unicode, Any]
+ # type: (Sphinx) -> Dict[str, Any]
directives.register_directive('highlight', Highlight)
directives.register_directive('highlightlang', HighlightLang)
directives.register_directive('code-block', CodeBlock)