all2md.options

Configuration options and settings for all2md conversion modules.

This module provides dataclass-based configuration options for all conversion modules in the all2md library. Using dataclasses provides type safety, default values, and a clean API for configuring conversion behavior.

Each converter module has its own Options dataclass with module-specific parameters.

class all2md.options.CloneFrozenMixin

Bases: object

Mixin providing frozen dataclass cloning capabilities.

This mixin adds the ability to create modified copies of frozen dataclass instances, which is useful for immutable configuration objects.

create_updated(**kwargs: Any) Self

Create a new instance with updated field values.

Parameters:

**kwargs (Any) – Field names and their new values

Returns:

New instance with specified fields updated

Return type:

Self

__init__() None
class all2md.options.BaseRendererOptions

Bases: CloneFrozenMixin

Base class for all renderer options.

This class serves as the foundation for format-specific renderer options. Renderers convert AST documents into various output formats (Markdown, DOCX, PDF, etc.).

Parameters:
  • fail_on_resource_errors (bool, default=False) – Whether to raise RenderingError when resource loading fails (e.g., images). If False (default), warnings are logged but rendering continues. If True, rendering stops immediately on resource errors.

  • max_asset_size_bytes (int) – Maximum allowed size in bytes for any single asset (images, downloads, etc.)

Notes

Subclasses should define format-specific rendering options as frozen dataclass fields.

fail_on_resource_errors: bool = False
max_asset_size_bytes: int = 52428800
metadata_policy: MetadataRenderPolicy
creator: str | None = 'all2md'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md') None
class all2md.options.BaseParserOptions

Bases: CloneFrozenMixin

Base class for all parser options.

This class serves as the foundation for format-specific parser options. Parsers convert source documents into AST representation.

For parsers that handle attachments (images, downloads, etc.), also inherit from AttachmentOptionsMixin to get attachment-related configuration fields.

Parameters:

extract_metadata (bool) – Whether to extract document metadata

Notes

Subclasses should define format-specific parsing options as frozen dataclass fields.

For parsers handling binary assets (PDF, DOCX, HTML, etc.), also inherit from AttachmentOptionsMixin:

@dataclass(frozen=True)
class PdfOptions(BaseParserOptions, AttachmentOptionsMixin):
    pass
extract_metadata: bool = False
__init__(extract_metadata: bool = False) None
class all2md.options.AttachmentOptionsMixin

Bases: CloneFrozenMixin

Mixin providing attachment handling options for parsers.

This mixin adds attachment-related configuration options to parser classes that need to handle embedded images, downloads, and other binary assets. Only parsers that actually process attachments should inherit from this mixin.

Parameters:
  • attachment_mode (AttachmentMode) – How to handle attachments/images during parsing

  • alt_text_mode (AltTextMode) – How to render alt-text content

  • attachment_output_dir (str or None) – Directory to save attachments when using save mode

  • attachment_base_url (str or None) – Base URL for resolving attachment references

  • max_asset_size_bytes (int) – Maximum allowed size in bytes for any single asset

  • attachment_filename_template (str) – Template for attachment filenames

  • attachment_overwrite (Literal["unique", "overwrite", "skip"]) – File collision strategy

  • attachment_deduplicate_by_hash (bool) – Avoid saving duplicate attachments by content hash

  • attachments_footnotes_section (str or None) – Section title for footnote-style attachment references

Notes

This mixin should be used by parsers that handle formats with embedded images or binary assets (PDF, DOCX, HTML, EPUB, etc.). Pure text formats (CSV, plaintext, source code) should not use this mixin.

Examples

Parser with attachments:

@dataclass(frozen=True)
class PdfOptions(BaseParserOptions, AttachmentOptionsMixin):
    # PDF-specific options here
    pass

Pure text parser without attachments:

@dataclass(frozen=True)
class CsvOptions(BaseParserOptions):
    # CSV-specific options here
    pass
attachment_mode: Literal['skip', 'alt_text', 'save', 'base64'] = 'alt_text'
alt_text_mode: Literal['default', 'plain_filename', 'strict_markdown', 'footnote'] = 'default'
attachment_output_dir: str | None = None
attachment_base_url: str | None = None
max_asset_size_bytes: int = 52428800
attachment_filename_template: str = '{stem}_{type}{seq}.{ext}'
attachment_overwrite: Literal['unique', 'overwrite', 'skip'] = 'unique'
attachment_deduplicate_by_hash: bool = False
attachments_footnotes_section: str | None = 'Attachments'
__init__(attachment_mode: Literal['skip', 'alt_text', 'save', 'base64'] = 'alt_text', alt_text_mode: Literal['default', 'plain_filename', 'strict_markdown', 'footnote'] = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: Literal['unique', 'overwrite', 'skip'] = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments') None
class all2md.options.NetworkFetchOptions

Bases: CloneFrozenMixin

Network security options for remote resource fetching.

This dataclass contains settings that control how remote resources (images, CSS, etc.) are fetched, including security constraints to prevent SSRF attacks.

Parameters:
  • allow_remote_fetch (bool, default False) – Whether to allow fetching remote URLs for images and other resources. When False, prevents SSRF attacks by blocking all network requests.

  • allowed_hosts (list[str] | None, default None) – List of allowed hostnames or CIDR blocks for remote fetching. If None and allow_remote_fetch=True, all hosts are allowed, which may pose an SSRF (Server-Side Request Forgery) risk. A security warning will be logged. In security-sensitive contexts, explicitly set this to an allowlist of trusted hosts.

  • require_https (bool, default True) – Whether to require HTTPS for all remote URL fetching.

  • require_head_success (bool, default True) – Whether to require a successful HEAD request before fetching remote URLs.

  • network_timeout (float, default 10.0) – Timeout in seconds for remote URL fetching.

  • max_requests_per_second (float, default 10.0) – Maximum number of network requests per second (rate limiting).

  • max_concurrent_requests (int, default 5) – Maximum number of concurrent network requests.

Notes

Asset size limits are inherited from BaseParserOptions.max_asset_size_bytes.

allow_remote_fetch: bool = False
allowed_hosts: list[str] | None = None
require_https: bool = True
require_head_success: bool = True
network_timeout: float = 10.0
max_redirects: int = 5
allowed_content_types: tuple[str, ...] | None = ('image/',)
max_requests_per_second: float = 10.0
max_concurrent_requests: int = 5
__init__(allow_remote_fetch: bool = False, allowed_hosts: list[str] | None = None, require_https: bool = True, require_head_success: bool = True, network_timeout: float = 10.0, max_redirects: int = 5, allowed_content_types: tuple[str, ...] | None = ('image/',), max_requests_per_second: float = 10.0, max_concurrent_requests: int = 5) None
class all2md.options.LocalFileAccessOptions

Bases: CloneFrozenMixin

Local file access security options.

This dataclass contains settings that control access to local files via file:// URLs and similar mechanisms.

Parameters:
  • allow_local_files (bool, default False) – Whether to allow access to local files via file:// URLs.

  • local_file_allowlist (list[str] | None, default None) – List of directories allowed for local file access. Only applies when allow_local_files=True.

  • local_file_denylist (list[str] | None, default None) – List of directories denied for local file access.

  • allow_cwd_files (bool, default False) – Whether to allow local files from current working directory and subdirectories.

allow_local_files: bool = False
local_file_allowlist: list[str] | None = None
local_file_denylist: list[str] | None = None
allow_cwd_files: bool = False
__init__(allow_local_files: bool = False, local_file_allowlist: list[str] | None = None, local_file_denylist: list[str] | None = None, allow_cwd_files: bool = False) None
class all2md.options.AsciiDocRendererOptions

Bases: BaseRendererOptions

Configuration options for AST-to-AsciiDoc rendering.

This dataclass contains settings for rendering AST documents as AsciiDoc output.

Parameters:
  • list_indent (int, default 2) – Number of spaces for nested list indentation.

  • use_attributes (bool, default True) – Whether to include document attributes in output. When True, renders :name: value attributes at document start.

  • line_length (int, default 0) – Target line length for wrapping text (0 = no wrapping).

  • html_passthrough_mode ({"pass-through", "escape", "drop", "sanitize"}, default "pass-through") – How to handle HTMLBlock and HTMLInline nodes: - “pass-through”: Pass through unchanged (use only with trusted content) - “escape”: HTML-escape the content - “drop”: Remove HTML content entirely - “sanitize”: Remove dangerous elements/attributes (requires bleach for best results)

  • comment_mode ({"comment", "note", "ignore"}, default "comment") – How to render Comment and CommentInline AST nodes: - “comment”: Render as AsciiDoc comments (// Comment text) - “note”: Render as NOTE admonition blocks (visible annotations) - “ignore”: Skip comment nodes entirely This is the sole option controlling comment rendering behavior.

list_indent: int = 2
use_attributes: bool = True
line_length: int = 0
html_passthrough_mode: Literal['pass-through', 'escape', 'drop', 'sanitize'] = 'escape'
comment_mode: Literal['comment', 'note', 'ignore'] = 'comment'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', list_indent: int = 2, use_attributes: bool = True, line_length: int = 0, html_passthrough_mode: HtmlPassthroughMode = 'escape', comment_mode: AsciiDocCommentMode = 'comment') None
class all2md.options.AsciiDocOptions

Bases: BaseParserOptions

Configuration options for AsciiDoc-to-AST parsing.

This dataclass contains settings specific to parsing AsciiDoc documents into AST representation using a custom parser.

Parameters:
  • parse_attributes (bool, default True) – Whether to parse document attributes (:name: value syntax). When True, attributes are collected and can be referenced.

  • parse_admonitions (bool, default True) – Whether to parse admonition blocks ([NOTE], [IMPORTANT], etc.). When True, admonitions are converted to appropriate AST nodes.

  • parse_includes (bool, default False) – Whether to process include directives (include::file[]). SECURITY: Disabled by default to prevent file system access.

  • strict_mode (bool, default False) – Whether to raise errors on invalid AsciiDoc syntax. When False, attempts to recover gracefully.

  • resolve_attribute_refs (bool, default True) – Whether to resolve attribute references ({name}) in text. When True, {name} is replaced with attribute value.

  • strip_comments (bool, default False) – Whether to strip comments (// syntax) instead of preserving as Comment nodes. When False, comments are preserved as Comment AST nodes with comment_type=’asciidoc’.

parse_attributes: bool = True
parse_admonitions: bool = True
parse_includes: bool = False
strict_mode: bool = False
resolve_attribute_refs: bool = True
attribute_missing_policy: Literal['keep', 'blank', 'warn'] = 'keep'
support_unconstrained_formatting: bool = True
table_header_detection: Literal['first-row', 'attribute-based', 'auto'] = 'attribute-based'
honor_hard_breaks: bool = True
parse_table_spans: bool = True
strip_comments: bool = False
__init__(extract_metadata: bool = False, parse_attributes: bool = True, parse_admonitions: bool = True, parse_includes: bool = False, strict_mode: bool = False, resolve_attribute_refs: bool = True, attribute_missing_policy: Literal['keep', 'blank', 'warn'] = 'keep', support_unconstrained_formatting: bool = True, table_header_detection: Literal['first-row', 'attribute-based', 'auto'] = 'attribute-based', honor_hard_breaks: bool = True, parse_table_spans: bool = True, strip_comments: bool = False) None
class all2md.options.AstJsonParserOptions

Bases: BaseParserOptions

Options for parsing JSON AST documents.

Parameters:
  • validate_schema (bool, default = True) – Whether to validate the schema version during parsing

  • strict_mode (bool, default = False) – Whether to fail on unknown node types or attributes

validate_schema: bool = True
strict_mode: bool = False
__init__(extract_metadata: bool = False, validate_schema: bool = True, strict_mode: bool = False) None
class all2md.options.AstJsonRendererOptions

Bases: BaseRendererOptions

Options for rendering documents to JSON AST format.

Parameters:
  • indent (int or None, default = 2) – Number of spaces for JSON indentation. None for compact output.

  • ensure_ascii (bool, default = False) – Whether to escape non-ASCII characters in JSON output

  • sort_keys (bool, default = False) – Whether to sort JSON object keys alphabetically

Examples

Compact JSON output:
>>> options = AstJsonRendererOptions(indent=None)
Pretty-printed JSON with sorted keys:
>>> options = AstJsonRendererOptions(indent=2, sort_keys=True)
ASCII-only output:
>>> options = AstJsonRendererOptions(ensure_ascii=True)
indent: int | None = 2
ensure_ascii: bool = False
sort_keys: bool = False
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', indent: int | None = 2, ensure_ascii: bool = False, sort_keys: bool = False) None
class all2md.options.ChmOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for CHM-to-Markdown conversion.

This dataclass contains settings specific to Microsoft Compiled HTML Help (CHM) document processing, including page handling, table of contents generation, and HTML parsing configuration. Inherits attachment handling from AttachmentOptionsMixin for embedded images and resources.

Parameters:
  • include_toc (bool, default True) – Whether to generate and prepend a Markdown Table of Contents from the CHM’s internal TOC structure at the start of the document.

  • merge_pages (bool, default True) – Whether to merge all pages into a single continuous document. If False, pages are separated with thematic breaks.

  • html_options (HtmlOptions or None, default None) – Options for parsing HTML content within the CHM file. If None, uses default HTML parsing options.

include_toc: bool = True
merge_pages: bool = True
html_options: HtmlOptions | None = None
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, include_toc: bool = True, merge_pages: bool = True, html_options: HtmlOptions | None = None) None
class all2md.options.CsvOptions

Bases: BaseParserOptions

Configuration options for CSV/TSV conversion.

This dataclass contains settings specific to delimiter-separated value file processing, including dialect detection and data limits.

Parameters:
  • detect_csv_dialect (bool, default True) – Enable csv.Sniffer-based dialect detection (ignored if csv_delimiter is set).

  • delimiter (str | None, default None) – Override CSV/TSV delimiter (e.g., ‘,’, ‘\t’, ‘;’, ‘|’). When set, disables dialect detection.

  • quote_char (str | None, default None) – Override quote character (e.g., ‘”’, “’”). When set, uses this for quoting.

  • escape_char (str | None, default None) – Override escape character (e.g., ‘\’). When set, uses this for escaping.

  • double_quote (bool | None, default None) – Enable/disable double quoting (two quote chars = one literal quote). When set, overrides dialect’s doublequote setting.

  • has_header (bool, default True) – Whether the first row contains column headers. When False, generates generic headers (Column 1, Column 2, etc.).

  • max_rows (int | None, default None) – Maximum number of data rows per table (excluding header). None = unlimited.

  • max_cols (int | None, default None) – Maximum number of columns per table. None = unlimited.

  • truncation_indicator (str, default "...") – Appended note when rows/columns are truncated.

  • header_case (str, default "preserve") – Transform header case: preserve, title, upper, or lower.

  • skip_empty_rows (bool, default True) – Whether to skip completely empty rows.

  • strip_whitespace (bool, default False) – Whether to strip leading/trailing whitespace from all cells.

  • dialect_sample_size (int, default 4096) – Number of bytes to sample for csv.Sniffer dialect detection. Larger values may improve detection for heavily columnated files but increase memory usage during detection.

detect_csv_dialect: bool = True
dialect_sample_size: int = 4096
delimiter: str | None = None
quote_char: str | None = None
escape_char: str | None = None
double_quote: bool | None = None
has_header: bool = True
max_rows: int | None = None
max_cols: int | None = None
truncation_indicator: str = '...'
header_case: Literal['preserve', 'title', 'upper', 'lower'] = 'preserve'
skip_empty_rows: bool = True
strip_whitespace: bool = False
__init__(extract_metadata: bool = False, detect_csv_dialect: bool = True, dialect_sample_size: int = 4096, delimiter: str | None = None, quote_char: str | None = None, escape_char: str | None = None, double_quote: bool | None = None, has_header: bool = True, max_rows: int | None = None, max_cols: int | None = None, truncation_indicator: str = '...', header_case: Literal['preserve', 'title', 'upper', 'lower'] = 'preserve', skip_empty_rows: bool = True, strip_whitespace: bool = False) None
class all2md.options.DocxOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for DOCX-to-Markdown conversion.

This dataclass contains settings specific to Word document processing, including image handling and formatting preferences. Inherits attachment handling from AttachmentOptionsMixin for embedded images and media.

Parameters:

preserve_tables (bool, default True) – Whether to preserve table formatting in Markdown.

Examples

Convert with base64 image embedding:
>>> options = DocxOptions(attachment_mode="base64")
preserve_tables: bool = True
include_footnotes: bool = True
include_endnotes: bool = True
include_comments: bool = False
comments_position: Literal['inline', 'footnotes'] = 'footnotes'
include_image_captions: bool = True
code_style_names: list[str]
code_char_style_names: list[str]
quote_style_names: list[str]
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, preserve_tables: bool = True, include_footnotes: bool = True, include_endnotes: bool = True, include_comments: bool = False, comments_position: Literal['inline', 'footnotes']='footnotes', include_image_captions: bool = True, code_style_names: list[str] = <factory>, code_char_style_names: list[str] = <factory>, quote_style_names: list[str] = <factory>) None
class all2md.options.DocxRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST to DOCX format.

This dataclass contains settings specific to Word document generation, including fonts, styles, and formatting preferences.

Parameters:
  • default_font (str, default "Calibri") – Default font name for body text.

  • default_font_size (int, default 11) – Default font size in points for body text.

  • heading_font_sizes (dict[int, int] or None, default None) – Font sizes for heading levels 1-6. If None, uses built-in Word heading styles.

  • use_styles (bool, default True) – Whether to use built-in Word styles vs direct formatting.

  • table_style (str or None, default "Light Grid Accent 1") – Built-in table style name. If None, uses plain table formatting.

  • code_font (str, default "Courier New") – Font name for code blocks and inline code.

  • code_font_size (int, default 10) – Font size for code blocks and inline code.

  • preserve_formatting (bool, default True) – Whether to preserve text formatting (bold, italic, etc.).

  • template_path (str or None, default None) – Path to .docx template file. When specified, the renderer uses the template’s styles (headings, body text, etc.) instead of creating a blank document. This is powerful for corporate environments where documents must adopt specific style guidelines defined in a template.

  • network (NetworkFetchOptions, default NetworkFetchOptions()) – Network security settings for fetching remote images. By default, remote image fetching is disabled (allow_remote_fetch=False). Set network.allow_remote_fetch=True to enable secure remote image fetching with the same security guardrails as PPTX renderer.

  • comment_mode ({"native", "visible", "ignore"}, default "native") – How to render Comment and CommentInline AST nodes: - “native”: Use python-docx native comment API (preserves Word comments when possible) - “visible”: Render as regular text paragraphs with attribution - “ignore”: Skip comment nodes entirely This controls presentation of comments from DOCX source files and other formats.

  • promote_title (bool, default True) – When True, a leading H1 is rendered with Word’s “Title” style instead of “Heading 1”, and all subsequent headings are promoted by one level (H2 → Heading 1, H3 → Heading 2, etc.). Set to False to keep all H1s as “Heading 1”.

default_font: str = 'Calibri'
default_font_size: int = 11
heading_font_sizes: dict[int, int] | None = None
use_styles: bool = True
table_style: str | None = 'Light Grid Accent 1'
code_font: str = 'Courier New'
code_font_size: int = 10
preserve_formatting: bool = True
template_path: str | None = None
clear_template_body: bool = False
comment_mode: Literal['native', 'visible', 'ignore'] = 'native'
promote_title: bool = True
network: NetworkFetchOptions
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', default_font: str = 'Calibri', default_font_size: int = 11, heading_font_sizes: dict[int, int] | None=None, use_styles: bool = True, table_style: str | None = 'Light Grid Accent 1', code_font: str = 'Courier New', code_font_size: int = 10, preserve_formatting: bool = True, template_path: str | None = None, clear_template_body: bool = False, comment_mode: Literal['native', 'visible', 'ignore']='native', promote_title: bool = True, network: NetworkFetchOptions = <factory>) None
class all2md.options.DokuWikiOptions

Bases: BaseRendererOptions

Configuration options for DokuWiki rendering.

This dataclass contains settings for rendering AST documents as DokuWiki markup, suitable for DokuWiki-based wikis.

Parameters:
  • use_html_for_unsupported (bool, default True) – Whether to use HTML tags as fallback for unsupported elements. When True, unsupported formatting uses HTML tags (e.g., <del>strikethrough</del>). When False, unsupported formatting is stripped.

  • monospace_fence (bool, default False) – Whether to use fence syntax for monospace text. When True, inline code uses <code>text</code>. When False, inline code uses double single quotes (DokuWiki native).

  • html_passthrough_mode ({"pass-through", "escape", "drop", "sanitize"}, default "pass-through") – How to handle HTMLBlock and HTMLInline nodes: - “pass-through”: Pass through unchanged (use only with trusted content) - “escape”: HTML-escape the content - “drop”: Remove HTML content entirely - “sanitize”: Remove dangerous elements/attributes (requires bleach for best results)

  • comment_mode ({"html", "visible", "ignore"}, default "html") – How to render Comment and CommentInline AST nodes: - “html”: Use HTML/C-style comments (default) - “visible”: Render as visible text - “ignore”: Skip comments entirely

Examples

Basic DokuWiki rendering:
>>> from all2md.ast import Document, Heading, Text
>>> from all2md.renderers.dokuwiki import DokuWikiRenderer
>>> from all2md.options.dokuwiki import DokuWikiOptions
>>> doc = Document(children=[
...     Heading(level=1, content=[Text(content="Title")])
... ])
>>> options = DokuWikiOptions()
>>> renderer = DokuWikiRenderer(options)
>>> wiki_text = renderer.render_to_string(doc)
use_html_for_unsupported: bool = True
monospace_fence: bool = False
html_passthrough_mode: Literal['pass-through', 'escape', 'drop', 'sanitize'] = 'escape'
comment_mode: Literal['html', 'visible', 'ignore'] = 'html'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', use_html_for_unsupported: bool = True, monospace_fence: bool = False, html_passthrough_mode: HtmlPassthroughMode = 'escape', comment_mode: DokuWikiCommentMode = 'html') None
class all2md.options.DokuWikiParserOptions

Bases: BaseParserOptions

Configuration options for DokuWiki-to-AST parsing.

This dataclass contains settings specific to parsing DokuWiki markup documents into AST representation using custom regex-based parsing.

Parameters:
  • parse_plugins (bool, default False) – Whether to parse plugin syntax (e.g., <WRAP>, <button>) or strip them. When True, plugin tags are converted to HTMLInline/HTMLBlock nodes. When False, plugin tags are completely removed from the output.

  • strip_comments (bool, default True) – Whether to strip comments from the output. Strips both C-style (/* ... */) and HTML (<!-- ... -->) comments. When True, comments are removed completely. When False, comments are preserved as HTMLInline nodes.

  • parse_interwiki (bool, default True) – Whether to parse interwiki links (e.g., [[wp>Article]]). When True, interwiki links are preserved in Link nodes. When False, interwiki syntax is treated as regular internal links.

  • html_passthrough_mode ({"pass-through", "escape", "drop", "sanitize"}, default "escape") – How to handle inline HTML in DokuWiki markup: - “pass-through”: Preserve HTML unchanged (use only with trusted content) - “escape”: HTML-escape the content to display as text - “drop”: Remove HTML content entirely - “sanitize”: Remove dangerous elements/attributes

Examples

Basic usage:
>>> options = DokuWikiParserOptions()
>>> parser = DokuWikiParser(options)
Parse plugin syntax as HTML:
>>> options = DokuWikiParserOptions(parse_plugins=True)
>>> parser = DokuWikiParser(options)
parse_plugins: bool = False
strip_comments: bool = True
parse_interwiki: bool = True
html_passthrough_mode: Literal['pass-through', 'escape', 'drop', 'sanitize'] = 'escape'
__init__(extract_metadata: bool = False, parse_plugins: bool = False, strip_comments: bool = True, parse_interwiki: bool = True, html_passthrough_mode: Literal['pass-through', 'escape', 'drop', 'sanitize'] = 'escape') None
class all2md.options.EmlOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for EML-to-Markdown conversion.

This dataclass contains settings specific to email message processing, including robust parsing, date handling, quote processing, and URL cleaning. Inherits attachment handling from AttachmentOptionsMixin for email attachments.

Parameters:
  • include_headers (bool, default True) – Whether to include email headers (From, To, Subject, Date) in output.

  • preserve_thread_structure (bool, default True) – Whether to maintain email thread/reply chain structure.

  • date_format_mode ({"iso8601", "locale", "strftime"}, default "strftime") – How to format dates in output: - “iso8601”: Use ISO 8601 format (2023-01-01T10:00:00Z) - “locale”: Use system locale-aware formatting - “strftime”: Use custom strftime pattern

  • date_strftime_pattern (str, default "%m/%d/%y %H:%M") – Custom strftime pattern when date_format_mode is “strftime”.

  • convert_html_to_markdown (bool, default False) – Whether to convert HTML content to Markdown When True, HTML parts are converted to Markdown; when False, HTML is preserved as-is.

  • clean_quotes (bool, default True) – Whether to clean and normalize quoted content (”> “ prefixes, etc.).

  • detect_reply_separators (bool, default True) – Whether to detect common reply separators like “On <date>, <name> wrote:”.

  • normalize_headers (bool, default True) – Whether to normalize header casing and whitespace.

  • preserve_raw_headers (bool, default False) – Whether to preserve both raw and decoded header values.

  • clean_wrapped_urls (bool, default True) – Whether to clean URL defense/safety wrappers from links.

  • url_wrappers (list[str], default from constants) – List of URL wrapper domains to clean (urldefense.com, safelinks, etc.).

Examples

Convert email with ISO 8601 date formatting:
>>> options = EmlOptions(date_format_mode="iso8601")
Convert with HTML-to-Markdown conversion enabled:
>>> options = EmlOptions(convert_html_to_markdown=True)
Disable quote cleaning and URL unwrapping:
>>> options = EmlOptions(clean_quotes=False, clean_wrapped_urls=False)
include_headers: bool = True
preserve_thread_structure: bool = True
date_format_mode: Literal['iso8601', 'locale', 'strftime'] = 'strftime'
date_strftime_pattern: str = '%m/%d/%y %H:%M'
convert_html_to_markdown: bool = False
clean_quotes: bool = True
detect_reply_separators: bool = True
normalize_headers: bool = True
preserve_raw_headers: bool = False
clean_wrapped_urls: bool = True
url_wrappers: list[str] | None
html_network: NetworkFetchOptions
sort_order: Literal['asc', 'desc'] = 'asc'
subject_as_h1: bool = True
include_attach_section_heading: bool = True
attach_section_title: str = 'Attachments'
include_html_parts: bool = True
include_plain_parts: bool = True
include_rtf_parts: bool = True
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, include_headers: bool = True, preserve_thread_structure: bool = True, date_format_mode: DateFormatMode = 'strftime', date_strftime_pattern: str = '%m/%d/%y %H:%M', convert_html_to_markdown: bool = False, clean_quotes: bool = True, detect_reply_separators: bool = True, normalize_headers: bool = True, preserve_raw_headers: bool = False, clean_wrapped_urls: bool = True, url_wrappers: list[str] | None = <factory>, html_network: NetworkFetchOptions = <factory>, sort_order: EmailSortOrder = 'asc', subject_as_h1: bool = True, include_attach_section_heading: bool = True, attach_section_title: str = 'Attachments', include_html_parts: bool = True, include_plain_parts: bool = True, include_rtf_parts: bool = True) None
class all2md.options.EpubOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for EPUB-to-Markdown conversion.

This dataclass contains settings specific to EPUB document processing, including chapter handling, table of contents generation, and image handling. Inherits attachment handling from AttachmentOptionsMixin for embedded images.

Parameters:
  • merge_chapters (bool, default True) – Whether to merge chapters into a single continuous document. If False, a separator is placed between chapters.

  • include_toc (bool, default True) – Whether to generate and prepend a Markdown Table of Contents.

merge_chapters: bool = True
include_toc: bool = True
html_options: HtmlOptions | None = None
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, merge_chapters: bool = True, include_toc: bool = True, html_options: HtmlOptions | None = None) None
class all2md.options.EpubRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST to EPUB format.

This dataclass contains settings specific to EPUB generation from AST, including chapter splitting strategies, metadata, and EPUB structure.

Parameters:
  • chapter_split_mode ({"separator", "heading", "auto"}, default "auto") – How to split the AST into chapters: - “separator”: Split on ThematicBreak nodes (mirrors parser behavior) - “heading”: Split on specific heading level - “auto”: Try separator first, fallback to heading-based splitting

  • chapter_split_heading_level (int, default 1) – Heading level to use for chapter splits when using heading mode. Level 1 (H1) typically represents chapter boundaries.

  • title (str or None, default None) – EPUB book title. If None, extracted from document metadata.

  • author (str or None, default None) – EPUB book author. If None, extracted from document metadata.

  • language (str, default "en") – EPUB book language code (ISO 639-1).

  • identifier (str or None, default None) – Unique identifier (ISBN, UUID, etc.). Auto-generated if None.

  • chapter_title_template (str, default "Chapter {num}") – Template for auto-generated chapter titles. Supports {num} placeholder.

  • use_heading_as_chapter_title (bool, default True) – Use first heading in chapter as chapter title in NCX/navigation.

  • generate_toc (bool, default True) – Generate table of contents (NCX and nav.xhtml files).

  • include_cover (bool, default False) – Include cover image in EPUB package.

  • cover_image_path (str or None, default None) – Path to cover image file. Only used if include_cover=True.

  • network (NetworkFetchOptions, default NetworkFetchOptions()) – Network security options for fetching remote images. By default, remote image fetching is disabled (allow_remote_fetch=False). Set network.allow_remote_fetch=True to enable secure remote image fetching.

chapter_split_mode: Literal['separator', 'heading', 'auto'] = 'auto'
chapter_split_heading_level: int = 1
title: str | None = None
author: str | None = None
language: str = 'en'
identifier: str | None = None
chapter_title_template: str = 'Chapter {num}'
use_heading_as_chapter_title: bool = True
generate_toc: bool = True
include_cover: bool = False
cover_image_path: str | None = None
network: NetworkFetchOptions
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', chapter_split_mode: Literal['separator', 'heading', 'auto']='auto', chapter_split_heading_level: int = 1, title: str | None = None, author: str | None = None, language: str = 'en', identifier: str | None = None, chapter_title_template: str = 'Chapter {num}', use_heading_as_chapter_title: bool = True, generate_toc: bool = True, include_cover: bool = False, cover_image_path: str | None = None, network: NetworkFetchOptions = <factory>) None
class all2md.options.Fb2Options

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for FB2-to-AST conversion.

Inherits attachment handling from AttachmentOptionsMixin for embedded images in FictionBook 2.0 ebooks.

Parameters:
  • include_notes (bool, default True) – Whether to include bodies/sections marked as notes in the output.

  • notes_section_title (str, default "Notes") – Heading text to use when appending collected note sections.

  • fallback_encodings (tuple[str, ...], default ("utf-8", "windows-1251", "koi8-r")) – Additional encodings to try when the XML declaration is missing or parsing fails with the declared encoding.

include_notes: bool = True
notes_section_title: str = 'Notes'
fallback_encodings: tuple[str, ...] = ('utf-8', 'windows-1251', 'koi8-r')
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, include_notes: bool = True, notes_section_title: str = 'Notes', fallback_encodings: tuple[str, ...] = ('utf-8', 'windows-1251', 'koi8-r')) None
class all2md.options.HtmlRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST to HTML format.

This dataclass contains settings specific to HTML generation, including document structure, styling, templating, and feature toggles.

Parameters:
  • standalone (bool, default True) – Generate complete HTML document with <html>, <head>, <body> tags. If False, generates only the content fragment. Ignored when template_mode is not None.

  • css_style ({"inline", "embedded", "external", "none"}, default "embedded") – How to include CSS styles: - “inline”: Add style attributes to elements - “embedded”: Include <style> block in <head> - “external”: Reference external CSS file - “none”: No styling

  • css_file (str or None, default None) – Path to external CSS file (used when css_style=”external”).

  • include_toc (bool, default False) – Generate table of contents from headings.

  • syntax_highlighting (bool, default True) – Add language classes to code blocks for syntax highlighting.

  • render_mermaid (bool, default False) – Render fenced code blocks whose language is mermaid as <pre class="mermaid"> (a hook for a client-side mermaid.js) instead of the usual <pre><code>. Used by the view/serve commands.

  • escape_html (bool, default True) – Escape HTML special characters in text content.

  • math_renderer ({"mathjax", "katex", "none"}, default "mathjax") – Math rendering library to use for MathML/LaTeX math: - “mathjax”: Include MathJax CDN script - “katex”: Include KaTeX CDN script - “none”: Render math as plain text

  • html_passthrough_mode ({"pass-through", "escape", "drop", "sanitize"}, default "pass-through") – How to handle HTMLBlock and HTMLInline nodes: - “pass-through”: Pass through unchanged (use only with trusted content) - “escape”: HTML-escape the content - “drop”: Remove HTML content entirely - “sanitize”: Remove dangerous elements/attributes (requires bleach for best results)

  • language (str, default "en") – Document language code (ISO 639-1) for the <html lang=”…”> attribute. Can be overridden by document metadata.

  • external_links_new_tab (bool, default False) – If True, external links (absolute http/https/ftp/mailto URLs) are rendered with target=”_blank” rel=”noopener noreferrer” so they open in a new tab. Relative and anchor links are unaffected. Used by the view/serve commands.

  • template_mode ({"inject", "replace", "jinja"} or None, default None) – Template mode for rendering HTML: - None: Use standalone mode (default behavior) - “inject”: Inject content into existing HTML file at selector - “replace”: Replace placeholders in template file - “jinja”: Use Jinja2 template engine with full context When set, standalone is ignored.

  • template_file (str or None, default None) – Path to template file (required when template_mode is not None).

  • template_selector (str, default "#content") – CSS selector for injection target (used with template_mode=”inject”).

  • toc_selector (str or None, default None) – CSS selector for separate TOC injection point (used with template_mode=”inject”). If not set, TOC is included with content at template_selector. Allows placing TOC in a different location like a sidebar or header.

  • injection_mode ({"append", "prepend", "replace"}, default "replace") – How to inject content at selector (used with template_mode=”inject”): - “append”: Add content after existing content - “prepend”: Add content before existing content - “replace”: Replace existing content

  • content_placeholder (str, default "{CONTENT}") – Placeholder string to replace with content (used with template_mode=”replace”).

  • css_class_map (dict[str, str | list[str]] or None, default None) – Map AST node type names to custom CSS classes. Example: {“Heading”: “article-heading”, “CodeBlock”: [“code”, “highlight”]}

  • allow_remote_scripts (bool, default False) – Allow loading remote scripts (e.g., MathJax/KaTeX from CDN). Default is False for security - requires explicit opt-in for CDN usage. When False and math_renderer != ‘none’, will raise a warning.

  • csp_enabled (bool, default False) – Add Content-Security-Policy meta tag to standalone HTML documents. Helps prevent XSS attacks by restricting resource loading.

  • csp_policy (str or None, default (secure policy)) – Custom Content-Security-Policy header value. If None, uses default: “default-src ‘self’; script-src ‘self’; style-src ‘self’ ‘unsafe-inline’;”

  • comment_mode ({"native", "visible", "ignore"}, default "native") – How to render Comment and CommentInline AST nodes: - “native”: Render as HTML comments (<!– Comment by Author: text –>) - “visible”: Render as visible <div>/<span> elements with class=”comment” and metadata in data attributes - “ignore”: Skip comment nodes entirely This controls presentation of comments from DOCX reviewer comments, source HTML comments, and other format-specific annotations.

Examples

Inject into existing HTML:
>>> options = HtmlRendererOptions(
...     template_mode="inject",
...     template_file="layout.html",
...     template_selector="#main-content"
... )
Replace placeholders:
>>> options = HtmlRendererOptions(
...     template_mode="replace",
...     template_file="template.html",
...     content_placeholder="{CONTENT}"
... )
Use Jinja2 template:
>>> options = HtmlRendererOptions(
...     template_mode="jinja",
...     template_file="article.html"
... )
Custom CSS classes:
>>> options = HtmlRendererOptions(
...     css_class_map={"Heading": "prose-heading", "CodeBlock": "code-block"}
... )
standalone: bool = True
css_style: Literal['inline', 'embedded', 'external', 'none'] = 'embedded'
css_file: str | None = None
include_toc: bool = False
syntax_highlighting: bool = True
render_mermaid: bool = False
escape_html: bool = True
math_renderer: Literal['mathjax', 'katex', 'none'] = 'mathjax'
html_passthrough_mode: Literal['pass-through', 'escape', 'drop', 'sanitize'] = 'escape'
language: str = 'en'
external_links_new_tab: bool = False
template_mode: Literal['inject', 'replace', 'jinja'] | None = None
template_file: str | None = None
template_selector: str = '#content'
toc_selector: str | None = None
injection_mode: Literal['append', 'prepend', 'replace'] = 'replace'
content_placeholder: str = '{CONTENT}'
css_class_map: dict[str, str | list[str]] | None = None
allow_remote_scripts: bool = False
csp_enabled: bool = True
csp_policy: str | None = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';"
comment_mode: Literal['native', 'visible', 'ignore'] = 'native'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', standalone: bool = True, css_style: CssStyle = 'embedded', css_file: str | None = None, include_toc: bool = False, syntax_highlighting: bool = True, render_mermaid: bool = False, escape_html: bool = True, math_renderer: MathRenderer = 'mathjax', html_passthrough_mode: HtmlPassthroughMode = 'escape', language: str = 'en', external_links_new_tab: bool = False, template_mode: TemplateMode | None = None, template_file: str | None = None, template_selector: str = '#content', toc_selector: str | None = None, injection_mode: InjectionMode = 'replace', content_placeholder: str = '{CONTENT}', css_class_map: dict[str, str | list[str]] | None=None, allow_remote_scripts: bool = False, csp_enabled: bool = True, csp_policy: str | None = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';", comment_mode: HtmlCommentMode = 'native') None
class all2md.options.HtmlOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for HTML-to-Markdown conversion.

This dataclass contains settings specific to HTML document processing, including heading styles, title extraction, image handling, content sanitization, and advanced formatting options. Inherits attachment handling from AttachmentOptionsMixin for images and embedded media.

Parameters:
  • extract_title (bool, default False) – Whether to extract and use the HTML <title> element.

  • convert_nbsp (bool, default False) – Whether to convert non-breaking spaces (&nbsp;) to regular spaces in the output.

  • strip_dangerous_elements (bool, default False) – Whether to remove potentially dangerous HTML elements (script, style, etc.) and event handler attributes (onclick, onload, etc.).

  • strip_framework_attributes (bool, default False) – Whether to remove JavaScript framework attributes (Alpine.js x-, Vue.js v-, Angular ng-, HTMX hx-, etc.) that can execute code in framework contexts. Only needed if output HTML will be rendered in browsers with these frameworks.

  • detect_table_alignment (bool, default True) – Whether to automatically detect table column alignment from CSS/attributes.

  • allowed_attributes (tuple[str, ...] | dict[str, tuple[str, ...]] | None, default None) – Whitelist of allowed HTML attributes. Supports two modes: - Global allowlist: tuple of attribute names applied to all elements - Per-element allowlist: dict mapping element names to tuples of allowed attributes Note: When using CLI, pass complex dict structures as JSON strings for proper parsing.

  • base_url (str or None, default None) – Base URL for resolving relative hrefs in <a> tags. This is separate from attachment_base_url (used for images/assets). Allows precise control over navigational link URLs vs. resource URLs.

Examples

Convert and extract page title:
>>> options = HtmlOptions(extract_title=True)
Convert with content sanitization:
>>> options = HtmlOptions(strip_dangerous_elements=True, convert_nbsp=True)
Use global attribute allowlist:
>>> options = HtmlOptions(allowed_attributes=('class', 'id', 'href', 'src'))
Use per-element attribute allowlist:
>>> options = HtmlOptions(allowed_attributes={
...     'img': ('src', 'alt', 'title'),
...     'a': ('href', 'title'),
...     'div': ('class', 'id')
... })
Extract only the readable article content:
>>> options = HtmlOptions(extract_readable=True)
extract_title: bool = False
convert_nbsp: bool = False
strip_dangerous_elements: bool = False
strip_framework_attributes: bool = False
detect_table_alignment: bool = True
network: NetworkFetchOptions
local_files: LocalFileAccessOptions
strip_comments: bool = True
collapse_whitespace: bool = True
extract_readable: bool = False
br_handling: Literal['newline', 'space'] = 'newline'
allowed_elements: tuple[str, ...] | None = None
allowed_attributes: tuple[str, ...] | dict[str, tuple[str, ...]] | None = None
figures_parsing: Literal['blockquote', 'paragraph', 'image_with_caption', 'caption_only', 'html', 'skip'] = 'blockquote'
details_parsing: Literal['blockquote', 'paragraph', 'html', 'skip'] = 'blockquote'
extract_microdata: bool = True
base_url: str | None = None
html_parser: Literal['html.parser', 'html5lib', 'lxml'] = 'html.parser'
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, extract_title: bool = False, convert_nbsp: bool = False, strip_dangerous_elements: bool = False, strip_framework_attributes: bool = False, detect_table_alignment: bool = True, network: NetworkFetchOptions = <factory>, local_files: LocalFileAccessOptions = <factory>, strip_comments: bool = True, collapse_whitespace: bool = True, extract_readable: bool = False, br_handling: BrHandling = 'newline', allowed_elements: tuple[str, ...] | None=None, allowed_attributes: tuple[str, ...] | dict[str, tuple[str, ...]] | None=None, figures_parsing: FiguresParsing = 'blockquote', details_parsing: DetailsParsing = 'blockquote', extract_microdata: bool = True, base_url: str | None = None, html_parser: HtmlParser = 'html.parser') None
class all2md.options.IpynbOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for IPYNB-to-Markdown conversion.

This dataclass contains settings specific to Jupyter Notebook processing, including output handling and image conversion preferences. Inherits attachment handling from AttachmentOptionsMixin for notebook output images.

Parameters:
  • include_inputs (bool, default True) – Whether to include cell input (source code) in output.

  • include_outputs (bool, default True) – Whether to include cell outputs in the markdown.

  • skip_empty_cells (bool, default True) – Whether to skip cells with no content. When False, empty cells are preserved as empty blocks to maintain round-trip fidelity. When True, empty cells are omitted for cleaner output.

  • show_execution_count (bool, default False) – Whether to show execution counts for code cells.

  • output_types (list[str] or None, default ["stream", "execute_result", "display_data"]) – Types of outputs to include. Valid types: “stream”, “execute_result”, “display_data”, “error”. If None, includes all output types.

  • truncate_long_outputs (int or None, default DEFAULT_TRUNCATE_OUTPUT_LINES) – Maximum number of lines for text outputs before truncating. If None, outputs are not truncated.

  • truncate_output_message (str or None, default DEFAULT_TRUNCATE_OUTPUT_MESSAGE) – The message to place to indicate truncated output.

  • strip_html_from_markdown (bool, default True) – Whether to strip HTML elements (HTMLInline and HTMLBlock nodes) from markdown cells for security. When True, HTML in markdown cells is removed to prevent XSS attacks. When False, HTML is preserved as-is (use only with trusted notebooks).

include_inputs: bool = True
include_outputs: bool = True
skip_empty_cells: bool = True
show_execution_count: bool = False
output_types: tuple[str, ...] | None = ('stream', 'execute_result', 'display_data')
truncate_long_outputs: int | None = None
truncate_output_message: str | None = '\n... (output truncated) ...\n'
strip_html_from_markdown: bool = True
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, include_inputs: bool = True, include_outputs: bool = True, skip_empty_cells: bool = True, show_execution_count: bool = False, output_types: tuple[str, ...] | None = ('stream', 'execute_result', 'display_data'), truncate_long_outputs: int | None = None, truncate_output_message: str | None = '\n... (output truncated) ...\n', strip_html_from_markdown: bool = True) None
class all2md.options.IpynbRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST documents to Jupyter notebooks.

These options control notebook metadata inference, attachment handling, and preservation of notebook-specific metadata to support near round-tripping between AST and .ipynb formats.

Parameters:
  • nbformat (int or "auto", default 4) – Major notebook format version to emit. When “auto”, use the version discovered in the source document metadata and fall back to 4.

  • nbformat_minor (int or "auto", default "auto") – Minor notebook format revision. “auto” preserves the original value from document metadata when available.

  • default_language (str, default "python") – Fallback programming language when the document does not provide one.

  • default_kernel_name (str, default "python3") – Fallback kernel name for kernelspec metadata when inference fails.

  • default_kernel_display_name (str, default "Python 3") – Fallback kernel display name when inference fails.

  • infer_language_from_document (bool, default True) – When True, prefer Document.metadata[“language”] (and related fields) before default_language.

  • infer_kernel_from_document (bool, default True) – When True, attempt to build kernelspec metadata from document metadata (e.g., custom[“kernel”]) before falling back to defaults.

  • include_trusted_metadata (bool, default False) – When False, strip trusted flags from cell metadata for safer output.

  • include_ui_metadata (bool, default False) – When False, drop UI hints such as collapsed, scrolled, and widget metadata to avoid propagating viewer state.

  • preserve_unknown_metadata (bool, default True) – When True, retain metadata keys that are not explicitly filtered out.

  • inline_attachments (bool, default True) – Whether to emit attachments inline (base64-encoded) in the notebook instead of delegating to external download locations.

  • markdown_options (MarkdownRendererOptions or None, default None) – Optional Markdown renderer configuration used when consolidating AST nodes into markdown notebook cells. When None, a default renderer is constructed per cell.

nbformat: int | Literal['auto'] = 4
nbformat_minor: int | Literal['auto'] = 'auto'
default_language: str = 'python'
default_kernel_name: str = 'python3'
default_kernel_display_name: str = 'Python 3'
infer_language_from_document: bool = True
infer_kernel_from_document: bool = True
include_trusted_metadata: bool = False
include_ui_metadata: bool = False
preserve_unknown_metadata: bool = True
inline_attachments: bool = True
markdown_options: MarkdownRendererOptions | None = None
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', nbformat: int | Literal['auto'] = 4, nbformat_minor: int | Literal['auto'] = 'auto', default_language: str = 'python', default_kernel_name: str = 'python3', default_kernel_display_name: str = 'Python 3', infer_language_from_document: bool = True, infer_kernel_from_document: bool = True, include_trusted_metadata: bool = False, include_ui_metadata: bool = False, preserve_unknown_metadata: bool = True, inline_attachments: bool = True, markdown_options: MarkdownRendererOptions | None = None) None
class all2md.options.JinjaRendererOptions

Bases: BaseRendererOptions

Configuration options for Jinja2 template-based rendering.

This dataclass contains settings for rendering AST documents using custom Jinja2 templates. Templates have full access to the document AST and can produce any text-based output format (XML, YAML, custom markup, etc.).

Parameters:
  • template_file (str or None, default None) – Path to Jinja2 template file. Either template_file or template_string must be provided.

  • template_string (str or None, default None) – Inline Jinja2 template as a string. Either template_file or template_string must be provided. If both are provided, template_file takes precedence.

  • template_dir (str or None, default None) – Directory for template includes and extends. If None and template_file is provided, uses the directory containing template_file. Required when using template_string with includes/extends.

  • escape_strategy ({"xml", "html", "latex", "yaml", "markdown", "none", "custom"} or None, default None) – Default escaping strategy for the output format: - “xml”: XML/HTML entity escaping - “html”: Same as xml - “latex”: LaTeX special character escaping - “yaml”: YAML string escaping - “markdown”: Markdown special character escaping - “none”: No escaping - “custom”: Use custom_escape_function - None: No default strategy (templates must handle escaping explicitly) This affects the default |render filter behavior.

  • custom_escape_function (Callable[[str], str] or None, default None) – Custom escape function when escape_strategy=”custom”. Function signature: (text: str) -> str

  • autoescape (bool, default False) – Enable Jinja2 autoescape for the template environment. When True, uses the escape_strategy for automatic escaping. Default is False to give templates full control.

  • enable_render_filter (bool, default True) – Enable the render filter for rendering nodes with default logic. When enabled, templates can use {{ node|render }} for convenience.

  • enable_escape_filters (bool, default True) – Enable format-specific escape filters (escape_xml, escape_latex, etc.). When enabled, templates can use {{ text|escape_xml }}.

  • enable_traversal_helpers (bool, default True) – Enable AST traversal helper functions (get_headings, get_links, etc.). When enabled, templates can use {{ get_headings(document) }}.

  • default_render_format ({"markdown", "plain", "html"}, default "markdown") – Default format for the render filter when no escape_strategy is set. Determines how nodes are rendered when using {{ node|render }}.

  • extra_context (dict[str, Any] or None, default None) – Additional context variables to make available in templates. These will be merged into the template context.

  • strict_undefined (bool, default True) – Raise errors for undefined variables in templates (Jinja2 StrictUndefined). When False, undefined variables render as empty strings.

Examples

Render using a template file:
>>> from all2md.options import JinjaRendererOptions
>>> options = JinjaRendererOptions(
...     template_file="templates/docbook.xml.jinja2",
...     escape_strategy="xml"
... )
Render using an inline template string:
>>> template = '''
... <doc>
... {% for node in document.children -%}
...   {{ node|render }}
... {%- endfor %}
... </doc>
... '''
>>> options = JinjaRendererOptions(
...     template_string=template,
...     escape_strategy="xml"
... )
Use custom escape function:
>>> def my_escape(text: str) -> str:
...     return text.replace("&", "&amp;")
>>> options = JinjaRendererOptions(
...     template_file="custom.jinja2",
...     escape_strategy="custom",
...     custom_escape_function=my_escape
... )
Add extra context variables:
>>> options = JinjaRendererOptions(
...     template_file="report.jinja2",
...     extra_context={"version": "1.0", "author": "Tool"}
... )

Notes

Templates receive the following context: - document: The Document node (typed AST object) - ast: The document as a dictionary (template-friendly) - metadata: Document metadata dictionary - title: Document title (metadata.get(“title”, “”)) - headings: List of all headings (if enable_traversal_helpers=True) - links: List of all links (if enable_traversal_helpers=True) - images: List of all images (if enable_traversal_helpers=True) - footnotes: List of all footnote definitions (if enable_traversal_helpers=True) - Any keys from extra_context

Available filters (if enabled):
  • render: Render a node with default logic

  • render_inline: Render inline content

  • to_dict: Convert Node to dictionary

  • escape_xml, escape_html: XML/HTML escaping

  • escape_latex: LaTeX escaping

  • escape_yaml: YAML escaping

  • escape_markdown: Markdown escaping

  • node_type: Get node type name as string

Available functions (if enabled): - get_headings(doc): Extract all heading nodes - get_links(doc): Extract all link nodes - get_images(doc): Extract all image nodes - get_footnotes(doc): Extract all footnote definitions - find_nodes(doc, node_type): Find all nodes of specified type - filter_nodes(doc, predicate): Filter nodes by custom predicate

template_file: str | None = None
template_string: str | None = None
template_dir: str | None = None
escape_strategy: Literal['xml', 'html', 'latex', 'yaml', 'markdown', 'none', 'custom'] | None = None
custom_escape_function: Callable[[str], str] | None = None
autoescape: bool = False
enable_render_filter: bool = True
enable_escape_filters: bool = True
enable_traversal_helpers: bool = True
default_render_format: Literal['markdown', 'plain', 'html'] = 'markdown'
extra_context: dict[str, Any] | None = None
strict_undefined: bool = True
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', template_file: str | None = None, template_string: str | None = None, template_dir: str | None = None, escape_strategy: JinjaEscapeStrategy | None = None, custom_escape_function: Callable[[str], str] | None = None, autoescape: bool = False, enable_render_filter: bool = True, enable_escape_filters: bool = True, enable_traversal_helpers: bool = True, default_render_format: JinjaRenderFormat = 'markdown', extra_context: dict[str, Any] | None = None, strict_undefined: bool = True) None
class all2md.options.LatexRendererOptions

Bases: BaseRendererOptions

Configuration options for AST-to-LaTeX rendering.

This dataclass contains settings for rendering AST documents as LaTeX output suitable for compilation with pdflatex/xelatex.

Parameters:
  • document_class (str, default "article") – LaTeX document class to use (article, report, book, etc.).

  • include_preamble (bool, default True) – Whether to generate a complete document with preamble. When False, generates only document body (for inclusion).

  • packages (list[str], default ["amsmath", "graphicx", "hyperref"]) – LaTeX packages to include in preamble.

  • math_mode ({"inline", "display"}, default "display") – Preferred math rendering mode for ambiguous cases.

  • line_width (int, default 0) – Target line width for text wrapping (0 = no wrapping).

  • escape_special (bool, default True) – Whether to escape special LaTeX characters ($, %, &, etc.). Only disable if input is already LaTeX-safe.

  • use_unicode (bool, default True) – Whether to allow Unicode characters in output. When False, uses LaTeX escapes for special characters.

  • comment_mode ({"percent", "todonotes", "marginnote", "ignore"}, default "percent") – How to render Comment and CommentInline AST nodes: - “percent”: Render as LaTeX comments (% Comment text) - “todonotes”: Use \todo{} command from todonotes package (colored margin notes) - “marginnote”: Use \marginpar{} for margin notes (simple side notes) - “ignore”: Skip comment nodes entirely This controls presentation of comments from source documents.

document_class: str = 'article'
include_preamble: bool = True
packages: list[str]
math_mode: Literal['inline', 'display'] = 'display'
line_width: int = 0
escape_special: bool = True
use_unicode: bool = True
comment_mode: Literal['percent', 'todonotes', 'marginnote', 'ignore'] = 'percent'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', document_class: str = 'article', include_preamble: bool = True, packages: list[str] = <factory>, math_mode: LatexMathRenderMode = 'display', line_width: int = 0, escape_special: bool = True, use_unicode: bool = True, comment_mode: LatexCommentMode = 'percent') None
class all2md.options.LatexOptions

Bases: BaseParserOptions

Configuration options for LaTeX-to-AST parsing.

This dataclass contains settings specific to parsing LaTeX documents into AST representation using pylatexenc library.

Parameters:
  • parse_preamble (bool, default True) – Whether to parse document preamble for metadata. When True, extracts title, author, date, etc.

  • parse_math (bool, default True) – Whether to parse math environments into MathBlock/MathInline nodes. When True, preserves LaTeX math notation in AST.

  • parse_custom_commands (bool, default False) – Whether to attempt parsing custom LaTeX commands. SECURITY: Disabled by default to prevent unexpected behavior.

  • strict_mode (bool, default False) – Whether to raise errors on invalid LaTeX syntax. When False, attempts to recover gracefully.

  • encoding (str, default "utf-8") – Text encoding to use when reading LaTeX files.

  • preserve_comments (bool, default False) – Whether to preserve LaTeX comments in the AST. When True, comments are stored in node metadata.

parse_preamble: bool = True
parse_math: bool = True
parse_custom_commands: bool = False
strict_mode: bool = False
encoding: str = 'utf-8'
preserve_comments: bool = False
__init__(extract_metadata: bool = False, parse_preamble: bool = True, parse_math: bool = True, parse_custom_commands: bool = False, strict_mode: bool = False, encoding: str = 'utf-8', preserve_comments: bool = False) None
class all2md.options.MarkdownRendererOptions

Bases: BaseRendererOptions

Markdown rendering options for converting AST to Markdown text.

When a flavor is specified, default values for unsupported_table_mode and unsupported_inline_mode are automatically set to flavor-appropriate values unless explicitly overridden. This is handled via the __new__ method to apply flavor-aware defaults before instance creation.

This dataclass contains settings that control how Markdown output is formatted and structured. These options are used by multiple conversion modules to ensure consistent Markdown generation.

Parameters:
  • escape_special (bool, default True) – Whether to escape special Markdown characters in text content. When True, characters like *, _, #, [, ], (, ), \ are escaped to prevent unintended formatting.

  • emphasis_symbol ({"*", "_"}, default "*") – Symbol to use for emphasis/italic formatting in Markdown.

  • bullet_symbols (str, default "*-+") – Characters to cycle through for nested bullet lists.

  • list_indent_width (int, default 4) – Number of spaces to use for each level of list indentation.

  • underline_mode ({"html", "markdown", "ignore"}, default "markdown") – Fallback for flavors that don’t natively support underline. Flavors that do (markdown_plus) always emit ^^text^^; for the rest: - “markdown”: Use ^^text^^ (the pymdownx insert spelling; roundtrips, needs an extension to render) - “html”: Use <u>text</u> tags (wider display support, but escaped on roundtrip) - “ignore”: Strip underline formatting

  • superscript_mode ({"html", "markdown", "ignore"}, default "markdown") – Fallback for flavors that don’t natively support superscript. Flavors that do (markdown_plus) always emit ^text^; for the rest: - “markdown”: Use ^text^ (roundtrips; non-standard, needs an extension to render) - “html”: Use <sup>text</sup> tags (wider display support, but escaped on roundtrip) - “ignore”: Strip superscript formatting

  • subscript_mode ({"html", "markdown", "ignore"}, default "markdown") – Fallback for flavors that don’t natively support subscript. Flavors that do (markdown_plus) always emit ~text~; for the rest: - “markdown”: Use ~text~ (roundtrips; non-standard, needs an extension to render) - “html”: Use <sub>text</sub> tags (wider display support, but escaped on roundtrip) - “ignore”: Strip subscript formatting

  • use_hash_headings (bool, default True) – Whether to use # syntax for headings instead of underline style. When True, generates “# Heading” style. When False, generates “Headingn=======” style for level 1 and “Headingn——-” for levels 2+.

  • flavor ({"gfm", "commonmark", "markdown_plus"}, default "gfm") – Markdown flavor/dialect to use for output: - “gfm”: GitHub Flavored Markdown (tables, strikethrough, task lists) - “commonmark”: Strict CommonMark specification - “markdown_plus”: All extensions enabled (footnotes, definition lists, etc.)

  • unsupported_table_mode ({"drop", "ascii", "force", "html"}, default "force") – How to handle tables when the selected flavor doesn’t support them: - “drop”: Skip table entirely - “ascii”: Render as ASCII art table - “force”: Render as pipe table anyway (may not be valid for flavor) - “html”: Render as HTML <table>

  • unsupported_inline_mode ({"plain", "force", "html"}, default "plain") – How to handle inline elements unsupported by the selected flavor: - “plain”: Render content without the unsupported formatting - “force”: Use markdown syntax anyway (may not be valid for flavor) - “html”: Use HTML tags (e.g., <u> for underline)

  • heading_level_offset (int, default 0) – Shift all heading levels by this amount (positive or negative). Useful when collating multiple documents into a parent document with existing structure.

  • code_fence_char ({"`", "~"}, default "`") – Character to use for code fences (backtick or tilde).

  • code_fence_min (int, default 3) – Minimum length for code fences (typically 3).

  • collapse_blank_lines (bool, default True) – Collapse multiple consecutive blank lines into at most 2 (normalizing whitespace).

  • link_style ({"inline", "reference"}, default "inline") – Link style to use: - “inline”: [text](url) style links - “reference”: [text][ref] style with reference definitions at end

  • reference_link_placement ({"end_of_document", "after_block"}, default "end_of_document") – Where to place reference link definitions when using reference-style links: - “end_of_document”: All reference definitions at document end (current behavior) - “after_block”: Reference definitions placed after each block-level element

  • autolink_bare_urls (bool, default False) – Automatically convert bare URLs (e.g., http://example.com) found in Text nodes into Markdown autolinks (<http://example.com>). Ensures all URLs are clickable.

  • table_pipe_escape (bool, default True) – Whether to escape pipe characters (|) in table cell content.

  • math_mode ({"latex", "mathml", "html"}, default "latex") – Preferred math representation for flavors that support math. When the requested representation is unavailable on a node, the renderer falls back to any available representation while preserving flavor constraints.

  • html_passthrough_mode ({"pass-through", "escape", "drop", "sanitize"}, default "escape") – How to handle raw HTML content in markdown (HTMLBlock and HTMLInline nodes): - “pass-through”: Pass HTML through unchanged (use only with trusted content) - “escape”: HTML-escape the content to show as text (secure default) - “drop”: Remove HTML content entirely - “sanitize”: Remove dangerous elements/attributes (requires bleach for best results) Note: This does not affect fenced code blocks with language=”html”, which are always rendered as code and are already safe.

  • comment_mode ({"html", "blockquote", "ignore"}, default "blockquote") – How to render Comment and CommentInline AST nodes: - “html”: Render as HTML comments (<!– Comment text –>) - “blockquote”: Render as blockquotes with attribution ([Comment by Author: text]) - “ignore”: Skip comment nodes entirely This controls presentation of comments from DOCX reviewer comments, HTML comments, and other format-specific annotations.

escape_special: bool = True
emphasis_symbol: Literal['*', '_'] = '*'
bullet_symbols: str = '*-+'
list_indent_width: int = 4
underline_mode: Literal['html', 'markdown', 'ignore'] = 'markdown'
superscript_mode: Literal['html', 'markdown', 'ignore'] = 'markdown'
subscript_mode: Literal['html', 'markdown', 'ignore'] = 'markdown'
use_hash_headings: bool = True
flavor: Literal['gfm', 'commonmark', 'multimarkdown', 'pandoc', 'kramdown', 'markdown_plus'] = 'gfm'
strict_flavor_validation: bool = False
unsupported_table_mode: Literal['drop', 'ascii', 'force', 'html'] | object = <object object>
unsupported_inline_mode: Literal['plain', 'force', 'html'] | object = <object object>
pad_table_cells: bool = False
prefer_setext_headings: bool = False
max_line_width: int | None = None
table_alignment_default: str = 'left'
heading_level_offset: int = 0
code_fence_char: Literal['`', '~'] = '`'
code_fence_min: int = 3
collapse_blank_lines: bool = True
link_style: Literal['inline', 'reference'] = 'inline'
reference_link_placement: Literal['end_of_document', 'after_block'] = 'end_of_document'
autolink_bare_urls: bool = False
table_pipe_escape: bool = True
math_mode: Literal['latex', 'mathml', 'html'] = 'latex'
metadata_frontmatter: bool = False
metadata_format: Literal['yaml', 'toml', 'json'] = 'yaml'
html_passthrough_mode: Literal['pass-through', 'escape', 'drop', 'sanitize'] = 'escape'
comment_mode: Literal['html', 'blockquote', 'ignore'] = 'blockquote'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', escape_special: bool = True, emphasis_symbol: EmphasisSymbol = '*', bullet_symbols: str = '*-+', list_indent_width: int = 4, underline_mode: UnderlineMode = 'markdown', superscript_mode: SuperscriptMode = 'markdown', subscript_mode: SubscriptMode = 'markdown', use_hash_headings: bool = True, flavor: FlavorType = 'gfm', strict_flavor_validation: bool = False, unsupported_table_mode: UnsupportedTableMode | object = <object object>, unsupported_inline_mode: UnsupportedInlineMode | object = <object object>, pad_table_cells: bool = False, prefer_setext_headings: bool = False, max_line_width: int | None = None, table_alignment_default: str = 'left', heading_level_offset: int = 0, code_fence_char: CodeFenceChar = '`', code_fence_min: int = 3, collapse_blank_lines: bool = True, link_style: LinkStyleType = 'inline', reference_link_placement: ReferenceLinkPlacement = 'end_of_document', autolink_bare_urls: bool = False, table_pipe_escape: bool = True, math_mode: MathMode = 'latex', metadata_frontmatter: bool = False, metadata_format: MetadataFormatType = 'yaml', html_passthrough_mode: HtmlPassthroughMode = 'escape', comment_mode: CommentMode = 'blockquote') None
class all2md.options.MarkdownParserOptions

Bases: BaseParserOptions

Configuration options for Markdown-to-AST parsing.

This dataclass contains settings specific to parsing Markdown documents into AST representation, supporting various Markdown flavors and extensions.

Parameters:
  • flavor ({"gfm", "commonmark", "multimarkdown", "pandoc", "kramdown", "markdown_plus"}, default "gfm") – Markdown flavor to parse. Determines which extensions are enabled.

  • parse_tables (bool, default True) – Whether to parse table syntax (GFM pipe tables).

  • parse_footnotes (bool, default True) – Whether to parse footnote references and definitions.

  • parse_math (bool, default True) – Whether to parse inline ($…$) and block ($$…$$) math.

  • parse_task_lists (bool, default True) – Whether to parse task list checkboxes (- [ ] and - [x]).

  • parse_definition_lists (bool, default True) – Whether to parse definition lists (term : definition).

  • parse_strikethrough (bool, default True) – Whether to parse strikethrough syntax (~~text~~).

  • parse_marks (bool, default True) – Whether to parse the inline mark family used by Material for MkDocs / pymdownx: highlight (==text==), insert/underline (^^text^^), superscript (^text^) and subscript (~text~).

  • parse_admonitions (bool, default True) – Whether to parse Material for MkDocs admonitions (!!! note "Title") and collapsible admonitions (??? note / ???+ note).

flavor: Literal['gfm', 'commonmark', 'multimarkdown', 'pandoc', 'kramdown', 'markdown_plus'] = 'gfm'
parse_tables: bool = True
parse_footnotes: bool = True
parse_math: bool = True
parse_task_lists: bool = True
parse_definition_lists: bool = True
parse_strikethrough: bool = True
parse_marks: bool = True
parse_admonitions: bool = True
parse_frontmatter: bool = True
__init__(extract_metadata: bool = False, flavor: Literal['gfm', 'commonmark', 'multimarkdown', 'pandoc', 'kramdown', 'markdown_plus'] = 'gfm', parse_tables: bool = True, parse_footnotes: bool = True, parse_math: bool = True, parse_task_lists: bool = True, parse_definition_lists: bool = True, parse_strikethrough: bool = True, parse_marks: bool = True, parse_admonitions: bool = True, parse_frontmatter: bool = True) None
class all2md.options.MediaWikiOptions

Bases: BaseRendererOptions

Configuration options for MediaWiki rendering.

This dataclass contains settings for rendering AST documents as MediaWiki markup, suitable for Wikipedia and other MediaWiki-based wikis.

Parameters:
  • use_html_for_unsupported (bool, default True) – Whether to use HTML tags as fallback for unsupported elements. When True, unsupported formatting uses HTML tags (e.g., <u>underline</u>). When False, unsupported formatting is stripped.

  • image_thumb (bool, default True) – Whether to render images as thumbnails. When True, images use |thumb option in MediaWiki syntax. When False, images are rendered at full size.

  • image_caption_mode ({"auto", "alt_only", "caption_only"}, default "alt_only") – How to render image captions when image_thumb is True: - “auto”: Use alt_text as caption, with alt attribute when available - “alt_only”: Only render alt attribute, no caption text (default, backward compatible) - “caption_only”: Only render caption text, no alt attribute

  • html_passthrough_mode ({"pass-through", "escape", "drop", "sanitize"}, default "pass-through") – How to handle HTMLBlock and HTMLInline nodes: - “pass-through”: Pass through unchanged (use only with trusted content) - “escape”: HTML-escape the content - “drop”: Remove HTML content entirely - “sanitize”: Remove dangerous elements/attributes (requires bleach for best results)

  • comment_mode ({"html", "visible", "ignore"}, default "html") – How to render Comment and CommentInline AST nodes: - “html”: Use HTML comment syntax <!– –> (default) - “visible”: Render as visible text - “ignore”: Skip comments entirely

Examples

Basic MediaWiki rendering:
>>> from all2md.ast import Document, Heading, Text
>>> from all2md.renderers.mediawiki import MediaWikiRenderer
>>> from all2md.options.mediawiki import MediaWikiOptions
>>> doc = Document(children=[
...     Heading(level=1, content=[Text(content="Title")])
... ])
>>> options = MediaWikiOptions()
>>> renderer = MediaWikiRenderer(options)
>>> wiki_text = renderer.render_to_string(doc)
use_html_for_unsupported: bool = True
image_thumb: bool = True
image_caption_mode: Literal['auto', 'alt_only', 'caption_only'] = 'alt_only'
html_passthrough_mode: Literal['pass-through', 'escape', 'drop', 'sanitize'] = 'escape'
comment_mode: Literal['html', 'visible', 'ignore'] = 'html'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', use_html_for_unsupported: bool = True, image_thumb: bool = True, image_caption_mode: MediaWikiImageCaptionMode = 'alt_only', html_passthrough_mode: HtmlPassthroughMode = 'escape', comment_mode: MediaWikiCommentMode = 'html') None
class all2md.options.MhtmlOptions

Bases: HtmlOptions

Configuration options for MHTML-to-Markdown conversion.

This dataclass contains settings specific to MHTML file processing, primarily for handling embedded assets like images and local file security.

Parameters:

HtmlOptions (Inherited from)

__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, extract_title: bool = False, convert_nbsp: bool = False, strip_dangerous_elements: bool = False, strip_framework_attributes: bool = False, detect_table_alignment: bool = True, network: NetworkFetchOptions = <factory>, local_files: LocalFileAccessOptions = <factory>, strip_comments: bool = True, collapse_whitespace: bool = True, extract_readable: bool = False, br_handling: BrHandling = 'newline', allowed_elements: tuple[str, ...] | None=None, allowed_attributes: tuple[str, ...] | dict[str, tuple[str, ...]] | None=None, figures_parsing: FiguresParsing = 'blockquote', details_parsing: DetailsParsing = 'blockquote', extract_microdata: bool = True, base_url: str | None = None, html_parser: HtmlParser = 'html.parser') None
class all2md.options.OdpOptions

Bases: PaginatedParserOptions

Configuration options for ODP-to-Markdown conversion.

This dataclass contains settings specific to OpenDocument Presentation (ODP) processing, including slide selection, numbering, and notes.

Parameters:
  • preserve_tables (bool, default True) – Whether to preserve table formatting in Markdown.

  • include_slide_numbers (bool, default False) – Whether to include slide numbers in the output.

  • include_notes (bool, default True) – Whether to include speaker notes in the conversion.

  • page_separator_template (str, default "---") – Template for slide separators. Supports placeholders: {page_num}, {total_pages}.

  • slides (str or None, default None) – Slide selection (e.g., “1,3-5,8” for slides 1, 3-5, and 8).

preserve_tables: bool = True
include_slide_numbers: bool = False
include_notes: bool = True
slides: str | None = None
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, page_separator_template: str = '-----', preserve_tables: bool = True, include_slide_numbers: bool = False, include_notes: bool = True, slides: str | None = None) None
class all2md.options.OdpRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST to ODP format.

This dataclass contains settings specific to OpenDocument Presentation generation from AST, including slide splitting strategies and layout.

Parameters:
  • slide_split_mode ({"separator", "heading", "auto"}, default "auto") – How to split the AST into slides: - “separator”: Split on ThematicBreak nodes - “heading”: Split on specific heading level - “auto”: Try separator first, fallback to heading-based splitting

  • slide_split_heading_level (int, default 2) – Heading level to use for slide splits when using heading mode.

  • default_layout (str, default "Default") – Default slide layout name.

  • title_slide_layout (str, default "Title") – Layout name for the first slide.

  • use_heading_as_slide_title (bool, default True) – Use first heading in slide content as slide title.

  • template_path (str or None, default None) – Path to .odp template file. If None, uses default blank template.

  • default_font (str, default "Liberation Sans") – Default font for slide content.

  • default_font_size (int, default 18) – Default font size in points for body text.

  • title_font_size (int, default 44) – Font size for slide titles.

  • network (NetworkFetchOptions, default NetworkFetchOptions()) – Network security options for fetching remote images in slides.

  • include_notes (bool, default True) – Whether to detect and render speaker notes from “Speaker Notes” sections. When True, H3 headings with “Speaker Notes” text are detected, and content after them is rendered to slide speaker notes. When False, speaker notes sections are ignored and rendered as regular slide content.

  • comment_mode ({"native", "visible", "ignore"}, default "native") – How to render Comment and CommentInline AST nodes: - “native”: Use ODF annotation elements (default) - “visible”: Render as visible text in slide content - “ignore”: Skip comments entirely

slide_split_mode: Literal['separator', 'heading', 'auto'] = 'auto'
slide_split_heading_level: int = 2
default_layout: str = 'Default'
title_slide_layout: str = 'Title'
use_heading_as_slide_title: bool = True
template_path: str | None = None
default_font: str = 'Liberation Sans'
default_font_size: int = 18
title_font_size: int = 44
network: NetworkFetchOptions
include_notes: bool = True
comment_mode: Literal['native', 'visible', 'ignore'] = 'native'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', slide_split_mode: SlideSplitMode = 'auto', slide_split_heading_level: int = 2, default_layout: str = 'Default', title_slide_layout: str = 'Title', use_heading_as_slide_title: bool = True, template_path: str | None = None, default_font: str = 'Liberation Sans', default_font_size: int = 18, title_font_size: int = 44, network: NetworkFetchOptions = <factory>, include_notes: bool = True, comment_mode: OdpCommentMode = 'native') None
class all2md.options.OdsSpreadsheetOptions

Bases: SpreadsheetParserOptions

Configuration options for ODS spreadsheet conversion.

This dataclass inherits all spreadsheet options from SpreadsheetParserOptions and adds ODS-specific options.

Parameters:
  • has_header (bool, default True) – Whether the first row contains column headers.

  • options. (See SpreadsheetParserOptions for complete documentation of inherited)

has_header: bool = True
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, sheets: list[str] | str | None = None, include_sheet_titles: bool = True, render_formulas: bool = True, max_rows: int | None = None, max_cols: int | None = None, truncation_indicator: str = '...', preserve_newlines_in_cells: bool = False, trim_empty: TrimEmptyMode = 'trailing', header_case: HeaderCaseOption = 'preserve', chart_mode: ChartMode = 'skip', merged_cell_mode: MergedCellMode = 'flatten', has_header: bool = True) None
class all2md.options.OdtOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for ODT-to-Markdown conversion.

This dataclass contains settings specific to OpenDocument Text (ODT) processing. Inherits attachment handling from AttachmentOptionsMixin for embedded images.

Parameters:

preserve_tables (bool, default True) – Whether to preserve table formatting in Markdown.

preserve_tables: bool = True
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, preserve_tables: bool = True) None
class all2md.options.OdtRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST to ODT format.

This dataclass contains settings specific to OpenDocument Text generation, including fonts, styles, and formatting preferences.

Parameters:
  • default_font (str, default "Liberation Sans") – Default font name for body text.

  • default_font_size (int, default 11) – Default font size in points for body text.

  • heading_font_sizes (dict[int, int] or None, default None) – Font sizes for heading levels 1-6. If None, uses built-in ODT heading styles.

  • use_styles (bool, default True) – Whether to use built-in ODT styles vs direct formatting.

  • code_font (str, default "Liberation Mono") – Font name for code blocks and inline code.

  • code_font_size (int, default 10) – Font size for code blocks and inline code.

  • preserve_formatting (bool, default True) – Whether to preserve text formatting (bold, italic, etc.).

  • template_path (str or None, default None) – Path to .odt template file. When specified, the renderer uses the template’s styles instead of creating a blank document.

  • network (NetworkFetchOptions, default NetworkFetchOptions()) – Network security settings for fetching remote images.

  • comment_mode ({"native", "visible", "ignore"}, default "native") – How to render Comment and CommentInline AST nodes: - “native”: Use odfpy native comment/annotation support (preserves ODT comments when possible) - “visible”: Render as regular text paragraphs with attribution - “ignore”: Skip comment nodes entirely This controls presentation of comments from ODT source files and other formats.

default_font: str = 'Liberation Sans'
default_font_size: int = 11
heading_font_sizes: dict[int, int] | None = None
use_styles: bool = True
code_font: str = 'Liberation Mono'
code_font_size: int = 10
preserve_formatting: bool = True
template_path: str | None = None
network: NetworkFetchOptions
comment_mode: Literal['native', 'visible', 'ignore'] = 'native'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', default_font: str = 'Liberation Sans', default_font_size: int = 11, heading_font_sizes: dict[int, int] | None=None, use_styles: bool = True, code_font: str = 'Liberation Mono', code_font_size: int = 10, preserve_formatting: bool = True, template_path: str | None = None, network: NetworkFetchOptions = <factory>, comment_mode: OdtCommentMode = 'native') None
class all2md.options.OrgParserOptions

Bases: BaseParserOptions

Configuration options for Org-Mode-to-AST parsing.

This dataclass contains settings specific to parsing Org-Mode documents into AST representation using orgparse.

Parameters:
  • parse_properties (bool, default True) – Whether to parse Org properties within drawers. When True, properties are extracted and stored in metadata.

  • parse_tags (bool, default True) – Whether to parse heading tags (e.g., :work:urgent:). When True, tags are extracted and stored in heading metadata.

  • parse_scheduling (bool, default True) – Whether to parse SCHEDULED and DEADLINE timestamps. When True, scheduling info is extracted and stored in metadata. For the first heading, scheduling is also added to Document.metadata.custom.

  • todo_keywords (list[str], default ["TODO", "DONE"]) – List of TODO keywords to recognize in headings. Common keywords: TODO, DONE, IN-PROGRESS, WAITING, CANCELLED, etc.

Examples

Basic usage:
>>> options = OrgParserOptions()
>>> parser = OrgParser(options)
Custom TODO keywords:
>>> options = OrgParserOptions(
...     todo_keywords=["TODO", "IN-PROGRESS", "DONE", "CANCELLED"]
... )
parse_properties: bool = True
parse_tags: bool = True
parse_scheduling: bool = True
todo_keywords: list[str]
parse_logbook: bool = True
parse_clock: bool = True
parse_closed: bool = True
preserve_timestamp_metadata: bool = True
__init__(extract_metadata: bool = False, parse_properties: bool = True, parse_tags: bool = True, parse_scheduling: bool = True, todo_keywords: list[str] = <factory>, parse_logbook: bool = True, parse_clock: bool = True, parse_closed: bool = True, preserve_timestamp_metadata: bool = True) None
class all2md.options.OrgRendererOptions

Bases: BaseRendererOptions

Configuration options for AST-to-Org-Mode rendering.

This dataclass contains settings for rendering AST documents as Org-Mode output.

Parameters:
  • heading_style ({"stars"}, default "stars") – Style for rendering headings. Currently only “stars” is supported (e.g., * Level 1, ** Level 2, *** Level 3).

  • preserve_properties (bool, default True) – Whether to preserve properties in rendered output. When True, properties stored in metadata are rendered in :PROPERTIES: drawer.

  • preserve_tags (bool, default True) – Whether to preserve heading tags in rendered output. When True, tags stored in metadata are rendered (e.g., :work:urgent:).

  • todo_keywords (list[str], default ["TODO", "DONE"]) – List of TODO keywords that may appear in headings. Used for validation and rendering.

  • comment_mode ({"comment", "drawer", "ignore"}, default "comment") – How to render Comment and CommentInline AST nodes: - “comment”: Render as Org-mode comments (# Comment text) - “drawer”: Render as :COMMENT: drawer blocks (visible annotations) - “ignore”: Skip comment nodes entirely This controls presentation of comments from source documents.

Notes

Heading Rendering:

Headings are rendered with stars (*, **, ***, etc.) based on level. TODO states and tags are preserved if present in metadata.

TODO States:

If a heading has metadata["org_todo_state"], it’s rendered before the heading text. Example: * TODO Write documentation

Tags:

If preserve_tags is True and metadata["org_tags"] exists, tags are rendered. Example: * Heading :work:urgent:

Properties:

If preserve_properties is True and metadata["org_properties"] exists, a :PROPERTIES: drawer is rendered under the heading.

heading_style: Literal['stars'] = 'stars'
preserve_properties: bool = True
preserve_tags: bool = True
todo_keywords: list[str]
comment_mode: Literal['comment', 'drawer', 'ignore'] = 'comment'
preserve_logbook: bool = True
preserve_clock: bool = True
preserve_closed: bool = True
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', heading_style: OrgHeadingStyle = 'stars', preserve_properties: bool = True, preserve_tags: bool = True, todo_keywords: list[str] = <factory>, comment_mode: OrgCommentMode = 'comment', preserve_logbook: bool = True, preserve_clock: bool = True, preserve_closed: bool = True) None
class all2md.options.PdfOptions

Bases: PaginatedParserOptions

Configuration options for PDF-to-Markdown conversion.

This dataclass contains settings specific to PDF document processing, including page selection, image handling, and formatting preferences.

Parameters:
  • pages (list[int], str, or None, default None) – Pages to convert (1-based indexing, like “page 1, page 2”). Can be a list [1, 2, 3] or string range “1-3,5,10-“. If None, converts all pages.

  • password (str or None, default None) – Password for encrypted PDF documents.

  • parameters (# Table detection)

  • header_sample_pages (int | list[int] | None, default None) – Pages to sample for header font size analysis. If None, samples all pages.

  • header_percentile_threshold (float, default 75) – Percentile threshold for header detection (e.g., 75 = top 25% of font sizes).

  • header_min_occurrences (int, default 3) – Minimum occurrences of a font size to consider it for headers.

  • header_size_allowlist (list[float] | None, default None) – Specific font sizes to always treat as headers.

  • header_size_denylist (list[float] | None, default None) – Font sizes to never treat as headers.

  • header_use_font_weight (bool, default True) – Consider bold/font weight when detecting headers.

  • header_use_all_caps (bool, default True) – Consider all-caps text as potential headers.

  • header_font_size_ratio (float, default 1.2) – Minimum ratio between header and body text font size.

  • header_max_line_length (int, default 100) – Maximum character length for text to be considered a header.

  • header_debug_output (bool, default False) – Enable debug output for header detection analysis. When enabled, stores font size distribution and classification decisions for inspection.

  • parameters

  • detect_columns (bool, default True) – Enable multi-column layout detection.

  • merge_hyphenated_words (bool, default True) – Merge words split by hyphens at line breaks.

  • handle_rotated_text (bool, default True) – Process rotated text blocks.

  • annotate_rotated_text (bool, default False) – Append a marker like *[rotated 90° counter-clockwise]* after rotated text. Off by default — most documents (e.g. figure axis labels) produce only noise. Consecutive same-direction rotated lines are grouped into a single paragraph regardless of this setting.

  • column_gap_threshold (float, default 20) – Minimum gap between columns in points.

  • column_detection_mode (str, default "auto") – Column detection strategy: “auto” (heuristic-based), “force_single” (disable detection), “force_multi” (force multi-column), or “disabled” (same as force_single).

  • use_column_clustering (bool, default False) – Use k-means clustering on x-coordinates for more robust column detection. Alternative to gap heuristics, better for layouts with irregular column positions.

  • consolidate_inline_formatting (bool, default True) – Merge adjacent same-type formatting nodes (bold+bold, italic+italic) and normalize whitespace around formatting markers. Fixes fragmented formatting like ‘text ** *more*’ becoming ‘**text more’.

  • parameters

  • enable_table_fallback_detection (bool, default True) – Use heuristic fallback if PyMuPDF table detection fails.

  • detect_merged_cells (bool, default True) – Attempt to identify merged cells in tables.

  • table_ruling_line_threshold (float, default 0.5) – Threshold for detecting table ruling lines (0.0-1.0, ratio of line length to page size).

  • table_fallback_extraction_mode (str, default "grid") – Table extraction mode for ruling line fallback: “none” (detect only, don’t extract), “grid” (grid-based cell segmentation), or “text_clustering” (future: text position clustering).

  • link_overlap_threshold (float, default 70.0) – Percentage overlap required for link detection (0-100). Lower values detect links with less overlap but may incorrectly link non-link text. Higher values reduce false positives but may miss valid links.

  • image_placement_markers (bool, default True) – Add markers showing image positions. Only applies when attachment_mode is save or base64 (modes that produce a real URL/path). In alt_text mode no markers are emitted because they would have no target.

  • include_image_captions (bool, default True) – Try to extract image captions.

  • include_page_numbers (bool, default False) – Include page numbers in output (automatically added to separator).

  • page_separator_template (str, default "-----") – Template for page separators between pages. Supports placeholders: {page_num}, {total_pages}.

  • table_detection_mode (str, default "both") – Table detection strategy: “pymupdf”, “ruling”, “both”, or “none”.

  • image_format (str, default "png") – Output format for extracted images: “png” or “jpeg”.

  • image_quality (int, default 90) – JPEG quality (1-100, only used when image_format=”jpeg”).

  • trim_headers_footers (bool, default False) – Remove repeated headers and footers from pages.

  • auto_trim_headers_footers (bool, default False) – Automatically detect and remove repeating headers/footers. When enabled, analyzes content across pages to identify repeating header/footer patterns and automatically sets header_height/footer_height values. Takes precedence over manually specified header_height/footer_height.

  • header_height (int, default 0) – Height in points to trim from top of page (requires trim_headers_footers).

  • footer_height (int, default 0) – Height in points to trim from bottom of page (requires trim_headers_footers).

  • skip_image_extraction (bool, default False) – Skip all image extraction for text-only conversion (improves performance for large PDFs).

  • ocr (OCROptions, default OCROptions()) – OCR settings for extracting text from scanned/image-based PDF pages. Requires optional dependencies: pip install all2md[ocr] See OCROptions documentation for detailed configuration options.

Notes

For large PDFs (hundreds of pages), consider using skip_image_extraction=True if you only need text content. This significantly reduces memory pressure by avoiding image decoding. Parallel processing (CLI –parallel flag) can further improve throughput for multi-file batches, but note that each worker process imports dependencies anew, adding startup overhead.

Examples

Convert only pages 1-3 with base64 images:
>>> options = PdfOptions(pages=[1, 2, 3], attachment_mode="base64")
>>> # Or using string range:
>>> options = PdfOptions(pages="1-3", attachment_mode="base64")
Convert with custom page separators:
>>> options = PdfOptions(
...     page_separator_template="--- Page {page_num} of {total_pages} ---",
...     include_page_numbers=True
... )
Configure header detection with debug output:
>>> options = PdfOptions(
...     header_sample_pages=[1, 2, 3],
...     header_percentile_threshold=80,
...     header_use_all_caps=True,
...     header_debug_output=True  # Enable debug analysis
... )
Use k-means clustering for robust column detection:
>>> options = PdfOptions(
...     use_column_clustering=True,
...     column_gap_threshold=25
... )
Configure link detection sensitivity:
>>> options = PdfOptions(
...     link_overlap_threshold=80.0  # Stricter link detection
... )
Enable table ruling line extraction:
>>> options = PdfOptions(
...     table_detection_mode="ruling",
...     table_fallback_extraction_mode="grid"
... )
Enable OCR for scanned PDF documents:
>>> from all2md.options.common import OCROptions
>>> options = PdfOptions(
...     ocr=OCROptions(enabled=True, mode="auto", languages="eng")
... )
pages: list[int] | str | None = None
password: str | None = None
header_sample_pages: int | list[int] | None = None
header_percentile_threshold: float = 75
header_min_occurrences: int = 5
header_size_allowlist: list[float] | None = None
header_size_denylist: list[float] | None = None
header_use_font_weight: bool = True
header_use_all_caps: bool = True
header_font_size_ratio: float = 1.05
header_max_line_length: int = 100
header_debug_output: bool = False
dedup_running_headings: bool = True
detect_columns: bool = True
merge_hyphenated_words: bool = True
handle_rotated_text: bool = True
annotate_rotated_text: bool = False
column_gap_threshold: float = 20
column_detection_mode: Literal['auto', 'force_single', 'force_multi', 'disabled'] = 'auto'
use_column_clustering: bool = False
consolidate_inline_formatting: bool = True
enable_table_fallback_detection: bool = True
detect_merged_cells: bool = True
table_ruling_line_threshold: float = 0.5
table_fallback_extraction_mode: Literal['none', 'grid', 'text_clustering'] = 'grid'
image_placement_markers: bool = True
include_image_captions: bool = True
include_page_numbers: bool = False
table_detection_mode: Literal['pymupdf', 'ruling', 'both', 'none'] = 'both'
image_format: Literal['png', 'jpeg'] = 'png'
image_quality: int = 90
min_image_dimension: float = 20.0
filter_header_footer_images: bool = True
collapse_excess_whitespace: bool = True
trim_headers_footers: bool = False
auto_trim_headers_footers: bool = False
header_height: int = 0
footer_height: int = 0
link_overlap_threshold: float = 70.0
skip_image_extraction: bool = False
ocr: OCROptions
layout_analysis_mode: Literal['auto', 'enabled', 'disabled'] = 'auto'
layout_iou_threshold: float = 0.3
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, page_separator_template: str = '-----', pages: list[int] | str | None = None, password: str | None = None, header_sample_pages: int | list[int] | None = None, header_percentile_threshold: float = 75, header_min_occurrences: int = 5, header_size_allowlist: list[float] | None = None, header_size_denylist: list[float] | None = None, header_use_font_weight: bool = True, header_use_all_caps: bool = True, header_font_size_ratio: float = 1.05, header_max_line_length: int = 100, header_debug_output: bool = False, dedup_running_headings: bool = True, detect_columns: bool = True, merge_hyphenated_words: bool = True, handle_rotated_text: bool = True, annotate_rotated_text: bool = False, column_gap_threshold: float = 20, column_detection_mode: Literal['auto', 'force_single', 'force_multi', 'disabled']='auto', use_column_clustering: bool = False, consolidate_inline_formatting: bool = True, enable_table_fallback_detection: bool = True, detect_merged_cells: bool = True, table_ruling_line_threshold: float = 0.5, table_fallback_extraction_mode: Literal['none', 'grid', 'text_clustering']='grid', image_placement_markers: bool = True, include_image_captions: bool = True, include_page_numbers: bool = False, table_detection_mode: Literal['pymupdf', 'ruling', 'both', 'none']='both', image_format: Literal['png', 'jpeg']='png', image_quality: int = 90, min_image_dimension: float = 20.0, filter_header_footer_images: bool = True, collapse_excess_whitespace: bool = True, trim_headers_footers: bool = False, auto_trim_headers_footers: bool = False, header_height: int = 0, footer_height: int = 0, link_overlap_threshold: float = 70.0, skip_image_extraction: bool = False, ocr: OCROptions = <factory>, layout_analysis_mode: Literal['auto', 'enabled', 'disabled']='auto', layout_iou_threshold: float = 0.3) None
class all2md.options.PdfRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST to PDF format.

This dataclass contains settings specific to PDF generation using ReportLab, including page layout, fonts, margins, and formatting preferences.

Parameters:
  • page_size ({"letter", "a4", "legal"}, default "letter") – Page size for the PDF document.

  • margin_top (float, default 72.0) – Top margin in points (72 points = 1 inch).

  • margin_bottom (float, default 72.0) – Bottom margin in points.

  • margin_left (float, default 72.0) – Left margin in points.

  • margin_right (float, default 72.0) – Right margin in points.

  • font_name (str, default "Helvetica") – Default font for body text. Standard PDF fonts: Helvetica, Times-Roman, Courier.

  • font_size (int, default 11) – Default font size in points for body text.

  • heading_fonts (dict[int, tuple[str, int]] or None, default None) – Font specifications for headings as {level: (font_name, font_size)}. If None, uses scaled versions of default font.

  • code_font (str, default "Courier") – Monospace font for code blocks and inline code.

  • line_spacing (float, default 1.2) – Line spacing multiplier (1.0 = single spacing).

  • include_page_numbers (bool, default True) – Add page numbers to footer.

  • include_toc (bool, default False) – Generate table of contents from headings.

  • network (NetworkFetchOptions, default NetworkFetchOptions()) – Network security settings for fetching remote images. By default, remote image fetching is disabled (allow_remote_fetch=False). Set network.allow_remote_fetch=True to enable secure remote image fetching with the same security guardrails as PPTX renderer.

  • comment_mode ({"visible", "ignore"}, default "ignore") – How to render Comment and CommentInline AST nodes: - “visible”: Render as visible text/box - “ignore”: Skip comments entirely (default)

page_size: Literal['letter', 'a4', 'legal'] = 'letter'
margin_top: float = 72.0
margin_bottom: float = 72.0
margin_left: float = 72.0
margin_right: float = 72.0
font_name: str = 'Helvetica'
font_size: int = 12
heading_fonts: dict[int, tuple[str, int]] | None = None
code_font: str = 'Courier'
line_spacing: float = 1.2
include_page_numbers: bool = True
include_toc: bool = False
network: NetworkFetchOptions
comment_mode: Literal['visible', 'ignore'] = 'ignore'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', page_size: Literal['letter', 'a4', 'legal']='letter', margin_top: float = 72.0, margin_bottom: float = 72.0, margin_left: float = 72.0, margin_right: float = 72.0, font_name: str = 'Helvetica', font_size: int = 12, heading_fonts: dict[int, tuple[str, int]] | None=None, code_font: str = 'Courier', line_spacing: float = 1.2, include_page_numbers: bool = True, include_toc: bool = False, network: NetworkFetchOptions = <factory>, comment_mode: Literal['visible', 'ignore']='ignore') None
class all2md.options.PptxOptions

Bases: PaginatedParserOptions

Configuration options for PPTX-to-Markdown conversion.

This dataclass contains settings specific to PowerPoint presentation processing, including slide numbering and image handling.

Parameters:
  • include_slide_numbers (bool, default False) – Whether to include slide numbers in the output.

  • include_notes (bool, default True) – Whether to include speaker notes in the conversion.

  • comment_mode ({"content", "comment", "ignore"}, default "content") – How to parse speaker notes in the AST: - “content”: Parse as regular content nodes with H3 heading (default, current behavior) - “comment”: Parse as Comment AST nodes with metadata - “ignore”: Skip speaker notes entirely Note: This controls parsing of speaker notes. For rendering, see PptxRendererOptions.comment_mode.

Examples

Convert with slide numbers and base64 images:
>>> options = PptxOptions(include_slide_numbers=True, attachment_mode="base64")
Convert slides only (no notes):
>>> options = PptxOptions(include_notes=False)
Parse speaker notes as Comment nodes:
>>> options = PptxOptions(comment_mode="comment")
include_slide_numbers: bool = False
include_notes: bool = True
comment_mode: Literal['content', 'comment', 'ignore'] = 'content'
slides: str | None = None
charts_mode: Literal['data', 'mermaid', 'both'] = 'data'
include_titles_as_h2: bool = True
strict_list_detection: bool = False
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, page_separator_template: str = '-----', include_slide_numbers: bool = False, include_notes: bool = True, comment_mode: PptxParserCommentMode = 'content', slides: str | None = None, charts_mode: ChartsMode = 'data', include_titles_as_h2: bool = True, strict_list_detection: bool = False) None
class all2md.options.PptxRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST to PPTX format.

This dataclass contains settings specific to PowerPoint presentation generation from AST, including slide splitting strategies and layout.

Parameters:
  • slide_split_mode ({"separator", "heading", "auto"}, default "auto") – How to split the AST into slides: - “separator”: Split on ThematicBreak nodes (mirrors parser behavior) - “heading”: Split on specific heading level - “auto”: Try separator first, fallback to heading-based splitting

  • slide_split_heading_level (int, default 2) – Heading level to use for slide splits when using heading mode. Level 2 (H2) is typical (H1 might be document title).

  • default_layout (str, default "Title and Content") – Default slide layout name from template.

  • title_slide_layout (str, default "Title Slide") – Layout name for the first slide.

  • use_heading_as_slide_title (bool, default True) – Use first heading in slide content as slide title.

  • template_path (str or None, default None) – Path to .pptx template file. If None, uses default blank template.

  • default_font (str, default "Calibri") – Default font for slide content.

  • default_font_size (int, default 18) – Default font size in points for body text.

  • title_font_size (int, default 44) – Font size for slide titles.

  • list_number_spacing (int, default 1) – Number of spaces after the number prefix in ordered lists (e.g., “1. “ has 1 space). Affects visual consistency of manually numbered lists.

  • list_indent_per_level (float, default 0.5) – Indentation per nesting level for lists, in inches. Controls horizontal spacing for nested lists. Note that actual indentation behavior may vary across PowerPoint templates.

  • table_left (float, default 0.5) – Left position for tables in inches.

  • table_top (float, default 2.0) – Top position for tables in inches.

  • table_width (float, default 9.0) – Width for tables in inches.

  • table_height_per_row (float, default 0.5) – Height per row for tables in inches.

  • image_left (float, default 1.0) – Left position for images in inches.

  • image_top (float, default 2.5) – Top position for images in inches.

  • image_width (float, default 4.0) – Width for images in inches (aspect ratio maintained).

  • network (NetworkFetchOptions, default NetworkFetchOptions()) – Network security options for fetching remote images in slides.

  • include_notes (bool, default True) – Whether to detect and render speaker notes from “Speaker Notes” sections. When True, H3 headings with “Speaker Notes” text are detected, and content after them is rendered to slide speaker notes. When False, speaker notes sections are ignored and rendered as regular slide content.

  • comment_mode ({"speaker_notes", "visible", "ignore"}, default "speaker_notes") – How to render Comment and CommentInline AST nodes: - “speaker_notes”: Render in slide speaker notes (default) - “visible”: Render as visible italic text in slide content - “ignore”: Skip comments entirely

  • force_textbox_bullets (bool, default True) – Enable bullets via OOXML manipulation for unordered lists in text boxes. When True (default), bullets are explicitly enabled via OOXML for all text boxes. When False, bullets are only applied to content placeholders (native PowerPoint behavior). Set to False if using strict templates that conflict with OOXML manipulation.

  • slide_width (float, default 13.333) – Slide width in inches. Default is widescreen 16:9 (13.333”).

  • slide_height (float, default 7.5) – Slide height in inches. Default is 7.5” (standard for both 4:3 and 16:9).

  • content_margin_left (float, default 0.5) – Left margin for content area in inches.

  • content_margin_right (float, default 0.5) – Right margin for content area in inches.

  • content_margin_top (float, default 1.5) – Top margin for content area in inches (below title area).

  • content_margin_bottom (float, default 0.5) – Bottom margin for content area in inches.

  • element_gap (float, default 0.2) – Vertical gap between content blocks in inches.

  • use_flow_layout (bool, default True) – Enable the flow layout engine that positions text, tables, and images sequentially to avoid overlap. When False, uses the legacy fixed-position behavior where all text shares one frame and tables/images use fixed positions.

Notes

List Rendering Limitations:

python-pptx has limited support for automatic list numbering. This renderer uses manual numbering for ordered lists by adding number prefixes (e.g., “1. “) as text runs. The following options provide some control over list formatting:

  • list_number_spacing: Controls spacing after numbers

  • list_indent_per_level: Controls nesting indentation

However, deeper nesting and exact spacing behavior can be inconsistent across different PowerPoint templates. These limitations are inherent to python-pptx’s API and the complexity of PowerPoint’s list formatting system.

Unordered Lists in Text Boxes:

For unordered lists, bullets are explicitly enabled via OOXML manipulation to ensure they appear in both text boxes and content placeholders. Text boxes do not enable bullets by default, unlike content placeholders.

slide_split_mode: Literal['separator', 'heading', 'auto'] = 'auto'
slide_split_heading_level: int = 2
default_layout: str = 'Title and Content'
title_slide_layout: str = 'Title Slide'
use_heading_as_slide_title: bool = True
template_path: str | None = None
default_font: str = 'Calibri'
default_font_size: int = 24
title_font_size: int = 44
list_number_spacing: int = 1
list_indent_per_level: float = 0.5
table_left: float = 0.5
table_top: float = 2.0
table_width: float = 12.333
table_height_per_row: float = 0.5
image_left: float = 1.0
image_top: float = 2.5
image_width: float = 5.0
network: NetworkFetchOptions
include_notes: bool = True
comment_mode: Literal['speaker_notes', 'visible', 'ignore'] = 'speaker_notes'
force_textbox_bullets: bool = True
slide_width: float = 13.333
slide_height: float = 7.5
content_margin_left: float = 0.5
content_margin_right: float = 0.5
content_margin_top: float = 1.5
content_margin_bottom: float = 0.5
element_gap: float = 0.2
use_flow_layout: bool = True
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', slide_split_mode: SlideSplitMode = 'auto', slide_split_heading_level: int = 2, default_layout: str = 'Title and Content', title_slide_layout: str = 'Title Slide', use_heading_as_slide_title: bool = True, template_path: str | None = None, default_font: str = 'Calibri', default_font_size: int = 24, title_font_size: int = 44, list_number_spacing: int = 1, list_indent_per_level: float = 0.5, table_left: float = 0.5, table_top: float = 2.0, table_width: float = 12.333, table_height_per_row: float = 0.5, image_left: float = 1.0, image_top: float = 2.5, image_width: float = 5.0, network: NetworkFetchOptions = <factory>, include_notes: bool = True, comment_mode: PptxCommentMode = 'speaker_notes', force_textbox_bullets: bool = True, slide_width: float = 13.333, slide_height: float = 7.5, content_margin_left: float = 0.5, content_margin_right: float = 0.5, content_margin_top: float = 1.5, content_margin_bottom: float = 0.5, element_gap: float = 0.2, use_flow_layout: bool = True) None
class all2md.options.RstParserOptions

Bases: BaseParserOptions

Configuration options for reStructuredText-to-AST parsing.

This dataclass contains settings specific to parsing reStructuredText documents into AST representation using docutils.

Parameters:
  • strict_mode (bool, default False) – Whether to raise errors on invalid RST syntax. When False, attempts to recover gracefully.

  • parse_admonitions (bool, default True) – Whether to parse RST admonitions (note, warning, tip, important, etc.). When True, admonitions are converted to BlockQuote nodes with metadata indicating the admonition type. When False, admonitions are skipped.

  • strip_comments (bool, default False) – Whether to strip comments from the output. When True, RST comments are removed completely. When False, comments are preserved as Comment AST nodes with metadata.

Notes

RST directives are always processed by docutils. Directive types like code-block, image, and math are converted to their corresponding AST nodes. Admonitions (note, warning, tip, etc.) are converted to BlockQuote nodes with metadata when parse_admonitions=True.

strict_mode: bool = False
parse_admonitions: bool = True
strip_comments: bool = False
__init__(extract_metadata: bool = False, strict_mode: bool = False, parse_admonitions: bool = True, strip_comments: bool = False) None
class all2md.options.RstRendererOptions

Bases: BaseRendererOptions

Configuration options for AST-to-reStructuredText rendering.

This dataclass contains settings for rendering AST documents as reStructuredText output.

Parameters:
  • heading_chars (str, default "=-~^*") – Characters to use for heading underlines from h1 to h5. First character is for level 1, second for level 2, etc.

  • table_style ({"grid", "simple"}, default "grid") – Table rendering style: - “grid”: Grid tables with +—+ borders - “simple”: Simple tables with === separators

  • code_directive_style ({"double_colon", "directive"}, default "directive") – Code block rendering style: - “double_colon”: Use ::, literal blocks - “directive”: Use .. code-block::, directive

  • line_length (int, default 80) – Target line length for wrapping text.

  • hard_line_break_mode ({"line_block", "raw"}, default "line_block") – How to render hard line breaks: - “line_block”: Use RST line block syntax (pipe prefix), the standard approach - “raw”: Use plain newline, less faithful but simpler in complex containers

  • hard_line_break_fallback_in_containers (bool, default True) – Automatically fallback to raw mode for line breaks inside lists or blockquotes. When True, prevents semantic changes from line block syntax in containers. When False, always uses the configured hard_line_break_mode.

  • comment_mode ({"comment", "note", "ignore"}, default "comment") – How to render Comment and CommentInline AST nodes: - “comment”: Render as rST comments (.. Comment text) - “note”: Render as .. note:: directive blocks (visible annotations) - “ignore”: Skip comment nodes entirely This controls presentation of comments from source documents.

Notes

Text Escaping:

Special RST characters (asterisks, underscores, backticks, brackets, pipes, colons, angle brackets) are automatically escaped in text nodes to prevent unintended formatting.

Line Breaks:

Hard line breaks behavior depends on the hard_line_break_mode option:

  • line_block mode (default): Uses RST line block syntax (pipe prefix). This is the standard RST approach for preserving line structure. May be surprising inside complex containers like lists and block quotes as it changes semantic structure.

  • raw mode: Uses plain newlines. Less faithful to RST semantics but simpler in complex containers. May not preserve visual line breaks in all RST processors.

Soft line breaks always render as spaces, consistent with RST paragraph semantics.

Recommendation: Use “raw” mode if line blocks cause formatting issues in lists or nested structures. Use “line_block” (default) for maximum RST fidelity.

Unsupported Features:
  • Strikethrough: RST has no native strikethrough syntax. Content renders as plain text.

  • Underline: RST has no native underline syntax. Content renders as plain text.

  • Superscript/Subscript: Rendered using RST role syntax (:sup: and :sub:).

Table Limitations:

Both grid and simple table styles do not support multi-line content within cells. Cell content must be single-line text. Complex cell content (multiple paragraphs, nested lists) will be rendered inline, which may cause formatting issues.

heading_chars: str = '=-~^*'
table_style: Literal['grid', 'simple'] = 'grid'
code_directive_style: Literal['double_colon', 'directive'] = 'directive'
line_length: int = 80
hard_line_break_mode: Literal['line_block', 'raw'] = 'line_block'
hard_line_break_fallback_in_containers: bool = True
comment_mode: Literal['comment', 'note', 'ignore'] = 'comment'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', heading_chars: str = '=-~^*', table_style: RstTableStyle = 'grid', code_directive_style: RstCodeStyle = 'directive', line_length: int = 80, hard_line_break_mode: RstLineBreakMode = 'line_block', hard_line_break_fallback_in_containers: bool = True, comment_mode: RstCommentMode = 'comment') None
class all2md.options.RtfRendererOptions

Bases: BaseRendererOptions

Configuration options for rendering AST documents to RTF.

Parameters:
  • font_family ({"roman", "swiss"}, default "roman") – Base font family to pass to pyth’s Rtf15Writer. The roman family maps to Times New Roman, while swiss maps to Calibri.

  • bold_headings (bool, default True) – When True, heading text is rendered with the RTF bold style to distinguish it from body paragraphs.

  • comment_mode ({"bracketed", "ignore"}, default "bracketed") – How to render Comment and CommentInline AST nodes: - “bracketed”: Render as [bracketed text] (default) - “ignore”: Skip comments entirely

font_family: Literal['roman', 'swiss'] = 'roman'
bold_headings: bool = True
comment_mode: Literal['bracketed', 'ignore'] = 'bracketed'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', font_family: RtfFontFamily = 'roman', bold_headings: bool = True, comment_mode: RtfCommentMode = 'bracketed') None
class all2md.options.RtfOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for RTF-to-Markdown conversion.

This dataclass contains settings specific to Rich Text Format processing, including handling of embedded images and other attachments. Inherits attachment handling from AttachmentOptionsMixin.

Parameters:

AttachmentOptionsMixin (Inherited from BaseParserOptions and)

__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False) None
class all2md.options.SourceCodeOptions

Bases: BaseParserOptions

Configuration options for source code to Markdown conversion.

This dataclass contains settings specific to source code file processing, including language detection, formatting options, and output customization.

Parameters:
  • detect_language (bool, default True) – Whether to automatically detect programming language from file extension. When enabled, uses file extension to determine appropriate syntax highlighting language identifier for the Markdown code block.

  • language_override (str or None, default None) – Manual override for the language identifier. When provided, this language will be used instead of automatic detection. Useful for files with non-standard extensions or when forcing a specific syntax highlighting.

  • include_filename (bool, default False) – Whether to include the original filename as a comment at the top of the code block. The comment style is automatically chosen based on the detected or specified language.

detect_language: bool = True
language_override: str | None = None
include_filename: bool = False
__init__(extract_metadata: bool = False, detect_language: bool = True, language_override: str | None = None, include_filename: bool = False) None
class all2md.options.PlainTextOptions

Bases: BaseRendererOptions

Configuration options for plain text rendering.

This dataclass contains settings for rendering AST documents as plain, unformatted text. All formatting (bold, italic, headings, etc.) is stripped, leaving only the text content.

Parameters:
  • max_line_width (int or None, default 80) – Maximum line width for wrapping text. Set to None to disable wrapping. When enabled, long lines will be wrapped at word boundaries.

  • table_cell_separator (str, default " | ") – Separator string to use between table cells.

  • include_table_headers (bool, default True) – Whether to include table headers in the output. When False, only table body rows are rendered.

  • paragraph_separator (str, default "nn") – Separator string to use between paragraphs and block elements.

  • list_item_prefix (str, default "- ") – Prefix to use for list items (both ordered and unordered).

  • preserve_code_blocks (bool, default True) – Whether to preserve code block content with original formatting. When False, code blocks are treated like regular paragraphs.

  • preserve_blank_lines (bool, default True) – Whether to preserve consecutive blank lines in the output. When False, consecutive blank lines are collapsed according to paragraph_separator. When True, provides literal pass-through of blank lines for consumers that need exact whitespace preservation.

  • comment_mode ({"visible", "ignore"}, default "ignore") – How to render Comment and CommentInline AST nodes: - “visible”: Render as bracketed text - “ignore”: Skip comments entirely (default)

Examples

Basic plain text rendering:
>>> from all2md.ast import Document, Paragraph, Text
>>> from all2md.renderers.plaintext import PlainTextRenderer
>>> from all2md.options import PlainTextOptions
>>> doc = Document(children=[
...     Paragraph(content=[Text(content="Hello world")])
... ])
>>> options = PlainTextOptions(max_line_width=None)
>>> renderer = PlainTextRenderer(options)
>>> text = renderer.render_to_string(doc)
max_line_width: int | None = 80
table_cell_separator: str = ' | '
include_table_headers: bool = True
paragraph_separator: str = '\n\n'
list_item_prefix: str = '- '
preserve_code_blocks: bool = True
preserve_blank_lines: bool = True
comment_mode: Literal['visible', 'ignore'] = 'ignore'
__init__(fail_on_resource_errors: bool = False, max_asset_size_bytes: int = 52428800, metadata_policy: MetadataRenderPolicy = <factory>, creator: str | None = 'all2md', max_line_width: int | None = 80, table_cell_separator: str = ' | ', include_table_headers: bool = True, paragraph_separator: str = '\n\n', list_item_prefix: str = '- ', preserve_code_blocks: bool = True, preserve_blank_lines: bool = True, comment_mode: Literal['visible', 'ignore']='ignore') None
class all2md.options.XlsxOptions

Bases: SpreadsheetParserOptions

Configuration options for XLSX spreadsheet conversion.

This dataclass inherits all spreadsheet options from SpreadsheetParserOptions. Currently, XLSX has no format-specific options beyond the base spreadsheet options.

See SpreadsheetParserOptions for complete documentation of available options.

__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, sheets: list[str] | str | None = None, include_sheet_titles: bool = True, render_formulas: bool = True, max_rows: int | None = None, max_cols: int | None = None, truncation_indicator: str = '...', preserve_newlines_in_cells: bool = False, trim_empty: TrimEmptyMode = 'trailing', header_case: HeaderCaseOption = 'preserve', chart_mode: ChartMode = 'skip', merged_cell_mode: MergedCellMode = 'flatten') None
class all2md.options.ZipOptions

Bases: BaseParserOptions, AttachmentOptionsMixin

Configuration options for ZIP archive to Markdown conversion.

This dataclass contains settings specific to ZIP/archive processing, including file filtering, directory structure handling, and attachment extraction. Inherits attachment handling from AttachmentOptionsMixin for extracting embedded resources.

Parameters:
  • include_patterns (list[str] or None, default None) – Glob patterns for files to include (e.g., ['*.pdf', '*.docx']). If None, all parseable files are included.

  • exclude_patterns (list[str] or None, default None) – Glob patterns for files to exclude (e.g., ['__MACOSX/*', '.DS_Store']).

  • max_depth (int or None, default None) – Maximum directory depth to traverse. None means unlimited.

  • create_section_headings (bool, default True) – Whether to create section headings for each extracted file.

  • preserve_directory_structure (bool, default True) – Whether to include directory path in section headings.

  • flatten_structure (bool, default False) – Whether to flatten directory structure (ignore paths in output).

  • extract_resource_files (bool, default True) – Whether to extract non-parseable files (images, CSS, etc.) to attachment directory.

  • resource_file_extensions (list[str] or None, default None) – List of file extensions to treat as resources (e.g., ['.png', '.css', '.js']). If None, uses default list from RESOURCE_FILE_EXTENSIONS in constants. If empty list [], no files are treated as resources (all are parsed). Extensions should include the leading dot and are case-insensitive.

  • skip_empty_files (bool, default True) – Whether to skip files with no content or that fail to parse.

  • include_resource_manifest (bool, default True) – Whether to include a manifest table of extracted resources at the end of the document.

  • enable_parallel_processing (bool, default False) – Whether to enable parallel processing for large archives (opt-in). When enabled and file count exceeds parallel_threshold, files are processed in parallel using a process pool for improved performance.

  • max_workers (int or None, default None) – Maximum number of worker processes for parallel processing. If None, defaults to the number of CPU cores available.

  • parallel_threshold (int, default 10) – Minimum number of files required to enable parallel processing. Archives with fewer files are always processed sequentially.

include_patterns: list[str] | None = None
exclude_patterns: list[str] | None = None
max_depth: int | None = None
create_section_headings: bool = True
preserve_directory_structure: bool = True
extract_resource_files: bool = True
resource_file_extensions: list[str] | None = None
skip_empty_files: bool = True
include_resource_manifest: bool = True
enable_parallel_processing: bool = False
max_workers: int | None = None
parallel_threshold: int = 10
__init__(attachment_mode: AttachmentMode = 'alt_text', alt_text_mode: AltTextMode = 'default', attachment_output_dir: str | None = None, attachment_base_url: str | None = None, max_asset_size_bytes: int = 52428800, attachment_filename_template: str = '{stem}_{type}{seq}.{ext}', attachment_overwrite: AttachmentOverwriteMode = 'unique', attachment_deduplicate_by_hash: bool = False, attachments_footnotes_section: str | None = 'Attachments', extract_metadata: bool = False, include_patterns: list[str] | None = None, exclude_patterns: list[str] | None = None, max_depth: int | None = None, create_section_headings: bool = True, preserve_directory_structure: bool = True, extract_resource_files: bool = True, resource_file_extensions: list[str] | None = None, skip_empty_files: bool = True, include_resource_manifest: bool = True, enable_parallel_processing: bool = False, max_workers: int | None = None, parallel_threshold: int = 10) None
all2md.options.create_updated_options(options: Any, **kwargs: Any) Any

Create a new options instance with updated values.

This helper function supports the immutable pattern for frozen dataclasses. It creates a new instance of the options with the specified fields updated, rather than modifying the existing instance.

Parameters:
  • options (Any) – The original options instance (must be a dataclass)

  • **kwargs – Keyword arguments with the field names and new values to update

Returns:

A new options instance with the updated values

Return type:

Any

Examples

>>> original = PdfOptions(pages=[1, 2, 3])
>>> updated = create_updated_options(original, attachment_mode="base64", pages=[1])
>>> # original remains unchanged, updated has new values

For options documentation, see the user guide at Configuration Options or Core API for base option classes.