mirror of
https://github.com/sphinx-doc/sphinx.git
synced 2025-02-25 18:55:22 -06:00
Merge branch '3.x'
This commit is contained in:
commit
502c4ee5fb
14
CHANGES
14
CHANGES
@ -78,6 +78,10 @@ Dependencies
|
||||
Incompatible changes
|
||||
--------------------
|
||||
|
||||
* Update Underscore.js to 1.12.0
|
||||
* #6550: html: The config variable ``html_add_permalinks`` is replaced by
|
||||
:confval:`html_permalinks` and :confval:`html_permalinks_icon`
|
||||
|
||||
Deprecated
|
||||
----------
|
||||
|
||||
@ -91,6 +95,8 @@ Deprecated
|
||||
* ``sphinx.ext.autodoc.importer.get_module_members()``
|
||||
* ``sphinx.ext.autosummary.generate._simple_info()``
|
||||
* ``sphinx.ext.autosummary.generate._simple_warn()``
|
||||
* ``sphinx.writers.html.HTMLTranslator.permalink_text``
|
||||
* ``sphinx.writers.html5.HTML5Translator.permalink_text``
|
||||
|
||||
Features added
|
||||
--------------
|
||||
@ -106,10 +112,14 @@ Features added
|
||||
* #6241: html: Allow to add JS/CSS files to the specific page when an extension
|
||||
calls ``app.add_js_file()`` or ``app.add_css_file()`` on
|
||||
:event:`html-page-context` event
|
||||
* #6550: html: Allow to use HTML permalink texts via
|
||||
:confval:`html_permalinks_icon`
|
||||
* #8649: imgconverter: Skip availability check if builder supports the image
|
||||
type
|
||||
* #8573: napoleon: Allow to change the style of custom sections using
|
||||
:confval:`napoleon_custom_styles`
|
||||
* #8004: napoleon: Type definitions in Google style docstrings are rendered as
|
||||
references when :confval:`napoleon_preprocess_types` enabled
|
||||
* #6241: mathjax: Include mathjax.js only on the document using equations
|
||||
* #8651: std domain: cross-reference for a rubric having inline item is broken
|
||||
* #8681: viewcode: Support incremental build
|
||||
@ -118,10 +128,12 @@ Features added
|
||||
* #2030: :rst:dir:`code-block` and :rst:dir:`literalinclude` supports automatic
|
||||
dedent via no-argument ``:dedent:`` option
|
||||
* C++, also hyperlink operator overloads in expressions and alias declarations.
|
||||
* #8247: Allow production lists to refer to tokens from other production groups
|
||||
|
||||
Bugs fixed
|
||||
----------
|
||||
|
||||
* #8727: apidoc: namespace module file is not generated if no submodules there
|
||||
* #741: autodoc: inherited-members doesn't work for instance attributes on super
|
||||
class
|
||||
* #8592: autodoc: ``:meta public:`` does not effect to variables
|
||||
@ -150,6 +162,8 @@ Bugs fixed
|
||||
* #8683: :confval:`html_last_updated_fmt` generates wrong time zone for %Z
|
||||
* #1112: ``download`` role creates duplicated copies when relative path is
|
||||
specified
|
||||
* #8735: LaTeX: wrong internal links in pdf to captioned code-blocks when
|
||||
:confval:`numfig` is not True
|
||||
|
||||
Testing
|
||||
--------
|
||||
|
@ -25,75 +25,75 @@ package.
|
||||
|
||||
.. currentmodule:: sphinx.application
|
||||
|
||||
.. automethod:: Sphinx.setup_extension(name)
|
||||
.. automethod:: Sphinx.setup_extension
|
||||
|
||||
.. automethod:: Sphinx.require_sphinx(version)
|
||||
.. automethod:: Sphinx.require_sphinx
|
||||
|
||||
.. automethod:: Sphinx.connect(event, callback)
|
||||
.. automethod:: Sphinx.connect
|
||||
|
||||
.. automethod:: Sphinx.disconnect(listener_id)
|
||||
.. automethod:: Sphinx.disconnect
|
||||
|
||||
.. automethod:: Sphinx.add_builder(builder)
|
||||
.. automethod:: Sphinx.add_builder
|
||||
|
||||
.. automethod:: Sphinx.add_config_value(name, default, rebuild)
|
||||
.. automethod:: Sphinx.add_config_value
|
||||
|
||||
.. automethod:: Sphinx.add_event(name)
|
||||
.. automethod:: Sphinx.add_event
|
||||
|
||||
.. automethod:: Sphinx.set_translator(name, translator_class)
|
||||
.. automethod:: Sphinx.set_translator
|
||||
|
||||
.. automethod:: Sphinx.add_node(node, \*\*kwds)
|
||||
.. automethod:: Sphinx.add_node
|
||||
|
||||
.. automethod:: Sphinx.add_enumerable_node(node, figtype, title_getter=None, \*\*kwds)
|
||||
.. automethod:: Sphinx.add_enumerable_node
|
||||
|
||||
.. automethod:: Sphinx.add_directive(name, directiveclass)
|
||||
.. automethod:: Sphinx.add_directive
|
||||
|
||||
.. automethod:: Sphinx.add_role(name, role)
|
||||
.. automethod:: Sphinx.add_role
|
||||
|
||||
.. automethod:: Sphinx.add_generic_role(name, nodeclass)
|
||||
.. automethod:: Sphinx.add_generic_role
|
||||
|
||||
.. automethod:: Sphinx.add_domain(domain)
|
||||
.. automethod:: Sphinx.add_domain
|
||||
|
||||
.. automethod:: Sphinx.add_directive_to_domain(domain, name, directiveclass)
|
||||
.. automethod:: Sphinx.add_directive_to_domain
|
||||
|
||||
.. automethod:: Sphinx.add_role_to_domain(domain, name, role)
|
||||
.. automethod:: Sphinx.add_role_to_domain
|
||||
|
||||
.. automethod:: Sphinx.add_index_to_domain(domain, index)
|
||||
.. automethod:: Sphinx.add_index_to_domain
|
||||
|
||||
.. automethod:: Sphinx.add_object_type(directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', doc_field_types=[])
|
||||
.. automethod:: Sphinx.add_object_type
|
||||
|
||||
.. automethod:: Sphinx.add_crossref_type(directivename, rolename, indextemplate='', ref_nodeclass=None, objname='')
|
||||
.. automethod:: Sphinx.add_crossref_type
|
||||
|
||||
.. automethod:: Sphinx.add_transform(transform)
|
||||
.. automethod:: Sphinx.add_transform
|
||||
|
||||
.. automethod:: Sphinx.add_post_transform(transform)
|
||||
.. automethod:: Sphinx.add_post_transform
|
||||
|
||||
.. automethod:: Sphinx.add_js_file(filename, **kwargs)
|
||||
.. automethod:: Sphinx.add_js_file
|
||||
|
||||
.. automethod:: Sphinx.add_css_file(filename, **kwargs)
|
||||
.. automethod:: Sphinx.add_css_file
|
||||
|
||||
.. automethod:: Sphinx.add_latex_package(packagename, options=None)
|
||||
.. automethod:: Sphinx.add_latex_package
|
||||
|
||||
.. automethod:: Sphinx.add_lexer(alias, lexer)
|
||||
.. automethod:: Sphinx.add_lexer
|
||||
|
||||
.. automethod:: Sphinx.add_autodocumenter(cls)
|
||||
.. automethod:: Sphinx.add_autodocumenter
|
||||
|
||||
.. automethod:: Sphinx.add_autodoc_attrgetter(type, getter)
|
||||
.. automethod:: Sphinx.add_autodoc_attrgetter
|
||||
|
||||
.. automethod:: Sphinx.add_search_language(cls)
|
||||
.. automethod:: Sphinx.add_search_language
|
||||
|
||||
.. automethod:: Sphinx.add_source_suffix(suffix, filetype)
|
||||
.. automethod:: Sphinx.add_source_suffix
|
||||
|
||||
.. automethod:: Sphinx.add_source_parser(parser)
|
||||
.. automethod:: Sphinx.add_source_parser
|
||||
|
||||
.. automethod:: Sphinx.add_env_collector(collector)
|
||||
.. automethod:: Sphinx.add_env_collector
|
||||
|
||||
.. automethod:: Sphinx.add_html_theme(name, theme_path)
|
||||
.. automethod:: Sphinx.add_html_theme
|
||||
|
||||
.. automethod:: Sphinx.add_html_math_renderer(name, inline_renderers, block_renderers)
|
||||
.. automethod:: Sphinx.add_html_math_renderer
|
||||
|
||||
.. automethod:: Sphinx.add_message_catalog(catalog, locale_dir)
|
||||
.. automethod:: Sphinx.add_message_catalog
|
||||
|
||||
.. automethod:: Sphinx.is_parallel_allowed(typ)
|
||||
.. automethod:: Sphinx.is_parallel_allowed
|
||||
|
||||
.. exception:: ExtensionError
|
||||
|
||||
@ -107,9 +107,9 @@ Emitting events
|
||||
.. class:: Sphinx
|
||||
:noindex:
|
||||
|
||||
.. automethod:: emit(event, \*arguments)
|
||||
.. automethod:: emit
|
||||
|
||||
.. automethod:: emit_firstresult(event, \*arguments)
|
||||
.. automethod:: emit_firstresult
|
||||
|
||||
|
||||
Sphinx runtime information
|
||||
|
@ -106,6 +106,16 @@ The following is a list of deprecated interfaces.
|
||||
- 5.0
|
||||
- :ref:`logging-api`
|
||||
|
||||
* - ``sphinx.writers.html.HTMLTranslator.permalink_text``
|
||||
- 3.5
|
||||
- 5.0
|
||||
- :confval:`html_permalinks_icon`
|
||||
|
||||
* - ``sphinx.writers.html5.HTML5Translator.permalink_text``
|
||||
- 3.5
|
||||
- 5.0
|
||||
- :confval:`html_permalinks_icon`
|
||||
|
||||
* - The ``follow_wrapped`` argument of ``sphinx.util.inspect.signature()``
|
||||
- 3.4
|
||||
- 5.0
|
||||
|
@ -95,6 +95,12 @@ Keys that you may want to override include:
|
||||
A string which will be positioned early in the preamble, designed to
|
||||
contain ``\\PassOptionsToPackage{options}{foo}`` commands.
|
||||
|
||||
.. hint::
|
||||
|
||||
It may be also used for loading LaTeX packages very early in the
|
||||
preamble. For example package ``fancybox`` is incompatible with
|
||||
being loaded via the ``'preamble'`` key, it must be loaded earlier.
|
||||
|
||||
Default: ``''``
|
||||
|
||||
.. versionadded:: 1.4
|
||||
|
@ -1135,6 +1135,23 @@ that use Sphinx's HTMLWriter class.
|
||||
This can now be a string to select the actual text of the link.
|
||||
Previously, only boolean values were accepted.
|
||||
|
||||
.. deprecated:: 3.5
|
||||
This has been replaced by :confval:`html_permalinks`
|
||||
|
||||
.. confval:: html_permalinks
|
||||
|
||||
If true, Sphinx will add "permalinks" for each heading and description
|
||||
environment. Default: ``True``.
|
||||
|
||||
.. versionadded:: 3.5
|
||||
|
||||
.. confval:: html_permalinks_icon
|
||||
|
||||
A text for permalinks for each heading and description environment. HTML
|
||||
tags are allowed. Default: a paragraph sign; ``¶``
|
||||
|
||||
.. versionadded:: 3.5
|
||||
|
||||
.. confval:: html_sidebars
|
||||
|
||||
Custom sidebar templates, must be a dictionary that maps document names to
|
||||
|
@ -569,6 +569,20 @@ __ http://pygments.org/docs/lexers
|
||||
|
||||
print 'Explicit is better than implicit.'
|
||||
|
||||
In order to cross-reference a code-block using either the
|
||||
:rst:role:`ref` or the :rst:role:`numref` role, it is necessary
|
||||
that both :strong:`name` and :strong:`caption` be defined. The
|
||||
argument of :strong:`name` can then be given to :rst:role:`numref`
|
||||
to generate the cross-reference. Example::
|
||||
|
||||
See :numref:`this-py` for an example.
|
||||
|
||||
When using :rst:role:`ref`, it is possible to generate a cross-reference
|
||||
with only :strong:`name` defined, provided an explicit title is
|
||||
given. Example::
|
||||
|
||||
See :ref:`this code snippet <this-py>` for an example.
|
||||
|
||||
.. versionadded:: 1.3
|
||||
|
||||
.. rst:directive:option:: dedent: number
|
||||
@ -1206,20 +1220,29 @@ the definition of the symbol. There is this directive:
|
||||
the following definition. If the definition spans multiple lines, each
|
||||
continuation line must begin with a colon placed at the same column as in
|
||||
the first line.
|
||||
Blank lines are not allowed within ``productionlist`` directive arguments.
|
||||
|
||||
The definition can contain token names which are marked as interpreted text
|
||||
(e.g., "``sum ::= `integer` "+" `integer```") -- this generates
|
||||
cross-references to the productions of these tokens. Outside of the
|
||||
production list, you can reference to token productions using
|
||||
:rst:role:`token`.
|
||||
|
||||
The *productionGroup* argument to :rst:dir:`productionlist` serves to
|
||||
distinguish different sets of production lists that belong to different
|
||||
grammars. Multiple production lists with the same *productionGroup* thus
|
||||
define rules in the same scope.
|
||||
|
||||
Blank lines are not allowed within ``productionlist`` directive arguments.
|
||||
Inside of the production list, tokens implicitly refer to productions
|
||||
from the current group. You can refer to the production of another
|
||||
grammar by prefixing the token with its group name and a colon, e.g,
|
||||
"``otherGroup:sum``". If the group of the token should not be shown in
|
||||
the production, it can be prefixed by a tilde, e.g.,
|
||||
"``~otherGroup:sum``". To refer to a production from an unnamed
|
||||
grammar, the token should be prefixed by a colon, e.g., "``:sum``".
|
||||
|
||||
The definition can contain token names which are marked as interpreted text
|
||||
(e.g. "``sum ::= `integer` "+" `integer```") -- this generates
|
||||
cross-references to the productions of these tokens. Outside of the
|
||||
production list, you can reference to token productions using
|
||||
:rst:role:`token`.
|
||||
However, if you have given a *productionGroup* argument you must prefix the
|
||||
Outside of the production list,
|
||||
if you have given a *productionGroup* argument you must prefix the
|
||||
token name in the cross-reference with the group name and a colon,
|
||||
e.g., "``myGroup:sum``" instead of just "``sum``".
|
||||
If the group should not be shown in the title of the link either
|
||||
|
@ -494,6 +494,10 @@ class Sphinx:
|
||||
documents.
|
||||
* ``''`` if a change in the setting will not need any special rebuild.
|
||||
|
||||
The *types* value takes a list of types that describes the type of
|
||||
configuration value. For example, ``[str]`` is used to describe a
|
||||
configuration that takes string value.
|
||||
|
||||
.. versionchanged:: 0.6
|
||||
Changed *rebuild* from a simple boolean (equivalent to ``''`` or
|
||||
``'env'``) to a string. However, booleans are still accepted and
|
||||
|
@ -1207,6 +1207,16 @@ def validate_html_favicon(app: Sphinx, config: Config) -> None:
|
||||
config.html_favicon = None # type: ignore
|
||||
|
||||
|
||||
def migrate_html_add_permalinks(app: Sphinx, config: Config) -> None:
|
||||
"""Migrate html_add_permalinks to html_permalinks*."""
|
||||
if config.html_add_permalinks:
|
||||
if (isinstance(config.html_add_permalinks, bool) and
|
||||
config.html_add_permalinks is False):
|
||||
config.html_permalinks = False # type: ignore
|
||||
else:
|
||||
config.html_permalinks_icon = html.escape(config.html_add_permalinks) # type: ignore # NOQA
|
||||
|
||||
|
||||
# for compatibility
|
||||
import sphinxcontrib.serializinghtml # NOQA
|
||||
|
||||
@ -1237,7 +1247,9 @@ def setup(app: Sphinx) -> Dict[str, Any]:
|
||||
app.add_config_value('html_sidebars', {}, 'html')
|
||||
app.add_config_value('html_additional_pages', {}, 'html')
|
||||
app.add_config_value('html_domain_indices', True, 'html', [list])
|
||||
app.add_config_value('html_add_permalinks', '¶', 'html')
|
||||
app.add_config_value('html_add_permalinks', None, 'html')
|
||||
app.add_config_value('html_permalinks', True, 'html')
|
||||
app.add_config_value('html_permalinks_icon', '¶', 'html')
|
||||
app.add_config_value('html_use_index', True, 'html')
|
||||
app.add_config_value('html_split_index', False, 'html')
|
||||
app.add_config_value('html_copy_source', True, 'html')
|
||||
@ -1269,6 +1281,7 @@ def setup(app: Sphinx) -> Dict[str, Any]:
|
||||
# event handlers
|
||||
app.connect('config-inited', convert_html_css_files, priority=800)
|
||||
app.connect('config-inited', convert_html_js_files, priority=800)
|
||||
app.connect('config-inited', migrate_html_add_permalinks, priority=800)
|
||||
app.connect('config-inited', validate_html_extra_path, priority=800)
|
||||
app.connect('config-inited', validate_html_static_path, priority=800)
|
||||
app.connect('config-inited', validate_html_logo, priority=800)
|
||||
|
@ -43,7 +43,7 @@ logger = logging.getLogger(__name__)
|
||||
# RE for option descriptions
|
||||
option_desc_re = re.compile(r'((?:/|--|-|\+)?[^\s=]+)(=?\s*.*)')
|
||||
# RE for grammar tokens
|
||||
token_re = re.compile(r'`(\w+)`', re.U)
|
||||
token_re = re.compile(r'`((~?\w*:)?\w+)`', re.U)
|
||||
|
||||
|
||||
class GenericObject(ObjectDescription[str]):
|
||||
@ -449,9 +449,23 @@ def token_xrefs(text: str, productionGroup: str = '') -> List[Node]:
|
||||
if m.start() > pos:
|
||||
txt = text[pos:m.start()]
|
||||
retnodes.append(nodes.Text(txt, txt))
|
||||
refnode = pending_xref(m.group(1), reftype='token', refdomain='std',
|
||||
reftarget=productionGroup + m.group(1))
|
||||
refnode += nodes.literal(m.group(1), m.group(1), classes=['xref'])
|
||||
token = m.group(1)
|
||||
if ':' in token:
|
||||
if token[0] == '~':
|
||||
_, title = token.split(':')
|
||||
target = token[1:]
|
||||
elif token[0] == ':':
|
||||
title = token[1:]
|
||||
target = title
|
||||
else:
|
||||
title = token
|
||||
target = token
|
||||
else:
|
||||
title = token
|
||||
target = productionGroup + token
|
||||
refnode = pending_xref(title, reftype='token', refdomain='std',
|
||||
reftarget=target)
|
||||
refnode += nodes.literal(token, title, classes=['xref'])
|
||||
retnodes.append(refnode)
|
||||
pos = m.end()
|
||||
if pos < len(text):
|
||||
|
@ -23,7 +23,7 @@ from copy import copy
|
||||
from fnmatch import fnmatch
|
||||
from importlib.machinery import EXTENSION_SUFFIXES
|
||||
from os import path
|
||||
from typing import Any, List, Tuple
|
||||
from typing import Any, Generator, List, Tuple
|
||||
|
||||
import sphinx.locale
|
||||
from sphinx import __display_version__, package_dir
|
||||
@ -200,14 +200,46 @@ def is_skipped_module(filename: str, opts: Any, excludes: List[str]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def walk(rootpath: str, excludes: List[str], opts: Any
|
||||
) -> Generator[Tuple[str, List[str], List[str]], None, None]:
|
||||
"""Walk through the directory and list files and subdirectories up."""
|
||||
followlinks = getattr(opts, 'followlinks', False)
|
||||
includeprivate = getattr(opts, 'includeprivate', False)
|
||||
|
||||
for root, subs, files in os.walk(rootpath, followlinks=followlinks):
|
||||
# document only Python module files (that aren't excluded)
|
||||
files = sorted(f for f in files
|
||||
if f.endswith(PY_SUFFIXES) and
|
||||
not is_excluded(path.join(root, f), excludes))
|
||||
|
||||
# remove hidden ('.') and private ('_') directories, as well as
|
||||
# excluded dirs
|
||||
if includeprivate:
|
||||
exclude_prefixes = ('.',) # type: Tuple[str, ...]
|
||||
else:
|
||||
exclude_prefixes = ('.', '_')
|
||||
|
||||
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and
|
||||
not is_excluded(path.join(root, sub), excludes))
|
||||
|
||||
yield root, subs, files
|
||||
|
||||
|
||||
def has_child_module(rootpath: str, excludes: List[str], opts: Any) -> bool:
|
||||
"""Check the given directory contains child modules at least one."""
|
||||
for root, subs, files in walk(rootpath, excludes, opts):
|
||||
if files:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def recurse_tree(rootpath: str, excludes: List[str], opts: Any,
|
||||
user_template_dir: str = None) -> List[str]:
|
||||
"""
|
||||
Look for every file in the directory tree and create the corresponding
|
||||
ReST files.
|
||||
"""
|
||||
followlinks = getattr(opts, 'followlinks', False)
|
||||
includeprivate = getattr(opts, 'includeprivate', False)
|
||||
implicit_namespaces = getattr(opts, 'implicit_namespaces', False)
|
||||
|
||||
# check if the base directory is a package and get its name
|
||||
@ -218,48 +250,36 @@ def recurse_tree(rootpath: str, excludes: List[str], opts: Any,
|
||||
root_package = None
|
||||
|
||||
toplevels = []
|
||||
for root, subs, files in os.walk(rootpath, followlinks=followlinks):
|
||||
# document only Python module files (that aren't excluded)
|
||||
py_files = sorted(f for f in files
|
||||
if f.endswith(PY_SUFFIXES) and
|
||||
not is_excluded(path.join(root, f), excludes))
|
||||
is_pkg = is_packagedir(None, py_files)
|
||||
for root, subs, files in walk(rootpath, excludes, opts):
|
||||
is_pkg = is_packagedir(None, files)
|
||||
is_namespace = not is_pkg and implicit_namespaces
|
||||
if is_pkg:
|
||||
for f in py_files[:]:
|
||||
for f in files[:]:
|
||||
if is_initpy(f):
|
||||
py_files.remove(f)
|
||||
py_files.insert(0, f)
|
||||
files.remove(f)
|
||||
files.insert(0, f)
|
||||
elif root != rootpath:
|
||||
# only accept non-package at toplevel unless using implicit namespaces
|
||||
if not implicit_namespaces:
|
||||
del subs[:]
|
||||
continue
|
||||
# remove hidden ('.') and private ('_') directories, as well as
|
||||
# excluded dirs
|
||||
if includeprivate:
|
||||
exclude_prefixes = ('.',) # type: Tuple[str, ...]
|
||||
else:
|
||||
exclude_prefixes = ('.', '_')
|
||||
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and
|
||||
not is_excluded(path.join(root, sub), excludes))
|
||||
|
||||
if is_pkg or is_namespace:
|
||||
# we are in a package with something to document
|
||||
if subs or len(py_files) > 1 or not is_skipped_package(root, opts):
|
||||
if subs or len(files) > 1 or not is_skipped_package(root, opts):
|
||||
subpackage = root[len(rootpath):].lstrip(path.sep).\
|
||||
replace(path.sep, '.')
|
||||
# if this is not a namespace or
|
||||
# a namespace and there is something there to document
|
||||
if not is_namespace or len(py_files) > 0:
|
||||
if not is_namespace or has_child_module(root, excludes, opts):
|
||||
create_package_file(root, root_package, subpackage,
|
||||
py_files, opts, subs, is_namespace, excludes,
|
||||
files, opts, subs, is_namespace, excludes,
|
||||
user_template_dir)
|
||||
toplevels.append(module_join(root_package, subpackage))
|
||||
else:
|
||||
# if we are at the root level, we don't require it to be a package
|
||||
assert root == rootpath and root_package is None
|
||||
for py_file in py_files:
|
||||
for py_file in files:
|
||||
if not is_skipped_module(path.join(rootpath, py_file), opts, excludes):
|
||||
module = py_file.split('.')[0]
|
||||
create_module_file(root_package, module, opts, user_template_dir)
|
||||
|
@ -54,6 +54,19 @@ _default_regex = re.compile(
|
||||
_SINGLETONS = ("None", "True", "False", "Ellipsis")
|
||||
|
||||
|
||||
def _convert_type_spec(_type: str, translations: Dict[str, str] = {}) -> str:
|
||||
"""Convert type specification to reference in reST."""
|
||||
if _type in translations:
|
||||
return translations[_type]
|
||||
else:
|
||||
if _type == 'None':
|
||||
return ':obj:`None`'
|
||||
else:
|
||||
return ':class:`%s`' % _type
|
||||
|
||||
return _type
|
||||
|
||||
|
||||
class GoogleDocstring:
|
||||
"""Convert Google style docstrings to reStructuredText.
|
||||
|
||||
@ -260,6 +273,10 @@ class GoogleDocstring:
|
||||
|
||||
if prefer_type and not _type:
|
||||
_type, _name = _name, _type
|
||||
|
||||
if _type and self._config.napoleon_preprocess_types:
|
||||
_type = _convert_type_spec(_type, self._config.napoleon_type_aliases or {})
|
||||
|
||||
indent = self._get_indent(line) + 1
|
||||
_descs = [_desc] + self._dedent(self._consume_indented_block(indent))
|
||||
_descs = self.__class__(_descs, self._config).lines()
|
||||
@ -288,7 +305,8 @@ class GoogleDocstring:
|
||||
_descs = self.__class__(_descs, self._config).lines()
|
||||
return _type, _descs
|
||||
|
||||
def _consume_returns_section(self) -> List[Tuple[str, str, List[str]]]:
|
||||
def _consume_returns_section(self, preprocess_types: bool = False
|
||||
) -> List[Tuple[str, str, List[str]]]:
|
||||
lines = self._dedent(self._consume_to_next_section())
|
||||
if lines:
|
||||
before, colon, after = self._partition_field_on_colon(lines[0])
|
||||
@ -302,6 +320,10 @@ class GoogleDocstring:
|
||||
|
||||
_type = before
|
||||
|
||||
if (_type and preprocess_types and
|
||||
self._config.napoleon_preprocess_types):
|
||||
_type = _convert_type_spec(_type, self._config.napoleon_type_aliases or {})
|
||||
|
||||
_desc = self.__class__(_desc, self._config).lines()
|
||||
return [(_name, _type, _desc,)]
|
||||
else:
|
||||
@ -647,7 +669,7 @@ class GoogleDocstring:
|
||||
return self._format_fields(section, self._consume_fields())
|
||||
|
||||
def _parse_custom_returns_style_section(self, section: str) -> List[str]:
|
||||
fields = self._consume_returns_section()
|
||||
fields = self._consume_returns_section(preprocess_types=True)
|
||||
return self._format_fields(section, fields)
|
||||
|
||||
def _parse_usage_section(self, section: str) -> List[str]:
|
||||
@ -779,7 +801,7 @@ class GoogleDocstring:
|
||||
return self._format_fields(_('Warns'), self._consume_fields())
|
||||
|
||||
def _parse_yields_section(self, section: str) -> List[str]:
|
||||
fields = self._consume_returns_section()
|
||||
fields = self._consume_returns_section(preprocess_types=True)
|
||||
return self._format_fields(_('Yields'), fields)
|
||||
|
||||
def _partition_field_on_colon(self, line: str) -> Tuple[str, str, str]:
|
||||
@ -1171,7 +1193,8 @@ class NumpyDocstring(GoogleDocstring):
|
||||
_desc = self.__class__(_desc, self._config).lines()
|
||||
return _name, _type, _desc
|
||||
|
||||
def _consume_returns_section(self) -> List[Tuple[str, str, List[str]]]:
|
||||
def _consume_returns_section(self, preprocess_types: bool = False
|
||||
) -> List[Tuple[str, str, List[str]]]:
|
||||
return self._consume_fields(prefer_type=True)
|
||||
|
||||
def _consume_section_header(self) -> str:
|
||||
|
@ -6,7 +6,7 @@
|
||||
%
|
||||
|
||||
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
|
||||
\ProvidesPackage{sphinx}[2019/09/02 v2.3.0 LaTeX package (Sphinx markup)]
|
||||
\ProvidesPackage{sphinx}[2021/01/23 v3.5.0 LaTeX package (Sphinx markup)]
|
||||
|
||||
% provides \ltx@ifundefined
|
||||
% (many packages load ltxcmds: graphicx does for pdftex and lualatex but
|
||||
@ -844,6 +844,12 @@
|
||||
|
||||
|
||||
%% NUMBERING OF FIGURES, TABLES, AND LITERAL BLOCKS
|
||||
|
||||
% Everything is delayed to \begin{document} to allow hyperref patches into
|
||||
% \newcounter to solve duplicate label problems for internal hyperlinks to
|
||||
% code listings (literalblock counter). User or extension re-definitions of
|
||||
% \theliteralblock, et al., thus have also to be delayed. (changed at 3.5.0)
|
||||
\AtBeginDocument{%
|
||||
\ltx@ifundefined{c@chapter}
|
||||
{\newcounter{literalblock}}%
|
||||
{\newcounter{literalblock}[chapter]%
|
||||
@ -884,62 +890,52 @@
|
||||
\g@addto@macro\spx@preBthefigure{\fi}}%
|
||||
\fi
|
||||
\ifnum\spx@opt@numfigreset>1
|
||||
\AtBeginDocument{%
|
||||
\@addtoreset{figure}{section}%
|
||||
\@addtoreset{table}{section}%
|
||||
\@addtoreset{literalblock}{section}%
|
||||
\ifspx@opt@mathnumfig
|
||||
\@addtoreset{equation}{section}%
|
||||
\fi%
|
||||
}%
|
||||
\g@addto@macro\spx@preAthefigure{\ifnum\c@section>\z@\arabic{section}.}%
|
||||
\g@addto@macro\spx@preBthefigure{\fi}%
|
||||
\fi
|
||||
\ifnum\spx@opt@numfigreset>2
|
||||
\AtBeginDocument{%
|
||||
\@addtoreset{figure}{subsection}%
|
||||
\@addtoreset{table}{subsection}%
|
||||
\@addtoreset{literalblock}{subsection}%
|
||||
\ifspx@opt@mathnumfig
|
||||
\@addtoreset{equation}{subsection}%
|
||||
\fi%
|
||||
}%
|
||||
\g@addto@macro\spx@preAthefigure{\ifnum\c@subsection>\z@\arabic{subsection}.}%
|
||||
\g@addto@macro\spx@preBthefigure{\fi}%
|
||||
\fi
|
||||
\ifnum\spx@opt@numfigreset>3
|
||||
\AtBeginDocument{%
|
||||
\@addtoreset{figure}{subsubsection}%
|
||||
\@addtoreset{table}{subsubsection}%
|
||||
\@addtoreset{literalblock}{subsubsection}%
|
||||
\ifspx@opt@mathnumfig
|
||||
\@addtoreset{equation}{subsubsection}%
|
||||
\fi%
|
||||
}%
|
||||
\g@addto@macro\spx@preAthefigure{\ifnum\c@subsubsection>\z@\arabic{subsubsection}.}%
|
||||
\g@addto@macro\spx@preBthefigure{\fi}%
|
||||
\fi
|
||||
\ifnum\spx@opt@numfigreset>4
|
||||
\AtBeginDocument{%
|
||||
\@addtoreset{figure}{paragraph}%
|
||||
\@addtoreset{table}{paragraph}%
|
||||
\@addtoreset{literalblock}{paragraph}%
|
||||
\ifspx@opt@mathnumfig
|
||||
\@addtoreset{equation}{paragraph}%
|
||||
\fi%
|
||||
}%
|
||||
\g@addto@macro\spx@preAthefigure{\ifnum\c@subparagraph>\z@\arabic{subparagraph}.}%
|
||||
\g@addto@macro\spx@preBthefigure{\fi}%
|
||||
\fi
|
||||
\ifnum\spx@opt@numfigreset>5
|
||||
\AtBeginDocument{%
|
||||
\@addtoreset{figure}{subparagraph}%
|
||||
\@addtoreset{table}{subparagraph}%
|
||||
\@addtoreset{literalblock}{subparagraph}%
|
||||
\ifspx@opt@mathnumfig
|
||||
\@addtoreset{equation}{subparagraph}%
|
||||
\fi%
|
||||
}%
|
||||
\g@addto@macro\spx@preAthefigure{\ifnum\c@subsubparagraph>\z@\arabic{subsubparagraph}.}%
|
||||
\g@addto@macro\spx@preBthefigure{\fi}%
|
||||
\fi
|
||||
@ -956,7 +952,7 @@
|
||||
\g@addto@macro\theequation{\arabic{equation}}%
|
||||
\fi
|
||||
\fi
|
||||
|
||||
}% end of big \AtBeginDocument
|
||||
|
||||
%% LITERAL BLOCKS
|
||||
%
|
||||
@ -966,9 +962,9 @@
|
||||
% - with possibly of a top caption, non-separable by pagebreak.
|
||||
% - and usable inside tables or footnotes ("footnotehyper-sphinx").
|
||||
|
||||
% For extensions which use \OriginalVerbatim and compatibility with Sphinx <
|
||||
% 1.5, we define and use these when (unmodified) Verbatim will be needed. But
|
||||
% Sphinx >= 1.5 does not modify the \Verbatim macro anymore.
|
||||
% Prior to Sphinx 1.5, \Verbatim and \endVerbatim were modified by Sphinx.
|
||||
% The aliases defined here are used in sphinxVerbatim environment and can
|
||||
% serve as hook-points with no need to modify \Verbatim itself.
|
||||
\let\OriginalVerbatim \Verbatim
|
||||
\let\endOriginalVerbatim\endVerbatim
|
||||
|
||||
|
2027
sphinx/themes/basic/static/underscore-1.12.0.js
Normal file
2027
sphinx/themes/basic/static/underscore-1.12.0.js
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,999 +0,0 @@
|
||||
// Underscore.js 1.3.1
|
||||
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
|
||||
// Underscore is freely distributable under the MIT license.
|
||||
// Portions of Underscore are inspired or borrowed from Prototype,
|
||||
// Oliver Steele's Functional, and John Resig's Micro-Templating.
|
||||
// For all details and documentation:
|
||||
// http://documentcloud.github.com/underscore
|
||||
|
||||
(function() {
|
||||
|
||||
// Baseline setup
|
||||
// --------------
|
||||
|
||||
// Establish the root object, `window` in the browser, or `global` on the server.
|
||||
var root = this;
|
||||
|
||||
// Save the previous value of the `_` variable.
|
||||
var previousUnderscore = root._;
|
||||
|
||||
// Establish the object that gets returned to break out of a loop iteration.
|
||||
var breaker = {};
|
||||
|
||||
// Save bytes in the minified (but not gzipped) version:
|
||||
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
|
||||
|
||||
// Create quick reference variables for speed access to core prototypes.
|
||||
var slice = ArrayProto.slice,
|
||||
unshift = ArrayProto.unshift,
|
||||
toString = ObjProto.toString,
|
||||
hasOwnProperty = ObjProto.hasOwnProperty;
|
||||
|
||||
// All **ECMAScript 5** native function implementations that we hope to use
|
||||
// are declared here.
|
||||
var
|
||||
nativeForEach = ArrayProto.forEach,
|
||||
nativeMap = ArrayProto.map,
|
||||
nativeReduce = ArrayProto.reduce,
|
||||
nativeReduceRight = ArrayProto.reduceRight,
|
||||
nativeFilter = ArrayProto.filter,
|
||||
nativeEvery = ArrayProto.every,
|
||||
nativeSome = ArrayProto.some,
|
||||
nativeIndexOf = ArrayProto.indexOf,
|
||||
nativeLastIndexOf = ArrayProto.lastIndexOf,
|
||||
nativeIsArray = Array.isArray,
|
||||
nativeKeys = Object.keys,
|
||||
nativeBind = FuncProto.bind;
|
||||
|
||||
// Create a safe reference to the Underscore object for use below.
|
||||
var _ = function(obj) { return new wrapper(obj); };
|
||||
|
||||
// Export the Underscore object for **Node.js**, with
|
||||
// backwards-compatibility for the old `require()` API. If we're in
|
||||
// the browser, add `_` as a global object via a string identifier,
|
||||
// for Closure Compiler "advanced" mode.
|
||||
if (typeof exports !== 'undefined') {
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
exports = module.exports = _;
|
||||
}
|
||||
exports._ = _;
|
||||
} else {
|
||||
root['_'] = _;
|
||||
}
|
||||
|
||||
// Current version.
|
||||
_.VERSION = '1.3.1';
|
||||
|
||||
// Collection Functions
|
||||
// --------------------
|
||||
|
||||
// The cornerstone, an `each` implementation, aka `forEach`.
|
||||
// Handles objects with the built-in `forEach`, arrays, and raw objects.
|
||||
// Delegates to **ECMAScript 5**'s native `forEach` if available.
|
||||
var each = _.each = _.forEach = function(obj, iterator, context) {
|
||||
if (obj == null) return;
|
||||
if (nativeForEach && obj.forEach === nativeForEach) {
|
||||
obj.forEach(iterator, context);
|
||||
} else if (obj.length === +obj.length) {
|
||||
for (var i = 0, l = obj.length; i < l; i++) {
|
||||
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
|
||||
}
|
||||
} else {
|
||||
for (var key in obj) {
|
||||
if (_.has(obj, key)) {
|
||||
if (iterator.call(context, obj[key], key, obj) === breaker) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Return the results of applying the iterator to each element.
|
||||
// Delegates to **ECMAScript 5**'s native `map` if available.
|
||||
_.map = _.collect = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
results[results.length] = iterator.call(context, value, index, list);
|
||||
});
|
||||
if (obj.length === +obj.length) results.length = obj.length;
|
||||
return results;
|
||||
};
|
||||
|
||||
// **Reduce** builds up a single result from a list of values, aka `inject`,
|
||||
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
|
||||
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
|
||||
var initial = arguments.length > 2;
|
||||
if (obj == null) obj = [];
|
||||
if (nativeReduce && obj.reduce === nativeReduce) {
|
||||
if (context) iterator = _.bind(iterator, context);
|
||||
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
|
||||
}
|
||||
each(obj, function(value, index, list) {
|
||||
if (!initial) {
|
||||
memo = value;
|
||||
initial = true;
|
||||
} else {
|
||||
memo = iterator.call(context, memo, value, index, list);
|
||||
}
|
||||
});
|
||||
if (!initial) throw new TypeError('Reduce of empty array with no initial value');
|
||||
return memo;
|
||||
};
|
||||
|
||||
// The right-associative version of reduce, also known as `foldr`.
|
||||
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
|
||||
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
|
||||
var initial = arguments.length > 2;
|
||||
if (obj == null) obj = [];
|
||||
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
|
||||
if (context) iterator = _.bind(iterator, context);
|
||||
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
|
||||
}
|
||||
var reversed = _.toArray(obj).reverse();
|
||||
if (context && !initial) iterator = _.bind(iterator, context);
|
||||
return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
|
||||
};
|
||||
|
||||
// Return the first value which passes a truth test. Aliased as `detect`.
|
||||
_.find = _.detect = function(obj, iterator, context) {
|
||||
var result;
|
||||
any(obj, function(value, index, list) {
|
||||
if (iterator.call(context, value, index, list)) {
|
||||
result = value;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Return all the elements that pass a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `filter` if available.
|
||||
// Aliased as `select`.
|
||||
_.filter = _.select = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (iterator.call(context, value, index, list)) results[results.length] = value;
|
||||
});
|
||||
return results;
|
||||
};
|
||||
|
||||
// Return all the elements for which a truth test fails.
|
||||
_.reject = function(obj, iterator, context) {
|
||||
var results = [];
|
||||
if (obj == null) return results;
|
||||
each(obj, function(value, index, list) {
|
||||
if (!iterator.call(context, value, index, list)) results[results.length] = value;
|
||||
});
|
||||
return results;
|
||||
};
|
||||
|
||||
// Determine whether all of the elements match a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `every` if available.
|
||||
// Aliased as `all`.
|
||||
_.every = _.all = function(obj, iterator, context) {
|
||||
var result = true;
|
||||
if (obj == null) return result;
|
||||
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Determine if at least one element in the object matches a truth test.
|
||||
// Delegates to **ECMAScript 5**'s native `some` if available.
|
||||
// Aliased as `any`.
|
||||
var any = _.some = _.any = function(obj, iterator, context) {
|
||||
iterator || (iterator = _.identity);
|
||||
var result = false;
|
||||
if (obj == null) return result;
|
||||
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
|
||||
each(obj, function(value, index, list) {
|
||||
if (result || (result = iterator.call(context, value, index, list))) return breaker;
|
||||
});
|
||||
return !!result;
|
||||
};
|
||||
|
||||
// Determine if a given value is included in the array or object using `===`.
|
||||
// Aliased as `contains`.
|
||||
_.include = _.contains = function(obj, target) {
|
||||
var found = false;
|
||||
if (obj == null) return found;
|
||||
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
|
||||
found = any(obj, function(value) {
|
||||
return value === target;
|
||||
});
|
||||
return found;
|
||||
};
|
||||
|
||||
// Invoke a method (with arguments) on every item in a collection.
|
||||
_.invoke = function(obj, method) {
|
||||
var args = slice.call(arguments, 2);
|
||||
return _.map(obj, function(value) {
|
||||
return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
|
||||
});
|
||||
};
|
||||
|
||||
// Convenience version of a common use case of `map`: fetching a property.
|
||||
_.pluck = function(obj, key) {
|
||||
return _.map(obj, function(value){ return value[key]; });
|
||||
};
|
||||
|
||||
// Return the maximum element or (element-based computation).
|
||||
_.max = function(obj, iterator, context) {
|
||||
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
|
||||
if (!iterator && _.isEmpty(obj)) return -Infinity;
|
||||
var result = {computed : -Infinity};
|
||||
each(obj, function(value, index, list) {
|
||||
var computed = iterator ? iterator.call(context, value, index, list) : value;
|
||||
computed >= result.computed && (result = {value : value, computed : computed});
|
||||
});
|
||||
return result.value;
|
||||
};
|
||||
|
||||
// Return the minimum element (or element-based computation).
|
||||
_.min = function(obj, iterator, context) {
|
||||
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
|
||||
if (!iterator && _.isEmpty(obj)) return Infinity;
|
||||
var result = {computed : Infinity};
|
||||
each(obj, function(value, index, list) {
|
||||
var computed = iterator ? iterator.call(context, value, index, list) : value;
|
||||
computed < result.computed && (result = {value : value, computed : computed});
|
||||
});
|
||||
return result.value;
|
||||
};
|
||||
|
||||
// Shuffle an array.
|
||||
_.shuffle = function(obj) {
|
||||
var shuffled = [], rand;
|
||||
each(obj, function(value, index, list) {
|
||||
if (index == 0) {
|
||||
shuffled[0] = value;
|
||||
} else {
|
||||
rand = Math.floor(Math.random() * (index + 1));
|
||||
shuffled[index] = shuffled[rand];
|
||||
shuffled[rand] = value;
|
||||
}
|
||||
});
|
||||
return shuffled;
|
||||
};
|
||||
|
||||
// Sort the object's values by a criterion produced by an iterator.
|
||||
_.sortBy = function(obj, iterator, context) {
|
||||
return _.pluck(_.map(obj, function(value, index, list) {
|
||||
return {
|
||||
value : value,
|
||||
criteria : iterator.call(context, value, index, list)
|
||||
};
|
||||
}).sort(function(left, right) {
|
||||
var a = left.criteria, b = right.criteria;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
}), 'value');
|
||||
};
|
||||
|
||||
// Groups the object's values by a criterion. Pass either a string attribute
|
||||
// to group by, or a function that returns the criterion.
|
||||
_.groupBy = function(obj, val) {
|
||||
var result = {};
|
||||
var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
|
||||
each(obj, function(value, index) {
|
||||
var key = iterator(value, index);
|
||||
(result[key] || (result[key] = [])).push(value);
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
// Use a comparator function to figure out at what index an object should
|
||||
// be inserted so as to maintain order. Uses binary search.
|
||||
_.sortedIndex = function(array, obj, iterator) {
|
||||
iterator || (iterator = _.identity);
|
||||
var low = 0, high = array.length;
|
||||
while (low < high) {
|
||||
var mid = (low + high) >> 1;
|
||||
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
|
||||
}
|
||||
return low;
|
||||
};
|
||||
|
||||
// Safely convert anything iterable into a real, live array.
|
||||
_.toArray = function(iterable) {
|
||||
if (!iterable) return [];
|
||||
if (iterable.toArray) return iterable.toArray();
|
||||
if (_.isArray(iterable)) return slice.call(iterable);
|
||||
if (_.isArguments(iterable)) return slice.call(iterable);
|
||||
return _.values(iterable);
|
||||
};
|
||||
|
||||
// Return the number of elements in an object.
|
||||
_.size = function(obj) {
|
||||
return _.toArray(obj).length;
|
||||
};
|
||||
|
||||
// Array Functions
|
||||
// ---------------
|
||||
|
||||
// Get the first element of an array. Passing **n** will return the first N
|
||||
// values in the array. Aliased as `head`. The **guard** check allows it to work
|
||||
// with `_.map`.
|
||||
_.first = _.head = function(array, n, guard) {
|
||||
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
|
||||
};
|
||||
|
||||
// Returns everything but the last entry of the array. Especcialy useful on
|
||||
// the arguments object. Passing **n** will return all the values in
|
||||
// the array, excluding the last N. The **guard** check allows it to work with
|
||||
// `_.map`.
|
||||
_.initial = function(array, n, guard) {
|
||||
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
|
||||
};
|
||||
|
||||
// Get the last element of an array. Passing **n** will return the last N
|
||||
// values in the array. The **guard** check allows it to work with `_.map`.
|
||||
_.last = function(array, n, guard) {
|
||||
if ((n != null) && !guard) {
|
||||
return slice.call(array, Math.max(array.length - n, 0));
|
||||
} else {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
};
|
||||
|
||||
// Returns everything but the first entry of the array. Aliased as `tail`.
|
||||
// Especially useful on the arguments object. Passing an **index** will return
|
||||
// the rest of the values in the array from that index onward. The **guard**
|
||||
// check allows it to work with `_.map`.
|
||||
_.rest = _.tail = function(array, index, guard) {
|
||||
return slice.call(array, (index == null) || guard ? 1 : index);
|
||||
};
|
||||
|
||||
// Trim out all falsy values from an array.
|
||||
_.compact = function(array) {
|
||||
return _.filter(array, function(value){ return !!value; });
|
||||
};
|
||||
|
||||
// Return a completely flattened version of an array.
|
||||
_.flatten = function(array, shallow) {
|
||||
return _.reduce(array, function(memo, value) {
|
||||
if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
|
||||
memo[memo.length] = value;
|
||||
return memo;
|
||||
}, []);
|
||||
};
|
||||
|
||||
// Return a version of the array that does not contain the specified value(s).
|
||||
_.without = function(array) {
|
||||
return _.difference(array, slice.call(arguments, 1));
|
||||
};
|
||||
|
||||
// Produce a duplicate-free version of the array. If the array has already
|
||||
// been sorted, you have the option of using a faster algorithm.
|
||||
// Aliased as `unique`.
|
||||
_.uniq = _.unique = function(array, isSorted, iterator) {
|
||||
var initial = iterator ? _.map(array, iterator) : array;
|
||||
var result = [];
|
||||
_.reduce(initial, function(memo, el, i) {
|
||||
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
|
||||
memo[memo.length] = el;
|
||||
result[result.length] = array[i];
|
||||
}
|
||||
return memo;
|
||||
}, []);
|
||||
return result;
|
||||
};
|
||||
|
||||
// Produce an array that contains the union: each distinct element from all of
|
||||
// the passed-in arrays.
|
||||
_.union = function() {
|
||||
return _.uniq(_.flatten(arguments, true));
|
||||
};
|
||||
|
||||
// Produce an array that contains every item shared between all the
|
||||
// passed-in arrays. (Aliased as "intersect" for back-compat.)
|
||||
_.intersection = _.intersect = function(array) {
|
||||
var rest = slice.call(arguments, 1);
|
||||
return _.filter(_.uniq(array), function(item) {
|
||||
return _.every(rest, function(other) {
|
||||
return _.indexOf(other, item) >= 0;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Take the difference between one array and a number of other arrays.
|
||||
// Only the elements present in just the first array will remain.
|
||||
_.difference = function(array) {
|
||||
var rest = _.flatten(slice.call(arguments, 1));
|
||||
return _.filter(array, function(value){ return !_.include(rest, value); });
|
||||
};
|
||||
|
||||
// Zip together multiple lists into a single array -- elements that share
|
||||
// an index go together.
|
||||
_.zip = function() {
|
||||
var args = slice.call(arguments);
|
||||
var length = _.max(_.pluck(args, 'length'));
|
||||
var results = new Array(length);
|
||||
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
|
||||
return results;
|
||||
};
|
||||
|
||||
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
|
||||
// we need this function. Return the position of the first occurrence of an
|
||||
// item in an array, or -1 if the item is not included in the array.
|
||||
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
|
||||
// If the array is large and already in sort order, pass `true`
|
||||
// for **isSorted** to use binary search.
|
||||
_.indexOf = function(array, item, isSorted) {
|
||||
if (array == null) return -1;
|
||||
var i, l;
|
||||
if (isSorted) {
|
||||
i = _.sortedIndex(array, item);
|
||||
return array[i] === item ? i : -1;
|
||||
}
|
||||
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
|
||||
for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
|
||||
_.lastIndexOf = function(array, item) {
|
||||
if (array == null) return -1;
|
||||
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
|
||||
var i = array.length;
|
||||
while (i--) if (i in array && array[i] === item) return i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
// Generate an integer Array containing an arithmetic progression. A port of
|
||||
// the native Python `range()` function. See
|
||||
// [the Python documentation](http://docs.python.org/library/functions.html#range).
|
||||
_.range = function(start, stop, step) {
|
||||
if (arguments.length <= 1) {
|
||||
stop = start || 0;
|
||||
start = 0;
|
||||
}
|
||||
step = arguments[2] || 1;
|
||||
|
||||
var len = Math.max(Math.ceil((stop - start) / step), 0);
|
||||
var idx = 0;
|
||||
var range = new Array(len);
|
||||
|
||||
while(idx < len) {
|
||||
range[idx++] = start;
|
||||
start += step;
|
||||
}
|
||||
|
||||
return range;
|
||||
};
|
||||
|
||||
// Function (ahem) Functions
|
||||
// ------------------
|
||||
|
||||
// Reusable constructor function for prototype setting.
|
||||
var ctor = function(){};
|
||||
|
||||
// Create a function bound to a given object (assigning `this`, and arguments,
|
||||
// optionally). Binding with arguments is also known as `curry`.
|
||||
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
|
||||
// We check for `func.bind` first, to fail fast when `func` is undefined.
|
||||
_.bind = function bind(func, context) {
|
||||
var bound, args;
|
||||
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
|
||||
if (!_.isFunction(func)) throw new TypeError;
|
||||
args = slice.call(arguments, 2);
|
||||
return bound = function() {
|
||||
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
|
||||
ctor.prototype = func.prototype;
|
||||
var self = new ctor;
|
||||
var result = func.apply(self, args.concat(slice.call(arguments)));
|
||||
if (Object(result) === result) return result;
|
||||
return self;
|
||||
};
|
||||
};
|
||||
|
||||
// Bind all of an object's methods to that object. Useful for ensuring that
|
||||
// all callbacks defined on an object belong to it.
|
||||
_.bindAll = function(obj) {
|
||||
var funcs = slice.call(arguments, 1);
|
||||
if (funcs.length == 0) funcs = _.functions(obj);
|
||||
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Memoize an expensive function by storing its results.
|
||||
_.memoize = function(func, hasher) {
|
||||
var memo = {};
|
||||
hasher || (hasher = _.identity);
|
||||
return function() {
|
||||
var key = hasher.apply(this, arguments);
|
||||
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
|
||||
};
|
||||
};
|
||||
|
||||
// Delays a function for the given number of milliseconds, and then calls
|
||||
// it with the arguments supplied.
|
||||
_.delay = function(func, wait) {
|
||||
var args = slice.call(arguments, 2);
|
||||
return setTimeout(function(){ return func.apply(func, args); }, wait);
|
||||
};
|
||||
|
||||
// Defers a function, scheduling it to run after the current call stack has
|
||||
// cleared.
|
||||
_.defer = function(func) {
|
||||
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
|
||||
};
|
||||
|
||||
// Returns a function, that, when invoked, will only be triggered at most once
|
||||
// during a given window of time.
|
||||
_.throttle = function(func, wait) {
|
||||
var context, args, timeout, throttling, more;
|
||||
var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
|
||||
return function() {
|
||||
context = this; args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
if (more) func.apply(context, args);
|
||||
whenDone();
|
||||
};
|
||||
if (!timeout) timeout = setTimeout(later, wait);
|
||||
if (throttling) {
|
||||
more = true;
|
||||
} else {
|
||||
func.apply(context, args);
|
||||
}
|
||||
whenDone();
|
||||
throttling = true;
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function, that, as long as it continues to be invoked, will not
|
||||
// be triggered. The function will be called after it stops being called for
|
||||
// N milliseconds.
|
||||
_.debounce = function(func, wait) {
|
||||
var timeout;
|
||||
return function() {
|
||||
var context = this, args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
func.apply(context, args);
|
||||
};
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function that will be executed at most one time, no matter how
|
||||
// often you call it. Useful for lazy initialization.
|
||||
_.once = function(func) {
|
||||
var ran = false, memo;
|
||||
return function() {
|
||||
if (ran) return memo;
|
||||
ran = true;
|
||||
return memo = func.apply(this, arguments);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns the first function passed as an argument to the second,
|
||||
// allowing you to adjust arguments, run code before and after, and
|
||||
// conditionally execute the original function.
|
||||
_.wrap = function(func, wrapper) {
|
||||
return function() {
|
||||
var args = [func].concat(slice.call(arguments, 0));
|
||||
return wrapper.apply(this, args);
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function that is the composition of a list of functions, each
|
||||
// consuming the return value of the function that follows.
|
||||
_.compose = function() {
|
||||
var funcs = arguments;
|
||||
return function() {
|
||||
var args = arguments;
|
||||
for (var i = funcs.length - 1; i >= 0; i--) {
|
||||
args = [funcs[i].apply(this, args)];
|
||||
}
|
||||
return args[0];
|
||||
};
|
||||
};
|
||||
|
||||
// Returns a function that will only be executed after being called N times.
|
||||
_.after = function(times, func) {
|
||||
if (times <= 0) return func();
|
||||
return function() {
|
||||
if (--times < 1) { return func.apply(this, arguments); }
|
||||
};
|
||||
};
|
||||
|
||||
// Object Functions
|
||||
// ----------------
|
||||
|
||||
// Retrieve the names of an object's properties.
|
||||
// Delegates to **ECMAScript 5**'s native `Object.keys`
|
||||
_.keys = nativeKeys || function(obj) {
|
||||
if (obj !== Object(obj)) throw new TypeError('Invalid object');
|
||||
var keys = [];
|
||||
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
|
||||
return keys;
|
||||
};
|
||||
|
||||
// Retrieve the values of an object's properties.
|
||||
_.values = function(obj) {
|
||||
return _.map(obj, _.identity);
|
||||
};
|
||||
|
||||
// Return a sorted list of the function names available on the object.
|
||||
// Aliased as `methods`
|
||||
_.functions = _.methods = function(obj) {
|
||||
var names = [];
|
||||
for (var key in obj) {
|
||||
if (_.isFunction(obj[key])) names.push(key);
|
||||
}
|
||||
return names.sort();
|
||||
};
|
||||
|
||||
// Extend a given object with all the properties in passed-in object(s).
|
||||
_.extend = function(obj) {
|
||||
each(slice.call(arguments, 1), function(source) {
|
||||
for (var prop in source) {
|
||||
obj[prop] = source[prop];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Fill in a given object with default properties.
|
||||
_.defaults = function(obj) {
|
||||
each(slice.call(arguments, 1), function(source) {
|
||||
for (var prop in source) {
|
||||
if (obj[prop] == null) obj[prop] = source[prop];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Create a (shallow-cloned) duplicate of an object.
|
||||
_.clone = function(obj) {
|
||||
if (!_.isObject(obj)) return obj;
|
||||
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
|
||||
};
|
||||
|
||||
// Invokes interceptor with the obj, and then returns obj.
|
||||
// The primary purpose of this method is to "tap into" a method chain, in
|
||||
// order to perform operations on intermediate results within the chain.
|
||||
_.tap = function(obj, interceptor) {
|
||||
interceptor(obj);
|
||||
return obj;
|
||||
};
|
||||
|
||||
// Internal recursive comparison function.
|
||||
function eq(a, b, stack) {
|
||||
// Identical objects are equal. `0 === -0`, but they aren't identical.
|
||||
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
|
||||
if (a === b) return a !== 0 || 1 / a == 1 / b;
|
||||
// A strict comparison is necessary because `null == undefined`.
|
||||
if (a == null || b == null) return a === b;
|
||||
// Unwrap any wrapped objects.
|
||||
if (a._chain) a = a._wrapped;
|
||||
if (b._chain) b = b._wrapped;
|
||||
// Invoke a custom `isEqual` method if one is provided.
|
||||
if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
|
||||
if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
|
||||
// Compare `[[Class]]` names.
|
||||
var className = toString.call(a);
|
||||
if (className != toString.call(b)) return false;
|
||||
switch (className) {
|
||||
// Strings, numbers, dates, and booleans are compared by value.
|
||||
case '[object String]':
|
||||
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
|
||||
// equivalent to `new String("5")`.
|
||||
return a == String(b);
|
||||
case '[object Number]':
|
||||
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
|
||||
// other numeric values.
|
||||
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
|
||||
case '[object Date]':
|
||||
case '[object Boolean]':
|
||||
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
|
||||
// millisecond representations. Note that invalid dates with millisecond representations
|
||||
// of `NaN` are not equivalent.
|
||||
return +a == +b;
|
||||
// RegExps are compared by their source patterns and flags.
|
||||
case '[object RegExp]':
|
||||
return a.source == b.source &&
|
||||
a.global == b.global &&
|
||||
a.multiline == b.multiline &&
|
||||
a.ignoreCase == b.ignoreCase;
|
||||
}
|
||||
if (typeof a != 'object' || typeof b != 'object') return false;
|
||||
// Assume equality for cyclic structures. The algorithm for detecting cyclic
|
||||
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
|
||||
var length = stack.length;
|
||||
while (length--) {
|
||||
// Linear search. Performance is inversely proportional to the number of
|
||||
// unique nested structures.
|
||||
if (stack[length] == a) return true;
|
||||
}
|
||||
// Add the first object to the stack of traversed objects.
|
||||
stack.push(a);
|
||||
var size = 0, result = true;
|
||||
// Recursively compare objects and arrays.
|
||||
if (className == '[object Array]') {
|
||||
// Compare array lengths to determine if a deep comparison is necessary.
|
||||
size = a.length;
|
||||
result = size == b.length;
|
||||
if (result) {
|
||||
// Deep compare the contents, ignoring non-numeric properties.
|
||||
while (size--) {
|
||||
// Ensure commutative equality for sparse arrays.
|
||||
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Objects with different constructors are not equivalent.
|
||||
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
|
||||
// Deep compare objects.
|
||||
for (var key in a) {
|
||||
if (_.has(a, key)) {
|
||||
// Count the expected number of properties.
|
||||
size++;
|
||||
// Deep compare each member.
|
||||
if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
|
||||
}
|
||||
}
|
||||
// Ensure that both objects contain the same number of properties.
|
||||
if (result) {
|
||||
for (key in b) {
|
||||
if (_.has(b, key) && !(size--)) break;
|
||||
}
|
||||
result = !size;
|
||||
}
|
||||
}
|
||||
// Remove the first object from the stack of traversed objects.
|
||||
stack.pop();
|
||||
return result;
|
||||
}
|
||||
|
||||
// Perform a deep comparison to check if two objects are equal.
|
||||
_.isEqual = function(a, b) {
|
||||
return eq(a, b, []);
|
||||
};
|
||||
|
||||
// Is a given array, string, or object empty?
|
||||
// An "empty" object has no enumerable own-properties.
|
||||
_.isEmpty = function(obj) {
|
||||
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
|
||||
for (var key in obj) if (_.has(obj, key)) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
// Is a given value a DOM element?
|
||||
_.isElement = function(obj) {
|
||||
return !!(obj && obj.nodeType == 1);
|
||||
};
|
||||
|
||||
// Is a given value an array?
|
||||
// Delegates to ECMA5's native Array.isArray
|
||||
_.isArray = nativeIsArray || function(obj) {
|
||||
return toString.call(obj) == '[object Array]';
|
||||
};
|
||||
|
||||
// Is a given variable an object?
|
||||
_.isObject = function(obj) {
|
||||
return obj === Object(obj);
|
||||
};
|
||||
|
||||
// Is a given variable an arguments object?
|
||||
_.isArguments = function(obj) {
|
||||
return toString.call(obj) == '[object Arguments]';
|
||||
};
|
||||
if (!_.isArguments(arguments)) {
|
||||
_.isArguments = function(obj) {
|
||||
return !!(obj && _.has(obj, 'callee'));
|
||||
};
|
||||
}
|
||||
|
||||
// Is a given value a function?
|
||||
_.isFunction = function(obj) {
|
||||
return toString.call(obj) == '[object Function]';
|
||||
};
|
||||
|
||||
// Is a given value a string?
|
||||
_.isString = function(obj) {
|
||||
return toString.call(obj) == '[object String]';
|
||||
};
|
||||
|
||||
// Is a given value a number?
|
||||
_.isNumber = function(obj) {
|
||||
return toString.call(obj) == '[object Number]';
|
||||
};
|
||||
|
||||
// Is the given value `NaN`?
|
||||
_.isNaN = function(obj) {
|
||||
// `NaN` is the only value for which `===` is not reflexive.
|
||||
return obj !== obj;
|
||||
};
|
||||
|
||||
// Is a given value a boolean?
|
||||
_.isBoolean = function(obj) {
|
||||
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
|
||||
};
|
||||
|
||||
// Is a given value a date?
|
||||
_.isDate = function(obj) {
|
||||
return toString.call(obj) == '[object Date]';
|
||||
};
|
||||
|
||||
// Is the given value a regular expression?
|
||||
_.isRegExp = function(obj) {
|
||||
return toString.call(obj) == '[object RegExp]';
|
||||
};
|
||||
|
||||
// Is a given value equal to null?
|
||||
_.isNull = function(obj) {
|
||||
return obj === null;
|
||||
};
|
||||
|
||||
// Is a given variable undefined?
|
||||
_.isUndefined = function(obj) {
|
||||
return obj === void 0;
|
||||
};
|
||||
|
||||
// Has own property?
|
||||
_.has = function(obj, key) {
|
||||
return hasOwnProperty.call(obj, key);
|
||||
};
|
||||
|
||||
// Utility Functions
|
||||
// -----------------
|
||||
|
||||
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
|
||||
// previous owner. Returns a reference to the Underscore object.
|
||||
_.noConflict = function() {
|
||||
root._ = previousUnderscore;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Keep the identity function around for default iterators.
|
||||
_.identity = function(value) {
|
||||
return value;
|
||||
};
|
||||
|
||||
// Run a function **n** times.
|
||||
_.times = function (n, iterator, context) {
|
||||
for (var i = 0; i < n; i++) iterator.call(context, i);
|
||||
};
|
||||
|
||||
// Escape a string for HTML interpolation.
|
||||
_.escape = function(string) {
|
||||
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
|
||||
};
|
||||
|
||||
// Add your own custom functions to the Underscore object, ensuring that
|
||||
// they're correctly added to the OOP wrapper as well.
|
||||
_.mixin = function(obj) {
|
||||
each(_.functions(obj), function(name){
|
||||
addToWrapper(name, _[name] = obj[name]);
|
||||
});
|
||||
};
|
||||
|
||||
// Generate a unique integer id (unique within the entire client session).
|
||||
// Useful for temporary DOM ids.
|
||||
var idCounter = 0;
|
||||
_.uniqueId = function(prefix) {
|
||||
var id = idCounter++;
|
||||
return prefix ? prefix + id : id;
|
||||
};
|
||||
|
||||
// By default, Underscore uses ERB-style template delimiters, change the
|
||||
// following template settings to use alternative delimiters.
|
||||
_.templateSettings = {
|
||||
evaluate : /<%([\s\S]+?)%>/g,
|
||||
interpolate : /<%=([\s\S]+?)%>/g,
|
||||
escape : /<%-([\s\S]+?)%>/g
|
||||
};
|
||||
|
||||
// When customizing `templateSettings`, if you don't want to define an
|
||||
// interpolation, evaluation or escaping regex, we need one that is
|
||||
// guaranteed not to match.
|
||||
var noMatch = /.^/;
|
||||
|
||||
// Within an interpolation, evaluation, or escaping, remove HTML escaping
|
||||
// that had been previously added.
|
||||
var unescape = function(code) {
|
||||
return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
|
||||
};
|
||||
|
||||
// JavaScript micro-templating, similar to John Resig's implementation.
|
||||
// Underscore templating handles arbitrary delimiters, preserves whitespace,
|
||||
// and correctly escapes quotes within interpolated code.
|
||||
_.template = function(str, data) {
|
||||
var c = _.templateSettings;
|
||||
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
|
||||
'with(obj||{}){__p.push(\'' +
|
||||
str.replace(/\\/g, '\\\\')
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(c.escape || noMatch, function(match, code) {
|
||||
return "',_.escape(" + unescape(code) + "),'";
|
||||
})
|
||||
.replace(c.interpolate || noMatch, function(match, code) {
|
||||
return "'," + unescape(code) + ",'";
|
||||
})
|
||||
.replace(c.evaluate || noMatch, function(match, code) {
|
||||
return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
|
||||
})
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\t/g, '\\t')
|
||||
+ "');}return __p.join('');";
|
||||
var func = new Function('obj', '_', tmpl);
|
||||
if (data) return func(data, _);
|
||||
return function(data) {
|
||||
return func.call(this, data, _);
|
||||
};
|
||||
};
|
||||
|
||||
// Add a "chain" function, which will delegate to the wrapper.
|
||||
_.chain = function(obj) {
|
||||
return _(obj).chain();
|
||||
};
|
||||
|
||||
// The OOP Wrapper
|
||||
// ---------------
|
||||
|
||||
// If Underscore is called as a function, it returns a wrapped object that
|
||||
// can be used OO-style. This wrapper holds altered versions of all the
|
||||
// underscore functions. Wrapped objects may be chained.
|
||||
var wrapper = function(obj) { this._wrapped = obj; };
|
||||
|
||||
// Expose `wrapper.prototype` as `_.prototype`
|
||||
_.prototype = wrapper.prototype;
|
||||
|
||||
// Helper function to continue chaining intermediate results.
|
||||
var result = function(obj, chain) {
|
||||
return chain ? _(obj).chain() : obj;
|
||||
};
|
||||
|
||||
// A method to easily add functions to the OOP wrapper.
|
||||
var addToWrapper = function(name, func) {
|
||||
wrapper.prototype[name] = function() {
|
||||
var args = slice.call(arguments);
|
||||
unshift.call(args, this._wrapped);
|
||||
return result(func.apply(_, args), this._chain);
|
||||
};
|
||||
};
|
||||
|
||||
// Add all of the Underscore functions to the wrapper object.
|
||||
_.mixin(_);
|
||||
|
||||
// Add all mutator Array functions to the wrapper.
|
||||
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
|
||||
var method = ArrayProto[name];
|
||||
wrapper.prototype[name] = function() {
|
||||
var wrapped = this._wrapped;
|
||||
method.apply(wrapped, arguments);
|
||||
var length = wrapped.length;
|
||||
if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
|
||||
return result(wrapped, this._chain);
|
||||
};
|
||||
});
|
||||
|
||||
// Add all accessor Array functions to the wrapper.
|
||||
each(['concat', 'join', 'slice'], function(name) {
|
||||
var method = ArrayProto[name];
|
||||
wrapper.prototype[name] = function() {
|
||||
return result(method.apply(this._wrapped, arguments), this._chain);
|
||||
};
|
||||
});
|
||||
|
||||
// Start chaining a wrapped Underscore object.
|
||||
wrapper.prototype.chain = function() {
|
||||
this._chain = true;
|
||||
return this;
|
||||
};
|
||||
|
||||
// Extracts the result from a wrapped and chained object.
|
||||
wrapper.prototype.value = function() {
|
||||
return this._wrapped;
|
||||
};
|
||||
|
||||
}).call(this);
|
File diff suppressed because one or more lines are too long
@ -12,6 +12,7 @@ import copy
|
||||
import os
|
||||
import posixpath
|
||||
import re
|
||||
import warnings
|
||||
from typing import TYPE_CHECKING, Iterable, Tuple, cast
|
||||
|
||||
from docutils import nodes
|
||||
@ -21,6 +22,7 @@ from docutils.writers.html4css1 import Writer
|
||||
|
||||
from sphinx import addnodes
|
||||
from sphinx.builders import Builder
|
||||
from sphinx.deprecation import RemovedInSphinx50Warning
|
||||
from sphinx.locale import _, __, admonitionlabels
|
||||
from sphinx.util import logging
|
||||
from sphinx.util.docutils import SphinxTranslator
|
||||
@ -90,11 +92,6 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
|
||||
self.docnames = [self.builder.current_docname] # for singlehtml builder
|
||||
self.manpages_url = self.config.manpages_url
|
||||
self.protect_literal_text = 0
|
||||
self.permalink_text = self.config.html_add_permalinks
|
||||
# support backwards-compatible setting to a bool
|
||||
if not isinstance(self.permalink_text, str):
|
||||
self.permalink_text = '¶' if self.permalink_text else ''
|
||||
self.permalink_text = self.encode(self.permalink_text)
|
||||
self.secnumber_suffix = self.config.html_secnumber_suffix
|
||||
self.param_separator = ''
|
||||
self.optional_param_level = 0
|
||||
@ -323,9 +320,10 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
|
||||
append_fignumber(figtype, node['ids'][0])
|
||||
|
||||
def add_permalink_ref(self, node: Element, title: str) -> None:
|
||||
if node['ids'] and self.permalink_text and self.builder.add_permalinks:
|
||||
if node['ids'] and self.config.html_permalinks and self.builder.add_permalinks:
|
||||
format = '<a class="headerlink" href="#%s" title="%s">%s</a>'
|
||||
self.body.append(format % (node['ids'][0], title, self.permalink_text))
|
||||
self.body.append(format % (node['ids'][0], title,
|
||||
self.config.html_permalinks_icon))
|
||||
|
||||
def generate_targets_for_listing(self, node: Element) -> None:
|
||||
"""Generate hyperlink targets for listings.
|
||||
@ -400,7 +398,7 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
|
||||
|
||||
def depart_title(self, node: Element) -> None:
|
||||
close_tag = self.context[-1]
|
||||
if (self.permalink_text and self.builder.add_permalinks and
|
||||
if (self.config.html_permalinks and self.builder.add_permalinks and
|
||||
node.parent.hasattr('ids') and node.parent['ids']):
|
||||
# add permalink anchor
|
||||
if close_tag.startswith('</h'):
|
||||
@ -410,7 +408,7 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
|
||||
node.parent['ids'][0] +
|
||||
'title="%s">%s' % (
|
||||
_('Permalink to this headline'),
|
||||
self.permalink_text))
|
||||
self.config.html_permalinks_icon))
|
||||
elif isinstance(node.parent, nodes.table):
|
||||
self.body.append('</span>')
|
||||
self.add_permalink_ref(node.parent, _('Permalink to this table'))
|
||||
@ -839,3 +837,9 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator):
|
||||
|
||||
def unknown_visit(self, node: Node) -> None:
|
||||
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
|
||||
|
||||
@property
|
||||
def permalink_text(self) -> str:
|
||||
warnings.warn('HTMLTranslator.permalink_text is deprecated.',
|
||||
RemovedInSphinx50Warning, stacklevel=2)
|
||||
return self.config.html_permalinks_icon
|
||||
|
@ -20,7 +20,7 @@ from docutils.writers.html5_polyglot import HTMLTranslator as BaseTranslator
|
||||
|
||||
from sphinx import addnodes
|
||||
from sphinx.builders import Builder
|
||||
from sphinx.deprecation import RemovedInSphinx60Warning
|
||||
from sphinx.deprecation import RemovedInSphinx50Warning, RemovedInSphinx60Warning
|
||||
from sphinx.locale import _, __, admonitionlabels
|
||||
from sphinx.util import logging
|
||||
from sphinx.util.docutils import SphinxTranslator
|
||||
@ -63,11 +63,6 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
|
||||
self.docnames = [self.builder.current_docname] # for singlehtml builder
|
||||
self.manpages_url = self.config.manpages_url
|
||||
self.protect_literal_text = 0
|
||||
self.permalink_text = self.config.html_add_permalinks
|
||||
# support backwards-compatible setting to a bool
|
||||
if not isinstance(self.permalink_text, str):
|
||||
self.permalink_text = '¶' if self.permalink_text else ''
|
||||
self.permalink_text = self.encode(self.permalink_text)
|
||||
self.secnumber_suffix = self.config.html_secnumber_suffix
|
||||
self.param_separator = ''
|
||||
self.optional_param_level = 0
|
||||
@ -296,9 +291,10 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
|
||||
append_fignumber(figtype, node['ids'][0])
|
||||
|
||||
def add_permalink_ref(self, node: Element, title: str) -> None:
|
||||
if node['ids'] and self.permalink_text and self.builder.add_permalinks:
|
||||
if node['ids'] and self.config.html_permalinks and self.builder.add_permalinks:
|
||||
format = '<a class="headerlink" href="#%s" title="%s">%s</a>'
|
||||
self.body.append(format % (node['ids'][0], title, self.permalink_text))
|
||||
self.body.append(format % (node['ids'][0], title,
|
||||
self.config.html_permalinks_icon))
|
||||
|
||||
# overwritten
|
||||
def visit_bullet_list(self, node: Element) -> None:
|
||||
@ -353,8 +349,8 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
|
||||
|
||||
def depart_title(self, node: Element) -> None:
|
||||
close_tag = self.context[-1]
|
||||
if (self.permalink_text and self.builder.add_permalinks and
|
||||
node.parent.hasattr('ids') and node.parent['ids']):
|
||||
if (self.config.html_permalinks and self.builder.add_permalinks and
|
||||
node.parent.hasattr('ids') and node.parent['ids']):
|
||||
# add permalink anchor
|
||||
if close_tag.startswith('</h'):
|
||||
self.add_permalink_ref(node.parent, _('Permalink to this headline'))
|
||||
@ -363,7 +359,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
|
||||
node.parent['ids'][0] +
|
||||
'title="%s">%s' % (
|
||||
_('Permalink to this headline'),
|
||||
self.permalink_text))
|
||||
self.config.html_permalinks_icon))
|
||||
elif isinstance(node.parent, nodes.table):
|
||||
self.body.append('</span>')
|
||||
self.add_permalink_ref(node.parent, _('Permalink to this table'))
|
||||
@ -773,6 +769,12 @@ class HTML5Translator(SphinxTranslator, BaseTranslator):
|
||||
def unknown_visit(self, node: Node) -> None:
|
||||
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
|
||||
|
||||
@property
|
||||
def permalink_text(self) -> str:
|
||||
warnings.warn('HTMLTranslator.permalink_text is deprecated.',
|
||||
RemovedInSphinx50Warning, stacklevel=2)
|
||||
return self.config.html_permalinks_icon
|
||||
|
||||
def generate_targets_for_table(self, node: Element) -> None:
|
||||
"""Generate hyperlink targets for tables.
|
||||
|
||||
|
@ -1641,3 +1641,23 @@ def test_highlight_options_old(app):
|
||||
location=ANY, opts={})
|
||||
assert call_args[2] == call(ANY, 'java', force=False, linenos=False,
|
||||
location=ANY, opts={})
|
||||
|
||||
|
||||
@pytest.mark.sphinx('html', testroot='basic',
|
||||
confoverrides={'html_permalinks': False})
|
||||
def test_html_permalink_disable(app):
|
||||
app.build()
|
||||
content = (app.outdir / 'index.html').read_text()
|
||||
|
||||
assert '<h1>The basic Sphinx documentation for testing</h1>' in content
|
||||
|
||||
|
||||
@pytest.mark.sphinx('html', testroot='basic',
|
||||
confoverrides={'html_permalinks_icon': '<span>[PERMALINK]</span>'})
|
||||
def test_html_permalink_icon(app):
|
||||
app.build()
|
||||
content = (app.outdir / 'index.html').read_text()
|
||||
|
||||
assert ('<h1>The basic Sphinx documentation for testing<a class="headerlink" '
|
||||
'href="#the-basic-sphinx-documentation-for-testing" '
|
||||
'title="Permalink to this headline"><span>[PERMALINK]</span></a></h1>' in content)
|
||||
|
@ -402,6 +402,22 @@ def test_productionlist(app, status, warning):
|
||||
assert "A</strong> ::= B C D E F G" in text
|
||||
|
||||
|
||||
def test_productionlist2(app):
|
||||
text = (".. productionlist:: P2\n"
|
||||
" A: `:A` `A`\n"
|
||||
" B: `P1:B` `~P1:B`\n")
|
||||
doctree = restructuredtext.parse(app, text)
|
||||
refnodes = list(doctree.traverse(pending_xref))
|
||||
assert_node(refnodes[0], pending_xref, reftarget="A")
|
||||
assert_node(refnodes[1], pending_xref, reftarget="P2:A")
|
||||
assert_node(refnodes[2], pending_xref, reftarget="P1:B")
|
||||
assert_node(refnodes[3], pending_xref, reftarget="P1:B")
|
||||
assert_node(refnodes[0], [pending_xref, nodes.literal, "A"])
|
||||
assert_node(refnodes[1], [pending_xref, nodes.literal, "A"])
|
||||
assert_node(refnodes[2], [pending_xref, nodes.literal, "P1:B"])
|
||||
assert_node(refnodes[3], [pending_xref, nodes.literal, "B"])
|
||||
|
||||
|
||||
def test_disabled_docref(app):
|
||||
text = (":doc:`index`\n"
|
||||
":doc:`!index`\n")
|
||||
|
@ -216,6 +216,8 @@ def test_trailing_underscore(make_app, apidoc):
|
||||
def test_excludes(apidoc):
|
||||
outdir = apidoc.outdir
|
||||
assert (outdir / 'conf.py').isfile()
|
||||
assert (outdir / 'a.rst').isfile()
|
||||
assert (outdir / 'a.b.rst').isfile()
|
||||
assert (outdir / 'a.b.c.rst').isfile() # generated because not empty
|
||||
assert not (outdir / 'a.b.e.rst').isfile() # skipped because of empty after excludes
|
||||
assert (outdir / 'a.b.x.rst').isfile()
|
||||
@ -231,6 +233,8 @@ def test_excludes_subpackage_should_be_skipped(apidoc):
|
||||
"""Subpackage exclusion should work."""
|
||||
outdir = apidoc.outdir
|
||||
assert (outdir / 'conf.py').isfile()
|
||||
assert (outdir / 'a.rst').isfile()
|
||||
assert (outdir / 'a.b.rst').isfile()
|
||||
assert (outdir / 'a.b.c.rst').isfile() # generated because not empty
|
||||
assert not (outdir / 'a.b.e.f.rst').isfile() # skipped because 'b/e' subpackage is skipped
|
||||
|
||||
@ -244,6 +248,8 @@ def test_excludes_module_should_be_skipped(apidoc):
|
||||
"""Module exclusion should work."""
|
||||
outdir = apidoc.outdir
|
||||
assert (outdir / 'conf.py').isfile()
|
||||
assert (outdir / 'a.rst').isfile()
|
||||
assert (outdir / 'a.b.rst').isfile()
|
||||
assert (outdir / 'a.b.c.rst').isfile() # generated because not empty
|
||||
assert not (outdir / 'a.b.e.f.rst').isfile() # skipped because of empty after excludes
|
||||
|
||||
@ -257,6 +263,8 @@ def test_excludes_module_should_not_be_skipped(apidoc):
|
||||
"""Module should be included if no excludes are used."""
|
||||
outdir = apidoc.outdir
|
||||
assert (outdir / 'conf.py').isfile()
|
||||
assert (outdir / 'a.rst').isfile()
|
||||
assert (outdir / 'a.b.rst').isfile()
|
||||
assert (outdir / 'a.b.c.rst').isfile() # generated because not empty
|
||||
assert (outdir / 'a.b.e.f.rst').isfile() # skipped because of empty after excludes
|
||||
|
||||
|
@ -1167,6 +1167,30 @@ Sample class with PEP 526 annotations and google docstring
|
||||
"""
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
def test_preprocess_types(self):
|
||||
docstring = """\
|
||||
Do as you please
|
||||
|
||||
Yield:
|
||||
str:Extended
|
||||
"""
|
||||
actual = str(GoogleDocstring(docstring))
|
||||
expected = """\
|
||||
Do as you please
|
||||
|
||||
:Yields: *str* -- Extended
|
||||
"""
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
config = Config(napoleon_preprocess_types=True)
|
||||
actual = str(GoogleDocstring(docstring, config))
|
||||
expected = """\
|
||||
Do as you please
|
||||
|
||||
:Yields: :class:`str` -- Extended
|
||||
"""
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
|
||||
class NumpyDocstringTest(BaseDocstringTest):
|
||||
docstrings = [(
|
||||
|
@ -81,7 +81,7 @@ def test_js_source(app, status, warning):
|
||||
jquery_src = (app.outdir / '_static' / 'jquery-{v}.js'.format(v=v)).read_text()
|
||||
assert 'jQuery JavaScript Library v{v}'.format(v=v) in jquery_src, msg
|
||||
|
||||
v = '1.3.1'
|
||||
v = '1.12.0'
|
||||
msg = 'underscore.js version does not match to {v}'.format(v=v)
|
||||
underscore_min = (app.outdir / '_static' / 'underscore.js').read_text()
|
||||
assert 'Underscore.js {v}'.format(v=v) in underscore_min, msg
|
||||
|
Loading…
Reference in New Issue
Block a user