Skip to content

Commit

Permalink
Improve docs layout.
Browse files Browse the repository at this point in the history
  • Loading branch information
domdfcoding committed May 17, 2021
1 parent 59dd3fa commit 924d94a
Show file tree
Hide file tree
Showing 12 changed files with 170 additions and 8 deletions.
1 change: 1 addition & 0 deletions doc-source/api/dynamic_quotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
===============================

.. automodule:: formate.dynamic_quotes
:no-autosummary:
1 change: 1 addition & 0 deletions doc-source/api/exceptions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
==========================

.. automodule:: formate.exceptions
:no-autosummary:
9 changes: 8 additions & 1 deletion doc-source/api/imports.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,12 @@
:mod:`formate.imports`
========================

.. raw:: latex

\begin{flushleft}

.. automodule:: formate.imports
:no-autosummary:

.. raw:: latex

\end{flushleft}
136 changes: 136 additions & 0 deletions doc-source/autosummary_widths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Based on https://github.com/sphinx-doc/sphinx/blob/3.x/sphinx/ext/autosummary/__init__.py
#
# Copyright (c) 2007-2021 by the Sphinx team.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

# stdlib
from itertools import chain
from typing import List, Tuple

# 3rd party
from docutils import nodes
from docutils.statemachine import StringList
from domdf_python_tools import stringlist
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.config import Config
from sphinx.ext.autosummary import Autosummary, autosummary_table
from sphinx.util import rst
from sphinx.util.docutils import SphinxDirective, switch_source_input
from sphinx_toolbox import latex


class AutosummaryWidths(Autosummary):

def get_table(self, items: List[Tuple[str, str, str, str]]) -> List[nodes.Node]:
"""
Generate a proper list of table nodes for autosummary:: directive.
:param items: A a list produced by :meth:`~.get_items`.
"""
table_spec = addnodes.tabular_col_spec()
# table_spec['spec'] = r'\Xx{1}{3}\Xx{2}{3}'
# table_spec['spec'] = r'\Xx{3}{8}\Xx{5}{8}'
# table_spec['spec'] = r'\Xx{7}{16}\Xx{9}{16}'

widths = chain.from_iterable(getattr(self.state.document, "autosummary_widths", ((1, 2), (1, 2))))
table_spec["spec"] = r'\Xx{{{}}}{{{}}}\Xx{{{}}}{{{}}}'.format(*widths)

table = autosummary_table('')
real_table = nodes.table('', classes=["longtable"])
table.append(real_table)
group = nodes.tgroup('', cols=2)
real_table.append(group)
group.append(nodes.colspec('', colwidth=10))
group.append(nodes.colspec('', colwidth=90))
body = nodes.tbody('')
group.append(body)

def append_row(*column_texts: str) -> None:
row = nodes.row('')
source, line = self.state_machine.get_source_and_line()
for text in column_texts:
node = nodes.paragraph('')
vl = StringList()
vl.append(text, "%s:%d:<autosummary>" % (source, line))
with switch_source_input(self.state, vl):
self.state.nested_parse(vl, 0, node)
try:
if isinstance(node[0], nodes.paragraph):
node = node[0]
except IndexError:
pass
row.append(nodes.entry('', node))
body.append(row)

for name, sig, summary, real_name in items:
qualifier = "obj"
if "nosignatures" not in self.options:
col1 = ":{}:`{} <{}>`\\ {}".format(qualifier, name, real_name, rst.escape(sig).replace('(', "(​"))
else:
col1 = f":{qualifier}:`{name} <{real_name}>`"
col2 = summary
append_row(col1, col2)

return [table_spec, table]


class WidthsDirective(SphinxDirective):
required_arguments = 2

def run(self):
widths = [arg.split('/') for arg in self.arguments]
self.state.document.autosummary_widths = widths
return []


def configure(app: Sphinx, config: Config):
"""
:param app:
:param config:
"""

latex_elements = getattr(app.config, "latex_elements", {}) # type: ignore

latex_preamble = stringlist.StringList(latex_elements.get("preamble", ''))
latex_preamble.blankline()
latex_preamble.append(r"\makeatletter")
latex_preamble.append(r"\newcolumntype{\Xx}[2]{>{\raggedright\arraybackslash}p{\dimexpr")
latex_preamble.append(r" (\linewidth-\arrayrulewidth)*#1/#2-\tw@\tabcolsep-\arrayrulewidth\relax}}")
latex_preamble.append(r"\makeatother")
latex_preamble.blankline()

latex_elements["preamble"] = str(latex_preamble)
app.config.latex_elements = latex_elements # type: ignore


def setup(app: Sphinx):
app.add_directive("autosummary", AutosummaryWidths, override=True)
app.add_directive("autosummary-widths", WidthsDirective)
app.connect("build-finished", latex.replace_unknown_unicode)
app.connect("config-inited", configure)
3 changes: 2 additions & 1 deletion doc-source/extending.rst
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ Hooks may also accept positional and/or keyword arguments, either named or with
.. clearpage::

Some hooks may require access the the global configuration dict (the ``[config]`` table in ``formate.toml``).
Some hooks may require access the the global configuration dict
(the :ref:`[config] <formate_toml_config>` table in ``formate.toml``).
Hooks can request this by using the :deco:`formate.config.wants_global_config` decorator,
which provides the configuration as the ``formate_global_config`` keyword argument:

Expand Down
10 changes: 9 additions & 1 deletion formate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,12 +215,14 @@ class Reformatter:
:param filename: The filename to reformat.
:param config: The ``formate`` configuration, parsed from a TOML file (or similar).
.. autosummary-widths:: 5/16 11/16
"""

#: The filename being reformatted.
filename: str

#: The filename being reformatted.
#: The filename being reformatted, as a POSIX-style path.
file_to_format: PathPlus

#: The ``formate`` configuration, parsed from a TOML file (or similar).
Expand Down Expand Up @@ -271,6 +273,10 @@ def get_diff(self) -> str:
def to_string(self) -> str:
"""
Return the reformatted file as a string.
:rtype:
.. latex:clearpage::
"""

if self._reformatted_source is None:
Expand All @@ -297,6 +303,8 @@ def reformat_file(
:param filename: The filename to reformat.
:param config: The ``formate`` configuration, parsed from a TOML file (or similar).
:param colour: Whether to force coloured output on (:py:obj:`True`) or off (:py:obj:`False`).
.. latex:clearpage::
"""

r = Reformatter(filename, config)
Expand Down
4 changes: 4 additions & 0 deletions formate/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# classes.py
"""
Core classes.
.. autosummary-widths:: 7/16 9/16
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <[email protected]>
Expand Down Expand Up @@ -82,6 +84,8 @@ class ExpandedHookDict(_BaseExpandedHookDict):
class Hook:
"""
Represents a ``formate`` reformatting hook.
.. autosummary-widths:: 6/16 10/16
"""

#: The name of the hook. The name is normalized into lowercase, with underscores replaced by hyphens.
Expand Down
6 changes: 1 addition & 5 deletions formate/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,11 @@ def wants_filename(func: _C_str) -> _C_str:
Decorator to indicate to ``formate`` that the filename being reformatted should be passed to this hook.
The configuration will be provided as the
``formate_filename``: :class:`~domdf_python_tools.typing.PathLike` keyword argument.
``formate_filename``: :py:obj:`~domdf_python_tools.typing.PathLike` keyword argument.
.. versionadded:: 0.2.0
:param func:
:rtype:
.. clearpage::
"""

func.wants_filename = True # type: ignore
Expand Down
2 changes: 2 additions & 0 deletions formate/reformat_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
Tuple[Union[str, bytes, int, float], ParamsMappingValueType],
None
]
.. autosummary-widths:: 7/16 9/16
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <[email protected]>
Expand Down
4 changes: 4 additions & 0 deletions formate/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# utils.py
"""
Utility functions.
.. autosummary-widths:: 6/16 10/16
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <[email protected]>
Expand Down Expand Up @@ -99,6 +101,8 @@ def name_match_func(name: str) -> bool:
class Rewriter(ast.NodeVisitor):
"""
ABC for rewriting Python source files from an AST and a token stream.
.. autosummary-widths:: 8/16 8/16
"""

#: The original source.
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ extensions = [
"sphinx_click",
"sphinx_toolbox.pre_commit",
"html_section",
"autosummary_widths",
]
sphinxemoji_style = "twemoji"
gitstamp_fmt = "%d %b %Y"
Expand Down
1 change: 1 addition & 0 deletions repo_helper.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ extra_sphinx_extensions:
- sphinx_click
- sphinx_toolbox.pre_commit
- html_section
- autosummary_widths

sphinx_conf_epilogue:
- "\tfrom sphinx_toolbox.latex import replace_unknown_unicode"
Expand Down

0 comments on commit 924d94a

Please sign in to comment.