summaryrefslogtreecommitdiff
path: root/sphinx
diff options
context:
space:
mode:
authorDmitry Shachnev <mitya57@gmail.com>2014-01-20 18:32:47 +0400
committerDmitry Shachnev <mitya57@gmail.com>2014-01-20 18:32:47 +0400
commitc7539932b582ce7f849d6a83de296426393594d6 (patch)
treebb18c53d431f98cb3a33df663efe9093af0775ea /sphinx
parentf3ff3c037b4a78fbadf528e4e86b455400b1361c (diff)
parent344417db950d6e816ab2efb21737c2bdf9d1ad53 (diff)
downloadsphinx-c7539932b582ce7f849d6a83de296426393594d6.tar.gz
Merge
Diffstat (limited to 'sphinx')
-rw-r--r--sphinx/apidoc.py9
-rw-r--r--sphinx/application.py19
-rw-r--r--sphinx/builders/devhelp.py2
-rw-r--r--sphinx/builders/epub.py8
-rw-r--r--sphinx/builders/gettext.py2
-rw-r--r--sphinx/builders/html.py6
-rw-r--r--sphinx/builders/htmlhelp.py9
-rw-r--r--sphinx/builders/linkcheck.py4
-rw-r--r--sphinx/builders/qthelp.py2
-rw-r--r--sphinx/builders/texinfo.py2
-rw-r--r--sphinx/builders/text.py2
-rw-r--r--sphinx/builders/xml.py2
-rw-r--r--sphinx/cmdline.py108
-rw-r--r--sphinx/config.py2
-rw-r--r--sphinx/directives/code.py8
-rw-r--r--sphinx/domains/c.py2
-rw-r--r--sphinx/domains/cpp.py4
-rw-r--r--sphinx/domains/std.py2
-rw-r--r--sphinx/environment.py16
-rw-r--r--sphinx/ext/autodoc.py8
-rw-r--r--sphinx/ext/autosummary/__init__.py2
-rw-r--r--sphinx/ext/autosummary/generate.py11
-rw-r--r--sphinx/ext/coverage.py2
-rw-r--r--sphinx/ext/doctest.py6
-rw-r--r--sphinx/ext/graphviz.py10
-rw-r--r--sphinx/ext/ifconfig.py2
-rw-r--r--sphinx/ext/inheritance_diagram.py2
-rw-r--r--sphinx/ext/intersphinx.py4
-rw-r--r--sphinx/ext/pngmath.py8
-rw-r--r--sphinx/pycode/__init__.py11
-rw-r--r--sphinx/pycode/pgen2/driver.py2
-rw-r--r--sphinx/pycode/pgen2/grammar.py13
-rw-r--r--sphinx/pycode/pgen2/literals.py3
-rw-r--r--sphinx/pycode/pgen2/pgen.py15
-rw-r--r--sphinx/pycode/pgen2/tokenize.py6
-rw-r--r--sphinx/quickstart.py111
-rw-r--r--sphinx/setup_command.py9
-rw-r--r--sphinx/transforms.py2
-rw-r--r--sphinx/util/__init__.py6
-rw-r--r--sphinx/util/docfields.py6
-rw-r--r--sphinx/util/docstrings.py4
-rw-r--r--sphinx/util/inspect.py6
-rw-r--r--sphinx/util/matching.py2
-rw-r--r--sphinx/util/osutil.py9
-rw-r--r--sphinx/util/pycompat.py2
-rw-r--r--sphinx/writers/html.py24
-rw-r--r--sphinx/writers/latex.py4
-rw-r--r--sphinx/writers/texinfo.py2
-rw-r--r--sphinx/writers/text.py2
49 files changed, 277 insertions, 226 deletions
diff --git a/sphinx/apidoc.py b/sphinx/apidoc.py
index 7e95cdae..f03638d4 100644
--- a/sphinx/apidoc.py
+++ b/sphinx/apidoc.py
@@ -14,6 +14,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import os
import sys
import optparse
@@ -50,12 +51,12 @@ def write_file(name, text, opts):
"""Write the output file for module/package <name>."""
fname = path.join(opts.destdir, '%s.%s' % (name, opts.suffix))
if opts.dryrun:
- print 'Would create file %s.' % fname
+ print('Would create file %s.' % fname)
return
if not opts.force and path.isfile(fname):
- print 'File %s already exists, skipping.' % fname
+ print('File %s already exists, skipping.' % fname)
else:
- print 'Creating file %s.' % fname
+ print('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
@@ -312,7 +313,7 @@ Note: By default this script will not overwrite already created files.""")
if opts.suffix.startswith('.'):
opts.suffix = opts.suffix[1:]
if not path.isdir(rootpath):
- print >>sys.stderr, '%s is not a directory.' % rootpath
+ print('%s is not a directory.' % rootpath, file=sys.stderr)
sys.exit(1)
if not path.isdir(opts.destdir):
if not opts.dryrun:
diff --git a/sphinx/application.py b/sphinx/application.py
index 6b86b181..014a8315 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -10,6 +10,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import os
import sys
@@ -38,6 +39,8 @@ from sphinx.util.tags import Tags
from sphinx.util.osutil import ENOENT
from sphinx.util.console import bold, lightgray, darkgray
+if hasattr(sys, 'intern'):
+ intern = sys.intern
# List of all known core events. Maps name to arguments description.
events = {
@@ -174,7 +177,7 @@ class Sphinx(object):
# this can raise if the data version doesn't fit
self.env.domains[domain] = self.domains[domain](self.env)
self.info('done')
- except Exception, err:
+ except Exception as err:
if type(err) is IOError and err.errno == ENOENT:
self.info('not yet created')
else:
@@ -185,7 +188,7 @@ class Sphinx(object):
def _init_builder(self, buildername):
if buildername is None:
- print >>self._status, 'No builder selected, using default: html'
+ print('No builder selected, using default: html', file=self._status)
buildername = 'html'
if buildername not in self.builderclasses:
raise SphinxError('Builder name %s not registered' % buildername)
@@ -209,7 +212,7 @@ class Sphinx(object):
self.builder.build_specific(filenames)
else:
self.builder.build_update()
- except Exception, err:
+ except Exception as err:
# delete the saved env to force a fresh build next time
envfile = path.join(self.doctreedir, ENV_PICKLE_FILENAME)
if path.isfile(envfile):
@@ -280,7 +283,7 @@ class Sphinx(object):
return
try:
mod = __import__(extension, None, None, ['setup'])
- except ImportError, err:
+ except ImportError as err:
self.verbose('Original exception:\n' + traceback.format_exc())
raise ExtensionError('Could not import extension %s' % extension,
err)
@@ -290,7 +293,7 @@ class Sphinx(object):
else:
try:
mod.setup(self)
- except VersionRequirementError, err:
+ except VersionRequirementError as err:
# add the extension name to the version required
raise VersionRequirementError(
'The %s extension used by this project needs at least '
@@ -307,17 +310,17 @@ class Sphinx(object):
"""Import an object from a 'module.name' string."""
try:
module, name = objname.rsplit('.', 1)
- except ValueError, err:
+ except ValueError as err:
raise ExtensionError('Invalid full object name %s' % objname +
(source and ' (needed for %s)' % source or ''),
err)
try:
return getattr(__import__(module, None, None, [name]), name)
- except ImportError, err:
+ except ImportError as err:
raise ExtensionError('Could not import %s' % module +
(source and ' (needed for %s)' % source or ''),
err)
- except AttributeError, err:
+ except AttributeError as err:
raise ExtensionError('Could not find %s' % objname +
(source and ' (needed for %s)' % source or ''),
err)
diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py
index 81d2e6ce..4595c7c2 100644
--- a/sphinx/builders/devhelp.py
+++ b/sphinx/builders/devhelp.py
@@ -94,7 +94,7 @@ class DevhelpBuilder(StandaloneHTMLBuilder):
def istoctree(node):
return isinstance(node, addnodes.compact_paragraph) and \
- node.has_key('toctree')
+ 'toctree' in node
for node in tocdoc.traverse(istoctree):
write_toc(node, chapters)
diff --git a/sphinx/builders/epub.py b/sphinx/builders/epub.py
index 35061b79..ad586165 100644
--- a/sphinx/builders/epub.py
+++ b/sphinx/builders/epub.py
@@ -218,7 +218,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
"""Collect section titles, their depth in the toc and the refuri."""
# XXX: is there a better way than checking the attribute
# toctree-l[1-8] on the parent node?
- if isinstance(doctree, nodes.reference) and doctree.has_key('refuri'):
+ if isinstance(doctree, nodes.reference) and 'refuri' in doctree:
refuri = doctree['refuri']
if refuri.startswith('http://') or refuri.startswith('https://') \
or refuri.startswith('irc:') or refuri.startswith('mailto:'):
@@ -417,7 +417,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
try:
copyfile(path.join(self.srcdir, src),
path.join(self.outdir, '_images', dest))
- except (IOError, OSError), err:
+ except (IOError, OSError) as err:
self.warn('cannot copy image file %r: %s' %
(path.join(self.srcdir, src), err))
continue
@@ -433,7 +433,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
img = img.resize((nw, nh), Image.BICUBIC)
try:
img.save(path.join(self.outdir, '_images', dest))
- except (IOError, OSError), err:
+ except (IOError, OSError) as err:
self.warn('cannot write image file %r: %s' %
(path.join(self.srcdir, src), err))
@@ -489,7 +489,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
fn = path.join(outdir, outname)
try:
os.mkdir(path.dirname(fn))
- except OSError, err:
+ except OSError as err:
if err.errno != EEXIST:
raise
f = codecs.open(path.join(outdir, outname), 'w', 'utf-8')
diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py
index f648c311..f11ac293 100644
--- a/sphinx/builders/gettext.py
+++ b/sphinx/builders/gettext.py
@@ -184,7 +184,7 @@ class MessageCatalogBuilder(I18nBuilder):
for textdomain, catalog in self.status_iterator(
self.catalogs.iteritems(), "writing message catalogs... ",
darkgreen, len(self.catalogs),
- lambda (textdomain, _): textdomain):
+ lambda textdomain__: textdomain__[0]):
# noop if config.gettext_compact is set
ensuredir(path.join(self.outdir, path.dirname(textdomain)))
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index d715607e..b5ca56bd 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -531,7 +531,7 @@ class StandaloneHTMLBuilder(Builder):
try:
copyfile(path.join(self.srcdir, src),
path.join(self.outdir, '_images', dest))
- except Exception, err:
+ except Exception as err:
self.warn('cannot copy image file %r: %s' %
(path.join(self.srcdir, src), err))
@@ -546,7 +546,7 @@ class StandaloneHTMLBuilder(Builder):
try:
copyfile(path.join(self.srcdir, src),
path.join(self.outdir, '_downloads', dest))
- except Exception, err:
+ except Exception as err:
self.warn('cannot copy downloadable file %r: %s' %
(path.join(self.srcdir, src), err))
@@ -773,7 +773,7 @@ class StandaloneHTMLBuilder(Builder):
f.write(output)
finally:
f.close()
- except (IOError, OSError), err:
+ except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err))
if self.copysource and ctx.get('sourcename'):
# copy the source file for the "show source" link
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index e1723ba0..e7fa4bde 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -9,6 +9,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import os
import codecs
@@ -197,7 +198,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
f = self.open_file(outdir, outname+'.stp')
try:
for word in sorted(stopwords):
- print >>f, word
+ print(word, file=f)
finally:
f.close()
@@ -217,8 +218,8 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
for fn in files:
if (staticdir and not fn.endswith('.js')) or \
fn.endswith('.html'):
- print >>f, path.join(root, fn)[olen:].replace(os.sep,
- '\\')
+ print(path.join(root, fn)[olen:].replace(os.sep, '\\'),
+ file=f)
finally:
f.close()
@@ -256,7 +257,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
write_toc(subnode, ullevel)
def istoctree(node):
return isinstance(node, addnodes.compact_paragraph) and \
- node.has_key('toctree')
+ 'toctree' in node
for node in tocdoc.traverse(istoctree):
write_toc(node)
f.write(contents_footer)
diff --git a/sphinx/builders/linkcheck.py b/sphinx/builders/linkcheck.py
index 171e68d5..88149ed0 100644
--- a/sphinx/builders/linkcheck.py
+++ b/sphinx/builders/linkcheck.py
@@ -153,7 +153,7 @@ class CheckExternalLinksBuilder(Builder):
req = HeadRequest(req_url)
f = opener.open(req, **kwargs)
f.close()
- except HTTPError, err:
+ except HTTPError as err:
if err.code != 405:
raise
# retry with GET if that fails, some servers
@@ -162,7 +162,7 @@ class CheckExternalLinksBuilder(Builder):
f = opener.open(req, **kwargs)
f.close()
- except Exception, err:
+ except Exception as err:
self.broken[uri] = str(err)
return 'broken', str(err), 0
if f.url.rstrip('/') == req_url.rstrip('/'):
diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py
index ce07315d..9ef480df 100644
--- a/sphinx/builders/qthelp.py
+++ b/sphinx/builders/qthelp.py
@@ -123,7 +123,7 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
prune_toctrees=False)
istoctree = lambda node: (
isinstance(node, addnodes.compact_paragraph)
- and node.has_key('toctree'))
+ and 'toctree' in node)
sections = []
for node in tocdoc.traverse(istoctree):
sections.extend(self.write_toc(node))
diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py
index 9510c150..40ead11a 100644
--- a/sphinx/builders/texinfo.py
+++ b/sphinx/builders/texinfo.py
@@ -223,6 +223,6 @@ class TexinfoBuilder(Builder):
mkfile.write(TEXINFO_MAKEFILE)
finally:
mkfile.close()
- except (IOError, OSError), err:
+ except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (fn, err))
self.info(' done')
diff --git a/sphinx/builders/text.py b/sphinx/builders/text.py
index f09ad654..b0704def 100644
--- a/sphinx/builders/text.py
+++ b/sphinx/builders/text.py
@@ -65,7 +65,7 @@ class TextBuilder(Builder):
f.write(self.writer.output)
finally:
f.close()
- except (IOError, OSError), err:
+ except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err))
def finish(self):
diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py
index 19147fb1..8bc447b1 100644
--- a/sphinx/builders/xml.py
+++ b/sphinx/builders/xml.py
@@ -81,7 +81,7 @@ class XMLBuilder(Builder):
f.write(self.writer.output)
finally:
f.close()
- except (IOError, OSError), err:
+ except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (outfilename, err))
def finish(self):
diff --git a/sphinx/cmdline.py b/sphinx/cmdline.py
index 97f9718b..12190833 100644
--- a/sphinx/cmdline.py
+++ b/sphinx/cmdline.py
@@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import os
import sys
@@ -28,9 +29,9 @@ from sphinx.util.pycompat import terminal_safe, bytes
def usage(argv, msg=None):
if msg:
- print >>sys.stderr, msg
- print >>sys.stderr
- print >>sys.stderr, """\
+ print(msg, file=sys.stderr)
+ print(file=sys.stderr)
+ print("""\
Sphinx v%s
Usage: %s [options] sourcedir outdir [filenames...]
@@ -75,7 +76,7 @@ Standard options
^^^^^^^^^^^^^^^^
-h, --help show this help and exit
--version show version information and exit
-""" % (__version__, argv[0])
+""" % (__version__, argv[0]), file=sys.stderr)
def main(argv):
@@ -87,6 +88,7 @@ def main(argv):
try:
opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:nNEqQWw:PThvj:',
['help', 'version'])
+<<<<<<< local
except getopt.error, err:
usage(argv, 'Error: %s' % err)
return 1
@@ -105,24 +107,47 @@ def main(argv):
# get paths (first and second positional argument)
try:
+=======
+ allopts = set(opt[0] for opt in opts)
+ if '-h' in allopts or '--help' in allopts:
+ usage(argv)
+ print(file=sys.stderr)
+ print('For more information, see <http://sphinx-doc.org/>.',
+ file=sys.stderr)
+ return 0
+ if '--version' in allopts:
+ print('Sphinx (sphinx-build) %s' % __version__)
+ return 0
+>>>>>>> other
srcdir = confdir = abspath(args[0])
if not path.isdir(srcdir):
- print >>sys.stderr, 'Error: Cannot find source directory `%s\'.' % (
- srcdir,)
+ print('Error: Cannot find source directory `%s\'.' % srcdir,
+ file=sys.stderr)
return 1
if not path.isfile(path.join(srcdir, 'conf.py')) and \
'-c' not in allopts and '-C' not in allopts:
+<<<<<<< local
print >>sys.stderr, ('Error: Source directory doesn\'t '
'contain a conf.py file.')
+=======
+ print('Error: Source directory doesn\'t contain conf.py file.',
+ file=sys.stderr)
+>>>>>>> other
return 1
outdir = abspath(args[1])
+<<<<<<< local
+=======
+ except getopt.error as err:
+ usage(argv, 'Error: %s' % err)
+ return 1
+>>>>>>> other
except IndexError:
usage(argv, 'Error: Insufficient arguments.')
return 1
except UnicodeError:
- print >>sys.stderr, (
+ print(
'Error: Multibyte filename not supported on this filesystem '
- 'encoding (%r).' % fs_encoding)
+ 'encoding (%r).' % fs_encoding, file=sys.stderr)
return 1
# handle remaining filename arguments
@@ -130,7 +155,7 @@ def main(argv):
err = 0
for filename in filenames:
if not path.isfile(filename):
- print >>sys.stderr, 'Error: Cannot find file %r.' % filename
+ print('Error: Cannot find file %r.' % filename, file=sys.stderr)
err = 1
if err:
return 1
@@ -169,8 +194,8 @@ def main(argv):
elif opt == '-c':
confdir = abspath(val)
if not path.isfile(path.join(confdir, 'conf.py')):
- print >>sys.stderr, ('Error: Configuration directory '
- 'doesn\'t contain conf.py file.')
+ print('Error: Configuration directory doesn\'t contain conf.py file.',
+ file=sys.stderr)
return 1
elif opt == '-C':
confdir = None
@@ -178,8 +203,8 @@ def main(argv):
try:
key, val = val.split('=')
except ValueError:
- print >>sys.stderr, ('Error: -D option argument must be '
- 'in the form name=value.')
+ print('Error: -D option argument must be in the form name=value.',
+ file=sys.stderr)
return 1
if likely_encoding and isinstance(val, bytes):
try:
@@ -191,8 +216,8 @@ def main(argv):
try:
key, val = val.split('=')
except ValueError:
- print >>sys.stderr, ('Error: -A option argument must be '
- 'in the form name=value.')
+ print('Error: -A option argument must be in the form name=value.',
+ file=sys.stderr)
return 1
try:
val = int(val)
@@ -229,8 +254,8 @@ def main(argv):
try:
parallel = int(val)
except ValueError:
- print >>sys.stderr, ('Error: -j option argument must be an '
- 'integer.')
+ print('Error: -j option argument must be an integer.',
+ file=sys.stderr)
return 1
if warning and warnfile:
@@ -240,7 +265,7 @@ def main(argv):
if not path.isdir(outdir):
if status:
- print >>status, 'Making output directory...'
+ print('Making output directory...', file=status)
os.makedirs(outdir)
app = None
@@ -250,24 +275,25 @@ def main(argv):
warningiserror, tags, verbosity, parallel)
app.build(force_all, filenames)
return app.statuscode
- except (Exception, KeyboardInterrupt), err:
+ except (Exception, KeyboardInterrupt) as err:
if use_pdb:
import pdb
- print >>error, red('Exception occurred while building, '
- 'starting debugger:')
+ print(red('Exception occurred while building, starting debugger:'),
+ file=error)
traceback.print_exc()
pdb.post_mortem(sys.exc_info()[2])
else:
- print >>error
+ print(file=error)
if show_traceback:
traceback.print_exc(None, error)
- print >>error
+ print(file=error)
if isinstance(err, KeyboardInterrupt):
- print >>error, 'interrupted!'
+ print('interrupted!', file=error)
elif isinstance(err, SystemMessage):
- print >>error, red('reST markup error:')
- print >>error, terminal_safe(err.args[0])
+ print(red('reST markup error:'), file=error)
+ print(terminal_safe(err.args[0]), file=error)
elif isinstance(err, SphinxError):
+<<<<<<< local
print >>error, red('%s:' % err.category)
print >>error, terminal_safe(unicode(err))
elif isinstance(err, UnicodeError):
@@ -277,19 +303,23 @@ def main(argv):
print >>error, red('The full traceback has been saved '
'in %s, if you want to report the '
'issue to the developers.' % tbpath)
+=======
+ print(red('%s:' % err.category), file=error)
+ print(terminal_safe(unicode(err)), file=error)
+>>>>>>> other
else:
- print >>error, red('Exception occurred:')
- print >>error, format_exception_cut_frames().rstrip()
+ print(red('Exception occurred:'), file=error)
+ print(format_exception_cut_frames().rstrip(), file=error)
tbpath = save_traceback(app)
- print >>error, red('The full traceback has been saved '
- 'in %s, if you want to report the '
- 'issue to the developers.' % tbpath)
- print >>error, ('Please also report this if it was a user '
- 'error, so that a better error message '
- 'can be provided next time.')
- print >>error, (
- 'Either send bugs to the mailing list at '
- '<http://groups.google.com/group/sphinx-users/>,\n'
- 'or report them in the tracker at '
- '<http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!')
+ print(red('The full traceback has been saved in %s, if you '
+ 'want to report the issue to the developers.' % tbpath),
+ file=error)
+ print('Please also report this if it was a user error, so '
+ 'that a better error message can be provided next time.',
+ file=error)
+ print('Either send bugs to the mailing list at '
+ '<http://groups.google.com/group/sphinx-users/>,\n'
+ 'or report them in the tracker at '
+ '<http://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!',
+ file=error)
return 1
diff --git a/sphinx/config.py b/sphinx/config.py
index ace5f2a6..127425ae 100644
--- a/sphinx/config.py
+++ b/sphinx/config.py
@@ -226,7 +226,7 @@ class Config(object):
os.chdir(dirname)
try:
execfile_(filename, config)
- except SyntaxError, err:
+ except SyntaxError as err:
raise ConfigError(CONFIG_SYNTAX_ERROR % err)
finally:
os.chdir(olddir)
diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py
index 6900ea6b..8b3faf52 100644
--- a/sphinx/directives/code.py
+++ b/sphinx/directives/code.py
@@ -39,7 +39,7 @@ class Highlight(Directive):
except Exception:
linenothreshold = 10
else:
- linenothreshold = sys.maxint
+ linenothreshold = sys.maxsize
return [addnodes.highlightlang(lang=self.arguments[0].strip(),
linenothreshold=linenothreshold)]
@@ -69,7 +69,7 @@ class CodeBlock(Directive):
try:
nlines = len(self.content)
hl_lines = [x+1 for x in parselinenos(linespec, nlines)]
- except ValueError, err:
+ except ValueError as err:
document = self.state.document
return [document.reporter.warning(str(err), line=self.lineno)]
else:
@@ -167,7 +167,7 @@ class LiteralInclude(Directive):
if linespec is not None:
try:
linelist = parselinenos(linespec, len(lines))
- except ValueError, err:
+ except ValueError as err:
return [document.reporter.warning(str(err), line=self.lineno)]
# just ignore nonexisting lines
nlines = len(lines)
@@ -181,7 +181,7 @@ class LiteralInclude(Directive):
if linespec:
try:
hl_lines = [x+1 for x in parselinenos(linespec, len(lines))]
- except ValueError, err:
+ except ValueError as err:
return [document.reporter.warning(str(err), line=self.lineno)]
else:
hl_lines = None
diff --git a/sphinx/domains/c.py b/sphinx/domains/c.py
index 26e3c984..568dfad4 100644
--- a/sphinx/domains/c.py
+++ b/sphinx/domains/c.py
@@ -68,7 +68,7 @@ class CObject(ObjectDescription):
def _parse_type(self, node, ctype):
# add cross-ref nodes for all words
- for part in filter(None, wsplit_re.split(ctype)):
+ 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 \
part not in self.stopwords:
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index d44c9cd7..ef2460c1 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -1065,7 +1065,7 @@ class CPPObject(ObjectDescription):
try:
rv = self.parse_definition(parser)
parser.assert_end()
- except DefinitionError, e:
+ except DefinitionError as e:
self.state_machine.reporter.warning(e.description, line=self.lineno)
raise ValueError
self.describe_signature(signode, rv)
@@ -1219,7 +1219,7 @@ class CPPCurrentNamespace(Directive):
try:
prefix = parser.parse_type()
parser.assert_end()
- except DefinitionError, e:
+ except DefinitionError as e:
self.state_machine.reporter.warning(e.description,
line=self.lineno)
else:
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index 895e35e5..49dc61b4 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -522,7 +522,7 @@ class StandardDomain(Domain):
if labelid is None:
continue
node = document.ids[labelid]
- if name.isdigit() or node.has_key('refuri') or \
+ if name.isdigit() or 'refuri' in node or \
node.tagname.startswith('desc_'):
# ignore footnote labels, labels automatically generated from a
# link and object descriptions
diff --git a/sphinx/environment.py b/sphinx/environment.py
index c5726e29..320331af 100644
--- a/sphinx/environment.py
+++ b/sphinx/environment.py
@@ -611,8 +611,16 @@ class BuildEnvironment:
pub.process_programmatic_settings(None, self.settings, None)
pub.set_source(None, src_path.encode(fs_encoding))
pub.set_destination(None, None)
+<<<<<<< local
pub.publish()
doctree = pub.document
+=======
+ try:
+ pub.publish()
+ doctree = pub.document
+ except UnicodeError as err:
+ raise SphinxError(str(err))
+>>>>>>> other
# post-processing
self.filter_messages(doctree)
@@ -790,7 +798,7 @@ class BuildEnvironment:
imgtype = imghdr.what(f)
finally:
f.close()
- except (OSError, IOError), err:
+ except (OSError, IOError) as err:
self.warn_node('image file %s not readable: %s' %
(filename, err), node)
if imgtype:
@@ -901,7 +909,7 @@ class BuildEnvironment:
longtitlenode = titlenode
# explicit title set with title directive; use this only for
# the <title> tag in HTML output
- if document.has_key('title'):
+ if 'title' in document:
longtitlenode = nodes.title()
longtitlenode += nodes.Text(document['title'])
# look for first section title and use that as the title
@@ -1405,7 +1413,7 @@ class BuildEnvironment:
for node in doctree.traverse(addnodes.only):
try:
ret = builder.tags.eval_condition(node['expr'])
- except Exception, err:
+ except Exception as err:
self.warn_node('exception while evaluating only '
'directive expression: %s' % err, node)
node.replace_self(node.children or nodes.comment())
@@ -1531,7 +1539,7 @@ class BuildEnvironment:
add_entry(first, _('see also %s') % second, link=False)
else:
self.warn(fn, 'unknown index entry type %r' % type)
- except ValueError, err:
+ except ValueError as err:
self.warn(fn, str(err))
# sort the index entries; put all symbols at the front, even those
diff --git a/sphinx/ext/autodoc.py b/sphinx/ext/autodoc.py
index 86837ff8..69c7753b 100644
--- a/sphinx/ext/autodoc.py
+++ b/sphinx/ext/autodoc.py
@@ -443,7 +443,7 @@ class Documenter(object):
# try to introspect the signature
try:
args = self.format_args()
- except Exception, err:
+ except Exception as err:
self.directive.warn('error while formatting arguments for '
'%s: %s' % (self.fullname, err))
args = None
@@ -763,7 +763,7 @@ class Documenter(object):
# parse right now, to get PycodeErrors on parsing (results will
# be cached anyway)
self.analyzer.find_attr_docs()
- except PycodeError, err:
+ except PycodeError as err:
self.env.app.debug('[autodoc] module analyzer failed: %s', err)
# no source file -- e.g. for builtin and C modules
self.analyzer = None
@@ -1229,7 +1229,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter):
ret = ClassLevelDocumenter.import_object(self)
if isinstance(self.object, classmethod) or \
(isinstance(self.object, MethodType) and
- self.object.im_self is not None):
+ self.object.__self__ is not None):
self.directivetype = 'classmethod'
# document class and static members before ordinary ones
self.member_order = self.member_order - 1
@@ -1421,7 +1421,7 @@ class AutoDirective(Directive):
try:
self.genopt = Options(assemble_option_dict(
self.options.items(), doc_class.option_spec))
- except (KeyError, ValueError, TypeError), err:
+ except (KeyError, ValueError, TypeError) as err:
# an option is either unknown or has a wrong type
msg = self.reporter.error('An option to %s is either unknown or '
'has an invalid value: %s' % (self.name, err),
diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py
index af0fa65c..27cd21c4 100644
--- a/sphinx/ext/autosummary/__init__.py
+++ b/sphinx/ext/autosummary/__init__.py
@@ -465,7 +465,7 @@ def _import_by_name(name):
return obj, parent
else:
return sys.modules[modname], None
- except (ValueError, ImportError, AttributeError, KeyError), e:
+ except (ValueError, ImportError, AttributeError, KeyError) as e:
raise ImportError(*e.args)
diff --git a/sphinx/ext/autosummary/generate.py b/sphinx/ext/autosummary/generate.py
index f45aa085..605521c2 100644
--- a/sphinx/ext/autosummary/generate.py
+++ b/sphinx/ext/autosummary/generate.py
@@ -17,6 +17,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import os
import re
@@ -70,10 +71,10 @@ def main(argv=sys.argv):
template_dir=options.templates)
def _simple_info(msg):
- print msg
+ print(msg)
def _simple_warn(msg):
- print >> sys.stderr, 'WARNING: ' + msg
+ print('WARNING: ' + msg, file=sys.stderr)
# -- Generating output ---------------------------------------------------------
@@ -127,7 +128,7 @@ def generate_autosummary_docs(sources, output_dir=None, suffix='.rst',
try:
name, obj, parent = import_by_name(name)
- except ImportError, e:
+ except ImportError as e:
warn('[autosummary] failed to import %r: %s' % (name, e))
continue
@@ -240,8 +241,8 @@ def find_autosummary_in_docstring(name, module=None, filename=None):
return find_autosummary_in_lines(lines, module=name, filename=filename)
except AttributeError:
pass
- except ImportError, e:
- print "Failed to import '%s': %s" % (name, e)
+ except ImportError as e:
+ print("Failed to import '%s': %s" % (name, e))
return []
def find_autosummary_in_lines(lines, module=None, filename=None):
diff --git a/sphinx/ext/coverage.py b/sphinx/ext/coverage.py
index 0e8bc4b2..53f4a483 100644
--- a/sphinx/ext/coverage.py
+++ b/sphinx/ext/coverage.py
@@ -134,7 +134,7 @@ class CoverageBuilder(Builder):
try:
mod = __import__(mod_name, fromlist=['foo'])
- except ImportError, err:
+ except ImportError as err:
self.warn('module %s could not be imported: %s' %
(mod_name, err))
self.py_undoc[mod_name] = {'error': err}
diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py
index cd6cbf22..b21e8405 100644
--- a/sphinx/ext/doctest.py
+++ b/sphinx/ext/doctest.py
@@ -289,14 +289,14 @@ Doctest summary
if self.config.doctest_test_doctest_blocks:
def condition(node):
return (isinstance(node, (nodes.literal_block, nodes.comment))
- and node.has_key('testnodetype')) or \
+ and 'testnodetype' in node) or \
isinstance(node, nodes.doctest_block)
else:
def condition(node):
return isinstance(node, (nodes.literal_block, nodes.comment)) \
- and node.has_key('testnodetype')
+ and 'testnodetype' in node
for node in doctree.traverse(condition):
- source = node.has_key('test') and node['test'] or node.astext()
+ source = 'test' in node and node['test'] or node.astext()
if not source:
self.warn('no code/output in %s block at %s:%s' %
(node.get('testnodetype', 'doctest'),
diff --git a/sphinx/ext/graphviz.py b/sphinx/ext/graphviz.py
index 32bb96d3..c3096e3a 100644
--- a/sphinx/ext/graphviz.py
+++ b/sphinx/ext/graphviz.py
@@ -156,7 +156,7 @@ def render_dot(self, code, options, format, prefix='graphviz'):
dot_args.extend(['-Tcmapx', '-o%s.map' % outfn])
try:
p = Popen(dot_args, stdout=PIPE, stdin=PIPE, stderr=PIPE)
- except OSError, err:
+ except OSError as err:
if err.errno != ENOENT: # No such file or directory
raise
self.builder.warn('dot command %r cannot be run (needed for graphviz '
@@ -168,7 +168,7 @@ def render_dot(self, code, options, format, prefix='graphviz'):
# Graphviz may close standard input when an error occurs,
# resulting in a broken pipe on communicate()
stdout, stderr = p.communicate(code)
- except (OSError, IOError), err:
+ except (OSError, IOError) as err:
if err.errno not in (EPIPE, EINVAL):
raise
# in this case, read the standard output and standard error streams
@@ -192,7 +192,7 @@ def render_dot_html(self, node, code, options, prefix='graphviz',
raise GraphvizError("graphviz_output_format must be one of 'png', "
"'svg', but is %r" % format)
fname, outfn = render_dot(self, code, options, format, prefix)
- except GraphvizError, exc:
+ except GraphvizError as exc:
self.builder.warn('dot code %r: ' % code + str(exc))
raise nodes.SkipNode
@@ -243,7 +243,7 @@ def html_visit_graphviz(self, node):
def render_dot_latex(self, node, code, options, prefix='graphviz'):
try:
fname, outfn = render_dot(self, code, options, 'pdf', prefix)
- except GraphvizError, exc:
+ except GraphvizError as exc:
self.builder.warn('dot code %r: ' % code + str(exc))
raise nodes.SkipNode
@@ -276,7 +276,7 @@ def latex_visit_graphviz(self, node):
def render_dot_texinfo(self, node, code, options, prefix='graphviz'):
try:
fname, outfn = render_dot(self, code, options, 'png', prefix)
- except GraphvizError, exc:
+ except GraphvizError as exc:
self.builder.warn('dot code %r: ' % code + str(exc))
raise nodes.SkipNode
if fname is not None:
diff --git a/sphinx/ext/ifconfig.py b/sphinx/ext/ifconfig.py
index 2e219614..dadecf9e 100644
--- a/sphinx/ext/ifconfig.py
+++ b/sphinx/ext/ifconfig.py
@@ -53,7 +53,7 @@ def process_ifconfig_nodes(app, doctree, docname):
for node in doctree.traverse(ifconfig):
try:
res = eval(node['expr'], ns)
- except Exception, err:
+ except Exception as err:
# handle exceptions in a clean fashion
from traceback import format_exception_only
msg = ''.join(format_exception_only(err.__class__, err))
diff --git a/sphinx/ext/inheritance_diagram.py b/sphinx/ext/inheritance_diagram.py
index fd973544..3c194a0b 100644
--- a/sphinx/ext/inheritance_diagram.py
+++ b/sphinx/ext/inheritance_diagram.py
@@ -306,7 +306,7 @@ class InheritanceDiagram(Directive):
class_names, env.temp_data.get('py:module'),
parts=node['parts'],
private_bases='private-bases' in self.options)
- except InheritanceException, err:
+ except InheritanceException as err:
return [node.document.reporter.warning(err.args[0],
line=self.lineno)]
diff --git a/sphinx/ext/intersphinx.py b/sphinx/ext/intersphinx.py
index 193562b2..a83258de 100644
--- a/sphinx/ext/intersphinx.py
+++ b/sphinx/ext/intersphinx.py
@@ -132,7 +132,7 @@ def fetch_inventory(app, uri, inv):
f = urllib2.urlopen(inv)
else:
f = open(path.join(app.srcdir, inv), 'rb')
- except Exception, err:
+ except Exception as err:
app.warn('intersphinx inventory %r not fetchable due to '
'%s: %s' % (inv, err.__class__, err))
return
@@ -149,7 +149,7 @@ def fetch_inventory(app, uri, inv):
except ValueError:
f.close()
raise ValueError('unknown or unsupported inventory version')
- except Exception, err:
+ except Exception as err:
app.warn('intersphinx inventory %r not readable due to '
'%s: %s' % (inv, err.__class__.__name__, err))
else:
diff --git a/sphinx/ext/pngmath.py b/sphinx/ext/pngmath.py
index e23bbd06..c87c9a9c 100644
--- a/sphinx/ext/pngmath.py
+++ b/sphinx/ext/pngmath.py
@@ -123,7 +123,7 @@ def render_math(self, math):
try:
try:
p = Popen(ltx_args, stdout=PIPE, stderr=PIPE)
- except OSError, err:
+ except OSError as err:
if err.errno != ENOENT: # No such file or directory
raise
self.builder.warn('LaTeX command %r cannot be run (needed for math '
@@ -150,7 +150,7 @@ def render_math(self, math):
dvipng_args.append(path.join(tempdir, 'math.dvi'))
try:
p = Popen(dvipng_args, stdout=PIPE, stderr=PIPE)
- except OSError, err:
+ except OSError as err:
if err.errno != ENOENT: # No such file or directory
raise
self.builder.warn('dvipng command %r cannot be run (needed for math '
@@ -190,7 +190,7 @@ def get_tooltip(self, node):
def html_visit_math(self, node):
try:
fname, depth = render_math(self, '$'+node['latex']+'$')
- except MathExtError, exc:
+ except MathExtError as exc:
msg = unicode(exc)
sm = nodes.system_message(msg, type='WARNING', level=2,
backrefs=[], source=node['latex'])
@@ -215,7 +215,7 @@ def html_visit_displaymath(self, node):
latex = wrap_displaymath(node['latex'], None)
try:
fname, depth = render_math(self, latex)
- except MathExtError, exc:
+ except MathExtError as exc:
sm = nodes.system_message(str(exc), type='WARNING', level=2,
backrefs=[], source=node['latex'])
sm.walkabout(self)
diff --git a/sphinx/pycode/__init__.py b/sphinx/pycode/__init__.py
index 54e79da6..ca5e8b09 100644
--- a/sphinx/pycode/__init__.py
+++ b/sphinx/pycode/__init__.py
@@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import sys
from os import path
@@ -182,7 +183,7 @@ class ModuleAnalyzer(object):
return cls.cache['file', filename]
try:
fileobj = open(filename, 'rb')
- except Exception, err:
+ except Exception as err:
raise PycodeError('error opening %r' % filename, err)
obj = cls(fileobj, modname, filename)
cls.cache['file', filename] = obj
@@ -202,7 +203,7 @@ class ModuleAnalyzer(object):
obj = cls.for_string(source, modname)
else:
obj = cls.for_file(source, modname)
- except PycodeError, err:
+ except PycodeError as err:
cls.cache['module', modname] = err
raise
cls.cache['module', modname] = obj
@@ -245,7 +246,7 @@ class ModuleAnalyzer(object):
return
try:
self.tokens = list(tokenize.generate_tokens(self.source.readline))
- except tokenize.TokenError, err:
+ except tokenize.TokenError as err:
raise PycodeError('tokenizing failed', err)
self.source.close()
@@ -256,7 +257,7 @@ class ModuleAnalyzer(object):
self.tokenize()
try:
self.parsetree = pydriver.parse_tokens(self.tokens)
- except parse.ParseError, err:
+ except parse.ParseError as err:
raise PycodeError('parsing failed', err)
def find_attr_docs(self, scope=''):
@@ -344,4 +345,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/pgen2/driver.py b/sphinx/pycode/pgen2/driver.py
index 422671db..c531edb3 100644
--- a/sphinx/pycode/pgen2/driver.py
+++ b/sphinx/pycode/pgen2/driver.py
@@ -131,7 +131,7 @@ def load_grammar(gt="Grammar.txt", gp=None,
logger.info("Writing grammar tables to %s", gp)
try:
g.dump(gp)
- except IOError, e:
+ except IOError as e:
logger.info("Writing failed:"+str(e))
else:
g = grammar.Grammar()
diff --git a/sphinx/pycode/pgen2/grammar.py b/sphinx/pycode/pgen2/grammar.py
index 01d84346..91874fa2 100644
--- a/sphinx/pycode/pgen2/grammar.py
+++ b/sphinx/pycode/pgen2/grammar.py
@@ -11,6 +11,7 @@ token module; the Python tokenize module reports all operators as the
fallback token code OP, but the parser needs the actual token code.
"""
+from __future__ import print_function
# Python imports
import pickle
@@ -100,17 +101,17 @@ class Grammar(object):
def report(self):
"""Dump the grammar tables to standard output, for debugging."""
from pprint import pprint
- print "s2n"
+ print("s2n")
pprint(self.symbol2number)
- print "n2s"
+ print("n2s")
pprint(self.number2symbol)
- print "states"
+ print("states")
pprint(self.states)
- print "dfas"
+ print("dfas")
pprint(self.dfas)
- print "labels"
+ print("labels")
pprint(self.labels)
- print "start", self.start
+ print("start", self.start)
# Map from operator to number (since tokenize doesn't do this)
diff --git a/sphinx/pycode/pgen2/literals.py b/sphinx/pycode/pgen2/literals.py
index d4893702..ce4a0ebc 100644
--- a/sphinx/pycode/pgen2/literals.py
+++ b/sphinx/pycode/pgen2/literals.py
@@ -4,6 +4,7 @@
# Extended to handle raw and unicode literals by Georg Brandl.
"""Safely evaluate Python string literals without using eval()."""
+from __future__ import print_function
import re
@@ -89,7 +90,7 @@ def test():
s = repr(c)
e = evalString(s)
if e != c:
- print i, c, s, e
+ print(i, c, s, e)
if __name__ == "__main__":
diff --git a/sphinx/pycode/pgen2/pgen.py b/sphinx/pycode/pgen2/pgen.py
index 0a04447d..f572ad58 100644
--- a/sphinx/pycode/pgen2/pgen.py
+++ b/sphinx/pycode/pgen2/pgen.py
@@ -2,6 +2,7 @@
# Licensed to PSF under a Contributor Agreement.
# Pgen imports
+from __future__ import print_function
from sphinx.pycode.pgen2 import grammar, token, tokenize
class PgenGrammar(grammar.Grammar):
@@ -203,10 +204,10 @@ class ParserGenerator(object):
return states # List of DFAState instances; first one is start
def dump_nfa(self, name, start, finish):
- print "Dump of NFA for", name
+ print("Dump of NFA for", name)
todo = [start]
for i, state in enumerate(todo):
- print " State", i, state is finish and "(final)" or ""
+ print(" State", i, state is finish and "(final)" or "")
for label, next in state.arcs:
if next in todo:
j = todo.index(next)
@@ -214,16 +215,16 @@ class ParserGenerator(object):
j = len(todo)
todo.append(next)
if label is None:
- print " -> %d" % j
+ print(" -> %d" % j)
else:
- print " %s -> %d" % (label, j)
+ print(" %s -> %d" % (label, j))
def dump_dfa(self, name, dfa):
- print "Dump of DFA for", name
+ print("Dump of DFA for", name)
for i, state in enumerate(dfa):
- print " State", i, state.isfinal and "(final)" or ""
+ print(" State", i, state.isfinal and "(final)" or "")
for label, next in state.arcs.iteritems():
- print " %s -> %d" % (label, dfa.index(next))
+ print(" %s -> %d" % (label, dfa.index(next)))
def simplify_dfa(self, dfa):
# This is not theoretically optimal, but works well enough.
diff --git a/sphinx/pycode/pgen2/tokenize.py b/sphinx/pycode/pgen2/tokenize.py
index 7ad9f012..93fd6578 100644
--- a/sphinx/pycode/pgen2/tokenize.py
+++ b/sphinx/pycode/pgen2/tokenize.py
@@ -25,6 +25,8 @@ are the same, except instead of generating tokens, tokeneater is a callback
function to which the 5 fields described above are passed as 5 arguments,
each time a new token is found."""
+from __future__ import print_function
+
__author__ = 'Ka-Ping Yee <ping@lfw.org>'
__credits__ = \
'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
@@ -146,8 +148,8 @@ class StopTokenizing(Exception): pass
def printtoken(type, token, scell, ecell, line): # for testing
srow, scol = scell
erow, ecol = ecell
- print "%d,%d-%d,%d:\t%s\t%s" % \
- (srow, scol, erow, ecol, tok_name[type], repr(token))
+ print("%d,%d-%d,%d:\t%s\t%s" %
+ (srow, scol, erow, ecol, tok_name[type], repr(token)))
def tokenize(readline, tokeneater=printtoken):
"""
diff --git a/sphinx/quickstart.py b/sphinx/quickstart.py
index fd358532..a57006fd 100644
--- a/sphinx/quickstart.py
+++ b/sphinx/quickstart.py
@@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import sys, os, time, re
from os import path
@@ -965,9 +966,9 @@ def do_prompt(d, key, text, default=None, validator=nonempty):
if TERM_ENCODING:
prompt = prompt.encode(TERM_ENCODING)
else:
- print turquoise('* Note: non-ASCII default value provided '
+ print(turquoise('* Note: non-ASCII default value provided '
'and terminal encoding unknown -- assuming '
- 'UTF-8 or Latin-1.')
+ 'UTF-8 or Latin-1.'))
try:
prompt = prompt.encode('utf-8')
except UnicodeEncodeError:
@@ -982,17 +983,17 @@ def do_prompt(d, key, text, default=None, validator=nonempty):
if TERM_ENCODING:
x = x.decode(TERM_ENCODING)
else:
- print turquoise('* Note: non-ASCII characters entered '
+ print(turquoise('* Note: non-ASCII characters entered '
'and terminal encoding unknown -- assuming '
- 'UTF-8 or Latin-1.')
+ 'UTF-8 or Latin-1.'))
try:
x = x.decode('utf-8')
except UnicodeDecodeError:
x = x.decode('latin1')
try:
x = validator(x)
- except ValidationError, err:
- print red('* ' + str(err))
+ except ValidationError as err:
+ print(red('* ' + str(err)))
continue
break
d[key] = x
@@ -1030,110 +1031,110 @@ def ask_user(d):
* batchfile: make command file
"""
- print bold('Welcome to the Sphinx %s quickstart utility.') % __version__
- print '''
+ print(bold('Welcome to the Sphinx %s quickstart utility.') % __version__)
+ print('''
Please enter values for the following settings (just press Enter to
-accept a default value, if one is given in brackets).'''
+accept a default value, if one is given in brackets).''')
if 'path' in d:
- print bold('''
-Selected root path: %s''' % d['path'])
+ print(bold('''
+Selected root path: %s''' % d['path']))
else:
- print '''
-Enter the root path for documentation.'''
+ print('''
+Enter the root path for documentation.''')
do_prompt(d, 'path', 'Root path for the documentation', '.', is_path)
while path.isfile(path.join(d['path'], 'conf.py')) or \
path.isfile(path.join(d['path'], 'source', 'conf.py')):
- print
- print bold('Error: an existing conf.py has been found in the '
- 'selected root path.')
- print 'sphinx-quickstart will not overwrite existing Sphinx projects.'
- print
+ print()
+ print(bold('Error: an existing conf.py has been found in the '
+ 'selected root path.'))
+ print('sphinx-quickstart will not overwrite existing Sphinx projects.')
+ print()
do_prompt(d, 'path', 'Please enter a new root path (or just Enter '
'to exit)', '', is_path)
if not d['path']:
sys.exit(1)
if 'sep' not in d:
- print '''
+ print('''
You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
-"source" and "build" directories within the root path.'''
+"source" and "build" directories within the root path.''')
do_prompt(d, 'sep', 'Separate source and build directories (y/n)', 'n',
boolean)
if 'dot' not in d:
- print '''
+ print('''
Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
-files. You can enter another prefix (such as ".") to replace the underscore.'''
+files. You can enter another prefix (such as ".") to replace the underscore.''')
do_prompt(d, 'dot', 'Name prefix for templates and static dir', '_', ok)
if 'project' not in d:
- print '''
-The project name will occur in several places in the built documentation.'''
+ print('''
+The project name will occur in several places in the built documentation.''')
do_prompt(d, 'project', 'Project name')
if 'author' not in d:
do_prompt(d, 'author', 'Author name(s)')
if 'version' not in d:
- print '''
+ print('''
Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1. If you don't need this dual structure,
-just set both to the same value.'''
+just set both to the same value.''')
do_prompt(d, 'version', 'Project version')
if 'release' not in d:
do_prompt(d, 'release', 'Project release', d['version'])
if 'language' not in d:
- print '''
+ print('''
If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.
For a list of supported codes, see
-http://sphinx-doc.org/config.html#confval-language.'''
+http://sphinx-doc.org/config.html#confval-language.''')
do_prompt(d, 'language', 'Project language', 'en')
if d['language'] == 'en':
d['language'] = None
if 'suffix' not in d:
- print '''
+ print('''
The file name suffix for source files. Commonly, this is either ".txt"
-or ".rst". Only files with this suffix are considered documents.'''
+or ".rst". Only files with this suffix are considered documents.''')
do_prompt(d, 'suffix', 'Source file suffix', '.rst', suffix)
if 'master' not in d:
- print '''
+ print('''
One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
-document is a custom template, you can also set this to another filename.'''
+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'])):
- print
- print bold('Error: the master file %s has already been found in the '
- 'selected root path.' % (d['master']+d['suffix']))
- print 'sphinx-quickstart will not overwrite the existing file.'
- print
+ print()
+ print(bold('Error: the master file %s has already been found in the '
+ '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 '
'existing file and press Enter', d['master'])
if 'epub' not in d:
- print '''
-Sphinx can also add configuration for epub output:'''
+ print('''
+Sphinx can also add configuration for epub output:''')
do_prompt(d, 'epub', 'Do you want to use the epub builder (y/n)',
'n', boolean)
if 'ext_autodoc' not in d:
- print '''
-Please indicate if you want to use one of the following Sphinx extensions:'''
+ print('''
+Please indicate if you want to use one of the following Sphinx extensions:''')
do_prompt(d, 'ext_autodoc', 'autodoc: automatically insert docstrings '
'from modules (y/n)', 'n', boolean)
if 'ext_doctest' not in d:
@@ -1155,8 +1156,8 @@ Please indicate if you want to use one of the following Sphinx extensions:'''
do_prompt(d, 'ext_mathjax', 'mathjax: include math, rendered in the '
'browser by MathJax (y/n)', 'n', boolean)
if d['ext_pngmath'] and d['ext_mathjax']:
- print '''Note: pngmath and mathjax cannot be enabled at the same time.
-pngmath has been deselected.'''
+ print('''Note: pngmath and mathjax cannot be enabled at the same time.
+pngmath has been deselected.''')
if 'ext_ifconfig' not in d:
do_prompt(d, 'ext_ifconfig', 'ifconfig: conditional inclusion of '
'content based on config values (y/n)', 'n', boolean)
@@ -1165,15 +1166,15 @@ pngmath has been deselected.'''
'code of documented Python objects (y/n)', 'n', boolean)
if 'makefile' not in d:
- print '''
+ print('''
A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
-directly.'''
+directly.''')
do_prompt(d, 'makefile', 'Create Makefile? (y/n)', 'y', boolean)
if 'batchfile' not in d:
do_prompt(d, 'batchfile', 'Create Windows command file? (y/n)',
'y', boolean)
- print
+ print()
def generate(d, overwrite=True, silent=False):
@@ -1232,14 +1233,14 @@ def generate(d, overwrite=True, silent=False):
def write_file(fpath, content, newline=None):
if overwrite or not path.isfile(fpath):
- print 'Creating file %s.' % fpath
+ print('Creating file %s.' % fpath)
f = open(fpath, 'wt', encoding='utf-8', newline=newline)
try:
f.write(content)
finally:
f.close()
else:
- print 'File %s already exists, skipping.' % fpath
+ print('File %s already exists, skipping.' % fpath)
conf_text = QUICKSTART_CONF % d
if d['epub']:
@@ -1265,9 +1266,9 @@ def generate(d, overwrite=True, silent=False):
if silent:
return
- print
- print bold('Finished: An initial directory structure has been created.')
- print '''
+ print()
+ print(bold('Finished: An initial directory structure has been created.'))
+ print('''
You should now populate your master file %s and create other documentation
source files. ''' % masterfile + ((d['makefile'] or d['batchfile']) and '''\
Use the Makefile to build the docs, like so:
@@ -1277,7 +1278,7 @@ Use the sphinx-build command to build the docs, like so:
sphinx-build -b builder %s %s
''' % (srcdir, builddir)) + '''\
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.
-'''
+''')
def main(argv=sys.argv):
@@ -1286,14 +1287,14 @@ def main(argv=sys.argv):
d = {}
if len(argv) > 3:
- print 'Usage: sphinx-quickstart [root]'
+ print('Usage: sphinx-quickstart [root]')
sys.exit(1)
elif len(argv) == 2:
d['path'] = argv[1]
try:
ask_user(d)
except (KeyboardInterrupt, EOFError):
- print
- print '[Interrupted.]'
+ print()
+ print('[Interrupted.]')
return
generate(d)
diff --git a/sphinx/setup_command.py b/sphinx/setup_command.py
index 7999bf59..9a863611 100644
--- a/sphinx/setup_command.py
+++ b/sphinx/setup_command.py
@@ -11,6 +11,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import sys
import os
@@ -158,12 +159,12 @@ class BuildDoc(Command):
try:
app.build(force_all=self.all_files)
- except Exception, err:
+ except Exception as err:
from docutils.utils import SystemMessage
if isinstance(err, SystemMessage):
- print >>sys.stderr, darkred('reST markup error:')
- print >>sys.stderr, err.args[0].encode('ascii',
- 'backslashreplace')
+ print(darkred('reST markup error:'), file=sys.stderr)
+ print(err.args[0].encode('ascii',
+ 'backslashreplace'), file=sys.stderr)
else:
raise
diff --git a/sphinx/transforms.py b/sphinx/transforms.py
index e44a3d3e..c991f7f7 100644
--- a/sphinx/transforms.py
+++ b/sphinx/transforms.py
@@ -69,7 +69,7 @@ class MoveModuleTargets(Transform):
for node in self.document.traverse(nodes.target):
if not node['ids']:
continue
- if (node.has_key('ismod') and
+ if ('ismod' in node and
node.parent.__class__ is nodes.section and
# index 0 is the section title node
node.parent.index(node) == 1):
diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py
index a20fc19b..64fbae79 100644
--- a/sphinx/util/__init__.py
+++ b/sphinx/util/__init__.py
@@ -208,7 +208,7 @@ def get_module_source(modname):
if modname not in sys.modules:
try:
__import__(modname)
- except Exception, err:
+ except Exception as err:
raise PycodeError('error importing %r' % modname, err)
mod = sys.modules[modname]
filename = getattr(mod, '__file__', None)
@@ -216,12 +216,12 @@ def get_module_source(modname):
if loader and getattr(loader, 'get_filename', None):
try:
filename = loader.get_filename(modname)
- except Exception, err:
+ except Exception as err:
raise PycodeError('error getting filename for %r' % filename, err)
if filename is None and loader:
try:
return 'string', loader.get_source(modname)
- except Exception, err:
+ except Exception as err:
raise PycodeError('error getting source for %r' % modname, err)
if filename is None:
raise PycodeError('no source found for module %r' % modname)
diff --git a/sphinx/util/docfields.py b/sphinx/util/docfields.py
index 150bf3a1..e42d5c49 100644
--- a/sphinx/util/docfields.py
+++ b/sphinx/util/docfields.py
@@ -240,10 +240,8 @@ class DocFieldTransformer(object):
if is_typefield:
# filter out only inline nodes; others will result in invalid
# markup being written out
- content = filter(
- lambda n: isinstance(n, nodes.Inline) or
- isinstance(n, nodes.Text),
- content)
+ content = [n for n in content if isinstance(n, nodes.Inline) or
+ isinstance(n, nodes.Text)]
if content:
types.setdefault(typename, {})[fieldarg] = content
continue
diff --git a/sphinx/util/docstrings.py b/sphinx/util/docstrings.py
index d45b938d..97303bd7 100644
--- a/sphinx/util/docstrings.py
+++ b/sphinx/util/docstrings.py
@@ -23,7 +23,7 @@ def prepare_docstring(s, ignore=1):
"""
lines = s.expandtabs().splitlines()
# Find minimum indentation of any non-blank lines after ignored lines.
- margin = sys.maxint
+ margin = sys.maxsize
for line in lines[ignore:]:
content = len(line.lstrip())
if content:
@@ -33,7 +33,7 @@ def prepare_docstring(s, ignore=1):
for i in range(ignore):
if i < len(lines):
lines[i] = lines[i].lstrip()
- if margin < sys.maxint:
+ if margin < sys.maxsize:
for i in range(ignore, len(lines)): lines[i] = lines[i][margin:]
# Remove any leading blank lines.
while lines and not lines[0]:
diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py
index c7556d05..d835bc41 100644
--- a/sphinx/util/inspect.py
+++ b/sphinx/util/inspect.py
@@ -60,7 +60,7 @@ else: # 2.6, 2.7
def getargspec(func):
"""Like inspect.getargspec but supports functools.partial as well."""
if inspect.ismethod(func):
- func = func.im_func
+ func = func.__func__
parts = 0, ()
if type(func) is partial:
keywords = func.keywords
@@ -70,8 +70,8 @@ else: # 2.6, 2.7
func = func.func
if not inspect.isfunction(func):
raise TypeError('%r is not a Python function' % func)
- args, varargs, varkw = inspect.getargs(func.func_code)
- func_defaults = func.func_defaults
+ args, varargs, varkw = inspect.getargs(func.__code__)
+ func_defaults = func.__defaults__
if func_defaults is None:
func_defaults = []
else:
diff --git a/sphinx/util/matching.py b/sphinx/util/matching.py
index b4c71076..61059c7c 100644
--- a/sphinx/util/matching.py
+++ b/sphinx/util/matching.py
@@ -77,4 +77,4 @@ def patfilter(names, pat):
if pat not in _pat_cache:
_pat_cache[pat] = re.compile(_translate_pattern(pat))
match = _pat_cache[pat].match
- return filter(match, names)
+ return list(filter(match, names))
diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py
index a5c461a6..a0b669f1 100644
--- a/sphinx/util/osutil.py
+++ b/sphinx/util/osutil.py
@@ -8,6 +8,7 @@
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
import os
import re
@@ -63,7 +64,7 @@ def ensuredir(path):
"""Ensure that a path exists."""
try:
os.makedirs(path)
- except OSError, err:
+ except OSError as err:
# 0 for Jython/Win32
if err.errno not in [0, EEXIST]:
raise
@@ -83,9 +84,9 @@ def walk(top, topdown=True, followlinks=False):
try:
fullpath = path.join(top, name)
except UnicodeError:
- print >>sys.stderr, (
- '%s:: ERROR: non-ASCII filename not supported on this '
- 'filesystem encoding %r, skipped.' % (name, fs_encoding))
+ print('%s:: ERROR: non-ASCII filename not supported on this '
+ 'filesystem encoding %r, skipped.' % (name, fs_encoding),
+ file=sys.stderr)
continue
if path.isdir(fullpath):
dirs.append(name)
diff --git a/sphinx/util/pycompat.py b/sphinx/util/pycompat.py
index 9941dc0c..4c9ef18d 100644
--- a/sphinx/util/pycompat.py
+++ b/sphinx/util/pycompat.py
@@ -41,7 +41,7 @@ if sys.version_info >= (3, 0):
source = refactoring_tool._read_python_source(filepath)[0]
try:
tree = refactoring_tool.refactor_string(source, 'conf.py')
- except ParseError, err:
+ except ParseError as err:
# do not propagate lib2to3 exceptions
lineno, offset = err.context[1]
# try to match ParseError details with SyntaxError details
diff --git a/sphinx/writers/html.py b/sphinx/writers/html.py
index 1e0c9f77..e5271cc4 100644
--- a/sphinx/writers/html.py
+++ b/sphinx/writers/html.py
@@ -70,7 +70,7 @@ class HTMLTranslator(BaseTranslator):
self.no_smarty = 0
self.builder = builder
self.highlightlang = builder.config.highlight_language
- self.highlightlinenothreshold = sys.maxint
+ self.highlightlinenothreshold = sys.maxsize
self.protect_literal_text = 0
self.permalink_text = builder.config.html_add_permalinks
# support backwards-compatible setting to a bool
@@ -260,11 +260,11 @@ class HTMLTranslator(BaseTranslator):
linenos = node.rawsource.count('\n') >= \
self.highlightlinenothreshold - 1
highlight_args = node.get('highlight_args', {})
- if node.has_key('language'):
+ if 'language' in node:
# code-block directives
lang = node['language']
highlight_args['force'] = True
- if node.has_key('linenos'):
+ if 'linenos' in node:
linenos = node['linenos']
def warner(msg):
self.builder.warn(msg, (self.builder.current_docname, node.line))
@@ -373,13 +373,13 @@ class HTMLTranslator(BaseTranslator):
if node['uri'].lower().endswith('svg') or \
node['uri'].lower().endswith('svgz'):
atts = {'src': node['uri']}
- if node.has_key('width'):
+ if 'width' in node:
atts['width'] = node['width']
- if node.has_key('height'):
+ if 'height' in node:
atts['height'] = node['height']
- if node.has_key('alt'):
+ if 'alt' in node:
atts['alt'] = node['alt']
- if node.has_key('align'):
+ if 'align' in node:
self.body.append('<div align="%s" class="align-%s">' %
(node['align'], node['align']))
self.context.append('</div>\n')
@@ -388,21 +388,21 @@ class HTMLTranslator(BaseTranslator):
self.body.append(self.emptytag(node, 'img', '', **atts))
return
- if node.has_key('scale'):
+ if 'scale' in node:
# Try to figure out image height and width. Docutils does that too,
# but it tries the final file name, which does not necessarily exist
# yet at the time the HTML file is written.
- if Image and not (node.has_key('width')
- and node.has_key('height')):
+ if Image and not ('width' in node
+ and 'height' in node):
try:
im = Image.open(os.path.join(self.builder.srcdir, olduri))
except (IOError, # Source image can't be found or opened
UnicodeError): # PIL doesn't like Unicode paths.
pass
else:
- if not node.has_key('width'):
+ if 'width' not in node:
node['width'] = str(im.size[0])
- if not node.has_key('height'):
+ if 'height' not in node:
node['height'] = str(im.size[1])
del im
BaseTranslator.visit_image(self, node)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 61aa5828..1c915431 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -248,7 +248,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
# the second item is the default for the master file and can be changed
# by .. highlight:: directive in the master file
self.hlsettingstack = 2 * [[builder.config.highlight_language,
- sys.maxint]]
+ sys.maxsize]]
self.footnotestack = []
self.curfilestack = []
self.handled_abbrs = set()
@@ -1152,7 +1152,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
else:
self.builder.warn(
'unknown index entry type %s found' % type)
- except ValueError, err:
+ except ValueError as err:
self.builder.warn(str(err))
raise nodes.SkipNode
diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py
index a930a525..e5d19127 100644
--- a/sphinx/writers/texinfo.py
+++ b/sphinx/writers/texinfo.py
@@ -655,7 +655,7 @@ class TexinfoTranslator(nodes.NodeVisitor):
def visit_reference(self, node):
# an xref's target is displayed in Info so we ignore a few
# cases for the sake of appearance
- if isinstance(node.parent, (nodes.title, addnodes.desc_type,)):
+ if isinstance(node.parent, (nodes.title, addnodes.desc_type)):
return
if isinstance(node[0], nodes.image):
return
diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py
index a174bc26..3efeac97 100644
--- a/sphinx/writers/text.py
+++ b/sphinx/writers/text.py
@@ -459,7 +459,7 @@ class TextTranslator(nodes.NodeVisitor):
pass
def visit_entry(self, node):
- if node.has_key('morerows') or node.has_key('morecols'):
+ if 'morerows' in node or 'morecols' in node:
raise NotImplementedError('Column or row spanning cells are '
'not implemented.')
self.new_state(0)