CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-bibtexparser

A comprehensive BibTeX parser library for Python 3 that enables parsing and writing of bibliographic data files

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

advanced-writing.mddocs/

Advanced Writing Configuration

Configurable writer with extensive formatting options for controlling BibTeX output format. The BibTexWriter class provides fine-grained control over indentation, alignment, field ordering, entry sorting, and various BibTeX syntax styles.

Capabilities

Writer Configuration

The BibTexWriter class provides comprehensive formatting control to generate BibTeX output that matches specific style requirements or personal preferences.

class BibTexWriter:
    """
    Writer to convert a BibDatabase object to a BibTeX-formatted string or file.
    
    Provides extensive configuration options for controlling output formatting
    including field ordering, indentation, alignment, and entry sorting.
    """
    
    def __init__(self, write_common_strings: bool = False):
        """
        Create a configurable BibTeX writer.

        Parameters:
        - write_common_strings (bool): If True, include common string definitions in output

        Attributes that can be configured after initialization:
        - contents (list): Elements to write ['comments', 'preambles', 'strings', 'entries']
        - indent (str): Characters for indenting field-value pairs
        - align_values (bool|int): Align field values by padding with spaces
        - align_multiline_values (bool): Align continuation lines in multiline values
        - entry_separator (str): Characters separating entries
        - order_entries_by (tuple): Fields for sorting entries
        - display_order (list): Preferred field order within entries
        - display_order_sorting (SortingStrategy): How to sort unlisted fields
        - comma_first (bool): Use comma-first syntax
        - add_trailing_comma (bool): Add comma after last field
        """

String Generation

Convert BibDatabase objects to formatted BibTeX strings with all configured formatting options applied.

def write(self, bib_database: BibDatabase) -> str:
    """
    Convert a bibliographic database to a BibTeX-formatted string.

    Parameters:
    - bib_database (BibDatabase): Database to convert

    Returns:
    str: BibTeX-formatted string with all formatting options applied
    """

Sorting Strategy

Enumeration defining different strategies for sorting fields not explicitly specified in display_order.

class SortingStrategy(Enum):
    """Defines sorting strategies for fields not in display_order."""
    
    ALPHABETICAL_ASC = auto()  # Alphabetical sorting in ascending order
    ALPHABETICAL_DESC = auto()  # Alphabetical sorting in descending order  
    PRESERVE = auto()  # Preserve original field order

Legacy Convenience Function

Backwards-compatible convenience function for simple writing tasks.

def to_bibtex(parsed: BibDatabase) -> str:
    """
    Convenience function for backwards compatibility.
    
    Parameters:
    - parsed (BibDatabase): Database to convert
    
    Returns:
    str: BibTeX-formatted string using default writer settings
    """

Configuration Options

Content Selection

Control which elements are included in the output:

from bibtexparser.bwriter import BibTexWriter

writer = BibTexWriter()

# Include all elements (default)
writer.contents = ['comments', 'preambles', 'strings', 'entries']

# Only include entries
writer.contents = ['entries']

# Custom order
writer.contents = ['preambles', 'entries', 'comments']

Indentation and Alignment

Configure spacing and alignment for readable output:

# Custom indentation (default is single space)
writer.indent = '  '  # Two spaces
writer.indent = '\t'  # Tab character

# Align field values
writer.align_values = True  # Auto-calculate alignment width
writer.align_values = 20    # Fixed alignment width
writer.align_values = False # No alignment (default)

# Align multiline values
writer.align_multiline_values = True

Entry Sorting

Control the order in which entries appear in the output:

# Sort by entry ID (default)
writer.order_entries_by = ('ID',)

# Sort by multiple fields
writer.order_entries_by = ('ENTRYTYPE', 'author', 'year')

# Disable sorting (preserve original order)
writer.order_entries_by = None

Field Ordering

Control the order of fields within each entry:

from bibtexparser.bwriter import SortingStrategy

# Specify preferred field order
writer.display_order = ['title', 'author', 'journal', 'year']

# Configure how unlisted fields are sorted
writer.display_order_sorting = SortingStrategy.ALPHABETICAL_ASC  # Default
writer.display_order_sorting = SortingStrategy.ALPHABETICAL_DESC
writer.display_order_sorting = SortingStrategy.PRESERVE

Syntax Style

Configure BibTeX syntax variations:

# Comma-first syntax (common in functional languages)
writer.comma_first = True  # Default is False

# Add trailing comma after last field
writer.add_trailing_comma = True  # Default is False

# Entry separator (default is newline)
writer.entry_separator = '\n\n'  # Double newline

Usage Examples

Clean Academic Format

from bibtexparser.bwriter import BibTexWriter, SortingStrategy

writer = BibTexWriter()
writer.indent = '  '
writer.align_values = True
writer.order_entries_by = ('ENTRYTYPE', 'year', 'author')
writer.display_order = ['title', 'author', 'journal', 'volume', 'pages', 'year']
writer.display_order_sorting = SortingStrategy.ALPHABETICAL_ASC

bibtex_str = writer.write(bib_database)

Compact Format

writer = BibTexWriter()
writer.indent = ''
writer.align_values = False
writer.entry_separator = '\n'
writer.contents = ['entries']  # Only entries, no comments/preambles

bibtex_str = writer.write(bib_database)

Comma-First Style

writer = BibTexWriter()
writer.comma_first = True
writer.add_trailing_comma = True
writer.indent = '  '

# Output format:
# @article{key
#   , title = {Example}
#   , author = {Author}
#   ,
# }

Custom Field Processing

from bibtexparser.bwriter import BibTexWriter

class CustomBibTexWriter(BibTexWriter):
    def _entry_to_bibtex(self, entry):
        # Override to add custom processing
        # Process entry before writing
        processed_entry = entry.copy()
        
        # Custom field transformations
        if 'doi' in processed_entry:
            processed_entry['doi'] = f"https://doi.org/{processed_entry['doi']}"
            
        return super()._entry_to_bibtex(processed_entry)

writer = CustomBibTexWriter()

Complete Configuration Example

from bibtexparser.bwriter import BibTexWriter, SortingStrategy

writer = BibTexWriter(write_common_strings=False)

# Content and structure
writer.contents = ['preambles', 'strings', 'entries', 'comments']
writer.entry_separator = '\n\n'

# Formatting
writer.indent = '    '  # 4 spaces
writer.align_values = 25
writer.align_multiline_values = True

# Entry ordering
writer.order_entries_by = ('ENTRYTYPE', 'year', 'author')

# Field ordering
writer.display_order = [
    'title', 'author', 'editor', 'journal', 'booktitle',
    'volume', 'number', 'pages', 'year', 'publisher', 'address'
]
writer.display_order_sorting = SortingStrategy.ALPHABETICAL_ASC

# Syntax style
writer.comma_first = False
writer.add_trailing_comma = True

# Generate formatted output
formatted_bibtex = writer.write(bib_database)

# Save to file with custom writer
with open('formatted_output.bib', 'w') as f:
    f.write(formatted_bibtex)

Writer for Different Output Contexts

# Configuration for journal submission
journal_writer = BibTexWriter()
journal_writer.indent = ' '
journal_writer.align_values = False
journal_writer.order_entries_by = ('author', 'year')
journal_writer.display_order = ['author', 'title', 'journal', 'volume', 'pages', 'year']

# Configuration for personal reference management
personal_writer = BibTexWriter()
personal_writer.indent = '  '
personal_writer.align_values = True
personal_writer.order_entries_by = ('year', 'author')
personal_writer.contents = ['entries']  # No comments for cleaner output

Install with Tessl CLI

npx tessl i tessl/pypi-bibtexparser@1.4.2

docs

advanced-parsing.md

advanced-writing.md

basic-operations.md

bibtex-expression.md

data-model.md

entry-customization.md

index.md

latex-encoding.md

tile.json