..
    This file is part of m.css.

    Copyright © 2017, 2018, 2019 Vladimír Vondruš <mosra@centrum.cz>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
..

Python docs
###########

:breadcrumb: {filename}/documentation.rst Doc generators
:summary: A modern, mobile-friendly Sphinx-compatible Python documentation
    generator with a first-class search functionality
:footer:
    .. note-dim::
        :class: m-text-center

        `« Doxygen C++ theme <{filename}/documentation/doxygen.rst>`_ | `Doc generators <{filename}/documentation.rst>`_

.. role:: cpp(code)
    :language: cpp
.. role:: css(code)
    :language: css
.. role:: js(code)
    :language: js
.. role:: py(code)
    :language: py

.. |wink| replace:: 😉

A modern, mobile-friendly Sphinx-compatible Python documentation generator with
a first-class search functionality. Generated by inspecting Python modules and
using either embedded docstrings or external :abbr:`reST <reStructuredText>`
files to populate the documentation.

One of the design goals is providing a similar user experience to the
`Doxygen documentation theme <{filename}doxygen.rst>`_.

.. note-danger:: Heavily experimental

    This functionality is *heavily* experimental at the moment. It's being used
    for the upcoming `Magnum Engine <https://magnum.graphics>`_ Python bindings
    and evolves solely based on that project needs. Note that not everything
    listed below is fully implemented yet --- in particular, the search
    functionality and :abbr:`reST <reStructuredText>` input processing is
    currently not yet implemented.

.. contents::
    :class: m-block m-default

`Basic usage`_
==============

The base is contained in a single Python script and related style/template
files, for advanced features such as math rendering it'll make use of internals
of some `m.css plugins <{filename}/plugins.rst>`_. Clone
:gh:`the m.css GitHub repository <mosra/m.css$master/documentation>` and look
into the ``documentation/`` directory:

.. code:: sh

    git clone git://github.com/mosra/m.css
    cd m.css/documentation

The script requires Python 3.6 and depends on `Jinja2 <http://jinja.pocoo.org/>`_
for templating and docutils for :abbr:`reST <reStructuredText>` markup
rendering. You can install the dependencies via ``pip`` or your distribution
package manager, in most cases you'll probably have them already installed:

.. code:: sh

    # You may need sudo here
    pip3 install docutils jinja2

Next, you need a configuration file which tells the script what modules to
inspect, how to name the project and where to put the output. In this example,
we'll generate documentation for the Python builtin ``math`` module:

.. code:: py

    PROJECT_TITLE = "Python math"
    INPUT_MODULES = ['math']

Now, run the script and pass path to the configuration file to it:

.. code:: sh

    ./python.py path/to/conf.py

This will generate an ``output/`` directory next to the ``conf.py`` file and
fill it with the generated output. Open ``index.html`` to see the result.

`Features`_
===========

-   Theme tailored from scratch for Python-specific language features
-   Uses code inspection to query modules, classes, data, functions and their
    signatures, does not rely on error-prone source code parsing
-   Does not force the documentation writer to explicitly list all symbols in
    order to have them documented
-   Can use both in-code docstrings and external :abbr:`reST <reStructuredText>`
    files to describe the APIs, giving the user a control over the code size vs
    documentation verbosity tradeoff

`Configuration`_
================

Together with the above :py:`PROJECT_TITLE` and :py:`INPUT_MODULES` variables
mentioned above, the configuration file supports the following variables. The
options are similar to the `Doxygen config <{filename}doxygen.rst#configuration>`_,
but free of the Doxygen-specific naming and constraints.

.. class:: m-table m-fullwidth

=================================== ===========================================
Variable                            Description
=================================== ===========================================
:py:`PROJECT_TITLE: str`            Project title. Rendered in top navbar, page
                                    title and fine print. If not set,
                                    :py:`"My Python Project"` is used.
:py:`PROJECT_SUBTITLE: str`         Project subtitle. If set, appended in a
                                    thinner font to :py:`PROJECT_TITLE`.
:py:`MAIN_PROJECT_URL: str`         If set and :py:`PROJECT_SUBTITLE` is also
                                    set, then :py:`PROJECT_TITLE` in the top
                                    navbar will link to this URL and
                                    :py:`PROJECT_SUBTITLE` to the documentation
                                    main page, similarly as
                                    `shown here <{filename}/css/page-layout.rst#link-back-to-main-site-from-a-subsite>`_.
:py:`INPUT_MODULES: List[Any]`      List of modules to generate the docs from.
                                    Values can be either strings or module
                                    objects.
:py:`OUTPUT: str`                   Where to save the output. Relative paths
                                    relative are to the config file base dir;
                                    if not set, ``output/`` is used.
:py:`THEME_COLOR: str`              Color for :html:`<meta name="theme-color" />`,
                                    corresponding to the CSS style. If empty,
                                    no :html:`<meta>` tag is rendered. See
                                    `Theme selection`_ for more information.
:py:`FAVICON: str`                  Favicon URL, used to populate
                                    :html:`<link rel="icon" />`. If empty, no
                                    :html:`<link>` tag is rendered. Relative
                                    paths are searched relative to the config
                                    file base dir and to the ``python.py``
                                    script dir as a fallback. See
                                    `Theme selection`_ for more information.
:py:`STYLESHEETS: List[str]`        List of CSS files to include. Relative
                                    paths are searched relative to the config
                                    file base dir and to the ``python.py``
                                    script dir as a fallback. See `Theme selection`_
                                    for more information.
:py:`HTML_HEADER: str`              HTML code to put at the end of the
                                    :html:`<head>` element. Useful for linking
                                    arbitrary JavaScript code or, for example,
                                    adding :html:`<link>` CSS stylesheets with
                                    additional properties and IDs that are
                                    otherwise not possible with just
                                    :py:`STYLESHEETS`.
:py:`EXTRA_FILES: List[str]`        List of extra files to copy (for example
                                    additional CSS files that are :css:`@import`\ ed
                                    from the primary one). Relative paths are
                                    searched relative to the config file base
                                    dir and to the ``python.py`` script dir as
                                    a fallback.
:py:`LINKS_NAVBAR1: List[Any]`      Left navbar column links. See
                                    `Navbar links`_ for more information.
:py:`LINKS_NAVBAR2: List[Any]`      Right navbar column links. See
                                    `Navbar links`_ for more information.
:py:`PAGE_HEADER: str`              :abbr:`reST <reStructuredText>` markup to
                                    put at the top of every page. If not set,
                                    nothing is added anywhere. The
                                    ``{filename}`` placeholder is replaced with
                                    current file name.
:py:`FINE_PRINT: str`               :abbr:`reST <reStructuredText>` markup to
                                    put into the footer. If not set, a default
                                    generic text is used. If empty, no footer
                                    is rendered at all.
:py:`CLASS_INDEX_EXPAND_LEVELS`     How many levels of the class index tree to
                                    expand. :py:`0` means only the top-level
                                    symbols are shown. If not set, :py:`1` is
                                    used.
:py:`CLASS_INDEX_EXPAND_INNER`      Whether to expand inner classes in the
                                    class index. If not set, :py:`False` is
                                    used.
:py:`PYBIND11_COMPATIBILITY`        Enable some additional tricks for better
                                    compatibility with pybind11. If not set,
                                    :py:`False` is used. See
                                    `pybind11 compatibility`_ for more
                                    information.
:py:`SEARCH_DISABLED: bool`         Disable search functionality. If this
                                    option is set, no search data is compiled
                                    and the rendered HTML does not contain
                                    search-related UI or support. If not set,
                                    :py:`False` is used.
:py:`SEARCH_DOWNLOAD_BINARY: bool`  Download search data as a binary to save
                                    bandwidth and initial processing time. If
                                    not set, :py:`False` is used. See `Search options`_
                                    for more information.
:py:`SEARCH_HELP: str`              :abbr:`reST <reStructuredText>` markup to
                                    display as help text on empty search popup.
                                    If not set, a default message is used. Has
                                    effect only if :py:`SEARCH_DISABLED` is not
                                    :py:`True`.
:py:`SEARCH_BASE_URL: str`          Base URL for OpenSearch-based search engine
                                    suggestions for web browsers. See
                                    `Search options`_ for more information. Has
                                    effect only if :py:`SEARCH_DISABLED` is not
                                    :py:`True`.
:py:`SEARCH_EXTERNAL_URL: str`      URL for external search. The ``{query}``
                                    placeholder is replaced with urlencoded
                                    search string. If not set, no external
                                    search is offered. See `Search options`_
                                    for more information. Has effect only if
                                    :py:`SEARCH_DISABLED` is not :py:`True`.
:py:`DOCUTILS_SETTINGS: Dict[Any]`  Additional docutils settings. Key/value
                                    pairs as described in `the docs <http://docutils.sourceforge.net/docs/user/config.html>`_.
=================================== ===========================================

`Theme selection`_
------------------

By default, the `dark m.css theme <{filename}/css/themes.rst#dark>`_ together
with documentation-theme-specific additions is used, which corresponds to the
following configuration:

.. code:: py

    STYLESHEETS = [
        'https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,600,600i%7CSource+Code+Pro:400,400i,600',
        '../css/m-dark+documentation.compiled.css']
    THEME_COLOR = '#22272e'
    FAVICON = 'favicon-dark.png'

If you have a site already using the ``m-dark.compiled.css`` file, there's
another file called ``m-dark.documentation.compiled.css``, which contains just
the documentation-theme-specific additions so you can reuse the already cached
``m-dark.compiled.css`` file from your main site:

.. code:: ini

    STYLESHEETS = [
        'https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,600,600i%7CSource+Code+Pro:400,400i,600',
        '../css/m-dark.compiled.css',
        '../css/m-dark.documentation.compiled.css']
    THEME_COLOR = '#22272e'
    FAVICON = 'favicon-dark.png'

If you prefer the `light m.css theme <{filename}/css/themes.rst#light>`_
instead, use the following configuration (and, similarly, you can use
``m-light.compiled.css`` together with ``m-light.documentation.compiled-css``
in place of ``m-light+documentation.compiled.css``:

.. code:: ini

    STYLESHEETS = [
        'https://fonts.googleapis.com/css?family=Libre+Baskerville:400,400i,700,700i%7CSource+Code+Pro:400,400i,600',
        '../css/m-light+documentation.compiled.css']
    THEME_COLOR = '#cb4b16'
    FAVICON = 'favicon-light.png'

See the `CSS files`_ section below for more information about customizing the
CSS files.

`Navbar links`_
---------------

The :py:`LINKS_NAVBAR1` and :py:`LINKS_NAVBAR2` options define which links are
shown on the top navbar, split into left and right column on small screen
sizes. These options take a list of :py:`(title, path, sub)` tuples ---
``title`` is the link title, ``path`` is path to a particular page or
module/class (in the form of ``module.sub.ClassName``, for example) and ``sub``
is an optional submenu, containing :py:`(title, path)` tuples. The ``path`` can
be also one of ``pages``, ``modules`` or ``classes``, linking to the page /
module / class index. When rendering, the path is converted to an actual URL to
the destination file.

By default the variables are defined like following --- there's just three
items in the left column, with no submenus and the right column is empty:

.. code:: py

    LINKS_NAVBAR1 = [
        ('Pages', 'pages', []),
        ('Modules', 'modules', []),
        ('Classes', 'classes', [])]
    LINKS_NAVBAR2 = []

A menu item is highlighted if a page with the same path is the current page.
The ``path`` can be also a full URL --- if it contains a scheme prefix (such as
``https://``), then it's taken as-is, without conversion.

`Search options`_
-----------------

Symbol search is implemented using JavaScript Typed Arrays and does not need
any server-side functionality to perform well --- the client automatically
downloads a tightly packed binary containing search data and performs search
directly on it.

However, due to `restrictions of Chromium-based browsers <https://bugs.chromium.org/p/chromium/issues/detail?id=40787&q=ajax%20local&colspec=ID%20Stars%20Pri%20Area%20Feature%20Type%20Status%20Summary%20Modified%20Owner%20Mstone%20OS>`_,
it's not possible to download data using :js:`XMLHttpRequest` when served from
a local file-system. Because of that, the search defaults to producing a
Base85-encoded representation of the search binary and loading that
asynchronously as a plain JavaScript file. This results in the search data
being 25% larger, but since this is for serving from a local filesystem, it's
not considered a problem. If your docs are accessed through a server (or you
don't need Chrome support), enable the :py:`SEARCH_DOWNLOAD_BINARY` option.

The site can provide search engine metadata using the `OpenSearch <http://www.opensearch.org/>`_
specification. On supported browsers this means you can add the search field to
search engines and search directly from the address bar. To enable search
engine metadata, point :py:`M_SEARCH_BASE_URL` to base URL of your
documentation, for example:

.. code:: py

    SEARCH_BASE_URL = 'https://doc.magnum.graphics/magnum/'

In general, even without the above setting, appending ``?q={query}#search`` to
the URL will directly open the search popup with results for ``{query}``.

.. note-info::

    OpenSearch also makes it possible to have autocompletion and search results
    directly in the browser address bar. However that requires a server-side
    search implementation and is not supported at the moment.

If :py:`SEARCH_EXTERNAL_URL` is specified, full-text search using an external
search engine is offered if nothing is found for given string or if the user
has JavaScript disabled. It's recommended to restrict the search to a
particular domain or add additional keywords to the search query to filter out
irrelevant results. Example, using Google search engine and restricting the
search to a subdomain:

.. code:: py

    SEARCH_EXTERNAL_URL = 'https://google.com/search?q=site:doc.magnum.graphics+{query}'

`Content`_
==========

By default, if a module contains the :py:`__all__` attribute, all names listed
there are exposed in the documentation. Otherwise, all module (and class)
members are extracted using :py:`inspect.getmembers()`, skipping names
:py:`import`\ ed from elsewhere and underscored names.

Detecting if a module is a submodule of the current package or if it's
:py:`import`\ ed from elsewhere is tricky, the script thus includes only
submodules that have their :py:`__package__` property the same or one level below
the parent package. If a module's :py:`__package__` is empty, it's assumed to
be a plain module (instead of a package) and since those can't have submodules,
all found submodules in it are ignored.

.. block-success:: Overriding the set of included names

    In case the autodetection includes more than you want or you need to
    include names from other modules as part of the module you need, you can
    temporarily override the :py:`__all__` attribute when generating the docs.
    For example, the following will list just the :py:`pow()` and :py:`log()`
    funtions from the :py:`math` module, ignoring the rest:

    .. code:: py

        import math
        math.__all__ = ['pow', 'log']

        INPUT_MODULES = [math]

`Docstrings`_
-------------

The first paragraph of a module-level, class-level and function-level docstring
is used as a brief documentation, copied as-is to the output without formatting
it in any way.

.. code:: py

    """Module brief docs"""

    class Foo:
        """Class brief docs"""

        def bar(self):
            """Function brief docs"""

.. block-warning:: Limitations

    With the current approach, there are a few limitations:

    -   Everything after the first paragraph is ignored (there's no way to have
        detailed documentation yet)
    -   Class and module-level variables can't have a docstring attached due to
        how Python works
    -   Because not every Python API can be documented using docstrings, the
        output contains everything, including undocumented names

`Function and variable annotations`_
------------------------------------

The script uses :py:`inspect.signature()` to query function parameter / return
type annotations together with default values and displays them in the output.
Similar is for module and class variables, extracted from the
:py:`__annotations__` property. If a variable type implements :py:`__repr__()`,
a :py:`repr()` of it is printed as the value, otherwise the value is omitted.

.. code:: py

    from typing import Tuple, List

    def foo(a: str, be_nice: bool = True) -> Tuple[int, str]:
        pass

    SETTINGS: List[Tuple[str, bool]] = []

For better readability, if the function signature contains type annotations or
a default value, the arguments are printed each on one line. Otherwise, to
avoid wasting vertical space, the arguments are listed on a single line.

Similarly to how the builtin :py:`help()` in Python 3.7 started annotating
boundaries between position-only, position-or-keyword and keyword-only
arguments with ``/`` and ``*``, the same is done here --- it's especially
helpful for native functions, where you can for example call :py:`math.sin(0.3)`
but not :py:`math.sin(x=0.3)`, because the ``x`` argument is positional-only.
Currently, positional-only arguments are possible only with native functions,
`PEP570 <https://www.python.org/dev/peps/pep-0570/>`_ adds them for pure Python
functions as well.

In some cases, especially when documenting native functions, the signature
can't be extracted and the function signature shows just an ellipsis (``…``)
instead of the actual argument list.

`Class methods, static methods, dunder methods, properties`_
------------------------------------------------------------

Methods decorated with :py:`@classmethod` are put into a "Class methods"
section, :py:`@staticmethod`\ s into a "Static methods" section.
Double-underscored methods explicitly implemented in the class are put into a
"Special methods" section, otherwise they're ignored --- by default, Python
adds a large collection of dunder methods to each class and the only way to
know if the method is user-provided or implicit is by checking the docstring.

.. code:: py

    class MyClass:
        @classmethod
        def a_classmethod(cls):
            """A class method"""

        @staticmethod
        def a_staticmethod():
            """A static method"""

        def __init__(self, foo, bar):
            """A constructor"""

Properties added to classes either using the :py:`@property` decorator or
created with the :py:`property()` builtin are added to the "Properties"
section. Each property is annotated with :label-flat-success:`get set del` if
it has a getter, a setter and a :py:`del`\ eter or with :label-flat-warning:`get`
and other variants if it has just some. The docstring and type annotation is
extracted from the property getter.

.. code:: py

    from typing import Tuple

    class MyClass:
        @property
        def a_read_write_property(self) -> Tuple[int, int]:
            """A read-write tuple property"""

        @a_read_write_property.setter
        def a_read_write_property(self, a):
            # Docstring and type annotation taken from the getter, no need to
            # have it repeated here too
            pass

.. block-warning:: Limitations

    Instance variables added inside :py:`__init__()` are not extracted, as this
    would require parsing Python code directly (which is what Sphinx has to do
    to support these).

`Documenting enum values`_
--------------------------

Python supplies an implicit docstrings for enums derived from :py:`enum.Enum`
and enum values implicitly inherit the docstring of the enum class. If either
is detected to be the case, docstring of the enum or the value is ignored.
While it's possible to document enum classes the usual way, there's a
non-obvious way to document enum values as well.

.. code:: py

    import enum

    class MyEnum(enum.Enum):
        """My enum"""

        ZERO = 0
        TWO = 3
        CONSISTENCY = -73

    MyEnum.ZERO.__doc__ = "Zero value"
    MyEnum.TWO.__doc__ = "Three, but named TWO for compatibility"

The documentation output for enums includes enum value values and the class it
was derived from, so it's possible to know whether it's an enum or a flag.

`pybind11 compatibility`_
=========================

C++ bindings generated using `pybind11 <https://pybind11.readthedocs.io/>`_ do
not have all information accessible through introspection and thus the script
has to do a few pybind11-specific workarounds to generate expected output. This
behavior is not enabled by default as it *might* have unwanted consequences in
pure Python code, enable it using the :py:`PYBIND11_COMPATIBILITY` option.

`Function signatures, property annotations`_
--------------------------------------------

For reasons explained in :gh:`pybind/pybind11#990`, pybind11 is not able to
provide function signatures through introspection and thus the script falls
back to parsing argument names, type annotations and default values from the
docstring instead. By default, unless :cpp:`py::arg()` is used, function
arguments are positional-only (shown as :py:`arg0`, :py:`arg1`, ...) and marked
as such in the output.

Similarly, property types are extracted from getter docstrings.

Unlike Python, pybind11 has a builtin support for overloaded functions ---
depending on types passed to a function, it dispatches to a particular C++
overload. The overloads are expanded in the output as well, meaning you can see
one function mentioned more than once with different signatures.

Because static methods in pybind11 are not decorated with :py:`@staticmethod`,
they are detected based on presence of ``self`` as the first parameter --- if
it's there, it's an instance method, otherwise it's a static method.

.. block-warning:: Limitations

    The static / instance method autodetection may fail when you name the first
    argument of a static method as :cpp:`py::arg("self")`. Don't do that |wink|

    The signature parsing can't handle all cases and, especially when templated
    C++ type names leak through, it may fail to extract the argument names. If
    that happens, the function signature shows just an ellipsis (``…``). On the
    other hand, encountering a pure C++ type in a Python function signature
    most probably points to a problem with the bindings as the type can't be
    expressed with Python code.

`Enums`_
--------

Enums in pybind11 are not derived from :py:`enum.Enum`, but rather are plain
classes. The only reliable way to detect a pybind11 enum is by looking for a
``__members__`` member, which is a dict providing string names and their
corresponding values. With pybind 2.2, it's only possible to document the
enum class itself, not the values.

.. note-info::

    pybind 2.3 (not released yet) is scheduled to support docstrings for enum
    values (see :gh:`pybind/pybind11#1160`). Support for this feature is not
    done on the script side yet.

`Command-line options`_
=======================

.. code:: sh

    ./python.py [-h] [--templates TEMPLATES] [--debug] conf

Arguments:

-   ``conf`` --- configuration file

Options:

-   ``-h``, ``--help`` --- show this help message and exit
-   ``--templates TEMPLATES`` --- template directory. Defaults to the
    ``templates/python/`` subdirectory if not set.
-   ``--debug`` --- verbose logging output. Useful for debugging.

`Customizing the template`_
===========================

The rest of the documentation explains how to customize the builtin template to
better suit your needs. Each documentation file is generated from one of the
template files that are bundled with the script. However, it's possible to
provide your own Jinja2 template files for customized experience as well as
modify the CSS styling.

`CSS files`_
------------

By default, compiled CSS files are used to reduce amount of HTTP requests and
bandwidth needed for viewing the documentation. However, for easier
customization and debugging it's better to use the unprocessed stylesheets. The
:py:`STYLESHEETS` option lists all files that go to the
:html:`<link rel="stylesheet" />` in the resulting HTML markup, while
:py:`EXTRA_FILES` list the indirectly referenced files that need to be copied
to the output as well. Below is an example configuration corresponding to the
dark theme:

.. code:: py

    STYLESHEETS = [
        'https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,600,600i%7CSource+Code+Pro:400,400i,600',
        '../css/m-dark.css',
        '../css/m-documentation.css']
    EXTRA_FILES = [
        '../css/m-grid.css',
        '../css/m-components.css',
        '../css/pygments-dark.css',
        '../css/pygments-console.css']
    THEME_COLOR = '#22272e'

After making desired changes to the source files, it's possible to postprocess
them back to the compiled version using the ``postprocess.py`` utility as
explained in the `CSS themes <{filename}/css/themes.rst#make-your-own>`_
documentation. In case of the dark theme, the ``m-dark+documentation.compiled.css``
and ``m-dark.documentation.compiled.css`` files are produced like this:

.. code:: sh

    cd css
    ./postprocess.py m-dark.css m-documentation.css -o m-dark+documentation.compiled.css
    ./postprocess.py m-dark.css m-documentation.css --no-import -o m-dark.documentation.compiled.css

`Module documentation template`_
--------------------------------

Each output file is rendered with one of these templates:

.. class:: m-table m-fullwidth

======================= =======================================================
Filename                Use
======================= =======================================================
``module.html``         Module documentation. See `Module properties`_ for more
                        information.
``class.html``          Class documentation. See `Class properties`_ for more
                        information.
======================= =======================================================

Each template gets passed all configuration values from the `Configuration`_
table as-is, together with a :py:`FILENAME` variable with name of given output
file. In addition to builtin Jinja2 filters, the ``basename_or_url`` filter
returns either a basename of file path, if the path is relative; or a full URL,
if the argument is an absolute URL. It's useful in cases like this:

.. code:: html+jinja

  {% for css in HTML_EXTRA_STYLESHEET %}
  <link rel="stylesheet" href="{{ css|basename_or_url }}" />
  {% endfor %}

The actual page contents are provided in a :py:`page` object, which has the
following properties. All exposed data are meant to be passed directly to the
HTML markup without any additional escaping.

.. class:: m-table m-fullwidth

======================================= =======================================
Property                                Description
======================================= =======================================
:py:`page.brief`                        Brief docs
:py:`page.url`                          File URL
:py:`page.breadcrumb`                   List of :py:`(title, URL)` tuples for
                                        breadcrumb navigation.
======================================= =======================================

Each module page has the following additional properties:

.. class:: m-table m-fullwidth

======================================= =======================================
Property                                Description
======================================= =======================================
:py:`page.prefix_wbr`                   Fully-qualified symbol prefix for given
                                        compound with trailing ``.`` with
                                        :html:`<wbr/>` tag after every ``.``.
:py:`page.modules`                      List of inner modules. See
                                        `Module properties`_ for details.
:py:`page.classes`                      List of classes. See
                                        `Class properties`_ for details.
:py:`page.enums`                        List of enums. See
                                        `Enum properties`_ for details.
:py:`page.functions`                    List of module-level functions. See
                                        `Function properties`_ for details.
:py:`page.data`                         List of module-level data. See
                                        `Data properties`_ for details.
:py:`page.has_enum_details`             If there is at least one enum with full
                                        description block [2]_
======================================= =======================================

Each class page has the following additional properties:

.. class:: m-table m-fullwidth

======================================= =======================================
Property                                Description
======================================= =======================================
:py:`page.prefix_wbr`                   Fully-qualified symbol prefix for given
                                        compound with trailing ``.`` with
                                        :html:`<wbr/>` tag after every ``.``.
:py:`page.classes`                      List of classes. See
                                        `Class properties`_ for details.
:py:`page.enums`                        List of enums. See
                                        `Enum properties`_ for details.
:py:`page.classmethods`                 List of class methods (annotated with
                                        :py:`@classmethod`). See
                                        `Function properties`_ for details.
:py:`page.staticmethods`                List of static methods (annotated with
                                        :py:`@staticmethod`). See
                                        `Function properties`_ for details.
:py:`page.methods`                      List of methods. See
                                        `Function properties`_ for details.
:py:`page.dunder_methods`               List of double-underscored special
                                        functions. See
                                        `Function properties`_ for details.
:py:`page.properties`                   List of properties. See
                                        `Property properties`_ for details.
:py:`page.data`                         List of data. See `Data properties`_
                                        for details.
:py:`page.has_enum_details`             If there is at least one enum with full
                                        description block [2]_
======================================= =======================================

`Module properties`_
````````````````````

.. class:: m-table m-fullwidth

======================================= =======================================
Property                                Description
======================================= =======================================
:py:`module.url`                        URL of detailed module documentation
:py:`module.name`                       Module name
:py:`module.brief`                      Brief docs
======================================= =======================================

`Class properties`_
```````````````````

.. class:: m-table m-fullwidth

======================================= =======================================
Property                                Description
======================================= =======================================
:py:`class_.url`                        URL of detailed class documentation
:py:`class_.name`                       Class name
:py:`class_.brief`                      Brief docs
======================================= =======================================

`Enum properties`_
```````````````````

.. class:: m-table m-fullwidth

======================================= =======================================
Property                                Description
======================================= =======================================
:py:`enum.name`                         Enum name
:py:`enum.brief`                        Brief docs
:py:`enum.base`                         Base class from which the enum is
                                        derived. Set to :py:`None` if no base
                                        class information is available.
:py:`enum.values`                       List of enum values
:py:`enum.has_details`                  If there is enough content for the full
                                        description block. [2]_
:py:`enum.has_value_details`            If the enum values have description.
                                        Impies :py:`enum.has_details`.
======================================= =======================================

Every item of :py:`enum.values` has the following properties:

.. class:: m-table m-fullwidth

=========================== ===================================================
Property                    Description
=========================== ===================================================
:py:`value.name`            Value name
:py:`value.value`           Value value. Set to :py:`None` if no value is
                            available.
:py:`value.brief`           Value brief docs
=========================== ===================================================

`Function properties`_
``````````````````````

.. class:: m-table m-fullwidth

=================================== ===========================================
Property                            Description
=================================== ===========================================
:py:`function.name`                 Function name
:py:`function.brief`                Brief docs
:py:`function.type`                 Function return type annotation [1]_
:py:`function.params`               List of function parameters. See below for
                                    details.
:py:`function.has_complex_params`   Set to :py:`True` if the parameter list
                                    should be wrapped on several lines for
                                    better readability (for example when it
                                    contains type annotations or default
                                    arguments). Set to :py:`False` when
                                    wrapping on multiple lines would only
                                    occupy too much vertical space.
:py:`function.has_details`          If there is enough content for the full
                                    description block. Currently always set to
                                    :py:`False`. [2]_
:py:`function.is_classmethod`       Set to :py:`True` if the function is
                                    annotated with :py:`@classmethod`,
                                    :py:`False` otherwise.
:py:`function.is_staticmethod`      Set to :py:`True` if the function is
                                    annotated with :py:`@staticmethod`,
                                    :py:`False` otherwise.
=================================== ===========================================

The :py:`func.params` is a list of function parameters and their description.
Each item has the following properties:

.. class:: m-table m-fullwidth

=========================== ===================================================
Property                    Description
=========================== ===================================================
:py:`param.name`            Parameter name
:py:`param.type`            Parameter type annotation [1]_
:py:`param.default`         Default parameter value, if any
:py:`param.kind`            Parameter kind, a string equivalent to one of the
                            `inspect.Parameter.kind <https://docs.python.org/3/library/inspect.html#inspect.Parameter.kind>`_
                            values
=========================== ===================================================

In some cases (for example in case of native APIs), the parameters can't be
introspected. In that case, the parameter list is a single entry with ``name``
set to :py:`"..."` and the rest being empty.

`Property properties`_
``````````````````````

.. class:: m-table m-fullwidth

=================================== ===========================================
Property                            Description
=================================== ===========================================
:py:`property.name`                 Property name
:py:`property.type`                 Property getter return type annotation [1]_
:py:`property.brief`                Brief docs
:py:`property.is_writable`          If the property is writable
:py:`property.is_deletable`         If the property is deletable with :py:`del`
:py:`property.has_details`          If there is enough content for the full
                                    description block. Currently always set to
                                    :py:`False`. [2]_
=================================== ===========================================

`Data properties`_
``````````````````

.. class:: m-table m-fullwidth

=================================== ===========================================
Property                            Description
=================================== ===========================================
:py:`data.name`                     Data name
:py:`data.type`                     Data type
:py:`data.brief`                    Brief docs. Currently always empty.
:py:`data.value`                    Data value representation
:py:`data.has_details`              If there is enough content for the full
                                    description block. Currently always set to
                                    :py:`False`. [2]_
=================================== ===========================================

`Index page templates`_
-----------------------

The following index pages are provided, showing a expandable tree of the
contents:

.. class:: m-table m-fullwidth

======================= =======================================================
Filename                Use
======================= =======================================================
``classes.html``        Class listing
``modules.html``        Module listing
``pages.html``          Page listing
======================= =======================================================

Each template is passed all configuration values from the `Configuration`_
table as-is, together with a :py:`FILENAME`, as above. The navigation tree is
provided in an :py:`index` object, which has the following properties:

.. class:: m-table m-fullwidth

=========================== ===================================================
Property                    Description
=========================== ===================================================
:py:`index.classes`         List of all modules + classes
:py:`index.pages`           List of all pages
=========================== ===================================================

The form of each list entry is the same:

.. class:: m-table m-fullwidth

=============================== ===============================================
Property                        Description
=============================== ===============================================
:py:`i.kind`                    Entry kind (one of :py:`'module'`,
                                :py:`'class'` or :py:`'page'`)
:py:`i.name`                    Name
:py:`i.url`                     URL of the file with detailed documentation
:py:`i.brief`                   Brief documentation
:py:`i.has_nestable_children`   If the list has nestable children (i.e., dirs
                                or namespaces)
:py:`i.children`                Recursive list of child entries
=============================== ===============================================

Module/class list is ordered in a way that all modules are before all classes.

-------------------------------

.. [1] :py:`i.type` is extracted out of function annotation. If the types
    aren't annotated, the annotation is empty.
.. [2] :py:`page.has_*_details` and :py:`i.has_details` are :py:`True` if
    there is detailed description, function parameter documentation or
    *documented* enum value listing that makes it worth to render the full
    description block. If :py:`False`, the member should be included only in
    the brief listing on top of the page to avoid unnecessary repetition.
