Debian Codegraph @

cloud_sptheme/ext/relbar_links.py

raw symbols SCIP
1 """
2 =================================================================
3 :mod:`cloud_sptheme.ext.relbar_links` - adds TOC entry to relbar
4 =================================================================
5
6 .. module:: cloud_sptheme.ext.relbar_links
7 :synopsis: adds TOC entry to right side of relbar
8
9 .. versionadded:: 1.8.1
10
11 Overview
12 ========
13 This Sphinx extension allows you to insert links into
14 the navigation bar ("relbar") at the top of bottom of all pages.
15
16 While it can be configured with arbitrary links, by default it automatically
17 inserts a Table Of Contents entry, similar to the old python documentation format.
18 This is mainly useful when the title link in the navigation bar has been redirected
19 to page other than Table Of Contents (such as allowed by the ``roottarget``
20 option of the :doc:`/cloud_theme`).
21
22 Configuration
23 =============
24 By default, this inserts a "TOC" link to the right of any "Next" or "Previous"
25 buttons, which points to your sphinx master document.
26
27 It can be customized using the following options in ``conf.py``:
28
29 ``relbar_links``
30
31 Optional list of links to insert, defaults to ``["toc"]``.
32 Each list item can have one of four formats:
33
34 * A dictionary containing the keys ``"page"`` and ``"label"``,
35 as well as optional ``"key"`` and ``"title"`` keywords.
36
37 "page" should be the an absolute path to your page (e.g. "contents",
38 or "lib/mypage"). "label" is the text that will be displayed on the link,
39 "title" is the tooltip set for the link, and "key" is the accesskey
40 for selecting the link.
41
42 * A 2-element tuple of ``(page, label)``
43
44 * A 4-element tuple of ``(page, title, key, label)``
45
46 * The predefined string ``"toc"``, which is replaced with a table
47 of contents link to your master document.
48
49 ``relbar_links_after``
50
51 When inserting the links, this extension will place them as far
52 left as possible, so long as they are to the right of any links
53 that are included in this list. Defaults to ``["next", "previous"]``.
54 """
55 #=========================================================
56 # imports
57 #=========================================================
58 # core
59 from __future__ import absolute_import, division, print_function
60 import logging
61 log = logging.getLogger(__name__)
62 # site
63 from sphinx.locale import _
64 # pkg
65 from cloud_sptheme import __version__
66 from cloud_sptheme.utils import unicode
67 # local
68 __all__ = [
69 "setup"
70 ]
71
72 #=========================================================
73 # helpers
74 #=========================================================
75
76 # indices for looking up link-row elements in relbar entry
77 # TODO: find authoriative source for this info.
78 NAME = 0 # name of document
79 TITLE = 1 # used for [title] attribute
80 ACCESS_KEY = 2 # used for [accesskey] attribute
81 LABEL = 3 # used for link content (NOTE: has already been run through translation)
82
83
84 def parse_entry(app, entry):
85 """
86 normalize entry representation from config
87 """
88 if entry == "toc":
89 master_doc = app.config.master_doc
90 return master_doc, _("Table Of Contents"), "C", _("toc")
91 if isinstance(entry, (list, tuple)):
92 if len(entry) == 4:
93 return entry
94 if len(entry) == 2:
95 page, label = entry
96 return page, label, None, label
97 elif isinstance(entry, dict):
98 page = entry.get("page")
99 label = entry.get("label")
100 if not (page and label):
101 raise ValueError("dict must define at least 'page' and "
102 "'label': %r" % (entry,))
103 title = entry.get("title") or label
104 key = entry.get("key")
105 return page, title, key, label
106 raise ValueError("expected dict or 2/4-element sequence: %r" % (entry,))
107
108 #=========================================================
109 # hooks
110 #=========================================================
111
112 def insert_relbar_links(app, pagename, templatename, ctx, event_arg):
113 # check for relbar link list
114 # NOTE: not defined for some pages of some builders,
115 # e.g. json builder's "genindex" page.
116 if "rellinks" not in ctx:
117 return
118 links = ctx['rellinks']
119
120 # get list of links to insert
121 custom_links = [parse_entry(app, entry)
122 for entry in app.config.relbar_links]
123
124 # remove existing links with same label
125 # NOTE: unicode() wrapper is to resolve any _TranslationProxy() instances
126 custom_labels = set(unicode(entry[LABEL]) for entry in custom_links)
127 idx = 0
128 while idx < len(links):
129 if unicode(links[idx][LABEL]) in custom_labels:
130 del links[idx]
131 else:
132 idx += 1
133
134 # insert custom links to right of any "next" / "previous" links
135 # NOTE: 'links' is in right to left order!
136 after_labels = set(unicode(_(label)) for label in app.config.relbar_links_after)
137 for pos, entry in enumerate(links):
138 if unicode(entry[LABEL]) in after_labels:
139 break
140 else:
141 pos = len(links)
142
143 # insert links
144 links[pos:pos] = custom_links
145
146 #=========================================================
147 # sphinx entrypoint
148 #=========================================================
149 def setup(app):
150 """
151 setup extension for sphinx run
152 """
153
154 # let user customize list of links
155 app.add_config_value('relbar_links', ["toc"], 'env')
156 app.add_config_value('relbar_links_after', ["next", "previous"], 'env')
157
158 # attach rewrite-hook
159 app.connect('html-page-context', insert_relbar_links)
160
161 # identifies the version of our extension
162 return {'version': __version__}
163
164 #=========================================================
165 # eof
166 #=========================================================