File: formatting.py

package info (click to toggle)
sphinx-toolbox 3.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,924 kB
  • sloc: python: 11,636; sh: 26; javascript: 25; makefile: 16
file content (227 lines) | stat: -rw-r--r-- 5,793 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python3
#
#  formatting.py
"""
Directives, roles and nodes for text formatting.

.. versionadded:: 0.2.0
.. extensions:: sphinx_toolbox.formatting


.. latex:vspace:: -10px

Usage
-------

.. rst:role:: iabbr

	An abbreviation. If the role content contains a parenthesized explanation,
	it will be treated specially: it will be shown in a tool-tip in HTML,
	and output only once in LaTeX.

	Unlike Sphinx's :rst:role:`abbr` role, this one shows the abbreviation in italics.

	.. versionadded:: 0.2.0

	:bold-title:`Example`

	.. rest-example::

		:iabbr:`LIFO (last-in, first-out)`


.. rst:role:: bold-title

	Role for displaying a pseudo title in bold.

	This is useful for breaking up Python docstrings.

	.. versionadded:: 2.12.0

	:bold-title:`Example`

	.. rest-example::

		:bold-title:`Examples:`

		:bold-title:`Other Extensions`


API Reference
---------------
"""
#
#  Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in all
#  copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
#  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
#  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
#  OR OTHER DEALINGS IN THE SOFTWARE.
#
#  Parts of the docstrings based on https://docutils.sourceforge.io/docs/howto/rst-roles.html
#

# stdlib
from typing import List, Tuple

# 3rd party
from docutils import nodes
from docutils.nodes import Node, system_message
from docutils.parsers.rst import roles
from sphinx.application import Sphinx
from sphinx.roles import Abbreviation
from sphinx.util.docutils import SphinxRole
from sphinx.writers.html5 import HTML5Translator
from sphinx.writers.latex import LaTeXTranslator

# this package
from sphinx_toolbox.utils import SphinxExtMetadata, metadata_add_version

__all__ = (
		"ItalicAbbreviationNode",
		"ItalicAbbreviation",
		"visit_iabbr_node",
		"depart_iabbr_node",
		"latex_visit_iabbr_node",
		"latex_depart_iabbr_node",
		"setup"
		)


class ItalicAbbreviationNode(nodes.abbreviation):
	"""
	Docutils Node to show an abbreviation in italics.
	"""


class ItalicAbbreviation(Abbreviation):
	"""
	Docutils role to show an abbreviation in italics.
	"""

	def run(self) -> Tuple[List[Node], List[system_message]]:
		"""
		Process the content of the italic abbreviation role.
		"""

		options = self.options.copy()
		matched = self.abbr_re.search(self.text)

		if matched:
			text = self.text[:matched.start()].strip()
			options["explanation"] = matched.group(1)
		else:
			text = self.text

		return [ItalicAbbreviationNode(self.rawtext, text, **options)], []


class BoldTitle(SphinxRole):
	"""
	Role for displaying a pseudo title in bold.

	This is useful for breaking up Python docstrings.
	"""

	def run(self) -> Tuple[List[nodes.Node], List[nodes.system_message]]:

		assert self.text is not None

		node_list: List[nodes.Node] = [
				nodes.raw('', r"\vspace{10px}", format="latex"),
				nodes.strong(f"**{self.text}**", self.text),
				]

		return node_list, []


def visit_iabbr_node(translator: HTML5Translator, node: ItalicAbbreviationNode) -> None:
	"""
	Visit an :class:`~.ItalicAbbreviationNode`.

	:param translator:
	:param node: The node being visited.
	"""

	translator.body.append('<i class="abbreviation">')
	attrs = {}

	if node.hasattr("explanation"):
		attrs["title"] = node["explanation"]

	translator.body.append(translator.starttag(node, "abbr", '', **attrs))


def depart_iabbr_node(translator: HTML5Translator, node: ItalicAbbreviationNode) -> None:
	"""
	Depart an :class:`~.ItalicAbbreviationNode`.

	:param translator:
	:param node: The node being visited.
	"""

	translator.body.append("</i></abbr>")


def latex_visit_iabbr_node(translator: LaTeXTranslator, node: ItalicAbbreviationNode) -> None:
	"""
	Visit an :class:`~.ItalicAbbreviationNode`.

	:param translator:
	:param node: The node being visited.
	"""

	abbr = node.astext()
	translator.body.append(r"\textit{\sphinxstyleabbreviation{")

	# spell out the explanation once
	if node.hasattr("explanation") and abbr not in translator.handled_abbrs:
		translator.context.append(f'}} ({translator.encode(node["explanation"])})')
		translator.handled_abbrs.add(abbr)
	else:
		translator.context.append('}')


def latex_depart_iabbr_node(translator: LaTeXTranslator, node: ItalicAbbreviationNode) -> None:
	"""
	Depart an :class:`~.ItalicAbbreviationNode`.

	:param translator:
	:param node: The node being visited.
	"""

	translator.body.append(translator.context.pop())
	translator.body.append('}')


@metadata_add_version
def setup(app: Sphinx) -> SphinxExtMetadata:
	"""
	Setup :mod:`sphinx_toolbox.formatting`.

	:param app: The Sphinx application.
	"""

	roles.register_local_role("iabbr", ItalicAbbreviation())
	app.add_role("bold-title", BoldTitle())

	app.add_node(
			ItalicAbbreviationNode,
			html=(visit_iabbr_node, depart_iabbr_node),
			latex=(latex_visit_iabbr_node, latex_depart_iabbr_node),
			)

	return {"parallel_read_safe": True}