Skip to content

utils

Class info

🛈 DocStrings

Small helpers around conversion: front matter, title extraction, sanitizing.

extract_title

extract_title(html: str) -> str | None

Return the text of the first <h1> in html, or None if there is none.

Markup inside the heading (emphasis, permalink anchors) is dropped and entities are unescaped.

Source code in src/mkconvert/utils.py
def extract_title(html: str) -> str | None:
    """Return the text of the first `<h1>` in `html`, or `None` if there is none.

    Markup inside the heading (emphasis, permalink anchors) is dropped and entities
    are unescaped.
    """
    parser = _TitleParser()
    parser.feed(html)
    parser.close()
    if not parser.done and not parser.in_h1:
        return None
    return " ".join("".join(parser.parts).split())

sanitize

sanitize(
    html: str, *, extra_attributes: Mapping[str, Set[str]] | None = None, **nh3_options: Any
) -> str

Sanitize HTML with nh3 (needs the nh3 extra).

Uses nh3's safe defaults, which drop e.g. id and class attributes (heading ids, code block languages). Allow them again with extra_attributes.

Parameters:

Name Type Description Default
html str

HTML to clean.

required
extra_attributes Mapping[str, Set[str]] | None

Attributes to allow in addition to the allowed ones, per tag; the key "*" means all tags, e.g. {"*": {"id", "class"}}.

None
nh3_options Any

Keyword arguments for nh3.clean, e.g. tags, attributes, url_schemes, link_rel.

{}
Source code in src/mkconvert/utils.py
def sanitize(
    html: str,
    *,
    extra_attributes: Mapping[str, AbstractSet[str]] | None = None,
    **nh3_options: Any,
) -> str:
    """Sanitize HTML with [nh3](https://github.com/messense/nh3) (needs the `nh3` extra).

    Uses nh3's safe defaults, which drop e.g. `id` and `class` attributes (heading ids,
    code block languages). Allow them again with `extra_attributes`.

    Args:
        html: HTML to clean.
        extra_attributes: Attributes to allow in addition to the allowed ones, per tag;
            the key `"*"` means all tags, e.g. `{"*": {"id", "class"}}`.
        nh3_options: Keyword arguments for `nh3.clean`, e.g. `tags`, `attributes`,
            `url_schemes`, `link_rel`.
    """
    try:
        import nh3
    except ImportError as e:
        msg = "sanitize() needs 'nh3'. Install it with: pip install 'mkconvert[nh3]'"
        raise MissingDependencyError(msg) from e

    if extra_attributes:
        base_attributes = nh3_options.get("attributes")
        if base_attributes is None:
            base_attributes = nh3.ALLOWED_ATTRIBUTES
        attributes = {k: set(v) for k, v in base_attributes.items()}
        for tag, names in extra_attributes.items():
            attributes[tag] = attributes.get(tag, set()) | set(names)
        nh3_options["attributes"] = attributes
    return nh3.clean(html, **nh3_options)

split_front_matter

split_front_matter(text: str) -> tuple[str | None, str]

Split a leading ----delimited front matter block off text.

The block may end with --- or .... It is returned unparsed (usually YAML).

Returns:

Type Description
tuple[str | None, str]

(front_matter, body); front_matter is None if there is none.

Source code in src/mkconvert/utils.py
def split_front_matter(text: str) -> tuple[str | None, str]:
    """Split a leading `---`-delimited front matter block off `text`.

    The block may end with `---` or `...`. It is returned unparsed (usually YAML).

    Returns:
        `(front_matter, body)`; `front_matter` is `None` if there is none.
    """
    if match := _FRONT_MATTER.match(text):
        return match.group(1) or "", text[match.end() :]
    return None, text