Command Line Interface
all2md provides a comprehensive command-line interface for converting documents to Markdown. This reference covers all available options and provides practical examples.
Basic Usage
Simple Conversion
The primary entry point is simply all2md. Provide one or more input paths and optional output arguments
to drive the conversion pipeline.
# Convert any document (output to stdout)
all2md document.pdf
# Save output to file
all2md document.pdf --out output.md
all2md document.docx -o report.md
# Process multiple files
for file in *.pdf; do
all2md "$file" --out "${file%.pdf}.md"
done
Reading from Standard Input
All file-processing commands support stdin by using - as the input argument. This follows standard Unix conventions and enables powerful piping workflows.
# Convert from stdin (main command)
cat document.pdf | all2md -
curl -s https://example.com/doc.pdf | all2md - --out output.md
# View from stdin in browser
echo "<h1>Quick Note</h1>" | all2md view -
cat presentation.pptx | all2md view - --theme dark
# Search content from stdin
cat report.pdf | all2md grep "search term" -
curl -s https://example.com/doc.html | all2md grep -i "keyword" -
# Compare with stdin (either source can be stdin, but not both)
echo "<p>Version 1</p>" | all2md diff - version2.html
cat modified.docx | all2md diff original.docx -
# With explicit format specification
cat unknown_file | all2md - --format pdf
Version and Help
# Show version
all2md --version
# Quick help with the most important options
all2md --help
all2md help
# Full reference (all options, grouped by format)
all2md help full
# Format-specific help (parser + renderer options)
all2md help pdf
all2md help docx
# Show detailed about information
all2md --about
Discovery Commands
List Available Formats
Use all2md list-formats to see all supported file formats and their details.
# List all formats
all2md list-formats
# Show only formats with all dependencies installed
all2md list-formats --available-only
# Display with rich formatting (tables and colors)
all2md list-formats --rich
Example output:
All2MD Supported Formats
================================================================================
Format Parser Renderer Extensions
--------------------------------------------------------------------------------
ARCHIVE [OK] N/A .tar, .tgz, .tar.gz, .tbz2 +6
ASCIIDOC [OK] [OK] .adoc, .asciidoc, .asc
DOCX [OK] [OK] .docx
HTML [OK] [OK] .html, .htm, .xhtml
PDF [OK] [OK] .pdf
XLSX [OK] N/A .xlsx
...
Total: 40 formats
Legend: [OK] = Available, [X] = Dependencies missing, N/A = Not implemented
Use 'all2md list-formats <format>' for detailed information
List Available Transforms
Use all2md list-transforms to see all available AST transforms. For detailed transform documentation, see AST Transforms and Hooks.
# List all transforms
all2md list-transforms
# Show details for a single transform
all2md list-transforms heading-offset
# Display with rich formatting
all2md list-transforms --rich
Example output:
Available Transforms
============================================================
add-heading-ids Generate and add unique IDs to heading nodes for anchors [headings, anchors, ids]
add-timestamp Add conversion timestamp to document metadata [metadata, timestamp]
heading-offset Shift heading levels by a specified offset [headings, structure]
remove-images Remove all Image nodes from the AST [images, cleanup]
text-replacer Find and replace text in Text nodes [text, replace]
title-promotion Promote a leading H1 to document title and shift subsequent headings up one level [headings, title, structure]
word-count Calculate word and character counts and add to metadata [metadata, statistics]
...
Total: 11 transforms
Use 'all2md list-transforms <transform>' for details
Search Command
all2md search builds a lightweight index over one or more documents and executes
keyword (BM25), vector (FAISS), hybrid, or simple grep searches. The command works
with any format supported by the core converters and can reuse or persist indexes for
faster follow-up queries.
# Keyword search across a directory (ephemeral index)
all2md search "contract termination" contracts/*.pdf --keyword
# Hybrid search with persisted index (requires extras: pip install all2md[search])
all2md search "macroeconomic outlook" reports/ --hybrid --index-dir ./index --persist
# Reuse an existing index without reprocessing inputs
all2md search "incident response" --index-dir ./index
Common grep-style flags are supported:
-A/-B/-Cto control trailing/leading context lines (e.g.-C 1for one line around each match)--regex/--no-regexto treat the query as a regular expression--richto enable colorized output (requiresrich)
Key options:
--mode/--grep/--keyword/--vector/--hybrid– select search strategy--index-dir– directory to load or store the index--persist– write the generated index to disk for later reuse--chunk-size/--chunk-overlap– control chunking granularity--vector-model– sentence-transformers model (vector or hybrid modes)
all2md search honours configuration defaults under the [search] section in
.all2md.toml. Install the optional extras all2md[search] to enable BM25 and
vector search backends.
Grep Command
all2md grep provides a simplified grep-style interface for text search across documents.
Unlike traditional grep, it works on binary document formats (PDF, DOCX, etc.) by converting
them to a searchable representation. This command is ideal for quick searches without the
overhead of building persistent indexes.
# Basic search
all2md grep "search term" document.pdf
# Case-insensitive search with line numbers
all2md grep -i -n "pattern" docs/*.md
# Search with context lines
all2md grep -C 2 "error" logs.pdf
# Limit line width and enable rich output
all2md grep -M 100 --rich "keyword" report.docx
Common grep-style options:
-i/--ignore-case– Perform case-insensitive matching (default: case-sensitive)-n/--line-number– Show line numbers for matching lines-A/--after-context– Print N lines of trailing context-B/--before-context– Print N lines of leading context-C/--context– Print N lines of leading and trailing context-e/--regex– Interpret query as a regular expression-M/--max-columns– Maximum display width for long lines (default: 150, 0 = unlimited)--rich– Enable colorized output with match highlighting--recursive– Recurse into directories when searching--exclude– Glob pattern to exclude files (repeatable)
The grep command provides section-based output, grouping matches by document structure
(headings, preambles) for better context. Line numbers are relative to each section when
using -n.
Diff Command
all2md diff compares two documents and generates a unified diff, similar to the Unix
diff command but supporting any document format (PDF, DOCX, HTML, etc.). The comparison
is text-based and guaranteed symmetric: comparing A to B produces the exact opposite of
comparing B to A (with +/- swapped).
Basic Usage
# Compare two documents (unified diff output by default)
all2md diff report_v1.pdf report_v2.pdf
# Compare documents of different formats
all2md diff contract.docx contract.pdf
# Save diff to file
all2md diff doc1.md doc2.md --output changes.diff
Common Options
Output Formats
# Unified diff (default, like diff -u)
all2md diff doc1.pdf doc2.pdf
# HTML visual diff (GitHub-style inline highlighting)
all2md diff doc1.pdf doc2.pdf --format html --output diff.html
# JSON structured diff (for programmatic access)
all2md diff doc1.pdf doc2.pdf --format json
Comparison Options
# Ignore whitespace changes (like diff -w)
all2md diff doc1.md doc2.md --ignore-whitespace
all2md diff doc1.md doc2.md -w
# Custom context lines (default: 3, like diff -C)
all2md diff doc1.pdf doc2.pdf --context 5
all2md diff doc1.pdf doc2.pdf -C 5
Color Output
# Colorize output automatically if terminal
all2md diff doc1.md doc2.md --color auto # (default)
# Always colorize (even when piped)
all2md diff doc1.md doc2.md --color always
# Never colorize
all2md diff doc1.md doc2.md --color never
Examples
Compare PDF Reports:
# Compare two versions of a report
all2md diff quarterly_report_q1.pdf quarterly_report_q2.pdf
# Generate visual HTML diff
all2md diff report_draft.pdf report_final.pdf \
--format html --output report_changes.html
Compare Word Documents:
# Compare contract versions, ignoring whitespace
all2md diff contract_v1.docx contract_v2.docx -w
# Save unified diff to file
all2md diff proposal_old.docx proposal_new.docx -o changes.diff
Cross-Format Comparison:
# Compare different formats of the same document
all2md diff document.md document.pdf
# Compare web page to markdown
all2md diff page.html page.md --ignore-whitespace
Symmetric Comparison:
# These produce opposite results (+ becomes -, - becomes +)
all2md diff doc1.pdf doc2.pdf
all2md diff doc2.pdf doc1.pdf
Output Formats
Unified Diff (Default)
Standard unified diff format compatible with patch, git diff, and other tools:
--- report_v1.pdf
+++ report_v2.pdf
@@ -1,5 +1,6 @@
# Executive Summary
This report covers Q1 performance.
+Key findings include revenue growth.
-## Challenges
+## Opportunities
We identified several growth areas.
HTML Visual Diff
GitHub-style inline highlighting with additions in green, deletions in red with strikethrough, and context in normal text. Ideal for viewing in a browser.
all2md diff doc1.pdf doc2.pdf --format html -o changes.html
# Open in browser: open changes.html
JSON Structured Diff
Machine-readable format for programmatic processing:
{
"type": "unified_diff",
"old_file": "doc1.pdf",
"new_file": "doc2.pdf",
"statistics": {
"lines_added": 3,
"lines_deleted": 2,
"lines_context": 15,
"total_changes": 5
},
"hunks": [
{
"header": "@@ -1,5 +1,6 @@",
"changes": [
{"type": "context", "content": "# Executive Summary"},
{"type": "added", "content": "Key findings..."},
{"type": "deleted", "content": "Old text..."}
]
}
]
}
ArXiv Command
all2md arxiv generates an ArXiv-ready LaTeX submission package from any supported
document format. The output is a .tar.gz archive (or directory) containing a
main.tex file, extracted figures, and an optional .bib bibliography file.
Basic Usage
# Generate a tar.gz submission archive from a document
all2md arxiv paper.md -o submission.tar.gz
# Include a bibliography file
all2md arxiv paper.docx -o submission.tar.gz --bib references.bib
# Output as a directory instead of tar.gz
all2md arxiv paper.pdf -o submission/ --output-format directory
Options
# Set document class and options
all2md arxiv paper.md -o out.tar.gz --document-class article
# Control figure extraction
all2md arxiv paper.md -o out.tar.gz --figure-format png --figure-dir figures
# Set bibliography style
all2md arxiv paper.md -o out.tar.gz --bib refs.bib --bib-style plainnat
# Custom main tex filename
all2md arxiv paper.md -o out.tar.gz --main-tex paper.tex
-o/--output(required) – Output path for archive or directory--bib– Path to a.bibbibliography file to include--document-class– LaTeX document class (default:article)--figure-format– Figure format:png,jpg, orpdf(default:png)--figure-dir– Figure subdirectory name in the archive (default:figures)--output-format–tar.gzordirectory(default:tar.gz)--bib-style– BibTeX bibliography style (default:plain)--main-tex– Main.texfilename (default:main.tex)
The generated archive contains:
main.tex– Complete LaTeX document with preamble, packages, and bodyfigures/– Extracted images wrapped in\begin{figure}environments*.bib– Bibliography file (if--bibwas provided)
Configuration Management
The all2md config command provides tools for managing configuration files.
See also
- Configuration Files
Comprehensive guide to configuration files, auto-discovery, priority order, and all supported formats (TOML, YAML, JSON, pyproject.toml).
Generate Default Configuration
Create a configuration file with all available options:
# Generate TOML configuration (recommended)
all2md config generate --out .all2md.toml
# Generate JSON configuration
all2md config generate --format json --out config.json
# Print to stdout
all2md config generate
all2md config generate --format json
The generated configuration includes: * A short header comment (TOML only) * Every available option with its current default value * Format-specific settings organized into one section per format
Example Generated Configuration (TOML):
# all2md configuration file
# Generated from current converter defaults
# Edit values as needed and remove sections you do not use.
extract_metadata = false
[html]
extract_title = false
strip_dangerous_elements = false
[markdown]
bullet_symbols = "*-+"
emphasis_symbol = "*"
use_hash_headings = true
[pdf]
detect_columns = true
enable_table_fallback_detection = true
merge_hyphenated_words = true
skip_image_extraction = false
# ... (one section per supported format)
Example Generated Configuration (JSON):
{
"html": {
"extract_title": false,
"strip_dangerous_elements": false
},
"markdown": {
"bullet_symbols": "*-+",
"emphasis_symbol": "*",
"use_hash_headings": true
},
"pdf": {
"detect_columns": true,
"enable_table_fallback_detection": true,
"merge_hyphenated_words": true,
"skip_image_extraction": false
}
}
Show Effective Configuration
Display the merged configuration from all sources:
# Show current configuration
all2md config show
# Show as JSON
all2md config show --format json
# Hide source information
all2md config show --no-source
This command shows configuration merged from:
1. ALL2MD_CONFIG environment variable
2. .all2md.toml or .all2md.json in current directory
3. .all2md.toml or .all2md.json in home directory
Example Output:
Configuration Sources (in priority order):
------------------------------------------------------------
1. ALL2MD_CONFIG env var: (not set)
2. /home/user/project/.all2md.toml [FOUND]
3. /home/user/.all2md.toml [-]
Effective Configuration:
============================================================
attachment_mode = "save"
attachment_output_dir = "./images"
[pdf]
detect_columns = true
[markdown]
emphasis_symbol = "_"
Validate Configuration File
Check configuration file syntax:
# Validate a configuration file
all2md config validate .all2md.toml
all2md config validate ~/.all2md.json
# Get detailed validation errors
all2md config validate my-config.toml
This verifies: * File can be read and parsed * JSON/TOML syntax is valid * Configuration structure is correct
Example Output (Valid Config):
Configuration file is valid: .all2md.toml
Format: .toml
Keys found: attachment_mode, pdf, html, markdown
Example Output (Invalid Config):
Invalid configuration file: Invalid TOML syntax at line 5: Expected '=' after key
Error validating configuration: .all2md.toml
Configuration Priority
Configuration sources are applied in this order (highest to lowest priority):
CLI arguments (highest priority)
--presetflag (see --preset for available presets)Explicit
--configflagEnvironment variable config (
ALL2MD_CONFIG)Auto-discovered config files (
.all2md.tomlor.all2md.json, lowest priority)
See also
- --preset
For information about preset configurations and how to use them
Example Workflow:
# 1. Generate a template
all2md config generate --out .all2md.toml
# 2. Edit the file with your preferences
vim .all2md.toml
# 3. Validate your changes
all2md config validate .all2md.toml
# 4. Check effective configuration
all2md config show
# 5. Use it (auto-discovered)
all2md document.pdf
Chunk Command
all2md chunk splits a document into chunks for retrieval-augmented generation
(RAG) and other LLM pipelines, emitting JSONL by default (one chunk per line).
Unlike flat-text chunkers, every chunk carries AST-derived provenance: the
section heading/level it came from and, where the source format records it, the
originating page span. This lets a downstream answer cite where a passage came
from.
Basic Usage
# Semantic chunks (section-bounded, real-token windows) as JSONL
all2md chunk report.pdf --strategy semantic --max-tokens 512 --overlap 64
# One chunk per section, written to a file
all2md chunk handbook.docx --strategy section --out chunks.jsonl
# Read from stdin
cat page.html | all2md chunk - --strategy paragraph
Strategies
Coarse (one chunk per semantic boundary): heading, section, auto.
Fine (windowed within each section, up to --max-tokens): semantic
(default), token, sentence, paragraph, word, line, char,
code.
Key Options
# Bound chunk size and overlap (overlap is coerced to 0 for coarse strategies)
all2md chunk doc.md --max-tokens 256 --overlap 32 --min-tokens 20
# Limit how deep section detection descends, and control structure
all2md chunk doc.md --max-heading-level 2 --no-include-preamble --no-heading-merge
# Output formats: jsonl (default), json (array), pretty (human-readable)
all2md chunk doc.md --format pretty
Element & Attachment Handling
The chunkers run on each section’s rendered Markdown, so tables, images, and code blocks appear in chunk text as their Markdown form. Fine strategies split by token budget and can otherwise cut a table mid-row; these flags give you control:
# Keep each table or fenced code block whole (its own chunk, may exceed --max-tokens)
all2md chunk report.pdf --avoid-table-split --avoid-code-split
# Strip noisy elements before chunking (aliases like images/tables accepted)
all2md chunk report.pdf --drop-elements image,table
# Long base64 data: URIs are elided to a placeholder by default; opt out with:
all2md chunk report.pdf --no-elide-data-uris
# Control how the converter handles images (avoids huge base64 blobs in chunks)
all2md chunk report.pdf --attachment-mode skip
all2md chunk also reads converter settings from a config file (the same [pdf],
[html], and top-level keys used by all2md/view/serve), honoring
--config/--no-config. --attachment-mode overrides the config value.
Tokenizer
Real BPE token counting (and the semantic/token/char strategies that
split on token boundaries) uses tiktoken:
pip install all2md[chunk]
Count-only strategies (sentence/word/line/paragraph/section/
heading/auto) fall back to a whitespace approximation when tiktoken is
not installed. Force a backend with --token-counter {auto,tiktoken,whitespace}.
JSONL Schema
Each line is a flat object: chunk_id, index, text, token_count,
token_counter, strategy, document_id, document_path,
section_heading, section_level, section_index, page, page_end,
source_line_start, source_line_end, char_start, char_end,
char_basis, prev_chunk_id, next_chunk_id. Character spans index into
the chunk’s rendered section text (char_basis="section_text"), and page
fields are populated only for formats that track pages.
Python API
The one-call all2md.chunk() mirrors to_markdown — convert and chunk a source
in a single step, returning ProvenanceChunk records:
import all2md
chunks = all2md.chunk("report.pdf", strategy="semantic", max_tokens=512, overlap=64)
for c in chunks:
print(c.chunk_id, c.section_heading, c.page, c.token_count)
record = c.to_dict() # the same flat object emitted as JSONL
It accepts the same shaping options as the CLI (min_tokens, avoid_table_split,
avoid_code_split, drop_elements=[...], elide_data_uris, …) and forwards any
extra keyword arguments to the converter (e.g. attachment_mode="skip").
document_id/document_path are derived from the source automatically.
For lower-level control over an AST you already hold, call
all2md.chunking.chunk_ast(doc, strategy=..., max_tokens=...) directly.
Report Command
all2md report prints a conversion confidence report — a reference-free
“quality card” for each document. Unlike roundtrip it needs no ground truth:
it surfaces the sanity signals the parsers already compute (text density, table
cell-fill and dot-leader ratios, OCR reliance, dropped-content events) as a
structured score instead of log noise.
# How much should I trust this conversion?
all2md report scan.pdf
# Gate a batch in CI: fail if any document scores below 80
all2md report inbox/*.docx --fail-under 80
# Machine-readable (an array when multiple inputs are given)
all2md report scan.pdf --json
$ all2md report scan.pdf
scan.pdf
confidence: 72/100 (MEDIUM)
producer: pdf
signals
chars per page 41 warn
ocr page fraction 1
tables detected 3
degraded events
warn table_rejected (mostly_empty)
The score starts at 100 and subtracts for observed evidence of lost or
low-fidelity content, so it inspects only what the converter itself saw. A
conversion that produced no quality instrumentation — no scored signals and
no degraded events, as docx, pptx and html do today — is banded NOT_ASSESSED
rather than HIGH: its 100 means “no detector ran”, not “verified clean”.
Key Options
--fail-under SCORE— exit non-zero if any document scores belowSCORE(0-100). Useful as a CI gate.--json— emit the report(s) as JSON (an array for multiple inputs).--out, -o FILE— write to a file instead of stdout.--attachment-mode {skip,alt_text,save,base64}— the report is unaffected by the choice; useskip/alt_textto avoid decoding large embedded images.--cache/--cache-dir DIR— reuse parsed documents from an on-disk cache (see Conversion Cache).
Python API
from all2md import confidence_report
report = confidence_report("scan.pdf")
print(report.score, report.band) # e.g. 72 medium
for event in report.degraded_events:
print(event.severity, event.kind, event.detail)
The same card rides on Document.metadata['confidence'] for every conversion,
so you can read it off any to_ast result without a second pass.
Roundtrip Command
all2md roundtrip converts a document to another format, parses it straight
back, and scores the structure that survived. Because the source document is its
own ground truth, a lossless round trip scores exactly 100 — anything less is
a concrete, itemized loss.
# How much does converting this DOCX to Markdown cost?
all2md roundtrip report.docx
# What would it cost to publish these notes as reStructuredText?
all2md roundtrip notes.md --via rst
# Gate a corpus in CI
all2md roundtrip docs/*.md --fail-under 95
The card reports an overall score plus the five dimensions behind it. Here a real DOCX loses only its underlines, which Markdown cannot express:
$ all2md roundtrip basic.docx
basic.docx
fidelity: 97/100 (HIGH)
pipeline: parse docx -> render markdown -> parse markdown
metrics
structure 100/100 headings, lists, tables, code blocks
text 100/100 the document's word stream
inline 82/100 bold, italic, code, links
tables 100/100 table dimensions and cell text
references 100/100 link and image targets
differences
warn inline_lost (underline)
structure carries the most weight (0.40), then text (0.30), inline
(0.15), tables (0.10) and references (0.05). Dimensions the source does
not exercise are dropped and the rest renormalized, so a document with no tables
is neither rewarded nor punished for the tables it does not have.
Key Options
--via FORMAT— the intermediate format (defaultmarkdown). It must have both a renderer and a parser; passing an unknown value prints the valid list.--format FORMAT— the source format, overriding auto-detection. Worth setting for stdin: piped Markdown sniffs as plaintext.--fail-under SCORE— exit non-zero if any document scores belowSCORE.--max-deltas N— show at mostNdifferences per document (0for all).--json— emit the report(s) as JSON for machine consumption.
Parser and renderer options come from the configuration file’s converter sections (see Configuration Files), not from flags on this subcommand.
Python API
from all2md import roundtrip_report, roundtrippable_formats
report = roundtrip_report("report.docx", via="markdown")
print(report.score, report.band, report.metrics["structure"])
for delta in report.deltas:
print(delta.severity, delta.kind, delta.detail)
print(roundtrippable_formats()) # formats usable as `via`
Because the score responds to converter options, it also prices a setting.
basic.md contains raw <u> tags, which the Markdown renderer escapes by
default as a security posture — that costs two points, and turning the escape off
recovers them:
roundtrip_report("basic.md").score # 98
roundtrip_report("basic.md", html_passthrough_mode="pass-through").score # 100
That makes this score a good way to price a renderer setting. It is not, however,
what all2md optimize searches on — re-parsing rendered output measures the
renderer, so it is blind to a parser that garbled the document in the first place (a
mangled table round-trips through Markdown perfectly). See Optimize Command.
Optimize Command
all2md optimize converts a document many times under different converter
settings and reports the ones that recover the most well-formed structure — as a
command you can run and a .all2md.toml snippet you can paste.
It is built for the documents that need it most: the gnarly PDF with no known-good output to compare against. So the objective is reference-free, and it is deliberately neither of the other two scores:
The confidence score (
all2md report) is a saturating breakage detector. On anything not visibly broken it pins to100regardless of settings — across a 16-combination sweep on a two-column PDF it produced one distinct score while the parsed AST produced four distinct outcomes. A flat objective cannot be searched.The round-trip score measures the renderer, not the parser (see above).
So the optimizer scores the parsed AST directly: how many well-formed tables, how much structure each setting recovers, and how much repeated furniture it left behind.
Body text is not one of those dimensions — it gates them. Losing a paragraph is data loss; leaving a running header in is an annoyance, and the two are not interchangeable at any exchange rate. A candidate’s body-text retention multiplies its score (cubed), so shedding 1% of the document costs roughly 3% of fitness and no amount of tidiness buys it back. The optimizer is deliberately conservative: advice that can silently delete text is not advice worth taking.
$ all2md optimize scanned.pdf
scanned.pdf
format: pdf
evaluated: 31 candidates
fitness: 98.93 (defaults scored 97.84, +1.09)
command
all2md scanned.pdf --pdf-trim-headers-footers
.all2md.toml
[pdf]
trim_headers_footers = true
The reported fitness ranks candidates against each other; it is not an absolute
quality score. For that, use all2md report (trust) or all2md roundtrip
(fidelity).
This is not cheap, and it is worth being concrete about why: the search runs tens of full conversions, and a PDF page costs roughly a second to parse. A 12-page paper is about 10 seconds per candidate, so a full run is ~5 minutes; a 100-page report is far worse. Two levers make that manageable:
--sample-pages Ntunes against a slice rather than the whole document.--cachemakes repeat runs nearly free — a warm cache cut a 31-candidate run from 18.5s to 0.3s.
Without --sample-pages the command says so on stderr before it starts, rather than
leaving you watching a blank terminal.
Key Options
--sample-pages N— tune against only the firstNpages. Use at least 2: running headers and footers are identified by the fact that they repeat, so a single-page sample cannot detect them at all.--rounds N— coordinate-descent passes over the knobs (default1). More rounds can find knobs that only pay off in combination, at proportionally more conversions.--no-presets— skip scoring the named presets and refine from the defaults only.--top N— how many ranked candidates to show (0for all).--out FILE— write the TOML snippet toFILE.--json— emit the full report, includingcommandandtoml, as JSON.--cache— reuse conversions across runs.
Tunable formats are pdf, html, and docx. The searched knobs are curated,
not derived from every option: an optimizer has no business flipping a security
posture such as strip_dangerous_elements.
Python API
from all2md import optimize_options, optimizable_formats
report = optimize_options("scanned.pdf", sample_pages=5)
print(report.best_options) # {'trim_headers_footers': True}
print(report.gain) # +1.09 over the defaults
for candidate in report.candidates[:5]:
print(candidate.fitness, candidate.origin, candidate.options)
print(optimizable_formats()) # ['docx', 'html', 'pdf']
Conversion Cache
Parsing is the expensive step, and several commands re-read the same files
repeatedly — optimize reconverts a document dozens of times, and grep /
search / chunk re-parse an unchanged corpus on every run. An opt-in
on-disk cache stores the parsed result keyed by the input’s fingerprint and the
conversion options, so a repeat run skips the re-parse entirely (a warm cache cut
a 31-candidate optimize run from 18.5s to 0.3s).
The cache is available on grep, search, chunk, view, report,
roundtrip and optimize:
all2md optimize scanned.pdf --cache
all2md report inbox/*.docx --cache
all2md grep "revenue" reports/ --cache
--cache— enable the cache for the command. Off by default. Also enabled by settingALL2MD_CACHE=1in the environment.--cache-dir DIR— where to store it. Defaults to a per-OS user cache directory, or$ALL2MD_CACHE_DIRif set.
An entry is reused only when both the input fingerprint and the conversion options match, so editing a file or changing a parser option transparently produces a fresh conversion. The environment variables are listed in Environment Variables.
Lint Command
all2md lint inspects converted documents and reports structural, heading,
link, list, table, image, and typography issues via a rule-based engine. The
linter operates on the AST, so it works against every format all2md can parse
(PDF, DOCX, HTML, Markdown, and the rest) without needing format-specific
logic. Forty-seven built-in rules ship across seven categories.
Rule Categories at a Glance
Code |
Count |
Category |
What it covers |
|---|---|---|---|
STR |
8 |
Structure |
Document shape: title presence, H1 uniqueness, heading hierarchy, empty/orphan headings, short sections, empty documents, excessive block-level nesting. |
HDG |
7 |
Headings |
Heading content: trailing punctuation, length, duplicates, capitalization consistency, emphasis-wrapped headings, sentence-shaped headings, URLs in headings. |
LNK |
7 |
Links |
Empty link text, missing URLs, duplicate URLs, bare URLs in prose,
low-quality link text, |
TYP |
8 |
Typography |
Trailing whitespace, multiple spaces, straight quotes, |
LST |
6 |
Lists |
Single-item lists, empty items, ordered-list numbering, excessive nesting, inconsistent trailing-punctuation, inconsistent capitalization across items. |
TBL |
6 |
Tables |
Missing header rows, empty cells, single-column / single-row tables, missing captions, excessive width. |
IMG |
5 |
Images |
Missing alt text, broken local image paths, duplicate images, oversized base64 inlining, unhelpful boilerplate alt text. |
Several typography and structure rules carry safe auto-fixes that --fix
applies in place — see Auto-Fix (--fix) below.
# Lint a single document
all2md lint document.md
# Lint every Markdown file in a directory tree
all2md lint docs/ --recursive
# Emit machine-readable JSON for CI consumption
all2md lint docs/ --format json --output lint-report.json
# Only run specific rules, or disable noisy ones
all2md lint --rule STR001 --rule STR003 document.md
all2md lint --disable TYP003 --disable HDG004 docs/
# Raise the reporting threshold (drops INFO from both output and exit code)
all2md lint --severity warning docs/
# Apply safe auto-fixes in place
all2md lint --fix README.md
# Preview --fix without writing the file
all2md lint --fix --dry-run README.md
# Start from a curated rule bundle (see --list-profiles)
all2md lint --profile prose report.md
all2md lint --list-profiles
Common options:
-R/--recursive– recurse into directories when collecting inputs--profile NAME– start from a curated rule bundle, then layer config-file and CLI settings on top (see Profiles below)--list-profiles– print the available profiles with descriptions and exit--format–text(default, human-readable) orjson(CI-friendly)--output– write the report to this file instead of stdout--config– explicit path to an.all2md.tomlorpyproject.toml--rule CODE– only run the listed rules (repeatable, acts as a whitelist)--disable CODE– skip the listed rules (repeatable, layered over config)--severity– minimum severity to report:info(default),warning, orerror--fix– apply safe auto-fixes in place (file inputs only)--dry-run– with--fix, report what would be changed without writing
Profiles
A profile packages a coherent set of rules and severities behind a single
flag, so you can opt into a house style without hand-assembling a long
--rule / --disable / --severity invocation. Three ship built in:
prose– polished long-form writing: typographic niceties, consistent heading style, and quality link text (curly-quote / em-dash / ellipsis rules promoted to warning). Ideal for a converted DOCX bound for publication.accessibility– alt text, descriptive link text, table headers, and a clean heading hierarchy enforced at error; stylistic typography omitted.technical-docs– enforce structure, valid links, and resolvable images, but relax prose-typography rules that fight code and reference-style writing.
Configuration layers on top of a profile in a fixed precedence — lowest to
highest: the --profile bundle, then [tool.all2md.lint] from the config
file, then explicit CLI flags. So --profile prose --disable TYP003 adopts
the prose bundle but silences one rule. --disable lists are unioned
across layers; severity and per-rule options merge with the more specific
layer winning. For a worked DOCX example and CI patterns, see Linting & Enforcing a Style Guide.
The --severity flag filters both the displayed output and the process
exit code. With --severity warning, info-level violations are dropped and
no longer affect CI gating — the mental model is “what you see is what fails
CI”.
Exit codes:
0– no violations remain after the severity filter3– one or more violations remain (EXIT_VALIDATION_ERROR)4– input file not found
Configuration lives under [tool.all2md.lint] in pyproject.toml (or
[lint] in .all2md.toml). See Lint Options for the full
schema and a worked example. To discover every registered rule at runtime,
import the registry:
from all2md.linter import rule_registry
print(rule_registry.list_rules()) # all 47 codes
print(rule_registry.list_rules(category="structure"))
Built-in Rules
Code |
Name |
Severity |
Check |
|---|---|---|---|
|
|
error |
Document has no top-level H1 heading. |
|
|
warning |
More than one H1 heading in the document. |
|
|
error |
Heading level skips (for example, H1 followed by H3). |
|
|
error |
Heading contains no text. |
|
|
warning |
A heading is the last child of the document with no content after it. |
|
|
info |
Heading ends with sentence-style punctuation ( |
|
|
info |
Heading exceeds |
|
|
warning |
Two headings at the same level share the same text (case-insensitive). |
|
|
info |
Same-level headings diverge from the dominant capitalization style. |
|
|
warning |
Heading content is a single |
|
|
warning |
Link has no visible text. |
|
|
error |
Link URL is empty or whitespace-only. |
|
|
info |
The same URL is linked from more than one place. |
|
|
info |
Raw URL appears in prose text instead of being wrapped in a |
|
|
warning |
Link text is a generic filler phrase (“click here”, “read more”, etc.). |
|
|
info |
A |
|
|
warning |
Text contains runs of two or more consecutive spaces. |
|
|
info |
Text uses straight ASCII quotes around a word instead of curly quotes. |
|
|
info |
Text contains |
|
|
warning |
Adjacent sibling lists disagree on the ordered/unordered style. |
|
|
info |
Text contains |
|
|
info |
Text has a space before |
|
|
warning |
Text contains repeated punctuation like |
|
|
info |
Section under a heading has fewer than |
|
|
error |
Document contains no children. |
|
|
warning |
Block-level nesting (blockquotes / list items) exceeds |
|
|
info |
Heading exceeds |
|
|
warning |
Heading text contains a URL. |
|
|
info |
Link uses |
|
|
info |
Link’s visible text duplicates its URL ( |
|
|
info |
List contains only one item — usually should be a paragraph. |
|
|
warning |
List item has no rendered text content. |
|
|
info |
Ordered list does not start at 1. |
|
|
warning |
List nesting exceeds |
|
|
info |
List items mix trailing-period and no-trailing-period styles. |
|
|
info |
List items mix upper- and lower-case first characters. |
|
|
warning |
Table has no header row. |
|
|
info |
Table contains cells with no rendered content. |
|
|
info |
Table has only one column — should usually be a list. |
|
|
info |
Table has only one body row — may not need to be a table. |
|
|
info |
Table has neither a caption nor a preceding paragraph introducing it. |
|
|
warning |
Table has more than |
|
|
warning |
Image has empty |
|
|
error |
Image’s local path does not exist on disk (resolved relative to the input file). |
|
|
info |
Same image URL appears more than once in the document. |
|
|
warning |
Inline base64 image exceeds |
|
|
info |
Alt text is a generic placeholder (“image”, “photo”, “screenshot”, etc.). |
Auto-Fix (--fix)
A subset of rules ship with safe auto-fixes that the linter can apply
in place. Pass --fix to apply them and rewrite the input file:
all2md lint --fix README.md
Currently auto-fixable (all classified as safe):
TYP001trailing-spaces — strip trailing whitespaceTYP002multiple-spaces — collapse runs of spaces to a single spaceTYP003straight-quotes — replace"…"/'…'with curly equivalentsTYP004double-hyphens — replace--with em-dash (—)TYP006ellipsis-character — replace...with…TYP007space-before-punctuation — remove the offending spaceSTR004empty-heading — remove the empty heading from the document
Use --dry-run together with --fix to see what would be changed
without writing the file:
all2md lint --fix --dry-run README.md
The reporter prints an applied N fix(es) summary per file plus the
post-fix violation list (everything still left to address). When two
fixes target the same AST node the linter applies them across multiple
internal passes, but a small handful may still defer with a
"... fix(es) deferred due to conflicts — re-run lint --fix to apply"
footer; rerun --fix to converge.
--fix requires file inputs — it cannot operate on stdin or remote
inputs because there is no file to rewrite. A clean document (no
applicable fixes) is never rewritten, so re-running --fix against an
already-clean file produces a byte-identical result.
Text Output Format
The default text reporter emits one line per violation in a ruff-style
path:line:column: CODE severity: message format, with optional
suggestion: and context: lines indented underneath:
docs/handbook.md:12:1: STR003 error: Heading level 4 follows level 1
suggestion: Use heading level 2 instead
docs/handbook.md:25:-: LNK001 warning: Link to 'https://example.com' has no visible text
suggestion: Add descriptive text for the link
Found 2 violations (1 errors, 1 warnings, 0 info) in 1 file
A dash (-) in the line or column slot means the underlying parser did not
populate a SourceLocation for the node. This is common for formats that
don’t carry positional information (PDF, DOCX, image-based OCR).
JSON Output Format
With --format json, the reporter emits a structured document suitable for
parsing in CI pipelines:
{
"summary": {
"files": 1,
"violations": 2,
"errors": 1,
"warnings": 1,
"info": 0
},
"results": [
{
"file_path": "docs/handbook.md",
"rules_checked": 20,
"error_count": 1,
"warning_count": 1,
"info_count": 0,
"violations": [
{
"rule_code": "STR003",
"rule_name": "heading-hierarchy",
"message": "Heading level 4 follows level 1",
"severity": "error",
"line": 12,
"column": 1,
"node_type": "Heading",
"suggestion": "Use heading level 2 instead",
"fixable": false,
"context": null
}
]
}
]
}
Python API
Every CLI capability is available from Python via the all2md.linter package:
from all2md import to_ast
from all2md.linter import LintConfig, lint_document, Severity
doc = to_ast("whitepaper.pdf")
config = LintConfig(
severity_threshold=Severity.WARNING,
disabled_rules=frozenset({"TYP003", "HDG004"}),
)
result = lint_document(doc, config=config)
print(f"Errors: {result.error_count}, Warnings: {result.warning_count}")
for violation in result.violations:
print(f" {violation.rule_code}: {violation.message}")
See Python API Workflows (“Document Linting”) for details on the runner, rule
registry, and writing custom rules via the all2md.lint_rules entry-point
group.
Static Site Generation
The all2md generate-site subcommand converts document collections into Hugo, Jekyll, MkDocs, Zola, or Eleventy static sites with proper frontmatter, asset organization, and directory structures.
all2md generate-site INPUT... --output-dir DIR --generator GENERATOR [OPTIONS]
Basic Usage
Convert a directory of documents to a Hugo site:
all2md generate-site docs/ \
--output-dir my-hugo-site \
--generator hugo \
--scaffold \
--recursive
Convert blog posts to a Jekyll site:
all2md generate-site posts/*.md \
--output-dir my-blog \
--generator jekyll \
--scaffold
Convert a directory of documents to an MkDocs site:
all2md generate-site docs/ \
--output-dir my-mkdocs-site \
--generator mkdocs \
--scaffold \
--recursive
Arguments
Required Arguments:
INPUT...One or more input files or directories to convert
--output-dir DIROutput directory for the generated site
--generator {hugo,jekyll,mkdocs,zola,eleventy}Static site generator to target (hugo, jekyll, mkdocs, zola, or eleventy)
Optional Arguments:
--scaffoldCreate complete site structure with config files and layouts
--frontmatter-format {yaml,toml}Override default frontmatter format (Hugo and Zola default to TOML; Jekyll, MkDocs, and Eleventy to YAML)
--content-subdir PATHSubdirectory within content dir for output (e.g., “posts” creates content/posts/ for Hugo)
--recursiveRecursively process directories
--exclude PATTERNExclude files matching pattern (can be used multiple times)
Examples
Hugo Site with Scaffolding:
# Create complete Hugo site structure
all2md generate-site documentation/ \
--output-dir my-docs-site \
--generator hugo \
--scaffold \
--recursive
# Result:
# my-docs-site/
# ├── config.toml
# ├── content/
# │ ├── _index.md
# │ ├── page1.md
# │ └── page2.md
# ├── static/images/
# │ └── (copied images)
# ├── themes/
# ├── layouts/
# └── data/
Jekyll Blog with Date Prefixes:
# Convert blog posts with metadata
all2md generate-site posts/ \
--output-dir my-blog \
--generator jekyll \
--scaffold \
--recursive
# Result:
# my-blog/
# ├── _config.yml
# ├── _posts/
# │ ├── 2025-01-22-my-post.md
# │ └── 2025-01-20-another-post.md
# ├── assets/images/
# │ └── (copied images)
# ├── _layouts/
# │ ├── default.html
# │ └── post.html
# └── _includes/
MkDocs Site with Scaffolding:
# Create complete MkDocs site structure
all2md generate-site documentation/ \
--output-dir my-mkdocs-site \
--generator mkdocs \
--scaffold \
--recursive
# Result:
# my-mkdocs-site/
# ├── mkdocs.yml
# └── docs/
# ├── index.md
# ├── page1.md
# ├── page2.md
# └── images/
# └── (copied images)
Zola Site with Scaffolding:
# Create complete Zola site structure (TOML frontmatter, like Hugo)
all2md generate-site documentation/ \
--output-dir my-zola-site \
--generator zola \
--scaffold \
--recursive
# Result:
# my-zola-site/
# ├── config.toml
# ├── content/
# │ ├── _index.md
# │ └── page1.md
# ├── static/images/
# │ └── (copied images)
# └── templates/
# ├── base.html
# ├── index.html
# ├── section.html
# └── page.html
Eleventy (11ty) Site with Scaffolding:
# Create complete Eleventy site structure
all2md generate-site documentation/ \
--output-dir my-eleventy-site \
--generator eleventy \
--scaffold \
--recursive
# Result:
# my-eleventy-site/
# ├── .eleventy.js
# ├── package.json
# └── src/
# ├── index.md
# ├── page1.md
# └── images/
# └── (copied images)
Without Scaffolding (Content Only):
# Just convert files, don't create config/layouts
all2md generate-site reports/ \
--output-dir hugo-reports \
--generator hugo \
--content-subdir reports
With Exclusions:
# Exclude drafts and private files
all2md generate-site content/ \
--output-dir site \
--generator hugo \
--recursive \
--exclude "draft-*" \
--exclude "private/*"
Custom Frontmatter Format:
# Use YAML frontmatter with Hugo (instead of default TOML)
all2md generate-site docs/ \
--output-dir hugo-site \
--generator hugo \
--frontmatter-format yaml
Frontmatter Generation
The command automatically generates frontmatter from document metadata:
Metadata Mapping:
title→ Extracted from document title or filenamedate→ From creation_date, date, or modified metadataauthor→ From author fielddescription→ From description or subject fieldtags→ From tags or keywords field (comma-separated)categories→ From categories or category field (comma-separated)
Generator-Specific Fields:
Hugo:
- draft: false (always set)
- weight (if present in metadata)
Jekyll:
- layout: post (default)
- permalink (if present in metadata)
MkDocs:
- Common fields only (title, date, author, description, tags); no generator-specific fields are added
Zola:
- draft: false (always set), weight (if present in metadata)
- tags/categories nested under [taxonomies] and author under [extra] (Zola rejects unknown top-level keys)
Eleventy:
- Common fields only; tags double as Eleventy collection names
Example frontmatter output (Hugo/TOML):
+++
title = "Getting Started Guide"
date = 2025-01-22T10:00:00
author = "Jane Doe"
description = "A comprehensive guide to getting started"
tags = ["tutorial", "beginner"]
draft = false
+++
Example frontmatter output (Jekyll/YAML):
---
title: Getting Started Guide
date: 2025-01-22 10:00:00
author: Jane Doe
description: A comprehensive guide to getting started
categories:
- tutorial
- beginner
layout: post
---
Asset Management
Images and other assets are automatically:
Collected from the document AST
Copied to the appropriate static directory
Referenced with updated paths in the markdown
Hugo: Assets → static/images/, referenced as /images/filename
Jekyll: Assets → assets/images/, referenced as /assets/images/filename
MkDocs: Assets → docs/images/, referenced as /images/filename
Zola: Assets → static/images/, referenced as /images/filename
Eleventy: Assets → src/images/ (passthrough-copied), referenced as /images/filename
See Also
Static Site Generation - Complete static site generation guide
Command Line Interface - Complete CLI reference
all2md --help- Built-in help
Document Viewing
The all2md view command provides a quick way to preview any supported document format by converting it to HTML and opening it in your default web browser. This is especially useful for rapid document inspection during development or when reviewing document conversions.
all2md view FILE [OPTIONS]
Basic Usage
Convert and view a document with the default minimal theme:
# View any supported document format
all2md view document.pdf
all2md view report.docx
all2md view slides.pptx
all2md view README.md
The command will:
Convert the document to HTML using the AST
Apply a clean, responsive theme
Open the result in your default browser
Wait for you to press Enter
Clean up the temporary HTML file (unless
--keepis used)
Arguments
Required Arguments:
FILEPath to the document to view. Supports all formats that all2md can convert (PDF, DOCX, PPTX, HTML, Markdown, etc.).
Optional Arguments:
--keep [PATH]Keep the HTML file instead of deleting it after viewing. Can optionally specify an output path.
Without an argument: Keep the temporary file in the system temp directory
With a path: Save directly to the specified file (no temp file, no cleanup prompt)
# Keep the temporary file all2md view document.pdf --keep # Save to specific file all2md view document.pdf --keep output.html # Save to subdirectory (created automatically) all2md view document.pdf --keep docs/preview.html
--no-waitDon’t wait for the browser to close before returning. Useful in scripts and non-interactive environments. The temp file is kept long enough for the browser to load it.
# Open in browser and return immediately all2md view document.pdf --no-wait
--tocInclude an automatically generated table of contents in the HTML output. The TOC is automatically placed based on the theme:
For most themes: TOC appears after the first heading in the content
For
sidebartheme: TOC appears in the left sidebar
# Add table of contents all2md view long-document.pdf --toc # Use sidebar theme with TOC all2md view document.pdf --toc --theme sidebar
--darkUse the dark mode theme with a dark background and light text. Quick shortcut for
--theme dark.# View in dark mode all2md view document.pdf --dark
--windowOpen the preview in a standalone native window (no address bar or browser chrome) instead of a browser tab. Requires the optional
pywebviewdependency (pip install all2md[window]); if it is not installed,all2mdprints a hint and falls back to a normal browser tab. Closing the window cleans up the temporary file (unless--keepwas given).# View in a standalone window all2md view document.pdf --window
--theme THEMESpecify a theme for the HTML output.
THEMEmay be a built-in theme name, a path to a custom.htmltemplate, a path to a plain.cssfile (wrapped automatically in a minimal HTML shell), or a name registered in the[themes]table of a configuration file (see Custom Themes).Built-in themes:
minimal(default) - Clean, centered layout with simple typographydark- Dark mode with VS Code-inspired color schemenewspaper- Classic newspaper style with serif fonts and justified textdocs- GitHub-style documentation layout with technical stylingsidebar- Two-column layout with sticky TOC sidebar (requires--toc)
# Use built-in newspaper theme all2md view article.md --theme newspaper # Use built-in docs theme all2md view technical-spec.pdf --theme docs # Use sidebar theme with TOC all2md view long-document.pdf --toc --theme sidebar # Use custom theme template all2md view document.pdf --theme /path/to/custom-theme.html
--no-mermaidDisable client-side rendering of
mermaidcode blocks as diagrams. By default, fenced blocks taggedmermaidare drawn with mermaid.js loaded from a CDN; with this flag they render as ordinary code blocks instead.--no-syntax-highlightDisable client-side syntax highlighting of code blocks. By default, code blocks are highlighted with highlight.js loaded from a CDN, matching the language tag on each fence (and the detected language of raw source files).
Note
Mermaid and highlight.js are loaded from cdn.jsdelivr.net. When offline the page
still renders: diagrams appear as their source text and code blocks are shown without
highlighting. The dark variants are used automatically with --dark or the dark
theme.
Built-in Themes
minimal (default)
Clean, modern design with a centered layout (800px max-width). Uses system fonts with excellent readability. Features subtle borders and shading for code blocks and tables.
Best for: General documents, reports, articles
Typography: Sans-serif system fonts
Layout: Single-column, centered
Colors: Light background with dark text
dark
Dark mode theme with a VS Code-inspired color palette. Reduces eye strain for extended viewing sessions. Syntax highlighting colors for code elements.
Best for: Late-night reading, code-heavy documents
Typography: Sans-serif system fonts
Layout: Single-column, centered (900px max-width)
Colors: Dark gray background (#1e1e1e) with light text (#d4d4d4)
Accents: Blue headings (#569cd6), teal links (#4ec9b0)
newspaper
Classic newspaper layout with serif typography and justified text. Features a distinctive drop cap on the first paragraph and traditional styling.
Best for: Long-form content, articles, essays
Typography: Georgia/Times New Roman serif fonts
Layout: Single-column with wider max-width (1000px)
Colors: Off-white background (#f9f7f3) with black text
Special: Drop cap on first paragraph, quote styling
docs
GitHub-inspired technical documentation style. Clean, professional appearance with excellent code formatting and technical elements.
Best for: Technical documentation, API docs, README files
Typography: System fonts with monospace for code
Layout: Single-column (1200px max-width)
Colors: Light gray background (#f6f8fa) with dark text
Special: Hash symbols on headings, enhanced code blocks
sidebar
Two-column layout with a fixed sidebar for the table of contents. The TOC stays visible while scrolling through long documents. Responsive design collapses to single column on mobile.
Best for: Long documents, reference materials, technical guides
Typography: Clean system fonts
Layout: Two-column (280px sidebar + flexible content area)
Colors: White background with light gray sidebar
Special: Sticky TOC navigation, smooth scrolling, mobile-responsive
Requires: Must be used with
--tocflag for meaningful layout
Custom Themes
You can create custom HTML themes using placeholder replacement. Themes are standard HTML files with placeholders that will be replaced with the converted content.
Available Placeholders:
{CONTENT}- The converted document content (required){TOC}- Table of contents (optional, only used when--tocis specified){TITLE}- Document title from metadata{AUTHOR}- Document author from metadata{DATE}- Document date from metadata{DESCRIPTION}- Document description from metadata
Basic Custom Theme Structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Viewer</title>
<style>
/* Your custom CSS here */
body {
font-family: Arial, sans-serif;
max-width: 900px;
margin: 0 auto;
padding: 2rem;
}
/* Add more styles as needed */
</style>
</head>
<body>
{CONTENT}
</body>
</html>
Custom Theme with Sidebar TOC:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{TITLE}</title>
<style>
body { display: flex; }
aside { width: 250px; padding: 1rem; }
main { flex: 1; padding: 2rem; }
</style>
</head>
<body>
<aside>{TOC}</aside>
<main>{CONTENT}</main>
</body>
</html>
Using Custom Themes:
# Save your custom theme as my-theme.html
all2md view document.pdf --theme ./my-theme.html
# Use custom theme with TOC
all2md view document.pdf --theme ./my-theme.html --toc
The HTML renderer will replace all placeholders with the appropriate content while preserving all your custom styling and structure.
CSS-only themes:
If you only want to change styling, you can point --theme at a plain .css file
instead of authoring a full HTML template. The stylesheet is wrapped automatically in a
minimal HTML shell that provides the {TITLE}/{CONTENT} placeholders:
all2md view document.pdf --theme ./my-styles.css
all2md serve ./docs --theme ./my-styles.css
Named themes via configuration:
Register reusable theme names in a [themes] table in any all2md configuration file
(.all2md.toml, pyproject.toml under [tool.all2md.themes], etc.). Values may
point at .html templates or .css files:
[themes]
corporate = "~/themes/corporate.html"
brand = "~/themes/brand.css"
# Resolve the registered name
all2md view report.pdf --theme corporate
all2md serve ./docs --theme brand
You can also set a default theme per command via the [view]/[serve] sections
(theme = "corporate").
Examples
Basic Viewing:
# View a PDF with default theme
all2md view report.pdf
# View a Word document with dark theme
all2md view document.docx --dark
# View a Markdown file with table of contents
all2md view README.md --toc
Theme Selection:
# Use newspaper theme for an article
all2md view article.md --theme newspaper
# Use docs theme for technical documentation
all2md view api-spec.pdf --theme docs
# Use custom theme
all2md view report.docx --theme ./company-theme.html
Saving Output Files:
# Keep the temporary file for later inspection
all2md view document.pdf --keep --dark
# Temporary file: /tmp/all2md-view-abc123.html
# Kept temporary file: /tmp/all2md-view-abc123.html
# Save directly to a specific file
all2md view document.pdf --keep output.html
# Saved to: /path/to/output.html
# Save to subdirectory (created automatically)
all2md view report.docx --keep previews/report-preview.html --dark
# Saved to: /path/to/previews/report-preview.html
Combined Options:
# View with all options
all2md view long-document.pdf --theme docs --toc --keep
# Dark mode with table of contents
all2md view technical-manual.docx --dark --toc
# Newspaper theme without cleanup
all2md view essay.md --theme newspaper --keep
Use Cases
Quick Document Preview:
View converted documents before committing to a full conversion pipeline:
# Preview how a PDF will convert all2md view input.pdf # Try different themes to find the best look all2md view document.pdf --theme minimal all2md view document.pdf --theme newspaper all2md view document.pdf --theme docs
Development and Testing:
During converter development or debugging:
# Quickly view conversion results all2md view test-document.pdf --keep # Save test output for comparison all2md view test-document.pdf --keep test-outputs/current.html # Check table of contents generation all2md view long-doc.pdf --toc # Generate HTML artifacts for CI/CD all2md view report.pdf --keep artifacts/report.html --theme docs
Documentation Review:
Preview documentation files with appropriate themes:
# View README with docs theme all2md view README.md --theme docs # View API docs with TOC all2md view api-reference.pdf --theme docs --toc
Presentation Review:
Quickly preview PowerPoint slides:
# View presentation slides all2md view presentation.pptx # Dark mode for better visibility all2md view slides.pptx --dark
Notes
The temporary HTML file is created in your system’s temp directory (
/tmpon Unix,%TEMP%on Windows)The file is automatically opened in your default web browser
Cleanup happens after you press Enter, ensuring the browser has time to load the file
With
--keep, the temporary file path is displayed for easy accessAll standard all2md conversion options are applied during the HTML generation
The command supports all document formats that all2md can process
See Also
Python API Workflows - For programmatic HTML generation
Configuration Options - For HTML rendering options
all2md --help- Built-in help
Document Outline
The --outline flag provides a quick way to view the structure of any document by extracting and displaying all headings as a table of contents. This is useful for understanding document organization, navigating large documents, or quickly assessing document structure before processing.
Basic Usage
Extract and display the document outline:
# View outline of any document
all2md document.pdf --outline
all2md report.docx --outline
all2md README.md --outline
The outline is displayed as a markdown-formatted list with proper indentation showing the heading hierarchy:
* Introduction
* Background
* Historical Context
* Objectives
* Methods
* Experimental Design
* Data Collection
* Results
* Findings
Options
--outlineOutput the document outline (table of contents) instead of full content. Shows all headings in markdown list format with indentation reflecting the heading hierarchy.
# Extract outline from PDF all2md document.pdf --outline # Extract outline from Word document all2md report.docx --outline
--outline-max-level LEVELLimit the depth of headings included in the outline (1-6, default: 6). This is useful for getting a high-level overview of deeply nested documents.
# Show only top 2 heading levels all2md document.pdf --outline --outline-max-level 2 # Show only top-level headings all2md report.docx --outline --outline-max-level 1
--line-numbers/-lnAnnotate each heading with the line number it occupies in the full Markdown conversion. This turns the outline into a heading → line map, which pairs directly with
--extract line:X-Y(see Extracting by Line Range) so a reader – or an LLM/agent – can jump straight to the range it cares about.all2md document.pdf --outline --line-numbers
1: * Introduction 5: * Background 19: * Methods 23: * Data Collection 27: * Conclusion
The same flag also numbers a normal conversion (every line,
cat -nstyle) and, with--extract, keeps the returned lines’ original numbers. Line numbers reference the Markdown rendering and are ignored for other output formats.
Output Options
The outline can be output to stdout (default) or saved to a file:
# Output to stdout
all2md document.pdf --outline
# Save to file
all2md document.pdf --outline --out outline.txt
all2md document.pdf --outline -o structure.md
Rich Formatting
When the rich library is installed, you can enable rich formatting for enhanced terminal output:
# Enable rich formatting with colors and styling
all2md document.pdf --outline --rich
# Rich formatting with pager for long outlines
all2md document.pdf --outline --rich --pager
The rich formatting applies markdown styling to the outline, making headings more visually distinct in the terminal.
Examples
Quick Document Overview:
# Check structure before processing
all2md large-document.pdf --outline
# Compare structures of two documents
all2md version1.docx --outline > v1-outline.txt
all2md version2.docx --outline > v2-outline.txt
diff v1-outline.txt v2-outline.txt
Depth Control:
# High-level overview (chapters only)
all2md book.pdf --outline --outline-max-level 1
# Two-level structure (chapters and sections)
all2md thesis.docx --outline --outline-max-level 2
# Full detailed structure
all2md technical-spec.pdf --outline --outline-max-level 6
Integration with Other Tools:
# Generate navigation structure for documentation site
all2md docs/*.md --outline --output-dir outlines/
# Extract outline and search for specific sections
all2md document.pdf --outline | grep -i "methodology"
# Create outline index for multiple documents
for file in *.pdf; do
echo "=== $file ===" >> outlines.txt
all2md "$file" --outline >> outlines.txt
echo "" >> outlines.txt
done
Restrictions
The
--outlineflag cannot be used together with--extract. Use--outlineto view document structure or--extractto extract specific sections.
# This will produce an error:
all2md document.pdf --outline --extract "Introduction"
# Instead, use them separately:
all2md document.pdf --outline # View structure
all2md document.pdf --extract "Introduction" # Extract section
Use Cases
Document Assessment:
Quickly understand the structure of unfamiliar documents before committing to full processing:
# Check if document has expected sections all2md contract.pdf --outline # Verify documentation structure all2md api-docs.docx --outline --outline-max-level 2
Navigation Aid:
Generate a roadmap for navigating large documents:
# Create quick reference for long manual all2md user-manual.pdf --outline --out manual-toc.md # Share document structure with team all2md specification.docx --outline --rich --out spec-outline.txt
Batch Analysis:
Analyze structure across multiple documents:
# Generate outlines for all PDFs in directory for pdf in reports/*.pdf; do all2md "$pdf" --outline --out "outlines/$(basename "$pdf" .pdf).txt" done # Compare document structures all2md doc1.pdf --outline > structure1.txt all2md doc2.pdf --outline > structure2.txt diff -u structure1.txt structure2.txt
Notes
The outline extraction works with any document format that all2md can parse
Heading levels are automatically detected from the document structure
The markdown list format uses 2-space indentation per heading level
Empty documents or documents without headings will show “No headings found in document”
The
--outline-max-levelparameter only applies when--outlineis used
See Also
--extract- Extract specific sections from documentsall2md view --toc- View document with visual table of contentsPython API Workflows - For programmatic outline extraction using
get_all_sections()
Extracting by Line Range
In addition to section names and indices, --extract accepts an output
line range with the line: prefix. Line numbers refer to the full
Markdown conversion – exactly the numbers reported by --outline --line-numbers
or by a --line-numbers conversion – so the typical workflow is inspect,
then pull:
# 1. See where everything is
all2md report.pdf --outline --line-numbers
# 2. Pull back an exact range (1-based, inclusive)
all2md report.pdf --extract line:42-87
# 3. Pull it back with its original line numbers, for further refinement
all2md report.pdf --extract line:42-87 --line-numbers
The range syntax mirrors index ranges: a single line (line:42), a closed
range (line:42-87), an open-ended range (line:42-), or several at once
(line:1-10,42-87). Non-adjacent selections are separated by a blank line.
Because the range is selected on the Markdown rendering, it can still be re-rendered to any target format – the selected lines are re-parsed before conversion:
all2md report.pdf --extract line:42-87 --out excerpt.html
Tables, Figures, and Multiple Extracts
--extract selects more than sections. Use a typed prefix to pull tables or
figures by their 1-based position in the document, and pass --extract more
than once to gather several pieces at a time:
# The second table in the document
all2md report.docx --extract table:2
# A range or all of them
all2md report.docx --extract table:1-3
all2md report.docx --extract table:*
# Figures/images (the two prefixes are aliases)
all2md paper.pdf --extract figure:1
all2md paper.pdf --extract image:*
# Several selectors at once -- emitted in the order given, separated by '---'
all2md paper.pdf --extract "Methods" --extract table:1 --extract figure:1
When --extract is repeated, results are concatenated in flag order (not
document order), so you control the sequence. A single line: range cannot be
combined with other selectors.
Capping length with ::N
Append ::N to any selector to cap its output at roughly N words. The cut
happens at node boundaries, so the returned content is always a valid document
(it never slices a paragraph or table in half):
# The Introduction, trimmed to about 500 words
all2md paper.pdf --extract "Introduction::500"
# Works with index and typed selectors too
all2md paper.pdf --extract "#:1::200"
Paging with --slice
--slice X/Y returns the Xth of Y semantic slices of a document to stdout
(or --out) without writing a pile of split files. The document is divided
into exactly Y balanced parts at section boundaries, and only slice X is
emitted, followed by a footer hint pointing at the next slice:
all2md long-report.pdf --slice 1/5
all2md long-report.pdf --slice 2/5 # ... up to 5/5
This is handy for feeding a large document to a tool with a context limit one
page at a time. --slice cannot be combined with
--extract/--outline/--split-by/--collate.
Line Windows: --head, --tail, --lines
For quick windows over the rendered output, three shorthand flags mirror the
familiar head/tail tools and the --extract line: range. All operate
on 1-based output lines and honor --line-numbers:
all2md document.pdf --head # first 10 lines (default)
all2md document.pdf --head 40 # first 40 lines
all2md document.pdf --tail 20 # last 20 lines
all2md document.pdf --lines 10:25 # lines 10-25 (inclusive)
all2md document.pdf --lines :25 # through line 25
all2md document.pdf --lines 40: # from line 40 to the end
These are mutually exclusive with each other and with
--extract/--outline/--split-by/--slice.
Document Serving
The all2md serve command provides an HTTP server for browsing documents locally with instant on-demand conversion. This is useful for exploring large document collections, sharing documents on a local network, or developing with live document preview.
all2md serve FILE_OR_DIRECTORY [OPTIONS]
Basic Usage
Serve a single document:
# Serve a PDF file
all2md serve document.pdf
# Serve a Markdown file
all2md serve README.md
Serve all documents in a directory:
# Serve all documents in current directory
all2md serve .
# Serve documents in docs folder
all2md serve ./docs
# Serve documents recursively (includes subdirectories)
all2md serve ./docs --recursive
The command will:
Scan the directory for supported document formats
Generate an index page with links to all documents (with
--recursive, each subdirectory gets its own index page with breadcrumb navigation)Start an HTTP server (default: http://127.0.0.1:8000/)
Convert documents on-demand when requested (lazy loading)
Cache converted HTML for faster subsequent requests
Arguments
Required Arguments:
FILE_OR_DIRECTORYPath to a file or directory to serve. When serving a directory, creates an index page with all supported documents. Supports all formats that all2md can convert.
Optional Arguments:
--port PORTPort to serve on. Default:
8000. If the requested port is unavailable (already in use, or access denied), the server automatically binds an OS-assigned random free port instead and prints the actual URL, rather than failing.# Serve on port 9000 all2md serve ./docs --port 9000
--host HOSTHost address to bind to. Default:
127.0.0.1(localhost only).# Allow access from local network all2md serve ./docs --host 0.0.0.0 # Localhost only (default) all2md serve ./docs --host 127.0.0.1
--browseOpen the served URL in your default web browser once the server has started. When bound to a wildcard host (e.g.
0.0.0.0), the browser is pointed at127.0.0.1.# Serve and open in the browser all2md serve ./docs --browse
-r,--recursiveRecursively serve subdirectories. When enabled, scans all nested folders for documents and generates a per-subdirectory index page for each folder. Each index lists immediate files and child directories, with breadcrumb navigation (e.g.,
Home > reports > 2026) for easy traversal of the directory tree.# Serve only immediate directory all2md serve ./docs # Serve all subdirectories recursively (with breadcrumb navigation) all2md serve ./docs --recursive
--tocInclude an automatically generated table of contents in converted documents.
# Serve with table of contents all2md serve ./docs --toc
--darkUse the dark mode theme. Quick shortcut for
--theme dark.# Serve with dark theme all2md serve ./docs --dark
--theme THEMESpecify a theme for HTML output.
THEMEmay be a built-in theme name, a custom.htmltemplate, a plain.cssfile, or a name registered in a[themes]configuration table (see Custom Themes).Built-in themes:
minimal(default) - Clean, centered layoutdark- Dark mode with VS Code colorsnewspaper- Classic newspaper styledocs- GitHub-style documentationsidebar- Two-column layout with TOC
# Use newspaper theme all2md serve ./articles --theme newspaper # Use custom theme all2md serve ./docs --theme /path/to/theme.html
--no-mermaidDisable client-side rendering of
mermaidcode blocks as diagrams (loaded from a CDN, on by default). See the note under theviewcommand’s options.--no-syntax-highlightDisable client-side syntax highlighting of code blocks and source files (highlight.js loaded from a CDN, on by default).
Note
The directory index lists only files all2md can convert. It offers an aligned table view (default) and a card view; the toggle is remembered per browser.
--enable-uploadEnable file upload form at
/uploadroute. This provides a web interface for uploading and converting documents. For development use only - do not expose to untrusted networks.# Enable upload form all2md serve ./docs --enable-upload
When enabled, a link to the upload page appears in the directory index.
--enable-apiEnable REST API endpoint at
/api/convert. Accepts document uploads and returns converted output in the requested format. For development use only - do not expose to untrusted networks.# Enable REST API all2md serve ./docs --enable-api # Enable both upload form and API all2md serve ./docs --enable-upload --enable-api
--max-upload-size SIZEMaximum upload file size in megabytes. Default:
50MB. Only applies when--enable-uploador--enable-apiis enabled.# Allow uploads up to 100MB all2md serve ./docs --enable-upload --max-upload-size 100 # Restrict to 10MB all2md serve . --enable-api --max-upload-size 10
--no-cacheDisable caching and always render fresh content on every request. Useful for live editing when you want to see changes without restarting the server.
# Serve with live reload (no caching) all2md serve document.md --no-cache # Serve directory with live updates all2md serve ./docs --no-cache --recursive
When to use:
Live editing: See document changes immediately without restarting
Development: Watch for file additions/removals in directories
Testing: Verify conversion behavior with frequently changing inputs
Performance note: Disabling cache means documents are re-converted on every request, which may be slower for large files or complex conversions.
--poll-interval SECONDSSeconds between background directory rescans. When serving a directory, a daemon thread periodically rescans for added, removed, or modified files; if the file set changes, the cached index page is invalidated so the next visit reflects the new contents. Default:
2.0. Set to0to disable polling (the index then only updates on server restart or when--no-cacheis in effect). No-op in single-file mode.# Faster pickup of new files (1s polling) all2md serve ./drafts --poll-interval 1 # Disable polling entirely (static directory) all2md serve ./archive --poll-interval 0
--force-auto-indexAlways render the auto-generated directory listing, even when an
index.html,index.md, orREADME.mdfile is present in the directory being served. See Index Files below for the default behavior.# Ignore the repo's README.md and show the file listing instead all2md serve . --recursive --force-auto-index
Index Files
When a request resolves to a directory, all2md serve first looks for an index file in that directory and, if one is present, renders it through the current theme instead of generating a file listing. Candidate names (case-insensitive, in priority order):
index.htmlindex.htmindex.mdREADME.md
This applies to every directory the server can reach — root and subdirectories alike — so you can drop a README.md into any folder to get a hand-authored landing page. Recurse-mode (--recursive) is fully supported: each subdirectory can have its own index file, and the auto-generated listing is used wherever no index file exists.
Pass --force-auto-index to opt out and always show the generated listing.
Examples
Basic Serving:
# Serve current directory on default port
all2md serve .
# Serve specific directory with dark theme
all2md serve ./documents --dark
# Serve on custom port
all2md serve ./docs --port 8080
Recursive Directory Serving:
# Serve entire documentation tree
all2md serve ./docs --recursive --toc
# Serve with sidebar theme
all2md serve ./manual --recursive --theme sidebar --toc
# Serve on local network with custom port
all2md serve ./shared-docs --recursive --host 0.0.0.0 --port 9000
Network Sharing:
# Share on local network (accessible to other devices)
all2md serve ./team-docs --host 0.0.0.0 --port 8000
# Then access from other devices at http://YOUR_IP:8000
Development Features:
# Enable upload form for testing conversions
all2md serve . --enable-upload
# Enable REST API for integration testing
all2md serve . --enable-api --max-upload-size 100
# Enable both with custom theme
all2md serve ./test-docs --enable-upload --enable-api --theme docs
# Development server with all features
all2md serve . --enable-upload --enable-api --recursive --toc --dark
Live Editing (No Cache):
# Edit and see changes immediately
all2md serve README.md --no-cache
# Watch directory for new files and changes
all2md serve ./docs --no-cache --recursive
# Live editing with dark theme and TOC
all2md serve ./documentation --no-cache --dark --toc
# Development workflow with live reload
all2md serve . --no-cache --theme docs --recursive
Performance
The serve command uses lazy loading for optimal performance:
Startup: Instant - only scans filenames and creates index
First request: Converts document on-demand
Subsequent requests: Served from in-memory cache (instant)
Concurrency: Requests are handled on per-connection threads, so a slow conversion doesn’t block other visitors
Memory: Efficient - only caches accessed documents
Live updates: A background poller (
--poll-interval, default 2.0s) rescans the directory; when files appear, disappear, or change, the cached index page is invalidated so the next visit picks up the new state without needing--no-cache
This makes it practical to serve directories with hundreds or thousands of documents.
With ``–no-cache`` flag:
Every request: Re-converts document from source
Directory index: Re-scans for new/removed files on each root request (background polling is skipped)
Memory: Minimal - no caching
Use case: Live editing of file contents (the regular cached mode already picks up added/removed files via polling)
The --no-cache mode trades performance for live updates, making it ideal for active development but slower for large files or frequent requests.
Use Cases
Local Documentation Server:
# Serve your project's documentation
all2md serve ./docs --recursive --theme docs --toc
Document Collection Browser:
# Browse a collection of PDFs, Word docs, etc.
all2md serve ~/Documents/reports --recursive
Team Document Sharing:
# Share documents on local network
all2md serve ./shared --host 0.0.0.0 --recursive
Development Preview:
# Live preview while editing documents (cached)
all2md serve . --dark
# Live editing with instant updates (no cache)
all2md serve . --no-cache --dark
Live Editing Workflow:
# Edit documentation and see changes immediately
all2md serve ./docs --no-cache --recursive --theme docs
# Watch for new files in directory
all2md serve ./drafts --no-cache
Development Features
The serve command includes optional file upload and REST API capabilities for development and testing. These features are disabled by default and should only be enabled in trusted environments.
Warning
The upload and API features are for development use only. Do not expose them to untrusted networks or use in production environments. When enabled, a security warning is displayed at server startup.
File Upload Form
Enable the web-based upload form at http://127.0.0.1:8000/upload:
# Enable upload form
all2md serve ./docs --enable-upload
# With custom upload size limit
all2md serve . --enable-upload --max-upload-size 100
The upload form provides:
Web interface matching the selected theme
Support for all input formats (PDF, DOCX, HTML, etc.)
Conversion to any supported output format (Markdown, HTML, PDF, etc.)
Immediate download of converted documents
File size validation before processing
REST API
Enable the REST API endpoint at http://127.0.0.1:8000/api/convert:
# Enable REST API
all2md serve . --enable-api
# Enable both features
all2md serve . --enable-upload --enable-api --max-upload-size 50
API Usage Examples:
Using curl with multipart/form-data:
# Convert PDF to Markdown
curl -X POST http://127.0.0.1:8000/api/convert \
-F "file=@document.pdf" \
-F "format=markdown" \
-o output.md
# Convert DOCX to HTML
curl -X POST http://127.0.0.1:8000/api/convert \
-F "file=@report.docx" \
-F "format=html" \
-o output.html
Using curl with JSON (base64):
# Prepare base64-encoded file
base64_content=$(base64 -w 0 document.pdf)
# Send request
curl -X POST http://127.0.0.1:8000/api/convert \
-H "Content-Type: application/json" \
-d "{\"file\": \"$base64_content\", \"format\": \"markdown\"}" \
-o output.md
Supported Output Formats:
The API supports conversion to: html, markdown, pdf, docx, epub, odt, rtf, latex, asciidoc, rst, org, mediawiki, dokuwiki, textile, json, yaml, toml, ini, csv, plaintext, and more.
Security Considerations:
Only enable in trusted development environments
Use
--host 127.0.0.1(default) to restrict to localhostSet appropriate
--max-upload-sizelimitsMonitor server output for suspicious activity
Never expose to public networks or production environments
Notes
Documents are converted on first access and cached in memory
The server runs until interrupted with Ctrl+C (shutdown is now prompt — no need to nudge it with another request)
Unsupported file types are automatically excluded from the index
Directory index shows file sizes and organizes by subdirectory
A directory containing an
index.html,index.md, orREADME.mdis rendered through the theme instead of an auto-generated listing (override with--force-auto-index)New, removed, or modified files in a served directory are picked up automatically by a background poller (configurable via
--poll-interval)All conversion errors are shown in the console and as HTTP 500 responses
Requests are handled on per-connection threads, suitable for local use and small teams
See Also
Python API Workflows - For programmatic HTTP server integration
all2md view- For single-file browser previewall2md --help- Built-in help
Document Editing
The all2md edit command launches a local web-based editor (Toast UI Editor with both a Markdown source view and a WYSIWYG view) pre-loaded with any supported document converted to Markdown. After editing, the result can be saved back to disk in any installed target format. When an existing file would be overwritten a .bak copy is created automatically.
all2md edit FILE [OPTIONS]
Basic Usage
# Edit a Markdown file in-place (default: overwrite original, .bak created on save)
all2md edit notes.md
# Edit a DOCX (default save target is notes.md next to the original; original is untouched)
all2md edit report.docx
# Open without auto-launching a browser tab
all2md edit report.docx --no-browser
The command will:
Detect the input format and convert it to Markdown for the editor’s initial value
Bind to
127.0.0.1on an OS-assigned ephemeral port (override with--port)Open the editor URL in your default browser (unless
--no-browseris set)Wait until you press Ctrl+C
Arguments
Required Argument:
FILEPath to the file to edit. Stdin (
-) is not accepted because saving back to stdin is meaningless.
Optional Arguments:
--port PORTPort to bind. Default:
0(OS-assigned ephemeral port). The chosen port is printed at startup.all2md edit report.docx --port 8765
--host HOSTHost address to bind to. Default:
127.0.0.1(localhost only).--no-browserDo not auto-open a browser tab. Useful for headless environments and tests.
--darkStart the editor in dark mode (dark page chrome and Toast UI’s dark theme). The 🌙/☀️ toggle in the editor header still switches modes at any time, and your choice is remembered in the browser’s
localStoragefor the next launch. Can also be set viadark = truein the[edit]config section.all2md edit notes.md --dark
--windowOpen the editor in a standalone native window (no address bar or browser chrome) instead of a browser tab. Requires the optional
pywebviewdependency (pip install all2md[window]); if it is not installed,all2mdprints a hint and falls back to a normal browser tab. Closing the window shuts the editor down. Can also be set viawindow = truein the[edit]config section.all2md edit notes.md --window
--default-format FMTPre-select a target format in the save dropdown. Must be a format whose renderer is installed (see
all2md list-formats --available-only). If unavailable, the default is used and a warning is printed.all2md edit notes.md --default-format html
--no-preserve-formattingWhen the source and target are both
.docx, the editor by default uses the original document as a rendering template — page setup, theme, headers/footers, and custom paragraph styles (“Chapter Title”, “Caption”, etc.) are inherited so the saved file looks like the document you started from. Pass this flag to disable that behavior and render a generic.docxinstead.all2md edit annual-report.docx --default-format docx --no-preserve-formatting
Save Behavior
The editor’s save controls (format dropdown, path field, overwrite checkbox) start with sensible defaults that depend on the original file’s format:
Markdown source (
.md): default target is the original path with overwrite enabled — saving creates a.baknext to the file before the new content lands.Any other source (
.docx,.pdf,.html,.eml…): default target is a sibling file with the same stem and the.mdextension, with overwrite disabled — you must tick the checkbox to overwrite an existing file.
The format dropdown is filtered at runtime: only target formats whose renderer is actually loadable (i.e. the relevant optional dependency is installed) are shown. markdown is always available and listed first.
When the format is changed in the dropdown, the path field’s extension is updated to match.
The save endpoint behaves as follows:
200— file written; response includes the resolved path and the backup path (if any).409— target file already exists and overwrite is unchecked. Either tick “Overwrite” or change the path.400— target format is not available, or the request payload is malformed.500— the underlying conversion (e.g. Markdown → DOCX) failed; the error message is shown inline.
Examples
Edit a markdown file with overwrite-and-backup workflow:
all2md edit README.md
# Default: save → README.md is overwritten, README.md.bak holds the previous version
Convert a DOCX to Markdown via interactive cleanup:
all2md edit annual-report.docx
# Default save target: annual-report.md (sibling, never touches the .docx)
Round-trip a DOCX through the editor with formatting preserved:
all2md edit annual-report.docx --default-format docx
# Save dropdown pre-selects docx; tick "Overwrite" to replace the original
# (a .bak is still created). The original document is used as a rendering
# template, so page setup, theme, headers/footers, and custom paragraph
# styles survive the round-trip.
Headless port-pinned use (e.g. Docker, remote dev):
all2md edit notes.md --no-browser --port 8765 --host 0.0.0.0
Editing Workflow
The Toast UI Editor offers two modes accessible via the toolbar tabs:
Markdown — split-pane source/preview. Best for technical documents, tables, math, and code blocks where you want exact control over the underlying syntax.
WYSIWYG — rich-text view with formatting toolbar. Best for prose, where you do not care about the underlying Markdown.
You can switch freely between the two; the editor maintains a single source of truth.
The status line beneath the save controls reports the result of the last save: the absolute path written, the backup path (if any), or the error message returned by the server.
Round-Trip Fidelity
Editing a non-Markdown source and saving it back to its original format is in general a lossy round-trip: the file is parsed → AST → Markdown → AST → original format. Constructs that the converter pipeline does not preserve (embedded objects, merged-cell tables, custom layouts, etc.) will be normalized away. For this reason:
Saving over a non-Markdown original is never the default — you must tick “Overwrite”.
A
.bakis always created when overwriting, regardless of source format.If you only need to read or annotate a binary document, prefer
all2md view(no save round-trip).
Markdown → Markdown editing is loss-free for the constructs Markdown can express, and is the recommended workflow.
DOCX round-trip preservation. When both source and target are .docx, the editor uses the original document as a rendering template by default: the AST replaces the body content, but the document inherits page setup, section properties, default fonts, theme, headers/footers, and the definitions of every named style. Paragraphs that originated from a custom style (“Chapter Title”, “Caption”, “Quote_Custom”, …) are tagged on the AST with the source style name and re-applied on output, so they keep that style instead of collapsing to “Heading 1” / “Normal”.
What still does not round-trip:
Run-level character styles (e.g. “Quote Char”, “Intense Reference”) — only paragraph-level styles are preserved today.
Direct/manual run formatting that wasn’t a named style (specific colors, highlights, custom fonts at the run level).
Content controls, fields, footnotes/endnotes if the AST drops them, drawings/SmartArt, and comments anchored to specific runs.
New content the user adds during editing receives the template’s default style — markdown’s structural model has no concept of the document’s custom inline character styles.
Pass --no-preserve-formatting to disable template inheritance and produce a generic .docx instead. Other binary targets (pptx, odt, odp) do not currently use template-based preservation.
Security Notes
The editor server is for development use on localhost. It is single-threaded and exposes a write-capable HTTP endpoint (
POST /api/save).The save endpoint accepts an arbitrary path and writes wherever your user has filesystem permission, so do not bind to
0.0.0.0on shared networks.The Toast UI Editor JavaScript and CSS are vendored under
src/all2md/cli/commands/themes/assets/(MIT licensed) and served from/assets/with an explicit allow-list — there is no general static-file route and no path traversal is possible.
See Also
all2md serve- Read-only browser preview of a directory of documentsall2md view- One-shot single-file browser previewPython API Workflows - For programmatic conversion (no editor)
Global Options
Output Control
--out,-oOutput file path. If not specified, output goes to stdout.
# Save to file all2md document.pdf --out converted.md all2md document.pdf -o converted.md
--formatForce a parser instead of using auto-detection (
autoremains the default). Accepted values line up withall2md list-formats(e.g.pdf,docx,markdown,asciidoc,pptx,zip,ast…). Alias:--input-type(useful when migrating Pandoc-flavoured scripts).# Force PDF processing for file without extension all2md mysterious_file --format pdf # Treat binary data as markdown for rendering cat draft.md | all2md - --format markdown
Attachment Handling
These top-level attachment flags apply to every parser that supports embedded assets (PDF, DOCX, HTML,
etc.). Formats without attachment handling simply ignore them, and format-prefixed switches such as
--pdf-attachment-mode override the global value when you need per-format exceptions.
--attachment-modeHow to handle images and attachments in documents.
Choices:
skip- Ignore all attachmentsalt_text- Replace with alt text or filename (default)save- Download attachments to local directorybase64- Embed attachments as base64 data URLs
Default:
alt_text# Download images to directory all2md document.pdf --attachment-mode save --attachment-output-dir ./images # Embed images as base64 all2md presentation.pptx --attachment-mode base64 # Skip all images all2md document.html --attachment-mode skip
--attachment-output-dirDirectory to save attachments when using
savemode.# Create images directory and save attachments all2md document.docx --attachment-mode save --attachment-output-dir ./doc_images
--attachment-base-urlBase URL for resolving relative attachment references.
# Resolve relative URLs in HTML documents all2md webpage.html --attachment-mode save --attachment-base-url https://example.com
Remote Input (HTTP/HTTPS)
--remote-input-enabledAllow all2md to fetch documents directly from HTTP(S) URLs. Disabled by default to prevent SSRF-style attacks.
# Convert a remote PDF after enabling remote input and restricting hosts all2md https://docs.example.com/guide.pdf \ --remote-input-enabled \ --remote-input-allowed-hosts docs.example.com
--remote-input-allowed-hostsComma-separated allowlist of hostnames or CIDR ranges permitted when remote input is enabled. If omitted, every host is allowed—explicitly listing trusted origins is strongly recommended.
--remote-input-allow-httpPermit plain HTTP downloads. HTTPS remains mandatory unless this flag is supplied.
--remote-input-timeoutNetwork timeout (seconds) for downloading remote inputs. Default:
10.--remote-input-max-size-bytesMaximum size (in bytes) for a remote document. Default:
20971520(20 MB). Requests exceeding the limit abort before parsing to protect memory budgets.--remote-input-user-agentCustom
User-Agentheader used for remote input requests. Defaults toall2md/<version>.
These options only affect the source document download. Per-format network controls (e.g. --html-network-*) still
apply to embedded resources fetched during conversion.
Markdown Formatting
--markdown-emphasis-symbolSymbol to use for emphasis and italic text.
Choices:
*(default),_# Use underscores for emphasis all2md document.pdf --markdown-emphasis-symbol "_"
--markdown-bullet-symbolsCharacters to cycle through for nested bullet lists.
Default:
*-+# Custom bullet symbols all2md document.docx --markdown-bullet-symbols "•◦▪"
--markdown-page-separator-templateTemplate text used to separate pages in multi-page documents. Use
{page_num}to include the page number.Default:
-----# Custom page separator template all2md document.pdf --markdown-page-separator-template "=== PAGE BREAK ===" # Include page numbers in separator all2md document.pdf --markdown-page-separator-template "--- Page {page_num} ---"
Rich Terminal Output
--richEnable Rich-rendered Markdown with colour, hyperlinks, and tables. Automatically disables itself when stdout is redirected, unless
--force-richis present.--force-richForce Rich formatting even when piping or redirecting output. Useful for capturing styled console logs.
--rich-code-theme/--rich-inline-code-themePick Pygments themes for fenced code blocks and inline code.
monokaiis the default. List available styles withpygmentize -L styles.--rich-word-wrapApply word-wrapping to long lines in the Rich renderer.
--rich-no-word-wrapDisable Rich’s automatic line wrapping when you need wide tables or preformatted output to stay on a single line.
--no-rich-hyperlinksDisable clickable hyperlinks (maps to
ALL2MD_RICH_HYPERLINKS=falsein env vars).--rich-justifyControl text justification for Rich Markdown (
left|center|right|full).
The related environment variables are ALL2MD_RICH, ALL2MD_FORCE_RICH, ALL2MD_RICH_CODE_THEME,
ALL2MD_RICH_INLINE_CODE_THEME, ALL2MD_RICH_WORD_WRAP, ALL2MD_RICH_HYPERLINKS (set to false to disable),
and ALL2MD_RICH_JUSTIFY.
Configuration and Debugging
--presetApply a preset configuration for common use cases. Presets provide pre-configured settings that can be overridden by CLI arguments.
See also
- Generate Default Configuration
To create a customizable configuration file based on a preset
--configPath to configuration file (JSON or TOML format). Command line options override config file settings.
Configuration files are automatically discovered in this order: 1. Explicit
--configflag 2.ALL2MD_CONFIGenvironment variable 3..all2md.tomlor.all2md.jsonin current directory 4..all2md.tomlor.all2md.jsonin home directoryNote
Passing List Values: For options that accept a list of values (e.g.,
--pdf-pages,--html-network-allowed-hosts), you can provide a comma-separated string. For more complex lists or to avoid shell escaping issues, using a configuration file is recommended.List-type options supporting comma-separated values:
html.network.allowed_hostseml.url_wrappersspreadsheet.sheetspdf.pages
Example:
# Pass a list of hosts via the CLI all2md webpage.html --html-network-allowed-hosts "cdn.example.com,images.example.org" # Pass multiple pages all2md document.pdf --pdf-pages "1,2,3,5"
Using configuration files for complex lists:
{ "html.network.allowed_hosts": ["cdn.example.com", "images.example.org"], "eml.url_wrappers": ["safelinks.protection.outlook.com", "urldefense.com"], "spreadsheet.sheets": ["Sheet1", "Summary", "Data"] }
Usage:
# Use config file for list values all2md webpage.html --config config.json --html-network-allow-remote-fetch # CLI flags can still override config settings all2md webpage.html --config config.toml --attachment-mode save
# Use options from config file all2md document.pdf --config config.toml # Config file settings with CLI overrides all2md document.pdf --config config.json --attachment-mode save # Auto-discovery (checks cwd, then home directory) all2md document.pdf # Uses .all2md.toml if present
Example TOML configuration (recommended):
# all2md configuration file attachment_mode = "save" attachment_output_dir = "./images" [pdf] detect_columns = true pages = [1, 2, 3] [markdown] emphasis_symbol = "_"
Example JSON configuration:
{ "attachment_mode": "save", "attachment_output_dir": "./images", "pdf.detect_columns": true, "pdf.pages": [1, 2, 3], "markdown.emphasis_symbol": "_" }
--no-configDisable all configuration file loading. When this flag is set, all2md ignores:
Auto-discovered configuration files (
.all2md.toml,.all2md.json, etc.)The
ALL2MD_CONFIGenvironment variableAny
--configflag that may be present
CLI arguments still work normally - only configuration files are skipped.
# Disable config file loading all2md document.pdf --no-config # --no-config ignores ALL2MD_CONFIG env var ALL2MD_CONFIG=/path/to/config.toml all2md document.pdf --no-config # --no-config takes precedence over --config all2md document.pdf --no-config --config some-config.toml
Use cases:
Ensure reproducible conversions without config file influence
Debug configuration issues by starting with defaults
Override project settings for one-off conversions
See also
- Configuration Files
Complete guide to configuration files and auto-discovery
--presetApply a preset configuration for common use cases. Presets provide pre-configured settings that can be overridden by CLI arguments.
Available Presets:
fast- Fast processing optimized for speed over qualityquality- High quality processing with maximum fidelityminimal- Text-only output with no attachments or imagescomplete- Complete preservation with all content and metadataarchival- Self-contained documents with embedded resources (base64)documentation- Optimized for technical documentation
Preset Comparison:
Setting
fast
quality
minimal
complete
archival
documentation
Attachment Mode
skip
save
skip
save
base64
save
PDF Column Detection
Disabled
Enabled
Default
Enabled
Enabled
Enabled
PDF Image Extraction
Skipped
Default
Skipped
Default
Default
Default
PDF Table Fallback
Disabled
Enabled
Default
Enabled
Default
Default
PDF Hyphen Merging
Disabled
Enabled
Default
Default
Enabled
Default
HTML Strip Dangerous
Enabled
Disabled
Enabled
Default
Default
Enabled
HTML Extract Title
Default
Enabled
Default
Enabled
Enabled
Enabled
HTML Remote Fetch
Default
Default
Default
Enabled
Default
Default
PPTX Include Notes
Disabled
Enabled
Default
Enabled
Default
Default
PPTX Slide Numbers
Default
Enabled
Default
Enabled
Default
Default
EPUB Merge Chapters
Default
Enabled
Default
Enabled
Enabled
Default
EPUB Include TOC
Default
Enabled
Default
Enabled
Enabled
Default
Jupyter Truncate
Default
Default
Default
Default
Default
50 lines
# Use fast preset for quick processing all2md document.pdf --preset fast # Use quality preset with overrides all2md document.pdf --preset quality --attachment-mode skip # Combine preset with config file all2md document.pdf --preset quality --config custom.toml
Detailed Preset Descriptions:
fast - Speed-optimized processing
Optimized for maximum conversion speed by skipping expensive operations:
attachment_mode: skip- No attachment processingpdf.skip_image_extraction: true- Skip PDF image extractionpdf.detect_columns: false- Disable column layout detectionpdf.enable_table_fallback_detection: false- Disable fallback table detectionhtml.strip_dangerous_elements: true- Basic securitypptx.include_notes: false- Skip speaker notes
Use when: You need quick text extraction from many documents and don’t need images or complex layout preservation.
quality - Maximum fidelity
Optimized for highest quality output with comprehensive content preservation:
attachment_mode: save- Save all attachments locallypdf.detect_columns: true- Detect multi-column layoutspdf.enable_table_fallback_detection: true- Advanced table detectionpdf.merge_hyphenated_words: true- Fix line-break hyphenationhtml.extract_title: true- Extract document titlespptx.include_notes: true- Include speaker notespptx.slide_numbers: true- Add slide numbersepub.merge_chapters: true- Create continuous documentepub.include_toc: true- Include table of contents
Use when: You need the highest quality output and have time for thorough processing.
minimal - Text-only extraction
Minimal processing focused on text content only:
attachment_mode: skip- No attachmentspdf.skip_image_extraction: true- Skip imageshtml.strip_dangerous_elements: true- Basic securitymarkdown.emphasis_symbol: *- Simple markdown
Use when: You only need plain text content without images, tables, or formatting.
complete - Full preservation
Complete content and metadata extraction:
attachment_mode: save- Download all attachmentspdf.detect_columns: true- Advanced layout detectionpdf.enable_table_fallback_detection: true- Comprehensive table detectionhtml.extract_title: true- Extract metadatahtml.network.allow_remote_fetch: true- Fetch remote resourceshtml.network.require_https: true- Secure fetching onlypptx.include_notes: true- Include all notespptx.slide_numbers: true- Number slidesepub.merge_chapters: true- Continuous documentepub.include_toc: true- Table of contentseml.include_headers: true- Email headerseml.preserve_thread_structure: true- Email threading
Use when: Creating an archive or need every piece of content and metadata preserved.
archival - Self-contained documents
Creates completely self-contained documents with no external dependencies:
attachment_mode: base64- Embed all resources inlinepdf.detect_columns: true- Preserve layoutpdf.merge_hyphenated_words: true- Clean texthtml.extract_title: true- Include metadataepub.merge_chapters: true- Single documentepub.include_toc: true- Navigation structure
Use when: Creating portable documents that must work without external files or network access.
documentation - Technical documentation
Optimized for technical documentation with readable code and clean formatting:
attachment_mode: save- External image filesmarkdown.emphasis_symbol: _- Underscore emphasis (common in tech docs)html.extract_title: true- Document structurehtml.strip_dangerous_elements: true- Clean HTMLipynb.truncate_long_outputs: 50- Limit output verbositypdf.detect_columns: true- Handle multi-column layouts
Use when: Converting technical documentation, API docs, or Jupyter notebooks for publication.
Working with Presets:
Presets can be combined with CLI arguments and configuration files. The priority order is:
CLI arguments (highest priority)
--presetflag--configfileAuto-discovered config files
Default values (lowest priority)
# Use quality preset with custom output directory all2md document.pdf --preset quality --attachment-output-dir ./my-images # Override preset's attachment mode all2md document.pdf --preset archival --attachment-mode save # Combine preset with config file all2md document.pdf --preset quality --config custom.toml # Fast preset for batch processing all2md *.pdf --preset fast --output-dir ./converted --parallel 8
Creating Custom Configurations Based on Presets:
You can create a configuration file inspired by a preset and customize it:
# Generate base config all2md config generate --out .all2md.toml # Edit to match a preset's settings and add customizations vim .all2md.toml # Use your custom config all2md document.pdf --config .all2md.toml
Example of customizing the
qualitypreset:# Based on 'quality' preset with customizations attachment_mode = "save" attachment_output_dir = "./document-assets" [pdf] detect_columns = true enable_table_fallback_detection = true merge_hyphenated_words = true pages = [1, 2, 3, 5] # Custom: only specific pages [html] extract_title = true [markdown] emphasis_symbol = "_" # Custom: prefer underscore flavor = "gfm" # Custom: GitHub-flavored markdown
Note
Use
all2md --helpto see preset descriptions in the command-line help. To create a configuration file with customizable settings, useall2md config generate(see Generate Default Configuration below).--log-levelSet logging level for debugging and detailed output.
Choices:
DEBUG,INFO,WARNING(default),ERRORTip
Validation warnings such as ignored
--outarguments or attachment directory mismatches are emitted through the logger. Make sure the selected log level includesWARNINGmessages when you want those hints on the console.# Enable debug logging all2md document.pdf --log-level DEBUG # Quiet mode (errors only) all2md document.pdf --log-level ERROR
--log-fileWrite log output to a file instead of (or in addition to) console output.
# Save logs to file all2md *.pdf --log-file conversion.log --output-dir ./converted # Combine with verbose logging all2md ./docs --recursive --log-file debug.log --log-level DEBUG --output-dir ./output # Useful for batch processing all2md ./archive --recursive --log-file archive_conversion.log --skip-errors --output-dir ./converted
Note
Log files capture all log messages regardless of console output settings. This is useful for post-processing analysis and debugging batch conversions.
--traceEnable trace mode with very verbose output including per-stage timing information. This is equivalent to
--log-level DEBUGwith additional timing instrumentation.# Trace mode for performance analysis all2md document.pdf --trace # Trace with log file for detailed analysis all2md complex_document.pdf --trace --log-file trace.log # Trace batch processing all2md *.pdf --trace --log-file batch_trace.log --output-dir ./converted
Trace Output Includes:
Detailed parsing timing for each stage
AST transformation timing
Rendering performance metrics
Timestamp-formatted log messages
Note
Trace mode is primarily useful for performance debugging and optimization. For normal operation, use
--log-level DEBUGor--verboseinstead.--strict-argsTreat unknown command-line arguments as fatal errors. By default the CLI logs a warning and continues; enabling
--strict-argsis useful in CI pipelines and scripts where typos must halt execution.# Fail fast if any flag is misspelled all2md report.pdf --strict-args --pdf-pages "1-3"
Configuration files may still contain extra keys; these produce validation warnings rather than aborting.
--aboutDisplay comprehensive system information including version, dependencies, and format availability.
# Show system information all2md --about
Output Includes:
all2md version and Python version
System platform and architecture
Installed dependencies with versions
Available format converters and their status
Missing optional dependencies
Note
Use
--aboutwhen reporting bugs or troubleshooting dependency issues. It provides a complete snapshot of your environment configuration.
Processing and Output Control
--richEnable rich terminal output with enhanced formatting and colors.
# Enhanced terminal output all2md document.pdf --rich
--pagerDisplay output using system pager for long documents (stdout only). Uses the system’s default pager (
lesson Unix,moreon Windows) or the pager specified inPAGERorMANPAGERenvironment variables.Note
Only applies to stdout output (not when using
--outor--output-dir)Paging is left to your environment; set
PAGER(orMANPAGER) to choose the pager.For ANSI-styled
--richoutput, use an ANSI-capable pager such asless -R. The Windows default (more) renders color codes as literal noise; when--pager --richis used on Windows without a configuredPAGER, all2md prints a one-line hint pointing you atless.lessships with Git for Windows and is also available viascoop install lessorwinget install jftuga.less.
# View long document with pager all2md long_document.pdf --pager # Combine with other options all2md report.pdf --pager --pdf-pages "1,2,3,4,5" # Enable color support in the pager (bash/zsh) export PAGER="less -R" all2md document.pdf --pager --rich # Same on Windows (PowerShell / cmd) set PAGER=less -R all2md document.pdf --pager --rich
--progressShow progress bar for file conversions (automatically enabled for multiple files).
# Force progress bar for single file all2md document.pdf --progress
--output-dirDirectory to save converted files (for multi-file processing).
# Convert multiple files to directory all2md *.pdf --output-dir ./markdown_output
--recursive,-rProcess directories recursively.
# Recursively convert all files in a directory tree all2md ./documents --recursive --output-dir ./converted
--parallel,-pProcess files in parallel (optionally specify number of workers).
# Process files in parallel (auto-detect CPU cores) all2md *.pdf --parallel # Use specific number of workers all2md *.pdf --parallel 4
Note
Performance Considerations:
Parallel processing provides significant speedups for certain formats:
CPU-bound formats (best for parallel processing):
PDF: Excellent parallelization - parsing is CPU-intensive (text extraction, table detection, image decoding)
DOCX/PPTX: Good parallelization - XML parsing and formatting logic benefits from multiple cores
Images (OCR): Excellent parallelization - OCR operations are very CPU-intensive
I/O-bound formats (less benefit from parallel processing):
HTML/Markdown: Minimal benefit - parsing is fast, most time spent on I/O
Plain text: No benefit - trivial processing time
Memory Considerations:
Each worker process imports dependencies independently (startup overhead per worker)
Large PDFs with many images can use significant memory per worker
Recommendation: For large PDFs, use
--pdf-skip-image-extractionwith parallel mode if you only need textMonitor memory usage when processing large files in parallel (e.g.,
htopon Linux)
Optimal Worker Count:
Auto-detect (
--parallelwithout number): Uses CPU core count - good default for most casesCPU-bound workloads: Use core count or
core count - 1to leave headroom for OSMixed I/O/CPU: Start with 2-4 workers, increase if CPU utilization is low
Large PDFs with images: Reduce workers (e.g., 2-4) to avoid memory pressure
Network-heavy workloads: Can use more workers than CPU cores (e.g.,
core count * 2)
Example Configurations:
# Large PDFs, text-only, maximize throughput all2md *.pdf --parallel --pdf-skip-image-extraction --output-dir ./out # Medium PDFs with images, conservative memory usage all2md *.pdf --parallel 4 --output-dir ./out # Many small files, I/O bound all2md *.html --parallel 2 --output-dir ./out
--skip-errorsContinue processing remaining files if one fails.
# Don't stop on errors all2md *.pdf --skip-errors --output-dir ./converted
--preserve-structurePreserve directory structure in output directory.
# Maintain folder hierarchy all2md ./docs --recursive --preserve-structure --output-dir ./markdown
--collateCombine multiple files into a single output (stdout or file).
# Combine all chapters into one file all2md chapter_*.pdf --collate --out book.md # Collate to stdout all2md *.md --collate
--split-bySplit a large document into multiple output files based on various strategies. This is the inverse operation of
--collate.Requires either
--outor--output-dirto specify the output location for split files.Cannot be used with:
--collate,--extract, or--outlineStrategies:
Heading Level (
h1,h2,h3,h4,h5,h6) - Split at every heading of the specified levelWord Count (
length=N) - Split by approximate word count, maintaining section boundariesThematic Breaks (
break) - Split at horizontal rules (---,***,___)Delimiter (
delimiter=TEXT) - Split at custom text markers (e.g.,\n***\n,<!-- split -->)Equal Parts (
parts=N) - Split document into N roughly equal partsPage/Chapter (
page,chapter) - Reserved for PDF pages or EPUB chapters (currently falls back to h1)Auto-detect (
auto) - Automatically determine the best split strategy based on document structure
# Split by H1 headings all2md book.pdf --split-by h1 --out book.md # Split by H2 headings (more granular) all2md report.docx --split-by h2 --out report.md # Split by word count (~500 words per file) all2md long_document.md --split-by length=500 --out doc.md # Split at horizontal rules (simple and convenient) all2md article.md --split-by break --out article.md # Split at custom delimiters with escape sequences all2md notes.txt --split-by delimiter="\n***\n" --out notes.md # Split into 5 equal parts all2md thesis.pdf --split-by parts=5 --out thesis.md # Auto-detect best split strategy all2md manual.html --split-by auto --out manual.md
Output files are named with numeric suffixes:
book_001.md,book_002.md, etc.Note
About delimiter strategies:
Use
breakfor the simple case of splitting at horizontal rules (---,***,___). This works automatically with Markdown thematic breaks.Use
delimiter=TEXTfor custom text markers like<!-- split -->or when you need escape sequences like\n***\n.Splitting respects semantic boundaries and will never split in the middle of a section.
For word count splitting, sections are combined until the target word count is reached.
--split-by-namingControl file naming for split documents. Used with
--split-by.Options:
numeric(default) - Use numeric suffixes only:output_001.md,output_002.mdtitle- Include heading text in filenames:output_001_introduction.md,output_002_methods.md
# Use title-based naming all2md document.pdf --split-by h1 --split-by-naming title --out doc.md # Output: doc_001_introduction.md, doc_002_methods.md, etc.
--split-by-digitsNumber of digits to use for split file numbering (default: 3).
# Use 2-digit numbering (01, 02, ...) all2md book.pdf --split-by h1 --split-by-digits 2 --out book.md # Use 4-digit numbering (0001, 0002, ...) all2md large_book.pdf --split-by h1 --split-by-digits 4 --out book.md
--no-summaryDisable summary output after processing multiple files.
# Quiet multi-file processing all2md *.pdf --output-dir ./converted --no-summary
--save-configSave current CLI arguments to a configuration file.
# Save current settings to JSON all2md document.pdf --attachment-mode save --save-config my-config.json # Save and reuse all2md document.pdf --preset quality --save-config quality-config.json all2md other-doc.pdf --config quality-config.json
--dry-runShow what would be converted without actually processing files.
# Preview what would be processed all2md ./documents --recursive --dry-run
--excludeExclude files matching this glob pattern (can be specified multiple times).
# Exclude temporary and backup files all2md ./docs --recursive --exclude "*.tmp" --exclude "*.bak" # Exclude multiple patterns all2md ./source --recursive --exclude "__pycache__" --exclude "*.pyc"
Format-Specific Options
PDF Options
--pdf-pagesSpecific pages to convert (1-based indexing). Supports lists and ranges: “1,2,3”, “1-3,5”, “10-“.
# Convert first 3 pages all2md document.pdf --pdf-pages "1,2,3" # Convert pages 1, 5, and 10 all2md document.pdf --pdf-pages "1,5,10" # Convert page range 1-3 and page 5 all2md document.pdf --pdf-pages "1-3,5" # Convert from page 10 to end all2md document.pdf --pdf-pages "10-"
--pdf-passwordPassword for encrypted PDF documents.
# Provide password for encrypted PDF all2md encrypted.pdf --pdf-password "secret123"
--pdf-no-detect-columnsDisable multi-column layout detection.
Default: Column detection is enabled
# Disable column detection all2md document.pdf --pdf-no-detect-columns
--pdf-header-percentile-thresholdPercentile threshold for header detection (e.g., 75 = top 25% of font sizes).
Default: 75
# Use stricter header detection (top 10% of font sizes) all2md document.pdf --pdf-header-percentile-threshold 90
--pdf-no-enable-table-fallback-detectionDisable heuristic fallback when PyMuPDF table detection fails.
Default: Fallback detection is enabled
# Disable table fallback detection all2md document.pdf --pdf-no-enable-table-fallback-detection
--pdf-no-merge-hyphenated-wordsDisable merging of words split by hyphens at line breaks.
Default: Hyphenated word merging is enabled
# Keep hyphenated line breaks as-is all2md document.pdf --pdf-no-merge-hyphenated-words
HTML Options
--html-extract-titleExtract and use HTML
<title>element as main heading.# Use page title as main heading all2md webpage.html --html-extract-title
--html-strip-dangerous-elementsRemove potentially dangerous HTML elements (script, style, etc.).
# Clean up HTML by removing scripts and styles all2md webpage.html --html-strip-dangerous-elements
Network Security Options
--html-network-allow-remote-fetchAllow fetching remote URLs for images and resources (base64/save modes).
Default: Disabled (prevents SSRF attacks)
# Enable remote fetching with security controls all2md webpage.html --html-network-allow-remote-fetch --html-network-require-https --html-network-network-timeout 5
--html-network-allowed-hostsComma-separated list of allowed hostnames for remote fetching.
Note
For specifying multiple hosts in a list, you can use a comma-separated value as shown below for a single invocation. For more complex list specifications, use a configuration file with the
--configflag.# Only allow specific hosts (single host) all2md webpage.html --html-network-allow-remote-fetch --html-network-allowed-hosts "example.com" # Multiple hosts via config file (recommended for multiple values) # In config.json: {"html.network.allowed_hosts": ["example.com", "cdn.example.com"]} all2md webpage.html --html-network-allow-remote-fetch --config config.json
--html-network-require-httpsRequire HTTPS for all remote URL fetching.
Default: Disabled
# Force HTTPS for security all2md webpage.html --html-network-allow-remote-fetch --html-network-require-https
--html-network-network-timeoutTimeout in seconds for remote URL fetching.
Default: 10.0
# Set 5-second timeout all2md webpage.html --html-network-allow-remote-fetch --html-network-network-timeout 5
--html-network-max-remote-asset-bytesMaximum allowed size in bytes for downloaded remote assets.
Default: 20971520 (20MB)
# Limit remote assets to 2MB all2md webpage.html --html-network-allow-remote-fetch --html-network-max-remote-asset-bytes 2097152
Global Network Control
For maximum security, use the ALL2MD_DISABLE_NETWORK environment variable to globally block all network operations:
# Disable all network operations globally
export ALL2MD_DISABLE_NETWORK=1
all2md webpage.html # Will skip all remote resources regardless of options
Security Examples
# Secure web scraping with allowlist
all2md webpage.html \
--html-network-allow-remote-fetch \
--html-network-allowed-hosts "trusted-site.com" \
--html-network-require-https \
--html-network-network-timeout 5 \
--html-network-max-remote-asset-bytes 1048576 \
--attachment-mode save \
--attachment-output-dir ./secure_images
# Maximum security (no network access)
ALL2MD_DISABLE_NETWORK=1 all2md webpage.html --attachment-mode skip
Security Preset Options
For common security scenarios, all2md provides convenient preset flags that configure multiple security settings at once. These presets are especially useful when processing untrusted HTML or web content.
--strict-html-sanitizeStrict security preset: strips dangerous HTML elements and disables all remote and local file fetching.
- Applies the following settings:
strip_dangerous_elements=True- Removes script, style, and other potentially dangerous tagsallow_remote_fetch=False- Blocks all remote URL fetchingallow_local_files=False- Blocks local file accessallow_cwd_files=False- Blocks current directory file access
# Maximum HTML sanitization all2md untrusted.html --strict-html-sanitize
--safe-modeBalanced security preset: sanitizes HTML and allows remote fetch with HTTPS requirement, but blocks local file access.
- Applies the following settings:
strip_dangerous_elements=True- Removes dangerous HTML elementsallow_remote_fetch=True- Allows remote fetching with restrictionsrequire_https=True- Enforces HTTPS for all remote URLsallow_local_files=False- Blocks local file accessallow_cwd_files=False- Blocks current directory file access
# Balanced security for web content all2md webpage.html --safe-mode --attachment-mode save
--paranoid-modeMaximum security preset: sanitizes HTML, blocks all remote and local file access, and caps asset size.
- Applies the following settings:
strip_dangerous_elements=True- Removes dangerous HTML elementsallow_remote_fetch=False- Blocks ALL remote URL fetchingallow_local_files=False- Blocks local file accessallow_cwd_files=False- Blocks current directory file accessmax_asset_size_bytes=5242880- Caps each asset at 5MB (default 50MB)
Note
Paranoid mode disables remote fetching entirely (
allow_remote_fetch=False), so a host allowlist has no effect. If you need to fetch from specific trusted hosts, use--safe-modetogether with--html-network-allowed-hostsinstead.Host Allowlist Semantics (for
--safe-mode/ manual configuration):allowed_hosts=[](empty list) - Blocks ALL remote hostsallowed_hosts=None(not set) - Allows all hosts subject to other constraints (HTTPS requirement, size limits, etc.)allowed_hosts=["example.com"](specific hosts) - Only allows listed hosts
# Maximum security for untrusted sources all2md suspicious.html --paranoid-mode
Understanding Security Presets:
Security presets provide quick, pre-configured security settings for common scenarios. They’re especially valuable when processing untrusted HTML or web content where you need protection against:
Server-Side Request Forgery (SSRF) - Preventing malicious HTML from accessing internal network resources
Local File Disclosure - Blocking access to sensitive local files
Resource Exhaustion - Limiting download sizes to prevent DoS attacks
Script Injection - Removing dangerous HTML elements
Preset Comparison:
Setting |
strict-html-sanitize |
safe-mode |
paranoid-mode |
|---|---|---|---|
Strip dangerous elements |
✓ Yes |
✓ Yes |
✓ Yes |
Remote fetch |
✗ Blocked |
✓ HTTPS only |
✓ HTTPS only |
Local file access |
✗ Blocked |
✗ Blocked |
✗ Blocked |
Max download size |
N/A |
20MB (default) |
5MB (reduced) |
Host validation |
N/A |
Optional |
✓ Enforced |
When to Use Each Preset:
–strict-html-sanitize: Maximum security for completely untrusted HTML. Blocks all network and file access.
Use cases: User-submitted HTML, scraped content from unknown sources, any HTML that shouldn’t access external resources.
–safe-mode: Balanced security for web content that needs images. Allows HTTPS-only remote fetching.
Use cases: Converting web pages with images, processing HTML emails, documentation with external resources.
–paranoid-mode: Maximum security with some remote access. Like safe-mode but with stricter size limits and host validation.
Use cases: High-security environments, processing potentially malicious content, compliance-sensitive operations.
Overriding Preset Values:
Individual security flags specified after a preset will override the preset’s defaults. This allows you to start with a secure baseline and selectively relax restrictions:
# Start with strict sanitization, then allow specific trusted hosts
all2md webpage.html --safe-mode --html-network-allowed-hosts "cdn.example.com"
# Use paranoid mode but increase size limit for legitimate large images
all2md webpage.html --paranoid-mode --html-network-max-remote-asset-bytes 10485760 # 10MB
# Combine safe-mode with attachment downloads
all2md webpage.html --safe-mode --attachment-mode save --attachment-output-dir ./images
Important: CLI flags are processed left-to-right, so presets should come first:
# ✓ Correct: Preset first, then overrides
all2md page.html --safe-mode --html-network-max-remote-asset-bytes 5242880
# ✗ Wrong: Override will be reset by preset
all2md page.html --html-network-max-remote-asset-bytes 5242880 --safe-mode
Progressive Security Examples:
# From least to most secure processing of the same HTML file
# 1. No security (default - use only for trusted local HTML)
all2md trusted.html --attachment-mode save
# 2. Basic sanitization (remove scripts/styles)
all2md webpage.html --html-strip-dangerous-elements --attachment-mode save
# 3. Safe mode (HTTPS-only external resources)
all2md webpage.html --safe-mode --attachment-mode save
# 4. Paranoid mode (strict size limits and validation)
all2md webpage.html --paranoid-mode --attachment-mode save
# 5. Maximum security (no external access at all)
all2md untrusted.html --strict-html-sanitize --attachment-mode skip
Note on Network Access:
For absolute maximum security across all operations (not just HTML), use the ALL2MD_DISABLE_NETWORK environment variable which globally disables all network operations:
# Global network disable - overrides ALL other settings
export ALL2MD_DISABLE_NETWORK=1
all2md webpage.html # No network access regardless of flags
PowerPoint Options
--pptx-slide-numbersInclude slide numbers in output.
# Add slide numbers all2md presentation.pptx --pptx-slide-numbers
--pptx-no-include-notesExclude speaker notes from conversion.
Default: Notes are included
# Skip speaker notes all2md presentation.pptx --pptx-no-include-notes
Email Options
--eml-no-include-headersExclude email headers from output.
Default: Headers are included
# Skip email headers all2md message.eml --eml-no-include-headers
--eml-no-preserve-thread-structureDon’t maintain email thread/reply chain structure.
Default: Thread structure is preserved
# Flatten email thread structure all2md thread.eml --eml-no-preserve-thread-structure
OpenDocument Text (ODT) Options
--odt-no-preserve-tablesDisable table preservation when parsing ODT documents.
Default: Tables are preserved.
# Convert ODT tables to simple paragraphs all2md document.odt --odt-no-preserve-tables
Jupyter Notebook Options
--ipynb-truncate-long-outputsTruncate cell outputs longer than specified number of lines.
# Limit output to 20 lines all2md notebook.ipynb --ipynb-truncate-long-outputs 20 # No truncation (default) all2md notebook.ipynb
--ipynb-truncate-output-messageMessage to display when truncating long outputs.
Default:
\n... (output truncated) ...\n# Custom truncation message all2md notebook.ipynb --ipynb-truncate-long-outputs 10 --ipynb-truncate-output-message "*** OUTPUT CUT ***"
EPUB Options
--epub-no-merge-chaptersDon’t merge chapters into continuous document (add separators between chapters).
Default: Chapters are merged
# Keep chapters separate all2md book.epub --epub-no-merge-chapters
--epub-no-include-tocDon’t include a Table of Contents in the output.
Default: TOC is included
# Skip table of contents all2md book.epub --epub-no-include-toc
Batch Processing
Multi-File Processing
all2md supports processing multiple files with parallel execution and rich output formatting.
--output-dirDirectory to save converted files when processing multiple inputs.
# Convert all PDFs in current directory all2md *.pdf --output-dir ./converted # Convert with directory structure preservation all2md ./documents --recursive --output-dir ./markdown --preserve-structure
--output-extensionOverride the written file extension when saving to
--output-diror when using--watch. Useful for publishing Markdown previews with.txtsuffixes or forcing HTML to use legacy extensions.# Render Markdown but store files as .txt all2md *.md --output-dir ./preview --output-extension .txt
--recursive,-rProcess directories recursively.
# Convert all supported files in directory tree all2md ./documents --recursive --output-dir ./converted # Process specific formats recursively all2md ./documents --recursive --format pdf --output-dir ./pdfs
--parallel,-pProcess files in parallel with optional worker count.
# Use default number of workers (CPU count) all2md *.pdf --parallel --output-dir ./converted # Specify 4 parallel workers all2md *.pdf --parallel 4 --output-dir ./converted
--skip-errorsContinue processing remaining files if one fails.
# Don't stop on errors all2md *.pdf --skip-errors --output-dir ./converted
--preserve-structureMaintain directory structure in output directory.
# Keep original directory hierarchy all2md ./docs --recursive --preserve-structure --output-dir ./markdown
--collateCombine multiple files into a single output.
# Combine all PDFs into one markdown file all2md *.pdf --collate --out combined.md # Combine to stdout all2md *.pdf --collate > all_documents.md
Format-Specific Options in Batch Mode
When processing multiple formats in a single batch, you can use format-specific flags to override global settings. This is particularly useful when different formats require different attachment handling strategies.
Global + Format-Specific Overrides:
# Skip attachments by default, but download from PDFs
all2md *.* --attachment-mode skip \
--pdf-attachment-mode save \
--pdf-attachment-output-dir ./pdf_images \
--output-dir ./converted
# Use alt-text globally, but embed base64 for presentations
all2md docs/* reports/*.pdf slides/*.pptx \
--attachment-mode alt_text \
--pptx-attachment-mode base64 \
--output-dir ./output
# Different attachment directories per format
all2md mixed_content/* \
--attachment-mode save \
--pdf-attachment-output-dir ./assets/pdf \
--docx-attachment-output-dir ./assets/word \
--html-attachment-output-dir ./assets/web \
--output-dir ./converted
How It Works:
Global flags (
--attachment-mode,--attachment-output-dir, etc.) apply to every format that supports attachments; text-only converters ignore themFormat-specific flags (
--pdf-attachment-mode,--docx-attachment-mode, etc.) override global settings for that formatFormat-specific flags always take precedence over global flags
Use Cases:
Security policies - Strict defaults with exceptions for trusted formats
Performance optimization - Fast modes for text formats, thorough modes for complex documents
Mixed format directories - Different strategies per format type
Selective processing - Skip attachments except where needed
For a complete list of format-specific flags, see Attachment Handling or run all2md help <format>.
Batch from List
Process each entry from a plain text list file as a standalone conversion. Unlike --merge-from-list, every item is
rendered separately using the normal multi-file pipeline so per-file outputs, summaries, and progress reporting stay
intact.
--batch-from-listRead file paths (one per line) from a list file or
-(stdin). Lines beginning with#and blank lines are ignored, and relative paths are resolved relative to the list file itself (or the current directory when streaming via stdin). Paths must exist; nonexistent entries trigger a validation error before processing begins.# docs_to_convert.txt ./reports/q1.docx ./reports/q2.docx # Relative paths resolve from the list location ../shared/summary.pdf
# Convert every listed file into the output directory all2md --batch-from-list docs_to_convert.txt --output-dir ./converted # Feed a dynamically generated list from stdin find ./incoming -name '*.pptx' -print | all2md --batch-from-list - --output-dir ./slides
--batch-from-listcannot be combined with--merge-from-list. When you provide an explicit list file, stdin inputs (-) are ignored; use--batch-from-list -if you need to stream the list over stdin.
Merge from List
Create structured multi-document outputs by merging files listed in a TSV file. This feature is ideal for building complex documents like books, manuals, or reports from individual section files.
--merge-from-listMerge files from a TSV list file with optional section titles.
List File Format:
The list file uses a simple tab-separated format:
# Comments start with # path/to/file1.md path/to/file2.pdf<TAB>Section Title path/to/file3.docx<TAB>Another Section
Lines starting with
#are comments and ignoredBlank lines are ignored
File paths are resolved relative to the list file directory
Optional section titles follow a tab character
Files can be any supported format (PDF, DOCX, Markdown, etc.)
# Basic merge from list all2md --merge-from-list chapters.txt --out book.md # Merge to stdout all2md --merge-from-list sections.txt
--generate-tocGenerate a table of contents when using
--merge-from-list.# Add table of contents to merged document all2md --merge-from-list chapters.txt --generate-toc --out book.md
--toc-titleSet the title for the generated table of contents.
Default:
Table of Contents# Custom TOC title all2md --merge-from-list chapters.txt --generate-toc --toc-title "Contents" --out book.md
--toc-depthMaximum heading level to include in the table of contents (1-6).
Default: 3
# Include only level 1 and 2 headings in TOC all2md --merge-from-list chapters.txt --generate-toc --toc-depth 2 --out book.md
--toc-positionPosition of the table of contents in the output.
Choices:
top(default),bottom# Place TOC at the end of document all2md --merge-from-list chapters.txt --generate-toc --toc-position bottom --out book.md
--list-separatorSeparator character for the list file.
Default: Tab character (
\t)# Use comma separator instead of tab all2md --merge-from-list chapters.csv --list-separator "," --out book.md
--no-section-titlesDisable automatic section title headers when merging.
# Merge without adding section headers all2md --merge-from-list chapters.txt --no-section-titles --out book.md
Complete Example:
Create a list file book_chapters.txt:
# Book Structure
frontmatter/preface.md Preface
chapters/introduction.pdf Chapter 1: Introduction
chapters/methodology.docx Chapter 2: Methodology
chapters/results.pdf Chapter 3: Results
chapters/conclusion.md Chapter 4: Conclusion
# Appendices
appendix/references.md References
Merge with table of contents:
# Create complete book with TOC
all2md --merge-from-list book_chapters.txt \
--generate-toc \
--toc-title "Book Contents" \
--toc-depth 2 \
--out complete_book.md
Use Cases:
Multi-chapter books: Combine individual chapter files with automatic TOC generation
Technical documentation: Merge API docs, guides, and tutorials into a single document
Reports: Assemble executive summaries, analyses, and appendices
Project documentation: Combine README, architecture, and design docs
Course materials: Merge lecture notes, assignments, and resources
Integration with Transforms:
The merge-from-list feature works seamlessly with the transform system. Use --transform to apply custom AST transformations to the merged document:
# Merge and apply custom transforms
all2md --merge-from-list chapters.txt \
--generate-toc \
--transform "HeadingOffsetTransform offset=1" \
--out book.md
--excludeExclude files matching glob pattern (can be used multiple times).
# Exclude test files all2md ./docs --recursive --exclude "*test*" --output-dir ./converted # Multiple exclusions all2md ./docs --recursive --exclude "*.draft.*" --exclude "temp/*" --output-dir ./converted
Rich Output Features
--richEnable rich terminal output with formatting and colors.
# Pretty formatted output all2md *.pdf --rich --output-dir ./converted
--progressShow progress bar for file conversions.
# Show progress bar all2md *.pdf --progress --output-dir ./converted # Progress is auto-enabled for multiple files with --rich all2md *.pdf --rich --output-dir ./converted
--no-summaryDisable summary output after processing multiple files.
# No summary statistics all2md *.pdf --no-summary --output-dir ./converted
Advanced Features
--save-configSave current CLI arguments to a JSON configuration file.
# Save settings for reuse all2md document.pdf --attachment-mode base64 --save-config my_settings.json # Use saved settings all2md other_document.pdf --config my_settings.json
--dry-runPreview what would be converted without actually processing files.
# See what files would be processed all2md ./documents --recursive --dry-run # Test exclusion patterns all2md ./docs --recursive --exclude "*.draft.*" --dry-run
Output Packaging
--zipCreate a ZIP archive of the conversion output. Can be used with or without a custom path.
# Create ZIP archive with automatic naming all2md *.pdf --output-dir ./converted --zip # Create ZIP with custom path all2md *.pdf --output-dir ./converted --zip ./archive.zip # Combine with asset organization all2md *.docx --output-dir ./output --zip --assets-layout flat
Note
The ZIP archive includes all converted markdown files and their associated assets. When used without a path argument, the ZIP file is named after the output directory (e.g.,
converted.zip).--assets-layoutOrganize asset files (images, attachments) using different layout strategies.
Choices:
flat- All assets in a singleassets/directory (default)by-stem- Assets organized by document name:assets/{document}/structured- Preserves original directory structure
Default:
flat# Flat layout - all assets in assets/ all2md *.pdf --output-dir ./output --assets-layout flat # By-stem layout - assets/{doc_name}/ all2md report1.pdf report2.pdf --output-dir ./output --assets-layout by-stem # Structured layout - preserves directory structure all2md ./docs --recursive --output-dir ./output --assets-layout structured
Note
Asset organization automatically updates markdown links to point to the new locations. This is particularly useful when creating shareable documentation bundles.
Watch Mode
--watchMonitor files or directories for changes and automatically reconvert when changes are detected. Requires the
watchdoglibrary (install withpip install all2md[cli_extras]).# Watch a single file all2md document.txt --watch --output-dir ./output # Watch a directory all2md ./docs --watch --recursive --output-dir ./output # Watch with custom debounce all2md ./docs --watch --watch-debounce 2.0 --output-dir ./output # Watch with file exclusions all2md ./docs --watch --recursive --exclude "*.tmp" --exclude "draft_*" --output-dir ./output
Note
Watch mode runs continuously until interrupted with
Ctrl+CChanges are debounced to prevent duplicate processing of rapid changes
The
--output-dirflag is required for watch modeFiles matching
--excludepatterns are ignored
--watch-debounceSet the debounce delay in seconds for watch mode (prevents duplicate processing of rapid changes).
Default:
1.0# Short debounce for fast iteration all2md ./src --watch --watch-debounce 0.5 --output-dir ./docs # Longer debounce for slower systems all2md ./content --watch --watch-debounce 2.0 --output-dir ./output
Use Cases:
Documentation Development: Automatically regenerate docs as source files change
Content Authoring: Live preview of markdown output while editing
Integration Testing: Auto-convert test fixtures during development
Dependency Management
all2md provides built-in dependency management commands to check and install format-specific dependencies.
Check Dependencies
Check which dependencies are available for a specific format:
# Check all dependencies
all2md check-deps
# Check PDF dependencies
all2md check-deps pdf
# Check Word document dependencies
all2md check-deps docx
# Check all spreadsheet dependencies
all2md check-deps spreadsheet
# Show help for check command
all2md check-deps --help
Install Missing Dependencies
To install missing dependencies, use pip with the appropriate extra:
# Install PDF dependencies
pip install all2md[pdf]
# Install PowerPoint dependencies
pip install all2md[pptx]
# Install all optional dependencies
pip install all2md[all]
- Available dependency groups:
[pdf]- PyMuPDF for PDF processing[docx]- python-docx for Word documents[pptx]- python-pptx for PowerPoint[html]- BeautifulSoup4, httpx, and readability-lxml for HTML parsing and article extraction[epub]- ebooklib for EPUB e-books[rtf]- pyth3 for Rich Text Format[odf]- odfpy for OpenDocument formats[xlsx]- openpyxl for Excel files[all]- All optional dependencies
See Installation Guide for more details.
Format Detection and Planning
List Supported Formats
The list-formats command displays all supported file formats, their extensions, required dependencies, and availability status in your environment.
Basic Usage:
# List all supported formats with availability status
all2md list-formats
Example output:
Format Extensions Dependencies Status
─────────────────────────────────────────────────────────────
pdf .pdf PyMuPDF ✓ Available
docx .docx python-docx ✓ Available
html .html, .htm BeautifulSoup4, readability-lxml ✓ Available
pptx .pptx python-pptx ✗ Missing
...
Show Format Details:
# Get detailed information about a specific format
all2md list-formats pdf
Example output:
Format: pdf
Extensions: .pdf
MIME types: application/pdf
Dependencies:
- PyMuPDF (fitz) - ✓ Installed (version 1.23.8)
Features:
- Table detection and extraction
- Multi-column layout handling
- Image extraction
- Page-specific processing
- Encrypted PDF support
Filter by Availability:
# Show only formats with installed dependencies
all2md list-formats --available-only
Rich Output:
# Enhanced formatting with colors and styling (requires rich library)
all2md list-formats --rich
This command is especially useful for:
Diagnosing format support issues - Verify that required dependencies are installed
Planning installations - See what formats are available before processing files
CI/CD pipelines - Check environment setup programmatically
Documentation - Generate up-to-date format support lists
Detect File Format Without Converting
The --detect-only flag analyzes files to determine their format without performing conversion. This is useful for validating format detection, checking file types in batch operations, or verifying dependencies before processing.
Basic Usage:
# Detect format for a single file
all2md document.pdf --detect-only
Example output:
File: document.pdf
Detected format: pdf
Converter: pdf2markdown
Dependencies: ✓ All required dependencies available
Ready to convert: Yes
Batch Detection:
# Detect formats for multiple files
all2md *.* --detect-only
Example output:
File Format Status
───────────────────────────────────────────────
report.pdf pdf ✓ Ready
slides.pptx pptx ✗ Missing python-pptx
data.xlsx spreadsheet ✓ Ready
notes.txt txt ✓ Ready
webpage.html html ✓ Ready
With Rich Output:
# Enhanced detection table with colors and progress bar
all2md documents/*.* --detect-only --rich
Use Cases:
Pre-flight checks - Verify all files can be processed before starting batch conversion
Format validation - Confirm file extensions match actual content
Dependency verification - Identify missing dependencies for specific files
CI/CD integration - Validate document collections in automated pipelines
Dry Run Mode
The --dry-run flag shows exactly what would be converted without actually processing files. This is invaluable for previewing batch operations, verifying file selection patterns, and checking configurations.
Basic Usage:
# Preview what would be converted
all2md documents/*.pdf --dry-run --output-dir ./converted
Example output:
Dry run mode: No files will be converted
Planned conversions:
documents/report.pdf → ./converted/report.md
documents/analysis.pdf → ./converted/analysis.md
documents/summary.pdf → ./converted/summary.md
Total: 3 files would be converted
With Exclusions:
# Preview with exclusion patterns
all2md ./project --recursive --exclude "*.tmp" --exclude "__pycache__" --dry-run
Example output:
Dry run mode: No files will be converted
Scanning directory: ./project (recursive)
Exclusion patterns: *.tmp, __pycache__
Planned conversions:
./project/docs/readme.md → ./project/docs/readme.md (text)
./project/reports/q1.pdf → ./project/reports/q1.md
./project/data/sales.xlsx → ./project/data/sales.md
Excluded:
./project/cache/temp.tmp (matches *.tmp)
./project/__pycache__/config.pyc (matches __pycache__)
Total: 3 files would be converted, 2 excluded
With Rich Progress:
# Show dry run with rich formatting
all2md large_collection/*.* --dry-run --rich --progress
Example output:
🔍 Analyzing files...
┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Source ┃ Format ┃ Destination ┃
┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━┩
│ report.pdf │ pdf │ ./converted/report.md │
│ slides.pptx │ pptx │ ./converted/slides.md │
│ data.xlsx │ sheet │ ./converted/data.md │
└─────────────────────┴──────────┴───────────────────────┘
✓ 3 files ready to convert
⚠ 1 file missing dependencies (pptx)
Combined with Other Options:
# Preview complex batch operation
all2md ./documents \
--recursive \
--preserve-structure \
--output-dir ./markdown \
--exclude "*.draft.*" \
--exclude "temp/*" \
--parallel 4 \
--dry-run
This shows exactly how files will be processed, where they’ll be saved, and what directory structure will be created, all without touching any files.
Use Cases:
Validate glob patterns - Ensure file selection matches expectations
Test exclusion rules - Verify that unwanted files are properly filtered
Preview directory structure - See output layout with
--preserve-structureVerify batch settings - Check all configuration before starting long-running jobs
Safe experimentation - Try different options without risk
Practical Examples
Basic Document Conversion
# Convert common document types
all2md report.pdf --out report.md
all2md presentation.pptx --out slides.md
all2md spreadsheet.xlsx --out data.md
all2md notebook.ipynb --out analysis.md
Working with Images
# Download images from PDF to local directory
all2md manual.pdf --attachment-mode save --attachment-output-dir ./pdf_images
# Embed PowerPoint images as base64
all2md presentation.pptx --attachment-mode base64
# Process HTML with external images
all2md webpage.html --attachment-mode save --attachment-base-url https://example.com
Advanced PDF Processing
# Process specific pages with custom formatting
all2md large_document.pdf --pdf-pages "1,2,3,6,11" --markdown-emphasis-symbol "_"
# Handle encrypted PDF
all2md encrypted.pdf --pdf-password "secret" --attachment-mode save
# Disable column detection for simple layout
all2md simple.pdf --pdf-no-detect-columns
Email Processing
# Process email with attachments
all2md message.eml --attachment-mode save --attachment-output-dir ./email_files
# Clean email conversion (no headers, flat structure)
all2md thread.eml --eml-no-include-headers --eml-no-preserve-thread-structure
Batch Processing
# Process all PDFs in directory with parallel processing
all2md *.pdf --parallel --output-dir ./converted --skip-errors
# Recursive processing with structure preservation
all2md ./documents --recursive --preserve-structure --output-dir ./markdown --exclude "*.tmp"
# Process with consistent options using old approach
find ./documents -name "*.docx" -exec all2md {} --out {}.md --markdown-emphasis-symbol "_" \;
Web Content Processing
# Download and convert web page
curl -s "https://example.com/page.html" | all2md - --html-extract-title --html-strip-dangerous-elements
# Process saved web page with images
all2md saved_page.html --attachment-mode save --attachment-base-url "https://example.com"
Document Splitting
# Split large book by chapters (H1 headings)
all2md book.pdf --split-by h1 --out book.md
# Creates: book_001.md, book_002.md, book_003.md, ...
# Split technical report by sections (H2 headings) with title-based naming
all2md report.docx --split-by h2 --split-by-naming title --out report.md
# Creates: report_001_introduction.md, report_002_methodology.md, ...
# Split long document by word count (~500 words per file)
all2md thesis.pdf --split-by length=500 --out thesis.md
# Split at horizontal rules (---, ***, ___)
all2md article.md --split-by break --out article.md
# Split at custom text delimiters
all2md notes.txt --split-by delimiter="\n***\n" --out notes.md
# Split presentation into roughly 5 equal parts
all2md slides.pptx --split-by parts=5 --out slides.md
# Let all2md automatically determine the best split strategy
all2md manual.html --split-by auto --out manual.md
# Split with custom digit padding (2 digits: 01, 02, ...)
all2md chapters.pdf --split-by h1 --split-by-digits 2 --out ch.md
Advanced Multi-File Processing
# Recursively convert all documents with parallel processing
all2md ./documents --recursive --parallel 8 --output-dir ./markdown_output --rich
# Collate multiple chapters into a single book
all2md chapter_*.pdf --collate --out complete_book.md --skip-errors
# Process with exclusions and structure preservation
all2md ./project --recursive --preserve-structure --exclude "__pycache__" --exclude "*.tmp" --exclude "node_modules"
# Dry run to preview what would be processed
all2md ./large_project --recursive --dry-run --exclude "*.log"
# Quiet batch processing with error handling
all2md *.docx --parallel --skip-errors --no-summary --output-dir ./converted
Using Presets Effectively
# Scenario 1: Fast batch conversion of many PDFs
# Use the 'fast' preset to skip expensive operations
all2md *.pdf --preset fast --output-dir ./converted --parallel 8
# Scenario 2: Archival of important documents
# Use 'archival' preset for self-contained files with base64 images
all2md important_*.pdf --preset archival --out ./archive/
# Scenario 3: Creating technical documentation
# Use 'documentation' preset with custom notebook truncation
all2md *.ipynb --preset documentation --ipynb-truncate-long-outputs 30
# Scenario 4: Quality conversion with preset overrides
# Start with quality, but skip attachments for this specific use case
all2md research.pdf --preset quality --attachment-mode skip
# Scenario 5: Combining preset with config file
# Use preset as base, config file for project settings, CLI for one-off changes
all2md report.pdf --preset quality --config .all2md.toml --pdf-pages "1-5"
When to Use Each Preset:
For fast batch processing of many documents where you only need text:
all2md documents/*.pdf --preset fast --output-dir ./text-only --parallel
For high-quality conversions where accuracy matters most:
all2md important.pdf --preset quality --out important.md
For archival purposes where files must be completely self-contained:
all2md archive/*.* --preset archival --output-dir ./archive
For documentation projects with notebooks and technical content:
all2md docs/*.ipynb --preset documentation --output-dir ./docs
Configuration File Usage
Create a configuration file .all2md.toml (preferred):
# all2md configuration
attachment_mode = "save"
attachment_output_dir = "./attachments"
log_level = "INFO"
[markdown]
emphasis_symbol = "_"
bullet_symbols = "•◦▪"
[pdf]
detect_columns = true
[html]
strip_dangerous_elements = true
Or use JSON format:
{
"attachment_mode": "save",
"attachment_output_dir": "./attachments",
"markdown.emphasis_symbol": "_",
"markdown.bullet_symbols": "•◦▪",
"pdf.detect_columns": true,
"html.strip_dangerous_elements": true,
"log_level": "INFO"
}
Use the configuration:
# Auto-discovery (place .all2md.toml in current directory)
all2md document.pdf
# Explicit config file
all2md document.pdf --config custom-config.toml
# Override specific options
all2md document.pdf --config config.json --attachment-mode base64
# Combine with presets
all2md document.pdf --preset fast --config overrides.toml
Debugging and Troubleshooting
# Enable debug output
all2md problematic.pdf --log-level DEBUG
# Test format detection
all2md unknown_file --log-level DEBUG --format auto
# Force specific format if detection fails
all2md mystery_file --format pdf --log-level INFO
Error Handling
Common Exit Codes
The CLI provides granular exit codes for automation and scripting:
0- Success1- General/unexpected error2- Missing dependency error3- Validation error (invalid arguments)4- File error (not found, permission denied, malformed)5- Format error (unsupported/unknown format)6- Parsing error (failed to parse document)7- Rendering error (failed to generate output)8- Security error (SSRF, zip bombs, etc.)9- Password-protected file
See EXIT_CODES.md in the repository for detailed documentation and shell scripting examples.
Error Examples
# Missing dependency
$ all2md document.pdf
Error: PyMuPDF is required for PDF processing. Install with: pip install all2md[pdf]
# File not found
$ all2md nonexistent.pdf
Error: File not found: nonexistent.pdf
# Invalid option
$ all2md document.pdf --invalid-option
Error: unrecognized arguments: --invalid-option
Shell Integration
Bash Completion
Add to your .bashrc or .bash_profile:
# Basic completion for file extensions
complete -f -X '!*.@(pdf|docx|pptx|html|eml|epub|ipynb|odt|odp|xlsx|csv|tsv)' all2md
Aliases and Functions
# Useful aliases
alias pdf2md='all2md --format pdf --attachment-mode save'
alias docx2md='all2md --format docx --markdown-emphasis-symbol "_"'
alias html2md='all2md --format html --html-strip-dangerous-elements'
# Function for batch processing
all2md_batch() {
local dir="${1:-.}"
local pattern="${2:-*}"
find "$dir" -name "$pattern" -type f | while read -r file; do
echo "Converting: $file"
all2md "$file" --out "${file%.*}.md"
done
}
Environment Variables
all2md supports setting default values for all CLI options using environment variables. This provides a convenient way to configure defaults for scripts or user preferences.
Configuration File via Environment Variable:
ALL2MD_CONFIGPath to a configuration file (JSON or TOML) containing conversion options. This is equivalent to using
--configon the command line. The CLI argument--configtakes precedence over this environment variable if both are specified.# Set default config file location export ALL2MD_CONFIG="$HOME/.config/all2md/default.toml" # Now all commands use this config by default all2md document.pdf # Override with explicit flag all2md document.pdf --config ./project-config.json
Naming Convention:
Environment variables use the pattern ALL2MD_<OPTION_NAME> where <OPTION_NAME> is the CLI argument name in uppercase with hyphens and dots replaced by underscores.
Examples:
# CLI argument: --output-dir
export ALL2MD_OUTPUT_DIR="./converted"
# CLI argument: --markdown-emphasis-symbol
export ALL2MD_MARKDOWN_EMPHASIS_SYMBOL="_"
# CLI argument: --pdf-pages (comma-separated, 1-based)
export ALL2MD_PDF_PAGES="1,2,3"
# CLI argument: --parallel (integer)
export ALL2MD_PARALLEL="4"
Supported Value Types:
Strings: Use the value directly
Booleans: Use
true,1,yes, oronfor true; anything else for falseIntegers: Provide numeric values (validated for positive integers where applicable)
Lists: Use comma-separated values (e.g., for
--excludeor--pdf-pages)
Complete Example Configuration:
# Global attachment options (applies to attachment-capable formats)
export ALL2MD_ATTACHMENT_MODE="save"
export ALL2MD_ATTACHMENT_OUTPUT_DIR="./attachments"
# Markdown formatting
export ALL2MD_MARKDOWN_EMPHASIS_SYMBOL="_"
export ALL2MD_MARKDOWN_BULLET_SYMBOLS="•◦▪"
# Multi-file processing options
export ALL2MD_RICH="true"
export ALL2MD_PARALLEL="4"
export ALL2MD_OUTPUT_DIR="./converted"
export ALL2MD_SKIP_ERRORS="true"
export ALL2MD_RECURSIVE="true"
export ALL2MD_PRESERVE_STRUCTURE="true"
# Format-specific options
export ALL2MD_PDF_DETECT_COLUMNS="false"
export ALL2MD_HTML_STRIP_DANGEROUS_ELEMENTS="true"
export ALL2MD_PPTX_INCLUDE_SLIDE_NUMBERS="true"
# Exclusion patterns (comma-separated)
export ALL2MD_EXCLUDE="*.tmp,*.bak,__pycache__"
Precedence:
Command-line arguments always override environment variables:
export ALL2MD_OUTPUT_DIR="./default"
# This will use "./override" instead of "./default"
all2md document.pdf --output-dir ./override
Use Cases:
User Preferences: Set your preferred defaults in
.bashrcor.zshrcCI/CD Scripts: Configure consistent behavior across pipeline stages
Docker Containers: Set default configuration without modifying commands
Batch Processing: Avoid repeating common options
Global Network Control:
For security-sensitive environments, use ALL2MD_DISABLE_NETWORK to globally disable all network operations:
# Disable all network operations globally (overrides all other network settings)
export ALL2MD_DISABLE_NETWORK=1
all2md webpage.html # Will skip all remote resources
For complete option details and programmatic usage, see the Configuration Options reference and Python API documentation. Enhanced Help System ——————–
The CLI exposes a tiered help system that mirrors the dynamic options generated from dataclasses:
all2md --helporall2md helprenders a concise overview with the most important flags.all2md help fulllists every parser and renderer option, grouped by format.all2md help <format>(for examplepdfordocx) shows only the options relevant to that format. Renderer options appear alongside parser options so you can see both halves of the pipeline in one view.--richis available on the help subcommand to colourise headings, flags, defaults, and metadata when the rich library is installed.
The same formatting and grouping logic is used by the generated CLI output and this reference documentation, ensuring that new options surface automatically as dataclass metadata evolves.
Shell Completion
all2md supports intelligent shell completion for Bash, Zsh, and PowerShell. The completion scripts are context-aware and will suggest relevant options based on the current command line state.
Generate Completion Scripts
Use the all2md completion subcommand to generate completion scripts for your shell:
# Generate bash completion script
all2md completion bash
# Generate zsh completion script
all2md completion zsh
# Generate PowerShell completion script
all2md completion powershell
Installation
Bash:
# Save to system completion directory
all2md completion bash > ~/.local/share/bash-completion/completions/all2md
# Or source directly in your .bashrc
echo 'source <(all2md completion bash)' >> ~/.bashrc
Zsh:
# Create completion directory if needed
mkdir -p ~/.zsh/completions
# Save completion script
all2md completion zsh > ~/.zsh/completions/_all2md
# Add to .zshrc (if not already present)
echo 'fpath=(~/.zsh/completions $fpath)' >> ~/.zshrc
echo 'autoload -U compinit && compinit' >> ~/.zshrc
PowerShell:
# Add to your PowerShell profile
all2md completion powershell >> $PROFILE
# Or for current session only
all2md completion powershell | Out-String | Invoke-Expression
Completion Features
The generated completion scripts provide:
Subcommand completion - Complete all available subcommands (help, config, diff, etc.)
Global option completion - Complete universal options like
--out,--format,--verboseFormat-aware completion - When
--format pdfis present, suggest PDF-specific optionsFile extension detection - Automatically detect format from input file extension
Renderer context - Suggest renderer options when
--output-typeis specifiedChoice completion - Complete valid values for options with predefined choices
Install Skills Command
The all2md install-skills command copies bundled agent skills to a directory where AI coding assistants can discover them. See Agent Skills for full details on the skills themselves.
Basic Usage
# Install to default location (./.agents/skills/ or ~/.agents/skills/)
all2md install-skills
# List available skills without installing
all2md install-skills --list
# Install to local project
all2md install-skills --local
# Install globally
all2md install-skills --global
# Install to custom directory
all2md install-skills --target /path/to/skills
# Force overwrite existing skills
all2md install-skills --force
# Remove installed skills
all2md install-skills --uninstall
Options
Option |
Description |
|---|---|
|
Explicit target directory for skills |
|
Install to |
|
Install to |
|
Overwrite existing skills without warning |
|
List bundled skills without installing |
|
Remove |
The completion scripts are static and self-contained, requiring no runtime calls to all2md. If you add new formats via plugins, regenerate the completion script to include the new options.
LLM Help Command
The all2md llm-help command prints the bundled agent-skill reference files to
stdout. It is handy when driving the CLI from an LLM or script without installing
the skill into an assistant. The topics are auto-discovered from the skill’s
references/*.md files.
# List available topics
all2md llm-help --list
# Print a single topic
all2md llm-help convert
# Print every topic (the full reference)
all2md llm-help
Available topics are overview, read, convert, generate, grep,
search, and diff.
LLM Minify Command
The all2md llm-minify command converts any supported document just like the
default all2md <file> command, but strips filler that wastes LLM tokens. Use
it when you only need the content, not the formatting or spacing.
Two presets are available:
Compact Markdown (default) — keeps Markdown structure (headings, lists, code, tables) while dropping comments, frontmatter and raw HTML, replacing embedded base64 image data with an alt-text-only reference (so a single screenshot no longer costs tens of thousands of tokens), and collapsing redundant blank lines and interior whitespace.
Plain text (
--aggressive/--text) — strips all formatting down to bare text.
# Compact Markdown (default preset)
all2md llm-minify report.docx
# Strip all formatting to bare text
all2md llm-minify report.docx --aggressive
# Read from stdin, write to a file
cat notes.html | all2md llm-minify - --out notes.min.md
Additional pruning flags layer on top of either preset:
--strip-links— drop link URLs, keep the link text--strip-images— remove images entirely--strip-formatting— remove inline emphasis/strong/strikethrough markers
Command Aliases
A few commands accept short aliases:
all2md formatsis an alias forall2md list-formatsall2md transformsis an alias forall2md list-transforms
The config subcommands (generate/show) also accept --format yaml
in addition to toml and json.