Merge branch '4.x' into 4.0.x

This commit is contained in:
Takeshi KOMIYA 2021-06-13 17:20:01 +09:00 committed by GitHub
commit 7e71b759d7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
245 changed files with 22840 additions and 17391 deletions

View File

@ -23,9 +23,9 @@ jobs:
python: 3.9
docutils: du17
coverage: "--cov ./ --cov-append --cov-config setup.cfg"
# - name: py310-dev
# python: 3.10-dev
# docutils: du16
- name: py310-dev
python: 3.10-dev
docutils: du17
env:
PYTEST_ADDOPTS: ${{ matrix.coverage }}

51
.github/workflows/transifex.yml vendored Normal file
View File

@ -0,0 +1,51 @@
name: Sync translations on repository and transifex.com
on:
schedule:
- cron: "0 0 * * SUN"
workflow_dispatch:
jobs:
push:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: 4.x
- name: Set up Python
uses: actions/setup-python@v2
- name: Install dependencies
run: pip install -U babel jinja2 transifex-client
- name: Extract translations from source code
run: python setup.py extract_messages
- name: Push translations to transifex.com
run: cd sphinx/locale && tx push -s --no-interactive --parallel
env:
TX_TOKEN: ${{ secrets.TX_TOKEN }}
pull:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: 4.x
- name: Set up Python
uses: actions/setup-python@v2
- name: Install dependencies
run: pip install -U babel jinja2 transifex-client
- name: Extract translations from source code
run: python setup.py extract_messages
- name: Pull translations to transifex.com
run: cd sphinx/locale && tx pull -a -f --no-interactive --parallel
env:
TX_TOKEN: ${{ secrets.TX_TOKEN }}
- name: Compile message catalogs
run: python setup.py compile_catalog
- name: Create Pull Request
uses: peter-evans/create-pull-request@v3
with:
commit-message: 'Update message catalogs'
branch: bot/pull-translations
title: Update message catalogs

83
CHANGES
View File

@ -1,3 +1,83 @@
Release 4.1.0 (in development)
==============================
Dependencies
------------
* Support jinja2-3.0
Incompatible changes
--------------------
Deprecated
----------
* The ``app`` argument of ``sphinx.environment.BuildEnvironment`` becomes
required
* ``sphinx.application.Sphinx.html_theme``
* ``sphinx.ext.autosummary._app``
* ``sphinx.util.docstrings.extract_metadata()``
Features added
--------------
* #8107: autodoc: Add ``class-doc-from`` option to :rst:dir:`autoclass`
directive to control the content of the specific class like
:confval:`autoclass_content`
* #8588: autodoc: :confval:`autodoc_type_aliases` now supports dotted name. It
allows you to define an alias for a class with module name like
``foo.bar.BazClass``
* #9175: autodoc: Special member is not documented in the module
* #9195: autodoc: The arguments of ``typing.Literal`` are wrongly rendered
* #9185: autodoc: :confval:`autodoc_typehints` allows ``'both'`` setting to
allow typehints to be included both in the signature and description
* #4257: autodoc: Add :confval:`autodoc_class_signature` to separate the class
entry and the definition of ``__init__()`` method
* #8061, #9218: autodoc: Support variable comment for alias classes
* #3014: autodoc: Add :event:`autodoc-process-bases` to modify the base classes
of the class definitions
* #9272: autodoc: Render enum values for the default argument value better
* #3257: autosummary: Support instance attributes for classes
* #9129: html search: Show search summaries when html_copy_source = False
* #9120: html theme: Eliminate prompt characters of code-block from copyable
text
* #9176: i18n: Emit a debug message if message catalog file not found under
:confval:`locale_dirs`
* #9016: linkcheck: Support checking anchors on github.com
* #9016: linkcheck: Add a new event :event:`linkcheck-process-uri` to modify
URIs before checking hyperlinks
* #1874: py domain: Support union types using ``|`` in info-field-list
* #9268: py domain: :confval:`python_use_unqualified_type_names` supports type
field in info-field-list
* #9097: Optimize the paralell build
* #9131: Add :confval:`nitpick_ignore_regex` to ignore nitpicky warnings using
regular expressions
Bugs fixed
----------
* #8872: autodoc: stacked singledispatches are wrongly rendered
* #8597: autodoc: a docsting having metadata only should be treated as
undocumented
* #9185: autodoc: typehints for overloaded functions and methods are inaccurate
* #9250: autodoc: The inherited method not having docstring is wrongly parsed
* #9283: autodoc: autoattribute directive failed to generate document for an
attribute not having any comment
* #9270: html theme : pyramid theme generates incorrect logo links
* #9217: manpage: The name of manpage directory that is generated by
:confval:`man_make_section_directory` is not correct
* #9306: Linkcheck reports broken link when remote server closes the connection
on HEAD request
* #9280: py domain: "exceptions" module is not displayed
* #9224: ``:param:`` and ``:type:`` fields does not support a type containing
whitespace (ex. ``Dict[str, str]``)
* #8945: when transforming typed fields, call the specified role instead of
making an single xref. For C and C++, use the ``expr`` role for typed fields.
Testing
--------
Release 4.0.3 (in development)
==============================
@ -16,8 +96,7 @@ Features added
Bugs fixed
----------
* #9306: Linkcheck reports broken link when remote server closes the connection
on HEAD request
* 9313: LaTeX: complex table with merged cells broken since 4.0
Testing
--------

135
EXAMPLES
View File

@ -12,7 +12,6 @@ interesting examples.
Documentation using the alabaster theme
---------------------------------------
* `AIOHTTP <https://docs.aiohttp.org/>`__
* `Alabaster <https://alabaster.readthedocs.io/>`__
* `Blinker <https://pythonhosted.org/blinker/>`__
* `Calibre <https://manual.calibre-ebook.com/>`__
@ -26,14 +25,14 @@ Documentation using the alabaster theme
* `Flask-OpenID <https://pythonhosted.org/Flask-OpenID/>`__
* `Invoke <https://docs.pyinvoke.org/>`__
* `Jinja <https://jinja.palletsprojects.com/>`__
* `Lino <http://www.lino-framework.org/>`__ (customized)
* `Lino <https://www.lino-framework.org/>`__ (customized)
* `marbl <https://getmarbl.readthedocs.io/>`__
* `MDAnalysis <https://www.mdanalysis.org/docs/>`__ (customized)
* `MeshPy <https://documen.tician.de/meshpy/>`__
* `Molecule <https://molecule.readthedocs.io/>`__
* `PyCUDA <https://documen.tician.de/pycuda/>`__
* `PyOpenCL <https://documen.tician.de/pyopencl/>`__
* `PyLangAcq <http://pylangacq.org/>`__
* `PyLangAcq <https://pylangacq.org/>`__
* `pytest <https://docs.pytest.org/>`__ (customized)
* `python-apt <https://apt.alioth.debian.org/python-apt-doc/>`__
* `PyVisfile <https://documen.tician.de/pyvisfile/>`__
@ -48,10 +47,10 @@ Documentation using the alabaster theme
Documentation using the classic theme
-------------------------------------
* `Advanced Generic Widgets <http://xoomer.virgilio.it/infinity77/AGW_Docs/>`__ (customized)
* `Apache CouchDB <http://docs.couchdb.org/>`__ (customized)
* `Advanced Generic Widgets <https://xoomer.virgilio.it/infinity77/AGW_Docs/>`__ (customized)
* `Apache CouchDB <https://docs.couchdb.org/>`__ (customized)
* `APSW <https://rogerbinns.github.io/apsw/>`__
* `Arb <http://arblib.org/>`__
* `Arb <https://arblib.org/>`__
* `Bazaar <http://doc.bazaar.canonical.com/>`__ (customized)
* `Beautiful Soup <https://www.crummy.com/software/BeautifulSoup/bs4/doc/>`__
* `Blender API <https://docs.blender.org/api/current/>`__
@ -71,7 +70,7 @@ Documentation using the classic theme
* `GetFEM++ <http://getfem.org/>`__ (customized)
* `Glasgow Haskell Compiler <https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/>`__ (customized)
* `Grok <http://grok.zope.org/doc/current/>`__ (customized)
* `GROMACS <http://manual.gromacs.org/documentation/>`__
* `GROMACS <https://manual.gromacs.org/documentation/>`__
* `GSL Shell <https://www.nongnu.org/gsl-shell/>`__
* `Hands-on Python Tutorial <https://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/>`__
* `Kaa <https://api.freevo.org/kaa-base/>`__ (customized)
@ -79,9 +78,9 @@ Documentation using the classic theme
* `LEPL <http://www.acooke.org/lepl/>`__ (customized)
* `Mayavi <https://docs.enthought.com/mayavi/mayavi/>`__ (customized)
* `MediaGoblin <https://mediagoblin.readthedocs.io/>`__ (customized)
* `mpmath <http://mpmath.org/doc/current/>`__
* `mpmath <https://mpmath.org/doc/current/>`__
* `OpenCV <https://docs.opencv.org/>`__ (customized)
* `OpenEXR <http://excamera.com/articles/26/doc/index.html>`__
* `OpenEXR <https://excamera.com/articles/26/doc/index.html>`__
* `OpenGDA <http://www.opengda.org/gdadoc/html/>`__
* `Peach^3 <https://peach3.nl/doc/latest/userdoc/>`__ (customized)
* `Plone <https://docs.plone.org/>`__ (customized)
@ -120,8 +119,8 @@ Documentation using the sphinxdoc theme
* `Matplotlib <https://matplotlib.org/>`__
* `MDAnalysis Tutorial <https://www.mdanalysis.org/MDAnalysisTutorial/>`__
* `NetworkX <https://networkx.github.io/>`__
* `PyCantonese <http://pycantonese.org/>`__
* `Pyre <http://docs.danse.us/pyre/sphinx/>`__
* `PyCantonese <https://pycantonese.org/>`__
* `Pyre <https://docs.danse.us/pyre/sphinx/>`__
* `pySPACE <https://pyspace.github.io/pyspace/>`__
* `Pysparse <http://pysparse.sourceforge.net/>`__
* `PyTango <https://www.esrf.eu/computing/cs/tango/tango_doc/kernel_doc/pytango/latest/>`__
@ -135,7 +134,7 @@ Documentation using the nature theme
------------------------------------
* `Alembic <https://alembic.sqlalchemy.org/>`__
* `Cython <http://docs.cython.org/>`__
* `Cython <https://docs.cython.org/>`__
* `easybuild <https://easybuild.readthedocs.io/>`__
* `jsFiddle <http://doc.jsfiddle.net/>`__
* `libLAS <https://www.liblas.org/>`__ (customized)
@ -160,18 +159,19 @@ Documentation using another builtin theme
* `Pylons <https://docs.pylonsproject.org/projects/pylons-webframework/>`__ (pyramid)
* `Pyramid web framework <https://docs.pylonsproject.org/projects/pyramid/>`__ (pyramid)
* `RxDock <https://www.rxdock.org/documentation/html/devel/>`__
* `Sphinx <http://www.sphinx-doc.org/>`__ (sphinx13) :-)
* `Sphinx <https://www.sphinx-doc.org/>`__ (sphinx13) :-)
* `Valence <https://docs.valence.desire2learn.com/>`__ (haiku, customized)
Documentation using sphinx_rtd_theme
------------------------------------
* `Annotator <http://docs.annotatorjs.org/>`__
* `Annotator <https://docs.annotatorjs.org/>`__
* `Ansible <https://docs.ansible.com/>`__ (customized)
* `Arcade <http://arcade.academy/>`__
* `Arcade <https://arcade.academy/>`__
* `aria2 <https://aria2.github.io/manual/en/html/>`__
* `ASE <https://wiki.fysik.dtu.dk/ase/>`__
* `Autofac <http://docs.autofac.org/>`__
* `asvin <https://asvin.readthedocs.io/>`__
* `Autofac <https://docs.autofac.org/>`__
* `BigchainDB <https://docs.bigchaindb.com/>`__
* `Blender Reference Manual <https://docs.blender.org/manual/>`__
* `Blocks <https://blocks.readthedocs.io/>`__
@ -189,28 +189,28 @@ Documentation using sphinx_rtd_theme
* `DNF <https://dnf.readthedocs.io/>`__
* `Django-cas-ng <https://djangocas.dev/docs/>`__
* `edX <https://docs.edx.org/>`__
* `Electrum <http://docs.electrum.org/>`__
* `Elemental <http://libelemental.org/documentation/dev/>`__
* `Electrum <https://docs.electrum.org/>`__
* `Elemental <https://libelemental.org/documentation/dev/>`__
* `ESWP3 <https://eswp3.readthedocs.io/>`__
* `Ethereum Homestead <http://www.ethdocs.org/>`__
* `Ethereum Homestead <https://www.ethdocs.org/>`__
* `Exhale <https://exhale.readthedocs.io/>`__
* `Faker <https://faker.readthedocs.io/>`__
* `Fidimag <https://fidimag.readthedocs.io/>`__
* `Flake8 <http://flake8.pycqa.org/>`__
* `Flatpak <http://docs.flatpak.org/>`__
* `Flake8 <https://flake8.pycqa.org/>`__
* `Flatpak <https://docs.flatpak.org/>`__
* `FluidDyn <https://fluiddyn.readthedocs.io/>`__
* `Fluidsim <https://fluidsim.readthedocs.io/>`__
* `Gallium <https://gallium.readthedocs.io/>`__
* `GeoNode <http://docs.geonode.org/>`__
* `GeoNode <https://docs.geonode.org/>`__
* `Glances <https://glances.readthedocs.io/>`__
* `Godot <https://godot.readthedocs.io/>`__
* `Graylog <http://docs.graylog.org/>`__
* `Graylog <https://docs.graylog.org/>`__
* `GPAW <https://wiki.fysik.dtu.dk/gpaw/>`__ (customized)
* `HDF5 for Python (h5py) <http://docs.h5py.org/>`__
* `HDF5 for Python (h5py) <https://docs.h5py.org/>`__
* `Hyperledger Fabric <https://hyperledger-fabric.readthedocs.io/>`__
* `Hyperledger Sawtooth <https://intelledger.github.io/>`__
* `IdentityServer <http://docs.identityserver.io/>`__
* `Idris <http://docs.idris-lang.org/>`__
* `IdentityServer <https://docs.identityserver.io/>`__
* `Idris <https://docs.idris-lang.org/>`__
* `javasphinx <https://bronto-javasphinx.readthedocs.io/>`__
* `Julia <https://julia.readthedocs.io/>`__
* `Jupyter Notebook <https://jupyter-notebook.readthedocs.io/>`__
@ -220,45 +220,45 @@ Documentation using sphinx_rtd_theme
* `LibCEED <https://libceed.readthedocs.io/>`__
* `Linguistica <https://linguistica-uchicago.github.io/lxa5/>`__
* `Linux kernel <https://www.kernel.org/doc/html/latest/index.html>`__
* `Mailman <http://docs.list.org/>`__
* `Mailman <https://docs.list.org/>`__
* `MathJax <https://docs.mathjax.org/>`__
* `MDTraj <http://mdtraj.org/latest/>`__ (customized)
* `Mesa 3D <https://docs.mesa3d.org/>`__
* `micca - MICrobial Community Analysis <https://micca.readthedocs.io/>`__
* `MicroPython <https://docs.micropython.org/>`__
* `Minds <https://www.minds.org/docs/>`__ (customized)
* `Mink <http://mink.behat.org/>`__
* `Mockery <http://docs.mockery.io/>`__
* `Mink <https://mink.behat.org/>`__
* `Mockery <https://docs.mockery.io/>`__
* `mod_wsgi <https://modwsgi.readthedocs.io/>`__
* `MoinMoin <https://moin-20.readthedocs.io/>`__
* `Mopidy <https://docs.mopidy.com/>`__
* `mpi4py <https://mpi4py.readthedocs.io/>`__
* `MyHDL <http://docs.myhdl.org/>`__
* `MyHDL <https://docs.myhdl.org/>`__
* `Nextflow <https://www.nextflow.io/docs/latest/index.html>`__
* `NICOS <https://forge.frm2.tum.de/nicos/doc/nicos-master/>`__ (customized)
* `OpenFAST <https://openfast.readthedocs.io/>`__
* `Pelican <http://docs.getpelican.com/>`__
* `Pelican <https://docs.getpelican.com/>`__
* `picamera <https://picamera.readthedocs.io/>`__
* `Pillow <https://pillow.readthedocs.io/>`__
* `pip <https://pip.pypa.io/>`__
* `Paver <https://paver.readthedocs.io/>`__
* `peewee <http://docs.peewee-orm.com/>`__
* `Phinx <http://docs.phinx.org/>`__
* `peewee <https://docs.peewee-orm.com/>`__
* `Phinx <https://docs.phinx.org/>`__
* `phpMyAdmin <https://docs.phpmyadmin.net/>`__
* `PROS <https://pros.cs.purdue.edu/v5/>`__ (customized)
* `Pushkin <http://docs.pushkin.io/>`__
* `Pweave <http://mpastell.com/pweave/>`__
* `PyPy <http://doc.pypy.org/>`__
* `Pweave <https://mpastell.com/pweave/>`__
* `PyPy <https://doc.pypy.org/>`__
* `python-sqlparse <https://sqlparse.readthedocs.io/>`__
* `PyVISA <https://pyvisa.readthedocs.io/>`__
* `pyvista <https://docs.pyvista.org/>`__
* `Read The Docs <https://docs.readthedocs.io/>`__
* `ROCm Platform <https://rocm-documentation.readthedocs.io/>`__
* `Free your information from their silos (French) <http://redaction-technique.org/>`__ (customized)
* `Free your information from their silos (French) <https://redaction-technique.org/>`__ (customized)
* `Releases Sphinx extension <https://releases.readthedocs.io/>`__
* `Qtile <http://docs.qtile.org/>`__
* `Qtile <https://docs.qtile.org/>`__
* `Quex <http://quex.sourceforge.net/doc/html/main.html>`__
* `QuTiP <http://qutip.org/docs/latest/>`__
* `QuTiP <https://qutip.org/docs/latest/>`__
* `Satchmo <http://docs.satchmoproject.com/>`__
* `Scapy <https://scapy.readthedocs.io/>`__
* `SimGrid <https://simgrid.org/doc/latest/>`__
@ -266,7 +266,7 @@ Documentation using sphinx_rtd_theme
* `six <https://six.readthedocs.io/>`__
* `SlamData <https://newdocs.slamdata.com>`__
* `Solidity <https://solidity.readthedocs.io/>`__
* `Sonos Controller (SoCo) <http://docs.python-soco.com/>`__
* `Sonos Controller (SoCo) <https://docs.python-soco.com/>`__
* `Sphinx AutoAPI <https://sphinx-autoapi.readthedocs.io/>`__
* `sphinx-argparse <https://sphinx-argparse.readthedocs.io/>`__
* `Sphinx-Gallery <https://sphinx-gallery.readthedocs.io/>`__ (customized)
@ -278,7 +278,7 @@ Documentation using sphinx_rtd_theme
* `Sylius <http://docs.sylius.org/>`__
* `Syncthing <https://docs.syncthing.net/>`__
* `Tango Controls <https://tango-controls.readthedocs.io/>`__ (customized)
* `Topshelf <http://docs.topshelf-project.com/>`__
* `Topshelf <https://docs.topshelf-project.com/>`__
* `Theano <http://www.deeplearning.net/software/theano/>`__
* `ThreatConnect <https://docs.threatconnect.com/>`__
* `Tuleap <https://tuleap.net/doc/en/>`__
@ -287,7 +287,7 @@ Documentation using sphinx_rtd_theme
* `uWSGI <https://uwsgi-docs.readthedocs.io/>`__
* `virtualenv <https://virtualenv.readthedocs.io/>`__
* `Wagtail <https://docs.wagtail.io/>`__
* `Web Application Attack and Audit Framework (w3af) <http://docs.w3af.org/>`__
* `Web Application Attack and Audit Framework (w3af) <https://docs.w3af.org/>`__
* `Weblate <https://docs.weblate.org/>`__
* `x265 <https://x265.readthedocs.io/>`__
* `Zulip <https://zulip.readthedocs.io/>`__
@ -297,27 +297,28 @@ Documentation using sphinx_bootstrap_theme
* `Bootstrap Theme <https://ryan-roemer.github.io/sphinx-bootstrap-theme/>`__
* `C/C++ Software Development with Eclipse <https://eclipsebook.in/>`__
* `Dataverse <http://guides.dataverse.org/>`__
* `Dataverse <https://guides.dataverse.org/>`__
* `e-cidadania <https://e-cidadania.readthedocs.io/>`__
* `Hangfire <http://docs.hangfire.io/>`__
* `Hangfire <https://docs.hangfire.io/>`__
* `Hedge <https://documen.tician.de/hedge/>`__
* `ObsPy <https://docs.obspy.org/>`__
* `Open Dylan <https://opendylan.org/documentation/>`__
* `OPNFV <https://docs.opnfv.org/>`__
* `Pootle <http://docs.translatehouse.org/projects/pootle/>`__
* `Pootle <https://docs.translatehouse.org/projects/pootle/>`__
* `PyUblas <https://documen.tician.de/pyublas/>`__
* `seaborn <https://seaborn.pydata.org/>`__
Documentation using a custom theme or integrated in a website
-------------------------------------------------------------
* `AIOHTTP <https://docs.aiohttp.org/>`__
* `Apache Cassandra <https://cassandra.apache.org/doc/>`__
* `Astropy <http://docs.astropy.org/>`__
* `Astropy <https://docs.astropy.org/>`__
* `Bokeh <https://bokeh.pydata.org/>`__
* `Boto 3 <https://boto3.readthedocs.io/>`__
* `CakePHP <https://book.cakephp.org/>`__
* `CasperJS <http://docs.casperjs.org/>`__
* `Ceph <http://docs.ceph.com/docs/master/>`__
* `Ceph <https://docs.ceph.com/docs/master/>`__
* `Chef <https://docs.chef.io/>`__
* `CKAN <https://docs.ckan.org/>`__
* `Confluent Platform <https://docs.confluent.io/>`__
@ -326,24 +327,24 @@ Documentation using a custom theme or integrated in a website
* `Enterprise Toolkit for Acrobat products <https://www.adobe.com/devnet-docs/acrobatetk/>`__
* `FreeFEM <https://doc.freefem.org/introduction/>`__
* `fmt <https://fmt.dev/>`__
* `Gameduino <http://excamera.com/sphinx/gameduino/>`__
* `Gameduino <https://excamera.com/sphinx/gameduino/>`__
* `gensim <https://radimrehurek.com/gensim/>`__
* `GeoServer <http://docs.geoserver.org/>`__
* `gevent <http://www.gevent.org/>`__
* `GeoServer <https://docs.geoserver.org/>`__
* `gevent <https://www.gevent.org/>`__
* `GHC - Glasgow Haskell Compiler <https://downloads.haskell.org/~ghc/master/users-guide/>`__
* `Guzzle <http://docs.guzzlephp.org/>`__
* `H2O.ai <http://docs.h2o.ai/>`__
* `Guzzle <https://docs.guzzlephp.org/>`__
* `H2O.ai <https://docs.h2o.ai/>`__
* `Heka <https://hekad.readthedocs.io/>`__
* `Istihza (Turkish Python documentation project) <https://belgeler.yazbel.com/python-istihza/>`__
* `JupyterHub <https://jupyterhub.readthedocs.io/>`__
* `Kombu <http://docs.kombu.me/>`__
* `Lasso <http://lassoguide.com/>`__
* `Mako <http://docs.makotemplates.org/>`__
* `MirrorBrain <http://mirrorbrain.org/docs/>`__
* `Lasso <https://lassoguide.com/>`__
* `Mako <https://docs.makotemplates.org/>`__
* `MirrorBrain <https://mirrorbrain.org/docs/>`__
* `Mitiq <https://mitiq.readthedocs.io/>`__
* `MongoDB <https://docs.mongodb.com/>`__
* `Music21 <https://web.mit.edu/music21/doc/>`__
* `MyHDL <http://docs.myhdl.org/>`__
* `MyHDL <https://docs.myhdl.org/>`__
* `ndnSIM <https://ndnsim.net/current/>`__
* `nose <https://nose.readthedocs.io/>`__
* `ns-3 <https://www.nsnam.org/documentation/>`__
@ -353,30 +354,30 @@ Documentation using a custom theme or integrated in a website
* `OpenCV <https://docs.opencv.org/>`__
* `OpenLayers <http://docs.openlayers.org/>`__
* `OpenTURNS <https://openturns.github.io/openturns/master/>`__
* `Open vSwitch <http://docs.openvswitch.org/>`__
* `Open vSwitch <https://docs.openvswitch.org/>`__
* `PlatformIO <https://docs.platformio.org/>`__
* `PyEphem <http://rhodesmill.org/pyephem/>`__
* `Pygments <http://pygments.org/docs/>`__
* `PyEphem <https://rhodesmill.org/pyephem/>`__
* `Pygments <https://pygments.org/docs/>`__
* `Plone User Manual (German) <https://www.hasecke.com/plone-benutzerhandbuch/4.0/>`__
* `PSI4 <http://www.psicode.org/psi4manual/master/index.html>`__
* `PSI4 <https://www.psicode.org/psi4manual/master/index.html>`__
* `PyMOTW <https://pymotw.com/2/>`__
* `python-aspectlib <https://python-aspectlib.readthedocs.io/>`__ (`sphinx_py3doc_enhanced_theme <https://pypi.org/project/sphinx_py3doc_enhanced_theme/>`__)
* `QGIS <https://qgis.org/en/docs/index.html>`__
* `qooxdoo <https://www.qooxdoo.org/current/>`__
* `Roundup <http://www.roundup-tracker.org/>`__
* `Roundup <https://www.roundup-tracker.org/>`__
* `SaltStack <https://docs.saltstack.com/>`__
* `scikit-learn <http://scikit-learn.org/stable/>`__
* `scikit-learn <https://scikit-learn.org/stable/>`__
* `SciPy <https://docs.scipy.org/doc/scipy/reference/>`__
* `Scrapy <https://doc.scrapy.org/>`__
* `Seaborn <https://seaborn.pydata.org/>`__
* `Selenium <https://docs.seleniumhq.org/docs/>`__
* `Self <http://www.selflanguage.org/>`__
* `Self <https://www.selflanguage.org/>`__
* `Substance D <https://docs.pylonsproject.org/projects/substanced/>`__
* `Sulu <http://docs.sulu.io/>`__
* `Sulu <https://docs.sulu.io/>`__
* `SQLAlchemy <https://docs.sqlalchemy.org/>`__
* `tinyTiM <http://tinytim.sourceforge.net/docs/2.0/>`__
* `Twisted <https://twistedmatrix.com/documents/current/>`__
* `Ubuntu Packaging Guide <http://packaging.ubuntu.com/html/>`__
* `Ubuntu Packaging Guide <https://packaging.ubuntu.com/html/>`__
* `WebFaction <https://docs.webfaction.com/>`__
* `WTForms <https://wtforms.readthedocs.io/>`__
@ -387,7 +388,7 @@ Homepages and other non-documentation sites
* `Benoit Boissinot <https://bboissin.appspot.com/>`__ (classic, customized)
* `Computer Networks, Parallelization, and Simulation Laboratory (CNPSLab) <https://lab.miletic.net/>`__ (sphinx_rtd_theme)
* `Deep Learning Tutorials <http://www.deeplearning.net/tutorial/>`__ (sphinxdoc)
* `Eric Holscher <http://ericholscher.com/>`__ (alabaster)
* `Eric Holscher <https://ericholscher.com/>`__ (alabaster)
* `Lei Ma's Statistical Mechanics lecture notes <http://statisticalphysics.openmetric.org/>`__ (sphinx_bootstrap_theme)
* `Loyola University Chicago COMP 339-439 Distributed Systems course <https://books.cs.luc.edu/distributedsystems/>`__ (sphinx_bootstrap_theme)
* `Pylearn2 <http://www.deeplearning.net/software/pylearn2/>`__ (sphinxdoc, customized)
@ -408,7 +409,7 @@ Books produced using Sphinx
* `"Expert Python Programming" (Japanese translation) <https://www.amazon.co.jp/dp/4048686291/>`__
* `"Expert Python Programming 2nd Edition" (Japanese translation) <https://www.amazon.co.jp/dp/4048930613/>`__
* `"The Hitchhiker's Guide to Python" <https://docs.python-guide.org/>`__
* `"LassoGuide" <http://www.lassosoft.com/Lasso-Documentation>`__
* `"LassoGuide" <https://www.lassosoft.com/Lasso-Documentation>`__
* `"Learning Sphinx" (in Japanese) <https://www.oreilly.co.jp/books/9784873116488/>`__
* `"Learning System Programming with Go (Japanese)" <https://www.lambdanote.com/products/go>`__
* `"Mercurial: the definitive guide (Second edition)" <https://book.mercurial-scm.org/>`__
@ -416,7 +417,7 @@ Books produced using Sphinx
* `"Pioneers and Prominent Men of Utah" <http://pioneers.rstebbing.com/>`__
* `"Pomodoro Technique Illustrated" (Japanese translation) <https://www.amazon.co.jp/dp/4048689525/>`__
* `"Professional Software Development" <https://mixmastamyk.bitbucket.io/pro_soft_dev/>`__
* `"Python Professional Programming" (in Japanese) <http://www.amazon.co.jp/dp/4798032948/>`__
* `"Python Professional Programming" (in Japanese) <https://www.amazon.co.jp/dp/4798032948/>`__
* `"Python Professional Programming 2nd Edition" (in Japanese) <https://www.amazon.co.jp/dp/479804315X/>`__
* `"Python Professional Programming 3rd Edition" (in Japanese) <https://www.amazon.co.jp/dp/4798053821/>`__
* `Python Course by Yuri Petrov (Russian) <https://www.yuripetrov.ru/edu/python>`__

View File

@ -10,10 +10,6 @@
:target: http://www.sphinx-doc.org/
:alt: Documentation Status
.. image:: https://travis-ci.org/sphinx-doc/sphinx.svg?branch=master
:target: https://travis-ci.org/sphinx-doc/sphinx
:alt: Build Status (Travis CI)
.. image:: https://ci.appveyor.com/api/projects/status/github/sphinx-doc/sphinx?branch=master&svg=true
:target: https://ci.appveyor.com/project/sphinxdoc/sphinx
:alt: Build Status (AppVeyor)

View File

@ -1,7 +1,7 @@
# How to setup this file
# http://babel.pocoo.org/en/latest/installation.html
# https://babel.pocoo.org/en/latest/installation.html
# this file description:
# http://babel.pocoo.org/en/latest/messages.html
# https://babel.pocoo.org/en/latest/messages.html
# Extraction from Python source files
[python: **.py]

View File

@ -29,7 +29,7 @@
<li>{%trans%}<b>Automatic indices:</b> general index as well as a language-specific
module indices{%endtrans%}</li>
<li>{%trans%}<b>Code handling:</b> automatic highlighting using the <a
href="http://pygments.org">Pygments</a> highlighter{%endtrans%}</li>
href="https://pygments.org">Pygments</a> highlighter{%endtrans%}</li>
<li>{%trans path=pathto('ext/builtins')%}<b>Extensions:</b> automatic testing of code snippets, inclusion of
docstrings from Python modules (API docs), and
<a href="{{ path }}#builtin-sphinx-extensions">more</a>{%endtrans%}</li>
@ -38,10 +38,10 @@
most of them installable from PyPI{%endtrans%}</li>
</ul>
<p>{%trans%}
Sphinx uses <a href="http://docutils.sourceforge.net/rst.html">reStructuredText</a>
Sphinx uses <a href="https://docutils.sourceforge.io/rst.html">reStructuredText</a>
as its markup language, and many of its strengths come from the power and
straightforwardness of reStructuredText and its parsing and translating
suite, the <a href="http://docutils.sourceforge.net/">Docutils</a>.{%endtrans%}
suite, the <a href="https://docutils.sourceforge.io/">Docutils</a>.{%endtrans%}
</p>
<h2 style="margin-bottom: 0">{%trans%}Documentation{%endtrans%}</h2>

View File

@ -35,7 +35,7 @@ htmlhelp_basename = 'Sphinxdoc'
epub_theme = 'epub'
epub_basename = 'sphinx'
epub_author = 'Georg Brandl'
epub_publisher = 'http://sphinx-doc.org/'
epub_publisher = 'https://sphinx-doc.org/'
epub_uid = 'web-site'
epub_scheme = 'url'
epub_identifier = epub_publisher
@ -80,11 +80,11 @@ latex_use_xindy = True
autodoc_member_order = 'groupwise'
autosummary_generate = False
todo_include_todos = True
extlinks = {'duref': ('http://docutils.sourceforge.net/docs/ref/rst/'
extlinks = {'duref': ('https://docutils.sourceforge.io/docs/ref/rst/'
'restructuredtext.html#%s', ''),
'durole': ('http://docutils.sourceforge.net/docs/ref/rst/'
'durole': ('https://docutils.sourceforge.io/docs/ref/rst/'
'roles.html#%s', ''),
'dudir': ('http://docutils.sourceforge.net/docs/ref/rst/'
'dudir': ('https://docutils.sourceforge.io/docs/ref/rst/'
'directives.html#%s', '')}
man_pages = [

View File

@ -207,9 +207,9 @@ inside your module:
First, define the registration function, which accepts the arguments for
:event:`html-page-context`.
Within the registration function, define the template function that you'd like to use
within Jinja. The template function should return a string or Python objects (lists,
dictionaries) with strings inside that Jinja uses in the templating process
Within the registration function, define the template function that you'd like to
use within Jinja. The template function should return a string or Python objects
(lists, dictionaries) with strings inside that Jinja uses in the templating process
.. note::

View File

@ -181,9 +181,9 @@ This is the very basic principle of an extension that creates a new directive.
For a more advanced example, refer to :doc:`todo`.
.. _docutils: http://docutils.sourceforge.net/
.. _docutils directives: http://docutils.sourceforge.net/docs/howto/rst-directives.html
.. _docutils nodes: http://docutils.sourceforge.net/docs/ref/doctree.html
.. _docutils: https://docutils.sourceforge.io/
.. _docutils directives: https://docutils.sourceforge.io/docs/howto/rst-directives.html
.. _docutils nodes: https://docutils.sourceforge.io/docs/ref/doctree.html
.. _PyPI: https://pypi.org/
.. _Python package: https://packaging.python.org/
.. _Python path: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH

View File

@ -223,4 +223,4 @@ Further reading
For more information, refer to the `docutils`_ documentation and
:doc:`/extdev/index`.
.. _docutils: http://docutils.sourceforge.net/docs/
.. _docutils: https://docutils.sourceforge.io/docs/

View File

@ -105,7 +105,7 @@ is just a "general" node.
Many extensions will not have to create their own node classes and work fine
with the nodes already provided by `docutils
<http://docutils.sourceforge.net/docs/ref/doctree.html>`__ and :ref:`Sphinx
<https://docutils.sourceforge.io/docs/ref/doctree.html>`__ and :ref:`Sphinx
<nodes>`.
.. attention::
@ -362,6 +362,6 @@ For more information, refer to the `docutils`_ documentation and
:doc:`/extdev/index`.
.. _docutils: http://docutils.sourceforge.net/docs/
.. _docutils: https://docutils.sourceforge.io/docs/
.. _Python path: https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH
.. _docutils documentation: http://docutils.sourceforge.net/docs/ref/rst/directives.html
.. _docutils documentation: https://docutils.sourceforge.io/docs/ref/rst/directives.html

View File

@ -159,7 +159,9 @@ connect handlers to the events. Example:
Below is an overview of each event that happens during a build. In the list
below, we include the event name, its callback parameters, and the input and output
type for that event::
type for that event:
.. code-block:: none
1. event.config-inited(app,config)
2. event.builder-inited(app)
@ -377,13 +379,22 @@ Here is a more detailed list of these events.
``'page.html'`` as the HTML template for this page.
.. note:: You can install JS/CSS files for the specific page via
:meth:`Sphinx.add_js_file` and :meth:`Sphinx.add_css_file` since v3.5.0.
:meth:`Sphinx.add_js_file` and :meth:`Sphinx.add_css_file` since
v3.5.0.
.. versionadded:: 0.4
.. versionchanged:: 1.3
The return value can now specify a template name.
.. event:: linkcheck-process-uri (app, uri)
Emitted when the linkcheck builder collects hyperlinks from document. *uri*
is a collected URI. The event handlers can modify the URI by returning a
string.
.. versionadded:: 4.1
.. event:: build-finished (app, exception)
Emitted when a build has finished, before Sphinx exits, usually used for

View File

@ -22,6 +22,26 @@ The following is a list of deprecated interfaces.
- (will be) Removed
- Alternatives
* - The optional argument ``app`` for ``sphinx.environment.BuildEnvironment``
- 4.1
- 6.0
- The required argument
* - ``sphinx.application.Sphinx.html_theme``
- 4.1
- 6.0
- ``sphinx.registry.SphinxComponentRegistry.html_themes``
* - ``sphinx.ext.autosummary._app``
- 4.1
- 6.0
- N/A
* - ``sphinx.util.docstrings.extract_metadata()``
- 4.1
- 6.0
- ``sphinx.util.docstrings.separate_metadata()``
* - ``favicon`` variable in HTML templates
- 4.0
- TBD
@ -35,12 +55,12 @@ The following is a list of deprecated interfaces.
* - ``sphinx.directives.patches.ListTable``
- 4.0
- 6.0
- ``docutils.parsers.rst.diretives.tables.ListSVTable``
- ``docutils.parsers.rst.directives.tables.ListSVTable``
* - ``sphinx.directives.patches.RSTTable``
- 4.0
- 6.0
- ``docutils.parsers.rst.diretives.tables.RSTTable``
- ``docutils.parsers.rst.directives.tables.RSTTable``
* - ``sphinx.ext.autodoc.directive.DocumenterBridge.filename_set``
- 4.0
@ -80,7 +100,7 @@ The following is a list of deprecated interfaces.
* - ``sphinx.util.smartypants``
- 4.0
- 6.0
- ``docutils.utils.smartyquotes``
- ``docutils.utils.smartquotes``
* - ``sphinx.util.typing.DirectiveOption``
- 4.0

View File

@ -94,4 +94,4 @@ message catalog template and message catalogs, for example via `Babel`_:
$ pybabel extract --output=src/locale/myextension.pot src/
$ pybabel update --input-file=src/locale/myextension.pot --domain=myextension --output-dir=src/locale
.. _Babel: http://babel.pocoo.org/
.. _Babel: https://babel.pocoo.org/

View File

@ -112,7 +112,7 @@ in which a Sphinx project is built: this works in several phases.
existing files are read, temporary nodes are created.
There are nodes provided by docutils, which are documented `in the docutils
documentation <http://docutils.sourceforge.net/docs/ref/doctree.html>`__.
documentation <https://docutils.sourceforge.io/docs/ref/doctree.html>`__.
Additional nodes are provided by Sphinx and :ref:`documented here <nodes>`.
During reading, the build environment is updated with all meta- and cross

View File

@ -149,4 +149,4 @@ return ``node.children`` from the Directive.
`Creating directives`_ HOWTO of the Docutils documentation
.. _Creating directives: http://docutils.sourceforge.net/docs/howto/rst-directives.html
.. _Creating directives: https://docutils.sourceforge.io/docs/howto/rst-directives.html

View File

@ -8,7 +8,7 @@ Parser API
The Parser analyzes the input document and creates a node tree
representation.
__ http://docutils.sourceforge.net/docs/dev/hacking.html#parsing-the-document
__ https://docutils.sourceforge.io/docs/dev/hacking.html#parsing-the-document
In Sphinx, the parser modules works as same as docutils. The parsers are
registered to Sphinx by extensions using Application APIs;

View File

@ -145,7 +145,7 @@ Google Search
.. _Getting Started: https://docs.readthedocs.io/en/stable/intro/getting-started-with-sphinx.html
.. _api role: https://git.savannah.gnu.org/cgit/kenozooid.git/tree/doc/extapi.py
.. _xhtml to reST: http://docutils.sourceforge.net/sandbox/xhtml2rest/xhtml2rest.py
.. _xhtml to reST: https://docutils.sourceforge.io/sandbox/xhtml2rest/xhtml2rest.py
Sphinx vs. Docutils
@ -179,10 +179,10 @@ of the *writers* provided by docutils. This allows Sphinx to provide many
features that would simply not be possible with docutils, such as those
outlined above.
__ http://docutils.sourceforge.io/
__ http://docutils.sourceforge.io/docs/dev/hacking.html
__ http://docutils.sourceforge.io/rst.html
__ http://docutils.sourceforge.net/docs/user/tools.html
__ https://docutils.sourceforge.io/
__ https://docutils.sourceforge.io/docs/dev/hacking.html
__ https://docutils.sourceforge.io/rst.html
__ https://docutils.sourceforge.io/docs/user/tools.html
.. _epub-faq:
@ -259,7 +259,9 @@ The following list gives some hints for the creation of epub files:
``parent.xhtml`` -> ``child.xhtml`` -> ``parent.xhtml``
If you get the following error, fix your document structure::
If you get the following error, fix your document structure:
.. code-block:: none
Error(prcgen):E24011: TOC section scope is not included in the parent chapter:(title)
Error(prcgen):E24001: The table of content could not be built.

View File

@ -251,7 +251,7 @@ The parts of messages in Sphinx that go into builds are translated into several
locales. The translations are kept as gettext ``.po`` files translated from the
master template :file:`sphinx/locale/sphinx.pot`.
Sphinx uses `Babel <http://babel.pocoo.org/en/latest/>`_ to extract messages
Sphinx uses `Babel <https://babel.pocoo.org/en/latest/>`_ to extract messages
and maintain the catalog files. It is integrated in ``setup.py``:
* Use ``python setup.py extract_messages`` to update the ``.pot`` template.
@ -297,7 +297,7 @@ Debugging tips
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>`_.
<https://docutils.sourceforge.io/docs/user/config.html>`_.
* JavaScript stemming algorithms in ``sphinx/search/*.py`` (except ``en.py``)
are generated by this `modified snowballcode generator

View File

@ -19,7 +19,7 @@ if errorlevel 9009 (
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
echo.https://sphinx-doc.org/
exit /b 1
)

View File

@ -6,10 +6,11 @@
Templating
==========
Sphinx uses the `Jinja <http://jinja.pocoo.org>`_ templating engine for its HTML
templates. Jinja is a text-based engine, inspired by Django templates, so
anyone having used Django will already be familiar with it. It also has
excellent documentation for those who need to make themselves familiar with it.
Sphinx uses the `Jinja <https://jinja.palletsprojects.com/>`_ templating engine
for its HTML templates. Jinja is a text-based engine, inspired by Django
templates, so anyone having used Django will already be familiar with it. It
also has excellent documentation for those who need to make themselves familiar
with it.
Do I need to use Sphinx's templates to produce HTML?

View File

@ -13,7 +13,7 @@ navigation bars, Sphinx provides mechanisms facilitating the translation of
:width: 100%
Workflow visualization of translations in Sphinx. (The figure is created by
`plantuml <http://plantuml.com>`_.)
`plantuml <https://plantuml.com>`_.)
.. contents::
:local:
@ -118,7 +118,7 @@ section describe an easy way to translate with *sphinx-intl*.
#. Translate po files.
AS noted above, these are located in the ``./locale/<lang>/LC_MESSAGES``
As noted above, these are located in the ``./locale/<lang>/LC_MESSAGES``
directory. An example of one such file, from Sphinx, ``builders.po``, is
given below.
@ -193,7 +193,7 @@ pot file to the po file, use the :command:`sphinx-intl update` command.
.. code-block:: console
$ sphinx-intl update -p _build/locale
$ sphinx-intl update -p _build/gettext
Using Transifex service for team translation

View File

@ -61,7 +61,7 @@ This will return a dictionary containing the following items:
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
<http://jinja.pocoo.org/>`_ is:
<https://jinja.palletsprojects.com/>`_ is:
.. code-block:: html+jinja
@ -112,8 +112,8 @@ must update the websupport package's data::
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::
An example `Flask <https://flask.palletsprojects.com/>`_ function that checks
whether a user is logged in and then retrieves a document is::
from sphinxcontrib.websupport.errors import *
@ -152,8 +152,8 @@ To use the search form built-in to the Sphinx sidebar, create a function to
handle requests to the URL 'search' relative to the documentation root. The
user's search query will be in the GET parameters, with the key `q`. Then use
the :meth:`~sphinxcontrib.websupport.WebSupport.get_search_results` method to
retrieve search results. In `Flask <http://flask.pocoo.org/>`_ that would be
like this::
retrieve search results. In `Flask <https://flask.palletsprojects.com/>`_ that
would be like this::
@app.route('/search')
def search():

View File

@ -18,8 +18,8 @@ and output behavior.
directory to adjust `Docutils`_ configuration if not otherwise overridden or
set by Sphinx.
.. _`docutils`: http://docutils.sourceforge.net/
.. _`docutils.conf`: http://docutils.sourceforge.net/docs/user/config.html
.. _`docutils`: https://docutils.sourceforge.io/
.. _`docutils.conf`: https://docutils.sourceforge.io/docs/user/config.html
The configuration file is executed as Python code at build time (using
:func:`execfile`, and with the current directory set to its containing
@ -419,6 +419,20 @@ General configuration
.. versionadded:: 1.1
.. confval:: nitpick_ignore_regex
An extended version of :confval:`nitpick_ignore`, which instead interprets
the ``type`` and ``target`` strings as regular expressions. Note, that the
regular expression must match the whole string (as if the ``^`` and ``$``
markers were inserted).
For example, ``(r'py:.*', r'foo.*bar\.B.*')`` will ignore nitpicky warnings
for all python entities that start with ``'foo'`` and have ``'bar.B'`` in
them, such as ``('py:const', 'foo_package.bar.BAZ_VALUE')`` or
``('py:class', 'food.bar.Barman')``.
.. versionadded:: 4.1
.. confval:: numfig
If true, figures, tables and code-blocks are automatically numbered if they
@ -470,7 +484,7 @@ General configuration
languages, will be used to convert quotes and dashes to typographically
correct entities. Default: ``True``.
__ http://docutils.sourceforge.net/docs/user/smartquotes.html
__ https://docutils.sourceforge.io/docs/user/smartquotes.html
__ https://daringfireball.net/projects/smartypants/
.. versionadded:: 1.6.6
@ -483,8 +497,8 @@ General configuration
*deactivates* smart quotes via the corresponding `Docutils option`__. But
if it *activates* them, then :confval:`smartquotes` does prevail.
__ http://docutils.sourceforge.net/docs/user/config.html
__ http://docutils.sourceforge.net/docs/user/config.html#smart-quotes
__ https://docutils.sourceforge.io/docs/user/config.html
__ https://docutils.sourceforge.io/docs/user/config.html#smart-quotes
.. confval:: smartquotes_action
@ -577,17 +591,18 @@ General configuration
.. confval:: highlight_language
The default language to highlight source code in. The default is
``'python3'``. The value should be a valid Pygments lexer name, see
``'default'``. It is similar to ``'python3'``; it is mostly a superset of
``'python'`` but it fallbacks to ``'none'`` without warning if failed.
``'python3'`` and other languages will emit warning if failed.
The value should be a valid Pygments lexer name, see
:ref:`code-examples` for more details.
.. versionadded:: 0.5
.. versionchanged:: 1.4
The default is now ``'default'``. It is similar to ``'python3'``;
it is mostly a superset of ``'python'`` but it fallbacks to
``'none'`` without warning if failed. ``'python3'`` and other
languages will emit warning if failed. If you prefer Python 2
only highlighting, you can set it back to ``'python'``.
The default is now ``'default'``. If you prefer Python 2 only
highlighting, you can set it back to ``'python'``.
.. confval:: highlight_options
@ -780,6 +795,10 @@ documentation on :ref:`intl` for details.
The default is ``['locales']``.
.. note:: The :option:`-v option for sphinx-build command <sphinx-build -v>`
is useful to check the locale_dirs config works as expected. It
emits debug messages if message catalog directory not found.
.. versionchanged:: 1.5
Use ``locales`` directory as a default value
@ -1033,7 +1052,7 @@ that use Sphinx's HTMLWriter class.
A list of CSS files. The entry must be a *filename* string or a tuple
containing the *filename* string and the *attributes* dictionary. The
*filename* must be relative to the :confval:`html_static_path`, or a full URI
with scheme like ``http://example.org/style.css``. The *attributes* is used
with scheme like ``https://example.org/style.css``. The *attributes* is used
for attributes of ``<link>`` tag. It defaults to an empty list.
Example::
@ -1056,7 +1075,7 @@ that use Sphinx's HTMLWriter class.
A list of JavaScript *filename*. The entry must be a *filename* string or a
tuple containing the *filename* string and the *attributes* dictionary. The
*filename* must be relative to the :confval:`html_static_path`, or a full
URI with scheme like ``http://example.org/script.js``. The *attributes* is
URI with scheme like ``https://example.org/script.js``. The *attributes* is
used for attributes of ``<script>`` tag. It defaults to an empty list.
Example::
@ -1290,7 +1309,7 @@ that use Sphinx's HTMLWriter class.
.. confval:: html_use_opensearch
If nonempty, an `OpenSearch <http://www.opensearch.org/Home>`_ description
If nonempty, an `OpenSearch <https://www.opensearch.org/>`_ description
file will be output, and all pages will contain a ``<link>`` tag referring
to it. Since OpenSearch doesn't support relative URLs for its search page
location, the value of this option must be the base URL from which these
@ -1717,7 +1736,7 @@ Options for epub output
These options influence the epub output. As this builder derives from the HTML
builder, the HTML options also apply where appropriate. The actual values for
some of the options is not really important, they just have to be entered into
the `Dublin Core metadata <http://dublincore.org/>`_.
the `Dublin Core metadata <https://dublincore.org/>`_.
.. confval:: epub_basename
@ -2578,7 +2597,7 @@ Options for the linkcheck builder
as follows::
linkcheck_ignore = [
'http://www.sphinx-doc.org/en/1.7/intro.html#'
'https://www.sphinx-doc.org/en/1.7/intro.html#'
]
.. versionadded:: 1.5

View File

@ -343,6 +343,10 @@ inserting them into the page source under a suitable :rst:dir:`py:module`,
.. autoclass:: module.name::Noodle
* :rst:dir:`autoclass` also recognizes the ``class-doc-from`` option that
can be used to override the global value of :confval:`autoclass_content`.
.. versionadded:: 4.1
.. rst:directive:: autofunction
autodecorator
@ -459,6 +463,20 @@ There are also config values that you can set:
.. versionadded:: 1.4
.. confval:: autodoc_class_signature
This value selects how the signautre will be displayed for the class defined
by :rst:dir:`autoclass` directive. The possible values are:
``"mixed"``
Display the signature with the class name.
``"separated"``
Display the signature as a method.
The default is ``"mixed"``.
.. versionadded:: 4.1
.. confval:: autodoc_member_order
This value selects if automatically documented members are sorted
@ -507,7 +525,7 @@ There are also config values that you can set:
The supported options are ``'members'``, ``'member-order'``,
``'undoc-members'``, ``'private-members'``, ``'special-members'``,
``'inherited-members'``, ``'show-inheritance'``, ``'ignore-module-all'``,
``'imported-members'`` and ``'exclude-members'``.
``'imported-members'``, ``'exclude-members'`` and ``'class-doc-from'``.
.. versionadded:: 1.8
@ -517,6 +535,9 @@ There are also config values that you can set:
.. versionchanged:: 2.1
Added ``'imported-members'``.
.. versionchanged:: 4.1
Added ``'class-doc-from'``.
.. confval:: autodoc_docstring_signature
Functions imported from C modules cannot be introspected, and therefore the
@ -566,15 +587,27 @@ There are also config values that you can set:
This value controls how to represent typehints. The setting takes the
following values:
* ``'signature'`` -- Show typehints as its signature (default)
* ``'description'`` -- Show typehints as content of function or method
* ``'signature'`` -- Show typehints in the signature (default)
* ``'description'`` -- Show typehints as content of the function or method
The typehints of overloaded functions or methods will still be represented
in the signature.
* ``'none'`` -- Do not show typehints
* ``'both'`` -- Show typehints in the signature and as content of
the function or method
Overloaded functions or methods will not have typehints included in the
description because it is impossible to accurately represent all possible
overloads as a list of parameters.
.. versionadded:: 2.1
.. versionadded:: 3.0
New option ``'description'`` is added.
.. versionadded:: 4.1
New option ``'both'`` is added.
.. confval:: autodoc_typehints_description_target
This value controls whether the types of undocumented parameters and return
@ -730,6 +763,21 @@ needed docstring processing in event :event:`autodoc-process-docstring`:
.. autofunction:: cut_lines
.. autofunction:: between
.. event:: autodoc-process-bases (app, name, obj, options, bases)
.. versionadded:: 4.1
Emitted when autodoc has read and processed a class to determine the
base-classes. *bases* is a list of classes that the event handler can
modify **in place** to change what Sphinx puts into the output. It's
emitted only if ``show-inheritance`` option given.
:param app: the Sphinx application object
:param name: the fully qualified name of the object
:param obj: the object itself
:param options: the options given to the class directive
:param bases: the list of base classes signature. see above.
Skipping members
----------------

View File

@ -335,4 +335,4 @@ the title of a page.
You can use the :rst:dir:`autosummary` directive in the stub pages.
Stub pages are generated also based on these directives.
.. _`escape filter`: http://jinja.pocoo.org/docs/2.9/templates/#escape
.. _`escape filter`: https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.escape

View File

@ -230,7 +230,7 @@ There are also these config values:
.. graphviz::
digraph example {
a [label="sphinx", href="http://sphinx-doc.org", target="_top"];
a [label="sphinx", href="https://sphinx-doc.org", target="_top"];
b [label="other"];
a -> b;
}

View File

@ -220,7 +220,7 @@ Sphinx but is set to automatically include it from a third-party site.
The value is used as a parameter of ``MathJax.Hub.Config()``.
For more information, please read `Using in-line configuration options`__.
__ http://docs.mathjax.org/en/v2.7-latest/
__ https://docs.mathjax.org/en/v2.7-latest/
configuration.html#using-in-line-configuration-options
For example::

View File

@ -49,7 +49,7 @@ 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
.. _ReStructuredText: https://docutils.sourceforge.io/rst.html
.. _docstrings: https://www.python.org/dev/peps/pep-0287/
.. _Google Python Style Guide:
https://google.github.io/styleguide/pyguide.html
@ -267,14 +267,9 @@ Google style with types in docstrings::
`Python 2/3 compatible annotations`_ aren't currently
supported by Sphinx and won't show up in the docs.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
.. _PEP 526:
https://www.python.org/dev/peps/pep-0526/
.. _Python 2/3 compatible annotations:
https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
.. _PEP 484: https://www.python.org/dev/peps/pep-0484/
.. _PEP 526: https://www.python.org/dev/peps/pep-0526/
.. _Python 2/3 compatible annotations: https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
Configuration

View File

@ -189,26 +189,37 @@ the ``--pre`` flag.
Docker
------
Docker images for Sphinx are published on the `Docker Hub <https://hub.docker.com/>`_. There are two kind of images:
Docker images for Sphinx are published on the `Docker Hub`_. There are two kind
of images:
- `sphinxdoc/sphinx <https://hub.docker.com/repository/docker/sphinxdoc/sphinx>`_
- `sphinxdoc/sphinx-latexpdf <https://hub.docker.com/repository/docker/sphinxdoc/sphinx-latexpdf>`_
- `sphinxdoc/sphinx`_
- `sphinxdoc/sphinx-latexpdf`_
Former one is used for standard usage of Sphinx, and latter one is mainly used for PDF builds using LaTeX.
Please choose one for your purpose.
.. _Docker Hub: https://hub.docker.com/
.. _sphinxdoc/sphinx: https://hub.docker.com/repository/docker/sphinxdoc/sphinx
.. _sphinxdoc/sphinx-latexpdf: https://hub.docker.com/repository/docker/sphinxdoc/sphinx-latexpdf>
Former one is used for standard usage of Sphinx, and latter one is mainly used for
PDF builds using LaTeX. Please choose one for your purpose.
.. note::
sphinxdoc/sphinx-latexpdf contains TeXLive packages. So the image is very large (over 2GB!).
sphinxdoc/sphinx-latexpdf contains TeXLive packages. So the image is very large
(over 2GB!).
.. hint::
When using docker images, please use ``docker run`` command to invoke sphinx commands. For example,
you can use following command to create a Sphinx project::
When using docker images, please use ``docker run`` command to invoke sphinx
commands. For example, you can use following command to create a Sphinx
project:
.. code-block:: bash
$ docker run -it --rm -v /path/to/document:/docs sphinxdoc/sphinx sphinx-quickstart
And you can following command this to build HTML document::
And you can following command this to build HTML document:
.. code-block:: bash
$ docker run --rm -v /path/to/document:/docs sphinxdoc/sphinx make html

View File

@ -8,13 +8,13 @@ Markdown
`Markdown`__ is a lightweight markup language with a simplistic plain text
formatting syntax. It exists in many syntactically different *flavors*. To
support Markdown-based documentation, Sphinx can use `recommonmark`__.
recommonmark is a Docutils bridge to `CommonMark-py`__, a Python package for
support Markdown-based documentation, Sphinx can use `MyST-Parser`__.
MyST-Parser is a Docutils bridge to `markdown-it-py`__, a Python package for
parsing the `CommonMark`__ Markdown flavor.
__ https://daringfireball.net/projects/markdown/
__ https://recommonmark.readthedocs.io/en/latest/index.html
__ https://github.com/rtfd/CommonMark-py
__ https://myst-parser.readthedocs.io/en/latest/
__ https://github.com/executablebooks/markdown-it-py
__ https://commonmark.org/
Configuration
@ -22,23 +22,17 @@ Configuration
To configure your Sphinx project for Markdown support, proceed as follows:
#. Install the Markdown parser *recommonmark*::
#. Install the Markdown parser *MyST-Parser*::
pip install --upgrade recommonmark
pip install --upgrade myst-parser
.. note::
The configuration as explained here requires recommonmark version
0.5.0 or later.
#. Add *recommonmark* to the
#. Add *myst_parser* to the
:confval:`list of configured extensions <extensions>`::
extensions = ['recommonmark']
extensions = ['myst_parser']
.. versionchanged:: 1.8
Version 1.8 deprecates and version 3.0 removes the ``source_parsers``
configuration variable that was used by older *recommonmark* versions.
.. note::
MyST-Parser requires Sphinx 2.1 or newer.
#. If you want to use Markdown files with extensions other than ``.md``, adjust
the :confval:`source_suffix` variable. The following example configures
@ -51,8 +45,8 @@ To configure your Sphinx project for Markdown support, proceed as follows:
'.md': 'markdown',
}
#. You can further configure *recommonmark* to allow custom syntax that
standard *CommonMark* doesn't support. Read more in the `recommonmark
#. You can further configure *MyST-Parser* to allow custom syntax that
standard *CommonMark* doesn't support. Read more in the `MyST-Parser
documentation`__.
__ https://recommonmark.readthedocs.io/en/latest/auto_structify.html
__ https://myst-parser.readthedocs.io/en/latest/using/syntax-optional.html

View File

@ -24,7 +24,7 @@ default markup format used by Sphinx, :doc:`reStucturedText
For a great "introduction" to writing docs in general -- the whys and hows, see
also `Write the docs`__, written by Eric Holscher.
.. __: http://www.writethedocs.org/guide/writing/beginners-guide-to-docs/
.. __: https://www.writethedocs.org/guide/writing/beginners-guide-to-docs/
Setting up the documentation sources

View File

@ -15,7 +15,7 @@ language, this will not take too long.
.. seealso::
The authoritative `reStructuredText User Documentation
<http://docutils.sourceforge.net/rst.html>`_. The "ref" links in this
<https://docutils.sourceforge.io/rst.html>`_. The "ref" links in this
document link to the description of the individual constructs in the reST
reference.

View File

@ -424,7 +424,7 @@ code blocks using multiple varied syntaxes. Finally, the
in your documentation.
In all cases, Syntax highlighting is provided by `Pygments
<http://pygments.org>`_. When using literal blocks, this is configured using
<https://pygments.org>`_. When using literal blocks, this is configured using
any :rst:dir:`highlight` directives in the source file. When a ``highlight``
directive is encountered, it is used until the next ``highlight`` directive is
encountered. If there is no ``highlight`` directive in the file, the global
@ -452,7 +452,7 @@ If highlighting with the selected language fails (i.e. Pygments emits an
want to ensure consistent highlighting, you should fix your version of
Pygments.
__ http://pygments.org/docs/lexers
__ https://pygments.org/docs/lexers
.. rst:directive:: .. highlight:: language

View File

@ -1680,6 +1680,9 @@ There is a set of directives allowing documenting command-line programs:
then ``:option:`rm -r``` would refer to the first option, while
``:option:`svn -r``` would refer to the second one.
If ``None`` is passed to the argument, the directive will reset the
current program name.
The program name may contain spaces (in case you want to document
subcommands like ``svn add`` and ``svn commit`` separately).

View File

@ -12,7 +12,7 @@ The below guides go through the most important aspects of reST. For the
authoritative reStructuredText reference, refer to the `docutils
documentation`__.
__ http://docutils.sourceforge.net/rst.html
__ https://docutils.sourceforge.io/rst.html
.. toctree::
:maxdepth: 2

View File

@ -248,7 +248,8 @@ These themes are:
**scrolls**
A more lightweight theme, based on `the Jinja documentation
<http://jinja.pocoo.org/>`_. The following color options are available:
<https://jinja.palletsprojects.com/>`_. The following color options are
available:
- **headerbordercolor**
- **subheadlinecolor**

12
package-lock.json generated
View File

@ -486,9 +486,9 @@
}
},
"glob-parent": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.0.0.tgz",
"integrity": "sha512-Z2RwiujPRGluePM6j699ktJYxmPpJKCfpGA13jz2hmFZC7gKetzrWvg5KN3+OsIFmydGyZ1AVwERCq1w/ZZwRg==",
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"requires": {
"is-glob": "^4.0.1"
@ -704,9 +704,9 @@
}
},
"lodash": {
"version": "4.17.19",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz",
"integrity": "sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ==",
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"dev": true
},
"log4js": {

View File

@ -44,8 +44,11 @@ extras_require = {
'lint': [
'flake8>=3.5.0',
'isort',
'mypy>=0.800',
'mypy>=0.900',
'docutils-stubs',
"types-typed-ast",
"types-pkg_resources",
"types-requests",
],
'test': [
'pytest',
@ -173,7 +176,7 @@ else:
setup(
name='Sphinx',
version=sphinx.__version__,
url='http://sphinx-doc.org/',
url='https://sphinx-doc.org/',
download_url='https://pypi.org/project/Sphinx/',
license='BSD',
author='Georg Brandl',

View File

@ -27,8 +27,8 @@ if 'PYTHONWARNINGS' not in os.environ:
warnings.filterwarnings('ignore', "'U' mode is deprecated",
DeprecationWarning, module='docutils.io')
__version__ = '4.0.3+'
__released__ = '4.0.3' # used when Sphinx builds its own docs
__version__ = '4.1.0'
__released__ = '4.1.0' # used when Sphinx builds its own docs
#: Version info for better programmatic use.
#:
@ -38,7 +38,7 @@ __released__ = '4.0.3' # used when Sphinx builds its own docs
#:
#: .. versionadded:: 1.2
#: Before version 1.2, check the string ``sphinx.__version__``.
version_info = (4, 0, 3, 'beta', 0)
version_info = (4, 1, 0, 'final', 0)
package_dir = path.abspath(path.dirname(__file__))

View File

@ -14,6 +14,7 @@ import os
import pickle
import platform
import sys
import warnings
from collections import deque
from io import StringIO
from os import path
@ -29,6 +30,7 @@ from pygments.lexer import Lexer
import sphinx
from sphinx import locale, package_dir
from sphinx.config import Config
from sphinx.deprecation import RemovedInSphinx60Warning
from sphinx.domains import Domain, Index
from sphinx.environment import BuildEnvironment
from sphinx.environment.collectors import EnvironmentCollector
@ -141,22 +143,15 @@ class Sphinx:
self.phase = BuildPhase.INITIALIZATION
self.verbosity = verbosity
self.extensions: Dict[str, Extension] = {}
self.builder: Builder = None
self.env: BuildEnvironment = None
self.project: Project = None
self.builder: Optional[Builder] = None
self.env: Optional[BuildEnvironment] = None
self.project: Optional[Project] = None
self.registry = SphinxComponentRegistry()
self.html_themes: Dict[str, str] = {}
# validate provided directories
self.srcdir = abspath(srcdir)
self.outdir = abspath(outdir)
self.doctreedir = abspath(doctreedir)
self.confdir = confdir
if self.confdir: # confdir is optional
self.confdir = abspath(self.confdir)
if not path.isfile(path.join(self.confdir, 'conf.py')):
raise ApplicationError(__("config directory doesn't contain a "
"conf.py file (%s)") % confdir)
if not path.isdir(self.srcdir):
raise ApplicationError(__('Cannot find source directory (%s)') %
@ -174,7 +169,7 @@ class Sphinx:
if status is None:
self._status: IO = StringIO()
self.quiet = True
self.quiet: bool = True
else:
self._status = status
self.quiet = False
@ -211,9 +206,13 @@ class Sphinx:
# read config
self.tags = Tags(tags)
if self.confdir is None:
if confdir is None:
# set confdir to srcdir if -C given (!= no confdir); a few pieces
# of code expect a confdir to be set
self.confdir = self.srcdir
self.config = Config({}, confoverrides or {})
else:
self.confdir = abspath(confdir)
self.config = Config.read(self.confdir, confoverrides or {}, self.tags)
# initialize some limited config variables before initialize i18n and loading
@ -229,11 +228,6 @@ class Sphinx:
__('This project needs at least Sphinx v%s and therefore cannot '
'be built with this version.') % self.config.needs_sphinx)
# set confdir to srcdir if -C given (!= no confdir); a few pieces
# of code expect a confdir to be set
if self.confdir is None:
self.confdir = self.srcdir
# load all built-in extension modules
for extension in builtin_extensions:
self.setup_extension(extension)
@ -306,8 +300,7 @@ class Sphinx:
def _init_env(self, freshenv: bool) -> None:
filename = path.join(self.doctreedir, ENV_PICKLE_FILENAME)
if freshenv or not os.path.exists(filename):
self.env = BuildEnvironment()
self.env.setup(self)
self.env = BuildEnvironment(self)
self.env.find_files(self.config, self.builder)
else:
try:
@ -662,10 +655,10 @@ class Sphinx:
...
def setup(app):
add_directive('my-directive', MyDirective)
app.add_directive('my-directive', MyDirective)
For more details, see `the Docutils docs
<http://docutils.sourceforge.net/docs/howto/rst-directives.html>`__ .
<https://docutils.sourceforge.io/docs/howto/rst-directives.html>`__ .
.. versionchanged:: 0.6
Docutils 0.5-style directive classes are now supported.
@ -690,7 +683,7 @@ class Sphinx:
installed as the same name
For more details about role functions, see `the Docutils docs
<http://docutils.sourceforge.net/docs/howto/rst-roles.html>`__ .
<https://docutils.sourceforge.io/docs/howto/rst-roles.html>`__ .
.. versionchanged:: 1.8
Add *override* keyword.
@ -928,7 +921,7 @@ class Sphinx:
refs: `Transform Priority Range Categories`__
__ http://docutils.sourceforge.net/docs/ref/transforms.html#transform-priority-range-categories
__ https://docutils.sourceforge.io/docs/ref/transforms.html#transform-priority-range-categories
""" # NOQA
self.registry.add_transform(transform)
@ -1184,13 +1177,13 @@ class Sphinx:
def add_html_theme(self, name: str, theme_path: str) -> None:
"""Register a HTML Theme.
The *name* is a name of theme, and *path* is a full path to the theme
(refs: :ref:`distribute-your-theme`).
The *name* is a name of theme, and *theme_path* is a full path to the
theme (refs: :ref:`distribute-your-theme`).
.. versionadded:: 1.6
"""
logger.debug('[app] adding HTML theme: %r, %r', name, theme_path)
self.html_themes[name] = theme_path
self.registry.add_html_theme(name, theme_path)
def add_html_math_renderer(self, name: str,
inline_renderers: Tuple[Callable, Callable] = None,
@ -1257,6 +1250,12 @@ class Sphinx:
return True
@property
def html_themes(self) -> Dict[str, str]:
warnings.warn('app.html_themes is deprecated.',
RemovedInSphinx60Warning)
return self.registry.html_themes
class TemplateBridge:
"""

View File

@ -11,7 +11,8 @@
import pickle
import time
from os import path
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence, Set, Tuple, Type, Union
from typing import (TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple,
Type, Union)
from docutils import nodes
from docutils.nodes import Node
@ -88,7 +89,7 @@ class Builder:
ensuredir(self.doctreedir)
self.app: Sphinx = app
self.env: BuildEnvironment = None
self.env: Optional[BuildEnvironment] = None
self.events: EventManager = app.events
self.config: Config = app.config
self.tags: Tags = app.tags
@ -225,7 +226,7 @@ class Builder:
self.compile_catalogs(set(repo.catalogs), message)
def compile_specific_catalogs(self, specified_files: List[str]) -> None:
def to_domain(fpath: str) -> str:
def to_domain(fpath: str) -> Optional[str]:
docname = self.env.path2doc(path.abspath(fpath))
if docname:
return docname_to_domain(docname, self.config.gettext_compact)

View File

@ -13,7 +13,6 @@ from typing import Any, Dict
from sphinx.application import Sphinx
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.util import logging
from sphinx.util.osutil import SEP, os_path
@ -46,17 +45,6 @@ class DirectoryHTMLBuilder(StandaloneHTMLBuilder):
return outfilename
# for compatibility
deprecated_alias('sphinx.builders.html',
{
'DirectoryHTMLBuilder': DirectoryHTMLBuilder,
},
RemovedInSphinx40Warning,
{
'DirectoryHTMLBuilder': 'sphinx.builders.dirhtml.DirectoryHTMLBuilder',
})
def setup(app: Sphinx) -> Dict[str, Any]:
app.setup_extension('sphinx.builders.html')

View File

@ -21,7 +21,7 @@ from queue import PriorityQueue, Queue
from threading import Thread
from typing import (Any, Dict, Generator, List, NamedTuple, Optional, Pattern, Set, Tuple,
Union, cast)
from urllib.parse import unquote, urlparse
from urllib.parse import unquote, urlparse, urlunparse
from docutils import nodes
from docutils.nodes import Element
@ -129,7 +129,7 @@ class CheckExternalLinksBuilder(DummyBuilder):
# create queues and worker threads
self._wqueue: PriorityQueue[CheckRequestType] = PriorityQueue()
self._rqueue: Queue = Queue()
self._rqueue: Queue[CheckResult] = Queue()
@property
def anchors_ignore(self) -> List[Pattern]:
@ -228,43 +228,39 @@ class CheckExternalLinksBuilder(DummyBuilder):
)
return self._wqueue
def process_result(self, result: Tuple[str, str, int, str, str, int]) -> None:
uri, docname, lineno, status, info, code = result
def process_result(self, result: CheckResult) -> None:
filename = self.env.doc2path(result.docname, None)
filename = self.env.doc2path(docname, None)
linkstat = dict(filename=filename, lineno=lineno,
status=status, code=code, uri=uri,
info=info)
if status == 'unchecked':
self.write_linkstat(linkstat)
linkstat = dict(filename=filename, lineno=result.lineno,
status=result.status, code=result.code, uri=result.uri,
info=result.message)
self.write_linkstat(linkstat)
if result.status == 'unchecked':
return
if status == 'working' and info == 'old':
self.write_linkstat(linkstat)
if result.status == 'working' and result.message == 'old':
return
if lineno:
logger.info('(%16s: line %4d) ', docname, lineno, nonl=True)
if status == 'ignored':
if info:
logger.info(darkgray('-ignored- ') + uri + ': ' + info)
if result.lineno:
logger.info('(%16s: line %4d) ', result.docname, result.lineno, nonl=True)
if result.status == 'ignored':
if result.message:
logger.info(darkgray('-ignored- ') + result.uri + ': ' + result.message)
else:
logger.info(darkgray('-ignored- ') + uri)
self.write_linkstat(linkstat)
elif status == 'local':
logger.info(darkgray('-local- ') + uri)
self.write_entry('local', docname, filename, lineno, uri)
self.write_linkstat(linkstat)
elif status == 'working':
logger.info(darkgreen('ok ') + uri + info)
self.write_linkstat(linkstat)
elif status == 'broken':
logger.info(darkgray('-ignored- ') + result.uri)
elif result.status == 'local':
logger.info(darkgray('-local- ') + result.uri)
self.write_entry('local', result.docname, filename, result.lineno, result.uri)
elif result.status == 'working':
logger.info(darkgreen('ok ') + result.uri + result.message)
elif result.status == 'broken':
if self.app.quiet or self.app.warningiserror:
logger.warning(__('broken link: %s (%s)'), uri, info,
location=(filename, lineno))
logger.warning(__('broken link: %s (%s)'), result.uri, result.message,
location=(filename, result.lineno))
else:
logger.info(red('broken ') + uri + red(' - ' + info))
self.write_entry('broken', docname, filename, lineno, uri + ': ' + info)
self.write_linkstat(linkstat)
elif status == 'redirected':
logger.info(red('broken ') + result.uri + red(' - ' + result.message))
self.write_entry('broken', result.docname, filename, result.lineno,
result.uri + ': ' + result.message)
elif result.status == 'redirected':
try:
text, color = {
301: ('permanently', purple),
@ -272,16 +268,16 @@ class CheckExternalLinksBuilder(DummyBuilder):
303: ('with See Other', purple),
307: ('temporarily', turquoise),
308: ('permanently', purple),
}[code]
}[result.code]
except KeyError:
text, color = ('with unknown code', purple)
linkstat['text'] = text
logger.info(color('redirect ') + uri + color(' - ' + text + ' to ' + info))
self.write_entry('redirected ' + text, docname, filename,
lineno, uri + ' to ' + info)
self.write_linkstat(linkstat)
logger.info(color('redirect ') + result.uri +
color(' - ' + text + ' to ' + result.message))
self.write_entry('redirected ' + text, result.docname, filename,
result.lineno, result.uri + ' to ' + result.message)
else:
raise ValueError("Unknown status %s." % status)
raise ValueError("Unknown status %s." % result.status)
def write_entry(self, what: str, docname: str, filename: str, line: int,
uri: str) -> None:
@ -578,7 +574,7 @@ class HyperlinkAvailabilityCheckWorker(Thread):
if status == 'rate-limited':
logger.info(darkgray('-rate limited- ') + uri + darkgray(' | sleeping...'))
else:
self.rqueue.put((uri, docname, lineno, status, info, code))
self.rqueue.put(CheckResult(uri, docname, lineno, status, info, code))
self.wqueue.task_done()
def limit_rate(self, response: Response) -> Optional[float]:
@ -633,6 +629,10 @@ class HyperlinkCollector(SphinxPostTransform):
if 'refuri' not in refnode:
continue
uri = refnode['refuri']
newuri = self.app.emit_firstresult('linkcheck-process-uri', uri)
if newuri:
uri = newuri
lineno = get_node_line(refnode)
uri_info = Hyperlink(uri, self.env.docname, lineno)
if uri not in hyperlinks:
@ -642,12 +642,31 @@ class HyperlinkCollector(SphinxPostTransform):
for imgnode in self.document.traverse(nodes.image):
uri = imgnode['candidates'].get('?')
if uri and '://' in uri:
newuri = self.app.emit_firstresult('linkcheck-process-uri', uri)
if newuri:
uri = newuri
lineno = get_node_line(imgnode)
uri_info = Hyperlink(uri, self.env.docname, lineno)
if uri not in hyperlinks:
hyperlinks[uri] = uri_info
def rewrite_github_anchor(app: Sphinx, uri: str) -> Optional[str]:
"""Rewrite anchor name of the hyperlink to github.com
The hyperlink anchors in github.com are dynamically generated. This rewrites
them before checking and makes them comparable.
"""
parsed = urlparse(uri)
if parsed.hostname == "github.com" and parsed.fragment:
prefixed = parsed.fragment.startswith('user-content-')
if not prefixed:
fragment = f'user-content-{parsed.fragment}'
return urlunparse(parsed._replace(fragment=fragment))
return None
def setup(app: Sphinx) -> Dict[str, Any]:
app.add_builder(CheckExternalLinksBuilder)
app.add_post_transform(HyperlinkCollector)
@ -664,6 +683,9 @@ def setup(app: Sphinx) -> Dict[str, Any]:
app.add_config_value('linkcheck_anchors_ignore', ["^!"], None)
app.add_config_value('linkcheck_rate_limit_timeout', 300.0, None)
app.add_event('linkcheck-process-uri')
app.connect('linkcheck-process-uri', rewrite_github_anchor)
return {
'version': 'builtin',
'parallel_read_safe': True,

View File

@ -79,8 +79,9 @@ class ManualPageBuilder(Builder):
docsettings.section = section
if self.config.man_make_section_directory:
ensuredir(path.join(self.outdir, str(section)))
targetname = '%s/%s.%s' % (section, name, section)
dirname = 'man%s' % section
ensuredir(path.join(self.outdir, dirname))
targetname = '%s/%s.%s' % (dirname, name, section)
else:
targetname = '%s.%s' % (name, section)

View File

@ -16,7 +16,6 @@ from docutils.nodes import Node
from sphinx.application import Sphinx
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias
from sphinx.environment.adapters.toctree import TocTree
from sphinx.locale import __
from sphinx.util import logging, progress_message
@ -187,18 +186,6 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder):
self.handle_page('opensearch', {}, 'opensearch.xml', outfilename=fn)
# for compatibility
deprecated_alias('sphinx.builders.html',
{
'SingleFileHTMLBuilder': SingleFileHTMLBuilder,
},
RemovedInSphinx40Warning,
{
'SingleFileHTMLBuilder':
'sphinx.builders.singlehtml.SingleFileHTMLBuilder',
})
def setup(app: Sphinx) -> Dict[str, Any]:
app.setup_extension('sphinx.builders.html')

View File

@ -131,6 +131,7 @@ class Config:
'manpages_url': (None, 'env', []),
'nitpicky': (False, None, []),
'nitpick_ignore': ([], None, []),
'nitpick_ignore_regex': ([], None, []),
'numfig': (False, 'env', []),
'numfig_secnum_depth': (1, 'env', []),
'numfig_format': ({}, 'env', []), # will be initialized in init_numfig_format()
@ -165,6 +166,9 @@ class Config:
def read(cls, confdir: str, overrides: Dict = None, tags: Tags = None) -> "Config":
"""Create a Config object from configuration file."""
filename = path.join(confdir, CONFIG_FILENAME)
if not path.isfile(filename):
raise ConfigError(__("config directory doesn't contain a conf.py file (%s)") %
confdir)
namespace = eval_config_file(filename, tags)
return cls(namespace, overrides or {})
@ -309,7 +313,7 @@ class Config:
self.__dict__.update(state)
def eval_config_file(filename: str, tags: Tags) -> Dict[str, Any]:
def eval_config_file(filename: str, tags: Optional[Tags]) -> Dict[str, Any]:
"""Evaluate a config file."""
namespace: Dict[str, Any] = {}
namespace['__file__'] = filename

View File

@ -14,10 +14,6 @@ from importlib import import_module
from typing import Any, Dict, Type
class RemovedInSphinx40Warning(DeprecationWarning):
pass
class RemovedInSphinx50Warning(DeprecationWarning):
pass

View File

@ -11,8 +11,8 @@
import copy
from abc import ABC, abstractmethod
from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, List, NamedTuple, Tuple,
Type, Union, cast)
from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, List, NamedTuple, Optional,
Tuple, Type, Union, cast)
from docutils import nodes
from docutils.nodes import Element, Node, system_message
@ -196,7 +196,7 @@ class Domain:
#: data value for a fresh environment
initial_data: Dict = {}
#: data value
data: Dict = None
data: Dict
#: data version, bump this when the format of `self.data` changes
data_version = 0
@ -251,7 +251,7 @@ class Domain:
for role in objtype.roles:
self._role2type.setdefault(role, []).append(name)
def role(self, name: str) -> RoleFunction:
def role(self, name: str) -> Optional[RoleFunction]:
"""Return a role adapter function that always gives the registered
role its full name ('domain:name') as the first argument.
"""
@ -269,7 +269,7 @@ class Domain:
self._role_cache[name] = role_adapter
return role_adapter
def directive(self, name: str) -> Callable:
def directive(self, name: str) -> Optional[Callable]:
"""Return a directive adapter class that always gives the registered
directive its full name ('domain:name') as ``self.name``.
"""
@ -318,7 +318,7 @@ class Domain:
def resolve_xref(self, env: "BuildEnvironment", fromdocname: str, builder: "Builder",
typ: str, target: str, node: pending_xref, contnode: Element
) -> Element:
) -> Optional[Element]:
"""Resolve the pending_xref *node* with the given *typ* and *target*.
This method should return a new node, to replace the xref node,
@ -393,11 +393,11 @@ class Domain:
return type.lname
return _('%s %s') % (self.label, type.lname)
def get_enumerable_node_type(self, node: Node) -> str:
def get_enumerable_node_type(self, node: Node) -> Optional[str]:
"""Get type of enumerable nodes (experimental)."""
enum_node_type, _ = self.enumerable_nodes.get(node.__class__, (None, None))
return enum_node_type
def get_full_qualified_name(self, node: Element) -> str:
def get_full_qualified_name(self, node: Element) -> Optional[str]:
"""Return full qualified name for given node."""
return None

View File

@ -9,7 +9,8 @@
"""
import re
from typing import Any, Callable, Dict, Generator, Iterator, List, Tuple, TypeVar, Union, cast
from typing import (Any, Callable, Dict, Generator, Iterator, List, Optional, Tuple, TypeVar,
Union, cast)
from docutils import nodes
from docutils.nodes import Element, Node, TextElement, system_message
@ -3114,7 +3115,7 @@ class CObject(ObjectDescription[ASTDeclaration]):
doc_field_types = [
TypedField('parameter', label=_('Parameters'),
names=('param', 'parameter', 'arg', 'argument'),
typerolename='type', typenames=('type',)),
typerolename='expr', typenames=('type',)),
Field('returnvalue', label=_('Returns'), has_arg=False,
names=('returns', 'return')),
Field('returntype', label=_('Return type'), has_arg=False,
@ -3807,7 +3808,7 @@ class CDomain(Domain):
def _resolve_xref_inner(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
typ: str, target: str, node: pending_xref,
contnode: Element) -> Tuple[Element, str]:
contnode: Element) -> Tuple[Optional[Element], Optional[str]]:
parser = DefinitionParser(target, location=node, config=env.config)
try:
name = parser.parse_xref_object()
@ -3844,7 +3845,7 @@ class CDomain(Domain):
def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
typ: str, target: str, node: pending_xref,
contnode: Element) -> Element:
contnode: Element) -> Optional[Element]:
return self._resolve_xref_inner(env, fromdocname, builder, typ,
target, node, contnode)[0]

View File

@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING, Any, Dict, List, Set, Tuple, cast
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, cast
from docutils import nodes
from docutils.nodes import Element
@ -88,7 +88,7 @@ class CitationDomain(Domain):
def resolve_xref(self, env: "BuildEnvironment", fromdocname: str, builder: "Builder",
typ: str, target: str, node: pending_xref, contnode: Element
) -> Element:
) -> Optional[Element]:
docname, labelid, lineno = self.citations.get(target, ('', '', 0))
if not docname:
return None

View File

@ -2292,6 +2292,10 @@ class ASTDeclarator(ASTBase):
def name(self) -> ASTNestedName:
raise NotImplementedError(repr(self))
@name.setter
def name(self, name: ASTNestedName) -> None:
raise NotImplementedError(repr(self))
@property
def isPack(self) -> bool:
raise NotImplementedError(repr(self))
@ -2339,6 +2343,10 @@ class ASTDeclaratorNameParamQual(ASTDeclarator):
def name(self) -> ASTNestedName:
return self.declId
@name.setter
def name(self, name: ASTNestedName) -> None:
self.declId = name
@property
def isPack(self) -> bool:
return False
@ -2420,6 +2428,10 @@ class ASTDeclaratorNameBitField(ASTDeclarator):
def name(self) -> ASTNestedName:
return self.declId
@name.setter
def name(self, name: ASTNestedName) -> None:
self.declId = name
def get_param_id(self, version: int) -> str: # only the parameters (if any)
return ''
@ -2466,6 +2478,10 @@ class ASTDeclaratorPtr(ASTDeclarator):
def name(self) -> ASTNestedName:
return self.next.name
@name.setter
def name(self, name: ASTNestedName) -> None:
self.next.name = name
@property
def function_params(self) -> List[ASTFunctionParameter]:
return self.next.function_params
@ -2565,6 +2581,10 @@ class ASTDeclaratorRef(ASTDeclarator):
def name(self) -> ASTNestedName:
return self.next.name
@name.setter
def name(self, name: ASTNestedName) -> None:
self.next.name = name
@property
def isPack(self) -> bool:
return True
@ -2629,6 +2649,10 @@ class ASTDeclaratorParamPack(ASTDeclarator):
def name(self) -> ASTNestedName:
return self.next.name
@name.setter
def name(self, name: ASTNestedName) -> None:
self.next.name = name
@property
def function_params(self) -> List[ASTFunctionParameter]:
return self.next.function_params
@ -2689,6 +2713,10 @@ class ASTDeclaratorMemPtr(ASTDeclarator):
def name(self) -> ASTNestedName:
return self.next.name
@name.setter
def name(self, name: ASTNestedName) -> None:
self.next.name = name
@property
def function_params(self) -> List[ASTFunctionParameter]:
return self.next.function_params
@ -2782,6 +2810,10 @@ class ASTDeclaratorParen(ASTDeclarator):
def name(self) -> ASTNestedName:
return self.inner.name
@name.setter
def name(self, name: ASTNestedName) -> None:
self.inner.name = name
@property
def function_params(self) -> List[ASTFunctionParameter]:
return self.inner.function_params
@ -2913,6 +2945,10 @@ class ASTType(ASTBase):
def name(self) -> ASTNestedName:
return self.decl.name
@name.setter
def name(self, name: ASTNestedName) -> None:
self.decl.name = name
@property
def isPack(self) -> bool:
return self.decl.isPack
@ -6810,7 +6846,7 @@ class CPPObject(ObjectDescription[ASTDeclaration]):
GroupedField('template parameter', label=_('Template Parameters'),
names=('tparam', 'template parameter'),
can_collapse=True),
GroupedField('exceptions', label=_('Throws'), rolename='cpp:class',
GroupedField('exceptions', label=_('Throws'), rolename='expr',
names=('throws', 'throw', 'exception'),
can_collapse=True),
Field('returnvalue', label=_('Returns'), has_arg=False,
@ -7558,7 +7594,7 @@ class CPPDomain(Domain):
def _resolve_xref_inner(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
typ: str, target: str, node: pending_xref,
contnode: Element) -> Tuple[Element, str]:
contnode: Element) -> Tuple[Optional[Element], Optional[str]]:
# add parens again for those that could be functions
if typ == 'any' or typ == 'func':
target += '()'
@ -7707,7 +7743,7 @@ class CPPDomain(Domain):
def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
typ: str, target: str, node: pending_xref, contnode: Element
) -> Element:
) -> Optional[Element]:
return self._resolve_xref_inner(env, fromdocname, builder, typ,
target, node, contnode)[0]

View File

@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
from typing import Any, Dict, Iterator, List, Tuple, cast
from typing import Any, Dict, Iterator, List, Optional, Tuple, cast
from docutils import nodes
from docutils.nodes import Element, Node
@ -215,7 +215,7 @@ class JSCallable(JSObject):
TypedField('arguments', label=_('Arguments'),
names=('argument', 'arg', 'parameter', 'param'),
typerolename='func', typenames=('paramtype', 'type')),
GroupedField('errors', label=_('Throws'), rolename='err',
GroupedField('errors', label=_('Throws'), rolename='func',
names=('throws', ),
can_collapse=True),
Field('returnvalue', label=_('Returns'), has_arg=False,
@ -413,7 +413,7 @@ class JavaScriptDomain(Domain):
def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
typ: str, target: str, node: pending_xref, contnode: Element
) -> Element:
) -> Optional[Element]:
mod_name = node.get('js:module')
prefix = node.get('js:object')
searchorder = 1 if node.hasattr('refspecific') else 0

View File

@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Tuple
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple
from docutils import nodes
from docutils.nodes import Element, Node, make_id, system_message
@ -97,7 +97,7 @@ class MathDomain(Domain):
def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: "Builder",
typ: str, target: str, node: pending_xref, contnode: Element
) -> Element:
) -> Optional[Element]:
assert typ in ('eq', 'numref')
docname, number = self.equations.get(target, (None, None))
if docname:

View File

@ -15,11 +15,12 @@ import sys
import typing
import warnings
from inspect import Parameter
from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Tuple, Type, cast
from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Optional, Tuple, Type, cast
from docutils import nodes
from docutils.nodes import Element, Node
from docutils.parsers.rst import directives
from docutils.parsers.rst.states import Inliner
from sphinx import addnodes
from sphinx.addnodes import desc_signature, pending_xref, pending_xref_condition
@ -284,9 +285,13 @@ def _pseudo_parse_arglist(signode: desc_signature, arglist: str) -> None:
class PyXrefMixin:
def make_xref(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
contnode: Node = None, env: BuildEnvironment = None,
inliner: Inliner = None, location: Node = None) -> Node:
# we use inliner=None to make sure we get the old behaviour with a single
# pending_xref node
result = super().make_xref(rolename, domain, target, # type: ignore
innernode, contnode, env)
innernode, contnode,
env, inliner=None, location=None)
result['refspecific'] = True
result['py:module'] = env.ref_context.get('py:module')
result['py:class'] = env.ref_context.get('py:class')
@ -299,12 +304,23 @@ class PyXrefMixin:
for node in result.traverse(nodes.Text):
node.parent[node.parent.index(node)] = nodes.Text(text)
break
elif isinstance(result, pending_xref) and env.config.python_use_unqualified_type_names:
children = result.children
result.clear()
shortname = target.split('.')[-1]
textnode = innernode('', shortname)
contnodes = [pending_xref_condition('', '', textnode, condition='resolved'),
pending_xref_condition('', '', *children, condition='*')]
result.extend(contnodes)
return result
def make_xrefs(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> List[Node]:
delims = r'(\s*[\[\]\(\),](?:\s*or\s)?\s*|\s+or\s+|\.\.\.)'
contnode: Node = None, env: BuildEnvironment = None,
inliner: Inliner = None, location: Node = None) -> List[Node]:
delims = r'(\s*[\[\]\(\),](?:\s*or\s)?\s*|\s+or\s+|\s*\|\s*|\.\.\.)'
delims_re = re.compile(delims)
sub_targets = re.split(delims, target)
@ -319,7 +335,7 @@ class PyXrefMixin:
results.append(contnode or innernode(sub_target, sub_target))
else:
results.append(self.make_xref(rolename, domain, sub_target,
innernode, contnode, env))
innernode, contnode, env, inliner, location))
return results
@ -327,12 +343,14 @@ class PyXrefMixin:
class PyField(PyXrefMixin, Field):
def make_xref(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
contnode: Node = None, env: BuildEnvironment = None,
inliner: Inliner = None, location: Node = None) -> Node:
if rolename == 'class' and target == 'None':
# None is not a type, so use obj role instead.
rolename = 'obj'
return super().make_xref(rolename, domain, target, innernode, contnode, env)
return super().make_xref(rolename, domain, target, innernode, contnode,
env, inliner, location)
class PyGroupedField(PyXrefMixin, GroupedField):
@ -342,12 +360,14 @@ class PyGroupedField(PyXrefMixin, GroupedField):
class PyTypedField(PyXrefMixin, TypedField):
def make_xref(self, rolename: str, domain: str, target: str,
innernode: Type[TextlikeNode] = nodes.emphasis,
contnode: Node = None, env: BuildEnvironment = None) -> Node:
contnode: Node = None, env: BuildEnvironment = None,
inliner: Inliner = None, location: Node = None) -> Node:
if rolename == 'class' and target == 'None':
# None is not a type, so use obj role instead.
rolename = 'obj'
return super().make_xref(rolename, domain, target, innernode, contnode, env)
return super().make_xref(rolename, domain, target, innernode, contnode,
env, inliner, location)
class PyObject(ObjectDescription[Tuple[str, str]]):
@ -448,12 +468,9 @@ class PyObject(ObjectDescription[Tuple[str, str]]):
if prefix:
signode += addnodes.desc_addname(prefix, prefix)
elif add_module and self.env.config.add_module_names:
if modname and modname != 'exceptions':
# exceptions are a special case, since they are documented in the
# 'exceptions' module.
nodetext = modname + '.'
signode += addnodes.desc_addname(nodetext, nodetext)
elif modname and add_module and self.env.config.add_module_names:
nodetext = modname + '.'
signode += addnodes.desc_addname(nodetext, nodetext)
signode += addnodes.desc_name(name, name)
if arglist:
@ -1246,7 +1263,7 @@ class PythonDomain(Domain):
def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
type: str, target: str, node: pending_xref, contnode: Element
) -> Element:
) -> Optional[Element]:
modname = node.get('py:module')
clsname = node.get('py:class')
searchmode = 1 if node.hasattr('refspecific') else 0
@ -1344,7 +1361,7 @@ class PythonDomain(Domain):
else:
yield (refname, refname, obj.objtype, obj.docname, obj.node_id, 1)
def get_full_qualified_name(self, node: Element) -> str:
def get_full_qualified_name(self, node: Element) -> Optional[str]:
modname = node.get('py:module')
clsname = node.get('py:class')
target = node.get('reftarget')
@ -1363,10 +1380,6 @@ def builtin_resolver(app: Sphinx, env: BuildEnvironment,
return s in typing.__all__ # type: ignore
content = find_pending_xref_condition(node, 'resolved')
if content:
contnode = content.children[0] # type: ignore
if node.get('refdomain') != 'py':
return None
elif node.get('reftype') in ('class', 'obj') and node.get('reftarget') == 'None':

View File

@ -9,7 +9,7 @@
"""
import re
from typing import Any, Dict, Iterator, List, Tuple, cast
from typing import Any, Dict, Iterator, List, Optional, Tuple, cast
from docutils.nodes import Element
from docutils.parsers.rst import directives
@ -247,7 +247,7 @@ class ReSTDomain(Domain):
def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder,
typ: str, target: str, node: pending_xref, contnode: Element
) -> Element:
) -> Optional[Element]:
objtypes = self.objtypes_for_role(typ)
for objtype in objtypes:
todocname, node_id = self.objects.get((objtype, target), (None, None))

View File

@ -285,7 +285,7 @@ class OptionXRefRole(XRefRole):
def split_term_classifiers(line: str) -> List[Optional[str]]:
# split line into a term and classifiers. if no classifier, None is used..
parts = re.split(' +: +', line) + [None]
parts: List[Optional[str]] = re.split(' +: +', line) + [None]
return parts
@ -621,7 +621,7 @@ class StandardDomain(Domain):
}
# node_class -> (figtype, title_getter)
enumerable_nodes: Dict[Type[Node], Tuple[str, Callable]] = {
enumerable_nodes: Dict[Type[Node], Tuple[str, Optional[Callable]]] = {
nodes.figure: ('figure', None),
nodes.table: ('table', None),
nodes.container: ('code-block', None),
@ -812,7 +812,8 @@ class StandardDomain(Domain):
return newnode
def resolve_xref(self, env: "BuildEnvironment", fromdocname: str, builder: "Builder",
typ: str, target: str, node: pending_xref, contnode: Element) -> Element:
typ: str, target: str, node: pending_xref, contnode: Element
) -> Optional[Element]:
if typ == 'ref':
resolver = self._resolve_ref_xref
elif typ == 'numref':
@ -832,7 +833,7 @@ class StandardDomain(Domain):
def _resolve_ref_xref(self, env: "BuildEnvironment", fromdocname: str,
builder: "Builder", typ: str, target: str, node: pending_xref,
contnode: Element) -> Element:
contnode: Element) -> Optional[Element]:
if node['refexplicit']:
# reference to anonymous label; the reference uses
# the supplied link caption
@ -850,7 +851,7 @@ class StandardDomain(Domain):
def _resolve_numref_xref(self, env: "BuildEnvironment", fromdocname: str,
builder: "Builder", typ: str, target: str,
node: pending_xref, contnode: Element) -> Element:
node: pending_xref, contnode: Element) -> Optional[Element]:
if target in self.labels:
docname, labelid, figname = self.labels.get(target, ('', '', ''))
else:
@ -913,7 +914,7 @@ class StandardDomain(Domain):
def _resolve_keyword_xref(self, env: "BuildEnvironment", fromdocname: str,
builder: "Builder", typ: str, target: str,
node: pending_xref, contnode: Element) -> Element:
node: pending_xref, contnode: Element) -> Optional[Element]:
# keywords are oddballs: they are referenced by named labels
docname, labelid, _ = self.labels.get(target, ('', '', ''))
if not docname:
@ -923,7 +924,7 @@ class StandardDomain(Domain):
def _resolve_doc_xref(self, env: "BuildEnvironment", fromdocname: str,
builder: "Builder", typ: str, target: str,
node: pending_xref, contnode: Element) -> Element:
node: pending_xref, contnode: Element) -> Optional[Element]:
# directly reference to document by source name; can be absolute or relative
refdoc = node.get('refdoc', fromdocname)
docname = docname_join(refdoc, node['reftarget'])
@ -940,7 +941,7 @@ class StandardDomain(Domain):
def _resolve_option_xref(self, env: "BuildEnvironment", fromdocname: str,
builder: "Builder", typ: str, target: str,
node: pending_xref, contnode: Element) -> Element:
node: pending_xref, contnode: Element) -> Optional[Element]:
progname = node.get('std:program')
target = target.strip()
docname, labelid = self.progoptions.get((progname, target), ('', ''))
@ -977,7 +978,7 @@ class StandardDomain(Domain):
def _resolve_obj_xref(self, env: "BuildEnvironment", fromdocname: str,
builder: "Builder", typ: str, target: str,
node: pending_xref, contnode: Element) -> Element:
node: pending_xref, contnode: Element) -> Optional[Element]:
objtypes = self.objtypes_for_role(typ) or []
for objtype in objtypes:
if (objtype, target) in self.objects:
@ -1041,7 +1042,7 @@ class StandardDomain(Domain):
def is_enumerable_node(self, node: Node) -> bool:
return node.__class__ in self.enumerable_nodes
def get_numfig_title(self, node: Node) -> str:
def get_numfig_title(self, node: Node) -> Optional[str]:
"""Get the title of enumerable nodes to refer them using its title"""
if self.is_enumerable_node(node):
elem = cast(Element, node)
@ -1055,7 +1056,7 @@ class StandardDomain(Domain):
return None
def get_enumerable_node_type(self, node: Node) -> str:
def get_enumerable_node_type(self, node: Node) -> Optional[str]:
"""Get type of enumerable nodes."""
def has_child(node: Element, cls: Type) -> bool:
return any(isinstance(child, cls) for child in node)
@ -1094,7 +1095,7 @@ class StandardDomain(Domain):
# Maybe it is defined in orphaned document.
raise ValueError from exc
def get_full_qualified_name(self, node: Element) -> str:
def get_full_qualified_name(self, node: Element) -> Optional[str]:
if node.get('reftype') == 'option':
progname = node.get('std:program')
command = ws_re.split(node.get('reftarget'))
@ -1109,7 +1110,8 @@ class StandardDomain(Domain):
return None
def warn_missing_reference(app: "Sphinx", domain: Domain, node: pending_xref) -> bool:
def warn_missing_reference(app: "Sphinx", domain: Domain, node: pending_xref
) -> Optional[bool]:
if (domain and domain.name != 'std') or node['reftype'] != 'ref':
return None
else:

View File

@ -10,18 +10,20 @@
import os
import pickle
import warnings
from collections import defaultdict
from copy import copy
from datetime import datetime
from os import path
from typing import (TYPE_CHECKING, Any, Callable, Dict, Generator, Iterator, List, Set, Tuple,
Union)
from typing import (TYPE_CHECKING, Any, Callable, Dict, Generator, Iterator, List, Optional,
Set, Tuple, Union)
from docutils import nodes
from docutils.nodes import Node
from sphinx import addnodes
from sphinx.config import Config
from sphinx.deprecation import RemovedInSphinx60Warning
from sphinx.domains import Domain
from sphinx.environment.adapters.toctree import TocTree
from sphinx.errors import BuildEnvironmentError, DocumentError, ExtensionError, SphinxError
@ -87,7 +89,7 @@ class BuildEnvironment:
transformations to resolve links to them.
"""
domains: Dict[str, Domain] = None
domains: Dict[str, Domain]
# --------- ENVIRONMENT INITIALIZATION -------------------------------------
@ -181,6 +183,9 @@ class BuildEnvironment:
# set up environment
if app:
self.setup(app)
else:
warnings.warn("The 'app' argument for BuildEnvironment() becomes required now.",
RemovedInSphinx60Warning, stacklevel=2)
def __getstate__(self) -> Dict:
"""Obtains serializable data for pickling."""
@ -266,7 +271,7 @@ class BuildEnvironment:
raise an exception if the user tries to use an environment with an
incompatible versioning method.
"""
condition: Union[bool, Callable] = None
condition: Union[bool, Callable]
if callable(method):
condition = method
else:
@ -309,7 +314,7 @@ class BuildEnvironment:
domain.merge_domaindata(docnames, other.domaindata[domainname])
self.events.emit('env-merge-info', self, docnames, other)
def path2doc(self, filename: str) -> str:
def path2doc(self, filename: str) -> Optional[str]:
"""Return the docname for the filename if the file is document.
*filename* should be absolute or relative to the source directory.
@ -577,7 +582,7 @@ class BuildEnvironment:
# allow custom references to be resolved
self.events.emit('doctree-resolved', doctree, docname)
def collect_relations(self) -> Dict[str, List[str]]:
def collect_relations(self) -> Dict[str, List[Optional[str]]]:
traversed = set()
def traverse_toctree(parent: str, docname: str) -> Iterator[Tuple[str, str]]:

View File

@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING, Any, Iterable, List, cast
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, cast
from docutils import nodes
from docutils.nodes import Element, Node
@ -48,7 +48,7 @@ class TocTree:
def resolve(self, docname: str, builder: "Builder", toctree: addnodes.toctree,
prune: bool = True, maxdepth: int = 0, titles_only: bool = False,
collapse: bool = False, includehidden: bool = False) -> Element:
collapse: bool = False, includehidden: bool = False) -> Optional[Element]:
"""Resolve a *toctree* node into individual bullet lists with titles
as items, returning None (if no containing titles are found) or
a new node.
@ -313,7 +313,7 @@ class TocTree:
return toc
def get_toctree_for(self, docname: str, builder: "Builder", collapse: bool,
**kwargs: Any) -> Element:
**kwargs: Any) -> Optional[Element]:
"""Return the global TOC nodetree."""
doctree = self.env.get_doctree(self.env.config.root_doc)
toctrees: List[Element] = []

View File

@ -8,7 +8,7 @@
:license: BSD, see LICENSE for details.
"""
from typing import TYPE_CHECKING, Dict, List, Set
from typing import TYPE_CHECKING, Dict, List, Optional, Set
from docutils import nodes
@ -27,7 +27,7 @@ class EnvironmentCollector:
entries and toctrees, etc.
"""
listener_ids: Dict[str, int] = None
listener_ids: Optional[Dict[str, int]] = None
def enable(self, app: "Sphinx") -> None:
assert self.listener_ids is None

View File

@ -47,7 +47,7 @@ class MetadataCollector(EnvironmentCollector):
md[field_name.astext()] = field_body.astext()
elif isinstance(node, nodes.TextElement):
# other children must be TextElement
# see: http://docutils.sourceforge.net/docs/ref/doctree.html#bibliographic-elements # NOQA
# see: https://docutils.sourceforge.io/docs/ref/doctree.html#bibliographic-elements # NOQA
md[node.__class__.__name__] = node.astext()
for name, value in md.items():

View File

@ -30,7 +30,7 @@ from sphinx.ext.autodoc.mock import ismock, mock, undecorate
from sphinx.locale import _, __
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.util import inspect, logging
from sphinx.util.docstrings import extract_metadata, prepare_docstring
from sphinx.util.docstrings import prepare_docstring, separate_metadata
from sphinx.util.inspect import (evaluate_signature, getdoc, object_description, safe_getattr,
stringify_signature)
from sphinx.util.typing import OptionSpec, get_type_hints, restify
@ -70,6 +70,9 @@ class _All:
def __contains__(self, item: Any) -> bool:
return True
def append(self, item: Any) -> None:
pass # nothing
class _Empty:
"""A special value for :exclude-members: that never matches to any member."""
@ -129,6 +132,14 @@ def member_order_option(arg: Any) -> Optional[str]:
raise ValueError(__('invalid value for member-order option: %s') % arg)
def class_doc_from_option(arg: Any) -> Optional[str]:
"""Used to convert the :class-doc-from: option to autoclass directives."""
if arg in ('both', 'class', 'init'):
return arg
else:
raise ValueError(__('invalid value for class-doc-from option: %s') % arg)
SUPPRESS = object()
@ -381,8 +392,8 @@ class Documenter:
# functions can contain a signature which is then used instead of
# an autogenerated one
try:
explicit_modname, path, base, args, retann = \
py_ext_sig_re.match(self.name).groups()
matched = py_ext_sig_re.match(self.name)
explicit_modname, path, base, args, retann = matched.groups()
except AttributeError:
logger.warning(__('invalid signature for auto%s (%r)') % (self.objtype, self.name),
type='autodoc')
@ -404,8 +415,8 @@ class Documenter:
self.args = args
self.retann = retann
self.fullname = (self.modname or '') + \
('.' + '.'.join(self.objpath) if self.objpath else '')
self.fullname = ((self.modname or '') +
('.' + '.'.join(self.objpath) if self.objpath else ''))
return True
def import_object(self, raiseerror: bool = False) -> bool:
@ -701,6 +712,8 @@ class Documenter:
# if isattr is True, the member is documented as an attribute
if member is INSTANCEATTR:
isattr = True
elif (namespace, membername) in attr_docs:
isattr = True
else:
isattr = False
@ -722,9 +735,9 @@ class Documenter:
# hack for ClassDocumenter to inject docstring via ObjectMember
doc = obj.docstring
doc, metadata = separate_metadata(doc)
has_doc = bool(doc)
metadata = extract_metadata(doc)
if 'private' in metadata:
# consider a member private if docstring has "private" metadata
isprivate = True
@ -761,7 +774,6 @@ class Documenter:
else:
# keep documented attributes
keep = True
isattr = True
elif want_all and isprivate:
if has_doc or self.options.undoc_members:
if self.options.private_members is None:
@ -816,8 +828,9 @@ class Documenter:
if self.objpath:
self.env.temp_data['autodoc:class'] = self.objpath[0]
want_all = all_members or self.options.inherited_members or \
self.options.members is ALL
want_all = (all_members or
self.options.inherited_members or
self.options.members is ALL)
# find out which members are documentable
members_check_module, members = self.get_object_members(want_all)
@ -833,8 +846,7 @@ class Documenter:
classes.sort(key=lambda cls: cls.priority)
# give explicitly separated module name, so that members
# of inner classes can be documented
full_mname = self.modname + '::' + \
'.'.join(self.objpath + [mname])
full_mname = self.modname + '::' + '.'.join(self.objpath + [mname])
documenter = classes[-1](self.directive, full_mname, self.indent)
memberdocumenters.append((documenter, isattr))
@ -1306,7 +1318,7 @@ class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # typ
sigs = []
if (self.analyzer and
'.'.join(self.objpath) in self.analyzer.overloads and
self.config.autodoc_typehints == 'signature'):
self.config.autodoc_typehints != 'none'):
# Use signatures for overloaded functions instead of the implementation function.
overloaded = True
else:
@ -1320,12 +1332,12 @@ class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # typ
if typ is object:
pass # default implementation. skipped.
else:
self.annotate_to_first_argument(func, typ)
documenter = FunctionDocumenter(self.directive, '')
documenter.object = func
documenter.objpath = [None]
sigs.append(documenter.format_signature())
dispatchfunc = self.annotate_to_first_argument(func, typ)
if dispatchfunc:
documenter = FunctionDocumenter(self.directive, '')
documenter.object = dispatchfunc
documenter.objpath = [None]
sigs.append(documenter.format_signature())
if overloaded:
actual = inspect.signature(self.object,
type_aliases=self.config.autodoc_type_aliases)
@ -1350,28 +1362,34 @@ class FunctionDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # typ
return overload.replace(parameters=parameters)
def annotate_to_first_argument(self, func: Callable, typ: Type) -> None:
def annotate_to_first_argument(self, func: Callable, typ: Type) -> Optional[Callable]:
"""Annotate type hint to the first argument of function if needed."""
try:
sig = inspect.signature(func, type_aliases=self.config.autodoc_type_aliases)
except TypeError as exc:
logger.warning(__("Failed to get a function signature for %s: %s"),
self.fullname, exc)
return
return None
except ValueError:
return
return None
if len(sig.parameters) == 0:
return
return None
def dummy():
pass
params = list(sig.parameters.values())
if params[0].annotation is Parameter.empty:
params[0] = params[0].replace(annotation=typ)
try:
func.__signature__ = sig.replace(parameters=params) # type: ignore
dummy.__signature__ = sig.replace(parameters=params) # type: ignore
return dummy
except (AttributeError, TypeError):
# failed to update signature (ex. built-in or extension types)
return
return None
else:
return None
class DecoratorDocumenter(FunctionDocumenter):
@ -1417,6 +1435,7 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
'show-inheritance': bool_option, 'member-order': member_order_option,
'exclude-members': exclude_members_option,
'private-members': members_option, 'special-members': members_option,
'class-doc-from': class_doc_from_option,
}
_signature_class: Any = None
@ -1424,6 +1443,15 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
def __init__(self, *args: Any) -> None:
super().__init__(*args)
if self.config.autodoc_class_signature == 'separated':
# show __init__() method
if self.options.special_members is None:
self.options['special-members'] = {'__new__', '__init__'}
else:
self.options.special_members.append('__new__')
self.options.special_members.append('__init__')
merge_members_option(self.options)
@classmethod
@ -1540,12 +1568,15 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
def format_signature(self, **kwargs: Any) -> str:
if self.doc_as_attr:
return ''
if self.config.autodoc_class_signature == 'separated':
# do not show signatures
return ''
sig = super().format_signature()
sigs = []
overloads = self.get_overloaded_signatures()
if overloads and self.config.autodoc_typehints == 'signature':
if overloads and self.config.autodoc_typehints != 'none':
# Use signatures for overloaded methods instead of the implementation method.
method = safe_getattr(self._signature_class, self._signature_method_name, None)
__globals__ = safe_getattr(method, '__globals__', {})
@ -1610,18 +1641,23 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
# add inheritance info, if wanted
if not self.doc_as_attr and self.options.show_inheritance:
sourcename = self.get_sourcename()
self.add_line('', sourcename)
if hasattr(self.object, '__orig_bases__') and len(self.object.__orig_bases__):
# A subclass of generic types
# refs: PEP-560 <https://www.python.org/dev/peps/pep-0560/>
bases = [restify(cls) for cls in self.object.__orig_bases__]
self.add_line(' ' + _('Bases: %s') % ', '.join(bases), sourcename)
bases = list(self.object.__orig_bases__)
elif hasattr(self.object, '__bases__') and len(self.object.__bases__):
# A normal class
bases = [restify(cls) for cls in self.object.__bases__]
self.add_line(' ' + _('Bases: %s') % ', '.join(bases), sourcename)
bases = list(self.object.__bases__)
else:
bases = []
self.env.events.emit('autodoc-process-bases',
self.fullname, self.object, self.options, bases)
base_classes = [restify(cls) for cls in bases]
sourcename = self.get_sourcename()
self.add_line('', sourcename)
self.add_line(' ' + _('Bases: %s') % ', '.join(base_classes), sourcename)
def get_object_members(self, want_all: bool) -> Tuple[bool, ObjectMembers]:
members = get_class_members(self.object, self.objpath, self.get_attr)
@ -1645,13 +1681,17 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if self.doc_as_attr:
# Don't show the docstring of the class when it is an alias.
return None
comment = self.get_variable_comment()
if comment:
return []
else:
return None
lines = getattr(self, '_new_docstrings', None)
if lines is not None:
return lines
content = self.config.autoclass_content
classdoc_from = self.options.get('class-doc-from', self.config.autoclass_content)
docstrings = []
attrdocstring = self.get_attr(self.object, '__doc__', None)
@ -1660,11 +1700,11 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
# for classes, what the "docstring" is can be controlled via a
# config value; the default is only the class docstring
if content in ('both', 'init'):
if classdoc_from in ('both', 'init'):
__init__ = self.get_attr(self.object, '__init__', None)
initdocstring = getdoc(__init__, self.get_attr,
self.config.autodoc_inherit_docstrings,
self.parent, self.object_name)
self.object, '__init__')
# for new-style classes, no __init__ means default __init__
if (initdocstring is not None and
(initdocstring == object.__init__.__doc__ or # for pypy
@ -1675,14 +1715,14 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
__new__ = self.get_attr(self.object, '__new__', None)
initdocstring = getdoc(__new__, self.get_attr,
self.config.autodoc_inherit_docstrings,
self.parent, self.object_name)
self.object, '__new__')
# for new-style classes, no __new__ means default __new__
if (initdocstring is not None and
(initdocstring == object.__new__.__doc__ or # for pypy
initdocstring.strip() == object.__new__.__doc__)): # for !pypy
initdocstring = None
if initdocstring:
if content == 'init':
if classdoc_from == 'init':
docstrings = [initdocstring]
else:
docstrings.append(initdocstring)
@ -1690,9 +1730,18 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type:
tab_width = self.directive.state.document.settings.tab_width
return [prepare_docstring(docstring, ignore, tab_width) for docstring in docstrings]
def get_variable_comment(self) -> Optional[List[str]]:
try:
key = ('', '.'.join(self.objpath))
analyzer = ModuleAnalyzer.for_module(self.get_real_modname())
analyzer.analyze()
return list(self.analyzer.attr_docs.get(key, []))
except PycodeError:
return None
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False
) -> None:
if self.doc_as_attr:
if self.doc_as_attr and not self.get_variable_comment():
try:
more_content = StringList([_('alias of %s') % restify(self.object)], source='')
except AttributeError:
@ -1918,7 +1967,7 @@ class DataDocumenter(GenericAliasMixin, NewTypeMixin, TypeVarMixin,
return True
else:
doc = self.get_doc()
metadata = extract_metadata('\n'.join(sum(doc, [])))
docstring, metadata = separate_metadata('\n'.join(sum(doc, [])))
if 'hide-value' in metadata:
return True
@ -1952,8 +2001,8 @@ class DataDocumenter(GenericAliasMixin, NewTypeMixin, TypeVarMixin,
pass
def get_real_modname(self) -> str:
return self.get_attr(self.parent or self.object, '__module__', None) \
or self.modname
real_modname = self.get_attr(self.parent or self.object, '__module__', None)
return real_modname or self.modname
def get_module_comment(self, attrname: str) -> Optional[List[str]]:
try:
@ -2018,8 +2067,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type:
@classmethod
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any
) -> bool:
return inspect.isroutine(member) and \
not isinstance(parent, ModuleDocumenter)
return inspect.isroutine(member) and not isinstance(parent, ModuleDocumenter)
def import_object(self, raiseerror: bool = False) -> bool:
ret = super().import_object(raiseerror)
@ -2094,7 +2142,7 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type:
sigs = []
if (self.analyzer and
'.'.join(self.objpath) in self.analyzer.overloads and
self.config.autodoc_typehints == 'signature'):
self.config.autodoc_typehints != 'none'):
# Use signatures for overloaded methods instead of the implementation method.
overloaded = True
else:
@ -2109,13 +2157,13 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type:
if typ is object:
pass # default implementation. skipped.
else:
self.annotate_to_first_argument(func, typ)
documenter = MethodDocumenter(self.directive, '')
documenter.parent = self.parent
documenter.object = func
documenter.objpath = [None]
sigs.append(documenter.format_signature())
dispatchmeth = self.annotate_to_first_argument(func, typ)
if dispatchmeth:
documenter = MethodDocumenter(self.directive, '')
documenter.parent = self.parent
documenter.object = dispatchmeth
documenter.objpath = [None]
sigs.append(documenter.format_signature())
if overloaded:
if inspect.isstaticmethod(self.object, cls=self.parent, name=self.object_name):
actual = inspect.signature(self.object, bound_method=False,
@ -2149,27 +2197,66 @@ class MethodDocumenter(DocstringSignatureMixin, ClassLevelDocumenter): # type:
return overload.replace(parameters=parameters)
def annotate_to_first_argument(self, func: Callable, typ: Type) -> None:
def annotate_to_first_argument(self, func: Callable, typ: Type) -> Optional[Callable]:
"""Annotate type hint to the first argument of function if needed."""
try:
sig = inspect.signature(func, type_aliases=self.config.autodoc_type_aliases)
except TypeError as exc:
logger.warning(__("Failed to get a method signature for %s: %s"),
self.fullname, exc)
return
return None
except ValueError:
return
return None
if len(sig.parameters) == 1:
return
return None
def dummy():
pass
params = list(sig.parameters.values())
if params[1].annotation is Parameter.empty:
params[1] = params[1].replace(annotation=typ)
try:
func.__signature__ = sig.replace(parameters=params) # type: ignore
dummy.__signature__ = sig.replace(parameters=params) # type: ignore
return dummy
except (AttributeError, TypeError):
# failed to update signature (ex. built-in or extension types)
return
return None
else:
return None
def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if self.objpath[-1] == '__init__':
docstring = getdoc(self.object, self.get_attr,
self.config.autodoc_inherit_docstrings,
self.parent, self.object_name)
if (docstring is not None and
(docstring == object.__init__.__doc__ or # for pypy
docstring.strip() == object.__init__.__doc__)): # for !pypy
docstring = None
if docstring:
tab_width = self.directive.state.document.settings.tab_width
return [prepare_docstring(docstring, tabsize=tab_width)]
else:
return []
elif self.objpath[-1] == '__new__':
__new__ = self.get_attr(self.object, '__new__', None)
if __new__:
docstring = getdoc(__new__, self.get_attr,
self.config.autodoc_inherit_docstrings,
self.parent, self.object_name)
if (docstring is not None and
(docstring == object.__new__.__doc__ or # for pypy
docstring.strip() == object.__new__.__doc__)): # for !pypy
docstring = None
if docstring:
tab_width = self.directive.state.document.settings.tab_width
return [prepare_docstring(docstring, tabsize=tab_width)]
else:
return []
else:
return super().get_doc()
class NonDataDescriptorMixin(DataDocumenterMixinBase):
@ -2269,9 +2356,29 @@ class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase):
# An instance variable defined in __init__().
if self.get_attribute_comment(parent, self.objpath[-1]): # type: ignore
return True
elif self.is_runtime_instance_attribute_not_commented(parent):
return True
else:
return False
def is_runtime_instance_attribute_not_commented(self, parent: Any) -> bool:
"""Check the subject is an attribute defined in __init__() without comment."""
for cls in inspect.getmro(parent):
try:
module = safe_getattr(cls, '__module__')
qualname = safe_getattr(cls, '__qualname__')
analyzer = ModuleAnalyzer.for_module(module)
analyzer.analyze()
if qualname and self.objpath:
key = '.'.join([qualname, self.objpath[-1]])
if key in analyzer.tagorder:
return True
except (AttributeError, PycodeError):
pass
return None
def import_object(self, raiseerror: bool = False) -> bool:
"""Check the existence of runtime instance attribute when failed to import the
attribute."""
@ -2302,6 +2409,13 @@ class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase):
return (self.object is self.RUNTIME_INSTANCE_ATTRIBUTE or
super().should_suppress_value_header())
def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
if (self.object is self.RUNTIME_INSTANCE_ATTRIBUTE and
self.is_runtime_instance_attribute_not_commented(self.parent)):
return None
else:
return super().get_doc(ignore) # type: ignore
class UninitializedInstanceAttributeMixin(DataDocumenterMixinBase):
"""
@ -2447,8 +2561,8 @@ class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type:
return ret
def get_real_modname(self) -> str:
return self.get_attr(self.parent or self.object, '__module__', None) \
or self.modname
real_modname = self.get_attr(self.parent or self.object, '__module__', None)
return real_modname or self.modname
def should_suppress_value_header(self) -> bool:
if super().should_suppress_value_header():
@ -2456,7 +2570,7 @@ class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type:
else:
doc = self.get_doc()
if doc:
metadata = extract_metadata('\n'.join(sum(doc, [])))
docstring, metadata = separate_metadata('\n'.join(sum(doc, [])))
if 'hide-value' in metadata:
return True
@ -2549,8 +2663,8 @@ class PropertyDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter): #
pass
def get_real_modname(self) -> str:
return self.get_attr(self.parent or self.object, '__module__', None) \
or self.modname
real_modname = self.get_attr(self.parent or self.object, '__module__', None)
return real_modname or self.modname
def add_directive_header(self, sig: str) -> None:
super().add_directive_header(sig)
@ -2640,11 +2754,12 @@ def setup(app: Sphinx) -> Dict[str, Any]:
app.add_config_value('autoclass_content', 'class', True, ENUM('both', 'class', 'init'))
app.add_config_value('autodoc_member_order', 'alphabetical', True,
ENUM('alphabetic', 'alphabetical', 'bysource', 'groupwise'))
app.add_config_value('autodoc_class_signature', 'mixed', True, ENUM('mixed', 'separated'))
app.add_config_value('autodoc_default_options', {}, True)
app.add_config_value('autodoc_docstring_signature', True, True)
app.add_config_value('autodoc_mock_imports', [], True)
app.add_config_value('autodoc_typehints', "signature", True,
ENUM("signature", "description", "none"))
ENUM("signature", "description", "none", "both"))
app.add_config_value('autodoc_typehints_description_target', 'all', True,
ENUM('all', 'documented'))
app.add_config_value('autodoc_type_aliases', {}, True)
@ -2654,6 +2769,7 @@ def setup(app: Sphinx) -> Dict[str, Any]:
app.add_event('autodoc-process-docstring')
app.add_event('autodoc-process-signature')
app.add_event('autodoc-skip-member')
app.add_event('autodoc-process-bases')
app.connect('config-inited', migrate_autodoc_member_order, priority=800)

View File

@ -30,7 +30,7 @@ logger = logging.getLogger(__name__)
AUTODOC_DEFAULT_OPTIONS = ['members', 'undoc-members', 'inherited-members',
'show-inheritance', 'private-members', 'special-members',
'ignore-module-all', 'exclude-members', 'member-order',
'imported-members']
'imported-members', 'class-doc-from']
AUTODOC_EXTENDABLE_OPTIONS = ['members', 'private-members', 'special-members',
'exclude-members']

View File

@ -40,7 +40,7 @@ def record_typehints(app: Sphinx, objtype: str, name: str, obj: Any,
def merge_typehints(app: Sphinx, domain: str, objtype: str, contentnode: Element) -> None:
if domain != 'py':
return
if app.config.autodoc_typehints != 'description':
if app.config.autodoc_typehints not in ('both', 'description'):
return
try:

View File

@ -72,7 +72,8 @@ import sphinx
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.config import Config
from sphinx.deprecation import RemovedInSphinx50Warning
from sphinx.deprecation import (RemovedInSphinx50Warning, RemovedInSphinx60Warning,
deprecated_alias)
from sphinx.environment import BuildEnvironment
from sphinx.environment.adapters.toctree import TocTree
from sphinx.ext.autodoc import INSTANCEATTR, Documenter
@ -80,7 +81,9 @@ from sphinx.ext.autodoc.directive import DocumenterBridge, Options
from sphinx.ext.autodoc.importer import import_module
from sphinx.ext.autodoc.mock import mock
from sphinx.locale import __
from sphinx.project import Project
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.registry import SphinxComponentRegistry
from sphinx.util import logging, rst
from sphinx.util.docutils import (NullReporter, SphinxDirective, SphinxRole, new_document,
switch_source_input)
@ -163,17 +166,33 @@ def autosummary_table_visit_html(self: HTMLTranslator, node: autosummary_table)
# -- autodoc integration -------------------------------------------------------
deprecated_alias('sphinx.ext.autosummary',
{
'_app': None,
},
RemovedInSphinx60Warning,
{
})
# current application object (used in `get_documenter()`).
_app: Sphinx = None
class FakeApplication:
def __init__(self):
self.doctreedir = None
self.events = None
self.extensions = {}
self.srcdir = None
self.config = Config()
self.project = Project(None, None)
self.registry = SphinxComponentRegistry()
class FakeDirective(DocumenterBridge):
def __init__(self) -> None:
settings = Struct(tab_width=8)
document = Struct(settings=settings)
env = BuildEnvironment()
env.config = Config()
app = FakeApplication()
app.config.add('autodoc_class_signature', 'mixed', True, None)
env = BuildEnvironment(app) # type: ignore
state = Struct(document=document)
super().__init__(env, None, Options(), 0, state)
@ -662,8 +681,10 @@ def import_ivar_by_name(name: str, prefixes: List[str] = [None]) -> Tuple[str, A
name, attr = name.rsplit(".", 1)
real_name, obj, parent, modname = import_by_name(name, prefixes)
qualname = real_name.replace(modname + ".", "")
analyzer = ModuleAnalyzer.for_module(modname)
if (qualname, attr) in analyzer.find_attr_docs():
analyzer = ModuleAnalyzer.for_module(getattr(obj, '__module__', modname))
analyzer.analyze()
# check for presence in `annotations` to include dataclass attributes
if (qualname, attr) in analyzer.attr_docs or (qualname, attr) in analyzer.annotations:
return real_name + "." + attr, INSTANCEATTR, obj, modname
except (ImportError, ValueError, PycodeError):
pass

View File

@ -239,15 +239,33 @@ def generate_autosummary_content(name: str, obj: Any, parent: Any,
name, exc, type='autosummary')
return False
def get_class_members(obj: Any) -> Dict[str, Any]:
members = sphinx.ext.autodoc.get_class_members(obj, [qualname], safe_getattr)
return {name: member.object for name, member in members.items()}
def get_module_members(obj: Any) -> Dict[str, Any]:
members = {}
for name in dir(obj):
try:
members[name] = safe_getattr(obj, name)
except AttributeError:
continue
return members
def get_all_members(obj: Any) -> Dict[str, Any]:
if doc.objtype == "module":
return get_module_members(obj)
elif doc.objtype == "class":
return get_class_members(obj)
return {}
def get_members(obj: Any, types: Set[str], include_public: List[str] = [],
imported: bool = True) -> Tuple[List[str], List[str]]:
items: List[str] = []
public: List[str] = []
for name in dir(obj):
try:
value = safe_getattr(obj, name)
except AttributeError:
continue
all_members = get_all_members(obj)
for name, value in all_members.items():
documenter = get_documenter(app, value, obj)
if documenter.objtype in types:
# skip imported members if expected

View File

@ -45,7 +45,6 @@ from sphinx.environment import BuildEnvironment
from sphinx.locale import _, __
from sphinx.util import logging, requests
from sphinx.util.inventory import InventoryFile
from sphinx.util.nodes import find_pending_xref_condition
from sphinx.util.typing import Inventory
logger = logging.getLogger(__name__)
@ -287,16 +286,6 @@ def missing_reference(app: Sphinx, env: BuildEnvironment, node: pending_xref,
# Since Sphinx-2.1, properties are stored as py:method
objtypes.append('py:method')
# determine the contnode by pending_xref_condition
content = find_pending_xref_condition(node, 'resolved')
if content:
# resolved condition found.
contnodes = content.children
contnode = content.children[0] # type: ignore
else:
# not resolved. Use the given contnode
contnodes = [contnode]
to_try = [(inventories.main_inventory, target)]
if domain:
full_qualified_name = env.get_domain(domain).get_full_qualified_name(node)
@ -329,7 +318,7 @@ def missing_reference(app: Sphinx, env: BuildEnvironment, node: pending_xref,
newnode = nodes.reference('', '', internal=False, refuri=uri, reftitle=reftitle)
if node.get('refexplicit'):
# use whatever title was given
newnode.extend(contnodes)
newnode.append(contnode)
elif dispname == '-' or \
(domain == 'std' and node['reftype'] == 'keyword'):
# use whatever title was given, but strip prefix
@ -338,7 +327,7 @@ def missing_reference(app: Sphinx, env: BuildEnvironment, node: pending_xref,
newnode.append(contnode.__class__(title[len(in_set) + 1:],
title[len(in_set) + 1:]))
else:
newnode.extend(contnodes)
newnode.append(contnode)
else:
# else use the given display name (used for :ref:)
newnode.append(contnode.__class__(dispname, dispname))

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -12,18 +12,18 @@ Documentation.addTranslations({
"Collapse sidebar": "\u062a\u0627 \u06a9\u0631\u062f\u0646 \u0646\u0648\u0627\u0631 \u06a9\u0646\u0627\u0631\u0647",
"Complete Table of Contents": "\u0641\u0647\u0631\u0633\u062a \u06a9\u0627\u0645\u0644 \u0645\u0637\u0627\u0644\u0628",
"Contents": "\u0645\u062d\u062a\u0648\u0627 \u0647\u0627",
"Copyright": "\u062d\u0642 \u0627\u0646\u062a\u0634\u0627\u0631",
"Copyright": "\u06a9\u067e\u06cc \u0631\u0627\u06cc\u062a",
"Created using <a href=\"https://www.sphinx-doc.org/\">Sphinx</a> %(sphinx_version)s.": "\u0627\u06cc\u062c\u0627\u062f \u0634\u062f\u0647 \u0628\u0627<a href=\"https://www.sphinx-doc.org/\">Sphinx</a> %(sphinx_version)s.",
"Expand sidebar": "\u06af\u0633\u062a\u0631\u0634 \u0646\u0648\u0627\u0631 \u06a9\u0646\u0627\u0631\u0647",
"Full index on one page": "\u0641\u0647\u0631\u0633\u062a \u06a9\u0627\u0645\u0644 \u062f\u0631 \u06cc\u06a9 \u0635\u0641\u062d\u0647",
"General Index": "\u0641\u0647\u0631\u0633\u062a \u06a9\u0644\u06cc",
"Global Module Index": "\u0641\u0647\u0631\u0633\u062a \u06a9\u0644\u06cc \u0645\u0627\u0698\u0648\u0644 \u0647\u0627",
"Go": "\u0631\u0641\u062a\u0646 \u0628\u0647",
"Go": "\u0628\u0631\u0648",
"Hide Search Matches": "\u0639\u062f\u0645 \u0646\u0645\u0627\u06cc\u0634 \u0646\u062a\u0627\u06cc\u062c \u06cc\u0627\u0641\u062a \u0634\u062f\u0647",
"Index": "\u0641\u0647\u0631\u0633\u062a",
"Index &ndash; %(key)s": "\u0641\u0647\u0631\u0633\u062a &ndash; %(key)s",
"Index pages by letter": "\u0641\u0647\u0631\u0633\u062a \u0635\u0641\u062d\u0627\u062a \u0628\u0631 \u0627\u0633\u0627\u0633 \u062d\u0631\u0648\u0641",
"Indices and tables:": "\u0646\u0645\u0627\u06cc\u0647\u200c\u0647\u0627 \u0648 \u062c\u062f\u0648\u0644\u200c\u0647\u0627:",
"Indices and tables:": "\u0627\u06cc\u0646\u062f\u06a9\u0633 \u0647\u0627 \u0648 \u062c\u062f\u0627\u0648\u0644:",
"Last updated on %(last_updated)s.": "\u0622\u062e\u0631\u06cc\u0646 \u0628\u0631\u0648\u0632 \u0631\u0633\u0627\u0646\u06cc \u062f\u0631 %(last_updated)s .",
"Library changes": "\u062a\u063a\u06cc\u06cc\u0631\u0627\u062a \u06a9\u062a\u0627\u0628\u062e\u0627\u0646\u0647 \u0627\u06cc\u06cc",
"Navigation": "\u0646\u0627\u0648\u0628\u0631\u06cc",

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More