0
# LaTeX Support
1
2
Extensive LaTeX customization including custom directives, package management, layout improvements, and Unicode handling. These extensions provide fine-grained control over LaTeX output for professional PDF generation.
3
4
## Capabilities
5
6
### LaTeX Domain
7
8
Custom Sphinx domain providing LaTeX-specific directives for precise PDF formatting control.
9
10
```python { .api }
11
class LaTeXDomain(Domain):
12
"""Domain for LaTeX-specific directives."""
13
14
name = 'latex'
15
label = 'LaTeX'
16
17
directives = {
18
'samepage': SamepageDirective,
19
'clearpage': ClearPageDirective,
20
'cleardoublepage': ClearDoublePageDirective,
21
'vspace': VSpaceDirective,
22
}
23
24
class SamepageDirective(SphinxDirective):
25
"""Keeps content on the same page in LaTeX output."""
26
27
has_content = True
28
29
def run(self) -> List[Node]:
30
"""Create samepage node."""
31
32
class ClearPageDirective(SphinxDirective):
33
"""Starts a new page in LaTeX output."""
34
35
has_content = False
36
37
def run(self) -> List[Node]:
38
"""Create clearpage node."""
39
40
class ClearDoublePageDirective(SphinxDirective):
41
"""Starts a new right-hand page in LaTeX output."""
42
43
has_content = False
44
45
def run(self) -> List[Node]:
46
"""Create cleardoublepage node."""
47
48
class VSpaceDirective(SphinxDirective):
49
"""Adds vertical space in LaTeX output."""
50
51
required_arguments = 1 # space amount
52
has_content = False
53
54
def run(self) -> List[Node]:
55
"""Create vspace node."""
56
```
57
58
Usage:
59
60
```rst
61
.. latex:samepage::
62
63
This content will be kept together on the same page.
64
65
It won't be broken across page boundaries.
66
67
.. latex:clearpage::
68
69
.. latex:cleardoublepage::
70
71
.. latex:vspace:: 2cm
72
```
73
74
### Package Management
75
76
Functions for managing LaTeX packages and customizing the LaTeX preamble.
77
78
```python { .api }
79
def use_package(package: str, config: Config, *args, **kwargs) -> None:
80
"""
81
Add LaTeX package to document preamble.
82
83
Args:
84
package: Package name to include
85
config: Sphinx configuration object
86
*args: Package arguments
87
**kwargs: Package options
88
89
Example:
90
use_package('geometry', config, margin='1in')
91
use_package('xcolor', config, 'dvipsnames', 'table')
92
"""
93
94
def configure_latex_packages(config: Config) -> None:
95
"""Configure default LaTeX packages for sphinx-toolbox."""
96
97
def add_latex_preamble(config: Config, preamble: str) -> None:
98
"""
99
Add custom LaTeX code to document preamble.
100
101
Args:
102
config: Sphinx configuration object
103
preamble: LaTeX code to add
104
"""
105
```
106
107
### Layout Improvements
108
109
Enhanced LaTeX layout with better spacing, headers, and chapter formatting.
110
111
```python { .api }
112
def better_header_layout(config: Config, space_before: str = "20pt",
113
space_after: str = "20pt") -> None:
114
"""
115
Improve chapter and section header layout.
116
117
Args:
118
config: Sphinx configuration object
119
space_before: Space before headers
120
space_after: Space after headers
121
"""
122
123
def configure_chapter_styling(config: Config) -> None:
124
"""Configure enhanced chapter styling."""
125
126
def setup_page_geometry(config: Config, margin: str = "1in",
127
top: str = "1.2in", bottom: str = "1in") -> None:
128
"""
129
Configure page geometry and margins.
130
131
Args:
132
config: Sphinx configuration object
133
margin: General margin size
134
top: Top margin
135
bottom: Bottom margin
136
"""
137
138
def configure_paragraph_spacing(config: Config,
139
parskip: str = "6pt plus 2pt minus 1pt") -> None:
140
"""Configure paragraph spacing."""
141
```
142
143
### Enhanced Footnote Handling
144
145
Improved footnote formatting with symbol support and enhanced styling.
146
147
```python { .api }
148
def visit_footnote(translator: LaTeXTranslator, node: footnote) -> None:
149
"""
150
Enhanced footnote visitor with better formatting.
151
152
Args:
153
translator: LaTeX translator instance
154
node: Footnote node to process
155
"""
156
157
def depart_footnote(translator: LaTeXTranslator, node: footnote) -> None:
158
"""
159
Enhanced footnote departure with proper cleanup.
160
161
Args:
162
translator: LaTeX translator instance
163
node: Footnote node being processed
164
"""
165
166
def configure_footnote_styling(config: Config, style: str = "symbols") -> None:
167
"""
168
Configure footnote numbering style.
169
170
Args:
171
config: Sphinx configuration object
172
style: Style type ("numbers", "symbols", "roman")
173
"""
174
```
175
176
### Unicode and Character Handling
177
178
Enhanced Unicode support and character replacement for LaTeX compatibility.
179
180
```python { .api }
181
def replace_unknown_unicode(app: Sphinx, exception: Optional[Exception]) -> None:
182
"""
183
Replace unknown Unicode characters with LaTeX equivalents.
184
185
Args:
186
app: Sphinx application instance
187
exception: Build exception if any occurred
188
"""
189
190
def configure_unicode_support(config: Config) -> None:
191
"""Configure enhanced Unicode support for LaTeX."""
192
193
def add_character_replacements(replacements: Dict[str, str]) -> None:
194
"""
195
Add custom character replacements for LaTeX output.
196
197
Args:
198
replacements: Dictionary mapping Unicode chars to LaTeX commands
199
"""
200
201
# Predefined character replacements
202
UNICODE_REPLACEMENTS: Dict[str, str] = {
203
'—': '---', # em dash
204
'–': '--', # en dash
205
''': '`', # left single quote
206
''': "'", # right single quote
207
'"': '``', # left double quote
208
'"': "''", # right double quote
209
'…': r'\ldots{}', # ellipsis
210
'©': r'\copyright{}', # copyright
211
'®': r'\textregistered{}', # registered
212
'™': r'\texttrademark{}', # trademark
213
}
214
```
215
216
### Table of Contents Enhancements
217
218
Improved table of contents formatting and customization for LaTeX.
219
220
```python { .api }
221
def configure_toc_styling(config: Config) -> None:
222
"""Configure enhanced table of contents styling."""
223
224
def set_toc_depth(config: Config, depth: int = 3) -> None:
225
"""
226
Set table of contents depth.
227
228
Args:
229
config: Sphinx configuration object
230
depth: Maximum depth to include in TOC
231
"""
232
233
def customize_toc_formatting(config: Config, **kwargs) -> None:
234
"""Customize TOC formatting with various options."""
235
```
236
237
### Cross-Reference Improvements
238
239
Enhanced cross-referencing for LaTeX output with better formatting.
240
241
```python { .api }
242
def configure_cross_references(config: Config) -> None:
243
"""Configure enhanced cross-reference formatting."""
244
245
def format_cross_reference(target: str, text: str, ref_type: str) -> str:
246
"""
247
Format cross-reference for LaTeX output.
248
249
Args:
250
target: Reference target
251
text: Reference text
252
ref_type: Type of reference
253
254
Returns:
255
Formatted LaTeX cross-reference
256
"""
257
```
258
259
### See Also Formatting
260
261
Succinct "See also" section formatting for LaTeX output.
262
263
```python { .api }
264
def format_seealso_latex(translator: LaTeXTranslator, node: seealso) -> None:
265
"""
266
Format 'See also' sections with succinct LaTeX styling.
267
268
Args:
269
translator: LaTeX translator instance
270
node: See also node to format
271
"""
272
273
def configure_seealso_styling(config: Config, style: str = "succinct") -> None:
274
"""
275
Configure 'See also' section styling.
276
277
Args:
278
config: Sphinx configuration object
279
style: Styling option ("succinct", "standard", "compact")
280
"""
281
```
282
283
### Configuration Integration
284
285
LaTeX support integrates with Sphinx configuration for easy customization.
286
287
```python { .api }
288
def configure(app: Sphinx, config: Config) -> None:
289
"""
290
Configure LaTeX elements and settings.
291
292
Args:
293
app: Sphinx application instance
294
config: Sphinx configuration object
295
"""
296
297
# Configuration values added by LaTeX support
298
latex_elements_config = {
299
'papersize': 'letterpaper',
300
'pointsize': '11pt',
301
'fncychap': r'\usepackage[Bjornstrup]{fncychap}',
302
'preamble': '', # Custom preamble additions
303
'figure_align': 'htbp',
304
'geometry': r'\usepackage[margin=1in]{geometry}',
305
}
306
```
307
308
### Advanced LaTeX Customizations
309
310
Advanced features for power users and complex document formatting.
311
312
```python { .api }
313
def setup_custom_environments(config: Config, environments: Dict[str, str]) -> None:
314
"""
315
Set up custom LaTeX environments.
316
317
Args:
318
config: Sphinx configuration object
319
environments: Dictionary of environment definitions
320
"""
321
322
def configure_bibliography(config: Config, style: str = "plain",
323
backend: str = "bibtex") -> None:
324
"""
325
Configure bibliography processing.
326
327
Args:
328
config: Sphinx configuration object
329
style: Bibliography style
330
backend: Bibliography backend ("bibtex", "biber")
331
"""
332
333
def setup_theorem_environments(config: Config) -> None:
334
"""Set up theorem-like environments (theorem, lemma, proof, etc.)."""
335
336
def configure_code_highlighting(config: Config, style: str = "default") -> None:
337
"""
338
Configure code syntax highlighting for LaTeX.
339
340
Args:
341
config: Sphinx configuration object
342
style: Highlighting style name
343
"""
344
```
345
346
### Error Handling
347
348
LaTeX support includes comprehensive error handling for common LaTeX issues.
349
350
```python { .api }
351
class LaTeXError(SphinxError):
352
"""Base exception for LaTeX processing errors."""
353
354
class PackageError(LaTeXError):
355
"""Raised when LaTeX package handling fails."""
356
357
class UnicodeError(LaTeXError):
358
"""Raised when Unicode character replacement fails."""
359
360
def handle_latex_warnings(app: Sphinx, warning: str) -> None:
361
"""Handle and filter LaTeX compilation warnings."""
362
```
363
364
### Usage Examples
365
366
Basic LaTeX customization in `conf.py`:
367
368
```python
369
# Load LaTeX support
370
extensions = ['sphinx_toolbox.latex']
371
372
# Configure LaTeX elements
373
latex_elements = {
374
'papersize': 'a4paper',
375
'pointsize': '11pt',
376
'preamble': r'''
377
\usepackage{geometry}
378
\geometry{margin=1in}
379
\usepackage{fancyhdr}
380
\pagestyle{fancy}
381
''',
382
}
383
384
# Configure enhanced features
385
latex_show_pagerefs = True
386
latex_show_urls = 'footnote'
387
```
388
389
Using LaTeX directives in documents:
390
391
```rst
392
Chapter Introduction
393
===================
394
395
.. latex:samepage::
396
397
This important content will stay together:
398
399
* Key point 1
400
* Key point 2
401
* Key point 3
402
403
.. latex:vspace:: 1cm
404
405
Next section with some spacing above.
406
407
.. latex:clearpage::
408
409
New Chapter
410
===========
411
412
This starts on a fresh page.
413
```