Merge pull request #5650 from tk0miya/refactor_IndexEntry

Add IndexEntry class to represent an entry of indices
This commit is contained in:
Takeshi KOMIYA 2018-11-21 11:09:54 +09:00 committed by GitHub
commit 2cbc921946
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 31 additions and 16 deletions

View File

@ -58,7 +58,7 @@ if False:
from typing import Any, Dict, IO, Iterable, Iterator, List, Type, Tuple, Union # NOQA from typing import Any, Dict, IO, Iterable, Iterator, List, Type, Tuple, Union # NOQA
from sphinx.application import Sphinx # NOQA from sphinx.application import Sphinx # NOQA
from sphinx.config import Config # NOQA from sphinx.config import Config # NOQA
from sphinx.domains import Domain, Index # NOQA from sphinx.domains import Domain, Index, IndexEntry # NOQA
from sphinx.util.tags import Tags # NOQA from sphinx.util.tags import Tags # NOQA
# Experimental HTML5 Writer # Experimental HTML5 Writer
@ -249,7 +249,7 @@ class StandaloneHTMLBuilder(Builder):
default_html5_translator = False default_html5_translator = False
imgpath = None # type: unicode imgpath = None # type: unicode
domain_indices = [] # type: List[Tuple[unicode, Type[Index], List[Tuple[unicode, List[List[Union[unicode, int]]]]], bool]] # NOQA domain_indices = [] # type: List[Tuple[unicode, Type[Index], List[Tuple[unicode, List[IndexEntry]]], bool]] # NOQA
# cached publisher object for snippets # cached publisher object for snippets
_publisher = None _publisher = None

View File

@ -11,6 +11,7 @@
""" """
import copy import copy
from typing import NamedTuple
from sphinx.errors import SphinxError from sphinx.errors import SphinxError
from sphinx.locale import _ from sphinx.locale import _
@ -53,6 +54,15 @@ class ObjType:
self.attrs.update(attrs) self.attrs.update(attrs)
IndexEntry = NamedTuple('IndexEntry', [('name', str),
('subtype', int),
('docname', str),
('anchor', str),
('extra', str),
('qualifier', str),
('descr', str)])
class Index: class Index:
""" """
An Index is the description for a domain-specific index. To add an index to An Index is the description for a domain-specific index. To add an index to
@ -80,7 +90,7 @@ class Index:
self.domain = domain self.domain = domain
def generate(self, docnames=None): def generate(self, docnames=None):
# type: (Iterable[unicode]) -> Tuple[List[Tuple[unicode, List[List[Union[unicode, int]]]]], bool] # NOQA # type: (Iterable[unicode]) -> Tuple[List[Tuple[unicode, List[IndexEntry]]], bool]
"""Return entries for the index given by *name*. If *docnames* is """Return entries for the index given by *name*. If *docnames* is
given, restrict to entries referring to these docnames. given, restrict to entries referring to these docnames.

View File

@ -17,7 +17,7 @@ from docutils.parsers.rst import directives
from sphinx import addnodes, locale from sphinx import addnodes, locale
from sphinx.deprecation import DeprecatedDict, RemovedInSphinx30Warning from sphinx.deprecation import DeprecatedDict, RemovedInSphinx30Warning
from sphinx.directives import ObjectDescription from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType, Index from sphinx.domains import Domain, ObjType, Index, IndexEntry
from sphinx.locale import _, __ from sphinx.locale import _, __
from sphinx.roles import XRefRole from sphinx.roles import XRefRole
from sphinx.util import logging from sphinx.util import logging
@ -669,8 +669,8 @@ class PythonModuleIndex(Index):
shortname = _('modules') shortname = _('modules')
def generate(self, docnames=None): def generate(self, docnames=None):
# type: (Iterable[unicode]) -> Tuple[List[Tuple[unicode, List[List[Union[unicode, int]]]]], bool] # NOQA # type: (Iterable[unicode]) -> Tuple[List[Tuple[unicode, List[IndexEntry]]], bool]
content = {} # type: Dict[unicode, List] content = {} # type: Dict[unicode, List[IndexEntry]]
# list of prefixes to ignore # list of prefixes to ignore
ignores = None # type: List[unicode] ignores = None # type: List[unicode]
ignores = self.domain.env.config['modindex_common_prefix'] # type: ignore ignores = self.domain.env.config['modindex_common_prefix'] # type: ignore
@ -705,19 +705,22 @@ class PythonModuleIndex(Index):
if prev_modname == package: if prev_modname == package:
# first submodule - make parent a group head # first submodule - make parent a group head
if entries: if entries:
entries[-1][1] = 1 last = entries[-1]
entries[-1] = IndexEntry(last[0], 1, last[2], last[3],
last[4], last[5], last[6])
entries.append(IndexEntry(stripped + package, 1, '', '', '', '', ''))
elif not prev_modname.startswith(package): elif not prev_modname.startswith(package):
# submodule without parent in list, add dummy entry # submodule without parent in list, add dummy entry
entries.append([stripped + package, 1, '', '', '', '', '']) entries.append(IndexEntry(stripped + package, 1, '', '', '', '', ''))
subtype = 2 subtype = 2
else: else:
num_toplevels += 1 num_toplevels += 1
subtype = 0 subtype = 0
qualifier = deprecated and _('Deprecated') or '' qualifier = deprecated and _('Deprecated') or ''
entries.append([stripped + modname, subtype, docname, entries.append(IndexEntry(stripped + modname, subtype, docname,
'module-' + stripped + modname, platforms, 'module-' + stripped + modname, platforms,
qualifier, synopsis]) qualifier, synopsis))
prev_modname = modname prev_modname = modname
# apply heuristics when to collapse modindex at page load: # apply heuristics when to collapse modindex at page load:

View File

@ -44,6 +44,7 @@ if False:
from typing import Any, Callable, Dict, Iterator, List, Pattern, Tuple, Set, Union # NOQA from typing import Any, Callable, Dict, Iterator, List, Pattern, Tuple, Set, Union # NOQA
from sphinx.builders.latex import LaTeXBuilder # NOQA from sphinx.builders.latex import LaTeXBuilder # NOQA
from sphinx.builders.latex import nodes as latexnodes # NOQA from sphinx.builders.latex import nodes as latexnodes # NOQA
from sphinx.domains import IndexEntry # NOQA
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -773,7 +774,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
def generate_indices(self): def generate_indices(self):
# type: () -> unicode # type: () -> unicode
def generate(content, collapsed): def generate(content, collapsed):
# type: (List[Tuple[unicode, List[Tuple[unicode, unicode, unicode, unicode, unicode]]]], bool) -> None # NOQA # type: (List[Tuple[unicode, List[IndexEntry]]], bool) -> None
ret.append('\\begin{sphinxtheindex}\n') ret.append('\\begin{sphinxtheindex}\n')
ret.append('\\let\\bigletter\\sphinxstyleindexlettergroup\n') ret.append('\\let\\bigletter\\sphinxstyleindexlettergroup\n')
for i, (letter, entries) in enumerate(content): for i, (letter, entries) in enumerate(content):
@ -809,7 +810,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
continue continue
ret.append(u'\\renewcommand{\\indexname}{%s}\n' % ret.append(u'\\renewcommand{\\indexname}{%s}\n' %
indexcls.localname) indexcls.localname)
generate(content, collapsed) # type: ignore generate(content, collapsed)
return ''.join(ret) return ''.join(ret)

View File

@ -26,6 +26,7 @@ if False:
# For type annotation # For type annotation
from typing import Any, Callable, Dict, Iterator, List, Pattern, Set, Tuple, Union # NOQA from typing import Any, Callable, Dict, Iterator, List, Pattern, Set, Tuple, Union # NOQA
from sphinx.builders.texinfo import TexinfoBuilder # NOQA from sphinx.builders.texinfo import TexinfoBuilder # NOQA
from sphinx.domains import IndexEntry # NOQA
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -480,15 +481,15 @@ class TexinfoTranslator(nodes.NodeVisitor):
def collect_indices(self): def collect_indices(self):
# type: () -> None # type: () -> None
def generate(content, collapsed): def generate(content, collapsed):
# type: (List[Tuple[unicode, List[List[Union[unicode, int]]]]], bool) -> unicode # type: (List[Tuple[unicode, List[IndexEntry]]], bool) -> unicode
ret = ['\n@menu\n'] # type: List[unicode] ret = ['\n@menu\n'] # type: List[unicode]
for letter, entries in content: for letter, entries in content:
for entry in entries: for entry in entries:
if not entry[3]: if not entry[3]:
continue continue
name = self.escape_menu(entry[0]) # type: ignore name = self.escape_menu(entry[0])
sid = self.get_short_id('%s:%s' % (entry[2], entry[3])) sid = self.get_short_id('%s:%s' % (entry[2], entry[3]))
desc = self.escape_arg(entry[6]) # type: ignore desc = self.escape_arg(entry[6])
me = self.format_menu_entry(name, sid, desc) me = self.format_menu_entry(name, sid, desc)
ret.append(me) ret.append(me)
ret.append('@end menu\n') ret.append('@end menu\n')