AsciiDoc Defs

This script collects named HTTPS links from AsciiDoc files in the current directory and writes an index called useful_links.adoc. For example, running python extract_adoc_defs.py contents adds a link back to contents.html at the top of the index.

from __future__ import annotations

import re
import sys
from collections import defaultdict
from pathlib import Path

Rendering the index

Sorting by the case-folded name orders entries within each section while preserving their original spelling for display. The uppercase initial supplies the section heading, so names beginning with a digit or punctuation also have a place in the index.

Each heading is ordinary AsciiDoc so it can appear in the table of contents. Its list is an HTML passthrough block so each anchor can specify target="_blank".

def build_output(definitions: list[tuple[str, str]]) -> str:
    grouped: dict[str, list[tuple[str, str]]] = defaultdict(list)

    for def_name, url in sorted(definitions, key=lambda item: item[0].casefold()):
        first_letter = def_name[:1].upper()
        grouped[first_letter].append((def_name, url))

    lines: list[str] = []

    for letter in sorted(grouped.keys()):
        lines.append(f"=== {letter}")
        lines.append("")
        lines.append("++++")
        lines.append("<ul>")
        for def_name, url in grouped[letter]:
            lines.append(f'<li><a href="{url}" target="_blank">{def_name}</a></li>')
            lines.append("")
        lines.append("</ul>")
        lines.append("++++")

    def_list = "\n".join(lines).rstrip()
    return f"""= Useful Links
:toc: left

link:{content_link}.html[<Contents>]

---

{def_list}
"""