CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pylatex

A comprehensive Python library for programmatically creating and compiling LaTeX documents and snippets.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

sectioning.mddocs/

Document Sectioning

Hierarchical document structure with chapters, sections, subsections, and automatic numbering and labeling. PyLaTeX provides a complete sectioning system that mirrors LaTeX's document structure commands.

Capabilities

Section Hierarchy

PyLaTeX provides the complete LaTeX sectioning hierarchy with automatic numbering and optional labeling.

class Section(Container):
    def __init__(self, title, numbering=None, *, label=True, **kwargs):
        """
        Document section with automatic numbering and labeling.
        
        Parameters:
        - title: str, section title
        - numbering: bool, enable/disable numbering (None uses default)
        - label: bool or str, automatic label generation or custom label
        """
    
    # Properties
    marker_prefix = "sec"  # Default label prefix

class Chapter(Section):
    """Chapter-level section (\\chapter)."""
    marker_prefix = "chap"

class Subsection(Section):
    """Subsection (\\subsection)."""
    marker_prefix = "subsec"

class Subsubsection(Section):
    """Sub-subsection (\\subsubsection)."""
    marker_prefix = "ssubsec"

Section Usage

Basic section creation with automatic numbering:

from pylatex import Document, Chapter, Section, Subsection, Subsubsection

# For book or report document class
doc = Document(documentclass='report')

with doc.create(Chapter('Introduction')):
    doc.append('This is the introduction chapter.')
    
    with doc.create(Section('Background')):
        doc.append('Background information.')
        
        with doc.create(Subsection('Historical Context')):
            doc.append('Historical background.')
            
            with doc.create(Subsubsection('Ancient Period')):
                doc.append('Ancient historical context.')

# For article document class (no chapters)
article = Document(documentclass='article')

with article.create(Section('Methods')):
    article.append('Methodology description.')
    
    with article.create(Subsection('Data Collection')):
        article.append('How data was collected.')

Numbering Control

Control section numbering behavior:

from pylatex import Document, Section, Subsection

doc = Document()

# Numbered sections (default)
with doc.create(Section('Numbered Section')):
    doc.append('This section is numbered.')

# Unnumbered sections
with doc.create(Section('Unnumbered Section', numbering=False)):
    doc.append('This section is not numbered.')

# Mixed numbering
with doc.create(Section('Parent Section')):
    with doc.create(Subsection('Numbered Subsection')):
        doc.append('This subsection is numbered.')
    
    with doc.create(Subsection('Unnumbered Subsection', numbering=False)):
        doc.append('This subsection is not numbered.')

Label Management

Automatic and manual label generation for cross-referencing:

from pylatex import Document, Section, Ref

doc = Document()

# Automatic labeling (default)
with doc.create(Section('Methods')) as methods:
    methods.append('This section has an automatic label.')

# Custom labels
with doc.create(Section('Results', label='custom-results')) as results:
    results.append('This section has a custom label.')

# Disable labeling
with doc.create(Section('Discussion', label=False)) as discussion:
    discussion.append('This section has no label.')

# Reference sections
doc.append('See ')
doc.append(Ref('sec:methods'))
doc.append(' for methodology details.')

Section Patterns

Nested Section Structure

Create complex document hierarchies:

from pylatex import Document, Chapter, Section, Subsection

doc = Document(documentclass='book')

with doc.create(Chapter('Literature Review')):
    with doc.create(Section('Theoretical Framework')):
        with doc.create(Subsection('Core Concepts')):
            doc.append('Fundamental concepts.')
        
        with doc.create(Subsection('Related Work')):
            doc.append('Previous research.')
    
    with doc.create(Section('Research Gaps')):
        doc.append('Identified gaps in literature.')

with doc.create(Chapter('Methodology')):
    with doc.create(Section('Research Design')):
        doc.append('Overall research approach.')
    
    with doc.create(Section('Data Analysis')):
        with doc.create(Subsection('Quantitative Methods')):
            doc.append('Statistical analysis methods.')
        
        with doc.create(Subsection('Qualitative Methods')):
            doc.append('Qualitative analysis approach.')

Section with Complex Content

Sections can contain any LaTeX content:

from pylatex import Document, Section, Subsection
from pylatex import Figure, Table, Math

doc = Document()

with doc.create(Section('Analysis')) as analysis:
    analysis.append('This section contains various content types.')
    
    # Add figure
    with analysis.create(Figure(position='h')) as fig:
        fig.add_image('data_plot.png', width=NoEscape(r'0.8\\textwidth'))
        fig.add_caption('Data visualization')
    
    # Add subsection with math
    with analysis.create(Subsection('Mathematical Model')):
        with analysis.create(Math()) as math:
            math.append(r'E = mc^2')
    
    # Add table
    with analysis.create(Subsection('Results Summary')):
        # Table creation code here...
        pass

Document Class Considerations

Different document classes support different sectioning levels:

# Article class hierarchy
article = Document(documentclass='article')
# Available: Section, Subsection, Subsubsection, Paragraph, Subparagraph

# Report class hierarchy  
report = Document(documentclass='report')
# Available: Chapter, Section, Subsection, Subsubsection, Paragraph, Subparagraph

# Book class hierarchy
book = Document(documentclass='book')
# Available: Part, Chapter, Section, Subsection, Subsubsection, Paragraph, Subparagraph

Custom Section Formatting

Customize section appearance and behavior:

from pylatex import Document, Section, Command

doc = Document()

# Add custom section formatting to preamble
doc.preamble.append(Command('titleformat', 
                           arguments=[NoEscape(r'\section'),
                                    NoEscape(r'\Large\bfseries'),
                                    NoEscape(r'\thesection'),
                                    NoEscape(r'1em'),
                                    NoEscape(r'{}')]))

# Use sections normally
with doc.create(Section('Custom Formatted Section')):
    doc.append('This section uses custom formatting.')

Advanced Section Features

Table of Contents Integration

Sections automatically appear in table of contents:

from pylatex import Document, Chapter, Section, Command

doc = Document(documentclass='report')

# Add table of contents
doc.append(Command('tableofcontents'))
doc.append(Command('newpage'))

# Create sections (automatically added to TOC)
with doc.create(Chapter('Introduction')):
    doc.append('Introduction content.')

with doc.create(Chapter('Methods')):
    with doc.create(Section('Data Collection')):
        doc.append('Data collection methods.')

Section Depth Control

Control how deep sections appear in TOC:

from pylatex import Document, Command

doc = Document()

# Set TOC depth (0=chapter, 1=section, 2=subsection, etc.)
doc.preamble.append(Command('setcounter', arguments=['tocdepth', '2']))

# Set section numbering depth
doc.preamble.append(Command('setcounter', arguments=['secnumdepth', '3']))

Cross-Referencing Sections

Use section labels for cross-references throughout the document:

from pylatex import Document, Section, Ref, Pageref

doc = Document()

with doc.create(Section('Introduction', label='intro')):
    doc.append('This is the introduction.')

with doc.create(Section('Methods', label='methods')):
    doc.append('As discussed in ')
    doc.append(Ref('intro'))
    doc.append(', this research uses the following methods.')

# Page references
doc.append('See page ')
doc.append(Pageref('methods'))
doc.append(' for detailed methodology.')

Install with Tessl CLI

npx tessl i tessl/pypi-pylatex

docs

base-classes.md

configuration.md

document.md

figures.md

index.md

layout.md

lists.md

math.md

quantities.md

references.md

sectioning.md

tables.md

text-formatting.md

tikz.md

utilities.md

tile.json