merge with stable
diff --git a/AUTHORS b/AUTHORS
index 2a9dbba..ce4f4bf 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -3,6 +3,15 @@
 Substantial parts of the templates were written by Armin Ronacher
 <armin.ronacher@active-4.com>.
 
+Other co-maintainers:
+
+* Takayuki Shimizukawa <shimizukawa@gmail.com>
+* Daniel Neuhäuser <@DasIch>
+* Jon Waltman <@jonwaltman>
+* Rob Ruana <@RelentlessIdiot>
+* Robert Lehmann <@lehmannro>
+* Roland Meister <@rolmei>
+
 Other contributors, listed alphabetically, are:
 
 * Andi Albrecht -- agogo theme
@@ -32,6 +41,7 @@
 * Christopher Perkins -- autosummary integration
 * Benjamin Peterson -- unittests
 * T. Powers -- HTML output improvements
+* Rob Ruana -- napoleon extension
 * Stefan Seefeld -- toctree improvements
 * Shibukawa Yoshiki -- pluggable search API and Japanese search
 * Antonio Valentino -- qthelp builder
diff --git a/CHANGES b/CHANGES
index a0aa269..6279c44 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,17 +1,236 @@
-Release 1.2.4 (in development)
-==============================
+Release 1.3 (in development)
+============================
+
+Incompatible changes
+--------------------
+
+* Dropped support for Python 2.5, 3.1 and 3.2.
+* Dropped support for docutils versions up to 0.9.
+* Removed the ``sphinx.ext.oldcmarkup`` extension.
+* The deprecated config values ``exclude_trees``, ``exclude_dirnames`` and
+  ``unused_docs`` have been removed.
+* A new node, ``sphinx.addnodes.literal_strong``, has been added, for text that
+  should appear literally (i.e. no smart quotes) in strong font.  Custom writers
+  will have to be adapted to handle this node.
+* PR#269, #1476: replace `<tt>` tag by `<code>`. User customized stylesheets
+  should be updated If the css contain some styles for `<tt>` tag.
+  Thanks to Takeshi Komiya.
+* #1543: :confval:`templates_path` is automatically added to
+  :confval:`exclude_patterns` to avoid reading autosummary rst templates in the
+  templates directory.
 
 Features added
 --------------
 
+* Add support for Python 3.4.
+* Add support for docutils 0.12
+* Added ``sphinx.ext.napoleon`` extension for NumPy and Google style docstring
+  support.
 * Exception logs now contain the last 10 messages emitted by Sphinx.
+* Added support for extension versions (a string returned by ``setup()``, these
+  can be shown in the traceback log files).  Version requirements for extensions
+  can be specified in projects using the new :confval:`needs_extensions` config
+  value.
+* PR#214: Added stemming support for 14 languages, so that the built-in document
+  search can now handle these.  Thanks to Shibukawa Yoshiki.
+* PR#202: Allow "." and "~" prefixed references in ``:param:`` doc fields
+  for Python.
+* PR#184: Add :confval:`autodoc_mock_imports`, allowing to mock imports of
+  external modules that need not be present when autodocumenting.
+* #925: Allow list-typed config values to be provided on the command line,
+  like ``-D key=val1,val2``.
+* #668: Allow line numbering of ``code-block`` and ``literalinclude`` directives
+  to start at an arbitrary line number, with a new ``lineno-start`` option.
+* PR#172, PR#266: The :rst:dir:`code-block` and :rst:dir:`literalinclude`
+  directives now can have a ``caption`` option that shows a filename before the
+  code in the output. Thanks to Nasimul Haque, Takeshi Komiya.
+* Prompt for the document language in sphinx-quickstart.
+* PR#217: Added config values to suppress UUID and location information in
+  generated gettext catalogs.
+* PR#236, #1456: apidoc: Add a -M option to put module documentation before
+  submodule documentation. Thanks to Wes Turner and Luc Saffre.
+* #1434: Provide non-minified JS files for jquery.js and underscore.js to
+  clarify the source of the minified files.
+* PR#252, #1291: Windows color console support. Thanks to meu31.
+* PR#255: When generating latex references, also insert latex target/anchor
+  for the ids defined on the node. Thanks to Olivier Heurtier.
+* PR#229: Allow registration of other translators. Thanks to Russell Sim.
+* Add app.set_translator() API to register or override a Docutils translator
+  class like :confval:`html_translator_class`.
+* PR#267, #1134: add 'diff' parameter to literalinclude. Thanks to Richard Wall
+  and WAKAYAMA shirou.
+* PR#272: Added 'bizstyle' theme. Thanks to Shoji KUMAGAI.
+* Automatically compile ``*.mo`` files from ``*.po`` files when
+  :confval:`gettext_auto_build` is True (default) and ``*.po`` is newer than
+  ``*.mo`` file.
+* #623: :mod:`~sphinx.ext.viewcode` supports imported function/class aliases.
+* PR#275: :mod:`~sphinx.ext.intersphinx` supports multiple target for the
+  inventory. Thanks to Brigitta Sipocz.
 
 Bugs fixed
 ----------
 
+* #1568: fix a crash when a "centered" directive contains a reference.
 * #1563: :meth:`~sphinx.application.Sphinx.add_search_language` raises
   AssertionError for correct type of argument. Thanks to rikoman.
-* #1568: fix a crash when a "centered" directive contains a reference.  
+* #1174: Fix smart quotes being applied inside roles like :rst:role:`program` or
+  :rst:role:`makevar`.
+* #1335: Fix autosummary template overloading with exclamation prefix like
+  ``{% extends "!autosummary/class.rst" %}`` cause infinite recursive function
+  call. This was caused by PR#181.
+* #1337: Fix autodoc with ``autoclass_content="both"`` uses useless
+  ``object.__init__`` docstring when class does not have ``__init__``.
+  This was caused by a change for #1138.
+* #1340: Can't search alphabetical words on the HTML quick search generated
+  with language='ja'.
+* #1319: Do not crash if the :confval:`html_logo` file does not exist.
+* #603: Do not use the HTML-ized title for building the search index (that
+  resulted in "literal" being found on every page with a literal in the
+  title).
+* #751: Allow production lists longer than a page in LaTeX by using longtable.
+* #764: Always look for stopwords lowercased in JS search.
+* #814: autodoc: Guard against strange type objects that don't have
+  ``__bases__``.
+* #932: autodoc: Do not crash if ``__doc__`` is not a string.
+* #933: Do not crash if an :rst:role:`option` value is malformed (contains
+  spaces but no option name).
+* #908: On Python 3, handle error messages from LaTeX correctly in the pngmath
+  extension.
+* #943: In autosummary, recognize "first sentences" to pull from the docstring
+  if they contain uppercase letters.
+* #923: Take the entire LaTeX document into account when caching
+  pngmath-generated images.  This rebuilds them correctly when
+  :confval:`pngmath_latex_preamble` changes.
+* #901: Emit a warning when using docutils' new "math" markup without a Sphinx
+  math extension active.
+* #845: In code blocks, when the selected lexer fails, display line numbers
+  nevertheless if configured.
+* #929: Support parsed-literal blocks in LaTeX output correctly.
+* #949: Update the tabulary.sty packed with Sphinx.
+* #1050: Add anonymous labels into ``objects.inv`` to be referenced via
+  :mod:`~sphinx.ext.intersphinx`.
+* #1095: Fix print-media stylesheet being included always in the "scrolls"
+  theme.
+* #1085: Fix current classname not getting set if class description has
+  ``:noindex:`` set.
+* #1181: Report option errors in autodoc directives more gracefully.
+* #1155: Fix autodocumenting C-defined methods as attributes in Python 3.
+* #1233: Allow finding both Python classes and exceptions with the "class" and
+  "exc" roles in intersphinx.
+* #1198: Allow "image" for the "figwidth" option of the :rst:dir:`figure`
+  directive as documented by docutils.
+* #1152: Fix pycode parsing errors of Python 3 code by including two grammar
+  versions for Python 2 and 3, and loading the appropriate version for the
+  running Python version.
+* #1017: Be helpful and tell the user when the argument to :rst:dir:`option`
+  does not match the required format.
+* #1345: Fix two bugs with :confval:`nitpick_ignore`; now you don't have to
+  remove the store environment for changes to have effect.
+* #1072: In the JS search, fix issues searching for upper-cased words by
+  lowercasing words before stemming.
+* #1299: Make behavior of the :rst:dir:`math` directive more consistent and
+  avoid producing empty environments in LaTeX output.
+* #1308: Strip HTML tags from the content of "raw" nodes before feeding it
+  to the search indexer.
+* #1249: Fix duplicate LaTeX page numbering for manual documents.
+* #1292: In the linkchecker, retry HEAD requests when denied by HTTP 405.
+  Also make the redirect code apparent and tweak the output a bit to be
+  more obvious.
+* #1285: Avoid name clashes between C domain objects and section titles.
+* #848: Always take the newest code in incremental rebuilds with the
+  :mod:`sphinx.ext.viewcode` extension.
+* #979, #1266: Fix exclude handling in ``sphinx-apidoc``.
+* #1302: Fix regression in :mod:`sphinx.ext.inheritance_diagram` when
+  documenting classes that can't be pickled.
+* #1316: Remove hard-coded ``font-face`` resources from epub theme.
+* #1329: Fix traceback with empty translation msgstr in .po files.
+* #1300: Fix references not working in translated documents in some instances.
+* #1283: Fix a bug in the detection of changed files that would try to access
+  doctrees of deleted documents.
+* #1330: Fix :confval:`exclude_patterns` behavior with subdirectories in the
+  :confval:`html_static_path`.
+* #1323: Fix emitting empty ``<ul>`` tags in the HTML writer, which is not
+  valid HTML.
+* #1147: Don't emit a sidebar search box in the "singlehtml" builder.
+* PR#211: When checking for existence of the :confval:`html_logo` file, check
+  the full relative path and not the basename.
+* #1357: Option names documented by :rst:dir:`option` are now again allowed to
+  not start with a dash or slash, and referencing them will work correctly.
+* #1358: Fix handling of image paths outside of the source directory when using
+  the "wildcard" style reference.
+* #1374: Fix for autosummary generating overly-long summaries if first line
+  doesn't end with a period.
+* #1391: Actually prevent using "pngmath" and "mathjax" extensions at the same
+  time in sphinx-quickstart.
+* #1386: Fix bug preventing more than one theme being added by the entry point
+  mechanism.
+* #1370: Ignore "toctree" nodes in text writer, instead of raising.
+* #1364: Fix 'make gettext' fails when the '.. todolist::' directive is present.
+* #1367: Fix a change of PR#96 that break sphinx.util.docfields.Field.make_field
+  interface/behavior for `item` argument usage.
+* #1363: Fix i18n: missing python domain's cross-references with currentmodule
+  directive or currentclass directive.
+* #1419: Generated i18n sphinx.js files are missing message catalog entries
+  from '.js_t' and '.html'. The issue was introduced in Sphinx 1.1.
+* #636: Keep straight single quotes in literal blocks in the LaTeX build.
+* PR#235: comment db schema of websupport lacked a length of the node_id field.
+  Thanks to solos.
+* #1466,PR#241: Fix failure of the cpp domain parser to parse C+11
+  "variadic templates" declarations. Thanks to Victor Zverovich.
+* #1459,PR#244: Fix default mathjax js path point to `http://` that cause
+  mixed-content error on HTTPS server. Thanks to sbrandtb and robo9k.
+* PR#157: autodoc remove spurious signatures from @property decorated
+  attributes. Thanks to David Ham.
+* PR#159: Add coverage targets to quickstart generated Makefile and make.bat.
+  Thanks to Matthias Troffaes.
+* #1251: When specifying toctree :numbered: option and :tocdepth: metadata,
+  sub section number that is larger depth than `:tocdepth:` is shrinked.
+* PR#260: Encode underscore in citation labels for latex export. Thanks to
+  Lennart Fricke.
+* PR#264: Fix could not resolve xref for figure node with :name: option.
+  Thanks to Takeshi Komiya.
+* PR#265: Fix could not capture caption of graphviz node by xref. Thanks to
+  Takeshi Komiya.
+* PR#263, #1013, #1103: Rewrite of C++ domain. Thanks to Jakob Lykke Andersen.
+
+  * Hyperlinks to all found nested names and template arguments (#1103).
+  * Support for function types everywhere, e.g., in
+    std::function<bool(int, int)> (#1013).
+  * Support for virtual functions.
+  * Changed interpretation of function arguments to following standard
+    prototype declarations, i.e., void f(arg) means that arg is the type of the
+    argument, instead of it being the name.
+  * Updated tests.
+  * Updated documentation with elaborate description of what declarations are
+    supported and how the namespace declarations influence declaration and
+    cross-reference lookup.
+  * Index names may be different now. Elements are indexed by their fully
+    qualified name. It should be rather easy to change this behaviour and
+    potentially index by namespaces/classes as well.
+
+* PR#258, #939: Add dedent option for :rst:dir:`code-block` and
+  :rst:dir:`literal-include`. Thanks to Zafar Siddiqui.
+* PR#268: Fix numbering section does not work at singlehtml mode. It still
+  ad-hoc fix because there is a issue that section IDs are conflicted.
+  Thanks to Takeshi Komiya.
+* PR#273, #1536: Fix RuntimeError with numbered circular toctree. Thanks to
+  Takeshi Komiya.
+* PR#274: Set its URL as a default title value if URL appears in toctree.
+  Thanks to Takeshi Komiya.
+* PR#276, #1381: :rst:role:`rfc` and :rst:role:`pep` roles support custom link
+  text. Thanks to Takeshi Komiya.
+* PR#277, #1513: highlights for function pointers in argument list of
+  :rst:dir:`c:function`. Thanks to Takeshi Komiya.
+* PR#278: Fix section entries were shown twice if toctree has been put under
+  only directive. Thanks to Takeshi Komiya.
+* #1547: pgen2 tokenizer doesn't recognize `...` literal (Ellipsis for py3).
+
+Documentation
+-------------
+
+* Add clarification about the syntax of tags. (:file:`doc/markup/misc.rst`)
+* #1325: Added a "Intersphinx" tutorial section. (:file:`doc/tutorial.rst`)
+* Extended the :ref:`documentation about building extensions <dev-extensions>`.
 
 
 Release 1.2.3 (released Sep 1, 2014)
@@ -420,7 +639,7 @@
   - The :confval:`latex_documents`, :confval:`texinfo_documents`, and
     :confval:`man_pages` configuration values will be set to default values based
     on the :confval:`master_doc` if not explicitly set in :file:`conf.py`.
-    Previously, if these values were not set, no output would be genereted by
+    Previously, if these values were not set, no output would be generated by
     their respective builders.
 
 * Internationalization:
@@ -461,7 +680,7 @@
   - sphinx-build now provides more specific error messages when called with
     invalid options or arguments.
   - sphinx-build now has a verbose option :option:`-v` which can be repeated for
-    greater effect.  A single occurrance provides a slightly more verbose output
+    greater effect.  A single occurrence provides a slightly more verbose output
     than normal.  Two or more occurrences of this option provides more detailed
     output which may be useful for debugging.
 
@@ -921,7 +1140,7 @@
 * #515: Fix tracebacks in the viewcode extension for Python objects
   that do not have a valid signature.
 
-* Fix strange reportings of line numbers for warnings generated from
+* Fix strange reports of line numbers for warnings generated from
   autodoc-included docstrings, due to different behavior depending
   on docutils version.
 
diff --git a/EXAMPLES b/EXAMPLES
index cc4c4de..17143e9 100644
--- a/EXAMPLES
+++ b/EXAMPLES
@@ -22,18 +22,19 @@
 * Cormoran: http://cormoran.nhopkg.org/docs/
 * Director: http://pythonhosted.org/director/
 * Dirigible: http://www.projectdirigible.com/documentation/
-* Elemental: http://elemental.googlecode.com/hg/doc/build/html/index.html
 * F2py: http://f2py.sourceforge.net/docs/
 * GeoDjango: http://geodjango.org/docs/
-* Genomedata: http://noble.gs.washington.edu/proj/genomedata/doc/1.2.2/genomedata.html
+* Genomedata:
+  http://noble.gs.washington.edu/proj/genomedata/doc/1.2.2/genomedata.html
 * gevent: http://www.gevent.org/
-* Google Wave API: http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/index.html
+* Google Wave API:
+  http://wave-robot-python-client.googlecode.com/svn/trunk/pydocs/index.html
 * GSL Shell: http://www.nongnu.org/gsl-shell/
 * Heapkeeper: http://heapkeeper.org/
-* Hands-on Python Tutorial: http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/
+* Hands-on Python Tutorial:
+  http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/
 * Hedge: http://documen.tician.de/hedge/
-* Kaa: http://doc.freevo.org/api/kaa/
-* Leo: http://webpages.charter.net/edreamleo/front.html
+* Leo: http://leoeditor.com/
 * Lino: http://lino.saffre-rumma.net/
 * MeshPy: http://documen.tician.de/meshpy/
 * mpmath: http://mpmath.googlecode.com/svn/trunk/doc/build/index.html
@@ -41,13 +42,13 @@
 * OpenGDA: http://www.opengda.org/gdadoc/html/
 * openWNS: http://docs.openwns.org/
 * Paste: http://pythonpaste.org/script/
-* Paver: http://paver.github.com/paver/
+* Paver: http://paver.github.io/paver/
 * Pioneers and Prominent Men of Utah: http://pioneers.rstebbing.com/
 * Pyccuracy: https://github.com/heynemann/pyccuracy/wiki/
 * PyCuda: http://documen.tician.de/pycuda/
 * Pyevolve: http://pyevolve.sourceforge.net/
 * Pylo: http://documen.tician.de/pylo/
-* PyMQI: http://packages.python.org/pymqi/
+* PyMQI: http://pythonhosted.org/pymqi/
 * PyPubSub: http://pubsub.sourceforge.net/
 * pyrticle: http://documen.tician.de/pyrticle/
 * Python: http://docs.python.org/
@@ -59,7 +60,7 @@
 * SimPy: http://simpy.sourceforge.net/SimPyDocs/index.html
 * SymPy: http://docs.sympy.org/
 * WTForms: http://wtforms.simplecodes.com/docs/
-* z3c: http://docs.carduner.net/z3c-tutorial/
+* z3c: http://www.ibiblio.org/paulcarduner/z3ctutorial/
 
 
 Documentation using a customized version of the default theme
@@ -69,16 +70,19 @@
   http://xoomer.virgilio.it/infinity77/AGW_Docs/index.html
 * Bazaar: http://doc.bazaar.canonical.com/en/
 * CakePHP: http://book.cakephp.org/2.0/en/index.html
-* Chaco: http://code.enthought.com/projects/chaco/docs/html/
+* Chaco: http://docs.enthought.com/chaco/
 * Chef: http://docs.opscode.com/
 * Djagios: http://djagios.org/
 * GetFEM++: http://home.gna.org/getfem/
-* Google or-tools: https://or-tools.googlecode.com/svn/trunk/documentation/user_manual/index.html
+* Google or-tools:
+  https://or-tools.googlecode.com/svn/trunk/documentation/user_manual/index.html
 * GPAW: https://wiki.fysik.dtu.dk/gpaw/
 * Grok: http://grok.zope.org/doc/current/
 * IFM: http://fluffybunny.memebot.com/ifm-docs/index.html
+* Kaa: http://api.freevo.org/kaa-base/
 * LEPL: http://www.acooke.org/lepl/
-* Mayavi: http://code.enthought.com/projects/mayavi/docs/development/html/mayavi
+* Mayavi: http://docs.enthought.com/mayavi/mayavi/
+* NICOS: http://trac.frm2.tum.de/nicos/doc/nicos-master/index.html
 * NOC: http://redmine.nocproject.org/projects/noc
 * NumPy: http://docs.scipy.org/doc/numpy/reference/
 * OpenCV: http://docs.opencv.org/
@@ -92,7 +96,7 @@
 * Varnish: https://www.varnish-cache.org/docs/
 * Zentyal: http://doc.zentyal.org/
 * Zope: http://docs.zope.org/zope2/index.html
-* zc.async: http://packages.python.org/zc.async/1.5.0/
+* zc.async: http://pythonhosted.org/zc.async/1.5.0/
 
 
 Documentation using the sphinxdoc theme
@@ -100,20 +104,16 @@
 
 * Fityk: http://fityk.nieto.pl/
 * MapServer: http://mapserver.org/
-* Matplotlib: http://matplotlib.sourceforge.net/
-* Music21: http://mit.edu/music21/doc/html/contents.html
-* MyHDL: http://www.myhdl.org/doc/0.6/
-* NetworkX: http://networkx.lanl.gov/
+* Matplotlib: http://matplotlib.org/
+* Music21: http://web.mit.edu/music21/doc/index.html
+* NetworkX: http://networkx.github.io/
 * Pweave: http://mpastell.com/pweave/
 * Pyre: http://docs.danse.us/pyre/sphinx/
 * Pysparse: http://pysparse.sourceforge.net/
 * PyTango:
   http://www.tango-controls.org/static/PyTango/latest/doc/html/index.html
-* Python Wild Magic:
-  http://python-wild-magic.googlecode.com/svn/doc/html/index.html
+* Python Wild Magic: http://vmlaker.github.io/pythonwildmagic/
 * Reteisi: http://www.reteisi.org/contents.html
-* Satchmo: http://www.satchmoproject.com/docs/dev/
-* Sphinx: http://sphinx-doc.org/
 * Sqlkit: http://sqlkit.argolinux.org/
 * Tau: http://www.tango-controls.org/static/tau/latest/doc/html/index.html
 * Total Open Station: http://tops.berlios.de/
@@ -125,16 +125,17 @@
 -----------------------------------------
 
 * C/C++ Development with Eclipse: http://eclipsebook.in/ (agogo)
-* Distribute: http://packages.python.org/distribute/ (nature)
 * Jinja: http://jinja.pocoo.org/ (scrolls)
 * jsFiddle: http://doc.jsfiddle.net/ (nature)
-* libLAS: http://liblas.org/ (nature)
+* libLAS: http://www.liblas.org/ (nature)
 * MPipe: http://vmlaker.github.io/mpipe/ (sphinx13)
 * pip: http://pip.openplans.org/ (nature)
+* Pyramid web framework:
+  http://docs.pylonsproject.org/projects/pyramid/en/latest/ (pyramid)
 * Programmieren mit PyGTK und Glade (German):
   http://www.florian-diesch.de/doc/python-und-glade/online/ (agogo)
-* Spring Python: http://springpython.webfactional.com/current/sphinx/index.html
-  (nature)
+* Setuptools: http://pythonhosted.org/setuptools/ (nature)
+* Spring Python: http://docs.spring.io/spring-python/1.2.x/sphinx/html/ (nature)
 * sqlparse: http://python-sqlparse.googlecode.com/svn/docs/api/index.html
   (agogo)
 * Sylli: http://sylli.sourceforge.net/ (nature)
@@ -151,35 +152,42 @@
 * Classy: http://classy.pocoo.org/
 * DEAP: http://deap.gel.ulaval.ca/doc/0.8/index.html
 * Django: http://docs.djangoproject.com/
-* Enterprise Toolkit for Acrobat products: http://www.adobe.com/devnet-docs/acrobatetk/
+* Elemental: http://libelemental.org/documentation/dev/index.html
+* Enterprise Toolkit for Acrobat products:
+  http://www.adobe.com/devnet-docs/acrobatetk/
 * e-cidadania: http://e-cidadania.readthedocs.org/en/latest/
 * Flask: http://flask.pocoo.org/docs/
-* Flask-OpenID: http://packages.python.org/Flask-OpenID/
+* Flask-OpenID: http://pythonhosted.org/Flask-OpenID/
 * Gameduino: http://excamera.com/sphinx/gameduino/
 * GeoServer: http://docs.geoserver.org/
 * Glashammer: http://glashammer.org/
-* Istihza (Turkish Python documentation project): http://www.istihza.com/py2/icindekiler_python.html
+* Istihza (Turkish Python documentation project):
+  http://www.istihza.com/py2/icindekiler_python.html
+* Lasso: http://lassoguide.com/
 * MathJax: http://docs.mathjax.org/en/latest/
 * MirrorBrain: http://mirrorbrain.org/docs/
-* nose: http://somethingaboutorange.com/mrl/projects/nose/
+* MyHDL: http://docs.myhdl.org/en/latest/
+* nose: http://nose.readthedocs.org/en/latest/
 * NoTex: https://notex.ch/overview/
-* ObjectListView: http://objectlistview.sourceforge.net/python
+* ObjectListView: http://objectlistview.sourceforge.net/python/
 * Open ERP: http://doc.openerp.com/
 * OpenCV: http://docs.opencv.org/
-* Open Dylan: http://opendylan.org/documentation/ and also provides
+* Open Dylan: http://opendylan.org/documentation/ and also provides a
   `dylan domain <https://github.com/dylan-lang/sphinx-extensions/blob/master/dylandomain/reference.rst>`__
 * OpenLayers: http://docs.openlayers.org/
 * PyEphem: http://rhodesmill.org/pyephem/
 * German Plone user manual: http://www.hasecke.com/plone-benutzerhandbuch/
 * PSI4: http://sirius.chem.vt.edu/psi4manual/latest/index.html
-* Pylons: http://pylonshq.com/docs/en/0.9.7/
-* PyMOTW: http://www.doughellmann.com/PyMOTW/
+* Pylons: http://docs.pylonsproject.org/projects/pylons-webframework/en/latest/
+* PyMOTW: http://pymotw.com/2/
 * pypol: http://pypol.altervista.org/ (celery)
-* QGIS: http://qgis.org/
-* qooxdoo: http://manual.qooxdoo.org/current
+* QGIS: http://qgis.org/en/docs/index.html
+* qooxdoo: http://manual.qooxdoo.org/current/
 * Roundup: http://www.roundup-tracker.org/
-* Selenium: http://seleniumhq.org/docs/
+* Satchmo: http://docs.satchmoproject.com/en/latest/
+* Selenium: http://docs.seleniumhq.org/docs/
 * Self: http://selflanguage.org/
+* Substance D: http://docs.pylonsproject.org/projects/substanced/en/latest/
 * Tablib: http://tablib.org/
 * SQLAlchemy: http://www.sqlalchemy.org/docs/
 * tinyTiM: http://tinytim.sourceforge.net/docs/2.0/
@@ -198,7 +206,8 @@
 * lunarsite: http://lunaryorn.de/
 * Red Hot Chili Python: http://redhotchilipython.com/
 * The Wine Cellar Book: http://www.thewinecellarbook.com/doc/en/
-* Uni. Berkeley Advanced Control Systems course: http://www.me.berkeley.edu/ME233/sp14/
+* UC Berkeley Advanced Control Systems course:
+  http://www.me.berkeley.edu/ME233/sp14/
 * VOR: http://www.vor-cycling.be/
 
 
@@ -224,6 +233,8 @@
   https://www.varnish-software.com/static/book/
 * "Learning Sphinx" (in Japanese):
   http://www.oreilly.co.jp/books/9784873116488/
+* "LassoGuide":
+  http://www.lassosoft.com/Lasso-Documentation
 
 
 Thesis using Sphinx
diff --git a/LICENSE b/LICENSE
index 7aa7620..c8a7928 100644
--- a/LICENSE
+++ b/LICENSE
@@ -244,3 +244,37 @@
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
+
+-------------------------------------------------------------------------------
+
+The included implementation of NumpyDocstring._parse_numpydoc_see_also_section
+was derived from code under the following license:
+
+-------------------------------------------------------------------------------
+
+Copyright (C) 2008 Stefan van der Walt <stefan@mentat.za.net>, Pauli Virtanen <pav@iki.fi>
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ 1. Redistributions of source code must retain the above copyright
+    notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+-------------------------------------------------------------------------------
diff --git a/MANIFEST.in b/MANIFEST.in
index 5db26b8..4cafcdc 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -19,7 +19,6 @@
 recursive-include sphinx/ext/autosummary/templates *
 recursive-include tests *
 recursive-include utils *
-recursive-include custom_fixers *
 include sphinx/pycode/Grammar-py2.txt
 include sphinx/pycode/Grammar-py3.txt
 
diff --git a/README.rst b/README.rst
index 5963a0a..9b22008 100644
--- a/README.rst
+++ b/README.rst
@@ -39,4 +39,17 @@
 Contributing
 ============
 
-Send wishes, comments, patches, etc. to sphinx-dev@googlegroups.com.
+#. Check for open issues or open a fresh issue to start a discussion around a
+   feature idea or a bug. There are Non Assigned issues:
+   https://bitbucket.org/birkenfeld/sphinx/issues?status=new&status=open&responsible=
+#. If you feel uncomfortable or uncertain about an issue or your changes, feel
+   free to email sphinx-dev@googlegroups.com.
+#. Fork the repository on Bitbucket https://bitbucket.org/birkenfeld/sphinx
+   to start making your changes to the **default** branch for next major
+   version, or **stable** branch for next minor version.
+#. Write a test which shows that the bug was fixed or that the feature works
+   as expected.
+#. Send a pull request and bug the maintainer until it gets merged and
+   published. Make sure to add yourself to AUTHORS
+   <https://bitbucket.org/birkenfeld/sphinx/src/tip/AUTHORS> and the change to
+   CHANGES <https://bitbucket.org/birkenfeld/sphinx/src/tip/CHANGES>.
diff --git a/custom_fixers/__init__.py b/custom_fixers/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/custom_fixers/__init__.py
+++ /dev/null
diff --git a/custom_fixers/fix_alt_unicode.py b/custom_fixers/fix_alt_unicode.py
deleted file mode 100644
index 55175e9..0000000
--- a/custom_fixers/fix_alt_unicode.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from lib2to3.fixer_base import BaseFix
-from lib2to3.fixer_util import Name
-
-class FixAltUnicode(BaseFix):
-    PATTERN = """
-    func=funcdef< 'def' name='__unicode__'
-                  parameters< '(' NAME ')' > any+ >
-    """
-
-    def transform(self, node, results):
-        name = results['name']
-        name.replace(Name('__str__', prefix=name.prefix))
diff --git a/doc/_static/bookcover.png b/doc/_static/bookcover.png
index 1c91f91..5b521b6 100644
--- a/doc/_static/bookcover.png
+++ b/doc/_static/bookcover.png
Binary files differ
diff --git a/doc/_static/pocoo.png b/doc/_static/pocoo.png
index eeb18ea..67663b9 100644
--- a/doc/_static/pocoo.png
+++ b/doc/_static/pocoo.png
Binary files differ
diff --git a/doc/_static/sphinx.png b/doc/_static/sphinx.png
index a4a3e1a..4bd9c75 100644
--- a/doc/_static/sphinx.png
+++ b/doc/_static/sphinx.png
Binary files differ
diff --git a/doc/_templates/index.html b/doc/_templates/index.html
index e6ef917..45581e0 100644
--- a/doc/_templates/index.html
+++ b/doc/_templates/index.html
@@ -97,4 +97,14 @@
     powerful built-in search that exceeds the possibilities of Sphinx' JavaScript-based
     offline search.{%endtrans%}</p>
 
+  <h2>{%trans%}Contributor Guide{%endtrans%}</h2>
+
+  <p>{%trans%}If you want to contribute to the project,
+    this part of the documentation is for you.{%endtrans%}</p>
+
+    <ul>
+      <li>{%trans path=pathto("devguide")%}<a href="{{ path }}">Sphinx Developer’s Guide</a></li>{%endtrans%}
+      <li>{%trans path=pathto("authors")%}<a href="{{ path }}">Sphinx Authors</a></li>{%endtrans%}
+    </ul>
+
 {% endblock %}
diff --git a/doc/_templates/indexsidebar.html b/doc/_templates/indexsidebar.html
index 4a350ae..019b20f 100644
--- a/doc/_templates/indexsidebar.html
+++ b/doc/_templates/indexsidebar.html
@@ -14,7 +14,7 @@
 <p>{%trans%}Current version: <b>{{ version }}</b>{%endtrans%}</p>
 <p>{%trans%}Get Sphinx from the <a href="http://pypi.python.org/pypi/Sphinx">Python Package
 Index</a>, or install it with:{%endtrans%}</p>
-<pre>easy_install -U Sphinx</pre>
+<pre>pip install -U Sphinx</pre>
 <p>{%trans%}Latest <a href="http://sphinx-doc.org/latest/">development version docs</a>
 are also available.{%endtrans%}</p>
 {% endif %}
diff --git a/doc/_themes/sphinx13/static/bodybg.png b/doc/_themes/sphinx13/static/bodybg.png
index 506b6f9..ebe92f6 100644
--- a/doc/_themes/sphinx13/static/bodybg.png
+++ b/doc/_themes/sphinx13/static/bodybg.png
Binary files differ
diff --git a/doc/_themes/sphinx13/static/footerbg.png b/doc/_themes/sphinx13/static/footerbg.png
index d1922b4..df783e2 100644
--- a/doc/_themes/sphinx13/static/footerbg.png
+++ b/doc/_themes/sphinx13/static/footerbg.png
Binary files differ
diff --git a/doc/_themes/sphinx13/static/headerbg.png b/doc/_themes/sphinx13/static/headerbg.png
index 6d3e1d5..22830f9 100644
--- a/doc/_themes/sphinx13/static/headerbg.png
+++ b/doc/_themes/sphinx13/static/headerbg.png
Binary files differ
diff --git a/doc/_themes/sphinx13/static/relbg.png b/doc/_themes/sphinx13/static/relbg.png
index 4722585..2006af7 100644
--- a/doc/_themes/sphinx13/static/relbg.png
+++ b/doc/_themes/sphinx13/static/relbg.png
Binary files differ
diff --git a/doc/_themes/sphinx13/static/sphinxheader.png b/doc/_themes/sphinx13/static/sphinxheader.png
index 2b33f09..12988c3 100644
--- a/doc/_themes/sphinx13/static/sphinxheader.png
+++ b/doc/_themes/sphinx13/static/sphinxheader.png
Binary files differ
diff --git a/doc/authors.rst b/doc/authors.rst
new file mode 100644
index 0000000..04c8b2b
--- /dev/null
+++ b/doc/authors.rst
@@ -0,0 +1,9 @@
+:tocdepth: 2

+

+.. _authors:

+

+Sphinx authors

+==============

+

+.. include:: ../AUTHORS

+

diff --git a/doc/builders.rst b/doc/builders.rst
index 333750e..3c6f6b9 100644
--- a/doc/builders.rst
+++ b/doc/builders.rst
@@ -153,11 +153,6 @@
 
    .. autoattribute:: supported_image_types
 
-   .. note::
-
-      This builder requires the docutils manual page writer, which is only
-      available as of docutils 0.6.
-
    .. versionadded:: 1.0
 
 
@@ -282,8 +277,8 @@
 .. class:: ChangesBuilder
 
    This builder produces an HTML overview of all :rst:dir:`versionadded`,
-   :rst:dir:`versionchanged` and :rst:dir:`deprecated` directives for the current
-   :confval:`version`.  This is useful to generate a ChangeLog file, for
+   :rst:dir:`versionchanged` and :rst:dir:`deprecated` directives for the
+   current :confval:`version`.  This is useful to generate a ChangeLog file, for
    example.
 
    .. autoattribute:: name
diff --git a/doc/conf.py b/doc/conf.py
index 9640e2e..3ae9482 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -5,6 +5,7 @@
 import re
 import sphinx
 
+
 extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo',
               'sphinx.ext.autosummary', 'sphinx.ext.extlinks']
 
diff --git a/doc/config.rst b/doc/config.rst
index 26079e6..cc35a75 100644
--- a/doc/config.rst
+++ b/doc/config.rst
@@ -45,7 +45,8 @@
 * There is a special object named ``tags`` available in the config file.
   It can be used to query and change the tags (see :ref:`tags`).  Use
   ``tags.has('tag')`` to query, ``tags.add('tag')`` and ``tags.remove('tag')``
-  to change.
+  to change. Only tags set via the ``-t`` command-line option or via
+  ``tags.add('tag')`` can be queried using ``tags.has('tag')``.
   Note that the current builder tag is not available in ``conf.py``, as it is
   created *after* the builder is initialized.
 
@@ -115,44 +116,16 @@
 
    .. versionadded:: 1.0
 
-.. confval:: unused_docs
-
-   A list of document names that are present, but not currently included in the
-   toctree.  Use this setting to suppress the warning that is normally emitted
-   in that case.
-
-   .. deprecated:: 1.0
-      Use :confval:`exclude_patterns` instead.
-
-.. confval:: exclude_trees
-
-   A list of directory paths, relative to the source directory, that are to be
-   recursively excluded from the search for source files, that is, their
-   subdirectories won't be searched too.  The default is ``[]``.
-
-   .. versionadded:: 0.4
-
-   .. deprecated:: 1.0
-      Use :confval:`exclude_patterns` instead.
-
-.. confval:: exclude_dirnames
-
-   A list of directory names that are to be excluded from any recursive
-   operation Sphinx performs (e.g. searching for source files or copying static
-   files).  This is useful, for example, to exclude version-control-specific
-   directories like ``'CVS'``.  The default is ``[]``.
-
-   .. versionadded:: 0.5
-
-   .. deprecated:: 1.0
-      Use :confval:`exclude_patterns` instead.
-
 .. confval:: templates_path
 
    A list of paths that contain extra templates (or templates that overwrite
    builtin/theme-specific templates).  Relative paths are taken as relative to
    the configuration directory.
 
+   .. versionchanged:: 1.3
+      As these files are not meant to be built, they are automatically added to
+      :confval:`exclude_patterns`.
+
 .. confval:: template_bridge
 
    A string with the fully-qualified name of a callable (or simply a class) that
@@ -228,6 +201,19 @@
 
    .. versionadded:: 1.0
 
+.. confval:: needs_extensions
+
+   This value can be a dictionary specifying version requirements for extensions
+   in :confval:`extensions`, e.g. ``needs_extensions =
+   {'sphinxcontrib.something': '1.5'}``.  The version strings should be in the
+   form ``major.minor``.  Requirements do not have to be specified for all
+   extensions, only for those you want to check.
+
+   This requires that the extension specifies its version to Sphinx (see
+   :ref:`dev-extensions` for how to do that).
+
+   .. versionadded:: 1.3
+
 .. confval:: nitpicky
 
    If true, Sphinx will warn about *all* references where the target cannot be
@@ -341,8 +327,8 @@
    If true, doctest flags (comments looking like ``# doctest: FLAG, ...``) at
    the ends of lines and ``<BLANKLINE>`` markers are removed for all code
    blocks showing interactive Python sessions (i.e. doctests).  Default is
-   true.  See the extension :mod:`~sphinx.ext.doctest` for more possibilities
-   of including doctests.
+   ``True``.  See the extension :mod:`~sphinx.ext.doctest` for more
+   possibilities of including doctests.
 
    .. versionadded:: 1.0
    .. versionchanged:: 1.1
@@ -354,7 +340,7 @@
 Options for internationalization
 --------------------------------
 
-These options influence Sphinx' *Native Language Support*.  See the
+These options influence Sphinx's *Native Language Support*.  See the
 documentation on :ref:`intl` for details.
 
 .. confval:: language
@@ -435,6 +421,32 @@
    By default, the document ``markup/code.rst`` ends up in the ``markup`` text
    domain.  With this option set to ``False``, it is ``markup/code``.
 
+.. confval:: gettext_uuid
+
+   If true, Sphinx generates uuid information for version tracking in message
+   catalogs.
+
+   The default is ``True``.
+
+   .. versionadded:: 1.3
+
+.. confval:: gettext_location
+
+   If true, Sphinx generates location information for messages in message
+   catalogs.
+
+   The default is ``True``.
+
+   .. versionadded:: 1.3
+
+.. confval:: gettext_auto_build
+
+   If true, Sphinx builds mo file for each translation catalog files.
+
+   The default is ``True``.
+
+   .. versionadded:: 1.3
+
 
 .. _html-options:
 
@@ -442,7 +454,7 @@
 -----------------------
 
 These options influence HTML as well as HTML Help output, and other builders
-that use Sphinx' HTMLWriter class.
+that use Sphinx's HTMLWriter class.
 
 .. confval:: html_theme
 
@@ -470,14 +482,14 @@
 .. confval:: html_style
 
    The style sheet to use for HTML pages.  A file of that name must exist either
-   in Sphinx' :file:`static/` path, or in one of the custom paths given in
+   in Sphinx's :file:`static/` path, or in one of the custom paths given in
    :confval:`html_static_path`.  Default is the stylesheet given by the selected
    theme.  If you only want to add or override a few things compared to the
    theme's stylesheet, use CSS ``@import`` to import the theme's stylesheet.
 
 .. confval:: html_title
 
-   The "title" for HTML documentation generated with Sphinx' own templates.
+   The "title" for HTML documentation generated with Sphinx's own templates.
    This is appended to the ``<title>`` tag of individual pages, and used in the
    navigation bar as the "topmost" element.  It defaults to :samp:`'{<project>}
    v{<revision>} documentation'` (with the values coming from the config
@@ -513,9 +525,10 @@
 .. confval:: html_favicon
 
    If given, this must be the name of an image file (path relative to the
-   :term:`configuration directory`) that is the favicon of the docs.  Modern browsers use this
-   as icon for tabs, windows and bookmarks.  It should be a Windows-style icon
-   file (``.ico``), which is 16x16 or 32x32 pixels large.  Default: ``None``.
+   :term:`configuration directory`) that is the favicon of the docs.  Modern
+   browsers use this as the icon for tabs, windows and bookmarks.  It should
+   be a Windows-style icon file (``.ico``), which is 16x16 or 32x32
+   pixels large.  Default: ``None``.
 
    .. versionadded:: 0.4
       The image file will be copied to the ``_static`` directory of the output
@@ -557,8 +570,9 @@
 
 .. confval:: html_use_smartypants
 
-   If true, *SmartyPants* will be used to convert quotes and dashes to
-   typographically correct entities.  Default: ``True``.
+   If true, `SmartyPants <http://daringfireball.net/projects/smartypants/>`_
+   will be used to convert quotes and dashes to typographically correct
+   entities.  Default: ``True``.
 
 .. confval:: html_add_permalinks
 
@@ -600,7 +614,8 @@
 
    Builtin sidebar templates that can be rendered are:
 
-   * **localtoc.html** -- a fine-grained table of contents of the current document
+   * **localtoc.html** -- a fine-grained table of contents of the current
+     document
    * **globaltoc.html** -- a coarse-grained table of contents for the whole
      documentation set, collapsed
    * **relations.html** -- two links to the previous and next documents
@@ -717,13 +732,16 @@
 .. confval:: html_translator_class
 
    A string with the fully-qualified name of a HTML Translator class, that is, a
-   subclass of Sphinx' :class:`~sphinx.writers.html.HTMLTranslator`, that is used
-   to translate document trees to HTML.  Default is ``None`` (use the builtin
-   translator).
+   subclass of Sphinx's :class:`~sphinx.writers.html.HTMLTranslator`, that is
+   used to translate document trees to HTML.  Default is ``None`` (use the
+   builtin translator).
+
+   .. seealso::  :meth:`~sphinx.application.Sphinx.set_translator`
 
 .. confval:: html_show_copyright
 
-   If true, "(C) Copyright ..." is shown in the HTML footer. Default is ``True``.
+   If true, "(C) Copyright ..." is shown in the HTML footer. Default is
+   ``True``.
 
    .. versionadded:: 1.0
 
@@ -766,10 +784,37 @@
 
    Support is present for these languages:
 
+   * ``da`` -- Danish
+   * ``nl`` -- Dutch
    * ``en`` -- English
+   * ``fi`` -- Finnish
+   * ``fr`` -- French
+   * ``de`` -- German
+   * ``hu`` -- Hungarian
+   * ``it`` -- Italian
    * ``ja`` -- Japanese
+   * ``no`` -- Norwegian
+   * ``pr`` -- Portuguese
+   * ``ro`` -- Romanian
+   * ``ru`` -- Russian
+   * ``es`` -- Spanish
+   * ``sv`` -- Swedish
+   * ``tr`` -- Turkish
+
+   .. admonition:: Accelerating build speed
+
+      Each language (except Japanese) provides its own stemming algorithm.
+      Sphinx uses a Python implementation by default.  You can use a C
+      implementation to accelerate building the index file.
+
+      * `PorterStemmer <https://pypi.python.org/pypi/PorterStemmer>`_ (``en``)
+      * `PyStemmer <https://pypi.python.org/pypi/PyStemmer>`_ (all languages)
 
    .. versionadded:: 1.1
+      With support for ``en`` and ``ja``.
+
+   .. versionchanged:: 1.3
+      Added additional languages.
 
 .. confval:: html_search_options
 
@@ -791,7 +836,7 @@
 
 .. confval:: html_search_scorer
 
-   The name of a javascript file (relative to the configuration directory) that
+   The name of a JavaScript file (relative to the configuration directory) that
    implements a search results scorer.  If empty, the default will be used.
 
    .. XXX describe interface for scorer here
@@ -900,7 +945,7 @@
    the optional guide information. See the OPF documentation
    at `<http://idpf.org/epub>`_ for details. If possible, default entries
    for the *cover* and *toc* types are automatically inserted. However,
-   the types can be explicitely overwritten if the default entries are not
+   the types can be explicitly overwritten if the default entries are not
    appropriate. Example::
 
       epub_guide = (('cover', 'cover.html', u'Cover Page'),)
@@ -940,8 +985,8 @@
 .. confval:: epub_tocdup
 
    This flag determines if a toc entry is inserted again at the beginning of
-   it's nested toc listing.  This allows easier navitation to the top of
-   a chapter, but can be confusing because it mixes entries of differnet
+   its nested toc listing.  This allows easier navigation to the top of
+   a chapter, but can be confusing because it mixes entries of different
    depth in one list.  The default value is ``True``.
 
 .. confval:: epub_tocscope
@@ -1024,11 +1069,11 @@
      ``'John \and Sarah'``.
    * *documentclass*: Normally, one of ``'manual'`` or ``'howto'`` (provided by
      Sphinx).  Other document classes can be given, but they must include the
-     "sphinx" package in order to define Sphinx' custom LaTeX commands.
-     "howto" documents will not get appendices.  Also, howtos will have a simpler
-     title page.
+     "sphinx" package in order to define Sphinx's custom LaTeX commands. "howto"
+     documents will not get appendices.  Also, howtos will have a simpler title
+     page.
 
-   * *toctree_only*: Must be ``True`` or ``False``.  If ``True``, the *startdoc*
+   * *toctree_only*: Must be ``True`` or ``False``.  If true, the *startdoc*
      document itself is not included in the output, only the documents
      referenced by it via TOC trees.  With this option, you can put extra stuff
      in the master document that shows up in the HTML, but not the LaTeX output.
@@ -1135,6 +1180,12 @@
         "Rejne".  You can also set this to ``''`` to disable fncychap.
      ``'preamble'``
         Additional preamble content, default empty.
+     ``'figure_align'``
+        Latex figure float alignment, default 'htbp' (here, top, bottom, page).
+        Whenever an image doesn't fit into the current page, it will be
+        'floated' into the next page but may be preceded by any other text.
+        If you don't like this behavior, use 'H' which will disable floating
+        and position figures strictly in the order they appear in the source.
      ``'footer'``
         Additional footer content (before the indices), default empty.
 
@@ -1167,7 +1218,8 @@
         ``'\\printindex'``.  Override if you want to generate the index
         differently or append some content after the index.
 
-   * Keys that are set by other options and therefore should not be overridden are:
+   * Keys that are set by other options and therefore should not be overridden
+     are:
 
      ``'docclass'``
      ``'classoptions'``
@@ -1324,7 +1376,7 @@
      file.
    * *category*: Specifies the section which this entry will appear in the
      top-level ``DIR`` menu file.
-   * *toctree_only*: Must be ``True`` or ``False``.  If ``True``, the *startdoc*
+   * *toctree_only*: Must be ``True`` or ``False``.  If true, the *startdoc*
      document itself is not included in the output, only the documents
      referenced by it via TOC trees.  With this option, you can put extra stuff
      in the master document that shows up in the HTML, but not the Texinfo
@@ -1400,7 +1452,6 @@
      ``'project'``
      ``'release'``
      ``'title'``
-     ``'direntry'``
 
    .. versionadded:: 1.1
 
@@ -1434,9 +1485,9 @@
 
 .. confval:: linkcheck_anchors
 
-   True or false, whether to check the validity of ``#anchor``\ s in links.
-   Since this requires downloading the whole document, it's considerably slower
-   when enabled.  Default is ``True``.
+   If true, check the validity of ``#anchor``\ s in links. Since this requires
+   downloading the whole document, it's considerably slower when enabled.
+   Default is ``True``.
 
    .. versionadded:: 1.2
 
@@ -1446,7 +1497,7 @@
 
 .. confval:: xml_pretty
 
-   If True, pretty-print the XML.  Default is ``True``.
+   If true, pretty-print the XML.  Default is ``True``.
 
    .. versionadded:: 1.2
 
diff --git a/doc/contents.rst b/doc/contents.rst
index d3fd3c8..a51910b 100644
--- a/doc/contents.rst
+++ b/doc/contents.rst
@@ -26,6 +26,7 @@
    devguide
    changes
    examples
+   authors
 
 
 Indices and tables
diff --git a/doc/develop.rst b/doc/develop.rst
index aad3ff1..5110aa3 100644
--- a/doc/develop.rst
+++ b/doc/develop.rst
@@ -55,6 +55,7 @@
 - hyphenator: client-side hyphenation of HTML using hyphenator_
 - inlinesyntaxhighlight_: inline syntax highlighting
 - lassodomain: a domain for documenting Lasso_ source code
+- libreoffice: an extension to include any drawing supported by LibreOffice (e.g. odg, vsd...).
 - lilypond: an extension inserting music scripts from Lilypond_ in PNG format.
 - makedomain_: a domain for `GNU Make`_
 - matlabdomain: document MATLAB_ code.
@@ -68,7 +69,8 @@
 - paverutils: an alternate integration of Sphinx with Paver_.
 - phpdomain: an extension for PHP support
 - plantuml: embed UML diagram by using PlantUML_
-- py_directive: Execute python code in a ``py`` directive and return a math node.
+- py_directive: Execute python code in a ``py`` directive and return a math
+  node.
 - rawfiles: copy raw files, like a CNAME.
 - requirements: declare requirements wherever you need (e.g. in test
   docstrings), mark statuses and collect them in a single list
diff --git a/doc/devguide.rst b/doc/devguide.rst
index fccdd3f..885d52b 100644
--- a/doc/devguide.rst
+++ b/doc/devguide.rst
@@ -54,6 +54,23 @@
 committing the changes.  The pull request will then need to be approved by one
 of the core developers before it is merged into the main repository.
 
+#. Check for open issues or open a fresh issue to start a discussion around a
+   feature idea or a bug. There are `Non Assigned`_ issues.
+#. If you feel uncomfortable or uncertain about an issue or your changes, feel
+   free to email sphinx-dev@googlegroups.com.
+#. Fork `the repository`_ on Bitbucket to start making your changes to the
+   **default** branch for next major version, or **stable** branch for next
+   minor version.
+#. Write a test which shows that the bug was fixed or that the feature works
+   as expected.
+#. Send a pull request and bug the maintainer until it gets merged and
+   published. Make sure to add yourself to AUTHORS_ and the change to
+   CHANGES_.
+
+.. _`the repository`: https://bitbucket.org/birkenfeld/sphinx
+.. _AUTHORS: https://bitbucket.org/birkenfeld/sphinx/src/tip/AUTHORS
+.. _CHANGES: https://bitbucket.org/birkenfeld/sphinx/src/tip/CHANGES
+.. _Non Assigned: https://bitbucket.org/birkenfeld/sphinx/issues?status=new&status=open&responsible=
 
 Getting Started
 ~~~~~~~~~~~~~~~
@@ -113,8 +130,8 @@
    * For bug fixes, first add a test that fails without your changes and passes
      after they are applied.
 
-#. Please add a bullet point to :file:`CHANGES` if the fix or feature is not trivial
-   (small doc updates, typo fixes).  Then commit::
+#. Please add a bullet point to :file:`CHANGES` if the fix or feature is not
+   trivial (small doc updates, typo fixes).  Then commit::
 
        hg commit -m '#42: Add useful new feature that does this.'
 
@@ -191,9 +208,9 @@
 values for :confval:`language` in ``doc/config.rst``.
 
 The Sphinx core messages can also be translated on `Transifex
-<https://www.transifex.com/>`_.  There exists a client tool named ``tx`` in the Python
-package "transifex_client", which can be used to pull translations in ``.po``
-format from Transifex.  To do this, go to ``sphinx/locale`` and then run
+<https://www.transifex.com/>`_.  There exists a client tool named ``tx`` in the
+Python package "transifex_client", which can be used to pull translations in
+``.po`` format from Transifex.  To do this, go to ``sphinx/locale`` and then run
 ``tx pull -f -l LANG`` where LANG is an existing language identifier.  It is
 good practice to run ``python setup.py update_catalog`` afterwards to make sure
 the ``.po`` file has the canonical Babel formatting.
@@ -235,11 +252,23 @@
 * Use ``node.pformat()`` and ``node.asdom().toxml()`` to generate a printable
   representation of the document structure.
 
-* Set the configuration variable :confval:`keep_warnings` to True so warnings
-  will be displayed in the generated output.
+* Set the configuration variable :confval:`keep_warnings` to ``True`` so
+  warnings will be displayed in the generated output.
 
-* Set the configuration variable :confval:`nitpicky` to True so that Sphinx
+* Set the configuration variable :confval:`nitpicky` to ``True`` so that Sphinx
   will complain about references without a known target.
 
 * Set the debugging options in the `Docutils configuration file
   <http://docutils.sourceforge.net/docs/user/config.html>`_.
+
+* JavaScript stemming algorithms in `sphinx/search/*.py` (except `en.py`) are
+  generated by this
+  `modified snowballcode generator <https://github.com/shibukawa/snowball>`_.
+  Generated `JSX <http://jsx.github.io/>`_ files are
+  in `this repository <https://github.com/shibukawa/snowball-stemmer.jsx>`_.
+  You can get the resulting JavaScript files using the following command:
+
+  .. code-block:: bash
+
+     $ npm install
+     $ node_modules/.bin/grunt build # -> dest/*.global.js
diff --git a/doc/domains.rst b/doc/domains.rst
index 4b5a903..4bfc91e 100644
--- a/doc/domains.rst
+++ b/doc/domains.rst
@@ -127,7 +127,8 @@
 
    This directive marks the beginning of the description of a module (or package
    submodule, in which case the name should be fully qualified, including the
-   package name).  It does not create content (like e.g. :rst:dir:`py:class` does).
+   package name).  It does not create content (like e.g. :rst:dir:`py:class`
+   does).
 
    This directive will also cause an entry in the global module index.
 
@@ -157,17 +158,6 @@
 
 The following directives are provided for module and class contents:
 
-.. rst:directive:: .. py:data:: name
-
-   Describes global data in a module, including both variables and values used
-   as "defined constants."  Class and object attributes are not documented
-   using this environment.
-
-.. rst:directive:: .. py:exception:: name
-
-   Describes an exception class.  The signature can, but need not include
-   parentheses with constructor arguments.
-
 .. rst:directive:: .. py:function:: name(parameters)
 
    Describes a module-level function.  The signature should include the
@@ -178,11 +168,23 @@
 
    For methods you should use :rst:dir:`py:method`.
 
-   The description should include information about the parameters required and
-   how they are used (especially whether mutable objects passed as parameters
-   are modified), side effects, and possible exceptions.  This information can
-   optionally be given in a structured form, see :ref:`info-field-lists`.  A
-   small example may be provided.
+   The description normally includes information about the parameters required
+   and how they are used (especially whether mutable objects passed as
+   parameters are modified), side effects, and possible exceptions.
+
+   This information can (in any ``py`` directive) optionally be given in a
+   structured form, see :ref:`info-field-lists`.
+
+.. rst:directive:: .. py:data:: name
+
+   Describes global data in a module, including both variables and values used
+   as "defined constants."  Class and object attributes are not documented
+   using this environment.
+
+.. rst:directive:: .. py:exception:: name
+
+   Describes an exception class.  The signature can, but need not include
+   parentheses with constructor arguments.
 
 .. rst:directive:: .. py:class:: name
                    .. py:class:: name(parameters)
@@ -374,7 +376,7 @@
    Reference a Python function; dotted names may be used.  The role text needs
    not include trailing parentheses to enhance readability; they will be added
    automatically by Sphinx if the :confval:`add_function_parentheses` config
-   value is true (the default).
+   value is ``True`` (the default).
 
 .. rst:role:: py:data
 
@@ -518,23 +520,26 @@
 
 The C++ domain (name **cpp**) supports documenting C++ projects.
 
-The following directives are available:
+The following directives are available. All declarations can start with a visibility statement
+(``public``, ``private`` or ``protected``).
 
-.. rst:directive:: .. cpp:class:: signatures
-               .. cpp:function:: signatures
-               .. cpp:member:: signatures
-               .. cpp:type:: signatures
+.. rst:directive:: .. cpp:class:: class speicifer
 
-   Describe a C++ object.  Full signature specification is supported -- give the
-   signature as you would in the declaration.  Here some examples::
+   Describe a class/struct, possibly with specification of inheritance, e.g.,::
+   
+      .. cpp:class:: SomeName::SomeClass : public MyBase, MyOtherBase
+
+.. rst:directive:: .. cpp:function:: (member-)function prototype
+
+   Describe a function or member function, e.g.,::
 
       .. cpp:function:: bool namespaced::theclass::method(int arg1, std::string arg2)
 
          Describes a method with parameters and types.
 
-      .. cpp:function:: bool namespaced::theclass::method(arg1, arg2)
+      .. cpp:function:: bool namespaced::theclass::method(T1, T2)
 
-         Describes a method without types.
+         Describes a method with unnamed parameters.
 
       .. cpp:function:: const T &array<T>::operator[]() const
 
@@ -548,43 +553,41 @@
 
          Describe a constexpr function here.
 
-      .. cpp:member:: std::string theclass::name
+      .. cpp:function:: MyClass::MyClass(const MyClass&) = default
 
-      .. cpp:member:: std::string theclass::name[N][M]
+         Describe a copy constructor with default implementation.
 
-      .. cpp:type:: theclass::const_iterator
+.. rst:directive:: .. cpp:member:: variable or member declaration
 
-   Will be rendered like this:
-
-      .. cpp:function:: bool namespaced::theclass::method(int arg1, std::string arg2)
-
-         Describes a method with parameters and types.
-
-      .. cpp:function:: bool namespaced::theclass::method(arg1, arg2)
-
-         Describes a method without types.
-
-      .. cpp:function:: const T &array<T>::operator[]() const
-
-         Describes the constant indexing operator of a templated array.
-
-      .. cpp:function:: operator bool() const
-
-         Describe a casting operator here.
-
-      .. cpp:function:: constexpr void foo(std::string &bar[2]) noexcept
-
-         Describe a constexpr function here.
+   Describe a varible or member variable, e.g.,::
 
       .. cpp:member:: std::string theclass::name
 
       .. cpp:member:: std::string theclass::name[N][M]
 
+.. rst:directive:: .. cpp:type:: typedef-like declaration
+                   .. cpp:type:: name
+
+   Describe a type as in a typedef declaration, or the name of a type with unspecified type, e.g.,::
+
+      .. cpp:type:: std::vector<int> MyList
+
+         A typedef-like declaration of a type.
+
       .. cpp:type:: theclass::const_iterator
 
+         Declaration of a type alias with unspecified type.
+
 .. rst:directive:: .. cpp:namespace:: namespace
 
-   Select the current C++ namespace for the following objects.
+   Select the current namespace for the following objects. Note that the namespace
+   does not need to correspond to C++ namespaces, but can end in names of classes, e.g.,::
+
+      .. cpp:namespace:: Namespace1::Namespace2::SomeClass::AnInnerClass
+
+   All following objects will be defined as if their name were declared with the namespace
+   prepended. The following cross-references will be search for by both their specified name
+   and with the namespace prepended.
 
 
 .. _cpp-roles:
@@ -596,12 +599,12 @@
           cpp:member
           cpp:type
 
-   Reference a C++ object.  You can give the full signature (and need to, for
+   Reference a C++ object.  You can give the full specification (and need to, for
    overloaded functions.)
 
    .. note::
 
-      Sphinx' syntax to give references a custom title can interfere with
+      Sphinx's syntax to give references a custom title can interfere with
       linking to template classes, if nothing follows the closing angle
       bracket, i.e. if the link looks like this: ``:cpp:class:`MyClass<T>```.
       This is interpreted as a link to ``T`` with a title of ``MyClass``.
@@ -617,6 +620,12 @@
    specific overload.  Currently Sphinx will link to the first overloaded
    version of the method / function.
 
+.. admonition:: Note on Template Delcarations
+
+   The C++ domain currently does not support template classes/functions/aliases/variables
+   (e.g., ``template<typename T> MyClass``), only template instantiations
+   (e.g., ``MyClass<T>``).
+
 
 The Standard Domain
 -------------------
@@ -654,9 +663,9 @@
 
 .. rst:directive:: .. program:: name
 
-   Like :rst:dir:`py:currentmodule`, this directive produces no output.  Instead, it
-   serves to notify Sphinx that all following :rst:dir:`option` directives
-   document options for the program called *name*.
+   Like :rst:dir:`py:currentmodule`, this directive produces no output.
+   Instead, it serves to notify Sphinx that all following :rst:dir:`option`
+   directives document options for the program called *name*.
 
    If you use :rst:dir:`program`, you have to qualify the references in your
    :rst:role:`option` roles by the program name, so if you have the following
diff --git a/doc/ext/autodoc.rst b/doc/ext/autodoc.rst
index 7f64698..844c636 100644
--- a/doc/ext/autodoc.rst
+++ b/doc/ext/autodoc.rst
@@ -35,6 +35,16 @@
 two locations for documentation, while at the same time avoiding
 auto-generated-looking pure API documentation.
 
+If you prefer `NumPy`_ or `Google`_ style docstrings over reStructuredText,
+you can also enable the :mod:`napoleon <sphinx.ext.napoleon>` extension.
+:mod:`napoleon <sphinx.ext.napoleon>` is a preprocessor that converts your
+docstrings to correct reStructuredText before :mod:`autodoc` processes them.
+
+.. _Google:
+   http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Comments
+.. _NumPy:
+   https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
+
 :mod:`autodoc` provides several directives that are versions of the usual
 :rst:dir:`py:module`, :rst:dir:`py:class` and so forth.  On parsing time, they
 import the corresponding module and extract the docstring of the given objects,
@@ -204,6 +214,12 @@
 
      .. versionadded:: 1.2
 
+   * Add a list of modules in the :confval:`autodoc_mock_imports` to prevent
+     import errors to halt the building process when some external dependencies
+     are not importable at build time.
+
+     .. versionadded:: 1.3
+
 
 .. rst:directive:: autofunction
                    autodata
@@ -258,13 +274,14 @@
               """Docstring for instance attribute spam."""
 
    .. versionchanged:: 0.6
-      :rst:dir:`autodata` and :rst:dir:`autoattribute` can now extract docstrings.
+      :rst:dir:`autodata` and :rst:dir:`autoattribute` can now extract
+      docstrings.
    .. versionchanged:: 1.1
       Comment docs are now allowed on the same line after an assignment.
 
    .. versionchanged:: 1.2
-      :rst:dir:`autodata` and :rst:dir:`autoattribute` have
-      an ``annotation`` option
+      :rst:dir:`autodata` and :rst:dir:`autoattribute` have an ``annotation``
+      option.
 
    .. note::
 
@@ -344,6 +361,14 @@
 
    .. versionadded:: 1.1
 
+.. confval:: autodoc_mock_imports
+
+   This value contains a list of modules to be mocked up. This is useful when
+   some external dependencies are not met at build time and break the building
+   process.
+
+   .. versionadded:: 1.3
+
 
 Docstring preprocessing
 -----------------------
@@ -389,8 +414,8 @@
       ``noindex`` that are true if the flag option of same name was given to the
       auto directive
    :param signature: function signature, as a string of the form
-      ``"(parameter_1, parameter_2)"``, or ``None`` if introspection didn't succeed
-      and signature wasn't specified in the directive.
+      ``"(parameter_1, parameter_2)"``, or ``None`` if introspection didn't
+      succeed and signature wasn't specified in the directive.
    :param return_annotation: function return annotation as a string of the form
       ``" -> annotation"``, or ``None`` if there is no return annotation
 
@@ -421,8 +446,8 @@
       ``"attribute"``)
    :param name: the fully qualified name of the object
    :param obj: the object itself
-   :param skip: a boolean indicating if autodoc will skip this member if the user
-      handler does not override the decision
+   :param skip: a boolean indicating if autodoc will skip this member if the
+      user handler does not override the decision
    :param options: the options given to the directive: an object with attributes
       ``inherited_members``, ``undoc_members``, ``show_inheritance`` and
       ``noindex`` that are true if the flag option of same name was given to the
diff --git a/doc/ext/autosummary.rst b/doc/ext/autosummary.rst
index e3de183..8548fbd 100644
--- a/doc/ext/autosummary.rst
+++ b/doc/ext/autosummary.rst
@@ -15,15 +15,15 @@
 
 The :mod:`sphinx.ext.autosummary` extension does this in two parts:
 
-1. There is an :rst:dir:`autosummary` directive for generating summary listings that
-   contain links to the documented items, and short summary blurbs extracted
-   from their docstrings.
+1. There is an :rst:dir:`autosummary` directive for generating summary listings
+   that contain links to the documented items, and short summary blurbs
+   extracted from their docstrings.
 
 2. Optionally, the convenience script :program:`sphinx-autogen` or the new
    :confval:`autosummary_generate` config value can be used to generate short
    "stub" files for the entries listed in the :rst:dir:`autosummary` directives.
-   These files by default contain only the corresponding :mod:`sphinx.ext.autodoc`
-   directive, but can be customized with templates.
+   These files by default contain only the corresponding
+   :mod:`sphinx.ext.autodoc` directive, but can be customized with templates.
 
 
 .. rst:directive:: autosummary
@@ -62,8 +62,8 @@
 
    **Options**
 
-   * If you want the :rst:dir:`autosummary` table to also serve as a :rst:dir:`toctree`
-     entry, use the ``toctree`` option, for example::
+   * If you want the :rst:dir:`autosummary` table to also serve as a
+     :rst:dir:`toctree` entry, use the ``toctree`` option, for example::
 
          .. autosummary::
             :toctree: DIRNAME
@@ -78,8 +78,8 @@
      directory. If no argument is given, output is placed in the same directory
      as the file that contains the directive.
 
-   * If you don't want the :rst:dir:`autosummary` to show function signatures in the
-     listing, include the ``nosignatures`` option::
+   * If you don't want the :rst:dir:`autosummary` to show function signatures in
+     the listing, include the ``nosignatures`` option::
 
          .. autosummary::
             :nosignatures:
@@ -112,8 +112,8 @@
 
     $ sphinx-autogen -o generated *.rst
 
-will read all :rst:dir:`autosummary` tables in the :file:`*.rst` files that have the
-``:toctree:`` option set, and output corresponding stub pages in directory
+will read all :rst:dir:`autosummary` tables in the :file:`*.rst` files that have
+the ``:toctree:`` option set, and output corresponding stub pages in directory
 ``generated`` for all documented items.  The generated pages by default contain
 text of the form::
 
diff --git a/doc/ext/doctest.rst b/doc/ext/doctest.rst
index 554987e..9b1b4e6 100644
--- a/doc/ext/doctest.rst
+++ b/doc/ext/doctest.rst
@@ -142,8 +142,8 @@
 
 
 The following is an example for the usage of the directives.  The test via
-:rst:dir:`doctest` and the test via :rst:dir:`testcode` and :rst:dir:`testoutput` are
-equivalent. ::
+:rst:dir:`doctest` and the test via :rst:dir:`testcode` and
+:rst:dir:`testoutput` are equivalent. ::
 
    The parrot module
    =================
@@ -236,5 +236,5 @@
    Note though that you can't have blank lines in reST doctest blocks.  They
    will be interpreted as one block ending and another one starting.  Also,
    removal of ``<BLANKLINE>`` and ``# doctest:`` options only works in
-   :rst:dir:`doctest` blocks, though you may set :confval:`trim_doctest_flags` to
-   achieve that in all code blocks with Python console content.
+   :rst:dir:`doctest` blocks, though you may set :confval:`trim_doctest_flags`
+   to achieve that in all code blocks with Python console content.
diff --git a/doc/ext/example_google.py b/doc/ext/example_google.py
new file mode 100644
index 0000000..c94dcdf
--- /dev/null
+++ b/doc/ext/example_google.py
@@ -0,0 +1,223 @@
+# -*- coding: utf-8 -*-
+"""Example Google style docstrings.
+
+This module demonstrates documentation as specified by the `Google Python
+Style Guide`_. Docstrings may extend over multiple lines. Sections are created
+with a section header and a colon followed by a block of indented text.
+
+Example:
+  Examples can be given using either the ``Example`` or ``Examples``
+  sections. Sections support any reStructuredText formatting, including
+  literal blocks::
+
+      $ python example_google.py
+
+Section breaks are created by simply resuming unindented text. Section breaks
+are also implicitly created anytime a new section starts.
+
+Attributes:
+  module_level_variable (int): Module level variables may be documented in
+    either the ``Attributes`` section of the module docstring, or in an
+    inline docstring immediately following the variable.
+
+    Either form is acceptable, but the two should not be mixed. Choose
+    one convention to document module level variables and be consistent
+    with it.
+
+.. _Google Python Style Guide:
+   http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
+
+"""
+
+module_level_variable = 12345
+
+
+def module_level_function(param1, param2=None, *args, **kwargs):
+    """This is an example of a module level function.
+
+    Function parameters should be documented in the ``Args`` section. The name
+    of each parameter is required. The type and description of each parameter
+    is optional, but should be included if not obvious.
+
+    If the parameter itself is optional, it should be noted by adding
+    ", optional" to the type. If \*args or \*\*kwargs are accepted, they
+    should be listed as \*args and \*\*kwargs.
+
+    The format for a parameter is::
+
+        name (type): description
+          The description may span multiple lines. Following
+          lines should be indented.
+
+          Multiple paragraphs are supported in parameter
+          descriptions.
+
+    Args:
+      param1 (int): The first parameter.
+      param2 (str, optional): The second parameter. Defaults to None.
+        Second line of description should be indented.
+      *args: Variable length argument list.
+      **kwargs: Arbitrary keyword arguments.
+
+    Returns:
+      bool: True if successful, False otherwise.
+
+      The return type is optional and may be specified at the beginning of
+      the ``Returns`` section followed by a colon.
+
+      The ``Returns`` section may span multiple lines and paragraphs.
+      Following lines should be indented to match the first line.
+
+      The ``Returns`` section supports any reStructuredText formatting,
+      including literal blocks::
+
+          {
+              'param1': param1,
+              'param2': param2
+          }
+
+    Raises:
+      AttributeError: The ``Raises`` section is a list of all exceptions
+        that are relevant to the interface.
+      ValueError: If `param2` is equal to `param1`.
+
+    """
+    if param1 == param2:
+        raise ValueError('param1 may not be equal to param2')
+    return True
+
+
+def example_generator(n):
+    """Generators have a ``Yields`` section instead of a ``Returns`` section.
+
+    Args:
+      n (int): The upper limit of the range to generate, from 0 to `n` - 1
+
+    Yields:
+      int: The next number in the range of 0 to `n` - 1
+
+    Examples:
+      Examples should be written in doctest format, and should illustrate how
+      to use the function.
+
+      >>> print [i for i in example_generator(4)]
+      [0, 1, 2, 3]
+
+    """
+    for i in range(n):
+        yield i
+
+
+class ExampleError(Exception):
+    """Exceptions are documented in the same way as classes.
+
+    The __init__ method may be documented in either the class level
+    docstring, or as a docstring on the __init__ method itself.
+
+    Either form is acceptable, but the two should not be mixed. Choose one
+    convention to document the __init__ method and be consistent with it.
+
+    Note:
+      Do not include the `self` parameter in the ``Args`` section.
+
+    Args:
+      msg (str): Human readable string describing the exception.
+      code (int, optional): Error code, defaults to 2.
+
+    Attributes:
+      msg (str): Human readable string describing the exception.
+      code (int): Exception error code.
+
+    """
+    def __init__(self, msg, code=2):
+        self.msg = msg
+        self.code = code
+
+
+class ExampleClass(object):
+    """The summary line for a class docstring should fit on one line.
+
+    If the class has public attributes, they should be documented here
+    in an ``Attributes`` section and follow the same formatting as a
+    function's ``Args`` section.
+
+    Attributes:
+      attr1 (str): Description of `attr1`.
+      attr2 (list of str): Description of `attr2`.
+      attr3 (int): Description of `attr3`.
+
+    """
+    def __init__(self, param1, param2, param3=0):
+        """Example of docstring on the __init__ method.
+
+        The __init__ method may be documented in either the class level
+        docstring, or as a docstring on the __init__ method itself.
+
+        Either form is acceptable, but the two should not be mixed. Choose one
+        convention to document the __init__ method and be consistent with it.
+
+        Note:
+          Do not include the `self` parameter in the ``Args`` section.
+
+        Args:
+          param1 (str): Description of `param1`.
+          param2 (list of str): Description of `param2`. Multiple
+            lines are supported.
+          param3 (int, optional): Description of `param3`, defaults to 0.
+
+        """
+        self.attr1 = param1
+        self.attr2 = param2
+        self.attr3 = param3
+
+    def example_method(self, param1, param2):
+        """Class methods are similar to regular functions.
+
+        Note:
+          Do not include the `self` parameter in the ``Args`` section.
+
+        Args:
+          param1: The first parameter.
+          param2: The second parameter.
+
+        Returns:
+          True if successful, False otherwise.
+
+        """
+        return True
+
+    def __special__(self):
+        """By default special members with docstrings are included.
+
+        Special members are any methods or attributes that start with and
+        end with a double underscore. Any special member with a docstring
+        will be included in the output.
+
+        This behavior can be disabled by changing the following setting in
+        Sphinx's conf.py::
+
+            napoleon_include_special_with_doc = False
+
+        """
+        pass
+
+    def __special_without_docstring__(self):
+        pass
+
+    def _private(self):
+        """By default private members are not included.
+
+        Private members are any methods or attributes that start with an
+        underscore and are *not* special. By default they are not included
+        in the output.
+
+        This behavior can be changed such that private members *are* included
+        by changing the following setting in Sphinx's conf.py::
+
+            napoleon_include_private_with_doc = True
+
+        """
+        pass
+
+    def _private_without_docstring(self):
+        pass
diff --git a/doc/ext/example_google.rst b/doc/ext/example_google.rst
new file mode 100644
index 0000000..0650808
--- /dev/null
+++ b/doc/ext/example_google.rst
@@ -0,0 +1,15 @@
+:orphan:
+
+.. _example_google:
+
+Example Google Style Python Docstrings
+======================================
+
+.. seealso::
+
+   :ref:`example_numpy`
+
+Download: :download:`example_google.py <example_google.py>`
+
+.. literalinclude:: example_google.py
+   :language: python
diff --git a/doc/ext/example_numpy.py b/doc/ext/example_numpy.py
new file mode 100644
index 0000000..df1d20e
--- /dev/null
+++ b/doc/ext/example_numpy.py
@@ -0,0 +1,272 @@
+# -*- coding: utf-8 -*-
+"""Example NumPy style docstrings.
+
+This module demonstrates documentation as specified by the `NumPy
+Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections
+are created with a section header followed by an underline of equal length.
+
+Example
+-------
+Examples can be given using either the ``Example`` or ``Examples``
+sections. Sections support any reStructuredText formatting, including
+literal blocks::
+
+    $ python example_numpy.py
+
+
+Section breaks are created with two blank lines. Section breaks are also
+implicitly created anytime a new section starts. Section bodies *may* be
+indented:
+
+Notes
+-----
+    This is an example of an indented section. It's like any other section,
+    but the body is indented to help it stand out from surrounding text.
+
+If a section is indented, then a section break is created simply by
+resuming unindented text.
+
+Attributes
+----------
+module_level_variable : int
+    Module level variables may be documented in either the ``Attributes``
+    section of the module docstring, or in an inline docstring immediately
+    following the variable.
+
+    Either form is acceptable, but the two should not be mixed. Choose
+    one convention to document module level variables and be consistent
+    with it.
+
+.. _NumPy Documentation HOWTO:
+   https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
+
+"""
+
+module_level_variable = 12345
+
+
+def module_level_function(param1, param2=None, *args, **kwargs):
+    """This is an example of a module level function.
+
+    Function parameters should be documented in the ``Parameters`` section.
+    The name of each parameter is required. The type and description of each
+    parameter is optional, but should be included if not obvious.
+
+    If the parameter itself is optional, it should be noted by adding
+    ", optional" to the type. If \*args or \*\*kwargs are accepted, they
+    should be listed as \*args and \*\*kwargs.
+
+    The format for a parameter is::
+
+        name : type
+            description
+
+            The description may span multiple lines. Following lines
+            should be indented to match the first line of the description.
+
+            Multiple paragraphs are supported in parameter
+            descriptions.
+
+    Parameters
+    ----------
+    param1 : int
+        The first parameter.
+    param2 : str, optional
+        The second parameter, defaults to None.
+    *args
+        Variable length argument list.
+    **kwargs
+        Arbitrary keyword arguments.
+
+    Returns
+    -------
+    bool
+        True if successful, False otherwise.
+
+        The return type is not optional. The ``Returns`` section may span
+        multiple lines and paragraphs. Following lines should be indented to
+        match the first line of the description.
+
+        The ``Returns`` section supports any reStructuredText formatting,
+        including literal blocks::
+
+            {
+                'param1': param1,
+                'param2': param2
+            }
+
+    Raises
+    ------
+    AttributeError
+        The ``Raises`` section is a list of all exceptions
+        that are relevant to the interface.
+    ValueError
+        If `param2` is equal to `param1`.
+
+    """
+    if param1 == param2:
+        raise ValueError('param1 may not be equal to param2')
+    return True
+
+
+def example_generator(n):
+    """Generators have a ``Yields`` section instead of a ``Returns`` section.
+
+    Parameters
+    ----------
+    n : int
+        The upper limit of the range to generate, from 0 to `n` - 1
+
+    Yields
+    ------
+    int
+        The next number in the range of 0 to `n` - 1
+
+    Examples
+    --------
+    Examples should be written in doctest format, and should illustrate how
+    to use the function.
+
+    >>> print [i for i in example_generator(4)]
+    [0, 1, 2, 3]
+
+    """
+    for i in range(n):
+        yield i
+
+
+class ExampleError(Exception):
+    """Exceptions are documented in the same way as classes.
+
+    The __init__ method may be documented in either the class level
+    docstring, or as a docstring on the __init__ method itself.
+
+    Either form is acceptable, but the two should not be mixed. Choose one
+    convention to document the __init__ method and be consistent with it.
+
+    Note
+    ----
+    Do not include the `self` parameter in the ``Parameters`` section.
+
+    Parameters
+    ----------
+    msg : str
+        Human readable string describing the exception.
+    code : int, optional
+        Error code, defaults to 2.
+
+    Attributes
+    ----------
+    msg : str
+        Human readable string describing the exception.
+    code : int
+        Exception error code.
+
+    """
+    def __init__(self, msg, code=2):
+        self.msg = msg
+        self.code = code
+
+
+class ExampleClass(object):
+    """The summary line for a class docstring should fit on one line.
+
+    If the class has public attributes, they should be documented here
+    in an ``Attributes`` section and follow the same formatting as a
+    function's ``Parameters`` section.
+
+    Attributes
+    ----------
+    attr1 : str
+        Description of `attr1`.
+    attr2 : list of str
+        Description of `attr2`.
+    attr3 : int
+        Description of `attr3`.
+
+    """
+    def __init__(self, param1, param2, param3=0):
+        """Example of docstring on the __init__ method.
+
+        The __init__ method may be documented in either the class level
+        docstring, or as a docstring on the __init__ method itself.
+
+        Either form is acceptable, but the two should not be mixed. Choose one
+        convention to document the __init__ method and be consistent with it.
+
+        Note
+        ----
+        Do not include the `self` parameter in the ``Parameters`` section.
+
+        Parameters
+        ----------
+        param1 : str
+            Description of `param1`.
+        param2 : list of str
+            Description of `param2`. Multiple
+            lines are supported.
+        param3 : int, optional
+            Description of `param3`, defaults to 0.
+
+        """
+        self.attr1 = param1
+        self.attr2 = param2
+        self.attr3 = param3
+
+    def example_method(self, param1, param2):
+        """Class methods are similar to regular functions.
+
+        Note
+        ----
+        Do not include the `self` parameter in the ``Parameters`` section.
+
+        Parameters
+        ----------
+        param1
+            The first parameter.
+        param2
+            The second parameter.
+
+        Returns
+        -------
+        bool
+            True if successful, False otherwise.
+
+        """
+        return True
+
+    def __special__(self):
+        """By default special members with docstrings are included.
+
+        Special members are any methods or attributes that start with and
+        end with a double underscore. Any special member with a docstring
+        will be included in the output.
+
+        This behavior can be disabled by changing the following setting in
+        Sphinx's conf.py::
+
+            napoleon_include_special_with_doc = False
+
+        """
+        pass
+
+    def __special_without_docstring__(self):
+        pass
+
+    def _private(self):
+        """By default private members are not included.
+
+        Private members are any methods or attributes that start with an
+        underscore and are *not* special. By default they are not included
+        in the output.
+
+        This behavior can be changed such that private members *are* included
+        by changing the following setting in Sphinx's conf.py::
+
+            napoleon_include_private_with_doc = True
+
+        """
+        pass
+
+    def _private_without_docstring(self):
+        pass
diff --git a/doc/ext/example_numpy.rst b/doc/ext/example_numpy.rst
new file mode 100644
index 0000000..a3b4161
--- /dev/null
+++ b/doc/ext/example_numpy.rst
@@ -0,0 +1,15 @@
+:orphan:
+
+.. _example_numpy:
+
+Example NumPy Style Python Docstrings
+======================================
+
+.. seealso::
+
+   :ref:`example_google`
+
+Download: :download:`example_numpy.py <example_numpy.py>`
+
+.. literalinclude:: example_numpy.py
+   :language: python
diff --git a/doc/ext/intersphinx.rst b/doc/ext/intersphinx.rst
index 7997472..94047f8 100644
--- a/doc/ext/intersphinx.rst
+++ b/doc/ext/intersphinx.rst
@@ -88,7 +88,7 @@
 
    This will download the corresponding :file:`objects.inv` file from the
    Internet and generate links to the pages under the given URI.  The downloaded
-   inventory is cached in the Sphinx environment, so it must be redownloaded
+   inventory is cached in the Sphinx environment, so it must be re-downloaded
    whenever you do a full rebuild.
 
    A second example, showing the meaning of a non-``None`` value of the second
@@ -99,8 +99,22 @@
 
    This will read the inventory from :file:`python-inv.txt` in the source
    directory, but still generate links to the pages under
-   ``http://docs.python.org/3.2``.  It is up to you to update the inventory file as
-   new objects are added to the Python documentation.
+   ``http://docs.python.org/3.2``.  It is up to you to update the inventory file
+   as new objects are added to the Python documentation.
+
+   **Multiple target for the inventory**
+
+   .. versionadded:: 1.3
+
+   Alternative files can be specified for each inventory. One can give a
+   tuple for the second inventory tuple item as shown in the following
+   example. This will read the inventory iterating through the (second)
+   tuple items until the first successful fetch. The primary use case for
+   this to specify mirror sites for server downtime of the primary
+   inventory::
+
+      intersphinx_mapping = {'python': ('http://docs.python.org/3.2',
+                                        (None, 'python-inv.txt'))}
 
 .. confval:: intersphinx_cache_limit
 
diff --git a/doc/ext/linkcode.rst b/doc/ext/linkcode.rst
index a69a5b1..05d2cc6 100644
--- a/doc/ext/linkcode.rst
+++ b/doc/ext/linkcode.rst
@@ -31,7 +31,8 @@
    - ``py``: ``module`` (name of the module), ``fullname`` (name of the object)
    - ``c``: ``names`` (list of names for the object)
    - ``cpp``: ``names`` (list of names for the object)
-   - ``javascript``: ``object`` (name of the object), ``fullname`` (name of the item)
+   - ``javascript``: ``object`` (name of the object), ``fullname``
+     (name of the item)
 
    Example:
 
diff --git a/doc/ext/math.rst b/doc/ext/math.rst
index 8b2924c..4c15461 100644
--- a/doc/ext/math.rst
+++ b/doc/ext/math.rst
@@ -169,8 +169,8 @@
 
 .. confval:: pngmath_add_tooltips
 
-   Default: true.  If false, do not add the LaTeX code as an "alt" attribute for
-   math images.
+   Default: ``True``.  If false, do not add the LaTeX code as an "alt" attribute
+   for math images.
 
    .. versionadded:: 1.1
 
@@ -197,7 +197,7 @@
 
    The default is the ``http://`` URL that loads the JS files from the `MathJax
    CDN <http://docs.mathjax.org/en/latest/start.html>`_.  If you want MathJax to
-   be available offline, you have to donwload it and set this value to a
+   be available offline, you have to download it and set this value to a
    different path.
 
    The path can be absolute or relative; if it is relative, it is relative to
diff --git a/doc/ext/napoleon.rst b/doc/ext/napoleon.rst
new file mode 100644
index 0000000..8d4a931
--- /dev/null
+++ b/doc/ext/napoleon.rst
@@ -0,0 +1,380 @@
+:mod:`sphinx.ext.napoleon` -- Support for NumPy and Google style docstrings
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. module:: sphinx.ext.napoleon
+   :synopsis: Support for NumPy and Google style docstrings
+
+.. moduleauthor:: Rob Ruana
+
+.. versionadded:: 1.3
+
+Napoleon - *Marching toward legible docstrings*
+===============================================
+
+Are you tired of writing docstrings that look like this::
+
+    :param path: The path of the file to wrap
+    :type path: str
+    :param field_storage: The :class:`FileStorage` instance to wrap
+    :type field_storage: FileStorage
+    :param temporary: Whether or not to delete the file when the File
+       instance is destructed
+    :type temporary: bool
+    :returns: A buffered writable file descriptor
+    :rtype: BufferedFileStorage
+
+`ReStructuredText`_ is great, but it creates visually dense, hard to read
+`docstrings`_. Compare the jumble above to the same thing rewritten
+according to the `Google Python Style Guide`_::
+
+    Args:
+        path (str): The path of the file to wrap
+        field_storage (FileStorage): The :class:`FileStorage` instance to wrap
+        temporary (bool): Whether or not to delete the file when the File
+           instance is destructed
+
+    Returns:
+        BufferedFileStorage: A buffered writable file descriptor
+
+Much more legible, no?
+
+Napoleon is a :doc:`../extensions` that enables Sphinx to parse both `NumPy`_
+and `Google`_ style docstrings - the style recommended by `Khan Academy`_.
+
+Napoleon is a pre-processor that parses `NumPy`_ and `Google`_ style
+docstrings and converts them to reStructuredText before Sphinx attempts to
+parse them. This happens in an intermediate step while Sphinx is processing
+the documentation, so it doesn't modify any of the docstrings in your actual
+source code files.
+
+.. _ReStructuredText: http://docutils.sourceforge.net/rst.html
+.. _docstrings: http://www.python.org/dev/peps/pep-0287/
+.. _Google Python Style Guide:
+   http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
+.. _Google:
+   http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Comments
+.. _NumPy:
+   https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
+.. _Khan Academy:
+   https://sites.google.com/a/khanacademy.org/forge/for-developers/styleguide/python#TOC-Docstrings
+
+Getting Started
+---------------
+
+1. After :doc:`setting up Sphinx <../tutorial>` to build your docs, enable
+   napoleon in the Sphinx `conf.py` file::
+
+       # conf.py
+
+       # Add autodoc and napoleon to the extensions list
+       extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']
+
+2. Use `sphinx-apidoc` to build your API documentation::
+
+       $ sphinx-apidoc -f -o docs/source projectdir
+
+
+Docstrings
+----------
+
+Napoleon interprets every docstring that :mod:`autodoc <sphinx.ext.autodoc>`
+can find, including docstrings on: ``modules``, ``classes``, ``attributes``,
+``methods``, ``functions``, and ``variables``. Inside each docstring,
+specially formatted `Sections`_ are parsed and converted to
+reStructuredText.
+
+All standard reStructuredText formatting still works as expected.
+
+
+.. _Sections:
+
+Docstring Sections
+------------------
+
+All of the following section headers are supported:
+
+    * ``Args`` *(alias of Parameters)*
+    * ``Arguments`` *(alias of Parameters)*
+    * ``Attributes``
+    * ``Example``
+    * ``Examples``
+    * ``Keyword Args`` *(alias of Keyword Arguments)*
+    * ``Keyword Arguments``
+    * ``Methods``
+    * ``Note``
+    * ``Notes``
+    * ``Other Parameters``
+    * ``Parameters``
+    * ``Return`` *(alias of Returns)*
+    * ``Returns``
+    * ``Raises``
+    * ``References``
+    * ``See Also``
+    * ``Warning``
+    * ``Warnings`` *(alias of Warning)*
+    * ``Warns``
+    * ``Yields``
+
+Google vs NumPy
+---------------
+
+Napoleon supports two styles of docstrings: `Google`_ and `NumPy`_. The
+main difference between the two styles is that Google uses indention to
+separate sections, whereas NumPy uses underlines.
+
+Google style::
+
+    def func(arg1, arg2):
+        """Summary line.
+
+        Extended description of function.
+
+        Args:
+            arg1 (int): Description of arg1
+            arg2 (str): Description of arg2
+
+        Returns:
+            bool: Description of return value
+
+        """
+        return True
+
+NumPy style::
+
+    def func(arg1, arg2):
+        """Summary line.
+
+        Extended description of function.
+
+        Parameters
+        ----------
+        arg1 : int
+            Description of arg1
+        arg2 : str
+            Description of arg2
+
+        Returns
+        -------
+        bool
+            Description of return value
+
+        """
+        return True
+
+NumPy style tends to require more vertical space, whereas Google style
+tends to use more horizontal space. Google style tends to be easier to
+read for short and simple docstrings, whereas NumPy style tends be easier
+to read for long and in-depth docstrings.
+
+The `Khan Academy`_ recommends using Google style.
+
+The choice between styles is largely aesthetic, but the two styles should
+not be mixed. Choose one style for your project and be consistent with it.
+
+.. seealso::
+
+   For complete examples:
+
+   * :ref:`example_google`
+   * :ref:`example_numpy`
+
+
+Configuration
+=============
+
+Listed below are all the settings used by napoleon and their default
+values. These settings can be changed in the Sphinx `conf.py` file. Make
+sure that both "sphinx.ext.autodoc" and "sphinx.ext.napoleon" are
+enabled in `conf.py`::
+
+    # conf.py
+
+    # Add any Sphinx extension module names here, as strings
+    extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']
+
+    # Napoleon settings
+    napoleon_google_docstring = True
+    napoleon_numpy_docstring = True
+    napoleon_include_private_with_doc = False
+    napoleon_include_special_with_doc = True
+    napoleon_use_admonition_for_examples = False
+    napoleon_use_admonition_for_notes = False
+    napoleon_use_admonition_for_references = False
+    napoleon_use_ivar = False
+    napoleon_use_param = True
+    napoleon_use_rtype = True
+
+.. _Google style:
+   http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
+.. _NumPy style:
+   https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
+
+
+
+.. confval:: napoleon_google_docstring
+
+   True to parse `Google style`_ docstrings. False to disable support
+   for Google style docstrings. *Defaults to True.*
+
+.. confval:: napoleon_numpy_docstring
+
+   True to parse `NumPy style`_ docstrings. False to disable support
+   for NumPy style docstrings. *Defaults to True.*
+
+.. confval:: napoleon_include_private_with_doc
+
+   True to include private members (like ``_membername``) with docstrings
+   in the documentation. False to fall back to Sphinx's default behavior.
+   *Defaults to False.*
+
+   **If True**::
+
+       def _included(self):
+           """
+           This will be included in the docs because it has a docstring
+           """
+           pass
+
+       def _skipped(self):
+           # This will NOT be included in the docs
+           pass
+
+.. confval:: napoleon_include_special_with_doc
+
+   True to include special members (like ``__membername__``) with
+   docstrings in the documentation. False to fall back to Sphinx's
+   default behavior. *Defaults to True.*
+
+   **If True**::
+
+       def __str__(self):
+           """
+           This will be included in the docs because it has a docstring
+           """
+           return unicode(self).encode('utf-8')
+
+       def __unicode__(self):
+           # This will NOT be included in the docs
+           return unicode(self.__class__.__name__)
+
+.. confval:: napoleon_use_admonition_for_examples
+
+   True to use the ``.. admonition::`` directive for the **Example** and
+   **Examples** sections. False to use the ``.. rubric::`` directive
+   instead. One may look better than the other depending on what HTML
+   theme is used. *Defaults to False.*
+
+   This `NumPy style`_ snippet will be converted as follows::
+
+       Example
+       -------
+       This is just a quick example
+
+   **If True**::
+
+       .. admonition:: Example
+
+          This is just a quick example
+
+   **If False**::
+
+       .. rubric:: Example
+
+       This is just a quick example
+
+.. confval:: napoleon_use_admonition_for_notes
+
+   True to use the ``.. admonition::`` directive for **Notes** sections.
+   False to use the ``.. rubric::`` directive instead. *Defaults to False.*
+
+   .. note:: The singular **Note** section will always be converted to a
+      ``.. note::`` directive.
+
+   .. seealso::
+
+      :attr:`napoleon_use_admonition_for_examples`
+
+.. confval:: napoleon_use_admonition_for_references
+
+   True to use the ``.. admonition::`` directive for **References**
+   sections. False to use the ``.. rubric::`` directive instead.
+   *Defaults to False.*
+
+   .. seealso::
+
+      :attr:`napoleon_use_admonition_for_examples`
+
+.. confval:: napoleon_use_ivar
+
+   True to use the ``:ivar:`` role for instance variables. False to use
+   the ``.. attribute::`` directive instead. *Defaults to False.*
+
+   This `NumPy style`_ snippet will be converted as follows::
+
+       Attributes
+       ----------
+       attr1 : int
+           Description of `attr1`
+
+   **If True**::
+
+       :ivar attr1: Description of `attr1`
+       :vartype attr1: int
+
+   **If False**::
+
+       .. attribute:: attr1
+
+          *int*
+
+          Description of `attr1`
+
+.. confval:: napoleon_use_param
+
+   True to use a ``:param:`` role for each function parameter. False to
+   use a single ``:parameters:`` role for all the parameters.
+   *Defaults to True.*
+
+   This `NumPy style`_ snippet will be converted as follows::
+
+       Parameters
+       ----------
+       arg1 : str
+           Description of `arg1`
+       arg2 : int, optional
+           Description of `arg2`, defaults to 0
+
+   **If True**::
+
+       :param arg1: Description of `arg1`
+       :type arg1: str
+       :param arg2: Description of `arg2`, defaults to 0
+       :type arg2: int, optional
+
+   **If False**::
+
+       :parameters: * **arg1** (*str*) --
+                      Description of `arg1`
+                    * **arg2** (*int, optional*) --
+                      Description of `arg2`, defaults to 0
+
+.. confval:: napoleon_use_rtype
+
+   True to use the ``:rtype:`` role for the return type. False to output
+   the return type inline with the description. *Defaults to True.*
+
+   This `NumPy style`_ snippet will be converted as follows::
+
+       Returns
+       -------
+       bool
+           True if successful, False otherwise
+
+   **If True**::
+
+       :returns: True if successful, False otherwise
+       :rtype: bool
+
+   **If False**::
+
+       :returns: *bool* -- True if successful, False otherwise
diff --git a/doc/ext/oldcmarkup.rst b/doc/ext/oldcmarkup.rst
deleted file mode 100644
index 0fdd9fe..0000000
--- a/doc/ext/oldcmarkup.rst
+++ /dev/null
@@ -1,35 +0,0 @@
-:mod:`sphinx.ext.oldcmarkup` -- Compatibility extension for old C markup
-========================================================================
-
-.. module:: sphinx.ext.oldcmarkup
-   :synopsis: Allow further use of the pre-domain C markup
-.. moduleauthor:: Georg Brandl
-
-.. versionadded:: 1.0
-
-
-This extension is a transition helper for projects that used the old
-(pre-domain) C markup, i.e. the directives like ``cfunction`` and roles like
-``cfunc``.  Since the introduction of domains, they must be called by their
-fully-qualified name (``c:function`` and ``c:func``, respectively) or, with the
-default domain set to ``c``, by their new name (``function`` and ``func``).
-(See :ref:`c-domain` for the details.)
-
-If you activate this extension, it will register the old names, and you can
-use them like before Sphinx 1.0.  The directives are:
-
-- ``cfunction``
-- ``cmember``
-- ``cmacro``
-- ``ctype``
-- ``cvar``
-
-The roles are:
-
-- ``cdata``
-- ``cfunc``
-- ``cmacro``
-- ``ctype``
-
-However, it is advised to migrate to the new markup -- this extension is a
-compatibility convenience and will disappear in a future version of Sphinx.
diff --git a/doc/ext/todo.rst b/doc/ext/todo.rst
index 349d286..c0d94ba 100644
--- a/doc/ext/todo.rst
+++ b/doc/ext/todo.rst
@@ -13,18 +13,19 @@
 
    Use this directive like, for example, :rst:dir:`note`.
 
-   It will only show up in the output if :confval:`todo_include_todos` is true.
+   It will only show up in the output if :confval:`todo_include_todos` is
+   ``True``.
 
 
 .. rst:directive:: todolist
 
    This directive is replaced by a list of all todo directives in the whole
-   documentation, if :confval:`todo_include_todos` is true.
+   documentation, if :confval:`todo_include_todos` is ``True``.
 
 
 There is also an additional config value:
 
 .. confval:: todo_include_todos
 
-   If this is ``True``, :rst:dir:`todo` and :rst:dir:`todolist` produce output, else
-   they produce nothing.  The default is ``False``.
+   If this is ``True``, :rst:dir:`todo` and :rst:dir:`todolist` produce output,
+   else they produce nothing.  The default is ``False``.
diff --git a/doc/ext/viewcode.rst b/doc/ext/viewcode.rst
index ba6c8f8..f2b6c92 100644
--- a/doc/ext/viewcode.rst
+++ b/doc/ext/viewcode.rst
@@ -16,4 +16,25 @@
 from the source to the description will also be inserted.
 
 There are currently no configuration values for this extension; you just need to
-add ``'sphinx.ext.viewcode'`` to your :confval:`extensions` value for it to work.
+add ``'sphinx.ext.viewcode'`` to your :confval:`extensions` value for it to
+work.
+
+There is also an additional config value:
+
+.. confval:: viewcode_import
+
+   If this is ``True``, viewcode extension will follow alias objects that
+   imported from another module such as functions, classes and attributes.
+   As side effects, this option
+   else they produce nothing.  The default is ``True``.
+
+   .. warning::
+
+      :confval:`viewcode_import` **imports** the modules to be followed real
+      location.  If any modules have side effects on import, these will be
+      executed by ``viewcode`` when ``sphinx-build`` is run.
+
+      If you document scripts (as opposed to library modules), make sure their
+      main routine is protected by a ``if __name__ == '__main__'`` condition.
+
+   .. versionadded:: 1.3
diff --git a/doc/extdev/appapi.rst b/doc/extdev/appapi.rst
index 0321f5e..8df8194 100644
--- a/doc/extdev/appapi.rst
+++ b/doc/extdev/appapi.rst
@@ -82,16 +82,31 @@
 
    Register an event called *name*.  This is needed to be able to emit it.
 
+.. method:: Sphinx.set_translator(name, translator_class)
+               
+   Register or override a Docutils translator class. This is used to register
+   a custom output translator or to replace a builtin translator.
+   This allows extensions to use custom translator and define custom
+   nodes for the translator (see :meth:`add_node`).
+
+   This is a API version of :confval:`html_translator_class` for all other
+   builders. Note that if :confval:`html_translator_class` is specified and
+   this API is called for html related builders, API overriding takes
+   precedence.
+
+   .. versionadded:: 1.3
+
 .. method:: Sphinx.add_node(node, **kwds)
 
    Register a Docutils node class.  This is necessary for Docutils internals.
    It may also be used in the future to validate nodes in the parsed documents.
 
    Node visitor functions for the Sphinx HTML, LaTeX, text and manpage writers
-   can be given as keyword arguments: the keyword must be one or more of
-   ``'html'``, ``'latex'``, ``'text'``, ``'man'``, ``'texinfo'``, the value a
-   2-tuple of ``(visit, depart)`` methods.  ``depart`` can be ``None`` if the
-   ``visit`` function raises :exc:`docutils.nodes.SkipNode`.  Example:
+   can be given as keyword arguments: the keyword should be one or more of
+   ``'html'``, ``'latex'``, ``'text'``, ``'man'``, ``'texinfo'`` or any other
+   supported translators, the value a 2-tuple of ``(visit, depart)`` methods.
+   ``depart`` can be ``None`` if the ``visit`` function raises
+   :exc:`docutils.nodes.SkipNode`.  Example:
 
    .. code-block:: python
 
@@ -131,8 +146,8 @@
      The directive class must inherit from the class
      ``docutils.parsers.rst.Directive``.
 
-   For example, the (already existing) :rst:dir:`literalinclude` directive would be
-   added like this:
+   For example, the (already existing) :rst:dir:`literalinclude` directive would
+   be added like this:
 
    .. code-block:: python
 
@@ -212,10 +227,13 @@
       .. index:: pair: function; directive
 
    The reference node will be of class ``literal`` (so it will be rendered in a
-   proportional font, as appropriate for code) unless you give the *ref_nodeclass*
-   argument, which must be a docutils node class (most useful are
-   ``docutils.nodes.emphasis`` or ``docutils.nodes.strong`` -- you can also use
-   ``docutils.nodes.generated`` if you want no further text decoration).
+   proportional font, as appropriate for code) unless you give the
+   *ref_nodeclass* argument, which must be a docutils node class.  Most useful
+   are ``docutils.nodes.emphasis`` or ``docutils.nodes.strong`` -- you can also
+   use ``docutils.nodes.generated`` if you want no further text decoration.  If
+   the text should be treated as literal (e.g. no smart quote replacement), but
+   not have typewriter styling, use ``sphinx.addnodes.literal_emphasis`` or
+   ``sphinx.addnodes.literal_strong``.
 
    For the role content, you have the same syntactical possibilities as for
    standard Sphinx roles (see :ref:`xref-syntax`).
@@ -229,8 +247,8 @@
    directive it generates must be empty, and will produce no output.
 
    That means that you can add semantic targets to your sources, and refer to
-   them using custom roles instead of generic ones (like :rst:role:`ref`).  Example
-   call::
+   them using custom roles instead of generic ones (like :rst:role:`ref`).
+   Example call::
 
       app.add_crossref_type('topic', 'topic', 'single: %s', docutils.nodes.emphasis)
 
diff --git a/doc/extdev/index.rst b/doc/extdev/index.rst
index b76928c..a82f33a 100644
--- a/doc/extdev/index.rst
+++ b/doc/extdev/index.rst
@@ -18,6 +18,11 @@
 notifies Sphinx of everything the extension offers -- see the extension tutorial
 for examples.
 
+.. versionadded:: 1.3
+   The ``setup()`` function can return a string, this is treated by Sphinx as
+   the version of the extension and used for informational purposes such as the
+   traceback file when an exception occurs.
+
 The configuration file itself can be treated as an extension if it contains a
 ``setup()`` function.  All other extensions to load must be listed in the
 :confval:`extensions` configuration value.
diff --git a/doc/extdev/tutorial.rst b/doc/extdev/tutorial.rst
index a03d6e0..8f1773c 100644
--- a/doc/extdev/tutorial.rst
+++ b/doc/extdev/tutorial.rst
@@ -45,7 +45,7 @@
    parsed documents into an output format, or otherwise process them (e.g. check
    external links).
 
-   If you have the application object, the environment is available as
+   If you have the application object, the builder is available as
    ``app.builder``.
 
 **Config**
@@ -162,6 +162,8 @@
        app.connect('doctree-resolved', process_todo_nodes)
        app.connect('env-purge-doc', purge_todos)
 
+       return '0.1'   # identifies the version of our extension
+
 The calls in this function refer to classes and functions not yet written.  What
 the individual calls do is the following:
 
diff --git a/doc/extensions.rst b/doc/extensions.rst
index b2adbc1..b0d98e3 100644
--- a/doc/extensions.rst
+++ b/doc/extensions.rst
@@ -31,7 +31,7 @@
    ext/extlinks
    ext/viewcode
    ext/linkcode
-   ext/oldcmarkup
+   ext/napoleon
 
 
 Third-party extensions
diff --git a/doc/faq.rst b/doc/faq.rst
index 7aa35d1..7a49aed 100644
--- a/doc/faq.rst
+++ b/doc/faq.rst
@@ -10,9 +10,9 @@
 -----------
 
 ... create PDF files without LaTeX?
-   You can use `rst2pdf <http://rst2pdf.googlecode.com>`_ version 0.12 or greater
-   which comes with built-in Sphinx integration.  See the :ref:`builders`
-   section for details.
+   You can use `rst2pdf <http://rst2pdf.googlecode.com>`_ version 0.12 or
+   greater which comes with built-in Sphinx integration.  See the
+   :ref:`builders` section for details.
 
 ... get section numbers?
    They are automatic in LaTeX output; for HTML, give a ``:numbered:`` option to
@@ -32,9 +32,9 @@
    See the :ref:`extension tutorial <exttut>`.
 
 ... convert from my existing docs using MoinMoin markup?
-   The easiest way is to convert to xhtml, then convert `xhtml to reST`_.  You'll
-   still need to mark up classes and such, but the headings and code examples
-   come through cleanly.
+   The easiest way is to convert to xhtml, then convert `xhtml to reST`_.
+   You'll still need to mark up classes and such, but the headings and code
+   examples come through cleanly.
 
 ... create HTML slides from Sphinx documents?
    See the "Hieroglyph" package at https://github.com/nyergler/hieroglyph.
@@ -50,10 +50,11 @@
 --------------------
 
 Read the Docs
-    https://readthedocs.org is a documentation hosting service based around Sphinx.
-    They will host sphinx documentation, along with supporting a number of other
-    features including version support, PDF generation, and more. The `Getting
-    Started <http://read-the-docs.readthedocs.org/en/latest/getting_started.html>`_
+    https://readthedocs.org is a documentation hosting service based around
+    Sphinx. They will host sphinx documentation, along with supporting a number
+    of other features including version support, PDF generation, and more. The
+    `Getting Started
+    <http://read-the-docs.readthedocs.org/en/latest/getting_started.html>`_
     guide is a good place to start.
 
 Epydoc
@@ -70,8 +71,8 @@
 
 PyPI
    Jannis Leidel wrote a `setuptools command
-   <https://pypi.python.org/pypi/Sphinx-PyPI-upload>`_ that automatically uploads
-   Sphinx documentation to the PyPI package documentation area at
+   <https://pypi.python.org/pypi/Sphinx-PyPI-upload>`_ that automatically
+   uploads Sphinx documentation to the PyPI package documentation area at
    http://pythonhosted.org/.
 
 GitHub Pages
diff --git a/doc/glossary.rst b/doc/glossary.rst
index 8bc393e..3ef1623 100644
--- a/doc/glossary.rst
+++ b/doc/glossary.rst
@@ -12,7 +12,7 @@
       use the builder builders that e.g. check for broken links in the
       documentation, or build coverage information.
 
-      See :ref:`builders` for an overview over Sphinx' built-in builders.
+      See :ref:`builders` for an overview over Sphinx's built-in builders.
 
    configuration directory
       The directory containing :file:`conf.py`.  By default, this is the same as
@@ -37,11 +37,11 @@
    document name
       Since reST source files can have different extensions (some people like
       ``.txt``, some like ``.rst`` -- the extension can be configured with
-      :confval:`source_suffix`) and different OSes have different path separators,
-      Sphinx abstracts them: :dfn:`document names` are always relative to the
-      :term:`source directory`, the extension is stripped, and path separators
-      are converted to slashes.  All values, parameters and such referring to
-      "documents" expect such document names.
+      :confval:`source_suffix`) and different OSes have different path
+      separators, Sphinx abstracts them: :dfn:`document names` are always
+      relative to the :term:`source directory`, the extension is stripped, and
+      path separators are converted to slashes.  All values, parameters and such
+      referring to "documents" expect such document names.
 
       Examples for document names are ``index``, ``library/zipfile``, or
       ``reference/datamodel/types``.  Note that there is no leading or trailing
@@ -70,8 +70,8 @@
 
    object
       The basic building block of Sphinx documentation.  Every "object
-      directive" (e.g. :rst:dir:`function` or :rst:dir:`object`) creates such a block;
-      and most objects can be cross-referenced to.
+      directive" (e.g. :rst:dir:`function` or :rst:dir:`object`) creates such a
+      block; and most objects can be cross-referenced to.
 
    role
       A reStructuredText markup element that allows marking a piece of text.
diff --git a/doc/install.rst b/doc/install.rst
index bf65387..71e37e9 100644
--- a/doc/install.rst
+++ b/doc/install.rst
@@ -4,7 +4,7 @@
 =================
 
 Since Sphinx is written in the Python language, you need to install Python
-(the required version is at least 2.5) and Sphinx.
+(the required version is at least 2.6) and Sphinx.
 
 Sphinx packages are available on the `Python Package Index
 <https://pypi.python.org/pypi/Sphinx>`_.
@@ -79,8 +79,8 @@
 
 .. note::
 
-   Currently, Python offers two major versions, 2.x and 3.x. Sphinx 1.2 can run
-   under Python 2.5 to 2.7 and 3.1 to 3.3, with the recommended version being
+   Currently, Python offers two major versions, 2.x and 3.x. Sphinx 1.3 can run
+   under Python 2.6, 2.7, 3.2, 3.3, with the recommended version being
    2.7.  This chapter assumes you have installed Python 2.7.
 
 Follow the Windows installer for Python.
diff --git a/doc/intl.rst b/doc/intl.rst
index 3363dc5..c4859d0 100644
--- a/doc/intl.rst
+++ b/doc/intl.rst
@@ -38,9 +38,9 @@
 way to do that.
 
 After Sphinx successfully ran the
-:class:`~sphinx.builders.gettext.MessageCatalogBuilder` you will find a collection
-of ``.pot`` files in your output directory.  These are **catalog templates**
-and contain messages in your original language *only*.
+:class:`~sphinx.builders.gettext.MessageCatalogBuilder` you will find a
+collection of ``.pot`` files in your output directory.  These are **catalog
+templates** and contain messages in your original language *only*.
 
 They can be delivered to translators which will transform them to ``.po`` files
 --- so called **message catalogs** --- containing a mapping from the original
@@ -202,10 +202,13 @@
 
    .. code-block:: bash
 
-      $ tx init --user=<transifex-username> --pass=<transifex-password>
+      $ tx init
       Creating .tx folder...
       Transifex instance [https://www.transifex.com]:
       ...
+      Please enter your transifex username: <transifex-username>
+      Password: <transifex-password>
+      ...
       Done.
 
 #. Upload pot files to transifex service
@@ -285,7 +288,7 @@
 
 .. rubric:: Footnotes
 
-.. [1] See the `GNU gettext utilites
+.. [1] See the `GNU gettext utilities
        <http://www.gnu.org/software/gettext/manual/gettext.html#Introduction>`_
        for details on that software suite.
 .. [2] Because nobody expects the Spanish Inquisition!
diff --git a/doc/intro.rst b/doc/intro.rst
index 66d0c58..a796d93 100644
--- a/doc/intro.rst
+++ b/doc/intro.rst
@@ -54,8 +54,8 @@
 Prerequisites
 -------------
 
-Sphinx needs at least **Python 2.5** or **Python 3.1** to run, as well as the
-docutils_ and Jinja2_ libraries.  Sphinx should work with docutils version 0.7
+Sphinx needs at least **Python 2.6** or **Python 3.2** to run, as well as the
+docutils_ and Jinja2_ libraries.  Sphinx should work with docutils version 0.10
 or some (not broken) SVN trunk snapshot.  If you like to have source code
 highlighting support, you must also install the Pygments_ library.
 
diff --git a/doc/invocation.rst b/doc/invocation.rst
index 654921b..d347f50 100644
--- a/doc/invocation.rst
+++ b/doc/invocation.rst
@@ -83,8 +83,8 @@
 
 .. option:: -t tag
 
-   Define the tag *tag*.  This is relevant for :rst:dir:`only` directives that only
-   include their content if this tag is set.
+   Define the tag *tag*.  This is relevant for :rst:dir:`only` directives that
+   only include their content if this tag is set.
 
    .. versionadded:: 0.6
 
@@ -124,13 +124,22 @@
 .. option:: -D setting=value
 
    Override a configuration value set in the :file:`conf.py` file.  The value
-   must be a string or dictionary value.  For the latter, supply the setting
-   name and key like this: ``-D latex_elements.docclass=scrartcl``.  For boolean
-   values, use ``0`` or ``1`` as the value.
+   must be a number, string, list or dictionary value.
+
+   For lists, you can separate elements with a comma like this: ``-D
+   html_theme_path=path1,path2``.
+
+   For dictionary values, supply the setting name and key like this:
+   ``-D latex_elements.docclass=scrartcl``.
+
+   For boolean values, use ``0`` or ``1`` as the value.
 
    .. versionchanged:: 0.6
       The value can now be a dictionary value.
 
+   .. versionchanged:: 1.3
+      The value can now also be a list value.
+
 .. option:: -A name=value
 
    Make the *name* assigned to *value* in the HTML templates.
@@ -145,8 +154,7 @@
 
 .. option:: -N
 
-   Do not emit colored output.  (On Windows, colored output is disabled in any
-   case.)
+   Do not emit colored output.
 
 .. option:: -v
 
diff --git a/doc/man/sphinx-build.rst b/doc/man/sphinx-build.rst
index aa1d71c..13564ff 100644
--- a/doc/man/sphinx-build.rst
+++ b/doc/man/sphinx-build.rst
@@ -102,12 +102,14 @@
                       Configuration can only be set with the -D option.
 -D <setting=value>    Override a setting from the configuration file.
 -t <tag>              Define *tag* for use in "only" blocks.
--A <name=value>       Pass a value into the HTML templates (only for HTML builders).
+-A <name=value>       Pass a value into the HTML templates (only for HTML
+                      builders).
 -n                    Run in nit-picky mode, warn about all missing references.
 -v                    Increase verbosity (can be repeated).
 -N                    Prevent colored output.
 -q                    Quiet operation, just print warnings and errors on stderr.
--Q                    Very quiet operation, don't print anything except for errors.
+-Q                    Very quiet operation, don't print anything except for
+                      errors.
 -w <file>             Write warnings and errors into the given file, in addition
                       to stderr.
 -W                    Turn warnings into errors.
diff --git a/doc/markup/code.rst b/doc/markup/code.rst
index 957774f..f69bb16 100644
--- a/doc/markup/code.rst
+++ b/doc/markup/code.rst
@@ -79,14 +79,22 @@
 
 This will produce line numbers for all code blocks longer than five lines.
 
-For :rst:dir:`code-block` blocks, a ``linenos`` flag option can be given to switch
-on line numbers for the individual block::
+For :rst:dir:`code-block` blocks, a ``linenos`` flag option can be given to
+switch on line numbers for the individual block::
 
    .. code-block:: ruby
       :linenos:
 
       Some more Ruby code.
 
+The first line number can be selected with the ``lineno-start`` option.  If
+present, ``linenos`` is automatically activated as well.
+
+   .. code-block:: ruby
+      :lineno-start: 10
+
+      Some more Ruby code, with line numbering starting at 10.
+
 Additionally, an ``emphasize-lines`` option can be given to have Pygments
 emphasize particular lines::
 
@@ -102,16 +110,19 @@
 .. versionchanged:: 1.1
    ``emphasize-lines`` has been added.
 
+.. versionchanged:: 1.3
+   ``lineno-start`` has been added.
+
 
 Includes
 ^^^^^^^^
 
 .. rst:directive:: .. literalinclude:: filename
 
-   Longer displays of verbatim text may be included by storing the example text in
-   an external file containing only plain text.  The file may be included using the
-   ``literalinclude`` directive. [1]_ For example, to include the Python source file
-   :file:`example.py`, use::
+   Longer displays of verbatim text may be included by storing the example text
+   in an external file containing only plain text.  The file may be included
+   using the ``literalinclude`` directive. [1]_ For example, to include the
+   Python source file :file:`example.py`, use::
 
       .. literalinclude:: example.py
 
@@ -122,10 +133,11 @@
    Tabs in the input are expanded if you give a ``tab-width`` option with the
    desired tab width.
 
-   The directive also supports the ``linenos`` flag option to switch on line
-   numbers, the ``emphasize-lines`` option to emphasize particular lines, and
-   a ``language`` option to select a language different from the current
-   file's standard language.  Example with options::
+   Like :rst:dir:`code-block`, the directive supports the ``linenos`` flag
+   option to switch on line numbers, the ``lineno-start`` option to select the
+   first line number, the ``emphasize-lines`` option to emphasize particular
+   lines, and a ``language`` option to select a language different from the
+   current file's standard language.  Example with options::
 
       .. literalinclude:: example.rb
          :language: ruby
@@ -168,6 +180,16 @@
    ``prepend`` and ``append`` option, respectively.  This is useful e.g. for
    highlighting PHP code that doesn't include the ``<?php``/``?>`` markers.
 
+
+   If you want to show the diff of the code, you can specify the old
+   file by giving a ``diff`` option::
+
+      .. literalinclude:: example.py
+         :diff: example.py.orig
+
+   This shows the diff between example.py and example.py.orig with unified diff format.
+
+
    .. versionadded:: 0.4.3
       The ``encoding`` option.
    .. versionadded:: 0.6
@@ -175,6 +197,43 @@
       as well as support for absolute filenames.
    .. versionadded:: 1.0
       The ``prepend`` and ``append`` options, as well as ``tab-width``.
+   .. versionadded:: 1.3
+      The ``diff`` option.
+
+
+Showing a file name
+^^^^^^^^^^^^^^^^^^^
+
+.. versionadded:: 1.3
+
+A ``caption`` option can be given to show that name before the code block.  For
+example::
+
+   .. code-block:: python
+      :caption: this.py
+
+      print 'Explicit is better than implicit.'
+
+
+:rst:dir:`literalinclude` also supports the ``caption`` option, with the
+additional feature that if you leave the value empty, the shown filename will be
+exactly the one given as an argument.
+
+
+Dedent
+^^^^^^
+
+.. versionadded:: 1.3
+
+A ``dedent`` option can be given to strip a precedence characters from the code
+block. For example::
+
+   .. literalinclude:: example.rb
+      :language: ruby
+      :dedent: 4
+      :lines: 10-15
+
+:rst:dir:`code-block` also supports the ``dedent`` option.
 
 
 .. rubric:: Footnotes
diff --git a/doc/markup/inline.rst b/doc/markup/inline.rst
index 69dd832..0cc97f4 100644
--- a/doc/markup/inline.rst
+++ b/doc/markup/inline.rst
@@ -24,7 +24,7 @@
 
 Cross-references are generated by many semantic interpreted text roles.
 Basically, you only need to write ``:role:`target```, and a link will be created
-to the item named *target* of the type indicated by *role*.  The links's text
+to the item named *target* of the type indicated by *role*.  The link's text
 will be the same as *target*.
 
 There are some additional facilities, however, that make cross-referencing roles
@@ -102,9 +102,10 @@
      to, but you must give the link an explicit title, using this syntax:
      ``:ref:`Link title <label-name>```.
 
-   Using :rst:role:`ref` is advised over standard reStructuredText links to sections
-   (like ```Section title`_``) because it works across files, when section
-   headings are changed, and for all builders that support cross-references.
+   Using :rst:role:`ref` is advised over standard reStructuredText links to
+   sections (like ```Section title`_``) because it works across files, when
+   section headings are changed, and for all builders that support
+   cross-references.
 
 
 Cross-referencing documents
@@ -349,8 +350,8 @@
 Substitutions
 ~~~~~~~~~~~~~
 
-The documentation system provides three substitutions that are defined by default.
-They are set in the build configuration file.
+The documentation system provides three substitutions that are defined by
+default. They are set in the build configuration file.
 
 .. describe:: |release|
 
diff --git a/doc/markup/misc.rst b/doc/markup/misc.rst
index 5a391d0..fd31480 100644
--- a/doc/markup/misc.rst
+++ b/doc/markup/misc.rst
@@ -52,16 +52,16 @@
 
    By default, this markup isn't reflected in the output in any way (it helps
    keep track of contributions), but you can set the configuration value
-   :confval:`show_authors` to True to make them produce a paragraph in the
+   :confval:`show_authors` to ``True`` to make them produce a paragraph in the
    output.
 
 
 .. rst:directive:: .. codeauthor:: name <email>
 
-   The :rst:dir:`codeauthor` directive, which can appear multiple times, names the
-   authors of the described code, just like :rst:dir:`sectionauthor` names the
-   author(s) of a piece of documentation.  It too only produces output if the
-   :confval:`show_authors` configuration value is True.
+   The :rst:dir:`codeauthor` directive, which can appear multiple times, names
+   the authors of the described code, just like :rst:dir:`sectionauthor` names
+   the author(s) of a piece of documentation.  It too only produces output if
+   the :confval:`show_authors` configuration value is ``True``.
 
 
 Index-generating markup
@@ -189,6 +189,14 @@
    These standard tags are set *after* the configuration file is read, so they
    are not available there.
 
+   All tags must follow the standard Python identifier syntax as set out in
+   the `Identifiers and keywords
+   <https://docs.python.org/reference/lexical_analysis.html#identifiers>`_
+   documentation.  That is, a tag expression may only consist of tags that
+   conform to the syntax of Python variables.  In ASCII, this consists of the
+   uppercase and lowercase letters ``A`` through ``Z``, the underscore ``_``
+   and, except for the first character, the digits ``0`` through ``9``.
+
    .. versionadded:: 0.6
    .. versionchanged:: 1.2
       Added the name of the builder and the prefixes.
diff --git a/doc/markup/para.rst b/doc/markup/para.rst
index b532bc6..c6a49b1 100644
--- a/doc/markup/para.rst
+++ b/doc/markup/para.rst
@@ -70,12 +70,12 @@
    external documents.  These lists are created using the :rst:dir:`seealso`
    directive.
 
-   The :rst:dir:`seealso` directive is typically placed in a section just before any
-   sub-sections.  For the HTML output, it is shown boxed off from the main flow
-   of the text.
+   The :rst:dir:`seealso` directive is typically placed in a section just before
+   any subsections.  For the HTML output, it is shown boxed off from the main
+   flow of the text.
 
-   The content of the :rst:dir:`seealso` directive should be a reST definition list.
-   Example::
+   The content of the :rst:dir:`seealso` directive should be a reST definition
+   list. Example::
 
       .. seealso::
 
@@ -206,8 +206,8 @@
    continuation line must begin with a colon placed at the same column as in the
    first line.
 
-   The argument to :rst:dir:`productionlist` serves to distinguish different sets of
-   production lists that belong to different grammars.
+   The argument to :rst:dir:`productionlist` serves to distinguish different
+   sets of production lists that belong to different grammars.
 
    Blank lines are not allowed within ``productionlist`` directive arguments.
 
diff --git a/doc/more.png b/doc/more.png
index 3eb7b05..a27a0fc 100644
--- a/doc/more.png
+++ b/doc/more.png
Binary files differ
diff --git a/doc/pythonorg.png b/doc/pythonorg.png
index 83b54df..32f0787 100644
--- a/doc/pythonorg.png
+++ b/doc/pythonorg.png
Binary files differ
diff --git a/doc/rest.rst b/doc/rest.rst
index b5efbf9..c6a4ada 100644
--- a/doc/rest.rst
+++ b/doc/rest.rst
@@ -312,7 +312,7 @@
   - :dudir:`default-role` (set a new default role)
   - :dudir:`role` (create a new role)
 
-  Since these are only per-file, better use Sphinx' facilities for setting the
+  Since these are only per-file, better use Sphinx's facilities for setting the
   :confval:`default_role`.
 
 Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and
@@ -485,5 +485,6 @@
 
 .. rubric:: Footnotes
 
-.. [1] When the default domain contains a :rst:dir:`class` directive, this directive
-       will be shadowed.  Therefore, Sphinx re-exports it as :rst:dir:`rst-class`.
+.. [1] When the default domain contains a :rst:dir:`class` directive, this
+       directive will be shadowed.  Therefore, Sphinx re-exports it as
+       :rst:dir:`rst-class`.
diff --git a/doc/templating.rst b/doc/templating.rst
index b9561b6..fde00ef 100644
--- a/doc/templating.rst
+++ b/doc/templating.rst
@@ -11,8 +11,8 @@
 excellent documentation for those who need to make themselves familiar with it.
 
 
-Do I need to use Sphinx' templates to produce HTML?
----------------------------------------------------
+Do I need to use Sphinx's templates to produce HTML?
+----------------------------------------------------
 
 No.  You have several other options:
 
@@ -50,7 +50,7 @@
 template is evaluated, **tags**, which control the logic of the template and
 **blocks** which are used for template inheritance.
 
-Sphinx' *basic* theme provides base templates with a couple of blocks it will
+Sphinx's *basic* theme provides base templates with a couple of blocks it will
 fill with data.  These are located in the :file:`themes/basic` subdirectory of
 the Sphinx installation directory, and used by all builtin Sphinx themes.
 Templates with the same name in the :confval:`templates_path` override templates
@@ -273,7 +273,7 @@
 .. data:: has_source
 
    True if the reST document sources are copied (if :confval:`html_copy_source`
-   is true).
+   is ``True``).
 
 .. data:: last_updated
 
@@ -333,7 +333,7 @@
 
 .. data:: show_source
 
-   True if :confval:`html_show_sourcelink` is true.
+   True if :confval:`html_show_sourcelink` is ``True``.
 
 .. data:: sphinx_version
 
@@ -372,7 +372,7 @@
 .. data:: sourcename
 
    The name of the copied source file for the current document.  This is only
-   nonempty if the :confval:`html_copy_source` value is true.
+   nonempty if the :confval:`html_copy_source` value is ``True``.
 
 .. data:: toc
 
@@ -384,14 +384,14 @@
    A callable yielding the global TOC tree containing the current page, rendered
    as HTML bullet lists.  Optional keyword arguments:
 
-   * ``collapse`` (true by default): if true, all TOC entries that are not
+   * ``collapse`` (``True`` by default): if true, all TOC entries that are not
      ancestors of the current page are collapsed
 
    * ``maxdepth`` (defaults to the max depth selected in the toctree directive):
      the maximum depth of the tree; set it to ``-1`` to allow unlimited depth
 
-   * ``titles_only`` (false by default): if true, put only toplevel document
+   * ``titles_only`` (``False`` by default): if true, put only toplevel document
      titles in the tree
 
-   * ``includehidden`` (false by default): if true, the TOC tree will also
+   * ``includehidden`` (``False`` by default): if true, the TOC tree will also
      contain hidden entries.
diff --git a/doc/themes/agogo.png b/doc/themes/agogo.png
index d29aa45..453a1f7 100644
--- a/doc/themes/agogo.png
+++ b/doc/themes/agogo.png
Binary files differ
diff --git a/doc/themes/bizstyle.png b/doc/themes/bizstyle.png
new file mode 100644
index 0000000..4deae9a
--- /dev/null
+++ b/doc/themes/bizstyle.png
Binary files differ
diff --git a/doc/themes/default.png b/doc/themes/default.png
index 93d8526..6989ebe 100644
--- a/doc/themes/default.png
+++ b/doc/themes/default.png
Binary files differ
diff --git a/doc/themes/fullsize/agogo.png b/doc/themes/fullsize/agogo.png
index 93fadfc..bfdba3a 100644
--- a/doc/themes/fullsize/agogo.png
+++ b/doc/themes/fullsize/agogo.png
Binary files differ
diff --git a/doc/themes/fullsize/bizstyle.png b/doc/themes/fullsize/bizstyle.png
new file mode 100644
index 0000000..d917e2f
--- /dev/null
+++ b/doc/themes/fullsize/bizstyle.png
Binary files differ
diff --git a/doc/themes/fullsize/default.png b/doc/themes/fullsize/default.png
index b6af8bc..9c00f68 100644
--- a/doc/themes/fullsize/default.png
+++ b/doc/themes/fullsize/default.png
Binary files differ
diff --git a/doc/themes/fullsize/haiku.png b/doc/themes/fullsize/haiku.png
index 1590da5..8d807f4 100644
--- a/doc/themes/fullsize/haiku.png
+++ b/doc/themes/fullsize/haiku.png
Binary files differ
diff --git a/doc/themes/fullsize/nature.png b/doc/themes/fullsize/nature.png
index d42957e..02d8743 100644
--- a/doc/themes/fullsize/nature.png
+++ b/doc/themes/fullsize/nature.png
Binary files differ
diff --git a/doc/themes/fullsize/pyramid.png b/doc/themes/fullsize/pyramid.png
index 429a8b7..961cb89 100644
--- a/doc/themes/fullsize/pyramid.png
+++ b/doc/themes/fullsize/pyramid.png
Binary files differ
diff --git a/doc/themes/fullsize/scrolls.png b/doc/themes/fullsize/scrolls.png
index 7d46f7e..4e5c45f 100644
--- a/doc/themes/fullsize/scrolls.png
+++ b/doc/themes/fullsize/scrolls.png
Binary files differ
diff --git a/doc/themes/fullsize/sphinxdoc.png b/doc/themes/fullsize/sphinxdoc.png
index 722fb90..b746334 100644
--- a/doc/themes/fullsize/sphinxdoc.png
+++ b/doc/themes/fullsize/sphinxdoc.png
Binary files differ
diff --git a/doc/themes/fullsize/traditional.png b/doc/themes/fullsize/traditional.png
index 103fd3c..da69efe 100644
--- a/doc/themes/fullsize/traditional.png
+++ b/doc/themes/fullsize/traditional.png
Binary files differ
diff --git a/doc/themes/haiku.png b/doc/themes/haiku.png
index a8ae855..78a2570 100644
--- a/doc/themes/haiku.png
+++ b/doc/themes/haiku.png
Binary files differ
diff --git a/doc/themes/nature.png b/doc/themes/nature.png
index 3d4f587..cbe773d 100644
--- a/doc/themes/nature.png
+++ b/doc/themes/nature.png
Binary files differ
diff --git a/doc/themes/pyramid.png b/doc/themes/pyramid.png
index b16095c..eb13cd5 100644
--- a/doc/themes/pyramid.png
+++ b/doc/themes/pyramid.png
Binary files differ
diff --git a/doc/themes/scrolls.png b/doc/themes/scrolls.png
index 8073c10..30ccc8d 100644
--- a/doc/themes/scrolls.png
+++ b/doc/themes/scrolls.png
Binary files differ
diff --git a/doc/themes/sphinxdoc.png b/doc/themes/sphinxdoc.png
index f4b59ec..31512d8 100644
--- a/doc/themes/sphinxdoc.png
+++ b/doc/themes/sphinxdoc.png
Binary files differ
diff --git a/doc/themes/traditional.png b/doc/themes/traditional.png
index 4ad2b5c..5ff44f8 100644
--- a/doc/themes/traditional.png
+++ b/doc/themes/traditional.png
Binary files differ
diff --git a/doc/theming.rst b/doc/theming.rst
index 73ec9f2..0a2d726 100644
--- a/doc/theming.rst
+++ b/doc/theming.rst
@@ -102,6 +102,10 @@
 |                    |                    |
 | *haiku*            | *pyramid*          |
 +--------------------+--------------------+
+| |bizstyle|         |                    |
+|                    |                    |
+| *bizstyle*         |                    |
++--------------------+--------------------+
 
 .. |default|     image:: themes/default.png
 .. |sphinxdoc|   image:: themes/sphinxdoc.png
@@ -111,6 +115,7 @@
 .. |nature|      image:: themes/nature.png
 .. |haiku|       image:: themes/haiku.png
 .. |pyramid|     image:: themes/pyramid.png
+.. |bizstyle|    image:: themes/bizstyle.png
 
 Sphinx comes with a selection of themes to choose from.
 
@@ -122,7 +127,7 @@
   these options (which are inherited by the other themes):
 
   - **nosidebar** (true or false): Don't include the sidebar.  Defaults to
-    false.
+    ``False``.
 
   - **sidebarwidth** (an integer): Width of the sidebar in pixels.  (Do not
     include ``px`` in the value.)  Defaults to 230 pixels.
@@ -132,18 +137,18 @@
   options:
 
   - **rightsidebar** (true or false): Put the sidebar on the right side.
-    Defaults to false.
+    Defaults to ``False``.
 
   - **stickysidebar** (true or false): Make the sidebar "fixed" so that it
     doesn't scroll out of view for long body content.  This may not work well
-    with all browsers.  Defaults to false.
+    with all browsers.  Defaults to ``False``.
 
   - **collapsiblesidebar** (true or false): Add an *experimental* JavaScript
     snippet that makes the sidebar collapsible via a button on its side.
-    *Doesn't work with "stickysidebar".* Defaults to false.
+    *Doesn't work with "stickysidebar".* Defaults to ``False``.
 
   - **externalrefs** (true or false): Display external links differently from
-    internal links.  Defaults to false.
+    internal links.  Defaults to ``False``.
 
   There are also various color and font options that can change the color scheme
   without having to write a custom stylesheet:
@@ -152,7 +157,7 @@
   - **footertextcolor** (CSS color): Text color for the footer line.
   - **sidebarbgcolor** (CSS color): Background color for the sidebar.
   - **sidebarbtncolor** (CSS color): Background color for the sidebar collapse
-    button (used when *collapsiblesidebar* is true).
+    button (used when *collapsiblesidebar* is ``True``).
   - **sidebartextcolor** (CSS color): Text color for the sidebar.
   - **sidebarlinkcolor** (CSS color): Link color for the sidebar.
   - **relbarbgcolor** (CSS color): Background color for the relation bar.
@@ -218,10 +223,10 @@
   <http://www.haiku-os.org/docs/userguide/en/contents.html>`_.  The following
   options are supported:
 
-  - **full_logo** (true or false, default false): If this is true, the header
-    will only show the :confval:`html_logo`.  Use this for large logos.  If this
-    is false, the logo (if present) will be shown floating right, and the
-    documentation title will be put in the header.
+  - **full_logo** (true or false, default ``False``): If this is true, the
+    header will only show the :confval:`html_logo`.  Use this for large logos.
+    If this is false, the logo (if present) will be shown floating right, and
+    the documentation title will be put in the header.
   - **textcolor**, **headingcolor**, **linkcolor**, **visitedlinkcolor**,
     **hoverlinkcolor** (CSS colors): Colors for various body elements.
 
@@ -232,10 +237,20 @@
   space which is a sparse resource on ebook readers.  The following options
   are supported:
 
-  - **relbar1** (true or false, default true): If this is true, the
+  - **relbar1** (true or false, default ``True``): If this is true, the
     `relbar1` block is inserted in the epub output, otherwise it is omitted.
-  - **footer**  (true or false, default true): If this is true, the
-    `footer` block is inserted in the epub output, otherwise it is ommitted.
+  - **footer**  (true or false, default ``True``): If this is true, the
+    `footer` block is inserted in the epub output, otherwise it is omitted.
+
+- **bizstyle** -- A simple bluish theme. The following options are supported
+  beyond *nosidebar* and *sidebarwidth*:
+
+  - **rightsidebar** (true or false): Put the sidebar on the right side.
+    Defaults to ``False``.
+
+.. versionadded:: 1.3
+   'bizstyle' theme.
+
 
 Creating themes
 ---------------
@@ -318,4 +333,3 @@
 .. [1] It is not an executable Python file, as opposed to :file:`conf.py`,
        because that would pose an unnecessary security risk if themes are
        shared.
-
diff --git a/doc/translation.png b/doc/translation.png
index aa368b6..347e287 100644
--- a/doc/translation.png
+++ b/doc/translation.png
Binary files differ
diff --git a/doc/tutorial.rst b/doc/tutorial.rst
index cae4c8d..0a12a27 100644
--- a/doc/tutorial.rst
+++ b/doc/tutorial.rst
@@ -10,6 +10,15 @@
 the described task.
 
 
+Install Sphinx
+--------------
+
+Install Sphinx, either from a distribution package or from
+`PyPI <https://pypi.python.org/pypi/Sphinx>`_ with ::
+
+   $ pip install Sphinx
+
+
 Setting up the documentation sources
 ------------------------------------
 
@@ -138,7 +147,7 @@
 Documenting objects
 -------------------
 
-One of Sphinx' main objectives is easy documentation of :dfn:`objects` (in a
+One of Sphinx's main objectives is easy documentation of :dfn:`objects` (in a
 very general sense) in any :dfn:`domain`.  A domain is a collection of object
 types that belong together, complete with markup to create and reference
 descriptions of these objects.
@@ -200,7 +209,7 @@
 your documents.  In that file, which is executed as a Python source file, you
 assign configuration values.  For advanced users: since it is executed by
 Sphinx, you can do non-trivial tasks in it, like extending :data:`sys.path` or
-importing a module to find out the version your are documenting.
+importing a module to find out the version you are documenting.
 
 The config values that you probably want to change are already put into the
 :file:`conf.py` by :program:`sphinx-quickstart` and initially commented out
@@ -300,7 +309,7 @@
 
 .. rubric:: Footnotes
 
-.. [#] This is the usual lay-out.  However, :file:`conf.py` can also live in
+.. [#] This is the usual layout.  However, :file:`conf.py` can also live in
        another directory, the :term:`configuration directory`.  See
        :ref:`invocation`.
 
diff --git a/doc/web/quickstart.rst b/doc/web/quickstart.rst
index 1bcd217..eab1919 100644
--- a/doc/web/quickstart.rst
+++ b/doc/web/quickstart.rst
@@ -45,7 +45,7 @@
                         search='xapian')
 
 You'll only need one of these for each set of documentation you will be working
-with.  You can then call it's :meth:`~.WebSupport.get_document` method to access
+with.  You can then call its :meth:`~.WebSupport.get_document` method to access
 individual documents::
 
    contents = support.get_document('contents')
@@ -56,8 +56,8 @@
 * **sidebar**: The sidebar of the document as HTML
 * **relbar**: A div containing links to related documents
 * **title**: The title of the document
-* **css**: Links to css files used by Sphinx
-* **js**: Javascript containing comment options
+* **css**: Links to CSS files used by Sphinx
+* **js**: JavaScript containing comment options
 
 This dict can then be used as context for templates.  The goal is to be easy to
 integrate with your existing templating system.  An example using `Jinja2
@@ -109,8 +109,8 @@
    support.update_username(old_username, new_username)
 
 *username* should be a unique string which identifies a user, and *moderator*
-should be a boolean representing whether the user has moderation privilieges.
-The default value for *moderator* is *False*.
+should be a boolean representing whether the user has moderation privileges.
+The default value for *moderator* is ``False``.
 
 An example `Flask <http://flask.pocoo.org/>`_ function that checks whether a
 user is logged in and then retrieves a document is::
diff --git a/setup.py b/setup.py
index 9872226..9e000d5 100644
--- a/setup.py
+++ b/setup.py
@@ -41,27 +41,21 @@
 * Setuptools integration
 '''
 
-requires = ['Pygments>=1.2', 'docutils>=0.7']
-
-if sys.version_info[:3] >= (3, 3, 0):
-    requires[1] = 'docutils>=0.10'
-
 if sys.version_info < (2, 6) or (3, 0) <= sys.version_info < (3, 3):
-    requires.append('Jinja2>=2.3,<2.7')
-else:
-    requires.append('Jinja2>=2.3')
-
-if sys.version_info < (2, 5):
-    print('ERROR: Sphinx requires at least Python 2.5 to run.')
+    print('ERROR: Sphinx requires at least Python 2.6 or 3.3 to run.')
     sys.exit(1)
 
-# tell distribute to use 2to3 with our own fixers
-extra = {}
-if sys.version_info >= (3, 0):
-    extra.update(
-        use_2to3=True,
-        use_2to3_fixers=['custom_fixers']
-    )
+requires = [
+    'six>=1.4',
+    'Jinja2>=2.3',
+    'Pygments>=1.2',
+    'docutils>=0.10',
+    'snowballstemmer>=1.1',
+    'babel',
+]
+
+if sys.platform == 'win32':
+    requires.append('colorama')
 
 # Provide a "compile_catalog" command that also creates the translated
 # JavaScript files if Babel is available.
@@ -185,7 +179,7 @@
         'Topic :: Utilities',
     ],
     platforms='any',
-    packages=find_packages(exclude=['custom_fixers', 'test']),
+    packages=find_packages(exclude=['test']),
     include_package_data=True,
     entry_points={
         'console_scripts': [
@@ -200,5 +194,4 @@
     },
     install_requires=requires,
     cmdclass=cmdclass,
-    **extra
 )
diff --git a/sphinx/__init__.py b/sphinx/__init__.py
index 49bbc28..cd8baee 100644
--- a/sphinx/__init__.py
+++ b/sphinx/__init__.py
@@ -15,12 +15,12 @@
 import sys
 from os import path
 
-__version__  = '1.2.3+'
-__released__ = '1.2.3'  # used when Sphinx builds its own docs
+__version__  = '1.3a0'
+__released__ = '1.3a0'  # used when Sphinx builds its own docs
 # version info for better programmatic use
 # possible values for 3rd element: 'alpha', 'beta', 'rc', 'final'
 # 'final' has 0 as the last element
-version_info = (1, 2, 3, 'final', 0)
+version_info = (1, 3, 0, 'alpha', 0)
 
 package_dir = path.abspath(path.dirname(__file__))
 
@@ -49,8 +49,9 @@
 
 def build_main(argv=sys.argv):
     """Sphinx build "main" command-line entry."""
-    if sys.version_info[:3] < (2, 5, 0):
-        sys.stderr.write('Error: Sphinx requires at least Python 2.5 to run.\n')
+    if (sys.version_info[:3] < (2, 6, 0) or
+       (3, 0, 0) <= sys.version_info[:3] < (3, 3, 0)):
+        sys.stderr.write('Error: Sphinx requires at least Python 2.6 to run.\n')
         return 1
     try:
         from sphinx import cmdline
@@ -78,12 +79,12 @@
                 sys.stderr.write(hint)
             return 1
         raise
-    if sys.version_info[:3] >= (3, 3, 0):
-        from sphinx.util.compat import docutils_version
-        if docutils_version < (0, 10):
-            sys.stderr.write('Error: Sphinx requires at least '
-                             'Docutils 0.10 for Python 3.3 and above.\n')
-            return 1
+
+    from sphinx.util.compat import docutils_version
+    if docutils_version < (0, 10):
+        sys.stderr.write('Error: Sphinx requires at least Docutils 0.10 to '
+                         'run.\n')
+        return 1
     return cmdline.main(argv)
 
 
diff --git a/sphinx/__main__.py b/sphinx/__main__.py
new file mode 100644
index 0000000..270bc4e
--- /dev/null
+++ b/sphinx/__main__.py
@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.__main__
+    ~~~~~~~~~~~~~~~
+
+    The Sphinx documentation toolchain.
+
+    :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+import sys
+from sphinx import main
+
+sys.exit(main(sys.argv))
diff --git a/sphinx/addnodes.py b/sphinx/addnodes.py
index 2806a05..55abdb0 100644
--- a/sphinx/addnodes.py
+++ b/sphinx/addnodes.py
@@ -168,6 +168,11 @@
     applied (e.g. smartypants for HTML output).
     """
 
+class literal_strong(nodes.strong):
+    """Node that behaves like `strong`, but further text processors are not
+    applied (e.g. smartypants for HTML output).
+    """
+
 class abbreviation(nodes.Inline, nodes.TextElement):
     """Node for abbreviations with explanations."""
 
diff --git a/sphinx/apidoc.py b/sphinx/apidoc.py
index 755ea5e..f716286 100644
--- a/sphinx/apidoc.py
+++ b/sphinx/apidoc.py
@@ -14,6 +14,8 @@
     :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
     :license: BSD, see LICENSE for details.
 """
+from __future__ import print_function
+
 import os
 import sys
 import optparse
@@ -53,12 +55,12 @@
     """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)
@@ -95,6 +97,10 @@
     """Build the text of the file and write the file."""
     text = format_heading(1, '%s package' % makename(master_package, subroot))
 
+    if opts.modulefirst:
+        text += format_directive(subroot, master_package)
+        text += '\n'
+
     # build a list of directories that are szvpackages (contain an INITPY file)
     subs = [sub for sub in subs if path.isfile(path.join(root, sub, INITPY))]
     # if there are some package directories, add a TOC for theses subpackages
@@ -134,8 +140,9 @@
                 text += '\n'
         text += '\n'
 
-    text += format_heading(2, 'Module contents')
-    text += format_directive(subroot, master_package)
+    if not opts.modulefirst:
+        text += format_heading(2, 'Module contents')
+        text += format_directive(subroot, master_package)
 
     write_file(makename(master_package, subroot), text, opts)
 
@@ -287,6 +294,10 @@
                       help='Don\'t create headings for the module/package '
                            'packages (e.g. when the docstrings already contain '
                            'them)')
+    parser.add_option('-M', '--module-first', action='store_true',
+                      dest='modulefirst',
+                      help='Put module documentation before submodule '
+                      'documentation')
     parser.add_option('-s', '--suffix', action='store', dest='suffix',
                       help='file suffix (default: rst)', default='rst')
     parser.add_option('-F', '--full', action='store_true', dest='full',
@@ -307,7 +318,7 @@
     (opts, args) = parser.parse_args(argv[1:])
 
     if opts.show_version:
-        print 'Sphinx (sphinx-apidoc) %s' %  __version__
+        print('Sphinx (sphinx-apidoc) %s' %  __version__)
         return 0
 
     if not args:
@@ -321,7 +332,7 @@
     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 7113b60..fe87040 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -10,15 +10,18 @@
     :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
     :license: BSD, see LICENSE for details.
 """
+from __future__ import print_function
 
 import os
 import sys
 import types
 import posixpath
+import traceback
 from os import path
-from cStringIO import StringIO
 from collections import deque
 
+from six import iteritems, itervalues
+from six.moves import cStringIO
 from docutils import nodes
 from docutils.parsers.rst import convert_directive_function, \
     directives, roles
@@ -38,6 +41,8 @@
 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 = {
@@ -67,6 +72,7 @@
         self.verbosity = verbosity
         self.next_listener_id = 0
         self._extensions = {}
+        self._extension_versions = {}
         self._listeners = {}
         self.domains = BUILTIN_DOMAINS.copy()
         self.builderclasses = BUILTIN_BUILDERS.copy()
@@ -81,20 +87,21 @@
         self.parallel = parallel
 
         if status is None:
-            self._status = StringIO()
+            self._status = cStringIO()
             self.quiet = True
         else:
             self._status = status
             self.quiet = False
 
         if warning is None:
-            self._warning = StringIO()
+            self._warning = cStringIO()
         else:
             self._warning = warning
         self._warncount = 0
         self.warningiserror = warningiserror
 
         self._events = events.copy()
+        self._translators = {}
 
         # keep last few messages for traceback
         self.messagelog = deque(maxlen=10)
@@ -116,8 +123,6 @@
         if self.confdir is None:
             self.confdir = self.srcdir
 
-        # backwards compatibility: activate old C markup
-        self.setup_extension('sphinx.ext.oldcmarkup')
         # load all user-given extension modules
         for extension in self.config.extensions:
             self.setup_extension(extension)
@@ -134,7 +139,7 @@
                 )
 
         # now that we know all config values, collect them from conf.py
-        self.config.init_values()
+        self.config.init_values(self.warn)
 
         # check the Sphinx version if requested
         if self.config.needs_sphinx and \
@@ -143,6 +148,21 @@
                 'This project needs at least Sphinx v%s and therefore cannot '
                 'be built with this version.' % self.config.needs_sphinx)
 
+        # check extension versions if requested
+        if self.config.needs_extensions:
+            for extname, needs_ver in self.config.needs_extensions.items():
+                if extname not in self._extensions:
+                    self.warn('needs_extensions config value specifies a '
+                              'version requirement for extension %s, but it is '
+                              'not loaded' % extname)
+                    continue
+                has_ver = self._extension_versions[extname]
+                if has_ver == 'unknown version' or needs_ver > has_ver:
+                    raise VersionRequirementError(
+                        'This project needs the extension %s at least in '
+                        'version %s and therefore cannot be built with the '
+                        'loaded version (%s).' % (extname, needs_ver, has_ver))
+
         # set up translation infrastructure
         self._init_i18n()
         # set up the build environment
@@ -187,7 +207,7 @@
                     # 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:
@@ -198,7 +218,7 @@
 
     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)
@@ -217,12 +237,15 @@
     def build(self, force_all=False, filenames=None):
         try:
             if force_all:
+                self.builder.compile_all_catalogs()
                 self.builder.build_all()
             elif filenames:
+                self.builder.compile_specific_catalogs(filenames)
                 self.builder.build_specific(filenames)
             else:
+                self.builder.compile_update_catalogs()
                 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):
@@ -336,22 +359,27 @@
             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)
         if not hasattr(mod, 'setup'):
             self.warn('extension %r has no setup() function; is it really '
                       'a Sphinx extension module?' % extension)
+            version = None
         else:
             try:
-                mod.setup(self)
-            except VersionRequirementError, err:
+                version = mod.setup(self)
+            except VersionRequirementError as err:
                 # add the extension name to the version required
                 raise VersionRequirementError(
                     'The %s extension used by this project needs at least '
                     'Sphinx v%s; it therefore cannot be built with this '
                     'version.' % (extension, err))
+        if version is None:
+            version = 'unknown version'
         self._extensions[extension] = mod
+        self._extension_versions[extension] = version
 
     def require_sphinx(self, version):
         # check the Sphinx version if requested
@@ -362,17 +390,17 @@
         """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)
@@ -398,7 +426,7 @@
 
     def disconnect(self, listener_id):
         self.debug('[app] disconnecting event: [id=%s]', listener_id)
-        for event in self._listeners.itervalues():
+        for event in itervalues(self._listeners):
             event.pop(listener_id, None)
 
     def emit(self, event, *args):
@@ -409,7 +437,7 @@
             pass
         results = []
         if event in self._listeners:
-            for _, callback in self._listeners[event].iteritems():
+            for _, callback in iteritems(self._listeners[event]):
                 results.append(callback(self, *args))
         return results
 
@@ -450,16 +478,23 @@
             raise ExtensionError('Event %r already present' % name)
         self._events[name] = ''
 
+    def set_translator(self, name, translator_class):
+        self.info(bold('A Translator for the %s builder is changed.' % name))
+        self._translators[name] = translator_class
+
     def add_node(self, node, **kwds):
         self.debug('[app] adding node: %r', (node, kwds))
         nodes._add_node_class_names([node.__name__])
-        for key, val in kwds.iteritems():
+        for key, val in iteritems(kwds):
             try:
                 visit, depart = val
             except ValueError:
                 raise ExtensionError('Value for key %r must be a '
                                      '(visit, depart) function tuple' % key)
-            if key == 'html':
+            translator = self._translators.get(key)
+            if translator is not None:
+                pass
+            elif key == 'html':
                 from sphinx.writers.html import HTMLTranslator as translator
             elif key == 'latex':
                 from sphinx.writers.latex import LaTeXTranslator as translator
diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py
index c02ecb5..833269c 100644
--- a/sphinx/builders/__init__.py
+++ b/sphinx/builders/__init__.py
@@ -20,7 +20,8 @@
 
 from docutils import nodes
 
-from sphinx.util.osutil import SEP, relative_uri
+from sphinx.util import i18n, path_stabilize
+from sphinx.util.osutil import SEP, relative_uri, find_catalog
 from sphinx.util.console import bold, purple, darkgreen, term_width_line
 
 # side effect: registers roles and directives
@@ -65,6 +66,9 @@
         # images that need to be copied over (source -> dest)
         self.images = {}
 
+        # load default translator class
+        self.translator_class = app._translators.get(self.name)
+
         self.init()
 
     # helper methods
@@ -170,6 +174,46 @@
                 continue
             self.images[candidate] = self.env.images[candidate][1]
 
+    # compile po methods
+
+    def compile_catalogs(self, catalogs, message):
+        if not self.config.gettext_auto_build:
+            return
+        self.info(bold('building [mo]: '), nonl=1)
+        self.info(message)
+        for catalog in self.status_iterator(
+                catalogs, 'writing output... ', darkgreen, len(catalogs),
+                lambda c: c.mo_path):
+            catalog.write_mo(self.config.language)
+
+    def compile_all_catalogs(self):
+        catalogs = i18n.get_catalogs(
+            [path.join(self.srcdir, x) for x in self.config.locale_dirs],
+            self.config.language, True)
+        message = 'all of %d po files' % len(catalogs)
+        self.compile_catalogs(catalogs, message)
+
+    def compile_specific_catalogs(self, specified_files):
+        def to_domain(fpath):
+            docname, _ = path.splitext(path_stabilize(fpath))
+            dom = find_catalog(docname, self.config.gettext_compact)
+            return dom
+
+        specified_domains = set(map(to_domain, specified_files))
+        catalogs = i18n.get_catalogs(
+            [path.join(self.srcdir, x) for x in self.config.locale_dirs],
+            self.config.language, True)
+        catalogs = [f for f in catalogs if f.domain in specified_domains]
+        message = 'targets for %d po files that are specified' % len(catalogs)
+        self.compile_catalogs(catalogs, message)
+
+    def compile_update_catalogs(self):
+        catalogs = i18n.get_catalogs(
+            [path.join(self.srcdir, x) for x in self.config.locale_dirs],
+            self.config.language)
+        message = 'targets for %d po files that are out of date' % len(catalogs)
+        self.compile_catalogs(catalogs, message)
+
     # build methods
 
     def build_all(self):
diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py
index c9317af..aa947c9 100644
--- a/sphinx/builders/changes.py
+++ b/sphinx/builders/changes.py
@@ -12,6 +12,8 @@
 import codecs
 from os import path
 
+from six import iteritems
+
 from sphinx import package_dir
 from sphinx.util import copy_static_entry
 from sphinx.locale import _
@@ -93,9 +95,9 @@
             'version': version,
             'docstitle': self.config.html_title,
             'shorttitle': self.config.html_short_title,
-            'libchanges': sorted(libchanges.iteritems()),
+            'libchanges': sorted(iteritems(libchanges)),
             'apichanges': sorted(apichanges),
-            'otherchanges': sorted(otherchanges.iteritems()),
+            'otherchanges': sorted(iteritems(otherchanges)),
             'show_copyright': self.config.html_show_copyright,
             'show_sphinx': self.config.html_show_sphinx,
         }
@@ -143,7 +145,7 @@
             finally:
                 f.close()
         themectx = dict(('theme_' + key, val) for (key, val) in
-                        self.theme.get_options({}).iteritems())
+                        iteritems(self.theme.get_options({})))
         copy_static_entry(path.join(package_dir, 'themes', 'default',
                                     'static', 'default.css_t'),
                           self.outdir, self, themectx)
diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py
index 61482fd..afe4b40 100644
--- a/sphinx/builders/devhelp.py
+++ b/sphinx/builders/devhelp.py
@@ -94,7 +94,7 @@
 
         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 a73679c..95a0ef0 100644
--- a/sphinx/builders/epub.py
+++ b/sphinx/builders/epub.py
@@ -12,7 +12,6 @@
 
 import os
 import re
-import sys
 import time
 import codecs
 import zipfile
@@ -219,7 +218,7 @@
         """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:'):
@@ -418,7 +417,7 @@
                 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
@@ -434,7 +433,7 @@
                     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))
 
@@ -490,7 +489,7 @@
         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')
@@ -750,12 +749,5 @@
             zipfile.ZIP_STORED)
         for file in projectfiles:
             fp = path.join(outdir, file)
-            if sys.version_info < (2, 6):
-                # When zipile.ZipFile.write call with unicode filename, ZipFile
-                # encode filename to 'utf-8' (only after Python-2.6).
-                if isinstance(file, unicode):
-                    # OEBPS Container Format (OCF) 2.0.1 specification require
-                    # "File Names MUST be UTF-8 encoded".
-                    file = file.encode('utf-8')
             epub.write(fp, file, zipfile.ZIP_DEFLATED)
         epub.close()
diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py
index 250bef8..657ce92 100644
--- a/sphinx/builders/gettext.py
+++ b/sphinx/builders/gettext.py
@@ -10,6 +10,7 @@
 """
 
 from __future__ import with_statement
+from __future__ import unicode_literals
 
 from os import path, walk
 from codecs import open
@@ -18,6 +19,8 @@
 from collections import defaultdict
 from uuid import uuid4
 
+from six import iteritems
+
 from sphinx.builders import Builder
 from sphinx.util import split_index_msg
 from sphinx.util.nodes import extract_messages, traverse_translatable_index
@@ -25,7 +28,7 @@
 from sphinx.util.console import darkgreen, purple, bold
 from sphinx.locale import pairindextypes
 
-POHEADER = ur"""
+POHEADER = r"""
 # SOME DESCRIPTIVE TITLE.
 # Copyright (C) %(copyright)s
 # This file is distributed under the same license as the %(project)s package.
@@ -96,6 +99,9 @@
     def prepare_writing(self, docnames):
         return
 
+    def compile_catalogs(self, catalogs, message):
+        return
+
     def write_doc(self, docname, doctree):
         catalog = self.catalogs[find_catalog(docname,
                                              self.config.gettext_compact)]
@@ -186,9 +192,9 @@
                 timestamp, ltz).strftime('%Y-%m-%d %H:%M%z'),
         )
         for textdomain, catalog in self.status_iterator(
-                self.catalogs.iteritems(), "writing message catalogs... ",
+                iteritems(self.catalogs), "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)))
 
@@ -200,19 +206,21 @@
                 for message in catalog.messages:
                     positions = catalog.metadata[message]
 
-                    # generate "#: file1:line1\n#: file2:line2 ..."
-                    pofile.write(u"#: %s\n" % "\n#: ".join("%s:%s" %
-                        (safe_relpath(source, self.outdir), line)
-                        for source, line, _ in positions))
-                    # generate "# uuid1\n# uuid2\n ..."
-                    pofile.write(u"# %s\n" % "\n# ".join(uid for _, _, uid
-                        in positions))
+                    if self.config.gettext_location:
+                        # generate "#: file1:line1\n#: file2:line2 ..."
+                        pofile.write("#: %s\n" % "\n#: ".join("%s:%s" %
+                            (safe_relpath(source, self.outdir), line)
+                            for source, line, _ in positions))
+                    if self.config.gettext_uuid:
+                        # generate "# uuid1\n# uuid2\n ..."
+                        pofile.write("# %s\n" % "\n# ".join(
+                            uid for _, _, uid in positions))
 
                     # message contains *one* line of text ready for translation
-                    message = message.replace(u'\\', ur'\\'). \
-                                      replace(u'"', ur'\"'). \
-                                      replace(u'\n', u'\\n"\n"')
-                    pofile.write(u'msgid "%s"\nmsgstr ""\n\n' % message)
+                    message = message.replace('\\', r'\\'). \
+                                      replace('"', r'\"'). \
+                                      replace('\n', '\\n"\n"')
+                    pofile.write('msgid "%s"\nmsgstr ""\n\n' % message)
 
             finally:
                 pofile.close()
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 9c039e3..ec3a818 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -14,14 +14,11 @@
 import zlib
 import codecs
 import posixpath
-import cPickle as pickle
 from os import path
-try:
-    from hashlib import md5
-except ImportError:
-    # 2.4 compatibility
-    from md5 import md5
+from hashlib import md5
 
+from six import iteritems, itervalues, text_type, string_types
+from six.moves import cPickle as pickle
 from docutils import nodes
 from docutils.io import DocTreeInput, StringOutput
 from docutils.core import Publisher
@@ -35,8 +32,6 @@
      movefile, ustrftime, copyfile
 from sphinx.util.nodes import inline_all_toctrees
 from sphinx.util.matching import patmatch, compile_matchers
-from sphinx.util.pycompat import any, b
-from sphinx.errors import SphinxError
 from sphinx.locale import _
 from sphinx.search import js_index
 from sphinx.theming import Theme
@@ -63,7 +58,7 @@
         return get_stable_hash(list(obj.items()))
     elif isinstance(obj, (list, tuple)):
         obj = sorted(get_stable_hash(o) for o in obj)
-    return md5(unicode(obj).encode('utf8')).hexdigest()
+    return md5(text_type(obj).encode('utf8')).hexdigest()
 
 
 class StandaloneHTMLBuilder(Builder):
@@ -157,7 +152,9 @@
                                           self.config.trim_doctest_flags)
 
     def init_translator_class(self):
-        if self.config.html_translator_class:
+        if self.translator_class is not None:
+            pass
+        elif self.config.html_translator_class:
             self.translator_class = self.app.import_object(
                 self.config.html_translator_class,
                 'html_translator_class setting')
@@ -168,7 +165,7 @@
 
     def get_outdated_docs(self):
         cfgdict = dict((name, self.config[name])
-                       for (name, desc) in self.config.values.iteritems()
+                       for (name, desc) in iteritems(self.config.values)
                        if desc[1] == 'html')
         self.config_hash = get_stable_hash(cfgdict)
         self.tags_hash = get_stable_hash(sorted(self.tags))
@@ -225,7 +222,7 @@
         """Utility: Render a lone doctree node."""
         if node is None:
             return {'fragment': ''}
-        doc = new_document(b('<partial node>'))
+        doc = new_document(b'<partial node>')
         doc.append(node)
 
         if self._publisher is None:
@@ -269,7 +266,7 @@
         # html_domain_indices can be False/True or a list of index names
         indices_config = self.config.html_domain_indices
         if indices_config:
-            for domain in self.env.domains.itervalues():
+            for domain in itervalues(self.env.domains):
                 for indexcls in domain.indices:
                     indexname = '%s-%s' % (domain.name, indexcls.name)
                     if isinstance(indices_config, list):
@@ -300,7 +297,7 @@
         if favicon and os.path.splitext(favicon)[1] != '.ico':
             self.warn('html_favicon is not an .ico file')
 
-        if not isinstance(self.config.html_use_opensearch, basestring):
+        if not isinstance(self.config.html_use_opensearch, string_types):
             self.warn('html_use_opensearch config value must now be a string')
 
         self.relations = self.env.collect_relations()
@@ -350,7 +347,7 @@
         if self.theme:
             self.globalcontext.update(
                 ('theme_' + key, val) for (key, val) in
-                self.theme.get_options(self.theme_options).iteritems())
+                iteritems(self.theme.get_options(self.theme_options)))
         self.globalcontext.update(self.config.html_context)
 
     def get_doc_context(self, docname, body, metatags):
@@ -535,7 +532,7 @@
                 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))
 
@@ -550,7 +547,7 @@
                 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))
 
@@ -583,10 +580,7 @@
         # then, copy over all user-supplied static files
         staticentries = [path.join(self.confdir, spath)
                          for spath in self.config.html_static_path]
-        matchers = compile_matchers(
-            self.config.exclude_patterns +
-            ['**/' + d for d in self.config.exclude_dirnames]
-        )
+        matchers = compile_matchers(self.config.exclude_patterns)
         for entry in staticentries:
             if not path.exists(entry):
                 self.warn('html_static_path entry %r does not exist' % entry)
@@ -704,7 +698,7 @@
         sidebars = None
         matched = None
         customsidebar = None
-        for pattern, patsidebars in self.config.html_sidebars.iteritems():
+        for pattern, patsidebars in iteritems(self.config.html_sidebars):
             if patmatch(pagename, pattern):
                 if matched:
                     if has_wildcard(pattern):
@@ -721,7 +715,7 @@
         if sidebars is None:
             # keep defaults
             pass
-        elif isinstance(sidebars, basestring):
+        elif isinstance(sidebars, string_types):
             # 0.x compatible mode: insert custom sidebar before searchbox
             customsidebar = sidebars
             sidebars = None
@@ -782,7 +776,7 @@
                 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
@@ -806,7 +800,7 @@
                      % (self.config.project, self.config.version)
                     ).encode('utf-8'))
             compressor = zlib.compressobj(9)
-            for domainname, domain in self.env.domains.iteritems():
+            for domainname, domain in iteritems(self.env.domains):
                 for name, dispname, type, docname, anchor, prio in \
                         domain.get_objects():
                     if anchor.endswith(name):
@@ -825,7 +819,9 @@
         self.info('done')
 
     def dump_search_index(self):
-        self.info(bold('dumping search index... '), nonl=True)
+        self.info(
+            bold('dumping search index in %s ... ' % self.indexer.label()),
+            nonl=True)
         self.indexer.prune(self.env.all_docs)
         searchindexfn = path.join(self.outdir, self.searchindex_filename)
         # first write to a temporary file, so that if dumping fails,
@@ -919,6 +915,23 @@
         self.fix_refuris(tree)
         return tree
 
+    def assemble_toc_secnumbers(self):
+        # Assemble toc_secnumbers to resolve section numbers on SingleHTML.
+        # Merge all secnumbers to single secnumber.
+        #
+        # Note: current Sphinx has refid confliction in singlehtml mode.
+        #       To avoid the problem, it replaces key of secnumbers to
+        #       tuple of docname and refid.
+        #
+        #       There are related codes in inline_all_toctres() and
+        #       HTMLTranslter#add_secnumber().
+        new_secnumbers = {}
+        for docname, secnums in iteritems(self.env.toc_secnumbers):
+            for id, secnum in iteritems(secnums):
+                new_secnumbers[(docname, id)] = secnum
+
+        return {self.config.master_doc: new_secnumbers}
+
     def get_doc_context(self, docname, body, metatags):
         # no relation links...
         toc = self.env.get_toctree_for(self.config.master_doc, self, False)
@@ -954,6 +967,7 @@
 
         self.info(bold('assembling single document... '), nonl=True)
         doctree = self.assemble_doctree()
+        self.env.toc_secnumbers = self.assemble_toc_secnumbers()
         self.info()
         self.info(bold('writing... '), nonl=True)
         self.write_doc_serialized(self.config.master_doc, doctree)
@@ -1100,8 +1114,4 @@
     searchindex_filename = 'searchindex.json'
 
     def init(self):
-        if jsonimpl.json is None:
-            raise SphinxError(
-                'The module simplejson (or json in Python >= 2.6) '
-                'is not available. The JSONHTMLBuilder builder will not work.')
         SerializingHTMLBuilder.init(self)
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index 77fcd43..400fbdc 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -9,6 +9,7 @@
     :copyright: Copyright 2007-2014 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 @@
         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 @@
                 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 @@
                         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/latex.py b/sphinx/builders/latex.py
index f545330..bf7991c 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -12,6 +12,7 @@
 import os
 from os import path
 
+from six import iteritems
 from docutils import nodes
 from docutils.io import FileOutput
 from docutils.utils import new_document
@@ -56,7 +57,7 @@
         return self.get_target_uri(to, typ)
 
     def init_document_data(self):
-        preliminary_document_data = map(list, self.config.latex_documents)
+        preliminary_document_data = [list(x) for x in self.config.latex_documents]
         if not preliminary_document_data:
             self.warn('no "latex_documents" config value found; no documents '
                       'will be written')
@@ -152,7 +153,7 @@
         # copy image files
         if self.images:
             self.info(bold('copying images...'), nonl=1)
-            for src, dest in self.images.iteritems():
+            for src, dest in iteritems(self.images):
                 self.info(' '+src, nonl=1)
                 copyfile(path.join(self.srcdir, src),
                          path.join(self.outdir, dest))
diff --git a/sphinx/builders/linkcheck.py b/sphinx/builders/linkcheck.py
index f0cb3c9..bf50e64 100644
--- a/sphinx/builders/linkcheck.py
+++ b/sphinx/builders/linkcheck.py
@@ -10,15 +10,15 @@
 """
 
 import re
-import sys
-import Queue
 import socket
 import threading
 from os import path
-from urllib2 import build_opener, unquote, Request, \
-    HTTPError, HTTPRedirectHandler
-from HTMLParser import HTMLParser, HTMLParseError
 
+from six.moves import queue
+from six.moves.urllib.request import build_opener, Request, HTTPRedirectHandler
+from six.moves.urllib.parse import unquote
+from six.moves.urllib.error import HTTPError
+from six.moves.html_parser import HTMLParser, HTMLParseError
 from docutils import nodes
 
 from sphinx.builders import Builder
@@ -90,7 +90,7 @@
     name = 'linkcheck'
 
     def init(self):
-        self.to_ignore = map(re.compile, self.app.config.linkcheck_ignore)
+        self.to_ignore = [re.compile(x) for x in self.app.config.linkcheck_ignore]
         self.good = set()
         self.broken = {}
         self.redirected = {}
@@ -100,8 +100,8 @@
         open(path.join(self.outdir, 'output.txt'), 'w').close()
 
         # create queues and worker threads
-        self.wqueue = Queue.Queue()
-        self.rqueue = Queue.Queue()
+        self.wqueue = queue.Queue()
+        self.rqueue = queue.Queue()
         self.workers = []
         for i in range(self.app.config.linkcheck_workers):
             thread = threading.Thread(target=self.check_thread)
@@ -111,7 +111,7 @@
 
     def check_thread(self):
         kwargs = {}
-        if sys.version_info > (2, 5) and self.app.config.linkcheck_timeout:
+        if self.app.config.linkcheck_timeout:
             kwargs['timeout'] = self.app.config.linkcheck_timeout
 
         def check():
@@ -158,7 +158,7 @@
                         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
@@ -167,7 +167,7 @@
                         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/manpage.py b/sphinx/builders/manpage.py
index 4de82a7..dfbf898 100644
--- a/sphinx/builders/manpage.py
+++ b/sphinx/builders/manpage.py
@@ -11,16 +11,16 @@
 
 from os import path
 
+from six import string_types
 from docutils.io import FileOutput
 from docutils.frontend import OptionParser
 
 from sphinx import addnodes
-from sphinx.errors import SphinxError
 from sphinx.builders import Builder
 from sphinx.environment import NoUri
 from sphinx.util.nodes import inline_all_toctrees
 from sphinx.util.console import bold, darkgreen
-from sphinx.writers.manpage import ManualPageWriter, has_manpage_writer
+from sphinx.writers.manpage import ManualPageWriter
 
 
 class ManualPageBuilder(Builder):
@@ -32,9 +32,6 @@
     supported_image_types = []
 
     def init(self):
-        if not has_manpage_writer:
-            raise SphinxError('The docutils manual page writer can\'t be '
-                              'found; it is only available as of docutils 0.6.')
         if not self.config.man_pages:
             self.warn('no "man_pages" config value found; no manual pages '
                       'will be written')
@@ -58,7 +55,7 @@
 
         for info in self.config.man_pages:
             docname, name, description, authors, section = info
-            if isinstance(authors, basestring):
+            if isinstance(authors, string_types):
                 if authors:
                     authors = [authors]
                 else:
diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py
index 1d46284..c0fff2a 100644
--- a/sphinx/builders/qthelp.py
+++ b/sphinx/builders/qthelp.py
@@ -15,6 +15,7 @@
 import posixpath
 from os import path
 
+from six import text_type
 from docutils import nodes
 
 from sphinx import addnodes
@@ -123,7 +124,7 @@
                                                   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))
@@ -136,7 +137,7 @@
         # they are all unicode strings before joining them
         new_sections = []
         for section in sections:
-            if not isinstance(section, unicode):
+            if not isinstance(section, text_type):
                 new_sections.append(force_decode(section, None))
             else:
                 new_sections.append(section)
diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py
index 39499e6..53463f3 100644
--- a/sphinx/builders/texinfo.py
+++ b/sphinx/builders/texinfo.py
@@ -11,6 +11,7 @@
 
 from os import path
 
+from six import iteritems
 from docutils import nodes
 from docutils.io import FileOutput
 from docutils.utils import new_document
@@ -107,7 +108,7 @@
         return self.get_target_uri(to, typ)
 
     def init_document_data(self):
-        preliminary_document_data = map(list, self.config.texinfo_documents)
+        preliminary_document_data = [list(x) for x in self.config.texinfo_documents]
         if not preliminary_document_data:
             self.warn('no "texinfo_documents" config value found; no documents '
                       'will be written')
@@ -207,7 +208,7 @@
         # copy image files
         if self.images:
             self.info(bold('copying images...'), nonl=1)
-            for src, dest in self.images.iteritems():
+            for src, dest in iteritems(self.images):
                 self.info(' '+src, nonl=1)
                 copyfile(path.join(self.srcdir, src),
                          path.join(self.outdir, dest))
@@ -223,6 +224,6 @@
                 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 0aeeb5f..46b4d72 100644
--- a/sphinx/builders/text.py
+++ b/sphinx/builders/text.py
@@ -65,7 +65,7 @@
                 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/websupport.py b/sphinx/builders/websupport.py
index 6cf9810..7b0e6f7 100644
--- a/sphinx/builders/websupport.py
+++ b/sphinx/builders/websupport.py
@@ -46,7 +46,8 @@
         self.storage = storage
 
     def init_translator_class(self):
-        self.translator_class = WebSupportTranslator
+        if self.translator_class is None:
+            self.translator_class = WebSupportTranslator
 
     def prepare_writing(self, docnames):
         PickleHTMLBuilder.prepare_writing(self, docnames)
diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py
index 9a9aec9..b0fcd2f 100644
--- a/sphinx/builders/xml.py
+++ b/sphinx/builders/xml.py
@@ -81,7 +81,7 @@
                 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 ec24d90..6e7ab32 100644
--- a/sphinx/cmdline.py
+++ b/sphinx/cmdline.py
@@ -8,6 +8,7 @@
     :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
     :license: BSD, see LICENSE for details.
 """
+from __future__ import print_function
 
 import os
 import sys
@@ -15,6 +16,7 @@
 import traceback
 from os import path
 
+from six import text_type, binary_type
 from docutils.utils import SystemMessage
 
 from sphinx import __version__
@@ -23,14 +25,14 @@
 from sphinx.util import Tee, format_exception_cut_frames, save_traceback
 from sphinx.util.console import red, nocolor, color_terminal
 from sphinx.util.osutil import abspath, fs_encoding
-from sphinx.util.pycompat import terminal_safe, bytes
+from sphinx.util.pycompat import terminal_safe
 
 
 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,19 +77,18 @@
 ^^^^^^^^^^^^^^^^
 -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):
     if not color_terminal():
-        # Windows' poor cmd box doesn't understand ANSI sequences
         nocolor()
 
     # parse options
     try:
         opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:nNEqQWw:PThvj:',
                                    ['help', 'version'])
-    except getopt.error, err:
+    except getopt.error as err:
         usage(argv, 'Error: %s' % err)
         return 1
 
@@ -96,33 +97,34 @@
     # help and version options
     if '-h' in allopts or '--help' in allopts:
         usage(argv)
-        print >>sys.stderr
-        print >>sys.stderr, 'For more information, see <http://sphinx-doc.org/>.'
+        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__
+        print('Sphinx (sphinx-build) %s' %  __version__)
         return 0
 
     # get paths (first and second positional argument)
     try:
         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:
-            print >>sys.stderr, ('Error: Source directory doesn\'t '
-                                 'contain a conf.py file.')
+            print('Error: Source directory doesn\'t contain a conf.py file.',
+                  file=sys.stderr)
             return 1
         outdir = abspath(args[1])
     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 +132,7 @@
     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 +171,8 @@
         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,29 +180,26 @@
             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
-            try:
-                val = int(val)
-            except ValueError:
-                if likely_encoding and isinstance(val, bytes):
-                    try:
-                        val = val.decode(likely_encoding)
-                    except UnicodeError:
-                        pass
+            if likely_encoding and isinstance(val, binary_type):
+                try:
+                    val = val.decode(likely_encoding)
+                except UnicodeError:
+                    pass
             confoverrides[key] = val
         elif opt == '-A':
             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)
             except ValueError:
-                if likely_encoding and isinstance(val, bytes):
+                if likely_encoding and isinstance(val, binary_type):
                     try:
                         val = val.decode(likely_encoding)
                     except UnicodeError:
@@ -232,8 +231,8 @@
             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:
@@ -243,7 +242,7 @@
 
     if not path.isdir(outdir):
         if status:
-            print >>status, 'Making output directory...'
+            print('Making output directory...', file=status)
         os.makedirs(outdir)
 
     app = None
@@ -253,44 +252,44 @@
                      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):
-                print >>error, red('%s:' % err.category)
-                print >>error, terminal_safe(unicode(err))
+                print(red('%s:' % err.category), file=error)
+                print(terminal_safe(text_type(err)), file=error)
             elif isinstance(err, UnicodeError):
-                print >>error, red('Encoding error:')
-                print >>error, terminal_safe(unicode(err))
+                print(red('Encoding error:'), file=error)
+                print(terminal_safe(text_type(err)), 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(red('The full traceback has been saved in %s, if you want '
+                          'to report the issue to the developers.' % tbpath),
+                      file=error)
             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, (
-                    'A bug report can be filed in the tracker at '
-                    '<https://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('A bug report can be filed in the tracker at '
+                      '<https://bitbucket.org/birkenfeld/sphinx/issues/>. Thanks!',
+                      file=error)
             return 1
diff --git a/sphinx/config.py b/sphinx/config.py
index a4fc234..9e5705e 100644
--- a/sphinx/config.py
+++ b/sphinx/config.py
@@ -11,18 +11,19 @@
 
 import os
 import re
-import sys
 from os import path
 
+from six import PY3, iteritems, string_types, binary_type, integer_types
+
 from sphinx.errors import ConfigError
 from sphinx.locale import l_
 from sphinx.util.osutil import make_filename
-from sphinx.util.pycompat import bytes, b, execfile_
+from sphinx.util.pycompat import execfile_
 
-nonascii_re = re.compile(b(r'[\x80-\xff]'))
+nonascii_re = re.compile(br'[\x80-\xff]')
 
 CONFIG_SYNTAX_ERROR = "There is a syntax error in your configuration file: %s"
-if sys.version_info >= (3, 0):
+if PY3:
     CONFIG_SYNTAX_ERROR += "\nDid you change the syntax from 2.x to 3.x?"
 
 class Config(object):
@@ -51,10 +52,6 @@
         source_suffix = ('.rst', 'env'),
         source_encoding = ('utf-8-sig', 'env'),
         exclude_patterns = ([], 'env'),
-        # the next three are all deprecated now
-        unused_docs = ([], 'env'),
-        exclude_trees = ([], 'env'),
-        exclude_dirnames = ([], 'env'),
         default_role = (None, 'env'),
         add_function_parentheses = (True, 'env'),
         add_module_names = (True, 'env'),
@@ -71,6 +68,7 @@
         trim_doctest_flags = (True, 'env'),
         primary_domain = ('py', 'env'),
         needs_sphinx = (None, None),
+        needs_extensions = ({}, None),
         nitpicky = (False, 'env'),
         nitpick_ignore = ([], 'html'),
 
@@ -205,6 +203,9 @@
 
         # gettext options
         gettext_compact = (True, 'gettext'),
+        gettext_location = (True, 'gettext'),
+        gettext_uuid = (True, 'gettext'),
+        gettext_auto_build = (True, 'env'),
 
         # XML options
         xml_pretty = (True, 'env'),
@@ -214,8 +215,11 @@
         self.overrides = overrides
         self.values = Config.config_values.copy()
         config = {}
-        if "extensions" in overrides:
-            config["extensions"] = overrides["extensions"]
+        if 'extensions' in overrides:
+            if isinstance(overrides['extensions'], string_types):
+                config['extensions'] = overrides.pop('extensions').split(',')
+            else:
+                config['extensions'] = overrides.pop('extensions')
         if dirname is not None:
             config_file = path.join(dirname, filename)
             config['__file__'] = config_file
@@ -227,7 +231,7 @@
                 os.chdir(dirname)
                 try:
                     execfile_(filename, config)
-                except SyntaxError, err:
+                except SyntaxError as err:
                     raise ConfigError(CONFIG_SYNTAX_ERROR % err)
             finally:
                 os.chdir(olddir)
@@ -241,19 +245,43 @@
     def check_unicode(self, warn):
         # check all string values for non-ASCII characters in bytestrings,
         # since that can result in UnicodeErrors all over the place
-        for name, value in self._raw_config.iteritems():
-            if isinstance(value, bytes) and nonascii_re.search(value):
+        for name, value in iteritems(self._raw_config):
+            if isinstance(value, binary_type) and nonascii_re.search(value):
                 warn('the config value %r is set to a string with non-ASCII '
                      'characters; this can lead to Unicode errors occurring. '
                      'Please use Unicode strings, e.g. %r.' % (name, u'Content')
                 )
 
-    def init_values(self):
+    def init_values(self, warn):
         config = self._raw_config
-        for valname, value in self.overrides.iteritems():
+        for valname, value in iteritems(self.overrides):
             if '.' in valname:
                 realvalname, key = valname.split('.', 1)
                 config.setdefault(realvalname, {})[key] = value
+                continue
+            elif valname not in self.values:
+                warn('unknown config value %r in override, ignoring' % valname)
+                continue
+            defvalue = self.values[valname][0]
+            if isinstance(value, string_types):
+                if isinstance(defvalue, dict):
+                    warn('cannot override dictionary config setting %r, '
+                         'ignoring (use %r to set individual elements)' %
+                         (valname, valname + '.key=value'))
+                    continue
+                elif isinstance(defvalue, list):
+                    config[valname] = value.split(',')
+                elif isinstance(defvalue, integer_types):
+                    try:
+                        config[valname] = int(value)
+                    except ValueError:
+                        warn('invalid number %r for config value %r, ignoring'
+                             % (value, valname))
+                elif defvalue is not None and not isinstance(defvalue, string_types):
+                    warn('cannot override config setting %r with unsupported type, '
+                         'ignoring' % valname)
+                else:
+                    config[valname] = value
             else:
                 config[valname] = value
         for name in config:
diff --git a/sphinx/directives/__init__.py b/sphinx/directives/__init__.py
index 250a013..52b638f 100644
--- a/sphinx/directives/__init__.py
+++ b/sphinx/directives/__init__.py
@@ -178,7 +178,7 @@
         domain_name = self.arguments[0].lower()
         # if domain_name not in env.domains:
         #     # try searching by label
-        #     for domain in env.domains.itervalues():
+        #     for domain in itervalues(env.domains):
         #         if domain.label.lower() == domain_name:
         #             domain_name = domain.name
         #             break
diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py
index 9bfac5a..6ea525b 100644
--- a/sphinx/directives/code.py
+++ b/sphinx/directives/code.py
@@ -9,10 +9,13 @@
 
 import sys
 import codecs
+from difflib import unified_diff
 
 from docutils import nodes
 from docutils.parsers.rst import Directive, directives
 
+from six import string_types
+
 from sphinx import addnodes
 from sphinx.util import parselinenos
 from sphinx.util.nodes import set_source_info
@@ -39,11 +42,26 @@
             except Exception:
                 linenothreshold = 10
         else:
-            linenothreshold = sys.maxint
+            linenothreshold = sys.maxsize
         return [addnodes.highlightlang(lang=self.arguments[0].strip(),
                                        linenothreshold=linenothreshold)]
 
 
+
+def dedent_lines(lines, dedent):
+    if not dedent:
+        return lines
+
+    new_lines = []
+    for line in lines:
+        new_line = line[dedent:]
+        if line.endswith('\n') and not new_line:
+            new_line = '\n'  # keep CRLF
+        new_lines.append(new_line)
+
+    return new_lines
+
+
 class CodeBlock(Directive):
     """
     Directive for a code block with special highlighting or line numbering
@@ -56,7 +74,10 @@
     final_argument_whitespace = False
     option_spec = {
         'linenos': directives.flag,
+        'dedent': int,
+        'lineno-start': int,
         'emphasize-lines': directives.unchanged_required,
+        'caption': directives.unchanged_required,
     }
 
     def run(self):
@@ -67,17 +88,29 @@
             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:
             hl_lines = None
+        
+        if 'dedent' in self.options:
+            lines = code.split('\n')
+            lines = dedent_lines(lines, self.options['dedent'])
+            code = '\n'.join(lines)
 
         literal = nodes.literal_block(code, code)
         literal['language'] = self.arguments[0]
-        literal['linenos'] = 'linenos' in self.options
+        caption = self.options.get('caption')
+        if caption:
+            literal['caption'] = caption
+        literal['linenos'] = 'linenos' in self.options or \
+                             'lineno-start' in self.options
+        extra_args = literal['highlight_args'] = {}
         if hl_lines is not None:
-            literal['highlight_args'] = {'hl_lines': hl_lines}
+            extra_args['hl_lines'] = hl_lines
+        if 'lineno-start' in self.options:
+            extra_args['linenostart'] = self.options['lineno-start']
         set_source_info(self, literal)
         return [literal]
 
@@ -94,7 +127,9 @@
     optional_arguments = 0
     final_argument_whitespace = True
     option_spec = {
+        'dedent': int,
         'linenos': directives.flag,
+        'lineno-start': int,
         'tab-width': int,
         'language': directives.unchanged_required,
         'encoding': directives.encoding,
@@ -105,8 +140,31 @@
         'prepend': directives.unchanged_required,
         'append': directives.unchanged_required,
         'emphasize-lines': directives.unchanged_required,
+        'caption': directives.unchanged,
+        'diff': directives.unchanged_required,
     }
 
+    def read_with_encoding(self, filename, document, codec_info, encoding):
+        f = None
+        try:
+            f = codecs.StreamReaderWriter(open(filename, 'rb'),
+                                          codec_info[2], codec_info[3], 'strict')
+            lines = f.readlines()
+            lines = dedent_lines(lines, self.options.get('dedent'))
+            return lines
+        except (IOError, OSError):
+            return [document.reporter.warning(
+                'Include file %r not found or reading it failed' % filename,
+                line=self.lineno)]
+        except UnicodeError:
+            return [document.reporter.warning(
+                'Encoding %r used for reading included file %r seems to '
+                'be wrong, try giving an :encoding: option' %
+                (encoding, filename))]
+        finally:
+            if f is not None:
+                f.close()
+
     def run(self):
         document = self.state.document
         if not document.settings.file_insertion_enabled:
@@ -122,23 +180,26 @@
 
         encoding = self.options.get('encoding', env.config.source_encoding)
         codec_info = codecs.lookup(encoding)
-        f = None
-        try:
-            f = codecs.StreamReaderWriter(open(filename, 'rb'),
-                    codec_info[2], codec_info[3], 'strict')
-            lines = f.readlines()
-        except (IOError, OSError):
-            return [document.reporter.warning(
-                'Include file %r not found or reading it failed' % filename,
-                line=self.lineno)]
-        except UnicodeError:
-            return [document.reporter.warning(
-                'Encoding %r used for reading included file %r seems to '
-                'be wrong, try giving an :encoding: option' %
-                (encoding, filename))]
-        finally:
-            if f is not None:
-                f.close()
+
+        lines = self.read_with_encoding(filename, document,
+                                        codec_info, encoding)
+        if not isinstance(lines[0], string_types):
+            return lines
+
+        diffsource = self.options.get('diff')
+        if diffsource is not None:
+            tmp, fulldiffsource = env.relfn2path(diffsource)
+
+            difflines = self.read_with_encoding(fulldiffsource, document,
+                                           codec_info, encoding)
+            if not isinstance(difflines[0], string_types):
+                return difflines
+            diff = unified_diff(
+                difflines,
+                lines,
+                diffsource,
+                self.arguments[0])
+            lines = list(diff)
 
         objectname = self.options.get('pyobject')
         if objectname is not None:
@@ -156,7 +217,7 @@
         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)
@@ -170,7 +231,7 @@
         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
@@ -202,12 +263,22 @@
             text = text.expandtabs(self.options['tab-width'])
         retnode = nodes.literal_block(text, text, source=filename)
         set_source_info(self, retnode)
+        if diffsource is not None:  # if diff is set, set udiff
+            retnode['language'] = 'udiff'
         if self.options.get('language', ''):
             retnode['language'] = self.options['language']
-        if 'linenos' in self.options:
-            retnode['linenos'] = True
+        retnode['linenos'] = 'linenos' in self.options or \
+                             'lineno-start' in self.options
+        caption = self.options.get('caption')
+        if caption is not None:
+            if not caption:
+                caption = self.arguments[0]
+            retnode['caption'] = caption
+        extra_args = retnode['highlight_args'] = {}
         if hl_lines is not None:
-            retnode['highlight_args'] = {'hl_lines': hl_lines}
+            extra_args['hl_lines'] = hl_lines
+        if 'lineno-start' in self.options:
+            extra_args['linenostart'] = self.options['lineno-start']
         env.note_dependency(rel_filename)
         return [retnode]
 
diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py
index d28c00f..01c8c01 100644
--- a/sphinx/directives/other.py
+++ b/sphinx/directives/other.py
@@ -7,6 +7,7 @@
     :license: BSD, see LICENSE for details.
 """
 
+from six.moves import range
 from docutils import nodes
 from docutils.parsers.rst import Directive, directives
 from docutils.parsers.rst.directives.admonitions import BaseAdmonition
@@ -368,7 +369,7 @@
             # be placed in the doctree.
             n_sects_to_raise = current_depth - nested_depth + 1
             parent = self.state.parent
-            for i in xrange(n_sects_to_raise):
+            for i in range(n_sects_to_raise):
                 if parent.parent:
                     parent = parent.parent
             parent.append(node)
diff --git a/sphinx/domains/__init__.py b/sphinx/domains/__init__.py
index 200fd51..51b886f 100644
--- a/sphinx/domains/__init__.py
+++ b/sphinx/domains/__init__.py
@@ -10,6 +10,8 @@
     :license: BSD, see LICENSE for details.
 """
 
+from six import iteritems
+
 from sphinx.errors import SphinxError
 from sphinx.locale import _
 
@@ -153,7 +155,7 @@
         self._role_cache = {}
         self._directive_cache = {}
         self._role2type = {}
-        for name, obj in self.object_types.iteritems():
+        for name, obj in iteritems(self.object_types):
             for rolename in obj.roles:
                 self._role2type.setdefault(rolename, []).append(name)
         self.objtypes_for_role = self._role2type.get
diff --git a/sphinx/domains/c.py b/sphinx/domains/c.py
index fb38cfe..4d12c14 100644
--- a/sphinx/domains/c.py
+++ b/sphinx/domains/c.py
@@ -39,6 +39,13 @@
         \( (.*) \)         # arguments
         (\s+const)? $      # const specifier
     ''', re.VERBOSE)
+c_funcptr_arg_sig_re = re.compile(
+    r'''^\s*([^(,]+?)      # return type
+        \( ([^()]+) \) \s* # name in parentheses
+        \( (.*) \)         # arguments
+        (\s+const)?        # const specifier
+        \s*(?=$|,)         # end with comma or end of string
+    ''', re.VERBOSE)
 c_funcptr_name_re = re.compile(r'^\(\s*\*\s*(.*?)\s*\)$')
 
 
@@ -68,7 +75,7 @@
 
     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:
@@ -80,6 +87,24 @@
             else:
                 node += tnode
 
+    def _parse_arglist(self, arglist):
+        while True:
+            m = c_funcptr_arg_sig_re.match(arglist)
+            if m:
+                yield m.group()
+                arglist = c_funcptr_arg_sig_re.sub('', arglist)
+                if ',' in arglist:
+                    _, arglist = arglist.split(',', 1)
+                else:
+                    break
+            else:
+                if ',' in arglist:
+                    arg, arglist = arglist.split(',', 1)
+                    yield arg
+                else:
+                    yield arglist
+                    break
+
     def handle_signature(self, sig, signode):
         """Transform a C signature into RST nodes."""
         # first try the function pointer signature regex, it's more specific
@@ -122,19 +147,25 @@
         paramlist = addnodes.desc_parameterlist()
         arglist = arglist.replace('`', '').replace('\\ ', '') # remove markup
         # this messes up function pointer types, but not too badly ;)
-        args = arglist.split(',')
-        for arg in args:
+        for arg in self._parse_arglist(arglist):
             arg = arg.strip()
             param = addnodes.desc_parameter('', '', noemph=True)
             try:
-                ctype, argname = arg.rsplit(' ', 1)
+                m = c_funcptr_arg_sig_re.match(arg)
+                if m:
+                    self._parse_type(param, m.group(1) + '(')
+                    param += nodes.emphasis(m.group(2), m.group(2))
+                    self._parse_type(param, ')(' + m.group(3) + ')')
+                    if m.group(4):
+                        param += addnodes.desc_addname(m.group(4), m.group(4))
+                else:
+                    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)
             except ValueError:
                 # no argument name given, only the type
                 self._parse_type(param, arg)
-            else:
-                self._parse_type(param, ctype)
-                # separate by non-breaking space in the output
-                param += nodes.emphasis(' '+argname, u'\xa0'+argname)
             paramlist += param
         signode += paramlist
         if const:
@@ -234,7 +265,7 @@
     }
 
     def clear_doc(self, docname):
-        for fullname, (fn, _) in self.data['objects'].items():
+        for fullname, (fn, _) in list(self.data['objects'].items()):
             if fn == docname:
                 del self.data['objects'][fullname]
 
@@ -249,5 +280,5 @@
                             contnode, target)
 
     def get_objects(self):
-        for refname, (docname, type) in self.data['objects'].iteritems():
+        for refname, (docname, type) in list(self.data['objects'].items()):
             yield (refname, refname, type, docname, 'c.' + refname, 1)
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index cb64a60..23bd469 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -7,11 +7,144 @@
 
     :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
     :license: BSD, see LICENSE for details.
+    
+    See http://www.nongnu.org/hcb/ for the grammar.
+    See http://mentorembedded.github.io/cxx-abi/abi.html#mangling for the
+    inspiration for the id generation.
+    
+    common grammar things:
+           simple-declaration
+        -> attribute-specifier-seq[opt] decl-specifier-seq[opt]
+           init-declarator-list[opt] ;
+        # Drop the semi-colon. For now: drop the attributes (TODO).
+        # Use at most 1 init-declerator.
+        -> decl-specifier-seq init-declerator
+        -> decl-specifier-seq declerator initializer
+        
+        decl-specifier ->
+              storage-class-specifier -> "static" (only for member_object and
+              function_object)
+            | type-specifier -> trailing-type-specifier
+            | function-specifier -> "inline" | "virtual" | "explicit" (only
+              for function_object)
+            | "friend" (only for function_object)
+            | "constexpr" (only for member_object and function_object)
+        trailing-type-specifier ->
+              simple-type-specifier
+            | elaborated-type-specifier
+            | typename-specifier
+            | cv-qualifier -> "const" | "volatile"
+        stricter grammar for decl-specifier-seq (with everything, each object
+        uses a subset):
+            visibility storage-class-specifier function-specifier "friend"
+            "constexpr" "volatile" "const" trailing-type-specifier
+            # where trailing-type-specifier can no be cv-qualifier
+        # Inside e.g., template paramters a strict subset is used
+        # (see type-specifier-seq)
+        trailing-type-specifier ->
+              simple-type-specifier ->
+                ::[opt] nested-name-specifier[opt] type-name
+              | ::[opt] nested-name-specifier "template" simple-template-id
+              | "char" | "bool" | ect.
+              | decltype-specifier
+            | elaborated-type-specifier ->
+                class-key attribute-specifier-seq[opt] ::[opt]
+                nested-name-specifier[opt] identifier
+              | class-key ::[opt] nested-name-specifier[opt] template[opt]
+                simple-template-id
+              | "enum" ::[opt] nested-name-specifier[opt] identifier
+            | typename-specifier ->
+                "typename" ::[opt] nested-name-specifier identifier
+              | "typename" ::[opt] nested-name-specifier template[opt]
+                simple-template-id
+        class-key -> "class" | "struct" | "union"
+        type-name ->* identifier | simple-template-id
+        # ignoring attributes and decltype, and then some left-factoring
+        trailing-type-specifier ->
+            rest-of-trailing
+            ("class" | "struct" | "union" | "typename") rest-of-trailing
+            build-in -> "char" | "bool" | ect.
+            decltype-specifier
+        rest-of-trailing -> (with some simplification)
+            "::"[opt] list-of-elements-separated-by-::
+        element ->
+            "template"[opt] identifier ("<" template-argument-list ">")[opt]
+        template-argument-list ->
+              template-argument "..."[opt]
+            | template-argument-list "," template-argument "..."[opt]
+        template-argument ->
+              constant-expression
+            | type-specifier-seq abstract-declerator
+            | id-expression
+        
+        
+        declerator ->
+              ptr-declerator
+            | noptr-declarator parameters-and-qualifiers trailing-return-type
+              (TODO: for now we don't support it)
+        ptr-declerator ->
+              noptr-declerator
+            | ptr-operator ptr-declarator
+        noptr-declerator ->
+              declarator-id attribute-specifier-seq[opt] ->
+                    "..."[opt] id-expression
+                  | rest-of-trailing
+            | noptr-declerator parameters-and-qualifiers
+            | noptr-declarator "[" constant-expression[opt] "]"
+              attribute-specifier-seq[opt]
+            | "(" ptr-declarator ")"  # TODO: not implemented yet
+        # function_object must use a parameters-and-qualifiers, the others may
+        # use it (e.g., function poitners)
+        parameters-and-qualifiers ->
+            "(" parameter-clause ")" attribute-specifier-seq[opt]
+            cv-qualifier-seq[opt] ref-qualifier[opt]
+            exception-specification[opt]
+        ref-qualifier -> "&" | "&&"
+        exception-specification ->
+            "noexcept" ("(" constant-expression ")")[opt]
+            "throw" ("(" type-id-list ")")[opt]
+        # TODO: we don't implement attributes
+        # member functions can have initializers, but we fold them into here
+        memberFunctionInit -> "=" "0"
+        # (note: only "0" is allowed as the value, according to the standard,
+        # right?)
+         
+    
+    We additionally add the possibility for specifying the visibility as the
+    first thing.
+    
+    type_object:
+        goal:
+            either a single type (e.g., "MyClass:Something_T" or a typedef-like
+            thing (e.g. "Something Something_T" or "int I_arr[]"
+        grammar, single type: based on a type in a function parameter, but
+        without a name:
+               parameter-declaration
+            -> attribute-specifier-seq[opt] decl-specifier-seq
+               abstract-declarator[opt]
+            # Drop the attributes
+            -> decl-specifier-seq abstract-declarator[opt]
+        grammar, typedef-like: no initilizer
+            decl-specifier-seq declerator
+        
+        
+    member_object:
+        goal: as a type_object which must have a declerator, and optionally
+        with a initializer
+        grammar:
+            decl-specifier-seq declerator initializer
+        
+    function_object:
+        goal: a function declaration, TODO: what about templates? for now: skip
+        grammar: no initializer
+           decl-specifier-seq declerator
 """
 
 import re
+import traceback
 from copy import deepcopy
 
+from six import iteritems, text_type
 from docutils import nodes
 
 from sphinx import addnodes
@@ -21,6 +154,7 @@
 from sphinx.directives import ObjectDescription
 from sphinx.util.nodes import make_refnode
 from sphinx.util.compat import Directive
+from sphinx.util.pycompat import UnicodeMixin
 from sphinx.util.docfields import Field, GroupedField
 
 
@@ -40,88 +174,112 @@
     |   [!<>=/*%+|&^~-]=?
 ''')
 
-_id_shortwords = {
-    'char':                 'c',
-    'signed char':          'c',
-    'unsigned char':        'C',
-    'int':                  'i',
-    'signed int':           'i',
-    'unsigned int':         'U',
-    'long':                 'l',
-    'signed long':          'l',
-    'unsigned long':        'L',
-    'bool':                 'b',
-    'size_t':               's',
-    'std::string':          'ss',
-    'std::ostream':         'os',
-    'std::istream':         'is',
-    'std::iostream':        'ios',
-    'std::vector':          'v',
-    'std::map':             'm',
-    'operator[]':           'subscript-operator',
-    'operator()':           'call-operator',
-    'operator!':            'not-operator',
-    'operator<':            'lt-operator',
-    'operator<=':           'lte-operator',
-    'operator>':            'gt-operator',
-    'operator>=':           'gte-operator',
-    'operator=':            'assign-operator',
-    'operator/':            'div-operator',
-    'operator*':            'mul-operator',
-    'operator%':            'mod-operator',
-    'operator+':            'add-operator',
-    'operator-':            'sub-operator',
-    'operator|':            'or-operator',
-    'operator&':            'and-operator',
-    'operator^':            'xor-operator',
-    'operator&&':           'sand-operator',
-    'operator||':           'sor-operator',
-    'operator==':           'eq-operator',
-    'operator!=':           'neq-operator',
-    'operator<<':           'lshift-operator',
-    'operator>>':           'rshift-operator',
-    'operator-=':           'sub-assign-operator',
-    'operator+=':           'add-assign-operator',
-    'operator*-':           'mul-assign-operator',
-    'operator/=':           'div-assign-operator',
-    'operator%=':           'mod-assign-operator',
-    'operator&=':           'and-assign-operator',
-    'operator|=':           'or-assign-operator',
-    'operator<<=':          'lshift-assign-operator',
-    'operator>>=':          'rshift-assign-operator',
-    'operator^=':           'xor-assign-operator',
-    'operator,':            'comma-operator',
-    'operator->':           'pointer-operator',
-    'operator->*':          'pointer-by-pointer-operator',
-    'operator~':            'inv-operator',
-    'operator++':           'inc-operator',
-    'operator--':           'dec-operator',
-    'operator new':         'new-operator',
-    'operator new[]':       'new-array-operator',
-    'operator delete':      'delete-operator',
-    'operator delete[]':    'delete-array-operator'
+_id_prefix = '_CPP'
+_id_fundamental = {
+    # not all of these are actually parsed as fundamental types, TODO: do that
+    'void': 'v',
+    'bool': 'b',
+    'char': 'c',
+    'signed char': 'a',
+    'unsigned char': 'h',
+    'wchar_t': 'w',
+    'char32_t': 'Di',
+    'char16_t': 'Ds',
+    'short': 's',
+    'short int': 's',
+    'signed short': 's',
+    'signed short int': 's',
+    'unsigned short': 't',
+    'unsigned short int': 't',
+    'int': 'i',
+    'signed': 'i',
+    'signed int': 'i',
+    'unsigned': 'j',
+    'unsigned int': 'j',
+    'long': 'l',
+    'long int': 'l',
+    'signed long': 'l',
+    'signed long int': 'l',
+    'unsigned long': 'm',
+    'unsigned long int': 'm',
+    'long long': 'x',
+    'long long int': 'x',
+    'signed long long': 'x',
+    'signed long long int': 'x',
+    'unsigned long long': 'y',
+    'unsigned long long int': 'y',
+    'float': 'f',
+    'double': 'd',
+    'long double': 'e',
+    'auto': 'Da',
+    'decltype(auto)': 'Dc',
+    'std::nullptr_t': 'Dn'
+}
+_id_operator = {
+    'new': 'nw',
+    'new[]': 'na',
+    'delete': 'dl',
+    'delete[]': 'da',
+    # the arguments will make the difference between unary and binary
+    # '+(unary)' : 'ps',
+    #'-(unary)' : 'ng',
+    #'&(unary)' : 'ad',
+    #'*(unary)' : 'de',
+    '~': 'co',
+    '+': 'pl',
+    '-': 'mi',
+    '*': 'ml',
+    '/': 'dv',
+    '%': 'rm',
+    '&': 'an',
+    '|': 'or',
+    '^': 'eo',
+    '=': 'aS',
+    '+=': 'pL',
+    '-=': 'mI',
+    '*=': 'mL',
+    '/=': 'dV',
+    '%=': 'rM',
+    '&=': 'aN',
+    '|=': 'oR',
+    '^=': 'eO',
+    '<<': 'ls',
+    '>>': 'rs',
+    '<<=': 'lS',
+    '>>=': 'rS',
+    '==': 'eq',
+    '!=': 'ne',
+    '<': 'lt',
+    '>': 'gt',
+    '<=': 'le',
+    '>=': 'ge',
+    '!': 'nt',
+    '&&': 'aa',
+    '||': 'oo',
+    '++': 'pp',
+    '--': 'mm',
+    ',': 'cm',
+    '->*': 'pm',
+    '->': 'pt',
+    '()': 'cl',
+    '[]': 'ix'
 }
 
 
-class DefinitionError(Exception):
-
+class DefinitionError(UnicodeMixin, Exception):
     def __init__(self, description):
         self.description = description
 
-    def __str__(self):
-        return unicode(self).encode('utf-8')
-
     def __unicode__(self):
         return self.description
 
 
-class DefExpr(object):
-
+class ASTBase(UnicodeMixin):
     def __eq__(self, other):
         if type(self) is not type(other):
             return False
         try:
-            for key, value in self.__dict__.iteritems():
+            for key, value in iteritems(self.__dict__):
                 if value != getattr(other, key):
                     return False
         except AttributeError:
@@ -139,7 +297,7 @@
 
     def get_id(self):
         """Return the id for the node."""
-        return u''
+        raise NotImplementedError(repr(self))
 
     def get_name(self):
         """Return the name.
@@ -147,402 +305,748 @@
         Returns either `None` or a node with a name you might call
         :meth:`split_owner` on.
         """
-        return None
+        raise NotImplementedError(repr(self))
 
-    def split_owner(self):
-        """Nodes returned by :meth:`get_name` can split off their
-        owning parent.  This function returns the owner and the
-        name as a tuple of two items.  If a node does not support
-        it, it returns None as owner and self as name.
-        """
-        return None, self
-
-    def prefix(self, prefix):
+    def prefix_nested_name(self, prefix):
         """Prefix a name node (a node returned by :meth:`get_name`)."""
-        raise NotImplementedError()
-
-    def __str__(self):
-        return unicode(self).encode('utf-8')
+        raise NotImplementedError(repr(self))
 
     def __unicode__(self):
-        raise NotImplementedError()
+        raise NotImplementedError(repr(self))
 
     def __repr__(self):
         return '<%s %s>' % (self.__class__.__name__, self)
 
 
-class PrimaryDefExpr(DefExpr):
+def _verify_description_mode(mode):
+    if not mode in ('lastIsName', 'noneIsName', 'markType', 'param'):
+        raise Exception("Description mode '%s' is invalid." % mode)
 
-    def get_name(self):
+
+class ASTOperatorBuildIn(ASTBase):
+    def __init__(self, op):
+        self.op = op
+
+    def get_id(self):
+        if not self.op in _id_operator:
+            raise Exception('Internal error: Build-in operator "%s" can not '
+                            'be mapped to an id.' % self.op)
+        return _id_operator[self.op]
+
+    def __unicode__(self):
+        if self.op in ('new', 'new[]', 'delete', 'delete[]'):
+            return u'operator ' + self.op
+        else:
+            return u'operator' + self.op
+
+    def get_name_no_template(self):
+        return text_type(self)
+
+    def describe_signature(self, signode, mode, env, prefix):
+        _verify_description_mode(mode)
+        identifier = text_type(self)
+        if mode == 'lastIsName':
+            signode += addnodes.desc_name(identifier, identifier)
+        else:
+            signode += addnodes.desc_addname(identifier, identifier)
+
+
+class ASTOperatorType(ASTBase):
+    def __init__(self, type):
+        self.type = type
+
+    def __unicode__(self):
+        return u''.join(['operator ', text_type(self.type)])
+
+    def get_id(self):
+        return u'cv' + self.type.get_id()
+
+    def get_name_no_template(self):
+        return text_type(self)
+
+    def describe_signature(self, signode, mode, env, prefix):
+        _verify_description_mode(mode)
+        identifier = text_type(self)
+        if mode == 'lastIsName':
+            signode += addnodes.desc_name(identifier, identifier)
+        else:
+            signode += addnodes.desc_addname(identifier, identifier)
+
+
+class ASTTemplateArgConstant(ASTBase):
+    def __init__(self, value):
+        self.value = value
+
+    def __unicode__(self):
+        return text_type(self.value)
+
+    def get_id(self):
+        # TODO: doing this properly needs parsing of expressions, let's just
+        # juse it verbatim for now
+        return u'X' + text_type(self) + u'E'
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        signode += nodes.Text(text_type(self))
+
+
+class ASTNestedNameElement(ASTBase):
+    def __init__(self, identifier, templateArgs):
+        self.identifier = identifier
+        self.templateArgs = templateArgs
+
+    def get_id(self):
+        res = []
+        if self.identifier == "std":
+            res.append(u'St')
+        else:
+            res.append(text_type(len(self.identifier)))
+            res.append(self.identifier)
+        if self.templateArgs:
+            res.append('I')
+            for a in self.templateArgs:
+                res.append(a.get_id())
+            res.append('E')
+        return u''.join(res)
+
+    def __unicode__(self):
+        res = []
+        res.append(self.identifier)
+        if self.templateArgs:
+            res.append('<')
+            first = True
+            for a in self.templateArgs:
+                if not first:
+                    res.append(', ')
+                first = False
+                res.append(text_type(a))
+            res.append('>')
+        return u''.join(res)
+
+    def get_name_no_template(self):
+        return text_type(self.identifier)
+
+    def describe_signature(self, signode, mode, env, prefix):
+        _verify_description_mode(mode)
+        if mode == 'markType':
+            targetText = prefix + text_type(self)
+            pnode = addnodes.pending_xref(
+                '', refdomain='cpp', reftype='type',
+                reftarget=targetText, modname=None, classname=None)
+            if env:  # during testing we don't have an env, do we?
+                pnode['cpp:parent'] = env.temp_data.get('cpp:parent')
+            pnode += nodes.Text(text_type(self.identifier))
+            signode += pnode
+        elif mode == 'lastIsName':
+            name = text_type(self.identifier)
+            signode += addnodes.desc_name(name, name)
+        else:
+            raise Exception('Unknown description mode: %s' % mode)
+        if self.templateArgs:
+            signode += nodes.Text('<')
+            first = True
+            for a in self.templateArgs:
+                if not first:
+                    signode += nodes.Text(', ')
+                first = False
+                a.describe_signature(signode, 'markType', env)
+            signode += nodes.Text('>')
+
+
+class ASTNestedName(ASTBase):
+    def __init__(self, names):
+        """Use an empty string as the first name if it should start with '::'
+        """
+        self.names = names
+
+    @property
+    def name(self):
         return self
 
-    def prefix(self, prefix):
-        if isinstance(prefix, PathDefExpr):
-            prefix = prefix.clone()
-            prefix.path.append(self)
-            return prefix
-        return PathDefExpr([prefix, self])
+    def get_id(self):
+        res = []
+        if len(self.names) > 1:
+            res.append('N')
+        for n in self.names:
+            res.append(n.get_id())
+        if len(self.names) > 1:
+            res.append('E')
+        return u''.join(res)
+
+    def get_name_no_last_template(self):
+        res = u'::'.join([text_type(n) for n in self.names[:-1]])
+        if len(self.names) > 1:
+            res += '::'
+        res += self.names[-1].get_name_no_template()
+        return res
+
+    def prefix_nested_name(self, prefix):
+        if self.names[0] == '':
+            return self  # it's defined at global namespace, don't tuch it
+        assert isinstance(prefix, ASTNestedName)
+        names = prefix.names[:]
+        names.extend(self.names)
+        return ASTNestedName(names)
+
+    def __unicode__(self):
+        return u'::'.join([text_type(n) for n in self.names])
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        if mode == 'lastIsName':
+            addname = u'::'.join([text_type(n) for n in self.names[:-1]])
+            if len(self.names) > 1:
+                addname += u'::'
+            name = text_type(self.names[-1])
+            signode += addnodes.desc_addname(addname, addname)
+            self.names[-1].describe_signature(signode, mode, env, '')
+        elif mode == 'noneIsName':
+            name = text_type(self)
+            signode += nodes.Text(name)
+        elif mode == 'param':
+            name = text_type(self)
+            signode += nodes.emphasis(name, name)
+        elif mode == 'markType':
+            # each element should be a pending xref targeting the complete
+            # prefix. however, only the identifier part should be a link, such
+            # that template args can be a link as well.
+            prefix = ''
+            first = True
+            for name in self.names:
+                if not first:
+                    signode += nodes.Text('::')
+                    prefix += '::'
+                first = False
+                if name != '':
+                    name.describe_signature(signode, mode, env, prefix)
+                prefix += text_type(name)
+        else:
+            raise Exception('Unknown description mode: %s' % mode)
 
 
-class NameDefExpr(PrimaryDefExpr):
-
+class ASTTrailingTypeSpecFundamental(ASTBase):
     def __init__(self, name):
         self.name = name
 
-    def get_id(self):
-        name = _id_shortwords.get(self.name)
-        if name is not None:
-            return name
-        return self.name.replace(u' ', u'-')
-
     def __unicode__(self):
-        return unicode(self.name)
-
-
-class PathDefExpr(PrimaryDefExpr):
-
-    def __init__(self, parts):
-        self.path = parts
+        return self.name
 
     def get_id(self):
-        rv = u'::'.join(x.get_id() for x in self.path)
-        return _id_shortwords.get(rv, rv)
+        if not self.name in _id_fundamental:
+            raise Exception(
+                'Semi-internal error: Fundamental type "%s" can not be mapped '
+                'to an id. Is it a true fundamental type? If not so, the '
+                'parser should have rejected it.' % self.name)
+        return _id_fundamental[self.name]
 
-    def split_owner(self):
-        if len(self.path) > 1:
-            return PathDefExpr(self.path[:-1]), self.path[-1]
-        return None, self
-
-    def prefix(self, prefix):
-        if isinstance(prefix, PathDefExpr):
-            prefix = prefix.clone()
-            prefix.path.extend(self.path)
-            return prefix
-        return PathDefExpr([prefix] + self.path)
-
-    def __unicode__(self):
-        return u'::'.join(map(unicode, self.path))
+    def describe_signature(self, signode, mode, env):
+        signode += nodes.Text(text_type(self.name))
 
 
-class ArrayTypeSuffixDefExpr(object):
-
-    def __init__(self, size_hint=None):
-        self.size_hint = size_hint
-
-    def get_id_suffix(self):
-        return 'A'
-
-    def __unicode__(self):
-        return u'[%s]' % (
-            self.size_hint is not None and unicode(self.size_hint) or u'',
-        )
-
-
-class TemplateDefExpr(PrimaryDefExpr):
-
-    def __init__(self, typename, args):
-        self.typename = typename
-        self.args = args
-
-    def split_owner(self):
-        owner, typename = self.typename.split_owner()
-        return owner, TemplateDefExpr(typename, self.args)
-
-    def get_id(self):
-        return u'%s:%s:' % (self.typename.get_id(),
-                            u'.'.join(x.get_id() for x in self.args))
-
-    def __unicode__(self):
-        return u'%s<%s>' % (self.typename, u', '.join(map(unicode, self.args)))
-
-
-class ConstantTemplateArgExpr(PrimaryDefExpr):
-
-    def __init__(self, arg):
-        self.arg = arg
-
-    def get_id(self):
-        return self.arg.replace(u' ', u'-')
-
-    def __unicode__(self):
-        return unicode(self.arg)
-
-
-class WrappingDefExpr(DefExpr):
-
-    def __init__(self, typename):
-        self.typename = typename
-
-    def get_name(self):
-        return self.typename.get_name()
-
-
-class ModifierDefExpr(WrappingDefExpr):
-
-    def __init__(self, typename, modifiers):
-        WrappingDefExpr.__init__(self, typename)
-        self.modifiers = modifiers
-
-    def get_id(self):
-        pieces = [_id_shortwords.get(unicode(x), unicode(x))
-                  for x in self.modifiers]
-        pieces.append(self.typename.get_id())
-        return u'-'.join(pieces)
-
-    def __unicode__(self):
-        return u' '.join(map(unicode, list(self.modifiers) + [self.typename]))
-
-
-class PtrDefExpr(WrappingDefExpr):
-
-    def get_id(self):
-        return self.typename.get_id() + u'P'
-
-    def __unicode__(self):
-        return u'%s*' % self.typename
-
-
-class LValRefDefExpr(WrappingDefExpr):
-
-    def get_id(self):
-        return self.typename.get_id() + u'R'
-
-    def __unicode__(self):
-        return u'%s&' % self.typename
-
-
-class RValRefDefExpr(WrappingDefExpr):
-
-    def get_id(self):
-        return self.typename.get_id() + u'RR'
-
-    def __unicode__(self):
-        return u'%s&&' % self.typename
-
-
-class ConstDefExpr(WrappingDefExpr):
-
-    def __init__(self, typename, prefix=False):
-        WrappingDefExpr.__init__(self, typename)
+class ASTTrailingTypeSpecName(ASTBase):
+    def __init__(self, prefix, nestedName):
         self.prefix = prefix
+        self.nestedName = nestedName
+
+    @property
+    def name(self):
+        return self.nestedName
 
     def get_id(self):
-        return self.typename.get_id() + u'C'
+        return self.nestedName.get_id()
 
     def __unicode__(self):
-        return (self.prefix and u'const %s' or u'%s const') % self.typename
+        res = []
+        if self.prefix:
+            res.append(self.prefix)
+            res.append(' ')
+        res.append(text_type(self.nestedName))
+        return u''.join(res)
+
+    def describe_signature(self, signode, mode, env):
+        if self.prefix:
+            signode += addnodes.desc_annotation(self.prefix, self.prefix)
+            signode += nodes.Text(' ')
+        self.nestedName.describe_signature(signode, mode, env)
 
 
-class CastOpDefExpr(PrimaryDefExpr):
-
-    def __init__(self, typename):
-        self.typename = typename
+class ASTFunctinoParameter(ASTBase):
+    def __init__(self, arg, ellipsis=False):
+        self.arg = arg
+        self.ellipsis = ellipsis
 
     def get_id(self):
-        return u'castto-%s-operator' % self.typename.get_id()
+        if self.ellipsis:
+            return 'z'
+        else:
+            return self.arg.get_id()
 
     def __unicode__(self):
-        return u'operator %s' % self.typename
+        if self.ellipsis:
+            return '...'
+        else:
+            return text_type(self.arg)
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        if self.ellipsis:
+            signode += nodes.Text('...')
+        else:
+            self.arg.describe_signature(signode, mode, env)
 
 
-class ArgumentDefExpr(DefExpr):
+class ASTParametersQualifiers(ASTBase):
+    def __init__(self, args, volatile, const, refQual, exceptionSpec, override,
+                 final, initializer):
+        self.args = args
+        self.volatile = volatile
+        self.const = const
+        self.refQual = refQual
+        self.exceptionSpec = exceptionSpec
+        self.override = override
+        self.final = final
+        self.initializer = initializer
 
-    def __init__(self, type, name, type_suffixes, default=None):
-        self.name = name
-        self.type = type
-        self.type_suffixes = type_suffixes
-        self.default = default
+    def get_modifiers_id(self):
+        res = []
+        if self.volatile:
+            res.append('V')
+        if self.const:
+            res.append('K')
+        if self.refQual == '&&':
+            res.append('O')
+        elif self.refQual == '&':
+            res.append('R')
+        return u''.join(res)
 
-    def get_name(self):
-        return self.name.get_name()
-
-    def get_id(self):
-        buf = []
-        buf.append(self.type and self.type.get_id() or 'X')
-        for suffix in self.type_suffixes:
-            buf.append(suffix.get_id_suffix())
-        return u''.join(buf)
+    def get_param_id(self):
+        if len(self.args) == 0:
+            return 'v'
+        else:
+            return u''.join(a.get_id() for a in self.args)
 
     def __unicode__(self):
-        buf = [(u'%s %s' % (self.type or u'', self.name or u'')).strip()]
-        if self.default is not None:
-            buf.append('=%s' % self.default)
-        for suffix in self.type_suffixes:
-            buf.append(unicode(suffix))
-        return u''.join(buf)
+        res = []
+        res.append('(')
+        first = True
+        for a in self.args:
+            if not first:
+                res.append(', ')
+            first = False
+            res.append(text_type(a))
+        res.append(')')
+        if self.volatile:
+            res.append(' volatile')
+        if self.const:
+            res.append(' const')
+        if self.refQual:
+            res.append(' ')
+            res.append(self.refQual)
+        if self.exceptionSpec:
+            res.append(' ')
+            res.append(text_type(self.exceptionSpec))
+        if self.final:
+            res.append(' final')
+        if self.override:
+            res.append(' override')
+        if self.initializer:
+            res.append(' = ')
+            res.append(self.initializer)
+        return u''.join(res)
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        paramlist = addnodes.desc_parameterlist()
+        for arg in self.args:
+            param = addnodes.desc_parameter('', '', noemph=True)
+            if mode == 'lastIsName':  # i.e., outer-function params
+                arg.describe_signature(param, 'param', env)
+            else:
+                arg.describe_signature(param, 'markType', env)
+            paramlist += param
+        signode += paramlist
+
+        def _add_anno(signode, text):
+            signode += nodes.Text(' ')
+            signode += addnodes.desc_annotation(text, text)
+
+        def _add_text(signode, text):
+            signode += nodes.Text(' ' + text)
+
+        if self.volatile:
+            _add_anno(signode, 'volatile')
+        if self.const:
+            _add_anno(signode, 'const')
+        if self.refQual:
+            _add_text(signode, self.refQual)
+        if self.exceptionSpec:
+            _add_anno(signode, text_type(self.exceptionSpec))
+        if self.final:
+            _add_anno(signode, 'final')
+        if self.override:
+            _add_anno(signode, 'override')
+        if self.initializer:
+            _add_text(signode, '= ' + text_type(self.initializer))
 
 
-class NamedDefExpr(DefExpr):
-
-    def __init__(self, name, visibility, static):
-        self.name = name
+class ASTDeclSpecs(ASTBase):
+    def __init__(self, outer, visibility, storage, inline, virtual, explicit,
+                 constexpr, volatile, const, trailing):
+        self.outer = outer
         self.visibility = visibility
-        self.static = static
-
-    def get_name(self):
-        return self.name.get_name()
-
-    def get_modifiers(self, visibility='public'):
-        rv = []
-        if self.visibility != visibility:
-            rv.append(self.visibility)
-        if self.static:
-            rv.append(u'static')
-        return rv
-
-
-class TypeObjDefExpr(NamedDefExpr):
-
-    def __init__(self, name, visibility, static, typename, type_suffixes):
-        NamedDefExpr.__init__(self, name, visibility, static)
-        self.typename = typename
-        self.type_suffixes = type_suffixes
-
-    def get_id(self):
-        if self.typename is None:
-            buf = [self.name.get_id()]
-        else:
-            buf = [u'%s__%s' % (self.name.get_id(), self.typename.get_id())]
-        for suffix in self.type_suffixes:
-            buf.append(suffix.get_id_suffix())
-        return u''.join(buf)
-
-    def __unicode__(self):
-        buf = self.get_modifiers()
-        if self.typename is None:
-            buf.append(unicode(self.name))
-        else:
-            buf.extend(map(unicode, (self.typename, self.name)))
-        buf = [u' '.join(buf)]
-        for suffix in self.type_suffixes:
-            buf.append(unicode(suffix))
-        return u''.join(buf)
-
-
-class MemberObjDefExpr(NamedDefExpr):
-
-    def __init__(self, name, visibility, static, typename, type_suffixes,
-                 value):
-        NamedDefExpr.__init__(self, name, visibility, static)
-        self.typename = typename
-        self.type_suffixes = type_suffixes
-        self.value = value
-
-    def get_id(self):
-        buf = [u'%s__%s' % (self.name.get_id(), self.typename.get_id())]
-        for suffix in self.type_suffixes:
-            buf.append(suffix.get_id_suffix())
-        return u''.join(buf)
-
-    def __unicode__(self):
-        buf = self.get_modifiers()
-        buf.extend((unicode(self.typename), unicode(self.name)))
-        buf = [u' '.join(buf)]
-        for suffix in self.type_suffixes:
-            buf.append(unicode(suffix))
-        if self.value is not None:
-            buf.append(u' = %s' % self.value)
-        return u''.join(buf)
-
-
-class FuncDefExpr(NamedDefExpr):
-
-    def __init__(self, name, visibility, static, explicit, constexpr, rv,
-                 signature, **kwargs):
-        NamedDefExpr.__init__(self, name, visibility, static)
-        self.rv = rv
-        self.signature = signature
+        self.storage = storage
+        self.inline = inline
+        self.virtual = virtual
         self.explicit = explicit
         self.constexpr = constexpr
-        self.const = kwargs.get('const', False)
-        self.volatile = kwargs.get('volatile', False)
-        self.noexcept = kwargs.get('noexcept', False)
-        self.override = kwargs.get('override', False)
-        self.rvalue_this = kwargs.get('rvalue_this', False)
-        self.lvalue_this = kwargs.get('lvalue_this', False)
-        self.pure_virtual = kwargs.get('pure_virtual', False)
-        self.delete = kwargs.get('delete', False)
-        self.default = kwargs.get('default', False)
+        self.volatile = volatile
+        self.const = const
+        self.trailingTypeSpec = trailing
+
+    @property
+    def name(self):
+        return self.trailingTypeSpec.name
 
     def get_id(self):
-        return u'%s%s%s%s' % (
-            self.name.get_id(),
-            self.signature and u'__' +
-                u'.'.join(x.get_id() for x in self.signature) or u'',
-            self.const and u'C' or u'',
-            self.constexpr and 'CE' or ''
-        )
+        res = []
+        if self.volatile:
+            res.append('V')
+        if self.const:
+            res.append('K')
+        res.append(self.trailingTypeSpec.get_id())
+        return u''.join(res)
+
+    def _print_visibility(self):
+        return (self.visibility and
+                not (
+                    self.outer in ('type', 'member', 'function') and
+                    self.visibility == 'public'))
 
     def __unicode__(self):
-        buf = self.get_modifiers()
+        res = []
+        if self._print_visibility():
+            res.append(self.visibility)
+        if self.storage:
+            res.append(self.storage)
+        if self.inline:
+            res.append('inline')
+        if self.virtual:
+            res.append('virtual')
         if self.explicit:
-            buf.append(u'explicit')
+            res.append('explicit')
         if self.constexpr:
-            buf.append(u'constexpr')
-        if self.rv is not None:
-            buf.append(unicode(self.rv))
-        buf.append(u'%s(%s)' % (self.name, u', '.join(
-            map(unicode, self.signature))))
-        if self.const:
-            buf.append(u'const')
+            res.append('constexpr')
         if self.volatile:
-            buf.append(u'volatile')
-        if self.rvalue_this:
-            buf.append(u'&&')
-        if self.lvalue_this:
-            buf.append(u'&')
-        if self.noexcept:
-            buf.append(u'noexcept')
-        if self.override:
-            buf.append(u'override')
-        if self.pure_virtual:
-            buf.append(u'= 0')
-        if self.default:
-            buf.append(u'= default')
-        if self.delete:
-            buf.append(u'= delete')
-        return u' '.join(buf)
+            res.append('volatile')
+        if self.const:
+            res.append('const')
+        if self.trailingTypeSpec:
+            res.append(text_type(self.trailingTypeSpec))
+        return u' '.join(res)
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        modifiers = []
+
+        def _add(modifiers, text):
+            if len(modifiers) > 0:
+                modifiers.append(nodes.Text(' '))
+            modifiers.append(addnodes.desc_annotation(text, text))
+
+        if self._print_visibility():
+            _add(modifiers, self.visibility)
+        if self.storage:
+            _add(modifiers, self.storage)
+        if self.inline:
+            _add(modifiers, 'inline')
+        if self.virtual:
+            _add(modifiers, 'virtual')
+        if self.explicit:
+            _add(modifiers, 'explicit')
+        if self.constexpr:
+            _add(modifiers, 'constexpr')
+        if self.volatile:
+            _add(modifiers, 'volatile')
+        if self.const:
+            _add(modifiers, 'const')
+        for m in modifiers:
+            signode += m
+        if self.trailingTypeSpec:
+            if len(modifiers) > 0:
+                signode += nodes.Text(' ')
+            self.trailingTypeSpec.describe_signature(signode, mode, env)
 
 
-class ClassDefExpr(NamedDefExpr):
+class ASTPtrOpPtr(ASTBase):
+    def __init__(self, volatile, const):
+        self.volatile = volatile
+        self.const = const
 
-    def __init__(self, name, visibility, static, bases):
-        NamedDefExpr.__init__(self, name, visibility, static)
+    def __unicode__(self):
+        res = ['*']
+        if self.volatile:
+            res.append('volatile ')
+        if self.const:
+            res.append('const ')
+        return u''.join(res)
+
+    def get_id(self):
+        res = ['P']
+        if self.volatile:
+            res.append('V')
+        if self.const:
+            res.append('C')
+        return u''.join(res)
+
+
+class ASTPtrOpRef(ASTBase):
+    def __unicode__(self):
+        return '&'
+
+    def get_id(self):
+        return 'R'
+
+
+class ASTPtrOpParamPack(ASTBase):
+    def __unicode__(self):
+        return '...'
+
+    def get_id(self):
+        return 'Dp'
+
+
+class ASTArray(ASTBase):
+    def __init__(self, size):
+        self.size = size
+
+    def __unicode__(self):
+        return u''.join(['[', text_type(self.size), ']'])
+
+    def get_id(self):
+        # TODO: this should maybe be done differently
+        return u'A' + text_type(self.size) + u'_'
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        signode += nodes.Text(text_type(self))
+
+
+class ASTDeclerator(ASTBase):
+    def __init__(self, ptrOps, declId, suffixOps):
+        self.ptrOps = ptrOps
+        self.declId = declId
+        self.suffixOps = suffixOps
+
+    @property
+    def name(self):
+        return self.declId
+
+    def get_modifiers_id(self):  # only the modifiers for a function, e.g.,
+        # cv-qualifiers
+        for op in self.suffixOps:
+            if isinstance(op, ASTParametersQualifiers):
+                return op.get_modifiers_id()
+        raise Exception(
+            "This should only be called on a function: %s" % text_type(self))
+
+    def get_param_id(self):  # only the parameters (if any)
+        for op in self.suffixOps:
+            if isinstance(op, ASTParametersQualifiers):
+                return op.get_param_id()
+        return ''
+
+    def get_ptr_suffix_id(self):  # only the ptr ops and array specifiers
+        return u''.join(
+            a.get_id()
+            for a in self.ptrOps + self.suffixOps
+            if not isinstance(a, ASTParametersQualifiers))
+
+    def require_start_space(self):
+        if (len(self.ptrOps) > 0 and
+                isinstance(self.ptrOps[-1], ASTPtrOpParamPack)):
+            return False
+        else:
+            return self.declId != None
+
+    def __unicode__(self):
+        res = []
+        for op in self.ptrOps:
+            res.append(text_type(op))
+            if isinstance(op, ASTPtrOpParamPack) and self.declId:
+                res.append(' ')
+        if self.declId:
+            res.append(text_type(self.declId))
+        for op in self.suffixOps:
+            res.append(text_type(op))
+        return u''.join(res)
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        for op in self.ptrOps:
+            signode += nodes.Text(text_type(op))
+            if isinstance(op, ASTPtrOpParamPack) and self.declId:
+                signode += nodes.Text(' ')
+        if self.declId:
+            self.declId.describe_signature(signode, mode, env)
+        for op in self.suffixOps:
+            op.describe_signature(signode, mode, env)
+
+
+class ASTInitializer(ASTBase):
+    def __init__(self, value):
+        self.value = value
+
+    def __unicode__(self):
+        return u''.join([' = ', text_type(self.value)])
+
+    def describe_signature(self, signode, mode):
+        _verify_description_mode(mode)
+        signode += nodes.Text(text_type(self))
+
+
+class ASTType(ASTBase):
+    def __init__(self, declSpecs, decl):
+        self.declSpecs = declSpecs
+        self.decl = decl
+        self.objectType = None
+
+    @property
+    def name(self):
+        name = self.decl.name
+        if not name:
+            name = self.declSpecs.name
+        return name
+
+    def get_id(self):
+        res = []
+        if self.objectType:  # needs the name
+            res.append(_id_prefix)
+            if self.objectType == 'function':  # also modifiers
+                res.append(self.decl.get_modifiers_id())
+                res.append(self.prefixedName.get_id())
+                res.append(self.decl.get_param_id())
+            elif self.objectType == 'type':  # just the name
+                res.append(self.prefixedName.get_id())
+            else:
+                print(self.objectType)
+                assert False
+        else:  # only type encoding
+            res.append(self.decl.get_ptr_suffix_id())
+            res.append(self.declSpecs.get_id())
+            res.append(self.decl.get_param_id())
+        return u''.join(res)
+
+    def __unicode__(self):
+        res = []
+        declSpecs = text_type(self.declSpecs)
+        res.append(declSpecs)
+        if self.decl.require_start_space() and len(declSpecs) > 0:
+            res.append(u' ')
+        res.append(text_type(self.decl))
+        return u''.join(res)
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        self.declSpecs.describe_signature(signode, 'markType', env)
+        if (self.decl.require_start_space() and
+                    len(text_type(self.declSpecs)) > 0):
+            signode += nodes.Text(' ')
+        self.decl.describe_signature(signode, mode, env)
+
+
+class ASTTypeWithInit(ASTBase):
+    def __init__(self, type, init):
+        self.objectType = None
+        self.type = type
+        self.init = init
+
+    @property
+    def name(self):
+        return self.type.name
+
+    def get_id(self):
+        if self.objectType == 'member':
+            return _id_prefix + self.prefixedName.get_id()
+        else:
+            return self.type.get_id()
+
+    def __unicode__(self):
+        res = []
+        res.append(text_type(self.type))
+        if self.init:
+            res.append(text_type(self.init))
+        return u''.join(res)
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        self.type.describe_signature(signode, mode, env)
+        if self.init:
+            self.init.describe_signature(signode, mode)
+
+
+class ASTBaseClass(ASTBase):
+    def __init__(self, name, visibility):
+        self.name = name
+        self.visibility = visibility
+
+    def __unicode__(self):
+        res = []
+        if self.visibility != 'private':
+            res.append(self.visibility)
+            res.append(' ')
+        res.append(text_type(self.name))
+        return u''.join(res)
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        if self.visibility != 'private':
+            signode += addnodes.desc_annotation(
+                self.visibility, self.visibility)
+            signode += nodes.Text(' ')
+            self.name.describe_signature(signode, mode, env)
+
+
+class ASTClass(ASTBase):
+    def __init__(self, name, bases):
+        self.name = name
         self.bases = bases
 
     def get_id(self):
-        return self.name.get_id()
-
-    def _tostring(self, visibility='public'):
-        buf = self.get_modifiers(visibility)
-        buf.append(unicode(self.name))
-        if self.bases:
-            buf.append(u':')
-            buf.append(u', '.join(base._tostring('private')
-                                  for base in self.bases))
-        return u' '.join(buf)
+        return _id_prefix + self.prefixedName.get_id()
 
     def __unicode__(self):
-        return self._tostring('public')
+        res = []
+        res.append(text_type(self.name))
+        if len(self.bases) > 0:
+            res.append(' : ')
+            first = True
+            for b in self.bases:
+                if not first:
+                    res.append(', ')
+                first = False
+                res.append(text_type(b))
+        return u''.join(res)
+
+    def describe_signature(self, signode, mode, env):
+        _verify_description_mode(mode)
+        self.name.describe_signature(signode, mode, env)
+        if len(self.bases) > 0:
+            signode += nodes.Text(' : ')
+            for b in self.bases:
+                b.describe_signature(signode, mode, env)
+                signode += nodes.Text(', ')
+            signode.pop()
+
 
 class DefinitionParser(object):
+    # those without signedness and size modifiers
+    # see http://en.cppreference.com/w/cpp/language/types
+    _simple_fundemental_types = (
+        'void', 'bool', 'char', 'wchar_t', 'char16_t', 'char32_t', 'int',
+        'float', 'double', 'auto'
+    )
 
-    # mapping of valid type modifiers.  if the set is None it means
-    # the modifier can prefix all types, otherwise only the types
-    # (actually more keywords) in the set.  Also check
-    # _guess_typename when changing this.
-    _modifiers = {
-        'volatile':     None,
-        'register':     None,
-        'mutable':      None,
-        'const':        None,
-        'typename':     None,
-        'struct':       None,
-        'unsigned':     set(('char', 'short', 'int', 'long')),
-        'signed':       set(('char', 'short', 'int', 'long')),
-        'short':        set(('int',)),
-        'long':         set(('int', 'long', 'double'))
-    }
+    _prefix_keys = ('class', 'struct', 'union', 'typename')
 
     def __init__(self, definition):
         self.definition = definition.strip()
@@ -552,8 +1056,10 @@
         self._previous_state = (0, None)
 
     def fail(self, msg):
-        raise DefinitionError('Invalid definition: %s [error at %d]\n  %s' %
-            (msg, self.pos, self.definition))
+        indicator = '-' * self.pos + '^'
+        raise DefinitionError(
+            'Invalid definition: %s [error at %d]\n  %s\n  %s' %
+            (msg, self.pos, self.definition, indicator))
 
     def match(self, regex):
         match = regex.match(self.definition, self.pos)
@@ -602,369 +1108,6 @@
         if self.last_match is not None:
             return self.last_match.group()
 
-    def _parse_operator(self):
-        self.skip_ws()
-        # thank god, a regular operator definition
-        if self.match(_operator_re):
-            return NameDefExpr('operator' +
-                                _whitespace_re.sub('', self.matched_text))
-
-        # new/delete operator?
-        for allocop in 'new', 'delete':
-            if not self.skip_word(allocop):
-                continue
-            self.skip_ws()
-            if self.skip_string('['):
-                self.skip_ws()
-                if not self.skip_string(']'):
-                    self.fail('expected "]" for ' + allocop)
-                allocop += '[]'
-            return NameDefExpr('operator ' + allocop)
-
-        # oh well, looks like a cast operator definition.
-        # In that case, eat another type.
-        type = self._parse_type()
-        return CastOpDefExpr(type)
-
-    def _parse_name(self):
-        return self._parse_name_or_template_arg(False)
-
-    def _parse_name_or_template_arg(self, in_template):
-        if not self.match(_identifier_re):
-            if not in_template:
-                self.fail('expected name')
-            if not self.match(_template_arg_re):
-                self.fail('expected name or constant template argument')
-            return ConstantTemplateArgExpr(self.matched_text.strip())
-        identifier = self.matched_text
-
-        # strictly speaking, operators are not regular identifiers
-        # but because operator is a keyword, it might not be used
-        # for variable names anyways, so we can safely parse the
-        # operator here as identifier
-        if identifier == 'operator':
-            return self._parse_operator()
-
-        return NameDefExpr(identifier)
-
-    def _guess_typename(self, path):
-        if not path:
-            return [], 'int'
-        # for the long type, we don't want the int in there
-        if 'long' in path:
-            path = [x for x in path if x != 'int']
-            # remove one long
-            path.remove('long')
-            return path, 'long'
-        if path[-1] in ('int', 'char'):
-            return path[:-1], path[-1]
-        return path, 'int'
-
-    def _attach_crefptr(self, expr, is_const=False):
-        if is_const:
-            expr = ConstDefExpr(expr, prefix=True)
-        while 1:
-            self.skip_ws()
-            if self.skip_word('const'):
-                expr = ConstDefExpr(expr)
-            elif self.skip_string('*'):
-                expr = PtrDefExpr(expr)
-            elif self.skip_string('&'):
-                if self.skip_string('&'):
-                    expr = RValRefDefExpr(expr)
-                else:
-                    expr = LValRefDefExpr(expr)
-            else:
-                return expr
-
-    def _try_parse_type_suffixes(self):
-        rv = []
-        while self.match(_array_def_re):
-            rv.append(ArrayTypeSuffixDefExpr(self.last_match.group(1)))
-            self.skip_ws()
-        return rv
-
-    def _peek_const(self, path):
-        try:
-            path.remove('const')
-            return True
-        except ValueError:
-            return False
-
-    def _parse_builtin(self, modifiers):
-        modifier = modifiers[-1]
-        path = modifiers
-        following = self._modifiers[modifier]
-        while 1:
-            self.skip_ws()
-            if not self.match(_identifier_re):
-                break
-            identifier = self.matched_text
-            if identifier in following:
-                path.append(identifier)
-                following = self._modifiers[modifier]
-                assert following
-            else:
-                self.backout()
-                break
-
-        is_const = self._peek_const(path)
-        modifiers, typename = self._guess_typename(path)
-        rv = ModifierDefExpr(NameDefExpr(typename), modifiers)
-        return self._attach_crefptr(rv, is_const)
-
-    def _parse_type_expr(self, in_template=False):
-        typename = self._parse_name_or_template_arg(in_template)
-        self.skip_ws()
-        if not self.skip_string('<'):
-            return typename
-
-        args = []
-        while 1:
-            self.skip_ws()
-            if self.skip_string('>'):
-                break
-            if args:
-                if not self.skip_string(','):
-                    self.fail('"," or ">" in template expected')
-                self.skip_ws()
-            args.append(self._parse_type(True))
-        return TemplateDefExpr(typename, args)
-
-    def _parse_type(self, in_template=False):
-        self.skip_ws()
-        result = []
-        modifiers = []
-
-        # if there is a leading :: or not, we don't care because we
-        # treat them exactly the same.  Buf *if* there is one, we
-        # don't have to check for type modifiers
-        if not self.skip_string('::'):
-            self.skip_ws()
-            while self.match(_identifier_re):
-                modifier = self.matched_text
-                if modifier in self._modifiers:
-                    following = self._modifiers[modifier]
-                    # if the set is not none, there is a limited set
-                    # of types that might follow.  It is technically
-                    # impossible for a template to follow, so what
-                    # we do is go to a different function that just
-                    # eats types
-                    modifiers.append(modifier)
-                    if following is not None:
-                        return self._parse_builtin(modifiers)
-                    self.skip_ws()
-                else:
-                    self.backout()
-                    break
-
-        while 1:
-            self.skip_ws()
-            if (in_template and self.current_char in ',>') or \
-               (result and not self.skip_string('::')) or \
-               self.eof:
-                break
-            result.append(self._parse_type_expr(in_template))
-
-        if not result:
-            self.fail('expected type')
-        if len(result) == 1:
-            rv = result[0]
-        else:
-            rv = PathDefExpr(result)
-        is_const = self._peek_const(modifiers)
-        if modifiers:
-            rv = ModifierDefExpr(rv, modifiers)
-        return self._attach_crefptr(rv, is_const)
-
-    def _parse_default_expr(self):
-        self.skip_ws()
-        if self.match(_string_re):
-            return self.matched_text
-        paren_stack_depth = 0
-        max_pos = len(self.definition)
-        rv_start = self.pos
-        while 1:
-            idx0 = self.definition.find('(', self.pos)
-            idx1 = self.definition.find(',', self.pos)
-            idx2 = self.definition.find(')', self.pos)
-            if idx0 < 0:
-                idx0 = max_pos
-            if idx1 < 0:
-                idx1 = max_pos
-            if idx2 < 0:
-                idx2 = max_pos
-            idx = min(idx0, idx1, idx2)
-            if idx >= max_pos:
-                self.fail('unexpected end in default expression')
-            if idx == idx0:
-                paren_stack_depth += 1
-            elif idx == idx2:
-                paren_stack_depth -= 1
-                if paren_stack_depth < 0:
-                    break
-            elif paren_stack_depth == 0:
-                break
-            self.pos = idx+1
-
-        rv = self.definition[rv_start:idx]
-        self.pos = idx
-        return rv
-
-    def _parse_signature(self):
-        self.skip_ws()
-        if not self.skip_string('('):
-            self.fail('expected parentheses for function')
-
-        args = []
-        while 1:
-            self.skip_ws()
-            if self.eof:
-                self.fail('missing closing parentheses')
-            if self.skip_string(')'):
-                break
-            if args:
-                if not self.skip_string(','):
-                    self.fail('expected comma between arguments')
-                self.skip_ws()
-
-            if self.skip_string('...'):
-                args.append(ArgumentDefExpr(None, '...', [], None))
-                if self.skip_string(')'):
-                    break
-                else:
-                    self.fail('expected closing parenthesis after ellipses')
-
-            argname = default = None
-            argtype = self._parse_type()
-            self.skip_ws()
-            type_suffixes = self._try_parse_type_suffixes()
-            if self.skip_string('='):
-                default = self._parse_default_expr()
-            elif self.current_char not in ',)':
-                argname = self._parse_name()
-                self.skip_ws()
-                type_suffixes.extend(self._try_parse_type_suffixes())
-                if self.skip_string('='):
-                    default = self._parse_default_expr()
-            if argname is None:
-                argname = argtype
-                argtype = None
-
-            args.append(ArgumentDefExpr(argtype, argname,
-                                        type_suffixes, default))
-        self.skip_ws()
-        attributes = dict(
-            signature=args,
-            const=self.skip_word_and_ws('const'),
-            volatile=self.skip_word_and_ws('volatile'),
-            noexcept=self.skip_word_and_ws('noexcept'),
-            override=self.skip_word_and_ws('override'),
-            pure_virtual=False,
-            lvalue_this=False,
-            rvalue_this=False,
-            delete=False,
-            default=False)
-
-        if self.skip_string('&&'):
-            attributes['rvalue_this'] = True
-        if self.skip_string('&'):
-            attributes['lvalue_this'] = True
-
-        if attributes['lvalue_this'] and attributes['rvalue_this']:
-            self.fail('rvalue reference for *this specifier must be one of'
-                      '"&&" or "&"')
-
-        if self.skip_string('='):
-            self.skip_ws()
-            if self.skip_string('0'):
-                attributes['pure_virtual'] = True
-                return attributes
-            if self.skip_word('NULL') or self.skip_word('nullptr'):
-                attributes['pure_virtual'] = True
-                return attributes
-            if self.skip_word('delete'):
-                attributes['delete'] = True
-                return attributes
-            if self.skip_word('default'):
-                attributes['default'] = True
-                return attributes
-
-            self.fail('functions must be defined with '
-                      'either 0, NULL, nullptr, default or delete, other'
-                      'macros are not allowed')
-        return attributes
-
-    def _parse_visibility_static(self):
-        visibility = 'public'
-        if self.match(_visibility_re):
-            visibility = self.matched_text
-        static = self.skip_word_and_ws('static')
-        return visibility, static
-
-    def parse_type(self):
-        return self._parse_type()
-
-    def parse_type_object(self):
-        visibility, static = self._parse_visibility_static()
-        typename = self._parse_type()
-        self.skip_ws()
-        if not self.eof:
-            name = self._parse_type()
-            type_suffixes = self._try_parse_type_suffixes()
-        else:
-            name = typename
-            typename = None
-            type_suffixes = []
-        return TypeObjDefExpr(name, visibility, static, typename, type_suffixes)
-
-    def parse_member_object(self):
-        visibility, static = self._parse_visibility_static()
-        typename = self._parse_type()
-        name = self._parse_type()
-        type_suffixes = self._try_parse_type_suffixes()
-        self.skip_ws()
-        if self.skip_string('='):
-            value = self.read_rest().strip()
-        else:
-            value = None
-        return MemberObjDefExpr(name, visibility, static, typename,
-                                type_suffixes, value)
-
-    def parse_function(self):
-        visibility, static = self._parse_visibility_static()
-        explicit = self.skip_word_and_ws('explicit')
-        constexpr = self.skip_word_and_ws('constexpr')
-
-        rv = self._parse_type()
-        self.skip_ws()
-        # some things just don't have return values
-        if self.current_char == '(':
-            name = rv
-            rv = None
-        else:
-            name = self._parse_type()
-        return FuncDefExpr(name, visibility, static, explicit, constexpr, rv,
-                           **self._parse_signature())
-
-    def parse_class(self):
-        visibility, static = self._parse_visibility_static()
-        name = self._parse_type()
-        bases = []
-        if self.skip_string(':'):
-            self.skip_ws()
-            while 1:
-                access = 'private'
-                if self.match(_visibility_re):
-                    access = self.matched_text
-                base = self._parse_type()
-                bases.append(ClassDefExpr(base, access, False, []))
-                if self.skip_string(','):
-                    self.skip_ws()
-                else:
-                    break
-        return ClassDefExpr(name, visibility, static, bases)
-
     def read_rest(self):
         rv = self.definition[self.pos:]
         self.pos = self.end
@@ -976,6 +1119,518 @@
             self.fail('expected end of definition, got %r' %
                       self.definition[self.pos:])
 
+    def _parse_operator(self):
+        self.skip_ws()
+        # adapted from the old code
+        # thank god, a regular operator definition
+        if self.match(_operator_re):
+            return ASTOperatorBuildIn(self.matched_text)
+
+        # new/delete operator?
+        for op in 'new', 'delete':
+            if not self.skip_word(op):
+                continue
+            self.skip_ws()
+            if self.skip_string('['):
+                self.skip_ws()
+                if not self.skip_string(']'):
+                    self.fail('Expected "]" after  "operator ' + op + '["')
+                op += '[]'
+            return ASTOperatorBuildIn(op)
+
+        # oh well, looks like a cast operator definition.
+        # In that case, eat another type.
+        type = self._parse_type()
+        return ASTOperatorType(type)
+
+    def _parse_nested_name(self):
+        names = []
+
+        self.skip_ws()
+        if self.skip_string('::'):
+            names.append(u'')
+        while 1:
+            self.skip_ws()
+            # TODO: parse the "template" keyword
+            if not self.match(_identifier_re):
+                self.fail("expected identifier")
+            identifier = self.matched_text
+            if identifier == 'operator':
+                op = self._parse_operator()
+                names.append(op)
+            else:
+                templateArgs = None
+                self.skip_ws()
+                if self.skip_string('<'):
+                    templateArgs = []
+                    while 1:
+                        pos = self.pos
+                        try:
+                            type = self._parse_type(allowParams=True)
+                            templateArgs.append(type)
+                        except DefinitionError:
+                            self.pos = pos
+                            symbols = []
+                            startPos = self.pos
+                            self.skip_ws()
+                            if self.match(_string_re):
+                                value = self.matched_text
+                            else:
+                                while not self.eof:
+                                    if (len(symbols) == 0 and
+                                                self.current_char in (
+                                            ',', '>')):
+                                        break
+                                    # TODO: actually implement nice handling
+                                    # of quotes, braces, brackets, parens, and
+                                    # whatever
+                                    self.pos += 1
+                                if self.eof:
+                                    self.pos = startPos
+                                    self.fail(
+                                        'Could not find end of constant '
+                                        'template argument.')
+                                value = self.definition[
+                                        startPos:self.pos].strip()
+                            templateArgs.append(ASTTemplateArgConstant(value))
+                        self.skip_ws()
+                        if self.skip_string('>'):
+                            break
+                        elif self.skip_string(','):
+                            continue
+                        else:
+                            self.fail('Expected ">" or "," in template '
+                                      'argument list.')
+                names.append(ASTNestedNameElement(identifier, templateArgs))
+
+            self.skip_ws()
+            if not self.skip_string('::'):
+                break
+        return ASTNestedName(names)
+
+    def _parse_trailing_type_spec(self):
+        # fundemental types
+        self.skip_ws()
+        for t in self._simple_fundemental_types:
+            if self.skip_word(t):
+                return ASTTrailingTypeSpecFundamental(t)
+
+        # TODO: this could/should be more strict
+        elements = []
+        self.skip_ws()
+        if self.skip_word_and_ws('signed'):
+            elements.append('signed')
+        elif self.skip_word_and_ws('unsigned'):
+            elements.append('unsigned')
+        while 1:
+            if self.skip_word_and_ws('short'):
+                elements.append('short')
+            elif self.skip_word_and_ws('long'):
+                elements.append('long')
+            else:
+                break
+        if self.skip_word_and_ws('int'):
+            elements.append('int')
+        elif self.skip_word_and_ws('double'):
+            elements.append('double')
+        if len(elements) > 0:
+            return ASTTrailingTypeSpecFundamental(u' '.join(elements))
+
+        # decltype
+        self.skip_ws()
+        if self.skip_word_and_ws('decltype'):
+            self.fail('"decltype(.)" in trailing_type_spec not implemented')
+
+        # prefixed
+        prefix = None
+        self.skip_ws()
+        for k in self._prefix_keys:
+            if self.skip_word_and_ws(k):
+                prefix = k
+                break
+
+        nestedName = self._parse_nested_name()
+        return ASTTrailingTypeSpecName(prefix, nestedName)
+
+    def _parse_parameters_and_qualifiers(self, paramMode):
+        self.skip_ws()
+        if not self.skip_string('('):
+            if paramMode == 'function':
+                self.fail('Expecting "(" in parameters_and_qualifiers.')
+            else:
+                return None
+        args = []
+        self.skip_ws()
+        if not self.skip_string(')'):
+            while 1:
+                self.skip_ws()
+                if self.skip_string('...'):
+                    args.append(ASTFunctinoParameter(None, True))
+                    self.skip_ws()
+                    if not self.skip_string(')'):
+                        self.fail('Expected ")" after "..." in '
+                                  'parameters_and_qualifiers.')
+                    break
+                if paramMode == 'function':
+                    arg = self._parse_type_with_init(named='maybe')
+                else:
+                    arg = self._parse_type()
+                # TODO: parse default parameters
+                args.append(ASTFunctinoParameter(arg))
+
+                self.skip_ws()
+                if self.skip_string(','):
+                    continue
+                elif self.skip_string(')'):
+                    break
+                else:
+                    self.fail(
+                        'Expecting "," or ")" in parameters_and_qualifiers, '
+                        'got "%s".' % self.current_char)
+
+        if paramMode != 'function':
+            return ASTParametersQualifiers(
+                args, None, None, None, None, None, None, None)
+
+        self.skip_ws()
+        const = self.skip_word_and_ws('const')
+        volatile = self.skip_word_and_ws('volatile')
+        if not const:  # the can be permuted
+            const = self.skip_word_and_ws('const')
+
+        refQual = None
+        if self.skip_string('&&'):
+            refQual = '&&'
+        if not refQual and self.skip_string('&'):
+            refQual = '&'
+
+        exceptionSpec = None
+        override = None
+        final = None
+        initializer = None
+        self.skip_ws()
+        if self.skip_string('noexcept'):
+            exceptionSpec = 'noexcept'
+            self.skip_ws()
+            if self.skip_string('('):
+                self.fail('Parameterised "noexcept" not implemented.')
+
+        self.skip_ws()
+        override = self.skip_word_and_ws('override')
+        final = self.skip_word_and_ws('final')
+        if not override:
+            override = self.skip_word_and_ws(
+                'override')  # they can be permuted
+
+        self.skip_ws()
+        if self.skip_string('='):
+            self.skip_ws()
+            valid = ('0', 'delete', 'default')
+            for w in valid:
+                if self.skip_word_and_ws(w):
+                    initializer = w
+                    break
+            if not initializer:
+                self.fail(
+                    'Expected "%s" in initializer-specifier.'
+                    % u'" or "'.join(valid))
+
+        return ASTParametersQualifiers(
+            args, volatile, const, refQual, exceptionSpec, override, final,
+            initializer)
+
+    def _parse_decl_specs(self, outer, typed=True):
+        """
+        visibility storage-class-specifier function-specifier "constexpr"
+        "volatile" "const" trailing-type-specifier
+
+        storage-class-specifier -> "static" (only for member_object and
+        function_object)
+
+        function-specifier -> "inline" | "virtual" | "explicit" (only for
+        function_object)
+
+        "constexpr" (only for member_object and function_object)
+        """
+        visibility = None
+        storage = None
+        inline = None
+        virtual = None
+        explicit = None
+        constexpr = None
+        volatile = None
+        const = None
+
+        if outer:
+            self.skip_ws()
+            if self.match(_visibility_re):
+                visibility = self.matched_text
+
+        while 1:  # accept any permutation of a subset of some decl-specs
+            self.skip_ws()
+            if not storage:
+                if outer in ('member', 'function'):
+                    if self.skip_word('static'):
+                        storage = 'static'
+                        continue
+                if outer == 'member':
+                    if self.skip_word('mutable'):
+                        storage = 'mutable'
+                        continue
+                if outer == 'fuction':
+                    # TODO: maybe in more contexts, missing test cases
+                    if self.skip_word('register'):
+                        storage = 'register'
+                        continue
+
+            if outer == 'function':
+                # function-specifiers
+                if not inline:
+                    inline = self.skip_word('inline')
+                    if inline:
+                        continue
+                if not virtual:
+                    virtual = self.skip_word('virtual')
+                    if virtual:
+                        continue
+                if not explicit:
+                    explicit = self.skip_word('explicit')
+                    if explicit:
+                        continue
+
+            if not constexpr and outer in ('member', 'function'):
+                constexpr = self.skip_word("constexpr")
+                if constexpr:
+                    continue
+            if not volatile and typed:
+                volatile = self.skip_word('volatile')
+                if volatile:
+                    continue
+            if not const and typed:
+                const = self.skip_word('const')
+                if const:
+                    continue
+            break
+
+        if typed:
+            trailing = self._parse_trailing_type_spec()
+        else:
+            trailing = None
+        return ASTDeclSpecs(
+            outer, visibility, storage, inline, virtual, explicit, constexpr,
+            volatile, const, trailing)
+
+    def _parse_declerator(self, named, paramMode=None, typed=True):
+        if paramMode:
+            if not paramMode in ('type', 'function'):
+                raise Exception(
+                    "Internal error, unknown paramMode '%s'." % paramMode)
+        ptrOps = []
+        while 1:
+            if not typed:
+                break
+            self.skip_ws()
+            if self.skip_string('*'):
+                self.skip_ws()
+                volatile = self.skip_word_and_ws('volatile')
+                const = self.skip_word_and_ws('const')
+                ptrOps.append(ASTPtrOpPtr(volatile=volatile, const=const))
+            elif self.skip_string('&'):
+                ptrOps.append(ASTPtrOpRef())
+            elif self.skip_string('...'):
+                ptrOps.append(ASTPtrOpParamPack())
+                break
+            else:
+                break
+
+        if named == 'maybe':
+            try:
+                declId = self._parse_nested_name()
+            except DefinitionError:
+                declId = None
+        elif named:
+            declId = self._parse_nested_name()
+        else:
+            declId = None
+
+        suffixOpts = []
+        while 1:
+            self.skip_ws()
+            if typed and self.skip_string('['):
+                startPos = self.pos - 1
+                openCount = 1
+                while not self.eof:
+                    c = self.current_char
+                    if c == '[':
+                        openCount += 1
+                    elif c == ']':
+                        openCount -= 1
+                    if openCount == 0:
+                        break
+                    self.pos += 1
+                if self.eof:
+                    self.pos = startPos
+                    self.fail(
+                        "Could not find closing square bracket for array.")
+                self.pos += 1
+                suffixOpts.append(ASTArray(
+                    self.definition[startPos + 1:self.pos - 1].strip()))
+                continue
+            if paramMode:
+                paramQual = self._parse_parameters_and_qualifiers(paramMode)
+                if paramQual:
+                    suffixOpts.append(paramQual)
+            break
+
+        return ASTDeclerator(ptrOps, declId, suffixOpts)
+
+    def _parse_initializer(self, outer=None):
+        self.skip_ws()
+        # TODO: support paren and brace initialization for memberObject
+        if not self.skip_string('='):
+            return None
+        else:
+            if outer == 'member':
+                value = self.read_rest().strip()
+                return ASTInitializer(value)
+            elif outer == None:  # function parameter
+                symbols = []
+                startPos = self.pos
+                self.skip_ws()
+                if self.match(_string_re):
+                    value = self.matched_text
+                    return ASTInitializer(value)
+                while not self.eof:
+                    if len(symbols) == 0 and self.current_char in (',', ')'):
+                        break
+                    elif len(symbols) > 0 and self.current_char == symbols[-1]:
+                        symbols.pop()
+                    elif self.current_char == '(':
+                        symbols.append(')')
+                    # TODO: actually implement nice handling of quotes, braces,
+                    # brackets, parens, and whatever
+                    self.pos += 1
+                if self.eof:
+                    self.pos = startPos
+                    self.fail(
+                        'Could not find end of default value for function '
+                        'parameter.')
+                value = self.definition[startPos:self.pos].strip()
+                return ASTInitializer(value)
+            else:
+                self.fail(
+                    "Internal error, initializer for outer '%s' not "
+                    "implemented." % outer)
+
+    def _parse_type(self, outer=None, named=False, allowParams=False):
+        """
+        named=False|'maybe'|True: 'maybe' is e.g., for function objects which
+        doesn't need to name the arguments
+        """
+        if outer:  # always named
+            if not outer in ('type', 'member', 'function'):
+                raise Exception('Internal error, unknown outer "%s".' % outer)
+            assert not named
+
+        if outer in ('type', 'function'):
+            # We allow type objects to just be a name.
+            # Some functions don't have normal return types: constructors,
+            # destrutors, cast operators
+            startPos = self.pos
+            # first try without the type
+            try:
+                declSpecs = self._parse_decl_specs(outer=outer, typed=False)
+                decl = self._parse_declerator(named=True, paramMode=outer,
+                                              typed=False)
+                self.assert_end()
+            except DefinitionError as exUntyped:
+                self.pos = startPos
+                try:
+                    declSpecs = self._parse_decl_specs(outer=outer)
+                    decl = self._parse_declerator(named=True, paramMode=outer)
+                except DefinitionError as exTyped:
+                    if outer == 'type':
+                        raise DefinitionError(
+                            'Type must be either just a name or a '
+                            'typedef-like declaration.\nJust a name error: '
+                            '%s\nTypedef-like expression error: %s'
+                            % (exUntyped.description, exTyped.description))
+                    else:
+                        # do it again to get the proper traceback (how do you
+                        # relieable save a traceback when an exception is
+                        # constructed?)
+                        self.pos = startPos
+                        declSpecs = self._parse_decl_specs(outer=outer)
+                        decl = self._parse_declerator(named=True,
+                                                      paramMode=outer)
+        else:
+            if outer:
+                named = True
+                allowParams = True
+            if allowParams:
+                paramMode = 'type'
+            else:
+                paramMode = None
+            declSpecs = self._parse_decl_specs(outer=outer)
+            decl = self._parse_declerator(named=named, paramMode=paramMode)
+        return ASTType(declSpecs, decl)
+
+    def _parse_type_with_init(self, outer=None, named=False):
+        if outer:
+            assert outer in ('type', 'member', 'function')
+        type = self._parse_type(outer=outer, named=named)
+        init = self._parse_initializer(outer=outer)
+        return ASTTypeWithInit(type, init)
+
+    def _parse_class(self):
+        name = self._parse_nested_name()
+        bases = []
+        self.skip_ws()
+        if self.skip_string(':'):
+            while 1:
+                self.skip_ws()
+                visibility = 'private'
+                if self.match(_visibility_re):
+                    visibility = self.matched_text
+                baseName = self._parse_nested_name()
+                bases.append(ASTBaseClass(baseName, visibility))
+                self.skip_ws()
+                if self.skip_string(','):
+                    continue
+                else:
+                    break
+        return ASTClass(name, bases)
+
+    def parse_type_object(self):
+        res = self._parse_type(outer='type')
+        res.objectType = 'type'
+        return res
+
+    def parse_member_object(self):
+        res = self._parse_type_with_init(outer='member')
+        res.objectType = 'member'
+        return res
+
+    def parse_function_object(self):
+        res = self._parse_type(outer='function')
+        res.objectType = 'function'
+        return res
+
+    def parse_class_object(self):
+        res = self._parse_class()
+        res.objectType = 'class'
+        return res
+
+    def parse_namespace_object(self):
+        res = self._parse_nested_name()
+        res.objectType = 'namespace'
+        return res
+
+    def parse_xref_object(self):
+        res = self._parse_nested_name()
+        res.objectType = 'xref'
+        return res
+
 
 class CPPObject(ObjectDescription):
     """Description of a C++ language object."""
@@ -991,214 +1646,120 @@
               names=('returns', 'return')),
     ]
 
-    def attach_name(self, node, name):
-        owner, name = name.split_owner()
-        varname = unicode(name)
-        if owner is not None:
-            owner = unicode(owner) + '::'
-            node += addnodes.desc_addname(owner, owner)
-        node += addnodes.desc_name(varname, varname)
-
-    def attach_type_suffixes(self, node, suffixes):
-        for suffix in suffixes:
-            node += nodes.Text(unicode(suffix))
-
-    def attach_type(self, node, type):
-        # XXX: link to c?
-        text = unicode(type)
-        pnode = addnodes.pending_xref(
-            '', refdomain='cpp', reftype='type',
-            reftarget=text, modname=None, classname=None)
-        pnode['cpp:parent'] = self.env.temp_data.get('cpp:parent')
-        pnode += nodes.Text(text)
-        node += pnode
-
-    def attach_modifiers(self, node, obj, visibility='public'):
-        if obj.visibility != visibility:
-            node += addnodes.desc_annotation(obj.visibility,
-                                             obj.visibility)
-            node += nodes.Text(' ')
-        if obj.static:
-            node += addnodes.desc_annotation('static', 'static')
-            node += nodes.Text(' ')
-        if getattr(obj, 'constexpr', False):
-            node += addnodes.desc_annotation('constexpr', 'constexpr')
-            node += nodes.Text(' ')
-
-    def add_target_and_index(self, sigobj, sig, signode):
-        theid = sigobj.get_id()
-        name = unicode(sigobj.name)
+    def add_target_and_index(self, ast, sig, signode):
+        theid = ast.get_id()
+        name = text_type(ast.prefixedName)
         if theid not in self.state.document.ids:
-            signode['names'].append(theid)
+            # the name is not unique, the first one will win
+            objects = self.env.domaindata['cpp']['objects']
+            if not name in objects:
+                signode['names'].append(name)
             signode['ids'].append(theid)
             signode['first'] = (not self.names)
             self.state.document.note_explicit_target(signode)
-
-            self.env.domaindata['cpp']['objects'].setdefault(name,
-                (self.env.docname, self.objtype, theid))
+            if not name in objects:
+                objects.setdefault(name,
+                                   (self.env.docname, ast.objectType, theid))
+                # add the uninstantiated template if it doesn't exist
+                uninstantiated = ast.prefixedName.get_name_no_last_template()
+                if uninstantiated != name and uninstantiated not in objects:
+                    signode['names'].append(uninstantiated)
+                    objects.setdefault(uninstantiated, (
+                    self.env.docname, ast.objectType, theid))
+            self.env.temp_data['cpp:lastname'] = ast.prefixedName
 
         indextext = self.get_index_text(name)
-        if indextext:
-            self.indexnode['entries'].append(('single', indextext, theid, ''))
-
-    def before_content(self):
-        lastname = self.names and self.names[-1]
-        if lastname and not self.env.temp_data.get('cpp:parent'):
-            assert isinstance(lastname, NamedDefExpr)
-            self.env.temp_data['cpp:parent'] = lastname.name
-            self.parentname_set = True
-        else:
-            self.parentname_set = False
-
-    def after_content(self):
-        if self.parentname_set:
-            self.env.temp_data['cpp:parent'] = None
+        if not re.compile(r'^[a-zA-Z0-9_]*$').match(theid):
+            self.state_machine.reporter.warning(
+                'Index id generation for C++ object "%s" failed, please '
+                'report as bug (id=%s).' % (text_type(ast), theid),
+                line=self.lineno)
+        self.indexnode['entries'].append(('single', indextext, theid, ''))
 
     def parse_definition(self, parser):
         raise NotImplementedError()
 
-    def describe_signature(self, signode, arg):
+    def describe_signature(self, signode, ast):
         raise NotImplementedError()
 
     def handle_signature(self, sig, signode):
         parser = DefinitionParser(sig)
         try:
-            rv = self.parse_definition(parser)
+            ast = self.parse_definition(parser)
             parser.assert_end()
-        except DefinitionError, e:
-            self.state_machine.reporter.warning(e.description, line=self.lineno)
+        except DefinitionError as e:
+            self.state_machine.reporter.warning(e.description,
+                                                line=self.lineno)
             raise ValueError
-        self.describe_signature(signode, rv)
+        self.describe_signature(signode, ast)
 
         parent = self.env.temp_data.get('cpp:parent')
-        if parent is not None:
-            rv = rv.clone()
-            rv.name = rv.name.prefix(parent)
-        return rv
-
-
-class CPPClassObject(CPPObject):
-
-    def get_index_text(self, name):
-        return _('%s (C++ class)') % name
-
-    def parse_definition(self, parser):
-        return parser.parse_class()
-
-    def describe_signature(self, signode, cls):
-        self.attach_modifiers(signode, cls)
-        signode += addnodes.desc_annotation('class ', 'class ')
-        self.attach_name(signode, cls.name)
-        if cls.bases:
-            signode += nodes.Text(' : ')
-            for base in cls.bases:
-                self.attach_modifiers(signode, base, 'private')
-                signode += nodes.emphasis(unicode(base.name),
-                                          unicode(base.name))
-                signode += nodes.Text(', ')
-            signode.pop()  # remove the trailing comma
+        if parent and len(parent) > 0:
+            ast = ast.clone()
+            ast.prefixedName = ast.name.prefix_nested_name(parent[-1])
+        else:
+            ast.prefixedName = ast.name
+        return ast
 
 
 class CPPTypeObject(CPPObject):
-
     def get_index_text(self, name):
-        if self.objtype == 'type':
-            return _('%s (C++ type)') % name
-        return ''
+        return _('%s (C++ type)') % name
 
     def parse_definition(self, parser):
         return parser.parse_type_object()
 
-    def describe_signature(self, signode, obj):
-        self.attach_modifiers(signode, obj)
+    def describe_signature(self, signode, ast):
         signode += addnodes.desc_annotation('type ', 'type ')
-        if obj.typename is not None:
-            self.attach_type(signode, obj.typename)
-            signode += nodes.Text(' ')
-        self.attach_name(signode, obj.name)
-        self.attach_type_suffixes(signode, obj.type_suffixes)
+        ast.describe_signature(signode, 'lastIsName', self.env)
 
 
 class CPPMemberObject(CPPObject):
-
     def get_index_text(self, name):
-        if self.objtype == 'member':
-            return _('%s (C++ member)') % name
-        return ''
+        return _('%s (C++ member)') % name
 
     def parse_definition(self, parser):
         return parser.parse_member_object()
 
-    def describe_signature(self, signode, obj):
-        self.attach_modifiers(signode, obj)
-        self.attach_type(signode, obj.typename)
-        signode += nodes.Text(' ')
-        self.attach_name(signode, obj.name)
-        self.attach_type_suffixes(signode, obj.type_suffixes)
-        if obj.value is not None:
-            signode += nodes.Text(u' = ' + obj.value)
+    def describe_signature(self, signode, ast):
+        ast.describe_signature(signode, 'lastIsName', self.env)
 
 
 class CPPFunctionObject(CPPObject):
-
-    def attach_function(self, node, func):
-        owner, name = func.name.split_owner()
-        if owner is not None:
-            owner = unicode(owner) + '::'
-            node += addnodes.desc_addname(owner, owner)
-
-        # cast operator is special.  in this case the return value
-        # is reversed.
-        if isinstance(name, CastOpDefExpr):
-            node += addnodes.desc_name('operator', 'operator')
-            node += nodes.Text(u' ')
-            self.attach_type(node, name.typename)
-        else:
-            funcname = unicode(name)
-            node += addnodes.desc_name(funcname, funcname)
-
-        paramlist = addnodes.desc_parameterlist()
-        for arg in func.signature:
-            param = addnodes.desc_parameter('', '', noemph=True)
-            if arg.type is not None:
-                self.attach_type(param, arg.type)
-                param += nodes.Text(u' ')
-            param += nodes.emphasis(unicode(arg.name), unicode(arg.name))
-            self.attach_type_suffixes(param, arg.type_suffixes)
-            if arg.default is not None:
-                def_ = u'=' + unicode(arg.default)
-                param += nodes.emphasis(def_, def_)
-            paramlist += param
-
-        node += paramlist
-        if func.const:
-            node += addnodes.desc_addname(' const', ' const')
-        if func.noexcept:
-            node += addnodes.desc_addname(' noexcept', ' noexcept')
-        if func.pure_virtual:
-            node += addnodes.desc_addname(' = 0', ' = 0')
-
     def get_index_text(self, name):
         return _('%s (C++ function)') % name
 
     def parse_definition(self, parser):
-        return parser.parse_function()
+        return parser.parse_function_object()
 
-    def describe_signature(self, signode, func):
-        self.attach_modifiers(signode, func)
-        if func.explicit:
-            signode += addnodes.desc_annotation('explicit', 'explicit')
-            signode += nodes.Text(' ')
-        # return value is None for things with a reverse return value
-        # such as casting operator definitions or constructors
-        # and destructors.
-        if func.rv is not None:
-            self.attach_type(signode, func.rv)
-        signode += nodes.Text(u' ')
-        self.attach_function(signode, func)
+    def describe_signature(self, signode, ast):
+        ast.describe_signature(signode, 'lastIsName', self.env)
 
 
-class CPPCurrentNamespace(Directive):
+class CPPClassObject(CPPObject):
+    def get_index_text(self, name):
+        return _('%s (C++ class)') % name
+
+    def before_content(self):
+        lastname = self.env.temp_data['cpp:lastname']
+        assert lastname
+        if 'cpp:parent' in self.env.temp_data:
+            self.env.temp_data['cpp:parent'].append(lastname)
+        else:
+            self.env.temp_data['cpp:parent'] = [lastname]
+
+    def after_content(self):
+        self.env.temp_data['cpp:parent'].pop()
+
+    def parse_definition(self, parser):
+        return parser.parse_class_object()
+
+    def describe_signature(self, signode, ast):
+        signode += addnodes.desc_annotation('class ', 'class ')
+        ast.describe_signature(signode, 'lastIsName', self.env)
+
+
+class CPPNamespaceObject(Directive):
     """
     This directive is just to tell Sphinx that we're documenting stuff in
     namespace foo.
@@ -1213,26 +1774,27 @@
     def run(self):
         env = self.state.document.settings.env
         if self.arguments[0].strip() in ('NULL', '0', 'nullptr'):
-            env.temp_data['cpp:prefix'] = None
+            env.temp_data['cpp:parent'] = []
         else:
             parser = DefinitionParser(self.arguments[0])
             try:
-                prefix = parser.parse_type()
+                prefix = parser.parse_namespace_object()
                 parser.assert_end()
-            except DefinitionError, e:
+            except DefinitionError as e:
                 self.state_machine.reporter.warning(e.description,
                                                     line=self.lineno)
             else:
-                env.temp_data['cpp:prefix'] = prefix
+                env.temp_data['cpp:parent'] = [prefix]
         return []
 
 
 class CPPXRefRole(XRefRole):
-
     def process_link(self, env, refnode, has_explicit_title, title, target):
-        refnode['cpp:parent'] = env.temp_data.get('cpp:parent')
+        parent = env.temp_data.get('cpp:parent')
+        if parent:
+            refnode['cpp:parent'] = parent[:]
         if not has_explicit_title:
-            target = target.lstrip('~') # only has a meaning for the title
+            target = target.lstrip('~')  # only has a meaning for the title
             # if the first character is a tilde, don't display the module/class
             # parts of the contents
             if title[:1] == '~':
@@ -1248,70 +1810,69 @@
     name = 'cpp'
     label = 'C++'
     object_types = {
-        'class':    ObjType(l_('class'),    'class'),
+        'class': ObjType(l_('class'), 'class'),
         'function': ObjType(l_('function'), 'func'),
-        'member':   ObjType(l_('member'),   'member'),
-        'type':     ObjType(l_('type'),     'type')
+        'member': ObjType(l_('member'), 'member'),
+        'type': ObjType(l_('type'), 'type')
     }
 
     directives = {
-        'class':        CPPClassObject,
-        'function':     CPPFunctionObject,
-        'member':       CPPMemberObject,
-        'type':         CPPTypeObject,
-        'namespace':    CPPCurrentNamespace
+        'class': CPPClassObject,
+        'function': CPPFunctionObject,
+        'member': CPPMemberObject,
+        'type': CPPTypeObject,
+        'namespace': CPPNamespaceObject
     }
     roles = {
-        'class':  CPPXRefRole(),
-        'func' :  CPPXRefRole(fix_parens=True),
+        'class': CPPXRefRole(),
+        'func': CPPXRefRole(fix_parens=True),
         'member': CPPXRefRole(),
-        'type':   CPPXRefRole()
+        'type': CPPXRefRole()
     }
     initial_data = {
-        'objects': {},  # fullname -> docname, objtype
+        'objects': {},  # prefixedName -> (docname, objectType, id)
     }
 
     def clear_doc(self, docname):
-        for fullname, (fn, _, _) in self.data['objects'].items():
-            if fn == docname:
+        for fullname, data in list(self.data['objects'].items()):
+            if data[0] == docname:
                 del self.data['objects'][fullname]
 
     def resolve_xref(self, env, fromdocname, builder,
                      typ, target, node, contnode):
-        def _create_refnode(expr):
-            name = unicode(expr)
+        def _create_refnode(nameAst):
+            name = text_type(nameAst)
             if name not in self.data['objects']:
-                return None
-            obj = self.data['objects'][name]
-            if obj[1] not in self.objtypes_for_role(typ):
-                return None
-            return make_refnode(builder, fromdocname, obj[0], obj[2],
-                                contnode, name)
+                # try dropping the last template
+                name = nameAst.get_name_no_last_template()
+                if name not in self.data['objects']:
+                    return None
+            docname, objectType, id = self.data['objects'][name]
+            return make_refnode(builder, fromdocname, docname, id, contnode,
+                                name)
 
         parser = DefinitionParser(target)
         try:
-            expr = parser.parse_type().get_name()
+            nameAst = parser.parse_xref_object().name
             parser.skip_ws()
-            if not parser.eof or expr is None:
+            if not parser.eof:
                 raise DefinitionError('')
         except DefinitionError:
             env.warn_node('unparseable C++ definition: %r' % target, node)
             return None
 
+        # try as is the name is fully qualified
+        refNode = _create_refnode(nameAst)
+        if refNode:
+            return refNode
+
+        # try qualifying it with the parent
         parent = node.get('cpp:parent', None)
-
-        rv = _create_refnode(expr)
-        if rv is not None or parent is None:
-            return rv
-        parent = parent.get_name()
-
-        rv = _create_refnode(expr.prefix(parent))
-        if rv is not None:
-            return rv
-
-        parent, name = parent.split_owner()
-        return _create_refnode(expr.prefix(parent))
+        if parent and len(parent) > 0:
+            return _create_refnode(nameAst.prefix_nested_name(parent[-1]))
+        else:
+            return None
 
     def get_objects(self):
-        for refname, (docname, type, theid) in self.data['objects'].iteritems():
-            yield (refname, refname, type, docname, refname, 1)
+        for refname, (docname, type, theid) in iteritems(self.data['objects']):
+            yield (refname, refname, type, docname, refname, 1)
\ No newline at end of file
diff --git a/sphinx/domains/javascript.py b/sphinx/domains/javascript.py
index 9b7777f..2718b87 100644
--- a/sphinx/domains/javascript.py
+++ b/sphinx/domains/javascript.py
@@ -183,7 +183,7 @@
     }
 
     def clear_doc(self, docname):
-        for fullname, (fn, _) in self.data['objects'].items():
+        for fullname, (fn, _) in list(self.data['objects'].items()):
             if fn == docname:
                 del self.data['objects'][fullname]
 
@@ -215,6 +215,6 @@
                             name.replace('$', '_S_'), contnode, name)
 
     def get_objects(self):
-        for refname, (docname, type) in self.data['objects'].iteritems():
+        for refname, (docname, type) in list(self.data['objects'].items()):
             yield refname, refname, type, docname, \
                   refname.replace('$', '_S_'), 1
diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py
index 792cffd..a7a93cb 100644
--- a/sphinx/domains/python.py
+++ b/sphinx/domains/python.py
@@ -11,6 +11,7 @@
 
 import re
 
+from six import iteritems
 from docutils import nodes
 from docutils.parsers.rst import directives
 
@@ -81,6 +82,23 @@
         signode += paramlist
 
 
+# This override allows our inline type specifiers to behave like :class: link
+# when it comes to handling "." and "~" prefixes.
+class PyTypedField(TypedField):
+    def make_xref(self, rolename, domain, target, innernode=nodes.emphasis):
+        result = super(PyTypedField, self).make_xref(rolename, domain, target,
+                                                     innernode)
+        if target.startswith('.'):
+            result['reftarget'] = target[1:]
+            result['refspecific'] = True
+            result[0][0] = nodes.Text(target[1:])
+        if target.startswith('~'):
+            result['reftarget'] = target[1:]
+            title = target.split('.')[-1]
+            result[0][0] = nodes.Text(title)
+        return result
+
+
 class PyObject(ObjectDescription):
     """
     Description of a general Python object.
@@ -92,7 +110,7 @@
     }
 
     doc_field_types = [
-        TypedField('parameter', label=l_('Parameters'),
+        PyTypedField('parameter', label=l_('Parameters'),
                    names=('param', 'parameter', 'arg', 'argument',
                           'keyword', 'kwarg', 'kwparam'),
                    typerolename='obj', typenames=('paramtype', 'type'),
@@ -497,7 +515,7 @@
         ignores = self.domain.env.config['modindex_common_prefix']
         ignores = sorted(ignores, key=len, reverse=True)
         # list of all modules, sorted by module name
-        modules = sorted(self.domain.data['modules'].iteritems(),
+        modules = sorted(iteritems(self.domain.data['modules']),
                          key=lambda x: x[0].lower())
         # sort out collapsable modules
         prev_modname = ''
@@ -547,7 +565,7 @@
         collapse = len(modules) - num_toplevels < num_toplevels
 
         # sort by first letter
-        content = sorted(content.iteritems())
+        content = sorted(iteritems(content))
 
         return content, collapse
 
@@ -602,10 +620,10 @@
     ]
 
     def clear_doc(self, docname):
-        for fullname, (fn, _) in self.data['objects'].items():
+        for fullname, (fn, _) in list(self.data['objects'].items()):
             if fn == docname:
                 del self.data['objects'][fullname]
-        for modname, (fn, _, _, _) in self.data['modules'].items():
+        for modname, (fn, _, _, _) in list(self.data['modules'].items()):
             if fn == docname:
                 del self.data['modules'][modname]
 
@@ -703,8 +721,8 @@
                                 contnode, name)
 
     def get_objects(self):
-        for modname, info in self.data['modules'].iteritems():
+        for modname, info in iteritems(self.data['modules']):
             yield (modname, modname, 'module', info[0], 'module-' + modname, 0)
-        for refname, (docname, type) in self.data['objects'].iteritems():
+        for refname, (docname, type) in iteritems(self.data['objects']):
             if type != 'module':  # modules are already handled
                 yield (refname, refname, type, docname, refname, 1)
diff --git a/sphinx/domains/rst.py b/sphinx/domains/rst.py
index c51c85f..e213211 100644
--- a/sphinx/domains/rst.py
+++ b/sphinx/domains/rst.py
@@ -11,6 +11,8 @@
 
 import re
 
+from six import iteritems
+
 from sphinx import addnodes
 from sphinx.domains import Domain, ObjType
 from sphinx.locale import l_, _
@@ -117,7 +119,7 @@
     }
 
     def clear_doc(self, docname):
-        for (typ, name), doc in self.data['objects'].items():
+        for (typ, name), doc in list(self.data['objects'].items()):
             if doc == docname:
                 del self.data['objects'][typ, name]
 
@@ -133,5 +135,5 @@
                                     contnode, target + ' ' + objtype)
 
     def get_objects(self):
-        for (typ, name), docname in self.data['objects'].iteritems():
+        for (typ, name), docname in iteritems(self.data['objects']):
             yield name, name, typ, docname, typ + '-' + name, 1
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index 43341e4..bb044e3 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -12,6 +12,7 @@
 import re
 import unicodedata
 
+from six import iteritems
 from docutils import nodes
 from docutils.parsers.rst import directives
 from docutils.statemachine import ViewList
@@ -508,29 +509,29 @@
     }
 
     def clear_doc(self, docname):
-        for key, (fn, _) in self.data['progoptions'].items():
+        for key, (fn, _) in list(self.data['progoptions'].items()):
             if fn == docname:
                 del self.data['progoptions'][key]
-        for key, (fn, _) in self.data['objects'].items():
+        for key, (fn, _) in list(self.data['objects'].items()):
             if fn == docname:
                 del self.data['objects'][key]
-        for key, (fn, _, _) in self.data['labels'].items():
+        for key, (fn, _, _) in list(self.data['labels'].items()):
             if fn == docname:
                 del self.data['labels'][key]
-        for key, (fn, _) in self.data['anonlabels'].items():
+        for key, (fn, _) in list(self.data['anonlabels'].items()):
             if fn == docname:
                 del self.data['anonlabels'][key]
 
     def process_doc(self, env, docname, document):
         labels, anonlabels = self.data['labels'], self.data['anonlabels']
-        for name, explicit in document.nametypes.iteritems():
+        for name, explicit in iteritems(document.nametypes):
             if not explicit:
                 continue
             labelid = document.nameids[name]
             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
@@ -548,6 +549,13 @@
                         break
                 else:
                     continue
+            elif node.tagname == 'image' and node.parent.tagname == 'figure':
+                for n in node.parent:
+                    if n.tagname == 'caption':
+                        sectname = clean_astext(n)
+                        break
+                else:
+                    continue
             elif node.tagname == 'table':
                 for n in node:
                     if n.tagname == 'title':
@@ -621,16 +629,16 @@
                                 labelid, contnode)
 
     def get_objects(self):
-        for (prog, option), info in self.data['progoptions'].iteritems():
+        for (prog, option), info in iteritems(self.data['progoptions']):
             yield (option, option, 'option', info[0], info[1], 1)
-        for (type, name), info in self.data['objects'].iteritems():
+        for (type, name), info in iteritems(self.data['objects']):
             yield (name, name, type, info[0], info[1],
                    self.object_types[type].attrs['searchprio'])
-        for name, info in self.data['labels'].iteritems():
+        for name, info in iteritems(self.data['labels']):
             yield (name, info[2], 'label', info[0], info[1], -1)
         # add anonymous-only labels as well
         non_anon_labels = set(self.data['labels'])
-        for name, info in self.data['anonlabels'].iteritems():
+        for name, info in iteritems(self.data['anonlabels']):
             if name not in non_anon_labels:
                 yield (name, name, 'label', info[0], info[1], -1)
 
diff --git a/sphinx/environment.py b/sphinx/environment.py
index 69a8b57..d51e7a1 100644
--- a/sphinx/environment.py
+++ b/sphinx/environment.py
@@ -18,11 +18,12 @@
 import imghdr
 import string
 import unicodedata
-import cPickle as pickle
 from os import path
 from glob import glob
-from itertools import izip, groupby
+from itertools import groupby
 
+from six import iteritems, itervalues, text_type, class_types
+from six.moves import cPickle as pickle, zip
 from docutils import nodes
 from docutils.io import FileInput, NullOutput
 from docutils.core import Publisher
@@ -39,8 +40,6 @@
 from sphinx.util.nodes import clean_astext, make_refnode, WarningStream
 from sphinx.util.osutil import SEP, fs_encoding, find_catalog_files
 from sphinx.util.matching import compile_matchers
-from sphinx.util.pycompat import class_types
-from sphinx.util.compat import docutils_version
 from sphinx.util.websupport import is_commentable
 from sphinx.errors import SphinxError, ExtensionError
 from sphinx.locale import _
@@ -137,7 +136,7 @@
         del self.domains
         picklefile = open(filename, 'wb')
         # remove potentially pickling-problematic values from config
-        for key, val in vars(self.config).items():
+        for key, val in list(vars(self.config).items()):
             if key.startswith('_') or \
                    isinstance(val, types.ModuleType) or \
                    isinstance(val, types.FunctionType) or \
@@ -279,11 +278,11 @@
             self.images.purge_doc(docname)
             self.dlfiles.purge_doc(docname)
 
-            for subfn, fnset in self.files_to_rebuild.items():
+            for subfn, fnset in list(self.files_to_rebuild.items()):
                 fnset.discard(docname)
                 if not fnset:
                     del self.files_to_rebuild[subfn]
-            for key, (fn, _) in self.citations.items():
+            for key, (fn, _) in list(self.citations.items()):
                 if fn == docname:
                     del self.citations[key]
             for version, changes in self.versionchanges.items():
@@ -340,10 +339,8 @@
         """
         matchers = compile_matchers(
             config.exclude_patterns[:] +
+            config.templates_path +
             config.html_extra_path +
-            config.exclude_trees +
-            [d + config.source_suffix for d in config.unused_docs] +
-            ['**/' + d for d in config.exclude_dirnames] +
             ['**/_sources', '.#*']
         )
         self.found_docs = set(get_matching_docs(
@@ -425,7 +422,7 @@
         else:
             # check if a config value was changed that affects how
             # doctrees are read
-            for key, descr in config.values.iteritems():
+            for key, descr in iteritems(config.values):
                 if descr[1] != 'env':
                     continue
                 if self.config[key] != config[key]:
@@ -497,14 +494,14 @@
 
     def warn_and_replace(self, error):
         """Custom decoding error handler that warns and replaces."""
-        linestart = error.object.rfind('\n', 0, error.start)
-        lineend = error.object.find('\n', error.start)
+        linestart = error.object.rfind(b'\n', 0, error.start)
+        lineend = error.object.find(b'\n', error.start)
         if lineend == -1: lineend = len(error.object)
-        lineno = error.object.count('\n', 0, error.start) + 1
+        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] + '>>>' +
-                   error.object[error.start:error.end] + '<<<' +
+                  (error.object[linestart+1:error.start] + b'>>>' +
+                   error.object[error.start:error.end] + b'<<<' +
                    error.object[error.end:lineend]), lineno)
         return (u'?', error.end)
 
@@ -594,12 +591,13 @@
             def __init__(self_, *args, **kwds):
                 # don't call sys.exit() on IOErrors
                 kwds['handle_io_errors'] = False
+                kwds['error_handler'] = 'sphinx'  # py3: handle error on open.
                 FileInput.__init__(self_, *args, **kwds)
 
             def decode(self_, data):
-                if isinstance(data, unicode):
+                if isinstance(data, text_type):  # py3: `data` already decoded.
                     return data
-                return data.decode(self_.encoding, 'sphinx')
+                return data.decode(self_.encoding, 'sphinx')  # py2: decoding
 
             def read(self_):
                 data = FileInput.read(self_)
@@ -620,10 +618,7 @@
                         destination_class=NullOutput)
         pub.set_components(None, 'restructuredtext', None)
         pub.process_programmatic_settings(None, self.settings, None)
-        if docutils_version < (0, 8):  #1531
-            pub.set_source(None, src_path.encode(fs_encoding))
-        else:
-            pub.set_source(None, src_path)
+        pub.set_source(None, src_path)
         pub.set_destination(None, None)
         pub.publish()
         doctree = pub.document
@@ -639,7 +634,7 @@
         self.note_indexentries_from(docname, doctree)
         self.note_citations_from(docname, doctree)
         self.build_toc_from(docname, doctree)
-        for domain in self.domains.itervalues():
+        for domain in itervalues(self.domains):
             domain.process_doc(self, docname, doctree)
 
         # allow extension-specific post-processing
@@ -816,7 +811,7 @@
                                 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:
@@ -825,7 +820,7 @@
                 candidates['*'] = rel_imgpath
             # map image paths to unique image names (so that they can be put
             # into a single directory)
-            for imgpath in candidates.itervalues():
+            for imgpath in itervalues(candidates):
                 self.dependencies.setdefault(docname, set()).add(imgpath)
                 if not os.access(path.join(self.srcdir, imgpath), os.R_OK):
                     self.warn_node('image file not readable: %s' % imgpath,
@@ -856,6 +851,14 @@
             else:
                 name, body = node
                 md[name.astext()] = body.astext()
+        for name, value in md.items():
+            if name in ('tocdepth',):
+                try:
+                    value = int(value)
+                except ValueError:
+                    value = 0
+                md[name] = value
+
         del doctree[0]
 
     def process_refonly_bullet_lists(self, docname, doctree):
@@ -927,7 +930,7 @@
         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
@@ -975,11 +978,6 @@
         """Build a TOC from the doctree and store it in the inventory."""
         numentries = [0] # nonlocal again...
 
-        try:
-            maxdepth = int(self.metadata[docname].get('tocdepth', 0))
-        except ValueError:
-            maxdepth = 0
-
         def traverse_in_section(node, cls):
             """Like traverse(), but stay within the same section."""
             result = []
@@ -1003,6 +1001,7 @@
                     if blist:
                         onlynode += blist.children
                         entries.append(onlynode)
+                    continue
                 if not isinstance(sectionnode, nodes.section):
                     for toctreenode in traverse_in_section(sectionnode,
                                                            addnodes.toctree):
@@ -1032,8 +1031,7 @@
                 para = addnodes.compact_paragraph('', '', reference)
                 item = nodes.list_item('', para)
                 sub_item = build_toc(sectionnode, depth + 1)
-                if maxdepth == 0 or depth < maxdepth:
-                    item += sub_item
+                item += sub_item
                 entries.append(item)
             if entries:
                 return nodes.bullet_list('', *entries)
@@ -1221,6 +1219,8 @@
                 try:
                     refdoc = None
                     if url_re.match(ref):
+                        if title is None:
+                            title = ref
                         reference = nodes.reference('', '', internal=False,
                                                     refuri=ref, anchorname='',
                                                     *[nodes.Text(title)])
@@ -1249,6 +1249,8 @@
                             continue
                         refdoc = ref
                         toc = self.tocs[ref].deepcopy()
+                        maxdepth = self.metadata[ref].get('tocdepth', 0)
+                        _toctree_prune(toc, 2, maxdepth)
                         self.process_only_nodes(toc, builder, ref)
                         if title and toc.children and len(toc.children) == 1:
                             child = toc.children[0]
@@ -1431,7 +1433,7 @@
         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())
@@ -1446,6 +1448,7 @@
         # a list of all docnames whose section numbers changed
         rewrite_needed = []
 
+        assigned = set()
         old_secnumbers = self.toc_secnumbers
         self.toc_secnumbers = {}
 
@@ -1485,17 +1488,19 @@
             if depth == 0:
                 return
             for (title, ref) in toctreenode['entries']:
-                if url_re.match(ref) or ref == 'self':
+                if url_re.match(ref) or ref == 'self' or ref in assigned:
                     # don't mess with those
                     continue
                 if ref in self.tocs:
                     secnums = self.toc_secnumbers[ref] = {}
+                    assigned.add(ref)
                     _walk_toc(self.tocs[ref], secnums, depth,
                               self.titles.get(ref))
                     if secnums != old_secnumbers.get(ref):
                         rewrite_needed.append(ref)
 
         for docname in self.numbered_toctrees:
+            assigned.add(docname)
             doctree = self.get_doctree(docname)
             for toctreenode in doctree.traverse(addnodes.toctree):
                 depth = toctreenode.get('numbered', 0)
@@ -1515,7 +1520,7 @@
             # Force the word to be unicode if it's a ASCII bytestring.
             # This will solve problems with unicode normalization later.
             # For instance the RFC role will add bytestrings at the moment
-            word = unicode(word)
+            word = text_type(word)
             entry = dic.get(word)
             if not entry:
                 dic[word] = entry = [[], {}]
@@ -1529,7 +1534,7 @@
                 else:
                     entry[0].append((main, uri))
 
-        for fn, entries in self.indexentries.iteritems():
+        for fn, entries in iteritems(self.indexentries):
             # new entry types must be listed in directives/other.py!
             for type, value, tid, main in entries:
                 try:
@@ -1557,7 +1562,7 @@
                         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
@@ -1567,8 +1572,7 @@
             if lckey[0:1] in lcletters:
                 return chr(127) + lckey
             return lckey
-        newlist = new.items()
-        newlist.sort(key=keyfunc)
+        newlist = sorted(new.items(), key=keyfunc)
 
         if group_entries:
             # fixup entries: transform
@@ -1604,7 +1608,7 @@
         def keyfunc2(item, letters=string.ascii_uppercase + '_'):
             # hack: mutating the subitems dicts to a list in the keyfunc
             k, v = item
-            v[1] = sorted((si, se) for (si, (se, void)) in v[1].iteritems())
+            v[1] = sorted((si, se) for (si, (se, void)) in iteritems(v[1]))
             # now calculate the key
             letter = unicodedata.normalize('NFD', k[0])[0].upper()
             if letter in letters:
@@ -1656,7 +1660,7 @@
                 # else it will stay None
             # same for children
             if includes:
-                for subindex, args in enumerate(izip(includes,
+                for subindex, args in enumerate(zip(includes,
                                                      [None] + includes,
                                                      includes[1:] + [None])):
                     collect([(docname, subindex)] + parents,
diff --git a/sphinx/ext/autodoc.py b/sphinx/ext/autodoc.py
index 423f921..5b014d0 100644
--- a/sphinx/ext/autodoc.py
+++ b/sphinx/ext/autodoc.py
@@ -17,10 +17,12 @@
 import traceback
 from types import FunctionType, BuiltinFunctionType, MethodType
 
+from six import iteritems, itervalues, text_type, class_types
 from docutils import nodes
 from docutils.utils import assemble_option_dict
 from docutils.statemachine import ViewList
 
+import sphinx
 from sphinx.util import rpartition, force_decode
 from sphinx.locale import _
 from sphinx.pycode import ModuleAnalyzer, PycodeError
@@ -29,7 +31,6 @@
 from sphinx.util.compat import Directive
 from sphinx.util.inspect import getargspec, isdescriptor, safe_getmembers, \
      safe_getattr, safe_repr, is_builtin_class_method
-from sphinx.util.pycompat import base_exception, class_types
 from sphinx.util.docstrings import prepare_docstring
 
 
@@ -54,9 +55,10 @@
             return dict.__getitem__(self, key)
         except KeyError:
             return self.default
-    def __nonzero__(self):
+    def __bool__(self):
         # docutils check "if option_spec"
         return True
+    __nonzero__ = __bool__  # for python2 compatibility
 
 identity = lambda x: x
 
@@ -70,6 +72,35 @@
             return None
 
 
+class _MockModule(object):
+    """Used by autodoc_mock_imports."""
+    def __init__(self, *args, **kwargs):
+        pass
+
+    def __call__(self, *args, **kwargs):
+        return _MockModule()
+
+    @classmethod
+    def __getattr__(cls, name):
+        if name in ('__file__', '__path__'):
+            return '/dev/null'
+        elif name[0] == name[0].upper():
+            # Not very good, we assume Uppercase names are classes...
+            mocktype = type(name, (), {})
+            mocktype.__module__ = __name__
+            return mocktype
+        else:
+            return _MockModule()
+
+def mock_import(modname):
+    if '.' in modname:
+        pkg, _n, mods = modname.rpartition('.')
+        mock_import(pkg)
+    mod = _MockModule()
+    sys.modules[modname] = mod
+    return mod
+
+
 ALL = object()
 INSTANCEATTR = object()
 
@@ -235,7 +266,7 @@
     @staticmethod
     def get_attr(obj, name, *defargs):
         """getattr() override for types such as Zope interfaces."""
-        for typ, func in AutoDirective._special_attrgetters.iteritems():
+        for typ, func in iteritems(AutoDirective._special_attrgetters):
             if isinstance(obj, typ):
                 return func(obj, name, *defargs)
         return safe_getattr(obj, name, *defargs)
@@ -332,6 +363,9 @@
                 self.modname, '.'.join(self.objpath))
         try:
             dbg('[autodoc] import %s', self.modname)
+            for modname in self.env.config.autodoc_mock_imports:
+                dbg('[autodoc] adding a mock module %s!', self.modname)
+                mock_import(modname)
             __import__(self.modname)
             parent = None
             obj = self.module = sys.modules[self.modname]
@@ -415,7 +449,7 @@
             # 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
@@ -452,7 +486,7 @@
         docstring = self.get_attr(self.object, '__doc__', None)
         # make sure we have Unicode docstrings, then sanitize and split
         # into lines
-        if isinstance(docstring, unicode):
+        if isinstance(docstring, text_type):
             return [prepare_docstring(docstring, ignore)]
         elif isinstance(docstring, str):  # this will not trigger on Py3
             return [prepare_docstring(force_decode(docstring, encoding),
@@ -476,9 +510,9 @@
         # set sourcename and add content from attribute documentation
         if self.analyzer:
             # prevent encoding errors when the file name is non-ASCII
-            if not isinstance(self.analyzer.srcname, unicode):
-                filename = unicode(self.analyzer.srcname,
-                                   sys.getfilesystemencoding(), 'replace')
+            if not isinstance(self.analyzer.srcname, text_type):
+                filename = text_type(self.analyzer.srcname,
+                                     sys.getfilesystemencoding(), 'replace')
             else:
                 filename = self.analyzer.srcname
             sourcename = u'%s:docstring of %s' % (filename, self.fullname)
@@ -522,7 +556,7 @@
         if self.analyzer:
             attr_docs = self.analyzer.find_attr_docs()
             namespace = '.'.join(self.objpath)
-            for item in attr_docs.iteritems():
+            for item in iteritems(attr_docs):
                 if item[0][0] == namespace:
                     analyzed_member_names.add(item[0][1])
         if not want_all:
@@ -663,7 +697,7 @@
         # document non-skipped members
         memberdocumenters = []
         for (mname, member, isattr) in self.filter_members(members, want_all):
-            classes = [cls for cls in AutoDirective._registry.itervalues()
+            classes = [cls for cls in itervalues(AutoDirective._registry)
                        if cls.can_document_member(member, mname, isattr, self)]
             if not classes:
                 # don't know how to document this member
@@ -735,7 +769,7 @@
             # 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
@@ -942,6 +976,23 @@
                 self.args, self.retann = result
         return Documenter.format_signature(self)
 
+class DocstringStripSignatureMixin(DocstringSignatureMixin):
+    """
+    Mixin for AttributeDocumenter to provide the
+    feature of stripping any function signature from the docstring.
+    """
+    def format_signature(self):
+        if self.args is None and self.env.config.autodoc_docstring_signature:
+            # only act if a signature is not explicitly given already, and if
+            # the feature is enabled
+            result = self._find_signature()
+            if result is not None:
+                # Discarding _args is a only difference with
+                # DocstringSignatureMixin.format_signature.
+                # Documenter.format_signature use self.args value to format.
+                _args, self.retann = result
+        return Documenter.format_signature(self)
+
 
 class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter):
     """
@@ -1100,7 +1151,7 @@
                     docstrings.append(initdocstring)
         doc = []
         for docstring in docstrings:
-            if not isinstance(docstring, unicode):
+            if not isinstance(docstring, text_type):
                 docstring = force_decode(docstring, encoding)
             doc.append(prepare_docstring(docstring))
         return doc
@@ -1135,7 +1186,7 @@
     @classmethod
     def can_document_member(cls, member, membername, isattr, parent):
         return isinstance(member, class_types) and \
-               issubclass(member, base_exception)
+               issubclass(member, BaseException)
 
 
 class DataDocumenter(ModuleLevelDocumenter):
@@ -1184,42 +1235,25 @@
         return inspect.isroutine(member) and \
                not isinstance(parent, ModuleDocumenter)
 
-    if sys.version_info >= (3, 0):
-        def import_object(self):
-            ret = ClassLevelDocumenter.import_object(self)
-            if not ret:
-                return ret
-            obj_from_parent = self.parent.__dict__.get(self.object_name)
-            if isinstance(obj_from_parent, classmethod):
-                self.directivetype = 'classmethod'
-                self.member_order = self.member_order - 1
-            elif isinstance(obj_from_parent, staticmethod):
-                self.directivetype = 'staticmethod'
-                self.member_order = self.member_order - 1
-            else:
-                self.directivetype = 'method'
+    def import_object(self):
+        ret = ClassLevelDocumenter.import_object(self)
+        if not ret:
             return ret
-    else:
-        def import_object(self):
-            ret = ClassLevelDocumenter.import_object(self)
-            if not ret:
-                return ret
-            if isinstance(self.object, classmethod) or \
-                   (isinstance(self.object, MethodType) and
-                    self.object.im_self is not None):
-                self.directivetype = 'classmethod'
-                # document class and static members before ordinary ones
-                self.member_order = self.member_order - 1
-            elif isinstance(self.object, FunctionType) or \
-                 (isinstance(self.object, BuiltinFunctionType) and
-                  hasattr(self.object, '__self__') and
-                  self.object.__self__ is not None):
-                self.directivetype = 'staticmethod'
-                # document class and static members before ordinary ones
-                self.member_order = self.member_order - 1
-            else:
-                self.directivetype = 'method'
-            return ret
+
+        # to distinguish classmethod/staticmethod
+        obj = self.parent.__dict__.get(self.object_name)
+
+        if isinstance(obj, classmethod):
+            self.directivetype = 'classmethod'
+            # document class and static members before ordinary ones
+            self.member_order = self.member_order - 1
+        elif isinstance(obj, staticmethod):
+            self.directivetype = 'staticmethod'
+            # document class and static members before ordinary ones
+            self.member_order = self.member_order - 1
+        else:
+            self.directivetype = 'method'
+        return ret
 
     def format_args(self):
         if inspect.isbuiltin(self.object) or \
@@ -1238,7 +1272,7 @@
         pass
 
 
-class AttributeDocumenter(ClassLevelDocumenter):
+class AttributeDocumenter(DocstringStripSignatureMixin,ClassLevelDocumenter):
     """
     Specialized Documenter subclass for attributes.
     """
@@ -1401,7 +1435,7 @@
         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),
@@ -1465,10 +1499,13 @@
     app.add_config_value('autodoc_member_order', 'alphabetic', True)
     app.add_config_value('autodoc_default_flags', [], True)
     app.add_config_value('autodoc_docstring_signature', True, True)
+    app.add_config_value('autodoc_mock_imports', [], True)
     app.add_event('autodoc-process-docstring')
     app.add_event('autodoc-process-signature')
     app.add_event('autodoc-skip-member')
 
+    return sphinx.__version__
+
 
 class testcls:
     """test doc string"""
diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py
index c5c8f15..31bbfb8 100644
--- a/sphinx/ext/autosummary/__init__.py
+++ b/sphinx/ext/autosummary/__init__.py
@@ -59,10 +59,12 @@
 import inspect
 import posixpath
 
+from six import text_type
 from docutils.parsers.rst import directives
 from docutils.statemachine import ViewList
 from docutils import nodes
 
+import sphinx
 from sphinx import addnodes
 from sphinx.util.compat import Directive
 from sphinx.pycode import ModuleAnalyzer, PycodeError
@@ -117,7 +119,7 @@
             par = col1_entry[0]
             for j, subnode in enumerate(list(par)):
                 if isinstance(subnode, nodes.Text):
-                    new_text = unicode(subnode.astext())
+                    new_text = text_type(subnode.astext())
                     new_text = new_text.replace(u" ", u"\u00a0")
                     par[j] = nodes.Text(new_text)
     except IndexError:
@@ -270,11 +272,11 @@
             # try to also get a source code analyzer for attribute docs
             try:
                 documenter.analyzer = ModuleAnalyzer.for_module(
-                    documenter.get_real_modname())
+                                            documenter.get_real_modname())
                 # parse right now, to get PycodeErrors on parsing (results will
                 # be cached anyway)
                 documenter.analyzer.find_attr_docs()
-            except PycodeError, err:
+            except PycodeError as err:
                 documenter.env.app.debug(
                     '[autodoc] module analyzer failed: %s', err)
                 # no source file -- e.g. for builtin and C modules
@@ -497,7 +499,7 @@
             return obj, parent, modname
         else:
             return sys.modules[modname], None, modname
-    except (ValueError, ImportError, AttributeError, KeyError), e:
+    except (ValueError, ImportError, AttributeError, KeyError) as e:
         raise ImportError(*e.args)
 
 
@@ -568,3 +570,4 @@
     app.connect('doctree-read', process_autosummary_toc)
     app.connect('builder-inited', process_generate_options)
     app.add_config_value('autosummary_generate', [], True)
+    return sphinx.__version__
diff --git a/sphinx/ext/autosummary/generate.py b/sphinx/ext/autosummary/generate.py
index 47ef986..11b1dfe 100644
--- a/sphinx/ext/autosummary/generate.py
+++ b/sphinx/ext/autosummary/generate.py
@@ -17,6 +17,7 @@
     :copyright: Copyright 2007-2014 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 @@
                               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 ---------------------------------------------------------
 
@@ -109,14 +110,11 @@
     # read
     items = find_autosummary_in_files(sources)
 
-    # remove possible duplicates
-    items = dict([(item, True) for item in items]).keys()
-
     # keep track of new files
     new_files = []
 
     # write
-    for name, path, template_name in sorted(items, key=str):
+    for name, path, template_name in sorted(set(items), key=str):
         if path is None:
             # The corresponding autosummary:: directive did not have
             # a :toctree: option
@@ -127,7 +125,7 @@
 
         try:
             name, obj, parent, mod_name = import_by_name(name)
-        except ImportError, e:
+        except ImportError as e:
             warn('[autosummary] failed to import %r: %s' % (name, e))
             continue
 
@@ -240,9 +238,9 @@
         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 SystemExit, e:
+    except ImportError as e:
+        print("Failed to import '%s': %s" % (name, e))
+    except SystemExit as e:
         print("Failed to import '%s'; the module executes module level "
               "statement and it might call sys.exit()." % name)
     return []
diff --git a/sphinx/ext/coverage.py b/sphinx/ext/coverage.py
index 52be1bd..49dc02f 100644
--- a/sphinx/ext/coverage.py
+++ b/sphinx/ext/coverage.py
@@ -13,9 +13,12 @@
 import re
 import glob
 import inspect
-import cPickle as pickle
 from os import path
 
+from six import iteritems
+from six.moves import cPickle as pickle
+
+import sphinx
 from sphinx.builders import Builder
 
 
@@ -52,7 +55,7 @@
                 self.warn('invalid regex %r in coverage_c_regexes' % exp)
 
         self.c_ignorexps = {}
-        for (name, exps) in self.config.coverage_ignore_c_items.iteritems():
+        for (name, exps) in iteritems(self.config.coverage_ignore_c_items):
             self.c_ignorexps[name] = compile_regex_list(
                 'coverage_ignore_c_items', exps, self.warn)
         self.mod_ignorexps = compile_regex_list(
@@ -109,7 +112,7 @@
                 write_header(op, 'Undocumented C API elements', '=')
             op.write('\n')
 
-            for filename, undoc in self.c_undoc.iteritems():
+            for filename, undoc in iteritems(self.c_undoc):
                 write_header(op, filename)
                 for typ, name in undoc:
                     op.write(' * %-50s [%9s]\n' % (name, typ))
@@ -134,7 +137,7 @@
 
             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}
@@ -211,8 +214,7 @@
         try:
             if self.config.coverage_write_headline:
                 write_header(op, 'Undocumented Python objects', '=')
-            keys = self.py_undoc.keys()
-            keys.sort()
+            keys = sorted(self.py_undoc.keys())
             for name in keys:
                 undoc = self.py_undoc[name]
                 if 'error' in undoc:
@@ -229,7 +231,7 @@
                     if undoc['classes']:
                         op.write('Classes:\n')
                         for name, methods in sorted(
-                                                 undoc['classes'].iteritems()):
+                                                 iteritems(undoc['classes'])):
                             if not methods:
                                 op.write(' * %s\n' % name)
                             else:
@@ -263,3 +265,4 @@
     app.add_config_value('coverage_ignore_c_items', {}, False)
     app.add_config_value('coverage_write_headline', True, False)
     app.add_config_value('coverage_skip_undoc_in_source', False, False)
+    return sphinx.__version__
diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py
index 70beb9b..20b8692 100644
--- a/sphinx/ext/doctest.py
+++ b/sphinx/ext/doctest.py
@@ -14,20 +14,20 @@
 import sys
 import time
 import codecs
-import StringIO
 from os import path
 # circumvent relative import
 doctest = __import__('doctest')
 
+from six import itervalues, StringIO, binary_type
 from docutils import nodes
 from docutils.parsers.rst import directives
 
+import sphinx
 from sphinx.builders import Builder
 from sphinx.util import force_decode
 from sphinx.util.nodes import set_source_info
 from sphinx.util.compat import Directive
 from sphinx.util.console import bold
-from sphinx.util.pycompat import bytes
 
 blankline_re = re.compile(r'^\s*<BLANKLINE>', re.MULTILINE)
 doctestopt_re = re.compile(r'#\s*doctest:.+$', re.MULTILINE)
@@ -158,7 +158,7 @@
 
 class SphinxDocTestRunner(doctest.DocTestRunner):
     def summarize(self, out, verbose=None):
-        string_io = StringIO.StringIO()
+        string_io = StringIO()
         old_stdout = sys.stdout
         sys.stdout = string_io
         try:
@@ -233,7 +233,7 @@
         self.info(text, nonl=True)
         if self.app.quiet:
             self.warn(text)
-        if isinstance(text, bytes):
+        if isinstance(text, binary_type):
             text = force_decode(text, None)
         self.outfile.write(text)
 
@@ -289,14 +289,14 @@
         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'),
@@ -312,24 +312,24 @@
                     groups[groupname] = TestGroup(groupname)
                 groups[groupname].add_code(code)
         for code in add_to_all_groups:
-            for group in groups.itervalues():
+            for group in itervalues(groups):
                 group.add_code(code)
         if self.config.doctest_global_setup:
             code = TestCode(self.config.doctest_global_setup,
                             'testsetup', lineno=0)
-            for group in groups.itervalues():
+            for group in itervalues(groups):
                 group.add_code(code, prepend=True)
         if self.config.doctest_global_cleanup:
             code = TestCode(self.config.doctest_global_cleanup,
                             'testcleanup', lineno=0)
-            for group in groups.itervalues():
+            for group in itervalues(groups):
                 group.add_code(code)
         if not groups:
             return
 
         self._out('\nDocument: %s\n----------%s\n' %
                   (docname, '-'*len(docname)))
-        for group in groups.itervalues():
+        for group in itervalues(groups):
             self.test_group(group, self.env.doc2path(docname, base=None))
         # Separately count results from setup code
         res_f, res_t = self.setup_runner.summarize(self._out, verbose=False)
@@ -435,3 +435,4 @@
     app.add_config_value('doctest_test_doctest_blocks', 'default', False)
     app.add_config_value('doctest_global_setup', '', False)
     app.add_config_value('doctest_global_cleanup', '', False)
+    return sphinx.__version__
diff --git a/sphinx/ext/extlinks.py b/sphinx/ext/extlinks.py
index 18da573..c0cfbcd 100644
--- a/sphinx/ext/extlinks.py
+++ b/sphinx/ext/extlinks.py
@@ -24,8 +24,10 @@
     :license: BSD, see LICENSE for details.
 """
 
+from six import iteritems
 from docutils import nodes, utils
 
+import sphinx
 from sphinx.util.nodes import split_explicit_title
 
 
@@ -51,9 +53,10 @@
     return role
 
 def setup_link_roles(app):
-    for name, (base_url, prefix) in app.config.extlinks.iteritems():
+    for name, (base_url, prefix) in iteritems(app.config.extlinks):
         app.add_role(name, make_link_role(base_url, prefix))
 
 def setup(app):
     app.add_config_value('extlinks', {}, 'env')
     app.connect('builder-inited', setup_link_roles)
+    return sphinx.__version__
diff --git a/sphinx/ext/graphviz.py b/sphinx/ext/graphviz.py
index 028560b..b4b8bc2 100644
--- a/sphinx/ext/graphviz.py
+++ b/sphinx/ext/graphviz.py
@@ -15,14 +15,14 @@
 import posixpath
 from os import path
 from subprocess import Popen, PIPE
-try:
-    from hashlib import sha1 as sha
-except ImportError:
-    from sha import sha
+from hashlib import sha1
 
+from six import text_type
 from docutils import nodes
 from docutils.parsers.rst import directives
+from docutils.statemachine import ViewList
 
+import sphinx
 from sphinx.errors import SphinxError
 from sphinx.locale import _
 from sphinx.util.osutil import ensuredir, ENOENT, EPIPE, EINVAL
@@ -40,6 +40,20 @@
     pass
 
 
+def figure_wrapper(directive, node, caption):
+    figure_node = nodes.figure('', node)
+
+    parsed = nodes.Element()
+    directive.state.nested_parse(ViewList([caption], source=''),
+                                 directive.content_offset, parsed)
+    caption_node = nodes.caption(parsed[0].rawsource, '',
+                                 *parsed[0].children)
+    caption_node.source = parsed[0].source
+    caption_node.line = parsed[0].line
+    figure_node += caption_node
+    return figure_node
+
+
 class Graphviz(Directive):
     """
     Directive to insert arbitrary dot markup.
@@ -85,9 +99,12 @@
         node['options'] = []
         if 'alt' in self.options:
             node['alt'] = self.options['alt']
-        if 'caption' in self.options:
-            node['caption'] = self.options['caption']
         node['inline'] = 'inline' in self.options
+
+        caption = self.options.get('caption')
+        if caption and not node['inline']:
+            node = figure_wrapper(self, node, caption)
+
         return [node]
 
 
@@ -112,9 +129,12 @@
         node['options'] = []
         if 'alt' in self.options:
             node['alt'] = self.options['alt']
-        if 'caption' in self.options:
-            node['caption'] = self.options['caption']
         node['inline'] = 'inline' in self.options
+
+        caption = self.options.get('caption')
+        if caption and not node['inline']:
+            node = figure_wrapper(self, node, caption)
+
         return [node]
 
 
@@ -125,7 +145,7 @@
               str(self.builder.config.graphviz_dot_args)
               ).encode('utf-8')
 
-    fname = '%s-%s.%s' % (prefix, sha(hashkey).hexdigest(), format)
+    fname = '%s-%s.%s' % (prefix, sha1(hashkey).hexdigest(), format)
     if hasattr(self.builder, 'imgpath'):
         # HTML
         relfn = posixpath.join(self.builder.imgpath, fname)
@@ -145,7 +165,7 @@
     ensuredir(path.dirname(outfn))
 
     # graphviz expects UTF-8 by default
-    if isinstance(code, unicode):
+    if isinstance(code, text_type):
         code = code.encode('utf-8')
 
     dot_args = [self.builder.config.graphviz_dot]
@@ -156,7 +176,7 @@
         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 +188,7 @@
         # 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 +212,7 @@
             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
 
@@ -228,9 +248,6 @@
                 self.body.append('<img src="%s" alt="%s" usemap="#%s" %s/>\n' %
                                  (fname, alt, mapname, imgcss))
                 self.body.extend([item.decode('utf-8') for item in imgmap])
-        if node.get('caption') and not inline:
-            self.body.append('</p>\n<p class="caption">')
-            self.body.append(self.encode(node['caption']))
 
     self.body.append('</%s>\n' % wrapper)
     raise nodes.SkipNode
@@ -243,7 +260,7 @@
 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
 
@@ -254,18 +271,8 @@
         para_separator = '\n'
 
     if fname is not None:
-        caption = node.get('caption')
-        # XXX add ids from previous target node
-        if caption and not inline:
-            self.body.append('\n\\begin{figure}[h!]')
-            self.body.append('\n\\begin{center}')
-            self.body.append('\n\\caption{%s}' % self.encode(caption))
-            self.body.append('\n\\includegraphics{%s}' % fname)
-            self.body.append('\n\\end{center}')
-            self.body.append('\n\\end{figure}\n')
-        else:
-            self.body.append('%s\\includegraphics{%s}%s' %
-                             (para_separator, fname, para_separator))
+        self.body.append('%s\\includegraphics{%s}%s' %
+                         (para_separator, fname, para_separator))
     raise nodes.SkipNode
 
 
@@ -276,16 +283,11 @@
 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:
-        self.body.append('\n\n@float\n')
-        caption = node.get('caption')
-        if caption:
-            self.body.append('@caption{%s}\n' % self.escape_arg(caption))
-        self.body.append('@image{%s,,,[graphviz],png}\n'
-                         '@end float\n\n' % fname[:-4])
+        self.body.append('@image{%s,,,[graphviz],png}\n' % fname[:-4])
     raise nodes.SkipNode
 
 def texinfo_visit_graphviz(self, node):
@@ -321,3 +323,4 @@
     app.add_config_value('graphviz_dot', 'dot', 'html')
     app.add_config_value('graphviz_dot_args', [], 'html')
     app.add_config_value('graphviz_output_format', 'png', 'html')
+    return sphinx.__version__
diff --git a/sphinx/ext/ifconfig.py b/sphinx/ext/ifconfig.py
index 3362e56..ab15e1e 100644
--- a/sphinx/ext/ifconfig.py
+++ b/sphinx/ext/ifconfig.py
@@ -22,6 +22,7 @@
 
 from docutils import nodes
 
+import sphinx
 from sphinx.util.nodes import set_source_info
 from sphinx.util.compat import Directive
 
@@ -53,7 +54,7 @@
     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))
@@ -72,3 +73,4 @@
     app.add_node(ifconfig)
     app.add_directive('ifconfig', IfConfig)
     app.connect('doctree-resolved', process_ifconfig_nodes)
+    return sphinx.__version__
diff --git a/sphinx/ext/inheritance_diagram.py b/sphinx/ext/inheritance_diagram.py
index 5b8eab3..bbae5c1 100644
--- a/sphinx/ext/inheritance_diagram.py
+++ b/sphinx/ext/inheritance_diagram.py
@@ -45,9 +45,11 @@
 except ImportError:
     from md5 import md5
 
+from six import text_type
 from docutils import nodes
 from docutils.parsers.rst import directives
 
+import sphinx
 from sphinx.ext.graphviz import render_dot_html, render_dot_latex, \
     render_dot_texinfo
 from sphinx.pycode import ModuleAnalyzer
@@ -162,7 +164,7 @@
                 if cls.__doc__:
                     enc = ModuleAnalyzer.for_module(cls.__module__).encoding
                     doc = cls.__doc__.strip().split("\n")[0]
-                    if not isinstance(doc, unicode):
+                    if not isinstance(doc, text_type):
                         doc = force_decode(doc, enc)
                     if doc:
                         tooltip = '"%s"' % doc.replace('"', '\\"')
@@ -311,7 +313,7 @@
                 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)]
 
@@ -405,3 +407,4 @@
     app.add_config_value('inheritance_graph_attrs', {}, False),
     app.add_config_value('inheritance_node_attrs', {}, False),
     app.add_config_value('inheritance_edge_attrs', {}, False),
+    return sphinx.__version__
diff --git a/sphinx/ext/intersphinx.py b/sphinx/ext/intersphinx.py
index c3adf56..43507a3 100644
--- a/sphinx/ext/intersphinx.py
+++ b/sphinx/ext/intersphinx.py
@@ -27,27 +27,28 @@
 import time
 import zlib
 import codecs
-import urllib2
 import posixpath
 from os import path
 import re
 
+from six import iteritems
+from six.moves.urllib import request
 from docutils import nodes
 from docutils.utils import relative_path
 
+import sphinx
 from sphinx.locale import _
 from sphinx.builders.html import INVENTORY_FILENAME
-from sphinx.util.pycompat import b
 
 
-handlers = [urllib2.ProxyHandler(), urllib2.HTTPRedirectHandler(),
-            urllib2.HTTPHandler()]
+handlers = [request.ProxyHandler(), request.HTTPRedirectHandler(),
+            request.HTTPHandler()]
 try:
-    handlers.append(urllib2.HTTPSHandler)
+    handlers.append(request.HTTPSHandler)
 except AttributeError:
     pass
 
-urllib2.install_opener(urllib2.build_opener(*handlers))
+request.install_opener(request.build_opener(*handlers))
 
 UTF8StreamReader = codecs.lookup('utf-8')[2]
 
@@ -55,9 +56,9 @@
 def read_inventory_v1(f, uri, join):
     f = UTF8StreamReader(f)
     invdata = {}
-    line = f.next()
+    line = next(f)
     projname = line.rstrip()[11:]
-    line = f.next()
+    line = next(f)
     version = line.rstrip()[11:]
     for line in f:
         name, type, location = line.rstrip().split(None, 2)
@@ -85,19 +86,19 @@
 
     def read_chunks():
         decompressor = zlib.decompressobj()
-        for chunk in iter(lambda: f.read(bufsize), b('')):
+        for chunk in iter(lambda: f.read(bufsize), b''):
             yield decompressor.decompress(chunk)
         yield decompressor.flush()
 
     def split_lines(iter):
-        buf = b('')
+        buf = b''
         for chunk in iter:
             buf += chunk
-            lineend = buf.find(b('\n'))
+            lineend = buf.find(b'\n')
             while lineend != -1:
                 yield buf[:lineend].decode('utf-8')
                 buf = buf[lineend+1:]
-                lineend = buf.find(b('\n'))
+                lineend = buf.find(b'\n')
         assert not buf
 
     for line in split_lines(read_chunks()):
@@ -129,10 +130,10 @@
     join = localuri and path.join or posixpath.join
     try:
         if inv.find('://') != -1:
-            f = urllib2.urlopen(inv)
+            f = request.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 +150,7 @@
         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:
@@ -167,7 +168,7 @@
         env.intersphinx_named_inventory = {}
     cache = env.intersphinx_cache
     update = False
-    for key, value in app.config.intersphinx_mapping.iteritems():
+    for key, value in iteritems(app.config.intersphinx_mapping):
         if isinstance(value, tuple):
             # new format
             name, (uri, inv) = key, value
@@ -179,19 +180,25 @@
         # we can safely assume that the uri<->inv mapping is not changed
         # during partial rebuilds since a changed intersphinx_mapping
         # setting will cause a full environment reread
-        if not inv:
-            inv = posixpath.join(uri, INVENTORY_FILENAME)
-        # decide whether the inventory must be read: always read local
-        # files; remote ones only if the cache time is expired
-        if '://' not in inv or uri not in cache \
-               or cache[uri][1] < cache_time:
-            app.info('loading intersphinx inventory from %s...' % inv)
-            invdata = fetch_inventory(app, uri, inv)
-            if invdata:
-                cache[uri] = (name, now, invdata)
-            else:
-                cache.pop(uri, None)
-            update = True
+        if not isinstance(inv, tuple):
+            invs = (inv, )
+        else:
+            invs = inv
+
+        for inv in invs:
+            if not inv:
+                inv = posixpath.join(uri, INVENTORY_FILENAME)
+            # decide whether the inventory must be read: always read local
+            # files; remote ones only if the cache time is expired
+            if '://' not in inv or uri not in cache \
+                    or cache[uri][1] < cache_time:
+                app.info('loading intersphinx inventory from %s...' % inv)
+                invdata = fetch_inventory(app, uri, inv)
+                if invdata:
+                    cache[uri] = (name, now, invdata)
+                    update = True
+                    break
+
     if update:
         env.intersphinx_inventory = {}
         env.intersphinx_named_inventory = {}
@@ -202,13 +209,13 @@
         # add the unnamed inventories last.  This means that the
         # unnamed inventories will shadow the named ones but the named
         # ones can still be accessed when the name is specified.
-        cached_vals = list(cache.itervalues())
+        cached_vals = list(cache.values())
         named_vals = sorted(v for v in cached_vals if v[0])
         unnamed_vals = [v for v in cached_vals if not v[0]]
         for name, _, invdata in named_vals + unnamed_vals:
             if name:
                 env.intersphinx_named_inventory[name] = invdata
-            for type, objects in invdata.iteritems():
+            for type, objects in iteritems(invdata):
                 env.intersphinx_inventory.setdefault(
                     type, {}).update(objects)
 
@@ -269,3 +276,4 @@
     app.add_config_value('intersphinx_cache_limit', 5, False)
     app.connect('missing-reference', missing_reference)
     app.connect('builder-inited', load_mappings)
+    return sphinx.__version__
diff --git a/sphinx/ext/jsmath.py b/sphinx/ext/jsmath.py
index 8907576..897d87a 100644
--- a/sphinx/ext/jsmath.py
+++ b/sphinx/ext/jsmath.py
@@ -12,6 +12,7 @@
 
 from docutils import nodes
 
+import sphinx
 from sphinx.application import ExtensionError
 from sphinx.ext.mathbase import setup_math as mathbase_setup
 
@@ -56,3 +57,4 @@
     mathbase_setup(app, (html_visit_math, None), (html_visit_displaymath, None))
     app.add_config_value('jsmath_path', '', False)
     app.connect('builder-inited', builder_inited)
+    return sphinx.__version__
diff --git a/sphinx/ext/linkcode.py b/sphinx/ext/linkcode.py
index 77bd9f2..bbb0698 100644
--- a/sphinx/ext/linkcode.py
+++ b/sphinx/ext/linkcode.py
@@ -11,6 +11,7 @@
 
 from docutils import nodes
 
+import sphinx
 from sphinx import addnodes
 from sphinx.locale import _
 from sphinx.errors import SphinxError
@@ -70,3 +71,4 @@
 def setup(app):
     app.connect('doctree-read', doctree_read)
     app.add_config_value('linkcode_resolve', None, '')
+    return sphinx.__version__
diff --git a/sphinx/ext/mathjax.py b/sphinx/ext/mathjax.py
index ee27866..fd5c5f1 100644
--- a/sphinx/ext/mathjax.py
+++ b/sphinx/ext/mathjax.py
@@ -13,6 +13,7 @@
 
 from docutils import nodes
 
+import sphinx
 from sphinx.application import ExtensionError
 from sphinx.ext.mathbase import setup_math as mathbase_setup
 
@@ -60,9 +61,12 @@
 
 def setup(app):
     mathbase_setup(app, (html_visit_math, None), (html_visit_displaymath, None))
+    # more information for mathjax secure url is here:
+    # http://docs.mathjax.org/en/latest/start.html#secure-access-to-the-cdn
     app.add_config_value('mathjax_path',
-                         'http://cdn.mathjax.org/mathjax/latest/MathJax.js?'
+                         'https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?'
                          'config=TeX-AMS-MML_HTMLorMML', False)
     app.add_config_value('mathjax_inline', [r'\(', r'\)'], 'html')
     app.add_config_value('mathjax_display', [r'\[', r'\]'], 'html')
     app.connect('builder-inited', builder_inited)
+    return sphinx.__version__
diff --git a/sphinx/ext/napoleon/__init__.py b/sphinx/ext/napoleon/__init__.py
new file mode 100644
index 0000000..554162e
--- /dev/null
+++ b/sphinx/ext/napoleon/__init__.py
@@ -0,0 +1,391 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.ext.napoleon
+    ~~~~~~~~~~~~~~~~~~~
+
+    Support for NumPy and Google style docstrings.
+
+    :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import sys
+
+from six import PY2, iteritems
+
+import sphinx
+from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring
+
+
+class Config(object):
+    """Sphinx napoleon extension settings in `conf.py`.
+
+    Listed below are all the settings used by napoleon and their default
+    values. These settings can be changed in the Sphinx `conf.py` file. Make
+    sure that both "sphinx.ext.autodoc" and "sphinx.ext.napoleon" are
+    enabled in `conf.py`::
+
+        # conf.py
+
+        # Add any Sphinx extension module names here, as strings
+        extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']
+
+        # Napoleon settings
+        napoleon_google_docstring = True
+        napoleon_numpy_docstring = True
+        napoleon_include_private_with_doc = False
+        napoleon_include_special_with_doc = True
+        napoleon_use_admonition_for_examples = False
+        napoleon_use_admonition_for_notes = False
+        napoleon_use_admonition_for_references = False
+        napoleon_use_ivar = False
+        napoleon_use_param = True
+        napoleon_use_rtype = True
+
+    .. _Google style:
+       http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
+    .. _NumPy style:
+       https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
+
+    Attributes
+    ----------
+    napoleon_google_docstring : bool, defaults to True
+        True to parse `Google style`_ docstrings. False to disable support
+        for Google style docstrings.
+    napoleon_numpy_docstring : bool, defaults to True
+        True to parse `NumPy style`_ docstrings. False to disable support
+        for NumPy style docstrings.
+    napoleon_include_private_with_doc : bool, defaults to False
+        True to include private members (like ``_membername``) with docstrings
+        in the documentation. False to fall back to Sphinx's default behavior.
+
+        **If True**::
+
+            def _included(self):
+                \"\"\"
+                This will be included in the docs because it has a docstring
+                \"\"\"
+                pass
+
+            def _skipped(self):
+                # This will NOT be included in the docs
+                pass
+
+    napoleon_include_special_with_doc : bool, defaults to True
+        True to include special members (like ``__membername__``) with
+        docstrings in the documentation. False to fall back to Sphinx's
+        default behavior.
+
+        **If True**::
+
+            def __str__(self):
+                \"\"\"
+                This will be included in the docs because it has a docstring
+                \"\"\"
+                return unicode(self).encode('utf-8')
+
+            def __unicode__(self):
+                # This will NOT be included in the docs
+                return unicode(self.__class__.__name__)
+
+    napoleon_use_admonition_for_examples : bool, defaults to False
+        True to use the ``.. admonition::`` directive for the **Example** and
+        **Examples** sections. False to use the ``.. rubric::`` directive
+        instead. One may look better than the other depending on what HTML
+        theme is used.
+
+        This `NumPy style`_ snippet will be converted as follows::
+
+            Example
+            -------
+            This is just a quick example
+
+        **If True**::
+
+            .. admonition:: Example
+
+               This is just a quick example
+
+        **If False**::
+
+            .. rubric:: Example
+
+            This is just a quick example
+
+    napoleon_use_admonition_for_notes : bool, defaults to False
+        True to use the ``.. admonition::`` directive for **Notes** sections.
+        False to use the ``.. rubric::`` directive instead.
+
+        Note
+        ----
+        The singular **Note** section will always be converted to a
+        ``.. note::`` directive.
+
+        See Also
+        --------
+        :attr:`napoleon_use_admonition_for_examples`
+
+    napoleon_use_admonition_for_references : bool, defaults to False
+        True to use the ``.. admonition::`` directive for **References**
+        sections. False to use the ``.. rubric::`` directive instead.
+
+        See Also
+        --------
+        :attr:`napoleon_use_admonition_for_examples`
+
+    napoleon_use_ivar : bool, defaults to False
+        True to use the ``:ivar:`` role for instance variables. False to use
+        the ``.. attribute::`` directive instead.
+
+        This `NumPy style`_ snippet will be converted as follows::
+
+            Attributes
+            ----------
+            attr1 : int
+                Description of `attr1`
+
+        **If True**::
+
+            :ivar attr1: Description of `attr1`
+            :vartype attr1: int
+
+        **If False**::
+
+            .. attribute:: attr1
+
+               *int*
+
+               Description of `attr1`
+
+    napoleon_use_param : bool, defaults to True
+        True to use a ``:param:`` role for each function parameter. False to
+        use a single ``:parameters:`` role for all the parameters.
+
+        This `NumPy style`_ snippet will be converted as follows::
+
+            Parameters
+            ----------
+            arg1 : str
+                Description of `arg1`
+            arg2 : int, optional
+                Description of `arg2`, defaults to 0
+
+        **If True**::
+
+            :param arg1: Description of `arg1`
+            :type arg1: str
+            :param arg2: Description of `arg2`, defaults to 0
+            :type arg2: int, optional
+
+        **If False**::
+
+            :parameters: * **arg1** (*str*) --
+                           Description of `arg1`
+                         * **arg2** (*int, optional*) --
+                           Description of `arg2`, defaults to 0
+
+    napoleon_use_rtype : bool, defaults to True
+        True to use the ``:rtype:`` role for the return type. False to output
+        the return type inline with the description.
+
+        This `NumPy style`_ snippet will be converted as follows::
+
+            Returns
+            -------
+            bool
+                True if successful, False otherwise
+
+        **If True**::
+
+            :returns: True if successful, False otherwise
+            :rtype: bool
+
+        **If False**::
+
+            :returns: *bool* -- True if successful, False otherwise
+
+    """
+    _config_values = {
+        'napoleon_google_docstring': (True, 'env'),
+        'napoleon_numpy_docstring': (True, 'env'),
+        'napoleon_include_private_with_doc': (False, 'env'),
+        'napoleon_include_special_with_doc': (True, 'env'),
+        'napoleon_use_admonition_for_examples': (False, 'env'),
+        'napoleon_use_admonition_for_notes': (False, 'env'),
+        'napoleon_use_admonition_for_references': (False, 'env'),
+        'napoleon_use_ivar': (False, 'env'),
+        'napoleon_use_param': (True, 'env'),
+        'napoleon_use_rtype': (True, 'env'),
+    }
+
+    def __init__(self, **settings):
+        for name, (default, rebuild) in iteritems(self._config_values):
+            setattr(self, name, default)
+        for name, value in iteritems(settings):
+            setattr(self, name, value)
+
+
+def setup(app):
+    """Sphinx extension setup function.
+
+    When the extension is loaded, Sphinx imports this module and executes
+    the ``setup()`` function, which in turn notifies Sphinx of everything
+    the extension offers.
+
+    Parameters
+    ----------
+    app : sphinx.application.Sphinx
+        Application object representing the Sphinx process
+
+    See Also
+    --------
+    The Sphinx documentation on `Extensions`_, the `Extension Tutorial`_, and
+    the `Extension API`_.
+
+    .. _Extensions: http://sphinx-doc.org/extensions.html
+    .. _Extension Tutorial: http://sphinx-doc.org/ext/tutorial.html
+    .. _Extension API: http://sphinx-doc.org/ext/appapi.html
+
+    """
+    from sphinx.application import Sphinx
+    if not isinstance(app, Sphinx):
+        return  # probably called by tests
+
+    app.connect('autodoc-process-docstring', _process_docstring)
+    app.connect('autodoc-skip-member', _skip_member)
+
+    for name, (default, rebuild) in iteritems(Config._config_values):
+        app.add_config_value(name, default, rebuild)
+    return sphinx.__version__
+
+
+def _process_docstring(app, what, name, obj, options, lines):
+    """Process the docstring for a given python object.
+
+    Called when autodoc has read and processed a docstring. `lines` is a list
+    of docstring lines that `_process_docstring` modifies in place to change
+    what Sphinx outputs.
+
+    The following settings in conf.py control what styles of docstrings will
+    be parsed:
+
+    * ``napoleon_google_docstring`` -- parse Google style docstrings
+    * ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
+
+    Parameters
+    ----------
+    app : sphinx.application.Sphinx
+        Application object representing the Sphinx process.
+    what : str
+        A string specifying the type of the object to which the docstring
+        belongs. Valid values: "module", "class", "exception", "function",
+        "method", "attribute".
+    name : str
+        The fully qualified name of the object.
+    obj : module, class, exception, function, method, or attribute
+        The object to which the docstring belongs.
+    options : sphinx.ext.autodoc.Options
+        The options given to the directive: an object with attributes
+        inherited_members, undoc_members, show_inheritance and noindex that
+        are True if the flag option of same name was given to the auto
+        directive.
+    lines : list of str
+        The lines of the docstring, see above.
+
+        .. note:: `lines` is modified *in place*
+
+    """
+    result_lines = lines
+    if app.config.napoleon_numpy_docstring:
+        docstring = NumpyDocstring(result_lines, app.config, app, what, name,
+                                   obj, options)
+        result_lines = docstring.lines()
+    if app.config.napoleon_google_docstring:
+        docstring = GoogleDocstring(result_lines, app.config, app, what, name,
+                                    obj, options)
+        result_lines = docstring.lines()
+    lines[:] = result_lines[:]
+
+
+def _skip_member(app, what, name, obj, skip, options):
+    """Determine if private and special class members are included in docs.
+
+    The following settings in conf.py determine if private and special class
+    members are included in the generated documentation:
+
+    * ``napoleon_include_private_with_doc`` --
+      include private members if they have docstrings
+    * ``napoleon_include_special_with_doc`` --
+      include special members if they have docstrings
+
+    Parameters
+    ----------
+    app : sphinx.application.Sphinx
+        Application object representing the Sphinx process
+    what : str
+        A string specifying the type of the object to which the member
+        belongs. Valid values: "module", "class", "exception", "function",
+        "method", "attribute".
+    name : str
+        The name of the member.
+    obj : module, class, exception, function, method, or attribute.
+        For example, if the member is the __init__ method of class A, then
+        `obj` will be `A.__init__`.
+    skip : bool
+        A boolean indicating if autodoc will skip this member if `_skip_member`
+        does not override the decision
+    options : sphinx.ext.autodoc.Options
+        The options given to the directive: an object with attributes
+        inherited_members, undoc_members, show_inheritance and noindex that
+        are True if the flag option of same name was given to the auto
+        directive.
+
+    Returns
+    -------
+    bool
+        True if the member should be skipped during creation of the docs,
+        False if it should be included in the docs.
+
+    """
+    has_doc = getattr(obj, '__doc__', False)
+    is_member = (what == 'class' or what == 'exception' or what == 'module')
+    if name != '__weakref__' and name != '__init__' and has_doc and is_member:
+        cls_is_owner = False
+        if what == 'class' or what == 'exception':
+            if PY2:
+                cls = getattr(obj, 'im_class', getattr(obj, '__objclass__',
+                              None))
+                cls_is_owner = (cls and hasattr(cls, name) and
+                                name in cls.__dict__)
+            elif sys.version_info >= (3, 3):
+                qualname = getattr(obj, '__qualname__', '')
+                cls_path, _, _ = qualname.rpartition('.')
+                if cls_path:
+                    try:
+                        if '.' in cls_path:
+                            import importlib
+                            import functools
+
+                            mod = importlib.import_module(obj.__module__)
+                            mod_path = cls_path.split('.')
+                            cls = functools.reduce(getattr, mod_path, mod)
+                        else:
+                            cls = obj.__globals__[cls_path]
+                    except:
+                        cls_is_owner = False
+                    else:
+                        cls_is_owner = (cls and hasattr(cls, name) and
+                                        name in cls.__dict__)
+                else:
+                    cls_is_owner = False
+            else:
+                cls_is_owner = True
+
+        if what == 'module' or cls_is_owner:
+            is_special = name.startswith('__') and name.endswith('__')
+            is_private = not is_special and name.startswith('_')
+            inc_special = app.config.napoleon_include_special_with_doc
+            inc_private = app.config.napoleon_include_private_with_doc
+            if (is_special and inc_special) or (is_private and inc_private):
+                return False
+    return skip
diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py
new file mode 100644
index 0000000..19f5f39
--- /dev/null
+++ b/sphinx/ext/napoleon/docstring.py
@@ -0,0 +1,860 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.ext.napoleon.docstring
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+    Classes for docstring parsing and formatting.
+
+
+    :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import collections
+import inspect
+import re
+
+from six import string_types
+from six.moves import range
+
+from sphinx.ext.napoleon.iterators import modify_iter
+from sphinx.util.pycompat import UnicodeMixin
+
+
+_directive_regex = re.compile(r'\.\. \S+::')
+_google_untyped_arg_regex = re.compile(r'\s*(\w+)\s*:\s*(.*)')
+_google_typed_arg_regex = re.compile(r'\s*(\w+)\s*\(\s*(.+?)\s*\)\s*:\s*(.*)')
+
+
+class GoogleDocstring(UnicodeMixin):
+    """Parse Google style docstrings.
+
+    Convert Google style docstrings to reStructuredText.
+
+    Parameters
+    ----------
+    docstring : str or list of str
+        The docstring to parse, given either as a string or split into
+        individual lines.
+    config : sphinx.ext.napoleon.Config or sphinx.config.Config, optional
+        The configuration settings to use. If not given, defaults to the
+        config object on `app`; or if `app` is not given defaults to the
+        a new `sphinx.ext.napoleon.Config` object.
+
+        See Also
+        --------
+        :class:`sphinx.ext.napoleon.Config`
+
+    Other Parameters
+    ----------------
+    app : sphinx.application.Sphinx, optional
+        Application object representing the Sphinx process.
+    what : str, optional
+        A string specifying the type of the object to which the docstring
+        belongs. Valid values: "module", "class", "exception", "function",
+        "method", "attribute".
+    name : str, optional
+        The fully qualified name of the object.
+    obj : module, class, exception, function, method, or attribute
+        The object to which the docstring belongs.
+    options : sphinx.ext.autodoc.Options, optional
+        The options given to the directive: an object with attributes
+        inherited_members, undoc_members, show_inheritance and noindex that
+        are True if the flag option of same name was given to the auto
+        directive.
+
+    Example
+    -------
+    >>> from sphinx.ext.napoleon import Config
+    >>> config = Config(napoleon_use_param=True, napoleon_use_rtype=True)
+    >>> docstring = '''One line summary.
+    ...
+    ... Extended description.
+    ...
+    ... Args:
+    ...   arg1(int): Description of `arg1`
+    ...   arg2(str): Description of `arg2`
+    ... Returns:
+    ...   str: Description of return value.
+    ... '''
+    >>> print(GoogleDocstring(docstring, config))
+    One line summary.
+    <BLANKLINE>
+    Extended description.
+    <BLANKLINE>
+    :param arg1: Description of `arg1`
+    :type arg1: int
+    :param arg2: Description of `arg2`
+    :type arg2: str
+    <BLANKLINE>
+    :returns: Description of return value.
+    :rtype: str
+
+    """
+    def __init__(self, docstring, config=None, app=None, what='', name='',
+                 obj=None, options=None):
+        self._config = config
+        self._app = app
+
+        if not self._config:
+            from sphinx.ext.napoleon import Config
+            self._config = self._app and self._app.config or Config()
+
+        if not what:
+            if inspect.isclass(obj):
+                what = 'class'
+            elif inspect.ismodule(obj):
+                what = 'module'
+            elif isinstance(obj, collections.Callable):
+                what = 'function'
+            else:
+                what = 'object'
+
+        self._what = what
+        self._name = name
+        self._obj = obj
+        self._opt = options
+        if isinstance(docstring, string_types):
+            docstring = docstring.splitlines()
+        self._lines = docstring
+        self._line_iter = modify_iter(docstring, modifier=lambda s: s.rstrip())
+        self._parsed_lines = []
+        self._is_in_section = False
+        self._section_indent = 0
+        if not hasattr(self, '_directive_sections'):
+            self._directive_sections = []
+        if not hasattr(self, '_sections'):
+            self._sections = {
+                'args': self._parse_parameters_section,
+                'arguments': self._parse_parameters_section,
+                'attributes': self._parse_attributes_section,
+                'example': self._parse_examples_section,
+                'examples': self._parse_examples_section,
+                'keyword args': self._parse_keyword_arguments_section,
+                'keyword arguments': self._parse_keyword_arguments_section,
+                'methods': self._parse_methods_section,
+                'note': self._parse_note_section,
+                'notes': self._parse_notes_section,
+                'other parameters': self._parse_other_parameters_section,
+                'parameters': self._parse_parameters_section,
+                'return': self._parse_returns_section,
+                'returns': self._parse_returns_section,
+                'raises': self._parse_raises_section,
+                'references': self._parse_references_section,
+                'see also': self._parse_see_also_section,
+                'warning': self._parse_warning_section,
+                'warnings': self._parse_warning_section,
+                'warns': self._parse_warns_section,
+                'yields': self._parse_yields_section,
+            }
+        self._parse()
+
+    def __unicode__(self):
+        """Return the parsed docstring in reStructuredText format.
+
+        Returns
+        -------
+        unicode
+            Unicode version of the docstring.
+
+        """
+        return u'\n'.join(self.lines())
+
+    def lines(self):
+        """Return the parsed lines of the docstring in reStructuredText format.
+
+        Returns
+        -------
+        list of str
+            The lines of the docstring in a list.
+
+        """
+        return self._parsed_lines
+
+    def _consume_indented_block(self, indent=1):
+        lines = []
+        line = self._line_iter.peek()
+        while(not self._is_section_break()
+              and (not line or self._is_indented(line, indent))):
+            lines.append(next(self._line_iter))
+            line = self._line_iter.peek()
+        return lines
+
+    def _consume_contiguous(self):
+        lines = []
+        while (self._line_iter.has_next()
+               and self._line_iter.peek()
+               and not self._is_section_header()):
+            lines.append(next(self._line_iter))
+        return lines
+
+    def _consume_empty(self):
+        lines = []
+        line = self._line_iter.peek()
+        while self._line_iter.has_next() and not line:
+            lines.append(next(self._line_iter))
+            line = self._line_iter.peek()
+        return lines
+
+    def _consume_field(self, parse_type=True, prefer_type=False):
+        line = next(self._line_iter)
+
+        match = None
+        _name, _type, _desc = line.strip(), '', ''
+        if parse_type:
+            match = _google_typed_arg_regex.match(line)
+            if match:
+                _name = match.group(1)
+                _type = match.group(2)
+                _desc = match.group(3)
+
+        if not match:
+            match = _google_untyped_arg_regex.match(line)
+            if match:
+                _name = match.group(1)
+                _desc = match.group(2)
+
+        if prefer_type and not _type:
+            _type, _name = _name, _type
+        indent = self._get_indent(line) + 1
+        _desc = [_desc] + self._dedent(self._consume_indented_block(indent))
+        _desc = self.__class__(_desc, self._config).lines()
+        return _name, _type, _desc
+
+    def _consume_fields(self, parse_type=True, prefer_type=False):
+        self._consume_empty()
+        fields = []
+        while not self._is_section_break():
+            _name, _type, _desc = self._consume_field(parse_type, prefer_type)
+            if _name or _type or _desc:
+                fields.append((_name, _type, _desc,))
+        return fields
+
+    def _consume_returns_section(self):
+        lines = self._dedent(self._consume_to_next_section())
+        if lines:
+            _name, _type, _desc = '', '', lines
+            match = _google_typed_arg_regex.match(lines[0])
+            if match:
+                _name = match.group(1)
+                _type = match.group(2)
+                _desc = match.group(3)
+            else:
+                match = _google_untyped_arg_regex.match(lines[0])
+                if match:
+                    _type = match.group(1)
+                    _desc = match.group(2)
+            if match:
+                lines[0] = _desc
+                _desc = lines
+
+            _desc = self.__class__(_desc, self._config).lines()
+            return [(_name, _type, _desc,)]
+        else:
+            return []
+
+    def _consume_section_header(self):
+        section = next(self._line_iter)
+        stripped_section = section.strip(':')
+        if stripped_section.lower() in self._sections:
+            section = stripped_section
+        return section
+
+    def _consume_to_next_section(self):
+        self._consume_empty()
+        lines = []
+        while not self._is_section_break():
+            lines.append(next(self._line_iter))
+        return lines + self._consume_empty()
+
+    def _dedent(self, lines, full=False):
+        if full:
+            return [line.lstrip() for line in lines]
+        else:
+            min_indent = self._get_min_indent(lines)
+            return [line[min_indent:] for line in lines]
+
+    def _format_admonition(self, admonition, lines):
+        lines = self._strip_empty(lines)
+        if len(lines) == 1:
+            return ['.. %s:: %s' % (admonition, lines[0].strip()), '']
+        elif lines:
+            lines = self._indent(self._dedent(lines), 3)
+            return ['.. %s::' % admonition, ''] + lines + ['']
+        else:
+            return ['.. %s::' % admonition, '']
+
+    def _format_block(self, prefix, lines, padding=None):
+        if lines:
+            if padding is None:
+                padding = ' ' * len(prefix)
+            result_lines = []
+            for i, line in enumerate(lines):
+                if line:
+                    if i == 0:
+                        result_lines.append(prefix + line)
+                    else:
+                        result_lines.append(padding + line)
+                else:
+                    result_lines.append('')
+            return result_lines
+        else:
+            return [prefix]
+
+    def _format_field(self, _name, _type, _desc):
+        separator = any([s for s in _desc]) and ' --' or ''
+        if _name:
+            if _type:
+                if '`' in _type:
+                    field = ['**%s** (%s)%s' % (_name, _type, separator)]
+                else:
+                    field = ['**%s** (*%s*)%s' % (_name, _type, separator)]
+            else:
+                field = ['**%s**%s' % (_name, separator)]
+        elif _type:
+            if '`' in _type:
+                field = ['%s%s' % (_type, separator)]
+            else:
+                field = ['*%s*%s' % (_type, separator)]
+        else:
+            field = []
+        return field + _desc
+
+    def _format_fields(self, field_type, fields):
+        field_type = ':%s:' % field_type.strip()
+        padding = ' ' * len(field_type)
+        multi = len(fields) > 1
+        lines = []
+        for _name, _type, _desc in fields:
+            field = self._format_field(_name, _type, _desc)
+            if multi:
+                if lines:
+                    lines.extend(self._format_block(padding + ' * ', field))
+                else:
+                    lines.extend(self._format_block(field_type + ' * ', field))
+            else:
+                lines.extend(self._format_block(field_type + ' ', field))
+        return lines
+
+    def _get_current_indent(self, peek_ahead=0):
+        line = self._line_iter.peek(peek_ahead + 1)[peek_ahead]
+        while line != self._line_iter.sentinel:
+            if line:
+                return self._get_indent(line)
+            peek_ahead += 1
+            line = self._line_iter.peek(peek_ahead + 1)[peek_ahead]
+        return 0
+
+    def _get_indent(self, line):
+        for i, s in enumerate(line):
+            if not s.isspace():
+                return i
+        return len(line)
+
+    def _get_min_indent(self, lines):
+        min_indent = None
+        for line in lines:
+            if line:
+                indent = self._get_indent(line)
+                if min_indent is None:
+                    min_indent = indent
+                elif indent < min_indent:
+                    min_indent = indent
+        return min_indent or 0
+
+    def _indent(self, lines, n=4):
+        return [(' ' * n) + line for line in lines]
+
+    def _is_indented(self, line, indent=1):
+        for i, s in enumerate(line):
+            if i >= indent:
+                return True
+            elif not s.isspace():
+                return False
+        return False
+
+    def _is_section_header(self):
+        section = self._line_iter.peek().lower()
+        if section.strip(':') in self._sections:
+            header_indent = self._get_indent(section)
+            section_indent = self._get_current_indent(peek_ahead=1)
+            return section_indent > header_indent
+        elif self._directive_sections:
+            if _directive_regex.match(section):
+                for directive_section in self._directive_sections:
+                    if section.startswith(directive_section):
+                        return True
+        return False
+
+    def _is_section_break(self):
+        line = self._line_iter.peek()
+        return (not self._line_iter.has_next()
+                or self._is_section_header()
+                or (self._is_in_section
+                    and line
+                    and not self._is_indented(line, self._section_indent)))
+
+    def _parse(self):
+        self._parsed_lines = self._consume_empty()
+        while self._line_iter.has_next():
+            if self._is_section_header():
+                try:
+                    section = self._consume_section_header()
+                    self._is_in_section = True
+                    self._section_indent = self._get_current_indent()
+                    if _directive_regex.match(section):
+                        lines = [section] + self._consume_to_next_section()
+                    else:
+                        lines = self._sections[section.lower()](section)
+                finally:
+                    self._is_in_section = False
+                    self._section_indent = 0
+            else:
+                if not self._parsed_lines:
+                    lines = self._consume_contiguous() + self._consume_empty()
+                else:
+                    lines = self._consume_to_next_section()
+            self._parsed_lines.extend(lines)
+
+    def _parse_attributes_section(self, section):
+        lines = []
+        for _name, _type, _desc in self._consume_fields():
+            if self._config.napoleon_use_ivar:
+                field = ':ivar %s: ' % _name
+                lines.extend(self._format_block(field, _desc))
+                if _type:
+                    lines.append(':vartype %s: %s' % (_name, _type))
+            else:
+                lines.append('.. attribute:: ' + _name)
+                if _type:
+                    lines.append('')
+                    if '`' in _type:
+                        lines.append('   %s' % _type)
+                    else:
+                        lines.append('   *%s*' % _type)
+                if _desc:
+                    lines.extend([''] + self._indent(_desc, 3))
+                lines.append('')
+        if self._config.napoleon_use_ivar:
+            lines.append('')
+        return lines
+
+    def _parse_examples_section(self, section):
+        use_admonition = self._config.napoleon_use_admonition_for_examples
+        return self._parse_generic_section(section, use_admonition)
+
+    def _parse_generic_section(self, section, use_admonition):
+        lines = self._strip_empty(self._consume_to_next_section())
+        lines = self._dedent(lines)
+        if use_admonition:
+            header = '.. admonition:: %s' % section
+            lines = self._indent(lines, 3)
+        else:
+            header = '.. rubric:: %s' % section
+        if lines:
+            return [header, ''] + lines + ['']
+        else:
+            return [header, '']
+
+    def _parse_keyword_arguments_section(self, section):
+        return self._format_fields('Keyword Arguments', self._consume_fields())
+
+    def _parse_methods_section(self, section):
+        lines = []
+        for _name, _, _desc in self._consume_fields(parse_type=False):
+            lines.append('.. method:: %s' % _name)
+            if _desc:
+                lines.extend([''] + self._indent(_desc, 3))
+            lines.append('')
+        return lines
+
+    def _parse_note_section(self, section):
+        lines = self._consume_to_next_section()
+        return self._format_admonition('note', lines)
+
+    def _parse_notes_section(self, section):
+        use_admonition = self._config.napoleon_use_admonition_for_notes
+        return self._parse_generic_section('Notes', use_admonition)
+
+    def _parse_other_parameters_section(self, section):
+        return self._format_fields('Other Parameters', self._consume_fields())
+
+    def _parse_parameters_section(self, section):
+        fields = self._consume_fields()
+        if self._config.napoleon_use_param:
+            lines = []
+            for _name, _type, _desc in fields:
+                field = ':param %s: ' % _name
+                lines.extend(self._format_block(field, _desc))
+                if _type:
+                    lines.append(':type %s: %s' % (_name, _type))
+            return lines + ['']
+        else:
+            return self._format_fields('Parameters', fields)
+
+    def _parse_raises_section(self, section):
+        fields = self._consume_fields()
+        field_type = ':raises:'
+        padding = ' ' * len(field_type)
+        multi = len(fields) > 1
+        lines = []
+        for _name, _type, _desc in fields:
+            sep = _desc and ' -- ' or ''
+            if _name:
+                if ' ' in _name:
+                    _name = '**%s**' % _name
+                else:
+                    _name = ':exc:`%s`' % _name
+                if _type:
+                    if '`' in _type:
+                        field = ['%s (%s)%s' % (_name, _type, sep)]
+                    else:
+                        field = ['%s (*%s*)%s' % (_name, _type, sep)]
+                else:
+                    field = ['%s%s' % (_name, sep)]
+            elif _type:
+                if '`' in _type:
+                    field = ['%s%s' % (_type, sep)]
+                else:
+                    field = ['*%s*%s' % (_type, sep)]
+            else:
+                field = []
+            field = field + _desc
+            if multi:
+                if lines:
+                    lines.extend(self._format_block(padding + ' * ', field))
+                else:
+                    lines.extend(self._format_block(field_type + ' * ', field))
+            else:
+                lines.extend(self._format_block(field_type + ' ', field))
+        return lines
+
+    def _parse_references_section(self, section):
+        use_admonition = self._config.napoleon_use_admonition_for_references
+        return self._parse_generic_section('References', use_admonition)
+
+    def _parse_returns_section(self, section):
+        fields = self._consume_returns_section()
+        multi = len(fields) > 1
+        if multi:
+            use_rtype = False
+        else:
+            use_rtype = self._config.napoleon_use_rtype
+
+        lines = []
+        for _name, _type, _desc in fields:
+            if use_rtype:
+                field = self._format_field(_name, '', _desc)
+            else:
+                field = self._format_field(_name, _type, _desc)
+
+            if multi:
+                if lines:
+                    lines.extend(self._format_block('          * ', field))
+                else:
+                    lines.extend(self._format_block(':returns: * ', field))
+            else:
+                lines.extend(self._format_block(':returns: ', field))
+                if _type and use_rtype:
+                    lines.append(':rtype: %s' % _type)
+                    lines.append('')
+        return lines
+
+    def _parse_see_also_section(self, section):
+        lines = self._consume_to_next_section()
+        return self._format_admonition('seealso', lines)
+
+    def _parse_warning_section(self, section):
+        lines = self._consume_to_next_section()
+        return self._format_admonition('warning', lines)
+
+    def _parse_warns_section(self, section):
+        return self._format_fields('Warns', self._consume_fields())
+
+    def _parse_yields_section(self, section):
+        fields = self._consume_fields(prefer_type=True)
+        return self._format_fields('Yields', fields)
+
+    def _strip_empty(self, lines):
+        if lines:
+            start = -1
+            for i, line in enumerate(lines):
+                if line:
+                    start = i
+                    break
+            if start == -1:
+                lines = []
+            end = -1
+            for i in reversed(range(len(lines))):
+                line = lines[i]
+                if line:
+                    end = i
+                    break
+            if start > 0 or end + 1 < len(lines):
+                lines = lines[start:end + 1]
+        return lines
+
+
+class NumpyDocstring(GoogleDocstring):
+    """Parse NumPy style docstrings.
+
+    Convert NumPy style docstrings to reStructuredText.
+
+    Parameters
+    ----------
+    docstring : str or list of str
+        The docstring to parse, given either as a string or split into
+        individual lines.
+    config : sphinx.ext.napoleon.Config or sphinx.config.Config, optional
+        The configuration settings to use. If not given, defaults to the
+        config object on `app`; or if `app` is not given defaults to the
+        a new `sphinx.ext.napoleon.Config` object.
+
+        See Also
+        --------
+        :class:`sphinx.ext.napoleon.Config`
+
+    Other Parameters
+    ----------------
+    app : sphinx.application.Sphinx, optional
+        Application object representing the Sphinx process.
+    what : str, optional
+        A string specifying the type of the object to which the docstring
+        belongs. Valid values: "module", "class", "exception", "function",
+        "method", "attribute".
+    name : str, optional
+        The fully qualified name of the object.
+    obj : module, class, exception, function, method, or attribute
+        The object to which the docstring belongs.
+    options : sphinx.ext.autodoc.Options, optional
+        The options given to the directive: an object with attributes
+        inherited_members, undoc_members, show_inheritance and noindex that
+        are True if the flag option of same name was given to the auto
+        directive.
+
+    Example
+    -------
+    >>> from sphinx.ext.napoleon import Config
+    >>> config = Config(napoleon_use_param=True, napoleon_use_rtype=True)
+    >>> docstring = '''One line summary.
+    ...
+    ... Extended description.
+    ...
+    ... Parameters
+    ... ----------
+    ... arg1 : int
+    ...     Description of `arg1`
+    ... arg2 : str
+    ...     Description of `arg2`
+    ... Returns
+    ... -------
+    ... str
+    ...     Description of return value.
+    ... '''
+    >>> print(NumpyDocstring(docstring, config))
+    One line summary.
+    <BLANKLINE>
+    Extended description.
+    <BLANKLINE>
+    :param arg1: Description of `arg1`
+    :type arg1: int
+    :param arg2: Description of `arg2`
+    :type arg2: str
+    <BLANKLINE>
+    :returns: Description of return value.
+    :rtype: str
+
+    Methods
+    -------
+    __str__()
+        Return the parsed docstring in reStructuredText format.
+
+        Returns
+        -------
+        str
+            UTF-8 encoded version of the docstring.
+
+    __unicode__()
+        Return the parsed docstring in reStructuredText format.
+
+        Returns
+        -------
+        unicode
+            Unicode version of the docstring.
+
+    lines()
+        Return the parsed lines of the docstring in reStructuredText format.
+
+        Returns
+        -------
+        list of str
+            The lines of the docstring in a list.
+
+    """
+    def __init__(self, docstring, config=None, app=None, what='', name='',
+                 obj=None, options=None):
+        self._directive_sections = ['.. index::']
+        super(NumpyDocstring, self).__init__(docstring, config, app, what,
+                                             name, obj, options)
+
+    def _consume_field(self, parse_type=True, prefer_type=False):
+        line = next(self._line_iter)
+        if parse_type:
+            _name, _, _type = line.partition(':')
+        else:
+            _name, _type = line, ''
+        _name, _type = _name.strip(), _type.strip()
+        if prefer_type and not _type:
+            _type, _name = _name, _type
+        indent = self._get_indent(line)
+        _desc = self._dedent(self._consume_indented_block(indent + 1))
+        _desc = self.__class__(_desc, self._config).lines()
+        return _name, _type, _desc
+
+    def _consume_returns_section(self):
+        return self._consume_fields(prefer_type=True)
+
+    def _consume_section_header(self):
+        section = next(self._line_iter)
+        if not _directive_regex.match(section):
+            # Consume the header underline
+            next(self._line_iter)
+        return section
+
+    def _is_section_break(self):
+        line1, line2 = self._line_iter.peek(2)
+        return (not self._line_iter.has_next()
+                or self._is_section_header()
+                or ['', ''] == [line1, line2]
+                or (self._is_in_section
+                    and line1
+                    and not self._is_indented(line1, self._section_indent)))
+
+    def _is_section_header(self):
+        section, underline = self._line_iter.peek(2)
+        section = section.lower()
+        if section in self._sections and isinstance(underline, string_types):
+            pattern = r'[=\-`:\'"~^_*+#<>]{' + str(len(section)) + r'}$'
+            return bool(re.match(pattern, underline))
+        elif self._directive_sections:
+            if _directive_regex.match(section):
+                for directive_section in self._directive_sections:
+                    if section.startswith(directive_section):
+                        return True
+        return False
+
+    _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|"
+                           r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X)
+
+    def _parse_see_also_section(self, section):
+        lines = self._consume_to_next_section()
+        try:
+            return self._parse_numpydoc_see_also_section(lines)
+        except ValueError:
+            return self._format_admonition('seealso', lines)
+
+    def _parse_numpydoc_see_also_section(self, content):
+        """
+        Derived from the NumpyDoc implementation of _parse_see_also.
+
+        func_name : Descriptive text
+            continued text
+        another_func_name : Descriptive text
+        func_name1, func_name2, :meth:`func_name`, func_name3
+
+        """
+        items = []
+
+        def parse_item_name(text):
+            """Match ':role:`name`' or 'name'"""
+            m = self._name_rgx.match(text)
+            if m:
+                g = m.groups()
+                if g[1] is None:
+                    return g[3], None
+                else:
+                    return g[2], g[1]
+            raise ValueError("%s is not a item name" % text)
+
+        def push_item(name, rest):
+            if not name:
+                return
+            name, role = parse_item_name(name)
+            items.append((name, list(rest), role))
+            del rest[:]
+
+        current_func = None
+        rest = []
+
+        for line in content:
+            if not line.strip():
+                continue
+
+            m = self._name_rgx.match(line)
+            if m and line[m.end():].strip().startswith(':'):
+                push_item(current_func, rest)
+                current_func, line = line[:m.end()], line[m.end():]
+                rest = [line.split(':', 1)[1].strip()]
+                if not rest[0]:
+                    rest = []
+            elif not line.startswith(' '):
+                push_item(current_func, rest)
+                current_func = None
+                if ',' in line:
+                    for func in line.split(','):
+                        if func.strip():
+                            push_item(func, [])
+                elif line.strip():
+                    current_func = line
+            elif current_func is not None:
+                rest.append(line.strip())
+        push_item(current_func, rest)
+
+        if not items:
+            return []
+
+        roles = {
+            'method': 'meth',
+            'meth': 'meth',
+            'function': 'func',
+            'func': 'func',
+            'class': 'class',
+            'exception': 'exc',
+            'exc': 'exc',
+            'object': 'obj',
+            'obj': 'obj',
+            'module': 'mod',
+            'mod': 'mod',
+            'data': 'data',
+            'constant': 'const',
+            'const': 'const',
+            'attribute': 'attr',
+            'attr': 'attr'
+        }
+        if self._what is None:
+            func_role = 'obj'
+        else:
+            func_role = roles.get(self._what, '')
+        lines = []
+        last_had_desc = True
+        for func, desc, role in items:
+            if role:
+                link = ':%s:`%s`' % (role, func)
+            elif func_role:
+                link = ':%s:`%s`' % (func_role, func)
+            else:
+                link = "`%s`_" % func
+            if desc or last_had_desc:
+                lines += ['']
+                lines += [link]
+            else:
+                lines[-1] += ", %s" % link
+            if desc:
+                lines += self._indent([' '.join(desc)])
+                last_had_desc = True
+            else:
+                last_had_desc = False
+        lines += ['']
+
+        return self._format_admonition('seealso', lines)
diff --git a/sphinx/ext/napoleon/iterators.py b/sphinx/ext/napoleon/iterators.py
new file mode 100644
index 0000000..482fe1d
--- /dev/null
+++ b/sphinx/ext/napoleon/iterators.py
@@ -0,0 +1,239 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.ext.napoleon.iterators
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+    A collection of helpful iterators.
+
+
+    :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import collections
+
+
+class peek_iter(object):
+    """An iterator object that supports peeking ahead.
+
+    Parameters
+    ----------
+    o : iterable or callable
+        `o` is interpreted very differently depending on the presence of
+        `sentinel`.
+
+        If `sentinel` is not given, then `o` must be a collection object
+        which supports either the iteration protocol or the sequence protocol.
+
+        If `sentinel` is given, then `o` must be a callable object.
+
+    sentinel : any value, optional
+        If given, the iterator will call `o` with no arguments for each
+        call to its `next` method; if the value returned is equal to
+        `sentinel`, :exc:`StopIteration` will be raised, otherwise the
+        value will be returned.
+
+    See Also
+    --------
+    `peek_iter` can operate as a drop in replacement for the built-in
+    `iter <http://docs.python.org/2/library/functions.html#iter>`_ function.
+
+    Attributes
+    ----------
+    sentinel
+        The value used to indicate the iterator is exhausted. If `sentinel`
+        was not given when the `peek_iter` was instantiated, then it will
+        be set to a new object instance: ``object()``.
+
+    """
+    def __init__(self, *args):
+        """__init__(o, sentinel=None)"""
+        self._iterable = iter(*args)
+        self._cache = collections.deque()
+        if len(args) == 2:
+            self.sentinel = args[1]
+        else:
+            self.sentinel = object()
+
+    def __iter__(self):
+        return self
+
+    def __next__(self, n=None):
+        # note: prevent 2to3 to transform self.next() in next(self) which
+        # causes an infinite loop !
+        return getattr(self, 'next')(n)
+
+    def _fillcache(self, n):
+        """Cache `n` items. If `n` is 0 or None, then 1 item is cached."""
+        if not n:
+            n = 1
+        try:
+            while len(self._cache) < n:
+                self._cache.append(next(self._iterable))
+        except StopIteration:
+            while len(self._cache) < n:
+                self._cache.append(self.sentinel)
+
+    def has_next(self):
+        """Determine if iterator is exhausted.
+
+        Returns
+        -------
+        bool
+            True if iterator has more items, False otherwise.
+
+        Note
+        ----
+        Will never raise :exc:`StopIteration`.
+
+        """
+        return self.peek() != self.sentinel
+
+    def next(self, n=None):
+        """Get the next item or `n` items of the iterator.
+
+        Parameters
+        ----------
+        n : int or None
+            The number of items to retrieve. Defaults to None.
+
+        Returns
+        -------
+        item or list of items
+            The next item or `n` items of the iterator. If `n` is None, the
+            item itself is returned. If `n` is an int, the items will be
+            returned in a list. If `n` is 0, an empty list is returned.
+
+        Raises
+        ------
+        StopIteration
+            Raised if the iterator is exhausted, even if `n` is 0.
+
+        """
+        self._fillcache(n)
+        if not n:
+            if self._cache[0] == self.sentinel:
+                raise StopIteration
+            if n is None:
+                result = self._cache.popleft()
+            else:
+                result = []
+        else:
+            if self._cache[n - 1] == self.sentinel:
+                raise StopIteration
+            result = [self._cache.popleft() for i in range(n)]
+        return result
+
+    def peek(self, n=None):
+        """Preview the next item or `n` items of the iterator.
+
+        The iterator is not advanced when peek is called.
+
+        Returns
+        -------
+        item or list of items
+            The next item or `n` items of the iterator. If `n` is None, the
+            item itself is returned. If `n` is an int, the items will be
+            returned in a list. If `n` is 0, an empty list is returned.
+
+            If the iterator is exhausted, `peek_iter.sentinel` is returned,
+            or placed as the last item in the returned list.
+
+        Note
+        ----
+        Will never raise :exc:`StopIteration`.
+
+        """
+        self._fillcache(n)
+        if n is None:
+            result = self._cache[0]
+        else:
+            result = [self._cache[i] for i in range(n)]
+        return result
+
+
+class modify_iter(peek_iter):
+    """An iterator object that supports modifying items as they are returned.
+
+    Parameters
+    ----------
+    o : iterable or callable
+        `o` is interpreted very differently depending on the presence of
+        `sentinel`.
+
+        If `sentinel` is not given, then `o` must be a collection object
+        which supports either the iteration protocol or the sequence protocol.
+
+        If `sentinel` is given, then `o` must be a callable object.
+
+    sentinel : any value, optional
+        If given, the iterator will call `o` with no arguments for each
+        call to its `next` method; if the value returned is equal to
+        `sentinel`, :exc:`StopIteration` will be raised, otherwise the
+        value will be returned.
+
+    modifier : callable, optional
+        The function that will be used to modify each item returned by the
+        iterator. `modifier` should take a single argument and return a
+        single value. Defaults to ``lambda x: x``.
+
+        If `sentinel` is not given, `modifier` must be passed as a keyword
+        argument.
+
+    Attributes
+    ----------
+    modifier : callable
+        `modifier` is called with each item in `o` as it is iterated. The
+        return value of `modifier` is returned in lieu of the item.
+
+        Values returned by `peek` as well as `next` are affected by
+        `modifier`. However, `modify_iter.sentinel` is never passed through
+        `modifier`; it will always be returned from `peek` unmodified.
+
+    Example
+    -------
+    >>> a = ["     A list    ",
+    ...      "   of strings  ",
+    ...      "      with     ",
+    ...      "      extra    ",
+    ...      "   whitespace. "]
+    >>> modifier = lambda s: s.strip().replace('with', 'without')
+    >>> for s in modify_iter(a, modifier=modifier):
+    ...   print('"%s"' % s)
+    "A list"
+    "of strings"
+    "without"
+    "extra"
+    "whitespace."
+
+    """
+    def __init__(self, *args, **kwargs):
+        """__init__(o, sentinel=None, modifier=lambda x: x)"""
+        if 'modifier' in kwargs:
+            self.modifier = kwargs['modifier']
+        elif len(args) > 2:
+            self.modifier = args[2]
+            args = args[:2]
+        else:
+            self.modifier = lambda x: x
+        if not callable(self.modifier):
+            raise TypeError('modify_iter(o, modifier): '
+                            'modifier must be callable')
+        super(modify_iter, self).__init__(*args)
+
+    def _fillcache(self, n):
+        """Cache `n` modified items. If `n` is 0 or None, 1 item is cached.
+
+        Each item returned by the iterator is passed through the
+        `modify_iter.modified` function before being cached.
+
+        """
+        if not n:
+            n = 1
+        try:
+            while len(self._cache) < n:
+                self._cache.append(self.modifier(next(self._iterable)))
+        except StopIteration:
+            while len(self._cache) < n:
+                self._cache.append(self.sentinel)
diff --git a/sphinx/ext/oldcmarkup.py b/sphinx/ext/oldcmarkup.py
deleted file mode 100644
index aa10246..0000000
--- a/sphinx/ext/oldcmarkup.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-    sphinx.ext.oldcmarkup
-    ~~~~~~~~~~~~~~~~~~~~~
-
-    Extension for compatibility with old C markup (directives and roles).
-
-    :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
-    :license: BSD, see LICENSE for details.
-"""
-
-from docutils.parsers.rst import directives
-
-from sphinx.util.compat import Directive
-
-_warned_oldcmarkup = False
-WARNING_MSG = 'using old C markup; please migrate to new-style markup ' \
-              '(e.g. c:function instead of cfunction), see ' \
-              'http://sphinx-doc.org/domains.html'
-
-
-class OldCDirective(Directive):
-    has_content = True
-    required_arguments = 1
-    optional_arguments = 0
-    final_argument_whitespace = True
-    option_spec = {
-        'noindex': directives.flag,
-        'module': directives.unchanged,
-    }
-
-    def run(self):
-        env = self.state.document.settings.env
-        if not env.app._oldcmarkup_warned:
-            self.state_machine.reporter.warning(WARNING_MSG, line=self.lineno)
-            env.app._oldcmarkup_warned = True
-        newname = 'c:' + self.name[1:]
-        newdir = env.lookup_domain_element('directive', newname)[0]
-        return newdir(newname, self.arguments, self.options,
-                      self.content, self.lineno, self.content_offset,
-                      self.block_text, self.state, self.state_machine).run()
-
-
-def old_crole(typ, rawtext, text, lineno, inliner, options={}, content=[]):
-    env = inliner.document.settings.env
-    if not typ:
-        typ = env.config.default_role
-    if not env.app._oldcmarkup_warned:
-        inliner.reporter.warning(WARNING_MSG, line=lineno)
-        env.app._oldcmarkup_warned = True
-    newtyp = 'c:' + typ[1:]
-    newrole = env.lookup_domain_element('role', newtyp)[0]
-    return newrole(newtyp, rawtext, text, lineno, inliner, options, content)
-
-
-def setup(app):
-    app._oldcmarkup_warned = False
-    app.add_directive('cfunction', OldCDirective)
-    app.add_directive('cmember', OldCDirective)
-    app.add_directive('cmacro', OldCDirective)
-    app.add_directive('ctype', OldCDirective)
-    app.add_directive('cvar', OldCDirective)
-    app.add_role('cdata', old_crole)
-    app.add_role('cfunc', old_crole)
-    app.add_role('cmacro', old_crole)
-    app.add_role('ctype', old_crole)
-    app.add_role('cmember', old_crole)
diff --git a/sphinx/ext/pngmath.py b/sphinx/ext/pngmath.py
index b654630..ee108d1 100644
--- a/sphinx/ext/pngmath.py
+++ b/sphinx/ext/pngmath.py
@@ -16,17 +16,16 @@
 import posixpath
 from os import path, getcwd, chdir
 from subprocess import Popen, PIPE
-try:
-    from hashlib import sha1 as sha
-except ImportError:
-    from sha import sha
+from hashlib import sha1
 
+from six import text_type
 from docutils import nodes
 
+import sphinx
 from sphinx.errors import SphinxError
 from sphinx.util.png import read_png_depth, write_png_depth
 from sphinx.util.osutil import ensuredir, ENOENT
-from sphinx.util.pycompat import b, sys_encoding
+from sphinx.util.pycompat import sys_encoding
 from sphinx.ext.mathbase import setup_math as mathbase_setup, wrap_displaymath
 
 class MathExtError(SphinxError):
@@ -66,7 +65,7 @@
 \end{document}
 '''
 
-depth_re = re.compile(b(r'\[\d+ depth=(-?\d+)\]'))
+depth_re = re.compile(br'\[\d+ depth=(-?\d+)\]')
 
 def render_math(self, math):
     """Render the LaTeX math expression *math* using latex and dvipng.
@@ -85,7 +84,7 @@
     latex = DOC_HEAD + self.builder.config.pngmath_latex_preamble
     latex += (use_preview and DOC_BODY_PREVIEW or DOC_BODY) % math
 
-    shasum = "%s.png" % sha(latex.encode('utf-8')).hexdigest()
+    shasum = "%s.png" % sha1(latex.encode('utf-8')).hexdigest()
     relfn = posixpath.join(self.builder.imgpath, 'math', shasum)
     outfn = path.join(self.builder.outdir, '_images', 'math', shasum)
     if path.isfile(outfn):
@@ -123,7 +122,7 @@
     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 +149,7 @@
     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,8 +189,8 @@
 def html_visit_math(self, node):
     try:
         fname, depth = render_math(self, '$'+node['latex']+'$')
-    except MathExtError, exc:
-        msg = unicode(exc)
+    except MathExtError as exc:
+        msg = text_type(exc)
         sm = nodes.system_message(msg, type='WARNING', level=2,
                                   backrefs=[], source=node['latex'])
         sm.walkabout(self)
@@ -215,7 +214,7 @@
         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)
@@ -247,3 +246,4 @@
     app.add_config_value('pngmath_latex_preamble', '', 'html')
     app.add_config_value('pngmath_add_tooltips', True, 'html')
     app.connect('build-finished', cleanup_tempdir)
+    return sphinx.__version__
diff --git a/sphinx/ext/todo.py b/sphinx/ext/todo.py
index 9f521fb..d70617b 100644
--- a/sphinx/ext/todo.py
+++ b/sphinx/ext/todo.py
@@ -14,6 +14,7 @@
 
 from docutils import nodes
 
+import sphinx
 from sphinx.locale import _
 from sphinx.environment import NoUri
 from sphinx.util.nodes import set_source_info
@@ -171,4 +172,4 @@
     app.connect('doctree-read', process_todos)
     app.connect('doctree-resolved', process_todo_nodes)
     app.connect('env-purge-doc', purge_todos)
-
+    return sphinx.__version__
diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py
index 74a0046..3653a2d 100644
--- a/sphinx/ext/viewcode.py
+++ b/sphinx/ext/viewcode.py
@@ -9,37 +9,61 @@
     :license: BSD, see LICENSE for details.
 """
 
+import traceback
+
+from six import iteritems, text_type
 from docutils import nodes
 
+import sphinx
 from sphinx import addnodes
 from sphinx.locale import _
 from sphinx.pycode import ModuleAnalyzer
+from sphinx.util import get_full_modname
 from sphinx.util.nodes import make_refnode
 
 
+def _get_full_modname(app, modname, attribute):
+    try:
+        return get_full_modname(modname, attribute)
+    except AttributeError:
+        # sphinx.ext.viewcode can't follow class instance attribute
+        # then AttributeError logging output only verbose mode.
+        app.verbose('Didn\'t find %s in %s' % (attribute, modname))
+        return None
+    except Exception as e:
+        # sphinx.ext.viewcode follow python domain directives.
+        # because of that, if there are no real modules exists that specified
+        # by py:function or other directives, viewcode emits a lot of warnings.
+        # It should be displayed only verbose mode.
+        app.verbose(traceback.format_exc().rstrip())
+        app.verbose('viewcode can\'t import %s, failed with error "%s"' %
+                 (modname, e))
+        return None
+
+
 def doctree_read(app, doctree):
     env = app.builder.env
     if not hasattr(env, '_viewcode_modules'):
         env._viewcode_modules = {}
 
-    def has_tag(modname, fullname, docname):
+    def has_tag(modname, fullname, docname, refname):
         entry = env._viewcode_modules.get(modname, None)
         try:
             analyzer = ModuleAnalyzer.for_module(modname)
         except Exception:
             env._viewcode_modules[modname] = False
             return
-        if not isinstance(analyzer.code, unicode):
+        if not isinstance(analyzer.code, text_type):
             code = analyzer.code.decode(analyzer.encoding)
         else:
             code = analyzer.code
         if entry is None or entry[0] != code:
             analyzer.find_tags()
-            entry = code, analyzer.tags, {}
+            entry = code, analyzer.tags, {}, refname
             env._viewcode_modules[modname] = entry
         elif entry is False:
             return
-        code, tags, used = entry
+        _, tags, used, _ = entry
         if fullname in tags:
             used[fullname] = docname
             return True
@@ -52,10 +76,14 @@
             if not isinstance(signode, addnodes.desc_signature):
                 continue
             modname = signode.get('module')
+            fullname = signode.get('fullname')
+            refname = modname
+            if env.config.viewcode_import:
+                modname = _get_full_modname(app, modname, fullname)
             if not modname:
                 continue
             fullname = signode.get('fullname')
-            if not has_tag(modname, fullname, env.docname):
+            if not has_tag(modname, fullname, env.docname, refname):
                 continue
             if fullname in names:
                 # only one link per name, please
@@ -91,10 +119,10 @@
     app.builder.info(' (%d module code pages)' %
                      len(env._viewcode_modules), nonl=1)
 
-    for modname, entry in env._viewcode_modules.iteritems():
+    for modname, entry in iteritems(env._viewcode_modules):
         if not entry:
             continue
-        code, tags, used = entry
+        code, tags, used, refname = entry
         # construct a page name for the highlighted source
         pagename = '_modules/' + modname.replace('.', '/')
         # highlight the source using the builder's highlighter
@@ -109,9 +137,9 @@
         # the collected tags (HACK: this only works if the tag boundaries are
         # properly nested!)
         maxindex = len(lines) - 1
-        for name, docname in used.iteritems():
+        for name, docname in iteritems(used):
             type, start, end = tags[name]
-            backlink = urito(pagename, docname) + '#' + modname + '.' + name
+            backlink = urito(pagename, docname) + '#' + refname + '.' + name
             lines[start] = (
                 '<div class="viewcode-block" id="%s"><a class="viewcode-back" '
                 'href="%s">%s</a>' % (name, backlink, _('[docs]'))
@@ -170,8 +198,10 @@
 
 
 def setup(app):
+    app.add_config_value('viewcode_import', True, False)
     app.connect('doctree-read', doctree_read)
     app.connect('html-collect-pages', collect_pages)
     app.connect('missing-reference', missing_reference)
     #app.add_config_value('viewcode_include_modules', [], 'env')
     #app.add_config_value('viewcode_exclude_modules', [], 'env')
+    return sphinx.__version__
diff --git a/sphinx/highlighting.py b/sphinx/highlighting.py
index 600a7cf..599a76a 100644
--- a/sphinx/highlighting.py
+++ b/sphinx/highlighting.py
@@ -9,7 +9,6 @@
     :license: BSD, see LICENSE for details.
 """
 
-import sys
 import re
 import textwrap
 
@@ -19,6 +18,8 @@
     # parser is not available on Jython
     parser = None
 
+from six import PY2, text_type
+
 from sphinx.util.pycompat import htmlescape
 from sphinx.util.texescape import tex_hl_escape_map_new
 from sphinx.ext import doctest
@@ -69,12 +70,6 @@
 \renewcommand\PYGZsq{\textquotesingle}
 '''
 
-parsing_exceptions = (SyntaxError, UnicodeEncodeError)
-if sys.version_info < (2, 5):
-    # Python <= 2.4 raises MemoryError when parsing an
-    # invalid encoding cookie
-    parsing_exceptions += MemoryError,
-
 
 class PygmentsBridge(object):
     # Set these attributes if you want to have different Pygments formatters
@@ -137,11 +132,7 @@
         # lines beginning with "..." are probably placeholders for suite
         src = re.sub(r"(?m)^(\s*)" + mark + "(.)", r"\1"+ mark + r"# \2", src)
 
-        # if we're using 2.5, use the with statement
-        if sys.version_info >= (2, 5):
-            src = 'from __future__ import with_statement\n' + src
-
-        if sys.version_info < (3, 0) and isinstance(src, unicode):
+        if PY2 and isinstance(src, text_type):
             # Non-ASCII chars will only occur in string literals
             # and comments.  If we wanted to give them to the parser
             # correctly, we'd have to find out the correct source
@@ -149,24 +140,18 @@
             # just replace all non-ASCII characters.
             src = src.encode('ascii', 'replace')
 
-        if (3, 0) <= sys.version_info < (3, 2):
-            # Python 3.1 can't process '\r' as linesep.
-            # `parser.suite("print('hello')\r\n")` cause error.
-            if '\r\n' in src:
-                src = src.replace('\r\n', '\n')
-
         if parser is None:
             return True
 
         try:
             parser.suite(src)
-        except parsing_exceptions:
+        except (SyntaxError, UnicodeEncodeError):
             return False
         else:
             return True
 
     def highlight_block(self, source, lang, warn=None, force=False, **kwargs):
-        if not isinstance(source, unicode):
+        if not isinstance(source, text_type):
             source = source.decode()
         if not pygments:
             return self.unhighlighted(source)
@@ -223,7 +208,7 @@
         if self.dest == 'html':
             return hlsource
         else:
-            if not isinstance(hlsource, unicode):  # Py2 / Pygments < 1.6
+            if not isinstance(hlsource, text_type):  # Py2 / Pygments < 1.6
                 hlsource = hlsource.decode()
             return hlsource.translate(tex_hl_escape_map_new)
 
diff --git a/sphinx/jinja2glue.py b/sphinx/jinja2glue.py
index f4a5a81..b161b42 100644
--- a/sphinx/jinja2glue.py
+++ b/sphinx/jinja2glue.py
@@ -12,6 +12,7 @@
 from os import path
 from pprint import pformat
 
+from six import string_types
 from jinja2 import FileSystemLoader, BaseLoader, TemplateNotFound, \
      contextfunction
 from jinja2.utils import open_if_exists
@@ -22,7 +23,7 @@
 
 
 def _tobool(val):
-    if isinstance(val, basestring):
+    if isinstance(val, string_types):
         return val.lower() in ('true', '1', 'yes', 'on')
     return bool(val)
 
@@ -113,7 +114,7 @@
         self.pathchain = pathchain
 
         # make the paths into loaders
-        self.loaders = map(SphinxFileSystemLoader, loaderchain)
+        self.loaders = [SphinxFileSystemLoader(x) for x in loaderchain]
 
         use_i18n = builder.app.translator is not None
         extensions = use_i18n and ['jinja2.ext.i18n'] or []
diff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py
index b76aab1..9332f47 100644
--- a/sphinx/locale/__init__.py
+++ b/sphinx/locale/__init__.py
@@ -9,12 +9,13 @@
     :license: BSD, see LICENSE for details.
 """
 
-import sys
 import gettext
-import UserString
+
+from six import PY3, text_type
+from six.moves import UserString
 
 
-class _TranslationProxy(UserString.UserString, object):
+class _TranslationProxy(UserString, object):
     """
     Class for proxy strings from gettext translations.  This is a helper for the
     lazy_* functions from this module.
@@ -32,7 +33,7 @@
     def __new__(cls, func, *args):
         if not args:
             # not called with "function" and "arguments", but a plain string
-            return unicode(func)
+            return text_type(func)
         return object.__new__(cls)
 
     def __getnewargs__(self):
@@ -59,11 +60,12 @@
     def __contains__(self, key):
         return key in self.data
 
-    def __nonzero__(self):
+    def __bool__(self):
         return bool(self.data)
+    __nonzero__ = __bool__  # for python2 compatibility
 
     def __dir__(self):
-        return dir(unicode)
+        return dir(text_type)
 
     def __iter__(self):
         return iter(self.data)
@@ -75,7 +77,7 @@
         return str(self.data)
 
     def __unicode__(self):
-        return unicode(self.data)
+        return text_type(self.data)
 
     def __add__(self, other):
         return self.data + other
@@ -132,7 +134,7 @@
 
     def __repr__(self):
         try:
-            return 'i' + repr(unicode(self.data))
+            return 'i' + repr(text_type(self.data))
         except:
             return '<%s broken>' % self.__class__.__name__
 
@@ -183,7 +185,7 @@
 
 translators = {}
 
-if sys.version_info >= (3, 0):
+if PY3:
     def _(message):
         return translators['sphinx'].gettext(message)
 else:
diff --git a/sphinx/make_mode.py b/sphinx/make_mode.py
index b4b5b74..feca51e 100644
--- a/sphinx/make_mode.py
+++ b/sphinx/make_mode.py
@@ -14,6 +14,7 @@
     :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
     :license: BSD, see LICENSE for details.
 """
+from __future__ import print_function
 
 import os
 import sys
@@ -69,92 +70,93 @@
         if not path.exists(self.builddir):
             return
         elif not path.isdir(self.builddir):
-            print "Error: %r is not a directory!" % self.builddir
+            print("Error: %r is not a directory!" % self.builddir)
             return 1
-        print "Removing everything under %r..." % self.builddir
+        print("Removing everything under %r..." % self.builddir)
         for item in os.listdir(self.builddir):
             shutil.rmtree(self.builddir_join(item))
 
     def build_help(self):
-        print bold("Sphinx v%s" % sphinx.__version__)
-        print "Please use `make %s' where %s is one of" % ((blue('target'),)*2)
+        print(bold("Sphinx v%s" % sphinx.__version__))
+        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)
+                print('  %s  %s' % (blue(bname.ljust(10)), description))
 
     def build_html(self):
         if self.run_generic_build('html') > 0:
             return 1
-        print
-        print 'Build finished. The HTML pages are in %s.' % self.builddir_join('html')
+        print()
+        print('Build finished. The HTML pages are in %s.' % self.builddir_join('html'))
 
     def build_dirhtml(self):
         if self.run_generic_build('dirhtml') > 0:
             return 1
-        print
-        print 'Build finished. The HTML pages are in %s.' % self.builddir_join('dirhtml')
+        print()
+        print('Build finished. The HTML pages are in %s.' %
+              self.builddir_join('dirhtml'))
 
     def build_singlehtml(self):
         if self.run_generic_build('singlehtml') > 0:
             return 1
-        print
-        print 'Build finished. The HTML page is in %s.' % \
-            self.builddir_join('singlehtml')
+        print()
+        print('Build finished. The HTML page is in %s.' %
+              self.builddir_join('singlehtml'))
 
     def build_pickle(self):
         if self.run_generic_build('pickle') > 0:
             return 1
-        print
-        print 'Build finished; now you can process the pickle files.'
+        print()
+        print('Build finished; now you can process the pickle files.')
 
     def build_json(self):
         if self.run_generic_build('json') > 0:
             return 1
-        print
-        print 'Build finished; now you can process the JSON files.'
+        print()
+        print('Build finished; now you can process the JSON files.')
 
     def build_htmlhelp(self):
         if self.run_generic_build('htmlhelp') > 0:
             return 1
-        print
-        print ('Build finished; now you can run HTML Help Workshop with the '
-               '.hhp project file in %s.') % self.builddir_join('htmlhelp')
+        print()
+        print('Build finished; now you can run HTML Help Workshop with the '
+              '.hhp project file in %s.' % self.builddir_join('htmlhelp'))
 
     def build_qthelp(self):
         if self.run_generic_build('qthelp') > 0:
             return 1
-        print
-        print ('Build finished; now you can run "qcollectiongenerator" with the '
-               '.qhcp project file in %s, like this:') % self.builddir_join('qthelp')
-        print '$ qcollectiongenerator %s.qhcp' % self.builddir_join('qthelp', proj_name)
-        print 'To view the help file:'
-        print '$ assistant -collectionFile %s.qhc' % \
-            self.builddir_join('qthelp', proj_name)
+        print()
+        print('Build finished; now you can run "qcollectiongenerator" with the '
+              '.qhcp project file in %s, like this:' % self.builddir_join('qthelp'))
+        print('$ qcollectiongenerator %s.qhcp' % self.builddir_join('qthelp', proj_name))
+        print('To view the help file:')
+        print('$ assistant -collectionFile %s.qhc' %
+              self.builddir_join('qthelp', proj_name))
 
     def build_devhelp(self):
         if self.run_generic_build('devhelp') > 0:
             return 1
-        print
-        print "Build finished."
-        print "To view the help file:"
-        print "$ mkdir -p $HOME/.local/share/devhelp/" + proj_name
-        print "$ ln -s %s $HOME/.local/share/devhelp/%s" % \
-            (self.builddir_join('devhelp'), proj_name)
-        print "$ devhelp"
+        print()
+        print("Build finished.")
+        print("To view the help file:")
+        print("$ mkdir -p $HOME/.local/share/devhelp/" + proj_name)
+        print("$ ln -s %s $HOME/.local/share/devhelp/%s" %
+              (self.builddir_join('devhelp'), proj_name))
+        print("$ devhelp")
 
     def build_epub(self):
         if self.run_generic_build('epub') > 0:
             return 1
-        print
-        print 'Build finished. The ePub file is in %s.' % self.builddir_join('epub')
+        print()
+        print('Build finished. The ePub file is in %s.' % self.builddir_join('epub'))
 
     def build_latex(self):
         if self.run_generic_build('latex') > 0:
             return 1
-        print "Build finished; the LaTeX files are in %s." % self.builddir_join('latex')
+        print("Build finished; the LaTeX files are in %s." % self.builddir_join('latex'))
         if os.name == 'posix':
-            print "Run `make' in that directory to run these through (pdf)latex"
-            print "(use `make latexpdf' here to do that automatically)."
+            print("Run `make' in that directory to run these through (pdf)latex")
+            print("(use `make latexpdf' here to do that automatically).")
 
     def build_latexpdf(self):
         if self.run_generic_build('latex') > 0:
@@ -169,17 +171,17 @@
     def build_text(self):
         if self.run_generic_build('text') > 0:
             return 1
-        print
-        print 'Build finished. The text files are in %s.' % self.builddir_join('text')
+        print()
+        print('Build finished. The text files are in %s.' % self.builddir_join('text'))
 
     def build_texinfo(self):
         if self.run_generic_build('texinfo') > 0:
             return 1
-        print "Build finished; the Texinfo files are in %s." % \
-            self.builddir_join('texinfo')
+        print("Build finished; the Texinfo files are in %s." %
+              self.builddir_join('texinfo'))
         if os.name == 'posix':
-            print "Run `make' in that directory to run these through makeinfo"
-            print "(use `make info' here to do that automatically)."
+            print("Run `make' in that directory to run these through makeinfo")
+            print("(use `make info' here to do that automatically).")
 
     def build_info(self):
         if self.run_generic_build('texinfo') > 0:
@@ -190,50 +192,50 @@
         dtdir = self.builddir_join('gettext', '.doctrees')
         if self.run_generic_build('gettext', doctreedir=dtdir) > 0:
             return 1
-        print
-        print 'Build finished. The message catalogs are in %s.' % \
-            self.builddir_join('gettext')
+        print()
+        print('Build finished. The message catalogs are in %s.' %
+              self.builddir_join('gettext'))
 
     def build_changes(self):
         if self.run_generic_build('changes') > 0:
             return 1
-        print
-        print 'Build finished. The overview file is in %s.' % \
-            self.builddir_join('changes')
+        print()
+        print('Build finished. The overview file is in %s.' %
+              self.builddir_join('changes'))
 
     def build_linkcheck(self):
         res = self.run_generic_build('linkcheck')
-        print
-        print ('Link check complete; look for any errors in the above output '
-               'or in %s.') % self.builddir_join('linkcheck', 'output.txt')
+        print()
+        print('Link check complete; look for any errors in the above output '
+              'or in %s.' % self.builddir_join('linkcheck', 'output.txt'))
         return res
 
     def build_doctest(self):
         res = self.run_generic_build('doctest')
-        print ("Testing of doctests in the sources finished, look at the "
-               "results in %s." % self.builddir_join('doctest', 'output.txt'))
+        print("Testing of doctests in the sources finished, look at the "
+              "results in %s." % self.builddir_join('doctest', 'output.txt'))
         return res
 
     def build_coverage(self):
         if self.run_generic_build('coverage') > 0:
-            print "Has the coverage extension been enabled?"
+            print("Has the coverage extension been enabled?")
             return 1
-        print
-        print ("Testing of coverage in the sources finished, look at the "
-               "results in %s." % self.builddir_join('coverage'))
+        print()
+        print("Testing of coverage in the sources finished, look at the "
+              "results in %s." % self.builddir_join('coverage'))
 
     def build_xml(self):
         if self.run_generic_build('xml') > 0:
             return 1
-        print
-        print 'Build finished. The XML files are in %s.' % self.builddir_join('xml')
+        print()
+        print('Build finished. The XML files are in %s.' % self.builddir_join('xml'))
 
     def build_pseudoxml(self):
         if self.run_generic_build('pseudoxml') > 0:
             return 1
-        print
-        print 'Build finished. The pseudo-XML files are in %s.' % \
-            self.builddir_join('pseudoxml')
+        print()
+        print('Build finished. The pseudo-XML files are in %s.' %
+              self.builddir_join('pseudoxml'))
 
     def run_generic_build(self, builder, doctreedir=None):
         # compatibility with old Makefile
@@ -249,8 +251,8 @@
 
 def run_make_mode(args):
     if len(args) < 3:
-        print >>sys.stderr, ('Error: at least 3 arguments (builder, source '
-                             'dir, build dir) are required.')
+        print('Error: at least 3 arguments (builder, source '
+              'dir, build dir) are required.', file=sys.stderr)
         return 1
     make = Make(args[1], args[2], args[3:])
     run_method = 'build_' + args[0]
diff --git a/sphinx/pycode/__init__.py b/sphinx/pycode/__init__.py
index 7a6f59b..461eea0 100644
--- a/sphinx/pycode/__init__.py
+++ b/sphinx/pycode/__init__.py
@@ -8,16 +8,19 @@
     :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
     :license: BSD, see LICENSE for details.
 """
+from __future__ import print_function
 
 import sys
 from os import path
 
+from six import iteritems, text_type, BytesIO, StringIO
+
 from sphinx import package_dir
 from sphinx.errors import PycodeError
 from sphinx.pycode import nodes
 from sphinx.pycode.pgen2 import driver, token, tokenize, parse, literals
 from sphinx.util import get_module_source, detect_encoding
-from sphinx.util.pycompat import next, StringIO, BytesIO, TextIOWrapper
+from sphinx.util.pycompat import TextIOWrapper
 from sphinx.util.docstrings import prepare_docstring, prepare_commentdoc
 
 
@@ -29,9 +32,9 @@
 
 # an object with attributes corresponding to token and symbol names
 class sym: pass
-for k, v in pygrammar.symbol2number.iteritems():
+for k, v in iteritems(pygrammar.symbol2number):
     setattr(sym, k, v)
-for k, v in token.tok_name.iteritems():
+for k, v in iteritems(token.tok_name):
     setattr(sym, v, k)
 
 # a dict mapping terminal and nonterminal numbers to their names
@@ -97,7 +100,7 @@
                 continue  # skip over semicolon
             if parent[idx].type == sym.NEWLINE:
                 prefix = parent[idx].get_prefix()
-                if not isinstance(prefix, unicode):
+                if not isinstance(prefix, text_type):
                     prefix = prefix.decode(self.encoding)
                 docstring = prepare_commentdoc(prefix)
                 if docstring:
@@ -115,7 +118,7 @@
             if not pnode or pnode.type not in (token.INDENT, token.DEDENT):
                 break
             prefix = pnode.get_prefix()
-        if not isinstance(prefix, unicode):
+        if not isinstance(prefix, text_type):
             prefix = prefix.decode(self.encoding)
         docstring = prepare_commentdoc(prefix)
         self.add_docstring(node, docstring)
@@ -182,7 +185,7 @@
             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 +205,7 @@
                 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 +248,7 @@
             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 +259,7 @@
         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=''):
@@ -338,10 +341,10 @@
     x1 = time.time()
     ma.parse()
     x2 = time.time()
-    #for (ns, name), doc in ma.find_attr_docs().iteritems():
+    #for (ns, name), doc in iteritems(ma.find_attr_docs()):
     #    print '>>', ns, name
     #    print '\n'.join(doc)
     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 422671d..c531edb 100644
--- a/sphinx/pycode/pgen2/driver.py
+++ b/sphinx/pycode/pgen2/driver.py
@@ -131,7 +131,7 @@
             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 01d8434..91874fa 100644
--- a/sphinx/pycode/pgen2/grammar.py
+++ b/sphinx/pycode/pgen2/grammar.py
@@ -11,6 +11,7 @@
 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 @@
     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 d489370..25e09b6 100644
--- a/sphinx/pycode/pgen2/literals.py
+++ b/sphinx/pycode/pgen2/literals.py
@@ -4,9 +4,13 @@
 # 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
 
+from six import text_type
+
+
 simple_escapes = {"a": "\a",
                   "b": "\b",
                   "f": "\f",
@@ -66,7 +70,7 @@
 def evalString(s, encoding=None):
     regex = escape_re
     repl = escape
-    if encoding and not isinstance(s, unicode):
+    if encoding and not isinstance(s, text_type):
         s = s.decode(encoding)
     if s.startswith('u') or s.startswith('U'):
         regex = uni_escape_re
@@ -89,7 +93,7 @@
         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/parse.c b/sphinx/pycode/pgen2/parse.c
index e09f505..96fa6c8 100644
--- a/sphinx/pycode/pgen2/parse.c
+++ b/sphinx/pycode/pgen2/parse.c
@@ -353,95 +353,6 @@
 
 static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],     PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,     const char* function_name); /*proto*/
 
-#if PY_VERSION_HEX < 0x02050000
-#ifndef PyAnySet_CheckExact
-
-#define PyAnySet_CheckExact(ob) \
-    ((ob)->ob_type == &PySet_Type || \
-     (ob)->ob_type == &PyFrozenSet_Type)
-
-#define PySet_New(iterable) \
-    PyObject_CallFunctionObjArgs((PyObject *)&PySet_Type, (iterable), NULL)
-
-#define Pyx_PyFrozenSet_New(iterable) \
-    PyObject_CallFunctionObjArgs((PyObject *)&PyFrozenSet_Type, (iterable), NULL)
-
-#define PySet_Size(anyset) \
-    PyObject_Size((anyset))
-
-#define PySet_Contains(anyset, key) \
-    PySequence_Contains((anyset), (key))
-
-#define PySet_Pop(set) \
-    PyObject_CallMethod(set, (char *)"pop", NULL)
-
-static INLINE int PySet_Clear(PyObject *set) {
-    PyObject *ret = PyObject_CallMethod(set, (char *)"clear", NULL);
-    if (!ret) return -1;
-    Py_DECREF(ret); return 0;
-}
-
-static INLINE int PySet_Discard(PyObject *set, PyObject *key) {
-    PyObject *ret = PyObject_CallMethod(set, (char *)"discard", (char *)"O", key);
-    if (!ret) return -1;
-    Py_DECREF(ret); return 0;
-}
-
-static INLINE int PySet_Add(PyObject *set, PyObject *key) {
-    PyObject *ret = PyObject_CallMethod(set, (char *)"add", (char *)"O", key);
-    if (!ret) return -1;
-    Py_DECREF(ret); return 0;
-}
-
-#endif /* PyAnySet_CheckExact (<= Py2.4) */
-
-#if PY_VERSION_HEX < 0x02040000
-#ifndef Py_SETOBJECT_H
-#define Py_SETOBJECT_H
-
-static PyTypeObject *__Pyx_PySet_Type = NULL;
-static PyTypeObject *__Pyx_PyFrozenSet_Type = NULL;
-
-#define PySet_Type (*__Pyx_PySet_Type)
-#define PyFrozenSet_Type (*__Pyx_PyFrozenSet_Type)
-
-#define PyAnySet_Check(ob) \
-    (PyAnySet_CheckExact(ob) || \
-     PyType_IsSubtype((ob)->ob_type, &PySet_Type) || \
-     PyType_IsSubtype((ob)->ob_type, &PyFrozenSet_Type))
-
-#define PyFrozenSet_CheckExact(ob) ((ob)->ob_type == &PyFrozenSet_Type)
-
-static int __Pyx_Py23SetsImport(void) {
-    PyObject *sets=0, *Set=0, *ImmutableSet=0;
-
-    sets = PyImport_ImportModule((char *)"sets");
-    if (!sets) goto bad;
-    Set = PyObject_GetAttrString(sets, (char *)"Set");
-    if (!Set) goto bad;
-    ImmutableSet = PyObject_GetAttrString(sets, (char *)"ImmutableSet");
-    if (!ImmutableSet) goto bad;
-    Py_DECREF(sets);
-
-    __Pyx_PySet_Type       = (PyTypeObject*) Set;
-    __Pyx_PyFrozenSet_Type = (PyTypeObject*) ImmutableSet;
-
-    return 0;
-
- bad:
-    Py_XDECREF(sets);
-    Py_XDECREF(Set);
-    Py_XDECREF(ImmutableSet);
-    return -1;
-}
-
-#else
-static int __Pyx_Py23SetsImport(void) { return 0; }
-#endif /* !Py_SETOBJECT_H */
-#endif /* < Py2.4  */
-#endif /* < Py2.5  */
-
-
 static INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) {
     PyObject *r;
     if (!j) return NULL;
diff --git a/sphinx/pycode/pgen2/pgen.py b/sphinx/pycode/pgen2/pgen.py
index 0a04447..e199ed8 100644
--- a/sphinx/pycode/pgen2/pgen.py
+++ b/sphinx/pycode/pgen2/pgen.py
@@ -1,7 +1,12 @@
 # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
 # Licensed to PSF under a Contributor Agreement.
 
+from __future__ import print_function
+
+from six import iteritems
+
 # Pgen imports
+
 from sphinx.pycode.pgen2 import grammar, token, tokenize
 
 class PgenGrammar(grammar.Grammar):
@@ -26,7 +31,7 @@
 
     def make_grammar(self):
         c = PgenGrammar()
-        names = self.dfas.keys()
+        names = list(self.dfas.keys())
         names.sort()
         names.remove(self.startsymbol)
         names.insert(0, self.startsymbol)
@@ -39,7 +44,7 @@
             states = []
             for state in dfa:
                 arcs = []
-                for label, next in state.arcs.iteritems():
+                for label, next in iteritems(state.arcs):
                     arcs.append((self.make_label(c, label), dfa.index(next)))
                 if state.isfinal:
                     arcs.append((0, dfa.index(state)))
@@ -105,7 +110,7 @@
                     return ilabel
 
     def addfirstsets(self):
-        names = self.dfas.keys()
+        names = list(self.dfas.keys())
         names.sort()
         for name in names:
             if name not in self.first:
@@ -118,7 +123,7 @@
         state = dfa[0]
         totalset = {}
         overlapcheck = {}
-        for label, next in state.arcs.iteritems():
+        for label, next in iteritems(state.arcs):
             if label in self.dfas:
                 if label in self.first:
                     fset = self.first[label]
@@ -133,7 +138,7 @@
                 totalset[label] = 1
                 overlapcheck[label] = {label: 1}
         inverse = {}
-        for label, itsfirst in overlapcheck.iteritems():
+        for label, itsfirst in iteritems(overlapcheck):
             for symbol in itsfirst:
                 if symbol in inverse:
                     raise ValueError("rule %s is ambiguous; %s is in the"
@@ -192,7 +197,7 @@
                 for label, next in nfastate.arcs:
                     if label is not None:
                         addclosure(next, arcs.setdefault(label, {}))
-            for label, nfaset in arcs.iteritems():
+            for label, nfaset in iteritems(arcs):
                 for st in states:
                     if st.nfaset == nfaset:
                         break
@@ -203,10 +208,10 @@
         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 +219,16 @@
                     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 ""
-            for label, next in state.arcs.iteritems():
-                print "    %s -> %d" % (label, dfa.index(next))
+            print("  State", i, state.isfinal and "(final)" or "")
+            for label, next in iteritems(state.arcs):
+                print("    %s -> %d" % (label, dfa.index(next)))
 
     def simplify_dfa(self, dfa):
         # This is not theoretically optimal, but works well enough.
@@ -319,9 +324,9 @@
         return value
 
     def gettoken(self):
-        tup = self.generator.next()
+        tup = next(self.generator)
         while tup[0] in (tokenize.COMMENT, tokenize.NL):
-            tup = self.generator.next()
+            tup = next(self.generator)
         self.type, self.value, self.begin, self.end, self.line = tup
         #print token.tok_name[self.type], repr(self.value)
 
@@ -330,7 +335,7 @@
             try:
                 msg = msg % args
             except:
-                msg = " ".join([msg] + map(str, args))
+                msg = " ".join([msg] + [str(x) for x in args])
         raise SyntaxError(msg, (self.filename, self.end[0],
                                 self.end[1], self.line))
 
@@ -348,7 +353,7 @@
 
     def __init__(self, nfaset, final):
         assert isinstance(nfaset, dict)
-        assert isinstance(iter(nfaset).next(), NFAState)
+        assert isinstance(next(iter(nfaset)), NFAState)
         assert isinstance(final, NFAState)
         self.nfaset = nfaset
         self.isfinal = final in nfaset
@@ -361,7 +366,7 @@
         self.arcs[label] = next
 
     def unifystate(self, old, new):
-        for label, next in self.arcs.iteritems():
+        for label, next in iteritems(self.arcs):
             if next is old:
                 self.arcs[label] = new
 
@@ -374,7 +379,7 @@
         # would invoke this method recursively, with cycles...
         if len(self.arcs) != len(other.arcs):
             return False
-        for label, next in self.arcs.iteritems():
+        for label, next in iteritems(self.arcs):
             if next is not other.arcs.get(label):
                 return False
         return True
diff --git a/sphinx/pycode/pgen2/token.py b/sphinx/pycode/pgen2/token.py
index 56a40ce..55bf5e8 100755
--- a/sphinx/pycode/pgen2/token.py
+++ b/sphinx/pycode/pgen2/token.py
@@ -68,7 +68,7 @@
 #--end constants--
 
 tok_name = {}
-for _name, _value in globals().items():
+for _name, _value in list(globals().items()):
     if type(_value) is type(0):
         tok_name[_value] = _name
 
diff --git a/sphinx/pycode/pgen2/tokenize.py b/sphinx/pycode/pgen2/tokenize.py
index 7ad9f01..d625350 100644
--- a/sphinx/pycode/pgen2/tokenize.py
+++ b/sphinx/pycode/pgen2/tokenize.py
@@ -23,13 +23,17 @@
     tokenize(readline, tokeneater=printtoken)
 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."""
+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'
 
 import string, re
+from six import PY3
 from sphinx.pycode.pgen2.token import *
 from sphinx.pycode.pgen2 import token
 
@@ -81,6 +85,9 @@
 
 Bracket = '[][(){}]'
 Special = group(r'\r?\n', r'[:;.,`@]')
+if PY3:
+    Ellipsis_ = r'\.{3}'
+    Special = group(Ellipsis_, Special)
 Funny = group(Operator, Bracket, Special)
 
 PlainToken = group(Number, Funny, String, Name)
@@ -94,8 +101,9 @@
 PseudoExtras = group(r'\\\r?\n', Comment, Triple)
 PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
 
-tokenprog, pseudoprog, single3prog, double3prog = map(
-    re.compile, (Token, PseudoToken, Single3, Double3))
+tokenprog, pseudoprog, single3prog, double3prog = [
+    re.compile(x) for x in (Token, PseudoToken, Single3, Double3)
+]
 endprogs = {"'": re.compile(Single), '"': re.compile(Double),
             "'''": single3prog, '"""': double3prog,
             "r'''": single3prog, 'r"""': double3prog,
@@ -146,8 +154,8 @@
 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):
     """
@@ -352,8 +360,9 @@
                 spos, epos, pos = (lnum, start), (lnum, end), end
                 token, initial = line[start:end], line[start]
 
-                if initial in numchars or \
-                   (initial == '.' and token != '.'):      # ordinary number
+                if initial in numchars or (
+                   initial == '.' and token not in ('.', '...')
+                   ):                                      # ordinary number
                     yield (NUMBER, token, spos, epos, line)
                 elif initial in '\r\n':
                     newline = NEWLINE
@@ -389,6 +398,8 @@
                         yield (STRING, token, spos, epos, line)
                 elif initial in namechars:                 # ordinary name
                     yield (NAME, token, spos, epos, line)
+                elif token in ('...',):                    # ordinary name
+                    yield (NAME, token, spos, epos, line)
                 elif initial == '\\':                      # continued stmt
                     # This yield is new; needed for better idempotency:
                     yield (NL, token, spos, (lnum, pos), line)
diff --git a/sphinx/quickstart.py b/sphinx/quickstart.py
index 5cf067e..fdfb810 100644
--- a/sphinx/quickstart.py
+++ b/sphinx/quickstart.py
@@ -8,12 +8,26 @@
     :copyright: Copyright 2007-2014 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
+from io import open
 
 TERM_ENCODING = getattr(sys.stdin, 'encoding', None)
 
+#try to import readline, unix specific enhancement
+try:
+    import readline
+    if readline.__doc__ and 'libedit' in readline.__doc__:
+        readline.parse_and_bind("bind ^I rl_complete")
+    else:
+        readline.parse_and_bind("tab: complete")
+except ImportError:
+    pass
+
+from six import PY2, PY3, text_type
+from six.moves import input
 from docutils.utils import column_width
 
 from sphinx import __version__
@@ -21,19 +35,14 @@
 from sphinx.util.console import purple, bold, red, turquoise, \
      nocolor, color_terminal
 from sphinx.util import texescape
-from sphinx.util.pycompat import open
 
 # function to get input from terminal -- overridden by the test suite
-try:
-    # this raw_input is not converted by 2to3
-    term_input = raw_input
-except NameError:
-    term_input = input
+term_input = input
 
 
 PROMPT_PREFIX = '> '
 
-if sys.version_info >= (3, 0):
+if PY3:
     # prevents that the file is checked for being written in Python 2.x syntax
     QUICKSTART_CONF = u'#!/usr/bin/env python3\n'
 else:
@@ -99,7 +108,10 @@
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
-#language = None
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = %(language)r
 
 # There are two options for replacing |today|: either, you set today to some
 # non-false value, then it is used:
@@ -217,10 +229,23 @@
 # This is the file name suffix for HTML files (e.g. ".xhtml").
 #html_file_suffix = None
 
+# Language to be used for generating the HTML full-text search index.
+# Sphinx supports the following languages:
+#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
+#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
+#html_search_language = 'en'
+
+# A dictionary with options for the search language support, empty by default.
+# Now only 'ja' uses this config value
+#html_search_options = {'type': 'default'}
+
+# The name of a javascript file (relative to the configuration directory) that
+# implements a search results scorer. If empty, the default will be used.
+#html_search_scorer = 'scorer.js'
+
 # Output file base name for HTML help builder.
 htmlhelp_basename = '%(project_fn)sdoc'
 
-
 # -- Options for LaTeX output ---------------------------------------------
 
 latex_elements = {
@@ -232,6 +257,9 @@
 
 # Additional stuff for the LaTeX preamble.
 #'preamble': '',
+
+# Latex figure (float) alignment
+#'figure_align': 'htbp',
 }
 
 # Grouping the document tree into LaTeX files. List of tuples
@@ -320,7 +348,7 @@
 #epub_theme = 'epub'
 
 # The language of the text. It defaults to the language option
-# or en if the language is not set.
+# or 'en' if the language is not set.
 #epub_language = ''
 
 # The scheme of the identifier. Typical schemes are ISBN or URL.
@@ -432,7 +460,7 @@
 I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) %(rsrcdir)s
 
 .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp \
-epub latex latexpdf text man changes linkcheck doctest gettext
+epub latex latexpdf text man changes linkcheck doctest coverage gettext
 
 help:
 \t@echo "Please use \\`make <target>' where <target> is one of"
@@ -459,6 +487,7 @@
 \t@echo "  linkcheck  to check all external links for integrity"
 \t@echo "  doctest    to run all doctests embedded in the documentation \
 (if enabled)"
+\t@echo "  coverage   to run coverage check of the documentation (if enabled)"
 
 clean:
 \trm -rf $(BUILDDIR)/*
@@ -581,6 +610,11 @@
 \t@echo "Testing of doctests in the sources finished, look at the " \\
 \t      "results in $(BUILDDIR)/doctest/output.txt."
 
+coverage:
+\t$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
+\t@echo "Testing of coverage in the sources finished, look at the " \\
+\t      "results in $(BUILDDIR)/coverage/python.txt."
+
 xml:
 \t$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
 \t@echo
@@ -632,6 +666,7 @@
 \techo.  pseudoxml  to make pseudoxml-XML files for display purposes
 \techo.  linkcheck  to check all external links for integrity
 \techo.  doctest    to run all doctests embedded in the documentation if enabled
+\techo.  coverage   to run coverage check of the documentation if enabled
 \tgoto end
 )
 
@@ -642,6 +677,14 @@
 )
 
 
+REM Check if sphinx-build is available and fallback to Python version if any
+%%SPHINXBUILD%% 2> nul
+if errorlevel 9009 goto sphinx_python
+goto sphinx_ok
+
+:sphinx_python
+
+set SPHINXBUILD=python -m sphinx.__init__
 %%SPHINXBUILD%% 2> nul
 if errorlevel 9009 (
 \techo.
@@ -655,6 +698,9 @@
 \texit /b 1
 )
 
+:sphinx_ok
+
+
 if "%%1" == "html" (
 \t%%SPHINXBUILD%% -b html %%ALLSPHINXOPTS%% %%BUILDDIR%%/html
 \tif errorlevel 1 exit /b 1
@@ -818,6 +864,15 @@
 \tgoto end
 )
 
+if "%%1" == "coverage" (
+\t%%SPHINXBUILD%% -b coverage %%ALLSPHINXOPTS%% %%BUILDDIR%%/coverage
+\tif errorlevel 1 exit /b 1
+\techo.
+\techo.Testing of coverage in the sources finished, look at the ^
+results in %%BUILDDIR%%/coverage/python.txt.
+\tgoto end
+)
+
 if "%%1" == "xml" (
 \t%%SPHINXBUILD%% -b xml %%ALLSPHINXOPTS%% %%BUILDDIR%%/xml
 \tif errorlevel 1 exit /b 1
@@ -918,6 +973,7 @@
     """Raised for validation errors."""
 
 def is_path(x):
+    x = path.expanduser(x)
     if path.exists(x) and not path.isdir(x):
         raise ValidationError("Please enter a valid path name.")
     return x
@@ -955,16 +1011,16 @@
             prompt = PROMPT_PREFIX + '%s [%s]: ' % (text, default)
         else:
             prompt = PROMPT_PREFIX + text + ': '
-        if sys.version_info < (3, 0):
+        if PY2:
             # for Python 2.x, try to get a Unicode string out of it
             if prompt.encode('ascii', 'replace').decode('ascii', 'replace') \
                     != prompt:
                 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:
@@ -973,29 +1029,29 @@
         x = term_input(prompt).strip()
         if default and not x:
             x = default
-        if not isinstance(x, unicode):
+        if not isinstance(x, text_type):
             # for Python 2.x, try to get a Unicode string out of it
             if x.decode('ascii', 'replace').encode('ascii', 'replace') != x:
                 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
 
 
-if sys.version_info >= (3, 0):
+if PY3:
     # remove Unicode literal prefixes
     def _convert_python_source(source, rex=re.compile(r"[uU]('.*?')")):
         return rex.sub('\\1', source)
@@ -1018,6 +1074,7 @@
     * author:    author names
     * version:   version of project
     * release:   release of project
+    * language:  document language
     * suffix:    source file suffix
     * master:    master document name
     * epub:      use epub (bool)
@@ -1026,98 +1083,110 @@
     * 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('''
+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.''')
+        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:
@@ -1139,8 +1208,8 @@
         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.''')
         d['ext_pngmath'] = False
     if 'ext_ifconfig' not in d:
         do_prompt(d, 'ext_ifconfig', 'ifconfig: conditional inclusion of '
@@ -1150,15 +1219,15 @@
                   '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):
@@ -1186,10 +1255,10 @@
     else:
         d['extensions'] = extensions
     d['copyright'] = time.strftime('%Y') + ', ' + d['author']
-    d['author_texescaped'] = unicode(d['author']).\
+    d['author_texescaped'] = text_type(d['author']).\
                              translate(texescape.tex_escape_map)
     d['project_doc'] = d['project'] + ' Documentation'
-    d['project_doc_texescaped'] = unicode(d['project'] + ' Documentation').\
+    d['project_doc_texescaped'] = text_type(d['project'] + ' Documentation').\
                                   translate(texescape.tex_escape_map)
 
     # escape backslashes and single quotes in strings that are put into
@@ -1217,14 +1286,14 @@
 
     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']:
@@ -1250,9 +1319,9 @@
 
     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:
@@ -1262,7 +1331,7 @@
    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):
@@ -1271,14 +1340,18 @@
 
     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)
+
+
+if __name__ == '__main__':
+    sys.exit(main(sys.argv))
diff --git a/sphinx/roles.py b/sphinx/roles.py
index c31ec05..aaf6272 100644
--- a/sphinx/roles.py
+++ b/sphinx/roles.py
@@ -11,6 +11,7 @@
 
 import re
 
+from six import iteritems
 from docutils import nodes, utils
 from docutils.parsers.rst import roles
 
@@ -22,19 +23,19 @@
 
 
 generic_docroles = {
-    'command' : nodes.strong,
+    'command' : addnodes.literal_strong,
     'dfn' : nodes.emphasis,
     'kbd' : nodes.literal,
     'mailheader' : addnodes.literal_emphasis,
-    'makevar' : nodes.strong,
+    'makevar' : addnodes.literal_strong,
     'manpage' : addnodes.literal_emphasis,
     'mimetype' : addnodes.literal_emphasis,
     'newsgroup' : addnodes.literal_emphasis,
-    'program' : nodes.strong,  # XXX should be an x-ref
+    'program' : addnodes.literal_strong,  # XXX should be an x-ref
     'regexp' : nodes.literal,
 }
 
-for rolename, nodeclass in generic_docroles.iteritems():
+for rolename, nodeclass in iteritems(generic_docroles):
     generic = roles.GenericRole(rolename, nodeclass)
     role = roles.CustomRole(rolename, generic, {'classes': [rolename]})
     roles.register_local_role(rolename, role)
@@ -157,7 +158,7 @@
         return [node], []
 
 
-def indexmarkup_role(typ, rawtext, etext, lineno, inliner,
+def indexmarkup_role(typ, rawtext, text, lineno, inliner,
                      options={}, content=[]):
     """Role for PEP/RFC references that generate an index entry."""
     env = inliner.document.settings.env
@@ -165,47 +166,53 @@
         typ = env.config.default_role
     else:
         typ = typ.lower()
-    text = utils.unescape(etext)
+    has_explicit_title, title, target = split_explicit_title(text)
+    title = utils.unescape(title)
+    target = utils.unescape(target)
     targetid = 'index-%s' % env.new_serialno('index')
     indexnode = addnodes.index()
     targetnode = nodes.target('', '', ids=[targetid])
     inliner.document.note_explicit_target(targetnode)
     if typ == 'pep':
         indexnode['entries'] = [
-            ('single', _('Python Enhancement Proposals; PEP %s') % text,
+            ('single', _('Python Enhancement Proposals; PEP %s') % target,
              targetid, '')]
         anchor = ''
-        anchorindex = text.find('#')
+        anchorindex = target.find('#')
         if anchorindex > 0:
-            text, anchor = text[:anchorindex], text[anchorindex:]
+            target, anchor = target[:anchorindex], target[anchorindex:]
+        if not has_explicit_title:
+            title = "PEP " + utils.unescape(title)
         try:
-            pepnum = int(text)
+            pepnum = int(target)
         except ValueError:
-            msg = inliner.reporter.error('invalid PEP number %s' % text,
+            msg = inliner.reporter.error('invalid PEP number %s' % target,
                                          line=lineno)
             prb = inliner.problematic(rawtext, rawtext, msg)
             return [prb], [msg]
         ref = inliner.document.settings.pep_base_url + 'pep-%04d' % pepnum
-        sn = nodes.strong('PEP '+text, 'PEP '+text)
+        sn = nodes.strong(title, title)
         rn = nodes.reference('', '', internal=False, refuri=ref+anchor,
                              classes=[typ])
         rn += sn
         return [indexnode, targetnode, rn], []
     elif typ == 'rfc':
-        indexnode['entries'] = [('single', 'RFC; RFC %s' % text, targetid, '')]
+        indexnode['entries'] = [('single', 'RFC; RFC %s' % target, targetid, '')]
         anchor = ''
-        anchorindex = text.find('#')
+        anchorindex = target.find('#')
         if anchorindex > 0:
-            text, anchor = text[:anchorindex], text[anchorindex:]
+            target, anchor = target[:anchorindex], target[anchorindex:]
+        if not has_explicit_title:
+            title = "RFC " + utils.unescape(title)
         try:
-            rfcnum = int(text)
+            rfcnum = int(target)
         except ValueError:
-            msg = inliner.reporter.error('invalid RFC number %s' % text,
+            msg = inliner.reporter.error('invalid RFC number %s' % target,
                                          line=lineno)
             prb = inliner.problematic(rawtext, rawtext, msg)
             return [prb], [msg]
         ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum
-        sn = nodes.strong('RFC '+text, 'RFC '+text)
+        sn = nodes.strong(title, title)
         rn = nodes.reference('', '', internal=False, refuri=ref+anchor,
                              classes=[typ])
         rn += sn
@@ -263,10 +270,12 @@
     text = utils.unescape(text)
     m = _abbr_re.search(text)
     if m is None:
-        return [addnodes.abbreviation(text, text)], []
+        return [addnodes.abbreviation(text, text, **options)], []
     abbr = text[:m.start()].strip()
     expl = m.group(1)
-    return [addnodes.abbreviation(abbr, abbr, explanation=expl)], []
+    options = options.copy()
+    options['explanation'] = expl
+    return [addnodes.abbreviation(abbr, abbr, **options)], []
 
 
 def index_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
@@ -313,5 +322,5 @@
     'index': index_role,
 }
 
-for rolename, func in specific_docroles.iteritems():
+for rolename, func in iteritems(specific_docroles):
     roles.register_local_role(rolename, func)
diff --git a/sphinx/search/__init__.py b/sphinx/search/__init__.py
index bd95ecc..b81e08b 100644
--- a/sphinx/search/__init__.py
+++ b/sphinx/search/__init__.py
@@ -9,9 +9,11 @@
     :license: BSD, see LICENSE for details.
 """
 from __future__ import with_statement
-import re
-import cPickle as pickle
 
+import re
+
+from six import iteritems, itervalues, text_type, string_types
+from six.moves import cPickle as pickle
 from docutils.nodes import raw, comment, title, Text, NodeVisitor, SkipNode
 
 from sphinx.util import jsdump, rpartition
@@ -40,6 +42,7 @@
        type, before searching index. Default implementation does nothing.
     """
     lang = None
+    language_name = None
     stopwords = set()
     js_stemmer_code = """
 /**
@@ -89,16 +92,49 @@
         Return true if the target word should be registered in the search index.
         This method is called after stemming.
         """
-        return not (((len(word) < 3) and (12353 < ord(word[0]) < 12436)) or
-            (ord(word[0]) < 256 and (len(word) < 3 or word in self.stopwords or
-                                     word.isdigit())))
+        return (
+            len(word) == 0 or not (
+                ((len(word) < 3) and (12353 < ord(word[0]) < 12436)) or
+                (ord(word[0]) < 256 and (
+                    len(word) < 3 or word in self.stopwords or word.isdigit()
+                ))))
 
 
-from sphinx.search import en, ja
+# SearchEnglish imported after SearchLanguage is defined due to circular import
+from sphinx.search.en import SearchEnglish
 
+
+def parse_stop_word(source):
+    """
+    parse snowball style word list like this:
+
+    * http://snowball.tartarus.org/algorithms/finnish/stop.txt
+    """
+    result = set()
+    for line in source.splitlines():
+        line = line.split('|')[0] # remove comment
+        result.update(line.split())
+    return result
+
+
+# maps language name to module.class or directly a class
 languages = {
-    'en': en.SearchEnglish,
-    'ja': ja.SearchJapanese,
+    'da': 'sphinx.search.da.SearchDanish',
+    'de': 'sphinx.search.de.SearchGerman',
+    'en': SearchEnglish,
+    'es': 'sphinx.search.es.SearchSpanish',
+    'fi': 'sphinx.search.fi.SearchFinnish',
+    'fr': 'sphinx.search.fr.SearchFrench',
+    'hu': 'sphinx.search.hu.SearchHungarian',
+    'it': 'sphinx.search.it.SearchItalian',
+    'ja': 'sphinx.search.ja.SearchJapanese',
+    'nl': 'sphinx.search.nl.SearchDutch',
+    'no': 'sphinx.search.no.SearchNorwegian',
+    'pt': 'sphinx.search.pt.SearchPortuguese',
+    'ro': 'sphinx.search.ro.SearchRomanian',
+    'ru': 'sphinx.search.ru.SearchRussian',
+    'sv': 'sphinx.search.sv.SearchSwedish',
+    'tr': 'sphinx.search.tr.SearchTurkish',
 }
 
 
@@ -185,7 +221,17 @@
         # objtype index -> (domain, type, objname (localized))
         self._objnames = {}
         # add language-specific SearchLanguage instance
-        self.lang = languages[lang](options)
+        lang_class = languages.get(lang)
+        if lang_class is None:
+            self.lang = SearchEnglish(options)
+        elif isinstance(lang_class, str):
+            module, classname = lang_class.rsplit('.', 1)
+            lang_class = getattr(__import__(module, None, None, [classname]),
+                                 classname)
+            self.lang = lang_class(options)
+        else:
+            # it's directly a class (e.g. added by app.add_search_language)
+            self.lang = lang_class(options)
 
         if scoring:
             with open(scoring, 'rb') as fp:
@@ -195,7 +241,7 @@
 
     def load(self, stream, format):
         """Reconstruct from frozen data."""
-        if isinstance(format, basestring):
+        if isinstance(format, string_types):
             format = self.formats[format]
         frozen = format.load(stream)
         # if an old index is present, we treat it as not existing.
@@ -207,7 +253,7 @@
 
         def load_terms(mapping):
             rv = {}
-            for k, v in mapping.iteritems():
+            for k, v in iteritems(mapping):
                 if isinstance(v, int):
                     rv[k] = set([index2fn[v]])
                 else:
@@ -220,7 +266,7 @@
 
     def dump(self, stream, format):
         """Dump the frozen index to a stream."""
-        if isinstance(format, basestring):
+        if isinstance(format, string_types):
             format = self.formats[format]
         format.dump(self.freeze(), stream)
 
@@ -228,7 +274,7 @@
         rv = {}
         otypes = self._objtypes
         onames = self._objnames
-        for domainname, domain in self.env.domains.iteritems():
+        for domainname, domain in iteritems(self.env.domains):
             for fullname, dispname, type, docname, anchor, prio in \
                     domain.get_objects():
                 # XXX use dispname?
@@ -247,7 +293,7 @@
                     if otype:
                         # use unicode() to fire translation proxies
                         onames[typeindex] = (domainname, type,
-                            unicode(domain.get_type_name(otype)))
+                            text_type(domain.get_type_name(otype)))
                     else:
                         onames[typeindex] = (domainname, type, type)
                 if anchor == fullname:
@@ -262,7 +308,7 @@
     def get_terms(self, fn2index):
         rvs = {}, {}
         for rv, mapping in zip(rvs, (self._mapping, self._title_mapping)):
-            for k, v in mapping.iteritems():
+            for k, v in iteritems(mapping):
                 if len(v) == 1:
                     fn, = v
                     if fn in fn2index:
@@ -273,19 +319,22 @@
 
     def freeze(self):
         """Create a usable data structure for serializing."""
-        filenames = self._titles.keys()
-        titles = self._titles.values()
+        filenames = list(self._titles.keys())
+        titles = list(self._titles.values())
         fn2index = dict((f, i) for (i, f) in enumerate(filenames))
         terms, title_terms = self.get_terms(fn2index)
 
         objects = self.get_objects(fn2index)  # populates _objtypes
         objtypes = dict((v, k[0] + ':' + k[1])
-                        for (k, v) in self._objtypes.iteritems())
+                        for (k, v) in iteritems(self._objtypes))
         objnames = self._objnames
         return dict(filenames=filenames, titles=titles, terms=terms,
                     objects=objects, objtypes=objtypes, objnames=objnames,
                     titleterms=title_terms, envversion=self.env.version)
 
+    def label(self):
+        return "%s (code: %s)" % (self.lang.language_name, self.lang.lang)
+
     def prune(self, filenames):
         """Remove data for all filenames not in the list."""
         new_titles = {}
@@ -293,9 +342,9 @@
             if filename in self._titles:
                 new_titles[filename] = self._titles[filename]
         self._titles = new_titles
-        for wordnames in self._mapping.itervalues():
+        for wordnames in itervalues(self._mapping):
             wordnames.intersection_update(filenames)
-        for wordnames in self._title_mapping.itervalues():
+        for wordnames in itervalues(self._title_mapping):
             wordnames.intersection_update(filenames)
 
     def feed(self, filename, title, doctree):
diff --git a/sphinx/search/da.py b/sphinx/search/da.py
new file mode 100644
index 0000000..755122b
--- /dev/null
+++ b/sphinx/search/da.py
@@ -0,0 +1,130 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.search.da
+    ~~~~~~~~~~~~~~~~
+
+    Danish search language: includes the JS Danish stemmer.
+
+    :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from sphinx.search import SearchLanguage, parse_stop_word
+
+import snowballstemmer
+
+danish_stopwords = parse_stop_word(u'''
+| source: http://snowball.tartarus.org/algorithms/danish/stop.txt
+og           | and
+i            | in
+jeg          | I
+det          | that (dem. pronoun)/it (pers. pronoun)
+at           | that (in front of a sentence)/to (with infinitive)
+en           | a/an
+den          | it (pers. pronoun)/that (dem. pronoun)
+til          | to/at/for/until/against/by/of/into, more
+er           | present tense of "to be"
+som          | who, as
+på           | on/upon/in/on/at/to/after/of/with/for, on
+de           | they
+med          | with/by/in, along
+han          | he
+af           | of/by/from/off/for/in/with/on, off
+for          | at/for/to/from/by/of/ago, in front/before, because
+ikke         | not
+der          | who/which, there/those
+var          | past tense of "to be"
+mig          | me/myself
+sig          | oneself/himself/herself/itself/themselves
+men          | but
+et           | a/an/one, one (number), someone/somebody/one
+har          | present tense of "to have"
+om           | round/about/for/in/a, about/around/down, if
+vi           | we
+min          | my
+havde        | past tense of "to have"
+ham          | him
+hun          | she
+nu           | now
+over         | over/above/across/by/beyond/past/on/about, over/past
+da           | then, when/as/since
+fra          | from/off/since, off, since
+du           | you
+ud           | out
+sin          | his/her/its/one's
+dem          | them
+os           | us/ourselves
+op           | up
+man          | you/one
+hans         | his
+hvor         | where
+eller        | or
+hvad         | what
+skal         | must/shall etc.
+selv         | myself/youself/herself/ourselves etc., even
+her          | here
+alle         | all/everyone/everybody etc.
+vil          | will (verb)
+blev         | past tense of "to stay/to remain/to get/to become"
+kunne        | could
+ind          | in
+når          | when
+være         | present tense of "to be"
+dog          | however/yet/after all
+noget        | something
+ville        | would
+jo           | you know/you see (adv), yes
+deres        | their/theirs
+efter        | after/behind/according to/for/by/from, later/afterwards
+ned          | down
+skulle       | should
+denne        | this
+end          | than
+dette        | this
+mit          | my/mine
+også         | also
+under        | under/beneath/below/during, below/underneath
+have         | have
+dig          | you
+anden        | other
+hende        | her
+mine         | my
+alt          | everything
+meget        | much/very, plenty of
+sit          | his, her, its, one's
+sine         | his, her, its, one's
+vor          | our
+mod          | against
+disse        | these
+hvis         | if
+din          | your/yours
+nogle        | some
+hos          | by/at
+blive        | be/become
+mange        | many
+ad           | by/through
+bliver       | present tense of "to be/to become"
+hendes       | her/hers
+været        | be
+thi          | for (conj)
+jer          | you
+sådan        | such, like this/like that
+''')
+
+js_stemmer = u"""
+var JSX={};(function(g){function j(b,e){var a=function(){};a.prototype=e.prototype;var c=new a;for(var d in b){b[d].prototype=c}}function I(c,b){for(var a in b.prototype)if(b.prototype.hasOwnProperty(a))c.prototype[a]=b.prototype[a]}function i(a,b,d){function c(a,b,c){delete a[b];a[b]=c;return c}Object.defineProperty(a,b,{get:function(){return c(a,b,d())},set:function(d){c(a,b,d)},enumerable:true,configurable:true})}function J(a,b,c){return a[b]=a[b]/c|0}var E=parseInt;var D=parseFloat;function K(a){return a!==a}var A=isFinite;var z=encodeURIComponent;var y=decodeURIComponent;var x=encodeURI;var w=decodeURI;var u=Object.prototype.toString;var C=Object.prototype.hasOwnProperty;function f(){}g.require=function(b){var a=p[b];return a!==undefined?a:null};g.profilerIsRunning=function(){return f.getResults!=null};g.getProfileResults=function(){return(f.getResults||function(){return{}})()};g.postProfileResults=function(a,b){if(f.postResults==null)throw new Error('profiler has not been turned on');return f.postResults(a,b)};g.resetProfileResults=function(){if(f.resetResults==null)throw new Error('profiler has not been turned on');return f.resetResults()};g.DEBUG=false;function t(){};j([t],Error);function b(a,b,c){this.G=a.length;this.S=a;this.V=b;this.J=c;this.I=null;this.W=null};j([b],Object);function l(){};j([l],Object);function d(){var a;var b;var c;this.F={};a=this.D='';b=this._=0;c=this.A=a.length;this.B=0;this.C=b;this.E=c};j([d],l);function v(a,b){a.D=b.D;a._=b._;a.A=b.A;a.B=b.B;a.C=b.C;a.E=b.E};function n(b,d,c,e){var a;if(b._>=b.A){return false}a=b.D.charCodeAt(b._);if(a>e||a<c){return false}a-=c;if((d[a>>>3]&1<<(a&7))===0){return false}b._++;return true};function m(b,d,c,e){var a;if(b._<=b.B){return false}a=b.D.charCodeAt(b._-1);if(a>e||a<c){return false}a-=c;if((d[a>>>3]&1<<(a&7))===0){return false}b._--;return true};function r(a,d,c,e){var b;if(a._>=a.A){return false}b=a.D.charCodeAt(a._);if(b>e||b<c){a._++;return true}b-=c;if((d[b>>>3]&1<<(b&7))===0){a._++;return true}return false};function q(a,d,c,e){var b;if(a._<=a.B){return false}b=a.D.charCodeAt(a._-1);if(b>e||b<c){a._--;return true}b-=c;if((d[b>>>3]&1<<(b&7))===0){a._--;return true}return false};function h(a,b,d){var c;if(a._-a.B<b){return false}if(a.D.slice((c=a._)-b,c)!==d){return false}a._-=b;return true};function e(d,m,p){var b;var g;var e;var n;var f;var k;var l;var i;var h;var c;var a;var j;var o;b=0;g=p;e=d._;n=d.B;f=0;k=0;l=false;while(true){i=b+(g-b>>1);h=0;c=f<k?f:k;a=m[i];for(j=a.G-1-c;j>=0;j--){if(e-c===n){h=-1;break}h=d.D.charCodeAt(e-1-c)-a.S.charCodeAt(j);if(h!==0){break}c++}if(h<0){g=i;k=c}else{b=i;f=c}if(g-b<=1){if(b>0){break}if(g===b){break}if(l){break}l=true}}while(true){a=m[b];if(f>=a.G){d._=e-a.G|0;if(a.I==null){return a.J}o=a.I(d);d._=e-a.G|0;if(o){return a.J}}b=a.V;if(b<0){return 0}}return-1};function s(a,b,d,e){var c;c=e.length-(d-b);a.D=a.D.slice(0,b)+e+a.D.slice(d);a.A+=c|0;if(a._>=d){a._+=c|0}else if(a._>b){a._=b}return c|0};function c(a,f){var b;var c;var d;var e;b=false;if((c=a.C)<0||c>(d=a.E)||d>(e=a.A)||e>a.D.length?false:true){s(a,a.C,a.E,f);b=true}return b};function o(a,f){var b;var c;var d;var e;b='';if((c=a.C)<0||c>(d=a.E)||d>(e=a.A)||e>a.D.length?false:true){b=a.D.slice(a.C,a.E)}return b};d.prototype.H=function(){return false};d.prototype.T=function(b){var a;var c;var d;var e;a=this.F['.'+b];if(a==null){c=this.D=b;d=this._=0;e=this.A=c.length;this.B=0;this.C=d;this.E=e;this.H();a=this.D;this.F['.'+b]=a}return a};d.prototype.stemWord=d.prototype.T;d.prototype.U=function(e){var d;var b;var c;var a;var f;var g;var h;d=[];for(b=0;b<e.length;b++){c=e[b];a=this.F['.'+c];if(a==null){f=this.D=c;g=this._=0;h=this.A=f.length;this.B=0;this.C=g;this.E=h;this.H();a=this.D;this.F['.'+c]=a}d.push(a)}return d};d.prototype.stemWords=d.prototype.U;function a(){d.call(this);this.I_x=0;this.I_p1=0;this.S_ch=''};j([a],d);a.prototype.K=function(a){this.I_x=a.I_x;this.I_p1=a.I_p1;this.S_ch=a.S_ch;v(this,a)};a.prototype.copy_from=a.prototype.K;a.prototype.P=function(){var g;var d;var b;var e;var c;var f;var i;var j;var k;var h;this.I_p1=j=this.A;g=i=this._;b=i+3|0;if(0>b||b>j){return false}h=this._=b;this.I_x=h;this._=g;a:while(true){d=this._;e=true;b:while(e===true){e=false;if(!n(this,a.g_v,97,248)){break b}this._=d;break a}k=this._=d;if(k>=this.A){return false}this._++}a:while(true){c=true;b:while(c===true){c=false;if(!r(this,a.g_v,97,248)){break b}break a}if(this._>=this.A){return false}this._++}this.I_p1=this._;f=true;a:while(f===true){f=false;if(!(this.I_p1<this.I_x)){break a}this.I_p1=this.I_x}return true};a.prototype.r_mark_regions=a.prototype.P;function G(b){var h;var e;var c;var f;var d;var g;var j;var k;var l;var i;b.I_p1=k=b.A;h=j=b._;c=j+3|0;if(0>c||c>k){return false}i=b._=c;b.I_x=i;b._=h;a:while(true){e=b._;f=true;b:while(f===true){f=false;if(!n(b,a.g_v,97,248)){break b}b._=e;break a}l=b._=e;if(l>=b.A){return false}b._++}a:while(true){d=true;b:while(d===true){d=false;if(!r(b,a.g_v,97,248)){break b}break a}if(b._>=b.A){return false}b._++}b.I_p1=b._;g=true;a:while(g===true){g=false;if(!(b.I_p1<b.I_x)){break a}b.I_p1=b.I_x}return true};a.prototype.O=function(){var b;var f;var d;var g;var h;var i;f=this.A-(g=this._);if(g<this.I_p1){return false}h=this._=this.I_p1;d=this.B;this.B=h;i=this._=this.A-f;this.E=i;b=e(this,a.a_0,32);if(b===0){this.B=d;return false}this.C=this._;this.B=d;switch(b){case 0:return false;case 1:if(!c(this,'')){return false}break;case 2:if(!m(this,a.g_s_ending,97,229)){return false}if(!c(this,'')){return false}break}return true};a.prototype.r_main_suffix=a.prototype.O;function H(b){var d;var g;var f;var h;var i;var j;g=b.A-(h=b._);if(h<b.I_p1){return false}i=b._=b.I_p1;f=b.B;b.B=i;j=b._=b.A-g;b.E=j;d=e(b,a.a_0,32);if(d===0){b.B=f;return false}b.C=b._;b.B=f;switch(d){case 0:return false;case 1:if(!c(b,'')){return false}break;case 2:if(!m(b,a.g_s_ending,97,229)){return false}if(!c(b,'')){return false}break}return true};a.prototype.N=function(){var f;var g;var b;var h;var d;var i;var j;var k;var l;f=(h=this.A)-(d=this._);g=h-d;if(d<this.I_p1){return false}i=this._=this.I_p1;b=this.B;this.B=i;j=this._=this.A-g;this.E=j;if(e(this,a.a_1,4)===0){this.B=b;return false}this.C=this._;l=this.B=b;k=this._=this.A-f;if(k<=l){return false}this._--;this.C=this._;return!c(this,'')?false:true};a.prototype.r_consonant_pair=a.prototype.N;function k(b){var i;var j;var d;var g;var f;var k;var l;var m;var h;i=(g=b.A)-(f=b._);j=g-f;if(f<b.I_p1){return false}k=b._=b.I_p1;d=b.B;b.B=k;l=b._=b.A-j;b.E=l;if(e(b,a.a_1,4)===0){b.B=d;return false}b.C=b._;h=b.B=d;m=b._=b.A-i;if(m<=h){return false}b._--;b.C=b._;return!c(b,'')?false:true};a.prototype.Q=function(){var f;var l;var m;var d;var j;var b;var g;var n;var i;var p;var o;l=this.A-this._;b=true;a:while(b===true){b=false;this.E=this._;if(!h(this,2,'st')){break a}this.C=this._;if(!h(this,2,'ig')){break a}if(!c(this,'')){return false}}i=this._=(n=this.A)-l;m=n-i;if(i<this.I_p1){return false}p=this._=this.I_p1;d=this.B;this.B=p;o=this._=this.A-m;this.E=o;f=e(this,a.a_2,5);if(f===0){this.B=d;return false}this.C=this._;this.B=d;switch(f){case 0:return false;case 1:if(!c(this,'')){return false}j=this.A-this._;g=true;a:while(g===true){g=false;if(!k(this)){break a}}this._=this.A-j;break;case 2:if(!c(this,'løs')){return false}break}return true};a.prototype.r_other_suffix=a.prototype.Q;function F(b){var d;var p;var m;var f;var l;var g;var i;var o;var j;var q;var n;p=b.A-b._;g=true;a:while(g===true){g=false;b.E=b._;if(!h(b,2,'st')){break a}b.C=b._;if(!h(b,2,'ig')){break a}if(!c(b,'')){return false}}j=b._=(o=b.A)-p;m=o-j;if(j<b.I_p1){return false}q=b._=b.I_p1;f=b.B;b.B=q;n=b._=b.A-m;b.E=n;d=e(b,a.a_2,5);if(d===0){b.B=f;return false}b.C=b._;b.B=f;switch(d){case 0:return false;case 1:if(!c(b,'')){return false}l=b.A-b._;i=true;a:while(i===true){i=false;if(!k(b)){break a}}b._=b.A-l;break;case 2:if(!c(b,'løs')){return false}break}return true};a.prototype.R=function(){var e;var b;var d;var f;var g;var i;var j;e=this.A-(f=this._);if(f<this.I_p1){return false}g=this._=this.I_p1;b=this.B;this.B=g;i=this._=this.A-e;this.E=i;if(!q(this,a.g_v,97,248)){this.B=b;return false}this.C=this._;j=this.S_ch=o(this,this.S_ch);if(j===''){return false}this.B=b;return!(d=this.S_ch,h(this,d.length,d))?false:!c(this,'')?false:true};a.prototype.r_undouble=a.prototype.R;function B(b){var f;var d;var e;var g;var i;var j;var k;f=b.A-(g=b._);if(g<b.I_p1){return false}i=b._=b.I_p1;d=b.B;b.B=i;j=b._=b.A-f;b.E=j;if(!q(b,a.g_v,97,248)){b.B=d;return false}b.C=b._;k=b.S_ch=o(b,b.S_ch);if(k===''){return false}b.B=d;return!(e=b.S_ch,h(b,e.length,e))?false:!c(b,'')?false:true};a.prototype.H=function(){var i;var g;var h;var j;var b;var c;var d;var a;var e;var l;var m;var n;var o;var p;var q;var f;i=this._;b=true;a:while(b===true){b=false;if(!G(this)){break a}}l=this._=i;this.B=l;n=this._=m=this.A;g=m-n;c=true;a:while(c===true){c=false;if(!H(this)){break a}}p=this._=(o=this.A)-g;h=o-p;d=true;a:while(d===true){d=false;if(!k(this)){break a}}f=this._=(q=this.A)-h;j=q-f;a=true;a:while(a===true){a=false;if(!F(this)){break a}}this._=this.A-j;e=true;a:while(e===true){e=false;if(!B(this)){break a}}this._=this.B;return true};a.prototype.stem=a.prototype.H;a.prototype.L=function(b){return b instanceof a};a.prototype.equals=a.prototype.L;a.prototype.M=function(){var c;var a;var b;var d;c='DanishStemmer';a=0;for(b=0;b<c.length;b++){d=c.charCodeAt(b);a=(a<<5)-a+d;a=a&a}return a|0};a.prototype.hashCode=a.prototype.M;a.serialVersionUID=1;i(a,'methodObject',function(){return new a});i(a,'a_0',function(){return[new b('hed',-1,1),new b('ethed',0,1),new b('ered',-1,1),new b('e',-1,1),new b('erede',3,1),new b('ende',3,1),new b('erende',5,1),new b('ene',3,1),new b('erne',3,1),new b('ere',3,1),new b('en',-1,1),new b('heden',10,1),new b('eren',10,1),new b('er',-1,1),new b('heder',13,1),new b('erer',13,1),new b('s',-1,2),new b('heds',16,1),new b('es',16,1),new b('endes',18,1),new b('erendes',19,1),new b('enes',18,1),new b('ernes',18,1),new b('eres',18,1),new b('ens',16,1),new b('hedens',24,1),new b('erens',24,1),new b('ers',16,1),new b('ets',16,1),new b('erets',28,1),new b('et',-1,1),new b('eret',30,1)]});i(a,'a_1',function(){return[new b('gd',-1,-1),new b('dt',-1,-1),new b('gt',-1,-1),new b('kt',-1,-1)]});i(a,'a_2',function(){return[new b('ig',-1,1),new b('lig',0,1),new b('elig',1,1),new b('els',-1,1),new b('løst',-1,2)]});i(a,'g_v',function(){return[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,48,0,128]});i(a,'g_s_ending',function(){return[239,254,42,3,0,0,0,0,0,0,0,0,0,0,0,0,16]});var p={'src/stemmer.jsx':{Stemmer:l},'src/danish-stemmer.jsx':{DanishStemmer:a}}}(JSX))
+var Stemmer = JSX.require("src/danish-stemmer.jsx").DanishStemmer;
+"""
+
+
+class SearchDanish(SearchLanguage):
+    lang = 'da'
+    language_name = 'Danish'
+    js_stemmer_code = js_stemmer
+    stopwords = danish_stopwords
+
+    def init(self, options):
+        self.stemmer = snowballstemmer.stemmer('danish')
+
+    def stem(self, word):
+        return self.stemmer.stemWord(word)
diff --git a/sphinx/search/de.py b/sphinx/search/de.py
new file mode 100644
index 0000000..b46c7dd
--- /dev/null
+++ b/sphinx/search/de.py
@@ -0,0 +1,313 @@
+# -*- coding: utf-8 -*-
+"""
+    sphinx.search.de
+    ~~~~~~~~~~~~~~~~
+
+    German search language: includes the JS German stemmer.
+
+    :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+from sphinx.search import SearchLanguage, parse_stop_word
+
+import snowballstemmer
+
+german_stopwords = parse_stop_word(u'''
+|source: http://snowball.tartarus.org/algorithms/german/stop.txt
+aber           |  but
+
+alle           |  all
+allem
+allen
+aller
+alles
+
+als            |  than, as
+also           |  so
+am             |  an + dem
+an             |  at
+
+ander          |  other
+andere
+anderem
+anderen
+anderer
+anderes
+anderm
+andern
+anderr
+anders
+
+auch           |  also
+auf            |  on
+aus            |  out of
+bei            |  by
+bin            |  am
+bis            |  until
+bist           |  art
+da             |  there
+damit          |  with it
+dann           |  then
+
+der            |  the
+den
+des
+dem
+die
+das
+
+daß            |  that
+
+derselbe       |  the same
+derselben
+denselben
+desselben
+demselben
+dieselbe
+dieselben
+dasselbe
+
+dazu           |  to that
+
+dein           |  thy
+deine
+deinem
+deinen
+deiner
+deines
+
+denn           |  because
+
+derer          |  of those
+dessen         |  of him
+
+dich           |  thee
+dir            |  to thee
+du             |  thou
+
+dies           |  this
+diese
+diesem
+diesen
+dieser
+dieses
+
+
+doch           |  (several meanings)
+dort           |  (over) there
+
+
+durch          |  through
+
+ein            |  a
+eine
+einem
+einen
+einer
+eines
+
+einig          |  some
+einige
+einigem
+einigen
+einiger
+einiges
+
+einmal         |  once
+
+er             |  he
+ihn            |  him
+ihm            |  to him
+
+es             |  it
+etwas          |  something
+
+euer           |  your
+eure
+eurem
+euren
+eurer
+eures
+
+für            |  for
+gegen          |  towards
+gewesen        |  p.p. of sein
+hab            |  have
+habe           |  have
+haben          |  have
+hat            |  has
+hatte          |  had
+hatten         |  had
+hier           |  here
+hin            |  there
+hinter         |  behind
+
+ich            |  I
+mich           |  me
+mir            |  to me
+
+
+ihr            |  you, to her
+ihre
+ihrem
+ihren
+ihrer
+ihres
+euch           |  to you
+
+im             |  in + dem
+in             |  in
+indem          |  while
+ins            |  in + das
+ist            |  is
+
+jede           |  each, every
+jedem
+jeden
+jeder
+jedes
+
+jene           |  that
+jenem
+jenen
+jener
+jenes
+
+jetzt          |  now
+kann           |  can
+
+kein           |  no
+keine
+keinem
+keinen
+keiner
+keines
+
+können         |  can
+könnte         |  could
+machen         |  do
+man            |  one
+
+manche         |  some, many a
+manchem
+manchen
+mancher
+manches
+
+mein           |  my
+meine
+meinem
+meinen
+meiner
+meines
+
+mit            |  with
+muss           |  must
+musste         |  had to
+nach           |  to(wards)
+nicht          |  not
+nichts         |  nothing
+noch           |  still, yet
+nun            |  now
+nur            |  only
+ob             |  whether
+oder           |  or
+ohne           |  without
+sehr           |  very
+
+sein           |  his
+seine
+seinem
+seinen
+seiner
+seines
+
+selbst         |  self
+sich           |  herself
+
+sie            |  they, she
+ihnen          |  to them
+
+sind           |  are
+so             |  so
+
+solche         |  such
+solchem
+solchen
+solcher
+solches
+
+soll           |  shall
+sollte         |  should
+sondern        |  but
+sonst          |  else
+über           |  over
+um             |  about, around
+und            |  and
+
+uns            |  us
+unse
+unsem
+unsen
+unser
+unses
+
+unter          |  under
+viel           |  much
+vom            |  von + dem
+von            |  from
+vor            |  before
+während        |  while
+war            |  was
+waren          |  were
+warst          |  wast
+was            |  what
+weg            |  away, off
+weil           |  because
+weiter         |  further
+
+welche         |  which
+welchem
+welchen
+welcher
+welches
+
+wenn           |  when
+werde          |  will
+werden         |  will
+wie            |  how
+wieder         |  again
+will           |  want
+wir            |  we
+wird           |  will
+wirst          |  willst
+wo             |  where
+wollen         |  want
+wollte         |  wanted
+würde          |  would
+würden         |  would
+zu             |  to
+zum            |  zu + dem
+zur            |  zu + der
+zwar           |  indeed
+zwischen       |  between
+''')
+
+js_stemmer = u"""
+var JSX={};(function(j){function l(b,e){var a=function(){};a.prototype=e.prototype;var c=new a;for(var d in b){b[d].prototype=c}}function H(c,b){for(var a in b.prototype)if(b.prototype.hasOwnProperty(a))c.prototype[a]=b.prototype[a]}function g(a,b,d){function c(a,b,c){delete a[b];a[b]=c;return c}Object.defineProperty(a,b,{get:function(){return c(a,b,d())},set:function(d){c(a,b,d)},enumerable:true,configurable:true})}function I(a,b,c){return a[b]=a[b]/c|0}var C=parseInt;var r=parseFloat;function J(a){return a!==a}var z=isFinite;var y=encodeURIComponent;var x=decodeURIComponent;var w=encodeURI;var u=decodeURI;var t=Object.prototype.toString;var B=Object.prototype.hasOwnProperty;function i(){}j.require=function(b){var a=q[b];return a!==undefined?a:null};j.profilerIsRunning=function(){return i.getResults!=null};j.getProfileResults=function(){return(i.getResults||function(){return{}})()};j.postProfileResults=function(a,b){if(i.postResults==null)throw new Error('profiler has not been turned on');return i.postResults(a,b)};j.resetProfileResults=function(){if(i.resetResults==null)throw new Error('profiler has not been turned on');return i.resetResults()};j.DEBUG=false;function s(){};l([s],Error);function c(a,b,c){this.F=a.length;this.K=a;this.L=b;this.I=c;this.H=null;this.P=null};l([c],Object);function o(){};l([o],Object);function e(){var a;var b;var c;this.G={};a=this.D='';b=this._=0;c=this.A=a.length;this.E=0;this.C=b;this.B=c};l([e],o);function v(a,b){a.D=b.D;a._=b._;a.A=b.A;a.E=b.E;a.C=b.C;a.B=b.B};function f(b,d,c,e){var a;if(b._>=b.A){return false}a=b.D.charCodeAt(b._);if(a>e||a<c){return false}a-=c;if((d[a>>>3]&1<<(a&7))===0){return false}b._++;return true};function m(b,d,c,e){var a;if(b._<=b.E){return false}a=b.D.charCodeAt(b._-1);if(a>e||a<c){return false}a-=c;if((d[a>>>3]&1<<(a&7))===0){return false}b._--;return true};function n(a,d,c,e){var b;if(a._>=a.A){return false}b=a.D.charCodeAt(a._);if(b>e||b<c){a._++;return true}b-=c;if((d[b>>>3]&1<<(b&7))===0){a._++;return true}return false};function k(a,b,d){var c;if(a.A-a._<b){return false}if(a.D.slice(c=a._,c+b)!==d){return false}a._+=b;return true};function d(a,b,d){var c;if(a._-a.E<b){return false}if(a.D.slice((c=a._)-b,c)!==d){return false}a._-=b;return true};function p(f,m,p){var b;var d;var e;var n;var g;var k;var l;var i;var h;var c;var a;var j;var o;b=0;d=p;e=f._;n=f.A;g=0;k=0;l=false;while(true){i=b+(d-b>>>1);h=0;c=g<k?g:k;a=m[i];for(j=c;j<a.F;j++){if(e+c===n){h=-1;break}h=f.D.charCodeAt(e+c)-a.K.charCodeAt(j);if(h!==0){break}c++}if(h<0){d=i;k=c}else{b=i;g=c}if(d-b<=1){if(b>0){break}if(d===b){break}if(l){break}l=true}}while(true){a=m[b];if(g>=a.F){f._=e+a.F|0;if(a.H==null){return a.I}o=a.H(a.P);f._=e+a.F|0;if(o){return a.I}}b=a.L;if(b<0){return 0}}return-1};function h(d,m,p){var b;var g;var e;var n;var f;var k;var l;var i;var h;var c;var a;var j;var o;b=0;g=p;e=d._;n=d.E;f=0;k=0;l=false;while(true){i=b+(g-b>>1);h=0;c=f<k?f:k;a=m[i];for(j=a.F-1-c;j>=0;j--){if(e-c===n){h=-1;break}h=d.D.charCodeAt(e-1-c)-a.K.charCodeAt(j);if(h!==0){break}c++}if(h<0){g=i;k=c}else{b=i;f=c}if(g-b<=1){if(b>0){break}if(g===b){break}if(l){break}l=true}}while(true){a=m[b];if(f>=a.F){d._=e-a.F|0;if(a.H==null){return a.I}o=a.H(d);d._=e-a.F|0;if(o){return a.I}}b=a.L;if(b<0){return 0}}return-1};function D(a,b,d,e){var c;c=e.length-(d-b);a.D=a.D.slice(0,b)+e+a.D.slice(d);a.A+=c|0;if(a._>=d){a._+=c|0}else if(a._>b){a._=b}return c|0};function b(a,f){var b;var c;var d;var e;b=false;if((c=a.C)<0||c>(d=a.B)||d>(e=a.A)||e>a.D.length?false:true){D(a,a.C,a.B,f);b=true}return b};e.prototype.J=function(){return false};e.prototype.W=function(b){var a;var c;var d;var e;a=this.G['.'+b];if(a==null){c=this.D=b;d=this._=0;e=this.A=c.length;this.E=0;this.C=d;this.B=e;this.J();a=this.D;this.G['.'+b]=a}return a};e.prototype.stemWord=e.prototype.W;e.prototype.X=function(e){var d;var b;var c;var a;var f;var g;var h;d=[];for(b=0;b<e.length;b++){c=e[b];a=this.G['.'+c];if(a==null){f=this.D=c;g=this._=0;h=this.A=f.length;this.E=0;this.C=g;this.B=h;this.J();a=this.D;this.G['.'+c]=a}d.push(a)}return d};e.prototype.stemWords=e.prototype.X;function a(){e.call(this);this.I_x=0;this.I_p2=0;this.I_p1=0};l([a],e);a.prototype.M=function(a){this.I_x=a.I_x;this.I_p2=a.I_p2;this.I_p1=a.I_p1;v(this,a)};a.prototype.copy_from=a.prototype.M;a.prototype.U=function(){var m;var r;var n;var o;var d;var q;var e;var c;var g;var h;var i;var j;var l;var s;var p;m=this._;a:while(true){r=this._;e=true;b:while(e===true){e=false;c=true;c:while(c===true){c=false;n=this._;g=true;d:while(g===true){g=false;this.C=this._;if(!k(this,1,'ß')){break d}this.B=this._;if(!b(this,'ss')){return false}break c}s=this._=n;if(s>=this.A){break b}this._++}continue a}this._=r;break a}this._=m;b:while(true){o=this._;h=true;d:while(h===true){h=false;e:while(true){d=this._;i=true;a:while(i===true){i=false;if(!f(this,a.g_v,97,252)){break a}this.C=this._;j=true;f:while(j===true){j=false;q=this._;l=true;c:while(l===true){l=false;if(!k(this,1,'u')){break c}this.B=this._;if(!f(this,a.g_v,97,252)){break c}if(!b(this,'U')){return false}break f}this._=q;if(!k(this,1,'y')){break a}this.B=this._;if(!f(this,a.g_v,97,252)){break a}if(!b(this,'Y')){return false}}this._=d;break e}p=this._=d;if(p>=this.A){break d}this._++}continue b}this._=o;break b}return true};a.prototype.r_prelude=a.prototype.U;function G(c){var s;var n;var o;var p;var e;var r;var d;var g;var h;var i;var j;var l;var m;var t;var q;s=c._;a:while(true){n=c._;d=true;b:while(d===true){d=false;g=true;c:while(g===true){g=false;o=c._;h=true;d:while(h===true){h=false;c.C=c._;if(!k(c,1,'ß')){break d}c.B=c._;if(!b(c,'ss')){return false}break c}t=c._=o;if(t>=c.A){break b}c._++}continue a}c._=n;break a}c._=s;b:while(true){p=c._;i=true;d:while(i===true){i=false;e:while(true){e=c._;j=true;a:while(j===true){j=false;if(!f(c,a.g_v,97,252)){break a}c.C=c._;l=true;f:while(l===true){l=false;r=c._;m=true;c:while(m===true){m=false;if(!k(c,1,'u')){break c}c.B=c._;if(!f(c,a.g_v,97,252)){break c}if(!b(c,'U')){return false}break f}c._=r;if(!k(c,1,'y')){break a}c.B=c._;if(!f(c,a.g_v,97,252)){break a}if(!b(c,'Y')){return false}}c._=e;break e}q=c._=e;if(q>=c.A){break d}c._++}continue b}c._=p;break b}return true};a.prototype.S=function(){var j;var b;var d;var e;var c;var g;var h;var i;var l;var k;this.I_p1=i=this.A;this.I_p2=i;j=l=this._;b=l+3|0;if(0>b||b>i){return false}k=this._=b;this.I_x=k;this._=j;a:while(true){d=true;b:while(d===true){d=false;if(!f(this,a.g_v,97,252)){break b}break a}if(this._>=this.A){return false}this._++}a:while(true){e=true;b:while(e===true){e=false;if(!n(this,a.g_v,97,252)){break b}break a}if(this._>=this.A){return false}this._++}this.I_p1=this._;c=true;a:while(c===true){c=false;if(!(this.I_p1<this.I_x)){break a}this.I_p1=this.I_x}a:while(true){g=true;b:while(g===true){g=false;if(!f(this,a.g_v,97,252)){break b}break a}if(this._>=this.A){return false}this._++}a:while(true){h=true;b:while(h===true){h=false;if(!n(this,a.g_v,97,252)){break b}break a}if(this._>=this.A){return false}this._++}this.I_p2=this._;return true};a.prototype.r_mark_regions=a.prototype.S;function F(b){var k;var c;var e;var g;var d;var h;var i;var j;var m;var l;b.I_p1=j=b.A;b.I_p2=j;k=m=b._;c=m+3|0;if(0>c||c>j){return false}l=b._=c;b.I_x=l;b._=k;a:while(true){e=true;b:while(e===true){e=false;if(!f(b,a.g_v,97,252)){break b}break a}if(b._>=b.A){return false}b._++}a:while(true){g=true;b:while(g===true){g=false;if(!n(b,a.g_v,97,252)){break b}break a}if(b._>=b.A){return false}b._++}b.I_p1=b._;d=true;a:while(d===true){d=false;if(!(b.I_p1<b.I_x)){break a}b.I_p1=b.I_x}a:while(true){h=true;b:while(h===true){h=false;if(!f(b,a.g_v,97,252)){break b}break a}if(b._>=b.A){return false}b._++}a:while(true){i=true;b:while(i===true){i=false;if(!n(b,a.g_v,97,252)){break b}break a}if(b._>=b.A){return false}b._++}b.I_p2=b._;return true};a.prototype.T=function(){var c;var e;var d;b:while(true){e=this._;d=true;a:while(d===true){d=false;this.C=this._;c=p(this,a.a_0,6);if(c===0){break a}this.B=this._;switch(c){case 0:break a;case 1:if(!b(this,'y')){return false}break;case 2:if(!b(this,'u')){return false}break;case 3:if(!b(this,'a')){return false}break;case 4:if(!b(this,'o')){return false}bre