Box of handy tools for Sphinx providing comprehensive extensions and enhancements for documentation generation.
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.
Custom Sphinx domain providing LaTeX-specific directives for precise PDF formatting control.
class LaTeXDomain(Domain):
"""Domain for LaTeX-specific directives."""
name = 'latex'
label = 'LaTeX'
directives = {
'samepage': SamepageDirective,
'clearpage': ClearPageDirective,
'cleardoublepage': ClearDoublePageDirective,
'vspace': VSpaceDirective,
}
class SamepageDirective(SphinxDirective):
"""Keeps content on the same page in LaTeX output."""
has_content = True
def run(self) -> List[Node]:
"""Create samepage node."""
class ClearPageDirective(SphinxDirective):
"""Starts a new page in LaTeX output."""
has_content = False
def run(self) -> List[Node]:
"""Create clearpage node."""
class ClearDoublePageDirective(SphinxDirective):
"""Starts a new right-hand page in LaTeX output."""
has_content = False
def run(self) -> List[Node]:
"""Create cleardoublepage node."""
class VSpaceDirective(SphinxDirective):
"""Adds vertical space in LaTeX output."""
required_arguments = 1 # space amount
has_content = False
def run(self) -> List[Node]:
"""Create vspace node."""Usage:
.. latex:samepage::
This content will be kept together on the same page.
It won't be broken across page boundaries.
.. latex:clearpage::
.. latex:cleardoublepage::
.. latex:vspace:: 2cmFunctions for managing LaTeX packages and customizing the LaTeX preamble.
def use_package(package: str, config: Config, *args, **kwargs) -> None:
"""
Add LaTeX package to document preamble.
Args:
package: Package name to include
config: Sphinx configuration object
*args: Package arguments
**kwargs: Package options
Example:
use_package('geometry', config, margin='1in')
use_package('xcolor', config, 'dvipsnames', 'table')
"""
def configure_latex_packages(config: Config) -> None:
"""Configure default LaTeX packages for sphinx-toolbox."""
def add_latex_preamble(config: Config, preamble: str) -> None:
"""
Add custom LaTeX code to document preamble.
Args:
config: Sphinx configuration object
preamble: LaTeX code to add
"""Enhanced LaTeX layout with better spacing, headers, and chapter formatting.
def better_header_layout(config: Config, space_before: str = "20pt",
space_after: str = "20pt") -> None:
"""
Improve chapter and section header layout.
Args:
config: Sphinx configuration object
space_before: Space before headers
space_after: Space after headers
"""
def configure_chapter_styling(config: Config) -> None:
"""Configure enhanced chapter styling."""
def setup_page_geometry(config: Config, margin: str = "1in",
top: str = "1.2in", bottom: str = "1in") -> None:
"""
Configure page geometry and margins.
Args:
config: Sphinx configuration object
margin: General margin size
top: Top margin
bottom: Bottom margin
"""
def configure_paragraph_spacing(config: Config,
parskip: str = "6pt plus 2pt minus 1pt") -> None:
"""Configure paragraph spacing."""Improved footnote formatting with symbol support and enhanced styling.
def visit_footnote(translator: LaTeXTranslator, node: footnote) -> None:
"""
Enhanced footnote visitor with better formatting.
Args:
translator: LaTeX translator instance
node: Footnote node to process
"""
def depart_footnote(translator: LaTeXTranslator, node: footnote) -> None:
"""
Enhanced footnote departure with proper cleanup.
Args:
translator: LaTeX translator instance
node: Footnote node being processed
"""
def configure_footnote_styling(config: Config, style: str = "symbols") -> None:
"""
Configure footnote numbering style.
Args:
config: Sphinx configuration object
style: Style type ("numbers", "symbols", "roman")
"""Enhanced Unicode support and character replacement for LaTeX compatibility.
def replace_unknown_unicode(app: Sphinx, exception: Optional[Exception]) -> None:
"""
Replace unknown Unicode characters with LaTeX equivalents.
Args:
app: Sphinx application instance
exception: Build exception if any occurred
"""
def configure_unicode_support(config: Config) -> None:
"""Configure enhanced Unicode support for LaTeX."""
def add_character_replacements(replacements: Dict[str, str]) -> None:
"""
Add custom character replacements for LaTeX output.
Args:
replacements: Dictionary mapping Unicode chars to LaTeX commands
"""
# Predefined character replacements
UNICODE_REPLACEMENTS: Dict[str, str] = {
'—': '---', # em dash
'–': '--', # en dash
''': '`', # left single quote
''': "'", # right single quote
'"': '``', # left double quote
'"': "''", # right double quote
'…': r'\ldots{}', # ellipsis
'©': r'\copyright{}', # copyright
'®': r'\textregistered{}', # registered
'™': r'\texttrademark{}', # trademark
}Improved table of contents formatting and customization for LaTeX.
def configure_toc_styling(config: Config) -> None:
"""Configure enhanced table of contents styling."""
def set_toc_depth(config: Config, depth: int = 3) -> None:
"""
Set table of contents depth.
Args:
config: Sphinx configuration object
depth: Maximum depth to include in TOC
"""
def customize_toc_formatting(config: Config, **kwargs) -> None:
"""Customize TOC formatting with various options."""Enhanced cross-referencing for LaTeX output with better formatting.
def configure_cross_references(config: Config) -> None:
"""Configure enhanced cross-reference formatting."""
def format_cross_reference(target: str, text: str, ref_type: str) -> str:
"""
Format cross-reference for LaTeX output.
Args:
target: Reference target
text: Reference text
ref_type: Type of reference
Returns:
Formatted LaTeX cross-reference
"""Succinct "See also" section formatting for LaTeX output.
def format_seealso_latex(translator: LaTeXTranslator, node: seealso) -> None:
"""
Format 'See also' sections with succinct LaTeX styling.
Args:
translator: LaTeX translator instance
node: See also node to format
"""
def configure_seealso_styling(config: Config, style: str = "succinct") -> None:
"""
Configure 'See also' section styling.
Args:
config: Sphinx configuration object
style: Styling option ("succinct", "standard", "compact")
"""LaTeX support integrates with Sphinx configuration for easy customization.
def configure(app: Sphinx, config: Config) -> None:
"""
Configure LaTeX elements and settings.
Args:
app: Sphinx application instance
config: Sphinx configuration object
"""
# Configuration values added by LaTeX support
latex_elements_config = {
'papersize': 'letterpaper',
'pointsize': '11pt',
'fncychap': r'\usepackage[Bjornstrup]{fncychap}',
'preamble': '', # Custom preamble additions
'figure_align': 'htbp',
'geometry': r'\usepackage[margin=1in]{geometry}',
}Advanced features for power users and complex document formatting.
def setup_custom_environments(config: Config, environments: Dict[str, str]) -> None:
"""
Set up custom LaTeX environments.
Args:
config: Sphinx configuration object
environments: Dictionary of environment definitions
"""
def configure_bibliography(config: Config, style: str = "plain",
backend: str = "bibtex") -> None:
"""
Configure bibliography processing.
Args:
config: Sphinx configuration object
style: Bibliography style
backend: Bibliography backend ("bibtex", "biber")
"""
def setup_theorem_environments(config: Config) -> None:
"""Set up theorem-like environments (theorem, lemma, proof, etc.)."""
def configure_code_highlighting(config: Config, style: str = "default") -> None:
"""
Configure code syntax highlighting for LaTeX.
Args:
config: Sphinx configuration object
style: Highlighting style name
"""LaTeX support includes comprehensive error handling for common LaTeX issues.
class LaTeXError(SphinxError):
"""Base exception for LaTeX processing errors."""
class PackageError(LaTeXError):
"""Raised when LaTeX package handling fails."""
class UnicodeError(LaTeXError):
"""Raised when Unicode character replacement fails."""
def handle_latex_warnings(app: Sphinx, warning: str) -> None:
"""Handle and filter LaTeX compilation warnings."""Basic LaTeX customization in conf.py:
# Load LaTeX support
extensions = ['sphinx_toolbox.latex']
# Configure LaTeX elements
latex_elements = {
'papersize': 'a4paper',
'pointsize': '11pt',
'preamble': r'''
\usepackage{geometry}
\geometry{margin=1in}
\usepackage{fancyhdr}
\pagestyle{fancy}
''',
}
# Configure enhanced features
latex_show_pagerefs = True
latex_show_urls = 'footnote'Using LaTeX directives in documents:
Chapter Introduction
===================
.. latex:samepage::
This important content will stay together:
* Key point 1
* Key point 2
* Key point 3
.. latex:vspace:: 1cm
Next section with some spacing above.
.. latex:clearpage::
New Chapter
===========
This starts on a fresh page.Install with Tessl CLI
npx tessl i tessl/pypi-sphinx-toolbox