pyTooling.Sphinx.LaTeX

pyTooling/Sphinx/LaTeX.py
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
# ==================================================================================================================== #
#             _____           _ _               ____        _     _                                                    #
#  _ __  _   |_   _|__   ___ | (_)_ __   __ _  / ___| _ __ | |__ (_)_ __ __  __                                        #
# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | \___ \| '_ \| '_ \| | '_ \\ \/ /                                        #
# | |_) | |_| || | (_) | (_) | | | | | | (_| |_ ___) | |_) | | | | | | | |>  <                                         #
# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____/| .__/|_| |_|_|_| |_/_/\_\                                        #
# |_|    |___/                          |___/        |_|                                                               #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany                                                             #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
#
"""
Visitors writing pyTooling.Sphinx's nodes in LaTeX.

Each node has a ``visit_*`` and a ``depart_*`` function and a ``translate*`` pair of both, which
:data:`~pyTooling.Sphinx.NODES` registers. A node without visitors here is written by the visitors of its base-class.
"""
from textwrap                  import dedent

from docutils                  import nodes
from pygments.formatters.latex import escape_tex
from sphinx.writers.latex      import LaTeXTranslator

from pyTooling.Decorators      import export
from pyTooling.Sphinx.Node     import COVERAGE_STATES, DOCUMENTATION_STATES, CoverageListing, DocCoverageListing, \
                                      Landscape, LineBreak, ReportIndentation, TaskListCheckbox, visitFunc, \
                                      departFunc


__all__ = [
	"translateLandscape", "translateCoverageListing", "translateDocCoverageListing",
	"translateTaskListCheckbox", "translateLineBreak", "COVERAGE_MARKERS", "DOCUMENTATION_MARKERS", "TAB_WIDTH"
]

#: Per coverage state of a line, the color of its number - an ``xcolor`` expression - and the marker behind it.
COVERAGE_MARKERS = {
	"covered":   ("green!50!black", "+"),
	"partial":   ("orange",         "~"),
	"uncovered": ("red",            "-"),
	"excluded":  ("gray",           "x"),
	"":          ("gray",           " "),
}

#: Per documentation state of a line, the color of its number - an ``xcolor`` expression - and the marker behind it.
DOCUMENTATION_MARKERS = {
	"documented":   ("green!50!black", "+"),
	"undocumented": ("red",            "-"),
	"ignored":      ("gray",           "o"),
	"excluded":     ("gray",           "x"),
	"":             ("gray",           " "),
}

TAB_WIDTH = 4  #: Number of columns a tab advances to, as LaTeX doesn't expand tabs in a listing.


@export
def visit_Landscape(translator: LaTeXTranslator, node: Landscape) -> None:
	"""
	Open a landscape container in LaTeX: a ``landscape`` environment, which starts a new page in landscape orientation.

	:param translator: The LaTeX translator writing the document.
	:param node:       The landscape container.
	"""
	translator.body.append(dedent("""
		\\begin{landscape}
		""")
	)


@export
def depart_Landscape(translator: LaTeXTranslator, node: Landscape) -> None:
	"""
	Close a landscape container in LaTeX: the end of the ``landscape`` environment, which returns to portrait pages.

	:param translator: The LaTeX translator writing the document.
	:param node:       The landscape container.
	"""
	translator.body.append(dedent("""
		\\end{landscape}
		""")
	)


translateLandscape: tuple[visitFunc, departFunc] = (visit_Landscape, depart_Landscape)
"""Visit and depart function writing a :class:`~pyTooling.Sphinx.Node.Landscape` in LaTeX."""


@export
def highlightTokens(tokens: list[tuple[str, str]]) -> str:
	"""
	Write a listing line's tokens in LaTeX, as Sphinx writes highlighted code - ``\\PYG{<class>}{<text>}`` -, so the
	configured Pygments style colors them.

	Tabs are expanded to :data:`TAB_WIDTH` columns, as LaTeX doesn't expand them in a listing.

	:param tokens: The line's tokens as ``(CSS class, text)`` pairs; a token without a class is written as text.
	:returns:      The line's LaTeX.
	"""
	code: list[str] = []
	column = 0
	for cssClass, text in tokens:
		if "\t" in text:
			padding = column % TAB_WIDTH
			text = (" " * padding + text).expandtabs(TAB_WIDTH)[padding:]
		column += len(text)

		escaped = escape_tex(text, "PYG")
		code.append(escaped if cssClass == "" else f"\\PYG{{{cssClass}}}{{{escaped}}}")

	return "".join(code)


@export
def writeListing(
	translator: LaTeXTranslator,
	node: nodes.Element,
	lines: list[str],
	markers: dict[str, tuple[str, str]],
	states: dict[str, str]
) -> None:
	"""
	Write a listing in LaTeX: a line with the file's path and a legend of the markers, then a ``sphinxVerbatim``
	environment of the lines.

	:param translator: The LaTeX translator writing the document.
	:param node:       The listing, whose attribute ``path`` holds the file's path.
	:param lines:      The lines, each written as LaTeX.
	:param markers:    The color and marker per state.
	:param states:     The label per state, which the legend shows; the state ``""`` has no entry in the legend.
	"""
	legend = "\\quad{}".join(
		f"\\textcolor{{{color}}}{{\\texttt{{{escape_tex(marker, 'PYG')}}}}}~{states[state]}"
		for state, (color, marker) in markers.items() if state != ""
	)
	translator.body.append(
		f"\n\\par\\noindent\\sphinxcode{{{translator.encode(node['path'])}}}\\hfill{{}}{{\\small{{}}{legend}}}\\par\n"
	)
	translator.body.append("\n\\begin{sphinxVerbatim}[commandchars=\\\\\\{\\}]\n")
	translator.body.append("\n".join(lines))
	translator.body.append("\n\\end{sphinxVerbatim}\n")


@export
def visit_CoverageListing(translator: LaTeXTranslator, node: CoverageListing) -> None:
	"""
	Write a source file's code coverage in LaTeX, completely.

	The listing is a ``sphinxVerbatim`` environment with the tokens written as Sphinx writes highlighted code (see
	:func:`highlightTokens`). Each line starts with its number, colored by its coverage state, and a marker of
	:data:`COVERAGE_MARKERS`. A line above the listing shows the file's path and a legend of the markers. The node's
	text - the plain source - isn't written again.

	:param translator: The LaTeX translator writing the document.
	:param node:       The listing.
	:raises SkipNode:  Always, so the node's text isn't written again.
	"""
	width = len(str(max((number for number, *_ in node["lines"]), default=1)))

	lines: list[str] = []
	for number, status, _, _, _, tokens in node["lines"]:
		color, marker = COVERAGE_MARKERS[status]
		lines.append(f"\\textcolor{{{color}}}{{{number:>{width}} {marker}}} {highlightTokens(tokens)}")

	writeListing(translator, node, lines, COVERAGE_MARKERS, COVERAGE_STATES)

	raise nodes.SkipNode


@export
def depart_CoverageListing(translator: LaTeXTranslator, node: CoverageListing) -> None:
	"""
	Close a source file's code coverage in LaTeX, which writes nothing: :func:`visit_CoverageListing` wrote it all.

	:param translator: The LaTeX translator writing the document.
	:param node:       The listing.
	"""


translateCoverageListing: tuple[visitFunc, departFunc] = (visit_CoverageListing, depart_CoverageListing)
"""Visit and depart function writing a :class:`~pyTooling.Sphinx.Node.CoverageListing` in LaTeX."""


@export
def visit_DocCoverageListing(translator: LaTeXTranslator, node: DocCoverageListing) -> None:
	"""
	Write a Python module's documentation coverage in LaTeX, completely.

	Like a source file's code coverage (see :func:`visit_CoverageListing`): each line starts with its number, colored
	by its documentation state, and a marker of :data:`DOCUMENTATION_MARKERS`; an elided body's ``...`` has no number.
	The node's text - the condensed source - isn't written again.

	:param translator: The LaTeX translator writing the document.
	:param node:       The listing.
	:raises SkipNode:  Always, so the node's text isn't written again.
	"""
	width = len(str(max((number for number, *_ in node["lines"] if number is not None), default=1)))

	lines: list[str] = []
	for number, status, tokens in node["lines"]:
		color, marker = DOCUMENTATION_MARKERS[status]
		numberText = "" if number is None else f"{number}"
		lines.append(f"\\textcolor{{{color}}}{{{numberText:>{width}} {marker}}} {highlightTokens(tokens)}")

	writeListing(translator, node, lines, DOCUMENTATION_MARKERS, DOCUMENTATION_STATES)

	raise nodes.SkipNode


@export
def depart_DocCoverageListing(translator: LaTeXTranslator, node: DocCoverageListing) -> None:
	"""
	Close a Python module's documentation coverage in LaTeX, which writes nothing: :func:`visit_DocCoverageListing`
	wrote it all.

	:param translator: The LaTeX translator writing the document.
	:param node:       The listing.
	"""


translateDocCoverageListing: tuple[visitFunc, departFunc] = (visit_DocCoverageListing, depart_DocCoverageListing)
"""Visit and depart function writing a :class:`~pyTooling.Sphinx.Node.DocCoverageListing` in LaTeX."""


@export
def visit_TaskListCheckbox(translator: LaTeXTranslator, node: TaskListCheckbox) -> None:
	"""
	Write a task list item's checkbox in LaTeX, completely: ``\\boxtimes`` if the task is done, else ``\\square`` - both
	of package ``amssymb``, which Sphinx loads.

	:param translator: The LaTeX translator writing the document.
	:param node:       The checkbox.
	:raises SkipNode:  Always, so the node's text isn't written.
	"""
	translator.body.append("\\(\\boxtimes\\)" if node["checked"] else "\\(\\square\\)")

	raise nodes.SkipNode


@export
def depart_TaskListCheckbox(translator: LaTeXTranslator, node: TaskListCheckbox) -> None:
	"""
	Close a task list item's checkbox in LaTeX, which writes nothing: :func:`visit_TaskListCheckbox` wrote it all.

	:param translator: The LaTeX translator writing the document.
	:param node:       The checkbox.
	"""


translateTaskListCheckbox: tuple[visitFunc, departFunc] = (visit_TaskListCheckbox, depart_TaskListCheckbox)
"""Visit and depart function writing a :class:`~pyTooling.Sphinx.Node.TaskListCheckbox` in LaTeX."""


@export
def visit_LineBreak(translator: LaTeXTranslator, node: LineBreak) -> None:
	"""
	Write a line break in LaTeX, completely: ``\\newline``, which breaks the line in any environment.

	:param translator: The LaTeX translator writing the document.
	:param node:       The line break.
	:raises SkipNode:  Always, so the node's text isn't written.
	"""
	translator.body.append("\\newline{}")

	raise nodes.SkipNode


@export
def depart_LineBreak(translator: LaTeXTranslator, node: LineBreak) -> None:
	"""
	Close a line break in LaTeX, which writes nothing: :func:`visit_LineBreak` wrote it all.

	:param translator: The LaTeX translator writing the document.
	:param node:       The line break.
	"""


translateLineBreak: tuple[visitFunc, departFunc] = (visit_LineBreak, depart_LineBreak)
"""Visit and depart function writing a :class:`~pyTooling.Sphinx.Node.LineBreak` in LaTeX."""


@export
def visit_ReportIndentation(translator: LaTeXTranslator, node: ReportIndentation) -> None:
	"""
	Open an indented name of a report table in LaTeX: macro ``\\pyToolingReportIndentation`` of package
	:file:`pyTooling.Sphinx.sty` with the number of indentation steps.

	:param translator: The LaTeX translator writing the document.
	:param node:       The indented name.
	"""
	translator.body.append(f"\\pyToolingReportIndentation{{{node['level']}}}")


@export
def depart_ReportIndentation(translator: LaTeXTranslator, node: ReportIndentation) -> None:
	"""
	Close an indented name of a report table in LaTeX, which writes nothing: the macro indents the rest of the cell.

	:param translator: The LaTeX translator writing the document.
	:param node:       The indented name.
	"""


translateReportIndentation: tuple[visitFunc, departFunc] = (visit_ReportIndentation, depart_ReportIndentation)
"""Visit and depart function writing a :class:`~pyTooling.Sphinx.Node.ReportIndentation` in LaTeX."""