summaryrefslogtreecommitdiff
path: root/sphinx
diff options
context:
space:
mode:
authorTakeshi KOMIYA <i.tkomiya@gmail.com>2017-01-14 00:26:03 +0900
committerGitHub <noreply@github.com>2017-01-14 00:26:03 +0900
commitc03da8fdf4d785d93bd9b52fb9eb5ea89bd7ca99 (patch)
tree12a2f24bffef977444b25f14f2b643c242b098e4 /sphinx
parented6742fe2a19260857f23a70059d2b7838bf8bd3 (diff)
parent234379be9ee9479c407c7ccc644ecf70fa7078ba (diff)
downloadsphinx-git-c03da8fdf4d785d93bd9b52fb9eb5ea89bd7ca99.tar.gz
Merge branch 'stable' into 3256_update_release_script
Diffstat (limited to 'sphinx')
-rw-r--r--sphinx/__init__.py2
-rw-r--r--sphinx/apidoc.py4
-rw-r--r--sphinx/application.py8
-rw-r--r--sphinx/builders/__init__.py2
-rw-r--r--sphinx/builders/changes.py2
-rw-r--r--sphinx/builders/html.py6
-rw-r--r--sphinx/builders/htmlhelp.py10
-rw-r--r--sphinx/builders/latex.py6
-rw-r--r--sphinx/builders/linkcheck.py4
-rw-r--r--sphinx/builders/qthelp.py16
-rw-r--r--sphinx/builders/texinfo.py4
-rw-r--r--sphinx/builders/websupport.py2
-rw-r--r--sphinx/directives/code.py6
-rw-r--r--sphinx/directives/other.py4
-rw-r--r--sphinx/domains/c.py6
-rw-r--r--sphinx/domains/cpp.py4
-rw-r--r--sphinx/domains/javascript.py2
-rw-r--r--sphinx/domains/python.py2
-rw-r--r--sphinx/domains/std.py10
-rw-r--r--sphinx/environment/__init__.py2
-rw-r--r--sphinx/environment/managers/toctree.py8
-rw-r--r--sphinx/errors.py9
-rw-r--r--sphinx/ext/autosummary/__init__.py12
-rw-r--r--sphinx/ext/doctest.py4
-rw-r--r--sphinx/ext/imgmath.py2
-rw-r--r--sphinx/ext/intersphinx.py18
-rw-r--r--sphinx/ext/pngmath.py2
-rw-r--r--sphinx/ext/todo.py2
-rw-r--r--sphinx/make_mode.py2
-rw-r--r--sphinx/pycode/__init__.py2
-rw-r--r--sphinx/pycode/nodes.py4
-rw-r--r--sphinx/quickstart.py8
-rw-r--r--sphinx/roles.py4
-rw-r--r--sphinx/texinputs/sphinx.sty14
-rw-r--r--sphinx/transforms/i18n.py4
-rw-r--r--sphinx/util/__init__.py12
-rw-r--r--sphinx/util/console.py4
-rw-r--r--sphinx/util/docutils.py2
-rw-r--r--sphinx/util/fileutil.py4
-rw-r--r--sphinx/util/i18n.py17
-rw-r--r--sphinx/util/jsdump.py4
-rw-r--r--sphinx/util/nodes.py8
-rw-r--r--sphinx/util/osutil.py4
-rw-r--r--sphinx/util/parallel.py7
-rw-r--r--sphinx/util/requests.py7
-rw-r--r--sphinx/util/stemmer.py16
-rw-r--r--sphinx/websupport/search/__init__.py2
-rw-r--r--sphinx/writers/html.py4
-rw-r--r--sphinx/writers/latex.py6
-rw-r--r--sphinx/writers/manpage.py2
-rw-r--r--sphinx/writers/texinfo.py12
-rw-r--r--sphinx/writers/text.py12
52 files changed, 170 insertions, 150 deletions
diff --git a/sphinx/__init__.py b/sphinx/__init__.py
index e5768dcbe..2cd3a57de 100644
--- a/sphinx/__init__.py
+++ b/sphinx/__init__.py
@@ -30,7 +30,7 @@ if 'PYTHONWARNINGS' not in os.environ:
warnings.filterwarnings('ignore', "'U' mode is deprecated",
DeprecationWarning, module='docutils.io')
-__version__ = '1.5.2+'
+__version__ = '1.5.2+'
__released__ = '1.5.2' # used when Sphinx builds its own docs
# version info for better programmatic use
diff --git a/sphinx/apidoc.py b/sphinx/apidoc.py
index d4793ff4d..19a711370 100644
--- a/sphinx/apidoc.py
+++ b/sphinx/apidoc.py
@@ -368,8 +368,8 @@ Note: By default this script will not overwrite already created files.""")
text += ' %s\n' % module
d = dict(
path = opts.destdir,
- sep = False,
- dot = '_',
+ sep = False,
+ dot = '_',
project = opts.header,
author = opts.author or 'Author',
version = opts.version or '',
diff --git a/sphinx/application.py b/sphinx/application.py
index f3bc381bc..f38f6be47 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -258,7 +258,7 @@ class Sphinx(object):
for catinfo in find_catalog_source_files(
user_locale_dirs, self.config.language, domains=['sphinx'],
charset=self.config.source_encoding):
- catinfo.write_mo(self.config.language)
+ catinfo.write_mo(self.config.language, self.warn)
locale_dirs = [None, path.join(package_dir, 'locale')] + user_locale_dirs
else:
locale_dirs = []
@@ -484,7 +484,7 @@ class Sphinx(object):
summary = bold(summary)
for item in iterable:
l += 1
- s = '%s[%3d%%] %s' % (summary, 100*l/length,
+ s = '%s[%3d%%] %s' % (summary, 100 * l / length,
colorfunc(stringify_func(item)))
if self.verbosity:
s += '\n'
@@ -660,9 +660,9 @@ class Sphinx(object):
else:
# ignore invalid keys for compatibility
continue
- setattr(translator, 'visit_'+node.__name__, visit)
+ setattr(translator, 'visit_' + node.__name__, visit)
if depart:
- setattr(translator, 'depart_'+node.__name__, depart)
+ setattr(translator, 'depart_' + node.__name__, depart)
def add_enumerable_node(self, node, figtype, title_getter=None, **kwds):
self.enumerable_nodes[node] = (figtype, title_getter)
diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py
index fe0c9c665..79713f392 100644
--- a/sphinx/builders/__init__.py
+++ b/sphinx/builders/__init__.py
@@ -167,7 +167,7 @@ class Builder(object):
for catalog in self.app.status_iterator(
catalogs, 'writing output... ', darkgreen, len(catalogs),
cat2relpath):
- catalog.write_mo(self.config.language)
+ catalog.write_mo(self.config.language, self.warn)
def compile_all_catalogs(self):
catalogs = i18n.find_catalog_source_files(
diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py
index a756742c9..eadbad09a 100644
--- a/sphinx/builders/changes.py
+++ b/sphinx/builders/changes.py
@@ -130,7 +130,7 @@ class ChangesBuilder(Builder):
targetfn = path.join(self.outdir, 'rst', os_path(docname)) + '.html'
ensuredir(path.dirname(targetfn))
with codecs.open(targetfn, 'w', 'utf-8') as f:
- text = ''.join(hl(i+1, line) for (i, line) in enumerate(lines))
+ text = ''.join(hl(i + 1, line) for (i, line) in enumerate(lines))
ctx = {
'filename': self.env.doc2path(docname, None),
'text': text
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 9160080c8..b9ab44676 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -498,7 +498,7 @@ class StandaloneHTMLBuilder(Builder):
# additional pages from conf.py
for pagename, template in self.config.html_additional_pages.items():
- self.info(' '+pagename, nonl=1)
+ self.info(' ' + pagename, nonl=1)
self.handle_page(pagename, {}, template)
# the search page
@@ -953,7 +953,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder):
hashindex = refuri.find('#')
if hashindex < 0:
continue
- hashindex = refuri.find('#', hashindex+1)
+ hashindex = refuri.find('#', hashindex + 1)
if hashindex >= 0:
refnode['refuri'] = fname + refuri[hashindex:]
@@ -1059,7 +1059,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder):
# additional pages from conf.py
for pagename, template in self.config.html_additional_pages.items():
- self.info(' '+pagename, nonl=1)
+ self.info(' ' + pagename, nonl=1)
self.handle_page(pagename, {}, template)
if self.config.html_use_opensearch:
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index 79268ab74..11c614b5a 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -208,12 +208,12 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
def build_hhx(self, outdir, outname):
self.info('dumping stopword list...')
- with self.open_file(outdir, outname+'.stp') as f:
+ with self.open_file(outdir, outname + '.stp') as f:
for word in sorted(stopwords):
print(word, file=f)
self.info('writing project file...')
- with self.open_file(outdir, outname+'.hhp') as f:
+ with self.open_file(outdir, outname + '.hhp') as f:
f.write(project_template % {
'outname': outname,
'title': self.config.html_title,
@@ -234,7 +234,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
file=f)
self.info('writing TOC file...')
- with self.open_file(outdir, outname+'.hhc') as f:
+ with self.open_file(outdir, outname + '.hhc') as f:
f.write(contents_header)
# special books
f.write('<LI> ' + object_sitemap % (self.config.html_short_title,
@@ -259,7 +259,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
if ullevel != 0:
f.write('<UL>\n')
for subnode in node:
- write_toc(subnode, ullevel+1)
+ write_toc(subnode, ullevel + 1)
if ullevel != 0:
f.write('</UL>\n')
elif isinstance(node, addnodes.compact_paragraph):
@@ -275,7 +275,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
self.info('writing index file...')
index = self.env.create_index(self)
- with self.open_file(outdir, outname+'.hhk') as f:
+ with self.open_file(outdir, outname + '.hhk') as f:
f.write('<UL>\n')
def write_index(title, refs, subitems):
diff --git a/sphinx/builders/latex.py b/sphinx/builders/latex.py
index bfd002be5..82ca5521e 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -74,7 +74,7 @@ class LaTeXBuilder(Builder):
'document %s' % docname)
continue
self.document_data.append(entry)
- if docname.endswith(SEP+'index'):
+ if docname.endswith(SEP + 'index'):
docname = docname[:-5]
self.titles.append((docname, entry[2]))
@@ -188,7 +188,7 @@ class LaTeXBuilder(Builder):
if self.images:
self.info(bold('copying images...'), nonl=1)
for src, dest in iteritems(self.images):
- self.info(' '+src, nonl=1)
+ self.info(' ' + src, nonl=1)
copy_asset_file(path.join(self.srcdir, src),
path.join(self.outdir, dest))
self.info()
@@ -206,7 +206,7 @@ class LaTeXBuilder(Builder):
if self.config.latex_additional_files:
self.info(bold('copying additional files...'), nonl=1)
for filename in self.config.latex_additional_files:
- self.info(' '+filename, nonl=1)
+ self.info(' ' + filename, nonl=1)
copy_asset_file(path.join(self.confdir, filename), self.outdir)
self.info()
diff --git a/sphinx/builders/linkcheck.py b/sphinx/builders/linkcheck.py
index 3ca13d023..3ca00a3a2 100644
--- a/sphinx/builders/linkcheck.py
+++ b/sphinx/builders/linkcheck.py
@@ -225,7 +225,7 @@ class CheckExternalLinksBuilder(Builder):
self.info(darkgray('-local- ') + uri)
self.write_entry('local', docname, lineno, uri)
elif status == 'working':
- self.info(darkgreen('ok ') + uri + info)
+ self.info(darkgreen('ok ') + uri + info)
elif status == 'broken':
self.write_entry('broken', docname, lineno, uri + ': ' + info)
if self.app.quiet or self.app.warningiserror:
@@ -243,7 +243,7 @@ class CheckExternalLinksBuilder(Builder):
}[code]
self.write_entry('redirected ' + text, docname, lineno,
uri + ' to ' + info)
- self.info(color('redirect ') + uri + color(' - ' + text + ' to ' + info))
+ self.info(color('redirect ') + uri + color(' - ' + text + ' to ' + info))
def get_target_uri(self, docname, typ=None):
return ''
diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py
index 23bc24ce8..72fee656a 100644
--- a/sphinx/builders/qthelp.py
+++ b/sphinx/builders/qthelp.py
@@ -89,7 +89,7 @@ project_template = u'''\
'''
section_template = '<section title="%(title)s" ref="%(ref)s"/>'
-file_template = ' '*12 + '<file>%(filename)s</file>'
+file_template = ' ' * 12 + '<file>%(filename)s</file>'
class QtHelpBuilder(StandaloneHTMLBuilder):
@@ -190,7 +190,7 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
nspace = nspace.lower()
# write the project file
- with codecs.open(path.join(outdir, outname+'.qhp'), 'w', 'utf-8') as f:
+ with codecs.open(path.join(outdir, outname + '.qhp'), 'w', 'utf-8') as f:
f.write(project_template % {
'outname': htmlescape(outname),
'title': htmlescape(self.config.html_title),
@@ -207,7 +207,7 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
startpage = 'qthelp://' + posixpath.join(nspace, 'doc', 'index.html')
self.info('writing collection project file...')
- with codecs.open(path.join(outdir, outname+'.qhcp'), 'w', 'utf-8') as f:
+ with codecs.open(path.join(outdir, outname + '.qhcp'), 'w', 'utf-8') as f:
f.write(collection_template % {
'outname': htmlescape(outname),
'title': htmlescape(self.config.html_short_title),
@@ -236,10 +236,10 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
title = htmlescape(refnode.astext()).replace('"', '&quot;')
item = '<section title="%(title)s" ref="%(ref)s">' % \
{'title': title, 'ref': link}
- parts.append(' '*4*indentlevel + item)
+ parts.append(' ' * 4 * indentlevel + item)
for subnode in node.children[1]:
- parts.extend(self.write_toc(subnode, indentlevel+1))
- parts.append(' '*4*indentlevel + '</section>')
+ parts.extend(self.write_toc(subnode, indentlevel + 1))
+ parts.append(' ' * 4 * indentlevel + '</section>')
elif isinstance(node, nodes.list_item):
for subnode in node:
parts.extend(self.write_toc(subnode, indentlevel))
@@ -272,10 +272,10 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
id = None
if id:
- item = ' '*12 + '<keyword name="%s" id="%s" ref="%s"/>' % (
+ item = ' ' * 12 + '<keyword name="%s" id="%s" ref="%s"/>' % (
name, id, ref[1])
else:
- item = ' '*12 + '<keyword name="%s" ref="%s"/>' % (name, ref[1])
+ item = ' ' * 12 + '<keyword name="%s" ref="%s"/>' % (name, ref[1])
item.encode('ascii', 'xmlcharrefreplace')
return item
diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py
index cdba3df55..6ef97f75e 100644
--- a/sphinx/builders/texinfo.py
+++ b/sphinx/builders/texinfo.py
@@ -122,7 +122,7 @@ class TexinfoBuilder(Builder):
'document %s' % docname)
continue
self.document_data.append(entry)
- if docname.endswith(SEP+'index'):
+ if docname.endswith(SEP + 'index'):
docname = docname[:-5]
self.titles.append((docname, entry[2]))
@@ -210,7 +210,7 @@ class TexinfoBuilder(Builder):
if self.images:
self.info(bold('copying images...'), nonl=1)
for src, dest in iteritems(self.images):
- self.info(' '+src, nonl=1)
+ self.info(' ' + src, nonl=1)
copyfile(path.join(self.srcdir, src),
path.join(self.outdir, dest))
self.info()
diff --git a/sphinx/builders/websupport.py b/sphinx/builders/websupport.py
index 1154b3419..2ed37a697 100644
--- a/sphinx/builders/websupport.py
+++ b/sphinx/builders/websupport.py
@@ -141,7 +141,7 @@ class WebSupportBuilder(PickleHTMLBuilder):
# "show source" link
if ctx.get('sourcename'):
source_name = path.join(self.staticdir,
- '_sources', os_path(ctx['sourcename']))
+ '_sources', os_path(ctx['sourcename']))
ensuredir(path.dirname(source_name))
copyfile(self.env.doc2path(pagename), source_name)
diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py
index 519a32577..e0c1b682e 100644
--- a/sphinx/directives/code.py
+++ b/sphinx/directives/code.py
@@ -107,7 +107,7 @@ class CodeBlock(Directive):
if linespec:
try:
nlines = len(self.content)
- hl_lines = [x+1 for x in parselinenos(linespec, nlines)]
+ hl_lines = [x + 1 for x in parselinenos(linespec, nlines)]
except ValueError as err:
document = self.state.document
return [document.reporter.warning(str(err), line=self.lineno)]
@@ -266,7 +266,7 @@ class LiteralInclude(Directive):
'Object named %r not found in include file %r' %
(objectname, filename), line=self.lineno)]
else:
- lines = lines[tags[objectname][1]-1: tags[objectname][2]-1]
+ lines = lines[tags[objectname][1] - 1: tags[objectname][2] - 1]
if 'lineno-match' in self.options:
linenostart = tags[objectname][1]
@@ -298,7 +298,7 @@ class LiteralInclude(Directive):
linespec = self.options.get('emphasize-lines')
if linespec:
try:
- hl_lines = [x+1 for x in parselinenos(linespec, len(lines))]
+ hl_lines = [x + 1 for x in parselinenos(linespec, len(lines))]
except ValueError as err:
return [document.reporter.warning(str(err), line=self.lineno)]
else:
diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py
index b6d9f8129..a08e891d5 100644
--- a/sphinx/directives/other.py
+++ b/sphinx/directives/other.py
@@ -204,7 +204,7 @@ class VersionChange(Directive):
text = versionlabels[self.name] % self.arguments[0]
if len(self.arguments) == 2:
inodes, messages = self.state.inline_text(self.arguments[1],
- self.lineno+1)
+ self.lineno + 1)
para = nodes.paragraph(self.arguments[1], '', *inodes, translatable=False)
set_source_info(self, para)
node.append(para)
@@ -325,7 +325,7 @@ class HList(Directive):
index = 0
newnode = addnodes.hlist()
for column in range(ncolumns):
- endindex = index + (column < nmore and (npercol+1) or npercol)
+ endindex = index + (column < nmore and (npercol + 1) or npercol)
col = addnodes.hlistcol()
col += nodes.bullet_list()
col[0] += fulllist.children[index:endindex]
diff --git a/sphinx/domains/c.py b/sphinx/domains/c.py
index a50af9ae6..c71fef4b3 100644
--- a/sphinx/domains/c.py
+++ b/sphinx/domains/c.py
@@ -77,7 +77,7 @@ class CObject(ObjectDescription):
# add cross-ref nodes for all words
for part in [_f for _f in wsplit_re.split(ctype) if _f]:
tnode = nodes.Text(part, part)
- if part[0] in string.ascii_letters+'_' and \
+ if part[0] in string.ascii_letters + '_' and \
part not in self.stopwords:
pnode = addnodes.pending_xref(
'', refdomain='c', reftype='type', reftarget=part,
@@ -162,7 +162,7 @@ class CObject(ObjectDescription):
ctype, argname = arg.rsplit(' ', 1)
self._parse_type(param, ctype)
# separate by non-breaking space in the output
- param += nodes.emphasis(' '+argname, u'\xa0'+argname)
+ param += nodes.emphasis(' ' + argname, u'\xa0' + argname)
except ValueError:
# no argument name given, only the type
self._parse_type(param, arg)
@@ -230,7 +230,7 @@ class CXRefRole(XRefRole):
title = title[1:]
dot = title.rfind('.')
if dot != -1:
- title = title[dot+1:]
+ title = title[dot + 1:]
return title, target
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index 98e584546..9408757eb 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -2885,14 +2885,14 @@ class Symbol(object):
assert False # should have returned in the loop
def to_string(self, indent):
- res = ['\t'*indent]
+ res = ['\t' * indent]
if not self.parent:
res.append('::')
else:
if self.templateParams:
res.append(text_type(self.templateParams))
res.append('\n')
- res.append('\t'*indent)
+ res.append('\t' * indent)
if self.identifier:
res.append(text_type(self.identifier))
else:
diff --git a/sphinx/domains/javascript.py b/sphinx/domains/javascript.py
index f0b78589e..772cb16a9 100644
--- a/sphinx/domains/javascript.py
+++ b/sphinx/domains/javascript.py
@@ -148,7 +148,7 @@ class JSXRefRole(XRefRole):
title = title[1:]
dot = title.rfind('.')
if dot != -1:
- title = title[dot+1:]
+ title = title[dot + 1:]
if target[0:1] == '.':
target = target[1:]
refnode['refspecific'] = True
diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py
index a7e2bb8f6..ba38f4702 100644
--- a/sphinx/domains/python.py
+++ b/sphinx/domains/python.py
@@ -527,7 +527,7 @@ class PyXRefRole(XRefRole):
title = title[1:]
dot = title.rfind('.')
if dot != -1:
- title = title[dot+1:]
+ title = title[dot + 1:]
# if the first character is a dot, search more specific namespaces first
# else search builtins first
if target[0:1] == '.':
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index 021d26a46..244b12e45 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -58,7 +58,7 @@ class GenericObject(ObjectDescription):
colon = self.indextemplate.find(':')
if colon != -1:
indextype = self.indextemplate[:colon].strip()
- indexentry = self.indextemplate[colon+1:].strip() % (name,)
+ indexentry = self.indextemplate[colon + 1:].strip() % (name,)
else:
indextype = 'single'
indexentry = self.indextemplate % (name,)
@@ -118,7 +118,7 @@ class Target(Directive):
colon = indexentry.find(':')
if colon != -1:
indextype = indexentry[:colon].strip()
- indexentry = indexentry[colon+1:].strip()
+ indexentry = indexentry[colon + 1:].strip()
inode = addnodes.index(entries=[(indextype, indexentry,
targetname, '', None)])
ret.insert(0, inode)
@@ -566,7 +566,7 @@ class StandardDomain(Domain):
env.warn_node('duplicate label %s, ' % name + 'other instance '
'in ' + env.doc2path(labels[name][0]), node)
anonlabels[name] = docname, labelid
- if node.tagname == 'section':
+ if node.tagname in ('section', 'rubric'):
sectname = clean_astext(node[0]) # node[0] == title node
elif self.is_enumerable_node(node):
sectname = self.get_numfig_title(node)
@@ -673,13 +673,13 @@ class StandardDomain(Domain):
else:
title = env.config.numfig_format.get(figtype, '')
- if figname is None and '%{name}' in title:
+ if figname is None and '{name}' in title:
env.warn_node('the link has no caption: %s' % title, node)
return contnode
else:
fignum = '.'.join(map(str, fignumber))
if '{name}' in title or 'number' in title:
- # new style format (cf. "Fig.%{number}")
+ # new style format (cf. "Fig.{number}")
if figname:
newtitle = title.format(name=figname, number=fignum)
else:
diff --git a/sphinx/environment/__init__.py b/sphinx/environment/__init__.py
index 0f978e42e..f760583ec 100644
--- a/sphinx/environment/__init__.py
+++ b/sphinx/environment/__init__.py
@@ -632,7 +632,7 @@ class BuildEnvironment(object):
lineno = error.object.count(b'\n', 0, error.start) + 1
self.warn(self.docname, 'undecodable source characters, '
'replacing with "?": %r' %
- (error.object[linestart+1:error.start] + b'>>>' +
+ (error.object[linestart + 1:error.start] + b'>>>' +
error.object[error.start:error.end] + b'<<<' +
error.object[error.end:lineend]), lineno)
return (u'?', error.end)
diff --git a/sphinx/environment/managers/toctree.py b/sphinx/environment/managers/toctree.py
index 67fbfa7b6..cf57f4d88 100644
--- a/sphinx/environment/managers/toctree.py
+++ b/sphinx/environment/managers/toctree.py
@@ -224,11 +224,11 @@ class Toctree(EnvironmentManager):
if isinstance(subnode, (addnodes.compact_paragraph,
nodes.list_item)):
# for <p> and <li>, indicate the depth level and recurse
- subnode['classes'].append('toctree-l%d' % (depth-1))
+ subnode['classes'].append('toctree-l%d' % (depth - 1))
_toctree_add_classes(subnode, depth)
elif isinstance(subnode, nodes.bullet_list):
# for <ul>, just recurse
- _toctree_add_classes(subnode, depth+1)
+ _toctree_add_classes(subnode, depth + 1)
elif isinstance(subnode, nodes.reference):
# for <a>, identify which entries point to the current
# document and therefore may not be collapsed
@@ -417,7 +417,7 @@ class Toctree(EnvironmentManager):
subnode.parent.remove(subnode)
else:
# recurse on visible children
- self._toctree_prune(subnode, depth+1, maxdepth, collapse)
+ self._toctree_prune(subnode, depth + 1, maxdepth, collapse)
def assign_section_numbers(self):
"""Assign a section number to each heading under a numbered toctree."""
@@ -434,7 +434,7 @@ class Toctree(EnvironmentManager):
for subnode in node.children:
if isinstance(subnode, nodes.bullet_list):
numstack.append(0)
- _walk_toc(subnode, secnums, depth-1, titlenode)
+ _walk_toc(subnode, secnums, depth - 1, titlenode)
numstack.pop()
titlenode = None
elif isinstance(subnode, nodes.list_item):
diff --git a/sphinx/errors.py b/sphinx/errors.py
index 5fb77a135..01f29d7aa 100644
--- a/sphinx/errors.py
+++ b/sphinx/errors.py
@@ -10,8 +10,6 @@
:license: BSD, see LICENSE for details.
"""
-import traceback
-
class SphinxError(Exception):
"""
@@ -71,10 +69,9 @@ class SphinxParallelError(SphinxError):
category = 'Sphinx parallel build error'
- def __init__(self, orig_exc, traceback):
- self.orig_exc = orig_exc
+ def __init__(self, message, traceback):
+ self.message = message
self.traceback = traceback
def __str__(self):
- return traceback.format_exception_only(
- self.orig_exc.__class__, self.orig_exc)[0].strip()
+ return self.message
diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py
index 030fec301..ce87444dd 100644
--- a/sphinx/ext/autosummary/__init__.py
+++ b/sphinx/ext/autosummary/__init__.py
@@ -100,7 +100,7 @@ def process_autosummary_toc(app, doctree):
if not isinstance(subnode, nodes.section):
continue
if subnode not in crawled:
- crawl_toc(subnode, depth+1)
+ crawl_toc(subnode, depth + 1)
crawl_toc(doctree)
@@ -266,7 +266,7 @@ class Autosummary(Directive):
if not isinstance(obj, ModuleType):
# give explicitly separated module name, so that members
# of inner classes can be documented
- full_name = modname + '::' + full_name[len(modname)+1:]
+ full_name = modname + '::' + full_name[len(modname) + 1:]
# NB. using full_name here is important, since Documenters
# handle module prefixes slightly differently
documenter = get_documenter(obj, parent)(self, full_name)
@@ -403,13 +403,13 @@ def mangle_signature(sig, max_chars=30):
s = m.group(1)[:-2]
# Produce a more compact signature
- sig = limited_join(", ", args, max_chars=max_chars-2)
+ sig = limited_join(", ", args, max_chars=max_chars - 2)
if opts:
if not sig:
- sig = "[%s]" % limited_join(", ", opts, max_chars=max_chars-4)
+ sig = "[%s]" % limited_join(", ", opts, max_chars=max_chars - 4)
elif len(sig) < max_chars - 4 - 2 - 3:
sig += "[, %s]" % limited_join(", ", opts,
- max_chars=max_chars-len(sig)-4-2)
+ max_chars=max_chars - len(sig) - 4 - 2)
return u"(%s)" % sig
@@ -497,7 +497,7 @@ def _import_by_name(name):
# ... then as MODNAME, MODNAME.OBJ1, MODNAME.OBJ1.OBJ2, ...
last_j = 0
modname = None
- for j in reversed(range(1, len(name_parts)+1)):
+ for j in reversed(range(1, len(name_parts) + 1)):
last_j = j
modname = '.'.join(name_parts[:j])
try:
diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py
index 244762b69..b2f6225ec 100644
--- a/sphinx/ext/doctest.py
+++ b/sphinx/ext/doctest.py
@@ -241,7 +241,7 @@ class DocTestBuilder(Builder):
self.outfile.write('''\
Results of doctest builder run on %s
==================================%s
-''' % (date, '='*len(date)))
+''' % (date, '=' * len(date)))
def _out(self, text):
self.info(text, nonl=True)
@@ -348,7 +348,7 @@ Doctest summary
return
self._out('\nDocument: %s\n----------%s\n' %
- (docname, '-'*len(docname)))
+ (docname, '-' * len(docname)))
for group in itervalues(groups):
self.test_group(group, self.env.doc2path(docname, base=None))
# Separately count results from setup code
diff --git a/sphinx/ext/imgmath.py b/sphinx/ext/imgmath.py
index c800eee65..847dc1729 100644
--- a/sphinx/ext/imgmath.py
+++ b/sphinx/ext/imgmath.py
@@ -217,7 +217,7 @@ def get_tooltip(self, node):
def html_visit_math(self, node):
try:
- fname, depth = render_math(self, '$'+node['latex']+'$')
+ fname, depth = render_math(self, '$' + node['latex'] + '$')
except MathExtError as exc:
msg = text_type(exc)
sm = nodes.system_message(msg, type='WARNING', level=2,
diff --git a/sphinx/ext/intersphinx.py b/sphinx/ext/intersphinx.py
index b7cc849a4..ed37c083e 100644
--- a/sphinx/ext/intersphinx.py
+++ b/sphinx/ext/intersphinx.py
@@ -68,7 +68,7 @@ def read_inventory_v1(f, uri, join):
return invdata
-def read_inventory_v2(f, uri, join, bufsize=16*1024):
+def read_inventory_v2(f, uri, join, bufsize=16 * 1024):
invdata = {}
line = f.readline()
projname = line.rstrip()[11:].decode('utf-8')
@@ -91,7 +91,7 @@ def read_inventory_v2(f, uri, join, bufsize=16*1024):
lineend = buf.find(b'\n')
while lineend != -1:
yield buf[:lineend].decode('utf-8')
- buf = buf[lineend+1:]
+ buf = buf[lineend + 1:]
lineend = buf.find(b'\n')
assert not buf
@@ -116,7 +116,7 @@ def read_inventory_v2(f, uri, join, bufsize=16*1024):
return invdata
-def read_inventory(f, uri, join, bufsize=16*1024):
+def read_inventory(f, uri, join, bufsize=16 * 1024):
line = f.readline().rstrip().decode('utf-8')
if line == '# Sphinx inventory version 1':
return read_inventory_v1(f, uri, join)
@@ -221,8 +221,8 @@ def fetch_inventory(app, uri, inv):
try:
join = localuri and path.join or posixpath.join
invdata = read_inventory(f, uri, join)
- except ValueError:
- raise ValueError('unknown or unsupported inventory version')
+ except ValueError as exc:
+ raise ValueError('unknown or unsupported inventory version: %r' % exc)
except Exception as err:
app.warn('intersphinx inventory %r not readable due to '
'%s: %s' % (inv, err.__class__.__name__, err))
@@ -242,7 +242,7 @@ def load_mappings(app):
cache = env.intersphinx_cache
update = False
for key, value in iteritems(app.config.intersphinx_mapping):
- if isinstance(value, tuple):
+ if isinstance(value, (list, tuple)):
# new format
name, (uri, inv) = key, value
if not isinstance(name, string_types):
@@ -342,9 +342,9 @@ def missing_reference(app, env, node, contnode):
(domain == 'std' and node['reftype'] == 'keyword'):
# use whatever title was given, but strip prefix
title = contnode.astext()
- if in_set and title.startswith(in_set+':'):
- newnode.append(contnode.__class__(title[len(in_set)+1:],
- title[len(in_set)+1:]))
+ if in_set and title.startswith(in_set + ':'):
+ newnode.append(contnode.__class__(title[len(in_set) + 1:],
+ title[len(in_set) + 1:]))
else:
newnode.append(contnode)
else:
diff --git a/sphinx/ext/pngmath.py b/sphinx/ext/pngmath.py
index 655eb562f..0725cdc82 100644
--- a/sphinx/ext/pngmath.py
+++ b/sphinx/ext/pngmath.py
@@ -189,7 +189,7 @@ def get_tooltip(self, node):
def html_visit_math(self, node):
try:
- fname, depth = render_math(self, '$'+node['latex']+'$')
+ fname, depth = render_math(self, '$' + node['latex'] + '$')
except MathExtError as exc:
msg = text_type(exc)
sm = nodes.system_message(msg, type='WARNING', level=2,
diff --git a/sphinx/ext/todo.py b/sphinx/ext/todo.py
index f3b526ce6..15323c961 100644
--- a/sphinx/ext/todo.py
+++ b/sphinx/ext/todo.py
@@ -138,7 +138,7 @@ def process_todo_nodes(app, doctree, fromdocname):
(todo_info['source'], todo_info['lineno'])
)
desc1 = description[:description.find('<<')]
- desc2 = description[description.find('>>')+2:]
+ desc2 = description[description.find('>>') + 2:]
para += nodes.Text(desc1, desc1)
# Create a reference
diff --git a/sphinx/make_mode.py b/sphinx/make_mode.py
index 6aeeab802..e6bcd1315 100644
--- a/sphinx/make_mode.py
+++ b/sphinx/make_mode.py
@@ -79,7 +79,7 @@ class Make(object):
def build_help(self):
print(bold("Sphinx v%s" % sphinx.__display_version__))
- print("Please use `make %s' where %s is one of" % ((blue('target'),)*2))
+ print("Please use `make %s' where %s is one of" % ((blue('target'),) * 2))
for osname, bname, description in BUILDERS:
if not osname or os.name == osname:
print(' %s %s' % (blue(bname.ljust(10)), description))
diff --git a/sphinx/pycode/__init__.py b/sphinx/pycode/__init__.py
index baf5c0068..d1d151f6f 100644
--- a/sphinx/pycode/__init__.py
+++ b/sphinx/pycode/__init__.py
@@ -364,4 +364,4 @@ if __name__ == '__main__':
pprint.pprint(ma.find_tags())
x3 = time.time()
# print nodes.nice_repr(ma.parsetree, number2name)
- print("tokenizing %.4f, parsing %.4f, finding %.4f" % (x1-x0, x2-x1, x3-x2))
+ print("tokenizing %.4f, parsing %.4f, finding %.4f" % (x1 - x0, x2 - x1, x3 - x2))
diff --git a/sphinx/pycode/nodes.py b/sphinx/pycode/nodes.py
index ee40f3c0d..e3a1bc9f6 100644
--- a/sphinx/pycode/nodes.py
+++ b/sphinx/pycode/nodes.py
@@ -39,7 +39,7 @@ class BaseNode(object):
if child is self:
if i == 0:
return None
- return self.parent.children[i-1]
+ return self.parent.children[i - 1]
def get_next_sibling(self):
"""Return next child in parent's children, or None."""
@@ -48,7 +48,7 @@ class BaseNode(object):
for i, child in enumerate(self.parent.children):
if child is self:
try:
- return self.parent.children[i+1]
+ return self.parent.children[i + 1]
except IndexError:
return None
diff --git a/sphinx/quickstart.py b/sphinx/quickstart.py
index 3c7ab3d97..dda98ce5a 100644
--- a/sphinx/quickstart.py
+++ b/sphinx/quickstart.py
@@ -301,11 +301,11 @@ document is a custom template, you can also set this to another filename.''')
do_prompt(d, 'master', 'Name of your master document (without suffix)',
'index')
- while path.isfile(path.join(d['path'], d['master']+d['suffix'])) or \
- path.isfile(path.join(d['path'], 'source', d['master']+d['suffix'])):
+ while path.isfile(path.join(d['path'], d['master'] + d['suffix'])) or \
+ path.isfile(path.join(d['path'], 'source', d['master'] + d['suffix'])):
print()
print(bold('Error: the master file %s has already been found in the '
- 'selected root path.' % (d['master']+d['suffix'])))
+ 'selected root path.' % (d['master'] + d['suffix'])))
print('sphinx-quickstart will not overwrite the existing file.')
print()
do_prompt(d, 'master', 'Please enter a new file name, or rename the '
@@ -632,7 +632,7 @@ def main(argv=sys.argv):
d.setdefault('version', '')
d.setdefault('release', d['version'])
d2 = DEFAULT_VALUE.copy()
- d2.update(dict(("ext_"+ext, False) for ext in EXTENSIONS))
+ d2.update(dict(("ext_" + ext, False) for ext in EXTENSIONS))
d2.update(d)
d = d2
if 'no_makefile' in d:
diff --git a/sphinx/roles.py b/sphinx/roles.py
index 71bc83b2d..47cd694c4 100644
--- a/sphinx/roles.py
+++ b/sphinx/roles.py
@@ -201,7 +201,7 @@ def indexmarkup_role(typ, rawtext, text, lineno, inliner,
return [prb], [msg]
ref = inliner.document.settings.pep_base_url + 'pep-%04d' % pepnum
sn = nodes.strong(title, title)
- rn = nodes.reference('', '', internal=False, refuri=ref+anchor,
+ rn = nodes.reference('', '', internal=False, refuri=ref + anchor,
classes=[typ])
rn += sn
return [indexnode, targetnode, rn], []
@@ -223,7 +223,7 @@ def indexmarkup_role(typ, rawtext, text, lineno, inliner,
return [prb], [msg]
ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum
sn = nodes.strong(title, title)
- rn = nodes.reference('', '', internal=False, refuri=ref+anchor,
+ rn = nodes.reference('', '', internal=False, refuri=ref + anchor,
classes=[typ])
rn += sn
return [indexnode, targetnode, rn], []
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index f57283c19..3e82bafec 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -6,7 +6,7 @@
%
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
-\ProvidesPackage{sphinx}[2016/12/14 v1.5.2 LaTeX package (Sphinx markup)]
+\ProvidesPackage{sphinx}[2017/01/09 v1.5.2 LaTeX package (Sphinx markup)]
% we delay handling of options to after having loaded packages, because
% of the need to use \definecolor.
@@ -1090,8 +1090,14 @@
% make commands known to non-Sphinx document classes
\providecommand*{\sphinxtableofcontents}{\tableofcontents}
-\providecommand*{\sphinxthebibliography}{\thebibliography}
-\providecommand*{\sphinxtheindex}{\theindex}
+\spx@ifundefined{sphinxthebibliography}
+ {\newenvironment
+ {sphinxthebibliography}{\begin{thebibliography}}{\end{thebibliography}}%
+ }
+ {}% else clause of ifundefined
+\spx@ifundefined{sphinxtheindex}
+ {\newenvironment{sphinxtheindex}{\begin{theindex}}{\end{theindex}}}%
+ {}% else clause of ifundefined
% remove LaTeX's cap on nesting depth if 'maxlistdepth' key used.
% This is a hack, which works with the standard classes: it assumes \@toodeep
@@ -1122,7 +1128,7 @@
\expandafter\let
\csname @list\romannumeral\the\count@\expandafter\endcsname
\csname @list\romannumeral\the\numexpr\count@-\@ne\endcsname
- % higher \leftmargin... needed to fix issue with babel-french (v2.6--...)
+ % work around 2.6--3.2d babel-french issue (fixed in 3.2e; no change needed)
\spx@ifundefined{leftmargin\romannumeral\the\count@}
{\expandafter\let
\csname leftmargin\romannumeral\the\count@\expandafter\endcsname
diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py
index 38c5aef25..c19fd5f74 100644
--- a/sphinx/transforms/i18n.py
+++ b/sphinx/transforms/i18n.py
@@ -112,7 +112,7 @@ class Locale(Transform):
# literalblock need literal block notation to avoid it become
# paragraph.
if isinstance(node, LITERAL_TYPE_NODES):
- msgstr = '::\n\n' + indent(msgstr, ' '*3)
+ msgstr = '::\n\n' + indent(msgstr, ' ' * 3)
patch = publish_msgstr(
env.app, msgstr, source, node.line, env.config, settings)
@@ -237,7 +237,7 @@ class Locale(Transform):
# literalblock need literal block notation to avoid it become
# paragraph.
if isinstance(node, LITERAL_TYPE_NODES):
- msgstr = '::\n\n' + indent(msgstr, ' '*3)
+ msgstr = '::\n\n' + indent(msgstr, ' ' * 3)
patch = publish_msgstr(
env.app, msgstr, source, node.line, env.config, settings)
diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py
index e650f7aa9..dfe1f60b9 100644
--- a/sphinx/util/__init__.py
+++ b/sphinx/util/__init__.py
@@ -98,7 +98,7 @@ def get_matching_docs(dirname, suffixes, exclude_matchers=()):
for filename in get_matching_files(dirname, exclude_matchers):
for suffixpattern in suffixpatterns:
if fnmatch.fnmatch(filename, suffixpattern):
- yield filename[:-len(suffixpattern)+1]
+ yield filename[:-len(suffixpattern) + 1]
break
@@ -167,7 +167,7 @@ def copy_static_entry(source, targetdir, builder, context={},
if path.isdir(path.join(source, entry)):
newtarget = path.join(targetdir, entry)
copy_static_entry(path.join(source, entry), newtarget,
- builder, context, level=level+1,
+ builder, context, level=level + 1,
exclude_matchers=exclude_matchers)
@@ -360,9 +360,9 @@ def parselinenos(spec, total):
if len(begend) > 2:
raise ValueError
if len(begend) == 1:
- items.append(int(begend[0])-1)
+ items.append(int(begend[0]) - 1)
else:
- start = (begend[0] == '') and 0 or int(begend[0])-1
+ start = (begend[0] == '') and 0 or int(begend[0]) - 1
end = (begend[1] == '') and total or int(begend[1])
items.extend(range(start, end))
except Exception:
@@ -400,13 +400,13 @@ def rpartition(s, t):
"""Similar to str.rpartition from 2.5, but doesn't return the separator."""
i = s.rfind(t)
if i != -1:
- return s[:i], s[i+len(t):]
+ return s[:i], s[i + len(t):]
return '', s
def split_into(n, type, value):
"""Split an index entry into a given number of parts at semicolons."""
- parts = [x.strip() for x in value.split(';', n-1)]
+ parts = [x.strip() for x in value.split(';', n - 1)]
if sum(1 for part in parts if part) < n:
raise ValueError('invalid %s index entry %r' % (type, value))
return parts
diff --git a/sphinx/util/console.py b/sphinx/util/console.py
index 593634b11..292162b04 100644
--- a/sphinx/util/console.py
+++ b/sphinx/util/console.py
@@ -115,8 +115,8 @@ _colors = [
]
for i, (dark, light) in enumerate(_colors):
- codes[dark] = '\x1b[%im' % (i+30)
- codes[light] = '\x1b[%i;01m' % (i+30)
+ codes[dark] = '\x1b[%im' % (i + 30)
+ codes[light] = '\x1b[%i;01m' % (i + 30)
_orig_codes = codes.copy()
diff --git a/sphinx/util/docutils.py b/sphinx/util/docutils.py
index 8d1d58cf8..ecc03f066 100644
--- a/sphinx/util/docutils.py
+++ b/sphinx/util/docutils.py
@@ -16,7 +16,7 @@ import docutils
from docutils.parsers.rst import directives, roles
-__version_info__ = tuple(map(int, docutils.__version__.split('.')))
+__version_info__ = tuple(map(int, docutils.__version__.split('.')))
@contextmanager
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
index 4375b7e61..b258c2039 100644
--- a/sphinx/util/fileutil.py
+++ b/sphinx/util/fileutil.py
@@ -41,7 +41,9 @@ def copy_asset_file(source, destination, context=None, renderer=None):
renderer = SphinxRenderer()
with codecs.open(source, 'r', encoding='utf-8') as fsrc:
- with codecs.open(destination[:-2], 'w', encoding='utf-8') as fdst:
+ if destination.lower().endswith('_t'):
+ destination = destination[:-2]
+ with codecs.open(destination, 'w', encoding='utf-8') as fdst:
fdst.write(renderer.render_string(fsrc.read(), context))
else:
copyfile(source, destination)
diff --git a/sphinx/util/i18n.py b/sphinx/util/i18n.py
index 41a9c5e20..f46e36321 100644
--- a/sphinx/util/i18n.py
+++ b/sphinx/util/i18n.py
@@ -53,10 +53,19 @@ class CatalogInfo(LocaleFileInfoBase):
not path.exists(self.mo_path) or
path.getmtime(self.mo_path) < path.getmtime(self.po_path))
- def write_mo(self, locale):
- with io.open(self.po_path, 'rt', encoding=self.charset) as po:
- with io.open(self.mo_path, 'wb') as mo:
- write_mo(mo, read_po(po, locale))
+ def write_mo(self, locale, warnfunc):
+ with io.open(self.po_path, 'rt', encoding=self.charset) as file_po:
+ try:
+ po = read_po(file_po, locale)
+ except Exception:
+ warnfunc('reading error: %s' % self.po_path)
+ return
+
+ with io.open(self.mo_path, 'wb') as file_mo:
+ try:
+ write_mo(file_mo, po)
+ except Exception:
+ warnfunc('writing error: %s' % self.mo_path)
def find_catalog(docname, compaction):
diff --git a/sphinx/util/jsdump.py b/sphinx/util/jsdump.py
index 5a2148c5b..1dcb78946 100644
--- a/sphinx/util/jsdump.py
+++ b/sphinx/util/jsdump.py
@@ -16,8 +16,8 @@ from six import iteritems, integer_types, string_types
from sphinx.util.pycompat import u
-_str_re = re.compile(r'"(\\\\|\\"|[^"])*"')
-_int_re = re.compile(r'\d+')
+_str_re = re.compile(r'"(\\\\|\\"|[^"])*"')
+_int_re = re.compile(r'\d+')
_name_re = re.compile(r'[a-zA-Z_]\w*')
_nameonly_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py
index 1da3f69d8..463d7a32e 100644
--- a/sphinx/util/nodes.py
+++ b/sphinx/util/nodes.py
@@ -243,15 +243,15 @@ def process_index_entry(entry, targetid):
main = 'main'
entry = entry[1:].lstrip()
for type in pairindextypes:
- if entry.startswith(type+':'):
- value = entry[len(type)+1:].strip()
+ if entry.startswith(type + ':'):
+ value = entry[len(type) + 1:].strip()
value = pairindextypes[type] + '; ' + value
indexentries.append(('pair', value, targetid, main, None))
break
else:
for type in indextypes:
- if entry.startswith(type+':'):
- value = entry[len(type)+1:].strip()
+ if entry.startswith(type + ':'):
+ value = entry[len(type) + 1:].strip()
if type == 'double':
type = 'pair'
indexentries.append((type, value, targetid, main, None))
diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py
index b8fffb220..6368384e8 100644
--- a/sphinx/util/osutil.py
+++ b/sphinx/util/osutil.py
@@ -27,7 +27,7 @@ from six import PY2, text_type
# Errnos that we need.
EEXIST = getattr(errno, 'EEXIST', 0)
ENOENT = getattr(errno, 'ENOENT', 0)
-EPIPE = getattr(errno, 'EPIPE', 0)
+EPIPE = getattr(errno, 'EPIPE', 0)
EINVAL = getattr(errno, 'EINVAL', 0)
# SEP separates path elements in the canonical file names
@@ -67,7 +67,7 @@ def relative_uri(base, to):
# Special case: relative_uri('f/index.html','f/') should
# return './', not ''
return '.' + SEP
- return ('..' + SEP) * (len(b2)-1) + SEP.join(t2)
+ return ('..' + SEP) * (len(b2) - 1) + SEP.join(t2)
def ensuredir(path):
diff --git a/sphinx/util/parallel.py b/sphinx/util/parallel.py
index bace0b5fd..ce51ac0eb 100644
--- a/sphinx/util/parallel.py
+++ b/sphinx/util/parallel.py
@@ -73,7 +73,8 @@ class ParallelTasks(object):
ret = func(arg)
pipe.send((False, ret))
except BaseException as err:
- pipe.send((True, (err, traceback.format_exc())))
+ errmsg = traceback.format_exception_only(err.__class__, err)[0].strip()
+ pipe.send((True, (errmsg, traceback.format_exc())))
def add_task(self, task_func, arg=None, result_func=None):
tid = self._taskid
@@ -116,11 +117,11 @@ def make_chunks(arguments, nproc, maxbatch=10):
chunksize = nargs // nproc
if chunksize >= maxbatch:
# try to improve batch size vs. number of batches
- chunksize = int(sqrt(nargs/nproc * maxbatch))
+ chunksize = int(sqrt(nargs / nproc * maxbatch))
if chunksize == 0:
chunksize = 1
nchunks, rest = divmod(nargs, chunksize)
if rest:
nchunks += 1
# partition documents in "chunks" that will be written by one Process
- return [arguments[i*chunksize:(i+1)*chunksize] for i in range(nchunks)]
+ return [arguments[i * chunksize:(i + 1) * chunksize] for i in range(nchunks)]
diff --git a/sphinx/util/requests.py b/sphinx/util/requests.py
index 697e29087..8b7204c2f 100644
--- a/sphinx/util/requests.py
+++ b/sphinx/util/requests.py
@@ -17,7 +17,12 @@ import pkg_resources
from six import string_types
from six.moves.urllib.parse import urlsplit
-from requests.packages.urllib3.exceptions import SSLError, InsecureRequestWarning
+try:
+ from requests.packages.urllib3.exceptions import SSLError, InsecureRequestWarning
+except ImportError:
+ # python-requests package in Debian jessie does not provide ``requests.packages.urllib3``.
+ # So try to import the exceptions from urllib3 package.
+ from urllib3.exceptions import SSLError, InsecureRequestWarning
# try to load requests[security]
try:
diff --git a/sphinx/util/stemmer.py b/sphinx/util/stemmer.py
index 47fc41e87..951c6ab67 100644
--- a/sphinx/util/stemmer.py
+++ b/sphinx/util/stemmer.py
@@ -107,7 +107,7 @@ class PorterStemmer(object):
"""doublec(j) is TRUE <=> j,(j-1) contain a double consonant."""
if j < (self.k0 + 1):
return 0
- if (self.b[j] != self.b[j-1]):
+ if (self.b[j] != self.b[j - 1]):
return 0
return self.cons(j)
@@ -120,8 +120,8 @@ class PorterStemmer(object):
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
"""
- if i < (self.k0 + 2) or not self.cons(i) or self.cons(i-1) \
- or not self.cons(i-2):
+ if i < (self.k0 + 2) or not self.cons(i) or self.cons(i - 1) \
+ or not self.cons(i - 2):
return 0
ch = self.b[i]
if ch == 'w' or ch == 'x' or ch == 'y':
@@ -135,7 +135,7 @@ class PorterStemmer(object):
return 0
if length > (self.k - self.k0 + 1):
return 0
- if self.b[self.k-length+1:self.k+1] != s:
+ if self.b[self.k - length + 1:self.k + 1] != s:
return 0
self.j = self.k - length
return 1
@@ -144,7 +144,7 @@ class PorterStemmer(object):
"""setto(s) sets (j+1),...k to the characters in the string s,
readjusting k."""
length = len(s)
- self.b = self.b[:self.j+1] + s + self.b[self.j+length+1:]
+ self.b = self.b[:self.j + 1] + s + self.b[self.j + length + 1:]
self.k = self.j + length
def r(self, s):
@@ -203,7 +203,7 @@ class PorterStemmer(object):
"""step1c() turns terminal y to i when there is another vowel in
the stem."""
if (self.ends("y") and self.vowelinstem()):
- self.b = self.b[:self.k] + 'i' + self.b[self.k+1:]
+ self.b = self.b[:self.k] + 'i' + self.b[self.k + 1:]
def step2(self):
"""step2() maps double suffices to single ones.
@@ -376,7 +376,7 @@ class PorterStemmer(object):
self.j = self.k
if self.b[self.k] == 'e':
a = self.m()
- if a > 1 or (a == 1 and not self.cvc(self.k-1)):
+ if a > 1 or (a == 1 and not self.cvc(self.k - 1)):
self.k = self.k - 1
if self.b[self.k] == 'l' and self.doublec(self.k) and self.m() > 1:
self.k = self.k - 1
@@ -408,4 +408,4 @@ class PorterStemmer(object):
self.step3()
self.step4()
self.step5()
- return self.b[self.k0:self.k+1]
+ return self.b[self.k0:self.k + 1]
diff --git a/sphinx/websupport/search/__init__.py b/sphinx/websupport/search/__init__.py
index 80b5a3535..48279f0a8 100644
--- a/sphinx/websupport/search/__init__.py
+++ b/sphinx/websupport/search/__init__.py
@@ -106,7 +106,7 @@ class BaseSearch(object):
res = self.context_re.search(text)
if res is None:
return ''
- context_start = max(res.start() - int(length/2), 0)
+ context_start = max(res.start() - int(length / 2), 0)
context_end = context_start + length
context = ''.join([context_start > 0 and '...' or '',
text[context_start:context_end],
diff --git a/sphinx/writers/html.py b/sphinx/writers/html.py
index 016c04bd6..62eed2ada 100644
--- a/sphinx/writers/html.py
+++ b/sphinx/writers/html.py
@@ -454,7 +454,7 @@ class HTMLTranslator(BaseTranslator):
self.body.append(self.starttag(production, 'strong', ''))
self.body.append(lastname + '</strong> ::= ')
elif lastname is not None:
- self.body.append('%s ' % (' '*len(lastname)))
+ self.body.append('%s ' % (' ' * len(lastname)))
production.walkabout(self)
self.body.append('\n')
self.body.append('</pre>\n')
@@ -614,7 +614,7 @@ class HTMLTranslator(BaseTranslator):
self.body.append(token)
else:
# protect runs of multiple spaces; the last one can wrap
- self.body.append('&#160;' * (len(token)-1) + ' ')
+ self.body.append('&#160;' * (len(token) - 1) + ' ')
else:
if self.in_mailto and self.settings.cloak_email_addresses:
encoded = self.cloak_email(encoded)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 70a9c6f68..fdebaf23c 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1641,7 +1641,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
parindex = node.parent.index(node)
try:
try:
- next = node.parent[parindex+1]
+ next = node.parent[parindex + 1]
except IndexError:
# last node in parent, look at next after parent
# (for section of equal level) if it exists
@@ -1700,14 +1700,14 @@ class LaTeXTranslator(nodes.NodeVisitor):
elif type == 'pair':
p1, p2 = [self.encode(x) for x in split_into(2, 'pair', string)]
self.body.append(r'\index{%s!%s%s}\index{%s!%s%s}' %
- (p1, p2, m, p2, p1, m))
+ (p1, p2, m, p2, p1, m))
elif type == 'triple':
p1, p2, p3 = [self.encode(x)
for x in split_into(3, 'triple', string)]
self.body.append(
r'\index{%s!%s %s%s}\index{%s!%s, %s%s}'
r'\index{%s!%s %s%s}' %
- (p1, p2, p3, m, p2, p3, p1, m, p3, p1, p2, m))
+ (p1, p2, p3, m, p2, p3, p1, m, p3, p1, p2, m))
elif type == 'see':
p1, p2 = [self.encode(x) for x in split_into(2, 'see', string)]
self.body.append(r'\index{%s|see{%s}}' % (p1, p2))
diff --git a/sphinx/writers/manpage.py b/sphinx/writers/manpage.py
index 53cf29767..5bc077518 100644
--- a/sphinx/writers/manpage.py
+++ b/sphinx/writers/manpage.py
@@ -271,7 +271,7 @@ class ManualPageTranslator(BaseTranslator):
self.body.append(self.defs['strong'][1])
self.body.append(' ::= ')
elif lastname is not None:
- self.body.append('%s ' % (' '*len(lastname)))
+ self.body.append('%s ' % (' ' * len(lastname)))
production.walkabout(self)
self.body.append('\n')
self.body.append('\n.fi\n')
diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py
index 18dcd9177..a513823ea 100644
--- a/sphinx/writers/texinfo.py
+++ b/sphinx/writers/texinfo.py
@@ -318,10 +318,10 @@ class TexinfoTranslator(nodes.NodeVisitor):
for i, id in enumerate(entries):
# First child's prev is empty
if i != 0:
- rellinks[id][1] = entries[i-1]
+ rellinks[id][1] = entries[i - 1]
# Last child's next is empty
if i != len(entries) - 1:
- rellinks[id][0] = entries[i+1]
+ rellinks[id][0] = entries[i + 1]
# top's next is its first child
try:
first = node_menus['Top'][0]
@@ -383,7 +383,7 @@ class TexinfoTranslator(nodes.NodeVisitor):
s = '* %s: %s. ' % (name, node_name)
offset = max((24, (len(name) + 4) % 78))
wdesc = '\n'.join(' ' * offset + l for l in
- textwrap.wrap(desc, width=78-offset))
+ textwrap.wrap(desc, width=78 - offset))
return s + wdesc.strip() + '\n'
def add_menu_entries(self, entries, reg=re.compile(r'\s+---?\s+')):
@@ -641,7 +641,7 @@ class TexinfoTranslator(nodes.NodeVisitor):
parindex = node.parent.index(node)
try:
try:
- next = node.parent[parindex+1]
+ next = node.parent[parindex + 1]
except IndexError:
# last node in parent, look at next after parent
# (for section of equal level)
@@ -996,7 +996,7 @@ class TexinfoTranslator(nodes.NodeVisitor):
return
self.body.append('\n\n@multitable ')
for i, n in enumerate(self.colwidths):
- self.body.append('{%s} ' % ('x' * (n+2)))
+ self.body.append('{%s} ' % ('x' * (n + 2)))
def depart_colspec(self, node):
pass
@@ -1274,7 +1274,7 @@ class TexinfoTranslator(nodes.NodeVisitor):
self.add_anchor(id, production)
s = production['tokenname'].ljust(maxlen) + ' ::='
else:
- s = '%s ' % (' '*maxlen)
+ s = '%s ' % (' ' * maxlen)
self.body.append(self.escape(s))
self.body.append(self.escape(production.astext() + '\n'))
self.depart_literal_block(None)
diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py
index fc9e3378c..ceb8ed3fb 100644
--- a/sphinx/writers/text.py
+++ b/sphinx/writers/text.py
@@ -90,7 +90,7 @@ class TextWrapper(textwrap.TextWrapper):
for i, c in enumerate(word):
total += column_width(c)
if total > space_left:
- return word[:i-1], word[i-1:]
+ return word[:i - 1], word[i - 1:]
return word, ''
def _split(self, text):
@@ -194,7 +194,7 @@ class TextTranslator(nodes.NodeVisitor):
if not toformat:
return
if wrap:
- res = my_wrap(''.join(toformat), width=MAXWIDTH-maxindent)
+ res = my_wrap(''.join(toformat), width=MAXWIDTH - maxindent)
else:
res = ''.join(toformat).splitlines()
if end:
@@ -225,7 +225,7 @@ class TextTranslator(nodes.NodeVisitor):
def depart_document(self, node):
self.end_state()
- self.body = self.nl.join(line and (' '*indent + line)
+ self.body = self.nl.join(line and (' ' * indent + line)
for indent, lines in self.states[0]
for line in lines)
# XXX header/footer?
@@ -271,7 +271,7 @@ class TextTranslator(nodes.NodeVisitor):
def visit_title(self, node):
if isinstance(node.parent, nodes.Admonition):
- self.add_text(node.astext()+': ')
+ self.add_text(node.astext() + ': ')
raise nodes.SkipNode
self.new_state(0)
@@ -401,7 +401,7 @@ class TextTranslator(nodes.NodeVisitor):
self.add_text(production['tokenname'].ljust(maxlen) + ' ::=')
lastname = production['tokenname']
elif lastname is not None:
- self.add_text('%s ' % (' '*len(lastname)))
+ self.add_text('%s ' % (' ' * len(lastname)))
self.add_text(production.astext() + self.nl)
self.end_state(wrap=False)
raise nodes.SkipNode
@@ -552,7 +552,7 @@ class TextTranslator(nodes.NodeVisitor):
def writesep(char='-'):
out = ['+']
for width in realwidths:
- out.append(char * (width+2))
+ out.append(char * (width + 2))
out.append('+')
self.add_text(''.join(out) + self.nl)