diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 89dc8fde9c..3cdda918c6 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -4,16 +4,12 @@ on: [push, pull_request] jobs: ubuntu: - runs-on: ${{ matrix.os }} + runs-on: ubuntu-18.04 strategy: fail-fast: false matrix: - name: [py35, py36, py37, py38, py39] - os: [ubuntu-16.04] + name: [py36, py37, py38, py39, py310-dev] include: - - name: py35 - python: 3.5 - docutils: du12 - name: py36 python: 3.6 docutils: du13 @@ -30,7 +26,6 @@ jobs: - name: py310-dev python: 3.10-dev docutils: du16 - os: ubuntu-latest # required env: PYTEST_ADDOPTS: ${{ matrix.coverage }} diff --git a/CHANGES b/CHANGES index 8fa86a98b2..ad3c20988e 100644 --- a/CHANGES +++ b/CHANGES @@ -1,3 +1,113 @@ +Release 4.0.0 (in development) +============================== + +Dependencies +------------ + +* Drop python 3.5 support +* Drop docutils 0.12 and 0.13 support +* LaTeX: add ``tex-gyre`` font dependency + +Incompatible changes +-------------------- + +* domain: The ``Index`` class becomes subclasses of ``abc.ABC`` to indicate + methods that must be overrided in the concrete classes +* #4826: py domain: The structure of python objects is changed. A boolean value + is added to indicate that the python object is canonical one +* #7425: MathJax: The MathJax was changed from 2 to 3. Users using a custom + MathJax configuration may have to set the old MathJax path or update their + configuration for version 3. See :mod:`sphinx.ext.mathjax`. +* #7784: i18n: The msgid for alt text of image is changed +* #5560: napoleon: :confval:`napoleon_use_param` also affect "other parameters" + section +* #7996: manpage: Make a section directory on build manpage by default (see + :confval:`man_make_section_directory`) +* #7849: html: Change the default setting of + :confval:`html_codeblock_linenos_style` to ``'inline'`` +* #8380: html search: search results are wrapped with ``

`` instead of + ``

`` +* html theme: Move a script tag for documentation_options.js in + basic/layout.html to ``script_files`` variable +* html theme: Move CSS tags in basic/layout.html to ``css_files`` variable +* #8915: html theme: Emit a warning for sphinx_rtd_theme-0.2.4 or older +* #8508: LaTeX: uplatex becomes a default setting of latex_engine for Japanese + documents +* #5977: py domain: ``:var:``, ``:cvar:`` and ``:ivar:`` fields do not create + cross-references +* #4550: The ``align`` attribute of ``figure`` and ``table`` nodes becomes + ``None`` by default instead of ``'default'`` +* #8769: LaTeX refactoring: split sphinx.sty into multiple files and rename + some auxiliary files created in ``latex`` build output repertory +* #8937: Use explicit title instead of +* #8487: The :file: option for csv-table directive now recognizes an absolute + path as a relative path from source directory + +Deprecated +---------- + +* :confval:`html_codeblock_linenos_style` +* ``favicon`` and ``logo`` variable in HTML templates +* ``sphinx.directives.patches.CSVTable`` +* ``sphinx.directives.patches.ListTable`` +* ``sphinx.directives.patches.RSTTable`` +* ``sphinx.registry.SphinxComponentRegistry.get_source_input()`` +* ``sphinx.registry.SphinxComponentRegistry.source_inputs`` +* ``sphinx.transforms.FigureAligner`` +* ``sphinx.util.pycompat.convert_with_2to3()`` +* ``sphinx.util.pycompat.execfile_()`` +* ``sphinx.util.smartypants`` + +Features added +-------------- + +* #8924: autodoc: Support ``bound`` argument for TypeVar +* #7549: autosummary: Enable :confval:`autosummary_generate` by default +* #4826: py domain: Add ``:canonical:`` option to python directives to describe + the location where the object is defined +* #7199: py domain: Add :confval:`python_use_unqualified_type_names` to suppress + the module name of the python reference if it can be resolved (experimental) +* #7784: i18n: The alt text for image is translated by default (without + :confval:`gettext_additional_targets` setting) +* #2018: html: :confval:`html_favicon` and :confval:`html_logo` now accept URL + for the image +* #8070: html search: Support searching for 2characters word +* #8938: imgconverter: Show the error of the command availability check +* #7830: Add debug logs for change detection of sources and templates +* #8201: Emit a warning if toctree contains duplicated entries +* #8326: ``master_doc`` is now renamed to :confval:`root_doc` +* #8942: C++, add support for the C++20 spaceship operator, ``<=>``. +* #7199: A new node, ``sphinx.addnodes.pending_xref_condition`` has been added. + It can be used to choose appropriate content of the reference by conditions. + +Bugs fixed +---------- + +* #8917: autodoc: Raises a warning if function has wrong __globals__ value +* #8415: autodoc: a TypeVar imported from other module is not resolved (in + Python 3.7 or above) +* #8905: html: html_add_permalinks=None and html_add_permalinks="" are ignored +* #8380: html search: Paragraphs in search results are not identified as ``

`` +* #8915: html theme: The translation of sphinx_rtd_theme does not work +* #8342: Emit a warning if a unknown domain is given for directive or role (ex. + ``:unknown:doc:``) +* #8711: LaTeX: backticks in code-blocks trigger latexpdf build warning (and font + change) with late TeXLive 2019 +* #8253: LaTeX: Figures with no size defined get overscaled (compared to images + with size explicitly set in pixels) (fixed for ``'pdflatex'/'lualatex'`` only) +* #8925: LaTeX: 3.5.0 ``verbatimmaxunderfull`` setting does not work as + expected +* #8911: C++: remove the longest matching prefix in + :confval:`cpp_index_common_prefix` instead of the first that matches. +* C, properly reject function declarations when a keyword is used + as parameter name. +* #8933: viewcode: Failed to create back-links on parallel build +* #8960: C and C++, fix rendering of (member) function pointer types in + function parameter lists. + +Testing +-------- + Release 3.5.3 (in development) ============================== @@ -92,6 +202,9 @@ Features added * #8775: autodoc: Support type union operator (PEP-604) in Python 3.10 or above * #8297: autodoc: Allow to extend :confval:`autodoc_default_options` via directive options +* #759: autodoc: Add a new configuration :confval:`autodoc_preserve_defaults` as + an experimental feature. It preserves the default argument values of + functions in source code and keep them not evaluated for readability. * #8619: html: kbd role generates customizable HTML tags for compound keys * #8634: html: Allow to change the order of JS/CSS via ``priority`` parameter for :meth:`Sphinx.add_js_file()` and :meth:`Sphinx.add_css_file()` diff --git a/EXAMPLES b/EXAMPLES index 348e76c8ca..040637e964 100644 --- a/EXAMPLES +++ b/EXAMPLES @@ -12,19 +12,20 @@ interesting examples. Documentation using the alabaster theme --------------------------------------- +* `AIOHTTP `__ * `Alabaster `__ * `Blinker `__ * `Calibre `__ -* `Click `__ (customized) +* `Click `__ (customized) * `coala `__ (customized) * `CodePy `__ * `Eve `__ (Python REST API framework) * `Fabric `__ * `Fityk `__ -* `Flask `__ +* `Flask `__ * `Flask-OpenID `__ * `Invoke `__ -* `Jinja `__ +* `Jinja `__ * `Lino `__ (customized) * `marbl `__ * `MDAnalysis `__ (customized) @@ -41,7 +42,8 @@ Documentation using the alabaster theme * `Spyder `__ (customized) * `Tablib `__ * `urllib3 `__ (customized) -* `Werkzeug `__ (customized) +* `Werkzeug `__ +* `Write the Docs `__ Documentation using the classic theme ------------------------------------- @@ -132,7 +134,7 @@ Documentation using the sphinxdoc theme Documentation using the nature theme ------------------------------------ -* `Alembic `__ +* `Alembic `__ * `Cython `__ * `easybuild `__ * `jsFiddle `__ @@ -141,6 +143,7 @@ Documentation using the nature theme * `MapServer `__ (customized) * `Pandas `__ * `pyglet `__ (customized) +* `PyWavelets `__ * `Setuptools `__ * `Spring Python `__ * `StatsModels `__ (customized) @@ -156,6 +159,7 @@ Documentation using another builtin theme * `PyPubSub `__ (bizstyle) * `Pylons `__ (pyramid) * `Pyramid web framework `__ (pyramid) +* `RxDock `__ * `Sphinx `__ (sphinx13) :-) * `Valence `__ (haiku, customized) @@ -219,6 +223,7 @@ Documentation using sphinx_rtd_theme * `Mailman `__ * `MathJax `__ * `MDTraj `__ (customized) +* `Mesa 3D `__ * `micca - MICrobial Community Analysis `__ * `MicroPython `__ * `Minds `__ (customized) @@ -227,6 +232,7 @@ Documentation using sphinx_rtd_theme * `mod_wsgi `__ * `MoinMoin `__ * `Mopidy `__ +* `mpi4py `__ * `MyHDL `__ * `Nextflow `__ * `NICOS `__ (customized) @@ -247,6 +253,7 @@ Documentation using sphinx_rtd_theme * `PyVISA `__ * `pyvista `__ * `Read The Docs `__ +* `ROCm Platform `__ * `Free your information from their silos (French) `__ (customized) * `Releases Sphinx extension `__ * `Qtile `__ @@ -254,7 +261,7 @@ Documentation using sphinx_rtd_theme * `QuTiP `__ * `Satchmo `__ * `Scapy `__ -* `SimGrid `__ +* `SimGrid `__ * `SimPy `__ * `six `__ * `SlamData `__ @@ -283,7 +290,6 @@ Documentation using sphinx_rtd_theme * `Web Application Attack and Audit Framework (w3af) `__ * `Weblate `__ * `x265 `__ -* `ZeroNet `__ * `Zulip `__ Documentation using sphinx_bootstrap_theme @@ -319,6 +325,7 @@ Documentation using a custom theme or integrated in a website * `Doctrine `__ * `Enterprise Toolkit for Acrobat products `__ * `FreeFEM `__ +* `fmt `__ * `Gameduino `__ * `gensim `__ * `GeoServer `__ @@ -328,6 +335,7 @@ Documentation using a custom theme or integrated in a website * `H2O.ai `__ * `Heka `__ * `Istihza (Turkish Python documentation project) `__ +* `JupyterHub `__ * `Kombu `__ * `Lasso `__ * `Mako `__ diff --git a/MANIFEST.in b/MANIFEST.in index 1114ca19f8..7c2f852a81 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -15,6 +15,7 @@ include sphinx-quickstart.py include sphinx-apidoc.py include tox.ini include sphinx/locale/.tx/config +include sphinx/py.typed recursive-include sphinx/templates * recursive-include sphinx/texinputs * diff --git a/bindep.txt b/bindep.txt index dfee52c281..0c599b9f2b 100644 --- a/bindep.txt +++ b/bindep.txt @@ -12,10 +12,12 @@ texlive-luatex85 [platform:rpm] texlive-anyfontsize [platform:rpm] texlive-ctablestack [platform:rpm] texlive-gnu-freefont [platform:rpm] +texlive-tex-gyre [platform:rpm] latexmk [platform:rpm] texlive-latex-recommended [platform:dpkg] texlive-fonts-recommended [platform:dpkg] +tex-gyre [platform:dpkg] texlive-latex-extra [platform:dpkg] texlive-luatex [platform:dpkg] latexmk [platform:dpkg] diff --git a/doc/_static/conf.py.txt b/doc/_static/conf.py.txt index 5420e2717e..844451fd8a 100644 --- a/doc/_static/conf.py.txt +++ b/doc/_static/conf.py.txt @@ -43,7 +43,7 @@ source_suffix = '.rst' # source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +root_doc = 'index' # General information about the project. project = u'test' @@ -252,7 +252,7 @@ latex_elements = { # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'test.tex', u'test Documentation', + (root_doc, 'test.tex', u'test Documentation', u'test', 'manual'), ] @@ -283,7 +283,7 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'test', u'test Documentation', + (root_doc, 'test', u'test Documentation', [author], 1) ] @@ -298,7 +298,7 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'test', u'test Documentation', + (root_doc, 'test', u'test Documentation', author, 'test', 'One line description of project.', 'Miscellaneous'), ] diff --git a/doc/conf.py b/doc/conf.py index a3d2f5f12d..ddf68de051 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -9,7 +9,7 @@ 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'sphinx.ext.inheritance_diagram'] -master_doc = 'contents' +root_doc = 'contents' templates_path = ['_templates'] exclude_patterns = ['_build'] @@ -59,17 +59,6 @@ latex_logo = '_static/sphinx.png' latex_elements = { 'fontenc': r'\usepackage[LGR,X2,T1]{fontenc}', - 'fontpkg': r''' -\usepackage[sc]{mathpazo} -\usepackage[scaled]{helvet} -\usepackage{courier} -\substitutefont{LGR}{\rmdefault}{cmr} -\substitutefont{LGR}{\sfdefault}{cmss} -\substitutefont{LGR}{\ttdefault}{cmtt} -\substitutefont{X2}{\rmdefault}{cmr} -\substitutefont{X2}{\sfdefault}{cmss} -\substitutefont{X2}{\ttdefault}{cmtt} -''', 'passoptionstopackages': r''' \PassOptionsToPackage{svgnames}{xcolor} \PassOptionsToPackage{bookmarksdepth=3}{hyperref}% depth of pdf bookmarks @@ -79,7 +68,6 @@ \setcounter{tocdepth}{3}% depth of what is kept from toc file \setcounter{secnumdepth}{1}% depth of section numbering ''', - 'fvset': '\\fvset{fontsize=auto}', # fix missing index entry due to RTD doing only once pdflatex after makeindex 'printindex': r''' \IfFileExists{\jobname.ind} @@ -91,6 +79,7 @@ latex_use_xindy = True autodoc_member_order = 'groupwise' +autosummary_generate = False todo_include_todos = True extlinks = {'duref': ('http://docutils.sourceforge.net/docs/ref/rst/' 'restructuredtext.html#%s', ''), diff --git a/doc/development/tutorials/autodoc_ext.rst b/doc/development/tutorials/autodoc_ext.rst new file mode 100644 index 0000000000..d8905710c6 --- /dev/null +++ b/doc/development/tutorials/autodoc_ext.rst @@ -0,0 +1,142 @@ +.. _autodoc_ext_tutorial: + +Developing autodoc extension for IntEnum +======================================== + +The objective of this tutorial is to create an extension that adds +support for new type for autodoc. This autodoc extension will format +the ``IntEnum`` class from Python standard library. (module ``enum``) + +Overview +-------- + +We want the extension that will create auto-documentation for IntEnum. +``IntEnum`` is the integer enum class from standard library ``enum`` module. + +Currently this class has no special auto documentation behavior. + +We want to add following to autodoc: + +* A new ``autointenum`` directive that will document the ``IntEnum`` class. +* The generated documentation will have all the enum possible values + with names. +* The ``autointenum`` directive will have an option ``:hex:`` which will + cause the integers be printed in hexadecimal form. + + +Prerequisites +------------- + +We need the same setup as in :doc:`the previous extensions `. This time, +we will be putting out extension in a file called :file:`autodoc_intenum.py`. +The :file:`my_enums.py` will contain the sample enums we will document. + +Here is an example of the folder structure you might obtain: + +.. code-block:: text + + └── source +    ├── _ext + │   └── autodoc_intenum.py +    ├── conf.py +    ├── index.rst +    └── my_enums.py + + +Writing the extension +--------------------- + +Start with ``setup`` function for the extension. + +.. literalinclude:: examples/autodoc_intenum.py + :language: python + :linenos: + :pyobject: setup + + +The :meth:`~Sphinx.setup_extension` method will pull the autodoc extension +because our new extension depends on autodoc. :meth:`~Sphinx.add_autodocumenter` +is the method that registers our new auto documenter class. + +We want to import certain objects from the autodoc extension: + +.. literalinclude:: examples/autodoc_intenum.py + :language: python + :linenos: + :lines: 1-7 + + +There are several different documenter classes such as ``MethodDocumenter`` +or ``AttributeDocumenter`` available in the autodoc extension but +our new class is the subclass of ``ClassDocumenter`` which a +documenter class used by autodoc to document classes. + +This is the definition of our new the auto-documenter class: + +.. literalinclude:: examples/autodoc_intenum.py + :language: python + :linenos: + :pyobject: IntEnumDocumenter + + +Important attributes of the new class: + +**objtype** + This attribute determines the ``auto`` directive name. In + this case the auto directive will be ``autointenum``. + +**directivetype** + This attribute sets the generated directive name. In + this example the generated directive will be ``.. :py:class::``. + +**priority** + the larger the number the higher is the priority. We want our + documenter be higher priority than the parent. + +**option_spec** + option specifications. We copy the parent class options and + add a new option *hex*. + + +Overridden members: + +**can_document_member** + This member is important to override. It should + return *True* when the passed object can be documented by this class. + +**add_directive_header** + This method generates the directive header. We add + **:final:** directive option. Remember to call **super** or no directive + will be generated. + +**add_content** + This method generates the body of the class documentation. + After calling the super method we generate lines for enum description. + + +Using the extension +------------------- + +You can now use the new autodoc directive to document any ``IntEnum``. + +For example, you have the following ``IntEnum``: + +.. code-block:: python + :caption: my_enums.py + + class Colors(IntEnum): + """Colors enumerator""" + NONE = 0 + RED = 1 + GREEN = 2 + BLUE = 3 + + +This will be the documentation file with auto-documentation directive: + +.. code-block:: rst + :caption: index.rst + + .. autointenum:: my_enums.Colors + + diff --git a/doc/development/tutorials/examples/autodoc_intenum.py b/doc/development/tutorials/examples/autodoc_intenum.py new file mode 100644 index 0000000000..7fb85d0662 --- /dev/null +++ b/doc/development/tutorials/examples/autodoc_intenum.py @@ -0,0 +1,52 @@ +from enum import IntEnum +from typing import Any, Optional + +from docutils.statemachine import StringList + +from sphinx.application import Sphinx +from sphinx.ext.autodoc import ClassDocumenter, bool_option + + +class IntEnumDocumenter(ClassDocumenter): + objtype = 'intenum' + directivetype = 'class' + priority = 10 + ClassDocumenter.priority + option_spec = dict(ClassDocumenter.option_spec) + option_spec['hex'] = bool_option + + @classmethod + def can_document_member(cls, + member: Any, membername: str, + isattr: bool, parent: Any) -> bool: + return isinstance(member, IntEnum) + + def add_directive_header(self, sig: str) -> None: + super().add_directive_header(sig) + self.add_line(' :final:', self.get_sourcename()) + + def add_content(self, + more_content: Optional[StringList], + no_docstring: bool = False + ) -> None: + + super().add_content(more_content, no_docstring) + + source_name = self.get_sourcename() + enum_object: IntEnum = self.object + use_hex = self.options.hex + self.add_line('', source_name) + + for enum_value in enum_object: + the_value_name = enum_value.name + the_value_value = enum_value.value + if use_hex: + the_value_value = hex(the_value_value) + + self.add_line( + f"**{the_value_name}**: {the_value_value}", source_name) + self.add_line('', source_name) + + +def setup(app: Sphinx) -> None: + app.setup_extension('sphinx.ext.autodoc') # Require autodoc extension + app.add_autodocumenter(IntEnumDocumenter) diff --git a/doc/development/tutorials/index.rst b/doc/development/tutorials/index.rst index be126b3ca4..a7eee48991 100644 --- a/doc/development/tutorials/index.rst +++ b/doc/development/tutorials/index.rst @@ -13,3 +13,5 @@ Refer to the following tutorials to get started with extension development. helloworld todo recipe + autodoc_ext + diff --git a/doc/extdev/appapi.rst b/doc/extdev/appapi.rst index 4585df9493..9949910346 100644 --- a/doc/extdev/appapi.rst +++ b/doc/extdev/appapi.rst @@ -167,26 +167,33 @@ type for that event:: 4. event.env-before-read-docs(app, env, docnames) for docname in docnames: - 5. event.env-purge-doc(app, env, docname) + 5. event.env-purge-doc(app, env, docname) + if doc changed and not removed: 6. source-read(app, docname, source) - 7. run source parsers: text -> docutils.document (parsers can be added with the app.add_source_parser() API) - 8. apply transforms (by priority): docutils.document -> docutils.document - - event.doctree-read(app, doctree) is called in the middly of transforms, + 7. run source parsers: text -> docutils.document + - parsers can be added with the app.add_source_parser() API + 8. apply transforms based on priority: docutils.document -> docutils.document + - event.doctree-read(app, doctree) is called in the middle of transforms, transforms come before/after this event depending on their priority. - 9. (if running in parallel mode, for each process) event.env-merged-info(app, env, docnames, other) + + 9. event.env-merged-info(app, env, docnames, other) + - if running in parallel mode, this event will be emitted for each process + 10. event.env-updated(app, env) 11. event.env-get-updated(app, env) 12. event.env-check-consistency(app, env) # The updated-docs list can be builder dependent, but generally includes all new/changed documents, # plus any output from `env-get-updated`, and then all "parent" documents in the ToC tree - # For builders that output a single page, they are first joined into a single doctree before post-transforms/doctree-resolved + # For builders that output a single page, they are first joined into a single doctree before post-transforms + # or the doctree-resolved event is emitted for docname in updated-docs: 13. apply post-transforms (by priority): docutils.document -> docutils.document 14. event.doctree-resolved(app, doctree, docname) - - (for any reference node that fails to resolve) event.missing-reference(env, node, contnode) - - (for any reference node that fails to resolve) event.warn-missing-reference(domain, node) + - In the event that any reference nodes fail to resolve, the following may emit: + - event.missing-reference(env, node, contnode) + - event.warn-missing-reference(domain, node) 15. Generate output files 16. event.build-finished(app, exception) diff --git a/doc/extdev/deprecated.rst b/doc/extdev/deprecated.rst index ccf1e79da1..96bc84ff3b 100644 --- a/doc/extdev/deprecated.rst +++ b/doc/extdev/deprecated.rst @@ -22,6 +22,56 @@ The following is a list of deprecated interfaces. - (will be) Removed - Alternatives + * - ``favicon`` variable in HTML templates + - 4.0 + - TBD + - ``favicon_url`` + + * - ``logo`` variable in HTML templates + - 4.0 + - TBD + - ``logo_url`` + + * - ``sphinx.directives.patches.ListTable`` + - 4.0 + - 6.0 + - ``docutils.parsers.rst.diretives.tables.ListSVTable`` + + * - ``sphinx.directives.patches.RSTTable`` + - 4.0 + - 6.0 + - ``docutils.parsers.rst.diretives.tables.RSTTable`` + + * - ``sphinx.registry.SphinxComponentRegistry.get_source_input()`` + - 4.0 + - 6.0 + - N/A + + * - ``sphinx.registry.SphinxComponentRegistry.source_inputs`` + - 4.0 + - 6.0 + - N/A + + * - ``sphinx.transforms.FigureAligner`` + - 4.0 + - 6.0 + - N/A + + * - ``sphinx.util.pycompat.convert_with_2to3()`` + - 4.0 + - 6.0 + - N/A + + * - ``sphinx.util.pycompat.execfile_()`` + - 4.0 + - 6.0 + - N/A + + * - ``sphinx.util.smartypants`` + - 4.0 + - 6.0 + - ``docutils.utils.smartyquotes`` + * - pending_xref node for viewcode extension - 3.5 - 5.0 diff --git a/doc/extdev/nodes.rst b/doc/extdev/nodes.rst index 5d8272eae2..3976de4c70 100644 --- a/doc/extdev/nodes.rst +++ b/doc/extdev/nodes.rst @@ -37,8 +37,8 @@ New inline nodes .. autoclass:: index .. autoclass:: pending_xref +.. autoclass:: pending_xref_condition .. autoclass:: literal_emphasis -.. autoclass:: abbreviation .. autoclass:: download_reference Special nodes diff --git a/doc/latex.rst b/doc/latex.rst index 4467319645..b736c56ef0 100644 --- a/doc/latex.rst +++ b/doc/latex.rst @@ -139,57 +139,33 @@ Keys that you may want to override include: ``babel``, not ``polyglossia``. ``'fontpkg'`` - Font package inclusion. The default of ``'\\usepackage{times}'`` uses Times - for text, Helvetica for sans serif and Courier for monospace. - - In order to support occasional Cyrillic (физика частиц) or Greek - letters (Σωματιδιακή φυσική) in a document whose language is - English or a Latin European one, the default set-up is enhanced (only for - ``'pdflatex'`` engine) to do: - - .. code-block:: latex - - \substitutefont{LGR}{\rmdefault}{cmr} - \substitutefont{LGR}{\sfdefault}{cmss} - \substitutefont{LGR}{\ttdefault}{cmtt} - \substitutefont{X2}{\rmdefault}{cmr} - \substitutefont{X2}{\sfdefault}{cmss} - \substitutefont{X2}{\ttdefault}{cmtt} - - This is activated only under the condition that the ``'fontenc'`` key is - configured to load the ``LGR`` (Greek) and/or ``X2`` (Cyrillic) - pdflatex-font encodings (if the :confval:`language` is set to a Cyrillic - language, this ``'fontpkg'`` key must be used as "times" package has no - direct support for it; then keep only ``LGR`` lines from the above, if - support is needed for Greek in the text). - - The ``\substitutefont`` command is from the eponymous LaTeX package, which - is loaded by Sphinx if needed (on Ubuntu Xenial it is part of - ``texlive-latex-extra`` which is a Sphinx requirement). - - Only if the document actually does contain Unicode Greek letters (in text) - or Cyrillic letters, will the above default set-up cause additional - requirements for the PDF build. On Ubuntu Xenial, these are the - ``texlive-lang-greek``, ``texlive-lang-cyrillic``, and (with the above - choice of fonts) the ``cm-super`` (or ``cm-super-minimal``) packages. - - For ``'xelatex'`` and ``'lualatex'``, the default is to use the FreeFont - family: this OpenType font family supports both Cyrillic and Greek scripts - and is available as separate Ubuntu Xenial package ``fonts-freefont-otf``. - It is not necessary to install the much larger ``texlive-fonts-extra`` - package. - - ``'platex'`` (Japanese documents) engine supports individual Cyrillic and - Greek letters with no need of extra user set-up. - - Default: ``'\\usepackage{times}'`` (or ``''`` when using a Cyrillic script) + Font package inclusion. The default is:: + + r"""\usepackage{tgtermes} + \usepackage{tgheros} + \renewcommand\ttdefault{txtt} + """ + + For ``'xelatex'`` and ``'lualatex'`` however the default is to use + the GNU FreeFont. .. versionchanged:: 1.2 Defaults to ``''`` when the :confval:`language` uses the Cyrillic script. .. versionchanged:: 2.0 - Added support for individual Greek and Cyrillic letters: + Incorporates some font substitution commands to help support occasional + Greek or Cyrillic in a document using ``'pdflatex'`` engine. + + .. versionchanged:: 4.0.0 + - The font substitution commands added at ``2.0`` have been moved + to the ``'fontsubstitution'`` key, as their presence here made + it complicated for user to customize the value of ``'fontpkg'``. + - The default font setting has changed: it still uses Times and + Helvetica clones for serif and sans serif, but via better, more + complete TeX fonts and associated LaTeX packages. The + monospace font has been changed to better match the Times clone. + ``'fncychap'`` Inclusion of the "fncychap" package (which makes fancy chapter titles), @@ -320,37 +296,28 @@ Keys that don't need to be overridden unless in special cases are: .. versionadded:: 1.2 ``'fontenc'`` - "fontenc" package inclusion. + Customize this from its default ``'\\usepackage[T1]{fontenc}'`` to: - If ``'pdflatex'`` is the :confval:`latex_engine`, one can add ``LGR`` - for support of Greek letters in the document, and also ``X2`` (or - ``T2A``) for Cyrillic letters, like this: + - ``'\\usepackage[X2,T1]{fontenc}'`` if you need occasional + Cyrillic letters (физика частиц), - .. code-block:: latex + - ``'\\usepackage[LGR,T1]{fontenc}'`` if you need occasional + Greek letters (Σωματιδιακή φυσική). - r'\usepackage[LGR,X2,T1]{fontenc}' + Use ``[LGR,X2,T1]`` rather if both are needed. .. attention:: - If Greek is main language, do not use this key. Since Sphinx 2.2.1, - ``xelatex`` will be used automatically as :confval:`latex_engine`. - Formerly, Sphinx did not support producing PDF via LaTeX with Greek as - main language. + - Do not use this key for a :confval:`latex_engine` other than + ``'pdflatex'``. - Prior to 2.0, Unicode Greek letters were escaped to use LaTeX math - mark-up. This is not the case anymore, and the above must be used - (only in case of ``'pdflatex'`` engine) if the source contains such - Unicode Greek. + - If Greek is main language, do not use this key. Since Sphinx 2.2.1, + ``xelatex`` will be used automatically as :confval:`latex_engine`. - On Ubuntu xenial, packages ``texlive-lang-greek`` and ``cm-super`` - (for the latter, only if the ``'fontpkg'`` setting is left to its - default) are needed for ``LGR`` to work. In place of ``cm-super`` - one can install smaller ``cm-super-minimal``, but it requires the - LaTeX document to execute ``\usepackage[10pt]{type1ec}`` before - loading ``fontenc``. Thus, use this key with this extra at its - start if needed. - - Default: ``'\\usepackage[T1]{fontenc}'`` + - The TeX installation may need some extra packages. For example, + on Ubuntu xenial, packages ``texlive-lang-greek`` and ``cm-super`` + are needed for ``LGR`` to work. And ``texlive-lang-cyrillic`` and + ``cm-super`` are needed for support of Cyrillic. .. versionchanged:: 1.5 Defaults to ``'\\usepackage{fontspec}'`` when @@ -367,32 +334,37 @@ Keys that don't need to be overridden unless in special cases are: .. versionchanged:: 2.0 Detection of ``LGR``, ``T2A``, ``X2`` to trigger support of - occasional Greek or Cyrillic (``'pdflatex'`` only, as this support - is provided natively by ``'platex'`` and only requires suitable - font with ``'xelatex'/'lualatex'``). + occasional Greek or Cyrillic letters (``'pdflatex'``). .. versionchanged:: 2.3.0 - ``'xelatex'`` also executes + ``'xelatex'`` executes ``\defaultfontfeatures[\rmfamily,\sffamily]{}`` in order to avoid contractions of ``--`` into en-dash or transforms of straight quotes into curly ones in PDF (in non-literal text paragraphs) despite :confval:`smartquotes` being set to ``False``. -``'textgreek'`` - This is needed for ``pdflatex`` to support Unicode input of Greek - letters such as φύσις. Expert users may want to load the ``textalpha`` - package with its option ``normalize-symbols``. +``'fontsubstitution'`` + Ignored if ``'fontenc'`` was not configured to use ``LGR`` or ``X2`` (or + ``T2A``). In case ``'fontpkg'`` key is configured for usage with some + TeX fonts known to be available in the ``LGR`` or ``X2`` encodings, set + this one to be the empty string. Else leave to its default. - .. hint:: + Ignored with :confval:`latex_engine` other than ``'pdflatex'``. + + .. versionadded:: 4.0.0 + +``'textgreek'`` + For the support of occasional Greek letters. - Unicode Greek (but no further Unicode symbols) in :rst:dir:`math` - can be supported by ``'pdflatex'`` from setting this key to - ``r'\usepackage{textalpha,alphabeta}'``. Then ``:math:`α``` (U+03B1) - will render as :math:`\alpha`. For wider Unicode support in math - input, see the discussion of :confval:`latex_engine`. + It is ignored with ``'platex'``, ``'xelatex'`` or ``'lualatex'`` as + :confval:`latex_engine` and defaults to either the empty string or + to ``'\\usepackage{textalpha}'`` for ``'pdflatex'`` depending on + whether the ``'fontenc'`` key was used with ``LGR`` or not. Only + expert LaTeX users may want to customize this key. - With ``'platex'`` (Japanese), ``'xelatex'`` or ``'lualatex'``, this - key is ignored. + It can also be used as ``r'\usepackage{textalpha,alphabeta}'`` to let + ``'pdflatex'`` support Greek Unicode input in :rst:dir:`math` context. + For example ``:math:`α``` (U+03B1) will render as :math:`\alpha`. Default: ``'\\usepackage{textalpha}'`` or ``''`` if ``fontenc`` does not include the ``LGR`` option. @@ -517,19 +489,25 @@ Keys that don't need to be overridden unless in special cases are: Default: ``'\\printindex'`` ``'fvset'`` - Customization of ``fancyvrb`` LaTeX package. The default value of - ``'\\fvset{fontsize=\\small}'`` is used to adjust for the large character - width of the monospace font, used in code-blocks. You may need to modify - this if you use custom fonts. + Customization of ``fancyvrb`` LaTeX package. - Default: ``'\\fvset{fontsize=\\small}'`` + The default value is ``'\\fvset{fontsize=auto}'`` which means that the + font size will adjust correctly if a code-block ends up in a footnote. + You may need to modify this if you use custom fonts: + ``'\\fvset{fontsize=\\small}'`` if the monospace font is Courier-like. + + Default: ``'\\fvset{fontsize=auto}'`` .. versionadded:: 1.8 .. versionchanged:: 2.0 - Due to new default font choice for ``'xelatex'`` and ``'lualatex'`` - (FreeFont), Sphinx does ``\\fvset{fontsize=\\small}`` also with these - engines (and not ``\\fvset{fontsize=auto}``). + For ``'xelatex'`` and ``'lualatex'`` defaults to + ``'\\fvset{fontsize=\\small}'`` as this + is adapted to the relative widths of the FreeFont family. + + .. versionchanged:: 4.0.0 + Changed default for ``'pdflatex'``. Previously it was using + ``'\\fvset{fontsize=\\small}'``. Keys that are set by other options and therefore should not be overridden are: @@ -917,9 +895,36 @@ macros may be significant. LaTeX macros and environments ----------------------------- -Here are some macros from the package file :file:`sphinx.sty` and class files -:file:`sphinxhowto.cls`, :file:`sphinxmanual.cls`, which have public names -thus allowing redefinitions. Check the respective files for the defaults. +The "LaTeX package" file :file:`sphinx.sty` loads various components +providing support macros (aka commands), and environments, which are used in +the mark-up produced on output from the ``latex`` builder, before conversion +to ``pdf`` via the LaTeX toolchain. Also the "LaTeX class" files +:file:`sphinxhowto.cls` and :file:`sphinxmanual.cls` define or customize some +environments. All of these files can be found in the latex build repertory. + +Some of these provide facilities not available from pre-existing LaTeX +packages and work around LaTeX limitations with lists, table cells, verbatim +rendering, footnotes, etc... + +Others simply define macros with public names to make overwriting their +defaults easy via user-added contents to the preamble. We will survey most of +those public names here, but defaults have to be looked at in their respective +definition files. + +.. hint:: + + Sphinx LaTeX support code is split across multiple smaller-sized files. + Rather than adding code to the preamble via + `latex_elements `_\ [``'preamble'``] it is + also possible to replace entirely one of the component files of Sphinx + LaTeX code with a custom version, simply by including a modified copy in + the project source and adding the filename to the + :confval:`latex_additional_files` list. Check the LaTeX build repertory + for the filenames and contents. + +.. versionchanged:: 4.0.0 + split of :file:`sphinx.sty` into multiple smaller units, to facilitate + customization of many aspects simultaneously. .. _latex-macros: diff --git a/doc/man/sphinx-apidoc.rst b/doc/man/sphinx-apidoc.rst index 725d2f1692..3ce5b45233 100644 --- a/doc/man/sphinx-apidoc.rst +++ b/doc/man/sphinx-apidoc.rst @@ -145,7 +145,7 @@ These options are used when :option:`--full` is specified: * ``module.rst_t`` * ``package.rst_t`` * ``toc.rst_t`` - * ``master_doc.rst_t`` + * ``root_doc.rst_t`` * ``conf.py_t`` * ``Makefile_t`` * ``Makefile.new_t`` diff --git a/doc/man/sphinx-quickstart.rst b/doc/man/sphinx-quickstart.rst index 520a420ce7..16fc665605 100644 --- a/doc/man/sphinx-quickstart.rst +++ b/doc/man/sphinx-quickstart.rst @@ -72,7 +72,7 @@ Options .. option:: --master=MASTER - Master document name. (see :confval:`master_doc`). + Master document name. (see :confval:`root_doc`). .. rubric:: Extension Options @@ -149,7 +149,7 @@ Options sphinx project files generated by quickstart. Following Jinja2 template files are allowed: - * ``master_doc.rst_t`` + * ``root_doc.rst_t`` * ``conf.py_t`` * ``Makefile_t`` * ``Makefile.new_t`` diff --git a/doc/templating.rst b/doc/templating.rst index 548f8b8d93..61b714bfa3 100644 --- a/doc/templating.rst +++ b/doc/templating.rst @@ -274,7 +274,19 @@ in the future. .. data:: favicon - The path to the HTML favicon in the static path, or ``''``. + The path to the HTML favicon in the static path, or URL to the favicon, or + ``''``. + + .. deprecated:: 4.0 + + Recommend to use ``favicon_url`` instead. + +.. data:: favicon_url + + The relative path to the HTML favicon image from the current document, or + URL to the favicon, or ``''``. + + .. versionadded:: 4.0 .. data:: file_suffix @@ -297,11 +309,35 @@ in the future. .. data:: logo - The path to the HTML logo image in the static path, or ``''``. + The path to the HTML logo image in the static path, or URL to the logo, or + ``''``. + + .. deprecated:: 4.0 + + Recommend to use ``logo_url`` instead. + +.. data:: logo_url + + The relative path to the HTML logo image from the current document, or URL + to the logo, or ``''``. + + .. versionadded:: 4.0 .. data:: master_doc - The value of :confval:`master_doc`, for usage with :func:`pathto`. + Same as :data:`root_doc`. + + .. versionchanged:: 4.0 + + Renamed to ``root_doc``. + +.. data:: root_doc + + The value of :confval:`root_doc`, for usage with :func:`pathto`. + + .. versionchanged:: 4.0 + + Renamed from ``master_doc``. .. data:: pagename diff --git a/doc/usage/advanced/intl.rst b/doc/usage/advanced/intl.rst index 67d5e10e56..03b77fb6b3 100644 --- a/doc/usage/advanced/intl.rst +++ b/doc/usage/advanced/intl.rst @@ -306,7 +306,7 @@ Contributing to Sphinx reference translation The recommended way for new contributors to translate Sphinx reference is to join the translation team on Transifex. -There is `sphinx translation page`_ for Sphinx (master) documentation. +There is a `sphinx translation page`_ for Sphinx (master) documentation. 1. Login to transifex_ service. 2. Go to `sphinx translation page`_. @@ -314,6 +314,8 @@ There is `sphinx translation page`_ for Sphinx (master) documentation. 4. Wait acceptance by transifex sphinx translation maintainers. 5. (After acceptance) Translate on transifex. +Detail is here: https://docs.transifex.com/getting-started-1/translators + .. rubric:: Footnotes .. [1] See the `GNU gettext utilities diff --git a/doc/usage/builders/index.rst b/doc/usage/builders/index.rst index c45a8062fb..74853fee97 100644 --- a/doc/usage/builders/index.rst +++ b/doc/usage/builders/index.rst @@ -179,6 +179,7 @@ The builder's "name" must be given to the **-b** command-line option of * ``texlive-latex-recommended`` * ``texlive-fonts-recommended`` + * ``tex-gyre`` (if :confval:`latex_engine` is ``'pdflatex'``) * ``texlive-latex-extra`` * ``latexmk`` (this is a Sphinx requirement on GNU/Linux and MacOS X for functioning of ``make latexpdf``) @@ -186,17 +187,14 @@ The builder's "name" must be given to the **-b** command-line option of Additional packages are needed in some circumstances (see the discussion of the ``'fontpkg'`` key of :confval:`latex_elements` for more information): - * to support occasional Cyrillic letters or words, and a fortiori if - :confval:`language` is set to a Cyrillic language, the package - ``texlive-lang-cyrillic`` is required, and, with unmodified ``'fontpkg'``, - also ``cm-super`` or ``cm-super-minimal``, - * to support occasional Greek letters or words (in text, not in - :rst:dir:`math` directive contents), ``texlive-lang-greek`` is required, - and, with unmodified ``'fontpkg'``, also ``cm-super`` or - ``cm-super-minimal``, - * for ``'xelatex'`` or ``'lualatex'`` (see :confval:`latex_engine`), - ``texlive-xetex`` resp. ``texlive-luatex``, and, if leaving unchanged - ``'fontpkg'``, ``fonts-freefont-otf``. + * ``texlive-lang-cyrillic`` for Cyrillic (even individual letters), and, + ``cm-super`` or ``cm-super-minimal`` (if default fonts), + * ``texlive-lang-greek`` for Greek (even individual letters), and, + ``cm-super`` or ``cm-super-minimal`` (if default fonts), + * ``texlive-xetex`` if :confval:`latex_engine` is ``'xelatex'``, + * ``texlive-luatex`` if :confval:`latex_engine` is ``'lualatex'``, + * ``fonts-freefont-otf`` if :confval:`latex_engine` is ``'xelatex'`` + or ``'lualatex'``. The testing of Sphinx LaTeX is done on Ubuntu xenial whose TeX distribution is based on a TeXLive 2015 snapshot dated March 2016. @@ -207,6 +205,9 @@ The builder's "name" must be given to the **-b** command-line option of .. versionchanged:: 2.0 Formerly, testing had been done on Ubuntu trusty (TeXLive 2013). + .. versionchanged:: 4.0.0 + TeX Gyre fonts dependency for the default LaTeX font configuration. + .. note:: Since 1.6, ``make latexpdf`` uses ``latexmk`` (not on Windows). This diff --git a/doc/usage/configuration.rst b/doc/usage/configuration.rst index c2250eb7d9..989ce8737e 100644 --- a/doc/usage/configuration.rst +++ b/doc/usage/configuration.rst @@ -183,11 +183,20 @@ General configuration .. confval:: master_doc - The document name of the "master" document, that is, the document that + Same as :confval:`root_doc`. + + .. versionchanged:: 4.0 + Renamed ``master_doc`` to ``master_doc``. + +.. confval:: root_doc + + The document name of the "root" document, that is, the document that contains the root :rst:dir:`toctree` directive. Default is ``'index'``. .. versionchanged:: 2.0 The default is changed to ``'index'`` from ``'contents'``. + .. versionchanged:: 4.0 + Renamed ``master_doc`` from ``master_doc``. .. confval:: exclude_patterns @@ -479,11 +488,10 @@ General configuration .. confval:: smartquotes_action - This string, for use with Docutils ``0.14`` or later, customizes the Smart - Quotes transform. See the file :file:`smartquotes.py` at the `Docutils - repository`__ for details. The default ``'qDe'`` educates normal **q**\ - uote characters ``"``, ``'``, em- and en-**D**\ ashes ``---``, ``--``, and - **e**\ llipses ``...``. + This string customizes the Smart Quotes transform. See the file + :file:`smartquotes.py` at the `Docutils repository`__ for details. The + default ``'qDe'`` educates normal **q**\ uote characters ``"``, ``'``, + em- and en-**D**\ ashes ``---``, ``--``, and **e**\ llipses ``...``. .. versionadded:: 1.6.6 @@ -834,13 +842,16 @@ documentation on :ref:`intl` for details. :literal-block: literal blocks (``::`` annotation and ``code-block`` directive) :doctest-block: doctest block :raw: raw content - :image: image/figure uri and alt + :image: image/figure uri For example: ``gettext_additional_targets = ['literal-block', 'image']``. The default is ``[]``. .. versionadded:: 1.3 + .. versionchanged:: 4.0 + + The alt text for image is translated by default. .. confval:: figure_language_filename @@ -970,10 +981,15 @@ that use Sphinx's HTMLWriter class. The style of line numbers for code-blocks. - * ``'table'`` -- display line numbers using ```` tag (default) - * ``'inline'`` -- display line numbers using ```` tag + * ``'table'`` -- display line numbers using ``
`` tag + * ``'inline'`` -- display line numbers using ```` tag (default) .. versionadded:: 3.2 + .. versionchanged:: 4.0 + + It defaults to ``'inline'``. + + .. deprecated:: 4.0 .. confval:: html_context @@ -986,26 +1002,32 @@ that use Sphinx's HTMLWriter class. .. confval:: html_logo If given, this must be the name of an image file (path relative to the - :term:`configuration directory`) that is the logo of the docs. It is placed - at the top of the sidebar; its width should therefore not exceed 200 pixels. - Default: ``None``. + :term:`configuration directory`) that is the logo of the docs, or URL that + points an image file for the logo. It is placed at the top of the sidebar; + its width should therefore not exceed 200 pixels. Default: ``None``. .. versionadded:: 0.4.1 The image file will be copied to the ``_static`` directory of the output HTML, but only if the file does not already exist there. + .. versionchanged:: 4.0 + Also accepts the URL for the logo file. + .. confval:: html_favicon If given, this must be the name of an image file (path relative to the - :term:`configuration directory`) that is the favicon of the docs. Modern - browsers use this as the icon for tabs, windows and bookmarks. It should - be a Windows-style icon file (``.ico``), which is 16x16 or 32x32 - pixels large. Default: ``None``. + :term:`configuration directory`) that is the favicon of the docs, or URL that + points an image file for the favicon. Modern browsers use this as the icon + for tabs, windows and bookmarks. It should be a Windows-style icon file + (``.ico``), which is 16x16 or 32x32 pixels large. Default: ``None``. .. versionadded:: 0.4 The image file will be copied to the ``_static`` directory of the output HTML, but only if the file does not already exist there. + .. versionchanged:: 4.0 + Also accepts the URL for the favicon. + .. confval:: html_css_files A list of CSS files. The entry must be a *filename* string or a tuple @@ -1479,8 +1501,7 @@ that use Sphinx's HTMLWriter class. .. confval:: html_experimental_html5_writer - Output is processed with HTML5 writer. This feature needs docutils 0.13 or - newer. Default is ``False``. + Output is processed with HTML5 writer. Default is ``False``. .. versionadded:: 1.6 @@ -1957,8 +1978,8 @@ These options influence LaTeX output. * ``'pdflatex'`` -- PDFLaTeX (default) * ``'xelatex'`` -- XeLaTeX * ``'lualatex'`` -- LuaLaTeX - * ``'platex'`` -- pLaTeX (default if :confval:`language` is ``'ja'``) - * ``'uplatex'`` -- upLaTeX (experimental) + * ``'platex'`` -- pLaTeX + * ``'uplatex'`` -- upLaTeX (default if :confval:`language` is ``'ja'``) ``'pdflatex'``\ 's support for Unicode characters is limited. @@ -1988,6 +2009,10 @@ These options influence LaTeX output. Add ``uplatex`` support. + .. versionchanged:: 4.0 + + ``uplatex`` becomes the default setting of Japanese documents. + Contrarily to :ref:`MathJaX math rendering in HTML output `, LaTeX requires some extra configuration to support Unicode literals in :rst:dir:`math`: the only comprehensive solution (as far as we know) is to @@ -2007,8 +2032,8 @@ These options influence LaTeX output. *startdocname* String that specifies the :term:`document name` of the LaTeX file's master document. All documents referenced by the *startdoc* document in TOC trees - will be included in the LaTeX file. (If you want to use the default master - document for your LaTeX build, provide your :confval:`master_doc` here.) + will be included in the LaTeX file. (If you want to use the default root + document for your LaTeX build, provide your :confval:`root_doc` here.) *targetname* File name of the LaTeX file in the output directory. @@ -2277,7 +2302,7 @@ These options influence manual page output. String that specifies the :term:`document name` of the manual page's master document. All documents referenced by the *startdoc* document in TOC trees will be included in the manual file. (If you want to use the default - master document for your manual pages build, use your :confval:`master_doc` + root document for your manual pages build, use your :confval:`root_doc` here.) *name* @@ -2307,10 +2332,12 @@ These options influence manual page output. .. confval:: man_make_section_directory - If true, make a section directory on build man page. Default is False. + If true, make a section directory on build man page. Default is True. .. versionadded:: 3.3 + .. versionchanged:: 4.0 + The default is changed to ``False`` from ``True``. .. _texinfo-options: @@ -2331,7 +2358,7 @@ These options influence Texinfo output. master document. All documents referenced by the *startdoc* document in TOC trees will be included in the Texinfo file. (If you want to use the default master document for your Texinfo build, provide your - :confval:`master_doc` here.) + :confval:`root_doc` here.) *targetname* File name (no extension) of the Texinfo file in the output directory. @@ -2687,6 +2714,17 @@ Options for the C++ domain .. versionadded:: 1.5 +Options for the Python domain +----------------------------- + +.. confval:: python_use_unqualified_type_names + + If true, suppress the module name of the python reference if it can be + resolved. The default is ``False``. + + .. versionadded:: 4.0 + + .. note:: This configuration is still in experimental Example of configuration file ============================= diff --git a/doc/usage/extensions/autodoc.rst b/doc/usage/extensions/autodoc.rst index a07042781e..034c86e113 100644 --- a/doc/usage/extensions/autodoc.rst +++ b/doc/usage/extensions/autodoc.rst @@ -89,33 +89,96 @@ inserting them into the page source under a suitable :rst:dir:`py:module`, Boil the noodle *time* minutes. - **Options and advanced usage** + .. rubric:: Options + + .. rst:directive:option:: members + :type: no value or comma separated list + + If set, autodoc will generate document for the members of the target + module, class or exception. - * If you want to automatically document members, there's a ``members`` - option:: + For example:: .. automodule:: noodle :members: - will document all module members (recursively), and :: + will document all module members (recursively), and :: .. autoclass:: Noodle :members: - will document all non-private member functions and properties (that is, - those whose name doesn't start with ``_``). + will document all class member methods and properties. - For modules, ``__all__`` will be respected when looking for members unless - you give the ``ignore-module-all`` flag option. Without - ``ignore-module-all``, the order of the members will also be the order in - ``__all__``. + By default, autodoc will not generate document for the members that are + private, not having docstrings, inherited from super class, or special + members. - You can also give an explicit list of members; only these will then be - documented:: + For modules, ``__all__`` will be respected when looking for members unless + you give the ``ignore-module-all`` flag option. Without + ``ignore-module-all``, the order of the members will also be the order in + ``__all__``. + + You can also give an explicit list of members; only these will then be + documented:: .. autoclass:: Noodle :members: eat, slurp + .. rst:directive:option:: undoc-members + :type: no value + + If set, autodoc will also generate document for the members not having + docstrings:: + + .. automodule:: noodle + :members: + :undoc-members: + + .. rst:directive:option:: private-members + :type: no value or comma separated list + + If set, autodoc will also generate document for the private members + (that is, those named like ``_private`` or ``__private``):: + + .. automodule:: noodle + :members: + :private-members: + + It can also take an explicit list of member names to be documented as + arguments:: + + .. automodule:: noodle + :members: + :private-members: _spicy, _garlickly + + .. versionadded:: 1.1 + .. versionchanged:: 3.2 + The option can now take arguments. + + .. rst:directive:option:: special-members + :type: no value or comma separated list + + If set, autodoc will also generate document for the special members + (that is, those named like ``__special__``):: + + .. autoclass:: my.Class + :members: + :special-members: + + It can also take an explicit list of member names to be documented as + arguments:: + + .. autoclass:: my.Class + :members: + :special-members: __init__, __name__ + + .. versionadded:: 1.1 + + .. versionchanged:: 1.2 + The option can now take arguments + + **Options and advanced usage** + * If you want to make the ``members`` option (or other options described below) the default, see :confval:`autodoc_default_options`. @@ -139,31 +202,6 @@ inserting them into the page source under a suitable :rst:dir:`py:module`, .. versionchanged:: 3.5 The default options can be overridden or extended temporarily. - * Members without docstrings will be left out, unless you give the - ``undoc-members`` flag option:: - - .. automodule:: noodle - :members: - :undoc-members: - - * "Private" members (that is, those named like ``_private`` or ``__private``) - will be included if the ``private-members`` flag option is given:: - - .. automodule:: noodle - :members: - :private-members: - - It can also take an explicit list of member names to be documented as - arguments:: - - .. automodule:: noodle - :members: - :private-members: _spicy, _garlickly - - .. versionadded:: 1.1 - .. versionchanged:: 3.2 - The option can now take arguments. - * autodoc considers a member private if its docstring contains ``:meta private:`` in its :ref:`info-field-lists`. For example: @@ -203,21 +241,6 @@ inserting them into the page source under a suitable :rst:dir:`py:module`, .. versionadded:: 3.5 - * Python "special" members (that is, those named like ``__special__``) will - be included if the ``special-members`` flag option is given:: - - .. autoclass:: my.Class - :members: - :private-members: - :special-members: - - would document both "private" and "special" members of the class. - - .. versionadded:: 1.1 - - .. versionchanged:: 1.2 - The option can now take arguments, i.e. the special members to document. - * For classes and exceptions, members inherited from base classes will be left out when documenting all members, unless you give the ``inherited-members`` option, in addition to ``members``:: @@ -586,6 +609,16 @@ There are also config values that you can set: .. __: https://mypy.readthedocs.io/en/latest/kinds_of_types.html#type-aliases .. versionadded:: 3.3 +.. confval:: autodoc_preserve_defaults + + If True, the default argument values of functions will be not evaluated on + generating document. It preserves them as is in the source code. + + .. versionadded:: 4.0 + + Added as an experimental feature. This will be integrated into autodoc core + in the future. + .. confval:: autodoc_warningiserror This value controls the behavior of :option:`sphinx-build -W` during @@ -597,7 +630,7 @@ There are also config values that you can set: This value controls the docstrings inheritance. If set to True the docstring for classes or methods, if not explicitly set, - is inherited form parents. + is inherited from parents. The default is ``True``. diff --git a/doc/usage/extensions/autosummary.rst b/doc/usage/extensions/autosummary.rst index 03ea7548e2..28f207de7f 100644 --- a/doc/usage/extensions/autosummary.rst +++ b/doc/usage/extensions/autosummary.rst @@ -19,11 +19,13 @@ The :mod:`sphinx.ext.autosummary` extension does this in two parts: that contain links to the documented items, and short summary blurbs extracted from their docstrings. -2. Optionally, the convenience script :program:`sphinx-autogen` or the new - :confval:`autosummary_generate` config value can be used to generate short - "stub" files for the entries listed in the :rst:dir:`autosummary` directives. - These files by default contain only the corresponding - :mod:`sphinx.ext.autodoc` directive, but can be customized with templates. +2. A :rst:dir:`autosummary` directive also generates short "stub" files for the + entries listed in its content. These files by default contain only the + corresponding :mod:`sphinx.ext.autodoc` directive, but can be customized with + templates. + + The :program:`sphinx-autogen` script is also able to generate "stub" files + from command line. .. rst:directive:: autosummary @@ -161,7 +163,7 @@ also use these config values: .. confval:: autosummary_generate Boolean indicating whether to scan all found documents for autosummary - directives, and to generate stub pages for each. It is disabled by default. + directives, and to generate stub pages for each. It is enabled by default. Can also be a list of documents for which stub pages should be generated. @@ -173,6 +175,10 @@ also use these config values: Emits :event:`autodoc-skip-member` event as :mod:`~sphinx.ext.autodoc` does. + .. versionchanged:: 4.0 + + Enabled by default. + .. confval:: autosummary_generate_overwrite If true, autosummary overwrites existing files by generated stub pages. diff --git a/doc/usage/extensions/math.rst b/doc/usage/extensions/math.rst index 780e57ee29..655364767b 100644 --- a/doc/usage/extensions/math.rst +++ b/doc/usage/extensions/math.rst @@ -140,6 +140,12 @@ are built: .. module:: sphinx.ext.mathjax :synopsis: Render math using JavaScript via MathJax. +.. warning:: + Version 4.0 changes the version of MathJax used to version 3. You may need to + override ``mathjax_path`` to + ``https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=TeX-AMS-MML_HTMLorMML`` + or update your configuration options for version 3. + .. versionadded:: 1.1 This extension puts math as-is into the HTML files. The JavaScript package @@ -161,14 +167,14 @@ Sphinx but is set to automatically include it from a third-party site. MathJax. The default is the ``https://`` URL that loads the JS files from the - `cdnjs`__ Content Delivery Network. See the `MathJax Getting Started + `jsdelivr`__ Content Delivery Network. See the `MathJax Getting Started page`__ for details. If you want MathJax to be available offline or without including resources from a third-party site, you have to download it and set this value to a different path. - __ https://cdnjs.com + __ https://www.jsdelivr.com/ - __ https://docs.mathjax.org/en/latest/start.html + __ https://www.mathjax.org/#gettingstarted The path can be absolute or relative; if it is relative, it is relative to the ``_static`` directory of the built docs. diff --git a/doc/usage/installation.rst b/doc/usage/installation.rst index 46ef6a51ec..f0384ea9dd 100644 --- a/doc/usage/installation.rst +++ b/doc/usage/installation.rst @@ -12,7 +12,7 @@ Installing Sphinx Overview -------- -Sphinx is written in `Python`__ and supports Python 3.5+. It builds upon the +Sphinx is written in `Python`__ and supports Python 3.6+. It builds upon the shoulders of many third-party libraries such as `Docutils`__ and `Jinja`__, which are installed when Sphinx is installed. @@ -107,7 +107,30 @@ Anaconda Windows ------- -.. todo:: Could we start packaging this? +Sphinx can be install using `Chocolatey`__ or +:ref:`installed manually `. + +__ https://chocolatey.org/ + +Chocolatey +~~~~~~~~~~ + +:: + + $ choco install sphinx + +You would need to `install Chocolatey +`_ +before running this. + +For more information, refer to the `chocolatey page`__. + +__ https://chocolatey.org/packages/sphinx/ + +.. _windows-other-method: + +Other Methods +~~~~~~~~~~~~~ Most Windows users do not have Python installed by default, so we begin with the installation of Python itself. To check if you already have Python @@ -183,7 +206,7 @@ Please choose one for your purpose. 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:: - $ docker run --rm -v /path/to/document:/docs sphinxdoc/sphinx sphinx-quickstart + $ docker run -it --rm -v /path/to/document:/docs sphinxdoc/sphinx sphinx-quickstart And you can following command this to build HTML document:: diff --git a/doc/usage/restructuredtext/basics.rst b/doc/usage/restructuredtext/basics.rst index 8f596ed9a9..03b690f441 100644 --- a/doc/usage/restructuredtext/basics.rst +++ b/doc/usage/restructuredtext/basics.rst @@ -288,7 +288,7 @@ Roles ----- A role or "custom interpreted text role" (:duref:`ref `) is an inline -piece of explicit markup. It signifies that that the enclosed text should be +piece of explicit markup. It signifies that the enclosed text should be interpreted in a specific way. Sphinx uses this to provide semantic markup and cross-referencing of identifiers, as described in the appropriate section. The general syntax is ``:rolename:`content```. diff --git a/doc/usage/restructuredtext/directives.rst b/doc/usage/restructuredtext/directives.rst index e8b88c21b2..995804e370 100644 --- a/doc/usage/restructuredtext/directives.rst +++ b/doc/usage/restructuredtext/directives.rst @@ -197,9 +197,9 @@ tables of contents. The ``toctree`` directive is the central element. ` to let a document be built, but notify Sphinx that it is not reachable via a toctree. - The "master document" (selected by :confval:`master_doc`) is the "root" of - the TOC tree hierarchy. It can be used as the documentation's main page, or - as a "full table of contents" if you don't give a ``maxdepth`` option. + The "root document" (selected by :confval:`root_doc`) is the "root" of the TOC + tree hierarchy. It can be used as the documentation's main page, or as a + "full table of contents" if you don't give a ``maxdepth`` option. .. versionchanged:: 0.3 Added "globbing" option. @@ -404,10 +404,15 @@ Showing code examples single: sourcecode There are multiple ways to show syntax-highlighted literal code blocks in -Sphinx: using :ref:`reST doctest blocks `; using :ref:`reST -literal blocks `, optionally in combination with the -:rst:dir:`highlight` directive; using the :rst:dir:`code-block` directive; and -using the :rst:dir:`literalinclude` directive. Doctest blocks can only be used +Sphinx: + +* using :ref:`reST doctest blocks `; +* using :ref:`reST literal blocks `, optionally in + combination with the :rst:dir:`highlight` directive; +* using the :rst:dir:`code-block` directive; +* and using the :rst:dir:`literalinclude` directive. + +Doctest blocks can only be used to show interactive Python sessions, while the remaining three can be used for other languages. Of these three, literal blocks are useful when an entire document, or at least large sections of it, use code blocks with the same diff --git a/doc/usage/restructuredtext/domains.rst b/doc/usage/restructuredtext/domains.rst index e4909f7930..bd10640558 100644 --- a/doc/usage/restructuredtext/domains.rst +++ b/doc/usage/restructuredtext/domains.rst @@ -202,6 +202,14 @@ The following directives are provided for module and class contents: .. versionadded:: 2.1 + .. rst:directive:option:: canonical + :type: full qualified name including module name + + Describe the location where the object is defined if the object is + imported from other modules + + .. versionadded:: 4.0 + .. rst:directive:: .. py:data:: name Describes global data in a module, including both variables and values used @@ -220,6 +228,14 @@ The following directives are provided for module and class contents: .. versionadded:: 2.4 + .. rst:directive:option:: canonical + :type: full qualified name including module name + + Describe the location where the object is defined if the object is + imported from other modules + + .. versionadded:: 4.0 + .. rst:directive:: .. py:exception:: name Describes an exception class. The signature can, but need not include @@ -259,6 +275,14 @@ The following directives are provided for module and class contents: .. rubric:: options + .. rst:directive:option:: canonical + :type: full qualified name including module name + + Describe the location where the object is defined if the object is + imported from other modules + + .. versionadded:: 4.0 + .. rst:directive:option:: final :type: no value @@ -284,6 +308,14 @@ The following directives are provided for module and class contents: .. versionadded:: 2.4 + .. rst:directive:option:: canonical + :type: full qualified name including module name + + Describe the location where the object is defined if the object is + imported from other modules + + .. versionadded:: 4.0 + .. rst:directive:: .. py:method:: name(parameters) Describes an object method. The parameters should not include the ``self`` @@ -307,6 +339,14 @@ The following directives are provided for module and class contents: .. versionadded:: 2.1 + .. rst:directive:option:: canonical + :type: full qualified name including module name + + Describe the location where the object is defined if the object is + imported from other modules + + .. versionadded:: 4.0 + .. rst:directive:option:: classmethod :type: no value @@ -1848,7 +1888,7 @@ currently Ada_, CoffeeScript_, Erlang_, HTTP_, Lasso_, MATLAB_, PHP_, and Ruby_ domains. Also available are domains for `Chapel`_, `Common Lisp`_, dqn_, Go_, Jinja_, Operation_, and Scala_. -.. _sphinx-contrib: https://bitbucket.org/birkenfeld/sphinx-contrib/ +.. _sphinx-contrib: https://github.com/sphinx-contrib .. _Ada: https://pypi.org/project/sphinxcontrib-adadomain/ .. _Chapel: https://pypi.org/project/sphinxcontrib-chapeldomain/ diff --git a/doc/usage/theming.rst b/doc/usage/theming.rst index fb06e87411..fc135a0952 100644 --- a/doc/usage/theming.rst +++ b/doc/usage/theming.rst @@ -334,38 +334,15 @@ These themes are: Third Party Themes ~~~~~~~~~~~~~~~~~~ -.. cssclass:: longtable - -+--------------------+--------------------+ -| **Theme overview** | | -+--------------------+--------------------+ -| |sphinx_rtd_theme| | | -| | | -| *sphinx_rtd_theme* | | -+--------------------+--------------------+ - -.. |sphinx_rtd_theme| image:: /_static/themes/sphinx_rtd_theme.png - -There are many third-party themes available. Some of these are general use, -while others are specific to an individual project. A section of third-party -themes is listed below. Many more can be found on PyPI__, GitHub__, GitLab__ and -sphinx-themes.org__. - -.. cssclass:: clear - -**sphinx_rtd_theme** - `Read the Docs Sphinx Theme`_. - This is a mobile-friendly sphinx theme that was made for readthedocs.org. - View a working demo over on readthedocs.org. You can get install and options - information at `Read the Docs Sphinx Theme`_ page. - - .. _Read the Docs Sphinx Theme: https://pypi.org/project/sphinx_rtd_theme/ - - .. versionchanged:: 1.4 - **sphinx_rtd_theme** has become optional. +There are many third-party themes available for Sphinx. Some of these are for +general use, while others are specific to an individual project. +sphinx-themes.org__ is a gallery that showcases various themes for Sphinx, +with demo documentation rendered under each theme. Themes can also be found +on PyPI__ (using the classifier ``Framework :: Sphinx :: Theme``), GitHub__ +and GitLab__. +.. __: https://sphinx-themes.org/ .. __: https://pypi.org/search/?q=&o=&c=Framework+%3A%3A+Sphinx+%3A%3A+Theme -.. __: https://github.com/search?utf8=%E2%9C%93&q=sphinx+theme&type= +.. __: https://github.com/search?utf8=%E2%9C%93&q=sphinx+theme .. __: https://gitlab.com/explore?name=sphinx+theme -.. __: https://sphinx-themes.org/ diff --git a/setup.cfg b/setup.cfg index 7d629a9c56..14b071a9ec 100644 --- a/setup.cfg +++ b/setup.cfg @@ -45,7 +45,7 @@ paths = line_length = 95 [mypy] -python_version = 3.5 +python_version = 3.6 disallow_incomplete_defs = True show_column_numbers = True show_error_context = True @@ -61,7 +61,6 @@ filterwarnings = ignore::DeprecationWarning:docutils.io ignore::DeprecationWarning:pyximport.pyximport ignore::ImportWarning:importlib._bootstrap - ignore::PendingDeprecationWarning:sphinx.util.pycompat markers = apidoc setup_command diff --git a/setup.py b/setup.py index dfc80578f0..9258fded21 100644 --- a/setup.py +++ b/setup.py @@ -10,8 +10,8 @@ with open('README.rst') as f: long_desc = f.read() -if sys.version_info < (3, 5): - print('ERROR: Sphinx requires at least Python 3.5 to run.') +if sys.version_info < (3, 6): + print('ERROR: Sphinx requires at least Python 3.6 to run.') sys.exit(1) install_requires = [ @@ -23,7 +23,7 @@ 'sphinxcontrib-qthelp', 'Jinja2>=2.3', 'Pygments>=2.0', - 'docutils>=0.12', + 'docutils>=0.14', 'snowballstemmer>=1.1', 'babel>=1.3', 'alabaster>=0.7,<0.8', @@ -200,7 +200,6 @@ def _run_domain_js(self, domain): 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', @@ -242,7 +241,7 @@ def _run_domain_js(self, domain): 'build_sphinx = sphinx.setup_command:BuildDoc', ], }, - python_requires=">=3.5", + python_requires=">=3.6", install_requires=install_requires, extras_require=extras_require, cmdclass=cmdclass, diff --git a/sphinx/__init__.py b/sphinx/__init__.py index 7f72a3d02a..c44e7db134 100644 --- a/sphinx/__init__.py +++ b/sphinx/__init__.py @@ -19,11 +19,6 @@ from .deprecation import RemovedInNextVersionWarning -if False: - # For type annotation - from typing import Any # NOQA - - # by default, all DeprecationWarning under sphinx package will be emit. # Users can avoid this by using environment variable: PYTHONWARNINGS= if 'PYTHONWARNINGS' not in os.environ: @@ -32,8 +27,8 @@ warnings.filterwarnings('ignore', "'U' mode is deprecated", DeprecationWarning, module='docutils.io') -__version__ = '3.5.3+' -__released__ = '3.5.3' # used when Sphinx builds its own docs +__version__ = '4.0.0+' +__released__ = '4.0.0' # used when Sphinx builds its own docs #: Version info for better programmatic use. #: @@ -43,7 +38,7 @@ #: #: .. versionadded:: 1.2 #: Before version 1.2, check the string ``sphinx.__version__``. -version_info = (3, 5, 3, 'beta', 0) +version_info = (4, 0, 0, 'beta', 0) package_dir = path.abspath(path.dirname(__file__)) @@ -57,8 +52,8 @@ try: ret = subprocess.run(['git', 'show', '-s', '--pretty=format:%h'], cwd=package_dir, - stdout=PIPE, stderr=PIPE) + stdout=PIPE, stderr=PIPE, encoding='ascii') if ret.stdout: - __display_version__ += '/' + ret.stdout.decode('ascii').strip() + __display_version__ += '/' + ret.stdout.strip() except Exception: pass diff --git a/sphinx/addnodes.py b/sphinx/addnodes.py index 5f371e46bf..9ec4898c16 100644 --- a/sphinx/addnodes.py +++ b/sphinx/addnodes.py @@ -8,16 +8,12 @@ :license: BSD, see LICENSE for details. """ -import warnings -from typing import Any, Dict, List, Sequence +from typing import TYPE_CHECKING, Any, Dict, List, Sequence from docutils import nodes -from docutils.nodes import Element, Node +from docutils.nodes import Element -from sphinx.deprecation import RemovedInSphinx40Warning - -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx @@ -342,6 +338,54 @@ class pending_xref(nodes.Inline, nodes.Element): """ +class pending_xref_condition(nodes.Inline, nodes.TextElement): + """Node for cross-references that are used to choose appropriate + content of the reference by conditions on the resolving phase. + + When the :py:class:`pending_xref` node contains one or more + **pending_xref_condition** nodes, the cross-reference resolver + should choose the content of the reference using defined conditions + in ``condition`` attribute of each pending_xref_condition nodes:: + + + + StringIO + + + io.StringIO + + After the processing of cross-reference resolver, one of the content node + under pending_xref_condition node is chosen by its condition and to be + removed all of pending_xref_condition nodes:: + + # When resolved the cross-reference successfully + + + StringIO + + # When resolution is failed + + + io.StringIO + + .. note:: This node is only allowed to be placed under pending_xref node. + It is not allows to place it under other nodes. In addition, + pending_xref node must contain only pending_xref_condition + nodes if it contains one or more pending_xref_condition nodes. + + The pending_xref_condition node should have **condition** attribute. + Domains can be store their individual conditions into the attribute to + filter contents on resolving phase. As a reserved condition name, + ``condition="*"`` is used for the fallback of resolution failure. + Additionally, as a recommended condition name, ``condition="resolved"`` + is used for the representation of resolstion success in the intersphinx + module. + + .. versionadded:: 4.0 + """ + + class number_reference(nodes.reference): """Node for number references, similar to pending_xref.""" @@ -362,20 +406,6 @@ class literal_strong(nodes.strong, not_smartquotable): """ -class abbreviation(nodes.abbreviation): - """Node for abbreviations with explanations. - - .. deprecated:: 2.0 - """ - - def __init__(self, rawsource: str = '', text: str = '', - *children: Node, **attributes: Any) -> None: - warnings.warn("abbrevition node for Sphinx was replaced by docutils'.", - RemovedInSphinx40Warning, stacklevel=2) - - super().__init__(rawsource, text, *children, **attributes) - - class manpage(nodes.Inline, nodes.FixedTextElement): """Node for references to manpages.""" diff --git a/sphinx/application.py b/sphinx/application.py index f61a6a5497..7812cecc96 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -14,11 +14,10 @@ import pickle import platform import sys -import warnings from collections import deque from io import StringIO from os import path -from typing import IO, Any, Callable, Dict, List, Optional, Tuple, Union +from typing import IO, TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union from docutils import nodes from docutils.nodes import Element, TextElement @@ -30,14 +29,13 @@ import sphinx from sphinx import locale, package_dir from sphinx.config import Config -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.domains import Domain, Index from sphinx.environment import BuildEnvironment from sphinx.environment.collectors import EnvironmentCollector from sphinx.errors import ApplicationError, ConfigError, VersionRequirementError from sphinx.events import EventManager from sphinx.extension import Extension -from sphinx.highlighting import lexer_classes, lexers +from sphinx.highlighting import lexer_classes from sphinx.locale import __ from sphinx.project import Project from sphinx.registry import SphinxComponentRegistry @@ -52,10 +50,7 @@ from sphinx.util.tags import Tags from sphinx.util.typing import RoleFunction, TitleGetter -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from docutils.nodes import Node # NOQA from sphinx.builders import Builder @@ -135,6 +130,9 @@ class Sphinx: :ivar outdir: Directory for storing build documents. """ + warningiserror: bool + _warncount: int + def __init__(self, srcdir: str, confdir: Optional[str], outdir: str, doctreedir: str, buildername: str, confoverrides: Dict = None, status: IO = sys.stdout, warning: IO = sys.stderr, @@ -946,13 +944,6 @@ def add_post_transform(self, transform: "Type[Transform]") -> None: """ self.registry.add_post_transform(transform) - def add_javascript(self, filename: str, **kwargs: Any) -> None: - """An alias of :meth:`add_js_file`.""" - warnings.warn('The app.add_javascript() is deprecated. ' - 'Please use app.add_js_file() instead.', - RemovedInSphinx40Warning, stacklevel=2) - self.add_js_file(filename, **kwargs) - def add_js_file(self, filename: str, priority: int = 500, **kwargs: Any) -> None: """Register a JavaScript file to include in the HTML output. @@ -1032,6 +1023,8 @@ def add_css_file(self, filename: str, priority: int = 500, **kwargs: Any) -> Non * - Priority - Main purpose in Sphinx + * - 200 + - default priority for built-in CSS files * - 500 - default priority for extensions * - 800 @@ -1061,24 +1054,6 @@ def add_css_file(self, filename: str, priority: int = 500, **kwargs: Any) -> Non if hasattr(self.builder, 'add_css_file'): self.builder.add_css_file(filename, priority=priority, **kwargs) # type: ignore - def add_stylesheet(self, filename: str, alternate: bool = False, title: str = None - ) -> None: - """An alias of :meth:`add_css_file`.""" - warnings.warn('The app.add_stylesheet() is deprecated. ' - 'Please use app.add_css_file() instead.', - RemovedInSphinx40Warning, stacklevel=2) - - attributes = {} # type: Dict[str, Any] - if alternate: - attributes['rel'] = 'alternate stylesheet' - else: - attributes['rel'] = 'stylesheet' - - if title: - attributes['title'] = title - - self.add_css_file(filename, **attributes) - def add_latex_package(self, packagename: str, options: str = None, after_hyperref: bool = False) -> None: r"""Register a package to include in the LaTeX source code. @@ -1102,7 +1077,7 @@ def add_latex_package(self, packagename: str, options: str = None, """ self.registry.add_latex_package(packagename, options, after_hyperref) - def add_lexer(self, alias: str, lexer: Union[Lexer, "Type[Lexer]"]) -> None: + def add_lexer(self, alias: str, lexer: Type[Lexer]) -> None: """Register a new lexer for source code. Use *lexer* to highlight code blocks with the given language *alias*. @@ -1113,13 +1088,7 @@ def add_lexer(self, alias: str, lexer: Union[Lexer, "Type[Lexer]"]) -> None: still supported until Sphinx-3.x. """ logger.debug('[app] adding lexer: %r', (alias, lexer)) - if isinstance(lexer, Lexer): - warnings.warn('app.add_lexer() API changed; ' - 'Please give lexer class instead of instance', - RemovedInSphinx40Warning, stacklevel=2) - lexers[alias] = lexer - else: - lexer_classes[alias] = lexer + lexer_classes[alias] = lexer def add_autodocumenter(self, cls: Any, override: bool = False) -> None: """Register a new documenter class for the autodoc extension. @@ -1133,7 +1102,7 @@ def add_autodocumenter(self, cls: Any, override: bool = False) -> None: If *override* is True, the given *cls* is forcedly installed even if a documenter having the same name is already installed. - .. todo:: Add real docs for Documenter and subclassing + See :ref:`autodoc_ext_tutorial`. .. versionadded:: 0.6 .. versionchanged:: 2.2 diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py index 58030bb6c8..c4ac432e42 100644 --- a/sphinx/builders/__init__.py +++ b/sphinx/builders/__init__.py @@ -11,7 +11,7 @@ import pickle import time from os import path -from typing import Any, Dict, Iterable, List, Sequence, Set, Tuple, Union +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence, Set, Tuple, Type, Union from docutils import nodes from docutils.nodes import Node @@ -40,10 +40,7 @@ except ImportError: multiprocessing = None -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from sphinx.application import Sphinx @@ -416,9 +413,9 @@ def read(self) -> List[str]: else: self._read_serial(docnames) - if self.config.master_doc not in self.env.all_docs: - raise SphinxError('master file %s not found' % - self.env.doc2path(self.config.master_doc)) + if self.config.root_doc not in self.env.all_docs: + raise SphinxError('root file %s not found' % + self.env.doc2path(self.config.root_doc)) for retval in self.events.emit('env-updated', self.env): if retval is not None: @@ -520,7 +517,7 @@ def write(self, build_docnames: Iterable[str], updated_docnames: Sequence[str], for tocdocname in self.env.files_to_rebuild.get(docname, set()): if tocdocname in self.env.found_docs: docnames.add(tocdocname) - docnames.add(self.config.master_doc) + docnames.add(self.config.root_doc) with progress_message(__('preparing documents')): self.prepare_writing(docnames) diff --git a/sphinx/builders/_epub_base.py b/sphinx/builders/_epub_base.py index 7df3f8df57..3b19bb8d06 100644 --- a/sphinx/builders/_epub_base.py +++ b/sphinx/builders/_epub_base.py @@ -11,10 +11,8 @@ import html import os import re -import warnings -from collections import namedtuple from os import path -from typing import Any, Dict, List, Set, Tuple +from typing import Any, Dict, List, NamedTuple, Set, Tuple from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile from docutils import nodes @@ -23,7 +21,6 @@ from sphinx import addnodes from sphinx.builders.html import BuildInfo, StandaloneHTMLBuilder -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.locale import __ from sphinx.util import logging, status_iterator from sphinx.util.fileutil import copy_asset_file @@ -84,10 +81,30 @@ REFURI_RE = re.compile("([^#:]*#)(.*)") -ManifestItem = namedtuple('ManifestItem', ['href', 'id', 'media_type']) -Spine = namedtuple('Spine', ['idref', 'linear']) -Guide = namedtuple('Guide', ['type', 'title', 'uri']) -NavPoint = namedtuple('NavPoint', ['navpoint', 'playorder', 'text', 'refuri', 'children']) +class ManifestItem(NamedTuple): + href: str + id: str + media_type: str + + +class Spine(NamedTuple): + idref: str + linear: bool + + +class Guide(NamedTuple): + type: str + title: str + uri: str + + +class NavPoint(NamedTuple): + navpoint: str + playorder: int + text: str + refuri: str + children: List[Any] # mypy does not support recursive types + # https://github.com/python/mypy/issues/7069 def sphinx_smarty_pants(t: str, language: str = 'en') -> str: @@ -168,18 +185,6 @@ def make_id(self, name: str) -> str: self.id_cache[name] = id return id - def esc(self, name: str) -> str: - """Replace all characters not allowed in text an attribute values.""" - warnings.warn( - '%s.esc() is deprecated. Use html.escape() instead.' % self.__class__.__name__, - RemovedInSphinx40Warning, stacklevel=2) - name = name.replace('&', '&') - name = name.replace('<', '<') - name = name.replace('>', '>') - name = name.replace('"', '"') - name = name.replace('\'', ''') - return name - def get_refnodes(self, doctree: Node, result: List[Dict[str, Any]]) -> List[Dict[str, Any]]: # NOQA """Collect section titles, their depth in the toc and the refuri.""" # XXX: is there a better way than checking the attribute @@ -217,14 +222,14 @@ def check_refnodes(self, nodes: List[Dict[str, Any]]) -> None: appeared.add(node['refuri']) def get_toc(self) -> None: - """Get the total table of contents, containing the master_doc + """Get the total table of contents, containing the root_doc and pre and post files not managed by sphinx. """ - doctree = self.env.get_and_resolve_doctree(self.config.master_doc, + doctree = self.env.get_and_resolve_doctree(self.config.root_doc, self, prune_toctrees=False, includehidden=True) self.refnodes = self.get_refnodes(doctree, []) - master_dir = path.dirname(self.config.master_doc) + master_dir = path.dirname(self.config.root_doc) if master_dir: master_dir += '/' # XXX or os.sep? for item in self.refnodes: @@ -232,13 +237,13 @@ def get_toc(self) -> None: self.toc_add_files(self.refnodes) def toc_add_files(self, refnodes: List[Dict[str, Any]]) -> None: - """Add the master_doc, pre and post files to a list of refnodes. + """Add the root_doc, pre and post files to a list of refnodes. """ refnodes.insert(0, { 'level': 1, - 'refuri': html.escape(self.config.master_doc + self.out_suffix), + 'refuri': html.escape(self.config.root_doc + self.out_suffix), 'text': ssp(html.escape( - self.env.titles[self.config.master_doc].astext())) + self.env.titles[self.config.root_doc].astext())) }) for file, text in reversed(self.config.epub_pre_files): refnodes.insert(0, { @@ -461,30 +466,17 @@ def handle_page(self, pagename: str, addctx: Dict, templatename: str = 'page.htm addctx['doctype'] = self.doctype super().handle_page(pagename, addctx, templatename, outfilename, event_arg) - def build_mimetype(self, outdir: str = None, outname: str = 'mimetype') -> None: + def build_mimetype(self) -> None: """Write the metainfo file mimetype.""" - if outdir: - warnings.warn('The arguments of EpubBuilder.build_mimetype() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - else: - outdir = self.outdir + logger.info(__('writing mimetype file...')) + copy_asset_file(path.join(self.template_dir, 'mimetype'), self.outdir) - logger.info(__('writing %s file...'), outname) - copy_asset_file(path.join(self.template_dir, 'mimetype'), - path.join(outdir, outname)) - - def build_container(self, outdir: str = None, outname: str = 'META-INF/container.xml') -> None: # NOQA + def build_container(self, outname: str = 'META-INF/container.xml') -> None: # NOQA """Write the metainfo file META-INF/container.xml.""" - if outdir: - warnings.warn('The arguments of EpubBuilder.build_container() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - else: - outdir = self.outdir - - logger.info(__('writing %s file...'), outname) - filename = path.join(outdir, outname) - ensuredir(path.dirname(filename)) - copy_asset_file(path.join(self.template_dir, 'container.xml'), filename) + logger.info(__('writing META-INF/container.xml file...')) + outdir = path.join(self.outdir, 'META-INF') + ensuredir(outdir) + copy_asset_file(path.join(self.template_dir, 'container.xml'), outdir) def content_metadata(self) -> Dict[str, Any]: """Create a dictionary with all metadata for the content.opf @@ -505,23 +497,17 @@ def content_metadata(self) -> Dict[str, Any]: metadata['guides'] = [] return metadata - def build_content(self, outdir: str = None, outname: str = 'content.opf') -> None: + def build_content(self) -> None: """Write the metainfo file content.opf It contains bibliographic data, a file list and the spine (the reading order). """ - if outdir: - warnings.warn('The arguments of EpubBuilder.build_content() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - else: - outdir = self.outdir - - logger.info(__('writing %s file...'), outname) + logger.info(__('writing content.opf file...')) metadata = self.content_metadata() # files - if not outdir.endswith(os.sep): - outdir += os.sep - olen = len(outdir) + if not self.outdir.endswith(os.sep): + self.outdir += os.sep + olen = len(self.outdir) self.files = [] # type: List[str] self.ignored_files = ['.buildinfo', 'mimetype', 'content.opf', 'toc.ncx', 'META-INF/container.xml', @@ -530,7 +516,7 @@ def build_content(self, outdir: str = None, outname: str = 'content.opf') -> Non self.config.epub_exclude_files if not self.use_index: self.ignored_files.append('genindex' + self.out_suffix) - for root, dirs, files in os.walk(outdir): + for root, dirs, files in os.walk(self.outdir): dirs.sort() for fn in sorted(files): filename = path.join(root, fn)[olen:] @@ -620,9 +606,7 @@ def build_content(self, outdir: str = None, outname: str = 'content.opf') -> Non html.escape(self.refnodes[0]['refuri']))) # write the project file - copy_asset_file(path.join(self.template_dir, 'content.opf_t'), - path.join(outdir, outname), - metadata) + copy_asset_file(path.join(self.template_dir, 'content.opf_t'), self.outdir, metadata) def new_navpoint(self, node: Dict[str, Any], level: int, incr: bool = True) -> NavPoint: """Create a new entry in the toc from the node at given level.""" @@ -640,7 +624,7 @@ def build_navpoints(self, nodes: List[Dict[str, Any]]) -> List[NavPoint]: the parent node is reinserted in the subnav. """ navstack = [] # type: List[NavPoint] - navstack.append(NavPoint('dummy', '', '', '', [])) + navstack.append(NavPoint('dummy', 0, '', '', [])) level = 0 lastnode = None for node in nodes: @@ -688,18 +672,12 @@ def toc_metadata(self, level: int, navpoints: List[NavPoint]) -> Dict[str, Any]: metadata['navpoints'] = navpoints return metadata - def build_toc(self, outdir: str = None, outname: str = 'toc.ncx') -> None: + def build_toc(self) -> None: """Write the metainfo file toc.ncx.""" - if outdir: - warnings.warn('The arguments of EpubBuilder.build_toc() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - else: - outdir = self.outdir - - logger.info(__('writing %s file...'), outname) + logger.info(__('writing toc.ncx file...')) if self.config.epub_tocscope == 'default': - doctree = self.env.get_and_resolve_doctree(self.config.master_doc, + doctree = self.env.get_and_resolve_doctree(self.config.root_doc, self, prune_toctrees=False, includehidden=False) refnodes = self.get_refnodes(doctree, []) @@ -711,28 +689,21 @@ def build_toc(self, outdir: str = None, outname: str = 'toc.ncx') -> None: navpoints = self.build_navpoints(refnodes) level = max(item['level'] for item in self.refnodes) level = min(level, self.config.epub_tocdepth) - copy_asset_file(path.join(self.template_dir, 'toc.ncx_t'), - path.join(outdir, outname), + copy_asset_file(path.join(self.template_dir, 'toc.ncx_t'), self.outdir, self.toc_metadata(level, navpoints)) - def build_epub(self, outdir: str = None, outname: str = None) -> None: + def build_epub(self) -> None: """Write the epub file. It is a zip file with the mimetype file stored uncompressed as the first entry. """ - if outdir: - warnings.warn('The arguments of EpubBuilder.build_epub() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - else: - outdir = self.outdir - outname = self.config.epub_basename + '.epub' - + outname = self.config.epub_basename + '.epub' logger.info(__('writing %s file...'), outname) - epub_filename = path.join(outdir, outname) + epub_filename = path.join(self.outdir, outname) with ZipFile(epub_filename, 'w', ZIP_DEFLATED) as epub: - epub.write(path.join(outdir, 'mimetype'), 'mimetype', ZIP_STORED) + epub.write(path.join(self.outdir, 'mimetype'), 'mimetype', ZIP_STORED) for filename in ['META-INF/container.xml', 'content.opf', 'toc.ncx']: - epub.write(path.join(outdir, filename), filename, ZIP_DEFLATED) + epub.write(path.join(self.outdir, filename), filename, ZIP_DEFLATED) for filename in self.files: - epub.write(path.join(outdir, filename), filename, ZIP_DEFLATED) + epub.write(path.join(self.outdir, filename), filename, ZIP_DEFLATED) diff --git a/sphinx/builders/applehelp.py b/sphinx/builders/applehelp.py deleted file mode 100644 index bfc8c8dc8a..0000000000 --- a/sphinx/builders/applehelp.py +++ /dev/null @@ -1,45 +0,0 @@ -""" - sphinx.builders.applehelp - ~~~~~~~~~~~~~~~~~~~~~~~~~ - - Build Apple help books. - - :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import warnings -from typing import Any, Dict - -from sphinxcontrib.applehelp import (AppleHelpBuilder, AppleHelpCodeSigningFailed, - AppleHelpIndexerFailed) - -from sphinx.application import Sphinx -from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias - -deprecated_alias('sphinx.builders.applehelp', - { - 'AppleHelpCodeSigningFailed': AppleHelpCodeSigningFailed, - 'AppleHelpIndexerFailed': AppleHelpIndexerFailed, - 'AppleHelpBuilder': AppleHelpBuilder, - }, - RemovedInSphinx40Warning, - { - 'AppleHelpCodeSigningFailed': - 'sphinxcontrib.applehelp.AppleHelpCodeSigningFailed', - 'AppleHelpIndexerFailed': - 'sphinxcontrib.applehelp.AppleHelpIndexerFailed', - 'AppleHelpBuilder': 'sphinxcontrib.applehelp.AppleHelpBuilder', - }) - - -def setup(app: Sphinx) -> Dict[str, Any]: - warnings.warn('sphinx.builders.applehelp has been moved to sphinxcontrib-applehelp.', - RemovedInSphinx40Warning, stacklevel=2) - app.setup_extension('sphinxcontrib.applehelp') - - return { - 'version': 'builtin', - 'parallel_read_safe': True, - 'parallel_write_safe': True, - } diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py deleted file mode 100644 index 9625b62f47..0000000000 --- a/sphinx/builders/devhelp.py +++ /dev/null @@ -1,40 +0,0 @@ -""" - sphinx.builders.devhelp - ~~~~~~~~~~~~~~~~~~~~~~~ - - Build HTML documentation and Devhelp_ support files. - - .. _Devhelp: https://wiki.gnome.org/Apps/Devhelp - - :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import warnings -from typing import Any, Dict - -from sphinxcontrib.devhelp import DevhelpBuilder - -from sphinx.application import Sphinx -from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias - -deprecated_alias('sphinx.builders.devhelp', - { - 'DevhelpBuilder': DevhelpBuilder, - }, - RemovedInSphinx40Warning, - { - 'DevhelpBuilder': 'sphinxcontrib.devhelp.DevhelpBuilder' - }) - - -def setup(app: Sphinx) -> Dict[str, Any]: - warnings.warn('sphinx.builders.devhelp has been moved to sphinxcontrib-devhelp.', - RemovedInSphinx40Warning) - app.setup_extension('sphinxcontrib.devhelp') - - return { - 'version': 'builtin', - 'parallel_read_safe': True, - 'parallel_write_safe': True, - } diff --git a/sphinx/builders/epub3.py b/sphinx/builders/epub3.py index d1cf64eb3e..623ee45a45 100644 --- a/sphinx/builders/epub3.py +++ b/sphinx/builders/epub3.py @@ -10,16 +10,13 @@ """ import html -import warnings -from collections import namedtuple from os import path -from typing import Any, Dict, List, Set, Tuple +from typing import Any, Dict, List, NamedTuple, Set, Tuple from sphinx import package_dir from sphinx.application import Sphinx from sphinx.builders import _epub_base from sphinx.config import ENUM, Config -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.locale import __ from sphinx.util import logging, xmlname_checker from sphinx.util.fileutil import copy_asset_file @@ -29,7 +26,12 @@ logger = logging.getLogger(__name__) -NavPoint = namedtuple('NavPoint', ['text', 'refuri', 'children']) +class NavPoint(NamedTuple): + text: str + refuri: str + children: List[Any] # mypy does not support recursive types + # https://github.com/python/mypy/issues/7069 + # writing modes PAGE_PROGRESSION_DIRECTIONS = { @@ -81,10 +83,6 @@ def handle_finish(self) -> None: self.build_toc() self.build_epub() - def validate_config_value(self) -> None: - warnings.warn('Epub3Builder.validate_config_value() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - def content_metadata(self) -> Dict: """Create a dictionary with all metadata for the content.opf file properly escaped. @@ -162,19 +160,13 @@ def navigation_doc_metadata(self, navlist: List[NavPoint]) -> Dict: metadata['navlist'] = navlist return metadata - def build_navigation_doc(self, outdir: str = None, outname: str = 'nav.xhtml') -> None: + def build_navigation_doc(self) -> None: """Write the metainfo file nav.xhtml.""" - if outdir: - warnings.warn('The arguments of Epub3Builder.build_navigation_doc() ' - 'is deprecated.', RemovedInSphinx40Warning, stacklevel=2) - else: - outdir = self.outdir - - logger.info(__('writing %s file...'), outname) + logger.info(__('writing nav.xhtml file...')) if self.config.epub_tocscope == 'default': doctree = self.env.get_and_resolve_doctree( - self.config.master_doc, self, + self.config.root_doc, self, prune_toctrees=False, includehidden=False) refnodes = self.get_refnodes(doctree, []) self.toc_add_files(refnodes) @@ -182,13 +174,12 @@ def build_navigation_doc(self, outdir: str = None, outname: str = 'nav.xhtml') - # 'includehidden' refnodes = self.refnodes navlist = self.build_navlist(refnodes) - copy_asset_file(path.join(self.template_dir, 'nav.xhtml_t'), - path.join(outdir, outname), + copy_asset_file(path.join(self.template_dir, 'nav.xhtml_t'), self.outdir, self.navigation_doc_metadata(navlist)) # Add nav.xhtml to epub file - if outname not in self.files: - self.files.append(outname) + if 'nav.xhtml' not in self.files: + self.files.append('nav.xhtml') def validate_config_values(app: Sphinx) -> None: diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py index 75c95c0bc6..78ae06b74d 100644 --- a/sphinx/builders/gettext.py +++ b/sphinx/builders/gettext.py @@ -13,7 +13,7 @@ from datetime import datetime, timedelta, tzinfo from os import getenv, path, walk from time import time -from typing import Any, Dict, Generator, Iterable, List, Set, Tuple, Union +from typing import Any, DefaultDict, Dict, Generator, Iterable, List, Set, Tuple, Union from uuid import uuid4 from docutils import nodes @@ -33,33 +33,8 @@ from sphinx.util.tags import Tags from sphinx.util.template import SphinxRenderer -if False: - # For type annotation - from typing import DefaultDict # for python3.5.1 - logger = logging.getLogger(__name__) -POHEADER = r""" -# SOME DESCRIPTIVE TITLE. -# Copyright (C) %(copyright)s -# This file is distributed under the same license as the %(project)s package. -# FIRST AUTHOR , YEAR. -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: %(project)s %(version)s\n" -"Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: %(ctime)s\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: FULL NAME \n" -"Language-Team: LANGUAGE \n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" - -"""[1:] # RemovedInSphinx40Warning - class Message: """An entry of translatable message.""" diff --git a/sphinx/builders/html/__init__.py b/sphinx/builders/html/__init__.py index c799b01767..115f735381 100644 --- a/sphinx/builders/html/__init__.py +++ b/sphinx/builders/html/__init__.py @@ -13,9 +13,9 @@ import posixpath import re import sys -import warnings +from datetime import datetime from os import path -from typing import IO, Any, Dict, Iterable, Iterator, List, Set, Tuple +from typing import IO, Any, Dict, Iterable, Iterator, List, Set, Tuple, Type from urllib.parse import quote from docutils import nodes @@ -29,7 +29,6 @@ from sphinx.application import Sphinx from sphinx.builders import Builder from sphinx.config import ENUM, Config -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.domains import Domain, Index, IndexEntry from sphinx.environment.adapters.asset import ImageAdapter from sphinx.environment.adapters.indexentries import IndexEntries @@ -39,7 +38,7 @@ from sphinx.locale import _, __ from sphinx.search import js_index from sphinx.theming import HTMLThemeFactory -from sphinx.util import logging, md5, progress_message, status_iterator +from sphinx.util import isurl, logging, md5, progress_message, status_iterator from sphinx.util.docutils import is_html5_writer_available, new_document from sphinx.util.fileutil import copy_asset from sphinx.util.i18n import format_date @@ -49,11 +48,6 @@ from sphinx.util.tags import Tags from sphinx.writers.html import HTMLTranslator, HTMLWriter -if False: - # For type annotation - from typing import Type # for python3.5.1 - - # HTML5 Writer is available or not if is_html5_writer_available(): from sphinx.writers.html5 import HTML5Translator @@ -256,6 +250,14 @@ def _get_translations_js(self) -> str: return jsfile return None + def _get_style_filename(self) -> str: + if self.config.html_style is not None: + return self.config.html_style + elif self.theme: + return self.theme.get_config('theme', 'stylesheet') + else: + return 'default.css' + def get_theme_config(self) -> Tuple[str, Dict]: return self.config.html_theme, self.config.html_theme_options @@ -291,6 +293,9 @@ def init_highlighter(self) -> None: self.dark_highlighter = None def init_css_files(self) -> None: + self.add_css_file('pygments.css', priority=200) + self.add_css_file(self._get_style_filename(), priority=200) + for filename, attrs in self.app.registry.css_files: self.add_css_file(filename, **attrs) @@ -305,6 +310,8 @@ def add_css_file(self, filename: str, **kwargs: Any) -> None: self.css_files.append(Stylesheet(filename, **kwargs)) # type: ignore def init_js_files(self) -> None: + self.add_js_file('documentation_options.js', id="documentation_options", + data_url_root='', priority=200) self.add_js_file('jquery.js', priority=200) self.add_js_file('underscore.js', priority=200) self.add_js_file('doctools.js', priority=200) @@ -358,6 +365,7 @@ def get_outdated_docs(self) -> Iterator[str]: buildinfo = BuildInfo.load(fp) if self.build_info != buildinfo: + logger.debug('[build target] did not match: build_info ') yield from self.env.found_docs return except ValueError as exc: @@ -372,6 +380,7 @@ def get_outdated_docs(self) -> Iterator[str]: template_mtime = 0 for docname in self.env.found_docs: if docname not in self.env.all_docs: + logger.debug('[build target] did not in env: %r', docname) yield docname continue targetname = self.get_outfilename(docname) @@ -383,6 +392,14 @@ def get_outdated_docs(self) -> Iterator[str]: srcmtime = max(path.getmtime(self.env.doc2path(docname)), template_mtime) if srcmtime > targetmtime: + logger.debug( + '[build target] targetname %r(%s), template(%s), docname %r(%s)', + targetname, + datetime.utcfromtimestamp(targetmtime), + datetime.utcfromtimestamp(template_mtime), + docname, + datetime.utcfromtimestamp(path.getmtime(self.env.doc2path(docname))), + ) yield docname except OSError: # source doesn't exist anymore @@ -470,13 +487,6 @@ def prepare_writing(self, docnames: Set[str]) -> None: self._script_files = list(self.script_files) self._css_files = list(self.css_files) - if self.config.html_style is not None: - stylename = self.config.html_style - elif self.theme: - stylename = self.theme.get_config('theme', 'stylesheet') - else: - stylename = 'default.css' - self.globalcontext = { 'embedded': self.embedded, 'project': self.config.project, @@ -484,7 +494,8 @@ def prepare_writing(self, docnames: Set[str]) -> None: 'version': self.config.version, 'last_updated': self.last_updated, 'copyright': self.config.copyright, - 'master_doc': self.config.master_doc, + 'master_doc': self.config.root_doc, + 'root_doc': self.config.root_doc, 'use_opensearch': self.config.html_use_opensearch, 'docstitle': self.config.html_title, 'shorttitle': self.config.html_short_title, @@ -499,7 +510,7 @@ def prepare_writing(self, docnames: Set[str]) -> None: 'language': self.config.language, 'css_files': self.css_files, 'sphinx_version': __display_version__, - 'style': stylename, + 'style': self._get_style_filename(), 'rellinks': rellinks, 'builder': self.name, 'parents': [], @@ -786,12 +797,12 @@ def onerror(filename: str, error: Exception) -> None: excluded, context=context, renderer=self.templates, onerror=onerror) def copy_html_logo(self) -> None: - if self.config.html_logo: + if self.config.html_logo and not isurl(self.config.html_logo): copy_asset(path.join(self.confdir, self.config.html_logo), path.join(self.outdir, '_static')) def copy_html_favicon(self) -> None: - if self.config.html_favicon: + if self.config.html_favicon and not isurl(self.config.html_favicon): copy_asset(path.join(self.confdir, self.config.html_favicon), path.join(self.outdir, '_static')) @@ -889,21 +900,11 @@ def index_page(self, pagename: str, doctree: nodes.document, title: str) -> None # only index pages with title if self.indexer is not None and title: filename = self.env.doc2path(pagename, base=None) - try: - metadata = self.env.metadata.get(pagename, {}) - if 'nosearch' in metadata: - self.indexer.feed(pagename, filename, '', new_document('')) - else: - self.indexer.feed(pagename, filename, title, doctree) - except TypeError: - # fallback for old search-adapters - self.indexer.feed(pagename, title, doctree) # type: ignore - indexer_name = self.indexer.__class__.__name__ - warnings.warn( - 'The %s.feed() method signature is deprecated. Update to ' - '%s.feed(docname, filename, title, doctree).' % ( - indexer_name, indexer_name), - RemovedInSphinx40Warning, stacklevel=2) + metadata = self.env.metadata.get(pagename, {}) + if 'nosearch' in metadata: + self.indexer.feed(pagename, filename, '', new_document('')) + else: + self.indexer.feed(pagename, filename, title, doctree) def _get_local_toctree(self, docname: str, collapse: bool = True, **kwargs: Any) -> str: if 'includehidden' not in kwargs: @@ -1157,6 +1158,8 @@ def js_tag(js: JavaScript) -> str: if value is not None: if key == 'body': body = value + elif key == 'data_url_root': + attrs.append('data-url_root="%s"' % pathto('', resource=True)) else: attrs.append('%s="%s"' % (key, html.escape(value, True))) if js.filename: @@ -1169,6 +1172,26 @@ def js_tag(js: JavaScript) -> str: context['js_tag'] = js_tag +def setup_resource_paths(app: Sphinx, pagename: str, templatename: str, + context: Dict, doctree: Node) -> None: + """Set up relative resource paths.""" + pathto = context.get('pathto') + + # favicon_url + favicon = context.get('favicon') + if favicon and not isurl(favicon): + context['favicon_url'] = pathto('_static/' + favicon, resource=True) + else: + context['favicon_url'] = favicon + + # logo_url + logo = context.get('logo') + if logo and not isurl(logo): + context['logo_url'] = pathto('_static/' + logo, resource=True) + else: + context['logo_url'] = logo + + def validate_math_renderer(app: Sphinx) -> None: if app.builder.format != 'html': return @@ -1209,27 +1232,47 @@ def validate_html_static_path(app: Sphinx, config: Config) -> None: def validate_html_logo(app: Sphinx, config: Config) -> None: """Check html_logo setting.""" - if config.html_logo and not path.isfile(path.join(app.confdir, config.html_logo)): + if (config.html_logo and + not path.isfile(path.join(app.confdir, config.html_logo)) and + not isurl(config.html_logo)): logger.warning(__('logo file %r does not exist'), config.html_logo) config.html_logo = None # type: ignore def validate_html_favicon(app: Sphinx, config: Config) -> None: """Check html_favicon setting.""" - if config.html_favicon and not path.isfile(path.join(app.confdir, config.html_favicon)): + if (config.html_favicon and + not path.isfile(path.join(app.confdir, config.html_favicon)) and + not isurl(config.html_favicon)): logger.warning(__('favicon file %r does not exist'), config.html_favicon) config.html_favicon = None # type: ignore +class _stable_repr_object(): + + def __repr__(self): + return '' + + +UNSET = _stable_repr_object() + + def migrate_html_add_permalinks(app: Sphinx, config: Config) -> None: """Migrate html_add_permalinks to html_permalinks*.""" - if config.html_add_permalinks: - if (isinstance(config.html_add_permalinks, bool) and - config.html_add_permalinks is False): - config.html_permalinks = False # type: ignore - else: - config.html_permalinks_icon = html.escape(config.html_add_permalinks) # type: ignore # NOQA + html_add_permalinks = config.html_add_permalinks + if html_add_permalinks is UNSET: + return + + # RemovedInSphinx60Warning + logger.warning(__('html_add_permalinks has been deprecated since v3.5.0. ' + 'Please use html_permalinks and html_permalinks_icon instead.')) + if not html_add_permalinks: + config.html_permalinks = False # type: ignore[attr-defined] + return + config.html_permalinks_icon = html.escape( # type: ignore[attr-defined] + html_add_permalinks + ) # for compatibility import sphinxcontrib.serializinghtml # NOQA @@ -1261,7 +1304,7 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.add_config_value('html_sidebars', {}, 'html') app.add_config_value('html_additional_pages', {}, 'html') app.add_config_value('html_domain_indices', True, 'html', [list]) - app.add_config_value('html_add_permalinks', None, 'html') + app.add_config_value('html_add_permalinks', UNSET, 'html') app.add_config_value('html_permalinks', True, 'html') app.add_config_value('html_permalinks_icon', '¶', 'html') app.add_config_value('html_use_index', True, 'html') @@ -1283,7 +1326,7 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.add_config_value('html_search_scorer', '', None) app.add_config_value('html_scaled_image_link', True, 'html') app.add_config_value('html_baseurl', '', 'html') - app.add_config_value('html_codeblock_linenos_style', 'table', 'html', + app.add_config_value('html_codeblock_linenos_style', 'inline', 'html', # RemovedInSphinx60Warning # NOQA ENUM('table', 'inline')) app.add_config_value('html_math_renderer', None, 'env') app.add_config_value('html4_writer', False, 'html') @@ -1302,6 +1345,7 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.connect('config-inited', validate_html_favicon, priority=800) app.connect('builder-inited', validate_math_renderer) app.connect('html-page-context', setup_js_tag_helper) + app.connect('html-page-context', setup_resource_paths) # load default math renderer app.setup_extension('sphinx.ext.mathjax') diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py deleted file mode 100644 index 08719712ce..0000000000 --- a/sphinx/builders/htmlhelp.py +++ /dev/null @@ -1,47 +0,0 @@ -""" - sphinx.builders.htmlhelp - ~~~~~~~~~~~~~~~~~~~~~~~~ - - Build HTML help support files. - Parts adapted from Python's Doc/tools/prechm.py. - - :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import warnings -from typing import Any, Dict - -from sphinxcontrib.htmlhelp import (HTMLHelpBuilder, chm_htmlescape, chm_locales, - default_htmlhelp_basename) - -from sphinx.application import Sphinx -from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias - -deprecated_alias('sphinx.builders.htmlhelp', - { - 'chm_locales': chm_locales, - 'chm_htmlescape': chm_htmlescape, - 'HTMLHelpBuilder': HTMLHelpBuilder, - 'default_htmlhelp_basename': default_htmlhelp_basename, - }, - RemovedInSphinx40Warning, - { - 'chm_locales': 'sphinxcontrib.htmlhelp.chm_locales', - 'chm_htmlescape': 'sphinxcontrib.htmlhelp.chm_htmlescape', - 'HTMLHelpBuilder': 'sphinxcontrib.htmlhelp.HTMLHelpBuilder', - 'default_htmlhelp_basename': - 'sphinxcontrib.htmlhelp.default_htmlhelp_basename', - }) - - -def setup(app: Sphinx) -> Dict[str, Any]: - warnings.warn('sphinx.builders.htmlhelp has been moved to sphinxcontrib-htmlhelp.', - RemovedInSphinx40Warning, stacklevel=2) - app.setup_extension('sphinxcontrib.htmlhelp') - - return { - 'version': 'builtin', - 'parallel_read_safe': True, - 'parallel_write_safe': True, - } diff --git a/sphinx/builders/latex/__init__.py b/sphinx/builders/latex/__init__.py index 5c7a7412ac..681d3cfe6f 100644 --- a/sphinx/builders/latex/__init__.py +++ b/sphinx/builders/latex/__init__.py @@ -24,7 +24,7 @@ from sphinx.builders.latex.theming import Theme, ThemeFactory from sphinx.builders.latex.util import ExtBabel from sphinx.config import ENUM, Config -from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.environment.adapters.asset import ImageAdapter from sphinx.errors import NoUri, SphinxError from sphinx.locale import _, __ @@ -216,14 +216,18 @@ def init_multilingual(self) -> None: if not self.babel.uses_cyrillic(): if 'X2' in self.context['fontenc']: self.context['substitutefont'] = '\\usepackage{substitutefont}' - self.context['textcyrillic'] = '\\usepackage[Xtwo]{sphinxcyrillic}' + self.context['textcyrillic'] = ('\\usepackage[Xtwo]' + '{sphinxpackagecyrillic}') elif 'T2A' in self.context['fontenc']: self.context['substitutefont'] = '\\usepackage{substitutefont}' - self.context['textcyrillic'] = '\\usepackage[TtwoA]{sphinxcyrillic}' + self.context['textcyrillic'] = ('\\usepackage[TtwoA]' + '{sphinxpackagecyrillic}') if 'LGR' in self.context['fontenc']: self.context['substitutefont'] = '\\usepackage{substitutefont}' else: self.context['textgreek'] = '' + if self.context['substitutefont'] == '': + self.context['fontsubstitution'] = '' # 'babel' key is public and user setting must be obeyed if self.context['babel']: @@ -261,7 +265,6 @@ def write(self, *ignored: Any) -> None: defaults=self.env.settings, components=(docwriter,), read_config_files=True).get_default_values() # type: Any - patch_settings(docsettings) self.init_document_data() self.write_stylesheet() @@ -364,10 +367,6 @@ def assemble_doctree(self, indexfile: str, toctree_only: bool, appendices: List[ pendingnode.replace_self(newnodes) return largetree - def apply_transforms(self, doctree: nodes.document) -> None: - warnings.warn('LaTeXBuilder.apply_transforms() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - def finish(self) -> None: self.copy_image_files() self.write_message_catalog() @@ -462,44 +461,6 @@ def usepackages_after_hyperref(self) -> List[Tuple[str, str]]: return self.app.registry.latex_packages_after_hyperref -def patch_settings(settings: Any) -> Any: - """Make settings object to show deprecation messages.""" - - class Values(type(settings)): # type: ignore - @property - def author(self) -> str: - warnings.warn('settings.author is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - return self._author - - @property - def title(self) -> str: - warnings.warn('settings.title is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - return self._title - - @property - def contentsname(self) -> str: - warnings.warn('settings.contentsname is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - return self._contentsname - - @property - def docname(self) -> str: - warnings.warn('settings.docname is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - return self._docname - - @property - def docclass(self) -> str: - warnings.warn('settings.docclass is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - return self._docclass - - # dynamic subclassing - settings.__class__ = Values - - def validate_config_values(app: Sphinx, config: Config) -> None: for key in list(config.latex_elements): if key not in DEFAULT_SETTINGS: @@ -525,7 +486,7 @@ def install_packages_for_ja(app: Sphinx) -> None: def default_latex_engine(config: Config) -> str: """ Better default latex_engine settings for specific languages. """ if config.language == 'ja': - return 'platex' + return 'uplatex' elif (config.language or '').startswith('zh'): return 'xelatex' elif config.language == 'el': @@ -556,7 +517,7 @@ def default_latex_documents(config: Config) -> List[Tuple[str, str, str, str, st """ Better default latex_documents settings. """ project = texescape.escape(config.project, config.latex_engine) author = texescape.escape(config.author, config.latex_engine) - return [(config.master_doc, + return [(config.root_doc, make_filename_from_project(config.project) + '.tex', texescape.escape_abbr(project), texescape.escape_abbr(author), diff --git a/sphinx/builders/latex/constants.py b/sphinx/builders/latex/constants.py index 0b20c7cef7..e929736a75 100644 --- a/sphinx/builders/latex/constants.py +++ b/sphinx/builders/latex/constants.py @@ -11,7 +11,12 @@ from typing import Any, Dict PDFLATEX_DEFAULT_FONTPKG = r''' -\usepackage{times} +\usepackage{tgtermes} +\usepackage{tgheros} +\renewcommand{\ttdefault}{txtt} +''' + +PDFLATEX_DEFAULT_FONTSUBSTITUTION = r''' \expandafter\ifx\csname T@LGR\endcsname\relax \else % LGR was declared as font encoding @@ -76,7 +81,7 @@ 'maxlistdepth': '', 'sphinxpkgoptions': '', 'sphinxsetup': '', - 'fvset': '\\fvset{fontsize=\\small}', + 'fvset': '\\fvset{fontsize=auto}', 'passoptionstopackages': '', 'geometry': '\\usepackage{geometry}', 'inputenc': '', @@ -88,6 +93,7 @@ 'babel': '\\usepackage{babel}', 'polyglossia': '', 'fontpkg': PDFLATEX_DEFAULT_FONTPKG, + 'fontsubstitution': PDFLATEX_DEFAULT_FONTSUBSTITUTION, 'substitutefont': '', 'textcyrillic': '', 'textgreek': '\\usepackage{textalpha}', @@ -142,6 +148,8 @@ 'fontenc': ('\\usepackage{fontspec}\n' '\\defaultfontfeatures[\\rmfamily,\\sffamily,\\ttfamily]{}'), 'fontpkg': XELATEX_DEFAULT_FONTPKG, + 'fvset': '\\fvset{fontsize=\\small}', + 'fontsubstitution': '', 'textgreek': '', 'utf8extra': ('\\catcode`^^^^00a0\\active\\protected\\def^^^^00a0' '{\\leavevmode\\nobreak\\ }'), @@ -153,6 +161,8 @@ 'fontenc': ('\\usepackage{fontspec}\n' '\\defaultfontfeatures[\\rmfamily,\\sffamily,\\ttfamily]{}'), 'fontpkg': LUALATEX_DEFAULT_FONTPKG, + 'fvset': '\\fvset{fontsize=\\small}', + 'fontsubstitution': '', 'textgreek': '', 'utf8extra': ('\\catcode`^^^^00a0\\active\\protected\\def^^^^00a0' '{\\leavevmode\\nobreak\\ }'), @@ -161,7 +171,8 @@ 'latex_engine': 'platex', 'babel': '', 'classoptions': ',dvipdfmx', - 'fontpkg': '\\usepackage{times}', + 'fontpkg': PDFLATEX_DEFAULT_FONTPKG, + 'fontsubstitution': '', 'textgreek': '', 'fncychap': '', 'geometry': '\\usepackage[dvipdfm]{geometry}', @@ -170,7 +181,8 @@ 'latex_engine': 'uplatex', 'babel': '', 'classoptions': ',dvipdfmx', - 'fontpkg': '\\usepackage{times}', + 'fontpkg': PDFLATEX_DEFAULT_FONTPKG, + 'fontsubstitution': '', 'textgreek': '', 'fncychap': '', 'geometry': '\\usepackage[dvipdfm]{geometry}', diff --git a/sphinx/builders/manpage.py b/sphinx/builders/manpage.py index 292f495de6..f994309e1a 100644 --- a/sphinx/builders/manpage.py +++ b/sphinx/builders/manpage.py @@ -109,7 +109,7 @@ def finish(self) -> None: def default_man_pages(config: Config) -> List[Tuple[str, str, str, List[str], int]]: """ Better default man_pages settings. """ filename = make_filename_from_project(config.project) - return [(config.master_doc, filename, '%s %s' % (config.project, config.release), + return [(config.root_doc, filename, '%s %s' % (config.project, config.release), [config.author], 1)] @@ -118,7 +118,7 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.add_config_value('man_pages', default_man_pages, None) app.add_config_value('man_show_urls', False, None) - app.add_config_value('man_make_section_directory', False, None) + app.add_config_value('man_make_section_directory', True, None) return { 'version': 'builtin', diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py deleted file mode 100644 index c5219dd759..0000000000 --- a/sphinx/builders/qthelp.py +++ /dev/null @@ -1,42 +0,0 @@ -""" - sphinx.builders.qthelp - ~~~~~~~~~~~~~~~~~~~~~~ - - Build input files for the Qt collection generator. - - :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import warnings -from typing import Any, Dict - -from sphinxcontrib.qthelp import QtHelpBuilder, render_file - -import sphinx -from sphinx.application import Sphinx -from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias - -deprecated_alias('sphinx.builders.qthelp', - { - 'render_file': render_file, - 'QtHelpBuilder': QtHelpBuilder, - }, - RemovedInSphinx40Warning, - { - 'render_file': 'sphinxcontrib.qthelp.render_file', - 'QtHelpBuilder': 'sphinxcontrib.qthelp.QtHelpBuilder', - }) - - -def setup(app: Sphinx) -> Dict[str, Any]: - warnings.warn('sphinx.builders.qthelp has been moved to sphinxcontrib-qthelp.', - RemovedInSphinx40Warning) - - app.setup_extension('sphinxcontrib.qthelp') - - return { - 'version': sphinx.__display_version__, - 'parallel_read_safe': True, - 'parallel_write_safe': True, - } diff --git a/sphinx/builders/singlehtml.py b/sphinx/builders/singlehtml.py index 2e72887e37..1ef618dd0a 100644 --- a/sphinx/builders/singlehtml.py +++ b/sphinx/builders/singlehtml.py @@ -42,7 +42,7 @@ def get_outdated_docs(self) -> Union[str, List[str]]: # type: ignore def get_target_uri(self, docname: str, typ: str = None) -> str: if docname in self.env.all_docs: # all references are on the same page... - return self.config.master_doc + self.out_suffix + \ + return self.config.root_doc + self.out_suffix + \ '#document-' + docname else: # chances are this is a html_additional_page @@ -54,7 +54,7 @@ def get_relative_uri(self, from_: str, to: str, typ: str = None) -> str: def fix_refuris(self, tree: Node) -> None: # fix refuris with double anchor - fname = self.config.master_doc + self.out_suffix + fname = self.config.root_doc + self.out_suffix for refnode in tree.traverse(nodes.reference): if 'refuri' not in refnode: continue @@ -75,7 +75,7 @@ def _get_local_toctree(self, docname: str, collapse: bool = True, **kwargs: Any) return self.render_partial(toctree)['fragment'] def assemble_doctree(self) -> nodes.document: - master = self.config.master_doc + master = self.config.root_doc tree = self.env.get_doctree(master) tree = inline_all_toctrees(self, set(), master, tree, darkgreen, [master]) tree['docname'] = master @@ -99,7 +99,7 @@ def assemble_toc_secnumbers(self) -> Dict[str, Dict[str, Tuple[int, ...]]]: alias = "%s/%s" % (docname, id) new_secnumbers[alias] = secnum - return {self.config.master_doc: new_secnumbers} + return {self.config.root_doc: new_secnumbers} def assemble_toc_fignumbers(self) -> Dict[str, Dict[str, Dict[str, Tuple[int, ...]]]]: # Assemble toc_fignumbers to resolve figure numbers on SingleHTML. @@ -120,11 +120,11 @@ def assemble_toc_fignumbers(self) -> Dict[str, Dict[str, Dict[str, Tuple[int, .. for id, fignum in fignums.items(): new_fignumbers[alias][id] = fignum - return {self.config.master_doc: new_fignumbers} + return {self.config.root_doc: new_fignumbers} def get_doc_context(self, docname: str, body: str, metatags: str) -> Dict: # no relation links... - toctree = TocTree(self.env).get_toctree_for(self.config.master_doc, self, False) + toctree = TocTree(self.env).get_toctree_for(self.config.root_doc, self, False) # if there is no toctree, toc is None if toctree: self.fix_refuris(toctree) @@ -160,8 +160,8 @@ def write(self, *ignored: Any) -> None: self.env.toc_fignumbers = self.assemble_toc_fignumbers() with progress_message(__('writing')): - self.write_doc_serialized(self.config.master_doc, doctree) - self.write_doc(self.config.master_doc, doctree) + self.write_doc_serialized(self.config.root_doc, doctree) + self.write_doc(self.config.root_doc, doctree) def finish(self) -> None: self.write_additional_files() diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py index 1a56be0f90..bb2039e61e 100644 --- a/sphinx/builders/texinfo.py +++ b/sphinx/builders/texinfo.py @@ -197,7 +197,7 @@ def copy_support_files(self) -> None: def default_texinfo_documents(config: Config) -> List[Tuple[str, str, str, str, str, str, str]]: # NOQA """ Better default texinfo_documents settings. """ filename = make_filename_from_project(config.project) - return [(config.master_doc, filename, config.project, config.author, filename, + return [(config.root_doc, filename, config.project, config.author, filename, 'One line description of project', 'Miscellaneous')] diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py index 1b051119b5..88dfe83a91 100644 --- a/sphinx/builders/xml.py +++ b/sphinx/builders/xml.py @@ -9,7 +9,7 @@ """ from os import path -from typing import Any, Dict, Iterator, Set, Union +from typing import Any, Dict, Iterator, Set, Type, Union from docutils import nodes from docutils.io import StringOutput @@ -23,11 +23,6 @@ from sphinx.util.osutil import ensuredir, os_path from sphinx.writers.xml import PseudoXMLWriter, XMLWriter -if False: - # For type annotation - from typing import Type # for python3.5.1 - - logger = logging.getLogger(__name__) diff --git a/sphinx/cmd/make_mode.py b/sphinx/cmd/make_mode.py index aaa40fba0f..242329ae0a 100644 --- a/sphinx/cmd/make_mode.py +++ b/sphinx/cmd/make_mode.py @@ -50,6 +50,7 @@ ("", "doctest", "to run all doctests embedded in the documentation " "(if enabled)"), ("", "coverage", "to run coverage check of the documentation (if enabled)"), + ("", "clean", "to remove everything in the build directory"), ] diff --git a/sphinx/cmd/quickstart.py b/sphinx/cmd/quickstart.py index 4234c039cc..a40a210731 100644 --- a/sphinx/cmd/quickstart.py +++ b/sphinx/cmd/quickstart.py @@ -11,13 +11,11 @@ import argparse import locale import os -import re import sys import time -import warnings from collections import OrderedDict from os import path -from typing import Any, Callable, Dict, List, Pattern, Union +from typing import Any, Callable, Dict, List, Union # try to import readline, unix specific enhancement try: @@ -36,15 +34,11 @@ import sphinx.locale from sphinx import __display_version__, package_dir -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.locale import __ -from sphinx.util.console import (bold, color_terminal, colorize, nocolor, red, # type: ignore - turquoise) +from sphinx.util.console import bold, color_terminal, colorize, nocolor, red # type: ignore from sphinx.util.osutil import ensuredir from sphinx.util.template import SphinxRenderer -TERM_ENCODING = getattr(sys.stdin, 'encoding', None) # RemovedInSphinx40Warning - EXTENSIONS = OrderedDict([ ('autodoc', __('automatically insert docstrings from modules')), ('doctest', __('automatically test code snippets in doctest blocks')), @@ -135,30 +129,6 @@ def ok(x: str) -> str: return x -def term_decode(text: Union[bytes, str]) -> str: - warnings.warn('term_decode() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - if isinstance(text, str): - return text - - # Use the known encoding, if possible - if TERM_ENCODING: - return text.decode(TERM_ENCODING) - - # If ascii is safe, use it with no warning - if text.decode('ascii', 'replace').encode('ascii', 'replace') == text: - return text.decode('ascii') - - print(turquoise(__('* Note: non-ASCII characters entered ' - 'and terminal encoding unknown -- assuming ' - 'UTF-8 or Latin-1.'))) - try: - return text.decode() - except UnicodeDecodeError: - return text.decode('latin1') - - def do_prompt(text: str, default: str = None, validator: Callable[[str], Any] = nonempty) -> Union[str, bool]: # NOQA while True: if default is not None: @@ -187,22 +157,27 @@ def do_prompt(text: str, default: str = None, validator: Callable[[str], Any] = return x -def convert_python_source(source: str, rex: Pattern = re.compile(r"[uU]('.*?')")) -> str: - # remove Unicode literal prefixes - warnings.warn('convert_python_source() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - return rex.sub('\\1', source) - - class QuickstartRenderer(SphinxRenderer): def __init__(self, templatedir: str) -> None: self.templatedir = templatedir or '' super().__init__() + def _has_custom_template(self, template_name: str) -> bool: + """Check if custom template file exists. + + Note: Please don't use this function from extensions. + It will be removed in the future without deprecation period. + """ + template = path.join(self.templatedir, path.basename(template_name)) + if self.templatedir and path.exists(template): + return True + else: + return False + def render(self, template_name: str, context: Dict) -> str: - user_template = path.join(self.templatedir, path.basename(template_name)) - if self.templatedir and path.exists(user_template): - return self.render_from_file(user_template, context) + if self._has_custom_template(template_name): + custom_template = path.join(self.templatedir, path.basename(template_name)) + return self.render_from_file(custom_template, context) else: return super().render(template_name, context) @@ -355,6 +330,7 @@ def generate(d: Dict, overwrite: bool = True, silent: bool = False, templatedir: if 'mastertocmaxdepth' not in d: d['mastertocmaxdepth'] = 2 + d['root_doc'] = d['master'] d['now'] = time.asctime() d['project_underline'] = column_width(d['project']) * '=' d.setdefault('extensions', []) @@ -399,7 +375,13 @@ def write_file(fpath: str, content: str, newline: str = None) -> None: write_file(path.join(srcdir, 'conf.py'), template.render_string(conf_text, d)) masterfile = path.join(srcdir, d['master'] + d['suffix']) - write_file(masterfile, template.render('quickstart/master_doc.rst_t', d)) + if template._has_custom_template('quickstart/master_doc.rst_t'): + msg = ('A custom template `master_doc.rst_t` found. It has been renamed to ' + '`root_doc.rst_t`. Please rename it on your project too.') + print(colorize('red', msg)) # RemovedInSphinx60Warning + write_file(masterfile, template.render('quickstart/master_doc.rst_t', d)) + else: + write_file(masterfile, template.render('quickstart/root_doc.rst_t', d)) if d.get('make_mode') is True: makefile_template = 'quickstart/Makefile.new_t' diff --git a/sphinx/config.py b/sphinx/config.py index 4c038b0612..d7f9c4f8a2 100644 --- a/sphinx/config.py +++ b/sphinx/config.py @@ -11,24 +11,20 @@ import re import traceback import types -import warnings from collections import OrderedDict from os import getenv, path -from typing import (Any, Callable, Dict, Generator, Iterator, List, NamedTuple, Set, Tuple, - Union) +from typing import (TYPE_CHECKING, Any, Callable, Dict, Generator, Iterator, List, NamedTuple, + Set, Tuple, Union) -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.errors import ConfigError, ExtensionError from sphinx.locale import _, __ from sphinx.util import logging from sphinx.util.i18n import format_date -from sphinx.util.osutil import cd -from sphinx.util.pycompat import execfile_ +from sphinx.util.osutil import cd, fs_encoding from sphinx.util.tags import Tags from sphinx.util.typing import NoneType -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.environment import BuildEnvironment @@ -38,9 +34,11 @@ UNSERIALIZABLE_TYPES = (type, types.ModuleType, types.FunctionType) copyright_year_re = re.compile(r'^((\d{4}-)?)(\d{4})(?=[ ,])') -ConfigValue = NamedTuple('ConfigValue', [('name', str), - ('value', Any), - ('rebuild', Union[bool, str])]) + +class ConfigValue(NamedTuple): + name: str + value: Any + rebuild: Union[bool, str] def is_serializable(obj: Any) -> bool: @@ -73,10 +71,6 @@ def match(self, value: Union[str, List, Tuple]) -> bool: return value in self.candidates -# RemovedInSphinx40Warning -string_classes = [str] # type: List - - class Config: """Configuration file abstraction. @@ -111,9 +105,9 @@ class Config: 'figure_language_filename': ('{root}.{language}{ext}', 'env', [str]), 'master_doc': ('index', 'env', []), + 'root_doc': (lambda config: config.master_doc, 'env', []), 'source_suffix': ({'.rst': 'restructuredtext'}, 'env', Any), 'source_encoding': ('utf-8-sig', 'env', []), - 'source_parsers': ({}, 'env', []), 'exclude_patterns': ([], 'env', []), 'default_role': (None, 'env', [str]), 'add_function_parentheses': (True, 'env', []), @@ -324,7 +318,9 @@ def eval_config_file(filename: str, tags: Tags) -> Dict[str, Any]: with cd(path.dirname(filename)): # during executing config file, current dir is changed to ``confdir``. try: - execfile_(filename, namespace) + with open(filename, 'rb') as f: + code = compile(f.read(), filename.encode(fs_encoding), 'exec') + exec(code, namespace) except SyntaxError as err: msg = __("There is a syntax error in your configuration file: %s\n") raise ConfigError(msg % err) from err @@ -459,22 +455,6 @@ def check_confval_types(app: "Sphinx", config: Config) -> None: default=type(default))) -def check_unicode(config: Config) -> None: - """check all string values for non-ASCII characters in bytestrings, - since that can result in UnicodeErrors all over the place - """ - warnings.warn('sphinx.config.check_unicode() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - nonascii_re = re.compile(br'[\x80-\xff]') - - for name, value in config._raw_config.items(): - if isinstance(value, bytes) and nonascii_re.search(value): - logger.warning(__('the config value %r is set to a string with non-ASCII ' - 'characters; this can lead to Unicode errors occurring. ' - 'Please use Unicode strings, e.g. %r.'), name, 'Content') - - def check_primary_domain(app: "Sphinx", config: Config) -> None: primary_domain = config.primary_domain if primary_domain and not app.registry.has_domain(primary_domain): @@ -482,17 +462,17 @@ def check_primary_domain(app: "Sphinx", config: Config) -> None: config.primary_domain = None # type: ignore -def check_master_doc(app: "Sphinx", env: "BuildEnvironment", added: Set[str], - changed: Set[str], removed: Set[str]) -> Set[str]: - """Adjust master_doc to 'contents' to support an old project which does not have - no master_doc setting. +def check_root_doc(app: "Sphinx", env: "BuildEnvironment", added: Set[str], + changed: Set[str], removed: Set[str]) -> Set[str]: + """Adjust root_doc to 'contents' to support an old project which does not have + no root_doc setting. """ - if (app.config.master_doc == 'index' and + if (app.config.root_doc == 'index' and 'index' not in app.project.docnames and 'contents' in app.project.docnames): - logger.warning(__('Since v2.0, Sphinx uses "index" as master_doc by default. ' - 'Please add "master_doc = \'contents\'" to your conf.py.')) - app.config.master_doc = "contents" # type: ignore + logger.warning(__('Since v2.0, Sphinx uses "index" as root_doc by default. ' + 'Please add "root_doc = \'contents\'" to your conf.py.')) + app.config.root_doc = "contents" # type: ignore return changed @@ -504,7 +484,7 @@ def setup(app: "Sphinx") -> Dict[str, Any]: app.connect('config-inited', correct_copyright_year, priority=800) app.connect('config-inited', check_confval_types, priority=800) app.connect('config-inited', check_primary_domain, priority=800) - app.connect('env-get-outdated', check_master_doc) + app.connect('env-get-outdated', check_root_doc) return { 'version': 'builtin', diff --git a/sphinx/deprecation.py b/sphinx/deprecation.py index 161d7bcacf..aeefcc61fc 100644 --- a/sphinx/deprecation.py +++ b/sphinx/deprecation.py @@ -11,18 +11,14 @@ import sys import warnings from importlib import import_module -from typing import Any, Dict - -if False: - # For type annotation - from typing import Type # for python3.5.1 +from typing import Any, Dict, Type class RemovedInSphinx40Warning(DeprecationWarning): pass -class RemovedInSphinx50Warning(PendingDeprecationWarning): +class RemovedInSphinx50Warning(DeprecationWarning): pass @@ -30,11 +26,11 @@ class RemovedInSphinx60Warning(PendingDeprecationWarning): pass -RemovedInNextVersionWarning = RemovedInSphinx40Warning +RemovedInNextVersionWarning = RemovedInSphinx50Warning def deprecated_alias(modname: str, objects: Dict[str, object], - warning: "Type[Warning]", names: Dict[str, str] = None) -> None: + warning: "Type[Warning]", names: Dict[str, str] = {}) -> None: module = import_module(modname) sys.modules[modname] = _ModuleWrapper( # type: ignore module, modname, objects, warning, names) diff --git a/sphinx/directives/__init__.py b/sphinx/directives/__init__.py index e386b3eaaf..d4c82c9f3e 100644 --- a/sphinx/directives/__init__.py +++ b/sphinx/directives/__init__.py @@ -9,7 +9,7 @@ """ import re -from typing import Any, Dict, Generic, List, Tuple, TypeVar, cast +from typing import TYPE_CHECKING, Any, Dict, Generic, List, Tuple, TypeVar, cast from docutils import nodes from docutils.nodes import Node @@ -17,15 +17,13 @@ from sphinx import addnodes from sphinx.addnodes import desc_signature -from sphinx.deprecation import (RemovedInSphinx40Warning, RemovedInSphinx50Warning, - deprecated_alias) +from sphinx.deprecation import RemovedInSphinx50Warning, deprecated_alias from sphinx.util import docutils from sphinx.util.docfields import DocFieldTransformer, Field, TypedField from sphinx.util.docutils import SphinxDirective from sphinx.util.typing import DirectiveOption -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx @@ -266,52 +264,6 @@ def run(self) -> List[Node]: self.env.temp_data['default_domain'] = self.env.domains.get(domain_name) return [] -from sphinx.directives.code import CodeBlock, Highlight, LiteralInclude # noqa -from sphinx.directives.other import (Acks, Author, Centered, Class, HList, Include, # noqa - Only, SeeAlso, TabularColumns, TocTree, VersionChange) -from sphinx.directives.patches import Figure, Meta # noqa -from sphinx.domains.index import IndexDirective # noqa - -deprecated_alias('sphinx.directives', - { - 'Highlight': Highlight, - 'CodeBlock': CodeBlock, - 'LiteralInclude': LiteralInclude, - 'TocTree': TocTree, - 'Author': Author, - 'Index': IndexDirective, - 'VersionChange': VersionChange, - 'SeeAlso': SeeAlso, - 'TabularColumns': TabularColumns, - 'Centered': Centered, - 'Acks': Acks, - 'HList': HList, - 'Only': Only, - 'Include': Include, - 'Class': Class, - 'Figure': Figure, - 'Meta': Meta, - }, - RemovedInSphinx40Warning, - { - 'Highlight': 'sphinx.directives.code.Highlight', - 'CodeBlock': 'sphinx.directives.code.CodeBlock', - 'LiteralInclude': 'sphinx.directives.code.LiteralInclude', - 'TocTree': 'sphinx.directives.other.TocTree', - 'Author': 'sphinx.directives.other.Author', - 'Index': 'sphinx.directives.other.IndexDirective', - 'VersionChange': 'sphinx.directives.other.VersionChange', - 'SeeAlso': 'sphinx.directives.other.SeeAlso', - 'TabularColumns': 'sphinx.directives.other.TabularColumns', - 'Centered': 'sphinx.directives.other.Centered', - 'Acks': 'sphinx.directives.other.Acks', - 'HList': 'sphinx.directives.other.HList', - 'Only': 'sphinx.directives.other.Only', - 'Include': 'sphinx.directives.other.Include', - 'Class': 'sphinx.directives.other.Class', - 'Figure': 'sphinx.directives.patches.Figure', - 'Meta': 'sphinx.directives.patches.Meta', - }) deprecated_alias('sphinx.directives', { diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py index e01b8f9ec4..f5cd92b82b 100644 --- a/sphinx/directives/code.py +++ b/sphinx/directives/code.py @@ -8,9 +8,8 @@ import sys import textwrap -import warnings from difflib import unified_diff -from typing import Any, Dict, List, Tuple +from typing import TYPE_CHECKING, Any, Dict, List, Tuple from docutils import nodes from docutils.nodes import Element, Node @@ -19,14 +18,12 @@ from sphinx import addnodes from sphinx.config import Config -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.directives import optional_int from sphinx.locale import __ from sphinx.util import logging, parselinenos from sphinx.util.docutils import SphinxDirective -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx logger = logging.getLogger(__name__) @@ -58,16 +55,6 @@ def run(self) -> List[Node]: linenothreshold=linenothreshold)] -class HighlightLang(Highlight): - """highlightlang directive (deprecated)""" - - def run(self) -> List[Node]: - warnings.warn('highlightlang directive is deprecated. ' - 'Please use highlight directive instead.', - RemovedInSphinx40Warning, stacklevel=2) - return super().run() - - def dedent_lines(lines: List[str], dedent: int, location: Tuple[str, int] = None) -> List[str]: if not dedent: return textwrap.dedent(''.join(lines)).splitlines(True) @@ -470,7 +457,6 @@ def run(self) -> List[Node]: def setup(app: "Sphinx") -> Dict[str, Any]: directives.register_directive('highlight', Highlight) - directives.register_directive('highlightlang', HighlightLang) directives.register_directive('code-block', CodeBlock) directives.register_directive('sourcecode', CodeBlock) directives.register_directive('literalinclude', LiteralInclude) diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py index 2ace3738f7..7dd6252e2a 100644 --- a/sphinx/directives/other.py +++ b/sphinx/directives/other.py @@ -7,7 +7,7 @@ """ import re -from typing import Any, Dict, List, cast +from typing import TYPE_CHECKING, Any, Dict, List, cast from docutils import nodes from docutils.nodes import Element, Node @@ -17,7 +17,6 @@ from docutils.parsers.rst.directives.misc import Include as BaseInclude from sphinx import addnodes -from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias from sphinx.domains.changeset import VersionChange # NOQA # for compatibility from sphinx.locale import _ from sphinx.util import docname_join, url_re @@ -25,8 +24,7 @@ from sphinx.util.matching import Matcher, patfilter from sphinx.util.nodes import explicit_title_re -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx @@ -137,7 +135,13 @@ def parse_content(self, toctree: addnodes.toctree) -> List[Node]: line=self.lineno)) self.env.note_reread() else: - all_docnames.discard(docname) + if docname in all_docnames: + all_docnames.remove(docname) + else: + message = 'duplicated entry found in toctree: %s' + ret.append(self.state.document.reporter.warning(message % docname, + line=self.lineno)) + toctree['entries'].append((title, docname)) toctree['includefiles'].append(docname) @@ -361,19 +365,6 @@ def run(self) -> List[Node]: return super().run() -# Import old modules here for compatibility -from sphinx.domains.index import IndexDirective # NOQA - -deprecated_alias('sphinx.directives.other', - { - 'Index': IndexDirective, - }, - RemovedInSphinx40Warning, - { - 'Index': 'sphinx.domains.index.IndexDirective', - }) - - def setup(app: "Sphinx") -> Dict[str, Any]: directives.register_directive('toctree', TocTree) directives.register_directive('sectionauthor', Author) diff --git a/sphinx/directives/patches.py b/sphinx/directives/patches.py index 1eae6d0c80..1c3cfd853b 100644 --- a/sphinx/directives/patches.py +++ b/sphinx/directives/patches.py @@ -6,7 +6,10 @@ :license: BSD, see LICENSE for details. """ -from typing import Any, Dict, List, Tuple, cast +import os +import warnings +from os import path +from typing import TYPE_CHECKING, Any, Dict, List, Tuple, cast from docutils import nodes from docutils.nodes import Node, make_id, system_message @@ -14,16 +17,22 @@ from docutils.parsers.rst.directives import html, images, tables from sphinx import addnodes +from sphinx.deprecation import RemovedInSphinx60Warning from sphinx.directives import optional_int from sphinx.domains.math import MathDomain +from sphinx.locale import __ +from sphinx.util import logging from sphinx.util.docutils import SphinxDirective from sphinx.util.nodes import set_source_info +from sphinx.util.osutil import SEP, os_path, relpath -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx +logger = logging.getLogger(__name__) + + class Figure(images.Figure): """The figure directive which applies `:name:` option to the figure node instead of the image node. @@ -72,6 +81,11 @@ class RSTTable(tables.RSTTable): Only for docutils-0.13 or older version.""" + def run(self) -> List[Node]: + warnings.warn('RSTTable is deprecated.', + RemovedInSphinx60Warning) + return super().run() + def make_title(self) -> Tuple[nodes.title, List[system_message]]: title, message = super().make_title() if title: @@ -81,16 +95,25 @@ def make_title(self) -> Tuple[nodes.title, List[system_message]]: class CSVTable(tables.CSVTable): - """The csv-table directive which sets source and line information to its caption. - - Only for docutils-0.13 or older version.""" - - def make_title(self) -> Tuple[nodes.title, List[system_message]]: - title, message = super().make_title() - if title: - set_source_info(self, title) + """The csv-table directive which searches a CSV file from Sphinx project's source + directory when an absolute path is given via :file: option. + """ - return title, message + def run(self) -> List[Node]: + if 'file' in self.options and self.options['file'].startswith((SEP, os.sep)): + env = self.state.document.settings.env + filename = self.options['file'] + if path.exists(filename): + logger.warning(__('":file:" option for csv-table directive now recognizes ' + 'an absolute path as a relative path from source directory. ' + 'Please update your document.'), + location=(env.docname, self.lineno)) + else: + abspath = path.join(env.srcdir, os_path(self.options['file'][1:])) + docdir = path.dirname(env.doc2path(env.docname)) + self.options['file'] = relpath(abspath, docdir) + + return super().run() class ListTable(tables.ListTable): @@ -98,6 +121,11 @@ class ListTable(tables.ListTable): Only for docutils-0.13 or older version.""" + def run(self) -> List[Node]: + warnings.warn('ListTable is deprecated.', + RemovedInSphinx60Warning) + return super().run() + def make_title(self) -> Tuple[nodes.title, List[system_message]]: title, message = super().make_title() if title: @@ -208,9 +236,7 @@ def add_target(self, ret: List[Node]) -> None: def setup(app: "Sphinx") -> Dict[str, Any]: directives.register_directive('figure', Figure) directives.register_directive('meta', Meta) - directives.register_directive('table', RSTTable) directives.register_directive('csv-table', CSVTable) - directives.register_directive('list-table', ListTable) directives.register_directive('code', Code) directives.register_directive('math', MathDirective) diff --git a/sphinx/domains/__init__.py b/sphinx/domains/__init__.py index 60142f584d..d241b1523b 100644 --- a/sphinx/domains/__init__.py +++ b/sphinx/domains/__init__.py @@ -10,7 +10,9 @@ """ import copy -from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Tuple, Union, cast +from abc import ABC, abstractmethod +from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, List, NamedTuple, Tuple, + Type, Union, cast) from docutils import nodes from docutils.nodes import Element, Node, system_message @@ -22,10 +24,7 @@ from sphinx.roles import XRefRole from sphinx.util.typing import RoleFunction -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from sphinx.builders import Builder from sphinx.environment import BuildEnvironment @@ -56,16 +55,17 @@ def __init__(self, lname: str, *roles: Any, **attrs: Any) -> None: self.attrs.update(attrs) -IndexEntry = NamedTuple('IndexEntry', [('name', str), - ('subtype', int), - ('docname', str), - ('anchor', str), - ('extra', str), - ('qualifier', str), - ('descr', str)]) +class IndexEntry(NamedTuple): + name: str + subtype: int + docname: str + anchor: str + extra: str + qualifier: str + descr: str -class Index: +class Index(ABC): """ An Index is the description for a domain-specific index. To add an index to a domain, subclass Index, overriding the three name attributes: @@ -98,6 +98,7 @@ def __init__(self, domain: "Domain") -> None: % self.__class__.__name__) self.domain = domain + @abstractmethod def generate(self, docnames: Iterable[str] = None ) -> Tuple[List[Tuple[str, List[IndexEntry]]], bool]: """Get entries for the index. diff --git a/sphinx/domains/c.py b/sphinx/domains/c.py index 061010d665..0fecbad6d4 100644 --- a/sphinx/domains/c.py +++ b/sphinx/domains/c.py @@ -387,19 +387,6 @@ def describe_signature(self, signode: TextElement, mode: str, signode.append(nodes.Text('--')) -class ASTPostfixMember(ASTPostfixOp): - def __init__(self, name): - self.name = name - - def _stringify(self, transform: StringifyTransform) -> str: - return '.' + transform(self.name) - - def describe_signature(self, signode: TextElement, mode: str, - env: "BuildEnvironment", symbol: "Symbol") -> None: - signode.append(nodes.Text('.')) - self.name.describe_signature(signode, 'noneIsName', env, symbol) - - class ASTPostfixMemberOfPointer(ASTPostfixOp): def __init__(self, name): self.name = name @@ -682,15 +669,24 @@ def _stringify(self, transform: StringifyTransform) -> str: def describe_signature(self, signode: TextElement, mode: str, env: "BuildEnvironment", symbol: "Symbol") -> None: verify_description_mode(mode) - paramlist = addnodes.desc_parameterlist() - for arg in self.args: - param = addnodes.desc_parameter('', '', noemph=True) - if mode == 'lastIsName': # i.e., outer-function params + # only use the desc_parameterlist for the outer list, not for inner lists + if mode == 'lastIsName': + paramlist = addnodes.desc_parameterlist() + for arg in self.args: + param = addnodes.desc_parameter('', '', noemph=True) arg.describe_signature(param, 'param', env, symbol=symbol) - else: - arg.describe_signature(param, 'markType', env, symbol=symbol) - paramlist += param - signode += paramlist + paramlist += param + signode += paramlist + else: + signode += nodes.Text('(', '(') + first = True + for arg in self.args: + if not first: + signode += nodes.Text(', ', ', ') + first = False + arg.describe_signature(signode, 'markType', env, symbol=symbol) + signode += nodes.Text(')', ')') + for attr in self.attrs: signode += nodes.Text(' ') attr.describe_signature(signode) @@ -2256,7 +2252,7 @@ def _parse_postfix_expression(self) -> ASTPostfixExpr: # | postfix "[" expression "]" # | postfix "[" braced-init-list [opt] "]" # | postfix "(" expression-list [opt] ")" - # | postfix "." id-expression + # | postfix "." id-expression // taken care of in primary by nested name # | postfix "->" id-expression # | postfix "++" # | postfix "--" @@ -2274,17 +2270,6 @@ def _parse_postfix_expression(self) -> ASTPostfixExpr: self.fail("Expected ']' in end of postfix expression.") postFixes.append(ASTPostfixArray(expr)) continue - if self.skip_string('.'): - if self.skip_string('*'): - # don't steal the dot - self.pos -= 2 - elif self.skip_string('..'): - # don't steal the dot - self.pos -= 3 - else: - name = self._parse_nested_name() - postFixes.append(ASTPostfixMember(name)) - continue if self.skip_string('->'): if self.skip_string('*'): # don't steal the arrow @@ -2693,16 +2678,13 @@ def _parse_decl_specs(self, outer: str, typed: bool = True) -> ASTDeclSpecs: def _parse_declarator_name_suffix( self, named: Union[bool, str], paramMode: str, typed: bool ) -> ASTDeclarator: + assert named in (True, False, 'single') # now we should parse the name, and then suffixes - if named == 'maybe': - pos = self.pos - try: - declId = self._parse_nested_name() - except DefinitionError: - self.pos = pos - declId = None - elif named == 'single': + if named == 'single': if self.match(identifier_re): + if self.matched_text in _keywords: + self.fail("Expected identifier, " + "got keyword: %s" % self.matched_text) identifier = ASTIdentifier(self.matched_text) declId = ASTNestedName([identifier], rooted=False) else: @@ -2880,8 +2862,8 @@ def parser(): def _parse_type(self, named: Union[bool, str], outer: str = None) -> ASTType: """ - named=False|'maybe'|True: 'maybe' is e.g., for function objects which - doesn't need to name the arguments + named=False|'single'|True: 'single' is e.g., for function objects which + doesn't need to name the arguments, but otherwise is a single name """ if outer: # always named if outer not in ('type', 'member', 'function'): diff --git a/sphinx/domains/changeset.py b/sphinx/domains/changeset.py index ba323b7292..33234d6e03 100644 --- a/sphinx/domains/changeset.py +++ b/sphinx/domains/changeset.py @@ -8,8 +8,7 @@ :license: BSD, see LICENSE for details. """ -from collections import namedtuple -from typing import Any, Dict, List, cast +from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, cast from docutils import nodes from docutils.nodes import Node @@ -19,8 +18,7 @@ from sphinx.locale import _ from sphinx.util.docutils import SphinxDirective -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.environment import BuildEnvironment @@ -38,9 +36,13 @@ } -# TODO: move to typing.NamedTuple after dropping py35 support (see #5958) -ChangeSet = namedtuple('ChangeSet', - ['type', 'docname', 'lineno', 'module', 'descname', 'content']) +class ChangeSet(NamedTuple): + type: str + docname: str + lineno: int + module: str + descname: str + content: str class VersionChange(SphinxDirective): diff --git a/sphinx/domains/citation.py b/sphinx/domains/citation.py index 1ceb530373..772d486afb 100644 --- a/sphinx/domains/citation.py +++ b/sphinx/domains/citation.py @@ -8,7 +8,7 @@ :license: BSD, see LICENSE for details. """ -from typing import Any, Dict, List, Set, Tuple, cast +from typing import TYPE_CHECKING, Any, Dict, List, Set, Tuple, cast from docutils import nodes from docutils.nodes import Element @@ -20,8 +20,7 @@ from sphinx.util import logging from sphinx.util.nodes import copy_source_info, make_refnode -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.builders import Builder from sphinx.environment import BuildEnvironment diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py index 7ee023d1dc..3bd764de57 100644 --- a/sphinx/domains/cpp.py +++ b/sphinx/domains/cpp.py @@ -306,6 +306,7 @@ | \+\+ | -- | ->\*? | \, | (<<|>>)=? | && | \|\| + | <=> | [!<>=/*%+|&^~-]=? | (\b(and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|xor|xor_eq)\b) ''') @@ -494,6 +495,7 @@ '>': 'gt', '<=': 'le', '>=': 'ge', + '<=>': 'ss', '!': 'nt', 'not': 'nt', '&&': 'aa', 'and': 'aa', '||': 'oo', 'or': 'oo', @@ -528,7 +530,7 @@ ['^', 'xor'], ['&', 'bitand'], ['==', '!=', 'not_eq'], - ['<=', '>=', '<', '>'], + ['<=>', '<=', '>=', '<', '>'], ['<<', '>>'], ['+', '-'], ['*', '/', '%'], @@ -1965,15 +1967,23 @@ def _stringify(self, transform: StringifyTransform) -> str: def describe_signature(self, signode: TextElement, mode: str, env: "BuildEnvironment", symbol: "Symbol") -> None: verify_description_mode(mode) - paramlist = addnodes.desc_parameterlist() - for arg in self.args: - param = addnodes.desc_parameter('', '', noemph=True) - if mode == 'lastIsName': # i.e., outer-function params + # only use the desc_parameterlist for the outer list, not for inner lists + if mode == 'lastIsName': + paramlist = addnodes.desc_parameterlist() + for arg in self.args: + param = addnodes.desc_parameter('', '', noemph=True) arg.describe_signature(param, 'param', env, symbol=symbol) - else: - arg.describe_signature(param, 'markType', env, symbol=symbol) - paramlist += param - signode += paramlist + paramlist += param + signode += paramlist + else: + signode += nodes.Text('(', '(') + first = True + for arg in self.args: + if not first: + signode += nodes.Text(', ', ', ') + first = False + arg.describe_signature(signode, 'markType', env, symbol=symbol) + signode += nodes.Text(')', ')') def _add_anno(signode: TextElement, text: str) -> None: signode += nodes.Text(' ') @@ -5309,7 +5319,7 @@ def _parse_logical_or_expression(self, inTemplate: bool) -> ASTExpression: # exclusive-or = and ^ # and = equality & # equality = relational ==, != - # relational = shift <, >, <=, >= + # relational = shift <, >, <=, >=, <=> # shift = additive <<, >> # additive = multiplicative +, - # multiplicative = pm *, /, % @@ -7644,10 +7654,11 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.add_config_value("cpp_debug_lookup", False, '') app.add_config_value("cpp_debug_show_tree", False, '') - def setDebugFlags(app): + def initStuff(app): Symbol.debug_lookup = app.config.cpp_debug_lookup Symbol.debug_show_tree = app.config.cpp_debug_show_tree - app.connect("builder-inited", setDebugFlags) + app.config.cpp_index_common_prefix.sort(reverse=True) + app.connect("builder-inited", initStuff) return { 'version': 'builtin', diff --git a/sphinx/domains/index.py b/sphinx/domains/index.py index 4a91d6ad1e..fd1a766138 100644 --- a/sphinx/domains/index.py +++ b/sphinx/domains/index.py @@ -8,7 +8,7 @@ :license: BSD, see LICENSE for details. """ -from typing import Any, Dict, Iterable, List, Tuple +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Tuple from docutils import nodes from docutils.nodes import Node, system_message @@ -21,8 +21,7 @@ from sphinx.util.docutils import ReferenceRole, SphinxDirective from sphinx.util.nodes import process_index_entry -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx diff --git a/sphinx/domains/math.py b/sphinx/domains/math.py index 248a7a2a6a..70a27e6422 100644 --- a/sphinx/domains/math.py +++ b/sphinx/domains/math.py @@ -8,14 +8,12 @@ :license: BSD, see LICENSE for details. """ -import warnings -from typing import Any, Dict, Iterable, List, Tuple +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Tuple from docutils import nodes from docutils.nodes import Element, Node, make_id, system_message from sphinx.addnodes import pending_xref -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.domains import Domain from sphinx.environment import BuildEnvironment from sphinx.locale import __ @@ -23,8 +21,7 @@ from sphinx.util import logging from sphinx.util.nodes import make_refnode -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.builders import Builder @@ -139,24 +136,6 @@ def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: "Bu def get_objects(self) -> List: return [] - def add_equation(self, env: BuildEnvironment, docname: str, labelid: str) -> int: - warnings.warn('MathDomain.add_equation() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - if labelid in self.equations: - path = env.doc2path(self.equations[labelid][0]) - msg = __('duplicate label of equation %s, other instance in %s') % (labelid, path) - raise UserWarning(msg) - else: - eqno = self.get_next_equation_number(docname) - self.equations[labelid] = (docname, eqno) - return eqno - - def get_next_equation_number(self, docname: str) -> int: - warnings.warn('MathDomain.get_next_equation_number() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - targets = [eq for eq in self.equations.values() if eq[0] == docname] - return len(targets) + 1 - def has_equations(self, docname: str = None) -> bool: if docname: return self.data['has_equations'].get(docname, False) diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py index 552742bb86..40a67f82cc 100644 --- a/sphinx/domains/python.py +++ b/sphinx/domains/python.py @@ -15,17 +15,17 @@ import typing import warnings from inspect import Parameter -from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Tuple, cast +from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Tuple, Type, cast from docutils import nodes from docutils.nodes import Element, Node from docutils.parsers.rst import directives from sphinx import addnodes -from sphinx.addnodes import desc_signature, pending_xref +from sphinx.addnodes import desc_signature, pending_xref, pending_xref_condition from sphinx.application import Sphinx from sphinx.builders import Builder -from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.directives import ObjectDescription from sphinx.domains import Domain, Index, IndexEntry, ObjType from sphinx.environment import BuildEnvironment @@ -37,14 +37,9 @@ from sphinx.util.docfields import Field, GroupedField, TypedField from sphinx.util.docutils import SphinxDirective from sphinx.util.inspect import signature_from_str -from sphinx.util.nodes import make_id, make_refnode +from sphinx.util.nodes import find_pending_xref_condition, make_id, make_refnode from sphinx.util.typing import TextlikeNode -if False: - # For type annotation - from typing import Type # for python3.5.1 - - logger = logging.getLogger(__name__) @@ -68,14 +63,20 @@ 'builtin': _('built-in function'), } -ObjectEntry = NamedTuple('ObjectEntry', [('docname', str), - ('node_id', str), - ('objtype', str)]) -ModuleEntry = NamedTuple('ModuleEntry', [('docname', str), - ('node_id', str), - ('synopsis', str), - ('platform', str), - ('deprecated', bool)]) + +class ObjectEntry(NamedTuple): + docname: str + node_id: str + objtype: str + canonical: bool + + +class ModuleEntry(NamedTuple): + docname: str + node_id: str + synopsis: str + platform: str + deprecated: bool def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xref: @@ -91,7 +92,17 @@ def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xr else: kwargs = {} - return pending_xref('', nodes.Text(text), + if env.config.python_use_unqualified_type_names: + # Note: It would be better to use qualname to describe the object to support support + # nested classes. But python domain can't access the real python object because this + # module should work not-dynamically. + shortname = text.split('.')[-1] + contnodes = [pending_xref_condition('', shortname, condition='resolved'), + pending_xref_condition('', text, condition='*')] # type: List[Node] + else: + contnodes = [nodes.Text(text)] + + return pending_xref('', *contnodes, refdomain='py', reftype=reftype, reftarget=text, **kwargs) @@ -107,6 +118,11 @@ def unparse(node: ast.AST) -> List[Node]: return result elif isinstance(node, ast.BitOr): return [nodes.Text(' '), addnodes.desc_sig_punctuation('', '|'), nodes.Text(' ')] + elif isinstance(node, ast.Constant): # type: ignore + if node.value is Ellipsis: + return [addnodes.desc_sig_punctuation('', "...")] + else: + return [nodes.Text(node.value)] elif isinstance(node, ast.Expr): return unparse(node.value) elif isinstance(node, ast.Index): @@ -142,13 +158,6 @@ def unparse(node: ast.AST) -> List[Node]: return result else: - if sys.version_info >= (3, 6): - if isinstance(node, ast.Constant): - if node.value is Ellipsis: - return [addnodes.desc_sig_punctuation('', "...")] - else: - return [nodes.Text(node.value)] - if sys.version_info < (3, 8): if isinstance(node, ast.Ellipsis): return [addnodes.desc_sig_punctuation('', "...")] @@ -274,7 +283,7 @@ def _pseudo_parse_arglist(signode: desc_signature, arglist: str) -> None: # when it comes to handling "." and "~" prefixes. class PyXrefMixin: def make_xref(self, rolename: str, domain: str, target: str, - innernode: "Type[TextlikeNode]" = nodes.emphasis, + innernode: Type[TextlikeNode] = nodes.emphasis, contnode: Node = None, env: BuildEnvironment = None) -> Node: result = super().make_xref(rolename, domain, target, # type: ignore innernode, contnode, env) @@ -293,7 +302,7 @@ def make_xref(self, rolename: str, domain: str, target: str, return result def make_xrefs(self, rolename: str, domain: str, target: str, - innernode: "Type[TextlikeNode]" = nodes.emphasis, + innernode: Type[TextlikeNode] = nodes.emphasis, contnode: Node = None, env: BuildEnvironment = None) -> List[Node]: delims = r'(\s*[\[\]\(\),](?:\s*or\s)?\s*|\s+or\s+)' delims_re = re.compile(delims) @@ -317,7 +326,7 @@ def make_xrefs(self, rolename: str, domain: str, target: str, class PyField(PyXrefMixin, Field): def make_xref(self, rolename: str, domain: str, target: str, - innernode: "Type[TextlikeNode]" = nodes.emphasis, + innernode: Type[TextlikeNode] = nodes.emphasis, contnode: Node = None, env: BuildEnvironment = None) -> Node: if rolename == 'class' and target == 'None': # None is not a type, so use obj role instead. @@ -332,7 +341,7 @@ class PyGroupedField(PyXrefMixin, GroupedField): class PyTypedField(PyXrefMixin, TypedField): def make_xref(self, rolename: str, domain: str, target: str, - innernode: "Type[TextlikeNode]" = nodes.emphasis, + innernode: Type[TextlikeNode] = nodes.emphasis, contnode: Node = None, env: BuildEnvironment = None) -> Node: if rolename == 'class' and target == 'None': # None is not a type, so use obj role instead. @@ -352,6 +361,7 @@ class PyObject(ObjectDescription[Tuple[str, str]]): 'noindex': directives.flag, 'noindexentry': directives.flag, 'module': directives.unchanged, + 'canonical': directives.unchanged, 'annotation': directives.unchanged, } @@ -361,7 +371,7 @@ class PyObject(ObjectDescription[Tuple[str, str]]): 'keyword', 'kwarg', 'kwparam'), typerolename='class', typenames=('paramtype', 'type'), can_collapse=True), - PyTypedField('variable', label=_('Variables'), rolename='obj', + PyTypedField('variable', label=_('Variables'), names=('var', 'ivar', 'cvar'), typerolename='class', typenames=('vartype',), can_collapse=True), @@ -493,6 +503,11 @@ def add_target_and_index(self, name_cls: Tuple[str, str], sig: str, domain = cast(PythonDomain, self.env.get_domain('py')) domain.note_object(fullname, self.objtype, node_id, location=signode) + canonical_name = self.options.get('canonical') + if canonical_name: + domain.note_object(canonical_name, self.objtype, node_id, canonical=True, + location=signode) + if 'noindexentry' not in self.options: indextext = self.get_index_text(modname, name_cls) if indextext: @@ -557,40 +572,6 @@ def after_content(self) -> None: self.env.ref_context.pop('py:module') -class PyModulelevel(PyObject): - """ - Description of an object on module level (functions, data). - """ - - def run(self) -> List[Node]: - for cls in self.__class__.__mro__: - if cls.__name__ != 'DirectiveAdapter': - warnings.warn('PyModulelevel is deprecated. ' - 'Please check the implementation of %s' % cls, - RemovedInSphinx40Warning, stacklevel=2) - break - else: - warnings.warn('PyModulelevel is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - - return super().run() - - def needs_arglist(self) -> bool: - return self.objtype == 'function' - - def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str: - if self.objtype == 'function': - if not modname: - return _('%s() (built-in function)') % name_cls[0] - return _('%s() (in module %s)') % (name_cls[0], modname) - elif self.objtype == 'data': - if not modname: - return _('%s (built-in variable)') % name_cls[0] - return _('%s (in module %s)') % (name_cls[0], modname) - else: - return '' - - class PyFunction(PyObject): """Description of a function.""" @@ -705,91 +686,6 @@ def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str: return '' -class PyClassmember(PyObject): - """ - Description of a class member (methods, attributes). - """ - - def run(self) -> List[Node]: - for cls in self.__class__.__mro__: - if cls.__name__ != 'DirectiveAdapter': - warnings.warn('PyClassmember is deprecated. ' - 'Please check the implementation of %s' % cls, - RemovedInSphinx40Warning, stacklevel=2) - break - else: - warnings.warn('PyClassmember is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - - return super().run() - - def needs_arglist(self) -> bool: - return self.objtype.endswith('method') - - def get_signature_prefix(self, sig: str) -> str: - if self.objtype == 'staticmethod': - return 'static ' - elif self.objtype == 'classmethod': - return 'classmethod ' - return '' - - def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str: - name, cls = name_cls - add_modules = self.env.config.add_module_names - if self.objtype == 'method': - try: - clsname, methname = name.rsplit('.', 1) - except ValueError: - if modname: - return _('%s() (in module %s)') % (name, modname) - else: - return '%s()' % name - if modname and add_modules: - return _('%s() (%s.%s method)') % (methname, modname, clsname) - else: - return _('%s() (%s method)') % (methname, clsname) - elif self.objtype == 'staticmethod': - try: - clsname, methname = name.rsplit('.', 1) - except ValueError: - if modname: - return _('%s() (in module %s)') % (name, modname) - else: - return '%s()' % name - if modname and add_modules: - return _('%s() (%s.%s static method)') % (methname, modname, - clsname) - else: - return _('%s() (%s static method)') % (methname, clsname) - elif self.objtype == 'classmethod': - try: - clsname, methname = name.rsplit('.', 1) - except ValueError: - if modname: - return _('%s() (in module %s)') % (name, modname) - else: - return '%s()' % name - if modname: - return _('%s() (%s.%s class method)') % (methname, modname, - clsname) - else: - return _('%s() (%s class method)') % (methname, clsname) - elif self.objtype == 'attribute': - try: - clsname, attrname = name.rsplit('.', 1) - except ValueError: - if modname: - return _('%s (in module %s)') % (name, modname) - else: - return name - if modname and add_modules: - return _('%s (%s.%s attribute)') % (attrname, modname, clsname) - else: - return _('%s (%s attribute)') % (attrname, clsname) - else: - return '' - - class PyMethod(PyObject): """Description of a method.""" @@ -1200,7 +1096,8 @@ class PythonDomain(Domain): def objects(self) -> Dict[str, ObjectEntry]: return self.data.setdefault('objects', {}) # fullname -> ObjectEntry - def note_object(self, name: str, objtype: str, node_id: str, location: Any = None) -> None: + def note_object(self, name: str, objtype: str, node_id: str, + canonical: bool = False, location: Any = None) -> None: """Note a python object for cross reference. .. versionadded:: 2.1 @@ -1210,7 +1107,7 @@ def note_object(self, name: str, objtype: str, node_id: str, location: Any = Non logger.warning(__('duplicate object description of %s, ' 'other instance in %s, use :noindex: for one of them'), name, other.docname, location=location) - self.objects[name] = ObjectEntry(self.env.docname, node_id, objtype) + self.objects[name] = ObjectEntry(self.env.docname, node_id, objtype, canonical) @property def modules(self) -> Dict[str, ModuleEntry]: @@ -1322,7 +1219,15 @@ def resolve_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder if obj[2] == 'module': return self._make_module_refnode(builder, fromdocname, name, contnode) else: - return make_refnode(builder, fromdocname, obj[0], obj[1], contnode, name) + # determine the content of the reference by conditions + content = find_pending_xref_condition(node, 'resolved') + if content: + children = content.children + else: + # if not found, use contnode + children = [contnode] + + return make_refnode(builder, fromdocname, obj[0], obj[1], children, name) def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Builder, target: str, node: pending_xref, contnode: Element @@ -1339,9 +1244,17 @@ def resolve_any_xref(self, env: BuildEnvironment, fromdocname: str, builder: Bui self._make_module_refnode(builder, fromdocname, name, contnode))) else: + # determine the content of the reference by conditions + content = find_pending_xref_condition(node, 'resolved') + if content: + children = content.children + else: + # if not found, use contnode + children = [contnode] + results.append(('py:' + self.role_for_objtype(obj[2]), make_refnode(builder, fromdocname, obj[0], obj[1], - contnode, name))) + children, name))) return results def _make_module_refnode(self, builder: Builder, fromdocname: str, name: str, @@ -1363,7 +1276,11 @@ def get_objects(self) -> Iterator[Tuple[str, str, str, str, str, int]]: yield (modname, modname, 'module', mod.docname, mod.node_id, 0) for refname, obj in self.objects.items(): if obj.objtype != 'module': # modules are already handled - yield (refname, refname, obj.objtype, obj.docname, obj.node_id, 1) + if obj.canonical: + # canonical names are not full-text searchable. + yield (refname, refname, obj.objtype, obj.docname, obj.node_id, -1) + else: + yield (refname, refname, obj.objtype, obj.docname, obj.node_id, 1) def get_full_qualified_name(self, node: Element) -> str: modname = node.get('py:module') @@ -1404,12 +1321,13 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.setup_extension('sphinx.directives') app.add_domain(PythonDomain) + app.add_config_value('python_use_unqualified_type_names', False, 'env') app.connect('object-description-transform', filter_meta_fields) app.connect('missing-reference', builtin_resolver, priority=900) return { 'version': 'builtin', - 'env_version': 2, + 'env_version': 3, 'parallel_read_safe': True, 'parallel_write_safe': True, } diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py index 352e5c7f35..8b10c85477 100644 --- a/sphinx/domains/std.py +++ b/sphinx/domains/std.py @@ -12,7 +12,8 @@ import unicodedata import warnings from copy import copy -from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast +from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, Iterator, List, Optional, + Tuple, Type, Union, cast) from docutils import nodes from docutils.nodes import Element, Node, system_message @@ -21,7 +22,7 @@ from sphinx import addnodes from sphinx.addnodes import desc_signature, pending_xref -from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.directives import ObjectDescription from sphinx.domains import Domain, ObjType from sphinx.locale import _, __ @@ -31,10 +32,7 @@ from sphinx.util.nodes import clean_astext, make_id, make_refnode from sphinx.util.typing import RoleFunction -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.builders import Builder from sphinx.environment import BuildEnvironment @@ -292,8 +290,8 @@ def split_term_classifiers(line: str) -> List[Optional[str]]: def make_glossary_term(env: "BuildEnvironment", textnodes: Iterable[Node], index_key: str, - source: str, lineno: int, node_id: str = None, - document: nodes.document = None) -> nodes.term: + source: str, lineno: int, node_id: str, document: nodes.document + ) -> nodes.term: # get a text-only representation of the term and register it # as a cross-reference target term = nodes.term('', '', *textnodes) @@ -304,23 +302,10 @@ def make_glossary_term(env: "BuildEnvironment", textnodes: Iterable[Node], index if node_id: # node_id is given from outside (mainly i18n module), use it forcedly term['ids'].append(node_id) - elif document: + else: node_id = make_id(env, document, 'term', termtext) term['ids'].append(node_id) document.note_explicit_target(term) - else: - warnings.warn('make_glossary_term() expects document is passed as an argument.', - RemovedInSphinx40Warning, stacklevel=2) - gloss_entries = env.temp_data.setdefault('gloss_entries', set()) - node_id = nodes.make_id('term-' + termtext) - if node_id == 'term': - # "term" is not good for node_id. Generate it by sequence number instead. - node_id = 'term-%d' % env.new_serialno('glossary') - - while node_id in gloss_entries: - node_id = 'term-%d' % env.new_serialno('glossary') - gloss_entries.add(node_id) - term['ids'].append(node_id) std = cast(StandardDomain, env.get_domain('std')) std._note_term(termtext, node_id, location=term) @@ -428,7 +413,7 @@ def run(self) -> List[Node]: # use first classifier as a index key term = make_glossary_term(self.env, textnodes, parts[1], source, lineno, - document=self.state.document) + node_id=None, document=self.state.document) term.rawsource = line system_messages.extend(sysmsg) termtexts.append(term.astext()) @@ -837,11 +822,6 @@ def resolve_xref(self, env: "BuildEnvironment", fromdocname: str, builder: "Buil resolver = self._resolve_doc_xref elif typ == 'option': resolver = self._resolve_option_xref - elif typ == 'citation': - warnings.warn('pending_xref(domain=std, type=citation) is deprecated: %r' % node, - RemovedInSphinx40Warning, stacklevel=2) - domain = env.get_domain('citation') - return domain.resolve_xref(env, fromdocname, builder, typ, target, node, contnode) elif typ == 'term': resolver = self._resolve_term_xref else: @@ -1127,18 +1107,6 @@ def get_full_qualified_name(self, node: Element) -> str: else: return None - def note_citations(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA - warnings.warn('StandardDomain.note_citations() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - def note_citation_refs(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA - warnings.warn('StandardDomain.note_citation_refs() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - def note_labels(self, env: "BuildEnvironment", docname: str, document: nodes.document) -> None: # NOQA - warnings.warn('StandardDomain.note_labels() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - def warn_missing_reference(app: "Sphinx", domain: Domain, node: pending_xref) -> bool: if (domain and domain.name != 'std') or node['reftype'] != 'ref': diff --git a/sphinx/environment/__init__.py b/sphinx/environment/__init__.py index af3e2b8d54..60ede8188a 100644 --- a/sphinx/environment/__init__.py +++ b/sphinx/environment/__init__.py @@ -11,18 +11,18 @@ import os import pickle import posixpath -import warnings from collections import defaultdict from copy import copy +from datetime import datetime from os import path -from typing import Any, Callable, Dict, Generator, Iterator, List, Set, Tuple, Union, cast +from typing import (TYPE_CHECKING, Any, Callable, Dict, Generator, Iterator, List, 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 RemovedInSphinx40Warning from sphinx.domains import Domain from sphinx.environment.adapters.toctree import TocTree from sphinx.errors import BuildEnvironmentError, DocumentError, ExtensionError, SphinxError @@ -35,8 +35,7 @@ from sphinx.util.i18n import CatalogRepository, docname_to_domain from sphinx.util.nodes import is_translatable -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.builders import Builder @@ -320,28 +319,13 @@ def path2doc(self, filename: str) -> str: """ return self.project.path2doc(filename) - def doc2path(self, docname: str, base: Union[bool, str] = True, suffix: str = None) -> str: + def doc2path(self, docname: str, base: bool = True) -> str: """Return the filename for the document name. If *base* is True, return absolute path under self.srcdir. - If *base* is None, return relative path to self.srcdir. - If *base* is a path string, return absolute path under that. - If *suffix* is not None, add it instead of config.source_suffix. + If *base* is False, return relative path to self.srcdir. """ - if suffix: - warnings.warn('The suffix argument for doc2path() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - if base not in (True, False, None): - warnings.warn('The string style base argument for doc2path() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - pathname = self.project.doc2path(docname, base is True) - if suffix: - filename, _ = path.splitext(pathname) - pathname = filename + suffix - if base and base is not True: - pathname = path.join(base, pathname) # type: ignore - return pathname + return self.project.doc2path(docname, base) def relfn2path(self, filename: str, docname: str = None) -> Tuple[str, str]: """Return paths to a file referenced from a document, relative to @@ -409,21 +393,28 @@ def get_outdated_files(self, config_changed: bool) -> Tuple[Set[str], Set[str], else: for docname in self.found_docs: if docname not in self.all_docs: + logger.debug('[build target] added %r', docname) added.add(docname) continue # if the doctree file is not there, rebuild filename = path.join(self.doctreedir, docname + '.doctree') if not path.isfile(filename): + logger.debug('[build target] changed %r', docname) changed.add(docname) continue # check the "reread always" list if docname in self.reread_always: + logger.debug('[build target] changed %r', docname) changed.add(docname) continue # check the mtime of the document mtime = self.all_docs[docname] newmtime = path.getmtime(self.doc2path(docname)) if newmtime > mtime: + logger.debug('[build target] outdated %r: %s -> %s', + docname, + datetime.utcfromtimestamp(mtime), + datetime.utcfromtimestamp(newmtime)) changed.add(docname) continue # finally, check the mtime of dependencies @@ -609,7 +600,7 @@ def traverse_toctree(parent: str, docname: str) -> Iterator[Tuple[str, str]]: traversed.add(subdocname) relations = {} - docnames = traverse_toctree(None, self.config.master_doc) + docnames = traverse_toctree(None, self.config.root_doc) prevdoc = None parent, docname = next(docnames) for nextparent, nextdoc in docnames: @@ -627,7 +618,7 @@ def check_consistency(self) -> None: included = set().union(*self.included.values()) # type: ignore for docname in sorted(self.all_docs): if docname not in self.files_to_rebuild: - if docname == self.config.master_doc: + if docname == self.config.root_doc: # the master file is not included anywhere ;) continue if docname in included: @@ -642,19 +633,3 @@ def check_consistency(self) -> None: for domain in self.domains.values(): domain.check_consistency() self.events.emit('env-check-consistency', self) - - @property - def indexentries(self) -> Dict[str, List[Tuple[str, str, str, str, str]]]: - warnings.warn('env.indexentries() is deprecated. Please use IndexDomain instead.', - RemovedInSphinx40Warning, stacklevel=2) - from sphinx.domains.index import IndexDomain - domain = cast(IndexDomain, self.get_domain('index')) - return domain.entries - - @indexentries.setter - def indexentries(self, entries: Dict[str, List[Tuple[str, str, str, str, str]]]) -> None: - warnings.warn('env.indexentries() is deprecated. Please use IndexDomain instead.', - RemovedInSphinx40Warning, stacklevel=2) - from sphinx.domains.index import IndexDomain - domain = cast(IndexDomain, self.get_domain('index')) - domain.data['entries'] = entries diff --git a/sphinx/environment/adapters/toctree.py b/sphinx/environment/adapters/toctree.py index 93555d1721..d12055b843 100644 --- a/sphinx/environment/adapters/toctree.py +++ b/sphinx/environment/adapters/toctree.py @@ -8,7 +8,7 @@ :license: BSD, see LICENSE for details. """ -from typing import Any, Iterable, List, cast +from typing import TYPE_CHECKING, Any, Iterable, List, cast from docutils import nodes from docutils.nodes import Element, Node @@ -19,8 +19,7 @@ from sphinx.util.matching import Matcher from sphinx.util.nodes import clean_astext, process_only_nodes -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.builders import Builder from sphinx.environment import BuildEnvironment @@ -316,7 +315,7 @@ def get_toc_for(self, docname: str, builder: "Builder") -> Node: def get_toctree_for(self, docname: str, builder: "Builder", collapse: bool, **kwargs: Any) -> Element: """Return the global TOC nodetree.""" - doctree = self.env.get_doctree(self.env.config.master_doc) + doctree = self.env.get_doctree(self.env.config.root_doc) toctrees = [] # type: List[Element] if 'includehidden' not in kwargs: kwargs['includehidden'] = True diff --git a/sphinx/environment/collectors/__init__.py b/sphinx/environment/collectors/__init__.py index 4b7ac3472d..aa254bd9a1 100644 --- a/sphinx/environment/collectors/__init__.py +++ b/sphinx/environment/collectors/__init__.py @@ -8,14 +8,13 @@ :license: BSD, see LICENSE for details. """ -from typing import Dict, List, Set +from typing import TYPE_CHECKING, Dict, List, Set from docutils import nodes from sphinx.environment import BuildEnvironment -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx diff --git a/sphinx/environment/collectors/indexentries.py b/sphinx/environment/collectors/indexentries.py deleted file mode 100644 index 351cdc2de0..0000000000 --- a/sphinx/environment/collectors/indexentries.py +++ /dev/null @@ -1,63 +0,0 @@ -""" - sphinx.environment.collectors.indexentries - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - Index entries collector for sphinx.environment. - - :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import warnings -from typing import Any, Dict, Set - -from docutils import nodes - -from sphinx import addnodes -from sphinx.application import Sphinx -from sphinx.deprecation import RemovedInSphinx40Warning -from sphinx.environment import BuildEnvironment -from sphinx.environment.collectors import EnvironmentCollector -from sphinx.util import logging, split_index_msg - -logger = logging.getLogger(__name__) - - -class IndexEntriesCollector(EnvironmentCollector): - name = 'indices' - - def __init__(self) -> None: - warnings.warn('IndexEntriesCollector is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - def clear_doc(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None: - env.indexentries.pop(docname, None) - - def merge_other(self, app: Sphinx, env: BuildEnvironment, - docnames: Set[str], other: BuildEnvironment) -> None: - for docname in docnames: - env.indexentries[docname] = other.indexentries[docname] - - def process_doc(self, app: Sphinx, doctree: nodes.document) -> None: - docname = app.env.docname - entries = app.env.indexentries[docname] = [] - for node in doctree.traverse(addnodes.index): - try: - for entry in node['entries']: - split_index_msg(entry[0], entry[1]) - except ValueError as exc: - logger.warning(str(exc), location=node) - node.parent.remove(node) - else: - for entry in node['entries']: - entries.append(entry) - - -def setup(app: Sphinx) -> Dict[str, Any]: - app.add_env_collector(IndexEntriesCollector) - - return { - 'version': 'builtin', - 'parallel_read_safe': True, - 'parallel_write_safe': True, - } diff --git a/sphinx/environment/collectors/title.py b/sphinx/environment/collectors/title.py index 5225155e87..28e967427d 100644 --- a/sphinx/environment/collectors/title.py +++ b/sphinx/environment/collectors/title.py @@ -50,7 +50,7 @@ def process_doc(self, app: Sphinx, doctree: nodes.document) -> None: break else: # document has no title - titlenode += nodes.Text('') + titlenode += nodes.Text(doctree.get('title', '')) app.env.titles[app.env.docname] = titlenode app.env.longtitles[app.env.docname] = longtitlenode diff --git a/sphinx/environment/collectors/toctree.py b/sphinx/environment/collectors/toctree.py index 772451c563..aeb6ef3a6d 100644 --- a/sphinx/environment/collectors/toctree.py +++ b/sphinx/environment/collectors/toctree.py @@ -8,7 +8,7 @@ :license: BSD, see LICENSE for details. """ -from typing import Any, Dict, List, Set, Tuple, TypeVar, cast +from typing import Any, Dict, List, Set, Tuple, Type, TypeVar, cast from docutils import nodes from docutils.nodes import Element, Node @@ -22,11 +22,6 @@ from sphinx.transforms import SphinxContentsFilter from sphinx.util import logging, url_re -if False: - # For type annotation - from typing import Type # for python3.5.1 - - N = TypeVar('N') logger = logging.getLogger(__name__) @@ -286,7 +281,7 @@ def _walk_doc(docname: str, secnum: Tuple[int, ...]) -> None: _walk_doctree(docname, doctree, secnum) if env.config.numfig: - _walk_doc(env.config.master_doc, tuple()) + _walk_doc(env.config.root_doc, tuple()) for docname, fignums in env.toc_fignumbers.items(): if fignums != old_fignumbers.get(docname): rewrite_needed.append(docname) diff --git a/sphinx/events.py b/sphinx/events.py index e3a3b964f1..881882b411 100644 --- a/sphinx/events.py +++ b/sphinx/events.py @@ -10,29 +10,26 @@ :license: BSD, see LICENSE for details. """ -import warnings from collections import defaultdict from operator import attrgetter -from typing import Any, Callable, Dict, List, NamedTuple, Tuple +from typing import TYPE_CHECKING, Any, Callable, Dict, List, NamedTuple, Tuple, Type -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.errors import ExtensionError, SphinxError from sphinx.locale import __ from sphinx.util import logging from sphinx.util.inspect import safe_getattr -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from sphinx.application import Sphinx logger = logging.getLogger(__name__) -EventListener = NamedTuple('EventListener', [('id', int), - ('handler', Callable), - ('priority', int)]) + +class EventListener(NamedTuple): + id: int + handler: Callable + priority: int # List of all known core events. Maps name to arguments description. @@ -58,10 +55,7 @@ class EventManager: """Event manager for Sphinx.""" - def __init__(self, app: "Sphinx" = None) -> None: - if app is None: - warnings.warn('app argument is required for EventManager.', - RemovedInSphinx40Warning) + def __init__(self, app: "Sphinx") -> None: self.app = app self.events = core_events.copy() self.listeners = defaultdict(list) # type: Dict[str, List[EventListener]] @@ -91,7 +85,7 @@ def disconnect(self, listener_id: int) -> None: listeners.remove(listener) def emit(self, name: str, *args: Any, - allowed_exceptions: Tuple["Type[Exception]", ...] = ()) -> List: + allowed_exceptions: Tuple[Type[Exception], ...] = ()) -> List: """Emit a Sphinx event.""" try: logger.debug('[app] emitting event: %r%s', name, repr(args)[:100]) @@ -104,11 +98,7 @@ def emit(self, name: str, *args: Any, listeners = sorted(self.listeners[name], key=attrgetter("priority")) for listener in listeners: try: - if self.app is None: - # for compatibility; RemovedInSphinx40Warning - results.append(listener.handler(*args)) - else: - results.append(listener.handler(self.app, *args)) + results.append(listener.handler(self.app, *args)) except allowed_exceptions: # pass through the errors specified as *allowed_exceptions* raise @@ -121,7 +111,7 @@ def emit(self, name: str, *args: Any, return results def emit_firstresult(self, name: str, *args: Any, - allowed_exceptions: Tuple["Type[Exception]", ...] = ()) -> Any: + allowed_exceptions: Tuple[Type[Exception], ...] = ()) -> Any: """Emit a Sphinx event and returns first result. This returns the result of the first handler that doesn't return ``None``. diff --git a/sphinx/ext/apidoc.py b/sphinx/ext/apidoc.py index ebbdadbe8a..6affde942e 100644 --- a/sphinx/ext/apidoc.py +++ b/sphinx/ext/apidoc.py @@ -19,7 +19,6 @@ import locale import os import sys -import warnings from copy import copy from fnmatch import fnmatch from importlib.machinery import EXTENSION_SUFFIXES @@ -29,9 +28,7 @@ import sphinx.locale from sphinx import __display_version__, package_dir from sphinx.cmd.quickstart import EXTENSIONS -from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias from sphinx.locale import __ -from sphinx.util import rst from sphinx.util.osutil import FileAvoidWrite, ensuredir from sphinx.util.template import ReSTRenderer @@ -51,20 +48,6 @@ template_dir = path.join(package_dir, 'templates', 'apidoc') -def makename(package: str, module: str) -> str: - """Join package and module with a dot.""" - warnings.warn('makename() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - # Both package and module can be None/empty. - if package: - name = package - if module: - name += '.' + module - else: - name = module - return name - - def is_initpy(filename: str) -> bool: """Check *filename* is __init__ file or not.""" basename = path.basename(filename) @@ -109,26 +92,6 @@ def write_file(name: str, text: str, opts: Any) -> None: f.write(text) -def format_heading(level: int, text: str, escape: bool = True) -> str: - """Create a heading of [1, 2 or 3 supported].""" - warnings.warn('format_warning() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - if escape: - text = rst.escape(text) - underlining = ['=', '-', '~', ][level - 1] * len(text) - return '%s\n%s\n\n' % (text, underlining) - - -def format_directive(module: str, package: str = None) -> str: - """Create the automodule directive and add the options.""" - warnings.warn('format_directive() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - directive = '.. automodule:: %s\n' % module_join(package, module) - for option in OPTIONS: - directive += ' :%s:\n' % option - return directive - - def create_module_file(package: str, basename: str, opts: Any, user_template_dir: str = None) -> None: """Build the text of the file and write the file.""" @@ -206,33 +169,6 @@ def create_modules_toc_file(modules: List[str], opts: Any, name: str = 'modules' write_file(name, text, opts) -def shall_skip(module: str, opts: Any, excludes: List[str] = []) -> bool: - """Check if we want to skip this module.""" - warnings.warn('shall_skip() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - # skip if the file doesn't exist and not using implicit namespaces - if not opts.implicit_namespaces and not path.exists(module): - return True - - # Are we a package (here defined as __init__.py, not the folder in itself) - if is_initpy(module): - # Yes, check if we have any non-excluded modules at all here - all_skipped = True - basemodule = path.dirname(module) - for submodule in glob.glob(path.join(basemodule, '*.py')): - if not is_excluded(path.join(basemodule, submodule), excludes): - # There's a non-excluded module here, we won't skip - all_skipped = False - if all_skipped: - return True - - # skip if it has a "private" name and this is selected - filename = path.basename(module) - if is_initpy(filename) and filename.startswith('_') and not opts.includeprivate: - return True - return False - - def is_skipped_package(dirname: str, opts: Any, excludes: List[str] = []) -> bool: """Check if we want to skip this module.""" if not path.isdir(dirname): @@ -536,13 +472,6 @@ def main(argv: List[str] = sys.argv[1:]) -> int: return 0 -deprecated_alias('sphinx.ext.apidoc', - { - 'INITPY': '__init__.py', - }, - RemovedInSphinx40Warning) - - # So program can be started with "python -m sphinx.apidoc ..." if __name__ == "__main__": main() diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py index 3ae6dff758..0b57093014 100644 --- a/sphinx/ext/autodoc/__init__.py +++ b/sphinx/ext/autodoc/__init__.py @@ -14,16 +14,15 @@ import warnings from inspect import Parameter, Signature from types import ModuleType -from typing import (Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, - TypeVar, Union) +from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Sequence, + Set, Tuple, Type, TypeVar, Union) from docutils.statemachine import StringList import sphinx from sphinx.application import Sphinx from sphinx.config import ENUM, Config -from sphinx.deprecation import (RemovedInSphinx40Warning, RemovedInSphinx50Warning, - RemovedInSphinx60Warning) +from sphinx.deprecation import RemovedInSphinx50Warning, RemovedInSphinx60Warning from sphinx.environment import BuildEnvironment from sphinx.ext.autodoc.importer import (get_class_members, get_object_members, import_module, import_object) @@ -37,10 +36,7 @@ from sphinx.util.typing import get_type_hints, restify from sphinx.util.typing import stringify as stringify_typehint -if False: - # For type annotation - from typing import Type # NOQA # for python3.5.1 - +if TYPE_CHECKING: from sphinx.ext.autodoc.directive import DocumenterBridge @@ -327,7 +323,7 @@ def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: def __init__(self, directive: "DocumenterBridge", name: str, indent: str = '') -> None: self.directive = directive - self.config = directive.env.config + self.config = directive.env.config # type: Config self.env = directive.env # type: BuildEnvironment self.options = directive.genopt self.name = name @@ -351,7 +347,7 @@ def __init__(self, directive: "DocumenterBridge", name: str, indent: str = '') - self.analyzer = None # type: ModuleAnalyzer @property - def documenters(self) -> Dict[str, "Type[Documenter]"]: + def documenters(self) -> Dict[str, Type["Documenter"]]: """Returns registered Documenter classes""" return self.env.app.registry.documenters @@ -540,16 +536,12 @@ def add_directive_header(self, sig: str) -> None: # etc. don't support a prepended module name self.add_line(' :module: %s' % self.modname, sourcename) - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: + def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: """Decode and return lines of the docstring(s) for the object. When it returns None value, autodoc-process-docstring will not be called for this object. """ - if encoding is not None: - warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated." - % self.__class__.__name__, - RemovedInSphinx40Warning, stacklevel=2) if ignore is not None: warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated." % self.__class__.__name__, @@ -910,7 +902,7 @@ def generate(self, more_content: Optional[StringList] = None, real_modname: str # This is used for situations where you have a module that collects the # functions and classes of internal submodules. guess_modname = self.get_real_modname() - self.real_modname = real_modname or guess_modname + self.real_modname = real_modname or guess_modname # type: str # try to also get a source code analyzer for attribute docs try: @@ -1103,7 +1095,7 @@ def sort_members(self, documenters: List[Tuple["Documenter", bool]], # Sort by __all__ def keyfunc(entry: Tuple[Documenter, bool]) -> int: name = entry[0].name.split('::')[1] - if name in self.__all__: + if self.__all__ and name in self.__all__: return self.__all__.index(name) else: return len(self.__all__) @@ -1176,12 +1168,7 @@ class DocstringSignatureMixin: _new_docstrings = None # type: List[List[str]] _signatures = None # type: List[str] - def _find_signature(self, encoding: str = None) -> Tuple[str, str]: - if encoding is not None: - warnings.warn("The 'encoding' argument to autodoc.%s._find_signature() is " - "deprecated." % self.__class__.__name__, - RemovedInSphinx40Warning, stacklevel=2) - + def _find_signature(self) -> Tuple[str, str]: # candidates of the object name valid_names = [self.objpath[-1]] # type: ignore if isinstance(self, ClassDocumenter): @@ -1242,14 +1229,10 @@ def _find_signature(self, encoding: str = None) -> Tuple[str, str]: return result - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: - if encoding is not None: - warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated." - % self.__class__.__name__, - RemovedInSphinx40Warning, stacklevel=2) + def get_doc(self, ignore: int = None) -> List[List[str]]: if self._new_docstrings is not None: return self._new_docstrings - return super().get_doc(None, ignore) # type: ignore + return super().get_doc(ignore) # type: ignore def format_signature(self, **kwargs: Any) -> str: if self.args is None and self.config.autodoc_docstring_signature: # type: ignore @@ -1649,11 +1632,7 @@ def get_object_members(self, want_all: bool) -> Tuple[bool, ObjectMembers]: else: return False, [m for m in members.values() if m.class_ == self.object] - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: - if encoding is not None: - warnings.warn("The 'encoding' argument to autodoc.%s.get_doc() is deprecated." - % self.__class__.__name__, - RemovedInSphinx40Warning, stacklevel=2) + 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 @@ -1814,7 +1793,7 @@ def should_suppress_directive_header(self) -> bool: return (isinstance(self.object, TypeVar) or super().should_suppress_directive_header()) - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: + def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: if ignore is not None: warnings.warn("The 'ignore' argument to autodoc.%s.get_doc() is deprecated." % self.__class__.__name__, @@ -1833,6 +1812,8 @@ def update_content(self, more_content: StringList) -> None: attrs = [repr(self.object.__name__)] for constraint in self.object.__constraints__: attrs.append(stringify_typehint(constraint)) + if self.object.__bound__: + attrs.append(r"bound=\ " + restify(self.object.__bound__)) if self.object.__covariant__: attrs.append("covariant=True") if self.object.__contravariant__: @@ -1878,11 +1859,11 @@ def should_suppress_value_header(self) -> bool: return (self.object is UNINITIALIZED_ATTR or super().should_suppress_value_header()) - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: + def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: if self.object is UNINITIALIZED_ATTR: return [] else: - return super().get_doc(encoding, ignore) # type: ignore + return super().get_doc(ignore) # type: ignore class DataDocumenter(GenericAliasMixin, NewTypeMixin, TypeVarMixin, @@ -1977,13 +1958,13 @@ def get_module_comment(self, attrname: str) -> Optional[List[str]]: return None - def get_doc(self, encoding: str = None, ignore: int = None) -> List[List[str]]: + def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: # Check the variable has a docstring-comment comment = self.get_module_comment(self.objpath[-1]) if comment: return [comment] else: - return super().get_doc(encoding, ignore) + return super().get_doc(ignore) def add_content(self, more_content: Optional[StringList], no_docstring: bool = False ) -> None: @@ -2204,13 +2185,13 @@ def should_suppress_value_header(self) -> bool: return (not getattr(self, 'non_data_descriptor', False) or super().should_suppress_directive_header()) - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: + def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: if getattr(self, 'non_data_descriptor', False): # the docstring of non datadescriptor is very probably the wrong thing # to display return None else: - return super().get_doc(encoding, ignore) # type: ignore + return super().get_doc(ignore) # type: ignore class SlotsMixin(DataDocumenterMixinBase): @@ -2243,7 +2224,7 @@ def should_suppress_directive_header(self) -> bool: else: return super().should_suppress_directive_header() - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: + def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: if self.object is SLOTSATTR: try: __slots__ = inspect.getslots(self.parent) @@ -2257,7 +2238,7 @@ def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[Lis (self.parent.__qualname__, exc), type='autodoc') return [] else: - return super().get_doc(encoding, ignore) # type: ignore + return super().get_doc(ignore) # type: ignore class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase): @@ -2361,11 +2342,11 @@ def should_suppress_value_header(self) -> bool: return (self.object is UNINITIALIZED_ATTR or super().should_suppress_value_header()) - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: + def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: if self.object is UNINITIALIZED_ATTR: return None else: - return super().get_doc(encoding, ignore) # type: ignore + return super().get_doc(ignore) # type: ignore class AttributeDocumenter(GenericAliasMixin, NewTypeMixin, SlotsMixin, # type: ignore @@ -2512,7 +2493,7 @@ def get_attribute_comment(self, parent: Any, attrname: str) -> Optional[List[str return None - def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[List[str]]]: + def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: # Check the attribute has a docstring-comment comment = self.get_attribute_comment(self.parent, self.objpath[-1]) if comment: @@ -2524,7 +2505,7 @@ def get_doc(self, encoding: str = None, ignore: int = None) -> Optional[List[Lis # ref: https://github.com/sphinx-doc/sphinx/issues/7805 orig = self.config.autodoc_inherit_docstrings self.config.autodoc_inherit_docstrings = False # type: ignore - return super().get_doc(encoding, ignore) + return super().get_doc(ignore) finally: self.config.autodoc_inherit_docstrings = orig # type: ignore @@ -2589,7 +2570,7 @@ def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: return not isinstance(parent, ModuleDocumenter) and inspect.isNewType(member) -def get_documenters(app: Sphinx) -> Dict[str, "Type[Documenter]"]: +def get_documenters(app: Sphinx) -> Dict[str, Type[Documenter]]: """Returns registered Documenter classes""" warnings.warn("get_documenters() is deprecated.", RemovedInSphinx50Warning, stacklevel=2) return app.registry.documenters @@ -2653,6 +2634,7 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.connect('config-inited', migrate_autodoc_member_order, priority=800) + app.setup_extension('sphinx.ext.autodoc.preserve_defaults') app.setup_extension('sphinx.ext.autodoc.type_comment') app.setup_extension('sphinx.ext.autodoc.typehints') diff --git a/sphinx/ext/autodoc/directive.py b/sphinx/ext/autodoc/directive.py index c932c6f9f7..69177f2717 100644 --- a/sphinx/ext/autodoc/directive.py +++ b/sphinx/ext/autodoc/directive.py @@ -7,27 +7,22 @@ """ import warnings -from typing import Any, Callable, Dict, List, Set +from typing import Any, Callable, Dict, List, Set, Type from docutils import nodes from docutils.nodes import Element, Node -from docutils.parsers.rst.states import RSTState, Struct +from docutils.parsers.rst.states import RSTState from docutils.statemachine import StringList from docutils.utils import Reporter, assemble_option_dict from sphinx.config import Config -from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.environment import BuildEnvironment from sphinx.ext.autodoc import Documenter, Options from sphinx.util import logging from sphinx.util.docutils import SphinxDirective, switch_source_input from sphinx.util.nodes import nested_parse_with_titles -if False: - # For type annotation - from typing import Type # for python3.5.1 - - logger = logging.getLogger(__name__) @@ -56,23 +51,14 @@ class DocumenterBridge: """A parameters container for Documenters.""" def __init__(self, env: BuildEnvironment, reporter: Reporter, options: Options, - lineno: int, state: Any = None) -> None: + lineno: int, state: Any) -> None: self.env = env self._reporter = reporter self.genopt = options self.lineno = lineno self.filename_set = set() # type: Set[str] self.result = StringList() - - if state: - self.state = state - else: - # create fake object for self.state.document.settings.tab_width - warnings.warn('DocumenterBridge requires a state object on instantiation.', - RemovedInSphinx40Warning, stacklevel=2) - settings = Struct(tab_width=8) - document = Struct(settings=settings) - self.state = Struct(document=document) + self.state = state def warn(self, msg: str) -> None: logger.warning(msg, location=(self.env.docname, self.lineno)) diff --git a/sphinx/ext/autodoc/importer.py b/sphinx/ext/autodoc/importer.py index b792b1a5fd..6660391630 100644 --- a/sphinx/ext/autodoc/importer.py +++ b/sphinx/ext/autodoc/importer.py @@ -11,10 +11,9 @@ import importlib import traceback import warnings -from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Tuple +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple -from sphinx.deprecation import (RemovedInSphinx40Warning, RemovedInSphinx50Warning, - deprecated_alias) +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.ext.autodoc.mock import ismock, undecorate from sphinx.pycode import ModuleAnalyzer, PycodeError from sphinx.util import logging @@ -164,21 +163,10 @@ def get_module_members(module: Any) -> List[Tuple[str, Any]]: return sorted(list(members.values())) -Attribute = NamedTuple('Attribute', [('name', str), - ('directly_defined', bool), - ('value', Any)]) - - -def _getmro(obj: Any) -> Tuple["Type", ...]: - warnings.warn('sphinx.ext.autodoc.importer._getmro() is deprecated.', - RemovedInSphinx40Warning) - return getmro(obj) - - -def _getannotations(obj: Any) -> Mapping[str, Any]: - warnings.warn('sphinx.ext.autodoc.importer._getannotations() is deprecated.', - RemovedInSphinx40Warning) - return getannotations(obj) +class Attribute(NamedTuple): + name: str + directly_defined: bool + value: Any def get_object_members(subject: Any, objpath: List[str], attrgetter: Callable, @@ -327,24 +315,3 @@ def get_class_members(subject: Any, objpath: List[str], attrgetter: Callable pass return members - - -from sphinx.ext.autodoc.mock import (MockFinder, MockLoader, _MockModule, _MockObject, # NOQA - mock) - -deprecated_alias('sphinx.ext.autodoc.importer', - { - '_MockModule': _MockModule, - '_MockObject': _MockObject, - 'MockFinder': MockFinder, - 'MockLoader': MockLoader, - 'mock': mock, - }, - RemovedInSphinx40Warning, - { - '_MockModule': 'sphinx.ext.autodoc.mock._MockModule', - '_MockObject': 'sphinx.ext.autodoc.mock._MockObject', - 'MockFinder': 'sphinx.ext.autodoc.mock.MockFinder', - 'MockLoader': 'sphinx.ext.autodoc.mock.MockLoader', - 'mock': 'sphinx.ext.autodoc.mock.mock', - }) diff --git a/sphinx/ext/autodoc/mock.py b/sphinx/ext/autodoc/mock.py index d3f4291c21..80e3d2b50b 100644 --- a/sphinx/ext/autodoc/mock.py +++ b/sphinx/ext/autodoc/mock.py @@ -14,7 +14,7 @@ from importlib.abc import Loader, MetaPathFinder from importlib.machinery import ModuleSpec from types import ModuleType -from typing import Any, Generator, Iterator, List, Sequence, Tuple, Union +from typing import Any, Generator, Iterator, List, Optional, Sequence, Tuple, Union from sphinx.util import logging from sphinx.util.inspect import safe_getattr @@ -120,8 +120,8 @@ def __init__(self, modnames: List[str]) -> None: self.loader = MockLoader(self) self.mocked_modules = [] # type: List[str] - def find_spec(self, fullname: str, path: Sequence[Union[bytes, str]], - target: ModuleType = None) -> ModuleSpec: + def find_spec(self, fullname: str, path: Optional[Sequence[Union[bytes, str]]], + target: ModuleType = None) -> Optional[ModuleSpec]: for modname in self.modnames: # check if fullname is (or is a descendant of) one of our targets if modname == fullname or fullname.startswith(modname + '.'): diff --git a/sphinx/ext/autodoc/preserve_defaults.py b/sphinx/ext/autodoc/preserve_defaults.py new file mode 100644 index 0000000000..3d859fe8ee --- /dev/null +++ b/sphinx/ext/autodoc/preserve_defaults.py @@ -0,0 +1,88 @@ +""" + sphinx.ext.autodoc.preserve_defaults + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Preserve the default argument values of function signatures in source code + and keep them not evaluated for readability. + + :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import ast +import inspect +from typing import Any, Dict + +from sphinx.application import Sphinx +from sphinx.locale import __ +from sphinx.pycode.ast import parse as ast_parse +from sphinx.pycode.ast import unparse as ast_unparse +from sphinx.util import logging + +logger = logging.getLogger(__name__) + + +class DefaultValue: + def __init__(self, name: str) -> None: + self.name = name + + def __repr__(self) -> str: + return self.name + + +def get_function_def(obj: Any) -> ast.FunctionDef: + """Get FunctionDef object from living object. + This tries to parse original code for living object and returns + AST node for given *obj*. + """ + try: + source = inspect.getsource(obj) + if source.startswith((' ', r'\t')): + # subject is placed inside class or block. To read its docstring, + # this adds if-block before the declaration. + module = ast_parse('if True:\n' + source) + return module.body[0].body[0] # type: ignore + else: + module = ast_parse(source) + return module.body[0] # type: ignore + except (OSError, TypeError): # failed to load source code + return None + + +def update_defvalue(app: Sphinx, obj: Any, bound_method: bool) -> None: + """Update defvalue info of *obj* using type_comments.""" + if not app.config.autodoc_preserve_defaults: + return + + try: + function = get_function_def(obj) + if function.args.defaults or function.args.kw_defaults: + sig = inspect.signature(obj) + defaults = list(function.args.defaults) + kw_defaults = list(function.args.kw_defaults) + parameters = list(sig.parameters.values()) + for i, param in enumerate(parameters): + if param.default is not param.empty: + if param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD): + value = DefaultValue(ast_unparse(defaults.pop(0))) # type: ignore + parameters[i] = param.replace(default=value) + else: + value = DefaultValue(ast_unparse(kw_defaults.pop(0))) # type: ignore + parameters[i] = param.replace(default=value) + sig = sig.replace(parameters=parameters) + obj.__signature__ = sig + except (AttributeError, TypeError): + # failed to update signature (ex. built-in or extension types) + pass + except NotImplementedError as exc: # failed to ast.unparse() + logger.warning(__("Failed to parse a default argument value for %r: %s"), obj, exc) + + +def setup(app: Sphinx) -> Dict[str, Any]: + app.add_config_value('autodoc_preserve_defaults', False, True) + app.connect('autodoc-before-process-signature', update_defvalue) + + return { + 'version': '1.0', + 'parallel_read_safe': True + } diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py index b268127d04..1a0fd24092 100644 --- a/sphinx/ext/autosummary/__init__.py +++ b/sphinx/ext/autosummary/__init__.py @@ -60,19 +60,19 @@ import warnings from os import path from types import ModuleType -from typing import Any, Dict, List, Tuple, cast +from typing import Any, Dict, List, Tuple, Type, cast from docutils import nodes from docutils.nodes import Element, Node, system_message from docutils.parsers.rst import directives -from docutils.parsers.rst.states import Inliner, RSTStateMachine, Struct, state_classes +from docutils.parsers.rst.states import RSTStateMachine, Struct, state_classes from docutils.statemachine import StringList import sphinx from sphinx import addnodes from sphinx.application import Sphinx from sphinx.config import Config -from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.environment import BuildEnvironment from sphinx.environment.adapters.toctree import TocTree from sphinx.ext.autodoc import INSTANCEATTR, Documenter @@ -87,11 +87,6 @@ from sphinx.util.matching import Matcher from sphinx.writers.html import HTMLTranslator -if False: - # For type annotation - from typing import Type # for python3.5.1 - - logger = logging.getLogger(__name__) @@ -435,29 +430,6 @@ def append_row(*column_texts: str) -> None: return [table_spec, table] - def warn(self, msg: str) -> None: - warnings.warn('Autosummary.warn() is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - logger.warning(msg) - - @property - def genopt(self) -> Options: - warnings.warn('Autosummary.genopt is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - return self.bridge.genopt - - @property - def warnings(self) -> List[Node]: - warnings.warn('Autosummary.warnings is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - return [] - - @property - def result(self) -> StringList: - warnings.warn('Autosummary.result is deprecated', - RemovedInSphinx40Warning, stacklevel=2) - return self.bridge.result - def strip_arg_typehint(s: str) -> str: """Strip a type hint from argument definition.""" @@ -700,33 +672,6 @@ def import_ivar_by_name(name: str, prefixes: List[str] = [None]) -> Tuple[str, A # -- :autolink: (smart default role) ------------------------------------------- -def autolink_role(typ: str, rawtext: str, etext: str, lineno: int, inliner: Inliner, - options: Dict = {}, content: List[str] = [] - ) -> Tuple[List[Node], List[system_message]]: - """Smart linking role. - - Expands to ':obj:`text`' if `text` is an object that can be imported; - otherwise expands to '*text*'. - """ - warnings.warn('autolink_role() is deprecated.', RemovedInSphinx40Warning, stacklevel=2) - env = inliner.document.settings.env - pyobj_role = env.get_domain('py').role('obj') - objects, msg = pyobj_role('obj', rawtext, etext, lineno, inliner, options, content) - if msg != []: - return objects, msg - - assert len(objects) == 1 - pending_xref = cast(addnodes.pending_xref, objects[0]) - prefixes = get_import_prefixes_from_env(env) - try: - name, obj, parent, modname = import_by_name(pending_xref['reftarget'], prefixes) - except ImportError: - literal = cast(nodes.literal, pending_xref[0]) - objects[0] = nodes.emphasis(rawtext, literal.astext(), classes=literal['classes']) - - return objects, msg - - class AutoLink(SphinxRole): """Smart linking role. @@ -827,7 +772,7 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.connect('builder-inited', process_generate_options) app.add_config_value('autosummary_context', {}, True) app.add_config_value('autosummary_filename_map', {}, 'html') - app.add_config_value('autosummary_generate', [], True, [bool]) + app.add_config_value('autosummary_generate', True, True, [bool]) app.add_config_value('autosummary_generate_overwrite', True, False) app.add_config_value('autosummary_mock_imports', lambda config: config.autodoc_mock_imports, 'env') diff --git a/sphinx/ext/autosummary/generate.py b/sphinx/ext/autosummary/generate.py index 0240d2c7c4..59f526744d 100644 --- a/sphinx/ext/autosummary/generate.py +++ b/sphinx/ext/autosummary/generate.py @@ -28,7 +28,7 @@ import warnings from gettext import NullTranslations from os import path -from typing import Any, Callable, Dict, List, NamedTuple, Set, Tuple, Union +from typing import Any, Dict, List, NamedTuple, Set, Tuple, Type, Union from jinja2 import TemplateNotFound from jinja2.sandbox import SandboxedEnvironment @@ -38,7 +38,7 @@ from sphinx.application import Sphinx from sphinx.builders import Builder from sphinx.config import Config -from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.ext.autodoc import Documenter from sphinx.ext.autodoc.importer import import_module from sphinx.ext.autosummary import get_documenter, import_by_name, import_ivar_by_name @@ -50,11 +50,6 @@ from sphinx.util.osutil import ensuredir from sphinx.util.template import SphinxTemplateLoader -if False: - # For type annotation - from typing import Type # for python3.5.1 - - logger = logging.getLogger(__name__) @@ -79,10 +74,11 @@ def emit_firstresult(self, *args: Any) -> None: pass -AutosummaryEntry = NamedTuple('AutosummaryEntry', [('name', str), - ('path', str), - ('template', str), - ('recursive', bool)]) +class AutosummaryEntry(NamedTuple): + name: str + path: str + template: str + recursive: bool def setup_documenters(app: Any) -> None: @@ -352,25 +348,10 @@ def get_modules(obj: Any) -> Tuple[List[str], List[str]]: def generate_autosummary_docs(sources: List[str], output_dir: str = None, - suffix: str = '.rst', warn: Callable = None, - info: Callable = None, base_path: str = None, + suffix: str = '.rst', base_path: str = None, builder: Builder = None, template_dir: str = None, imported_members: bool = False, app: Any = None, overwrite: bool = True, encoding: str = 'utf-8') -> None: - if info: - warnings.warn('info argument for generate_autosummary_docs() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - _info = info - else: - _info = logger.info - - if warn: - warnings.warn('warn argument for generate_autosummary_docs() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - _warn = warn - else: - _warn = logger.warning - if builder: warnings.warn('builder argument for generate_autosummary_docs() is deprecated.', RemovedInSphinx50Warning, stacklevel=2) @@ -382,11 +363,11 @@ def generate_autosummary_docs(sources: List[str], output_dir: str = None, showed_sources = list(sorted(sources)) if len(showed_sources) > 20: showed_sources = showed_sources[:10] + ['...'] + showed_sources[-10:] - _info(__('[autosummary] generating autosummary for: %s') % - ', '.join(showed_sources)) + logger.info(__('[autosummary] generating autosummary for: %s') % + ', '.join(showed_sources)) if output_dir: - _info(__('[autosummary] writing to %s') % output_dir) + logger.info(__('[autosummary] writing to %s') % output_dir) if base_path is not None: sources = [os.path.join(base_path, filename) for filename in sources] @@ -423,7 +404,7 @@ def generate_autosummary_docs(sources: List[str], output_dir: str = None, name, obj, parent, modname = import_ivar_by_name(entry.name) qualname = name.replace(modname + ".", "") except ImportError: - _warn(__('[autosummary] failed to import %r: %s') % (entry.name, e)) + logger.warning(__('[autosummary] failed to import %r: %s') % (entry.name, e)) continue context = {} @@ -453,8 +434,8 @@ def generate_autosummary_docs(sources: List[str], output_dir: str = None, # descend recursively to new files if new_files: generate_autosummary_docs(new_files, output_dir=output_dir, - suffix=suffix, warn=warn, info=info, - base_path=base_path, + suffix=suffix, base_path=base_path, + builder=builder, template_dir=template_dir, imported_members=imported_members, app=app, overwrite=overwrite) diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py index 20afa2ec68..e48fca2486 100644 --- a/sphinx/ext/doctest.py +++ b/sphinx/ext/doctest.py @@ -13,10 +13,10 @@ import re import sys import time -import warnings from io import StringIO from os import path -from typing import Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple +from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Sequence, Set, Tuple, + Type) from docutils import nodes from docutils.nodes import Element, Node, TextElement @@ -26,17 +26,13 @@ import sphinx from sphinx.builders import Builder -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.locale import __ from sphinx.util import logging from sphinx.util.console import bold # type: ignore from sphinx.util.docutils import SphinxDirective from sphinx.util.osutil import relpath -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from sphinx.application import Sphinx @@ -46,12 +42,6 @@ doctestopt_re = re.compile(r'#\s*doctest:.+$', re.MULTILINE) -def doctest_encode(text: str, encoding: str) -> str: - warnings.warn('doctest_encode() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - return text - - def is_allowed_version(spec: str, version: str) -> bool: """Check `spec` satisfies `version` or not. diff --git a/sphinx/ext/imgconverter.py b/sphinx/ext/imgconverter.py index b0d40b551e..84fe6549c7 100644 --- a/sphinx/ext/imgconverter.py +++ b/sphinx/ext/imgconverter.py @@ -37,10 +37,10 @@ def is_available(self) -> bool: logger.debug('Invoking %r ...', args) subprocess.run(args, stdout=PIPE, stderr=PIPE, check=True) return True - except OSError: + except OSError as exc: logger.warning(__('convert command %r cannot be run, ' - 'check the image_converter setting'), - self.config.image_converter) + 'check the image_converter setting: %s'), + self.config.image_converter, exc) return False except CalledProcessError as exc: logger.warning(__('convert exited with error:\n' diff --git a/sphinx/ext/imgmath.py b/sphinx/ext/imgmath.py index cef50d548f..a0f4ddcc34 100644 --- a/sphinx/ext/imgmath.py +++ b/sphinx/ext/imgmath.py @@ -26,7 +26,6 @@ from sphinx.application import Sphinx from sphinx.builders import Builder from sphinx.config import Config -from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias from sphinx.errors import SphinxError from sphinx.locale import _, __ from sphinx.util import logging, sha1 @@ -58,35 +57,8 @@ class InvokeError(SphinxError): SUPPORT_FORMAT = ('png', 'svg') -DOC_HEAD = r''' -\documentclass[12pt]{article} -\usepackage[utf8x]{inputenc} -\usepackage{amsmath} -\usepackage{amsthm} -\usepackage{amssymb} -\usepackage{amsfonts} -\usepackage{anyfontsize} -\usepackage{bm} -\pagestyle{empty} -''' - -DOC_BODY = r''' -\begin{document} -\fontsize{%d}{%d}\selectfont %s -\end{document} -''' - -DOC_BODY_PREVIEW = r''' -\usepackage[active]{preview} -\begin{document} -\begin{preview} -\fontsize{%s}{%s}\selectfont %s -\end{preview} -\end{document} -''' - -depth_re = re.compile(br'\[\d+ depth=(-?\d+)\]') -depthsvg_re = re.compile(br'.*, depth=(.*)pt') +depth_re = re.compile(r'\[\d+ depth=(-?\d+)\]') +depthsvg_re = re.compile(r'.*, depth=(.*)pt') depthsvgcomment_re = re.compile(r'') @@ -174,10 +146,10 @@ def compile_math(latex: str, builder: Builder) -> str: raise MathExtError('latex exited with error', exc.stderr, exc.stdout) from exc -def convert_dvi_to_image(command: List[str], name: str) -> Tuple[bytes, bytes]: +def convert_dvi_to_image(command: List[str], name: str) -> Tuple[str, str]: """Convert DVI file to specific image format.""" try: - ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True) + ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True, encoding='ascii') return ret.stdout, ret.stderr except OSError as exc: logger.warning(__('%s command %r cannot be run (needed for math ' @@ -370,15 +342,6 @@ def html_visit_displaymath(self: HTMLTranslator, node: nodes.math_block) -> None raise nodes.SkipNode -deprecated_alias('sphinx.ext.imgmath', - { - 'DOC_BODY': DOC_BODY, - 'DOC_BODY_PREVIEW': DOC_BODY_PREVIEW, - 'DOC_HEAD': DOC_HEAD, - }, - RemovedInSphinx40Warning) - - def setup(app: Sphinx) -> Dict[str, Any]: app.add_html_math_renderer('imgmath', (html_visit_math, None), diff --git a/sphinx/ext/intersphinx.py b/sphinx/ext/intersphinx.py index 5569ad9ded..a01bcc37ab 100644 --- a/sphinx/ext/intersphinx.py +++ b/sphinx/ext/intersphinx.py @@ -33,10 +33,11 @@ from urllib.parse import urlsplit, urlunsplit from docutils import nodes -from docutils.nodes import Element, TextElement +from docutils.nodes import TextElement from docutils.utils import relative_path import sphinx +from sphinx.addnodes import pending_xref from sphinx.application import Sphinx from sphinx.builders.html import INVENTORY_FILENAME from sphinx.config import Config @@ -44,6 +45,7 @@ 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__) @@ -257,8 +259,8 @@ def load_mappings(app: Sphinx) -> None: inventories.main_inventory.setdefault(type, {}).update(objects) -def missing_reference(app: Sphinx, env: BuildEnvironment, node: Element, contnode: TextElement - ) -> nodes.reference: +def missing_reference(app: Sphinx, env: BuildEnvironment, node: pending_xref, + contnode: TextElement) -> nodes.reference: """Attempt to resolve a missing reference via intersphinx references.""" target = node['reftarget'] inventories = InventoryAdapter(env) @@ -284,6 +286,17 @@ def missing_reference(app: Sphinx, env: BuildEnvironment, node: Element, contnod if 'py:attribute' in objtypes: # 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) @@ -316,7 +329,7 @@ def missing_reference(app: Sphinx, env: BuildEnvironment, node: Element, contnod newnode = nodes.reference('', '', internal=False, refuri=uri, reftitle=reftitle) if node.get('refexplicit'): # use whatever title was given - newnode.append(contnode) + newnode.extend(contnodes) elif dispname == '-' or \ (domain == 'std' and node['reftype'] == 'keyword'): # use whatever title was given, but strip prefix @@ -325,7 +338,7 @@ def missing_reference(app: Sphinx, env: BuildEnvironment, node: Element, contnod newnode.append(contnode.__class__(title[len(in_set) + 1:], title[len(in_set) + 1:])) else: - newnode.append(contnode) + newnode.extend(contnodes) else: # else use the given display name (used for :ref:) newnode.append(contnode.__class__(dispname, dispname)) diff --git a/sphinx/ext/jsmath.py b/sphinx/ext/jsmath.py deleted file mode 100644 index cec40e224a..0000000000 --- a/sphinx/ext/jsmath.py +++ /dev/null @@ -1,33 +0,0 @@ -""" - sphinx.ext.jsmath - ~~~~~~~~~~~~~~~~~ - - Set up everything for use of JSMath to display math in HTML - via JavaScript. - - :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import warnings -from typing import Any, Dict - -from sphinxcontrib.jsmath import (html_visit_displaymath, html_visit_math, # NOQA - install_jsmath) - -import sphinx -from sphinx.application import Sphinx -from sphinx.deprecation import RemovedInSphinx40Warning - - -def setup(app: Sphinx) -> Dict[str, Any]: - warnings.warn('sphinx.ext.jsmath has been moved to sphinxcontrib-jsmath.', - RemovedInSphinx40Warning) - - app.setup_extension('sphinxcontrib.jsmath') - - return { - 'version': sphinx.__display_version__, - 'parallel_read_safe': True, - 'parallel_write_safe': True, - } diff --git a/sphinx/ext/mathjax.py b/sphinx/ext/mathjax.py index ff8ef37185..1cd2bd1cc1 100644 --- a/sphinx/ext/mathjax.py +++ b/sphinx/ext/mathjax.py @@ -25,8 +25,7 @@ # more information for mathjax secure url is here: # https://docs.mathjax.org/en/latest/start.html#secure-access-to-the-cdn -MATHJAX_URL = ('https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?' - 'config=TeX-AMS-MML_HTMLorMML') +MATHJAX_URL = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js' def html_visit_math(self: HTMLTranslator, node: nodes.math) -> None: diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py index bd1c445092..734adc4950 100644 --- a/sphinx/ext/napoleon/docstring.py +++ b/sphinx/ext/napoleon/docstring.py @@ -14,7 +14,7 @@ import inspect import re from functools import partial -from typing import Any, Callable, Dict, List, Tuple, Union +from typing import Any, Callable, Dict, List, Tuple, Type, Union from sphinx.application import Sphinx from sphinx.config import Config as SphinxConfig @@ -24,11 +24,6 @@ from sphinx.util.inspect import stringify_annotation from sphinx.util.typing import get_type_hints -if False: - # For type annotation - from typing import Type # for python3.5.1 - - logger = logging.getLogger(__name__) _directive_regex = re.compile(r'\.\. \S+::') @@ -723,7 +718,13 @@ def _parse_notes_section(self, section: str) -> List[str]: return self._parse_generic_section(_('Notes'), use_admonition) def _parse_other_parameters_section(self, section: str) -> List[str]: - return self._format_fields(_('Other Parameters'), self._consume_fields()) + if self._config.napoleon_use_param: + # Allow to declare multiple parameters at once (ex: x, y: int) + fields = self._consume_fields(multiple=True) + return self._format_docutils_params(fields) + else: + fields = self._consume_fields() + return self._format_fields(_('Other Parameters'), fields) def _parse_parameters_section(self, section: str) -> List[str]: if self._config.napoleon_use_param: diff --git a/sphinx/ext/todo.py b/sphinx/ext/todo.py index a73dea84d0..e0fdd31e0d 100644 --- a/sphinx/ext/todo.py +++ b/sphinx/ext/todo.py @@ -11,8 +11,7 @@ :license: BSD, see LICENSE for details. """ -import warnings -from typing import Any, Dict, Iterable, List, Tuple, cast +from typing import Any, Dict, List, Tuple, cast from docutils import nodes from docutils.nodes import Element, Node @@ -22,14 +21,12 @@ import sphinx from sphinx import addnodes from sphinx.application import Sphinx -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.domains import Domain from sphinx.environment import BuildEnvironment from sphinx.errors import NoUri from sphinx.locale import _, __ from sphinx.util import logging, texescape from sphinx.util.docutils import SphinxDirective, new_document -from sphinx.util.nodes import make_refnode from sphinx.writers.html import HTMLTranslator from sphinx.writers.latex import LaTeXTranslator @@ -104,33 +101,6 @@ def process_doc(self, env: BuildEnvironment, docname: str, location=todo) -def process_todos(app: Sphinx, doctree: nodes.document) -> None: - warnings.warn('process_todos() is deprecated.', RemovedInSphinx40Warning, stacklevel=2) - # collect all todos in the environment - # this is not done in the directive itself because it some transformations - # must have already been run, e.g. substitutions - env = app.builder.env - if not hasattr(env, 'todo_all_todos'): - env.todo_all_todos = [] # type: ignore - for node in doctree.traverse(todo_node): - app.events.emit('todo-defined', node) - - newnode = node.deepcopy() - newnode['ids'] = [] - env.todo_all_todos.append({ # type: ignore - 'docname': env.docname, - 'source': node.source or env.doc2path(env.docname), - 'lineno': node.line, - 'todo': newnode, - 'target': node['ids'][0], - }) - - if env.config.todo_emit_warnings: - label = cast(nodes.Element, node[1]) - logger.warning(__("TODO entry found: %s"), label.astext(), - location=node) - - class TodoList(SphinxDirective): """ A list of all todo entries. @@ -223,80 +193,6 @@ def resolve_reference(self, todo: todo_node, docname: str) -> None: self.document.remove(todo) -def process_todo_nodes(app: Sphinx, doctree: nodes.document, fromdocname: str) -> None: - """Replace all todolist nodes with a list of the collected todos. - Augment each todo with a backlink to the original location. - """ - warnings.warn('process_todo_nodes() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - domain = cast(TodoDomain, app.env.get_domain('todo')) - todos = sum(domain.todos.values(), []) # type: List[todo_node] - - for node in doctree.traverse(todolist): - if node.get('ids'): - content = [nodes.target()] # type: List[Element] - else: - content = [] - - if not app.config['todo_include_todos']: - node.replace_self(content) - continue - - for todo_info in todos: - para = nodes.paragraph(classes=['todo-source']) - if app.config['todo_link_only']: - description = _('<>') - else: - description = ( - _('(The <> is located in %s, line %d.)') % - (todo_info.source, todo_info.line) - ) - desc1 = description[:description.find('<<')] - desc2 = description[description.find('>>') + 2:] - para += nodes.Text(desc1, desc1) - - # Create a reference - innernode = nodes.emphasis(_('original entry'), _('original entry')) - try: - para += make_refnode(app.builder, fromdocname, todo_info['docname'], - todo_info['ids'][0], innernode) - except NoUri: - # ignore if no URI can be determined, e.g. for LaTeX output - pass - para += nodes.Text(desc2, desc2) - - todo_entry = todo_info.deepcopy() - todo_entry['ids'].clear() - - # (Recursively) resolve references in the todo content - app.env.resolve_references(todo_entry, todo_info['docname'], app.builder) # type: ignore # NOQA - - # Insert into the todolist - content.append(todo_entry) - content.append(para) - - node.replace_self(content) - - -def purge_todos(app: Sphinx, env: BuildEnvironment, docname: str) -> None: - warnings.warn('purge_todos() is deprecated.', RemovedInSphinx40Warning, stacklevel=2) - if not hasattr(env, 'todo_all_todos'): - return - env.todo_all_todos = [todo for todo in env.todo_all_todos # type: ignore - if todo['docname'] != docname] - - -def merge_info(app: Sphinx, env: BuildEnvironment, docnames: Iterable[str], - other: BuildEnvironment) -> None: - warnings.warn('merge_info() is deprecated.', RemovedInSphinx40Warning, stacklevel=2) - if not hasattr(other, 'todo_all_todos'): - return - if not hasattr(env, 'todo_all_todos'): - env.todo_all_todos = [] # type: ignore - env.todo_all_todos.extend(other.todo_all_todos) # type: ignore - - def visit_todo_node(self: HTMLTranslator, node: todo_node) -> None: if self.config.todo_include_todos: self.visit_admonition(node) diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py index 6bedf2e1c5..c98ff0c88f 100644 --- a/sphinx/ext/viewcode.py +++ b/sphinx/ext/viewcode.py @@ -146,7 +146,14 @@ def env_merge_info(app: Sphinx, env: BuildEnvironment, docnames: Iterable[str], if not hasattr(env, '_viewcode_modules'): env._viewcode_modules = {} # type: ignore # now merge in the information from the subprocess - env._viewcode_modules.update(other._viewcode_modules) # type: ignore + for modname, entry in other._viewcode_modules.items(): # type: ignore + if modname not in env._viewcode_modules: # type: ignore + env._viewcode_modules[modname] = entry # type: ignore + else: + used = env._viewcode_modules[modname][2] # type: ignore + for fullname, docname in entry[2].items(): + if fullname not in used: + used[fullname] = docname def env_purge_doc(app: Sphinx, env: BuildEnvironment, docname: str) -> None: diff --git a/sphinx/extension.py b/sphinx/extension.py index 8129d89af0..7ec6c8518c 100644 --- a/sphinx/extension.py +++ b/sphinx/extension.py @@ -8,15 +8,14 @@ :license: BSD, see LICENSE for details. """ -from typing import Any, Dict +from typing import TYPE_CHECKING, Any, Dict from sphinx.config import Config from sphinx.errors import VersionRequirementError from sphinx.locale import __ from sphinx.util import logging -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.application import Sphinx logger = logging.getLogger(__name__) diff --git a/sphinx/io.py b/sphinx/io.py index 3508dd58d1..f6ab0e1ef4 100644 --- a/sphinx/io.py +++ b/sphinx/io.py @@ -8,8 +8,7 @@ :license: BSD, see LICENSE for details. """ import codecs -import warnings -from typing import Any, List +from typing import TYPE_CHECKING, Any, List, Type from docutils import nodes from docutils.core import Publisher @@ -23,9 +22,7 @@ from docutils.writers import UnfilteredWriter from sphinx import addnodes -from sphinx.deprecation import RemovedInSphinx40Warning, deprecated_alias from sphinx.environment import BuildEnvironment -from sphinx.errors import FiletypeNotFoundError from sphinx.transforms import (AutoIndexUpgrader, DoctreeReadEvent, FigureAligner, SphinxTransformer) from sphinx.transforms.i18n import (Locale, PreserveTranslatableMessages, @@ -35,10 +32,7 @@ from sphinx.util.docutils import LoggingReporter from sphinx.versioning import UIDTransform -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from sphinx.application import Sphinx @@ -63,18 +57,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - @property - def app(self) -> "Sphinx": - warnings.warn('SphinxBaseReader.app is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - return self._app - - @property - def env(self) -> BuildEnvironment: - warnings.warn('SphinxBaseReader.env is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - return self._env - def setup(self, app: "Sphinx") -> None: self._app = app # hold application object only for compatibility self._env = app.env @@ -196,39 +178,12 @@ def read_doc(app: "Sphinx", env: BuildEnvironment, filename: str) -> nodes.docum # CommonMarkParser. parser.settings_spec = RSTParser.settings_spec - input_class = app.registry.get_source_input(filetype) - if input_class: - # Sphinx-1.8 style - source = input_class(app, env, source=None, source_path=filename, # type: ignore - encoding=env.config.source_encoding) - pub = Publisher(reader=reader, - parser=parser, - writer=SphinxDummyWriter(), - source_class=SphinxDummySourceClass, # type: ignore - destination=NullOutput()) - pub.process_programmatic_settings(None, env.settings, None) - pub.set_source(source, filename) - else: - # Sphinx-2.0 style - pub = Publisher(reader=reader, - parser=parser, - writer=SphinxDummyWriter(), - source_class=SphinxFileInput, - destination=NullOutput()) - pub.process_programmatic_settings(None, env.settings, None) - pub.set_source(source_path=filename) - + pub = Publisher(reader=reader, + parser=parser, + writer=SphinxDummyWriter(), + source_class=SphinxFileInput, + destination=NullOutput()) + pub.process_programmatic_settings(None, env.settings, None) + pub.set_source(source_path=filename) pub.publish() return pub.document - - -deprecated_alias('sphinx.io', - { - 'FiletypeNotFoundError': FiletypeNotFoundError, - 'get_filetype': get_filetype, - }, - RemovedInSphinx40Warning, - { - 'FiletypeNotFoundError': 'sphinx.errors.FiletypeNotFoundError', - 'get_filetype': 'sphinx.util.get_filetype', - }) diff --git a/sphinx/jinja2glue.py b/sphinx/jinja2glue.py index c890455f34..c239f5a4a1 100644 --- a/sphinx/jinja2glue.py +++ b/sphinx/jinja2glue.py @@ -10,7 +10,7 @@ from os import path from pprint import pformat -from typing import Any, Callable, Dict, Iterator, List, Tuple, Union +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Tuple, Union from jinja2 import BaseLoader, FileSystemLoader, TemplateNotFound, contextfunction from jinja2.environment import Environment @@ -22,8 +22,7 @@ from sphinx.util import logging from sphinx.util.osutil import mtimes_of_files -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.builders import Builder diff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py index bedd9e1cba..28dda2e1a4 100644 --- a/sphinx/locale/__init__.py +++ b/sphinx/locale/__init__.py @@ -106,7 +106,7 @@ def __repr__(self) -> str: translators = defaultdict(NullTranslations) # type: Dict[Tuple[str, str], NullTranslations] -def init(locale_dirs: List[Optional[str]], language: str, +def init(locale_dirs: List[Optional[str]], language: Optional[str], catalog: str = 'sphinx', namespace: str = 'general') -> Tuple[NullTranslations, bool]: """Look for message catalogs in `locale_dirs` and *ensure* that there is at least a NullTranslations catalog set in `translators`. If called multiple @@ -123,9 +123,11 @@ def init(locale_dirs: List[Optional[str]], language: str, if language and '_' in language: # for language having country code (like "de_AT") - languages = [language, language.split('_')[0]] - else: + languages = [language, language.split('_')[0]] # type: Optional[List[str]] + elif language: languages = [language] + else: + languages = None # loading for dir_ in locale_dirs: diff --git a/sphinx/parsers.py b/sphinx/parsers.py index 17c291af77..2ca6ef1113 100644 --- a/sphinx/parsers.py +++ b/sphinx/parsers.py @@ -9,7 +9,7 @@ """ import warnings -from typing import Any, Dict, List, Union +from typing import TYPE_CHECKING, Any, Dict, List, Type, Union import docutils.parsers import docutils.parsers.rst @@ -21,10 +21,7 @@ from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.util.rst import append_epilog, prepend_prolog -if False: - # For type annotation - from typing import Type # NOQA # for python3.5.1 - +if TYPE_CHECKING: from docutils.transforms import Transform # NOQA from sphinx.application import Sphinx @@ -73,7 +70,7 @@ def app(self) -> "Sphinx": class RSTParser(docutils.parsers.rst.Parser, Parser): """A reST parser for Sphinx.""" - def get_transforms(self) -> List["Type[Transform]"]: + def get_transforms(self) -> List[Type["Transform"]]: """Sphinx's reST parser replaces a transform class for smart-quotes by own's refs: sphinx.io.SphinxStandaloneReader diff --git a/sphinx/project.py b/sphinx/project.py index e5df4013ff..258b8d4d64 100644 --- a/sphinx/project.py +++ b/sphinx/project.py @@ -10,15 +10,15 @@ import os from glob import glob +from typing import TYPE_CHECKING from sphinx.locale import __ from sphinx.util import get_matching_files, logging, path_stabilize from sphinx.util.matching import compile_matchers from sphinx.util.osutil import SEP, relpath -if False: - # For type annotation - from typing import Dict, List, Set # NOQA +if TYPE_CHECKING: + from typing import Dict, List, Set logger = logging.getLogger(__name__) diff --git a/sphinx/pycode/__init__.py b/sphinx/pycode/__init__.py index ab0dfdbf83..aaf748559b 100644 --- a/sphinx/pycode/__init__.py +++ b/sphinx/pycode/__init__.py @@ -19,7 +19,7 @@ from typing import IO, Any, Dict, List, Optional, Tuple from zipfile import ZipFile -from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.errors import PycodeError from sphinx.pycode.parser import Parser @@ -79,7 +79,7 @@ def get_module_source(modname: str) -> Tuple[Optional[str], Optional[str]]: @classmethod def for_string(cls, string: str, modname: str, srcname: str = '' ) -> "ModuleAnalyzer": - return cls(StringIO(string), modname, srcname, decoded=True) + return cls(StringIO(string), modname, srcname) @classmethod def for_file(cls, filename: str, modname: str) -> "ModuleAnalyzer": @@ -87,7 +87,7 @@ def for_file(cls, filename: str, modname: str) -> "ModuleAnalyzer": return cls.cache['file', filename] try: with tokenize.open(filename) as f: - obj = cls(f, modname, filename, decoded=True) + obj = cls(f, modname, filename) cls.cache['file', filename] = obj except Exception as err: if '.egg' + path.sep in filename: @@ -127,21 +127,12 @@ def for_module(cls, modname: str) -> "ModuleAnalyzer": cls.cache['module', modname] = obj return obj - def __init__(self, source: IO, modname: str, srcname: str, decoded: bool = False) -> None: + def __init__(self, source: IO, modname: str, srcname: str) -> None: self.modname = modname # name of the module self.srcname = srcname # name of the source file # cache the source code as well - pos = source.tell() - if not decoded: - warnings.warn('decode option for ModuleAnalyzer is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - self._encoding, _ = tokenize.detect_encoding(source.readline) - source.seek(pos) - self.code = source.read().decode(self._encoding) - else: - self._encoding = None - self.code = source.read() + self.code = source.read() # will be filled by analyze() self.annotations = None # type: Dict[Tuple[str, str], str] @@ -164,7 +155,7 @@ def analyze(self) -> None: return None try: - parser = Parser(self.code, self._encoding) + parser = Parser(self.code) parser.parse() self.attr_docs = OrderedDict() @@ -192,9 +183,3 @@ def find_tags(self) -> Dict[str, Tuple[str, int, int]]: """Find class, function and method definitions and their location.""" self.analyze() return self.tags - - @property - def encoding(self) -> str: - warnings.warn('ModuleAnalyzer.encoding is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - return self._encoding diff --git a/sphinx/pycode/ast.py b/sphinx/pycode/ast.py index 65534f9583..e4e773b252 100644 --- a/sphinx/pycode/ast.py +++ b/sphinx/pycode/ast.py @@ -9,7 +9,7 @@ """ import sys -from typing import Dict, List, Optional, Type +from typing import Dict, List, Optional, Type, overload if sys.version_info > (3, 8): import ast @@ -62,6 +62,16 @@ def parse(code: str, mode: str = 'exec') -> "ast.AST": return ast.parse(code, mode=mode) +@overload +def unparse(node: None, code: str = '') -> None: + ... + + +@overload +def unparse(node: ast.AST, code: str = '') -> str: + ... + + def unparse(node: Optional[ast.AST], code: str = '') -> Optional[str]: """Unparse an AST to string.""" if node is None: @@ -98,7 +108,7 @@ def _visit_arg_with_default(self, arg: ast.arg, default: Optional[ast.AST]) -> s return name def visit_arguments(self, node: ast.arguments) -> str: - defaults = list(node.defaults) + defaults = list(node.defaults) # type: List[Optional[ast.expr]] positionals = len(node.args) posonlyargs = 0 if hasattr(node, "posonlyargs"): # for py38+ @@ -107,7 +117,7 @@ def visit_arguments(self, node: ast.arguments) -> str: for _ in range(len(defaults), positionals): defaults.insert(0, None) - kw_defaults = list(node.kw_defaults) + kw_defaults = list(node.kw_defaults) # type: List[Optional[ast.expr]] for _ in range(len(kw_defaults), len(node.kwonlyargs)): kw_defaults.insert(0, None) @@ -150,6 +160,17 @@ def visit_Call(self, node: ast.Call) -> str: ["%s=%s" % (k.arg, self.visit(k.value)) for k in node.keywords]) return "%s(%s)" % (self.visit(node.func), ", ".join(args)) + def visit_Constant(self, node: ast.Constant) -> str: # type: ignore + if node.value is Ellipsis: + return "..." + elif isinstance(node.value, (int, float, complex)): + if self.code and sys.version_info > (3, 8): + return ast.get_source_segment(self.code, node) # type: ignore + else: + return repr(node.value) + else: + return repr(node.value) + def visit_Dict(self, node: ast.Dict) -> str: keys = (self.visit(k) for k in node.keys) values = (self.visit(v) for v in node.values) @@ -197,18 +218,6 @@ def visit_Tuple(self, node: ast.Tuple) -> str: else: return "()" - if sys.version_info >= (3, 6): - def visit_Constant(self, node: ast.Constant) -> str: - if node.value is Ellipsis: - return "..." - elif isinstance(node.value, (int, float, complex)): - if self.code and sys.version_info > (3, 8): - return ast.get_source_segment(self.code, node) - else: - return repr(node.value) - else: - return repr(node.value) - if sys.version_info < (3, 8): # these ast nodes were deprecated in python 3.8 def visit_Bytes(self, node: ast.Bytes) -> str: diff --git a/sphinx/pycode/parser.py b/sphinx/pycode/parser.py index dca59acd4f..d157c7c1c5 100644 --- a/sphinx/pycode/parser.py +++ b/sphinx/pycode/parser.py @@ -10,7 +10,6 @@ import inspect import itertools import re -import sys import tokenize from collections import OrderedDict from inspect import Signature @@ -26,12 +25,6 @@ emptyline_re = re.compile('^\\s*(#.*)?$') -if sys.version_info >= (3, 6): - ASSIGN_NODES = (ast.Assign, ast.AnnAssign) -else: - ASSIGN_NODES = (ast.Assign) - - def filter_whitespace(code: str) -> str: return code.replace('\f', ' ') # replace FF (form feed) with whitespace @@ -94,7 +87,10 @@ def dummy() -> None: dummy.__doc__ = s docstring = inspect.getdoc(dummy) - return docstring.lstrip("\r\n").rstrip("\r\n") + if docstring: + return docstring.lstrip("\r\n").rstrip("\r\n") + else: + return "" class Token: @@ -398,13 +394,14 @@ def visit_Assign(self, node: ast.Assign) -> None: for varname in varnames: self.add_entry(varname) - def visit_AnnAssign(self, node: ast.AST) -> None: # Note: ast.AnnAssign not found in py35 + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: """Handles AnnAssign node and pick up a variable comment.""" self.visit_Assign(node) # type: ignore def visit_Expr(self, node: ast.Expr) -> None: """Handles Expr node and pick up a comment if string.""" - if (isinstance(self.previous, ASSIGN_NODES) and isinstance(node.value, ast.Str)): + if (isinstance(self.previous, (ast.Assign, ast.AnnAssign)) and + isinstance(node.value, ast.Str)): try: targets = get_assign_targets(self.previous) varnames = get_lvar_names(targets[0], self.get_self()) diff --git a/sphinx/registry.py b/sphinx/registry.py index c6a249e74c..cd7a7f4a03 100644 --- a/sphinx/registry.py +++ b/sphinx/registry.py @@ -9,9 +9,10 @@ """ import traceback +import warnings from importlib import import_module from types import MethodType -from typing import Any, Callable, Dict, Iterator, List, Tuple, Union +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Tuple, Type, Union from docutils import nodes from docutils.io import Input @@ -23,6 +24,7 @@ from sphinx.builders import Builder from sphinx.config import Config +from sphinx.deprecation import RemovedInSphinx60Warning from sphinx.domains import Domain, Index, ObjType from sphinx.domains.std import GenericObject, Target from sphinx.environment import BuildEnvironment @@ -35,10 +37,7 @@ from sphinx.util.logging import prefixed_warnings from sphinx.util.typing import RoleFunction, TitleGetter -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.ext.autodoc import Documenter @@ -288,6 +287,9 @@ def create_source_parser(self, app: "Sphinx", filename: str) -> Parser: return parser def get_source_input(self, filetype: str) -> "Type[Input]": + warnings.warn('SphinxComponentRegistry.get_source_input() is deprecated.', + RemovedInSphinx60Warning) + try: return self.source_inputs[filetype] except KeyError: diff --git a/sphinx/roles.py b/sphinx/roles.py index 4f9261360d..c3f594cbb2 100644 --- a/sphinx/roles.py +++ b/sphinx/roles.py @@ -9,25 +9,18 @@ """ import re -import warnings -from typing import Any, Dict, List, Tuple +from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type from docutils import nodes, utils from docutils.nodes import Element, Node, TextElement, system_message -from docutils.parsers.rst.states import Inliner from sphinx import addnodes -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.locale import _ from sphinx.util import ws_re from sphinx.util.docutils import ReferenceRole, SphinxRole -from sphinx.util.nodes import process_index_entry, set_role_source_info, split_explicit_title from sphinx.util.typing import RoleFunction -if False: - # For type annotation - from typing import Type # for python3.5.1 - +if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.environment import BuildEnvironment @@ -88,22 +81,6 @@ def __init__(self, fix_parens: bool = False, lowercase: bool = False, super().__init__() - def _fix_parens(self, env: "BuildEnvironment", has_explicit_title: bool, title: str, - target: str) -> Tuple[str, str]: - warnings.warn('XRefRole._fix_parens() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - if not has_explicit_title: - if title.endswith('()'): - # remove parentheses - title = title[:-2] - if env.config.add_function_parentheses: - # add them back to all occurrences if configured - title += '()' - # remove parentheses from the target too - if target.endswith('()'): - target = target[:-2] - return title, target - def update_title_and_target(self, title: str, target: str) -> Tuple[str, str]: if not self.has_explicit_title: if title.endswith('()'): @@ -194,75 +171,6 @@ def process_link(self, env: "BuildEnvironment", refnode: Element, has_explicit_t return result -def indexmarkup_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner, - options: Dict = {}, content: List[str] = [] - ) -> Tuple[List[Node], List[system_message]]: - """Role for PEP/RFC references that generate an index entry.""" - warnings.warn('indexmarkup_role() is deprecated. Please use PEP or RFC class instead.', - RemovedInSphinx40Warning, stacklevel=2) - env = inliner.document.settings.env - if not typ: - assert env.temp_data['default_role'] - typ = env.temp_data['default_role'].lower() - else: - typ = typ.lower() - - has_explicit_title, title, target = split_explicit_title(text) - title = utils.unescape(title) - target = utils.unescape(target) - targetid = 'index-%s' % env.new_serialno('index') - indexnode = addnodes.index() - targetnode = nodes.target('', '', ids=[targetid]) - inliner.document.note_explicit_target(targetnode) - if typ == 'pep': - indexnode['entries'] = [ - ('single', _('Python Enhancement Proposals; PEP %s') % target, - targetid, '', None)] - anchor = '' - anchorindex = target.find('#') - if anchorindex > 0: - target, anchor = target[:anchorindex], target[anchorindex:] - if not has_explicit_title: - title = "PEP " + utils.unescape(title) - try: - pepnum = int(target) - except ValueError: - msg = inliner.reporter.error('invalid PEP number %s' % target, - line=lineno) - prb = inliner.problematic(rawtext, rawtext, msg) - return [prb], [msg] - ref = inliner.document.settings.pep_base_url + 'pep-%04d' % pepnum - sn = nodes.strong(title, title) - rn = nodes.reference('', '', internal=False, refuri=ref + anchor, - classes=[typ]) - rn += sn - return [indexnode, targetnode, rn], [] - elif typ == 'rfc': - indexnode['entries'] = [ - ('single', 'RFC; RFC %s' % target, targetid, '', None)] - anchor = '' - anchorindex = target.find('#') - if anchorindex > 0: - target, anchor = target[:anchorindex], target[anchorindex:] - if not has_explicit_title: - title = "RFC " + utils.unescape(title) - try: - rfcnum = int(target) - except ValueError: - msg = inliner.reporter.error('invalid RFC number %s' % target, - line=lineno) - prb = inliner.problematic(rawtext, rawtext, msg) - return [prb], [msg] - ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum - sn = nodes.strong(title, title) - rn = nodes.reference('', '', internal=False, refuri=ref + anchor, - classes=[typ]) - rn += sn - return [indexnode, targetnode, rn], [] - else: - raise ValueError('unknown role type: %s' % typ) - - class PEP(ReferenceRole): def run(self) -> Tuple[List[Node], List[system_message]]: target_id = 'index-%s' % self.env.new_serialno('index') @@ -335,44 +243,6 @@ def build_uri(self) -> str: _amp_re = re.compile(r'(? Tuple[List[Node], List[system_message]]: - warnings.warn('menusel_role() is deprecated. ' - 'Please use MenuSelection or GUILabel class instead.', - RemovedInSphinx40Warning, stacklevel=2) - env = inliner.document.settings.env - if not typ: - assert env.temp_data['default_role'] - typ = env.temp_data['default_role'].lower() - else: - typ = typ.lower() - - text = utils.unescape(text) - if typ == 'menuselection': - text = text.replace('-->', '\N{TRIANGULAR BULLET}') - spans = _amp_re.split(text) - - node = nodes.inline(rawtext=rawtext) - for i, span in enumerate(spans): - span = span.replace('&&', '&') - if i == 0: - if len(span) > 0: - textnode = nodes.Text(span) - node += textnode - continue - accel_node = nodes.inline() - letter_node = nodes.Text(span[0]) - accel_node += letter_node - accel_node['classes'].append('accelerator') - node += accel_node - textnode = nodes.Text(span[1:]) - node += textnode - - node['classes'].append(typ) - return [node], [] - - class GUILabel(SphinxRole): amp_re = re.compile(r'(? Tuple[List[Node], List[system_message]]: parens_re = re.compile(r'(\\*{|\\*})') -def emph_literal_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner, - options: Dict = {}, content: List[str] = [] - ) -> Tuple[List[Node], List[system_message]]: - warnings.warn('emph_literal_role() is deprecated. ' - 'Please use EmphasizedLiteral class instead.', - RemovedInSphinx40Warning, stacklevel=2) - env = inliner.document.settings.env - if not typ: - assert env.temp_data['default_role'] - typ = env.temp_data['default_role'].lower() - else: - typ = typ.lower() - - retnode = nodes.literal(role=typ.lower(), classes=[typ]) - parts = list(parens_re.split(utils.unescape(text))) - stack = [''] - for part in parts: - matched = parens_re.match(part) - if matched: - backslashes = len(part) - 1 - if backslashes % 2 == 1: # escaped - stack[-1] += "\\" * int((backslashes - 1) / 2) + part[-1] - elif part[-1] == '{': # rparen - stack[-1] += "\\" * int(backslashes / 2) - if len(stack) >= 2 and stack[-2] == "{": - # nested - stack[-1] += "{" - else: - # start emphasis - stack.append('{') - stack.append('') - else: # lparen - stack[-1] += "\\" * int(backslashes / 2) - if len(stack) == 3 and stack[1] == "{" and len(stack[2]) > 0: - # emphasized word found - if stack[0]: - retnode += nodes.Text(stack[0], stack[0]) - retnode += nodes.emphasis(stack[2], stack[2]) - stack = [''] - else: - # emphasized word not found; the rparen is not a special symbol - stack.append('}') - stack = [''.join(stack)] - else: - stack[-1] += part - if ''.join(stack): - # remaining is treated as Text - text = ''.join(stack) - retnode += nodes.Text(text, text) - - return [retnode], [] - - class EmphasizedLiteral(SphinxRole): parens_re = re.compile(r'(\\\\|\\{|\\}|{|})') @@ -509,22 +326,6 @@ def parse(self, text: str) -> List[Node]: _abbr_re = re.compile(r'\((.*)\)$', re.S) -def abbr_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner, - options: Dict = {}, content: List[str] = [] - ) -> Tuple[List[Node], List[system_message]]: - warnings.warn('abbr_role() is deprecated. Please use Abbrevation class instead.', - RemovedInSphinx40Warning, stacklevel=2) - text = utils.unescape(text) - m = _abbr_re.search(text) - if m is None: - return [nodes.abbreviation(text, text, **options)], [] - abbr = text[:m.start()].strip() - expl = m.group(1) - options = options.copy() - options['explanation'] = expl - return [nodes.abbreviation(abbr, abbr, **options)], [] - - class Abbreviation(SphinxRole): abbr_re = re.compile(r'\((.*)\)$', re.S) @@ -540,62 +341,6 @@ def run(self) -> Tuple[List[Node], List[system_message]]: return [nodes.abbreviation(self.rawtext, text, **options)], [] -def index_role(typ: str, rawtext: str, text: str, lineno: int, inliner: Inliner, - options: Dict = {}, content: List[str] = [] - ) -> Tuple[List[Node], List[system_message]]: - warnings.warn('index_role() is deprecated. Please use Index class instead.', - RemovedInSphinx40Warning, stacklevel=2) - # create new reference target - env = inliner.document.settings.env - targetid = 'index-%s' % env.new_serialno('index') - targetnode = nodes.target('', '', ids=[targetid]) - # split text and target in role content - has_explicit_title, title, target = split_explicit_title(text) - title = utils.unescape(title) - target = utils.unescape(target) - # if an explicit target is given, we can process it as a full entry - if has_explicit_title: - entries = process_index_entry(target, targetid) - # otherwise we just create a "single" entry - else: - # but allow giving main entry - main = '' - if target.startswith('!'): - target = target[1:] - title = title[1:] - main = 'main' - entries = [('single', target, targetid, main, None)] - indexnode = addnodes.index() - indexnode['entries'] = entries - set_role_source_info(inliner, lineno, indexnode) - textnode = nodes.Text(title, title) - return [indexnode, targetnode, textnode], [] - - -class Index(ReferenceRole): - def run(self) -> Tuple[List[Node], List[system_message]]: - warnings.warn('Index role is deprecated.', RemovedInSphinx40Warning, stacklevel=2) - target_id = 'index-%s' % self.env.new_serialno('index') - if self.has_explicit_title: - # if an explicit target is given, process it as a full entry - title = self.title - entries = process_index_entry(self.target, target_id) - else: - # otherwise we just create a single entry - if self.target.startswith('!'): - title = self.title[1:] - entries = [('single', self.target[1:], target_id, 'main', None)] - else: - title = self.title - entries = [('single', self.target, target_id, '', None)] - - index = addnodes.index(entries=entries) - target = nodes.target('', '', ids=[target_id]) - text = nodes.Text(title, title) - self.set_source_info(index) - return [index, target, text], [] - - specific_docroles = { # links to download references 'download': XRefRole(nodeclass=addnodes.download_reference), diff --git a/sphinx/search/__init__.py b/sphinx/search/__init__.py index cd099a6b5c..2c06385311 100644 --- a/sphinx/search/__init__.py +++ b/sphinx/search/__init__.py @@ -10,24 +10,18 @@ import html import pickle import re -import warnings from importlib import import_module from os import path -from typing import IO, Any, Dict, Iterable, List, Set, Tuple +from typing import IO, Any, Dict, Iterable, List, Set, Tuple, Type from docutils import nodes from docutils.nodes import Node from sphinx import addnodes, package_dir -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.environment import BuildEnvironment from sphinx.search.jssplitter import splitter_code from sphinx.util import jsdump -if False: - # For type annotation - from typing import Type # for python3.5.1 - class SearchLanguage: """ @@ -116,7 +110,7 @@ def word_filter(self, word: str) -> bool: len(word) == 0 or not ( ((len(word) < 3) and (12353 < ord(word[0]) < 12436)) or (ord(word[0]) < 256 and ( - len(word) < 3 or word in self.stopwords + word in self.stopwords )))) @@ -199,11 +193,7 @@ def __init__(self, document: nodes.document, lang: SearchLanguage) -> None: self.found_title_words = [] # type: List[str] self.lang = lang - def is_meta_keywords(self, node: addnodes.meta, nodetype: Any = None) -> bool: - if nodetype is not None: - warnings.warn('"nodetype" argument for WordCollector.is_meta_keywords() ' - 'is deprecated.', RemovedInSphinx40Warning, stacklevel=2) - + def is_meta_keywords(self, node: addnodes.meta) -> bool: if isinstance(node, addnodes.meta) and node.get('name') == 'keywords': meta_lang = node.get('lang') if meta_lang is None: # lang not specified diff --git a/sphinx/setup_command.py b/sphinx/setup_command.py index 0a30ff82fe..a508c50a1c 100644 --- a/sphinx/setup_command.py +++ b/sphinx/setup_command.py @@ -16,6 +16,7 @@ from distutils.cmd import Command from distutils.errors import DistutilsExecError from io import StringIO +from typing import TYPE_CHECKING from sphinx.application import Sphinx from sphinx.cmd.build import handle_exception @@ -23,9 +24,8 @@ from sphinx.util.docutils import docutils_namespace, patch_docutils from sphinx.util.osutil import abspath -if False: - # For type annotation - from typing import Any, Dict # NOQA +if TYPE_CHECKING: + from typing import Any, Dict class BuildDoc(Command): @@ -190,6 +190,6 @@ def run(self): if not self.link_index: continue - src = app.config.master_doc + app.builder.out_suffix # type: ignore + src = app.config.root_doc + app.builder.out_suffix # type: ignore dst = app.builder.get_outfilename('index') # type: ignore os.symlink(src, dst) diff --git a/sphinx/templates/htmlhelp/project.hhc b/sphinx/templates/htmlhelp/project.hhc index c1096e7114..705cfeba7d 100644 --- a/sphinx/templates/htmlhelp/project.hhc +++ b/sphinx/templates/htmlhelp/project.hhc @@ -18,7 +18,7 @@
  • - {{ sitemap(short_title, master_doc)|indent(8) }} + {{ sitemap(short_title, root_doc)|indent(8) }}
  • {%- for indexname, indexcls, content, collapse in domain_indices %}
  • diff --git a/sphinx/templates/htmlhelp/project.hhp b/sphinx/templates/htmlhelp/project.hhp index b647b37138..17edc1f3dc 100644 --- a/sphinx/templates/htmlhelp/project.hhp +++ b/sphinx/templates/htmlhelp/project.hhp @@ -4,7 +4,7 @@ Binary Index=No Compiled file={{ outname }}.chm Contents file={{ outname }}.hhc Default Window={{ outname }} -Default topic={{ master_doc }} +Default topic={{ root_doc }} Display compile progress=No Full text search stop list file={{ outname }}.stp Full-text search=Yes @@ -13,7 +13,7 @@ Language={{ "%#x"|format(lcid) }} Title={{ title }} [WINDOWS] -{{ outname }}="{{ title }}","{{ outname }}.hhc","{{ outname }}.hhk","{{ master_doc }}","{{ master_doc }}",,,,,0x63520,220,0x10384e,[0,0,1024,768],,,,,,,0 +{{ outname }}="{{ title }}","{{ outname }}.hhc","{{ outname }}.hhk","{{ root_doc }}","{{ root_doc }}",,,,,0x63520,220,0x10384e,[0,0,1024,768],,,,,,,0 [FILES] {%- for filename in files %} diff --git a/sphinx/templates/latex/latex.tex_t b/sphinx/templates/latex/latex.tex_t index e288dda938..679660fdd7 100644 --- a/sphinx/templates/latex/latex.tex_t +++ b/sphinx/templates/latex/latex.tex_t @@ -13,6 +13,9 @@ \ifdefined\pdfpxdimen \let\sphinxpxdimen\pdfpxdimen\else\newdimen\sphinxpxdimen \fi \sphinxpxdimen=<%= pxunit %>\relax +\ifdefined\pdfimageresolution + \pdfimageresolution= \numexpr \dimexpr1in\relax/\sphinxpxdimen\relax +\fi <% if use_xindy -%> %% turn off hyperref patch of \index as sphinx.xdy xindy module takes care of %% suitable \hyperpage mark-up, working around hyperref-xindy incompatibility @@ -32,6 +35,7 @@ <%= substitutefont %> <%= textcyrillic %> <%= fontpkg %> +<%= fontsubstitution %> <%= textgreek %> <%= fncychap %> \usepackage<%= sphinxpkgoptions %>{sphinx} diff --git a/sphinx/templates/quickstart/Makefile_t b/sphinx/templates/quickstart/Makefile_t index af9c56304c..14b2dc5943 100644 --- a/sphinx/templates/quickstart/Makefile_t +++ b/sphinx/templates/quickstart/Makefile_t @@ -46,6 +46,7 @@ help: @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" @echo " dummy to check syntax errors of document sources" + @echo " clean to remove everything in the build directory" .PHONY: clean clean: diff --git a/sphinx/templates/quickstart/conf.py_t b/sphinx/templates/quickstart/conf.py_t index 8a20fc4c8a..0c5285f9ec 100644 --- a/sphinx/templates/quickstart/conf.py_t +++ b/sphinx/templates/quickstart/conf.py_t @@ -64,9 +64,9 @@ templates_path = ['{{ dot }}templates'] source_suffix = {{ suffix | repr }} {% endif -%} -{% if master != 'index' -%} -# The master toctree document. -master_doc = {{ master | repr }} +{% if root_doc != 'index' -%} +# The root document. +root_doc = {{ root_doc | repr }} {% endif -%} {% if language -%} diff --git a/sphinx/templates/quickstart/make.bat_t b/sphinx/templates/quickstart/make.bat_t index 830cf656e3..e5d93d1aed 100644 --- a/sphinx/templates/quickstart/make.bat_t +++ b/sphinx/templates/quickstart/make.bat_t @@ -43,6 +43,7 @@ if "%1" == "help" ( echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled echo. dummy to check syntax errors of document sources + echo. clean to remove everything in the build directory goto end ) diff --git a/sphinx/templates/quickstart/master_doc.rst_t b/sphinx/templates/quickstart/root_doc.rst_t similarity index 100% rename from sphinx/templates/quickstart/master_doc.rst_t rename to sphinx/templates/quickstart/root_doc.rst_t diff --git a/sphinx/testing/fixtures.py b/sphinx/testing/fixtures.py index 1cf66283f0..c284208cec 100644 --- a/sphinx/testing/fixtures.py +++ b/sphinx/testing/fixtures.py @@ -8,7 +8,6 @@ :license: BSD, see LICENSE for details. """ -import os import subprocess import sys from collections import namedtuple @@ -90,7 +89,6 @@ def app_params(request: Any, test_params: Dict, shared_result: SharedResult, args = [pargs[i] for i in sorted(pargs.keys())] # ##### process pytest.mark.test_params - if test_params['shared_result']: if 'srcdir' in kwargs: raise pytest.Exception('You can not specify shared_result and ' @@ -236,10 +234,7 @@ def sphinx_test_tempdir(tmpdir_factory: Any) -> "util.path": """ temporary directory that wrapped with `path` class. """ - tmpdir = os.environ.get('SPHINX_TEST_TEMPDIR') # RemovedInSphinx40Warning - if tmpdir is None: - tmpdir = tmpdir_factory.getbasetemp() - + tmpdir = tmpdir_factory.getbasetemp() return util.path(tmpdir).abspath() diff --git a/sphinx/testing/util.py b/sphinx/testing/util.py index 7d0cde143a..7868f4d625 100644 --- a/sphinx/testing/util.py +++ b/sphinx/testing/util.py @@ -21,15 +21,12 @@ from docutils.parsers.rst import directives, roles from sphinx import application, locale -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.pycode import ModuleAnalyzer from sphinx.testing.path import path from sphinx.util.osutil import relpath __all__ = [ - 'Struct', - 'SphinxTestApp', 'SphinxTestAppWrapperForSkipBuilding', - 'remove_unicode_literals', + 'Struct', 'SphinxTestApp', 'SphinxTestAppWrapperForSkipBuilding', ] @@ -177,12 +174,6 @@ def build(self, *args: Any, **kwargs: Any) -> None: _unicode_literals_re = re.compile(r'u(".*?")|u(\'.*?\')') -def remove_unicode_literals(s: str) -> str: - warnings.warn('remove_unicode_literals() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - return _unicode_literals_re.sub(lambda x: x.group(1) or x.group(2), s) - - def find_files(root: str, suffix: bool = None) -> Generator[str, None, None]: for dirpath, dirs, files in os.walk(root, followlinks=True): dirpath = path(dirpath) diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty index e6c27c123e..a71c64ffca 100644 --- a/sphinx/texinputs/sphinx.sty +++ b/sphinx/texinputs/sphinx.sty @@ -6,7 +6,7 @@ % \NeedsTeXFormat{LaTeX2e}[1995/12/01] -\ProvidesPackage{sphinx}[2021/01/23 v3.5.0 LaTeX package (Sphinx markup)] +\ProvidesPackage{sphinx}[2021/01/27 v4.0.0 LaTeX package (Sphinx markup)] % provides \ltx@ifundefined % (many packages load ltxcmds: graphicx does for pdftex and lualatex but @@ -31,262 +31,20 @@ }} -%% PACKAGES -% -% we delay handling of options to after having loaded packages, because -% of the need to use \definecolor. -\RequirePackage{graphicx} -\@ifclassloaded{memoir}{}{\RequirePackage{fancyhdr}} -% for \text macro and \iffirstchoice@ conditional even if amsmath not loaded -\RequirePackage{amstext} -\RequirePackage{textcomp}% "warn" option issued from template -\RequirePackage[nobottomtitles*]{titlesec} -\@ifpackagelater{titlesec}{2016/03/15}% - {\@ifpackagelater{titlesec}{2016/03/21}% - {}% - {\newif\ifsphinx@ttlpatch@ok - \IfFileExists{etoolbox.sty}{% - \RequirePackage{etoolbox}% - \patchcmd{\ttlh@hang}{\parindent\z@}{\parindent\z@\leavevmode}% - {\sphinx@ttlpatch@oktrue}{}% - \ifsphinx@ttlpatch@ok - \patchcmd{\ttlh@hang}{\noindent}{}{}{\sphinx@ttlpatch@okfalse}% - \fi - }{}% - \ifsphinx@ttlpatch@ok - \typeout{^^J Package Sphinx Info: ^^J - **** titlesec 2.10.1 successfully patched for bugfix ****^^J}% - \else - \AtEndDocument{\PackageWarningNoLine{sphinx}{^^J% -******** titlesec 2.10.1 has a bug, (section numbers disappear) ......|^^J% -******** and Sphinx could not patch it, perhaps because your local ...|^^J% -******** copy is already fixed without a changed release date. .......|^^J% -******** If not, you must update titlesec! ...........................|}}% - \fi - }% - }{} -\RequirePackage{tabulary} -% tabulary has a bug with its re-definition of \multicolumn in its first pass -% which is not \long. But now Sphinx does not use LaTeX's \multicolumn but its -% own macro. Hence we don't even need to patch tabulary. See sphinxmulticell.sty -% X or S (Sphinx) may have meanings if some table package is loaded hence -% \X was chosen to avoid possibility of conflict -\newcolumntype{\X}[2]{p{\dimexpr - (\linewidth-\arrayrulewidth)*#1/#2-\tw@\tabcolsep-\arrayrulewidth\relax}} -\newcolumntype{\Y}[1]{p{\dimexpr - #1\dimexpr\linewidth-\arrayrulewidth\relax-\tw@\tabcolsep-\arrayrulewidth\relax}} -% using here T (for Tabulary) feels less of a problem than the X could be -\newcolumntype{T}{J}% -% For tables allowing pagebreaks -\RequirePackage{longtable} -% User interface to set-up whitespace before and after tables: -\newcommand*\sphinxtablepre {0pt}% -\newcommand*\sphinxtablepost{\medskipamount}% -% Space from caption baseline to top of table or frame of literal-block -\newcommand*\sphinxbelowcaptionspace{.5\sphinxbaselineskip}% -% as one can not use \baselineskip from inside longtable (it is zero there) -% we need \sphinxbaselineskip, which defaults to \baselineskip -\def\sphinxbaselineskip{\baselineskip}% -% The following is to ensure that, whether tabular(y) or longtable: -% - if a caption is on top of table: -% a) the space between its last baseline and the top rule of table is -% exactly \sphinxbelowcaptionspace -% b) the space from last baseline of previous text to first baseline of -% caption is exactly \parskip+\baselineskip+ height of a strut. -% c) the caption text will wrap at width \LTcapwidth (4in) -% - make sure this works also if "caption" package is loaded by user -% (with its width or margin option taking place of \LTcapwidth role) -% TODO: obtain same for caption of literal block: a) & c) DONE, b) TO BE DONE +%% OPTION HANDLING % -% To modify space below such top caption, adjust \sphinxbelowcaptionspace -% To add or remove space above such top caption, adjust \sphinxtablepre: -% notice that \abovecaptionskip, \belowcaptionskip, \LTpre are **ignored** -% A. Table with longtable -\def\sphinxatlongtablestart - {\par - \vskip\parskip - \vskip\dimexpr\sphinxtablepre\relax % adjust vertical position - \vbox{}% get correct baseline from above - \LTpre\z@skip\LTpost\z@skip % set to zero longtable's own skips - \edef\sphinxbaselineskip{\dimexpr\the\dimexpr\baselineskip\relax\relax}% - }% -% Compatibility with caption package -\def\sphinxthelongtablecaptionisattop{% - \spx@ifcaptionpackage{\noalign{\vskip-\belowcaptionskip}}{}% -}% -% Achieves exactly \sphinxbelowcaptionspace below longtable caption -\def\sphinxlongtablecapskipadjust - {\dimexpr-\dp\strutbox - -\spx@ifcaptionpackage{\abovecaptionskip}{\sphinxbaselineskip}% - +\sphinxbelowcaptionspace\relax}% -\def\sphinxatlongtableend{\@nobreakfalse % latex3/latex2e#173 - \prevdepth\z@\vskip\sphinxtablepost\relax}% -% B. Table with tabular or tabulary -\def\sphinxattablestart{\par\vskip\dimexpr\sphinxtablepre\relax}% -\let\sphinxattableend\sphinxatlongtableend -% This is used by tabular and tabulary templates -\newcommand*\sphinxcapstartof[1]{% - \vskip\parskip - \vbox{}% force baselineskip for good positioning by capstart of hyperanchor - % hyperref puts the anchor 6pt above this baseline; in case of caption - % this baseline will be \ht\strutbox above first baseline of caption - \def\@captype{#1}% - \capstart -% move back vertically, as tabular (or its caption) will compensate - \vskip-\baselineskip\vskip-\parskip -}% -\def\sphinxthecaptionisattop{% locate it after \sphinxcapstartof - \spx@ifcaptionpackage - {\caption@setposition{t}% - \vskip\baselineskip\vskip\parskip % undo those from \sphinxcapstartof - \vskip-\belowcaptionskip % anticipate caption package skip - % caption package uses a \vbox, not a \vtop, so "single line" case - % gives different result from "multi-line" without this: - \nointerlineskip - }% - {}% -}% -\def\sphinxthecaptionisatbottom{% (not finalized; for template usage) - \spx@ifcaptionpackage{\caption@setposition{b}}{}% -}% -% The aim of \sphinxcaption is to apply to tabular(y) the maximal width -% of caption as done by longtable -\def\sphinxtablecapwidth{\LTcapwidth}% -\newcommand\sphinxcaption{\@dblarg\spx@caption}% -\long\def\spx@caption[#1]#2{% - \noindent\hb@xt@\linewidth{\hss - \vtop{\@tempdima\dimexpr\sphinxtablecapwidth\relax -% don't exceed linewidth for the caption width - \ifdim\@tempdima>\linewidth\hsize\linewidth\else\hsize\@tempdima\fi -% longtable ignores \abovecaptionskip/\belowcaptionskip, so do the same here - \abovecaptionskip\sphinxabovecaptionskip % \z@skip - \belowcaptionskip\sphinxbelowcaptionskip % \z@skip - \caption[{#1}]% - {\strut\ignorespaces#2\ifhmode\unskip\@finalstrut\strutbox\fi}% - }\hss}% - \par\prevdepth\dp\strutbox -}% -\def\sphinxabovecaptionskip{\z@skip}% Do not use! Flagged for removal -\def\sphinxbelowcaptionskip{\z@skip}% Do not use! Flagged for removal -% This wrapper of \abovecaptionskip is used in sphinxVerbatim for top -% caption, and with another value in sphinxVerbatimintable -% TODO: To unify space above caption of a code-block with the one above -% caption of a table/longtable, \abovecaptionskip must not be used -% This auxiliary will get renamed and receive a different meaning -% in future. -\def\spx@abovecaptionskip{\abovecaptionskip}% -% Achieve \sphinxbelowcaptionspace below a caption located above a tabular -% or a tabulary -\newcommand\sphinxaftertopcaption -{% - \spx@ifcaptionpackage - {\par\prevdepth\dp\strutbox\nobreak\vskip-\abovecaptionskip}{\nobreak}% - \vskip\dimexpr\sphinxbelowcaptionspace\relax - \vskip-\baselineskip\vskip-\parskip -}% -% varwidth is crucial for our handling of general contents in merged cells -\RequirePackage{varwidth} -% but addition of a compatibility patch with hyperref is needed -% (tested with varwidth v 0.92 Mar 2009) -\AtBeginDocument {% - \let\@@vwid@Hy@raisedlink\Hy@raisedlink - \long\def\@vwid@Hy@raisedlink#1{\@vwid@wrap{\@@vwid@Hy@raisedlink{#1}}}% - \edef\@vwid@setup{% - \let\noexpand\Hy@raisedlink\noexpand\@vwid@Hy@raisedlink % HYPERREF ! - \unexpanded\expandafter{\@vwid@setup}}% -}% -% Homemade package to handle merged cells -\RequirePackage{sphinxmulticell} -\RequirePackage{makeidx} -% For framing code-blocks and warning type notices, and shadowing topics -\RequirePackage{framed} + +% We first handle options then load packages, but we need \definecolor from +% xcolor/color. + +% FIXME: we should \RequirePackage{xcolor} always now % The xcolor package draws better fcolorboxes around verbatim code \IfFileExists{xcolor.sty}{ \RequirePackage{xcolor} }{ \RequirePackage{color} } -% For highlighted code. -\RequirePackage{fancyvrb} -\define@key{FV}{hllines}{\def\sphinx@verbatim@checkifhl##1{\in@{, ##1,}{#1}}} -% sphinxVerbatim must be usable by third party without requiring hllines set-up -\def\sphinxresetverbatimhllines{\def\sphinx@verbatim@checkifhl##1{\in@false}} -\sphinxresetverbatimhllines -% For hyperlinked footnotes in tables; also for gathering footnotes from -% topic and warning blocks. Also to allow code-blocks in footnotes. -\RequirePackage{footnotehyper-sphinx} -% For the H specifier. Do not \restylefloat{figure}, it breaks Sphinx code -% for allowing figures in tables. -\RequirePackage{float} -% For floating figures in the text. Better to load after float. -\RequirePackage{wrapfig} -% Separate paragraphs by space by default. -\IfFileExists{parskip-2001-04-09.sty}% since September 2018 TeXLive update -% new parskip.sty, but let it rollback to old one. -% hopefully TeX installation not broken and LaTeX kernel not too old - {\RequirePackage{parskip}[=v1]} -% standard one from 1989. Admittedly \section of article/book gives possibly -% anomalous spacing, but we can't require September 2018 release for some time. - {\RequirePackage{parskip}} -% For parsed-literal blocks. -\RequirePackage{alltt} -% Display "real" single quotes in literal blocks. -\RequirePackage{upquote} -% control caption around literal-block -\RequirePackage{capt-of} -\RequirePackage{needspace} -% LaTeX 2018-04-01 and later provides \@removefromreset -\ltx@ifundefined{@removefromreset} - {\RequirePackage{remreset}} - {}% avoid warning -% To support hlist directive -\RequirePackage{multicol} -% to make pdf with correct encoded bookmarks in Japanese -% this should precede the hyperref package -\ifx\kanjiskip\@undefined -% for non-Japanese: make sure bookmarks are ok also with lualatex - \PassOptionsToPackage{pdfencoding=unicode}{hyperref} -\else - \RequirePackage{atbegshi} - \ifx\ucs\@undefined - \ifnum 42146=\euc"A4A2 - \AtBeginShipoutFirst{\special{pdf:tounicode EUC-UCS2}} - \else - \AtBeginShipoutFirst{\special{pdf:tounicode 90ms-RKSJ-UCS2}} - \fi - \else - \AtBeginShipoutFirst{\special{pdf:tounicode UTF8-UCS2}} - \fi -\fi -\ifx\@jsc@uplatextrue\@undefined\else - \PassOptionsToPackage{setpagesize=false}{hyperref} -\fi - -% These options can be overriden inside 'hyperref' key -% or by later use of \hypersetup. -\PassOptionsToPackage{colorlinks,breaklinks,% - linkcolor=InnerLinkColor,filecolor=OuterLinkColor,% - menucolor=OuterLinkColor,urlcolor=OuterLinkColor,% - citecolor=InnerLinkColor}{hyperref} - -% stylesheet for highlighting with pygments -\RequirePackage{sphinxhighlight} -% fix baseline increase from Pygments latex formatter in case of error tokens -% and keep \fboxsep's scope local via added braces -\def\PYG@tok@err{% - \def\PYG@bc##1{{\setlength{\fboxsep}{-\fboxrule}% - \fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}% -} -\def\PYG@tok@cs{% - \def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}% - \def\PYG@bc##1{{\setlength{\fboxsep}{0pt}% - \colorbox[rgb]{1.00,0.94,0.94}{\strut ##1}}}% -}% - - -%% OPTIONS -% % Handle options via "kvoptions" (later loaded by hyperref anyhow) \RequirePackage{kvoptions} \SetupKeyvalOptions{prefix=spx@opt@} % use \spx@opt@ prefix @@ -415,6 +173,7 @@ \DisableKeyvalOption{sphinx}{numfigreset} \DisableKeyvalOption{sphinx}{nonumfigreset} \DisableKeyvalOption{sphinx}{mathnumfig} +% FIXME: this is unrelated to an option, move this elsewhere % To allow hyphenation of first word in narrow contexts; no option, % customization to be done via 'preamble' key \newcommand*\sphinxAtStartPar{\leavevmode\nobreak\hskip\z@skip} @@ -424,426 +183,121 @@ \newcommand\sphinxsetup[1]{\setkeys{sphinx}{#1}} -%% ALPHANUMERIC LIST ITEMS -\newcommand\sphinxsetlistlabels[5] -{% #1 = style, #2 = enum, #3 = enumnext, #4 = prefix, #5 = suffix - % #2 and #3 are counters used by enumerate environement e.g. enumi, enumii. - % #1 is a macro such as \arabic or \alph - % prefix and suffix are strings (by default empty and a dot). - \@namedef{the#2}{#1{#2}}% - \@namedef{label#2}{#4\@nameuse{the#2}#5}% - \@namedef{p@#3}{\@nameuse{p@#2}#4\@nameuse{the#2}#5}% -}% - - -%% MAXLISTDEPTH +%% MISCELLANEOUS CONTEXT % -% remove LaTeX's cap on nesting depth if 'maxlistdepth' key used. -% This is a hack, which works with the standard classes: it assumes \@toodeep -% is always used in "true" branches: "\if ... \@toodeep \else .. \fi." - -% will force use the "false" branch (if there is one) -\def\spx@toodeep@hack{\fi\iffalse} - -% do nothing if 'maxlistdepth' key not used or if package enumitem loaded. -\ifnum\spx@opt@maxlistdepth=\z@\expandafter\@gobbletwo\fi +% flag to be set in a framed environment +% (defined here as currently needed by three sphinxlatex....sty files and +% even if not needed if such files are replaced, the definition does no harm) +\newif\ifspx@inframed +% +% \spx@ifcaptionpackage (defined at begin document) +% is needed currently in macros from: +% sphinxlatexliterals.sty (sphinxVerbatim) +% sphinxlatextables.sty (for some macros used in the table templates) +% +% \sphinxcaption is mark-up injected by the tabular and tabulary templates +% it is defined in sphinxlatextables.sty +% +% store the original \caption macro for usage with figures inside longtable +% and tabulary cells. Make sure we get the final \caption in presence of +% caption package, whether the latter was loaded before or after sphinx. \AtBeginDocument{% -\@ifpackageloaded{enumitem}{\remove@to@nnil}{}% - \let\spx@toodeepORI\@toodeep - \def\@toodeep{% - \ifnum\@listdepth<\spx@opt@maxlistdepth\relax - \expandafter\spx@toodeep@hack - \else - \expandafter\spx@toodeepORI - \fi}% -% define all missing \@list... macros - \count@\@ne - \loop - \ltx@ifundefined{@list\romannumeral\the\count@} - {\iffalse}{\iftrue\advance\count@\@ne}% - \repeat - \loop - \ifnum\count@>\spx@opt@maxlistdepth\relax\else - \expandafter\let - \csname @list\romannumeral\the\count@\expandafter\endcsname - \csname @list\romannumeral\the\numexpr\count@-\@ne\endcsname - % workaround 2.6--3.2d babel-french issue (fixed in 3.2e; no change needed) - \ltx@ifundefined{leftmargin\romannumeral\the\count@} - {\expandafter\let - \csname leftmargin\romannumeral\the\count@\expandafter\endcsname - \csname leftmargin\romannumeral\the\numexpr\count@-\@ne\endcsname}{}% - \advance\count@\@ne - \repeat -% define all missing enum... counters and \labelenum... macros and \p@enum.. - \count@\@ne - \loop - \ltx@ifundefined{c@enum\romannumeral\the\count@} - {\iffalse}{\iftrue\advance\count@\@ne}% - \repeat - \loop - \ifnum\count@>\spx@opt@maxlistdepth\relax\else - \newcounter{enum\romannumeral\the\count@}% - \expandafter\def - \csname labelenum\romannumeral\the\count@\expandafter\endcsname - \expandafter - {\csname theenum\romannumeral\the\numexpr\count@\endcsname.}% - \expandafter\def - \csname p@enum\romannumeral\the\count@\expandafter\endcsname - \expandafter - {\csname p@enum\romannumeral\the\numexpr\count@-\@ne\expandafter - \endcsname\csname theenum\romannumeral\the\numexpr\count@-\@ne\endcsname.}% - \advance\count@\@ne - \repeat -% define all missing labelitem... macros - \count@\@ne - \loop - \ltx@ifundefined{labelitem\romannumeral\the\count@} - {\iffalse}{\iftrue\advance\count@\@ne}% - \repeat - \loop - \ifnum\count@>\spx@opt@maxlistdepth\relax\else - \expandafter\let - \csname labelitem\romannumeral\the\count@\expandafter\endcsname - \csname labelitem\romannumeral\the\numexpr\count@-\@ne\endcsname - \advance\count@\@ne - \repeat - \PackageInfo{sphinx}{maximal list depth extended to \spx@opt@maxlistdepth}% -\@gobble\@nnil + \let\spx@originalcaption\caption + \@ifpackageloaded{caption} + {\let\spx@ifcaptionpackage\@firstoftwo + \caption@AtBeginDocument*{\let\spx@originalcaption\caption}% +% in presence of caption package, drop our own \sphinxcaption whose aim was to +% ensure same width of caption to all kinds of tables (tabular(y), longtable), +% because caption package has its own width (or margin) option + \def\sphinxcaption{\caption}% + }% + {\let\spx@ifcaptionpackage\@secondoftwo}% } - -%% INDEX, BIBLIOGRAPHY, APPENDIX, TABLE OF CONTENTS +%% PASS OPTIONS % -% fix the double index and bibliography on the table of contents -% in jsclasses (Japanese standard document classes) -\ifx\@jsc@uplatextrue\@undefined\else - \renewenvironment{sphinxtheindex} - {\cleardoublepage\phantomsection - \begin{theindex}} - {\end{theindex}} - - \renewenvironment{sphinxthebibliography}[1] - {\cleardoublepage% \phantomsection % not needed here since TeXLive 2010's hyperref - \begin{thebibliography}{#1}} - {\end{thebibliography}} -\fi - -% disable \@chappos in Appendix in pTeX -\ifx\kanjiskip\@undefined\else - \let\py@OldAppendix=\appendix - \renewcommand{\appendix}{ - \py@OldAppendix - \gdef\@chappos{} - } -\fi +% pass options to hyperref; it must not have been loaded already +\input{sphinxoptionshyperref.sty} +% pass options to geometry; it must not have been loaded already +\input{sphinxoptionsgeometry.sty} -% make commands known to non-Sphinx document classes -\providecommand*{\sphinxmaketitle}{\maketitle} -\providecommand*{\sphinxtableofcontents}{\tableofcontents} -\ltx@ifundefined{sphinxthebibliography} - {\newenvironment - {sphinxthebibliography}{\begin{thebibliography}}{\end{thebibliography}}% - } - {}% else clause of \ltx@ifundefined -\ltx@ifundefined{sphinxtheindex} - {\newenvironment{sphinxtheindex}{\begin{theindex}}{\end{theindex}}}% - {}% else clause of \ltx@ifundefined - -% for usage with xindy: this string gets internationalized in preamble -\newcommand*{\sphinxnonalphabeticalgroupname}{} -% redefined in preamble, headings for makeindex produced index -\newcommand*{\sphinxsymbolsname}{} -\newcommand*{\sphinxnumbersname}{} %% COLOR (general) % -% FIXME: \normalcolor should probably be used in place of \py@NormalColor -% elsewhere, and \py@NormalColor should never be defined. \normalcolor -% switches to the colour from last \color call in preamble. +% FIXME: these two should be deprecated +% +% FIXME: \normalcolor should be used and \py@NormalColor never defined \def\py@NormalColor{\color{black}} -% FIXME: it is probably better to use \color{TitleColor}, as TitleColor -% can be customized from 'sphinxsetup', and drop usage of \py@TitleColor +% FIXME: \color{TitleColor} should be used directly and \py@TitleColor +% should never get defined. \def\py@TitleColor{\color{TitleColor}} -% FIXME: this line should be dropped, as "9" is default anyhow. -\ifdefined\pdfcompresslevel\pdfcompresslevel = 9 \fi -%% PAGE STYLING +%% PACKAGES % -% Style parameters and macros used by most documents here -\raggedbottom -\sloppy -\hbadness = 5000 % don't print trivial gripes - -% Use \pagestyle{normal} as the primary pagestyle for text. -% Redefine the 'normal' header/footer style when using "fancyhdr" package: -\@ifpackageloaded{fancyhdr}{% - \ltx@ifundefined{c@chapter} - {% no \chapter, "howto" (non-Japanese) docclass - \fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[C]{{\py@HeaderFamily\thepage}} - \renewcommand{\headrulewidth}{0pt} - \renewcommand{\footrulewidth}{0pt} - } - % Same as 'plain', this way we can use it in template - % FIXME: shouldn't this have a running header with Name and Release like 'manual'? - \fancypagestyle{normal}{ - \fancyhf{} - \fancyfoot[C]{{\py@HeaderFamily\thepage}} - \renewcommand{\headrulewidth}{0pt} - \renewcommand{\footrulewidth}{0pt} - } - }% - {% classes with \chapter command - \fancypagestyle{normal}{ - \fancyhf{} - \fancyfoot[RO]{{\py@HeaderFamily\thepage}} - \fancyfoot[LO]{{\py@HeaderFamily\nouppercase{\rightmark}}} - \fancyhead[RO]{{\py@HeaderFamily \@title\sphinxheadercomma\py@release}} - \if@twoside - \fancyfoot[LE]{{\py@HeaderFamily\thepage}} - \fancyfoot[RE]{{\py@HeaderFamily\nouppercase{\leftmark}}} - \fancyhead[LE]{{\py@HeaderFamily \@title\sphinxheadercomma\py@release}} - \fi - \renewcommand{\headrulewidth}{0.4pt} - \renewcommand{\footrulewidth}{0.4pt} - % define chaptermark with \@chappos when \@chappos is available for Japanese - \ltx@ifundefined{@chappos}{} - {\def\chaptermark##1{\markboth{\@chapapp\space\thechapter\space\@chappos\space ##1}{}}} - } - % Update the plain style so we get the page number & footer line, - % but not a chapter or section title. This is to keep the first - % page of a chapter `clean.' - \fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[RO]{{\py@HeaderFamily\thepage}} - \if@twoside\fancyfoot[LE]{{\py@HeaderFamily\thepage}}\fi - \renewcommand{\headrulewidth}{0pt} - \renewcommand{\footrulewidth}{0.4pt} - } - } - } - {% no fancyhdr: memoir class - % Provide default for 'normal' style simply as an alias of 'plain' style - % This way we can use \pagestyle{normal} in LaTeX template - \def\ps@normal{\ps@plain} - % Users of memoir class are invited to redefine 'normal' style in preamble - } +% as will be indicated below, secondary style files load some more packages +% +% For \text macro (sphinx.util.texescape) +% also for usage of \firstchoice@true(false) in sphinxlatexgraphics.sty +\RequirePackage{amstext} +% It was passed "warn" option from latex template in case it is already loaded +% via some other package before \usepackage{sphinx} in preamble +\RequirePackage{textcomp} +% For the H specifier. Do not \restylefloat{figure}, it breaks Sphinx code +% for allowing figures in tables. +\RequirePackage{float} +% For floating figures in the text. Better to load after float. +\RequirePackage{wrapfig} +% Provides \captionof, used once by latex writer (\captionof{figure}) +\RequirePackage{capt-of} +% Support hlist directive +\RequirePackage{multicol} -% geometry -\ifx\kanjiskip\@undefined - \PassOptionsToPackage{% - hmargin={\unexpanded{\spx@opt@hmargin}},% - vmargin={\unexpanded{\spx@opt@vmargin}},% - marginpar=\unexpanded{\spx@opt@marginpar}} - {geometry} -\else - % set text width for Japanese documents to be integer multiple of 1zw - % and text height to be integer multiple of \baselineskip - % the execution is delayed to \sphinxsetup then geometry.sty - \normalsize\normalfont - \newcommand*\sphinxtextwidthja[1]{% - \if@twocolumn\tw@\fi - \dimexpr - \numexpr\dimexpr\paperwidth-\tw@\dimexpr#1\relax\relax/ - \dimexpr\if@twocolumn\tw@\else\@ne\fi zw\relax - zw\relax}% - \newcommand*\sphinxmarginparwidthja[1]{% - \dimexpr\numexpr\dimexpr#1\relax/\dimexpr1zw\relax zw\relax}% - \newcommand*\sphinxtextlinesja[1]{% - \numexpr\@ne+\dimexpr\paperheight-\topskip-\tw@\dimexpr#1\relax\relax/ - \baselineskip\relax}% - \ifx\@jsc@uplatextrue\@undefined\else - % the way we found in order for the papersize special written by - % geometry in the dvi file to be correct in case of jsbook class - \ifnum\mag=\@m\else % do nothing special if nomag class option or 10pt - \PassOptionsToPackage{truedimen}{geometry}% - \fi - \fi - \PassOptionsToPackage{% - hmarginratio={1:1},% - textwidth=\unexpanded{\sphinxtextwidthja{\spx@opt@hmargin}},% - vmarginratio={1:1},% - lines=\unexpanded{\sphinxtextlinesja{\spx@opt@vmargin}},% - marginpar=\unexpanded{\sphinxmarginparwidthja{\spx@opt@marginpar}},% - footskip=2\baselineskip,% - }{geometry}% - \AtBeginDocument - {% update a dimension used by the jsclasses - \ifx\@jsc@uplatextrue\@undefined\else\fullwidth\textwidth\fi - % for some reason, jreport normalizes all dimensions with \@settopoint - \@ifclassloaded{jreport} - {\@settopoint\textwidth\@settopoint\textheight\@settopoint\marginparwidth} - {}% <-- "false" clause of \@ifclassloaded - }% -\fi -% fix fncychap's bug which uses prematurely the \textwidth value -\@ifpackagewith{fncychap}{Bjornstrup} - {\AtBeginDocument{\mylen\textwidth\advance\mylen-2\myhi}}% - {}% <-- "false" clause of \@ifpackagewith +%% GRAPHICS +% +% It will always be needed, so let's load it here +\RequirePackage{graphicx} +\input{sphinxlatexgraphics.sty} -%% TITLES +%% FRAMED ENVIRONMENTS % -% Since Sphinx 1.5, users should use HeaderFamily key to 'sphinxsetup' rather -% than defining their own \py@HeaderFamily command (which is still possible). -% Memo: \py@HeaderFamily is also used by \maketitle as defined in -% sphinxmanual.cls/sphinxhowto.cls -\newcommand{\py@HeaderFamily}{\spx@opt@HeaderFamily} +\input{sphinxlatexadmonitions.sty} +\input{sphinxlatexliterals.sty} +\input{sphinxlatexshadowbox.sty} -% This sets up the fancy chapter headings that make the documents look -% at least a little better than the usual LaTeX output. -\@ifpackagewith{fncychap}{Bjarne}{ - \ChNameVar {\raggedleft\normalsize \py@HeaderFamily} - \ChNumVar {\raggedleft\Large \py@HeaderFamily} - \ChTitleVar{\raggedleft\Large \py@HeaderFamily} - % This creates (numbered) chapter heads without the leading \vspace*{}: - \def\@makechapterhead#1{% - {\parindent \z@ \raggedright \normalfont - \ifnum \c@secnumdepth >\m@ne - \if@mainmatter - \DOCH - \fi - \fi - \interlinepenalty\@M - \if@mainmatter - \DOTI{#1}% - \else% - \DOTIS{#1}% - \fi - }} -}{}% <-- "false" clause of \@ifpackagewith -% Augment the sectioning commands used to get our own font family in place, -% and reset some internal data items (\titleformat from titlesec package) -\titleformat{\section}{\Large\py@HeaderFamily}% - {\py@TitleColor\thesection}{0.5em}{\py@TitleColor} -\titleformat{\subsection}{\large\py@HeaderFamily}% - {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor} -\titleformat{\subsubsection}{\py@HeaderFamily}% - {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor} -% By default paragraphs (and subsubsections) will not be numbered because -% sphinxmanual.cls and sphinxhowto.cls set secnumdepth to 2 -\titleformat{\paragraph}{\py@HeaderFamily}% - {\py@TitleColor\theparagraph}{0.5em}{\py@TitleColor} -\titleformat{\subparagraph}{\py@HeaderFamily}% - {\py@TitleColor\thesubparagraph}{0.5em}{\py@TitleColor} +%% PYGMENTS +% stylesheet for highlighting with pygments +\RequirePackage{sphinxhighlight} +% fix baseline increase from Pygments latex formatter in case of error tokens +% and keep \fboxsep's scope local via added braces +\def\PYG@tok@err{% + \def\PYG@bc##1{{\setlength{\fboxsep}{-\fboxrule}% + \fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}% +} +\def\PYG@tok@cs{% + \def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}% + \def\PYG@bc##1{{\setlength{\fboxsep}{0pt}% + \colorbox[rgb]{1.00,0.94,0.94}{\strut ##1}}}% +}% -%% GRAPHICS -% -% \sphinxincludegraphics resizes images larger than the TeX \linewidth (which -% is adjusted in indented environments), or taller than a certain maximal -% height (usually \textheight and this is reduced in the environments which use -% framed.sty to avoid infinite loop if image too tall). -% -% In case height or width options are present the rescaling is done -% (since 2.0), in a way keeping the width:height ratio either native from -% image or from the width and height options if both were present. +%% TABLES % -\newdimen\spx@image@maxheight -\AtBeginDocument{\spx@image@maxheight\textheight} - -% box scratch register -\newbox\spx@image@box -\newcommand*{\sphinxsafeincludegraphics}[2][]{% - % #1 contains possibly width=, height=, but no scale= since 1.8.4 - \setbox\spx@image@box\hbox{\includegraphics[#1,draft]{#2}}% - \in@false % use some handy boolean flag - \ifdim \wd\spx@image@box>\linewidth - \in@true % flag to remember to adjust options and set box dimensions - % compute height which results from rescaling width to \linewidth - % and keep current aspect ratio. multiply-divide in \numexpr uses - % temporarily doubled precision, hence no overflow. (of course we - % assume \ht is not a few sp's below \maxdimen...(about 16384pt). - \edef\spx@image@rescaledheight % with sp units - {\the\numexpr\ht\spx@image@box - *\linewidth/\wd\spx@image@box sp}% - \ifdim\spx@image@rescaledheight>\spx@image@maxheight - % the rescaled height will be too big, so it is height which decides - % the rescaling factor - \def\spx@image@requiredheight{\spx@image@maxheight}% dimen register - \edef\spx@image@requiredwidth % with sp units - {\the\numexpr\wd\spx@image@box - *\spx@image@maxheight/\ht\spx@image@box sp}% - % TODO: decide if this commented-out block could be needed due to - % rounding in numexpr operations going up - % \ifdim\spx@image@requiredwidth>\linewidth - % \def\spx@image@requiredwidth{\linewidth}% dimen register - % \fi - \else - \def\spx@image@requiredwidth{\linewidth}% dimen register - \let\spx@image@requiredheight\spx@image@rescaledheight% sp units - \fi - \else - % width is ok, let's check height - \ifdim\ht\spx@image@box>\spx@image@maxheight - \in@true - \edef\spx@image@requiredwidth % with sp units - {\the\numexpr\wd\spx@image@box - *\spx@image@maxheight/\ht\spx@image@box sp}% - \def\spx@image@requiredheight{\spx@image@maxheight}% dimen register - \fi - \fi % end of check of width and height - \ifin@ - \setbox\spx@image@box - \hbox{\includegraphics - [%#1,% contained only width and/or height and overruled anyhow - width=\spx@image@requiredwidth,height=\spx@image@requiredheight]% - {#2}}% - % \includegraphics does not set box dimensions to the exactly - % requested ones, see https://github.com/latex3/latex2e/issues/112 - \wd\spx@image@box\spx@image@requiredwidth - \ht\spx@image@box\spx@image@requiredheight - \leavevmode\box\spx@image@box - \else - % here we do not modify the options, no need to adjust width and height - % on output, they will be computed exactly as with "draft" option - \setbox\spx@image@box\box\voidb@x % clear memory - \includegraphics[#1]{#2}% - \fi -}% -% Use the "safe" one by default (2.0) -\def\sphinxincludegraphics{\sphinxsafeincludegraphics} +\input{sphinxlatextables.sty} -%% FIGURE IN TABLE +%% NUMBERING OF FIGURES, TABLES, AND LITERAL BLOCKS % -\newenvironment{sphinxfigure-in-table}[1][\linewidth]{% - \def\@captype{figure}% - \sphinxsetvskipsforfigintablecaption - \begin{minipage}{#1}% -}{\end{minipage}} -% store the original \caption macro for usage with figures inside longtable -% and tabulary cells. Make sure we get the final \caption in presence of -% caption package, whether the latter was loaded before or after sphinx. -\AtBeginDocument{% - \let\spx@originalcaption\caption - \@ifpackageloaded{caption} - {\let\spx@ifcaptionpackage\@firstoftwo - \caption@AtBeginDocument*{\let\spx@originalcaption\caption}% -% in presence of caption package, drop our own \sphinxcaption whose aim was to -% ensure same width of caption to all kinds of tables (tabular(y), longtable), -% because caption package has its own width (or margin) option - \def\sphinxcaption{\caption}% - }% - {\let\spx@ifcaptionpackage\@secondoftwo}% -} -% tabulary expands twice contents, we need to prevent double counter stepping -\newcommand*\sphinxfigcaption - {\ifx\equation$%$% this is trick to identify tabulary first pass - \firstchoice@false\else\firstchoice@true\fi - \spx@originalcaption } -\newcommand*\sphinxsetvskipsforfigintablecaption - {\abovecaptionskip\smallskipamount - \belowcaptionskip\smallskipamount} +\input{sphinxlatexnumfig.sty} -%% CITATIONS +%% LISTS % -\protected\def\sphinxcite{\cite} +\input{sphinxlatexlists.sty} + %% FOOTNOTES % @@ -869,1295 +323,33 @@ p. #2, % <- space \fi #1% no space } -% Support large numbered footnotes in minipage -% But now obsolete due to systematic use of \savenotes/\spewnotes -% when minipages are in use in the various macro definitions next. +% support large numbered footnotes in minipage; but this is now obsolete +% from systematic use of savenotes environment around minipages \def\thempfootnote{\arabic{mpfootnote}} +% This package is needed to support hyperlinked footnotes in tables and +% framed contents, and to allow code-blocks in footnotes. +\RequirePackage{sphinxpackagefootnote} -%% NUMBERING OF FIGURES, TABLES, AND LITERAL BLOCKS - -% Everything is delayed to \begin{document} to allow hyperref patches into -% \newcounter to solve duplicate label problems for internal hyperlinks to -% code listings (literalblock counter). User or extension re-definitions of -% \theliteralblock, et al., thus have also to be delayed. (changed at 3.5.0) -\AtBeginDocument{% -\ltx@ifundefined{c@chapter} - {\newcounter{literalblock}}% - {\newcounter{literalblock}[chapter]% - \def\theliteralblock{\ifnum\c@chapter>\z@\arabic{chapter}.\fi - \arabic{literalblock}}% - }% -\ifspx@opt@nonumfigreset - \ltx@ifundefined{c@chapter}{}{% - \@removefromreset{figure}{chapter}% - \@removefromreset{table}{chapter}% - \@removefromreset{literalblock}{chapter}% - \ifspx@opt@mathnumfig - \@removefromreset{equation}{chapter}% - \fi - }% - \def\thefigure{\arabic{figure}}% - \def\thetable {\arabic{table}}% - \def\theliteralblock{\arabic{literalblock}}% - \ifspx@opt@mathnumfig - \def\theequation{\arabic{equation}}% - \fi -\else -\let\spx@preAthefigure\@empty -\let\spx@preBthefigure\@empty -% \ifspx@opt@usespart % <-- LaTeX writer could pass such a 'usespart' boolean -% % as sphinx.sty package option -% If document uses \part, (triggered in Sphinx by latex_toplevel_sectioning) -% LaTeX core per default does not reset chapter or section -% counters at each part. -% But if we modify this, we need to redefine \thechapter, \thesection to -% include the part number and this will cause problems in table of contents -% because of too wide numbering. Simplest is to do nothing. -% \fi -\ifnum\spx@opt@numfigreset>0 - \ltx@ifundefined{c@chapter} - {} - {\g@addto@macro\spx@preAthefigure{\ifnum\c@chapter>\z@\arabic{chapter}.}% - \g@addto@macro\spx@preBthefigure{\fi}}% -\fi -\ifnum\spx@opt@numfigreset>1 - \@addtoreset{figure}{section}% - \@addtoreset{table}{section}% - \@addtoreset{literalblock}{section}% - \ifspx@opt@mathnumfig - \@addtoreset{equation}{section}% - \fi% - \g@addto@macro\spx@preAthefigure{\ifnum\c@section>\z@\arabic{section}.}% - \g@addto@macro\spx@preBthefigure{\fi}% -\fi -\ifnum\spx@opt@numfigreset>2 - \@addtoreset{figure}{subsection}% - \@addtoreset{table}{subsection}% - \@addtoreset{literalblock}{subsection}% - \ifspx@opt@mathnumfig - \@addtoreset{equation}{subsection}% - \fi% - \g@addto@macro\spx@preAthefigure{\ifnum\c@subsection>\z@\arabic{subsection}.}% - \g@addto@macro\spx@preBthefigure{\fi}% -\fi -\ifnum\spx@opt@numfigreset>3 - \@addtoreset{figure}{subsubsection}% - \@addtoreset{table}{subsubsection}% - \@addtoreset{literalblock}{subsubsection}% - \ifspx@opt@mathnumfig - \@addtoreset{equation}{subsubsection}% - \fi% - \g@addto@macro\spx@preAthefigure{\ifnum\c@subsubsection>\z@\arabic{subsubsection}.}% - \g@addto@macro\spx@preBthefigure{\fi}% -\fi -\ifnum\spx@opt@numfigreset>4 - \@addtoreset{figure}{paragraph}% - \@addtoreset{table}{paragraph}% - \@addtoreset{literalblock}{paragraph}% - \ifspx@opt@mathnumfig - \@addtoreset{equation}{paragraph}% - \fi% - \g@addto@macro\spx@preAthefigure{\ifnum\c@subparagraph>\z@\arabic{subparagraph}.}% - \g@addto@macro\spx@preBthefigure{\fi}% -\fi -\ifnum\spx@opt@numfigreset>5 - \@addtoreset{figure}{subparagraph}% - \@addtoreset{table}{subparagraph}% - \@addtoreset{literalblock}{subparagraph}% - \ifspx@opt@mathnumfig - \@addtoreset{equation}{subparagraph}% - \fi% - \g@addto@macro\spx@preAthefigure{\ifnum\c@subsubparagraph>\z@\arabic{subsubparagraph}.}% - \g@addto@macro\spx@preBthefigure{\fi}% -\fi -\expandafter\g@addto@macro -\expandafter\spx@preAthefigure\expandafter{\spx@preBthefigure}% -\let\thefigure\spx@preAthefigure -\let\thetable\spx@preAthefigure -\let\theliteralblock\spx@preAthefigure -\g@addto@macro\thefigure{\arabic{figure}}% -\g@addto@macro\thetable{\arabic{table}}% -\g@addto@macro\theliteralblock{\arabic{literalblock}}% - \ifspx@opt@mathnumfig - \let\theequation\spx@preAthefigure - \g@addto@macro\theequation{\arabic{equation}}% - \fi -\fi -}% end of big \AtBeginDocument - -%% LITERAL BLOCKS -% -% Based on use of "fancyvrb.sty"'s Verbatim. -% - with framing allowing page breaks ("framed.sty") -% - with breaking of long lines (exploits Pygments mark-up), -% - with possibly of a top caption, non-separable by pagebreak. -% - and usable inside tables or footnotes ("footnotehyper-sphinx"). - -% Prior to Sphinx 1.5, \Verbatim and \endVerbatim were modified by Sphinx. -% The aliases defined here are used in sphinxVerbatim environment and can -% serve as hook-points with no need to modify \Verbatim itself. -\let\OriginalVerbatim \Verbatim -\let\endOriginalVerbatim\endVerbatim - -% for captions of literal blocks -% at start of caption title -\newcommand*{\fnum@literalblock}{\literalblockname\nobreakspace\theliteralblock} -% this will be overwritten in document preamble by Babel translation -\newcommand*{\literalblockname}{Listing } -% file extension needed for \caption's good functioning, the file is created -% only if a \listof{literalblock}{foo} command is encountered, which is -% analogous to \listoffigures, but for the code listings (foo = chosen title.) -\newcommand*{\ext@literalblock}{lol} - -\newif\ifspx@inframed % flag set if we are already in a framed environment -% if forced use of minipage encapsulation is needed (e.g. table cells) -\newif\ifsphinxverbatimwithminipage \sphinxverbatimwithminipagefalse - -% Framing macro for use with framed.sty's \FrameCommand -% - it obeys current indentation, -% - frame is \fboxsep separated from the contents, -% - the contents use the full available text width, -% - #1 = color of frame, #2 = color of background, -% - #3 = above frame, #4 = below frame, #5 = within frame, -% - #3 and #4 must be already typeset boxes; they must issue \normalcolor -% or similar, else, they are under scope of color #1 -\long\def\spx@fcolorbox #1#2#3#4#5{% - \hskip\@totalleftmargin - \hskip-\fboxsep\hskip-\fboxrule - % use of \color@b@x here is compatible with both xcolor.sty and color.sty - \color@b@x {\color{#1}\spx@CustomFBox{#3}{#4}}{\color{#2}}{#5}% - \hskip-\fboxsep\hskip-\fboxrule - \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth -}% -% #1 = for material above frame, such as a caption or a "continued" hint -% #2 = for material below frame, such as a caption or "continues on next page" -% #3 = actual contents, which will be typeset with a background color -\long\def\spx@CustomFBox#1#2#3{% - \begingroup - \setbox\@tempboxa\hbox{{#3}}% inner braces to avoid color leaks - \vbox{#1% above frame - % draw frame border _latest_ to avoid pdf viewer issue - \kern\fboxrule - \hbox{\kern\fboxrule - \copy\@tempboxa - \kern-\wd\@tempboxa\kern-\fboxrule - \vrule\@width\fboxrule - \kern\wd\@tempboxa - \vrule\@width\fboxrule}% - \kern-\dimexpr\ht\@tempboxa+\dp\@tempboxa+\fboxrule\relax - \hrule\@height\fboxrule - \kern\dimexpr\ht\@tempboxa+\dp\@tempboxa\relax - \hrule\@height\fboxrule - #2% below frame - }% - \endgroup -}% -\def\spx@fcolorbox@put@c#1{% hide width from framed.sty measuring - \moveright\dimexpr\fboxrule+.5\wd\@tempboxa\hb@xt@\z@{\hss#1\hss}% -}% -\def\spx@fcolorbox@put@r#1{% right align with contents, width hidden - \moveright\dimexpr\fboxrule+\wd\@tempboxa-\fboxsep\hb@xt@\z@{\hss#1}% -}% -\def\spx@fcolorbox@put@l#1{% left align with contents, width hidden - \moveright\dimexpr\fboxrule+\fboxsep\hb@xt@\z@{#1\hss}% -}% -% -\def\sphinxVerbatim@Continued - {\csname spx@fcolorbox@put@\spx@opt@verbatimcontinuedalign\endcsname - {\normalcolor\sphinxstylecodecontinued\literalblockcontinuedname}}% -\def\sphinxVerbatim@Continues - {\csname spx@fcolorbox@put@\spx@opt@verbatimcontinuesalign\endcsname - {\normalcolor\sphinxstylecodecontinues\literalblockcontinuesname}}% -\def\sphinxVerbatim@Title - {\spx@fcolorbox@put@c{\unhcopy\sphinxVerbatim@TitleBox}}% -\let\sphinxVerbatim@Before\@empty -\let\sphinxVerbatim@After\@empty -% Defaults are redefined in document preamble according to language -\newcommand*\literalblockcontinuedname{continued from previous page}% -\newcommand*\literalblockcontinuesname{continues on next page}% -% -\def\spx@verbatimfcolorbox{\spx@fcolorbox{VerbatimBorderColor}{VerbatimColor}}% -\def\sphinxVerbatim@FrameCommand - {\spx@verbatimfcolorbox\sphinxVerbatim@Before\sphinxVerbatim@After}% -\def\sphinxVerbatim@FirstFrameCommand - {\spx@verbatimfcolorbox\sphinxVerbatim@Before\sphinxVerbatim@Continues}% -\def\sphinxVerbatim@MidFrameCommand - {\spx@verbatimfcolorbox\sphinxVerbatim@Continued\sphinxVerbatim@Continues}% -\def\sphinxVerbatim@LastFrameCommand - {\spx@verbatimfcolorbox\sphinxVerbatim@Continued\sphinxVerbatim@After}% - -% For linebreaks inside Verbatim environment from package fancyvrb. -\newbox\sphinxcontinuationbox -\newbox\sphinxvisiblespacebox -\newcommand*\sphinxafterbreak {\copy\sphinxcontinuationbox} - -% Take advantage of the already applied Pygments mark-up to insert -% potential linebreaks for TeX processing. -% {, <, #, %, $, ' and ": go to next line. -% _, }, ^, &, >, -, ~, and \: stay at end of broken line. -% Use of \textquotesingle for straight quote. -% FIXME: convert this to package options ? -\newcommand*\sphinxbreaksbeforelist {% - \do\PYGZob\{\do\PYGZlt\<\do\PYGZsh\#\do\PYGZpc\%% {, <, #, %, - \do\PYGZdl\$\do\PYGZdq\"% $, " - \def\PYGZsq - {\discretionary{}{\sphinxafterbreak\textquotesingle}{\textquotesingle}}% ' -} -\newcommand*\sphinxbreaksafterlist {% - \do\PYGZus\_\do\PYGZcb\}\do\PYGZca\^\do\PYGZam\&% _, }, ^, &, - \do\PYGZgt\>\do\PYGZhy\-\do\PYGZti\~% >, -, ~ - \do\PYGZbs\\% \ -} -\newcommand*\sphinxbreaksatspecials {% - \def\do##1##2% - {\def##1{\discretionary{}{\sphinxafterbreak\char`##2}{\char`##2}}}% - \sphinxbreaksbeforelist - \def\do##1##2% - {\def##1{\discretionary{\char`##2}{\sphinxafterbreak}{\char`##2}}}% - \sphinxbreaksafterlist -} - -\def\sphinx@verbatim@nolig@list {\do \`}% -% Some characters . , ; ? ! / are neither pygmentized nor "tex-escaped". -% This macro makes them "active" and they will insert potential linebreaks. -% Not compatible with math mode (cf \sphinxunactivateextras). -\newcommand*\sphinxbreaksbeforeactivelist {}% none -\newcommand*\sphinxbreaksafteractivelist {\do\.\do\,\do\;\do\?\do\!\do\/} -\newcommand*\sphinxbreaksviaactive {% - \def\do##1{\lccode`\~`##1% - \lowercase{\def~}{\discretionary{}{\sphinxafterbreak\char`##1}{\char`##1}}% - \catcode`##1\active}% - \sphinxbreaksbeforeactivelist - \def\do##1{\lccode`\~`##1% - \lowercase{\def~}{\discretionary{\char`##1}{\sphinxafterbreak}{\char`##1}}% - \catcode`##1\active}% - \sphinxbreaksafteractivelist - \lccode`\~`\~ -} - -% If the linebreak is at a space, the latter will be displayed as visible -% space at end of first line, and a continuation symbol starts next line. -\def\spx@verbatim@space {% - \nobreak\hskip\z@skip - \discretionary{\copy\sphinxvisiblespacebox}{\sphinxafterbreak} - {\kern\fontdimen2\font}% -}% - -% if the available space on page is less than \literalblockneedspace, insert pagebreak -\newcommand{\sphinxliteralblockneedspace}{5\baselineskip} -\newcommand{\sphinxliteralblockwithoutcaptionneedspace}{1.5\baselineskip} -% The title (caption) is specified from outside as macro \sphinxVerbatimTitle. -% \sphinxVerbatimTitle is reset to empty after each use of Verbatim. -\newcommand*\sphinxVerbatimTitle {} -% This box to typeset the caption before framed.sty multiple passes for framing. -\newbox\sphinxVerbatim@TitleBox -% This box to measure contents if nested as inner \MakeFramed requires then -% minipage encapsulation but too long contents then break outer \MakeFramed -\newbox\sphinxVerbatim@ContentsBox -% This is a workaround to a "feature" of French lists, when literal block -% follows immediately; usable generally (does only \par then), a priori... -\newcommand*\sphinxvspacefixafterfrenchlists{% - \ifvmode\ifdim\lastskip<\z@ \vskip\parskip\fi\else\par\fi -} -% Holder macro for labels of literal blocks. Set-up by LaTeX writer. -\newcommand*\sphinxLiteralBlockLabel {} -\newcommand*\sphinxSetupCaptionForVerbatim [1] -{% - \sphinxvspacefixafterfrenchlists - \needspace{\sphinxliteralblockneedspace}% -% insert a \label via \sphinxLiteralBlockLabel -% reset to normal the color for the literal block caption - \def\sphinxVerbatimTitle - {\py@NormalColor\sphinxcaption{\sphinxLiteralBlockLabel #1}}% -} -\newcommand*\sphinxSetupCodeBlockInFootnote {% - \fvset{fontsize=\footnotesize}\let\caption\sphinxfigcaption - \sphinxverbatimwithminipagetrue % reduces vertical spaces - % we counteract (this is in a group) the \@normalsize from \caption - \let\normalsize\footnotesize\let\@parboxrestore\relax - \def\spx@abovecaptionskip{\sphinxverbatimsmallskipamount}% -} -\newcommand*{\sphinxverbatimsmallskipamount}{\smallskipamount} -% serves to implement line highlighting and line wrapping -\newcommand\sphinxFancyVerbFormatLine[1]{% - \expandafter\sphinx@verbatim@checkifhl\expandafter{\the\FV@CodeLineNo}% - \ifin@ - \sphinxVerbatimHighlightLine{#1}% - \else - \sphinxVerbatimFormatLine{#1}% - \fi -}% -\newcommand\sphinxVerbatimHighlightLine[1]{% - \edef\sphinxrestorefboxsep{\fboxsep\the\fboxsep\relax}% - \fboxsep0pt\relax % cf LaTeX bug graphics/4524 - \colorbox{sphinxVerbatimHighlightColor}% - {\sphinxrestorefboxsep\sphinxVerbatimFormatLine{#1}}% - % no need to restore \fboxsep here, as this ends up in a \hbox from fancyvrb -}% -% \sphinxVerbatimFormatLine will be set locally to one of those two: -\newcommand\sphinxVerbatimFormatLineWrap{% - \hsize\linewidth - \ifspx@opt@verbatimforcewraps - \expandafter\spx@verb@FormatLineForceWrap - \else\expandafter\spx@verb@FormatLineWrap - \fi -}% -\newcommand\sphinxVerbatimFormatLineNoWrap[1]{\hb@xt@\linewidth{\strut #1\hss}}% -\long\def\spx@verb@FormatLineWrap#1{% - \vtop{\raggedright\hyphenpenalty\z@\exhyphenpenalty\z@ - \doublehyphendemerits\z@\finalhyphendemerits\z@ - \strut #1\strut}% -}% -% -% The normal line wrapping allows breaks at spaces and ascii non -% letters, non digits. The \raggedright above means there will be -% an overfilled line only if some non-breakable "word" was -% encountered, which is longer than a line (it is moved always to -% be on its own on a new line). -% -% The "forced" line wrapping will parse the tokens to add potential -% breakpoints at each character. As some strings are highlighted, -% we have to apply the highlighting character per character, which -% requires to manipulate the output of the Pygments LaTeXFormatter. -% -% Doing this at latex level is complicated. The contents should -% be as expected: i.e. some active characters from -% \sphinxbreaksviaactive, some Pygments character escapes such as -% \PYGZdl{}, and the highlighting \PYG macro with always 2 -% arguments. No other macros should be there, except perhaps -% zero-parameter macros. In particular: -% - the texcomments Pygments option must be set to False -% -% With pdflatex, Unicode input gives multi-bytes characters -% where the first byte is active. We support the "utf8" macros -% only. "utf8x" is not supported. -% -% The highlighting macro \PYG will be applied character per -% character. Highlighting via a colored background gives thus a -% chain of small colored boxes which may cause some artefact in -% some pdf viewers. Can't do anything here if we do want the line -% break to be possible. -% -% First a measurement step is done of what would the standard line -% wrapping give (i.e line breaks only at spaces and non-letter, -% non-digit ascii characters), cf TeX by Topic for the basic -% dissecting technique: TeX unfortunately when building a vertical -% box does not store in an accessible way what was the maximal -% line-width during paragraph building. -% -% If the max width exceeds the linewidth by more than verbatimmaxoverfull -% character widths, or if the min width plus verbatimmaxunderfull character -% widths is inferior to linewidth, then we apply the "force wrapping" with -% potential line break at each character, else we don't. -\long\def\spx@verb@FormatLineForceWrap#1{% - % \spx@image@box is a scratch box register that we can use here - \global\let\spx@verb@maxwidth\z@ - \global\let\spx@verb@minwidth\linewidth - \setbox\spx@image@box - \vtop{\raggedright\hyphenpenalty\z@\exhyphenpenalty\z@ - \doublehyphendemerits\z@\finalhyphendemerits\z@ - \strut #1\strut\@@par - \spx@verb@getwidths}% - \ifdim\spx@verb@maxwidth> - \dimexpr\linewidth+\spx@opt@verbatimmaxoverfull\fontcharwd\font`X \relax - \spx@verb@FormatLineWrap{\spx@verb@wrapPYG #1\spx@verb@wrapPYG}% - \else - \ifdim\spx@verb@minwidth< - \dimexpr\linewidth-\spx@opt@verbatimmaxunderfull\fontcharwd\font`X \relax - \spx@verb@FormatLineWrap{\spx@verb@wrapPYG #1\spx@verb@wrapPYG}% - \else - \spx@verb@FormatLineWrap{#1}% - \fi\fi -}% -% auxiliary paragraph dissector to get max and min widths -\newbox\spx@scratchbox -\def\spx@verb@getwidths {% - \unskip\unpenalty - \setbox\spx@scratchbox\lastbox - \ifvoid\spx@scratchbox - \else - \setbox\spx@scratchbox\hbox{\unhbox\spx@scratchbox}% - \ifdim\spx@verb@maxwidth<\wd\spx@scratchbox - \xdef\spx@verb@maxwidth{\number\wd\spx@scratchbox sp}% - \fi - \ifdim\spx@verb@minwidth>\wd\spx@scratchbox - \xdef\spx@verb@minwidth{\number\wd\spx@scratchbox sp}% - \fi - \expandafter\spx@verb@getwidths - \fi -}% -% auxiliary macros to implement "cut long line even in middle of word" -\catcode`Z=3 % safe delimiter -\def\spx@verb@wrapPYG{% - \futurelet\spx@nexttoken\spx@verb@wrapPYG@i -}% -\def\spx@verb@wrapPYG@i{% - \ifx\spx@nexttoken\spx@verb@wrapPYG\let\next=\@gobble\else - \ifx\spx@nexttoken\PYG\let\next=\spx@verb@wrapPYG@PYG@onebyone\else - \discretionary{}{\sphinxafterbreak}{}% - \let\next\spx@verb@wrapPYG@ii - \fi\fi - \next -}% -% Let's recognize active characters. We don't support utf8x only utf8. -% And here #1 should not have picked up (non empty) braced contents -\long\def\spx@verb@wrapPYG@ii#1{% - \ifcat\noexpand~\noexpand#1\relax% active character - \expandafter\spx@verb@wrapPYG@active - \else % non-active character, control sequence such as \PYGZdl, or empty - \expandafter\spx@verb@wrapPYG@one - \fi {#1}% -}% -\long\def\spx@verb@wrapPYG@active#1{% -% Let's hope expansion of active character does not really require arguments, -% as we certainly don't want to go into expanding upfront token stream anyway. - \expandafter\spx@verb@wrapPYG@iii#1{}{}{}{}{}{}{}{}{}Z#1% -}% -\long\def\spx@verb@wrapPYG@iii#1#2Z{% - \ifx\UTFviii@four@octets#1\let\next=\spx@verb@wrapPYG@four\else - \ifx\UTFviii@three@octets#1\let\next=\spx@verb@wrapPYG@three\else - \ifx\UTFviii@two@octets#1\let\next=\spx@verb@wrapPYG@two\else - \let\next=\spx@verb@wrapPYG@one - \fi\fi\fi - \next -}% -\long\def\spx@verb@wrapPYG@one #1{#1\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% -\long\def\spx@verb@wrapPYG@two #1#2{#1#2\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% -\long\def\spx@verb@wrapPYG@three #1#2#3{#1#2#3\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% -\long\def\spx@verb@wrapPYG@four #1#2#3#4{#1#2#3#4\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% -% Replace \PYG by itself applied one character at a time! This way breakpoints -% can be inserted. -\def\spx@verb@wrapPYG@PYG@onebyone#1#2#3{% #1 = \PYG, #2 = highlight spec, #3 = tokens - \def\spx@verb@wrapPYG@PYG@spec{{#2}}% - \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i#3Z% -}% -\def\spx@verb@wrapPYG@PYG@i{% - \ifx\spx@nexttokenZ\let\next=\spx@verb@wrapPYG@PYG@done\else - \discretionary{}{\sphinxafterbreak}{}% - \let\next\spx@verb@wrapPYG@PYG@ii - \fi - \next -}% -\def\spx@verb@wrapPYG@PYG@doneZ{\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% -\long\def\spx@verb@wrapPYG@PYG@ii#1{% - \ifcat\noexpand~\noexpand#1\relax% active character - \expandafter\spx@verb@wrapPYG@PYG@active - \else % non-active character, control sequence such as \PYGZdl, or empty - \expandafter\spx@verb@wrapPYG@PYG@one - \fi {#1}% -}% -\long\def\spx@verb@wrapPYG@PYG@active#1{% -% Let's hope expansion of active character does not really require arguments, -% as we certainly don't want to go into expanding upfront token stream anyway. - \expandafter\spx@verb@wrapPYG@PYG@iii#1{}{}{}{}{}{}{}{}{}Z#1% -}% -\long\def\spx@verb@wrapPYG@PYG@iii#1#2Z{% - \ifx\UTFviii@four@octets#1\let\next=\spx@verb@wrapPYG@PYG@four\else - \ifx\UTFviii@three@octets#1\let\next=\spx@verb@wrapPYG@PYG@three\else - \ifx\UTFviii@two@octets#1\let\next=\spx@verb@wrapPYG@PYG@two\else - \let\next=\spx@verb@wrapPYG@PYG@one - \fi\fi\fi - \next -}% -\long\def\spx@verb@wrapPYG@PYG@one#1{% - \expandafter\PYG\spx@verb@wrapPYG@PYG@spec{#1}% - \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i -}% -\long\def\spx@verb@wrapPYG@PYG@two#1#2{% - \expandafter\PYG\spx@verb@wrapPYG@PYG@spec{#1#2}% - \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i -}% -\long\def\spx@verb@wrapPYG@PYG@three#1#2#3{% - \expandafter\PYG\spx@verb@wrapPYG@PYG@spec{#1#2#3}% - \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i -}% -\long\def\spx@verb@wrapPYG@PYG@four#1#2#3#4{% - \expandafter\PYG\spx@verb@wrapPYG@PYG@spec{#1#2#3#4}% - \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i -}% -\catcode`Z 11 % -% -\g@addto@macro\FV@SetupFont{% - \sbox\sphinxcontinuationbox {\spx@opt@verbatimcontinued}% - \sbox\sphinxvisiblespacebox {\spx@opt@verbatimvisiblespace}% -}% -\newenvironment{sphinxVerbatim}{% - % first, let's check if there is a caption - \ifx\sphinxVerbatimTitle\empty - \sphinxvspacefixafterfrenchlists - \parskip\z@skip - \vskip\sphinxverbatimsmallskipamount - % there was no caption. Check if nevertheless a label was set. - \ifx\sphinxLiteralBlockLabel\empty\else - % we require some space to be sure hyperlink target from \phantomsection - % will not be separated from upcoming verbatim by a page break - \needspace{\sphinxliteralblockwithoutcaptionneedspace}% - \phantomsection\sphinxLiteralBlockLabel - \fi - \else - \parskip\z@skip - \if t\spx@opt@literalblockcappos - \vskip\spx@abovecaptionskip - \def\sphinxVerbatim@Before - {\sphinxVerbatim@Title\nointerlineskip - \kern\dimexpr-\dp\strutbox+\sphinxbelowcaptionspace - % if no frame (code-blocks inside table cells), remove - % the "verbatimsep" whitespace from the top (better visually) - \ifspx@opt@verbatimwithframe\else-\sphinxverbatimsep\fi - % caption package adds \abovecaptionskip vspace, remove it - \spx@ifcaptionpackage{-\abovecaptionskip}{}\relax}% - \else - \vskip\sphinxverbatimsmallskipamount - \def\sphinxVerbatim@After - {\nointerlineskip\kern\dimexpr\dp\strutbox - \ifspx@opt@verbatimwithframe\else-\sphinxverbatimsep\fi - \spx@ifcaptionpackage{-\abovecaptionskip}{}\relax - \sphinxVerbatim@Title}% - \fi - \def\@captype{literalblock}% - \capstart - % \sphinxVerbatimTitle must reset color - \setbox\sphinxVerbatim@TitleBox - \hbox{\begin{minipage}{\linewidth}% - % caption package may detect wrongly if top or bottom, so we help it - \spx@ifcaptionpackage - {\caption@setposition{\spx@opt@literalblockcappos}}{}% - \sphinxVerbatimTitle - \end{minipage}}% - \fi - \global\let\sphinxLiteralBlockLabel\empty - \global\let\sphinxVerbatimTitle\empty - \fboxsep\sphinxverbatimsep \fboxrule\sphinxverbatimborder - \ifspx@opt@verbatimwithframe\else\fboxrule\z@\fi - \let\FrameCommand \sphinxVerbatim@FrameCommand - \let\FirstFrameCommand\sphinxVerbatim@FirstFrameCommand - \let\MidFrameCommand \sphinxVerbatim@MidFrameCommand - \let\LastFrameCommand \sphinxVerbatim@LastFrameCommand - \ifspx@opt@verbatimhintsturnover\else - \let\sphinxVerbatim@Continued\@empty - \let\sphinxVerbatim@Continues\@empty - \fi - \ifspx@opt@verbatimwrapslines - % fancyvrb's Verbatim puts each input line in (unbreakable) horizontal boxes. - % This customization wraps each line from the input in a \vtop, thus - % allowing it to wrap and display on two or more lines in the latex output. - % - The codeline counter will be increased only once. - % - The wrapped material will not break across pages, it is impossible - % to achieve this without extensive rewrite of fancyvrb. - % - The (not used in sphinx) obeytabs option to Verbatim is - % broken by this change (showtabs and tabspace work). - \let\sphinxVerbatimFormatLine\sphinxVerbatimFormatLineWrap - \let\FV@Space\spx@verbatim@space - % Allow breaks at special characters using \PYG... macros. - \sphinxbreaksatspecials - % Breaks at punctuation characters . , ; ? ! and / (needs catcode activation) - \fvset{codes*=\sphinxbreaksviaactive}% - \else % end of conditional code for wrapping long code lines - \let\sphinxVerbatimFormatLine\sphinxVerbatimFormatLineNoWrap - \fi - \let\FancyVerbFormatLine\sphinxFancyVerbFormatLine - \VerbatimEnvironment - % workaround to fancyvrb's check of current list depth - \def\@toodeep {\advance\@listdepth\@ne}% - % The list environment is needed to control perfectly the vertical space. - % Note: \OuterFrameSep used by framed.sty is later set to \topsep hence 0pt. - % - if caption: distance from last text baseline to caption baseline is - % A+(B-F)+\ht\strutbox, A = \abovecaptionskip (default 10pt), B = - % \baselineskip, F is the framed.sty \FrameHeightAdjust macro, default 6pt. - % Formula valid for F < 10pt. - % - distance of baseline of caption to top of frame is like for tables: - % \sphinxbelowcaptionspace (=0.5\baselineskip) - % - if no caption: distance of last text baseline to code frame is S+(B-F), - % with S = \sphinxverbatimtopskip (=\smallskip) - % - and distance from bottom of frame to next text baseline is - % \baselineskip+\parskip. - % The \trivlist is used to avoid possible "too deeply nested" error. - \itemsep \z@skip - \topsep \z@skip - \partopsep \z@skip - % trivlist will set \parsep to \parskip (which itself is set to zero above) - % \leftmargin will be set to zero by trivlist - \rightmargin\z@ - \parindent \z@% becomes \itemindent. Default zero, but perhaps overwritten. - \trivlist\item\relax - \ifspx@inframed\setbox\sphinxVerbatim@ContentsBox\vbox\bgroup - \@setminipage\hsize\linewidth - % use bulk of minipage paragraph shape restores (this is needed - % in indented contexts, at least for some) - \textwidth\hsize \columnwidth\hsize \@totalleftmargin\z@ - \leftskip\z@skip \rightskip\z@skip \@rightskip\z@skip - \else - \ifsphinxverbatimwithminipage\noindent\begin{minipage}{\linewidth}\fi - \MakeFramed {% adapted over from framed.sty's snugshade environment - \advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize\@setminipage - }% - \fi - % For grid placement from \strut's in \FancyVerbFormatLine - \lineskip\z@skip - % active comma should not be overwritten by \@noligs - \ifspx@opt@verbatimwrapslines - \let\verbatim@nolig@list \sphinx@verbatim@nolig@list - \fi - % will fetch its optional arguments if any - \OriginalVerbatim -} -{% - \endOriginalVerbatim - \ifspx@inframed - \egroup % finish \sphinxVerbatim@ContentsBox vbox - \nobreak % update page totals - \ifdim\dimexpr\ht\sphinxVerbatim@ContentsBox+ - \dp\sphinxVerbatim@ContentsBox+ - \ht\sphinxVerbatim@TitleBox+ - \dp\sphinxVerbatim@TitleBox+ - 2\fboxsep+2\fboxrule+ - % try to account for external frame parameters - \FrameSep+\FrameRule+ - % Usage here of 2 baseline distances is empirical. - % In border case where code-block fits barely in remaining space, - % it gets framed and looks good but the outer frame may continue - % on top of next page and give (if no contents after code-block) - % an empty framed line, as testing showed. - 2\baselineskip+ - % now add all to accumulated page totals and compare to \pagegoal - \pagetotal+\pagedepth>\pagegoal - % long contents: do not \MakeFramed. Do make a caption (either before or - % after) if title exists. Continuation hints across pagebreaks dropped. - % FIXME? a bottom caption may end up isolated at top of next page - % (no problem with a top caption, which is default) - \spx@opt@verbatimwithframefalse - \def\sphinxVerbatim@Title{\noindent\box\sphinxVerbatim@TitleBox\par}% - \sphinxVerbatim@Before - \noindent\unvbox\sphinxVerbatim@ContentsBox\par - \sphinxVerbatim@After - \else - % short enough contents: use \MakeFramed. As it is nested, this requires - % minipage encapsulation. - \noindent\begin{minipage}{\linewidth}% - \MakeFramed {% Use it now with the fetched contents - \advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize\@setminipage - }% - \unvbox\sphinxVerbatim@ContentsBox - % some of this may be superfluous: - \par\unskip\@minipagefalse\endMakeFramed - \end{minipage}% - \fi - \else % non-nested \MakeFramed - \par\unskip\@minipagefalse\endMakeFramed % from framed.sty snugshade - \ifsphinxverbatimwithminipage\end{minipage}\fi - \fi - \endtrivlist -} -\newenvironment {sphinxVerbatimNoFrame} - {\spx@opt@verbatimwithframefalse - \VerbatimEnvironment - \begin{sphinxVerbatim}} - {\end{sphinxVerbatim}} -\newenvironment {sphinxVerbatimintable} - {% don't use a frame if in a table cell - \spx@opt@verbatimwithframefalse - \sphinxverbatimwithminipagetrue - % the literal block caption uses \sphinxcaption which is wrapper of \caption, - % but \caption must be modified because longtable redefines it to work only - % for the own table caption, and tabulary has multiple passes - \let\caption\sphinxfigcaption - % reduce above caption skip - \def\spx@abovecaptionskip{\sphinxverbatimsmallskipamount}% - \VerbatimEnvironment - \begin{sphinxVerbatim}} - {\end{sphinxVerbatim}} - - -%% PARSED LITERALS -% allow long lines to wrap like they do in code-blocks - -% this should be kept in sync with definitions in sphinx.util.texescape -\newcommand*\sphinxbreaksattexescapedchars{% - \def\do##1##2% put potential break point before character - {\def##1{\discretionary{}{\sphinxafterbreak\char`##2}{\char`##2}}}% - \do\{\{\do\textless\<\do\#\#\do\%\%\do\$\$% {, <, #, %, $ - \def\do##1##2% put potential break point after character - {\def##1{\discretionary{\char`##2}{\sphinxafterbreak}{\char`##2}}}% - \do\_\_\do\}\}\do\textasciicircum\^\do\&\&% _, }, ^, &, - \do\textgreater\>\do\textasciitilde\~% >, ~ - \do\textbackslash\\% \ -} -\newcommand*\sphinxbreaksviaactiveinparsedliteral{% - \sphinxbreaksviaactive % by default handles . , ; ? ! / - \lccode`\~`\~ % - % update \dospecials as it is used by \url - % but deactivation will already have been done hence this is unneeded: - % \expandafter\def\expandafter\dospecials\expandafter{\dospecials - % \sphinxbreaksbeforeactivelist\sphinxbreaksafteractivelist\do\-}% -} -\newcommand*\sphinxbreaksatspaceinparsedliteral{% - \lccode`~32 \lowercase{\let~}\spx@verbatim@space\lccode`\~`\~ -} -\newcommand*{\sphinxunactivateextras}{\let\do\@makeother - \sphinxbreaksbeforeactivelist\sphinxbreaksafteractivelist}% -% the \catcode13=5\relax (deactivate end of input lines) is left to callers -\newcommand*{\sphinxunactivateextrasandspace}{\catcode32=10\relax - \sphinxunactivateextras}% -% now for the modified alltt environment -\newenvironment{sphinxalltt} -{% at start of next line to workaround Emacs/AUCTeX issue with this file -\begin{alltt}% - \ifspx@opt@parsedliteralwraps - \sbox\sphinxcontinuationbox {\spx@opt@verbatimcontinued}% - \sbox\sphinxvisiblespacebox {\spx@opt@verbatimvisiblespace}% - \sphinxbreaksattexescapedchars - \sphinxbreaksviaactiveinparsedliteral - \sphinxbreaksatspaceinparsedliteral -% alltt takes care of the ' as derivative ("prime") in math mode - \everymath\expandafter{\the\everymath\sphinxunactivateextrasandspace - \catcode`\<=12\catcode`\>=12\catcode`\^=7\catcode`\_=8 }% -% not sure if displayed math (align,...) can end up in parsed-literal, anyway - \everydisplay\expandafter{\the\everydisplay - \catcode13=5 \sphinxunactivateextrasandspace - \catcode`\<=12\catcode`\>=12\catcode`\^=7\catcode`\_=8 }% - \fi } -{\end{alltt}} - -% Protect \href's first argument in contexts such as sphinxalltt (or -% \sphinxcode). Sphinx uses \#, \%, \& ... always inside \sphinxhref. -\protected\def\sphinxhref#1#2{{% - \sphinxunactivateextrasandspace % never do \scantokens with active space! -% for the \endlinechar business, https://github.com/latex3/latex2e/issues/286 - \endlinechar\m@ne\everyeof{{\endlinechar13 #2}}% keep catcode regime for #2 - \scantokens{\href{#1}}% normalise it for #1 during \href expansion -}} -% Same for \url. And also \nolinkurl for coherence. -\protected\def\sphinxurl#1{{% - \sphinxunactivateextrasandspace\everyeof{}% (<- precaution for \scantokens) - \endlinechar\m@ne\scantokens{\url{#1}}% -}} -\protected\def\sphinxnolinkurl#1{{% - \sphinxunactivateextrasandspace\everyeof{}% - \endlinechar\m@ne\scantokens{\nolinkurl{#1}}% -}} - - -%% TOPIC AND CONTENTS BOXES -% -% Again based on use of "framed.sty", this allows breakable framed boxes. -\long\def\spx@ShadowFBox#1{% - \leavevmode\begingroup - % first we frame the box #1 - \setbox\@tempboxa - \hbox{\vrule\@width\sphinxshadowrule - \vbox{\hrule\@height\sphinxshadowrule - \kern\sphinxshadowsep - \hbox{\kern\sphinxshadowsep #1\kern\sphinxshadowsep}% - \kern\sphinxshadowsep - \hrule\@height\sphinxshadowrule}% - \vrule\@width\sphinxshadowrule}% - % Now we add the shadow, like \shadowbox from fancybox.sty would do - \dimen@\dimexpr.5\sphinxshadowrule+\sphinxshadowsize\relax - \hbox{\vbox{\offinterlineskip - \hbox{\copy\@tempboxa\kern-.5\sphinxshadowrule - % add shadow on right side - \lower\sphinxshadowsize - \hbox{\vrule\@height\ht\@tempboxa \@width\dimen@}% - }% - \kern-\dimen@ % shift back vertically to bottom of frame - % and add shadow at bottom - \moveright\sphinxshadowsize - \vbox{\hrule\@width\wd\@tempboxa \@height\dimen@}% - }% - % move left by the size of right shadow so shadow adds no width - \kern-\sphinxshadowsize - }% - \endgroup -} - -% use framed.sty to allow page breaks in frame+shadow -% works well inside Lists and Quote-like environments -% produced by ``topic'' directive (or local contents) -% could nest if LaTeX writer authorized it -\newenvironment{sphinxShadowBox} - {\def\FrameCommand {\spx@ShadowFBox }% - \advance\spx@image@maxheight - -\dimexpr2\sphinxshadowrule - +2\sphinxshadowsep - +\sphinxshadowsize - +\baselineskip\relax - % configure framed.sty not to add extra vertical spacing - \ltx@ifundefined{OuterFrameSep}{}{\OuterFrameSep\z@skip}% - % the \trivlist will add the vertical spacing on top and bottom which is - % typical of center environment as used in Sphinx <= 1.4.1 - % the \noindent has the effet of an extra blank line on top, to - % imitate closely the layout from Sphinx <= 1.4.1; the \FrameHeightAdjust - % will put top part of frame on this baseline. - \def\FrameHeightAdjust {\baselineskip}% - % use package footnote to handle footnotes - \savenotes - \trivlist\item\noindent - % use a minipage if we are already inside a framed environment - \ifspx@inframed\begin{minipage}{\linewidth}\fi - \MakeFramed {\spx@inframedtrue - % framed.sty puts into "\width" the added width (=2shadowsep+2shadowrule) - % adjust \hsize to what the contents must use - \advance\hsize-\width - % adjust LaTeX parameters to behave properly in indented/quoted contexts - \FrameRestore - % typeset the contents as in a minipage (Sphinx <= 1.4.1 used a minipage and - % itemize/enumerate are therein typeset more tightly, we want to keep - % that). We copy-paste from LaTeX source code but don't do a real minipage. - \@pboxswfalse - \let\@listdepth\@mplistdepth \@mplistdepth\z@ - \@minipagerestore - \@setminipage - }% - }% - {% insert the "endminipage" code - \par\unskip - \@minipagefalse - \endMakeFramed - \ifspx@inframed\end{minipage}\fi - \endtrivlist - % output the stored footnotes - \spewnotes - } - - -%% NOTICES AND ADMONITIONS -% -% Some are quite plain -% the spx@notice@bordercolor etc are set in the sphinxadmonition environment -\newenvironment{sphinxlightbox}{% - \par - \noindent{\color{spx@notice@bordercolor}% - \rule{\linewidth}{\spx@notice@border}}\par\nobreak - {\parskip\z@skip\noindent}% - } - {% - % counteract previous possible negative skip (French lists!): - % (we can't cancel that any earlier \vskip introduced a potential pagebreak) - \sphinxvspacefixafterfrenchlists - \nobreak\vbox{\noindent\kern\@totalleftmargin - {\color{spx@notice@bordercolor}% - \rule[\dimexpr.4\baselineskip-\spx@notice@border\relax] - {\linewidth}{\spx@notice@border}}\hss}\allowbreak - }% end of sphinxlightbox environment definition -% may be renewenvironment'd by user for complete customization -\newenvironment{sphinxnote}[1] - {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}} -\newenvironment{sphinxhint}[1] - {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}} -\newenvironment{sphinximportant}[1] - {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}} -\newenvironment{sphinxtip}[1] - {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}} -% or just use the package options -% these are needed for common handling by notice environment of lightbox -% and heavybox but they are currently not used by lightbox environment -% and there is consequently no corresponding package option -\definecolor{sphinxnoteBgColor}{rgb}{1,1,1} -\definecolor{sphinxhintBgColor}{rgb}{1,1,1} -\definecolor{sphinximportantBgColor}{rgb}{1,1,1} -\definecolor{sphinxtipBgColor}{rgb}{1,1,1} - -% Others get more distinction -% Code adapted from framed.sty's "snugshade" environment. -% Nesting works (inner frames do not allow page breaks). -\newenvironment{sphinxheavybox}{\par - \setlength{\FrameRule}{\spx@notice@border}% - \setlength{\FrameSep}{\dimexpr.6\baselineskip-\FrameRule\relax} - \advance\spx@image@maxheight - -\dimexpr2\FrameRule - +2\FrameSep - +\baselineskip\relax % will happen again if nested, needed indeed! - % configure framed.sty's parameters to obtain same vertical spacing - % as for "light" boxes. We need for this to manually insert parskip glue and - % revert a skip done by framed before the frame. - \ltx@ifundefined{OuterFrameSep}{}{\OuterFrameSep\z@skip}% - \vspace{\FrameHeightAdjust} - % copied/adapted from framed.sty's snugshade - \def\FrameCommand##1{\hskip\@totalleftmargin - \fboxsep\FrameSep \fboxrule\FrameRule - \fcolorbox{spx@notice@bordercolor}{spx@notice@bgcolor}{##1}% - \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}% - \savenotes - % use a minipage if we are already inside a framed environment - \ifspx@inframed - \noindent\begin{minipage}{\linewidth} - \else - % handle case where notice is first thing in a list item (or is quoted) - \if@inlabel - \noindent\par\vspace{-\baselineskip} - \else - \vspace{\parskip} - \fi - \fi - \MakeFramed {\spx@inframedtrue - \advance\hsize-\width \@totalleftmargin\z@ \linewidth\hsize - % minipage initialization copied from LaTeX source code. - \@pboxswfalse - \let\@listdepth\@mplistdepth \@mplistdepth\z@ - \@minipagerestore - \@setminipage }% - } - {% - \par\unskip - \@minipagefalse - \endMakeFramed - \ifspx@inframed\end{minipage}\fi - % set footnotes at bottom of page - \spewnotes - % arrange for similar spacing below frame as for "light" boxes. - \vskip .4\baselineskip - }% end of sphinxheavybox environment definition -% may be renewenvironment'd by user for complete customization -\newenvironment{sphinxwarning}[1] - {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} -\newenvironment{sphinxcaution}[1] - {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} -\newenvironment{sphinxattention}[1] - {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} -\newenvironment{sphinxdanger}[1] - {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} -\newenvironment{sphinxerror}[1] - {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} -% or just use package options - -% the \colorlet of xcolor (if at all loaded) is overkill for our use case -\newcommand{\sphinxcolorlet}[2] - {\expandafter\let\csname\@backslashchar color@#1\expandafter\endcsname - \csname\@backslashchar color@#2\endcsname } - -% the main dispatch for all types of notices -\newenvironment{sphinxadmonition}[2]{% #1=type, #2=heading - % can't use #1 directly in definition of end part - \def\spx@noticetype {#1}% - % set parameters of heavybox/lightbox - \sphinxcolorlet{spx@notice@bordercolor}{sphinx#1BorderColor}% - \sphinxcolorlet{spx@notice@bgcolor}{sphinx#1BgColor}% - \spx@notice@border \dimexpr\csname spx@opt@#1border\endcsname\relax - % start specific environment, passing the heading as argument - \begin{sphinx#1}{#2}} - % workaround some LaTeX "feature" of \end command - {\edef\spx@temp{\noexpand\end{sphinx\spx@noticetype}}\spx@temp} - - -%% PYTHON DOCS MACROS AND ENVIRONMENTS -% (some macros here used by \maketitle in sphinxmanual.cls and sphinxhowto.cls) - -% \moduleauthor{name}{email} -\newcommand{\moduleauthor}[2]{} - -% \sectionauthor{name}{email} -\newcommand{\sectionauthor}[2]{} - -% Allow the release number to be specified independently of the -% \date{}. This allows the date to reflect the document's date and -% release to specify the release that is documented. -% -\newcommand{\py@release}{\releasename\space\version} -\newcommand{\version}{}% part of \py@release, used by title page and headers -% \releaseinfo is used on titlepage (sphinxmanual.cls, sphinxhowto.cls) -\newcommand{\releaseinfo}{} -\newcommand{\setreleaseinfo}[1]{\renewcommand{\releaseinfo}{#1}} -% this is inserted via template and #1=release config variable -\newcommand{\release}[1]{\renewcommand{\version}{#1}} -% this is defined by template to 'releasename' latex_elements key -\newcommand{\releasename}{} -% Fix issue in case release and releasename deliberately left blank -\newcommand{\sphinxheadercomma}{, }% used in fancyhdr header definition -\newcommand{\sphinxifemptyorblank}[1]{% -% test after one expansion of macro #1 if contents is empty or spaces - \if&\expandafter\@firstofone\detokenize\expandafter{#1}&% - \expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}% -\AtBeginDocument {% - \sphinxifemptyorblank{\releasename} - {\sphinxifemptyorblank{\version}{\let\sphinxheadercomma\empty}{}} - {}% -}% - -% Allow specification of the author's address separately from the -% author's name. This can be used to format them differently, which -% is a good thing. -% -\newcommand{\py@authoraddress}{} -\newcommand{\authoraddress}[1]{\renewcommand{\py@authoraddress}{#1}} - -% {fulllineitems} is the main environment for object descriptions. +%% INDEX, BIBLIOGRAPHY, APPENDIX, TABLE OF CONTENTS % -\newcommand{\py@itemnewline}[1]{% - \kern\labelsep - \@tempdima\linewidth - \advance\@tempdima \labelwidth\makebox[\@tempdima][l]{#1}% - \kern-\labelsep -} - -\newenvironment{fulllineitems}{% - \begin{list}{}{\labelwidth \leftmargin - \rightmargin \z@ \topsep -\parskip \partopsep \parskip - \itemsep -\parsep - \let\makelabel=\py@itemnewline}% -}{\end{list}} +\input{sphinxlatexindbibtoc.sty} -% Signatures, possibly multi-line -% -\newlength{\py@argswidth} -\newcommand{\py@sigparams}[2]{% - \parbox[t]{\py@argswidth}{#1\sphinxcode{)}#2}} -\newcommand{\pysigline}[1]{\item[{#1}]} -\newcommand{\pysiglinewithargsret}[3]{% - \settowidth{\py@argswidth}{#1\sphinxcode{(}}% - \addtolength{\py@argswidth}{-2\py@argswidth}% - \addtolength{\py@argswidth}{\linewidth}% - \item[{#1\sphinxcode{(}\py@sigparams{#2}{#3}}]} -\newcommand{\pysigstartmultiline}{% - \def\pysigstartmultiline{\vskip\smallskipamount\parskip\z@skip\itemsep\z@skip}% - \edef\pysigstopmultiline - {\noexpand\leavevmode\parskip\the\parskip\relax\itemsep\the\itemsep\relax}% - \parskip\z@skip\itemsep\z@skip -} -% Production lists +%% STYLING % -\newenvironment{productionlist}{% -% \def\sphinxoptional##1{{\Large[}##1{\Large]}} - \def\production##1##2{\\\sphinxcode{\sphinxupquote{##1}}&::=&\sphinxcode{\sphinxupquote{##2}}}% - \def\productioncont##1{\\& &\sphinxcode{\sphinxupquote{##1}}}% - \parindent=2em - \indent - \setlength{\LTpre}{0pt}% - \setlength{\LTpost}{0pt}% - \begin{longtable}[l]{lcl} -}{% - \end{longtable} -} +\input{sphinxlatexstylepage.sty} +\input{sphinxlatexstyleheadings.sty} +\input{sphinxlatexstyletext.sty} -% Definition lists; requested by AMK for HOWTO documents. Probably useful -% elsewhere as well, so keep in in the general style support. -% -\newenvironment{definitions}{% - \begin{description}% - \def\term##1{\item[{##1}]\mbox{}\\*[0mm]}% -}{% - \end{description}% -} -%% FROM DOCTUTILS LATEX WRITER -% -% The following is stuff copied from docutils' latex writer. +%% MODULE RELEASE DATA AND OBJECT DESCRIPTIONS % -\newcommand{\optionlistlabel}[1]{\normalfont\bfseries #1 \hfill}% \bf deprecated -\newenvironment{optionlist}[1] -{\begin{list}{} - {\setlength{\labelwidth}{#1} - \setlength{\rightmargin}{1cm} - \setlength{\leftmargin}{\rightmargin} - \addtolength{\leftmargin}{\labelwidth} - \addtolength{\leftmargin}{\labelsep} - \renewcommand{\makelabel}{\optionlistlabel}} -}{\end{list}} +\input{sphinxlatexobjects.sty} -\newlength{\lineblockindentation} -\setlength{\lineblockindentation}{2.5em} -\newenvironment{lineblock}[1] -{\begin{list}{} - {\setlength{\partopsep}{\parskip} - \addtolength{\partopsep}{\baselineskip} - \topsep0pt\itemsep0.15\baselineskip\parsep0pt - \leftmargin#1\relax} - \raggedright} -{\end{list}} -% From docutils.writers.latex2e -% inline markup (custom roles) -% \DUrole{#1}{#2} tries \DUrole#1{#2} -\providecommand*{\DUrole}[2]{% - \ifcsname DUrole\detokenize{#1}\endcsname - \csname DUrole\detokenize{#1}\endcsname{#2}% - \else% backwards compatibility: try \docutilsrole#1{#2} - \ifcsname docutilsrole\detokenize{#1}\endcsname - \csname docutilsrole\detokenize{#1}\endcsname{#2}% - \else - #2% - \fi - \fi -} - -\providecommand*{\DUprovidelength}[2]{% - \ifdefined#1\else\newlength{#1}\setlength{#1}{#2}\fi -} - -\DUprovidelength{\DUlineblockindent}{2.5em} -\ifdefined\DUlineblock\else - \newenvironment{DUlineblock}[1]{% - \list{}{\setlength{\partopsep}{\parskip} - \addtolength{\partopsep}{\baselineskip} - \setlength{\topsep}{0pt} - \setlength{\itemsep}{0.15\baselineskip} - \setlength{\parsep}{0pt} - \setlength{\leftmargin}{#1}} - \raggedright - } - {\endlist} -\fi - -%% TEXT STYLING -% -% to obtain straight quotes we execute \@noligs as patched by upquote, and -% \scantokens is needed in cases where it would be too late for the macro to -% first set catcodes and then fetch its argument. We also make the contents -% breakable at non-escaped . , ; ? ! / using \sphinxbreaksviaactive, -% and also at \ character (which is escaped to \textbackslash{}). -\protected\def\sphinxtextbackslashbreakbefore - {\discretionary{}{\sphinxafterbreak\sphinx@textbackslash}{\sphinx@textbackslash}} -\protected\def\sphinxtextbackslashbreakafter - {\discretionary{\sphinx@textbackslash}{\sphinxafterbreak}{\sphinx@textbackslash}} -\let\sphinxtextbackslash\sphinxtextbackslashbreakafter -% the macro must be protected if it ends up used in moving arguments, -% in 'alltt' \@noligs is done already, and the \scantokens must be avoided. -\protected\def\sphinxupquote#1{{\def\@tempa{alltt}% - \ifx\@tempa\@currenvir\else - \ifspx@opt@inlineliteralwraps - % break at . , ; ? ! / - \sphinxbreaksviaactive - % break also at \ - \let\sphinx@textbackslash\textbackslash - \let\textbackslash\sphinxtextbackslash - % by default, no continuation symbol on next line but may be added - \let\sphinxafterbreak\sphinxafterbreakofinlineliteral - % do not overwrite the comma set-up - \let\verbatim@nolig@list\sphinx@literal@nolig@list - \fi - % fix a space-gobbling issue due to LaTeX's original \do@noligs -% TODO: using \@noligs as patched by upquote.sty is now unneeded because -% either ` and ' are escaped (non-unicode engines) or they don't build -% ligatures (unicode engines). Thus remove this and unify handling of `, <, >, -% ' and - with the characters . , ; ? ! / as handled via -% \sphinxbreaksviaactive. -% Hence \sphinx@do@noligs will be removed, or rather replaced with code -% inserting discretionaries, as they allow a continuation symbol on start of -% next line to achieve common design with code-blocks. - \let\do@noligs\sphinx@do@noligs - \@noligs\endlinechar\m@ne\everyeof{}% (<- in case inside \sphinxhref) - \expandafter\scantokens - \fi {{#1}}}}% extra brace pair to fix end-space gobbling issue... -\def\sphinx@do@noligs #1{\catcode`#1\active\begingroup\lccode`\~`#1\relax - \lowercase{\endgroup\def~{\leavevmode\kern\z@\char`#1 }}} -\def\sphinx@literal@nolig@list {\do\`\do\<\do\>\do\'\do\-}% -\let\sphinxafterbreakofinlineliteral\empty - -% Some custom font markup commands. -\protected\def\sphinxstrong#1{\textbf{#1}} -\protected\def\sphinxcode#1{\texttt{#1}} -\protected\def\sphinxbfcode#1{\textbf{\sphinxcode{#1}}} -\protected\def\sphinxemail#1{\textsf{#1}} -\protected\def\sphinxtablecontinued#1{\textsf{#1}} -\protected\def\sphinxtitleref#1{\emph{#1}} -\protected\def\sphinxmenuselection#1{\emph{#1}} -\protected\def\sphinxguilabel#1{\emph{#1}} -\protected\def\sphinxkeyboard#1{\sphinxcode{#1}} -\protected\def\sphinxaccelerator#1{\underline{#1}} -\protected\def\sphinxcrossref#1{\emph{#1}} -\protected\def\sphinxtermref#1{\emph{#1}} -% \optional is used for ``[, arg]``, i.e. desc_optional nodes. -\long\protected\def\sphinxoptional#1{% - {\textnormal{\Large[}}{#1}\hspace{0.5mm}{\textnormal{\Large]}}} - -% additional customizable styling -\def\sphinxstyleindexentry #1{\texttt{#1}} -\def\sphinxstyleindexextra #1{ (\emph{#1})} -\def\sphinxstyleindexpageref #1{, \pageref{#1}} -\def\sphinxstyleindexpagemain#1{\textbf{#1}} -\def\spxentry{\@backslashchar spxentry}% let to \sphinxstyleindexentry in index -\def\spxextra{\@backslashchar spxextra}% let to \sphinxstyleindexextra in index -\def\sphinxstyleindexlettergroup #1% - {{\Large\sffamily#1}\nopagebreak\vspace{1mm}} -\def\sphinxstyleindexlettergroupDefault #1% - {{\Large\sffamily\sphinxnonalphabeticalgroupname}\nopagebreak\vspace{1mm}} -\protected\def\sphinxstyletopictitle #1{\textbf{#1}\par\medskip} -\let\sphinxstylesidebartitle\sphinxstyletopictitle -\protected\def\sphinxstyleothertitle #1{\textbf{#1}} -\protected\def\sphinxstylesidebarsubtitle #1{~\\\textbf{#1} \smallskip} -% \text.. commands do not allow multiple paragraphs -\protected\def\sphinxstyletheadfamily {\sffamily} -\protected\def\sphinxstyleemphasis #1{\emph{#1}} -\protected\def\sphinxstyleliteralemphasis#1{\emph{\sphinxcode{#1}}} -\protected\def\sphinxstylestrong #1{\textbf{#1}} -\protected\def\sphinxstyleliteralstrong#1{\sphinxbfcode{#1}} -\protected\def\sphinxstyleabbreviation #1{\textsc{#1}} -\protected\def\sphinxstyleliteralintitle#1{\sphinxcode{#1}} -\newcommand*\sphinxstylecodecontinued[1]{\footnotesize(#1)}% -\newcommand*\sphinxstylecodecontinues[1]{\footnotesize(#1)}% -% figure legend comes after caption and may contain arbitrary body elements -\newenvironment{sphinxlegend}{\par\small}{\par} -% reduce hyperref "Token not allowed in a PDF string" warnings on PDF builds -\AtBeginDocument{\pdfstringdefDisableCommands{% -% all "protected" macros possibly ending up in section titles should be here -% TODO: examine if \sphinxhref, \sphinxurl, \sphinnolinkurl should be handled - \let\sphinxstyleemphasis \@firstofone - \let\sphinxstyleliteralemphasis \@firstofone - \let\sphinxstylestrong \@firstofone - \let\sphinxstyleliteralstrong \@firstofone - \let\sphinxstyleabbreviation \@firstofone - \let\sphinxstyleliteralintitle \@firstofone - \let\sphinxupquote \@firstofone - \let\sphinxstrong \@firstofone - \let\sphinxcode \@firstofone - \let\sphinxbfcode \@firstofone - \let\sphinxemail \@firstofone - \let\sphinxcrossref \@firstofone - \let\sphinxtermref \@firstofone - \let\sphinxhyphen\sphinxhyphenforbookmarks -}} - -% Special characters -% -% This definition prevents en-dash and em-dash TeX ligatures. -% -% It inserts a potential breakpoint after the hyphen. This is to keep in sync -% with behavior in code-blocks, parsed and inline literals. For a breakpoint -% before the hyphen use \leavevmode\kern\z@- (within \makeatletter/\makeatother) -\protected\def\sphinxhyphen#1{-\kern\z@} -% The {} from texescape mark-up is kept, else -- gives en-dash in PDF bookmark -\def\sphinxhyphenforbookmarks{-} - -% For curly braces inside \index macro -\def\sphinxleftcurlybrace{\{} -\def\sphinxrightcurlybrace{\}} +% FIXME: this line should be dropped, as "9" is default anyhow. +\ifdefined\pdfcompresslevel\pdfcompresslevel = 9 \fi -% Declare Unicode characters used by linux tree command to pdflatex utf8/utf8x -\def\spx@bd#1#2{% - \leavevmode - \begingroup - \ifx\spx@bd@height \@undefined\def\spx@bd@height{\baselineskip}\fi - \ifx\spx@bd@width \@undefined\setbox0\hbox{0}\def\spx@bd@width{\wd0 }\fi - \ifx\spx@bd@thickness\@undefined\def\spx@bd@thickness{.6\p@}\fi - \ifx\spx@bd@lower \@undefined\def\spx@bd@lower{\dp\strutbox}\fi - \lower\spx@bd@lower#1{#2}% - \endgroup -}% -\@namedef{sphinx@u2500}% BOX DRAWINGS LIGHT HORIZONTAL - {\spx@bd{\vbox to\spx@bd@height} - {\vss\hrule\@height\spx@bd@thickness - \@width\spx@bd@width\vss}}% -\@namedef{sphinx@u2502}% BOX DRAWINGS LIGHT VERTICAL - {\spx@bd{\hb@xt@\spx@bd@width} - {\hss\vrule\@height\spx@bd@height - \@width \spx@bd@thickness\hss}}% -\@namedef{sphinx@u2514}% BOX DRAWINGS LIGHT UP AND RIGHT - {\spx@bd{\hb@xt@\spx@bd@width} - {\hss\raise.5\spx@bd@height - \hb@xt@\z@{\hss\vrule\@height.5\spx@bd@height - \@width \spx@bd@thickness\hss}% - \vbox to\spx@bd@height{\vss\hrule\@height\spx@bd@thickness - \@width.5\spx@bd@width\vss}}}% -\@namedef{sphinx@u251C}% BOX DRAWINGS LIGHT VERTICAL AND RIGHT - {\spx@bd{\hb@xt@\spx@bd@width} - {\hss - \hb@xt@\z@{\hss\vrule\@height\spx@bd@height - \@width \spx@bd@thickness\hss}% - \vbox to\spx@bd@height{\vss\hrule\@height\spx@bd@thickness - \@width.5\spx@bd@width\vss}}}% -\protected\def\sphinxunichar#1{\@nameuse{sphinx@u#1}}% -% Tell TeX about pathological hyphenation cases: -\hyphenation{Base-HTTP-Re-quest-Hand-ler} \endinput diff --git a/sphinx/texinputs/sphinxlatexadmonitions.sty b/sphinx/texinputs/sphinxlatexadmonitions.sty new file mode 100644 index 0000000000..1e418c8c22 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexadmonitions.sty @@ -0,0 +1,148 @@ +%% NOTICES AND ADMONITIONS +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexadmonitions.sty}[2021/01/27 admonitions] + +% Provides support for this output mark-up from Sphinx latex writer: +% +% - sphinxadmonition (environment) +% This is a dispatch supporting +% +% - note, hint, important, tip (via sphinxlightbox) +% - warning, caution, attention, danger, error (via sphinxheavybox) +% +% Each sphinx environment can be redefined by user. +% The defaults are customizable via various colour and dimension +% settings, cf sphinx docs (latex customization). +% +% Requires: +\RequirePackage{framed}% used by sphinxheavybox +% +% Dependencies (they do not need to be defined at time of loading): +% - of course the various colour and dimension options handled via sphinx.sty +% - \sphinxstrong (for sphinxlightbox and sphinxheavybox) +% - dimension register \spx@image@maxheight from sphinxlatexgraphics.sty +% - \savenotes/\spewnotes from sphinxpackagefootnote (for sphinxheavybox) + +% Provides: (also in sphinxlatexliterals.sty) +\providecommand*\sphinxvspacefixafterfrenchlists{% + \ifvmode\ifdim\lastskip<\z@ \vskip\parskip\fi\else\par\fi +} + +% Some are quite plain +% the spx@notice@bordercolor etc are set in the sphinxadmonition environment +\newenvironment{sphinxlightbox}{% + \par + \noindent{\color{spx@notice@bordercolor}% + \rule{\linewidth}{\spx@notice@border}}\par\nobreak + {\parskip\z@skip\noindent}% + } + {% + % counteract previous possible negative skip (French lists!): + % (we can't cancel that any earlier \vskip introduced a potential pagebreak) + \sphinxvspacefixafterfrenchlists + \nobreak\vbox{\noindent\kern\@totalleftmargin + {\color{spx@notice@bordercolor}% + \rule[\dimexpr.4\baselineskip-\spx@notice@border\relax] + {\linewidth}{\spx@notice@border}}\hss}\allowbreak + }% end of sphinxlightbox environment definition +% may be renewenvironment'd by user for complete customization +\newenvironment{sphinxnote}[1] + {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}} +\newenvironment{sphinxhint}[1] + {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}} +\newenvironment{sphinximportant}[1] + {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}} +\newenvironment{sphinxtip}[1] + {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}} +% or just use the package options +% these are needed for common handling by notice environment of lightbox +% and heavybox but they are currently not used by lightbox environment +% and there is consequently no corresponding package option +\definecolor{sphinxnoteBgColor}{rgb}{1,1,1} +\definecolor{sphinxhintBgColor}{rgb}{1,1,1} +\definecolor{sphinximportantBgColor}{rgb}{1,1,1} +\definecolor{sphinxtipBgColor}{rgb}{1,1,1} + +% Others get more distinction +% Code adapted from framed.sty's "snugshade" environment. +% Nesting works (inner frames do not allow page breaks). +\newenvironment{sphinxheavybox}{\par + \setlength{\FrameRule}{\spx@notice@border}% + \setlength{\FrameSep}{\dimexpr.6\baselineskip-\FrameRule\relax} + \advance\spx@image@maxheight + -\dimexpr2\FrameRule + +2\FrameSep + +\baselineskip\relax % will happen again if nested, needed indeed! + % configure framed.sty's parameters to obtain same vertical spacing + % as for "light" boxes. We need for this to manually insert parskip glue and + % revert a skip done by framed before the frame. + \ltx@ifundefined{OuterFrameSep}{}{\OuterFrameSep\z@skip}% + \vspace{\FrameHeightAdjust} + % copied/adapted from framed.sty's snugshade + \def\FrameCommand##1{\hskip\@totalleftmargin + \fboxsep\FrameSep \fboxrule\FrameRule + \fcolorbox{spx@notice@bordercolor}{spx@notice@bgcolor}{##1}% + \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}% + \savenotes + % use a minipage if we are already inside a framed environment + \ifspx@inframed + \noindent\begin{minipage}{\linewidth} + \else + % handle case where notice is first thing in a list item (or is quoted) + \if@inlabel + \noindent\par\vspace{-\baselineskip} + \else + \vspace{\parskip} + \fi + \fi + \MakeFramed {\spx@inframedtrue + \advance\hsize-\width \@totalleftmargin\z@ \linewidth\hsize + % minipage initialization copied from LaTeX source code. + \@pboxswfalse + \let\@listdepth\@mplistdepth \@mplistdepth\z@ + \@minipagerestore + \@setminipage }% + } + {% + \par\unskip + \@minipagefalse + \endMakeFramed + \ifspx@inframed\end{minipage}\fi + % set footnotes at bottom of page + \spewnotes + % arrange for similar spacing below frame as for "light" boxes. + \vskip .4\baselineskip + }% end of sphinxheavybox environment definition +% may be renewenvironment'd by user for complete customization +\newenvironment{sphinxwarning}[1] + {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} +\newenvironment{sphinxcaution}[1] + {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} +\newenvironment{sphinxattention}[1] + {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} +\newenvironment{sphinxdanger}[1] + {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} +\newenvironment{sphinxerror}[1] + {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}} +% or just use package options + +% the \colorlet of xcolor (if at all loaded) is overkill for our use case +\newcommand{\sphinxcolorlet}[2] + {\expandafter\let\csname\@backslashchar color@#1\expandafter\endcsname + \csname\@backslashchar color@#2\endcsname } + +% the main dispatch for all types of notices +\newenvironment{sphinxadmonition}[2]{% #1=type, #2=heading + % can't use #1 directly in definition of end part + \def\spx@noticetype {#1}% + % set parameters of heavybox/lightbox + \sphinxcolorlet{spx@notice@bordercolor}{sphinx#1BorderColor}% + \sphinxcolorlet{spx@notice@bgcolor}{sphinx#1BgColor}% + \spx@notice@border \dimexpr\csname spx@opt@#1border\endcsname\relax + % start specific environment, passing the heading as argument + \begin{sphinx#1}{#2}} + % workaround some LaTeX "feature" of \end command + {\edef\spx@temp{\noexpand\end{sphinx\spx@noticetype}}\spx@temp} + +\endinput diff --git a/sphinx/texinputs/sphinxlatexgraphics.sty b/sphinx/texinputs/sphinxlatexgraphics.sty new file mode 100644 index 0000000000..fd0aae6386 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexgraphics.sty @@ -0,0 +1,122 @@ +%% GRAPHICS +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexgraphics.sty}[2021/01/27 graphics] + +% Provides support for this output mark-up from Sphinx latex writer: +% +% - macros: +% +% - \sphinxfigcaption +% - \sphinxincludegraphics +% +% - environments: +% +% - sphinxfigure-in-table +% +% May change: +% +% - \sphinxcaption (at begin document) +% +% Also provides: +% +% - \sphinxsafeincludegraphics (default of \sphinxincludegraphics since 2.0) +% - \spx@image@maxheight dimension (used by sphinxlatexadmonitions.sty) +% - \spx@image@box scratch box register (also used by sphinxlatexliterals.sty) +% +% Requires: +% \RequirePackage{graphicx}% done in sphinx.sty +\RequirePackage{amstext}% needed for \firstchoice@true(false) + +% \sphinxincludegraphics resizes images larger than the TeX \linewidth (which +% is adjusted in indented environments), or taller than a certain maximal +% height (usually \textheight and this is reduced in the environments which use +% framed.sty to avoid infinite loop if image too tall). +% +% In case height or width options are present the rescaling is done +% (since 2.0), in a way keeping the width:height ratio either native from +% image or from the width and height options if both were present. +% +\newdimen\spx@image@maxheight +\AtBeginDocument{\spx@image@maxheight\textheight} + +% box scratch register +\newbox\spx@image@box +\newcommand*{\sphinxsafeincludegraphics}[2][]{% + % #1 contains possibly width=, height=, but no scale= since 1.8.4 + \setbox\spx@image@box\hbox{\includegraphics[#1,draft]{#2}}% + \in@false % use some handy boolean flag + \ifdim \wd\spx@image@box>\linewidth + \in@true % flag to remember to adjust options and set box dimensions + % compute height which results from rescaling width to \linewidth + % and keep current aspect ratio. multiply-divide in \numexpr uses + % temporarily doubled precision, hence no overflow. (of course we + % assume \ht is not a few sp's below \maxdimen...(about 16384pt). + \edef\spx@image@rescaledheight % with sp units + {\the\numexpr\ht\spx@image@box + *\linewidth/\wd\spx@image@box sp}% + \ifdim\spx@image@rescaledheight>\spx@image@maxheight + % the rescaled height will be too big, so it is height which decides + % the rescaling factor + \def\spx@image@requiredheight{\spx@image@maxheight}% dimen register + \edef\spx@image@requiredwidth % with sp units + {\the\numexpr\wd\spx@image@box + *\spx@image@maxheight/\ht\spx@image@box sp}% + % TODO: decide if this commented-out block could be needed due to + % rounding in numexpr operations going up + % \ifdim\spx@image@requiredwidth>\linewidth + % \def\spx@image@requiredwidth{\linewidth}% dimen register + % \fi + \else + \def\spx@image@requiredwidth{\linewidth}% dimen register + \let\spx@image@requiredheight\spx@image@rescaledheight% sp units + \fi + \else + % width is ok, let's check height + \ifdim\ht\spx@image@box>\spx@image@maxheight + \in@true + \edef\spx@image@requiredwidth % with sp units + {\the\numexpr\wd\spx@image@box + *\spx@image@maxheight/\ht\spx@image@box sp}% + \def\spx@image@requiredheight{\spx@image@maxheight}% dimen register + \fi + \fi % end of check of width and height + \ifin@ + \setbox\spx@image@box + \hbox{\includegraphics + [%#1,% contained only width and/or height and overruled anyhow + width=\spx@image@requiredwidth,height=\spx@image@requiredheight]% + {#2}}% + % \includegraphics does not set box dimensions to the exactly + % requested ones, see https://github.com/latex3/latex2e/issues/112 + \wd\spx@image@box\spx@image@requiredwidth + \ht\spx@image@box\spx@image@requiredheight + \leavevmode\box\spx@image@box + \else + % here we do not modify the options, no need to adjust width and height + % on output, they will be computed exactly as with "draft" option + \setbox\spx@image@box\box\voidb@x % clear memory + \includegraphics[#1]{#2}% + \fi +}% +% Use the "safe" one by default (2.0) +\def\sphinxincludegraphics{\sphinxsafeincludegraphics} + + +%% FIGURE IN TABLE +% +\newenvironment{sphinxfigure-in-table}[1][\linewidth]{% + \def\@captype{figure}% + \sphinxsetvskipsforfigintablecaption + \begin{minipage}{#1}% +}{\end{minipage}} +% tabulary expands twice contents, we need to prevent double counter stepping +\newcommand*\sphinxfigcaption + {\ifx\equation$%$% this is trick to identify tabulary first pass + \firstchoice@false\else\firstchoice@true\fi + \spx@originalcaption } +\newcommand*\sphinxsetvskipsforfigintablecaption + {\abovecaptionskip\smallskipamount + \belowcaptionskip\smallskipamount} + +\endinput diff --git a/sphinx/texinputs/sphinxlatexindbibtoc.sty b/sphinx/texinputs/sphinxlatexindbibtoc.sty new file mode 100644 index 0000000000..79e30a1f19 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexindbibtoc.sty @@ -0,0 +1,69 @@ +%% INDEX, BIBLIOGRAPHY, APPENDIX, TABLE OF CONTENTS +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexindbibtoc.sty}[2021/01/27 index, bib., toc] + +% Provides support for this output mark-up from Sphinx latex writer: +% +% - environments: (backup defaults or get redefined) +% +% - sphinxtheindex (direct mark-up or via python.ist or sphinx.xdy) +% - sphinxthebibliography +% +% - macros: (defines defaults) +% +% - \sphinxmaketitle +% - \sphinxtableofcontents +% - \sphinxnonalphabeticalgroupname +% - \sphinxsymbolsname +% - \sphinxnumbersname +% - \sphinxcite +% +% Requires: +\RequirePackage{makeidx} + +% fix the double index and bibliography on the table of contents +% in jsclasses (Japanese standard document classes) +\ifx\@jsc@uplatextrue\@undefined\else + \renewenvironment{sphinxtheindex} + {\cleardoublepage\phantomsection + \begin{theindex}} + {\end{theindex}} + + \renewenvironment{sphinxthebibliography}[1] + {\cleardoublepage% \phantomsection % not needed here since TeXLive 2010's hyperref + \begin{thebibliography}{#1}} + {\end{thebibliography}} +\fi + +% disable \@chappos in Appendix in pTeX +\ifx\kanjiskip\@undefined\else + \let\py@OldAppendix=\appendix + \renewcommand{\appendix}{ + \py@OldAppendix + \gdef\@chappos{} + } +\fi + +% make commands known to non-Sphinx document classes +\providecommand*{\sphinxmaketitle}{\maketitle} +\providecommand*{\sphinxtableofcontents}{\tableofcontents} +\ltx@ifundefined{sphinxthebibliography} + {\newenvironment + {sphinxthebibliography}{\begin{thebibliography}}{\end{thebibliography}}% + } + {}% else clause of \ltx@ifundefined +\ltx@ifundefined{sphinxtheindex} + {\newenvironment{sphinxtheindex}{\begin{theindex}}{\end{theindex}}}% + {}% else clause of \ltx@ifundefined + +% for usage with xindy: this string gets internationalized in preamble +\newcommand*{\sphinxnonalphabeticalgroupname}{} +% redefined in preamble, headings for makeindex produced index +\newcommand*{\sphinxsymbolsname}{} +\newcommand*{\sphinxnumbersname}{} + +\protected\def\sphinxcite{\cite} + + +\endinput diff --git a/sphinx/texinputs/sphinxlatexlists.sty b/sphinx/texinputs/sphinxlatexlists.sty new file mode 100644 index 0000000000..3860090c29 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexlists.sty @@ -0,0 +1,97 @@ +%% ALPHANUMERIC LIST ITEMS +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexlists.sty}[2021/01/27 lists] + +% Provides support for this output mark-up from Sphinx latex writer: +% - \sphinxsetlistlabels + +% Dependencies: the \spx@opt@maxlistdepth from sphinx.sty + +\newcommand\sphinxsetlistlabels[5] +{% #1 = style, #2 = enum, #3 = enumnext, #4 = prefix, #5 = suffix + % #2 and #3 are counters used by enumerate environement e.g. enumi, enumii. + % #1 is a macro such as \arabic or \alph + % prefix and suffix are strings (by default empty and a dot). + \@namedef{the#2}{#1{#2}}% + \@namedef{label#2}{#4\@nameuse{the#2}#5}% + \@namedef{p@#3}{\@nameuse{p@#2}#4\@nameuse{the#2}#5}% +}% + + +%% MAXLISTDEPTH +% +% remove LaTeX's cap on nesting depth if 'maxlistdepth' key used. +% This is a hack, which works with the standard classes: it assumes \@toodeep +% is always used in "true" branches: "\if ... \@toodeep \else .. \fi." + +% will force use the "false" branch (if there is one) +\def\spx@toodeep@hack{\fi\iffalse} + +% do nothing if 'maxlistdepth' key not used or if package enumitem loaded. +\ifnum\spx@opt@maxlistdepth=\z@\expandafter\@gobbletwo\fi +\AtBeginDocument{% +\@ifpackageloaded{enumitem}{\remove@to@nnil}{}% + \let\spx@toodeepORI\@toodeep + \def\@toodeep{% + \ifnum\@listdepth<\spx@opt@maxlistdepth\relax + \expandafter\spx@toodeep@hack + \else + \expandafter\spx@toodeepORI + \fi}% +% define all missing \@list... macros + \count@\@ne + \loop + \ltx@ifundefined{@list\romannumeral\the\count@} + {\iffalse}{\iftrue\advance\count@\@ne}% + \repeat + \loop + \ifnum\count@>\spx@opt@maxlistdepth\relax\else + \expandafter\let + \csname @list\romannumeral\the\count@\expandafter\endcsname + \csname @list\romannumeral\the\numexpr\count@-\@ne\endcsname + % workaround 2.6--3.2d babel-french issue (fixed in 3.2e; no change needed) + \ltx@ifundefined{leftmargin\romannumeral\the\count@} + {\expandafter\let + \csname leftmargin\romannumeral\the\count@\expandafter\endcsname + \csname leftmargin\romannumeral\the\numexpr\count@-\@ne\endcsname}{}% + \advance\count@\@ne + \repeat +% define all missing enum... counters and \labelenum... macros and \p@enum.. + \count@\@ne + \loop + \ltx@ifundefined{c@enum\romannumeral\the\count@} + {\iffalse}{\iftrue\advance\count@\@ne}% + \repeat + \loop + \ifnum\count@>\spx@opt@maxlistdepth\relax\else + \newcounter{enum\romannumeral\the\count@}% + \expandafter\def + \csname labelenum\romannumeral\the\count@\expandafter\endcsname + \expandafter + {\csname theenum\romannumeral\the\numexpr\count@\endcsname.}% + \expandafter\def + \csname p@enum\romannumeral\the\count@\expandafter\endcsname + \expandafter + {\csname p@enum\romannumeral\the\numexpr\count@-\@ne\expandafter + \endcsname\csname theenum\romannumeral\the\numexpr\count@-\@ne\endcsname.}% + \advance\count@\@ne + \repeat +% define all missing labelitem... macros + \count@\@ne + \loop + \ltx@ifundefined{labelitem\romannumeral\the\count@} + {\iffalse}{\iftrue\advance\count@\@ne}% + \repeat + \loop + \ifnum\count@>\spx@opt@maxlistdepth\relax\else + \expandafter\let + \csname labelitem\romannumeral\the\count@\expandafter\endcsname + \csname labelitem\romannumeral\the\numexpr\count@-\@ne\endcsname + \advance\count@\@ne + \repeat + \PackageInfo{sphinx}{maximal list depth extended to \spx@opt@maxlistdepth}% +\@gobble\@nnil +} + +\endinput diff --git a/sphinx/texinputs/sphinxlatexliterals.sty b/sphinx/texinputs/sphinxlatexliterals.sty new file mode 100644 index 0000000000..a2943b2dc2 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexliterals.sty @@ -0,0 +1,774 @@ +%% LITERAL BLOCKS +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexliterals.sty}[2021/01/27 code-blocks and parsed literals] + +% Provides support for this output mark-up from Sphinx latex writer: +% +% - macros: +% - \sphinxLiteralBlockLabel +% - \sphinxSetupCaptionForVerbatim +% - \sphinxSetupCodeBlockInFootnote +% - \sphinxhref +% - \sphinxnolinkurl +% - \sphinxresetverbatimhllines +% - \sphinxunactivateextrasandspace +% - \sphinxupquote +% - \sphinxurl +% +% - environments: +% - sphinxVerbatim +% - sphinxVerbatimintable +% - sphinxalltt +% +% Dependency: +% +% - hyperref (for \phantomsection and \capstart) (loaded later) +% +% Executes \RequirePackage for: +% +% - framed +% - fancyvrb +% - alltt +% - upquote +% - needspace + +% also in sphinxlatexadmonitions.sty: +% This is a workaround to a "feature" of French lists, when literal block +% follows immediately; usable generally (does only \par then), a priori... +\providecommand*\sphinxvspacefixafterfrenchlists{% + \ifvmode\ifdim\lastskip<\z@ \vskip\parskip\fi\else\par\fi +} + +% For framing allowing pagebreaks +\RequirePackage{framed} +% For source code +% MEMO: fancyvrb is used mainly to +% 1- control horizontal and vertical spacing +% 2- optional line numbering +% 3- optional line emphasizing +% 4- while still allowing expansion of Pygments latex mark-up +% Other aspects such as framing, caption handling, codeline wrapping are +% added on top of it. We should stop using fancyvrb and implement +% 1, 2, 3, 4 by own Sphinx fully native Verbatim. This would allow to solve +% limitations with wrapped long code line not allowing page break. +\RequirePackage{fancyvrb} +% For parsed-literal blocks. +\RequirePackage{alltt} +% Display "real" single quotes in literal blocks. +\RequirePackage{upquote} +% Skip to next page if not enough space at bottom +\RequirePackage{needspace} + +% Based on use of "fancyvrb.sty"'s Verbatim. +% - with framing allowing page breaks ("framed.sty") +% - with breaking of long lines (exploits Pygments mark-up), +% - with possibly of a top caption, non-separable by pagebreak. +% - and usable inside tables or footnotes ("sphinxpackagefootnote.sty"). + +% for emphasizing lines +\define@key{FV}{hllines}{\def\sphinx@verbatim@checkifhl##1{\in@{, ##1,}{#1}}} +% sphinxVerbatim must be usable by third party without requiring hllines set-up +\def\sphinxresetverbatimhllines{\def\sphinx@verbatim@checkifhl##1{\in@false}} +\sphinxresetverbatimhllines + +% Prior to Sphinx 1.5, \Verbatim and \endVerbatim were modified by Sphinx. +% The aliases defined here are used in sphinxVerbatim environment and can +% serve as hook-points with no need to modify \Verbatim itself. +\let\OriginalVerbatim \Verbatim +\let\endOriginalVerbatim\endVerbatim + +% for captions of literal blocks +% at start of caption title +\newcommand*{\fnum@literalblock}{\literalblockname\nobreakspace\theliteralblock} +% this will be overwritten in document preamble by Babel translation +\newcommand*{\literalblockname}{Listing } +% file extension needed for \caption's good functioning, the file is created +% only if a \listof{literalblock}{foo} command is encountered, which is +% analogous to \listoffigures, but for the code listings (foo = chosen title.) +\newcommand*{\ext@literalblock}{lol} + +% if forced use of minipage encapsulation is needed (e.g. table cells) +\newif\ifsphinxverbatimwithminipage \sphinxverbatimwithminipagefalse + +% Framing macro for use with framed.sty's \FrameCommand +% - it obeys current indentation, +% - frame is \fboxsep separated from the contents, +% - the contents use the full available text width, +% - #1 = color of frame, #2 = color of background, +% - #3 = above frame, #4 = below frame, #5 = within frame, +% - #3 and #4 must be already typeset boxes; they must issue \normalcolor +% or similar, else, they are under scope of color #1 +\long\def\spx@fcolorbox #1#2#3#4#5{% + \hskip\@totalleftmargin + \hskip-\fboxsep\hskip-\fboxrule + % use of \color@b@x here is compatible with both xcolor.sty and color.sty + \color@b@x {\color{#1}\spx@CustomFBox{#3}{#4}}{\color{#2}}{#5}% + \hskip-\fboxsep\hskip-\fboxrule + \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth +}% +% #1 = for material above frame, such as a caption or a "continued" hint +% #2 = for material below frame, such as a caption or "continues on next page" +% #3 = actual contents, which will be typeset with a background color +\long\def\spx@CustomFBox#1#2#3{% + \begingroup + \setbox\@tempboxa\hbox{{#3}}% inner braces to avoid color leaks + \vbox{#1% above frame + % draw frame border _latest_ to avoid pdf viewer issue + \kern\fboxrule + \hbox{\kern\fboxrule + \copy\@tempboxa + \kern-\wd\@tempboxa\kern-\fboxrule + \vrule\@width\fboxrule + \kern\wd\@tempboxa + \vrule\@width\fboxrule}% + \kern-\dimexpr\ht\@tempboxa+\dp\@tempboxa+\fboxrule\relax + \hrule\@height\fboxrule + \kern\dimexpr\ht\@tempboxa+\dp\@tempboxa\relax + \hrule\@height\fboxrule + #2% below frame + }% + \endgroup +}% +\def\spx@fcolorbox@put@c#1{% hide width from framed.sty measuring + \moveright\dimexpr\fboxrule+.5\wd\@tempboxa\hb@xt@\z@{\hss#1\hss}% +}% +\def\spx@fcolorbox@put@r#1{% right align with contents, width hidden + \moveright\dimexpr\fboxrule+\wd\@tempboxa-\fboxsep\hb@xt@\z@{\hss#1}% +}% +\def\spx@fcolorbox@put@l#1{% left align with contents, width hidden + \moveright\dimexpr\fboxrule+\fboxsep\hb@xt@\z@{#1\hss}% +}% +% +\def\sphinxVerbatim@Continued + {\csname spx@fcolorbox@put@\spx@opt@verbatimcontinuedalign\endcsname + {\normalcolor\sphinxstylecodecontinued\literalblockcontinuedname}}% +\def\sphinxVerbatim@Continues + {\csname spx@fcolorbox@put@\spx@opt@verbatimcontinuesalign\endcsname + {\normalcolor\sphinxstylecodecontinues\literalblockcontinuesname}}% +\def\sphinxVerbatim@Title + {\spx@fcolorbox@put@c{\unhcopy\sphinxVerbatim@TitleBox}}% +\let\sphinxVerbatim@Before\@empty +\let\sphinxVerbatim@After\@empty +% Defaults are redefined in document preamble according to language +\newcommand*\literalblockcontinuedname{continued from previous page}% +\newcommand*\literalblockcontinuesname{continues on next page}% +% +\def\spx@verbatimfcolorbox{\spx@fcolorbox{VerbatimBorderColor}{VerbatimColor}}% +\def\sphinxVerbatim@FrameCommand + {\spx@verbatimfcolorbox\sphinxVerbatim@Before\sphinxVerbatim@After}% +\def\sphinxVerbatim@FirstFrameCommand + {\spx@verbatimfcolorbox\sphinxVerbatim@Before\sphinxVerbatim@Continues}% +\def\sphinxVerbatim@MidFrameCommand + {\spx@verbatimfcolorbox\sphinxVerbatim@Continued\sphinxVerbatim@Continues}% +\def\sphinxVerbatim@LastFrameCommand + {\spx@verbatimfcolorbox\sphinxVerbatim@Continued\sphinxVerbatim@After}% + +% For linebreaks inside Verbatim environment from package fancyvrb. +\newbox\sphinxcontinuationbox +\newbox\sphinxvisiblespacebox +\newcommand*\sphinxafterbreak {\copy\sphinxcontinuationbox} + +% Take advantage of the already applied Pygments mark-up to insert +% potential linebreaks for TeX processing. +% {, <, #, %, $, ' and ": go to next line. +% _, }, ^, &, >, -, ~, and \: stay at end of broken line. +% Use of \textquotesingle for straight quote. +% FIXME: convert this to package options ? +\newcommand*\sphinxbreaksbeforelist {% + \do\PYGZob\{\do\PYGZlt\<\do\PYGZsh\#\do\PYGZpc\%% {, <, #, %, + \do\PYGZdl\$\do\PYGZdq\"% $, " + \def\PYGZsq + {\discretionary{}{\sphinxafterbreak\textquotesingle}{\textquotesingle}}% ' +} +\newcommand*\sphinxbreaksafterlist {% + \do\PYGZus\_\do\PYGZcb\}\do\PYGZca\^\do\PYGZam\&% _, }, ^, &, + \do\PYGZgt\>\do\PYGZhy\-\do\PYGZti\~% >, -, ~ + \do\PYGZbs\\% \ +} +\newcommand*\sphinxbreaksatspecials {% + \def\do##1##2% + {\def##1{\discretionary{}{\sphinxafterbreak\char`##2}{\char`##2}}}% + \sphinxbreaksbeforelist + \def\do##1##2% + {\def##1{\discretionary{\char`##2}{\sphinxafterbreak}{\char`##2}}}% + \sphinxbreaksafterlist +} + +\def\sphinx@verbatim@nolig@list {\do \`}% +% Some characters . , ; ? ! / are neither pygmentized nor "tex-escaped". +% This macro makes them "active" and they will insert potential linebreaks. +% Not compatible with math mode (cf \sphinxunactivateextras). +\newcommand*\sphinxbreaksbeforeactivelist {}% none +\newcommand*\sphinxbreaksafteractivelist {\do\.\do\,\do\;\do\?\do\!\do\/} +\newcommand*\sphinxbreaksviaactive {% + \def\do##1{\lccode`\~`##1% + \lowercase{\def~}{\discretionary{}{\sphinxafterbreak\char`##1}{\char`##1}}% + \catcode`##1\active}% + \sphinxbreaksbeforeactivelist + \def\do##1{\lccode`\~`##1% + \lowercase{\def~}{\discretionary{\char`##1}{\sphinxafterbreak}{\char`##1}}% + \catcode`##1\active}% + \sphinxbreaksafteractivelist + \lccode`\~`\~ +} + +% If the linebreak is at a space, the latter will be displayed as visible +% space at end of first line, and a continuation symbol starts next line. +\def\spx@verbatim@space {% + \nobreak\hskip\z@skip + \discretionary{\copy\sphinxvisiblespacebox}{\sphinxafterbreak} + {\kern\fontdimen2\font}% +}% + +% if the available space on page is less than \literalblockneedspace, insert pagebreak +\newcommand{\sphinxliteralblockneedspace}{5\baselineskip} +\newcommand{\sphinxliteralblockwithoutcaptionneedspace}{1.5\baselineskip} +% The title (caption) is specified from outside as macro \sphinxVerbatimTitle. +% \sphinxVerbatimTitle is reset to empty after each use of Verbatim. +\newcommand*\sphinxVerbatimTitle {} +% This box to typeset the caption before framed.sty multiple passes for framing. +\newbox\sphinxVerbatim@TitleBox +% This box to measure contents if nested as inner \MakeFramed requires then +% minipage encapsulation but too long contents then break outer \MakeFramed +\newbox\sphinxVerbatim@ContentsBox +% Holder macro for labels of literal blocks. Set-up by LaTeX writer. +\newcommand*\sphinxLiteralBlockLabel {} +\newcommand*\sphinxSetupCaptionForVerbatim [1] +{% + \sphinxvspacefixafterfrenchlists + \needspace{\sphinxliteralblockneedspace}% +% insert a \label via \sphinxLiteralBlockLabel +% reset to normal the color for the literal block caption + \def\sphinxVerbatimTitle + {\py@NormalColor\sphinxcaption{\sphinxLiteralBlockLabel #1}}% +} +\newcommand*\sphinxSetupCodeBlockInFootnote {% + \fvset{fontsize=\footnotesize}\let\caption\sphinxfigcaption + \sphinxverbatimwithminipagetrue % reduces vertical spaces + % we counteract (this is in a group) the \@normalsize from \caption + \let\normalsize\footnotesize\let\@parboxrestore\relax + \def\spx@abovecaptionskip{\sphinxverbatimsmallskipamount}% +} +\newcommand*{\sphinxverbatimsmallskipamount}{\smallskipamount} +% serves to implement line highlighting and line wrapping +\newcommand\sphinxFancyVerbFormatLine[1]{% + \expandafter\sphinx@verbatim@checkifhl\expandafter{\the\FV@CodeLineNo}% + \ifin@ + \sphinxVerbatimHighlightLine{#1}% + \else + \sphinxVerbatimFormatLine{#1}% + \fi +}% +\newcommand\sphinxVerbatimHighlightLine[1]{% + \edef\sphinxrestorefboxsep{\fboxsep\the\fboxsep\relax}% + \fboxsep0pt\relax % cf LaTeX bug graphics/4524 + \colorbox{sphinxVerbatimHighlightColor}% + {\sphinxrestorefboxsep\sphinxVerbatimFormatLine{#1}}% + % no need to restore \fboxsep here, as this ends up in a \hbox from fancyvrb +}% +% \sphinxVerbatimFormatLine will be set locally to one of those two: +\newcommand\sphinxVerbatimFormatLineWrap{% + \hsize\linewidth + \ifspx@opt@verbatimforcewraps + \expandafter\spx@verb@FormatLineForceWrap + \else\expandafter\spx@verb@FormatLineWrap + \fi +}% +\newcommand\sphinxVerbatimFormatLineNoWrap[1]{\hb@xt@\linewidth{\strut #1\hss}}% +\long\def\spx@verb@FormatLineWrap#1{% + \vtop{\raggedright\hyphenpenalty\z@\exhyphenpenalty\z@ + \doublehyphendemerits\z@\finalhyphendemerits\z@ + \strut #1\strut}% +}% +% +% The normal line wrapping allows breaks at spaces and ascii non +% letters, non digits. The \raggedright above means there will be +% an overfilled line only if some non-breakable "word" was +% encountered, which is longer than a line (it is moved always to +% be on its own on a new line). +% +% The "forced" line wrapping will parse the tokens to add potential +% breakpoints at each character. As some strings are highlighted, +% we have to apply the highlighting character per character, which +% requires to manipulate the output of the Pygments LaTeXFormatter. +% +% Doing this at latex level is complicated. The contents should +% be as expected: i.e. some active characters from +% \sphinxbreaksviaactive, some Pygments character escapes such as +% \PYGZdl{}, and the highlighting \PYG macro with always 2 +% arguments. No other macros should be there, except perhaps +% zero-parameter macros. In particular: +% - the texcomments Pygments option must be set to False +% +% With pdflatex, Unicode input gives multi-bytes characters +% where the first byte is active. We support the "utf8" macros +% only. "utf8x" is not supported. +% +% The highlighting macro \PYG will be applied character per +% character. Highlighting via a colored background gives thus a +% chain of small colored boxes which may cause some artefact in +% some pdf viewers. Can't do anything here if we do want the line +% break to be possible. +% +% First a measurement step is done of what would the standard line +% wrapping give (i.e line breaks only at spaces and non-letter, +% non-digit ascii characters), cf TeX by Topic for the basic +% dissecting technique: TeX unfortunately when building a vertical +% box does not store in an accessible way what was the maximal +% line-width during paragraph building. +% +% If the max width exceeds the linewidth by more than verbatimmaxoverfull +% character widths, or if the min width plus verbatimmaxunderfull character +% widths is inferior to linewidth, then we apply the "force wrapping" with +% potential line break at each character, else we don't. +\long\def\spx@verb@FormatLineForceWrap#1{% + % \spx@image@box is a scratch box register that we can use here + \global\let\spx@verb@maxwidth\z@ + \global\let\spx@verb@minwidth\linewidth + \setbox\spx@image@box + \vtop{\raggedright\hyphenpenalty\z@\exhyphenpenalty\z@ + \doublehyphendemerits\z@\finalhyphendemerits\z@ + \strut #1\strut\@@par + \spx@verb@getwidths}% + \ifdim\spx@verb@maxwidth> + \dimexpr\linewidth+\spx@opt@verbatimmaxoverfull\fontcharwd\font`X \relax + \spx@verb@FormatLineWrap{\spx@verb@wrapPYG #1\spx@verb@wrapPYG}% + \else + \ifdim\spx@verb@minwidth< + \dimexpr\linewidth-\spx@opt@verbatimmaxunderfull\fontcharwd\font`X \relax + \spx@verb@FormatLineWrap{\spx@verb@wrapPYG #1\spx@verb@wrapPYG}% + \else + \spx@verb@FormatLineWrap{#1}% + \fi\fi +}% +% auxiliary paragraph dissector to get max and min widths +% but minwidth must not take into account the last line +\newbox\spx@scratchbox +\def\spx@verb@getwidths {% + \unskip\unpenalty + \setbox\spx@scratchbox\lastbox + \ifvoid\spx@scratchbox + \else + \setbox\spx@scratchbox\hbox{\unhbox\spx@scratchbox}% + \ifdim\spx@verb@maxwidth<\wd\spx@scratchbox + \xdef\spx@verb@maxwidth{\number\wd\spx@scratchbox sp}% + \fi + \expandafter\spx@verb@getwidths@loop + \fi +}% +\def\spx@verb@getwidths@loop {% + \unskip\unpenalty + \setbox\spx@scratchbox\lastbox + \ifvoid\spx@scratchbox + \else + \setbox\spx@scratchbox\hbox{\unhbox\spx@scratchbox}% + \ifdim\spx@verb@maxwidth<\wd\spx@scratchbox + \xdef\spx@verb@maxwidth{\number\wd\spx@scratchbox sp}% + \fi + \ifdim\spx@verb@minwidth>\wd\spx@scratchbox + \xdef\spx@verb@minwidth{\number\wd\spx@scratchbox sp}% + \fi + \expandafter\spx@verb@getwidths@loop + \fi +}% +% auxiliary macros to implement "cut long line even in middle of word" +\catcode`Z=3 % safe delimiter +\def\spx@verb@wrapPYG{% + \futurelet\spx@nexttoken\spx@verb@wrapPYG@i +}% +\def\spx@verb@wrapPYG@i{% + \ifx\spx@nexttoken\spx@verb@wrapPYG\let\next=\@gobble\else + \ifx\spx@nexttoken\PYG\let\next=\spx@verb@wrapPYG@PYG@onebyone\else + \discretionary{}{\sphinxafterbreak}{}% + \let\next\spx@verb@wrapPYG@ii + \fi\fi + \next +}% +% Let's recognize active characters. We don't support utf8x only utf8. +% And here #1 should not have picked up (non empty) braced contents +\long\def\spx@verb@wrapPYG@ii#1{% + \ifcat\noexpand~\noexpand#1\relax% active character + \expandafter\spx@verb@wrapPYG@active + \else % non-active character, control sequence such as \PYGZdl, or empty + \expandafter\spx@verb@wrapPYG@one + \fi {#1}% +}% +\long\def\spx@verb@wrapPYG@active#1{% +% Let's hope expansion of active character does not really require arguments, +% as we certainly don't want to go into expanding upfront token stream anyway. + \expandafter\spx@verb@wrapPYG@iii#1{}{}{}{}{}{}{}{}{}Z#1% +}% +\long\def\spx@verb@wrapPYG@iii#1#2Z{% + \ifx\UTFviii@four@octets#1\let\next=\spx@verb@wrapPYG@four\else + \ifx\UTFviii@three@octets#1\let\next=\spx@verb@wrapPYG@three\else + \ifx\UTFviii@two@octets#1\let\next=\spx@verb@wrapPYG@two\else + \let\next=\spx@verb@wrapPYG@one + \fi\fi\fi + \next +}% +\long\def\spx@verb@wrapPYG@one #1{#1\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% +\long\def\spx@verb@wrapPYG@two #1#2{#1#2\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% +\long\def\spx@verb@wrapPYG@three #1#2#3{#1#2#3\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% +\long\def\spx@verb@wrapPYG@four #1#2#3#4{#1#2#3#4\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% +% Replace \PYG by itself applied one character at a time! This way breakpoints +% can be inserted. +\def\spx@verb@wrapPYG@PYG@onebyone#1#2#3{% #1 = \PYG, #2 = highlight spec, #3 = tokens + \def\spx@verb@wrapPYG@PYG@spec{{#2}}% + \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i#3Z% +}% +\def\spx@verb@wrapPYG@PYG@i{% + \ifx\spx@nexttokenZ\let\next=\spx@verb@wrapPYG@PYG@done\else + \discretionary{}{\sphinxafterbreak}{}% + \let\next\spx@verb@wrapPYG@PYG@ii + \fi + \next +}% +\def\spx@verb@wrapPYG@PYG@doneZ{\futurelet\spx@nexttoken\spx@verb@wrapPYG@i}% +\long\def\spx@verb@wrapPYG@PYG@ii#1{% + \ifcat\noexpand~\noexpand#1\relax% active character + \expandafter\spx@verb@wrapPYG@PYG@active + \else % non-active character, control sequence such as \PYGZdl, or empty + \expandafter\spx@verb@wrapPYG@PYG@one + \fi {#1}% +}% +\long\def\spx@verb@wrapPYG@PYG@active#1{% +% Let's hope expansion of active character does not really require arguments, +% as we certainly don't want to go into expanding upfront token stream anyway. + \expandafter\spx@verb@wrapPYG@PYG@iii#1{}{}{}{}{}{}{}{}{}Z#1% +}% +\long\def\spx@verb@wrapPYG@PYG@iii#1#2Z{% + \ifx\UTFviii@four@octets#1\let\next=\spx@verb@wrapPYG@PYG@four\else + \ifx\UTFviii@three@octets#1\let\next=\spx@verb@wrapPYG@PYG@three\else + \ifx\UTFviii@two@octets#1\let\next=\spx@verb@wrapPYG@PYG@two\else + \let\next=\spx@verb@wrapPYG@PYG@one + \fi\fi\fi + \next +}% +\long\def\spx@verb@wrapPYG@PYG@one#1{% + \expandafter\PYG\spx@verb@wrapPYG@PYG@spec{#1}% + \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i +}% +\long\def\spx@verb@wrapPYG@PYG@two#1#2{% + \expandafter\PYG\spx@verb@wrapPYG@PYG@spec{#1#2}% + \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i +}% +\long\def\spx@verb@wrapPYG@PYG@three#1#2#3{% + \expandafter\PYG\spx@verb@wrapPYG@PYG@spec{#1#2#3}% + \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i +}% +\long\def\spx@verb@wrapPYG@PYG@four#1#2#3#4{% + \expandafter\PYG\spx@verb@wrapPYG@PYG@spec{#1#2#3#4}% + \futurelet\spx@nexttoken\spx@verb@wrapPYG@PYG@i +}% +\catcode`Z 11 % +% +\g@addto@macro\FV@SetupFont{% + \sbox\sphinxcontinuationbox {\spx@opt@verbatimcontinued}% + \sbox\sphinxvisiblespacebox {\spx@opt@verbatimvisiblespace}% +}% +\newenvironment{sphinxVerbatim}{% + % first, let's check if there is a caption + \ifx\sphinxVerbatimTitle\empty + \sphinxvspacefixafterfrenchlists + \parskip\z@skip + \vskip\sphinxverbatimsmallskipamount + % there was no caption. Check if nevertheless a label was set. + \ifx\sphinxLiteralBlockLabel\empty\else + % we require some space to be sure hyperlink target from \phantomsection + % will not be separated from upcoming verbatim by a page break + \needspace{\sphinxliteralblockwithoutcaptionneedspace}% + \phantomsection\sphinxLiteralBlockLabel + \fi + \else + \parskip\z@skip + \if t\spx@opt@literalblockcappos + \vskip\spx@abovecaptionskip + \def\sphinxVerbatim@Before + {\sphinxVerbatim@Title\nointerlineskip + \kern\dimexpr-\dp\strutbox+\sphinxbelowcaptionspace + % if no frame (code-blocks inside table cells), remove + % the "verbatimsep" whitespace from the top (better visually) + \ifspx@opt@verbatimwithframe\else-\sphinxverbatimsep\fi + % caption package adds \abovecaptionskip vspace, remove it + \spx@ifcaptionpackage{-\abovecaptionskip}{}\relax}% + \else + \vskip\sphinxverbatimsmallskipamount + \def\sphinxVerbatim@After + {\nointerlineskip\kern\dimexpr\dp\strutbox + \ifspx@opt@verbatimwithframe\else-\sphinxverbatimsep\fi + \spx@ifcaptionpackage{-\abovecaptionskip}{}\relax + \sphinxVerbatim@Title}% + \fi + \def\@captype{literalblock}% + \capstart + % \sphinxVerbatimTitle must reset color + \setbox\sphinxVerbatim@TitleBox + \hbox{\begin{minipage}{\linewidth}% + % caption package may detect wrongly if top or bottom, so we help it + \spx@ifcaptionpackage + {\caption@setposition{\spx@opt@literalblockcappos}}{}% + \sphinxVerbatimTitle + \end{minipage}}% + \fi + \global\let\sphinxLiteralBlockLabel\empty + \global\let\sphinxVerbatimTitle\empty + \fboxsep\sphinxverbatimsep \fboxrule\sphinxverbatimborder + \ifspx@opt@verbatimwithframe\else\fboxrule\z@\fi + \let\FrameCommand \sphinxVerbatim@FrameCommand + \let\FirstFrameCommand\sphinxVerbatim@FirstFrameCommand + \let\MidFrameCommand \sphinxVerbatim@MidFrameCommand + \let\LastFrameCommand \sphinxVerbatim@LastFrameCommand + \ifspx@opt@verbatimhintsturnover\else + \let\sphinxVerbatim@Continued\@empty + \let\sphinxVerbatim@Continues\@empty + \fi + \ifspx@opt@verbatimwrapslines + % fancyvrb's Verbatim puts each input line in (unbreakable) horizontal boxes. + % This customization wraps each line from the input in a \vtop, thus + % allowing it to wrap and display on two or more lines in the latex output. + % - The codeline counter will be increased only once. + % - The wrapped material will not break across pages, it is impossible + % to achieve this without extensive rewrite of fancyvrb. + % - The (not used in sphinx) obeytabs option to Verbatim is + % broken by this change (showtabs and tabspace work). + \let\sphinxVerbatimFormatLine\sphinxVerbatimFormatLineWrap + \let\FV@Space\spx@verbatim@space + % Allow breaks at special characters using \PYG... macros. + \sphinxbreaksatspecials + % Breaks at punctuation characters . , ; ? ! and / (needs catcode activation) + \fvset{codes*=\sphinxbreaksviaactive}% + \else % end of conditional code for wrapping long code lines + \let\sphinxVerbatimFormatLine\sphinxVerbatimFormatLineNoWrap + \fi + \let\FancyVerbFormatLine\sphinxFancyVerbFormatLine + \VerbatimEnvironment + % workaround to fancyvrb's check of current list depth + \def\@toodeep {\advance\@listdepth\@ne}% + % The list environment is needed to control perfectly the vertical space. + % Note: \OuterFrameSep used by framed.sty is later set to \topsep hence 0pt. + % - if caption: distance from last text baseline to caption baseline is + % A+(B-F)+\ht\strutbox, A = \abovecaptionskip (default 10pt), B = + % \baselineskip, F is the framed.sty \FrameHeightAdjust macro, default 6pt. + % Formula valid for F < 10pt. + % - distance of baseline of caption to top of frame is like for tables: + % \sphinxbelowcaptionspace (=0.5\baselineskip) + % - if no caption: distance of last text baseline to code frame is S+(B-F), + % with S = \sphinxverbatimtopskip (=\smallskip) + % - and distance from bottom of frame to next text baseline is + % \baselineskip+\parskip. + % The \trivlist is used to avoid possible "too deeply nested" error. + \itemsep \z@skip + \topsep \z@skip + \partopsep \z@skip + % trivlist will set \parsep to \parskip (which itself is set to zero above) + % \leftmargin will be set to zero by trivlist + \rightmargin\z@ + \parindent \z@% becomes \itemindent. Default zero, but perhaps overwritten. + \trivlist\item\relax + \ifspx@inframed\setbox\sphinxVerbatim@ContentsBox\vbox\bgroup + \@setminipage\hsize\linewidth + % use bulk of minipage paragraph shape restores (this is needed + % in indented contexts, at least for some) + \textwidth\hsize \columnwidth\hsize \@totalleftmargin\z@ + \leftskip\z@skip \rightskip\z@skip \@rightskip\z@skip + \else + \ifsphinxverbatimwithminipage\noindent\begin{minipage}{\linewidth}\fi + \MakeFramed {% adapted over from framed.sty's snugshade environment + \advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize\@setminipage + }% + \fi + % For grid placement from \strut's in \FancyVerbFormatLine + \lineskip\z@skip + % active comma should not be overwritten by \@noligs + \ifspx@opt@verbatimwrapslines + \let\verbatim@nolig@list \sphinx@verbatim@nolig@list + \fi + % will fetch its optional arguments if any + \OriginalVerbatim +} +{% + \endOriginalVerbatim + \ifspx@inframed + \egroup % finish \sphinxVerbatim@ContentsBox vbox + \nobreak % update page totals + \ifdim\dimexpr\ht\sphinxVerbatim@ContentsBox+ + \dp\sphinxVerbatim@ContentsBox+ + \ht\sphinxVerbatim@TitleBox+ + \dp\sphinxVerbatim@TitleBox+ + 2\fboxsep+2\fboxrule+ + % try to account for external frame parameters + \FrameSep+\FrameRule+ + % Usage here of 2 baseline distances is empirical. + % In border case where code-block fits barely in remaining space, + % it gets framed and looks good but the outer frame may continue + % on top of next page and give (if no contents after code-block) + % an empty framed line, as testing showed. + 2\baselineskip+ + % now add all to accumulated page totals and compare to \pagegoal + \pagetotal+\pagedepth>\pagegoal + % long contents: do not \MakeFramed. Do make a caption (either before or + % after) if title exists. Continuation hints across pagebreaks dropped. + % FIXME? a bottom caption may end up isolated at top of next page + % (no problem with a top caption, which is default) + \spx@opt@verbatimwithframefalse + \def\sphinxVerbatim@Title{\noindent\box\sphinxVerbatim@TitleBox\par}% + \sphinxVerbatim@Before + \noindent\unvbox\sphinxVerbatim@ContentsBox\par + \sphinxVerbatim@After + \else + % short enough contents: use \MakeFramed. As it is nested, this requires + % minipage encapsulation. + \noindent\begin{minipage}{\linewidth}% + \MakeFramed {% Use it now with the fetched contents + \advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize\@setminipage + }% + \unvbox\sphinxVerbatim@ContentsBox + % some of this may be superfluous: + \par\unskip\@minipagefalse\endMakeFramed + \end{minipage}% + \fi + \else % non-nested \MakeFramed + \par\unskip\@minipagefalse\endMakeFramed % from framed.sty snugshade + \ifsphinxverbatimwithminipage\end{minipage}\fi + \fi + \endtrivlist +} +\newenvironment {sphinxVerbatimNoFrame} + {\spx@opt@verbatimwithframefalse + \VerbatimEnvironment + \begin{sphinxVerbatim}} + {\end{sphinxVerbatim}} +\newenvironment {sphinxVerbatimintable} + {% don't use a frame if in a table cell + \spx@opt@verbatimwithframefalse + \sphinxverbatimwithminipagetrue + % the literal block caption uses \sphinxcaption which is wrapper of \caption, + % but \caption must be modified because longtable redefines it to work only + % for the own table caption, and tabulary has multiple passes + \let\caption\sphinxfigcaption + % reduce above caption skip + \def\spx@abovecaptionskip{\sphinxverbatimsmallskipamount}% + \VerbatimEnvironment + \begin{sphinxVerbatim}} + {\end{sphinxVerbatim}} + + +%% PARSED LITERALS +% allow long lines to wrap like they do in code-blocks + +% this should be kept in sync with definitions in sphinx.util.texescape +\newcommand*\sphinxbreaksattexescapedchars{% + \def\do##1##2% put potential break point before character + {\def##1{\discretionary{}{\sphinxafterbreak\char`##2}{\char`##2}}}% + \do\{\{\do\textless\<\do\#\#\do\%\%\do\$\$% {, <, #, %, $ + \def\do##1##2% put potential break point after character + {\def##1{\discretionary{\char`##2}{\sphinxafterbreak}{\char`##2}}}% + \do\_\_\do\}\}\do\textasciicircum\^\do\&\&% _, }, ^, &, + \do\textgreater\>\do\textasciitilde\~% >, ~ + \do\textbackslash\\% \ +} +\newcommand*\sphinxbreaksviaactiveinparsedliteral{% + \sphinxbreaksviaactive % by default handles . , ; ? ! / + \lccode`\~`\~ % + % update \dospecials as it is used by \url + % but deactivation will already have been done hence this is unneeded: + % \expandafter\def\expandafter\dospecials\expandafter{\dospecials + % \sphinxbreaksbeforeactivelist\sphinxbreaksafteractivelist\do\-}% +} +\newcommand*\sphinxbreaksatspaceinparsedliteral{% + \lccode`~32 \lowercase{\let~}\spx@verbatim@space\lccode`\~`\~ +} +\newcommand*{\sphinxunactivateextras}{\let\do\@makeother + \sphinxbreaksbeforeactivelist\sphinxbreaksafteractivelist}% +% the \catcode13=5\relax (deactivate end of input lines) is left to callers +\newcommand*{\sphinxunactivateextrasandspace}{\catcode32=10\relax + \sphinxunactivateextras}% +% now for the modified alltt environment +\newenvironment{sphinxalltt} +{% at start of next line to workaround Emacs/AUCTeX issue with this file +\begin{alltt}% + \ifspx@opt@parsedliteralwraps + \sbox\sphinxcontinuationbox {\spx@opt@verbatimcontinued}% + \sbox\sphinxvisiblespacebox {\spx@opt@verbatimvisiblespace}% + \sphinxbreaksattexescapedchars + \sphinxbreaksviaactiveinparsedliteral + \sphinxbreaksatspaceinparsedliteral +% alltt takes care of the ' as derivative ("prime") in math mode + \everymath\expandafter{\the\everymath\sphinxunactivateextrasandspace + \catcode`\<=12\catcode`\>=12\catcode`\^=7\catcode`\_=8 }% +% not sure if displayed math (align,...) can end up in parsed-literal, anyway + \everydisplay\expandafter{\the\everydisplay + \catcode13=5 \sphinxunactivateextrasandspace + \catcode`\<=12\catcode`\>=12\catcode`\^=7\catcode`\_=8 }% + \fi } +{\end{alltt}} + + +%% INLINE MARK-UP +% + +% Protect \href's first argument in contexts such as sphinxalltt (or +% \sphinxcode). Sphinx uses \#, \%, \& ... always inside \sphinxhref. +\protected\def\sphinxhref#1#2{{% + \sphinxunactivateextrasandspace % never do \scantokens with active space! +% for the \endlinechar business, https://github.com/latex3/latex2e/issues/286 + \endlinechar\m@ne\everyeof{{\endlinechar13 #2}}% keep catcode regime for #2 + \scantokens{\href{#1}}% normalise it for #1 during \href expansion +}} +% Same for \url. And also \nolinkurl for coherence. +\protected\def\sphinxurl#1{{% + \sphinxunactivateextrasandspace\everyeof{}% (<- precaution for \scantokens) + \endlinechar\m@ne\scantokens{\url{#1}}% +}} +\protected\def\sphinxnolinkurl#1{{% + \sphinxunactivateextrasandspace\everyeof{}% + \endlinechar\m@ne\scantokens{\nolinkurl{#1}}% +}} + +% \sphinxupquote +% to obtain straight quotes we execute \@noligs as patched by upquote, and +% \scantokens is needed in cases where it would be too late for the macro to +% first set catcodes and then fetch its argument. We also make the contents +% breakable at non-escaped . , ; ? ! / using \sphinxbreaksviaactive, +% and also at \ character (which is escaped to \textbackslash{}). +\protected\def\sphinxtextbackslashbreakbefore + {\discretionary{}{\sphinxafterbreak\sphinx@textbackslash}{\sphinx@textbackslash}} +\protected\def\sphinxtextbackslashbreakafter + {\discretionary{\sphinx@textbackslash}{\sphinxafterbreak}{\sphinx@textbackslash}} +\let\sphinxtextbackslash\sphinxtextbackslashbreakafter +% the macro must be protected if it ends up used in moving arguments, +% in 'alltt' \@noligs is done already, and the \scantokens must be avoided. +\protected\def\sphinxupquote#1{{\def\@tempa{alltt}% + \ifx\@tempa\@currenvir\else + \ifspx@opt@inlineliteralwraps + % break at . , ; ? ! / + \sphinxbreaksviaactive + % break also at \ + \let\sphinx@textbackslash\textbackslash + \let\textbackslash\sphinxtextbackslash + % by default, no continuation symbol on next line but may be added + \let\sphinxafterbreak\sphinxafterbreakofinlineliteral + % do not overwrite the comma set-up + \let\verbatim@nolig@list\sphinx@literal@nolig@list + \fi + % fix a space-gobbling issue due to LaTeX's original \do@noligs +% TODO: using \@noligs as patched by upquote.sty is now unneeded because +% either ` and ' are escaped (non-unicode engines) or they don't build +% ligatures (unicode engines). Thus remove this and unify handling of `, <, >, +% ' and - with the characters . , ; ? ! / as handled via +% \sphinxbreaksviaactive. +% Hence \sphinx@do@noligs will be removed, or rather replaced with code +% inserting discretionaries, as they allow a continuation symbol on start of +% next line to achieve common design with code-blocks. + \let\do@noligs\sphinx@do@noligs + \@noligs\endlinechar\m@ne\everyeof{}% (<- in case inside \sphinxhref) + \expandafter\scantokens + \fi {{#1}}}}% extra brace pair to fix end-space gobbling issue... +\def\sphinx@do@noligs #1{\catcode`#1\active\begingroup\lccode`\~`#1\relax + \lowercase{\endgroup\def~{\leavevmode\kern\z@\char`#1 }}} +\def\sphinx@literal@nolig@list {\do\`\do\<\do\>\do\'\do\-}% +\let\sphinxafterbreakofinlineliteral\empty + + +\endinput diff --git a/sphinx/texinputs/sphinxlatexnumfig.sty b/sphinx/texinputs/sphinxlatexnumfig.sty new file mode 100644 index 0000000000..6d72961051 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexnumfig.sty @@ -0,0 +1,122 @@ +%% NUMBERING OF FIGURES, TABLES, AND LITERAL BLOCKS +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexnumfig.sty}[2021/01/27 numbering] + +% Requires: remreset (old LaTeX only) +% relates to numfig and numfig_secnum_depth configuration variables + +% LaTeX 2018-04-01 and later provides \@removefromreset +\ltx@ifundefined{@removefromreset} + {\RequirePackage{remreset}} + {}% avoid warning +% Everything is delayed to \begin{document} to allow hyperref patches into +% \newcounter to solve duplicate label problems for internal hyperlinks to +% code listings (literalblock counter). User or extension re-definitions of +% \theliteralblock, et al., thus have also to be delayed. (changed at 3.5.0) +\AtBeginDocument{% +\ltx@ifundefined{c@chapter} + {\newcounter{literalblock}}% + {\newcounter{literalblock}[chapter]% + \def\theliteralblock{\ifnum\c@chapter>\z@\arabic{chapter}.\fi + \arabic{literalblock}}% + }% +\ifspx@opt@nonumfigreset + \ltx@ifundefined{c@chapter}{}{% + \@removefromreset{figure}{chapter}% + \@removefromreset{table}{chapter}% + \@removefromreset{literalblock}{chapter}% + \ifspx@opt@mathnumfig + \@removefromreset{equation}{chapter}% + \fi + }% + \def\thefigure{\arabic{figure}}% + \def\thetable {\arabic{table}}% + \def\theliteralblock{\arabic{literalblock}}% + \ifspx@opt@mathnumfig + \def\theequation{\arabic{equation}}% + \fi +\else +\let\spx@preAthefigure\@empty +\let\spx@preBthefigure\@empty +% \ifspx@opt@usespart % <-- LaTeX writer could pass such a 'usespart' boolean +% % as sphinx.sty package option +% If document uses \part, (triggered in Sphinx by latex_toplevel_sectioning) +% LaTeX core per default does not reset chapter or section +% counters at each part. +% But if we modify this, we need to redefine \thechapter, \thesection to +% include the part number and this will cause problems in table of contents +% because of too wide numbering. Simplest is to do nothing. +% \fi +\ifnum\spx@opt@numfigreset>0 + \ltx@ifundefined{c@chapter} + {} + {\g@addto@macro\spx@preAthefigure{\ifnum\c@chapter>\z@\arabic{chapter}.}% + \g@addto@macro\spx@preBthefigure{\fi}}% +\fi +\ifnum\spx@opt@numfigreset>1 + \@addtoreset{figure}{section}% + \@addtoreset{table}{section}% + \@addtoreset{literalblock}{section}% + \ifspx@opt@mathnumfig + \@addtoreset{equation}{section}% + \fi% + \g@addto@macro\spx@preAthefigure{\ifnum\c@section>\z@\arabic{section}.}% + \g@addto@macro\spx@preBthefigure{\fi}% +\fi +\ifnum\spx@opt@numfigreset>2 + \@addtoreset{figure}{subsection}% + \@addtoreset{table}{subsection}% + \@addtoreset{literalblock}{subsection}% + \ifspx@opt@mathnumfig + \@addtoreset{equation}{subsection}% + \fi% + \g@addto@macro\spx@preAthefigure{\ifnum\c@subsection>\z@\arabic{subsection}.}% + \g@addto@macro\spx@preBthefigure{\fi}% +\fi +\ifnum\spx@opt@numfigreset>3 + \@addtoreset{figure}{subsubsection}% + \@addtoreset{table}{subsubsection}% + \@addtoreset{literalblock}{subsubsection}% + \ifspx@opt@mathnumfig + \@addtoreset{equation}{subsubsection}% + \fi% + \g@addto@macro\spx@preAthefigure{\ifnum\c@subsubsection>\z@\arabic{subsubsection}.}% + \g@addto@macro\spx@preBthefigure{\fi}% +\fi +\ifnum\spx@opt@numfigreset>4 + \@addtoreset{figure}{paragraph}% + \@addtoreset{table}{paragraph}% + \@addtoreset{literalblock}{paragraph}% + \ifspx@opt@mathnumfig + \@addtoreset{equation}{paragraph}% + \fi% + \g@addto@macro\spx@preAthefigure{\ifnum\c@subparagraph>\z@\arabic{subparagraph}.}% + \g@addto@macro\spx@preBthefigure{\fi}% +\fi +\ifnum\spx@opt@numfigreset>5 + \@addtoreset{figure}{subparagraph}% + \@addtoreset{table}{subparagraph}% + \@addtoreset{literalblock}{subparagraph}% + \ifspx@opt@mathnumfig + \@addtoreset{equation}{subparagraph}% + \fi% + \g@addto@macro\spx@preAthefigure{\ifnum\c@subsubparagraph>\z@\arabic{subsubparagraph}.}% + \g@addto@macro\spx@preBthefigure{\fi}% +\fi +\expandafter\g@addto@macro +\expandafter\spx@preAthefigure\expandafter{\spx@preBthefigure}% +\let\thefigure\spx@preAthefigure +\let\thetable\spx@preAthefigure +\let\theliteralblock\spx@preAthefigure +\g@addto@macro\thefigure{\arabic{figure}}% +\g@addto@macro\thetable{\arabic{table}}% +\g@addto@macro\theliteralblock{\arabic{literalblock}}% + \ifspx@opt@mathnumfig + \let\theequation\spx@preAthefigure + \g@addto@macro\theequation{\arabic{equation}}% + \fi +\fi +}% end of big \AtBeginDocument + +\endinput diff --git a/sphinx/texinputs/sphinxlatexobjects.sty b/sphinx/texinputs/sphinxlatexobjects.sty new file mode 100644 index 0000000000..26e2862c11 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexobjects.sty @@ -0,0 +1,177 @@ +%% MODULE RELEASE DATA AND OBJECT DESCRIPTIONS +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexobjects.sty}[2021/01/27 documentation environments] + +% Provides support for this output mark-up from Sphinx latex writer: +% +% - environments +% +% - fulllineitems +% - productionlist +% - optionlist +% - DUlineblock (also "lineblock") +% +% - macros +% +% - \DUrole +% - various legacy support macros related to author and release +% data of documented objects and modules. + +% \moduleauthor{name}{email} +\newcommand{\moduleauthor}[2]{} + +% \sectionauthor{name}{email} +\newcommand{\sectionauthor}[2]{} + +% Allow the release number to be specified independently of the +% \date{}. This allows the date to reflect the document's date and +% release to specify the release that is documented. +% +\newcommand{\py@release}{\releasename\space\version} +\newcommand{\version}{}% part of \py@release, used by title page and headers +% \releaseinfo is used on titlepage (sphinxmanual.cls, sphinxhowto.cls) +\newcommand{\releaseinfo}{} +\newcommand{\setreleaseinfo}[1]{\renewcommand{\releaseinfo}{#1}} +% this is inserted via template and #1=release config variable +\newcommand{\release}[1]{\renewcommand{\version}{#1}} +% this is defined by template to 'releasename' latex_elements key +\newcommand{\releasename}{} +% Fix issue in case release and releasename deliberately left blank +\newcommand{\sphinxheadercomma}{, }% used in fancyhdr header definition +\newcommand{\sphinxifemptyorblank}[1]{% +% test after one expansion of macro #1 if contents is empty or spaces + \if&\expandafter\@firstofone\detokenize\expandafter{#1}&% + \expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}% +\AtBeginDocument {% + \sphinxifemptyorblank{\releasename} + {\sphinxifemptyorblank{\version}{\let\sphinxheadercomma\empty}{}} + {}% +}% + +% Allow specification of the author's address separately from the +% author's name. This can be used to format them differently, which +% is a good thing. +% +\newcommand{\py@authoraddress}{} +\newcommand{\authoraddress}[1]{\renewcommand{\py@authoraddress}{#1}} + +% {fulllineitems} is the main environment for object descriptions. +% +\newcommand{\py@itemnewline}[1]{% + \kern\labelsep + \@tempdima\linewidth + \advance\@tempdima \labelwidth\makebox[\@tempdima][l]{#1}% + \kern-\labelsep +} + +\newenvironment{fulllineitems}{% + \begin{list}{}{\labelwidth \leftmargin + \rightmargin \z@ \topsep -\parskip \partopsep \parskip + \itemsep -\parsep + \let\makelabel=\py@itemnewline}% +}{\end{list}} + +% Signatures, possibly multi-line +% +\newlength{\py@argswidth} +\newcommand{\py@sigparams}[2]{% + \parbox[t]{\py@argswidth}{#1\sphinxcode{)}#2}} +\newcommand{\pysigline}[1]{\item[{#1}]} +\newcommand{\pysiglinewithargsret}[3]{% + \settowidth{\py@argswidth}{#1\sphinxcode{(}}% + \addtolength{\py@argswidth}{-2\py@argswidth}% + \addtolength{\py@argswidth}{\linewidth}% + \item[{#1\sphinxcode{(}\py@sigparams{#2}{#3}}]} +\newcommand{\pysigstartmultiline}{% + \def\pysigstartmultiline{\vskip\smallskipamount\parskip\z@skip\itemsep\z@skip}% + \edef\pysigstopmultiline + {\noexpand\leavevmode\parskip\the\parskip\relax\itemsep\the\itemsep\relax}% + \parskip\z@skip\itemsep\z@skip +} + +% Production lists +% +\newenvironment{productionlist}{% +% \def\sphinxoptional##1{{\Large[}##1{\Large]}} + \def\production##1##2{\\\sphinxcode{\sphinxupquote{##1}}&::=&\sphinxcode{\sphinxupquote{##2}}}% + \def\productioncont##1{\\& &\sphinxcode{\sphinxupquote{##1}}}% + \parindent=2em + \indent + \setlength{\LTpre}{0pt}% + \setlength{\LTpost}{0pt}% + \begin{longtable}[l]{lcl} +}{% + \end{longtable} +} + +% Definition lists; requested by AMK for HOWTO documents. Probably useful +% elsewhere as well, so keep in in the general style support. +% +\newenvironment{definitions}{% + \begin{description}% + \def\term##1{\item[{##1}]\mbox{}\\*[0mm]}% +}{% + \end{description}% +} + +%% FROM DOCTUTILS LATEX WRITER +% +% The following is stuff copied from docutils' latex writer. +% +\newcommand{\optionlistlabel}[1]{\normalfont\bfseries #1 \hfill}% \bf deprecated +\newenvironment{optionlist}[1] +{\begin{list}{} + {\setlength{\labelwidth}{#1} + \setlength{\rightmargin}{1cm} + \setlength{\leftmargin}{\rightmargin} + \addtolength{\leftmargin}{\labelwidth} + \addtolength{\leftmargin}{\labelsep} + \renewcommand{\makelabel}{\optionlistlabel}} +}{\end{list}} + +\newlength{\lineblockindentation} +\setlength{\lineblockindentation}{2.5em} +\newenvironment{lineblock}[1] +{\begin{list}{} + {\setlength{\partopsep}{\parskip} + \addtolength{\partopsep}{\baselineskip} + \topsep0pt\itemsep0.15\baselineskip\parsep0pt + \leftmargin#1\relax} + \raggedright} +{\end{list}} + +% From docutils.writers.latex2e +% inline markup (custom roles) +% \DUrole{#1}{#2} tries \DUrole#1{#2} +\providecommand*{\DUrole}[2]{% + \ifcsname DUrole\detokenize{#1}\endcsname + \csname DUrole\detokenize{#1}\endcsname{#2}% + \else% backwards compatibility: try \docutilsrole#1{#2} + \ifcsname docutilsrole\detokenize{#1}\endcsname + \csname docutilsrole\detokenize{#1}\endcsname{#2}% + \else + #2% + \fi + \fi +} + +\providecommand*{\DUprovidelength}[2]{% + \ifdefined#1\else\newlength{#1}\setlength{#1}{#2}\fi +} + +\DUprovidelength{\DUlineblockindent}{2.5em} +\ifdefined\DUlineblock\else + \newenvironment{DUlineblock}[1]{% + \list{}{\setlength{\partopsep}{\parskip} + \addtolength{\partopsep}{\baselineskip} + \setlength{\topsep}{0pt} + \setlength{\itemsep}{0.15\baselineskip} + \setlength{\parsep}{0pt} + \setlength{\leftmargin}{#1}} + \raggedright + } + {\endlist} +\fi + +\endinput diff --git a/sphinx/texinputs/sphinxlatexshadowbox.sty b/sphinx/texinputs/sphinxlatexshadowbox.sty new file mode 100644 index 0000000000..8d6c78666c --- /dev/null +++ b/sphinx/texinputs/sphinxlatexshadowbox.sty @@ -0,0 +1,100 @@ +%% TOPIC AND CONTENTS BOXES +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexshadowbox.sty}[2021/01/27 sphinxShadowBox] + +% Provides support for this output mark-up from Sphinx latex writer: +% +% - sphinxShadowBox (environment) +% +% Dependencies (they do not need to be defined at time of loading): +% +% - of course the various colour and dimension options handled via sphinx.sty +% - dimension register \spx@image@maxheight from sphinxlatexgraphics.sty +% - \savenotes/\spewnotes from sphinxpackagefootnote +% - \ifspx@inframed defined in sphinx.sty +% +% Requires: +\RequirePackage{framed} + +% Again based on use of "framed.sty", this allows breakable framed boxes. +\long\def\spx@ShadowFBox#1{% + \leavevmode\begingroup + % first we frame the box #1 + \setbox\@tempboxa + \hbox{\vrule\@width\sphinxshadowrule + \vbox{\hrule\@height\sphinxshadowrule + \kern\sphinxshadowsep + \hbox{\kern\sphinxshadowsep #1\kern\sphinxshadowsep}% + \kern\sphinxshadowsep + \hrule\@height\sphinxshadowrule}% + \vrule\@width\sphinxshadowrule}% + % Now we add the shadow, like \shadowbox from fancybox.sty would do + \dimen@\dimexpr.5\sphinxshadowrule+\sphinxshadowsize\relax + \hbox{\vbox{\offinterlineskip + \hbox{\copy\@tempboxa\kern-.5\sphinxshadowrule + % add shadow on right side + \lower\sphinxshadowsize + \hbox{\vrule\@height\ht\@tempboxa \@width\dimen@}% + }% + \kern-\dimen@ % shift back vertically to bottom of frame + % and add shadow at bottom + \moveright\sphinxshadowsize + \vbox{\hrule\@width\wd\@tempboxa \@height\dimen@}% + }% + % move left by the size of right shadow so shadow adds no width + \kern-\sphinxshadowsize + }% + \endgroup +} + +% use framed.sty to allow page breaks in frame+shadow +% works well inside Lists and Quote-like environments +% produced by ``topic'' directive (or local contents) +% could nest if LaTeX writer authorized it +\newenvironment{sphinxShadowBox} + {\def\FrameCommand {\spx@ShadowFBox }% + \advance\spx@image@maxheight + -\dimexpr2\sphinxshadowrule + +2\sphinxshadowsep + +\sphinxshadowsize + +\baselineskip\relax + % configure framed.sty not to add extra vertical spacing + \ltx@ifundefined{OuterFrameSep}{}{\OuterFrameSep\z@skip}% + % the \trivlist will add the vertical spacing on top and bottom which is + % typical of center environment as used in Sphinx <= 1.4.1 + % the \noindent has the effet of an extra blank line on top, to + % imitate closely the layout from Sphinx <= 1.4.1; the \FrameHeightAdjust + % will put top part of frame on this baseline. + \def\FrameHeightAdjust {\baselineskip}% + % use package footnote to handle footnotes + \savenotes + \trivlist\item\noindent + % use a minipage if we are already inside a framed environment + \ifspx@inframed\begin{minipage}{\linewidth}\fi + \MakeFramed {\spx@inframedtrue + % framed.sty puts into "\width" the added width (=2shadowsep+2shadowrule) + % adjust \hsize to what the contents must use + \advance\hsize-\width + % adjust LaTeX parameters to behave properly in indented/quoted contexts + \FrameRestore + % typeset the contents as in a minipage (Sphinx <= 1.4.1 used a minipage and + % itemize/enumerate are therein typeset more tightly, we want to keep + % that). We copy-paste from LaTeX source code but don't do a real minipage. + \@pboxswfalse + \let\@listdepth\@mplistdepth \@mplistdepth\z@ + \@minipagerestore + \@setminipage + }% + }% + {% insert the "endminipage" code + \par\unskip + \@minipagefalse + \endMakeFramed + \ifspx@inframed\end{minipage}\fi + \endtrivlist + % output the stored footnotes + \spewnotes + } + +\endinput diff --git a/sphinx/texinputs/sphinxlatexstyleheadings.sty b/sphinx/texinputs/sphinxlatexstyleheadings.sty new file mode 100644 index 0000000000..fa9be82b44 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexstyleheadings.sty @@ -0,0 +1,83 @@ +%% TITLES +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexstyleheadings.sty}[2021/01/27 headings] + +\RequirePackage[nobottomtitles*]{titlesec} +\@ifpackagelater{titlesec}{2016/03/15}% + {\@ifpackagelater{titlesec}{2016/03/21}% + {}% + {\newif\ifsphinx@ttlpatch@ok + \IfFileExists{etoolbox.sty}{% + \RequirePackage{etoolbox}% + \patchcmd{\ttlh@hang}{\parindent\z@}{\parindent\z@\leavevmode}% + {\sphinx@ttlpatch@oktrue}{}% + \ifsphinx@ttlpatch@ok + \patchcmd{\ttlh@hang}{\noindent}{}{}{\sphinx@ttlpatch@okfalse}% + \fi + }{}% + \ifsphinx@ttlpatch@ok + \typeout{^^J Package Sphinx Info: ^^J + **** titlesec 2.10.1 successfully patched for bugfix ****^^J}% + \else + \AtEndDocument{\PackageWarningNoLine{sphinx}{^^J% +******** titlesec 2.10.1 has a bug, (section numbers disappear) ......|^^J% +******** and Sphinx could not patch it, perhaps because your local ...|^^J% +******** copy is already fixed without a changed release date. .......|^^J% +******** If not, you must update titlesec! ...........................|}}% + \fi + }% + }{} + +% Augment the sectioning commands used to get our own font family in place, +% and reset some internal data items (\titleformat from titlesec package) +\titleformat{\section}{\Large\py@HeaderFamily}% + {\py@TitleColor\thesection}{0.5em}{\py@TitleColor} +\titleformat{\subsection}{\large\py@HeaderFamily}% + {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor} +\titleformat{\subsubsection}{\py@HeaderFamily}% + {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor} +% By default paragraphs (and subsubsections) will not be numbered because +% sphinxmanual.cls and sphinxhowto.cls set secnumdepth to 2 +\titleformat{\paragraph}{\py@HeaderFamily}% + {\py@TitleColor\theparagraph}{0.5em}{\py@TitleColor} +\titleformat{\subparagraph}{\py@HeaderFamily}% + {\py@TitleColor\thesubparagraph}{0.5em}{\py@TitleColor} + + +% Since Sphinx 1.5, users should use HeaderFamily key to 'sphinxsetup' rather +% than defining their own \py@HeaderFamily command (which is still possible). +% Memo: \py@HeaderFamily is also used by \maketitle as defined in +% sphinxmanual.cls/sphinxhowto.cls +\newcommand{\py@HeaderFamily}{\spx@opt@HeaderFamily} + +% This sets up the fancy chapter headings that make the documents look +% at least a little better than the usual LaTeX output. +\@ifpackagewith{fncychap}{Bjarne}{ + \ChNameVar {\raggedleft\normalsize \py@HeaderFamily} + \ChNumVar {\raggedleft\Large \py@HeaderFamily} + \ChTitleVar{\raggedleft\Large \py@HeaderFamily} + % This creates (numbered) chapter heads without the leading \vspace*{}: + \def\@makechapterhead#1{% + {\parindent \z@ \raggedright \normalfont + \ifnum \c@secnumdepth >\m@ne + \if@mainmatter + \DOCH + \fi + \fi + \interlinepenalty\@M + \if@mainmatter + \DOTI{#1}% + \else% + \DOTIS{#1}% + \fi + }} +}{}% <-- "false" clause of \@ifpackagewith + +% fix fncychap's bug which uses prematurely the \textwidth value +\@ifpackagewith{fncychap}{Bjornstrup} + {\AtBeginDocument{\mylen\textwidth\advance\mylen-2\myhi}}% + {}% <-- "false" clause of \@ifpackagewith + + +\endinput diff --git a/sphinx/texinputs/sphinxlatexstylepage.sty b/sphinx/texinputs/sphinxlatexstylepage.sty new file mode 100644 index 0000000000..4066129bf2 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexstylepage.sty @@ -0,0 +1,79 @@ +%% PAGE STYLING +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexstylepage.sty}[2021/01/27 page styling] + +% Separate paragraphs by space by default. +\IfFileExists{parskip-2001-04-09.sty}% since September 2018 TeXLive update +% new parskip.sty, but let it rollback to old one. +% hopefully TeX installation not broken and LaTeX kernel not too old + {\RequirePackage{parskip}[=v1]} +% standard one from 1989. Admittedly \section of article/book gives possibly +% anomalous spacing, but we can't require September 2018 release for some time. + {\RequirePackage{parskip}} + +% Style parameters and macros used by most documents here +\raggedbottom +\sloppy +\hbadness = 5000 % don't print trivial gripes + +% Require package fancyhdr except under memoir class +\@ifclassloaded{memoir}{}{\RequirePackage{fancyhdr}} +% Use \pagestyle{normal} as the primary pagestyle for text. +% Redefine the 'normal' header/footer style when using "fancyhdr" package: +\@ifpackageloaded{fancyhdr}{% + \ltx@ifundefined{c@chapter} + {% no \chapter, "howto" (non-Japanese) docclass + \fancypagestyle{plain}{ + \fancyhf{} + \fancyfoot[C]{{\py@HeaderFamily\thepage}} + \renewcommand{\headrulewidth}{0pt} + \renewcommand{\footrulewidth}{0pt} + } + % Same as 'plain', this way we can use it in template + % FIXME: shouldn't this have a running header with Name and Release like 'manual'? + \fancypagestyle{normal}{ + \fancyhf{} + \fancyfoot[C]{{\py@HeaderFamily\thepage}} + \renewcommand{\headrulewidth}{0pt} + \renewcommand{\footrulewidth}{0pt} + } + }% + {% classes with \chapter command + \fancypagestyle{normal}{ + \fancyhf{} + \fancyfoot[RO]{{\py@HeaderFamily\thepage}} + \fancyfoot[LO]{{\py@HeaderFamily\nouppercase{\rightmark}}} + \fancyhead[RO]{{\py@HeaderFamily \@title\sphinxheadercomma\py@release}} + \if@twoside + \fancyfoot[LE]{{\py@HeaderFamily\thepage}} + \fancyfoot[RE]{{\py@HeaderFamily\nouppercase{\leftmark}}} + \fancyhead[LE]{{\py@HeaderFamily \@title\sphinxheadercomma\py@release}} + \fi + \renewcommand{\headrulewidth}{0.4pt} + \renewcommand{\footrulewidth}{0.4pt} + % define chaptermark with \@chappos when \@chappos is available for Japanese + \ltx@ifundefined{@chappos}{} + {\def\chaptermark##1{\markboth{\@chapapp\space\thechapter\space\@chappos\space ##1}{}}} + } + % Update the plain style so we get the page number & footer line, + % but not a chapter or section title. This is to keep the first + % page of a chapter `clean.' + \fancypagestyle{plain}{ + \fancyhf{} + \fancyfoot[RO]{{\py@HeaderFamily\thepage}} + \if@twoside\fancyfoot[LE]{{\py@HeaderFamily\thepage}}\fi + \renewcommand{\headrulewidth}{0pt} + \renewcommand{\footrulewidth}{0.4pt} + } + } + } + {% no fancyhdr: memoir class + % Provide default for 'normal' style simply as an alias of 'plain' style + % This way we can use \pagestyle{normal} in LaTeX template + \def\ps@normal{\ps@plain} + % Users of memoir class are invited to redefine 'normal' style in preamble + } + + +\endinput diff --git a/sphinx/texinputs/sphinxlatexstyletext.sty b/sphinx/texinputs/sphinxlatexstyletext.sty new file mode 100644 index 0000000000..ab50aed569 --- /dev/null +++ b/sphinx/texinputs/sphinxlatexstyletext.sty @@ -0,0 +1,126 @@ +%% TEXT STYLING +% +% change this info string if making any custom modification +\ProvidesFile{sphinxlatexstyletext.sty}[2021/01/27 text styling] + +% Basically everything here consists of macros which are part of the latex +% markup produced by the Sphinx latex writer + +% Some custom font markup commands. +\protected\def\sphinxstrong#1{\textbf{#1}} +\protected\def\sphinxcode#1{\texttt{#1}} +\protected\def\sphinxbfcode#1{\textbf{\sphinxcode{#1}}} +\protected\def\sphinxemail#1{\textsf{#1}} +\protected\def\sphinxtablecontinued#1{\textsf{#1}} +\protected\def\sphinxtitleref#1{\emph{#1}} +\protected\def\sphinxmenuselection#1{\emph{#1}} +\protected\def\sphinxguilabel#1{\emph{#1}} +\protected\def\sphinxkeyboard#1{\sphinxcode{#1}} +\protected\def\sphinxaccelerator#1{\underline{#1}} +\protected\def\sphinxcrossref#1{\emph{#1}} +\protected\def\sphinxtermref#1{\emph{#1}} +% \optional is used for ``[, arg]``, i.e. desc_optional nodes. +\long\protected\def\sphinxoptional#1{% + {\textnormal{\Large[}}{#1}\hspace{0.5mm}{\textnormal{\Large]}}} + +% additional customizable styling +\def\sphinxstyleindexentry #1{\texttt{#1}} +\def\sphinxstyleindexextra #1{ (\emph{#1})} +\def\sphinxstyleindexpageref #1{, \pageref{#1}} +\def\sphinxstyleindexpagemain#1{\textbf{#1}} +\def\spxentry{\@backslashchar spxentry}% let to \sphinxstyleindexentry in index +\def\spxextra{\@backslashchar spxextra}% let to \sphinxstyleindexextra in index +\def\sphinxstyleindexlettergroup #1% + {{\Large\sffamily#1}\nopagebreak\vspace{1mm}} +\def\sphinxstyleindexlettergroupDefault #1% + {{\Large\sffamily\sphinxnonalphabeticalgroupname}\nopagebreak\vspace{1mm}} +\protected\def\sphinxstyletopictitle #1{\textbf{#1}\par\medskip} +\let\sphinxstylesidebartitle\sphinxstyletopictitle +\protected\def\sphinxstyleothertitle #1{\textbf{#1}} +\protected\def\sphinxstylesidebarsubtitle #1{~\\\textbf{#1} \smallskip} +% \text.. commands do not allow multiple paragraphs +\protected\def\sphinxstyletheadfamily {\sffamily} +\protected\def\sphinxstyleemphasis #1{\emph{#1}} +\protected\def\sphinxstyleliteralemphasis#1{\emph{\sphinxcode{#1}}} +\protected\def\sphinxstylestrong #1{\textbf{#1}} +\protected\def\sphinxstyleliteralstrong#1{\sphinxbfcode{#1}} +\protected\def\sphinxstyleabbreviation #1{\textsc{#1}} +\protected\def\sphinxstyleliteralintitle#1{\sphinxcode{#1}} +\newcommand*\sphinxstylecodecontinued[1]{\footnotesize(#1)}% +\newcommand*\sphinxstylecodecontinues[1]{\footnotesize(#1)}% +% figure legend comes after caption and may contain arbitrary body elements +\newenvironment{sphinxlegend}{\par\small}{\par} +% reduce hyperref "Token not allowed in a PDF string" warnings on PDF builds +\AtBeginDocument{\pdfstringdefDisableCommands{% +% all "protected" macros possibly ending up in section titles should be here +% TODO: examine if \sphinxhref, \sphinxurl, \sphinnolinkurl should be handled + \let\sphinxstyleemphasis \@firstofone + \let\sphinxstyleliteralemphasis \@firstofone + \let\sphinxstylestrong \@firstofone + \let\sphinxstyleliteralstrong \@firstofone + \let\sphinxstyleabbreviation \@firstofone + \let\sphinxstyleliteralintitle \@firstofone + \let\sphinxupquote \@firstofone + \let\sphinxstrong \@firstofone + \let\sphinxcode \@firstofone + \let\sphinxbfcode \@firstofone + \let\sphinxemail \@firstofone + \let\sphinxcrossref \@firstofone + \let\sphinxtermref \@firstofone + \let\sphinxhyphen\sphinxhyphenforbookmarks +}} + +% Special characters +% +% This definition prevents en-dash and em-dash TeX ligatures. +% +% It inserts a potential breakpoint after the hyphen. This is to keep in sync +% with behavior in code-blocks, parsed and inline literals. For a breakpoint +% before the hyphen use \leavevmode\kern\z@- (within \makeatletter/\makeatother) +\protected\def\sphinxhyphen#1{-\kern\z@} +% The {} from texescape mark-up is kept, else -- gives en-dash in PDF bookmark +\def\sphinxhyphenforbookmarks{-} + +% For curly braces inside \index macro +\def\sphinxleftcurlybrace{\{} +\def\sphinxrightcurlybrace{\}} + +% Declare Unicode characters used by linux tree command to pdflatex utf8/utf8x +\def\spx@bd#1#2{% + \leavevmode + \begingroup + \ifx\spx@bd@height \@undefined\def\spx@bd@height{\baselineskip}\fi + \ifx\spx@bd@width \@undefined\setbox0\hbox{0}\def\spx@bd@width{\wd0 }\fi + \ifx\spx@bd@thickness\@undefined\def\spx@bd@thickness{.6\p@}\fi + \ifx\spx@bd@lower \@undefined\def\spx@bd@lower{\dp\strutbox}\fi + \lower\spx@bd@lower#1{#2}% + \endgroup +}% +\@namedef{sphinx@u2500}% BOX DRAWINGS LIGHT HORIZONTAL + {\spx@bd{\vbox to\spx@bd@height} + {\vss\hrule\@height\spx@bd@thickness + \@width\spx@bd@width\vss}}% +\@namedef{sphinx@u2502}% BOX DRAWINGS LIGHT VERTICAL + {\spx@bd{\hb@xt@\spx@bd@width} + {\hss\vrule\@height\spx@bd@height + \@width \spx@bd@thickness\hss}}% +\@namedef{sphinx@u2514}% BOX DRAWINGS LIGHT UP AND RIGHT + {\spx@bd{\hb@xt@\spx@bd@width} + {\hss\raise.5\spx@bd@height + \hb@xt@\z@{\hss\vrule\@height.5\spx@bd@height + \@width \spx@bd@thickness\hss}% + \vbox to\spx@bd@height{\vss\hrule\@height\spx@bd@thickness + \@width.5\spx@bd@width\vss}}}% +\@namedef{sphinx@u251C}% BOX DRAWINGS LIGHT VERTICAL AND RIGHT + {\spx@bd{\hb@xt@\spx@bd@width} + {\hss + \hb@xt@\z@{\hss\vrule\@height\spx@bd@height + \@width \spx@bd@thickness\hss}% + \vbox to\spx@bd@height{\vss\hrule\@height\spx@bd@thickness + \@width.5\spx@bd@width\vss}}}% +\protected\def\sphinxunichar#1{\@nameuse{sphinx@u#1}}% + +% Tell TeX about pathological hyphenation cases: +\hyphenation{Base-HTTP-Re-quest-Hand-ler} + +\endinput diff --git a/sphinx/texinputs/sphinxmulticell.sty b/sphinx/texinputs/sphinxlatextables.sty similarity index 65% rename from sphinx/texinputs/sphinxmulticell.sty rename to sphinx/texinputs/sphinxlatextables.sty index a6454918f3..c3c1d6ad1f 100644 --- a/sphinx/texinputs/sphinxmulticell.sty +++ b/sphinx/texinputs/sphinxlatextables.sty @@ -1,9 +1,173 @@ -\NeedsTeXFormat{LaTeX2e} -\ProvidesPackage{sphinxmulticell}% - [2017/02/23 v1.6 better span rows and columns of a table (Sphinx team)]% -\DeclareOption*{\PackageWarning{sphinxmulticell}{Option `\CurrentOption' is unknown}}% -\ProcessOptions\relax +%% TABLES (WITH SUPPORT FOR MERGED CELLS OF GENERAL CONTENTS) % +% change this info string if making any custom modification +\ProvidesFile{sphinxlatextables.sty}[2021/01/27 tables]% + +% Provides support for this output mark-up from Sphinx latex writer +% and table templates: +% +% - the tabulary and longtable environments from the eponymous packages +% - the varwidth environment +% - the >{} etc mark-up possible in tabularcolumns is from array package +% which is loaded by longtable and tabulary +% - \X, \Y, T column types; others (L, C, R, J) are from tabulary package +% - \sphinxaftertopcaption +% - \sphinxatlongtableend +% - \sphinxatlongtablestart +% - \sphinxattableend +% - \sphinxattablestart +% - \sphinxcapstartof +% - \sphinxcolwidth +% - \sphinxlongtablecapskipadjust +% - \sphinxmultirow +% - \sphinxstartmulticolumn +% - \sphinxstopmulticolumn +% - \sphinxtablestrut +% - \sphinxthecaptionisattop +% - \sphinxthelongtablecaptionisattop +% +% Executes \RequirePackage for: +% +% - tabulary +% - longtable +% - varwidth +% +% Extends tabulary and longtable via patches and custom macros to support +% merged cells possibly containing code-blocks in complex tables + +\RequirePackage{tabulary} +% tabulary has a bug with its re-definition of \multicolumn in its first pass +% which is not \long. But now Sphinx does not use LaTeX's \multicolumn but its +% own macro. Hence we don't even need to patch tabulary. See +% sphinxpackagemulticell.sty +% X or S (Sphinx) may have meanings if some table package is loaded hence +% \X was chosen to avoid possibility of conflict +\newcolumntype{\X}[2]{p{\dimexpr + (\linewidth-\arrayrulewidth)*#1/#2-\tw@\tabcolsep-\arrayrulewidth\relax}} +\newcolumntype{\Y}[1]{p{\dimexpr + #1\dimexpr\linewidth-\arrayrulewidth\relax-\tw@\tabcolsep-\arrayrulewidth\relax}} +% using here T (for Tabulary) feels less of a problem than the X could be +\newcolumntype{T}{J}% +% For tables allowing pagebreaks +\RequirePackage{longtable} +% User interface to set-up whitespace before and after tables: +\newcommand*\sphinxtablepre {0pt}% +\newcommand*\sphinxtablepost{\medskipamount}% +% Space from caption baseline to top of table or frame of literal-block +\newcommand*\sphinxbelowcaptionspace{.5\sphinxbaselineskip}% +% as one can not use \baselineskip from inside longtable (it is zero there) +% we need \sphinxbaselineskip, which defaults to \baselineskip +\def\sphinxbaselineskip{\baselineskip}% +% The following is to ensure that, whether tabular(y) or longtable: +% - if a caption is on top of table: +% a) the space between its last baseline and the top rule of table is +% exactly \sphinxbelowcaptionspace +% b) the space from last baseline of previous text to first baseline of +% caption is exactly \parskip+\baselineskip+ height of a strut. +% c) the caption text will wrap at width \LTcapwidth (4in) +% - make sure this works also if "caption" package is loaded by user +% (with its width or margin option taking place of \LTcapwidth role) +% TODO: obtain same for caption of literal block: a) & c) DONE, b) TO BE DONE +% +% To modify space below such top caption, adjust \sphinxbelowcaptionspace +% To add or remove space above such top caption, adjust \sphinxtablepre: +% notice that \abovecaptionskip, \belowcaptionskip, \LTpre are **ignored** +% A. Table with longtable +\def\sphinxatlongtablestart + {\par + \vskip\parskip + \vskip\dimexpr\sphinxtablepre\relax % adjust vertical position + \vbox{}% get correct baseline from above + \LTpre\z@skip\LTpost\z@skip % set to zero longtable's own skips + \edef\sphinxbaselineskip{\dimexpr\the\dimexpr\baselineskip\relax\relax}% + }% +% Compatibility with caption package +\def\sphinxthelongtablecaptionisattop{% + \spx@ifcaptionpackage{\noalign{\vskip-\belowcaptionskip}}{}% +}% +% Achieves exactly \sphinxbelowcaptionspace below longtable caption +\def\sphinxlongtablecapskipadjust + {\dimexpr-\dp\strutbox + -\spx@ifcaptionpackage{\abovecaptionskip}{\sphinxbaselineskip}% + +\sphinxbelowcaptionspace\relax}% +\def\sphinxatlongtableend{\@nobreakfalse % latex3/latex2e#173 + \prevdepth\z@\vskip\sphinxtablepost\relax}% +% B. Table with tabular or tabulary +\def\sphinxattablestart{\par\vskip\dimexpr\sphinxtablepre\relax}% +\let\sphinxattableend\sphinxatlongtableend +% This is used by tabular and tabulary templates +\newcommand*\sphinxcapstartof[1]{% + \vskip\parskip + \vbox{}% force baselineskip for good positioning by capstart of hyperanchor + % hyperref puts the anchor 6pt above this baseline; in case of caption + % this baseline will be \ht\strutbox above first baseline of caption + \def\@captype{#1}% + \capstart +% move back vertically, as tabular (or its caption) will compensate + \vskip-\baselineskip\vskip-\parskip +}% +\def\sphinxthecaptionisattop{% locate it after \sphinxcapstartof + \spx@ifcaptionpackage + {\caption@setposition{t}% + \vskip\baselineskip\vskip\parskip % undo those from \sphinxcapstartof + \vskip-\belowcaptionskip % anticipate caption package skip + % caption package uses a \vbox, not a \vtop, so "single line" case + % gives different result from "multi-line" without this: + \nointerlineskip + }% + {}% +}% +\def\sphinxthecaptionisatbottom{% (not finalized; for template usage) + \spx@ifcaptionpackage{\caption@setposition{b}}{}% +}% +% The aim of \sphinxcaption is to apply to tabular(y) the maximal width +% of caption as done by longtable +\def\sphinxtablecapwidth{\LTcapwidth}% +\newcommand\sphinxcaption{\@dblarg\spx@caption}% +\long\def\spx@caption[#1]#2{% + \noindent\hb@xt@\linewidth{\hss + \vtop{\@tempdima\dimexpr\sphinxtablecapwidth\relax +% don't exceed linewidth for the caption width + \ifdim\@tempdima>\linewidth\hsize\linewidth\else\hsize\@tempdima\fi +% longtable ignores \abovecaptionskip/\belowcaptionskip, so do the same here + \abovecaptionskip\sphinxabovecaptionskip % \z@skip + \belowcaptionskip\sphinxbelowcaptionskip % \z@skip + \caption[{#1}]% + {\strut\ignorespaces#2\ifhmode\unskip\@finalstrut\strutbox\fi}% + }\hss}% + \par\prevdepth\dp\strutbox +}% +\def\sphinxabovecaptionskip{\z@skip}% Do not use! Flagged for removal +\def\sphinxbelowcaptionskip{\z@skip}% Do not use! Flagged for removal +% This wrapper of \abovecaptionskip is used in sphinxVerbatim for top +% caption, and with another value in sphinxVerbatimintable +% TODO: To unify space above caption of a code-block with the one above +% caption of a table/longtable, \abovecaptionskip must not be used +% This auxiliary will get renamed and receive a different meaning +% in future. +\def\spx@abovecaptionskip{\abovecaptionskip}% +% Achieve \sphinxbelowcaptionspace below a caption located above a tabular +% or a tabulary +\newcommand\sphinxaftertopcaption +{% + \spx@ifcaptionpackage + {\par\prevdepth\dp\strutbox\nobreak\vskip-\abovecaptionskip}{\nobreak}% + \vskip\dimexpr\sphinxbelowcaptionspace\relax + \vskip-\baselineskip\vskip-\parskip +}% +% varwidth is crucial for our handling of general contents in merged cells +\RequirePackage{varwidth} +% but addition of a compatibility patch with hyperref is needed +% (tested with varwidth v 0.92 Mar 2009) +\AtBeginDocument {% + \let\@@vwid@Hy@raisedlink\Hy@raisedlink + \long\def\@vwid@Hy@raisedlink#1{\@vwid@wrap{\@@vwid@Hy@raisedlink{#1}}}% + \edef\@vwid@setup{% + \let\noexpand\Hy@raisedlink\noexpand\@vwid@Hy@raisedlink % HYPERREF ! + \unexpanded\expandafter{\@vwid@setup}}% +}% + +%%%%%%%%%%%%%%%%%%%%% % --- MULTICOLUMN --- % standard LaTeX's \multicolumn % 1. does not allow verbatim contents, @@ -205,7 +369,8 @@ \def\sphinx@multiwidth #1#2{\dimexpr % #1 to gobble the \@gobble (!) (\ifx\TY@final\@undefined\linewidth\else\sphinx@TY@tablewidth\fi -\arrayrulewidth)*#2-\tw@\tabcolsep-\arrayrulewidth\relax}% -% + +%%%%%%%%%%%%%%%%%% % --- MULTIROW --- % standard \multirow % 1. does not allow verbatim contents, @@ -312,6 +477,5 @@ % we need this to avoid colour panels hiding bottom parts of multirow text \sphinx@hack@CT }% + \endinput -%% -%% End of file `sphinxmulticell.sty'. diff --git a/sphinx/texinputs/sphinxoptionsgeometry.sty b/sphinx/texinputs/sphinxoptionsgeometry.sty new file mode 100644 index 0000000000..af5a804d59 --- /dev/null +++ b/sphinx/texinputs/sphinxoptionsgeometry.sty @@ -0,0 +1,54 @@ +%% OPTIONS FOR GEOMETRY +% +% change this info string if making any custom modification +\ProvidesFile{sphinxoptionsgeometry.sty}[2021/01/27 geometry] + +% geometry +\ifx\kanjiskip\@undefined + \PassOptionsToPackage{% + hmargin={\unexpanded{\spx@opt@hmargin}},% + vmargin={\unexpanded{\spx@opt@vmargin}},% + marginpar=\unexpanded{\spx@opt@marginpar}} + {geometry} +\else + % set text width for Japanese documents to be integer multiple of 1zw + % and text height to be integer multiple of \baselineskip + % the execution is delayed to \sphinxsetup then geometry.sty + \normalsize\normalfont + \newcommand*\sphinxtextwidthja[1]{% + \if@twocolumn\tw@\fi + \dimexpr + \numexpr\dimexpr\paperwidth-\tw@\dimexpr#1\relax\relax/ + \dimexpr\if@twocolumn\tw@\else\@ne\fi zw\relax + zw\relax}% + \newcommand*\sphinxmarginparwidthja[1]{% + \dimexpr\numexpr\dimexpr#1\relax/\dimexpr1zw\relax zw\relax}% + \newcommand*\sphinxtextlinesja[1]{% + \numexpr\@ne+\dimexpr\paperheight-\topskip-\tw@\dimexpr#1\relax\relax/ + \baselineskip\relax}% + \ifx\@jsc@uplatextrue\@undefined\else + % the way we found in order for the papersize special written by + % geometry in the dvi file to be correct in case of jsbook class + \ifnum\mag=\@m\else % do nothing special if nomag class option or 10pt + \PassOptionsToPackage{truedimen}{geometry}% + \fi + \fi + \PassOptionsToPackage{% + hmarginratio={1:1},% + textwidth=\unexpanded{\sphinxtextwidthja{\spx@opt@hmargin}},% + vmarginratio={1:1},% + lines=\unexpanded{\sphinxtextlinesja{\spx@opt@vmargin}},% + marginpar=\unexpanded{\sphinxmarginparwidthja{\spx@opt@marginpar}},% + footskip=2\baselineskip,% + }{geometry}% + \AtBeginDocument + {% update a dimension used by the jsclasses + \ifx\@jsc@uplatextrue\@undefined\else\fullwidth\textwidth\fi + % for some reason, jreport normalizes all dimensions with \@settopoint + \@ifclassloaded{jreport} + {\@settopoint\textwidth\@settopoint\textheight\@settopoint\marginparwidth} + {}% <-- "false" clause of \@ifclassloaded + }% +\fi + +\endinput diff --git a/sphinx/texinputs/sphinxoptionshyperref.sty b/sphinx/texinputs/sphinxoptionshyperref.sty new file mode 100644 index 0000000000..6017d89704 --- /dev/null +++ b/sphinx/texinputs/sphinxoptionshyperref.sty @@ -0,0 +1,35 @@ +%% Bookmarks and hyperlinks +% +% change this info string if making any custom modification +\ProvidesFile{sphinxoptionshyperref.sty}[2021/01/27 hyperref] + +% to make pdf with correct encoded bookmarks in Japanese +% this should precede the hyperref package +\ifx\kanjiskip\@undefined +% for non-Japanese: make sure bookmarks are ok also with lualatex + \PassOptionsToPackage{pdfencoding=unicode}{hyperref} +\else + \RequirePackage{atbegshi} + \ifx\ucs\@undefined + \ifnum 42146=\euc"A4A2 + \AtBeginShipoutFirst{\special{pdf:tounicode EUC-UCS2}} + \else + \AtBeginShipoutFirst{\special{pdf:tounicode 90ms-RKSJ-UCS2}} + \fi + \else + \AtBeginShipoutFirst{\special{pdf:tounicode UTF8-UCS2}} + \fi +\fi + +\ifx\@jsc@uplatextrue\@undefined\else + \PassOptionsToPackage{setpagesize=false}{hyperref} +\fi + +% These options can be overriden inside 'hyperref' key +% or by later use of \hypersetup. +\PassOptionsToPackage{colorlinks,breaklinks,% + linkcolor=InnerLinkColor,filecolor=OuterLinkColor,% + menucolor=OuterLinkColor,urlcolor=OuterLinkColor,% + citecolor=InnerLinkColor}{hyperref} + +\endinput diff --git a/sphinx/texinputs/sphinxcyrillic.sty b/sphinx/texinputs/sphinxpackagecyrillic.sty similarity index 98% rename from sphinx/texinputs/sphinxcyrillic.sty rename to sphinx/texinputs/sphinxpackagecyrillic.sty index 6747b5ec64..9aa62fc22b 100644 --- a/sphinx/texinputs/sphinxcyrillic.sty +++ b/sphinx/texinputs/sphinxpackagecyrillic.sty @@ -1,7 +1,7 @@ %% CYRILLIC IN NON-CYRILLIC DOCUMENTS (pdflatex only) % % refs: https://tex.stackexchange.com/q/460271/ -\ProvidesPackage{sphinxcyrillic}% +\ProvidesPackage{sphinxpackagecyrillic}% [2018/11/21 v2.0 support for Cyrillic in non-Cyrillic documents] \RequirePackage{kvoptions} \SetupKeyvalOptions{prefix=spx@cyropt@} % use \spx@cyropt@ prefix diff --git a/sphinx/texinputs/footnotehyper-sphinx.sty b/sphinx/texinputs/sphinxpackagefootnote.sty similarity index 96% rename from sphinx/texinputs/footnotehyper-sphinx.sty rename to sphinx/texinputs/sphinxpackagefootnote.sty index 3bba385a82..a6071cf103 100644 --- a/sphinx/texinputs/footnotehyper-sphinx.sty +++ b/sphinx/texinputs/sphinxpackagefootnote.sty @@ -1,8 +1,13 @@ \NeedsTeXFormat{LaTeX2e} -\ProvidesPackage{footnotehyper-sphinx}% - [2021/02/04 v1.1d hyperref aware footnote.sty for sphinx (JFB)] +\ProvidesPackage{sphinxpackagefootnote}% + [2021/02/04 v1.1d footnotehyper adapted to sphinx (Sphinx team)] +% Provides support for this output mark-up from Sphinx latex writer: +% - footnote environment +% - savenotes environment (table templates) +% - \sphinxfootnotemark +% %% -%% Package: footnotehyper-sphinx +%% Package: sphinxpackagefootnote %% Version: based on footnotehyper.sty 2021/02/04 v1.1d %% as available at https://www.ctan.org/pkg/footnotehyper %% License: the one applying to Sphinx @@ -18,7 +23,7 @@ %% 5. macro definition \sphinxlongtablepatch %% 6. replaced some \undefined by \@undefined \newif\iffootnotehyperparse\footnotehyperparsetrue -\DeclareOption*{\PackageWarning{footnotehyper-sphinx}{Option `\CurrentOption' is unknown}}% +\DeclareOption*{\PackageWarning{sphinxpackagefootnote}{Option `\CurrentOption' is unknown}}% \ProcessOptions\relax \newbox\FNH@notes \newtoks\FNH@toks % 1.1c @@ -292,7 +297,7 @@ }% % slight reformulation for Sphinx \def\FNH@bad@makefntext@alert{% - \PackageWarningNoLine{footnotehyper-sphinx}% + \PackageWarningNoLine{sphinxpackagefootnote}% {Footnotes will be sub-optimal, sorry. This is due to the document class or^^J some package modifying macro \string\@makefntext.^^J You can try to report this incompatibility at^^J @@ -322,6 +327,7 @@ \noexpand\if@endpe\noexpand\@endpetrue\noexpand\fi }% }% +% % some extras for Sphinx : % \sphinxfootnotemark: usable in section titles and silently removed from TOCs. \def\sphinxfootnotemark [#1]% @@ -387,4 +393,4 @@ }% \endinput %% -%% End of file `footnotehyper-sphinx.sty'. +%% End of file `sphinxpackagefootnote.sty'. diff --git a/sphinx/themes/agogo/layout.html b/sphinx/themes/agogo/layout.html index 1d9df693be..855ec8ccb1 100644 --- a/sphinx/themes/agogo/layout.html +++ b/sphinx/themes/agogo/layout.html @@ -13,14 +13,14 @@ {% block header %}
  • {%- endfor %} {%- block rootrellink %} - + {%- endblock %} {%- for parent in parents %} @@ -53,9 +51,9 @@

    {{ _('Navigation') }}

) if multiple IDs are assigned to listings. - That is invalid DOM structure. (This is a bug of docutils <= 0.13.1) - - This exports hyperlink targets before tables to make valid DOM structure. - """ - for id in node['ids'][1:]: - self.body.append('' % id) - node['ids'].remove(id) - def visit_table(self, node: Element) -> None: - self.generate_targets_for_table(node) - self._table_row_index = 0 atts = {} classes = [cls.strip(' \t\n') for cls in self.settings.table_style.split(',')] classes.insert(0, "docutils") # compat - if 'align' in node: - classes.append('align-%s' % node['align']) + + # set align-default if align not specified to give a default style + classes.append('align-%s' % node.get('align', 'default')) + if 'width' in node: atts['style'] = 'width: %s' % node['width'] tag = self.starttag(node, 'table', CLASS=' '.join(classes), **atts) @@ -794,3 +780,18 @@ def permalink_text(self) -> str: warnings.warn('HTMLTranslator.permalink_text is deprecated.', RemovedInSphinx50Warning, stacklevel=2) return self.config.html_permalinks_icon + + def generate_targets_for_table(self, node: Element) -> None: + """Generate hyperlink targets for tables. + + Original visit_table() generates hyperlink targets inside table tags + (
) if multiple IDs are assigned to listings. + That is invalid DOM structure. (This is a bug of docutils <= 0.13.1) + + This exports hyperlink targets before tables to make valid DOM structure. + """ + warnings.warn('generate_targets_for_table() is deprecated', + RemovedInSphinx60Warning, stacklevel=2) + for id in node['ids'][1:]: + self.body.append('' % id) + node['ids'].remove(id) diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py index 247a7dfb52..93f97d028e 100644 --- a/sphinx/writers/latex.py +++ b/sphinx/writers/latex.py @@ -15,14 +15,13 @@ import warnings from collections import defaultdict from os import path -from typing import Any, Dict, Iterable, Iterator, List, Set, Tuple, Union, cast +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Set, Tuple, cast from docutils import nodes, writers from docutils.nodes import Element, Node, Text from sphinx import addnodes, highlighting -from sphinx.deprecation import (RemovedInSphinx40Warning, RemovedInSphinx50Warning, - deprecated_alias) +from sphinx.deprecation import RemovedInSphinx50Warning from sphinx.domains import IndexEntry from sphinx.domains.std import StandardDomain from sphinx.errors import SphinxError @@ -39,8 +38,7 @@ # In Debain/Ubuntu, roman package is provided as roman, not as docutils.utils.roman from roman import toRoman # type: ignore -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.builders.latex import LaTeXBuilder from sphinx.builders.latex.theming import Theme @@ -110,7 +108,7 @@ class Table: def __init__(self, node: Element) -> None: self.header = [] # type: List[str] self.body = [] # type: List[str] - self.align = node.get('align') + self.align = node.get('align', 'default') self.colcount = 0 self.colspec = None # type: str self.colwidths = [] # type: List[int] @@ -166,15 +164,15 @@ def get_colspec(self) -> str: return self.colspec elif self.colwidths and 'colwidths-given' in self.classes: total = sum(self.colwidths) - colspecs = ['\\X{%d}{%d}' % (width, total) for width in self.colwidths] + colspecs = [r'\X{%d}{%d}' % (width, total) for width in self.colwidths] return '{|%s|}' % '|'.join(colspecs) + CR elif self.has_problematic: - return '{|*{%d}{\\X{1}{%d}|}}' % (self.colcount, self.colcount) + CR + return r'{|*{%d}{\X{1}{%d}|}}' % (self.colcount, self.colcount) + CR elif self.get_table_type() == 'tabulary': # sphinx.sty sets T to be J by default. return '{|' + ('T|' * self.colcount) + '}' + CR elif self.has_oldproblematic: - return '{|*{%d}{\\X{1}{%d}|}}' % (self.colcount, self.colcount) + CR + return r'{|*{%d}{\X{1}{%d}|}}' % (self.colcount, self.colcount) + CR else: return '{|' + ('l|' * self.colcount) + '}' + CR @@ -255,19 +253,19 @@ def rstdim_to_latexdim(width_str: str, scale: int = 100) -> str: if scale == 100: float(amount) # validate amount is float if unit in ('', "px"): - res = "%s\\sphinxpxdimen" % amount + res = r"%s\sphinxpxdimen" % amount elif unit == 'pt': res = '%sbp' % amount # convert to 'bp' elif unit == "%": - res = "%.3f\\linewidth" % (float(amount) / 100.0) + res = r"%.3f\linewidth" % (float(amount) / 100.0) else: amount_float = float(amount) * scale / 100.0 if unit in ('', "px"): - res = "%.5f\\sphinxpxdimen" % amount_float + res = r"%.5f\sphinxpxdimen" % amount_float elif unit == 'pt': res = '%.5fbp' % amount_float elif unit == "%": - res = "%.5f\\linewidth" % (amount_float / 100.0) + res = r"%.5f\linewidth" % (amount_float / 100.0) else: res = "%.5f%s" % (amount_float, unit) return res @@ -375,9 +373,9 @@ def __init__(self, document: nodes.document, builder: "LaTeXBuilder", if (self.config.language not in {None, 'en', 'ja'} and 'fncychap' not in self.config.latex_elements): # use Sonny style if any language specified (except English) - self.elements['fncychap'] = ('\\usepackage[Sonny]{fncychap}' + CR + - '\\ChNameVar{\\Large\\normalfont\\sffamily}' + CR + - '\\ChTitleVar{\\Large\\normalfont\\sffamily}') + self.elements['fncychap'] = (r'\usepackage[Sonny]{fncychap}' + CR + + r'\ChNameVar{\Large\normalfont\sffamily}' + CR + + r'\ChTitleVar{\Large\normalfont\sffamily}') self.babel = self.builder.babel if self.config.language and not self.babel.is_supported_language(): @@ -402,19 +400,19 @@ def __init__(self, document: nodes.document, builder: "LaTeXBuilder", logger.warning(__('too large :maxdepth:, ignored.')) tocdepth = len(LATEXSECTIONNAMES) - 2 - self.elements['tocdepth'] = '\\setcounter{tocdepth}{%d}' % tocdepth + self.elements['tocdepth'] = r'\setcounter{tocdepth}{%d}' % tocdepth minsecnumdepth = max(minsecnumdepth, tocdepth) if self.config.numfig and (self.config.numfig_secnum_depth > 0): minsecnumdepth = max(minsecnumdepth, self.numfig_secnum_depth - 1) if minsecnumdepth > self.secnumdepth: - self.elements['secnumdepth'] = '\\setcounter{secnumdepth}{%d}' %\ + self.elements['secnumdepth'] = r'\setcounter{secnumdepth}{%d}' %\ minsecnumdepth contentsname = document.get('contentsname') if contentsname: - self.elements['contentsname'] = self.babel_renewcommand('\\contentsname', + self.elements['contentsname'] = self.babel_renewcommand(r'\contentsname', contentsname) if self.elements['maxlistdepth']: @@ -422,8 +420,7 @@ def __init__(self, document: nodes.document, builder: "LaTeXBuilder", if sphinxpkgoptions: self.elements['sphinxpkgoptions'] = '[,%s]' % ','.join(sphinxpkgoptions) if self.elements['sphinxsetup']: - self.elements['sphinxsetup'] = ('\\sphinxsetup{%s}' % - self.elements['sphinxsetup']) + self.elements['sphinxsetup'] = (r'\sphinxsetup{%s}' % self.elements['sphinxsetup']) if self.elements['extraclassoptions']: self.elements['classoptions'] += ',' + \ self.elements['extraclassoptions'] @@ -468,8 +465,7 @@ def astext(self) -> str: def hypertarget(self, id: str, withdoc: bool = True, anchor: bool = True) -> str: if withdoc: id = self.curfilestack[-1] + ':' + id - return ('\\phantomsection' if anchor else '') + \ - '\\label{%s}' % self.idescape(id) + return (r'\phantomsection' if anchor else '') + r'\label{%s}' % self.idescape(id) def hypertarget_to(self, node: Element, anchor: bool = False) -> str: labels = ''.join(self.hypertarget(node_id, anchor=False) for node_id in node['ids']) @@ -479,48 +475,48 @@ def hypertarget_to(self, node: Element, anchor: bool = False) -> str: return labels def hyperlink(self, id: str) -> str: - return '{\\hyperref[%s]{' % self.idescape(id) + return r'{\hyperref[%s]{' % self.idescape(id) def hyperpageref(self, id: str) -> str: - return '\\autopageref*{%s}' % self.idescape(id) + return r'\autopageref*{%s}' % self.idescape(id) def escape(self, s: str) -> str: return texescape.escape(s, self.config.latex_engine) def idescape(self, id: str) -> str: - return '\\detokenize{%s}' % str(id).translate(tex_replace_map).\ + return r'\detokenize{%s}' % str(id).translate(tex_replace_map).\ encode('ascii', 'backslashreplace').decode('ascii').\ replace('\\', '_') def babel_renewcommand(self, command: str, definition: str) -> str: if self.elements['multilingual']: - prefix = '\\addto\\captions%s{' % self.babel.get_language() + prefix = r'\addto\captions%s{' % self.babel.get_language() suffix = '}' else: # babel is disabled (mainly for Japanese environment) prefix = '' suffix = '' - return '%s\\renewcommand{%s}{%s}%s' % (prefix, command, definition, suffix) + CR + return r'%s\renewcommand{%s}{%s}%s' % (prefix, command, definition, suffix) + CR def generate_indices(self) -> str: def generate(content: List[Tuple[str, List[IndexEntry]]], collapsed: bool) -> None: - ret.append('\\begin{sphinxtheindex}' + CR) - ret.append('\\let\\bigletter\\sphinxstyleindexlettergroup' + CR) + ret.append(r'\begin{sphinxtheindex}' + CR) + ret.append(r'\let\bigletter\sphinxstyleindexlettergroup' + CR) for i, (letter, entries) in enumerate(content): if i > 0: - ret.append('\\indexspace' + CR) - ret.append('\\bigletter{%s}' % self.escape(letter) + CR) + ret.append(r'\indexspace' + CR) + ret.append(r'\bigletter{%s}' % self.escape(letter) + CR) for entry in entries: if not entry[3]: continue - ret.append('\\item\\relax\\sphinxstyleindexentry{%s}' % + ret.append(r'\item\relax\sphinxstyleindexentry{%s}' % self.encode(entry[0])) if entry[4]: # add "extra" info - ret.append('\\sphinxstyleindexextra{%s}' % self.encode(entry[4])) - ret.append('\\sphinxstyleindexpageref{%s:%s}' % + ret.append(r'\sphinxstyleindexextra{%s}' % self.encode(entry[4])) + ret.append(r'\sphinxstyleindexpageref{%s:%s}' % (entry[2], self.idescape(entry[3])) + CR) - ret.append('\\end{sphinxtheindex}' + CR) + ret.append(r'\end{sphinxtheindex}' + CR) ret = [] # latex_domain_indices can be False/True or a list of index names @@ -536,7 +532,7 @@ def generate(content: List[Tuple[str, List[IndexEntry]]], collapsed: bool) -> No self.builder.docnames) if not content: continue - ret.append('\\renewcommand{\\indexname}{%s}' % indexcls.localname + CR) + ret.append(r'\renewcommand{\indexname}{%s}' % indexcls.localname + CR) generate(content, collapsed) return ''.join(ret) @@ -566,7 +562,7 @@ def visit_document(self, node: Element) -> None: self.first_document = 0 elif self.first_document == 0: # ... and all others are the appendices - self.body.append(CR + '\\appendix' + CR) + self.body.append(CR + r'\appendix' + CR) self.first_document = -1 if 'docname' in node: self.body.append(self.hypertarget(':doc')) @@ -599,11 +595,11 @@ def depart_problematic(self, node: Element) -> None: def visit_topic(self, node: Element) -> None: self.in_minipage = 1 - self.body.append(CR + '\\begin{sphinxShadowBox}' + CR) + self.body.append(CR + r'\begin{sphinxShadowBox}' + CR) def depart_topic(self, node: Element) -> None: self.in_minipage = 0 - self.body.append('\\end{sphinxShadowBox}' + CR) + self.body.append(r'\end{sphinxShadowBox}' + CR) visit_sidebar = visit_topic depart_sidebar = depart_topic @@ -615,20 +611,20 @@ def depart_glossary(self, node: Element) -> None: def visit_productionlist(self, node: Element) -> None: self.body.append(BLANKLINE) - self.body.append('\\begin{productionlist}' + CR) + self.body.append(r'\begin{productionlist}' + CR) self.in_production_list = 1 def depart_productionlist(self, node: Element) -> None: - self.body.append('\\end{productionlist}' + BLANKLINE) + self.body.append(r'\end{productionlist}' + BLANKLINE) self.in_production_list = 0 def visit_production(self, node: Element) -> None: if node['tokenname']: tn = node['tokenname'] self.body.append(self.hypertarget('grammar-token-' + tn)) - self.body.append('\\production{%s}{' % self.encode(tn)) + self.body.append(r'\production{%s}{' % self.encode(tn)) else: - self.body.append('\\productioncont{') + self.body.append(r'\productioncont{') def depart_production(self, node: Element) -> None: self.body.append('}' + CR) @@ -683,7 +679,7 @@ def visit_title(self, node: Element) -> None: logger.warning(__('encountered title node not in section, topic, table, ' 'admonition or sidebar'), location=node) - self.body.append('\\sphinxstyleothertitle{') + self.body.append(r'\sphinxstyleothertitle{') self.context.append('}' + CR) self.in_title = 1 @@ -696,7 +692,7 @@ def depart_title(self, node: Element) -> None: def visit_subtitle(self, node: Element) -> None: if isinstance(node.parent, nodes.sidebar): - self.body.append('\\sphinxstylesidebarsubtitle{') + self.body.append(r'\sphinxstylesidebarsubtitle{') self.context.append('}' + CR) else: self.context.append('') @@ -707,18 +703,18 @@ def depart_subtitle(self, node: Element) -> None: def visit_desc(self, node: Element) -> None: if self.config.latex_show_urls == 'footnote': self.body.append(BLANKLINE) - self.body.append('\\begin{savenotes}\\begin{fulllineitems}' + CR) + self.body.append(r'\begin{savenotes}\begin{fulllineitems}' + CR) else: self.body.append(BLANKLINE) - self.body.append('\\begin{fulllineitems}' + CR) + self.body.append(r'\begin{fulllineitems}' + CR) if self.table: self.table.has_problematic = True def depart_desc(self, node: Element) -> None: if self.config.latex_show_urls == 'footnote': - self.body.append(CR + '\\end{fulllineitems}\\end{savenotes}' + BLANKLINE) + self.body.append(CR + r'\end{fulllineitems}\end{savenotes}' + BLANKLINE) else: - self.body.append(CR + '\\end{fulllineitems}' + BLANKLINE) + self.body.append(CR + r'\end{fulllineitems}' + BLANKLINE) def _visit_signature_line(self, node: Element) -> None: for child in node: @@ -741,14 +737,14 @@ def visit_desc_signature(self, node: Element) -> None: self._visit_signature_line(node) else: self.body.append('%' + CR) - self.body.append('\\pysigstartmultiline' + CR) + self.body.append(r'\pysigstartmultiline' + CR) def depart_desc_signature(self, node: Element) -> None: if not node.get('is_multiline'): self._depart_signature_line(node) else: self.body.append('%' + CR) - self.body.append('\\pysigstopmultiline') + self.body.append(r'\pysigstopmultiline') def visit_desc_signature_line(self, node: Element) -> None: self._visit_signature_line(node) @@ -827,8 +823,8 @@ def depart_desc_content(self, node: Element) -> None: def visit_seealso(self, node: Element) -> None: self.body.append(BLANKLINE) - self.body.append('\\sphinxstrong{%s:}' % admonitionlabels['seealso'] + CR) - self.body.append('\\nopagebreak' + BLANKLINE) + self.body.append(r'\sphinxstrong{%s:}' % admonitionlabels['seealso'] + CR) + self.body.append(r'\nopagebreak' + BLANKLINE) def depart_seealso(self, node: Element) -> None: self.body.append(BLANKLINE) @@ -836,7 +832,7 @@ def depart_seealso(self, node: Element) -> None: def visit_rubric(self, node: Element) -> None: if len(node) == 1 and node.astext() in ('Footnotes', _('Footnotes')): raise nodes.SkipNode - self.body.append('\\subsubsection*{') + self.body.append(r'\subsubsection*{') self.context.append('}' + CR) self.in_title = 1 @@ -848,23 +844,23 @@ def visit_footnote(self, node: Element) -> None: self.in_footnote += 1 label = cast(nodes.label, node[0]) if 'auto' not in node: - self.body.append('\\sphinxstepexplicit ') + self.body.append(r'\sphinxstepexplicit ') if self.in_parsed_literal: - self.body.append('\\begin{footnote}[%s]' % label.astext()) + self.body.append(r'\begin{footnote}[%s]' % label.astext()) else: self.body.append('%' + CR) - self.body.append('\\begin{footnote}[%s]' % label.astext()) + self.body.append(r'\begin{footnote}[%s]' % label.astext()) if 'auto' not in node: - self.body.append('\\phantomsection' - '\\label{\\thesphinxscope.%s}%%' % label.astext() + CR) - self.body.append('\\sphinxAtStartFootnote' + CR) + self.body.append(r'\phantomsection' + r'\label{\thesphinxscope.%s}%%' % label.astext() + CR) + self.body.append(r'\sphinxAtStartFootnote' + CR) def depart_footnote(self, node: Element) -> None: if self.in_parsed_literal: - self.body.append('\\end{footnote}') + self.body.append(r'\end{footnote}') else: self.body.append('%' + CR) - self.body.append('\\end{footnote}') + self.body.append(r'\end{footnote}') self.in_footnote -= 1 def visit_label(self, node: Element) -> None: @@ -952,25 +948,24 @@ def visit_row(self, node: Element) -> None: self.body.append('&') if cell.width == 1: # insert suitable strut for equalizing row heights in given multirow - self.body.append('\\sphinxtablestrut{%d}' % cell.cell_id) + self.body.append(r'\sphinxtablestrut{%d}' % cell.cell_id) else: # use \multicolumn for wide multirow cell - self.body.append('\\multicolumn{%d}{|l|}' - '{\\sphinxtablestrut{%d}}' % + self.body.append(r'\multicolumn{%d}{|l|}\sphinxtablestrut{%d}}' % (cell.width, cell.cell_id)) def depart_row(self, node: Element) -> None: - self.body.append('\\\\' + CR) + self.body.append(r'\\' + CR) cells = [self.table.cell(self.table.row, i) for i in range(self.table.colcount)] underlined = [cell.row + cell.height == self.table.row + 1 for cell in cells] if all(underlined): - self.body.append('\\hline') + self.body.append(r'\hline') else: i = 0 underlined.extend([False]) # sentinel while i < len(underlined): if underlined[i] is True: j = underlined[i:].index(False) - self.body.append('\\cline{%d-%d}' % (i + 1, i + j)) + self.body.append(r'\cline{%d-%d}' % (i + 1, i + j)) i += j i += 1 self.table.row += 1 @@ -984,22 +979,22 @@ def visit_entry(self, node: Element) -> None: if cell.width > 1: if self.config.latex_use_latex_multicolumn: if self.table.col == 0: - self.body.append('\\multicolumn{%d}{|l|}{%%' % cell.width + CR) + self.body.append(r'\multicolumn{%d}{|l|}{%%' % cell.width + CR) else: - self.body.append('\\multicolumn{%d}{l|}{%%' % cell.width + CR) + self.body.append(r'\multicolumn{%d}{l|}{%%' % cell.width + CR) context = '}%' + CR else: - self.body.append('\\sphinxstartmulticolumn{%d}%%' % cell.width + CR) - context = '\\sphinxstopmulticolumn' + CR + self.body.append(r'\sphinxstartmulticolumn{%d}%%' % cell.width + CR) + context = r'\sphinxstopmulticolumn' + CR if cell.height > 1: # \sphinxmultirow 2nd arg "cell_id" will serve as id for LaTeX macros as well - self.body.append('\\sphinxmultirow{%d}{%d}{%%' % (cell.height, cell.cell_id) + CR) + self.body.append(r'\sphinxmultirow{%d}{%d}{%%' % (cell.height, cell.cell_id) + CR) context = '}%' + CR + context if cell.width > 1 or cell.height > 1: - self.body.append('\\begin{varwidth}[t]{\\sphinxcolwidth{%d}{%d}}' + self.body.append(r'\begin{varwidth}[t]{\sphinxcolwidth{%d}{%d}}' % (cell.width, self.table.colcount) + CR) - context = ('\\par' + CR + '\\vskip-\\baselineskip' - '\\vbox{\\hbox{\\strut}}\\end{varwidth}%' + CR + context) + context = (r'\par' + CR + r'\vskip-\baselineskip' + r'\vbox{\hbox{\strut}}\end{varwidth}%' + CR + context) self.needs_linetrimming = 1 if len(node.traverse(nodes.paragraph)) >= 2: self.table.has_oldproblematic = True @@ -1007,7 +1002,7 @@ def visit_entry(self, node: Element) -> None: if len(node) == 1 and isinstance(node[0], nodes.paragraph) and node.astext() == '': pass else: - self.body.append('\\sphinxstyletheadfamily ') + self.body.append(r'\sphinxstyletheadfamily ') if self.needs_linetrimming: self.pushbody([]) self.context.append(context) @@ -1038,11 +1033,10 @@ def depart_entry(self, node: Element) -> None: if nextcell.width == 1: # insert suitable strut for equalizing row heights in multirow # they also serve to clear colour panels which would hide the text - self.body.append('\\sphinxtablestrut{%d}' % nextcell.cell_id) + self.body.append(r'\sphinxtablestrut{%d}' % nextcell.cell_id) else: # use \multicolumn for wide multirow cell - self.body.append('\\multicolumn{%d}{l|}' - '{\\sphinxtablestrut{%d}}' % + self.body.append(r'\multicolumn{%d}{l|}{\sphinxtablestrut{%d}}' % (nextcell.width, nextcell.cell_id)) def visit_acks(self, node: Element) -> None: @@ -1057,13 +1051,13 @@ def visit_acks(self, node: Element) -> None: def visit_bullet_list(self, node: Element) -> None: if not self.compact_list: - self.body.append('\\begin{itemize}' + CR) + self.body.append(r'\begin{itemize}' + CR) if self.table: self.table.has_problematic = True def depart_bullet_list(self, node: Element) -> None: if not self.compact_list: - self.body.append('\\end{itemize}' + CR) + self.body.append(r'\end{itemize}' + CR) def visit_enumerated_list(self, node: Element) -> None: def get_enumtype(node: Element) -> str: @@ -1088,16 +1082,16 @@ def get_nested_level(node: Element) -> int: prefix = node.get('prefix', '') suffix = node.get('suffix', '.') - self.body.append('\\begin{enumerate}' + CR) - self.body.append('\\sphinxsetlistlabels{%s}{%s}{%s}{%s}{%s}%%' % + self.body.append(r'\begin{enumerate}' + CR) + self.body.append(r'\sphinxsetlistlabels{%s}{%s}{%s}{%s}{%s}%%' % (style, enum, enumnext, prefix, suffix) + CR) if 'start' in node: - self.body.append('\\setcounter{%s}{%d}' % (enum, node['start'] - 1) + CR) + self.body.append(r'\setcounter{%s}{%d}' % (enum, node['start'] - 1) + CR) if self.table: self.table.has_problematic = True def depart_enumerated_list(self, node: Element) -> None: - self.body.append('\\end{enumerate}' + CR) + self.body.append(r'\end{enumerate}' + CR) def visit_list_item(self, node: Element) -> None: # Append "{}" in case the next character is "[", which would break @@ -1108,12 +1102,12 @@ def depart_list_item(self, node: Element) -> None: self.body.append(CR) def visit_definition_list(self, node: Element) -> None: - self.body.append('\\begin{description}' + CR) + self.body.append(r'\begin{description}' + CR) if self.table: self.table.has_problematic = True def depart_definition_list(self, node: Element) -> None: - self.body.append('\\end{description}' + CR) + self.body.append(r'\end{description}' + CR) def visit_definition_list_item(self, node: Element) -> None: pass @@ -1125,11 +1119,11 @@ def visit_term(self, node: Element) -> None: self.in_term += 1 ctx = '' if node.get('ids'): - ctx = '\\phantomsection' + ctx = r'\phantomsection' for node_id in node['ids']: ctx += self.hypertarget(node_id, anchor=False) - ctx += '}] \\leavevmode' - self.body.append('\\item[{') + ctx += r'}] \leavevmode' + self.body.append(r'\item[{') self.context.append(ctx) def depart_term(self, node: Element) -> None: @@ -1149,12 +1143,12 @@ def depart_definition(self, node: Element) -> None: self.body.append(CR) def visit_field_list(self, node: Element) -> None: - self.body.append('\\begin{quote}\\begin{description}' + CR) + self.body.append(r'\begin{quote}\begin{description}' + CR) if self.table: self.table.has_problematic = True def depart_field_list(self, node: Element) -> None: - self.body.append('\\end{description}\\end{quote}' + CR) + self.body.append(r'\end{description}\end{quote}' + CR) def visit_field(self, node: Element) -> None: pass @@ -1174,7 +1168,7 @@ def visit_paragraph(self, node: Element) -> None: not isinstance(node.parent[index - 1], nodes.paragraph) and not isinstance(node.parent[index - 1], nodes.compound)): # insert blank line, if the paragraph follows a non-paragraph node in a compound - self.body.append('\\noindent' + CR) + self.body.append(r'\noindent' + CR) elif index == 1 and isinstance(node.parent, (nodes.footnote, footnotetext)): # don't insert blank line, if the paragraph is second child of a footnote # (first one is label node) @@ -1183,33 +1177,33 @@ def visit_paragraph(self, node: Element) -> None: # the \sphinxAtStartPar is to allow hyphenation of first word of # a paragraph in narrow contexts such as in a table cell # added as two items (cf. line trimming in depart_entry()) - self.body.extend([CR, '\\sphinxAtStartPar' + CR]) + self.body.extend([CR, r'\sphinxAtStartPar' + CR]) def depart_paragraph(self, node: Element) -> None: self.body.append(CR) def visit_centered(self, node: Element) -> None: - self.body.append(CR + '\\begin{center}') + self.body.append(CR + r'\begin{center}') if self.table: self.table.has_problematic = True def depart_centered(self, node: Element) -> None: - self.body.append(CR + '\\end{center}') + self.body.append(CR + r'\end{center}') def visit_hlist(self, node: Element) -> None: self.compact_list += 1 ncolumns = node['ncolumns'] if self.compact_list > 1: - self.body.append('\\setlength{\\multicolsep}{0pt}' + CR) - self.body.append('\\begin{multicols}{' + ncolumns + '}\\raggedright' + CR) - self.body.append('\\begin{itemize}\\setlength{\\itemsep}{0pt}' - '\\setlength{\\parskip}{0pt}' + CR) + self.body.append(r'\setlength{\multicolsep}{0pt}' + CR) + self.body.append(r'\begin{multicols}{' + ncolumns + '}\raggedright' + CR) + self.body.append(r'\begin{itemize}\setlength{\itemsep}{0pt}' + r'\setlength{\parskip}{0pt}' + CR) if self.table: self.table.has_problematic = True def depart_hlist(self, node: Element) -> None: self.compact_list -= 1 - self.body.append('\\end{itemize}\\raggedcolumns\\end{multicols}' + CR) + self.body.append(r'\end{itemize}\raggedcolumns\end{multicols}' + CR) def visit_hlistcol(self, node: Element) -> None: pass @@ -1219,7 +1213,7 @@ def depart_hlistcol(self, node: Element) -> None: # some testing with long items showed that columns may be too uneven. # And in case only of short items, the automatic column breaks should # match the ones pre-computed by the hlist() directive. - # self.body.append('\\columnbreak\n') + # self.body.append(r'\columnbreak\n') pass def latex_image_length(self, width_str: str, scale: int = 100) -> str: @@ -1267,15 +1261,14 @@ def visit_image(self, node: Element) -> None: align_prepost = { # By default latex aligns the top of an image. (1, 'top'): ('', ''), - (1, 'middle'): ('\\raisebox{-0.5\\height}{', '}'), - (1, 'bottom'): ('\\raisebox{-\\height}{', '}'), - (0, 'center'): ('{\\hspace*{\\fill}', '\\hspace*{\\fill}}'), - (0, 'default'): ('{\\hspace*{\\fill}', '\\hspace*{\\fill}}'), + (1, 'middle'): (r'\raisebox{-0.5\height}{', '}'), + (1, 'bottom'): (r'\raisebox{-\height}{', '}'), + (0, 'center'): (r'{\hspace*{\fill}', r'\hspace*{\fill}}'), # These 2 don't exactly do the right thing. The image should # be floated alongside the paragraph. See # https://www.w3.org/TR/html4/struct/objects.html#adef-align-IMG - (0, 'left'): ('{', '\\hspace*{\\fill}}'), - (0, 'right'): ('{\\hspace*{\\fill}', '}'), + (0, 'left'): ('{', r'\hspace*{\fill}}'), + (0, 'right'): (r'{\hspace*{\fill}', '}'), } try: pre.append(align_prepost[is_inline, node['align']][0]) @@ -1283,10 +1276,10 @@ def visit_image(self, node: Element) -> None: except KeyError: pass if self.in_parsed_literal: - pre.append('{\\sphinxunactivateextrasandspace ') + pre.append(r'{\sphinxunactivateextrasandspace ') post.append('}') if not is_inline and not has_hyperlink: - pre.append(CR + '\\noindent') + pre.append(CR + r'\noindent') post.append(CR) pre.reverse() if node['uri'] in self.builder.images: @@ -1307,10 +1300,10 @@ def visit_image(self, node: Element) -> None: if self.in_title and base: # Lowercase tokens forcely because some fncychap themes capitalize # the options of \sphinxincludegraphics unexpectly (ex. WIDTH=...). - self.body.append('\\lowercase{\\sphinxincludegraphics%s}{{%s}%s}' % + self.body.append(r'\lowercase{\sphinxincludegraphics%s}{{%s}%s}' % (options, base, ext)) else: - self.body.append('\\sphinxincludegraphics%s{{%s}%s}' % + self.body.append(r'\sphinxincludegraphics%s{{%s}%s}' % (options, base, ext)) self.body.extend(post) @@ -1326,14 +1319,14 @@ def visit_figure(self, node: Element) -> None: if 'width' in node: length = self.latex_image_length(node['width']) if length: - self.body.append('\\begin{sphinxfigure-in-table}[%s]' % length + CR) - self.body.append('\\centering' + CR) + self.body.append(r'\begin{sphinxfigure-in-table}[%s]' % length + CR) + self.body.append(r'\centering' + CR) else: - self.body.append('\\begin{sphinxfigure-in-table}' + CR) - self.body.append('\\centering' + CR) + self.body.append(r'\begin{sphinxfigure-in-table}' + CR) + self.body.append(r'\centering' + CR) if any(isinstance(child, nodes.caption) for child in node): - self.body.append('\\capstart') - self.context.append('\\end{sphinxfigure-in-table}\\relax' + CR) + self.body.append(r'\capstart') + self.context.append(r'\end{sphinxfigure-in-table}\relax' + CR) elif node.get('align', '') in ('left', 'right'): length = None if 'width' in node: @@ -1342,19 +1335,19 @@ def visit_figure(self, node: Element) -> None: length = self.latex_image_length(node[0]['width']) self.body.append(BLANKLINE) # Insert a blank line to prevent infinite loop # https://github.com/sphinx-doc/sphinx/issues/7059 - self.body.append('\\begin{wrapfigure}{%s}{%s}' % + self.body.append(r'\begin{wrapfigure}{%s}{%s}' % ('r' if node['align'] == 'right' else 'l', length or '0pt') + CR) - self.body.append('\\centering') - self.context.append('\\end{wrapfigure}' + CR) + self.body.append(r'\centering') + self.context.append(r'\end{wrapfigure}' + CR) elif self.in_minipage: - self.body.append(CR + '\\begin{center}') - self.context.append('\\end{center}' + CR) + self.body.append(CR + r'\begin{center}') + self.context.append(r'\end{center}' + CR) else: - self.body.append(CR + '\\begin{figure}[%s]' % align + CR) - self.body.append('\\centering' + CR) + self.body.append(CR + r'\begin{figure}[%s]' % align + CR) + self.body.append(r'\centering' + CR) if any(isinstance(child, nodes.caption) for child in node): - self.body.append('\\capstart' + CR) - self.context.append('\\end{figure}' + CR) + self.body.append(r'\capstart' + CR) + self.context.append(r'\end{figure}' + CR) def depart_figure(self, node: Element) -> None: self.body.append(self.context.pop()) @@ -1362,13 +1355,13 @@ def depart_figure(self, node: Element) -> None: def visit_caption(self, node: Element) -> None: self.in_caption += 1 if isinstance(node.parent, captioned_literal_block): - self.body.append('\\sphinxSetupCaptionForVerbatim{') + self.body.append(r'\sphinxSetupCaptionForVerbatim{') elif self.in_minipage and isinstance(node.parent, nodes.figure): - self.body.append('\\captionof{figure}{') + self.body.append(r'\captionof{figure}{') elif self.table and node.parent.tagname == 'figure': - self.body.append('\\sphinxfigcaption{') + self.body.append(r'\sphinxfigcaption{') else: - self.body.append('\\caption{') + self.body.append(r'\caption{') def depart_caption(self, node: Element) -> None: self.body.append('}') @@ -1378,27 +1371,27 @@ def depart_caption(self, node: Element) -> None: self.in_caption -= 1 def visit_legend(self, node: Element) -> None: - self.body.append(CR + '\\begin{sphinxlegend}') + self.body.append(CR + r'\begin{sphinxlegend}') def depart_legend(self, node: Element) -> None: - self.body.append('\\end{sphinxlegend}' + CR) + self.body.append(r'\end{sphinxlegend}' + CR) def visit_admonition(self, node: Element) -> None: - self.body.append(CR + '\\begin{sphinxadmonition}{note}') + self.body.append(CR + r'\begin{sphinxadmonition}{note}') self.no_latex_floats += 1 def depart_admonition(self, node: Element) -> None: - self.body.append('\\end{sphinxadmonition}' + CR) + self.body.append(r'\end{sphinxadmonition}' + CR) self.no_latex_floats -= 1 def _visit_named_admonition(self, node: Element) -> None: label = admonitionlabels[node.tagname] - self.body.append(CR + '\\begin{sphinxadmonition}{%s}{%s:}' % + self.body.append(CR + r'\begin{sphinxadmonition}{%s}{%s:}' % (node.tagname, label)) self.no_latex_floats += 1 def _depart_named_admonition(self, node: Element) -> None: - self.body.append('\\end{sphinxadmonition}' + CR) + self.body.append(r'\end{sphinxadmonition}' + CR) self.no_latex_floats -= 1 visit_attention = _visit_named_admonition @@ -1476,11 +1469,11 @@ def depart_target(self, node: Element) -> None: pass def visit_attribution(self, node: Element) -> None: - self.body.append(CR + '\\begin{flushright}' + CR) + self.body.append(CR + r'\begin{flushright}' + CR) self.body.append('---') def depart_attribution(self, node: Element) -> None: - self.body.append(CR + '\\end{flushright}' + CR) + self.body.append(CR + r'\end{flushright}' + CR) def visit_index(self, node: Element) -> None: def escape(value: str) -> str: @@ -1498,7 +1491,7 @@ def style(string: str) -> str: if match: return match.expand(r'\\spxentry{\1}\\spxextra{\2}') else: - return '\\spxentry{%s}' % string + return r'\spxentry{%s}' % string if not node.get('inline', True): self.body.append(CR) @@ -1545,7 +1538,7 @@ def style(string: str) -> str: except ValueError as err: logger.warning(str(err)) if not node.get('inline', True): - self.body.append('\\ignorespaces ') + self.body.append(r'\ignorespaces ') raise nodes.SkipNode def visit_raw(self, node: Element) -> None: @@ -1605,12 +1598,12 @@ def visit_reference(self, node: Element) -> None: else: if len(node) == 1 and uri == node[0]: if node.get('nolinkurl'): - self.body.append('\\sphinxnolinkurl{%s}' % self.encode_uri(uri)) + self.body.append(r'\sphinxnolinkurl{%s}' % self.encode_uri(uri)) else: - self.body.append('\\sphinxurl{%s}' % self.encode_uri(uri)) + self.body.append(r'\sphinxurl{%s}' % self.encode_uri(uri)) raise nodes.SkipNode else: - self.body.append('\\sphinxhref{%s}{' % self.encode_uri(uri)) + self.body.append(r'\sphinxhref{%s}{' % self.encode_uri(uri)) self.context.append('}') def depart_reference(self, node: Element) -> None: @@ -1624,16 +1617,16 @@ def visit_number_reference(self, node: Element) -> None: else: id = node.get('refuri', '')[1:].replace('#', ':') - title = self.escape(node.get('title', '%s')).replace('\\%s', '%s') - if '\\{name\\}' in title or '\\{number\\}' in title: + title = self.escape(node.get('title', '%s')).replace(r'\%s', '%s') + if r'\{name\}' in title or r'\{number\}' in title: # new style format (cf. "Fig.%{number}") - title = title.replace('\\{name\\}', '{name}').replace('\\{number\\}', '{number}') - text = escape_abbr(title).format(name='\\nameref{%s}' % self.idescape(id), - number='\\ref{%s}' % self.idescape(id)) + title = title.replace(r'\{name\}', '{name}').replace(r'\{number\}', '{number}') + text = escape_abbr(title).format(name=r'\nameref{%s}' % self.idescape(id), + number=r'\ref{%s}' % self.idescape(id)) else: # old style format (cf. "Fig.%{number}") - text = escape_abbr(title) % ('\\ref{%s}' % self.idescape(id)) - hyperref = '\\hyperref[%s]{%s}' % (self.idescape(id), text) + text = escape_abbr(title) % (r'\ref{%s}' % self.idescape(id)) + hyperref = r'\hyperref[%s]{%s}' % (self.idescape(id), text) self.body.append(hyperref) raise nodes.SkipNode @@ -1707,15 +1700,15 @@ def visit_thebibliography(self, node: Element) -> None: # adjust max width of citation labels not to break the layout longest_label = longest_label[:MAX_CITATION_LABEL_LENGTH] - self.body.append(CR + '\\begin{sphinxthebibliography}{%s}' % + self.body.append(CR + r'\begin{sphinxthebibliography}{%s}' % self.encode(longest_label) + CR) def depart_thebibliography(self, node: Element) -> None: - self.body.append('\\end{sphinxthebibliography}' + CR) + self.body.append(r'\end{sphinxthebibliography}' + CR) def visit_citation(self, node: Element) -> None: label = cast(nodes.label, node[0]) - self.body.append('\\bibitem[%s]{%s:%s}' % (self.encode(label.astext()), + self.body.append(r'\bibitem[%s]{%s:%s}' % (self.encode(label.astext()), node['docname'], node['ids'][0])) def depart_citation(self, node: Element) -> None: @@ -1725,7 +1718,7 @@ def visit_citation_reference(self, node: Element) -> None: if self.in_title: pass else: - self.body.append('\\sphinxcite{%s:%s}' % (node['docname'], node['refname'])) + self.body.append(r'\sphinxcite{%s:%s}' % (node['docname'], node['refname'])) raise nodes.SkipNode def depart_citation_reference(self, node: Element) -> None: @@ -1746,7 +1739,7 @@ def visit_footnote_reference(self, node: Element) -> None: raise nodes.SkipNode def visit_footnotemark(self, node: Element) -> None: - self.body.append('\\sphinxfootnotemark[') + self.body.append(r'\sphinxfootnotemark[') def depart_footnotemark(self, node: Element) -> None: self.body.append(']') @@ -1754,15 +1747,15 @@ def depart_footnotemark(self, node: Element) -> None: def visit_footnotetext(self, node: Element) -> None: label = cast(nodes.label, node[0]) self.body.append('%' + CR) - self.body.append('\\begin{footnotetext}[%s]' - '\\phantomsection\\label{\\thesphinxscope.%s}%%' + self.body.append(r'\begin{footnotetext}[%s]' + r'\phantomsection\label{\thesphinxscope.%s}%%' % (label.astext(), label.astext()) + CR) - self.body.append('\\sphinxAtStartFootnote' + CR) + self.body.append(r'\sphinxAtStartFootnote' + CR) def depart_footnotetext(self, node: Element) -> None: # the \ignorespaces in particular for after table header use self.body.append('%' + CR) - self.body.append('\\end{footnotetext}\\ignorespaces ') + self.body.append(r'\end{footnotetext}\ignorespaces ') def visit_captioned_literal_block(self, node: Element) -> None: pass @@ -1774,13 +1767,13 @@ def visit_literal_block(self, node: Element) -> None: if node.rawsource != node.astext(): # most probably a parsed-literal block -- don't highlight self.in_parsed_literal += 1 - self.body.append('\\begin{sphinxalltt}' + CR) + self.body.append(r'\begin{sphinxalltt}' + CR) else: labels = self.hypertarget_to(node) if isinstance(node.parent, captioned_literal_block): labels += self.hypertarget_to(node.parent) if labels and not self.in_footnote: - self.body.append(CR + '\\def\\sphinxLiteralBlockLabel{' + labels + '}') + self.body.append(CR + r'\def\sphinxLiteralBlockLabel{' + labels + '}') lang = node.get('language', 'default') linenos = node.get('linenos', False) @@ -1793,57 +1786,57 @@ def visit_literal_block(self, node: Element) -> None: location=node, **highlight_args ) if self.in_footnote: - self.body.append(CR + '\\sphinxSetupCodeBlockInFootnote') - hlcode = hlcode.replace('\\begin{Verbatim}', - '\\begin{sphinxVerbatim}') + self.body.append(CR + r'\sphinxSetupCodeBlockInFootnote') + hlcode = hlcode.replace(r'\begin{Verbatim}', + r'\begin{sphinxVerbatim}') # if in table raise verbatim flag to avoid "tabulary" environment # and opt for sphinxVerbatimintable to handle caption & long lines elif self.table: self.table.has_problematic = True self.table.has_verbatim = True - hlcode = hlcode.replace('\\begin{Verbatim}', - '\\begin{sphinxVerbatimintable}') + hlcode = hlcode.replace(r'\begin{Verbatim}', + r'\begin{sphinxVerbatimintable}') else: - hlcode = hlcode.replace('\\begin{Verbatim}', - '\\begin{sphinxVerbatim}') + hlcode = hlcode.replace(r'\begin{Verbatim}', + r'\begin{sphinxVerbatim}') # get consistent trailer hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim} if self.table and not self.in_footnote: - hlcode += '\\end{sphinxVerbatimintable}' + hlcode += r'\end{sphinxVerbatimintable}' else: - hlcode += '\\end{sphinxVerbatim}' + hlcode += r'\end{sphinxVerbatim}' hllines = str(highlight_args.get('hl_lines', []))[1:-1] if hllines: - self.body.append(CR + '\\fvset{hllines={, %s,}}%%' % hllines) + self.body.append(CR + r'\fvset{hllines={, %s,}}%%' % hllines) self.body.append(CR + hlcode + CR) if hllines: - self.body.append('\\sphinxresetverbatimhllines' + CR) + self.body.append(r'\sphinxresetverbatimhllines' + CR) raise nodes.SkipNode def depart_literal_block(self, node: Element) -> None: - self.body.append(CR + '\\end{sphinxalltt}' + CR) + self.body.append(CR + r'\end{sphinxalltt}' + CR) self.in_parsed_literal -= 1 visit_doctest_block = visit_literal_block depart_doctest_block = depart_literal_block def visit_line(self, node: Element) -> None: - self.body.append('\\item[] ') + self.body.append(r'\item[] ') def depart_line(self, node: Element) -> None: self.body.append(CR) def visit_line_block(self, node: Element) -> None: if isinstance(node.parent, nodes.line_block): - self.body.append('\\item[]' + CR) - self.body.append('\\begin{DUlineblock}{\\DUlineblockindent}' + CR) + self.body.append(r'\item[]' + CR) + self.body.append(r'\begin{DUlineblock}{\DUlineblockindent}' + CR) else: - self.body.append(CR + '\\begin{DUlineblock}{0em}' + CR) + self.body.append(CR + r'\begin{DUlineblock}{0em}' + CR) if self.table: self.table.has_problematic = True def depart_line_block(self, node: Element) -> None: - self.body.append('\\end{DUlineblock}' + CR) + self.body.append(r'\end{DUlineblock}' + CR) def visit_block_quote(self, node: Element) -> None: # If the block quote contains a single object and that object @@ -1856,7 +1849,7 @@ def visit_block_quote(self, node: Element) -> None: isinstance(child, nodes.enumerated_list): done = 1 if not done: - self.body.append('\\begin{quote}' + CR) + self.body.append(r'\begin{quote}' + CR) if self.table: self.table.has_problematic = True @@ -1868,7 +1861,7 @@ def depart_block_quote(self, node: Element) -> None: isinstance(child, nodes.enumerated_list): done = 1 if not done: - self.body.append('\\end{quote}' + CR) + self.body.append(r'\end{quote}' + CR) # option node handling copied from docutils' latex writer @@ -1889,7 +1882,7 @@ def depart_option_argument(self, node: Element) -> None: pass def visit_option_group(self, node: Element) -> None: - self.body.append('\\item [') + self.body.append(r'\item [') # flag for first option self.context.append(0) @@ -1898,12 +1891,12 @@ def depart_option_group(self, node: Element) -> None: self.body.append('] ') def visit_option_list(self, node: Element) -> None: - self.body.append('\\begin{optionlist}{3cm}' + CR) + self.body.append(r'\begin{optionlist}{3cm}' + CR) if self.table: self.table.has_problematic = True def depart_option_list(self, node: Element) -> None: - self.body.append('\\end{optionlist}' + CR) + self.body.append(r'\end{optionlist}' + CR) def visit_option_list_item(self, node: Element) -> None: pass @@ -1923,13 +1916,13 @@ def depart_description(self, node: Element) -> None: pass def visit_superscript(self, node: Element) -> None: - self.body.append('$^{\\text{') + self.body.append(r'$^{\text{') def depart_superscript(self, node: Element) -> None: self.body.append('}}$') def visit_subscript(self, node: Element) -> None: - self.body.append('$_{\\text{') + self.body.append(r'$_{\text{') def depart_subscript(self, node: Element) -> None: self.body.append('}}$') @@ -1996,7 +1989,7 @@ def encode(self, text: str) -> str: if self.literal_whitespace: # Insert a blank before the newline, to avoid # ! LaTeX Error: There's no line here to end. - text = text.replace(CR, '~\\\\' + CR).replace(' ', '~') + text = text.replace(CR, r'~\\' + CR).replace(' ', '~') return text def encode_uri(self, text: str) -> str: @@ -2004,9 +1997,9 @@ def encode_uri(self, text: str) -> str: # this must be checked against hyperref package exact dealings # mainly, %, #, {, } and \ need escaping via a \ escape # in \href, the tilde is allowed and must be represented literally - return self.encode(text).replace('\\textasciitilde{}', '~').\ - replace('\\sphinxhyphen{}', '-').\ - replace('\\textquotesingle{}', "'") + return self.encode(text).replace(r'\textasciitilde{}', '~').\ + replace(r'\sphinxhyphen{}', '-').\ + replace(r'\textquotesingle{}', "'") def visit_Text(self, node: Text) -> None: text = self.encode(node.astext()) @@ -2071,120 +2064,6 @@ def depart_math_reference(self, node: Element) -> None: def unknown_visit(self, node: Node) -> None: raise NotImplementedError('Unknown node: ' + node.__class__.__name__) - # --------- METHODS FOR COMPATIBILITY -------------------------------------- - - def collect_footnotes(self, node: Element) -> Dict[str, List[Union["collected_footnote", bool]]]: # NOQA - def footnotes_under(n: Element) -> Iterator[nodes.footnote]: - if isinstance(n, nodes.footnote): - yield n - else: - for c in n.children: - if isinstance(c, addnodes.start_of_file): - continue - elif isinstance(c, nodes.Element): - yield from footnotes_under(c) - - warnings.warn('LaTeXWriter.collected_footnote() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - fnotes = {} # type: Dict[str, List[Union[collected_footnote, bool]]] - for fn in footnotes_under(node): - label = cast(nodes.label, fn[0]) - num = label.astext().strip() - newnode = collected_footnote('', *fn.children, number=num) - fnotes[num] = [newnode, False] - return fnotes - - @property - def no_contractions(self) -> int: - warnings.warn('LaTeXTranslator.no_contractions is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - return 0 - - def babel_defmacro(self, name: str, definition: str) -> str: - warnings.warn('babel_defmacro() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - - if self.elements['babel']: - prefix = '\\addto\\extras%s{' % self.babel.get_language() - suffix = '}' - else: # babel is disabled (mainly for Japanese environment) - prefix = '' - suffix = '' - - return ('%s\\def%s{%s}%s' % (prefix, name, definition, suffix) + CR) - - def generate_numfig_format(self, builder: "LaTeXBuilder") -> str: - warnings.warn('generate_numfig_format() is deprecated.', - RemovedInSphinx40Warning, stacklevel=2) - ret = [] # type: List[str] - figure = self.config.numfig_format['figure'].split('%s', 1) - if len(figure) == 1: - ret.append('\\def\\fnum@figure{%s}' % self.escape(figure[0]).strip() + CR) - else: - definition = escape_abbr(self.escape(figure[0])) - ret.append(self.babel_renewcommand('\\figurename', definition)) - ret.append('\\makeatletter' + CR) - ret.append('\\def\\fnum@figure{\\figurename\\thefigure{}%s}' % - self.escape(figure[1]) + CR) - ret.append('\\makeatother' + CR) - - table = self.config.numfig_format['table'].split('%s', 1) - if len(table) == 1: - ret.append('\\def\\fnum@table{%s}' % self.escape(table[0]).strip() + CR) - else: - definition = escape_abbr(self.escape(table[0])) - ret.append(self.babel_renewcommand('\\tablename', definition)) - ret.append('\\makeatletter' + CR) - ret.append('\\def\\fnum@table{\\tablename\\thetable{}%s}' % - self.escape(table[1]) + CR) - ret.append('\\makeatother' + CR) - - codeblock = self.config.numfig_format['code-block'].split('%s', 1) - if len(codeblock) == 1: - pass # FIXME - else: - definition = self.escape(codeblock[0]).strip() - ret.append(self.babel_renewcommand('\\literalblockname', definition)) - if codeblock[1]: - pass # FIXME - - return ''.join(ret) - - -# Import old modules here for compatibility -from sphinx.builders.latex import constants # NOQA -from sphinx.builders.latex.util import ExtBabel # NOQA - -deprecated_alias('sphinx.writers.latex', - { - 'ADDITIONAL_SETTINGS': constants.ADDITIONAL_SETTINGS, - 'DEFAULT_SETTINGS': constants.DEFAULT_SETTINGS, - 'LUALATEX_DEFAULT_FONTPKG': constants.LUALATEX_DEFAULT_FONTPKG, - 'PDFLATEX_DEFAULT_FONTPKG': constants.PDFLATEX_DEFAULT_FONTPKG, - 'SHORTHANDOFF': constants.SHORTHANDOFF, - 'XELATEX_DEFAULT_FONTPKG': constants.XELATEX_DEFAULT_FONTPKG, - 'XELATEX_GREEK_DEFAULT_FONTPKG': constants.XELATEX_GREEK_DEFAULT_FONTPKG, - 'ExtBabel': ExtBabel, - }, - RemovedInSphinx40Warning, - { - 'ADDITIONAL_SETTINGS': - 'sphinx.builders.latex.constants.ADDITIONAL_SETTINGS', - 'DEFAULT_SETTINGS': - 'sphinx.builders.latex.constants.DEFAULT_SETTINGS', - 'LUALATEX_DEFAULT_FONTPKG': - 'sphinx.builders.latex.constants.LUALATEX_DEFAULT_FONTPKG', - 'PDFLATEX_DEFAULT_FONTPKG': - 'sphinx.builders.latex.constants.PDFLATEX_DEFAULT_FONTPKG', - 'SHORTHANDOFF': - 'sphinx.builders.latex.constants.SHORTHANDOFF', - 'XELATEX_DEFAULT_FONTPKG': - 'sphinx.builders.latex.constants.XELATEX_DEFAULT_FONTPKG', - 'XELATEX_GREEK_DEFAULT_FONTPKG': - 'sphinx.builders.latex.constants.XELATEX_GREEK_DEFAULT_FONTPKG', - 'ExtBabel': 'sphinx.builders.latex.util.ExtBabel', - }) # FIXME: Workaround to avoid circular import # refs: https://github.com/sphinx-doc/sphinx/issues/5433 diff --git a/sphinx/writers/manpage.py b/sphinx/writers/manpage.py index 9ef429ba32..917a71b3b0 100644 --- a/sphinx/writers/manpage.py +++ b/sphinx/writers/manpage.py @@ -8,7 +8,6 @@ :license: BSD, see LICENSE for details. """ -import warnings from typing import Any, Dict, Iterable, cast from docutils import nodes @@ -18,7 +17,6 @@ from sphinx import addnodes from sphinx.builders import Builder -from sphinx.deprecation import RemovedInSphinx40Warning from sphinx.locale import _, admonitionlabels from sphinx.util import logging from sphinx.util.docutils import SphinxTranslator @@ -77,14 +75,7 @@ class ManualPageTranslator(SphinxTranslator, BaseTranslator): _docinfo = {} # type: Dict[str, Any] - def __init__(self, *args: Any) -> None: - if isinstance(args[0], nodes.document) and isinstance(args[1], Builder): - document, builder = args - else: - warnings.warn('The order of arguments for ManualPageTranslator has been changed. ' - 'Please give "document" as 1st and "builder" as 2nd.', - RemovedInSphinx40Warning, stacklevel=2) - builder, document = args + def __init__(self, document: nodes.document, builder: Builder) -> None: super().__init__(document, builder) self.in_productionlist = 0 diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py index 6518d10da4..d918742999 100644 --- a/sphinx/writers/texinfo.py +++ b/sphinx/writers/texinfo.py @@ -12,8 +12,8 @@ import textwrap import warnings from os import path -from typing import (Any, Dict, Iterable, Iterator, List, Optional, Pattern, Set, Tuple, Union, - cast) +from typing import (TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, Optional, Pattern, Set, + Tuple, Union, cast) from docutils import nodes, writers from docutils.nodes import Element, Node, Text @@ -29,8 +29,7 @@ from sphinx.util.i18n import format_date from sphinx.writers.latex import collected_footnote -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.builders.texinfo import TexinfoBuilder diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py index c0ebe32a22..274a35d573 100644 --- a/sphinx/writers/text.py +++ b/sphinx/writers/text.py @@ -12,7 +12,8 @@ import re import textwrap from itertools import chain, groupby -from typing import Any, Dict, Generator, Iterable, List, Optional, Set, Tuple, Union, cast +from typing import (TYPE_CHECKING, Any, Dict, Generator, Iterable, List, Optional, Set, Tuple, + Union, cast) from docutils import nodes, writers from docutils.nodes import Element, Node, Text @@ -22,8 +23,7 @@ from sphinx.locale import _, admonitionlabels from sphinx.util.docutils import SphinxTranslator -if False: - # For type annotation +if TYPE_CHECKING: from sphinx.builders.text import TextBuilder diff --git a/tests/roots/test-directive-csv-table/conf.py b/tests/roots/test-directive-csv-table/conf.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/roots/test-directive-csv-table/example.csv b/tests/roots/test-directive-csv-table/example.csv new file mode 100644 index 0000000000..eb039aa9bf --- /dev/null +++ b/tests/roots/test-directive-csv-table/example.csv @@ -0,0 +1 @@ +foo,bar,baz diff --git a/tests/roots/test-directive-csv-table/subdir/example.csv b/tests/roots/test-directive-csv-table/subdir/example.csv new file mode 100644 index 0000000000..32fe56fad5 --- /dev/null +++ b/tests/roots/test-directive-csv-table/subdir/example.csv @@ -0,0 +1 @@ +FOO,BAR,BAZ diff --git a/tests/roots/test-domain-c/anon-dup-decl.rst b/tests/roots/test-domain-c/anon-dup-decl.rst index 5f6c3bdfe3..743ae2f6a8 100644 --- a/tests/roots/test-domain-c/anon-dup-decl.rst +++ b/tests/roots/test-domain-c/anon-dup-decl.rst @@ -1,3 +1,5 @@ +.. c:namespace:: anon_dup_decl_ns + .. c:struct:: anon_dup_decl .. c:struct:: @a.A diff --git a/tests/roots/test-domain-c/function_param_target.rst b/tests/roots/test-domain-c/function_param_target.rst index 05de01445d..d316d7bcd1 100644 --- a/tests/roots/test-domain-c/function_param_target.rst +++ b/tests/roots/test-domain-c/function_param_target.rst @@ -1,3 +1,5 @@ +.. c:namespace:: function_param_target + .. c:function:: void f(int i) - :c:var:`i` diff --git a/tests/roots/test-domain-c/index.rst b/tests/roots/test-domain-c/index.rst index 7e2c18be99..4febd63eff 100644 --- a/tests/roots/test-domain-c/index.rst +++ b/tests/roots/test-domain-c/index.rst @@ -1,3 +1,5 @@ +.. c:namespace:: index + test-domain-c ============= diff --git a/tests/roots/test-domain-c/semicolon.rst b/tests/roots/test-domain-c/semicolon.rst deleted file mode 100644 index 14ba177569..0000000000 --- a/tests/roots/test-domain-c/semicolon.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. c:member:: int member; -.. c:var:: int var; -.. c:function:: void f(); -.. .. c:macro:: NO_SEMICOLON; -.. c:struct:: Struct; -.. c:union:: Union; -.. c:enum:: Enum; -.. c:enumerator:: Enumerator; -.. c:type:: Type; -.. c:type:: int TypeDef; diff --git a/tests/roots/test-domain-py-python_use_unqualified_type_names/conf.py b/tests/roots/test-domain-py-python_use_unqualified_type_names/conf.py new file mode 100644 index 0000000000..c81bfe4c74 --- /dev/null +++ b/tests/roots/test-domain-py-python_use_unqualified_type_names/conf.py @@ -0,0 +1 @@ +python_use_unqualified_type_names = True diff --git a/tests/roots/test-domain-py-python_use_unqualified_type_names/index.rst b/tests/roots/test-domain-py-python_use_unqualified_type_names/index.rst new file mode 100644 index 0000000000..599206d8c7 --- /dev/null +++ b/tests/roots/test-domain-py-python_use_unqualified_type_names/index.rst @@ -0,0 +1,8 @@ +domain-py-smart_reference +========================= + +.. py:class:: Name + :module: foo + + +.. py:function:: hello(name: foo.Name, age: foo.Age) diff --git a/tests/roots/test-ext-autodoc/target/preserve_defaults.py b/tests/roots/test-ext-autodoc/target/preserve_defaults.py new file mode 100644 index 0000000000..c927fa0352 --- /dev/null +++ b/tests/roots/test-ext-autodoc/target/preserve_defaults.py @@ -0,0 +1,19 @@ +from datetime import datetime +from typing import Any + +CONSTANT = 'foo' +SENTINEL = object() + + +def foo(name: str = CONSTANT, + sentinal: Any = SENTINEL, + now: datetime = datetime.now()) -> None: + """docstring""" + + +class Class: + """docstring""" + + def meth(self, name: str = CONSTANT, sentinal: Any = SENTINEL, + now: datetime = datetime.now()) -> None: + """docstring""" diff --git a/tests/roots/test-ext-autodoc/target/typevar.py b/tests/roots/test-ext-autodoc/target/typevar.py index 864fea20ce..c330e2d885 100644 --- a/tests/roots/test-ext-autodoc/target/typevar.py +++ b/tests/roots/test-ext-autodoc/target/typevar.py @@ -17,6 +17,9 @@ #: T6 T6 = NewType("T6", int) +#: T7 +T7 = TypeVar("T7", bound=int) + class Class: #: T1 diff --git a/tests/roots/test-ext-doctest-skipif/conf.py b/tests/roots/test-ext-doctest-skipif/conf.py index c863dbc013..6f5498256d 100644 --- a/tests/roots/test-ext-doctest-skipif/conf.py +++ b/tests/roots/test-ext-doctest-skipif/conf.py @@ -1,7 +1,7 @@ extensions = ['sphinx.ext.doctest'] project = 'test project for the doctest :skipif: directive' -master_doc = 'skipif' +root_doc = 'skipif' source_suffix = '.txt' exclude_patterns = ['_build'] diff --git a/tests/roots/test-ext-doctest/conf.py b/tests/roots/test-ext-doctest/conf.py index fcf6a6cdaf..d0e8b107b2 100644 --- a/tests/roots/test-ext-doctest/conf.py +++ b/tests/roots/test-ext-doctest/conf.py @@ -1,6 +1,6 @@ extensions = ['sphinx.ext.doctest'] project = 'test project for doctest' -master_doc = 'doctest' +root_doc = 'doctest' source_suffix = '.txt' exclude_patterns = ['_build'] diff --git a/tests/roots/test-intl/xx/LC_MESSAGES/figure.po b/tests/roots/test-intl/xx/LC_MESSAGES/figure.po index 449b15e3f3..64bbdf763d 100644 --- a/tests/roots/test-intl/xx/LC_MESSAGES/figure.po +++ b/tests/roots/test-intl/xx/LC_MESSAGES/figure.po @@ -37,19 +37,17 @@ msgstr "BLOCK" msgid "image url and alt" msgstr "IMAGE URL AND ALT" -msgid "" -".. image:: img.png\n" -" :alt: img" -msgstr "" -".. image:: i18n.png\n" -" :alt: IMG -> I18N" +msgid "img" +msgstr "IMG -> I18N" -msgid "" -".. image:: i18n.png\n" -" :alt: i18n" -msgstr "" -".. image:: img.png\n" -" :alt: I18N -> IMG" +msgid ".. image:: img.png" +msgstr ".. image:: i18n.png" + +msgid "i18n" +msgstr "I18N -> IMG" + +msgid ".. image:: i18n.png" +msgstr ".. image:: img.png" msgid "image on substitution" msgstr "IMAGE ON SUBSTITUTION" diff --git a/tests/roots/test-latex-equations/conf.py b/tests/roots/test-latex-equations/conf.py index 0957543e66..d851892ba4 100644 --- a/tests/roots/test-latex-equations/conf.py +++ b/tests/roots/test-latex-equations/conf.py @@ -1,2 +1,2 @@ -master_doc = 'equations' +root_doc = 'equations' extensions = ['sphinx.ext.imgmath'] diff --git a/tests/roots/test-latex-includegraphics/conf.py b/tests/roots/test-latex-includegraphics/conf.py index b53df86a2b..65c19ab859 100644 --- a/tests/roots/test-latex-includegraphics/conf.py +++ b/tests/roots/test-latex-includegraphics/conf.py @@ -1,5 +1,3 @@ -master_doc = 'index' - exclude_patterns = ['_build'] latex_elements = { diff --git a/tests/roots/test-linkcheck/conf.py b/tests/roots/test-linkcheck/conf.py index ae8ef24b7e..ac54f73b02 100644 --- a/tests/roots/test-linkcheck/conf.py +++ b/tests/roots/test-linkcheck/conf.py @@ -1,4 +1,4 @@ -master_doc = 'links' +root_doc = 'links' source_suffix = '.txt' exclude_patterns = ['_build'] linkcheck_anchors = True diff --git a/tests/test_build.py b/tests/test_build.py index 62de3ea5f5..03643c91f6 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -48,12 +48,12 @@ def nonascii_srcdir(request, rootdir, sphinx_test_tempdir): ======================= """)) - master_doc = srcdir / 'index.txt' - master_doc.write_text(master_doc.read_text() + dedent(""" - .. toctree:: + root_doc = srcdir / 'index.txt' + root_doc.write_text(root_doc.read_text() + dedent(""" + .. toctree:: - %(test_name)s/%(test_name)s - """ % {'test_name': test_name})) + %(test_name)s/%(test_name)s + """ % {'test_name': test_name})) return srcdir @@ -71,7 +71,7 @@ def test_build_all(requests_head, make_app, nonascii_srcdir, buildername): app.build() -def test_master_doc_not_found(tempdir, make_app): +def test_root_doc_not_found(tempdir, make_app): (tempdir / 'conf.py').write_text('') assert tempdir.listdir() == ['conf.py'] diff --git a/tests/test_build_epub.py b/tests/test_build_epub.py index 982f4c1b94..c468b093d8 100644 --- a/tests/test_build_epub.py +++ b/tests/test_build_epub.py @@ -15,8 +15,6 @@ import pytest -from sphinx.util import docutils - # check given command is runnable def runnable(command): @@ -355,8 +353,6 @@ def test_epub_css_files(app): 'href="https://example.com/custom.css" />' not in content) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('epub', testroot='roles-download') def test_html_download_role(app, status, warning): app.build() diff --git a/tests/test_build_html.py b/tests/test_build_html.py index ffd32d6f56..fccf9cc6aa 100644 --- a/tests/test_build_html.py +++ b/tests/test_build_html.py @@ -21,7 +21,7 @@ from sphinx.builders.html import validate_html_extra_path, validate_html_static_path from sphinx.errors import ConfigError from sphinx.testing.util import strip_escseq -from sphinx.util import docutils, md5 +from sphinx.util import md5 from sphinx.util.inventory import InventoryFile ENV_WARNINGS = """\ @@ -413,8 +413,6 @@ def test_html4_output(app, status, warning): (".//a[@href='_sources/otherext.foo.txt']", ''), ] })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', tags=['testtag'], confoverrides={'html_context.hckey_co': 'hcval_co'}) @pytest.mark.test_params(shared_result='test_build_html_output') @@ -429,8 +427,6 @@ def test_html_parallel(app): app.build() -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html') @pytest.mark.test_params(shared_result='test_build_html_output') def test_html_download(app): @@ -455,8 +451,6 @@ def test_html_download(app): assert matched.group(1) == filename -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='roles-download') def test_html_download_role(app, status, warning): app.build() @@ -535,8 +529,6 @@ def test_html_translator(app): (".//h1//span[@class='section-number']", '2.1.1. ', True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='tocdepth') @pytest.mark.test_params(shared_result='test_build_html_tocdepth') def test_tocdepth(app, cached_etree_parse, fname, expect): @@ -582,8 +574,6 @@ def test_tocdepth(app, cached_etree_parse, fname, expect): (".//h4//span[@class='section-number']", '2.1.1. ', True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('singlehtml', testroot='tocdepth') @pytest.mark.test_params(shared_result='test_build_html_tocdepth') def test_tocdepth_singlehtml(app, cached_etree_parse, fname, expect): @@ -641,8 +631,6 @@ def test_numfig_disabled_warn(app, warning): "span[@class='caption-number']", None, True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='numfig') @pytest.mark.test_params(shared_result='test_build_html_numfig') def test_numfig_disabled(app, cached_etree_parse, fname, expect): @@ -749,8 +737,6 @@ def test_numfig_without_numbered_toctree_warn(app, warning): "span[@class='caption-number']", '^Listing 6 $', True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx( 'html', testroot='numfig', srcdir='test_numfig_without_numbered_toctree', @@ -857,8 +843,6 @@ def test_numfig_with_numbered_toctree_warn(app, warning): "span[@class='caption-number']", '^Listing 2.2 $', True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='numfig', confoverrides={'numfig': True}) @pytest.mark.test_params(shared_result='test_build_html_numfig_on') def test_numfig_with_numbered_toctree(app, cached_etree_parse, fname, expect): @@ -962,8 +946,6 @@ def test_numfig_with_prefix_warn(app, warning): "span[@class='caption-number']", '^Code-2.2 $', True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='numfig', confoverrides={'numfig': True, 'numfig_format': {'figure': 'Figure:%s', @@ -1068,8 +1050,6 @@ def test_numfig_with_secnum_depth_warn(app, warning): "span[@class='caption-number']", '^Listing 2.1.2 $', True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='numfig', confoverrides={'numfig': True, 'numfig_secnum_depth': 2}) @@ -1153,8 +1133,6 @@ def test_numfig_with_secnum_depth(app, cached_etree_parse, fname, expect): "span[@class='caption-number']", '^Listing 2.2 $', True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('singlehtml', testroot='numfig', confoverrides={'numfig': True}) @pytest.mark.test_params(shared_result='test_build_html_numfig_on') def test_numfig_with_singlehtml(app, cached_etree_parse, fname, expect): @@ -1179,8 +1157,6 @@ def test_numfig_with_singlehtml(app, cached_etree_parse, fname, expect): (".//li/p/a/span", 'No.2', True), ], })) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='add_enumerable_node', srcdir='test_enumerable_node') def test_enumerable_node(app, cached_etree_parse, fname, expect): @@ -1247,7 +1223,7 @@ def test_assets_order(app): content = (app.outdir / 'index.html').read_text() # css_files - expected = ['_static/pygments.css', '_static/alabaster.css', '_static/early.css', + expected = ['_static/early.css', '_static/pygments.css', '_static/alabaster.css', 'https://example.com/custom.css', '_static/normal.css', '_static/late.css', '_static/css/style.css', '_static/lazy.css'] pattern = '.*'.join('href="%s"' % f for f in expected) @@ -1385,8 +1361,8 @@ def test_alternate_stylesheets(app, cached_etree_parse, fname, expect): def test_html_style(app, status, warning): app.build() result = (app.outdir / 'index.html').read_text() - assert '' in result - assert ('' + assert '' in result + assert ('' not in result) diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py index cc79580f65..c8c94b44bd 100644 --- a/tests/test_build_latex.py +++ b/tests/test_build_latex.py @@ -21,7 +21,6 @@ from sphinx.config import Config from sphinx.errors import SphinxError from sphinx.testing.util import strip_escseq -from sphinx.util import docutils from sphinx.util.osutil import cd, ensuredir from sphinx.writers.latex import LaTeXTranslator @@ -198,7 +197,7 @@ def test_latex_basic_manual_ja(app, status, warning): app.builder.build_all() result = (app.outdir / 'test.tex').read_text(encoding='utf8') print(result) - assert r'\def\sphinxdocclass{jsbook}' in result + assert r'\def\sphinxdocclass{ujbook}' in result assert r'\documentclass[letterpaper,10pt,dvipdfmx]{sphinxmanual}' in result @@ -211,7 +210,7 @@ def test_latex_basic_howto_ja(app, status, warning): app.builder.build_all() result = (app.outdir / 'test.tex').read_text(encoding='utf8') print(result) - assert r'\def\sphinxdocclass{jreport}' in result + assert r'\def\sphinxdocclass{ujreport}' in result assert r'\documentclass[letterpaper,10pt,dvipdfmx]{sphinxhowto}' in result @@ -525,7 +524,7 @@ def test_babel_with_no_language_settings(app, status, warning): print(warning.getvalue()) assert '\\documentclass[letterpaper,10pt,english]{sphinxmanual}' in result assert '\\usepackage{babel}' in result - assert '\\usepackage{times}' in result + assert '\\usepackage{tgtermes}' in result assert '\\usepackage[Bjarne]{fncychap}' in result assert ('\\addto\\captionsenglish{\\renewcommand{\\contentsname}{Table of content}}\n' in result) @@ -550,7 +549,7 @@ def test_babel_with_language_de(app, status, warning): print(warning.getvalue()) assert '\\documentclass[letterpaper,10pt,ngerman]{sphinxmanual}' in result assert '\\usepackage{babel}' in result - assert '\\usepackage{times}' in result + assert '\\usepackage{tgtermes}' in result assert '\\usepackage[Sonny]{fncychap}' in result assert ('\\addto\\captionsngerman{\\renewcommand{\\contentsname}{Table of content}}\n' in result) @@ -575,7 +574,7 @@ def test_babel_with_language_ru(app, status, warning): print(warning.getvalue()) assert '\\documentclass[letterpaper,10pt,russian]{sphinxmanual}' in result assert '\\usepackage{babel}' in result - assert '\\usepackage{times}' not in result + assert '\\usepackage{tgtermes}' not in result assert '\\usepackage[Sonny]{fncychap}' in result assert ('\\addto\\captionsrussian{\\renewcommand{\\contentsname}{Table of content}}\n' in result) @@ -600,7 +599,7 @@ def test_babel_with_language_tr(app, status, warning): print(warning.getvalue()) assert '\\documentclass[letterpaper,10pt,turkish]{sphinxmanual}' in result assert '\\usepackage{babel}' in result - assert '\\usepackage{times}' in result + assert '\\usepackage{tgtermes}' in result assert '\\usepackage[Sonny]{fncychap}' in result assert ('\\addto\\captionsturkish{\\renewcommand{\\contentsname}{Table of content}}\n' in result) @@ -625,7 +624,7 @@ def test_babel_with_language_ja(app, status, warning): print(warning.getvalue()) assert '\\documentclass[letterpaper,10pt,dvipdfmx]{sphinxmanual}' in result assert '\\usepackage{babel}' not in result - assert '\\usepackage{times}' in result + assert '\\usepackage{tgtermes}' in result assert '\\usepackage[Sonny]{fncychap}' not in result assert '\\renewcommand{\\contentsname}{Table of content}\n' in result assert '\\shorthandoff' not in result @@ -649,7 +648,7 @@ def test_babel_with_unknown_language(app, status, warning): print(warning.getvalue()) assert '\\documentclass[letterpaper,10pt,english]{sphinxmanual}' in result assert '\\usepackage{babel}' in result - assert '\\usepackage{times}' in result + assert '\\usepackage{tgtermes}' in result assert '\\usepackage[Sonny]{fncychap}' in result assert ('\\addto\\captionsenglish{\\renewcommand{\\contentsname}{Table of content}}\n' in result) @@ -677,7 +676,7 @@ def test_polyglossia_with_language_de(app, status, warning): assert '\\documentclass[letterpaper,10pt,german]{sphinxmanual}' in result assert '\\usepackage{polyglossia}' in result assert '\\setmainlanguage[spelling=new]{german}' in result - assert '\\usepackage{times}' not in result + assert '\\usepackage{tgtermes}' not in result assert '\\usepackage[Sonny]{fncychap}' in result assert ('\\addto\\captionsgerman{\\renewcommand{\\contentsname}{Table of content}}\n' in result) @@ -703,7 +702,7 @@ def test_polyglossia_with_language_de_1901(app, status, warning): assert '\\documentclass[letterpaper,10pt,german]{sphinxmanual}' in result assert '\\usepackage{polyglossia}' in result assert '\\setmainlanguage[spelling=old]{german}' in result - assert '\\usepackage{times}' not in result + assert '\\usepackage{tgtermes}' not in result assert '\\usepackage[Sonny]{fncychap}' in result assert ('\\addto\\captionsgerman{\\renewcommand{\\contentsname}{Table of content}}\n' in result) @@ -1038,7 +1037,7 @@ def test_toctree_maxdepth_howto(app, status, warning): @pytest.mark.sphinx( 'latex', testroot='toctree-maxdepth', - confoverrides={'master_doc': 'foo'}) + confoverrides={'root_doc': 'foo'}) def test_toctree_not_found(app, status, warning): app.builder.build_all() result = (app.outdir / 'python.tex').read_text() @@ -1052,7 +1051,7 @@ def test_toctree_not_found(app, status, warning): @pytest.mark.sphinx( 'latex', testroot='toctree-maxdepth', - confoverrides={'master_doc': 'bar'}) + confoverrides={'root_doc': 'bar'}) def test_toctree_without_maxdepth(app, status, warning): app.builder.build_all() result = (app.outdir / 'python.tex').read_text() @@ -1065,7 +1064,7 @@ def test_toctree_without_maxdepth(app, status, warning): @pytest.mark.sphinx( 'latex', testroot='toctree-maxdepth', - confoverrides={'master_doc': 'qux'}) + confoverrides={'root_doc': 'qux'}) def test_toctree_with_deeper_maxdepth(app, status, warning): app.builder.build_all() result = (app.outdir / 'python.tex').read_text() @@ -1171,8 +1170,6 @@ def test_maxlistdepth_at_ten(app, status, warning): compile_latex_document(app, 'python.tex') -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('latex', testroot='latex-table') @pytest.mark.test_params(shared_result='latex-table') def test_latex_table_tabulars(app, status, warning): @@ -1242,8 +1239,6 @@ def get_expected(name): assert actual == expected -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('latex', testroot='latex-table') @pytest.mark.test_params(shared_result='latex-table') def test_latex_table_longtable(app, status, warning): @@ -1303,8 +1298,6 @@ def get_expected(name): assert actual == expected -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('latex', testroot='latex-table') @pytest.mark.test_params(shared_result='latex-table') def test_latex_table_complex_tables(app, status, warning): @@ -1539,7 +1532,7 @@ def test_latex_figure_in_admonition(app, status, warning): def test_default_latex_documents(): from sphinx.util import texescape texescape.init() - config = Config({'master_doc': 'index', + config = Config({'root_doc': 'index', 'project': 'STASI™ Documentation', 'author': "Wolfgang Schäuble & G'Beckstein."}) config.init_values() diff --git a/tests/test_build_manpage.py b/tests/test_build_manpage.py index a017abc69b..2affb8ba3d 100644 --- a/tests/test_build_manpage.py +++ b/tests/test_build_manpage.py @@ -17,9 +17,9 @@ @pytest.mark.sphinx('man') def test_all(app, status, warning): app.builder.build_all() - assert (app.outdir / 'sphinxtests.1').exists() + assert (app.outdir / '1' / 'sphinxtests.1').exists() - content = (app.outdir / 'sphinxtests.1').read_text() + content = (app.outdir / '1' / 'sphinxtests.1').read_text() assert r'\fBprint \fP\fIi\fP\fB\en\fP' in content assert r'\fBmanpage\en\fP' in content @@ -31,16 +31,16 @@ def test_all(app, status, warning): @pytest.mark.sphinx('man', testroot='basic', - confoverrides={'man_make_section_directory': True}) + confoverrides={'man_make_section_directory': False}) def test_man_make_section_directory(app, status, warning): app.build() - assert (app.outdir / '1' / 'python.1').exists() + assert (app.outdir / 'python.1').exists() @pytest.mark.sphinx('man', testroot='directive-code') def test_captioned_code_block(app, status, warning): app.builder.build_all() - content = (app.outdir / 'python.1').read_text() + content = (app.outdir / '1' / 'python.1').read_text() assert ('.sp\n' 'caption \\fItest\\fP rb\n' @@ -71,5 +71,5 @@ def test_default_man_pages(): @pytest.mark.sphinx('man', testroot='markup-rubric') def test_rubric(app, status, warning): app.build() - content = (app.outdir / 'python.1').read_text() + content = (app.outdir / '1' / 'python.1').read_text() assert 'This is a rubric\n' in content diff --git a/tests/test_config.py b/tests/test_config.py index 9a0b617d5d..a48e7ce30b 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -20,7 +20,7 @@ @pytest.mark.sphinx(testroot='config', confoverrides={ - 'master_doc': 'master', + 'root_doc': 'root', 'nonexisting_value': 'True', 'latex_elements.maketitle': 'blah blah blah', 'modindex_common_prefix': 'path1,path2'}) @@ -33,7 +33,7 @@ def test_core_config(app, status, warning): assert cfg.templates_path == ['_templates'] # overrides - assert cfg.master_doc == 'master' + assert cfg.root_doc == 'root' assert cfg.latex_elements['maketitle'] == 'blah blah blah' assert cfg.modindex_common_prefix == ['path1', 'path2'] @@ -78,11 +78,11 @@ def test_extension_values(): config = Config() # check standard settings - assert config.master_doc == 'index' + assert config.root_doc == 'index' # can't override it by add_config_value() with pytest.raises(ExtensionError) as excinfo: - config.add('master_doc', 'index', 'env', None) + config.add('root_doc', 'index', 'env', None) assert 'already present' in str(excinfo.value) # add a new config value @@ -201,13 +201,13 @@ def test_config_eol(logger, tempdir): assert logger.called is False -@pytest.mark.sphinx(confoverrides={'master_doc': 123, +@pytest.mark.sphinx(confoverrides={'root_doc': 123, 'language': 'foo', 'primary_domain': None}) def test_builtin_conf(app, status, warning): warnings = warning.getvalue() - assert 'master_doc' in warnings, ( - 'override on builtin "master_doc" should raise a type warning') + assert 'root_doc' in warnings, ( + 'override on builtin "root_doc" should raise a type warning') assert 'language' not in warnings, ( 'explicitly permitted override on builtin "language" should NOT raise ' 'a type warning') diff --git a/tests/test_directive_code.py b/tests/test_directive_code.py index ee67b738a5..a011a31e8f 100644 --- a/tests/test_directive_code.py +++ b/tests/test_directive_code.py @@ -9,9 +9,7 @@ """ import os -from distutils.version import LooseVersion -import pygments import pytest from docutils import nodes @@ -423,87 +421,18 @@ def test_literal_include_block_start_with_comment_or_brank(app, status, warning) def test_literal_include_linenos(app, status, warning): app.builder.build(['linenos']) html = (app.outdir / 'linenos.html').read_text() - pygments_version = tuple(LooseVersion(pygments.__version__).version) # :linenos: - if pygments_version >= (2, 8): - assert ('' in html) - else: - assert ('' in html) + assert (' 1' + '# Literally included file using Python highlighting' in html) # :lineno-start: - if pygments_version >= (2, 8): - assert ('' in html) - else: - assert ('' in html) - - # :lineno-match: - if pygments_version >= (2, 8): - assert ('' in html) - else: - assert ('' in html) + assert ('200' + '# Literally included file using Python highlighting' in html) + + # :lines: 5-9 + assert ('5class ' + 'Foo:' in html) @pytest.mark.sphinx('latex', testroot='directive-code') @@ -637,82 +566,17 @@ def test_linenothreshold(app, status, warning): app.builder.build(['linenothreshold']) html = (app.outdir / 'linenothreshold.html').read_text() - pygments_version = tuple(LooseVersion(pygments.__version__).version) - lineos_head = '' - # code-block using linenothreshold - if pygments_version >= (2, 8): - _, matched, html = html.partition(lineos_head + - '1\n' - '2\n' - '3\n' - '4\n' - '5\n' - '6' + lineos_tail) - else: - _, matched, html = html.partition(lineos_head + - '1\n' - '2\n' - '3\n' - '4\n' - '5\n' - '6' + lineos_tail) - assert matched - - # code-block not using linenothreshold - if pygments_version >= (2, 8): - html, matched, _ = html.partition(lineos_head + - '1\n' - '2' + lineos_tail) - else: - html, matched, _ = html.partition(lineos_head + - '1\n' - '2' + lineos_tail) - assert not matched + assert ('1class ' + 'Foo:' in html) + + # code-block not using linenothreshold (no line numbers) + assert '# comment' in html # literal include using linenothreshold - if pygments_version >= (2, 8): - _, matched, html = html.partition(lineos_head + - ' 1\n' - ' 2\n' - ' 3\n' - ' 4\n' - ' 5\n' - ' 6\n' - ' 7\n' - ' 8\n' - ' 9\n' - '10\n' - '11\n' - '12\n' - '13' + lineos_tail) - else: - _, matched, html = html.partition(lineos_head + - ' 1\n' - ' 2\n' - ' 3\n' - ' 4\n' - ' 5\n' - ' 6\n' - ' 7\n' - ' 8\n' - ' 9\n' - '10\n' - '11\n' - '12\n' - '13' + lineos_tail) - assert matched - - # literal include not using linenothreshold - if pygments_version >= (2, 8): - html, matched, _ = html.partition(lineos_head + - '1\n' - '2\n' - '3' + lineos_tail) - else: - html, matched, _ = html.partition(lineos_head + - '1\n' - '2\n' - '3' + lineos_tail) - assert not matched + assert (' 1' + '# Literally included file using Python highlighting' in html) + + # literal include not using linenothreshold (no line numbers) + assert ('# Very small literal include ' + '(linenothreshold check)' in html) diff --git a/tests/test_directive_patch.py b/tests/test_directive_patch.py index 7dc568b1d5..b28e0f1e57 100644 --- a/tests/test_directive_patch.py +++ b/tests/test_directive_patch.py @@ -8,6 +8,7 @@ :license: BSD, see LICENSE for details. """ +import pytest from docutils import nodes from sphinx.testing import restructuredtext @@ -54,6 +55,37 @@ def test_code_directive(app): assert_node(doctree[0], language="python", linenos=True, highlight_args={'linenostart': 5}) +@pytest.mark.sphinx(testroot='directive-csv-table') +def test_csv_table_directive(app): + # relative path from current document + text = ('.. csv-table::\n' + ' :file: example.csv\n') + doctree = restructuredtext.parse(app, text, docname="subdir/index") + assert_node(doctree, + ([nodes.table, nodes.tgroup, (nodes.colspec, + nodes.colspec, + nodes.colspec, + [nodes.tbody, nodes.row])],)) + assert_node(doctree[0][0][3][0], + ([nodes.entry, nodes.paragraph, "FOO"], + [nodes.entry, nodes.paragraph, "BAR"], + [nodes.entry, nodes.paragraph, "BAZ"])) + + # absolute path from source directory + text = ('.. csv-table::\n' + ' :file: /example.csv\n') + doctree = restructuredtext.parse(app, text, docname="subdir/index") + assert_node(doctree, + ([nodes.table, nodes.tgroup, (nodes.colspec, + nodes.colspec, + nodes.colspec, + [nodes.tbody, nodes.row])],)) + assert_node(doctree[0][0][3][0], + ([nodes.entry, nodes.paragraph, "foo"], + [nodes.entry, nodes.paragraph, "bar"], + [nodes.entry, nodes.paragraph, "baz"])) + + def test_math_directive(app): # normal case text = '.. math:: E = mc^2' diff --git a/tests/test_domain_c.py b/tests/test_domain_c.py index 2cfcf74faf..ef4858786d 100644 --- a/tests/test_domain_c.py +++ b/tests/test_domain_c.py @@ -417,6 +417,12 @@ def test_function_definitions(): check('function', 'void f(int arr[const static volatile 42])', {1: 'f'}, output='void f(int arr[static volatile const 42])') + with pytest.raises(DefinitionError): + parse('function', 'void f(int for)') + + # from #8960 + check('function', 'void f(void (*p)(int, double), int i)', {1: 'f'}) + def test_nested_name(): check('struct', '{key}.A', {1: "A"}) @@ -523,8 +529,15 @@ def test_attributes(): # raise DefinitionError("") +def split_warnigns(warning): + ws = warning.getvalue().split("\n") + assert len(ws) >= 1 + assert ws[-1] == "" + return ws[:-1] + + def filter_warnings(warning, file): - lines = warning.getvalue().split("\n") + lines = split_warnigns(warning) res = [l for l in lines if "domain-c" in l and "{}.rst".format(file) in l and "WARNING: document isn't included in any toctree" not in l] print("Filtered warnings for file '{}':".format(file)) @@ -578,10 +591,22 @@ def test_build_domain_c_anon_dup_decl(app, status, warning): assert "WARNING: c:identifier reference target not found: @b" in ws[1] -@pytest.mark.sphinx(testroot='domain-c', confoverrides={'nitpicky': True}) -def test_build_domain_c_semicolon(app, status, warning): - app.builder.build_all() - ws = filter_warnings(warning, "semicolon") +@pytest.mark.sphinx(confoverrides={'nitpicky': True}) +def test_build_domain_c_semicolon(app, warning): + text = """ +.. c:member:: int member; +.. c:var:: int var; +.. c:function:: void f(); +.. .. c:macro:: NO_SEMICOLON; +.. c:struct:: Struct; +.. c:union:: Union; +.. c:enum:: Enum; +.. c:enumerator:: Enumerator; +.. c:type:: Type; +.. c:type:: int TypeDef; +""" + restructuredtext.parse(app, text) + ws = split_warnigns(warning) assert len(ws) == 0 @@ -593,8 +618,8 @@ def test_build_function_param_target(app, warning): assert len(ws) == 0 entries = extract_role_links(app, "function_param_target.html") assert entries == [ - ('c.f', 'i', 'i'), - ('c.f', 'f.i', 'f.i'), + ('c.function_param_target.f', 'i', 'i'), + ('c.function_param_target.f', 'f.i', 'f.i'), ] @@ -656,6 +681,8 @@ def test_noindexentry(app): @pytest.mark.sphinx(testroot='domain-c-intersphinx', confoverrides={'nitpicky': True}) def test_intersphinx(tempdir, app, status, warning): + # a splitting of test_ids_vs_tags0 into the primary directives in a remote project, + # and then the references in the test project origSource = """\ .. c:member:: int _member .. c:var:: int _var diff --git a/tests/test_domain_cpp.py b/tests/test_domain_cpp.py index 690093f5c5..edd5ea5bc5 100644 --- a/tests/test_domain_cpp.py +++ b/tests/test_domain_cpp.py @@ -21,7 +21,6 @@ from sphinx.ext.intersphinx import load_mappings, normalize_intersphinx_mapping from sphinx.testing import restructuredtext from sphinx.testing.util import assert_node -from sphinx.util import docutils def parse(name, string): @@ -290,13 +289,16 @@ class Config: exprCheck('5 == 42', 'eqL5EL42E') exprCheck('5 != 42', 'neL5EL42E') exprCheck('5 not_eq 42', 'neL5EL42E') - # ['<=', '>=', '<', '>'] + # ['<=', '>=', '<', '>', '<=>'] exprCheck('5 <= 42', 'leL5EL42E') exprCheck('A <= 42', 'le1AL42E') exprCheck('5 >= 42', 'geL5EL42E') exprCheck('5 < 42', 'ltL5EL42E') exprCheck('A < 42', 'lt1AL42E') exprCheck('5 > 42', 'gtL5EL42E') + exprCheck('A > 42', 'gt1AL42E') + exprCheck('5 <=> 42', 'ssL5EL42E') + exprCheck('A <=> 42', 'ss1AL42E') # ['<<', '>>'] exprCheck('5 << 42', 'lsL5EL42E') exprCheck('A << 42', 'ls1AL42E') @@ -617,6 +619,9 @@ def test_function_definitions(): # from breathe#441 check('function', 'auto MakeThingy() -> Thingy*', {1: 'MakeThingy', 2: '10MakeThingyv'}) + # from #8960 + check('function', 'void f(void (*p)(int, double), int i)', {2: '1fPFvidEi'}) + def test_operators(): check('function', 'void operator new()', {1: "new-operator", 2: "nwv"}) @@ -662,6 +667,7 @@ def test_operators(): check('function', 'void operator>()', {1: "gt-operator", 2: "gtv"}) check('function', 'void operator<=()', {1: "lte-operator", 2: "lev"}) check('function', 'void operator>=()', {1: "gte-operator", 2: "gev"}) + check('function', 'void operator<=>()', {1: None, 2: "ssv"}) check('function', 'void operator!()', {1: "not-operator", 2: "ntv"}) check('function', 'void operator not()', {2: "ntv"}) check('function', 'void operator&&()', {1: "sand-operator", 2: "aav"}) @@ -1081,8 +1087,6 @@ def test_build_domain_cpp_misuse_of_roles(app, status, warning): assert len(ws) == len(warn) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'add_function_parentheses': True}) def test_build_domain_cpp_with_add_function_parentheses_is_True(app, status, warning): app.builder.build_all() @@ -1124,8 +1128,6 @@ def check(spec, text, file): check(s, t, f) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'add_function_parentheses': False}) def test_build_domain_cpp_with_add_function_parentheses_is_False(app, status, warning): app.builder.build_all() diff --git a/tests/test_domain_py.py b/tests/test_domain_py.py index b09021073e..03e865e845 100644 --- a/tests/test_domain_py.py +++ b/tests/test_domain_py.py @@ -214,20 +214,22 @@ def find_obj(modname, prefix, obj_name, obj_type, searchmode=0): assert (find_obj(None, None, 'NONEXISTANT', 'class') == []) assert (find_obj(None, None, 'NestedParentA', 'class') == - [('NestedParentA', ('roles', 'NestedParentA', 'class'))]) + [('NestedParentA', ('roles', 'NestedParentA', 'class', False))]) assert (find_obj(None, None, 'NestedParentA.NestedChildA', 'class') == - [('NestedParentA.NestedChildA', ('roles', 'NestedParentA.NestedChildA', 'class'))]) + [('NestedParentA.NestedChildA', + ('roles', 'NestedParentA.NestedChildA', 'class', False))]) assert (find_obj(None, 'NestedParentA', 'NestedChildA', 'class') == - [('NestedParentA.NestedChildA', ('roles', 'NestedParentA.NestedChildA', 'class'))]) + [('NestedParentA.NestedChildA', + ('roles', 'NestedParentA.NestedChildA', 'class', False))]) assert (find_obj(None, None, 'NestedParentA.NestedChildA.subchild_1', 'meth') == [('NestedParentA.NestedChildA.subchild_1', - ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method'))]) + ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False))]) assert (find_obj(None, 'NestedParentA', 'NestedChildA.subchild_1', 'meth') == [('NestedParentA.NestedChildA.subchild_1', - ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method'))]) + ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False))]) assert (find_obj(None, 'NestedParentA.NestedChildA', 'subchild_1', 'meth') == [('NestedParentA.NestedChildA.subchild_1', - ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method'))]) + ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False))]) def test_get_full_qualified_name(): @@ -557,7 +559,7 @@ def test_pydata(app): [desc_content, ()])])) assert_node(doctree[3][0][2][1], pending_xref, **{"py:module": "example"}) assert 'example.var' in domain.objects - assert domain.objects['example.var'] == ('index', 'example.var', 'data') + assert domain.objects['example.var'] == ('index', 'example.var', 'data', False) def test_pyfunction(app): @@ -587,9 +589,9 @@ def test_pyfunction(app): entries=[('single', 'func2() (in module example)', 'example.func2', '', None)]) assert 'func1' in domain.objects - assert domain.objects['func1'] == ('index', 'func1', 'function') + assert domain.objects['func1'] == ('index', 'func1', 'function', False) assert 'example.func2' in domain.objects - assert domain.objects['example.func2'] == ('index', 'example.func2', 'function') + assert domain.objects['example.func2'] == ('index', 'example.func2', 'function', False) def test_pyclass_options(app): @@ -611,13 +613,13 @@ def test_pyclass_options(app): assert_node(doctree[0], addnodes.index, entries=[('single', 'Class1 (built-in class)', 'Class1', '', None)]) assert 'Class1' in domain.objects - assert domain.objects['Class1'] == ('index', 'Class1', 'class') + assert domain.objects['Class1'] == ('index', 'Class1', 'class', False) # :final: assert_node(doctree[2], addnodes.index, entries=[('single', 'Class2 (built-in class)', 'Class2', '', None)]) assert 'Class2' in domain.objects - assert domain.objects['Class2'] == ('index', 'Class2', 'class') + assert domain.objects['Class2'] == ('index', 'Class2', 'class', False) def test_pymethod_options(app): @@ -663,7 +665,7 @@ def test_pymethod_options(app): [desc_parameterlist, ()])], [desc_content, ()])) assert 'Class.meth1' in domain.objects - assert domain.objects['Class.meth1'] == ('index', 'Class.meth1', 'method') + assert domain.objects['Class.meth1'] == ('index', 'Class.meth1', 'method', False) # :classmethod: assert_node(doctree[1][1][2], addnodes.index, @@ -673,7 +675,7 @@ def test_pymethod_options(app): [desc_parameterlist, ()])], [desc_content, ()])) assert 'Class.meth2' in domain.objects - assert domain.objects['Class.meth2'] == ('index', 'Class.meth2', 'method') + assert domain.objects['Class.meth2'] == ('index', 'Class.meth2', 'method', False) # :staticmethod: assert_node(doctree[1][1][4], addnodes.index, @@ -683,7 +685,7 @@ def test_pymethod_options(app): [desc_parameterlist, ()])], [desc_content, ()])) assert 'Class.meth3' in domain.objects - assert domain.objects['Class.meth3'] == ('index', 'Class.meth3', 'method') + assert domain.objects['Class.meth3'] == ('index', 'Class.meth3', 'method', False) # :async: assert_node(doctree[1][1][6], addnodes.index, @@ -693,7 +695,7 @@ def test_pymethod_options(app): [desc_parameterlist, ()])], [desc_content, ()])) assert 'Class.meth4' in domain.objects - assert domain.objects['Class.meth4'] == ('index', 'Class.meth4', 'method') + assert domain.objects['Class.meth4'] == ('index', 'Class.meth4', 'method', False) # :property: assert_node(doctree[1][1][8], addnodes.index, @@ -702,7 +704,7 @@ def test_pymethod_options(app): [desc_name, "meth5"])], [desc_content, ()])) assert 'Class.meth5' in domain.objects - assert domain.objects['Class.meth5'] == ('index', 'Class.meth5', 'method') + assert domain.objects['Class.meth5'] == ('index', 'Class.meth5', 'method', False) # :abstractmethod: assert_node(doctree[1][1][10], addnodes.index, @@ -712,7 +714,7 @@ def test_pymethod_options(app): [desc_parameterlist, ()])], [desc_content, ()])) assert 'Class.meth6' in domain.objects - assert domain.objects['Class.meth6'] == ('index', 'Class.meth6', 'method') + assert domain.objects['Class.meth6'] == ('index', 'Class.meth6', 'method', False) # :final: assert_node(doctree[1][1][12], addnodes.index, @@ -722,7 +724,7 @@ def test_pymethod_options(app): [desc_parameterlist, ()])], [desc_content, ()])) assert 'Class.meth7' in domain.objects - assert domain.objects['Class.meth7'] == ('index', 'Class.meth7', 'method') + assert domain.objects['Class.meth7'] == ('index', 'Class.meth7', 'method', False) def test_pyclassmethod(app): @@ -743,7 +745,7 @@ def test_pyclassmethod(app): [desc_parameterlist, ()])], [desc_content, ()])) assert 'Class.meth' in domain.objects - assert domain.objects['Class.meth'] == ('index', 'Class.meth', 'method') + assert domain.objects['Class.meth'] == ('index', 'Class.meth', 'method', False) def test_pystaticmethod(app): @@ -764,7 +766,7 @@ def test_pystaticmethod(app): [desc_parameterlist, ()])], [desc_content, ()])) assert 'Class.meth' in domain.objects - assert domain.objects['Class.meth'] == ('index', 'Class.meth', 'method') + assert domain.objects['Class.meth'] == ('index', 'Class.meth', 'method', False) def test_pyattribute(app): @@ -793,7 +795,7 @@ def test_pyattribute(app): assert_node(doctree[1][1][1][0][1][1], pending_xref, **{"py:class": "Class"}) assert_node(doctree[1][1][1][0][1][3], pending_xref, **{"py:class": "Class"}) assert 'Class.attr' in domain.objects - assert domain.objects['Class.attr'] == ('index', 'Class.attr', 'attribute') + assert domain.objects['Class.attr'] == ('index', 'Class.attr', 'attribute', False) def test_pydecorator_signature(app): @@ -808,7 +810,7 @@ def test_pydecorator_signature(app): domain="py", objtype="function", noindex=False) assert 'deco' in domain.objects - assert domain.objects['deco'] == ('index', 'deco', 'function') + assert domain.objects['deco'] == ('index', 'deco', 'function', False) def test_pydecoratormethod_signature(app): @@ -823,7 +825,22 @@ def test_pydecoratormethod_signature(app): domain="py", objtype="method", noindex=False) assert 'deco' in domain.objects - assert domain.objects['deco'] == ('index', 'deco', 'method') + assert domain.objects['deco'] == ('index', 'deco', 'method', False) + + +def test_canonical(app): + text = (".. py:class:: io.StringIO\n" + " :canonical: _io.StringIO") + domain = app.env.get_domain('py') + doctree = restructuredtext.parse(app, text) + assert_node(doctree, (addnodes.index, + [desc, ([desc_signature, ([desc_annotation, "class "], + [desc_addname, "io."], + [desc_name, "StringIO"])], + desc_content)])) + assert 'io.StringIO' in domain.objects + assert domain.objects['io.StringIO'] == ('index', 'io.StringIO', 'class', False) + assert domain.objects['_io.StringIO'] == ('index', 'io.StringIO', 'class', True) def test_info_field_list(app): @@ -873,6 +890,30 @@ def test_info_field_list(app): **{"py:module": "example", "py:class": "Class"}) +def test_info_field_list_var(app): + text = (".. py:class:: Class\n" + "\n" + " :var int attr: blah blah\n") + doctree = restructuredtext.parse(app, text) + + assert_node(doctree, (addnodes.index, + [desc, (desc_signature, + [desc_content, nodes.field_list, nodes.field])])) + assert_node(doctree[1][1][0][0], ([nodes.field_name, "Variables"], + [nodes.field_body, nodes.paragraph])) + + # :var int attr: + assert_node(doctree[1][1][0][0][1][0], + ([addnodes.literal_strong, "attr"], + " (", + [pending_xref, addnodes.literal_emphasis, "int"], + ")", + " -- ", + "blah blah")) + assert_node(doctree[1][1][0][0][1][0][2], pending_xref, + refdomain="py", reftype="class", reftarget="int", **{"py:class": "Class"}) + + @pytest.mark.sphinx(freshenv=True) def test_module_index(app): text = (".. py:module:: docutils\n" @@ -958,6 +999,25 @@ def test_noindexentry(app): assert_node(doctree[2], addnodes.index, entries=[]) +@pytest.mark.sphinx('html', testroot='domain-py-python_use_unqualified_type_names') +def test_python_python_use_unqualified_type_names(app, status, warning): + app.build() + content = (app.outdir / 'index.html').read_text() + assert ('' + 'Name' in content) + assert 'foo.Age' in content + + +@pytest.mark.sphinx('html', testroot='domain-py-python_use_unqualified_type_names', + confoverrides={'python_use_unqualified_type_names': False}) +def test_python_python_use_unqualified_type_names_disabled(app, status, warning): + app.build() + content = (app.outdir / 'index.html').read_text() + assert ('' + 'foo.Name' in content) + assert 'foo.Age' in content + + @pytest.mark.sphinx('dummy', testroot='domain-py-xref-warning') def test_warn_missing_reference(app, status, warning): app.build() diff --git a/tests/test_domain_std.py b/tests/test_domain_std.py index cf32e7964d..9d9e27bd06 100644 --- a/tests/test_domain_std.py +++ b/tests/test_domain_std.py @@ -21,7 +21,6 @@ from sphinx.domains.std import StandardDomain from sphinx.testing import restructuredtext from sphinx.testing.util import assert_node -from sphinx.util import docutils def test_process_doc_handle_figure_caption(): @@ -349,8 +348,6 @@ def test_multiple_cmdoptions(app): assert domain.progoptions[('cmd', '--output')] == ('index', 'cmdoption-cmd-o') -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx(testroot='productionlist') def test_productionlist(app, status, warning): app.builder.build_all() diff --git a/tests/test_environment.py b/tests/test_environment.py index 9791c2d5b2..5d3035ac0c 100644 --- a/tests/test_environment.py +++ b/tests/test_environment.py @@ -35,14 +35,14 @@ def test_config_status(make_app, app_params): assert "0 added, 0 changed, 0 removed" in app2._status.getvalue() # incremental build (config entry changed) - app3 = make_app(*args, confoverrides={'master_doc': 'indexx'}, **kwargs) + app3 = make_app(*args, confoverrides={'root_doc': 'indexx'}, **kwargs) fname = os.path.join(app3.srcdir, 'index.rst') assert os.path.isfile(fname) shutil.move(fname, fname[:-4] + 'x.rst') assert app3.env.config_status == CONFIG_CHANGED app3.build() shutil.move(fname[:-4] + 'x.rst', fname) - assert "[config changed ('master_doc')] 1 added" in app3._status.getvalue() + assert "[config changed ('root_doc')] 1 added" in app3._status.getvalue() # incremental build (extension changed) app4 = make_app(*args, confoverrides={'extensions': ['sphinx.ext.autodoc']}, **kwargs) @@ -85,7 +85,7 @@ def test_object_inventory(app): refs = app.env.domaindata['py']['objects'] assert 'func_without_module' in refs - assert refs['func_without_module'] == ('objects', 'func_without_module', 'function') + assert refs['func_without_module'] == ('objects', 'func_without_module', 'function', False) assert 'func_without_module2' in refs assert 'mod.func_in_module' in refs assert 'mod.Cls' in refs diff --git a/tests/test_ext_autodoc.py b/tests/test_ext_autodoc.py index 42aa3e8082..d9986e9ca5 100644 --- a/tests/test_ext_autodoc.py +++ b/tests/test_ext_autodoc.py @@ -286,7 +286,6 @@ def foo3(self, d='\n'): '(b, c=42, *d, **e)' -@pytest.mark.skipif(sys.version_info < (3, 5), reason='typing is available since python3.5.') @pytest.mark.sphinx('html', testroot='ext-autodoc') def test_autodoc_process_signature_typing_generic(app): actual = do_autodoc(app, 'class', 'target.generic_class.A', {}) @@ -1712,7 +1711,6 @@ def test_partialmethod_undoc_members(app): assert list(actual) == expected -@pytest.mark.skipif(sys.version_info < (3, 6), reason='py36+ is available since python3.6.') @pytest.mark.sphinx('html', testroot='ext-autodoc') def test_autodoc_typed_instance_variables(app): options = {"members": None, @@ -1811,7 +1809,6 @@ def test_autodoc_typed_instance_variables(app): ] -@pytest.mark.skipif(sys.version_info < (3, 6), reason='py36+ is available since python3.6.') @pytest.mark.sphinx('html', testroot='ext-autodoc') def test_autodoc_typed_inherited_instance_variables(app): options = {"members": None, @@ -1996,6 +1993,14 @@ def test_autodoc_TypeVar(app): '', ' alias of :class:`int`', '', + '', + '.. py:data:: T7', + ' :module: target.typevar', + '', + ' T7', + '', + " alias of TypeVar('T7', bound=\\ :class:`int`)", + '', ] @@ -2017,7 +2022,6 @@ def test_autodoc_Annotated(app): ] -@pytest.mark.skipif(sys.version_info < (3, 6), reason='py36+ is required.') @pytest.mark.sphinx('html', testroot='ext-autodoc') def test_autodoc_TYPE_CHECKING(app): options = {"members": None, @@ -2066,26 +2070,19 @@ def test_autodoc_for_egged_code(app): def test_singledispatch(app): options = {"members": None} actual = do_autodoc(app, 'module', 'target.singledispatch', options) - if sys.version_info < (3, 6): - # check the result via "in" because the order of singledispatch signatures is - # usually changed (because dict is not OrderedDict yet!) - assert '.. py:function:: func(arg, kwarg=None)' in actual - assert ' func(arg: int, kwarg=None)' in actual - assert ' func(arg: str, kwarg=None)' in actual - else: - assert list(actual) == [ - '', - '.. py:module:: target.singledispatch', - '', - '', - '.. py:function:: func(arg, kwarg=None)', - ' func(arg: int, kwarg=None)', - ' func(arg: str, kwarg=None)', - ' :module: target.singledispatch', - '', - ' A function for general use.', - '', - ] + assert list(actual) == [ + '', + '.. py:module:: target.singledispatch', + '', + '', + '.. py:function:: func(arg, kwarg=None)', + ' func(arg: int, kwarg=None)', + ' func(arg: str, kwarg=None)', + ' :module: target.singledispatch', + '', + ' A function for general use.', + '', + ] @pytest.mark.skipif(sys.version_info < (3, 8), diff --git a/tests/test_ext_autodoc_autofunction.py b/tests/test_ext_autodoc_autofunction.py index aa04766872..6150918894 100644 --- a/tests/test_ext_autodoc_autofunction.py +++ b/tests/test_ext_autodoc_autofunction.py @@ -9,8 +9,6 @@ :license: BSD, see LICENSE for details. """ -import sys - import pytest from .test_ext_autodoc import do_autodoc @@ -118,23 +116,16 @@ def test_decorated(app): def test_singledispatch(app): options = {} actual = do_autodoc(app, 'function', 'target.singledispatch.func', options) - if sys.version_info < (3, 6): - # check the result via "in" because the order of singledispatch signatures is - # usually changed (because dict is not OrderedDict yet!) - assert '.. py:function:: func(arg, kwarg=None)' in actual - assert ' func(arg: int, kwarg=None)' in actual - assert ' func(arg: str, kwarg=None)' in actual - else: - assert list(actual) == [ - '', - '.. py:function:: func(arg, kwarg=None)', - ' func(arg: int, kwarg=None)', - ' func(arg: str, kwarg=None)', - ' :module: target.singledispatch', - '', - ' A function for general use.', - '', - ] + assert list(actual) == [ + '', + '.. py:function:: func(arg, kwarg=None)', + ' func(arg: int, kwarg=None)', + ' func(arg: str, kwarg=None)', + ' :module: target.singledispatch', + '', + ' A function for general use.', + '', + ] @pytest.mark.sphinx('html', testroot='ext-autodoc') diff --git a/tests/test_ext_autodoc_preserve_defaults.py b/tests/test_ext_autodoc_preserve_defaults.py new file mode 100644 index 0000000000..f9833c2917 --- /dev/null +++ b/tests/test_ext_autodoc_preserve_defaults.py @@ -0,0 +1,45 @@ +""" + test_ext_autodoc_preserve_defaults + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Test the autodoc extension. + + :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import pytest + +from .test_ext_autodoc import do_autodoc + + +@pytest.mark.sphinx('html', testroot='ext-autodoc', + confoverrides={'autodoc_preserve_defaults': True}) +def test_preserve_defaults(app): + options = {"members": None} + actual = do_autodoc(app, 'module', 'target.preserve_defaults', options) + assert list(actual) == [ + '', + '.. py:module:: target.preserve_defaults', + '', + '', + '.. py:class:: Class()', + ' :module: target.preserve_defaults', + '', + ' docstring', + '', + '', + ' .. py:method:: Class.meth(name: str = CONSTANT, sentinal: Any = SENTINEL, ' + 'now: datetime.datetime = datetime.now()) -> None', + ' :module: target.preserve_defaults', + '', + ' docstring', + '', + '', + '.. py:function:: foo(name: str = CONSTANT, sentinal: Any = SENTINEL, now: ' + 'datetime.datetime = datetime.now()) -> None', + ' :module: target.preserve_defaults', + '', + ' docstring', + '', + ] diff --git a/tests/test_ext_autosectionlabel.py b/tests/test_ext_autosectionlabel.py index 0afe13b41d..96f81aacd2 100644 --- a/tests/test_ext_autosectionlabel.py +++ b/tests/test_ext_autosectionlabel.py @@ -12,11 +12,7 @@ import pytest -from sphinx.util import docutils - -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='ext-autosectionlabel') def test_autosectionlabel_html(app, status, warning, skipped_labels=False): app.builder.build_all() @@ -55,15 +51,11 @@ def test_autosectionlabel_html(app, status, warning, skipped_labels=False): # Re-use test definition from above, just change the test root directory -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='ext-autosectionlabel-prefix-document') def test_autosectionlabel_prefix_document_html(app, status, warning): test_autosectionlabel_html(app, status, warning) -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='ext-autosectionlabel', confoverrides={'autosectionlabel_maxdepth': 3}) def test_autosectionlabel_maxdepth(app, status, warning): diff --git a/tests/test_ext_intersphinx.py b/tests/test_ext_intersphinx.py index a876775257..523ed2acc3 100644 --- a/tests/test_ext_intersphinx.py +++ b/tests/test_ext_intersphinx.py @@ -196,6 +196,14 @@ def test_missing_reference_pydomain(tempdir, app, status, warning): rn = missing_reference(app, app.env, node, contnode) assert rn.astext() == 'Foo.bar' + # pending_xref_condition="resolved" + node = addnodes.pending_xref('', reftarget='Foo.bar', refdomain='py', reftype='attr') + node['py:module'] = 'module1' + node += addnodes.pending_xref_condition('', 'Foo.bar', condition='resolved') + node += addnodes.pending_xref_condition('', 'module1.Foo.bar', condition='*') + rn = missing_reference(app, app.env, node, nodes.Text('dummy-cont-node')) + assert rn.astext() == 'Foo.bar' + def test_missing_reference_stddomain(tempdir, app, status, warning): inv_file = tempdir / 'inventory' diff --git a/tests/test_ext_math.py b/tests/test_ext_math.py index 10c8c4866f..bd124c8c62 100644 --- a/tests/test_ext_math.py +++ b/tests/test_ext_math.py @@ -72,8 +72,8 @@ def test_mathjax_options(app, status, warning): content = (app.outdir / 'index.html').read_text() assert ('' in content) + 'src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">' + '' in content) @pytest.mark.sphinx('html', testroot='ext-math', diff --git a/tests/test_ext_napoleon_docstring.py b/tests/test_ext_napoleon_docstring.py index 362e6fb8e4..acf0001784 100644 --- a/tests/test_ext_napoleon_docstring.py +++ b/tests/test_ext_napoleon_docstring.py @@ -1482,12 +1482,18 @@ def test_parameters_with_class_reference(self): ---------- param1 : :class:`MyClass ` instance +Other Parameters +---------------- +param2 : :class:`MyClass ` instance + """ config = Config(napoleon_use_param=False) actual = str(NumpyDocstring(docstring, config)) expected = """\ :Parameters: **param1** (:class:`MyClass ` instance) + +:Other Parameters: **param2** (:class:`MyClass ` instance) """ self.assertEqual(expected, actual) @@ -1496,6 +1502,9 @@ def test_parameters_with_class_reference(self): expected = """\ :param param1: :type param1: :class:`MyClass ` instance + +:param param2: +:type param2: :class:`MyClass ` instance """ self.assertEqual(expected, actual) diff --git a/tests/test_ext_todo.py b/tests/test_ext_todo.py index b6fb2549c0..b4f9690044 100644 --- a/tests/test_ext_todo.py +++ b/tests/test_ext_todo.py @@ -12,11 +12,7 @@ import pytest -from sphinx.util import docutils - -@pytest.mark.skipif(docutils.__version_info__ < (0, 13), - reason='docutils-0.13 or above is required') @pytest.mark.sphinx('html', testroot='ext-todo', freshenv=True, confoverrides={'todo_include_todos': True, 'todo_emit_warnings': True}) def test_todo(app, status, warning): diff --git a/tests/test_intl.py b/tests/test_intl.py index 00f5995954..fa6a41079a 100644 --- a/tests/test_intl.py +++ b/tests/test_intl.py @@ -335,9 +335,9 @@ def test_text_figure_captions(app): "14.2. IMAGE URL AND ALT\n" "=======================\n" "\n" - "[image: i18n][image]\n" + "[image: I18N -> IMG][image]\n" "\n" - " [image: img][image]\n" + " [image: IMG -> I18N][image]\n" "\n" "\n" "14.3. IMAGE ON SUBSTITUTION\n" @@ -1090,12 +1090,12 @@ def test_additional_targets_should_not_be_translated(app): result = (app.outdir / 'figure.html').read_text() - # alt and src for image block should not be translated - expected_expr = """i18n""" + # src for image block should not be translated (alt is translated) + expected_expr = """I18N -> IMG""" assert_count(expected_expr, result, 1) - # alt and src for figure block should not be translated - expected_expr = """img""" + # src for figure block should not be translated (alt is translated) + expected_expr = """IMG -> I18N""" assert_count(expected_expr, result, 1) diff --git a/tests/test_pycode_parser.py b/tests/test_pycode_parser.py index 9169315fc9..e9099178d9 100644 --- a/tests/test_pycode_parser.py +++ b/tests/test_pycode_parser.py @@ -8,10 +8,6 @@ :license: BSD, see LICENSE for details. """ -import sys - -import pytest - from sphinx.pycode.parser import Parser from sphinx.util.inspect import signature_from_str @@ -95,8 +91,7 @@ def test_comment_picker_location(): ('Foo', 'attr3'): 'comment for attr3(3)'} -@pytest.mark.skipif(sys.version_info < (3, 6), reason='tests for py36+ syntax') -def test_annotated_assignment_py36(): +def test_annotated_assignment(): source = ('a: str = "Sphinx" #: comment\n' 'b: int = 1\n' '"""string on next line"""\n' diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index 11086f5f65..94144ef221 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -16,7 +16,6 @@ from sphinx import application from sphinx.cmd import quickstart as qs from sphinx.util.console import coloron, nocolor -from sphinx.util.pycompat import execfile_ warnfile = StringIO() @@ -108,7 +107,7 @@ def test_quickstart_defaults(tempdir): conffile = tempdir / 'conf.py' assert conffile.isfile() ns = {} - execfile_(conffile, ns) + exec(conffile.read_text(), ns) assert ns['extensions'] == [] assert ns['templates_path'] == ['_templates'] assert ns['project'] == 'Sphinx Test' @@ -158,13 +157,13 @@ def test_quickstart_all_answers(tempdir): conffile = tempdir / 'source' / 'conf.py' assert conffile.isfile() ns = {} - execfile_(conffile, ns) + exec(conffile.read_text(), ns) assert ns['extensions'] == [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo' ] assert ns['templates_path'] == ['.templates'] assert ns['source_suffix'] == '.txt' - assert ns['master_doc'] == 'contents' + assert ns['root_doc'] == 'contents' assert ns['project'] == 'STASI™' assert ns['copyright'] == '%s, Wolfgang Schäuble & G\'Beckstein' % \ time.strftime('%Y') @@ -239,7 +238,7 @@ def test_default_filename(tempdir): conffile = tempdir / 'conf.py' assert conffile.isfile() ns = {} - execfile_(conffile, ns) + exec(conffile.read_text(), ns) def test_extensions(tempdir): @@ -249,5 +248,5 @@ def test_extensions(tempdir): conffile = tempdir / 'conf.py' assert conffile.isfile() ns = {} - execfile_(conffile, ns) + exec(conffile.read_text(), ns) assert ns['extensions'] == ['foo', 'bar', 'baz'] diff --git a/tests/test_search.py b/tests/test_search.py index 1ceb6d55b5..dc4f546ca2 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -143,6 +143,7 @@ def test_IndexBuilder(): assert index._titles == {'docname': 'title', 'docname2': 'title2'} assert index._filenames == {'docname': 'filename', 'docname2': 'filename2'} assert index._mapping == { + 'ar': {'docname', 'docname2'}, 'fermion': {'docname', 'docname2'}, 'comment': {'docname', 'docname2'}, 'non': {'docname', 'docname2'}, @@ -161,7 +162,8 @@ def test_IndexBuilder(): 'objects': {'': {'objdispname': (0, 0, 1, '#anchor')}}, 'objnames': {0: ('dummy', 'objtype', 'objtype')}, 'objtypes': {0: 'dummy:objtype'}, - 'terms': {'comment': [0, 1], + 'terms': {'ar': [0, 1], + 'comment': [0, 1], 'fermion': [0, 1], 'index': [0, 1], 'non': [0, 1], @@ -197,6 +199,7 @@ def test_IndexBuilder(): assert index._titles == {'docname2': 'title2'} assert index._filenames == {'docname2': 'filename2'} assert index._mapping == { + 'ar': {'docname2'}, 'fermion': {'docname2'}, 'comment': {'docname2'}, 'non': {'docname2'}, @@ -215,7 +218,8 @@ def test_IndexBuilder(): 'objects': {}, 'objnames': {0: ('dummy', 'objtype', 'objtype')}, 'objtypes': {0: 'dummy:objtype'}, - 'terms': {'comment': 0, + 'terms': {'ar': 0, + 'comment': 0, 'fermion': 0, 'index': 0, 'non': 0, @@ -261,4 +265,4 @@ def test_nosearch(app): assert index['docnames'] == ['index', 'nosearch', 'tocitem'] assert 'latex' not in index['terms'] assert 'zfs' in index['terms'] - assert index['terms']['zfs'] == 0 # zfs on nosearch.rst is not registered to index + assert index['terms']['zfs'] == [] # zfs on nosearch.rst is not registered to index diff --git a/tests/test_setup_command.py b/tests/test_setup_command.py index 52dad14fd4..0561b2fc4f 100644 --- a/tests/test_setup_command.py +++ b/tests/test_setup_command.py @@ -93,12 +93,12 @@ def nonascii_srcdir(request, setup_command): ========================== """)) - master_doc = srcdir / 'index.txt' - master_doc.write_bytes((master_doc.read_text() + dedent(""" - .. toctree:: + root_doc = srcdir / 'index.txt' + root_doc.write_bytes((root_doc.read_text() + dedent(""" + .. toctree:: - %(mb_name)s/%(mb_name)s - """ % locals())).encode()) + %(mb_name)s/%(mb_name)s + """ % locals())).encode()) @pytest.mark.usefixtures('nonascii_srcdir') diff --git a/tests/test_smartquotes.py b/tests/test_smartquotes.py index 0cc0681dc9..a8d4b1ed6a 100644 --- a/tests/test_smartquotes.py +++ b/tests/test_smartquotes.py @@ -10,8 +10,6 @@ import pytest -from sphinx.util import docutils - @pytest.mark.sphinx(buildername='html', testroot='smartquotes', freshenv=True) def test_basic(app, status, warning): @@ -33,7 +31,7 @@ def test_text_builder(app, status, warning): def test_man_builder(app, status, warning): app.build() - content = (app.outdir / 'python.1').read_text() + content = (app.outdir / '1' / 'python.1').read_text() assert '\\-\\- "Sphinx" is a tool that makes it easy ...' in content @@ -63,8 +61,6 @@ def test_smartquotes_disabled(app, status, warning): assert '

-- "Sphinx" is a tool that makes it easy ...

' in content -@pytest.mark.skipif(docutils.__version_info__ < (0, 14), - reason='docutils-0.14 or above is required') @pytest.mark.sphinx(buildername='html', testroot='smartquotes', freshenv=True, confoverrides={'smartquotes_action': 'q'}) def test_smartquotes_action(app, status, warning): @@ -88,5 +84,5 @@ def test_smartquotes_excludes_language(app, status, warning): def test_smartquotes_excludes_builders(app, status, warning): app.build() - content = (app.outdir / 'python.1').read_text() + content = (app.outdir / '1' / 'python.1').read_text() assert '– “Sphinx” is a tool that makes it easy …' in content diff --git a/tests/test_theming.py b/tests/test_theming.py index 0dded07254..be0afe5226 100644 --- a/tests/test_theming.py +++ b/tests/test_theming.py @@ -127,7 +127,7 @@ def test_dark_style(app, status, warning): assert (app.outdir / '_static' / 'pygments_dark.css').exists() result = (app.outdir / 'index.html').read_text() - assert '' in result + assert '' in result assert ('') in result diff --git a/tests/test_util_inspect.py b/tests/test_util_inspect.py index 863f449215..7b86c6ade3 100644 --- a/tests/test_util_inspect.py +++ b/tests/test_util_inspect.py @@ -142,7 +142,13 @@ def test_signature_annotations(): # TypeVars and generic types with TypeVars sig = inspect.signature(f2) - assert stringify_signature(sig) == '(x: List[T], y: List[T_co], z: T) -> List[T_contra]' + if sys.version_info < (3, 7): + assert stringify_signature(sig) == '(x: List[T], y: List[T_co], z: T) -> List[T_contra]' + else: + assert stringify_signature(sig) == ('(x: List[tests.typing_test_data.T],' + ' y: List[tests.typing_test_data.T_co],' + ' z: tests.typing_test_data.T' + ') -> List[tests.typing_test_data.T_contra]') # Union types sig = inspect.signature(f3) @@ -223,10 +229,7 @@ def test_signature_annotations(): # type hints by string sig = inspect.signature(Node.children) - if (3, 5, 0) <= sys.version_info < (3, 5, 3): - assert stringify_signature(sig) == '(self) -> List[Node]' - else: - assert stringify_signature(sig) == '(self) -> List[tests.typing_test_data.Node]' + assert stringify_signature(sig) == '(self) -> List[tests.typing_test_data.Node]' sig = inspect.signature(Node.__init__) assert stringify_signature(sig) == '(self, parent: Optional[tests.typing_test_data.Node]) -> None' diff --git a/tests/test_util_pycompat.py b/tests/test_util_pycompat.py deleted file mode 100644 index 0e395fa7a2..0000000000 --- a/tests/test_util_pycompat.py +++ /dev/null @@ -1,38 +0,0 @@ -""" - test_util_pycompat - ~~~~~~~~~~~~~~~~~~ - - Tests sphinx.util.pycompat functions. - - :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -from sphinx.testing.util import strip_escseq -from sphinx.util import logging -from sphinx.util.pycompat import execfile_ - - -def test_execfile_python2(capsys, app, status, warning, tempdir): - logging.setup(app, status, warning) - - conf_py = tempdir / 'conf.py' - conf_py.write_bytes(b'print "hello"\n') - execfile_(conf_py, {}) - - msg = ( - 'Support for evaluating Python 2 syntax is deprecated ' - 'and will be removed in Sphinx 4.0. ' - 'Convert %s to Python 3 syntax.\n' % conf_py) - assert msg in strip_escseq(warning.getvalue()) - captured = capsys.readouterr() - assert captured.out == 'hello\n' - - -def test_execfile(capsys, tempdir): - conf_py = tempdir / 'conf.py' - conf_py.write_bytes(b'print("hello")\n') - execfile_(conf_py, {}) - - captured = capsys.readouterr() - assert captured.out == 'hello\n' diff --git a/tests/test_util_typing.py b/tests/test_util_typing.py index 927db73fdf..97732965e8 100644 --- a/tests/test_util_typing.py +++ b/tests/test_util_typing.py @@ -194,10 +194,17 @@ def test_stringify_type_hints_typevars(): T_co = TypeVar('T_co', covariant=True) T_contra = TypeVar('T_contra', contravariant=True) - assert stringify(T) == "T" - assert stringify(T_co) == "T_co" - assert stringify(T_contra) == "T_contra" - assert stringify(List[T]) == "List[T]" + if sys.version_info < (3, 7): + assert stringify(T) == "T" + assert stringify(T_co) == "T_co" + assert stringify(T_contra) == "T_contra" + assert stringify(List[T]) == "List[T]" + else: + assert stringify(T) == "tests.test_util_typing.T" + assert stringify(T_co) == "tests.test_util_typing.T_co" + assert stringify(T_contra) == "tests.test_util_typing.T_contra" + assert stringify(List[T]) == "List[tests.test_util_typing.T]" + assert stringify(MyInt) == "MyInt" diff --git a/tox.ini b/tox.ini index 21a0faec3f..bdf4c2ad33 100644 --- a/tox.ini +++ b/tox.ini @@ -1,6 +1,6 @@ [tox] minversion = 2.4.0 -envlist = docs,flake8,mypy,twine,coverage,py{35,36,37,38,39},du{12,13,14,15} +envlist = docs,flake8,mypy,twine,coverage,py{36,37,38,39},du{14,15,16} [testenv] usedevelop = True @@ -14,11 +14,9 @@ passenv = EPUBCHECK_PATH TERM description = - py{35,36,37,38,39}: Run unit tests against {envname}. + py{36,37,38,39}: Run unit tests against {envname}. du{12,13,14}: Run unit tests with the given version of docutils. deps = - du12: docutils==0.12 - du13: docutils==0.13.1 du14: docutils==0.14 du15: docutils==0.15 du16: docutils==0.16
'
-                ' 1\n'
-                ' 2\n'
-                ' 3\n'
-                ' 4\n'
-                ' 5\n'
-                ' 6\n'
-                ' 7\n'
-                ' 8\n'
-                ' 9\n'
-                '10\n'
-                '11\n'
-                '12\n'
-                '13
'
-                ' 1\n'
-                ' 2\n'
-                ' 3\n'
-                ' 4\n'
-                ' 5\n'
-                ' 6\n'
-                ' 7\n'
-                ' 8\n'
-                ' 9\n'
-                '10\n'
-                '11\n'
-                '12\n'
-                '13
'
-                '200\n'
-                '201\n'
-                '202\n'
-                '203\n'
-                '204\n'
-                '205\n'
-                '206\n'
-                '207\n'
-                '208\n'
-                '209\n'
-                '210\n'
-                '211\n'
-                '212
'
-                '200\n'
-                '201\n'
-                '202\n'
-                '203\n'
-                '204\n'
-                '205\n'
-                '206\n'
-                '207\n'
-                '208\n'
-                '209\n'
-                '210\n'
-                '211\n'
-                '212
'
-                '5\n'
-                '6\n'
-                '7\n'
-                '8\n'
-                '9
'
-                '5\n'
-                '6\n'
-                '7\n'
-                '8\n'
-                '9
'
-    lineos_tail = '