mirror of
https://github.com/sphinx-doc/sphinx.git
synced 2025-02-25 18:55:22 -06:00
Merge pull request #9470 from lmmx/4.x
Reviewed all docstrings to improve readability and correctness
This commit is contained in:
@@ -197,7 +197,7 @@ class Sphinx:
|
||||
|
||||
# notice for parallel build on macOS and py38+
|
||||
if sys.version_info > (3, 8) and platform.system() == 'Darwin' and parallel > 1:
|
||||
logger.info(bold(__("For security reason, parallel mode is disabled on macOS and "
|
||||
logger.info(bold(__("For security reasons, parallel mode is disabled on macOS and "
|
||||
"python3.8 and above. For more details, please read "
|
||||
"https://github.com/sphinx-doc/sphinx/issues/6803")))
|
||||
|
||||
@@ -415,7 +415,7 @@ class Sphinx:
|
||||
:param event: The name of target event
|
||||
:param callback: Callback function for the event
|
||||
:param priority: The priority of the callback. The callbacks will be invoked
|
||||
in the order of *priority* in asending.
|
||||
in order of *priority* (ascending).
|
||||
:return: A listener ID. It can be used for :meth:`disconnect`.
|
||||
|
||||
.. versionchanged:: 3.0
|
||||
@@ -493,7 +493,7 @@ class Sphinx:
|
||||
values accordingly.
|
||||
|
||||
|
||||
:param name: The name of configuration value. It is recommended to be prefixed
|
||||
:param name: The name of the configuration value. It is recommended to be prefixed
|
||||
with the extension name (ex. ``html_logo``, ``epub_title``)
|
||||
:param default: The default value of the configuration.
|
||||
:param rebuild: The condition of rebuild. It must be one of those values:
|
||||
@@ -539,10 +539,10 @@ class Sphinx:
|
||||
"""Register or override a Docutils translator class.
|
||||
|
||||
This is used to register a custom output translator or to replace a
|
||||
builtin translator. This allows extensions to use custom translator
|
||||
builtin translator. This allows extensions to use a custom translator
|
||||
and define custom nodes for the translator (see :meth:`add_node`).
|
||||
|
||||
:param name: The name of builder for the translator
|
||||
:param name: The name of the builder for the translator
|
||||
:param translator_class: A translator class
|
||||
:param override: If true, install the translator forcedly even if another translator
|
||||
is already installed as the same name
|
||||
@@ -606,11 +606,11 @@ class Sphinx:
|
||||
using :rst:role:`numref`.
|
||||
|
||||
:param node: A node class
|
||||
:param figtype: The type of enumerable nodes. Each figtypes have individual numbering
|
||||
sequences. As a system figtypes, ``figure``, ``table`` and
|
||||
``code-block`` are defined. It is able to add custom nodes to these
|
||||
default figtypes. It is also able to define new custom figtype if new
|
||||
figtype is given.
|
||||
:param figtype: The type of enumerable nodes. Each figtype has individual numbering
|
||||
sequences. As system figtypes, ``figure``, ``table`` and
|
||||
``code-block`` are defined. It is possible to add custom nodes to
|
||||
these default figtypes. It is also possible to define new custom
|
||||
figtype if a new figtype is given.
|
||||
:param title_getter: A getter function to obtain the title of node. It takes an
|
||||
instance of the enumerable node, and it must return its title as
|
||||
string. The title is used to the default title of references for
|
||||
@@ -629,7 +629,7 @@ class Sphinx:
|
||||
def add_directive(self, name: str, cls: Type[Directive], override: bool = False) -> None:
|
||||
"""Register a Docutils directive.
|
||||
|
||||
:param name: The name of directive
|
||||
:param name: The name of the directive
|
||||
:param cls: A directive class
|
||||
:param override: If true, install the directive forcedly even if another directive
|
||||
is already installed as the same name
|
||||
@@ -755,9 +755,9 @@ class Sphinx:
|
||||
Like :meth:`add_role`, but the role is added to the domain named
|
||||
*domain*.
|
||||
|
||||
:param domain: The name of target domain
|
||||
:param name: A name of role
|
||||
:param role: A role function
|
||||
:param domain: The name of the target domain
|
||||
:param name: The name of the role
|
||||
:param role: The role function
|
||||
:param override: If true, install the role forcedly even if another role is already
|
||||
installed as the same name
|
||||
|
||||
@@ -773,8 +773,8 @@ class Sphinx:
|
||||
|
||||
Add a custom *index* class to the domain named *domain*.
|
||||
|
||||
:param domain: The name of target domain
|
||||
:param index: A index class
|
||||
:param domain: The name of the target domain
|
||||
:param index: The index class
|
||||
:param override: If true, install the index forcedly even if another index is
|
||||
already installed as the same name
|
||||
|
||||
@@ -942,8 +942,8 @@ class Sphinx:
|
||||
Add *filename* to the list of JavaScript files that the default HTML
|
||||
template will include in order of *priority* (ascending). The filename
|
||||
must be relative to the HTML static path , or a full URI with scheme.
|
||||
If the priority of JavaScript file is the same as others, the JavaScript
|
||||
files will be included in order of the registration. If the keyword
|
||||
If the priority of the JavaScript file is the same as others, the JavaScript
|
||||
files will be included in order of registration. If the keyword
|
||||
argument ``body`` is given, its value will be added between the
|
||||
``<script>`` tags. Extra keyword arguments are included as attributes of
|
||||
the ``<script>`` tag.
|
||||
@@ -971,7 +971,7 @@ class Sphinx:
|
||||
* - 800
|
||||
- default priority for :confval:`html_js_files`
|
||||
|
||||
A JavaScript file can be added to the specific HTML page when on extension
|
||||
A JavaScript file can be added to the specific HTML page when an extension
|
||||
calls this method on :event:`html-page-context` event.
|
||||
|
||||
.. versionadded:: 0.5
|
||||
@@ -993,8 +993,8 @@ class Sphinx:
|
||||
Add *filename* to the list of CSS files that the default HTML template
|
||||
will include in order of *priority* (ascending). The filename must be
|
||||
relative to the HTML static path, or a full URI with scheme. If the
|
||||
priority of CSS file is the same as others, the CSS files will be
|
||||
included in order of the registration. The keyword arguments are also
|
||||
priority of the CSS file is the same as others, the CSS files will be
|
||||
included in order of registration. The keyword arguments are also
|
||||
accepted for attributes of ``<link>`` tag.
|
||||
|
||||
Example::
|
||||
@@ -1022,15 +1022,15 @@ class Sphinx:
|
||||
* - 800
|
||||
- default priority for :confval:`html_css_files`
|
||||
|
||||
A CSS file can be added to the specific HTML page when on extension calls
|
||||
A CSS file can be added to the specific HTML page when an extension calls
|
||||
this method on :event:`html-page-context` event.
|
||||
|
||||
.. versionadded:: 1.0
|
||||
|
||||
.. versionchanged:: 1.6
|
||||
Optional ``alternate`` and/or ``title`` attributes can be supplied
|
||||
with the *alternate* (of boolean type) and *title* (a string)
|
||||
arguments. The default is no title and *alternate* = ``False``. For
|
||||
with the arguments *alternate* (a Boolean) and *title* (a string).
|
||||
The default is no title and *alternate* = ``False``. For
|
||||
more information, refer to the `documentation
|
||||
<https://mdn.io/Web/CSS/Alternative_style_sheets>`__.
|
||||
|
||||
@@ -1051,7 +1051,7 @@ class Sphinx:
|
||||
r"""Register a package to include in the LaTeX source code.
|
||||
|
||||
Add *packagename* to the list of packages that LaTeX source code will
|
||||
include. If you provide *options*, it will be taken to `\usepackage`
|
||||
include. If you provide *options*, it will be taken to the `\usepackage`
|
||||
declaration. If you set *after_hyperref* truthy, the package will be
|
||||
loaded after ``hyperref`` package.
|
||||
|
||||
@@ -1087,7 +1087,7 @@ class Sphinx:
|
||||
|
||||
Add *cls* as a new documenter class for the :mod:`sphinx.ext.autodoc`
|
||||
extension. It must be a subclass of
|
||||
:class:`sphinx.ext.autodoc.Documenter`. This allows to auto-document
|
||||
:class:`sphinx.ext.autodoc.Documenter`. This allows auto-documenting
|
||||
new types of objects. See the source of the autodoc module for
|
||||
examples on how to subclass :class:`Documenter`.
|
||||
|
||||
@@ -1140,10 +1140,10 @@ class Sphinx:
|
||||
"""Register a suffix of source files.
|
||||
|
||||
Same as :confval:`source_suffix`. The users can override this
|
||||
using the setting.
|
||||
using the config setting.
|
||||
|
||||
If *override* is True, the given *suffix* is forcedly installed even if
|
||||
a same suffix is already installed.
|
||||
the same suffix is already installed.
|
||||
|
||||
.. versionadded:: 1.8
|
||||
"""
|
||||
@@ -1204,8 +1204,8 @@ class Sphinx:
|
||||
def add_message_catalog(self, catalog: str, locale_dir: str) -> None:
|
||||
"""Register a message catalog.
|
||||
|
||||
:param catalog: A name of catalog
|
||||
:param locale_dir: The base path of message catalog
|
||||
:param catalog: The name of the catalog
|
||||
:param locale_dir: The base path of the message catalog
|
||||
|
||||
For more details, see :func:`sphinx.locale.get_translation()`.
|
||||
|
||||
@@ -1216,7 +1216,7 @@ class Sphinx:
|
||||
|
||||
# ---- other methods -------------------------------------------------
|
||||
def is_parallel_allowed(self, typ: str) -> bool:
|
||||
"""Check parallel processing is allowed or not.
|
||||
"""Check whether parallel processing is allowed or not.
|
||||
|
||||
:param typ: A type of processing; ``'read'`` or ``'write'``.
|
||||
"""
|
||||
|
||||
@@ -56,7 +56,7 @@ def is_serializable(obj: Any) -> bool:
|
||||
|
||||
|
||||
class ENUM:
|
||||
"""represents the config value should be a one of candidates.
|
||||
"""Represents the candidates which a config value should be one of.
|
||||
|
||||
Example:
|
||||
app.add_config_value('latex_show_urls', 'no', None, ENUM('no', 'footnote', 'inline'))
|
||||
@@ -215,7 +215,8 @@ class Config:
|
||||
|
||||
def pre_init_values(self) -> None:
|
||||
"""
|
||||
Initialize some limited config variables before initialize i18n and loading extensions
|
||||
Initialize some limited config variables before initializing i18n and loading
|
||||
extensions.
|
||||
"""
|
||||
variables = ['needs_sphinx', 'suppress_warnings', 'language', 'locale_dirs']
|
||||
for name in variables:
|
||||
@@ -343,7 +344,7 @@ def eval_config_file(filename: str, tags: Optional[Tags]) -> Dict[str, Any]:
|
||||
|
||||
|
||||
def convert_source_suffix(app: "Sphinx", config: Config) -> None:
|
||||
"""This converts old styled source_suffix to new styled one.
|
||||
"""Convert old styled source_suffix to new styled one.
|
||||
|
||||
* old style: str or list
|
||||
* new style: a dict which maps from fileext to filetype
|
||||
@@ -371,7 +372,7 @@ def convert_highlight_options(app: "Sphinx", config: Config) -> None:
|
||||
"""Convert old styled highlight_options to new styled one.
|
||||
|
||||
* old style: options
|
||||
* new style: dict that maps language names to options
|
||||
* new style: a dict which maps from language name to options
|
||||
"""
|
||||
options = config.highlight_options
|
||||
if options and not all(isinstance(v, dict) for v in options.values()):
|
||||
@@ -392,7 +393,7 @@ def init_numfig_format(app: "Sphinx", config: Config) -> None:
|
||||
|
||||
|
||||
def correct_copyright_year(app: "Sphinx", config: Config) -> None:
|
||||
"""correct values of copyright year that are not coherent with
|
||||
"""Correct values of copyright year that are not coherent with
|
||||
the SOURCE_DATE_EPOCH environment variable (if set)
|
||||
|
||||
See https://reproducible-builds.org/specs/source-date-epoch/
|
||||
@@ -405,7 +406,7 @@ def correct_copyright_year(app: "Sphinx", config: Config) -> None:
|
||||
|
||||
|
||||
def check_confval_types(app: "Sphinx", config: Config) -> None:
|
||||
"""check all values for deviation from the default value's type, since
|
||||
"""Check all values for deviation from the default value's type, since
|
||||
that can result in TypeErrors all over the place NB.
|
||||
"""
|
||||
for confval in config:
|
||||
@@ -469,7 +470,7 @@ def check_primary_domain(app: "Sphinx", config: Config) -> None:
|
||||
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.
|
||||
any root_doc setting.
|
||||
"""
|
||||
if (app.config.root_doc == 'index' and
|
||||
'index' not in app.project.docnames and
|
||||
|
||||
@@ -129,5 +129,5 @@ class NoUri(Exception):
|
||||
|
||||
|
||||
class FiletypeNotFoundError(Exception):
|
||||
"Raised by get_filetype() if a filename matches no source suffix."
|
||||
"""Raised by get_filetype() if a filename matches no source suffix."""
|
||||
pass
|
||||
|
||||
@@ -226,7 +226,7 @@ def walk(rootpath: str, excludes: List[str], opts: Any
|
||||
|
||||
|
||||
def has_child_module(rootpath: str, excludes: List[str], opts: Any) -> bool:
|
||||
"""Check the given directory contains child modules at least one."""
|
||||
"""Check the given directory contains child module/s (at least one)."""
|
||||
for root, subs, files in walk(rootpath, excludes, opts):
|
||||
if files:
|
||||
return True
|
||||
|
||||
@@ -306,7 +306,7 @@ class Documenter:
|
||||
|
||||
A Documenter has an *option_spec* that works like a docutils directive's;
|
||||
in fact, it will be used to parse an auto directive's options that matches
|
||||
the documenter.
|
||||
the Documenter.
|
||||
"""
|
||||
#: name by which the directive is called (auto...) and the default
|
||||
#: generated directive name
|
||||
@@ -331,7 +331,7 @@ class Documenter:
|
||||
@classmethod
|
||||
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any
|
||||
) -> bool:
|
||||
"""Called to see if a member can be documented by this documenter."""
|
||||
"""Called to see if a member can be documented by this Documenter."""
|
||||
raise NotImplementedError('must be implemented in subclasses')
|
||||
|
||||
def __init__(self, directive: "DocumenterBridge", name: str, indent: str = '') -> None:
|
||||
@@ -552,7 +552,7 @@ class Documenter:
|
||||
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
|
||||
When it returns None, autodoc-process-docstring will not be called for this
|
||||
object.
|
||||
"""
|
||||
if ignore is not None:
|
||||
@@ -643,7 +643,7 @@ class Documenter:
|
||||
list of `(membername, member)` pairs of the members of *self.object*.
|
||||
|
||||
If *want_all* is True, return all members. Else, only return those
|
||||
members given by *self.options.members* (which may also be none).
|
||||
members given by *self.options.members* (which may also be None).
|
||||
"""
|
||||
warnings.warn('The implementation of Documenter.get_object_members() will be '
|
||||
'removed from Sphinx-6.0.', RemovedInSphinx60Warning)
|
||||
@@ -820,7 +820,7 @@ class Documenter:
|
||||
def document_members(self, all_members: bool = False) -> None:
|
||||
"""Generate reST for member documentation.
|
||||
|
||||
If *all_members* is True, do all members, else those given by
|
||||
If *all_members* is True, document all members, else those given by
|
||||
*self.options.members*.
|
||||
"""
|
||||
# set current namespace for finding members
|
||||
@@ -2382,7 +2382,7 @@ class RuntimeInstanceAttributeMixin(DataDocumenterMixinBase):
|
||||
return None
|
||||
|
||||
def import_object(self, raiseerror: bool = False) -> bool:
|
||||
"""Check the existence of runtime instance attribute when failed to import the
|
||||
"""Check the existence of runtime instance attribute after failing to import the
|
||||
attribute."""
|
||||
try:
|
||||
return super().import_object(raiseerror=True) # type: ignore
|
||||
|
||||
@@ -61,7 +61,7 @@ class DocumenterBridge:
|
||||
self.state = state
|
||||
|
||||
def warn(self, msg: str) -> None:
|
||||
warnings.warn('DocumenterBridge.warn is deprecated. Plase use sphinx.util.logging '
|
||||
warnings.warn('DocumenterBridge.warn is deprecated. Please use sphinx.util.logging '
|
||||
'module instead.',
|
||||
RemovedInSphinx60Warning, stacklevel=2)
|
||||
logger.warning(msg, location=(self.env.docname, self.lineno))
|
||||
@@ -107,7 +107,7 @@ def process_documenter_options(documenter: Type[Documenter], config: Config, opt
|
||||
|
||||
def parse_generated_content(state: RSTState, content: StringList, documenter: Documenter
|
||||
) -> List[Node]:
|
||||
"""Parse a generated content by Documenter."""
|
||||
"""Parse an item of content generated by Documenter."""
|
||||
with switch_source_input(state, content):
|
||||
if documenter.titles_allowed:
|
||||
node: Element = nodes.section()
|
||||
@@ -125,8 +125,8 @@ def parse_generated_content(state: RSTState, content: StringList, documenter: Do
|
||||
class AutodocDirective(SphinxDirective):
|
||||
"""A directive class for all autodoc directives. It works as a dispatcher of Documenters.
|
||||
|
||||
It invokes a Documenter on running. After the processing, it parses and returns
|
||||
the generated content by Documenter.
|
||||
It invokes a Documenter upon running. After the processing, it parses and returns
|
||||
the content generated by Documenter.
|
||||
"""
|
||||
option_spec = DummyOptionSpec()
|
||||
has_content = True
|
||||
|
||||
@@ -30,7 +30,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def mangle(subject: Any, name: str) -> str:
|
||||
"""mangle the given name."""
|
||||
"""Mangle the given name."""
|
||||
try:
|
||||
if isclass(subject) and name.startswith('__') and not name.endswith('__'):
|
||||
return "_%s%s" % (subject.__name__, name)
|
||||
@@ -41,7 +41,7 @@ def mangle(subject: Any, name: str) -> str:
|
||||
|
||||
|
||||
def unmangle(subject: Any, name: str) -> Optional[str]:
|
||||
"""unmangle the given name."""
|
||||
"""Unmangle the given name."""
|
||||
try:
|
||||
if isclass(subject) and not name.endswith('__'):
|
||||
prefix = "_%s__" % subject.__name__
|
||||
|
||||
@@ -568,7 +568,7 @@ def extract_summary(doc: List[str], document: Any) -> str:
|
||||
|
||||
def limited_join(sep: str, items: List[str], max_chars: int = 30,
|
||||
overflow_marker: str = "...") -> str:
|
||||
"""Join a number of strings to one, limiting the length to *max_chars*.
|
||||
"""Join a number of strings into one, limiting the length to *max_chars*.
|
||||
|
||||
If the string overflows this limit, replace the last fitting item by
|
||||
*overflow_marker*.
|
||||
|
||||
@@ -73,7 +73,8 @@ class SphinxBaseReader(standalone.Reader):
|
||||
return transforms
|
||||
|
||||
def new_document(self) -> nodes.document:
|
||||
"""Creates a new document object which having a special reporter object good
|
||||
"""
|
||||
Creates a new document object which has a special reporter object good
|
||||
for logging.
|
||||
"""
|
||||
document = super().new_document()
|
||||
|
||||
@@ -32,7 +32,7 @@ class Parser(docutils.parsers.Parser):
|
||||
of ``docutils.parsers.Parser``. Compared with ``docutils.parsers.Parser``, this class
|
||||
improves accessibility to Sphinx APIs.
|
||||
|
||||
The subclasses can access following objects and functions:
|
||||
The subclasses can access the following objects and functions:
|
||||
|
||||
self.app
|
||||
The application object (:class:`sphinx.application.Sphinx`)
|
||||
@@ -43,7 +43,7 @@ class Parser(docutils.parsers.Parser):
|
||||
self.warn()
|
||||
Emit a warning. (Same as :meth:`sphinx.application.Sphinx.warn()`)
|
||||
self.info()
|
||||
Emit a informational message. (Same as :meth:`sphinx.application.Sphinx.info()`)
|
||||
Emit an info message. (Same as :meth:`sphinx.application.Sphinx.info()`)
|
||||
|
||||
.. deprecated:: 1.6
|
||||
``warn()`` and ``info()`` is deprecated. Use :mod:`sphinx.util.logging` instead.
|
||||
@@ -70,7 +70,8 @@ class RSTParser(docutils.parsers.rst.Parser, Parser):
|
||||
"""A reST parser for Sphinx."""
|
||||
|
||||
def get_transforms(self) -> List[Type[Transform]]:
|
||||
"""Sphinx's reST parser replaces a transform class for smart-quotes by own's
|
||||
"""
|
||||
Sphinx's reST parser replaces a transform class for smart-quotes by its own
|
||||
|
||||
refs: sphinx.io.SphinxStandaloneReader
|
||||
"""
|
||||
|
||||
@@ -22,7 +22,7 @@ EXCLUDE_PATHS = ['**/_sources', '.#*', '**/.#*', '*.lproj/**']
|
||||
|
||||
|
||||
class Project:
|
||||
"""A project is source code set of Sphinx document."""
|
||||
"""A project is the source code set of the Sphinx document(s)."""
|
||||
|
||||
def __init__(self, srcdir: str, source_suffix: Dict[str, str]) -> None:
|
||||
#: Source directory.
|
||||
@@ -61,7 +61,7 @@ class Project:
|
||||
return self.docnames
|
||||
|
||||
def path2doc(self, filename: str) -> Optional[str]:
|
||||
"""Return the docname for the filename if the file is document.
|
||||
"""Return the docname for the filename if the file is a document.
|
||||
|
||||
*filename* should be absolute or relative to the source directory.
|
||||
"""
|
||||
|
||||
@@ -45,7 +45,7 @@ OPERATORS: Dict[Type[ast.AST], str] = {
|
||||
|
||||
|
||||
def parse(code: str, mode: str = 'exec') -> "ast.AST":
|
||||
"""Parse the *code* using built-in ast or typed_ast.
|
||||
"""Parse the *code* using the built-in ast or typed_ast libraries.
|
||||
|
||||
This enables "type_comments" feature if possible.
|
||||
"""
|
||||
|
||||
@@ -137,7 +137,7 @@ class TokenProcessor:
|
||||
return self.buffers[lineno - 1]
|
||||
|
||||
def fetch_token(self) -> Token:
|
||||
"""Fetch a next token from source code.
|
||||
"""Fetch the next token from source code.
|
||||
|
||||
Returns ``None`` if sequence finished.
|
||||
"""
|
||||
@@ -170,10 +170,10 @@ class TokenProcessor:
|
||||
|
||||
|
||||
class AfterCommentParser(TokenProcessor):
|
||||
"""Python source code parser to pick up comment after assignment.
|
||||
"""Python source code parser to pick up comments after assignments.
|
||||
|
||||
This parser takes a python code starts with assignment statement,
|
||||
and returns the comments for variable if exists.
|
||||
This parser takes code which starts with an assignment statement,
|
||||
and returns the comment for the variable if one exists.
|
||||
"""
|
||||
|
||||
def __init__(self, lines: List[str]) -> None:
|
||||
@@ -236,7 +236,7 @@ class VariableCommentPicker(ast.NodeVisitor):
|
||||
super().__init__()
|
||||
|
||||
def get_qualname_for(self, name: str) -> Optional[List[str]]:
|
||||
"""Get qualified name for given object as a list of string."""
|
||||
"""Get qualified name for given object as a list of string(s)."""
|
||||
if self.current_function:
|
||||
if self.current_classes and self.context[-1] == "__init__":
|
||||
# store variable comments inside __init__ method of classes
|
||||
@@ -309,7 +309,7 @@ class VariableCommentPicker(ast.NodeVisitor):
|
||||
return False
|
||||
|
||||
def get_self(self) -> Optional[ast.arg]:
|
||||
"""Returns the name of first argument if in function."""
|
||||
"""Returns the name of the first argument if in a function."""
|
||||
if self.current_function and self.current_function.args.args:
|
||||
return self.current_function.args.args[0]
|
||||
else:
|
||||
@@ -320,12 +320,12 @@ class VariableCommentPicker(ast.NodeVisitor):
|
||||
return self.buffers[lineno - 1]
|
||||
|
||||
def visit(self, node: ast.AST) -> None:
|
||||
"""Updates self.previous to ."""
|
||||
"""Updates self.previous to the given node."""
|
||||
super().visit(node)
|
||||
self.previous = node
|
||||
|
||||
def visit_Import(self, node: ast.Import) -> None:
|
||||
"""Handles Import node and record it to definition orders."""
|
||||
"""Handles Import node and record the order of definitions."""
|
||||
for name in node.names:
|
||||
self.add_entry(name.asname or name.name)
|
||||
|
||||
@@ -337,7 +337,7 @@ class VariableCommentPicker(ast.NodeVisitor):
|
||||
self.typing_overload = name.asname or name.name
|
||||
|
||||
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
|
||||
"""Handles Import node and record it to definition orders."""
|
||||
"""Handles Import node and record the order of definitions."""
|
||||
for name in node.names:
|
||||
self.add_entry(name.asname or name.name)
|
||||
|
||||
|
||||
@@ -467,7 +467,7 @@ class SphinxComponentRegistry:
|
||||
|
||||
|
||||
def merge_source_suffix(app: "Sphinx", config: Config) -> None:
|
||||
"""Merge source_suffix which specified by user and added by extensions."""
|
||||
"""Merge any user-specified source_suffix with any added by extensions."""
|
||||
for suffix, filetype in app.registry.source_suffix.items():
|
||||
if suffix not in app.config.source_suffix:
|
||||
app.config.source_suffix[suffix] = filetype
|
||||
|
||||
@@ -120,7 +120,7 @@ from sphinx.search.en import SearchEnglish
|
||||
|
||||
def parse_stop_word(source: str) -> Set[str]:
|
||||
"""
|
||||
parse snowball style word list like this:
|
||||
Parse snowball style word list like this:
|
||||
|
||||
* http://snowball.tartarus.org/algorithms/finnish/stop.txt
|
||||
"""
|
||||
@@ -155,7 +155,7 @@ languages: Dict[str, Any] = {
|
||||
|
||||
class _JavaScriptIndex:
|
||||
"""
|
||||
The search index as javascript file that calls a function
|
||||
The search index as JavaScript file that calls a function
|
||||
on the documentation search object to register the index.
|
||||
"""
|
||||
|
||||
@@ -228,7 +228,7 @@ class WordCollector(nodes.NodeVisitor):
|
||||
|
||||
class IndexBuilder:
|
||||
"""
|
||||
Helper class that creates a searchindex based on the doctrees
|
||||
Helper class that creates a search index based on the doctrees
|
||||
passed to the `feed` method.
|
||||
"""
|
||||
formats = {
|
||||
|
||||
@@ -30,8 +30,8 @@ class BuildDoc(Command):
|
||||
Distutils command to build Sphinx documentation.
|
||||
|
||||
The Sphinx build can then be triggered from distutils, and some Sphinx
|
||||
options can be set in ``setup.py`` or ``setup.cfg`` instead of Sphinx own
|
||||
configuration file.
|
||||
options can be set in ``setup.py`` or ``setup.cfg`` instead of Sphinx's
|
||||
own configuration file.
|
||||
|
||||
For instance, from `setup.py`::
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ DEFAULT_ENABLED_MARKERS = [
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
# register custom markers
|
||||
"""Register custom markers"""
|
||||
for marker in DEFAULT_ENABLED_MARKERS:
|
||||
config.addinivalue_line('markers', marker)
|
||||
|
||||
@@ -66,7 +66,7 @@ class SharedResult:
|
||||
def app_params(request: Any, test_params: Dict, shared_result: SharedResult,
|
||||
sphinx_test_tempdir: str, rootdir: str) -> Tuple[Dict, Dict]:
|
||||
"""
|
||||
parameters that is specified by 'pytest.mark.sphinx' for
|
||||
Parameters that are specified by 'pytest.mark.sphinx' for
|
||||
sphinx.application.Sphinx initialization
|
||||
"""
|
||||
|
||||
@@ -113,13 +113,13 @@ def app_params(request: Any, test_params: Dict, shared_result: SharedResult,
|
||||
@pytest.fixture
|
||||
def test_params(request: Any) -> Dict:
|
||||
"""
|
||||
test parameters that is specified by 'pytest.mark.test_params'
|
||||
Test parameters that are specified by 'pytest.mark.test_params'
|
||||
|
||||
:param Union[str] shared_result:
|
||||
If the value is provided, app._status and app._warning objects will be
|
||||
shared in the parametrized test functions and/or test functions that
|
||||
have same 'shared_result' value.
|
||||
**NOTE**: You can not specify shared_result and srcdir in same time.
|
||||
**NOTE**: You can not specify both shared_result and srcdir.
|
||||
"""
|
||||
if hasattr(request.node, 'get_closest_marker'): # pytest-3.6.0 or newer
|
||||
env = request.node.get_closest_marker('test_params')
|
||||
@@ -141,7 +141,7 @@ def test_params(request: Any) -> Dict:
|
||||
def app(test_params: Dict, app_params: Tuple[Dict, Dict], make_app: Callable,
|
||||
shared_result: SharedResult) -> Generator[SphinxTestApp, None, None]:
|
||||
"""
|
||||
provides sphinx.application.Sphinx object
|
||||
Provides the 'sphinx.application.Sphinx' object
|
||||
"""
|
||||
args, kwargs = app_params
|
||||
app_ = make_app(*args, **kwargs)
|
||||
@@ -161,7 +161,7 @@ def app(test_params: Dict, app_params: Tuple[Dict, Dict], make_app: Callable,
|
||||
@pytest.fixture(scope='function')
|
||||
def status(app: SphinxTestApp) -> StringIO:
|
||||
"""
|
||||
compat for testing with previous @with_app decorator
|
||||
Back-compatibility for testing with previous @with_app decorator
|
||||
"""
|
||||
return app._status
|
||||
|
||||
@@ -169,7 +169,7 @@ def status(app: SphinxTestApp) -> StringIO:
|
||||
@pytest.fixture(scope='function')
|
||||
def warning(app: SphinxTestApp) -> StringIO:
|
||||
"""
|
||||
compat for testing with previous @with_app decorator
|
||||
Back-compatibility for testing with previous @with_app decorator
|
||||
"""
|
||||
return app._warning
|
||||
|
||||
@@ -177,7 +177,7 @@ def warning(app: SphinxTestApp) -> StringIO:
|
||||
@pytest.fixture()
|
||||
def make_app(test_params: Dict, monkeypatch: Any) -> Generator[Callable, None, None]:
|
||||
"""
|
||||
provides make_app function to initialize SphinxTestApp instance.
|
||||
Provides make_app function to initialize SphinxTestApp instance.
|
||||
if you want to initialize 'app' in your test function. please use this
|
||||
instead of using SphinxTestApp class directory.
|
||||
"""
|
||||
@@ -232,7 +232,7 @@ def if_graphviz_found(app: SphinxTestApp) -> None:
|
||||
@pytest.fixture(scope='session')
|
||||
def sphinx_test_tempdir(tmpdir_factory: Any) -> "util.path":
|
||||
"""
|
||||
temporary directory that wrapped with `path` class.
|
||||
Temporary directory wrapped with `path` class.
|
||||
"""
|
||||
tmpdir = tmpdir_factory.getbasetemp()
|
||||
return util.path(tmpdir).abspath()
|
||||
@@ -241,15 +241,21 @@ def sphinx_test_tempdir(tmpdir_factory: Any) -> "util.path":
|
||||
@pytest.fixture
|
||||
def tempdir(tmpdir: str) -> "util.path":
|
||||
"""
|
||||
temporary directory that wrapped with `path` class.
|
||||
this fixture is for compat with old test implementation.
|
||||
Temporary directory wrapped with `path` class.
|
||||
This fixture is for back-compatibility with old test implementation.
|
||||
"""
|
||||
return util.path(tmpdir)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rollback_sysmodules():
|
||||
"""Rollback sys.modules to before testing to unload modules during tests."""
|
||||
"""
|
||||
Rollback sys.modules to its value before testing to unload modules
|
||||
during tests.
|
||||
|
||||
For example, used in test_ext_autosummary.py to permit unloading the
|
||||
target module to clear its cache.
|
||||
"""
|
||||
try:
|
||||
sysmodules = list(sys.modules)
|
||||
yield
|
||||
|
||||
@@ -142,7 +142,7 @@ class Theme:
|
||||
|
||||
|
||||
def is_archived_theme(filename: str) -> bool:
|
||||
"""Check the specified file is an archived theme file or not."""
|
||||
"""Check whether the specified file is an archived theme file or not."""
|
||||
try:
|
||||
with ZipFile(filename) as f:
|
||||
return THEMECONF in f.namelist()
|
||||
@@ -175,7 +175,7 @@ class HTMLThemeFactory:
|
||||
self.themes[name] = theme
|
||||
|
||||
def load_extra_theme(self, name: str) -> None:
|
||||
"""Try to load a theme having specified name."""
|
||||
"""Try to load a theme with the specified name."""
|
||||
if name == 'alabaster':
|
||||
self.load_alabaster_theme()
|
||||
else:
|
||||
@@ -187,7 +187,7 @@ class HTMLThemeFactory:
|
||||
self.themes['alabaster'] = path.join(alabaster.get_path(), 'alabaster')
|
||||
|
||||
def load_sphinx_rtd_theme(self) -> None:
|
||||
"""Load sphinx_rtd_theme theme (if exists)."""
|
||||
"""Load sphinx_rtd_theme theme (if installed)."""
|
||||
try:
|
||||
import sphinx_rtd_theme
|
||||
theme_path = sphinx_rtd_theme.get_html_theme_path()
|
||||
|
||||
@@ -202,7 +202,7 @@ TRANSLATABLE_NODES = {
|
||||
|
||||
class ApplySourceWorkaround(SphinxTransform):
|
||||
"""
|
||||
update source and rawsource attributes
|
||||
Update source and rawsource attributes
|
||||
"""
|
||||
default_priority = 10
|
||||
|
||||
@@ -214,7 +214,7 @@ class ApplySourceWorkaround(SphinxTransform):
|
||||
|
||||
class AutoIndexUpgrader(SphinxTransform):
|
||||
"""
|
||||
Detect old style; 4 column based indices and automatically upgrade to new style.
|
||||
Detect old style (4 column based indices) and automatically upgrade to new style.
|
||||
"""
|
||||
default_priority = 210
|
||||
|
||||
@@ -231,7 +231,7 @@ class AutoIndexUpgrader(SphinxTransform):
|
||||
|
||||
class ExtraTranslatableNodes(SphinxTransform):
|
||||
"""
|
||||
make nodes translatable
|
||||
Make nodes translatable
|
||||
"""
|
||||
default_priority = 10
|
||||
|
||||
@@ -250,7 +250,7 @@ class ExtraTranslatableNodes(SphinxTransform):
|
||||
|
||||
class UnreferencedFootnotesDetector(SphinxTransform):
|
||||
"""
|
||||
detect unreferenced footnotes and emit warnings
|
||||
Detect unreferenced footnotes and emit warnings
|
||||
"""
|
||||
default_priority = 200
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ class SphinxPostTransform(SphinxTransform):
|
||||
"""A base class of post-transforms.
|
||||
|
||||
Post transforms are invoked to modify the document to restructure it for outputting.
|
||||
They do resolving references, convert images, special transformation for each output
|
||||
They resolve references, convert images, do special transformation for each output
|
||||
formats and so on. This class helps to implement these post transforms.
|
||||
"""
|
||||
builders: Tuple[str, ...] = ()
|
||||
@@ -52,7 +52,7 @@ class SphinxPostTransform(SphinxTransform):
|
||||
return True
|
||||
|
||||
def run(self, **kwargs: Any) -> None:
|
||||
"""main method of post transforms.
|
||||
"""Main method of post transforms.
|
||||
|
||||
Subclasses should override this method instead of ``apply()``.
|
||||
"""
|
||||
@@ -230,7 +230,7 @@ class OnlyNodeTransform(SphinxPostTransform):
|
||||
|
||||
|
||||
class SigElementFallbackTransform(SphinxPostTransform):
|
||||
"""Fallback various desc_* nodes to inline if translator does not supported them."""
|
||||
"""Fallback various desc_* nodes to inline if translator does not support them."""
|
||||
default_priority = 200
|
||||
|
||||
def run(self, **kwargs: Any) -> None:
|
||||
|
||||
@@ -154,13 +154,13 @@ class ImageConverter(BaseImageConverter):
|
||||
"""A base class for image converters.
|
||||
|
||||
An image converter is kind of Docutils transform module. It is used to
|
||||
convert image files which does not supported by builder to appropriate
|
||||
format for that builder.
|
||||
convert image files which are not supported by a builder to the
|
||||
appropriate format for that builder.
|
||||
|
||||
For example, :py:class:`LaTeX builder <.LaTeXBuilder>` supports PDF,
|
||||
PNG and JPEG as image formats. However it does not support SVG images.
|
||||
For such case, to use image converters allows to embed these
|
||||
unsupported images into the document. One of image converters;
|
||||
For such case, using image converters allows to embed these
|
||||
unsupported images into the document. One of the image converters;
|
||||
:ref:`sphinx.ext.imgconverter <sphinx.ext.imgconverter>` can convert
|
||||
a SVG image to PNG format using Imagemagick internally.
|
||||
|
||||
@@ -258,10 +258,10 @@ class ImageConverter(BaseImageConverter):
|
||||
self.env.images.add_file(self.env.docname, destpath)
|
||||
|
||||
def convert(self, _from: str, _to: str) -> bool:
|
||||
"""Convert a image file to expected format.
|
||||
"""Convert an image file to the expected format.
|
||||
|
||||
*_from* is a path for source image file, and *_to* is a path for
|
||||
destination file.
|
||||
*_from* is a path of the source image file, and *_to* is a path
|
||||
of the destination file.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ def docname_join(basedocname: str, docname: str) -> str:
|
||||
|
||||
|
||||
def path_stabilize(filepath: str) -> str:
|
||||
"normalize path separater and unicode string"
|
||||
"Normalize path separator and unicode string"
|
||||
newpath = filepath.replace(os.path.sep, SEP)
|
||||
return unicodedata.normalize('NFC', newpath)
|
||||
|
||||
@@ -435,7 +435,7 @@ def split_full_qualified_name(name: str) -> Tuple[Optional[str], str]:
|
||||
A "full" qualified name means a string containing both module name and
|
||||
qualified name.
|
||||
|
||||
.. note:: This function imports module actually to check the exisitence.
|
||||
.. note:: This function actually imports the module to check its existence.
|
||||
Therefore you need to mock 3rd party modules if needed before
|
||||
calling this function.
|
||||
"""
|
||||
|
||||
@@ -25,7 +25,7 @@ codes: Dict[str, str] = {}
|
||||
|
||||
|
||||
def terminal_safe(s: str) -> str:
|
||||
"""safely encode a string for printing to the terminal."""
|
||||
"""Safely encode a string for printing to the terminal."""
|
||||
return s.encode('ascii', 'backslashreplace').decode('ascii')
|
||||
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class InventoryFileReader:
|
||||
"""A file reader for inventory file.
|
||||
"""A file reader for an inventory file.
|
||||
|
||||
This reader supports mixture of texts and compressed texts.
|
||||
"""
|
||||
|
||||
@@ -187,7 +187,7 @@ class MemoryHandler(logging.handlers.BufferingHandler):
|
||||
|
||||
@contextmanager
|
||||
def pending_warnings() -> Generator[logging.Handler, None, None]:
|
||||
"""Contextmanager to pend logging warnings temporary.
|
||||
"""Context manager to postpone logging warnings temporarily.
|
||||
|
||||
Similar to :func:`pending_logging`.
|
||||
"""
|
||||
@@ -215,7 +215,7 @@ def pending_warnings() -> Generator[logging.Handler, None, None]:
|
||||
|
||||
@contextmanager
|
||||
def suppress_logging() -> Generator[MemoryHandler, None, None]:
|
||||
"""Contextmanager to suppress logging all logs temporary.
|
||||
"""Context manager to suppress logging all logs temporarily.
|
||||
|
||||
For example::
|
||||
|
||||
@@ -244,7 +244,7 @@ def suppress_logging() -> Generator[MemoryHandler, None, None]:
|
||||
|
||||
@contextmanager
|
||||
def pending_logging() -> Generator[MemoryHandler, None, None]:
|
||||
"""Contextmanager to pend logging all logs temporary.
|
||||
"""Context manager to postpone logging all logs temporarily.
|
||||
|
||||
For example::
|
||||
|
||||
@@ -264,7 +264,7 @@ def pending_logging() -> Generator[MemoryHandler, None, None]:
|
||||
|
||||
@contextmanager
|
||||
def skip_warningiserror(skip: bool = True) -> Generator[None, None, None]:
|
||||
"""contextmanager to skip WarningIsErrorFilter for a while."""
|
||||
"""Context manager to skip WarningIsErrorFilter temporarily."""
|
||||
logger = logging.getLogger(NAMESPACE)
|
||||
|
||||
if skip is False:
|
||||
@@ -284,7 +284,7 @@ def skip_warningiserror(skip: bool = True) -> Generator[None, None, None]:
|
||||
|
||||
@contextmanager
|
||||
def prefixed_warnings(prefix: str) -> Generator[None, None, None]:
|
||||
"""Prepend prefix to all records for a while.
|
||||
"""Context manager to prepend prefix to all warning log records temporarily.
|
||||
|
||||
For example::
|
||||
|
||||
@@ -351,7 +351,7 @@ class InfoFilter(logging.Filter):
|
||||
|
||||
|
||||
def is_suppressed_warning(type: str, subtype: str, suppress_warnings: List[str]) -> bool:
|
||||
"""Check the warning is suppressed or not."""
|
||||
"""Check whether the warning is suppressed or not."""
|
||||
if type is None:
|
||||
return False
|
||||
|
||||
@@ -434,7 +434,7 @@ class DisableWarningIsErrorFilter(logging.Filter):
|
||||
|
||||
|
||||
class MessagePrefixFilter(logging.Filter):
|
||||
"""Prepend prefix to all records."""
|
||||
"""Prepend prefix to all log records."""
|
||||
|
||||
def __init__(self, prefix: str) -> None:
|
||||
self.prefix = prefix
|
||||
@@ -555,7 +555,7 @@ class SafeEncodingWriter:
|
||||
|
||||
|
||||
class LastMessagesWriter:
|
||||
"""Stream writer which memories last 10 messages to save trackback"""
|
||||
"""Stream writer storing last 10 messages in memory to save trackback"""
|
||||
def __init__(self, app: "Sphinx", stream: IO) -> None:
|
||||
self.app = app
|
||||
|
||||
|
||||
@@ -90,14 +90,16 @@ _pat_cache: Dict[str, Pattern] = {}
|
||||
|
||||
|
||||
def patmatch(name: str, pat: str) -> Optional[Match[str]]:
|
||||
"""Return if name matches pat. Adapted from fnmatch module."""
|
||||
"""Return if name matches the regular expression (pattern)
|
||||
``pat```. Adapted from fnmatch module."""
|
||||
if pat not in _pat_cache:
|
||||
_pat_cache[pat] = re.compile(_translate_pattern(pat))
|
||||
return _pat_cache[pat].match(name)
|
||||
|
||||
|
||||
def patfilter(names: Iterable[str], pat: str) -> List[str]:
|
||||
"""Return the subset of the list NAMES that match PAT.
|
||||
"""Return the subset of the list ``names`` that match
|
||||
the regular expression (pattern) ``pat``.
|
||||
|
||||
Adapted from fnmatch module.
|
||||
"""
|
||||
|
||||
@@ -40,8 +40,8 @@ caption_ref_re = explicit_title_re # b/w compat alias
|
||||
class NodeMatcher:
|
||||
"""A helper class for Node.traverse().
|
||||
|
||||
It checks that given node is an instance of specified node-classes and it has
|
||||
specified node-attributes.
|
||||
It checks that the given node is an instance of the specified node-classes and
|
||||
has the specified node-attributes.
|
||||
|
||||
For example, following example searches ``reference`` node having ``refdomain``
|
||||
and ``reftype`` attributes::
|
||||
@@ -91,7 +91,7 @@ class NodeMatcher:
|
||||
|
||||
def get_full_module_name(node: Node) -> str:
|
||||
"""
|
||||
return full module dotted path like: 'docutils.nodes.paragraph'
|
||||
Return full module dotted path like: 'docutils.nodes.paragraph'
|
||||
|
||||
:param nodes.Node node: target node
|
||||
:return: full module dotted path
|
||||
@@ -588,7 +588,7 @@ NON_SMARTQUOTABLE_PARENT_NODES = (
|
||||
|
||||
|
||||
def is_smartquotable(node: Node) -> bool:
|
||||
"""Check the node is smart-quotable or not."""
|
||||
"""Check whether the node is smart-quotable or not."""
|
||||
if isinstance(node.parent, NON_SMARTQUOTABLE_PARENT_NODES):
|
||||
return False
|
||||
elif node.parent.get('support_smartquotes', None) is False:
|
||||
@@ -600,7 +600,7 @@ def is_smartquotable(node: Node) -> bool:
|
||||
|
||||
|
||||
def process_only_nodes(document: Node, tags: "Tags") -> None:
|
||||
"""Filter ``only`` nodes which does not match *tags*."""
|
||||
"""Filter ``only`` nodes which do not match *tags*."""
|
||||
for node in document.traverse(addnodes.only):
|
||||
try:
|
||||
ret = tags.eval_condition(node['expr'])
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
sphinx.writers.html5
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Experimental docutils writers for HTML5 handling Sphinx' custom nodes.
|
||||
Experimental docutils writers for HTML5 handling Sphinx's custom nodes.
|
||||
|
||||
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
|
||||
:license: BSD, see LICENSE for details.
|
||||
|
||||
@@ -35,7 +35,7 @@ from sphinx.util.texescape import tex_replace_map
|
||||
try:
|
||||
from docutils.utils.roman import toRoman
|
||||
except ImportError:
|
||||
# In Debain/Ubuntu, roman package is provided as roman, not as docutils.utils.roman
|
||||
# In Debian/Ubuntu, roman package is provided as roman, not as docutils.utils.roman
|
||||
from roman import toRoman # type: ignore
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -123,7 +123,7 @@ class Table:
|
||||
self.col = 0
|
||||
self.row = 0
|
||||
|
||||
# A mapping a table location to the cell_id (cell = rectangular area)
|
||||
# A dict mapping a table location to a cell_id (cell = rectangular area)
|
||||
self.cells: Dict[Tuple[int, int], int] = defaultdict(int)
|
||||
self.cell_id = 0 # last assigned cell_id
|
||||
|
||||
@@ -202,7 +202,7 @@ class Table:
|
||||
|
||||
|
||||
class TableCell:
|
||||
"""A cell data of tables."""
|
||||
"""Data of a cell in a table."""
|
||||
|
||||
def __init__(self, table: Table, row: int, col: int) -> None:
|
||||
if table.cells[(row, col)] == 0:
|
||||
@@ -445,8 +445,7 @@ class LaTeXTranslator(SphinxTranslator):
|
||||
return body
|
||||
|
||||
def format_docclass(self, docclass: str) -> str:
|
||||
""" prepends prefix to sphinx document classes
|
||||
"""
|
||||
"""Prepends prefix to sphinx document classes"""
|
||||
warnings.warn('LaTeXWriter.format_docclass() is deprecated.',
|
||||
RemovedInSphinx50Warning, stacklevel=2)
|
||||
if docclass in self.docclasses:
|
||||
|
||||
@@ -73,7 +73,7 @@ class NestedInlineTransform:
|
||||
|
||||
class ManualPageTranslator(SphinxTranslator, BaseTranslator):
|
||||
"""
|
||||
Custom translator.
|
||||
Custom man page translator.
|
||||
"""
|
||||
|
||||
_docinfo: Dict[str, Any] = {}
|
||||
|
||||
@@ -29,7 +29,7 @@ if TYPE_CHECKING:
|
||||
|
||||
class Cell:
|
||||
"""Represents a cell in a table.
|
||||
It can span on multiple columns or on multiple lines.
|
||||
It can span multiple columns or multiple lines.
|
||||
"""
|
||||
def __init__(self, text: str = "", rowspan: int = 1, colspan: int = 1) -> None:
|
||||
self.text = text
|
||||
@@ -52,7 +52,7 @@ class Cell:
|
||||
|
||||
|
||||
class Table:
|
||||
"""Represents a table, handling cells that can span on multiple lines
|
||||
"""Represents a table, handling cells that can span multiple lines
|
||||
or rows, like::
|
||||
|
||||
+-----------+-----+
|
||||
@@ -63,22 +63,22 @@ class Table:
|
||||
| DDD | CCC |
|
||||
+-----+-----------+
|
||||
|
||||
This class can be used in two ways:
|
||||
This class can be used in two ways, either:
|
||||
|
||||
- Either with absolute positions: call ``table[line, col] = Cell(...)``,
|
||||
this overwrite an existing cell if any.
|
||||
- With absolute positions: call ``table[line, col] = Cell(...)``,
|
||||
this overwrites any existing cell(s) at these positions.
|
||||
|
||||
- Either with relative positions: call the ``add_row()`` and
|
||||
- With relative positions: call the ``add_row()`` and
|
||||
``add_cell(Cell(...))`` as needed.
|
||||
|
||||
Cell spanning on multiple rows or multiple columns (having a
|
||||
Cells spanning multiple rows or multiple columns (having a
|
||||
colspan or rowspan greater than one) are automatically referenced
|
||||
by all the table cells they covers. This is a useful
|
||||
representation as we can simply check ``if self[x, y] is self[x,
|
||||
y+1]`` to recognize a rowspan.
|
||||
by all the table cells they cover. This is a useful
|
||||
representation as we can simply check
|
||||
``if self[x, y] is self[x, y+1]`` to recognize a rowspan.
|
||||
|
||||
Colwidth is not automatically computed, it has to be given, either
|
||||
at construction time, either during the table construction.
|
||||
at construction time, or during the table construction.
|
||||
|
||||
Example usage::
|
||||
|
||||
@@ -112,14 +112,13 @@ class Table:
|
||||
self.current_col = 0
|
||||
|
||||
def set_separator(self) -> None:
|
||||
"""Sets the separator below the current line.
|
||||
"""
|
||||
"""Sets the separator below the current line."""
|
||||
self.separator = len(self.lines)
|
||||
|
||||
def add_cell(self, cell: Cell) -> None:
|
||||
"""Add a cell to the current line, to use with ``add_row()``. To add
|
||||
a cell spanning on multiple lines or rows, simply set the
|
||||
``cell.colspan`` or ``cell.rowspan`` BEFORE inserting it to
|
||||
a cell spanning multiple lines or rows, simply set the
|
||||
``cell.colspan`` or ``cell.rowspan`` BEFORE inserting it into
|
||||
the table.
|
||||
"""
|
||||
while self[self.current_line, self.current_col]:
|
||||
@@ -158,7 +157,7 @@ class Table:
|
||||
def cell_width(self, cell: Cell, source: List[int]) -> int:
|
||||
"""Give the cell width, according to the given source (either
|
||||
``self.colwidth`` or ``self.measured_widths``).
|
||||
This take into account cells spanning on multiple columns.
|
||||
This takes into account cells spanning multiple columns.
|
||||
"""
|
||||
width = 0
|
||||
for i in range(self[cell.row, cell.col].colspan):
|
||||
@@ -188,7 +187,7 @@ class Table:
|
||||
self.measured_widths[col] = max(self.measured_widths[col], width)
|
||||
|
||||
def physical_lines_for_line(self, line: List[Cell]) -> int:
|
||||
"""From a given line, compute the number of physical lines it spans
|
||||
"""For a given line, compute the number of physical lines it spans
|
||||
due to text wrapping.
|
||||
"""
|
||||
physical_lines = 1
|
||||
@@ -323,7 +322,7 @@ class TextWrapper(textwrap.TextWrapper):
|
||||
"""_split(text : string) -> [string]
|
||||
|
||||
Override original method that only split by 'wordsep_re'.
|
||||
This '_split' split wide-characters into chunk by one character.
|
||||
This '_split' splits wide-characters into chunks by one character.
|
||||
"""
|
||||
def split(t: str) -> List[str]:
|
||||
return super(TextWrapper, self)._split(t)
|
||||
|
||||
Reference in New Issue
Block a user