From 2192c2ebc77b7c3d205c8903f04df73d978d0240 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=B0brahim=20Sait=20Akar=C3=A7e=C5=9Fme?= <72226290+saitakarcesme@users.noreply.github.com> Date: Tue, 22 Sep 2026 03:54:26 +0200 Subject: [PATCH] Document tag_callback arguments and return behavior --- AUTHORS.rst | 1 + ChangeLog.rst | 5 +++++ docs/usage.md | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/AUTHORS.rst b/AUTHORS.rst index 5b3ac10..4ed3519 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -40,6 +40,7 @@ The AUTHORS/Contributors are (and/or have been): * Edward Ross * Gregory Anders * Alex Vandiver +* İbrahim S. Akarçeşme Maintainer: diff --git a/ChangeLog.rst b/ChangeLog.rst index 2d96e3b..48bdd88 100644 --- a/ChangeLog.rst +++ b/ChangeLog.rst @@ -1,3 +1,8 @@ +Unreleased +========== + +* Document the ``tag_callback`` hook and its return value (#432). + 2025.4.15 ========= ---- diff --git a/docs/usage.md b/docs/usage.md index 3bef7f8..5cac341 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -111,6 +111,43 @@ To alter any option the procedure is to create a parser with example: `parser.unicode_snob = True` to set the UNICODE_SNOB option. +Custom tag handling +------------------- + +Assign a callable to an `HTML2Text` instance's `tag_callback` attribute to +customize tag handling. It is called as `callback(converter, tag, attrs, start)`: + +- `converter` is the `HTML2Text` instance. +- `tag` is the tag name, such as `"b"` or `"a"`. +- `attrs` is a dictionary of attributes (values may be `None`); it is empty + for closing tags. +- `start` is `True` for an opening tag and `False` for a closing tag. + +Return exactly `True` to skip the converter's default handling of that tag. +Returning `False` or `None` allows normal handling to continue. Skipping a tag +does not skip its text or child tags, which are processed separately. + +For example, omit bold formatting while retaining the enclosed text and other +formatting: + +```python +import html2text + + +def skip_bold(converter, tag, attrs, start): + return tag in ("b", "strong") + + +converter = html2text.HTML2Text() +converter.tag_callback = skip_bold +text = converter.handle("Bold and italic.") +assert text == "Bold and _italic_.\n\n" +``` + +The callback handles both opening and closing bold tags. Set `tag_callback` +back to `None` to restore default tag handling. + + Command line options --------------------