File: __init__.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 (640 lines) | stat: -rw-r--r-- 18,193 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
#!/usr/bin/env python3
#
#  latex.py
r"""
Sphinx utilities for LaTeX builders.

.. versionadded:: 2.8.0

In addition to the developer API (see below), :mod:`sphinx_toolbox.latex`
configures Sphinx and LaTeX to correctly handle symbol footnotes.

.. versionchanged:: 2.12.0

	Sphinx is also configured to respect ``.. only:: html`` etc. directives surrounding
	toctree directives when determining the overall toctree depth.

.. extensions:: sphinx_toolbox.latex


.. latex:vspace:: -5px

Example Footnotes
--------------------

.. latex:vspace:: -10px

| Hello [1]_
| Goodbye [2]_
| Symbol [*]_
| Another Symbol [*]_
| Number Again [3]_
| Symbol 3 [*]_
| Symbol 4 [*]_
| Symbol 5 [*]_
| Symbol 6 [*]_
| Symbol 7 [*]_
| Symbol 8 [*]_
| Symbol 9 [*]_

.. latex:vspace:: 20px

.. [1] One
.. [2] Two
.. [*] Buckle my shoe
.. [*] The second symbol
.. [3] The number after the symbol
.. [*] Symbol 3
.. [*] Symbol 4
.. [*] Symbol 5
.. [*] Symbol 6
.. [*] Symbol 7
.. [*] Symbol 8
.. [*] Symbol 9


Usage
-------

.. latex:vspace:: -10px


.. rst:directive:: latex:samepage
                   samepage

	Configures LaTeX to make all content within this directive appear on the same page.

	This can be useful to avoid awkward page breaks.

	This directive has no effect with non-LaTeX builders.

	.. versionadded:: 2.9.0


.. rst:directive:: latex:clearpage
                   clearpage

	Configures LaTeX to start a new page.

	This directive has no effect with non-LaTeX builders.

	.. versionadded:: 2.10.0
	.. seealso:: :rst:dir:`latex:cleardoublepage`


.. rst:directive:: latex:cleardoublepage
                   cleardoublepage

	Configures LaTeX to start a new page.

	In a two-sided printing it also makes the next page a right-hand (odd-numbered) page,
	inserting a blank page if necessary.

	This directive has no effect with non-LaTeX builders.

	.. versionadded:: 2.10.0
	.. seealso:: :rst:dir:`latex:clearpage`


.. rst:directive:: .. latex:vspace:: space

	Configures LaTeX to add or remove vertical space.

	The value for ``space`` is passed verbatim to the ``\vspace{}`` command.
	Ensure you pass a valid value.

	This directive has no effect with non-LaTeX builders.

	.. versionadded:: 2.11.0


.. latex:clearpage::

API Reference
----------------

.. latex:vspace:: -20px
"""
#
#  Copyright © 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.
#
#  PatchedLaTeXBuilder based on Sphinx
#  Copyright (c) 2007-2020 by the Sphinx team.
#  |  All rights reserved.
#  |
#  |  Redistribution and use in source and binary forms, with or without
#  |  modification, are permitted provided that the following conditions are
#  |  met:
#  |
#  |  * Redistributions of source code must retain the above copyright
#  |    notice, this list of conditions and the following disclaimer.
#  |
#  |  * Redistributions in binary form must reproduce the above copyright
#  |    notice, this list of conditions and the following disclaimer in the
#  |    documentation and/or other materials provided with the distribution.
#  |
#  |  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#  |  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#  |  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#  |  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#  |  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  |  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#  |  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  |  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  |  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  |  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  |  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

# stdlib
import re
from os.path import join as joinpath
from textwrap import dedent
from typing import Any, List, Optional, cast

# 3rd party
import sphinx
from docutils import nodes
from docutils.frontend import OptionParser
from docutils.transforms.references import Footnotes
from domdf_python_tools.paths import PathPlus
from domdf_python_tools.stringlist import DelimitedList
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.builders.latex import LaTeXBuilder
from sphinx.domains import Domain
from sphinx.environment import BuildEnvironment
from sphinx.locale import __
from sphinx.util.docutils import SphinxDirective, SphinxFileOutput
from sphinx.util.nodes import process_only_nodes
from sphinx.writers.latex import LaTeXTranslator, LaTeXWriter

# this package
from sphinx_toolbox.utils import Config, SphinxExtMetadata, metadata_add_version

try:
	# 3rd party
	from sphinx.util.display import progress_message
except ImportError:
	# 3rd party
	from sphinx.util import progress_message  # type: ignore[no-redef]

_ = BuildEnvironment

__all__ = (
		"use_package",
		"visit_footnote",
		"depart_footnote",
		"SamepageDirective",
		"ClearPageDirective",
		"ClearDoublePageDirective",
		"VSpaceDirective",
		"LaTeXDomain",
		"replace_unknown_unicode",
		"better_header_layout",
		"configure",
		"setup",
		)

footmisc_symbols = ['0', *Footnotes.symbols]
# footmisc_symbols = ['0', '*', '†', '‡', '§', '¶', '‖', "**", "††", "‡‡"]


def visit_footnote(translator: LaTeXTranslator, node: nodes.footnote) -> None:
	"""
	Visit a :class:`docutils.nodes.footnote` node with the LaTeX translator.

	Unlike the default ``visit_footnote`` function, this one handles footnotes using symbols.

	.. versionadded:: 2.8.0

	:param translator:
	:param node:
	"""

	translator.in_footnote += 1
	footnote_id = str(cast(nodes.label, node[0]).astext())

	if not translator.in_parsed_literal:
		translator.body.append("%\n")

	if not footnote_id.isnumeric() and footnote_id in footmisc_symbols:
		footnote_id = str(footmisc_symbols.index(footnote_id))
		translator.body.append(r"\renewcommand\thefootnote{\thesymbolfootnote}")

	translator.body.append(rf"\begin{{footnote}}[{footnote_id}]")
	translator.body.append("\\sphinxAtStartFootnote\n")


def depart_footnote(translator: LaTeXTranslator, node: nodes.footnote) -> None:
	"""
	Depart a :class:`docutils.nodes.footnote` node with the LaTeX translator.

	.. versionadded:: 2.8.0

	:param translator:
	:param node:
	"""

	if not translator.in_parsed_literal:
		translator.body.append("%\n")

	translator.body.append(r"\end{footnote}")
	translator.body.append(r"\renewcommand\thefootnote{\thenumberfootnote}")
	translator.in_footnote -= 1


def use_package(package: str, config: Config, *args: str, **kwargs: str) -> None:
	r"""
	Configure LaTeX to use the given package.

	The ``\usepackage`` entry is added to the
	:py:obj:`sphinx.config.Config.latex_elements` ``["preamble"]`` attribute.

	:param package:
	:param config:
	:param \*args: Passed as options to the LaTeX package.
	:param \*\*kwargs: Passed as named options to the LaTeX package.
	"""

	options: DelimitedList[str] = DelimitedList()
	options.extend(args)
	options.extend(map("{}={}".format, kwargs.items()))

	use_string = rf"\usepackage[{options:,}]{{{package}}}"

	if not hasattr(config, "latex_elements") or not config.latex_elements:  # pragma: no cover
		config.latex_elements = {}

	latex_preamble = config.latex_elements.get("preamble", '')

	if use_string not in latex_preamble:
		config.latex_elements["preamble"] = f"{latex_preamble}\n{use_string}"


class SamepageDirective(SphinxDirective):
	"""
	Directive which configures LaTeX to make all content within this directive appear on the same page.

	This can be useful to avoid awkward page breaks.

	This directive has no effect with non-LaTeX builders.

	.. versionadded:: 2.9.0
	"""

	has_content = True

	def run(self) -> List[nodes.Node]:
		"""
		Process the content of the directive.
		"""

		content_node = nodes.container(rawsource='\n'.join(self.content))
		self.state.nested_parse(self.content, self.content_offset, content_node)

		return [
				nodes.raw('', r"\par\begin{samepage}", format="latex"),
				content_node,
				nodes.raw('', r"\end{samepage}\par", format="latex"),
				]


class ClearPageDirective(SphinxDirective):
	"""
	Directive which configures LaTeX to start a new page.

	This directive has no effect with non-LaTeX builders.

	.. versionadded:: 2.10.0
	.. seealso:: :class:`~.ClearDoublePageDirective`
	"""

	has_content = True

	def run(self) -> List[nodes.Node]:
		"""
		Process the content of the directive.
		"""

		return [nodes.raw('', r"\clearpage", format="latex")]


class ClearDoublePageDirective(SphinxDirective):
	"""
	Directive which configures LaTeX to start a new page.

	In a two-sided printing it also makes the next page a right-hand (odd-numbered) page,
	inserting a blank page if necessary.

	This directive has no effect with non-LaTeX builders.

	.. versionadded:: 2.10.0
	.. seealso:: :class:`~.ClearPageDirective`
	"""

	has_content = True

	def run(self) -> List[nodes.Node]:
		"""
		Process the content of the directive.
		"""

		return [nodes.raw('', r"\cleardoublepage", format="latex")]


class VSpaceDirective(SphinxDirective):
	"""
	Directive which configures LaTeX to add or remove vertical space.

	This directive has no effect with non-LaTeX builders.

	.. versionadded:: 2.11.0
	"""

	required_arguments = 1  # the space

	def run(self) -> List[nodes.Node]:
		"""
		Process the content of the directive.
		"""

		return [nodes.raw('', f"\n\\vspace{{{self.arguments[0]}}}\n", format="latex")]


class LaTeXDomain(Domain):
	"""
	Domain containing various LaTeX-specific directives.

	.. versionadded:: 2.11.0
	"""

	name = "latex"
	label = "LaTeX"
	directives = {
			"samepage": SamepageDirective,
			"clearpage": ClearPageDirective,
			"cleardoublepage": ClearDoublePageDirective,
			"vspace": VSpaceDirective,
			}


def replace_unknown_unicode(app: Sphinx, exception: Optional[Exception] = None) -> None:
	r"""
	Replaces certain unknown unicode characters in the Sphinx LaTeX output with the best equivalents.

	.. only:: html

		The mapping is as follows:

		* ♠ -- \spadesuit
		* ♥ -- \heartsuit
		* ♦ -- \diamondsuit
		* ♣ -- \clubsuit
		* Zero width space -- \hspace{0pt}
		* μ -- \textmu
		* ≡ -- \equiv (new in version 2.11.0)
		* ≈ -- \approx (new in version 2.12.0)
		* ≥ -- \geq (new in version 2.13.0)
		* ≤ -- \leq (new in version 2.13.0)

	This function can be hooked into the :event:`build-finished` event as follows:

	.. code-block:: python

		app.connect("build-finished", replace_unknown_unicode)

	.. versionadded:: 2.9.0

	:param app: The Sphinx application.
	:param exception: Any exception which occurred and caused Sphinx to abort.
	"""

	if exception:  # pragma: no cover
		return

	if app.builder is None or app.builder.name.lower() != "latex":
		return

	builder = cast(LaTeXBuilder, app.builder)
	output_file = PathPlus(builder.outdir) / f"{builder.titles[0][1].lower()}.tex"

	output_content = output_file.read_text()

	output_content = output_content.replace('♠', r' $\spadesuit$ ')
	output_content = output_content.replace('♥', r' $\heartsuit$ ')
	output_content = output_content.replace('♦', r' $\diamondsuit$ ')
	output_content = output_content.replace('♣', r' $\clubsuit$ ')
	output_content = output_content.replace('\u200b', r'\hspace{0pt}')  # Zero width space
	output_content = output_content.replace('μ', r"\textmu{}")
	output_content = output_content.replace('≡', r" $\equiv$ ")
	output_content = output_content.replace('≈', r" $\approx$ ")
	output_content = output_content.replace('≥', r" $\geq$ ")
	output_content = output_content.replace('≤', r" $\leq$ ")

	output_file.write_clean(output_content)


def better_header_layout(
		config: Config,
		space_before: int = 10,
		space_after: int = 20,
		) -> None:
	"""
	Makes LaTeX chapter names lowercase, and adjusts the spacing above and below the chapter name.

	.. versionadded:: 2.10.0

	:param config: The Sphinx configuration object.
	:param space_before: The space, in pixels, before the chapter name.
	:param space_after: The space, in pixels, after the chapter name.
	"""

	begin = "% begin st better header layout"
	end = "% end st better header layout"

	commands = rf"""
	{begin}
	\makeatletter
		\renewcommand{{\DOCH}}{{%
			\mghrulefill{{\RW}}\par\nobreak
			\CNV\FmN{{\@chapapp}}\par\nobreak
			\CNoV\TheAlphaChapter\par\nobreak
			\vskip -1\baselineskip\vskip 5pt\mghrulefill{{\RW}}\par\nobreak
			\vskip 10\p@
			}}
		\renewcommand{{\DOTI}}[1]{{%
			\CTV\FmTi{{#1}}\par\nobreak
			\vskip {space_before}\p@
			}}
		\renewcommand{{\DOTIS}}[1]{{%
			\CTV\FmTi{{#1}}\par\nobreak
			\vskip {space_after}\p@
			}}
	\makeatother
	{end}
	"""

	if not hasattr(config, "latex_elements") or not config.latex_elements:  # pragma: no cover
		config.latex_elements = {}

	latex_preamble = config.latex_elements.get("preamble", '')

	if begin in latex_preamble:
		config.latex_elements["preamble"] = re.sub(
				f"{begin}.*{end}",
				dedent(commands),
				latex_preamble,
				count=1,
				flags=re.DOTALL,
				)
	else:
		config.latex_elements["preamble"] = f"{latex_preamble}\n{dedent(commands)}"

	config.latex_elements["fncychap"] = "\\usepackage[Bjarne]{fncychap}\n\\ChNameAsIs\n\\ChTitleAsIs\n"


class PatchedLaTeXBuilder(LaTeXBuilder):
	"""
	Patched version of Sphinx's LaTeX builder which skips toctrees under ``.. only:: html`` etc. directives
	when determining the max toctree depth.

	The default behaviour uses the ``:maxdepth:`` option of the first toctree,
	irrespective of whether the toctree will exist with the LaTeX builder.
	"""  # noqa: D400

	# TODO: respect toctree caption for LaTeX table of contents too
	# \addto\captionsenglish{\renewcommand{\contentsname}{Documentation}}

	def write(self, *ignored: Any) -> None:
		assert self.env is not None

		docwriter = LaTeXWriter(self)
		docsettings: Any = OptionParser(
				defaults=self.env.settings,
				components=(docwriter, ),
				read_config_files=True,
				).get_default_values()

		if sphinx.version_info <= (4, 0):
			# 3rd party
			from sphinx.builders.latex import patch_settings  # type: ignore[attr-defined]
			patch_settings(docsettings)

		self.init_document_data()
		self.write_stylesheet()

		for entry in self.document_data:
			docname, targetname, title, author, themename = entry[:5]
			theme = self.themes.get(themename)
			toctree_only = False
			if len(entry) > 5:
				toctree_only = entry[5]
			destination = SphinxFileOutput(
					destination_path=joinpath(self.outdir, targetname),
					encoding="utf-8",
					overwrite_if_changed=True
					)
			with progress_message(__("processing %s") % targetname):
				doctree = self.env.get_doctree(docname)
				process_only_nodes(doctree, self.tags)

				if hasattr(doctree, "findall"):
					toctree = next(doctree.findall(addnodes.toctree), None)
				else:
					toctree = next(iter(doctree.traverse(addnodes.toctree)), None)

				if toctree and toctree.get("maxdepth") > 0:
					tocdepth = toctree.get("maxdepth")
				else:
					tocdepth = None

				doctree = self.assemble_doctree(
						docname,
						toctree_only,
						appendices=(self.config.latex_appendices if theme.name != "howto" else [])
						)
				doctree["docclass"] = theme.docclass
				doctree["contentsname"] = self.get_contentsname(docname)
				doctree["tocdepth"] = tocdepth
				self.post_process_images(doctree)
				self.update_doc_context(title, author, theme)

				if hasattr(self, "update_context"):  # pragma: no cover
					# Only present in newer Sphinx versions
					self.update_context()

			with progress_message(__("writing")):
				# pylint: disable=loop-invariant-statement
				docsettings._author = author
				docsettings._title = title
				docsettings._contentsname = doctree["contentsname"]
				docsettings._docname = docname
				docsettings._docclass = theme.name

				doctree.settings = docsettings
				docwriter.theme = theme
				docwriter.write(doctree, destination)
				# pylint: enable=loop-invariant-statement


def configure(app: Sphinx, config: Config) -> None:
	"""
	Configure :mod:`sphinx_toolbox.latex`.

	:param app: The Sphinx application.
	:param config:
	"""

	if not hasattr(config, "latex_elements") or not config.latex_elements:  # pragma: no cover
		config.latex_elements = {}

	latex_preamble = config.latex_elements.get("preamble", '')

	command_string = r"\newcommand\thesymbolfootnote{\fnsymbol{footnote}}\let\thenumberfootnote\thefootnote"

	if command_string not in latex_preamble:
		config.latex_elements["preamble"] = f"{latex_preamble}\n{command_string}"


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

	.. versionadded:: 2.8.0

	:param app: The Sphinx application.
	"""

	app.add_node(nodes.footnote, latex=(visit_footnote, depart_footnote), override=True)

	app.add_directive("samepage", SamepageDirective)
	app.add_directive("clearpage", ClearPageDirective)
	app.add_directive("cleardoublepage", ClearDoublePageDirective)

	app.add_domain(LaTeXDomain)

	app.add_builder(PatchedLaTeXBuilder, override=True)

	app.connect("config-inited", configure)

	return {}