Metadata-Version: 2.4
Name: hammerdown
Version: 4.1.1
Summary: Convert documents to Markdown with extracted images
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pymupdf<2
Requires-Dist: pymupdf4llm<2
Requires-Dist: python-docx
Requires-Dist: openpyxl
Requires-Dist: python-pptx
Requires-Dist: onnxruntime
Requires-Dist: tiktoken
Requires-Dist: rich
Requires-Dist: beautifulsoup4
Requires-Dist: lxml
Requires-Dist: pathspec
Dynamic: license-file

# hammerdown

[![Tests](https://img.shields.io/github/actions/workflow/status/sergeypugin/hammerdown/release.yaml?branch=main&label=tests&logo=github&style=flat-square)](https://github.com/sergeypugin/hammerdown/actions)
[![PyPI](https://img.shields.io/pypi/v/hammerdown?style=flat-square&color=2ea44f&logo=pypi&logoColor=white)](https://pypi.org/project/hammerdown/)
[![GitHub Release](https://img.shields.io/github/v/release/sergeypugin/hammerdown?style=flat-square&color=2ea44f&logo=github)](https://github.com/sergeypugin/hammerdown/releases)
[![Python Version](https://img.shields.io/badge/Python-3.10+-3776ab?style=flat-square&logo=python&logoColor=white)](https://www.python.org/)
[![Platform](https://img.shields.io/badge/Platform-Windows%20|%20Linux%20|%20macOS-blue?style=flat-square)](https://github.com/sergeypugin/hammerdown/releases)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-a1ffcb?style=flat-square&labelColor=191919)](CONTRIBUTING.md)

<div align="center">
  <img src="assets/logo.svg" alt="hammerdown logo" width="220" height="220">
</div>

<p align="center"><em>Only the worthy can lift it</em></p>

`hammerdown` is a cross-platform tool and Python library for converting PDF, Word, Excel, PowerPoint, OpenDocument, CSV, and plain-text documents into clean Markdown. Word charts are rendered as SVG, OpenDocument and Markdown images are extracted, and mathematical formulas are converted to LaTeX.

The PDF pipeline is built on [PyMuPDF](https://pymupdf.readthedocs.io/) and [PyMuPDF4LLM](https://github.com/pymupdf/PyMuPDF4LLM), which do the actual page-layout reconstruction and Markdown generation. This is the central feature the project was built around. Everything else -- routing, batch handling, merging, and file-manager integration -- is built around that core.

## Supported Formats

- **PDF and E-books**: `.pdf`, `.epub`, `.mobi`, `.fb2`, `.xps`
- **Word and OpenDocument**: `.docx`, `.doc`, `.odt`
- **Spreadsheets**: `.xlsx`, `.xls`, `.csv`
- **Presentations**: `.pptx`, `.ppt`
- **Text and Markdown**: `.txt`, `.md`, `.log`
- **Web pages**: `.html`, `.htm`
- **Google Drive exports**: `.zip` (Google Docs "Web page" export, containing an `.html` file and an optional `images/` folder)
- **Google Docs/Drive links**: public `docs.google.com` (document, spreadsheets, presentation) and `drive.google.com/file` URLs are downloaded automatically; **Drive folders are not supported**
- **Google Drive downloads**: `.gdoc`, `.gsheets`, `.gslides`, `.gfile` payloads (the HTML files produced when a Google Docs/Drive link is downloaded) convert like web pages

> [!important]
> Legacy binary formats (`.doc`, `.xls`, `.ppt`) require a compatible desktop office suite installed on the same computer as `hammerdown`. These applications are not bundled with `hammerdown`.
>
> - on Windows, the matching desktop Microsoft Office application is tried first, then LibreOffice
> - on Linux and macOS, LibreOffice is required
>
> Modern formats (`.docx`, `.xlsx`, `.pptx`) are processed without an external office suite.

## Table of Contents

- [Output Directory Layout](#output-directory-layout)
- [Installation](#installation)
  - [Recommended: Python package (pip)](#recommended-python-package-pip)
  - [Direct Download (Standalone binaries)](#direct-download-standalone-binaries)
  - [File Manager Context Menu Integration](#file-manager-context-menu-integration)
  - [Logging and Progress Tracking](#logging-and-progress-tracking)
- [Advanced Usage](#advanced-usage)
  - [Command Line Interface](#command-line-interface)
    - [Tree Mode](#tree-mode)
    - [Resource filters and ignore files](#resource-filters-and-ignore-files)
    - [Merging Documents into a Single File](#merging-documents-into-a-single-file)
    - [Streaming to stdout](#streaming-to-stdout)
  - [Python Library Quickstart](#python-library-quickstart)
- [Implementation Notes](#implementation-notes)
  - [Extracting Base64 Images from Markdown](#extracting-base64-images-from-markdown)
  - [Math Formulas and Symbol Normalization](#math-formulas-and-symbol-normalization)
  - [Tables and Spreadsheets](#tables-and-spreadsheets)
- [Credits and Attribution](#credits-and-attribution)
- [Documentation links](#documentation-links)

## Output Directory Layout

Output Markdown files have deterministic per-source names: `report.docx` becomes `hm_report_docx.md` and `notes.txt` becomes `hm_notes_txt.md`. The source extension is part of the name, with the extension normalized to lowercase, so `report.docx` and `report.doc` do not overwrite each other. On a normal successful rerun, Hammerdown replaces the Markdown target and the complete corresponding `hm_images_*` asset directory; stale asset files and old extensions are not retained, and an old asset directory is removed when the new conversion produces no assets. With `--skip-existing`, Hammerdown checks the target Markdown only: when it already exists, both that target and its asset directory remain untouched, even if stale, and conversion is skipped.

**Before conversion:**

```text
folder/
└── report.docx
```

**After conversion:**

```text
folder/
├── report.docx
├── hm_report_docx.md
└── hm_images_report_docx/
    └── chart_001.svg
```

PDF text is converted directly to Markdown without producing an asset folder. Asset folders are created only where the format exposes separate assets: Word charts are rendered as SVG, OpenDocument images are copied out, and base64 images in Markdown are decoded. Presentations and spreadsheets produce Markdown text and tables only. Web page (`.html`) and Google Drive ZIP exports copy their referenced images into the target folder with the same `hm_images_...` naming convention.

## Installation

### Recommended: Python package (pip)

If Python (3.10+) is installed on your system, install via pip:

```sh
pip install hammerdown
```

Or install from local source:

```sh
git clone https://github.com/sergeypugin/hammerdown.git
cd hammerdown
pip install .
```

#### Development install (editable)

To test the latest changes without waiting for a release, install the package in editable mode from the repository. This makes the `hammerdown` command point directly at your local source tree, so edits to `src/` are picked up immediately:

```sh
git clone https://github.com/sergeypugin/hammerdown.git
cd hammerdown
python -m pip install -e .
hammerdown --install
```

`hammerdown --install` registers the file-manager integration using the freshly installed local package, so right-clicking a document uses this build right away.

### Direct Download (Standalone binaries)

If you do not have Python installed, precompiled standalone binaries are available on the [GitHub Releases page](https://github.com/sergeypugin/hammerdown/releases) or you can download directly from the links below:

| OS | Download |
| :--- | :--- |
| **Windows** | [![Windows x64](https://img.shields.io/badge/Windows-x64-0078d7?style=flat-square&logo=windows&logoColor=white)](https://github.com/sergeypugin/hammerdown/releases/latest/download/hammerdown-windows-x64.exe) |
| **Linux** | [![Linux x64](https://img.shields.io/badge/Linux-x64-fcc624?style=flat-square&logo=linux&logoColor=black)](https://github.com/sergeypugin/hammerdown/releases/latest/download/hammerdown-linux-x64) |
| **macOS** | [![macOS x64](https://img.shields.io/badge/macOS-x64-000000?style=flat-square&logo=apple&logoColor=white)](https://github.com/sergeypugin/hammerdown/releases/latest/download/hammerdown-macos-x64) [![macOS ARM64](https://img.shields.io/badge/macOS-ARM64-ea4c89?style=flat-square&logo=apple&logoColor=white)](https://github.com/sergeypugin/hammerdown/releases/latest/download/hammerdown-macos-arm64) |

On Linux and macOS, make the downloaded binary executable before running:

```sh
chmod +x ./hammerdown-linux-x64
./hammerdown-linux-x64 --version
```

### File Manager Context Menu Integration

You can integrate `hammerdown` directly into your OS file manager to convert documents with a single right-click, without opening a terminal:

```sh
hammerdown --install
```

After installation, Hammerdown adds four file-manager actions. Their exact presentation depends on the platform, but the actions have the same meaning:

- **Convert to Markdown** converts each selected file or recursively selected folder into separate Markdown output and any extracted assets
- **Merge** converts the selected resources and combines successful results into one Markdown document
- **Tree** collects supported text and source files into one tree document
- **Tree with all formats** works like Tree and also includes supported document formats such as PDF, Word, Excel, PowerPoint, OpenDocument, e-books, and ZIP inputs

How to find the actions:

| Platform or file manager | Where the actions appear |
| :--- | :--- |
| Windows File Explorer | A **Hammerdown** submenu with the four actions for selected files and folders; matching commands are also available in **Send to** |
| KDE Dolphin | A **Hammerdown** submenu in the context menu |
| Nautilus, Nemo, and Caja | Four separate file-manager actions or scripts |
| macOS Finder | Four separate Quick Actions; the installed droplet is also available for drag and drop |

On Windows, multi-file selections are collected by a hidden background coordinator and opened in a single Windows Terminal window titled `Hammerdown`, so selecting several documents never produces several console windows. When Windows Terminal is not installed, the same run falls back to one regular console window instead.

To remove file manager integration and clean up shortcuts:

```sh
hammerdown --uninstall
```

> [!note]
> `hammerdown --install` creates or refreshes the four file-manager actions supported by your platform. On Windows it also refreshes the **Send to** commands.

#### Supported platforms for file-manager integration

File-manager integration is installed only on these systems:

| OS | Supported | Notes |
| :--- | :--- | :--- |
| Windows | yes | File Explorer context menu, SendTo shortcuts |
| macOS | yes | Finder Quick Action and droplet |
| Linux | yes | XDG `.desktop` entries, KDE ServiceMenus, Nautilus/Nemo/Caja scripts |
| FreeBSD and other systems | no | `--install` and `--uninstall` exit with an error |

On unsupported systems the converter itself still works normally from the terminal:

```sh
hammerdown report.pdf
hammerdown -m merged.md report.pdf notes.docx
```

Unknown desktop environments cannot be wired up automatically: every file manager exposes its own extension mechanism, and writing entries blindly could break existing associations with no reliable way to detect or undo it. If you need a context-menu action on a system that is not listed above, add a small adapter as described in [CONTRIBUTING.md](CONTRIBUTING.md#adding-support-for-another-platform) and open a pull request.


To update `hammerdown` to the latest version, use the built-in updater (which also refreshes launcher scripts and context menu entries):

```sh
hammerdown --upgrade
```

> [!note]
> **Upgrading from versions prior to 3.2.1:** due to a packaging configuration issue in versions 3.1.0 through 3.1.4 on PyPI, use `pip install --upgrade hammerdown` to update to 3.2.1+. Starting with version 3.2.1, `hammerdown --upgrade` (or `hammerdown --update`) works automatically.

### Versioning and release tags

`hammerdown` follows semantic versioning. A tag `vX.Y.Z` (for example `v3.2.1`) is a **stable** release: it is marked as the latest and published to PyPI. A tag with a prerelease suffix (for example `v3.2.1-pre1`) is a **preview**: it is published as a GitHub release but is never marked latest and is not pushed to PyPI.

Releases are published directly by pushing version tags (`git tag v3.2.1 && git push origin v3.2.1`). The CI release workflow builds standalone binaries for Windows, Linux, and macOS, extracts release notes from `CHANGELOG.md`, and publishes the package to PyPI.

### Logging and Progress Tracking

When converting documents from the terminal, `hammerdown` renders a live view instead of scrolling log lines. The `Summary` panel shows elapsed time, the preflight estimate, completed files, the running token count, and the number of errors. The `Processing` panel keeps a sliding window of the file queue:

<div align="center">
  <img src="docs/assets/batch-progress.png" alt="Live batch progress" width="600">
</div>

- a completed file gets a green marker and its duration, image count, and token count
- the active file shows an inline progress bar in the state column and its live elapsed time
- queued files are dimmed and show their preflight estimate
- failed files get a red marker and are repeated in a separate `Error list` panel with the failure reason
- the `Processing` panel border is orange while the batch is running and green once it finishes
- the `Results` panel summarizes merged documents, converted files, and extracted images

<div align="center">
  <img src="docs/assets/batch-summary.png" alt="Batch summary, error list, and results" width="600">
</div>

In non-interactive environments (CI pipelines, redirected logs, or non-TTY outputs) no live view is drawn. Each file is announced when it starts and reported when it finishes, and the same `Summary`, `Error list`, and `Results` panels are printed once at the end as plain text without terminal control characters:

```text
Processing report.pdf ~8.1s...
Completed report.pdf (8.1s, ~1_200 tokens)
Processing notes.txt ~0.5s...
Completed notes.txt (0.5s, ~12 tokens)
```

When using `hammerdown` as a Python library, custom progress callbacks can be passed to `to_markdown()` or `convert_file()`:

```python
def on_progress(current: int, total: int, unit: str):
    print(f"Processed {current}/{total} {unit}")

hammerdown.convert_file("report.pdf", progress_callback=on_progress)
```

## Advanced Usage

### Command Line Interface

Run with no arguments to print the tool description, supported formats, and the hint for `hammerdown --help`. A conversion invocation needs at least one input resource. A command made only from conversion flags exits with an error before discovery starts:

```sh
hammerdown
hammerdown --tree
hammerdown -m anything.ext
```

The first command prints the description. The last two have no input resource and fail immediately with `no input resources were provided`. The error is the same when the only arguments are filters, output options, or other conversion flags.

A normal conversion writes one Markdown file and its assets for each discovered file. Merge mode combines converted documents into one target Markdown file. Tree mode uses its own discovery rules and also writes one combined Markdown document; `--all-formats` extends tree discovery with supported document formats. Convert one or multiple files:

```sh
hammerdown report.pdf
hammerdown report.docx workbook.xlsx slides.pptx
```

Convert a public Google Docs, Sheets, or Slides link directly (it must be shared as "Anyone with the link"):

```sh
hammerdown "https://docs.google.com/document/d/...."
hammerdown "https://docs.google.com/spreadsheets/d/...."
hammerdown "https://docs.google.com/presentation/d/...."
hammerdown "https://drive.google.com/file/d/...."
```

The HTML export is downloaded to a temporary staging folder, converted, and then removed. Google Drive **folders** (`.../drive/folders/...`) are not supported because they require Drive API authentication, and private documents (HTTP 401) are reported as errors. Images referenced by Google are left as external links in the Markdown, since Google hosts them on `googleusercontent.com` rather than alongside the HTML.

Options:

- `-i`, `--include PATTERN` -- include paths matching a GitWildMatch/pathspec pattern; may be repeated
- `-e`, `--exclude PATTERN` -- exclude paths matching a GitWildMatch/pathspec pattern; may be repeated
- `--tree` -- gather a project tree into one Markdown output, using Gitingest-like text and code collection
- `--all-formats` -- in tree mode, also include supported Hammerdown document formats
- `--include-gitignored` -- do not apply repository `.gitignore` and `.gitingestignore` rules
- `-w`, `--overwrite` -- overwrite plain-text source files (`.txt`, `.md`, `.log`, `.csv`) in-place instead of creating a copy
- `-s`, `--skip-existing` -- skip conversion when the target Markdown file already exists; without it, existing `hm_*.md` outputs are overwritten and their complete asset directories are replaced
- `-o`, `--output-dir DIR` -- save Markdown output and extracted images under DIR, preserving the relative layout of the input tree
- `-m [OUTPUT_MD]`, `--merge [OUTPUT_MD]` -- merge converted documents into the target Markdown file; the next argument is the output, and an omitted target defaults to `hammerdowned.md`
- `-y`, `--yes` -- overwrite an existing merge or tree target without asking
- `-n`, `--no` -- keep an existing merge or tree target and exit `0` without converting
- `--stdout` -- write the merged Markdown document to stdout; errors go to stderr
- `--confirm` -- with `--stdout`, print a preflight estimate and ask for confirmation before writing anything
- `--tokens` -- report source and estimated token counts without converting
- `--time` -- report conversion time estimates without converting
- `--dir-struct` -- report the selected directory structure without converting
- `-v`, `--version` -- display version information

Option names are case-insensitive, including short and long forms, but option values, paths, and include/exclude filter patterns preserve the case supplied by the caller. Long options must use their exact two-dash names: single-dash long forms and abbreviated long forms remain errors, even when the abbreviation is unambiguous; Hammerdown prints a suggestion or the possible matches.

#### Tree Mode

A tree run without `--all-formats` gathers Gitingest-like text and code-like files. It does not add Hammerdown's binary document formats to the tree. With `--all-formats`, supported Hammerdown documents are included too; unknown binary files are skipped. Tree mode always produces one combined Markdown document: `hammerdowned.md` by default, or the file passed with `-m`. It is not a per-file conversion mode. The output starts with a YAML frontmatter metadata block -- the same one merge mode writes, described below -- recording the tool, version, date, mode, source, inputs, file count, and token estimate, so you can tell a stale target from a fresh one.

> [!important]
> tree mode always writes the same target file (`hammerdowned.md` unless `-m` sets one) and replaces it on every run, frontmatter included, so the metadata always reflects the latest run. If you need Markdown copies for long-term storage, use ordinary per-file conversion instead

```sh
hammerdown --tree project/
hammerdown project/ --tree --all-formats
```

`--tree` and `--all-formats` may appear before, between, or after resource arguments. These forms are equivalent:

```sh
hammerdown --tree --all-formats project/
hammerdown --tree project/ --all-formats
hammerdown project/ --tree --all-formats
```

`--all-formats` without `--tree` or `--dir-struct` is rejected. `.log` files are not excluded automatically in any conversion mode; a log is processed unless an ignore rule or filter excludes it.

#### Resource filters and ignore files

Repeated `-i` and `-e` options are evaluated as one ordered queue in the order they appear. A path starts included when no include option is present, or excluded when an include option is present; each matching `-e` excludes it and each later matching `-i` includes it again. The last matching operation decides, so a later include can restore a path excluded earlier. Pattern values can contain comma- or whitespace-separated patterns. Patterns use Gitingest-compatible GitWildMatch/pathspec syntax and are matched against paths relative to their resource context.

Quote pattern arguments with single or double quotes so the shell does not expand glob characters or split the argument. Single and double quotes can behave differently depending on the shell; for example, double quotes may still allow variable expansion. Hammerdown strips the matching quotes and then splits pattern values on commas or whitespace. Apostrophes or quote characters that are part of a file name are not supported by its quote parser. Backticks are not quoting syntax.

```sh
hammerdown -i 'src/**/*.py, docs/**/*.md' -e '**/generated/**' -i 'src/generated/keep.py' project/
```

For each selected resource, Hammerdown looks for `.gitignore` and `.gitingestignore` from the selected root up to the nearest Git root, and also discovers nested ignore files below that root. Nested rules apply to their paths and support negation. Ignore files above the Git root and global ignore configuration are not applied. `--include-gitignored` disables only these repository ignore files; command-line filters, safety exclusions, and format rules still apply.

Before processing, the `Ignore files used` panel lists every discovered ignore file. Files dropped by repository ignore rules are not added to the `Skipped files` panel; that panel is reserved for visible skips such as command-line filters and safety exclusions. When `--include-gitignored` is used, the discovered ignore files are still listed even though their rules are bypassed.

Repeated files, a file plus its containing directory, and overlapping parent/child roots are resolved to canonical paths and processed once. During recursive discovery, files named `hm_*.md` or `hammerdowned.md` are recognized as generated outputs and excluded instead of being treated as sources. Passing one of these generated files explicitly is an error. If a recursively selected directory contains only generated outputs, the run fails because no input resources remain.

#### Merging Documents into a Single File

`-m` / `--merge` treats the next argument as the output Markdown file and then expects one or more source resources. If the target is omitted, it defaults to `hammerdowned.md`. It converts the resources and concatenates the results into one Markdown file. This is convenient when you want to feed a whole project folder into an LLM as a single context block:

```sh
hammerdown -m summary.md project/report.pdf project/notes.docx project/drafts/
hammerdown project/report.pdf project/notes.docx project/drafts/ -m
```

The first command writes `summary.md`; the second writes the default `hammerdowned.md`. An argument immediately after `-m` is never an input resource. For example, `hammerdown -m report.pdf` treats `report.pdf` as the output target and then fails because no input remains, while `hammerdown -m output.md report.pdf` is valid.

> [!important]
> merge and tree always write the same target file (`hammerdowned.md` unless `-m` sets one) and replace it on every run, frontmatter included, so a later run with different arguments overwrites the previous merged output and its metadata. If you need Markdown copies for long-term storage, use ordinary per-file conversion instead: it writes `hm_<stem>_<ext>.md` next to each source and keeps different runs separate

The merged document starts with a YAML frontmatter metadata block, followed by two parts. It is assembled in a hidden staging directory and committed atomically once every source has been converted.

The frontmatter records the provenance of the run, so a stale target is easy to tell from a fresh one:

```markdown
---
tool: 'hammerdown'
version: '4.0.0'
date: '2026-11-10T21:34:05+03:00'
mode: 'merge'
source: 'C:/Users/serge/project'
inputs:
  - 'folder1'
  - 'folder1/folder2'
  - 'folder3'
files: 42
tokens_estimate: 15200
---
```

Field semantics:

- `tool`: always `hammerdown`
- `version`: hammerdown version that produced the file
- `date`: conversion date and time, local ISO 8601 with timezone offset
- `mode`: operation flags only -- `merge`, `tree`, or `tree --all-formats`
- `source`: resolved common root directory of all inputs (forward slashes); the per-file directory tree in the body is relative to it
- `inputs`: raw command-line arguments exactly as passed, one YAML list item each; written as `inputs: []` when empty
- `files`: number of discovered sources
- `tokens_estimate`: approximate output token count, plain integer, computed with the same rules as `--tokens` (exact counts for text sources, size//4 estimate for known binary formats); the metadata block itself is not counted in it

First, a directory tree of every source document, relative to their common root:

```text
Directory structure:
└── project/
    ├── report.pdf
    ├── notes.docx
    └── drafts/
        └── plan.md
```

Then one block per document. Each block starts with a line of 48 `=` characters, a `FILE:` line with the path relative to the common root, the same separator again, and the converted Markdown:

```text
================================================
FILE: report.pdf
================================================
# Quarterly Report

Revenue grew by 12% in Q3.

================================================
FILE: drafts/plan.md
================================================
# Draft Plan

- collect metrics
- review results
```

Key properties:

- the merged document is assembled in a hidden `.hammerdown-merge-` staging directory next to the target and committed atomically once every source has been appended; an interrupted run leaves the previous target untouched, and a rerun whose sources produced errors also preserves an existing target
- extracted assets are not mixed with the originals: for the target `summary.md`, images, charts, and decoded pictures are written into `hm_merged_into_summary_images/` next to the target, in subfolders that mirror each document's relative path, and their links are rewritten accordingly
- `--merge` is rejected together with `--overwrite` and with `--output-dir`, so plain-text sources are never modified during a merge
- combined with `-s` / `--skip-existing`, the whole merge is skipped when the target file already exists; the target and its merge asset directory are left untouched, even if stale
- when the target file already exists and `-s` is not set, a terminal session prints the existing file's frontmatter metadata (`Existing output was generated with:` followed by the block) and then asks `Overwrite <name>? [y/n]` before overwriting it; `-y`/`--yes` overwrites without asking, `-n`/`--no` keeps the existing target and exits `0`, and a non-interactive run without either flag exits `1` with guidance instead of hanging
- when a custom merge target is inside a recursively selected directory, discovery excludes that target so a rerun does not merge the previous output into itself; explicitly passing the target as a source remains an error

After the run the sources stay where they were, and the merged file sits next to its assets:

```text
project/
├── report.pdf
├── notes.docx
├── drafts/
│   └── plan.md
├── summary.md
└── hm_merged_into_summary_images/
    ├── hm_images_notes_docx/
    │   └── chart_001.svg
    └── drafts/
        └── hm_images_plan_md/
            └── embedded_img_1.png
```

#### Streaming to stdout

`--stdout` produces the same merged document as `-m`, but writes it to stdout instead of a file, and does not create any intermediate `hm_*.md` files:

- with **a single file**, `--stdout` emits just that file's raw Markdown (no merge header, no separator lines) — ideal for clean piping
- with **multiple files**, it emits the merged document with directory tree and per-file separators
- in both cases the stream stays headerless: the YAML frontmatter metadata block is written only to merge and tree file targets, never to stdout

```sh
hammerdown --stdout project/ > summary.md
```

Assets are inlined as base64 data URIs, so the stream is self-contained. Progress tables and per-file messages are suppressed; errors go to stderr, and the exit code is non-zero when any document failed.

Add `--confirm` to inspect the cost before anything is printed. Missing paths are reported first, then the preflight line shows the file count, a token estimate for text sources, and an estimated duration. The prompt accepts `y` and `yes`, rejects `n` and `no`, and re-asks on anything else:

```text
[!] drafts: file or directory not found
[!] missing.md: file or directory not found
Preflight: 16 files, ~2_400 tokens from text sources, estimated time ~1m 43.9s.
Continue and write Markdown to stdout? [y/n] Lk
Please answer "y" or "n".
Continue and write Markdown to stdout? [y/n] nO
Cancelled.
```

Only formats that are already plain text (`.txt`, `.md`, `.log`, `.csv`) contribute to the token estimate, because the size of a PDF, DOCX, or XLSX says nothing about the Markdown that comes out of it. For mixed inputs the clause is marked `from text sources`; when no such files are present, the token clause is omitted entirely. `--confirm` requires an interactive stdin; without a terminal it cancels safely instead of waiting. `--stdout` is incompatible with `--merge`, `--output-dir`, `--overwrite`, and `--skip-existing`.

### Python Library Quickstart

Use `hammerdown` directly in your Python code:

```python
import hammerdown

# Convert a file on disk
hammerdown.convert_file("report.pdf", skip_existing=True)

# Get Markdown text in memory
text, image_count = hammerdown.to_markdown("report.docx")

# Convert a batch with CLI-equivalent options
hammerdown.convert_files(["project/"], merge="summary.md", include=["reports/**"])
```

For specialized format converters and low-level helpers, see [docs/PYTHON.md](docs/PYTHON.md).

## Implementation Notes

### Extracting Base64 Images from Markdown

If you have a Markdown file with embedded base64 images, running `hammerdown` with `--overwrite` extracts each image using its MIME type (`png`, `jpeg`, `webp`, `gif`, `svg` and other supported image subtypes) into a sibling folder named after the source. For `LMS.md`, the first decoded image is written as `hm_images_LMS_md/embedded_img_1.png` and the link in the document is rewritten to that path. The image is not converted to PNG: PNG is used only when the source data URI says `image/png`.

```sh
hammerdown LMS.md --overwrite
```

### Math Formulas and Symbol Normalization

Equations inside Word and OpenDocument files are automatically translated into standard LaTeX syntax. Special math characters and Greek letters are mapped using a catalog aligned with official LaTeX references:

- Official Reference: [Rice University LaTeX Symbols Reference](https://cmor-faculty.rice.edu/~heinken/latex/symbols.pdf)
- Bundled Copy: [symbols.pdf](src/hammerdown/parsers/math/symbols.pdf)

### Tables and Spreadsheets

Tables are reconstructed as real Markdown tables instead of loose text:

- **CSV**: the delimiter is detected from the first lines (comma, semicolon, tab, or pipe), and the file is decoded through the same UTF-8, CP1251, CP1252, and Latin-1 fallback chain as other text inputs
- **XLSX**: every worksheet starts with a `# Sheet: Data` heading. Cells with evaluated values use them; when a formula has no cached value, the formula text itself is used. Empty rows and columns at the edges are trimmed, and separate blocks of cells on the same sheet become separate Markdown tables
- **DOCX and PPTX**: table cells are rendered as Markdown rows. Pipes inside a cell are escaped as `\|`, and empty cells are kept so the column layout stays stable

The shared renderer lives in `parsers/markdown_render.py`, and the matrix segmentation logic used by spreadsheets and CSV lives in `parsers/tables.py`.

## Credits and Attribution

- The CLI flag functionality for `-m` / `--merge`, `-i` / `--include`, and `-e` / `--exclude` was adapted from [gitingest](https://github.com/coderamp-labs/gitingest), an excellent reference implementation for packing a directory tree into a single LLM-friendly text blob. `hammerdown` adapts those ideas to document conversion.
- PDF, EPUB, MOBI, FB2, and XPS conversion is powered by [PyMuPDF](https://pymupdf.readthedocs.io/) and [PyMuPDF4LLM](https://github.com/pymupdf/PyMuPDF4LLM). This is the central feature the project was built around.
- Office documents are parsed with [python-docx](https://python-docx.readthedocs.io/), [openpyxl](https://openpyxl.readthedocs.io/), and [python-pptx](https://python-pptx.readthedocs.io/).

## Documentation links

For additional guides and specifications:

- [Python API Reference](docs/PYTHON.md) -- complete guide to Python library methods
- [Technical Reference](docs/TECHNICAL.md) -- internal format processing and parser details
- [Architecture](docs/ARCHITECTURE.md) -- system layers and Mermaid pipeline diagram
- [Performance & Estimation Model](docs/PERFORMANCE.md) -- conversion benchmarks, multi-threading architecture, and ETA model
- [Contributing Guidelines](CONTRIBUTING.md) -- development setup and testing guidelines
