Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

157 KB
Raw Blame
"""Citation formatter for adding hyperlinks and alternative citation styles."""

import html
import re
import unicodedata
import urllib.parse
from array import array
from enum import Enum
from html.entities import html5
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse, urlsplit, urlunsplit

from loguru import logger
from slugify import slugify

from ..content_fetcher.url_classifier import URLClassifier, URLType

# Schemes a citation may carry into a markdown link. An allowlist rather than a
# list of known-bad schemes: the formatter's job here is deciding what may be
# rendered, and `javascript:`, `data:`, `vbscript:`, `blob:` and whatever comes
# next all fail the same test without having to be enumerated. A relative URL
# stays allowed, because a library document is cited as `/library/...`. A
# destination that only looks scheme-less is still checked: its HTML-character-
# reference-decoded form must pass too (`javascript:` renders as a live
# `javascript:` href), and one that names a host (`//host/x`) is refused.
_LINKABLE_URL_SCHEMES = frozenset({"http", "https"})

# A scheme check alone is not enough. The destination is interpolated into
# `](...)`, so anything markdown would read as the end of that destination
# lets a source URL reopen markdown and write its own link past the gate.
# Percent-encoding keeps the link resolvable, since a server decodes `%20`
# back to a space. `[` and `]` are deliberately NOT encoded: they do not end a
# destination, and encoding them would break IPv6 literals (`http://[::1]/x`).
_DESTINATION_ESCAPES = {
    " ": "%20",
    "<": "%3C",
    ">": "%3E",
    '"': "%22",
    "'": "%27",
    "\\": "%5C",
    "`": "%60",
}

# Parentheses are the exception, and they are why this is two tables rather
# than one. CommonMark ends a bare destination at the first *unbalanced* `)`
# and carries balanced pairs through unharmed, so encoding them unconditionally
# rewrites ordinary URLs that nothing was wrong with -- Wikipedia alone titles
# thousands of articles `..._(disambiguation)` -- and the reader is shown a URL
# that is not the one the source served. A balanced destination is therefore
# left verbatim, and only an unbalanced one is encoded, which is exactly the
# case that would otherwise end early.
_PARENTHESIS_ESCAPES = {"(": "%28", ")": "%29"}


def _parentheses_are_balanced(url: str) -> bool:
    """Whether markdown will carry every `(`/`)` in ``url`` inside the link."""
    depth = 0
    for character in url:
        if character == "(":
            depth += 1
        elif character == ")":
            depth -= 1
            if depth < 0:
                return False
    return depth == 0


def _destination_is_refused(form: str) -> bool:
    """Whether one spelling of a destination fails the control or scheme rule."""
    if any(
        ord(character) < 0x20 or ord(character) == 0x7F for character in form
    ):
        return True
    try:
        scheme = urlsplit(form).scheme
    except ValueError:
        return True
    if scheme:
        return scheme not in _LINKABLE_URL_SCHEMES
    # No scheme reads as relative, except where a browser takes the host from
    # it: `//host/x`, and equally `///host/x` or `/\host/x`, which it resolves
    # the same way and ``urlsplit`` does not. Rendered from a file on disk,
    # an exported report resolves it to `file://host/x`.
    return form.lstrip().replace("\\", "/").startswith("//")


def _authority_head_has_userinfo(netloc: str, path: str) -> bool:
    """Whether a linkable-scheme URL spells its authority without ``//``.

    WHATWG-consuming renderers read ``https:user:[email protected]/x`` — and
    its ``https:/``, ``https:///`` and ``https:\\`` spellings — as the
    authority ``user:[email protected]``: any run of slashes or backslashes
    stands in for the ``//``. ``urlsplit`` populates ``netloc`` only for the
    ``//``-delimited form, so an @-in-netloc test alone lets those spellings
    keep their userinfo. The authority-ish head — what follows the scheme,
    past leading slashes or backslashes, up to the first ``/``, ``?`` or
    ``#`` — is where those parsers read it; an @ there is treated as a
    credential. An @ further along (``.../@author/...``, ``?q=a@b``) never
    lands in it.

    The head is rebuilt from the ``netloc`` and ``path`` that ``urlsplit``
    parsed, never cut out of the input at the scheme's length. ``urlsplit``
    drops leading spaces and C0 controls, and every tab and newline, before
    it reads the scheme, as a browser does. ``&#32;https:/user:pass@host``
    decodes to a leading space and then the URL, so a cut at
    ``len("https") + 1`` started on the ``:``, found no ``@`` before the
    next ``/``, and let the credential through. ``?`` and ``#`` need no
    search here: ``urlsplit`` has already split them off.
    """
    rest = f"//{netloc}{path}" if netloc else path
    head = rest.strip().lstrip("/\\").partition("/")[0]
    return "@" in head


def _spells_hidden_userinfo(candidate: str) -> bool:
    """Whether a raw or entity-decoded reading of ``candidate`` hides userinfo.

    Consulted after stripping literal userinfo, so every reading that finds
    an @ is a spelling the plain parse missed:
    an authority not delimited by ``//``, or one assembled by rendered HTML
    entities — ``https&#58;//user:pass@host`` breaks the scheme token, parses
    as scheme-less, and decodes into a live credential URL in a browser.

    A reading that ``urlsplit`` rejects counts as hiding userinfo, just as
    ``_destination_is_refused`` refuses one: the guard cannot vouch for what
    it cannot parse. Stripping can produce such a reading.
    ``https://[@v1.u:p]&#64;v1.example/`` parses, but its userinfo is the
    ``[`` before the first ``@``, and once that is removed what is left has
    an unbalanced ``]``, which ``urlsplit`` rejects. A browser still decodes
    that remainder into ``https://v1.u:p]@v1.example/``, whose userinfo is
    ``v1.u:p]``.
    """
    try:
        parsed = urlsplit(candidate)
    except ValueError:
        return True
    if (
        parsed.scheme in _LINKABLE_URL_SCHEMES
        and "@" not in parsed.netloc
        and _authority_head_has_userinfo(parsed.netloc, parsed.path)
    ):
        return True
    decoded = html.unescape(candidate)
    if decoded == candidate:
        return False
    try:
        cooked = urlsplit(decoded)
    except ValueError:
        return True
    return cooked.scheme in _LINKABLE_URL_SCHEMES and (
        "@" in cooked.netloc
        or _authority_head_has_userinfo(cooked.netloc, cooked.path)
    )


def _safe_link_destination(url: str) -> str:
    """Return ``url`` ready to be interpolated into ``](...)``, or "" to refuse.

    Four things have to hold, and what comes back is the string that was
    checked rather than the one that came in:

    1. No control character survives. ``urlsplit`` removes tabs and newlines
       and strips leading C0 controls only in order to *parse*; they stay in
       the string. A destination carrying a newline ends there and the rest is
       emitted as document body. NUL is not stripped at all, so
       ``java\x00script:`` parses as scheme-less and would otherwise pass.
    2. The scheme is ``http``, ``https``, or absent. Looser than
       ``CitationFormatter._is_linkable_url``, which requires a scheme and is
       what SOURCE_TAGGED uses to decide whether to render a link at all; the
       other modes keep linking the relative URLs a library document uses. A
       scheme-less destination that names a host (``//host/x``) is refused.
    3. HTTP userinfo is removed before the URL reaches a report or export.
       It is a credential even when the destination itself is otherwise
       safe, and it is refused rather than stripped when it is spelled
       where the plain parser does not look — an authority not delimited
       by ``//``, or one assembled from HTML entities — or when what is
       left once it is removed no longer parses.
    4. What markdown would read as syntax is percent-encoded, so the gate
       cannot be walked around by ending the destination early.

    Rules 1 and 2 are checked on the character-reference-decoded form too.
    marked and Python-Markdown copy the destination into ``href`` as written,
    and the HTML parser then decodes ``javascript&colon;alert(1)`` into a live
    ``javascript:`` URL. The decoded form is only checked, never emitted:
    rewriting ``&`` would break every query string with more than one
    parameter.

    The rendered markdown reaches the browser through DOMPurify, which strips a
    ``javascript:`` href before it reaches the DOM. That is one layer, and it is
    the only one today: an exported .md / .qmd / .tex and every other markdown
    consumer gets whatever this returns.

    A refused destination leaves the citation unlinked rather than dropping
    it: callers treat an empty URL as no URL, so the citation stays a plain
    ``[N]`` bracket, or an unlinked tag such as ``[local-N]`` in
    SOURCE_TAGGED mode.
    """
    candidate = url.strip()
    if not candidate:
        return ""
    if _destination_is_refused(candidate) or _destination_is_refused(
        html.unescape(candidate)
    ):
        return ""
    parsed = urlsplit(candidate)
    if parsed.scheme in _LINKABLE_URL_SCHEMES and "@" in parsed.netloc:
        # A parseable authority keeps its host and loses its userinfo.
        host = parsed.netloc.rpartition("@")[2]
        if not host:
            return ""
        candidate = urlunsplit(parsed._replace(netloc=host))
    if _spells_hidden_userinfo(candidate):
        # The userinfo is spelled where the plain parse does not look —
        # without the ``//``, or through HTML entities that a rendered
        # link decodes back into a live credential URL — or what is left
        # no longer parses. Refuse rather than emit it.
        return ""
    escapes = dict(_DESTINATION_ESCAPES)
    if not _parentheses_are_balanced(candidate):
        escapes.update(_PARENTHESIS_ESCAPES)
    return "".join(escapes.get(character, character) for character in candidate)


# Marker emitted by ``IntegratedReportGenerator._format_final_report``
# around the ``## Sources`` block it appends to the end of a detailed-mode
# report. Looked up by ``find_sources_section`` so the splitter can locate
# the appended sources section unambiguously, even when the LLM has
# emitted its own ``## Sources`` (or ``References:`` etc.) header earlier
# in the prose. The sentinel is an HTML comment, and renderMarkdown()
# (services/ui.js) shows raw HTML in Markdown as literal text, so it must
# not reach displayed report text: ``strip_appended_sources_sentinel``
# removes it when a detailed report is saved, when a saved report is
# assembled for display or export, and from news-feed findings.
LDR_APPENDED_SOURCES_SENTINEL = "<!-- LDR_APPENDED_SOURCES_START -->"

_SOURCES_SECTION_PATTERNS = [
    re.compile(
        r"^#{1,3}\s*(?:Sources|References|Bibliography|Citations)",
        re.MULTILINE | re.IGNORECASE,
    ),
    re.compile(
        r"^(?:Sources|References|Bibliography|Citations):?\s*$",
        re.MULTILINE | re.IGNORECASE,
    ),
]


def find_sources_section(
    content: str, *, trust_sentinel: bool = True
) -> Tuple[int, bool]:
    """Locate the sources/references section in *content*.

    Returns ``(position, on_sentinel)``. ``position`` is the character
    offset of the section start, or ``-1`` if no section is found.
    ``on_sentinel`` is ``True`` iff the unique sentinel emitted by the
    report generator was matched (in which case the boundary is correct
    by construction); ``False`` if the position came from the legacy
    regex patterns (which can match an early ``## Sources`` line inside
    the answer body and need an over-strip safety check downstream).

    The sentinel is matched at its **last** occurrence (``rfind``) so a
    spoofed earlier occurrence inside LLM-generated prose — e.g. the
    LLM quoting the marker string verbatim while summarizing the
    codebase — cannot silently truncate the answer body or disable the
    over-strip safety check. Only a sentinel on its own line is trusted;
    inline occurrences are skipped while searching backwards. The report
    generator only ever emits the sentinel once at the end of the assembled
    report, so the last standalone occurrence is the trusted one.

    When ``trust_sentinel`` is ``False`` (e.g. raw LLM output from the
    quick-mode save path, which never adds the sentinel itself), the
    sentinel branch is skipped — only the legacy regex patterns run, so
    a spurious ``on_sentinel=True`` cannot arise from the LLM quoting
    the marker.
    """
    if trust_sentinel:
        sentinel_pos = content.rfind(LDR_APPENDED_SOURCES_SENTINEL)
        while sentinel_pos != -1:
            preceded = sentinel_pos == 0 or content[sentinel_pos - 1] in (
                "\n",
                "\r",
            )
            after = content[sentinel_pos + len(LDR_APPENDED_SOURCES_SENTINEL) :]
            followed = not after or after[0] in ("\n", "\r")
            if preceded and followed:
                return sentinel_pos, True
            sentinel_pos = content.rfind(
                LDR_APPENDED_SOURCES_SENTINEL, 0, sentinel_pos
            )
    for pattern in _SOURCES_SECTION_PATTERNS:
        match = pattern.search(content)
        if match:
            return match.start(), False
    return -1, False


def strip_appended_sources_sentinel(content: str) -> str:
    """Remove the report generator's appended-sources sentinel from *content*.

    Only the occurrence ``find_sources_section`` trusts is removed: the last
    one that stands on its own line, which is the one
    ``IntegratedReportGenerator`` emitted. The line breaks around it are kept.
    A copy quoted inside a line, or an earlier one, is report text and is
    left as written.

    The sentinel is an HTML comment. renderMarkdown() (services/ui.js) shows
    raw HTML in Markdown as literal text, so a sentinel left in report text
    would appear on the page. The detailed-mode save site keeps the whole
    report, Sources block and sentinel included, in
    ``CitationMode.NO_HYPERLINKS`` mode and when the citation formatter
    raises; it now removes the sentinel before saving, and reports saved
    that way earlier still contain it.

    Anything that is not a non-empty string is returned unchanged.
    """
    if not isinstance(content, str) or not content:
        return content
    sentinel_start, on_sentinel = find_sources_section(content)
    if not on_sentinel:
        return content
    return (
        content[:sentinel_start]
        + content[sentinel_start + len(LDR_APPENDED_SOURCES_SENTINEL) :]
    )


_BIB_SOURCES_PATTERN = re.compile(
    r"^\[(\d+(?:\s*,\s*\d+)*)\]\s*(.+?)(?:\n\s*URL:\s*(.+?))?$",
    re.MULTILINE,
)


# Single-pass character map. A sequential replace() chain would re-escape
# the braces its own replacements introduce — the same class of bug that
# _escape_latex_text's single regex pass avoids below, where "\\" becomes
# "\textbackslash{}" without a later brace rule mangling it again.
_BIBTEX_ESCAPES = {
    "\\": r"\textbackslash{}",
    # Balanced pairs, not backslash escapes: BibTeX's field scanner counts
    # brace CHARACTERS and has no escape mechanism, so "\{" is still an open
    # brace to it. A backslashed brace left the value unbalanced, and the
    # scanner ran to EOF swallowing the rest of the .bib.
    "{": r"{\textbraceleft}",
    "}": r"{\textbraceright}",
    "&": r"\&",
    "%": r"\%",
    "$": r"\$",
    "#": r"\#",
    "_": r"\_",
    "~": r"\textasciitilde{}",
    "^": r"\textasciicircum{}",
    '"': "'",
}


# U+0085 NEL already falls inside the 0x7F-0x9F range below; only these two
# separators sit outside it.
_UNICODE_LINE_SEPARATORS = "\u2028\u2029"


def is_line_breaking_char(char: str) -> bool:
    """True if *char* can begin a new line for some consumer of our output.

    ONE definition, imported by every producer. The recurring bug in this
    area has been fixing one instance and leaving a sibling — CR handled
    but not NEL, the URL sanitised but not the citation index — so the
    union is deliberately wider than any single consumer needs: C0 and DEL
    for everything, C1 because such a codepoint is never legitimate text,
    and U+2028/U+2029 because CSS Text makes them mandatory breaks in
    rendered HTML even though Python's ``re`` and ``str.splitlines()``
    ignore them.

    Imported by ``search_utilities._sanitize_sources_field``;
    ``test_bibliography_escaping`` asserts the two agree on every BMP
    codepoint, so the claim cannot rot into a comment again.
    """
    code = ord(char)
    return (
        code < 0x20 or 0x7F <= code <= 0x9F or char in _UNICODE_LINE_SEPARATORS
    )


def _escape_bibtex(value: str) -> str:
    r"""Escape a value for interpolation into a BibTeX field.

    Titles come from search-result metadata — whatever a page calls itself
    — and were previously written into ``title = "{...}"`` raw. A title
    ending the field and opening another (``Benign}", url = "...", note =
    "{x``) injected an attacker-controlled ``url`` that BibTeX preferred,
    and an unbalanced brace ran the parser on into the rest of the file.
    """
    return "".join(
        # Control characters are flattened, not escaped. The .bib is
        # embedded in a ```bibtex markdown fence by the Quarto exporter,
        # and a bare CR — which ``_BIB_SOURCES_PATTERN``'s ``.`` matches,
        # since only ``\n`` is excluded — closes that fence once a reader
        # normalises CRLF, turning the remainder into live markup.
        # ``_safe_bibtex_url`` already rejects these; this matches it.
        " " if is_line_breaking_char(ch) else _BIBTEX_ESCAPES.get(ch, ch)
        for ch in value
    )


_LATEX_TEXT_SPECIALS: dict[str, str] = {
    "\\": r"\textbackslash{}",
    "&": r"\&",
    "%": r"\%",
    "$": r"\$",
    "#": r"\#",
    "_": r"\_",
    "{": r"\{",
    "}": r"\}",
    "~": r"\textasciitilde{}",
    "^": r"\textasciicircum{}",
}
_LATEX_TEXT_SPECIALS_RE = re.compile(
    "[" + re.escape("".join(_LATEX_TEXT_SPECIALS)) + "]"
)


def _escape_latex_text(text: str) -> str:
    r"""Escape every LaTeX-special character in one pass.

    One regex pass is load-bearing. Sequential ``str.replace`` passes
    re-process their own output: the braces in ``\textbackslash{}`` get
    escaped again and a literal backslash comes out as the invalid
    ``\textbackslash\{\}``. ``re.sub`` never rescans replacement text,
    so each special character is replaced exactly once.
    """
    return _LATEX_TEXT_SPECIALS_RE.sub(
        lambda m: _LATEX_TEXT_SPECIALS[m.group()], text
    )


# Matches the leading '#' markers of an ATX heading so the heading TEXT
# can be escaped while the marker itself survives for the
# heading-conversion pass in export_to_latex.
_HEADING_PREFIX_RE = re.compile(r"^(\s*#+\s+)(.*)$")


def _safe_bibtex_url(value: str) -> str:
    r"""Return *value* if it is safe to place in ``url = {...}``, else "".

    Escaping is wrong for a URL — a ``\%`` would corrupt a percent-encoded
    octet. Nor may the offending characters simply be DROPPED: removing a
    backslash from ``//trusted.example\@evil.example/p`` turns the trusted
    host into userinfo, so the exported link points at a different host
    than the one the reader vetted in the report. A URL containing a
    breakout character is not a URL to repair — it is omitted, and the
    caller falls through to its existing URL-less branch.

    What passes that check then goes through ``_safe_ris_url``, so a BibTeX
    or LaTeX bibliography drops URL userinfo (``user:secret@``) exactly as
    the RIS export does, and omits the URLs RIS omits. Before this the
    credential was re-emitted verbatim in ``url = {...}`` and ``\url{...}``.
    """
    if any(ch in '{}"\\ ' or is_line_breaking_char(ch) for ch in value):
        # Local-document sources legitimately trip this: a LangChain
        # retriever sets a result's url from its ``source`` metadata, which
        # is often a filesystem path carrying spaces or backslashes.
        # Dropping the link silently would leave the user guessing why a
        # bibliography entry has none, so record it.
        # Truncated: a hostile result can carry a megabyte-long URL, and
        # this fires once per affected entry — and the Quarto exporter
        # builds the bibliography twice per export, so it fires twice per
        # entry in practice. ``!r`` keeps control characters escaped.
        logger.debug(
            "Omitting unsafe bibliography URL: {!r}{}",
            value[:200],
            "…" if len(value) > 200 else "",
        )
        return ""
    return _safe_ris_url(value)


def _iter_citation_group(group: str):
    r"""Yield each index on one Sources line (``"1, 2, 3"`` -> "1", "2", "3").

    ``format_links_to_markdown`` collapses every citation of one source
    onto a single line carrying all of its indices, so a single-index
    pattern drops such a source from the bibliography entirely. Exporters
    emit one entry per index so each ``[N]`` in the body resolves.

    Indices are yielded as STRINGS, exactly as written: the body citations
    are rewritten from the same text, so converting ``007`` to ``7`` here
    would key the entry ``ref7`` while the body still cites ``ref007``.
    No digit filtering either — the pattern's ``\d`` matches only decimal
    digits (category ``Nd``), which ``int()`` always accepts, so filtering
    could only discard valid indices such as Arabic-Indic ones.
    """
    for part in group.split(","):
        part = part.strip()
        if part:
            yield part


def _sort_key(index: str):
    """Order bibliography entries numerically where possible."""
    try:
        return (0, int(index), "")
    except ValueError:
        return (1, 0, index)


def _collect_bibliography_entries(content: str) -> dict:
    """Map each citation index to the ``(title, url)`` it names.

    Selection rule: a URL-bearing entry never loses to a URL-less one, and
    among URL-bearing entries the LATER occurrence wins.

    Both halves matter. A report repeats its Sources block once per section
    and then again as a combined block, and the combined block is both last
    and authoritative — so later-wins. And the group-aware pattern can match
    a line of prose that opens with ``[1, 2]`` where a single-index pattern
    could not; such a line carries no ``URL:``, whereas every line
    ``format_links_to_markdown`` renders does, so the URL preference is what
    keeps prose from taking a citation key.

    Deliberately NOT scoped to a Sources section. Bounding the block at
    markers like ``\n---`` looked safer but silently emptied the
    bibliography whenever a thematic break, a setext underline or a table
    delimiter row came first — while the body was still rewritten to cite
    entries that no longer existed.
    """
    entries: dict[str, tuple[str, str]] = {}
    for match in _BIB_SOURCES_PATTERN.finditer(content):
        title = match.group(2).strip()
        url = match.group(3).strip() if match.group(3) else ""
        for index in _iter_citation_group(match.group(1)):
            # Prefer an entry carrying a URL: a real Sources line has one,
            # a prose false positive does not.
            if url or index not in entries:
                entries[index] = (title, url)
    return entries


class CitationMode(Enum):
    """Available citation formatting modes."""

    NUMBER_HYPERLINKS = "number_hyperlinks"  # [1] with hyperlinks
    DOMAIN_HYPERLINKS = "domain_hyperlinks"  # [arxiv.org] with hyperlinks
    DOMAIN_ID_HYPERLINKS = (
        "domain_id_hyperlinks"  # [arxiv.org] or [arxiv.org-1] with smart IDs
    )
    DOMAIN_ID_ALWAYS_HYPERLINKS = (
        "domain_id_always_hyperlinks"  # [arxiv.org-1] always with IDs
    )
    SOURCE_TAGGED_HYPERLINKS = "source_tagged_hyperlinks"
    """Preserve the global citation number and prefix it with a short source
    tag derived from the URL: known academic sources via ``URLClassifier``
    (``arxiv-7``, ``pubmed-3``), domain otherwise (``nytimes.com-9``), and
    ``local-N`` for empty / local URLs. Unlike DOMAIN_ID_* modes the
    suffix is the original citation number, so labels never collide and
    match the bibliography order: ``[1]`` arxiv + ``[2]`` openai + ``[3]``
    arxiv -> ``arxiv-1``, ``openai-2``, ``arxiv-3``."""
    NO_HYPERLINKS = "no_hyperlinks"  # [1] without hyperlinks


class CitationFormatter:
    """Formats citations in markdown documents with various styles."""

    def __init__(self, mode: CitationMode = CitationMode.NUMBER_HYPERLINKS):
        self.mode = mode
        # Use negative lookbehind and lookahead to avoid matching already formatted citations
        # Also match Unicode lenticular brackets 【】 (U+3010 and U+3011) that LLMs sometimes generate
        self.citation_pattern = re.compile(
            r"(?<![\[【])[\[【](\d+)[\]】](?![\]】])"
        )
        self.comma_citation_pattern = re.compile(
            r"[\[【](\d+(?:\s*,\s*\d+)+)[\]】]"  # (#6944) space allowed BEFORE the comma too — a hand-edited `[[2 ,3]]` must stay a group
        )
        # Also match "Source X" or "source X" patterns
        self.source_word_pattern = re.compile(r"\b[Ss]ource\s+(\d+)\b")
        self.sources_pattern = re.compile(
            r"^\[(\d+(?:\s*,\s*\d+)*)\]\s*(.+?)(?:\n\s*URL:\s*(.+?))?$",
            re.MULTILINE,
        )

    def _create_source_word_replacer(self, formatter_func):
        """Create a replacement function for 'Source X' patterns.

        Args:
            formatter_func: A function that takes citation_num and returns formatted text

        Returns:
            A replacement function for use with regex sub
        """

        def replace_source_word(match):
            citation_num = match.group(1)
            return formatter_func(citation_num)

        return replace_source_word

    def _create_citation_formatter(self, sources_dict, format_pattern):
        """Create a formatter function for citations.

        Args:
            sources_dict: Dictionary mapping citation numbers to data
            format_pattern: A callable that takes (citation_num, data) and returns formatted string

        Returns:
            A function that formats citations or returns fallback
        """

        def formatter(citation_num):
            if citation_num in sources_dict:
                data = sources_dict[citation_num]
                return format_pattern(citation_num, data)
            return f"[{citation_num}]"

        return formatter

    def _replace_comma_citations(self, content, lookup, format_one):
        """Replace comma-separated citations like [1, 2, 3] using *lookup* and *format_one*.

        Args:
            content: Text to process
            lookup: Dict mapping citation number (str) to data
            format_one: ``(num, data) -> str`` callback that formats a single citation
        """

        def _replacer(match):
            nums = [n.strip() for n in match.group(1).split(",")]
            parts = []
            for num in nums:
                if num in lookup:
                    parts.append(format_one(num, lookup[num]))
                else:
                    parts.append(f"[{num}]")
            return "".join(parts)

        return self.comma_citation_pattern.sub(_replacer, content)

    def format_document(self, content: str) -> str:
        """Format citations in *content* and return the full document.

        This is the legacy single-string entry point: it concatenates
        the answer half and the sources half produced by
        :meth:`format_document_split`. New code that needs to know
        where the boundary between answer and sources actually fell
        should use :meth:`format_document_split` instead so the boundary
        is returned explicitly (no re-parsing of the concatenated output).
        """
        formatted_answer, sources_md, _on_sentinel = self.format_document_split(
            content
        )
        return formatted_answer + sources_md

    def format_document_split(
        self, content: str, *, trust_sentinel: bool = True
    ) -> Tuple[str, str, bool]:
        """Format citations and return ``(answer, sources_md, on_sentinel)``.

        The boundary between the LLM's answer and the trailing Sources
        section is computed inside this method. Callers that only want
        the answer (e.g. the chat-mode save site) get a clean split
        without re-applying a regex on concatenated output downstream.
        ``on_sentinel`` mirrors the second element of
        :func:`find_sources_section`'s return — ``True`` iff the split
        boundary came from the appended-sources sentinel emitted by
        ``IntegratedReportGenerator``, in which case the boundary is
        correct by construction and downstream over-strip safety checks
        should be skipped. Pass ``trust_sentinel=False`` for raw LLM
        output (quick-mode save path) where the sentinel would only
        appear if the LLM quoted the marker itself.

        Returns ``(content, "", False)`` when the formatter is in
        NO_HYPERLINKS mode or when no Sources section can be found in
        ``content``.
        """
        if self.mode == CitationMode.NO_HYPERLINKS:
            return content, "", False

        sources_start, on_sentinel = find_sources_section(
            content, trust_sentinel=trust_sentinel
        )
        if sources_start == -1:
            return content, "", False

        document_content = content[:sources_start]
        sources_content = content[sources_start:]

        sources = self._parse_sources(sources_content)

        if self.mode == CitationMode.NUMBER_HYPERLINKS:
            formatted_content = self._format_number_hyperlinks(
                document_content, sources
            )
        elif self.mode == CitationMode.DOMAIN_HYPERLINKS:
            formatted_content = self._format_domain_hyperlinks(
                document_content, sources
            )
        elif self.mode == CitationMode.DOMAIN_ID_HYPERLINKS:
            formatted_content = self._format_domain_id_hyperlinks(
                document_content, sources
            )
        elif self.mode == CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS:
            formatted_content = self._format_domain_id_always_hyperlinks(
                document_content, sources
            )
        elif self.mode == CitationMode.SOURCE_TAGGED_HYPERLINKS:
            formatted_content = self._format_source_tagged_hyperlinks(
                document_content,
                sources,
                self._parse_collections(sources_content),
            )
        else:
            formatted_content = document_content

        return formatted_content, sources_content, on_sentinel

    def apply_inline_hyperlinks(
        self, content: str, sources: List[Dict[str, Any]]
    ) -> str:
        """Hyperlink ``[N]`` refs using a structured source list.

        Dispatches on ``self.mode`` so the user's chosen citation
        format (Settings → Report → Citation Format) is honored on
        the fallback path the same way it is in
        :meth:`format_document_split`. Inherits all the existing
        per-mode guards (lookbehind/lookahead against ``[[1]]``,
        comma-list handling like ``[1,2,3]``, ``Source N`` word form,
        missing-index pass-through, lenticular bracket support).

        Used as the safe fallback at save time when the LLM does NOT
        emit a Sources section in its prose — the structured source
        list (e.g. ``search_system.all_links_of_system``) is the
        canonical source of URLs and indices.
        """
        if not content or not sources:
            return content or ""
        if self.mode == CitationMode.NO_HYPERLINKS:
            return content

        # Search-engine result dicts use either "url" or "link" for the
        # destination — Searxng emits {"link": ..., "title": ..., "snippet": ...}
        # (search_engine_searxng.py:538) and other engines use "url".
        # Looking up only `s["url"]` silently dropped every Searxng-sourced
        # citation, leaving the answer body with plain `[N]` brackets even
        # though the Sources section beneath was fully populated. Accept
        # both keys so the hyperlink fallback works regardless of engine.
        def _src_url(s):
            return _safe_link_destination(s.get("url") or s.get("link") or "")

        adapted: Dict[str, Tuple[str, str]] = {}
        for source in sources:
            destination = _src_url(source)
            if destination and source.get("index") is not None:
                adapted[str(source["index"])] = (
                    source.get("title", "Untitled"),
                    destination,
                )
        if not adapted:
            return content

        # Per-mode dispatch — mirrors format_document_split so the user's
        # chosen citation format applies on this fallback path too.
        # Previously this was hard-coded to _format_number_hyperlinks,
        # which meant chat-mode answers (which always hit this fallback
        # because the langgraph-agent synthesis doesn't emit a ## Sources
        # block in its prose) ignored the report.citation_format setting
        # entirely — every chat answer came out as [[N]](url) even when
        # the user picked domain-based or source-tagged formatting.
        if self.mode == CitationMode.DOMAIN_HYPERLINKS:
            return self._format_domain_hyperlinks(content, adapted)
        if self.mode == CitationMode.DOMAIN_ID_HYPERLINKS:
            return self._format_domain_id_hyperlinks(content, adapted)
        if self.mode == CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS:
            return self._format_domain_id_always_hyperlinks(content, adapted)
        if self.mode == CitationMode.SOURCE_TAGGED_HYPERLINKS:
            # Pull collection names off the structured source dicts
            # (format_links_to_markdown uses the same shape:
            # link["metadata"]["collection_name"]) so the SOURCE_TAGGED
            # formatter can surface library/RAG tags as the citation
            # label when present.
            collections: Dict[str, str] = {}
            for s in sources:
                idx = s.get("index")
                if idx is None:
                    continue
                meta = s.get("metadata") or {}
                coll = meta.get("collection_name")
                if coll:
                    collections.setdefault(str(idx), str(coll))
            return self._format_source_tagged_hyperlinks(
                content, adapted, collections
            )
        # NUMBER_HYPERLINKS is the default and the catch-all for any
        # mode added later that doesn't have an explicit branch above.
        return self._format_number_hyperlinks(content, adapted)

    def _find_sources_section(
        self, content: str, trust_sentinel: bool = True
    ) -> Tuple[int, bool]:
        """Find the start of the sources/references section.

        Returns ``(position, on_sentinel)`` — see
        :func:`find_sources_section` for the semantics. ``on_sentinel``
        is True iff the boundary came from the unique sentinel emitted
        by the report generator (i.e. it is correct by construction).
        """
        return find_sources_section(content, trust_sentinel=trust_sentinel)

    def _parse_sources(
        self, sources_content: str
    ) -> Dict[str, Tuple[str, str]]:
        """
        Parse sources section to extract citation numbers, titles, and URLs.

        Returns:
            Dictionary mapping citation number to (title, url) tuple
        """
        sources = {}
        matches = list(self.sources_pattern.finditer(sources_content))

        for match in matches:
            citation_nums_str = match.group(1)
            title = match.group(2).strip()
            url = _safe_link_destination(match.group(3) or "")

            # Handle comma-separated citation numbers like [36, 3]
            # Split by comma and strip whitespace
            individual_nums = [
                num.strip() for num in citation_nums_str.split(",")
            ]

            # Add an entry for each individual number
            for num in individual_nums:
                sources[num] = (title, url)

        return sources

    def _format_number_hyperlinks(
        self, content: str, sources: Dict[str, Tuple[str, str]]
    ) -> str:
        """Replace [1] with hyperlinked version where only the number is linked."""
        # Filter sources that have URLs
        url_sources = {
            num: (title, url) for num, (title, url) in sources.items() if url
        }

        # Create formatter for citations with number hyperlinks
        def format_number_link(citation_num, data):
            _, url = data
            return f"[[{citation_num}]]({url})"

        # Handle comma-separated citations like [1, 2, 3]
        content = self._replace_comma_citations(
            content, url_sources, format_number_link
        )

        formatter = self._create_citation_formatter(
            url_sources, format_number_link
        )

        # Handle individual citations
        def replace_citation(match):
            return (
                formatter(match.group(1))
                if match.group(1) in url_sources
                else match.group(0)
            )

        content = self.citation_pattern.sub(replace_citation, content)

        # Also handle "Source X" patterns
        return self.source_word_pattern.sub(
            self._create_source_word_replacer(formatter), content
        )

    def _format_domain_hyperlinks(
        self, content: str, sources: Dict[str, Tuple[str, str]]
    ) -> str:
        """Replace [1] with [domain.com] hyperlinked version."""

        # Filter sources that have URLs
        url_sources = {
            num: (title, url) for num, (title, url) in sources.items() if url
        }

        # Pre-compute labels so [1, 2, 3] lists and standalone [N] refs
        # use the same string for a given citation. Previously this
        # closure called _extract_domain on every match, so a relative
        # URL (``/library/document/...``) produced ``[[]]`` for every
        # occurrence. _citation_label falls back to a slugified title
        # for relative URLs, keeping the label non-empty and readable.
        label_cache: Dict[str, str] = {
            num: self._citation_label(num, title, url)
            for num, (title, url) in url_sources.items()
        }

        # Create formatter for citations with domain hyperlinks
        def format_domain_link(citation_num, data):
            _, url = data
            label = label_cache[citation_num]
            return f"[[{label}]]({url})"

        # Handle comma-separated citations like [1, 2, 3]
        content = self._replace_comma_citations(
            content, url_sources, format_domain_link
        )

        formatter = self._create_citation_formatter(
            url_sources, format_domain_link
        )

        # Handle individual citations
        def replace_citation(match):
            return (
                formatter(match.group(1))
                if match.group(1) in url_sources
                else match.group(0)
            )

        content = self.citation_pattern.sub(replace_citation, content)

        # Also handle "Source X" patterns
        return self.source_word_pattern.sub(
            self._create_source_word_replacer(formatter), content
        )

    def _format_domain_id_hyperlinks(
        self, content: str, sources: Dict[str, Tuple[str, str]]
    ) -> str:
        """Replace [1] with [domain.com-1] hyperlinked version with hyphen-separated IDs."""
        # First, create a mapping of domains to their citation numbers.
        # _citation_label (vs raw _extract_domain) means relative URLs
        # like ``/library/document/...`` get a slugified title as the
        # "domain" instead of an empty string. Without this, a RAG
        # result with one citation rendered as ``[[]](url)`` (the
        # label disappeared), and a multi-citation set rendered as
        # ``[[-1]](url)`` (the orphaned ``-N`` suffix leaked through).
        domain_citations: dict[str, list[Any]] = {}

        for citation_num, (title, url) in sources.items():
            if url:
                domain = self._citation_label(citation_num, title, url)
                if domain not in domain_citations:
                    domain_citations[domain] = []
                domain_citations[domain].append((citation_num, url))

        # Create a mapping from citation number to domain with ID
        citation_to_domain_id = {}
        for domain, citations in domain_citations.items():
            if len(citations) > 1:
                # Multiple citations from same domain - add hyphen and number
                for idx, (citation_num, url) in enumerate(citations, 1):
                    citation_to_domain_id[citation_num] = (
                        f"{domain}-{idx}",
                        url,
                    )
            else:
                # Single citation from domain - no ID needed
                citation_num, url = citations[0]
                citation_to_domain_id[citation_num] = (domain, url)

        # Create formatter for citations with domain_id hyperlinks
        def format_domain_id_link(citation_num, data):
            domain_id, url = data
            return f"[[{domain_id}]]({url})"

        # Handle comma-separated citations
        content = self._replace_comma_citations(
            content, citation_to_domain_id, format_domain_id_link
        )

        formatter = self._create_citation_formatter(
            citation_to_domain_id, format_domain_id_link
        )

        # Handle individual citations
        def replace_citation(match):
            return (
                formatter(match.group(1))
                if match.group(1) in citation_to_domain_id
                else match.group(0)
            )

        content = self.citation_pattern.sub(replace_citation, content)

        # Also handle "Source X" patterns
        return self.source_word_pattern.sub(
            self._create_source_word_replacer(formatter), content
        )

    def _format_domain_id_always_hyperlinks(
        self, content: str, sources: Dict[str, Tuple[str, str]]
    ) -> str:
        """Replace [1] with [domain.com-1] hyperlinked version, always with IDs."""
        # Use _citation_label so relative URLs (e.g. RAG /library/document/...
        # results) produce a slugified-title prefix instead of an empty
        # string. Without this, every label here collapses to ``-N``
        # (e.g. ``[[-1]](url)``) and the user has no idea what the link
        # references. See _format_domain_id_hyperlinks for the same fix.
        domain_citations: dict[str, list[Any]] = {}

        for citation_num, (title, url) in sources.items():
            if url:
                domain = self._citation_label(citation_num, title, url)
                if domain not in domain_citations:
                    domain_citations[domain] = []
                domain_citations[domain].append((citation_num, url))

        # Create a mapping from citation number to domain with ID
        citation_to_domain_id = {}
        for domain, citations in domain_citations.items():
            # Always add hyphen and number for consistency
            for idx, (citation_num, url) in enumerate(citations, 1):
                citation_to_domain_id[citation_num] = (f"{domain}-{idx}", url)

        # Create formatter for citations with domain_id hyperlinks
        def format_domain_id_link(citation_num, data):
            domain_id, url = data
            return f"[[{domain_id}]]({url})"

        # Handle comma-separated citations
        content = self._replace_comma_citations(
            content, citation_to_domain_id, format_domain_id_link
        )

        formatter = self._create_citation_formatter(
            citation_to_domain_id, format_domain_id_link
        )

        # Handle individual citations
        def replace_citation(match):
            return (
                formatter(match.group(1))
                if match.group(1) in citation_to_domain_id
                else match.group(0)
            )

        content = self.citation_pattern.sub(replace_citation, content)

        # Also handle "Source X" patterns
        return self.source_word_pattern.sub(
            self._create_source_word_replacer(formatter), content
        )

    # Sources section may carry a "Collection: <name>" line for RAG /
    # library hits (emitted by ``utilities/search_utilities.format_links_to_markdown``).
    # Read one line at a time: overlapping multiline whitespace patterns
    # can repeatedly rescan an entire run of blank lines.
    _collection_header_pattern = re.compile(r"^\[(\d+(?:\s*,\s*\d+)*)\]")

    def _parse_collections(self, sources_content: str) -> Dict[str, str]:
        """Extract ``{citation_num: collection_name}`` from a sources
        block. Returns an empty dict when no ``Collection:`` lines exist
        — the absence of collection info is the common case (web URLs)
        and must never raise."""
        collections: Dict[str, str] = {}
        citation_nums = ()
        for line in sources_content.split("\n"):
            if line.startswith("["):
                match = self._collection_header_pattern.match(line)
                citation_nums = (
                    tuple(_iter_citation_group(match.group(1))) if match else ()
                )
                continue
            field = line.strip()
            if citation_nums and field.startswith("Collection:"):
                collection = field[len("Collection:") :].strip()
                if collection:
                    for num in citation_nums:
                        collections[num] = collection
                    citation_nums = ()
        return collections

    def _format_source_tagged_hyperlinks(
        self,
        content: str,
        sources: Dict[str, Tuple[str, str]],
        collections: Dict[str, str],
    ) -> str:
        """Replace ``[N]`` with ``[[source-N]](url)``.

        ``source`` resolves to (in order): the RAG ``Collection:``
        tag for library hits, the short URLClassifier tag for known
        academic sources (``arxiv``, ``pubmed``, ...), the cleaned
        domain otherwise, or ``local`` for empty/file URLs. ``N`` is
        the original global citation number — labels never collide and
        the suffix always matches the bibliography ordering.

        Args:
            content: Document body (sources section already split off).
            sources: ``{citation_num: (title, url)}`` parsed from the
                sources block.
            collections: ``{citation_num: collection_name}`` parsed from
                optional ``Collection:`` lines in the sources block
                (empty dict when no library/RAG hits are cited). Wins
                over URL-derived tags when present for a given citation.
        """

        # Pre-compute tags so each URL-having source resolves its label
        # once, however many [N] / [1, 2, 3] refs cite it.
        tag_cache: Dict[str, str] = {
            num: self._extract_source_label(
                url, collection=collections.get(num)
            )
            for num, (_, url) in sources.items()
            if url
        }

        def format_link(citation_num, data):
            _, url = data
            label = tag_cache.get(citation_num)
            if label is None:
                # Only URL-less sources are absent from tag_cache. Don't
                # pass this as dict.get()'s default — that would evaluate
                # the expensive lookup eagerly on every cache hit too.
                label = self._extract_source_label(
                    url, collection=collections.get(citation_num)
                )
            tag = f"{label}-{citation_num}"
            # Only emit a hyperlink for http(s) URLs — local/file URLs are
            # rendered as plain bracketed tags so the markdown stays clean
            # and viewers don't try to navigate to a server-local path.
            return (
                f"[[{tag}]]({url})"
                if self._is_linkable_url(url)
                else f"[{tag}]"
            )

        # Handle comma-separated citations like [1, 2, 3]
        content = self._replace_comma_citations(content, sources, format_link)

        formatter = self._create_citation_formatter(sources, format_link)

        # Handle individual citations
        def replace_citation(match):
            return (
                formatter(match.group(1))
                if match.group(1) in sources
                else match.group(0)
            )

        content = self.citation_pattern.sub(replace_citation, content)

        # Also handle "Source X" patterns
        return self.source_word_pattern.sub(
            self._create_source_word_replacer(formatter), content
        )

    @staticmethod
    def _slugify_collection(name: str) -> str:
        """Make a user-set collection name safe for inline citations.

        Collection names are free-form strings (``"My Papers"``,
        ``"team/finance"``). Citations need a compact token that won't
        break markdown — strip whitespace, lowercase, replace runs of
        non-alphanumeric chars with a single hyphen, trim leading and
        trailing hyphens, and fall back to ``"local"`` if the result is
        empty. ``-N`` is appended downstream so we strip trailing
        hyphens to keep the join clean.
        """
        slug = re.sub(r"[^a-z0-9]+", "-", name.strip().lower()).strip("-")
        return slug or "local"

    @staticmethod
    def _slugify_title(title: str, max_length: int = 32) -> Optional[str]:
        """Generate a slug from a document title using python-slugify.

        Returns ``None`` when ``title`` is empty / whitespace / pure
        punctuation, or when ``slugify`` produces an empty result. The
        ``None`` sentinel lets callers distinguish "no meaningful slug"
        from "slug happens to be a real word" (e.g. a document literally
        titled ``"Doc"`` must yield ``"doc"`` as its label, not fall
        through to the citation-number fallback).
        """
        if not title:
            return None
        slug = slugify(title, max_length=max_length, separator="-")
        return slug if slug else None

    def _citation_label(self, citation_num: str, title: str, url: str) -> str:
        """Return the inline-citation label for a source.

        Order of preference:
        1. The URL's domain (``arxiv.org``, ``example.com``) — used by
           web citations. Falls through when the URL is relative or
           empty, as is common for RAG / library documents.
        2. A slugified version of the document title (truncated to
           keep labels compact) — gives users a readable label for
           local-library hits.
        3. The citation number itself — last-resort guarantee the
           label is never empty (an empty label produces ``[[]]``
           which renders as an uninformative ``[]`` link).
        """
        domain = self._extract_domain(url) if url else ""
        if domain:
            return domain
        slug = self._slugify_title(title)
        if slug:
            return slug
        return str(citation_num)

    @staticmethod
    def _is_linkable_url(url: str) -> bool:
        """Return True iff ``url`` is a http(s) URL safe to wrap in a
        markdown hyperlink. Empty strings and file:// / local: schemes
        are not linkable.

        Built on ``_safe_link_destination`` so the scheme and control-character
        rules live in one place; the only thing added here is that a scheme has
        to be PRESENT. SOURCE_TAGGED uses that to decide whether to render a
        link at all, which is why it, alone among the modes, does not link a
        relative URL.
        """
        if not _safe_link_destination(url):
            return False
        try:
            return urlsplit(url.strip()).scheme in _LINKABLE_URL_SCHEMES
        except ValueError:
            return False

    def _extract_source_label(
        self, url: str, collection: str | None = None
    ) -> str:
        """Return a short source tag for ``url``.

        Resolution order:
        1. ``collection`` (when supplied) wins outright — RAG / library
           hits surface their collection name as the citation tag
           (``mypapers``, ``personal-notes``, ...). The renderer in
           ``utilities/search_utilities.format_links_to_markdown``
           emits a ``Collection:`` line per source for library results,
           which the formatter parses back into this argument.
        2. Empty URL or non-http(s) scheme (``file://``, ``local:``, ...) →
           ``"local"``. Uniform fallback when no collection name is
           available.
        3. ``URLClassifier`` matches a known academic source → use the
           enum value (``arxiv``, ``pubmed``, ``pmc``, ``biorxiv``,
           ``medrxiv``, ``semantic_scholar``, ``doi``).
        4. Otherwise → fall back to ``_extract_domain`` (e.g.
           ``arxiv.org``, ``nytimes.com``).
        """
        if collection:
            return self._slugify_collection(collection)
        if not url:
            return "local"
        try:
            parsed = urlparse(url)
        except (ValueError, AttributeError):
            return "local"
        scheme = (parsed.scheme or "").lower()
        if scheme not in ("http", "https"):
            return "local"

        url_type = URLClassifier.classify(url)
        # Generic HTML/PDF/INVALID → fall back to domain. Everything else
        # is a known academic source whose enum value is the short tag.
        if url_type in (URLType.HTML, URLType.PDF, URLType.INVALID):
            return self._extract_domain(url)
        return str(url_type.value)

    def _extract_domain(self, url: str) -> str:
        """Extract domain name from URL."""
        try:
            # The authority as browsers and requests read it: they end it at
            # a backslash, where urllib reads on, so
            # https://evil.example\@arxiv.org/ reaches evil.example.
            authority = urlparse("//" + urlparse(url).netloc.split("\\", 1)[0])
            # Without any userinfo: https://[email protected]/ reaches
            # evil.example, and https://user:[email protected]/ would put
            # the token in the label.
            domain = authority.netloc.rpartition("@")[2]
            # Remove www. prefix if present
            if domain.startswith("www."):
                domain = domain[4:]
            # Keep known domains as-is
            known_domains = {
                "arxiv.org": "arxiv.org",
                "github.com": "github.com",
                "reddit.com": "reddit.com",
                "youtube.com": "youtube.com",
                "pypi.org": "pypi.org",
                "milvus.io": "milvus.io",
                "medium.com": "medium.com",
            }

            # The host itself or a subdomain of it. A substring test on the
            # netloc also labelled arxiv.org.evil.example as arxiv.org. The
            # root dot of a fully qualified name (arxiv.org.) is dropped, as
            # utilities/arxiv.py does, since that host is still arxiv.org.
            # A port that is not a number hides the rest of the authority
            # from `hostname` (arxiv.org:443.evil.example), and requests
            # refuses it, so it earns no known label.
            try:
                _ = authority.port
                host = (authority.hostname or "").rstrip(".")
            except ValueError:
                host = ""
            for known, display in known_domains.items():
                if host == known or host.endswith("." + known):
                    return display

            # Preserve valid ports on other domains, as the existing
            # citation-label contract requires. For an invalid authority,
            # leave out a port that the check above refused (arxiv.org:99999);
            # a colon followed by more labels (arxiv.org:443.evil.example)
            # is still part of the untrusted name.
            name, _, port = domain.rpartition(":")
            if not host and name and "." not in port and "]" not in port:
                domain = name
            parts = domain.split(".")
            if len(parts) >= 2:
                return ".".join(parts[-2:])
            return domain
        except (ValueError, AttributeError):
            return "source"


# Whether a ``.qmd`` runs code is decided by more than one reader, and they
# disagree with each other. From quarto-cli and knitr:
#
#   languagesWithClasses (src/core/pandoc/pandoc-partition.ts), which picks
#   the engine, run over the WHOLE file with the /gm flags:
#     /^[\t >]*```+\s*\{([a-zA-Z][a-zA-Z0-9_.]*)([^}]*)?\}\s*$/gm
#   breakQuartoMd (src/core/lib/break-quarto-md.ts):
#     ^\s*(```+)\s*\{([=A-Za-z][=A-Za-z0-9._]*)( *[ ,].*)?\}\s*$
#   quartoMdToJupyter (src/core/jupyter/jupyter.ts), the Jupyter engine:
#     "^(\\s*)(```+)\\s*\\{" + kernelspec.language.toLowerCase() +
#       "( *[ ,].*)?\\}\\s*$"
#   knitr's md chunk.begin (R/pattern.R):
#     '^[\t >]*```+\\s*\\{([a-zA-Z0-9_]+( *[ ,].*)?)\\}\\s*$'
#
# They differ in fence tracking (none for languagesWithClasses and knitr,
# none that shields a cell for quartoMdToJupyter), in the prefix they allow
# (``>`` for blockquotes), in line splitting (/m treats \r, U+2028 and U+2029
# as line ends) and in the meaning of ``\s``. Modelling any one of them left
# a cell another one runs. So nothing is modelled: every one of them needs a
# run of three or more backticks, optional whitespace, ``{`` and a language
# character, and that shape is broken wherever it occurs.
#
# The whitespace class is the union of Python's ``\s`` (which adds
# \x1c-\x1f and \x85), JavaScript's (which adds U+FEFF) and U+180E (a space
# before Unicode 6.3). It includes every line break, so a header split
# across lines is caught too. A language character is ``=`` or anything
# Python's Unicode ``\w`` matches, a superset of the ASCII classes above and
# of a locale-dependent ``[a-zA-Z]``. ``{.class}`` and ``{#id}`` (Pandoc
# attributes, which no reader runs) are left alone.
_ANY_SPACE = r"[\s\ufeff\u180e]"
_QUARTO_CELL_HEADER = re.compile(
    rf"^(?P<indent>(?:{_ANY_SPACE}|>)*)(?P<fence>`{{3,}}){_ANY_SPACE}*"
    r"\{(?P<lang>[=\w][=\w.]*)"
    rf"(?P<rest>[^=\w.}}\n\r][^}}\n\r]*)?\}}{_ANY_SPACE}*$"
)
# The backstop: an opening brace of the same shape anywhere in the text. The
# lookbehind starts a match only at the first backtick of a run, which keeps
# the scan linear on a long run of backticks.
_QUARTO_CELL_BRACE = re.compile(
    rf"(?<!`)(?P<head>`{{3,}}{_ANY_SPACE}*)\{{(?=[=\w])"
)
# Quarto's own line splitting (``lines()`` in src/core/lib/text.ts).
_QUARTO_LINE_BREAK = re.compile(r"(\r\n?|\n)")


def _defuse_quarto_cells(body: str) -> str:
    """Turn executable Quarto cells in report prose into display fences.

    Markdown to ``.qmd`` is not format-preserving: a ```` ```{python} ````
    fence is inert text in a markdown report and an EXECUTABLE cell in a
    Quarto document, which ``quarto render`` — the only reason to ask for this
    format — runs. Report bodies carry web-influenced content, so the fence
    that arrives need not have been written by the user reading it.

    Dropping the braces keeps the code visible and stops it being a cell. A
    plain ```` ```python ```` fence is display-only already and is untouched.

    This fails closed. Every line shaped like a cell header is demoted, with
    any indent or ``>`` prefix, wherever it is: inside another fence, in a
    blockquote or in plain prose alike. The demotion removes only the two
    braces and the whitespace around them; the language and any options stay,
    so ```` ```{python, echo=false} ```` becomes ```` ```python, echo=false
    ````. A report that quotes the syntax as an example therefore shows it
    without its braces; that is the accepted cost. Any other occurrence of a
    fence followed by ``{`` and a language character — inside a line of
    prose, split across a line break, or with a ``}`` in its options — loses
    only that opening brace, so no text after it is dropped. Neither step
    adds or removes a backtick or a line break, so no line changes whether
    it opens a Markdown code fence.

    One regex test per line and one scan of the whole text: linear.
    """
    parts = _QUARTO_LINE_BREAK.split(body)
    for index in range(0, len(parts), 2):
        cell = _QUARTO_CELL_HEADER.match(parts[index])
        if cell:
            parts[index] = (
                f"{cell.group('indent')}{cell.group('fence')}"
                f"{cell.group('lang')}{cell.group('rest') or ''}"
            )
    return _QUARTO_CELL_BRACE.sub(r"\g<head>", "".join(parts))


# Quarto and Pandoc read more than cells out of the text before and while
# rendering it. Two features are reachable from a report body:
#
# * Shortcodes. ``{{< env NAME >}}`` or ``{{< meta key >}}`` prints the
#   renderer's environment or metadata into the output, and
#   ``{{< include path >}}`` pulls in a file, cells included, before the
#   engine is chosen.
# * YAML metadata blocks. src/core/yaml.ts collects every block in the file
#   with /gm, after removing HTML comments (/<!--[\W\w]*?-->/gm) and fenced
#   code, and merges them into the render metadata (engine, filters,
#   pdf-engine-opt, ...):
#     /(^)(---[ \t]*[\r\n]+(?![ \t]*[\r\n]+)[\W\w]*?[\r\n]+(?:---|\.\.\.))
#       ([ \t]*)$/gm
#   Pandoc's own yaml_metadata_block opens at a ``---`` line in any block
#   context: after a ``>`` or list prefix, and inside a grid-table cell
#   (``| --- |``), where the dashes do not end the line. Quarto removes the
#   front matter before Pandoc reads the file and passes the metadata with
#   ``--metadata-file`` (src/command/render/pandoc.ts in v1.10.18: the
#   ``partitionYamlFrontMatter`` call at line 1146 and the push at 1351), so
#   the reader format below switches that extension off and Pandoc reads no
#   metadata block from the body at all.
#
# Shortcodes are the hard part, because Quarto decodes text in many places
# before it looks for them (quarto-cli v1.10.18): Pandoc entities and
# backslash escapes in attribute values, a callout title or a caption
# attribute read again as a whole document (``string_to_quarto_ast_*``),
# ``qmd``/``qmd-base64`` attributes on a Span or Div, raw blocks in the
# ``pandoc-native``, ``pandoc-json`` or ``pandoc-reader-<any reader>``
# formats, ``\QuartoMarkdownBase64{}`` in raw LaTeX, and raw HTML whose
# attributes and tables Pandoc's HTML reader parses. Breaking each
# spelling in turn has failed repeatedly, so the exported file switches
# those readers off instead. Its front matter sets
# ``from: _QUARTO_READER_FORMAT``: Pandoc's markdown without raw HTML, raw
# TeX, raw attributes, fenced or native divs and spans, attribute blocks
# on headers, links, images, code and fences, YAML metadata blocks or a
# ``%`` title block.
# Quarto passes ``from`` to its reader (``user-defined-from`` in
# src/command/render/pandoc.ts, used by readqmd.lua for the document and
# for every string read again through ``string_to_quarto_ast_*``), so the
# body yields no attribute, no raw block or inline, no Div or Span and no
# metadata, and every decoder above is unreachable. The front matter itself
# is not read with that format: Quarto passes it to Pandoc with
# ``--metadata-file`` (pandoc.ts:1351), and Pandoc parses a metadata file
# with all of its default markdown extensions whenever the reader is not
# literally ``markdown`` or ``commonmark`` (``readerOptsMeta`` in Pandoc's
# App.hs). Quarto's reader is a Lua custom reader
# (filters/qmd-reader.lua), so raw HTML, a raw ``{=pandoc-native}`` inline
# or a ``[...]{qmd-base64=...}`` span in the title would reach the
# decoders above. ``_quarto_title_markdown`` therefore escapes the title
# so that Pandoc reads it as plain text, whatever the extensions.
# The same reader format applies to the markup Quarto itself
# appends to the body before Pandoc reads it (pandoc.ts:1275-1283): the
# ``:::{#quarto-meta-markdown .hidden}`` envelope of ``[...]{.hidden ...}``
# spans in a website, blog or book project (website.ts:328-330,
# website-meta.ts:588, markdown-pipeline.ts:99-121), and the same kind of
# envelope for revealjs (format-reveal.ts:304) or a document that sets
# ``math:`` (pandoc.ts:627-659), as well as the ``keep-source`` block
# (codetools.ts:72-89). The exported file sets none of these and is meant
# to be rendered on its own. Rendered inside such a project or with those
# options, that markup shows as text at the end of the page and what it
# feeds (the rendered page and site titles and descriptions) is lost. No
# reader format can keep Quarto's markup and drop the report's: both are
# read in one pass, and the Divs and Spans that markup needs are what the
# report would use to reach the decoders above.
# What still decodes body text is one fixed chain:
#
#   1. the raw file. lpegshortcode.lua opens a shortcode at a literal
#      ``{{<`` (escaped ``{{{<`` and ``{{</*``), and parse-shortcode.ts,
#      which expands includes, at a literal ``{{< ``. ``wrap_lpeg_match``
#      then restores ``cf5733e5-0370-4aae-8689-61bad1dd9ec0&#x<hex>;`` to
#      the character it encodes, after matching but before Pandoc reads
#      the text.
#   2. Pandoc, once: an entity (``&`` and non-space characters up to the
#      first ``;``, looked up as ``&name;``, ``&#123;`` or ``&#x7b;``) or a
#      backslash escape becomes its character, in text, link targets and
#      image sources. Code, code blocks and math are not decoded.
#   3. readqmd.lua hex-decodes
#      ``b58fc729-690b-4000-b19f-365a4093b2ff;<hex>;`` in text, code, math,
#      code blocks, link targets and image sources and reads the result as
#      a shortcode, and customnodes/shortcodes.lua runs the ``{{<`` parser
#      again on code, code blocks, math, link targets and image sources.
#
# Those two UUIDs are the only shortcode encodings in quarto-cli's filters
# (a sweep of every UUID in src/resources finds the others naming ids,
# data URIs, LaTeX placeholders, the AST vault or a Confluence macro).
# A few Quarto filters still read text with Pandoc's own reader, every
# extension on: a ``{...}`` ending a table caption (common/tables.lua),
# ``{#eq-...}`` after display math (crossref/equations.lua) and a
# ```` ```quarto-title-block ```` fence (quarto-post/book.lua, after
# shortcodes have run). In v1.10.18 none of them reaches a shortcode
# parser or the ``.qmd`` reader.
# Each step is broken by
# inserting a zero-width space (U+200B), which no reader treats as
# whitespace and no decoding removes:
#
# A. ``b58fc729...`` and ``cf5733e5...`` are broken after their first
#    letter, and so is ``quarto-shortcode__``, the class ast/parse.lua
#    turns into a shortcode (no Span can carry it any more; this is kept
#    as a second line). A letter can be spelled only as itself or as an
#    entity (rule B); ``-`` and ``_`` also with backslashes before them.
# B. An ``&`` gets the space after it if Pandoc would decode it (step 2)
#    to ``{``, ``-``, ``_`` or an ASCII letter or digit (the characters
#    of an opener or a sentinel), or if it starts ``&#`` and anything but
#    a plain decimal or hex reference of at most 8 digits up to the
#    ``;``. Pandoc decodes only once, so ``&amp;``, ``&lt;`` or ``&nbsp;``
#    stay as they are, and so does every ``&`` that starts no entity: one
#    that no ``;`` closes before a space, as in a URL query
#    (``?q=a&hl=en``) or C code (``&x``), or one whose name is not an
#    HTML5 entity.
# C. Two ``{``, with any backslashes before the second, followed after any
#    whitespace or backslashes by ``<``, ``%`` or ``&`` (which may decode
#    to either or to whitespace) get the space after the first. No step
#    can then put ``{{`` before a ``<`` or ``%``. ``{{\partial`` in math
#    is left alone.
# HTML comment openers ``<!--`` get the zero-width space between the
# dashes, so yaml.ts cannot remove a comment to join text into a new line
# start. Three dashes ending a line become four when everything before
# them on the line is whitespace and block-prefix characters (``>``,
# ``:``, ``~``, ``|``) or footnote labels (``[^1]:``): ``----`` is the
# same thematic break or setext underline to Markdown but opens no YAML
# block for Quarto's yaml.ts, which needs the dashes at the very start of
# a line. Any other text before them on the line leaves them alone, so
# prose ending in `` ---`` keeps its em dash and a URL ending in ``---``
# keeps its dashes. Pandoc reads no body metadata block with the reader
# format below, wherever the dashes are; the block prefixes are a second
# line against that. Nor does it read a ``%`` title block: Quarto starts the
# body it hands to Pandoc with a line break (``partitionYamlFrontMatter``
# in src/core/yaml.ts), which already keeps one from opening, and the
# reader format switches the extension off as well. It also switches
# ``multiline_tables`` off. With ``yaml_metadata_block`` off, a ``---``
# line (defused to ``----``) directly followed by text, with the next
# rule only after a blank line, would be a one-column multiline table:
# the report up to that rule, headings included, would sit in one cell,
# and an indented rule would cut the leading characters of every
# following line. Off, that shape stays a horizontal rule. A ``---``
# line, lines of text and another ``---`` line with no blank line
# between them are still a simple table, and pipe tables are unaffected.
# Genuine Pandoc multiline-table syntax in a report is no longer read
# as a multiline table: body rows render as paragraphs, and a headed
# table's header lines may render as a one-column table.
_QUARTO_READER_FORMAT = "markdown" + "".join(
    f"-{extension}"
    for extension in (
        "raw_html",
        "raw_tex",
        "raw_attribute",
        "native_divs",
        "native_spans",
        "fenced_divs",
        "bracketed_spans",
        "header_attributes",
        "link_attributes",
        "inline_code_attributes",
        "fenced_code_attributes",
        "yaml_metadata_block",
        "pandoc_title_block",
        "multiline_tables",
    )
)
_ZERO_WIDTH_SPACE = "\u200b"
_HTML_COMMENT_OPEN = re.compile(r"<!-(?=-)")
# Matched against one line at a time; group 1 is the whole prefix. Linear:
# anchored, and each prefix unit starts with a character no other unit
# starts with.
_YAML_BLOCK_DELIMITER = re.compile(
    rf"\A((?:[\s\ufeff\u180e>:~|]|\[\^[^\]]+\]:)*)---(?={_ANY_SPACE}*\Z)"
)
# Every line break any reader uses: Python's ``str.splitlines`` set, which
# includes JavaScript's /m line terminators (\n, \r, U+2028, U+2029).
_ANY_LINE_BREAK = re.compile(r"(\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029])")

# Pandoc's ``characterReference``: ``&``, then ``many1Till nonspaceChar
# (char ';')`` where a space is one of these four characters.
_PANDOC_SPACE = re.compile(r"[ \t\n\r]")
_SHORTCODE_CHARACTERS = frozenset(
    "{-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
_NUMERIC_REFERENCE = re.compile(r"#(?:([0-9]{1,8})|[xX]([0-9a-fA-F]{1,8}))")
# Longer than any HTML5 entity name (31 characters) or plain numeric
# reference (``#x`` and 8 digits), so never sliced out of the text.
_LONGEST_REFERENCE = 40
_QUARTO_SHORTCODE_BRACES = re.compile(
    rf"\{{(?=\\*\{{(?:{_ANY_SPACE}|\\)*[<%&])"
)
_QUARTO_SHORTCODE_TOKENS = re.compile(
    r"(?<=b)(?=58fc729\\*-690b\\*-4000\\*-b19f\\*-365a4093b2ff)"
    r"|(?<=c)(?=f5733e5\\*-0370\\*-4aae\\*-8689\\*-61bad1dd9ec0)"
    r"|(?<=q)(?=uarto\\*-shortcode\\*_\\*_)",
    re.IGNORECASE,
)


def _reference_is_hazardous(reference: str) -> bool:
    """True if Pandoc decodes ``&<reference>;`` to a character rule B breaks.

    *reference* is what Pandoc reads between the ``&`` and the ``;``. A
    numeric one is hazardous unless it is a plain decimal or hex number of
    a harmless character; a name is hazardous if it is an HTML5 entity for
    a character that can spell a shortcode or a sentinel. Any other name
    is no entity, so Pandoc keeps it as text.
    """
    if reference.startswith("#"):
        number = _NUMERIC_REFERENCE.fullmatch(reference)
        if number is None:
            return True
        decimal, hexadecimal = number.groups()
        code = int(decimal, 10) if decimal else int(hexadecimal, 16)
        if not 0 < code <= 0x10FFFF:
            return True
        return chr(code) in _SHORTCODE_CHARACTERS
    value = html5.get(reference + ";")
    return value is not None and bool(_SHORTCODE_CHARACTERS.intersection(value))


def _break_entities(text: str) -> str:
    """Rule B: no entity Pandoc decodes can spell a shortcode or sentinel.

    The ``;`` and the space after each ``&`` are found by searches that
    only move forward, so the scan is linear.
    """
    pieces = []
    position = 0
    semicolon = space = -1
    start = text.find("&")
    while start != -1:
        if semicolon < start + 2:
            semicolon = text.find(";", start + 2)
        if semicolon == -1:
            break
        if space <= start:
            found = _PANDOC_SPACE.search(text, start + 1)
            space = found.start() if found else len(text)
        if space > semicolon and (
            text[start + 1] == "#"
            if semicolon - start > _LONGEST_REFERENCE
            else _reference_is_hazardous(text[start + 1 : semicolon])
        ):
            pieces.append(text[position : start + 1])
            pieces.append(_ZERO_WIDTH_SPACE)
            position = start + 1
        start = text.find("&", start + 1)
    pieces.append(text[position:])
    return "".join(pieces)


def _defuse_quarto_text(text: str) -> str:
    """Break every shortcode and HTML-comment opener in *text*.

    Rules A-C above, for body text read with ``_QUARTO_READER_FORMAT``.
    Used on the report title too, before ``_quarto_title_markdown``
    escapes it (the title is not read with that format): Quarto expands
    shortcodes in metadata, and a comment opened in the title could be
    closed in the body. Only zero-width spaces are inserted; removing them
    gives back *text*. Linear: a constant number of scans.
    """
    text = _break_entities(text)
    text = _HTML_COMMENT_OPEN.sub("<!-" + _ZERO_WIDTH_SPACE, text)
    text = _QUARTO_SHORTCODE_BRACES.sub("{" + _ZERO_WIDTH_SPACE, text)
    return _QUARTO_SHORTCODE_TOKENS.sub(_ZERO_WIDTH_SPACE, text)


def _defuse_quarto_body(body: str) -> str:
    """Neutralise the cells, shortcodes and metadata blocks in a report body.

    Cells are demoted (``_defuse_quarto_cells``), shortcodes and HTML
    comments are broken (``_defuse_quarto_text``) and no line can open a
    YAML metadata block for Quarto (three dashes ending a line after
    nothing but whitespace, ``>``, ``:``, ``~``, ``|`` and footnote labels
    gain a fourth; prose ending in `` ---`` is left alone; Pandoc's own
    metadata blocks, which also open inside a grid-table cell, are
    switched off by ``_QUARTO_READER_FORMAT``). The exported file's
    metadata is then only the exporter's own front matter, which names no
    engine; no cell header is left and no file can be included, so
    Quarto's engine detection finds no language and picks its markdown
    engine, which runs no code, inline `` `r ...` `` and
    `` `{python} ...` `` expressions included. That holds for the file
    rendered on its own: an engine forced from outside it (a project
    ``_quarto.yml``, ``quarto render -M engine:knitr`` or ``knitr::knit``)
    would still evaluate those inline expressions, and a reader format
    that overrides the file's ``from`` from outside would turn the readers
    listed above back on.

    The steps only insert characters, or remove a cell's opening brace or a
    cell header's braces and the whitespace around them. None of that can
    create an opener another step breaks, so the result is a fixed point.
    Linear: a constant number of scans.
    """
    body = _defuse_quarto_cells(_defuse_quarto_text(body))
    parts = _ANY_LINE_BREAK.split(body)
    for index in range(0, len(parts), 2):
        parts[index] = _YAML_BLOCK_DELIMITER.sub(r"\1----", parts[index])
    return "".join(parts)


# Every ASCII punctuation character. Pandoc's markdown reads a backslash
# before any of them as that character (``all_symbols_escapable``).
_ASCII_PUNCTUATION = re.compile(r"([!-/:-@\[-`{-~])")
# Runs of what Pandoc's markdown reader treats as spaces and line endings.
_PANDOC_SPACE_RUN = re.compile(r"[ \t\n\r]+")


def _quarto_title_markdown(title: str) -> str:
    """The Markdown source for *title* in the exported front matter.

    Pandoc reads the front matter with all of its default markdown
    extensions, not with ``_QUARTO_READER_FORMAT`` (see the comment above
    it), so the title gets its own treatment. Runs of spaces, tabs and
    line breaks become one space and the ends are trimmed, so no line can
    start a block such as an indented code block; shortcodes and comment
    openers are broken (``_defuse_quarto_text``); and a backslash goes
    before every ASCII punctuation character. Pandoc then reads the title
    as ``Str`` and ``Space`` nodes only: no raw HTML or raw ``{=format}``
    inline, no span or attribute, no markup, entity, math or citation.
    The title renders as the same characters, with its whitespace
    collapsed; Markdown formatting, entities and typographic quotes or
    dashes in it are shown as written. Linear.
    """
    title = _PANDOC_SPACE_RUN.sub(" ", title).strip(" ")
    return _ASCII_PUNCTUATION.sub(r"\\\1", _defuse_quarto_text(title))


# Characters that must be escaped inside a YAML double-quoted scalar: the
# quote and backslash the double-quoted form itself requires, plus the
# control/line-break range ``is_line_breaking_char()`` above defines once
# for every producer in this module (C0, DEL, C1, and the Unicode line
# separators U+2028/U+2029).
_YAML_DQ_SPECIALS_RE = re.compile(r'["\\\x00-\x1f\x7f-\x9f\u2028\u2029]')


def _yaml_double_quote(value: str) -> str:
    r"""Render *value* as a YAML double-quoted scalar.

    Report titles derive from web-influenced content, so a bare
    interpolation into ``title: "..."`` lets a quote end the scalar
    early (front matter stops parsing) or a newline inject further
    front-matter keys. Escaping to YAML double-quoted rules keeps the
    value a single scalar that parses back exactly.
    """

    def _escape(match: re.Match) -> str:
        ch = match.group()
        if ch == '"':
            return '\\"'
        if ch == "\\":
            return "\\\\"
        if ch == "\n":
            return "\\n"
        if ch == "\r":
            return "\\r"
        if ch == "\t":
            return "\\t"
        code = ord(ch)
        return f"\\x{code:02x}" if code <= 0xFF else f"\\u{code:04x}"

    return '"' + _YAML_DQ_SPECIALS_RE.sub(_escape, value) + '"'


class QuartoExporter:
    """Export markdown documents to Quarto (.qmd) format."""

    def __init__(self):
        # Also match Unicode lenticular brackets 【】 (U+3010 and U+3011) that LLMs sometimes generate
        self.citation_pattern = re.compile(
            r"(?<![\[【])[\[【](\d+)[\]】](?![\]】])"
        )
        self.comma_citation_pattern = re.compile(
            r"[\[【](\d+(?:\s*,\s*\d+)+)[\]】]"  # (#6944) space allowed BEFORE the comma too — a hand-edited `[[2 ,3]]` must stay a group
        )

    def export_to_quarto(self, content: str, title: str | None = None) -> str:
        """
        Convert markdown document to Quarto format.

        Args:
            content: Markdown content
            title: Document title (if None, will extract from content)

        Returns:
            Quarto formatted content
        """
        # Extract title from markdown if not provided
        if not title:
            title_match = re.search(r"^#\s+(.+)$", content, re.MULTILINE)
            title = title_match.group(1) if title_match else "Research Report"

        # Create Quarto YAML header
        from datetime import UTC, datetime

        current_date = datetime.now(UTC).strftime("%Y-%m-%d")
        yaml_header = f"""---
title: {_yaml_double_quote(_quarto_title_markdown(title))}
author: "Local Deep Research"
date: "{current_date}"
from: {_QUARTO_READER_FORMAT}
format:
  html:
    toc: true
    toc-depth: 3
    number-sections: true
  pdf:
    toc: true
    number-sections: true
    colorlinks: true
bibliography: references.bib
csl: apa.csl
---

"""

        # Process content
        processed_content = content

        # Report math reaches a TeX engine when ``quarto render`` builds the
        # declared pdf format, so spans that use commands outside the math
        # allowlist are escaped to literal text here, exactly as the LaTeX
        # export does. Run before the citation and cell passes so the escaped
        # brackets of a rejected span are never mistaken for a citation.
        processed_content = _defuse_report_math_for_quarto(processed_content)

        # Cite only what references.bib defines: the bibliography is built
        # from these entries, so a number missing from them would be an
        # undefined reference. As in the LaTeX export, a group is cited only
        # when every member is listed, and anything else is prose such as
        # "versions [4, 5]" or "[2020]" and is left as written.
        entries = self._bibliography_entries(content)

        # First handle comma-separated citations like [1, 2, 3]
        def replace_comma_citations(match):
            citation_nums = match.group(1)
            # Split by comma and strip whitespace
            nums = [num.strip() for num in citation_nums.split(",")]
            if not all(num in entries for num in nums):
                return match.group(0)
            refs = [f"@ref{num}" for num in nums]
            return f"[{', '.join(refs)}]"

        processed_content = self.comma_citation_pattern.sub(
            replace_comma_citations, processed_content
        )

        # Then convert individual citations to Quarto format [@citation]
        def replace_citation(match):
            citation_num = match.group(1)
            if citation_num not in entries:
                return match.group(0)
            return f"[@ref{citation_num}]"

        processed_content = self.citation_pattern.sub(
            replace_citation, processed_content
        )

        # The report generator's sources sentinel is an HTML comment, which
        # the reader format would show as text (raw HTML is off) and
        # _defuse_quarto_body would break. Drop the one the bibliography is
        # scoped by (the last one on its own line); a quoted one elsewhere
        # is report text and is defused like any other comment.
        sentinel_start, on_sentinel = find_sources_section(processed_content)
        if on_sentinel:
            processed_content = (
                processed_content[:sentinel_start]
                + processed_content[
                    sentinel_start + len(LDR_APPENDED_SOURCES_SENTINEL) :
                ]
            )

        # Generate bibliography file content. It is shown in a code block,
        # which Pandoc does not decode, but readqmd.lua hex-decodes the
        # internal shortcode encodings in CodeBlock text too and
        # shortcodes.lua then expands the result, so a source title or URL
        # carrying one is broken as in the body. Its braces are already
        # escaped (``_escape_bibtex``) or rejected (``_safe_bibtex_url``).
        bib_content = _QUARTO_SHORTCODE_TOKENS.sub(
            _ZERO_WIDTH_SPACE, self._generate_bibliography(content)
        )

        # Add note about bibliography file. It is a plain paragraph: the
        # reader format turns fenced divs off, so a callout would show as
        # text.
        bibliography_note = (
            "\n\n**Bibliography File Required**\n\nThis document requires a `references.bib` file in the same directory with the following content:\n\n```bibtex\n"
            + bib_content
            + "\n```\n"
        )

        # The note and its bibtex fence are the exporter's own markup, so
        # of the note only the bibliography entries are defused (above).
        return (
            yaml_header
            + _defuse_quarto_body(processed_content)
            + bibliography_note
        )

    def _bibliography_entries(self, content: str) -> dict:
        """The entries references.bib is generated from."""
        sources_start, _on_sentinel = find_sources_section(content)
        # Keep accepting bare source lists for programmatic callers. A full
        # report's explicit Sources boundary takes precedence over its body.
        sources_content = (
            content[sources_start:] if sources_start != -1 else content
        )
        return _collect_bibliography_entries(sources_content)

    def _generate_bibliography(self, content: str) -> str:
        """Generate BibTeX bibliography from sources."""
        entries = self._bibliography_entries(content)

        bibliography = ""
        for citation_num in sorted(entries, key=_sort_key):
            title, url = entries[citation_num]
            safe_title = _escape_bibtex(title)
            safe_url = _safe_bibtex_url(url)
            bib_entry = f"@misc{{ref{citation_num},\n"
            bib_entry += f'  title = "{{{safe_title}}}",\n'
            if safe_url:
                bib_entry += f"  url = {{{safe_url}}},\n"
                bib_entry += f'  howpublished = "\\url{{{safe_url}}}",\n'
            bib_entry += f"  year = {{{2024}}},\n"
            bib_entry += '  note = "Accessed: \\today"\n'
            bib_entry += "}\n"

            bibliography += bib_entry + "\n"

        return bibliography.strip()


# One credential check, ``_ris_spells_userinfo``, decides for every RIS
# field built from source text: UR, TI, AU and DO are never written with a
# value it flags. It also reads each value as serialization writes it
# (``_ris_flatten``), so no field is written in a form it flags either. A
# source URL goes through ``_safe_ris_url``, which runs the check last; a
# title, author or DOI the check flags is replaced by ``_safe_ris_url``'s
# userinfo-free URL for it, or dropped (a title, by a placeholder). A
# password can hold a name, a year or a DOI, so no author, no year (PY)
# and no DOI matched in other text is cut out of a line that carries a
# credential (``_ris_line_carries_userinfo``): a line the check flags, or
# one in which a value read from it holds a credential when read as a URL
# as a whole from where the value starts (``_ris_value_starts_userinfo``).
# Nor is a year or DOI taken from a title that its cleaning joins into a
# credential URL. PB is derived from the host of the sanitized UR. TY, Y1,
# DA, LA and ER are fixed or dated, and ID holds the citation number.
# ``_safe_ris_url`` also omits URLs it cannot parse unambiguously; a title,
# author or DOI need not be a URL, so such text stays in those fields
# unless the check flags it.
#
# Userinfo is what precedes the last @ of a URL's authority, as the WHATWG
# URL Standard parses it. The authority ends at the first ``/``, ``?`` or
# ``#``, so a password that holds one of them unencoded is not userinfo,
# and the check does not flag it: ``https://user:2024/Secret@host/x`` has
# the host ``user``, the port 2024 and no credential. Under any scheme,
# and under none (``//host``), an authority follows ``//``. Under
# the schemes the WHATWG URL Standard calls special, it also follows the
# colon and any run of ``/`` or ``\`` (none included): a browser reads
# ``https:user:pass@host`` and ``https:\\user:pass@host`` as credential
# URLs. ``file`` is special too, but a file URL carries no userinfo. A
# value with no scheme is resolved against a base URL, and against a
# special one, such as an ``https`` page, any run of two or more ``/`` or
# ``\`` opens an authority as ``//`` does: a browser reads
# ``\\user:pass@host``, ``/\user:pass@host`` and ``///user:pass@host``
# there as ``https://user:pass@host``.
_RIS_SPECIAL_SCHEME = r"(?:https?|ftp|wss?)"

# An authority opened anywhere in a value, so a credential URL wrapped in
# ``<...>``, a markdown link, quotes, parentheses, backticks or emphasis, or
# written inside prose, is still seen; a run of two or more ``/`` or ``\``
# opens one wherever it appears, as ``//`` does. In each reading of a
# value (``_ris_readings``), a URL inside text ends at whitespace, as a
# linkifier ends it, so an e-mail address later in the text is not read
# as its userinfo. Neither is what follows whitespace inside a wrapped
# URL's authority, as in ``<https://user :pass@host>``; only a value that
# is a URL as a whole is read past it. The lookbehind keeps the ``ws:`` of
# ``news:`` and the ``ftp:`` of ``sftp:`` from opening an authority.
_RIS_EMBEDDED_AUTHORITY_RE = re.compile(
    rf"(?:(?<![a-z0-9+.\-]){_RIS_SPECIAL_SCHEME}:[/\\]*|[/\\]{{2,}})"
    r"([^\s/?#]*)",
    re.IGNORECASE,
)

# What a value that is a URL as a whole may begin and end with: whitespace,
# controls and U+FEFF. RIS serialization turns controls into spaces, and a
# reader may trim a field: JavaScript's ``trim()`` removes U+FEFF as well,
# which Python's ``strip()`` keeps. Inside a value, U+FEFF is not
# whitespace.
_RIS_TRIMMED = r"[\s\x00-\x20\x7f-\x9f\ufeff]"

# The authority of a value that is a URL as a whole, past any leading
# ``_RIS_TRIMMED`` characters. It runs up to the first ``/``, ``?`` or
# ``#``, whitespace included, as ``urlsplit`` delimits a netloc after
# ``//``. So a title spelling a URL that ``_safe_ris_url`` would strip a
# credential from is flagged too, as is ``\\ user:pass@host``, which a
# browser reads with the space encoded.
#
# Unless a base URL of the same scheme makes the value relative, a browser
# also reads whitespace after a special scheme's colon, or after the colon
# and one ``/`` or ``\``, as part of the authority: to it,
# ``https:/ user:pass@host`` and ``https: user:pass@host`` carry
# credentials, and so does the title ``HTTP: email me at [email protected]``,
# whose userinfo it reads as `` email me at bob``. After the colon and one
# ``/`` or ``\``, the authority runs past whitespace as above; no title
# begins that way. So that prose stays a title, an authority opened by the
# colon alone, with no ``/`` or ``\`` after it, may begin with whitespace
# only in the shape ``_RIS_SPACED_AUTHORITY`` matches. Past that
# whitespace must come a token of one or more characters other than
# whitespace, ``/``, ``\``, ``?`` and ``#``; optional whitespace; an @;
# and a host of characters other than those and @, followed by ``/``,
# ``\``, ``?``, ``#`` or nothing but ``_RIS_TRIMMED`` characters, as the
# value may begin with them. ``https: user:pass@host/x`` and
# ``https: user:pass @host`` are flagged. Three titles are not:
# ``HTTP: email me at [email protected]``, whose would-be userinfo holds
# whitespace; ``HTTP: [email protected] explains``, whose would-be host
# does; and ``HTTP: @mention``, which has no token before its @. Every
# reading of a value is matched, so a control where this shape takes
# whitespace is read as the space serialization writes for it
# (``_ris_flatten``). The host is matched possessively: it shares controls
# and U+FEFF with ``_RIS_TRIMMED``, and giving them back could only make
# the end of the value be scanned again, in time quadratic in its length.
_RIS_SPACED_AUTHORITY = "".join(
    (
        r"\s+[^\s/?#\\]+\s*@[^\s/?#@\\]++(?:[/?#\\]|",
        _RIS_TRIMMED,
        r"*\Z)",
    )
)
# What opens the authority of a URL as a whole.
_RIS_WHOLE_URL_START = (
    rf"(?:(?:{_RIS_SPECIAL_SCHEME}:)?[/\\]{{2,}}|[a-z][a-z0-9+.\-]*://"
    rf"|{_RIS_SPECIAL_SCHEME}:"
    rf"(?:[/\\]|(?!\s)|(?={_RIS_SPACED_AUTHORITY})))"
)
_RIS_WHOLE_URL_AUTHORITY_RE = re.compile(
    rf"{_RIS_TRIMMED}*{_RIS_WHOLE_URL_START}([^/?#]*)",
    re.IGNORECASE,
)

# Where a URL as a whole can start in a value read from a line
# (``_ris_line_carries_userinfo``): at the value's start, and after each
# comma, ``and`` or ampersand, where the author pattern splits a list into
# authors. As at the start of a value, the URL may follow whitespace,
# controls and U+FEFF, matched possessively, since none of them can open
# an authority. ``_ris_value_starts_userinfo`` finds where each such
# authority ends.
_RIS_VALUE_URL_START_RE = re.compile(
    rf"(?:\A|,|(?<=\s)(?-i:and)(?=\s)|&){_RIS_TRIMMED}*+"
    rf"{_RIS_WHOLE_URL_START}",
    re.IGNORECASE,
)
_RIS_AUTHORITY_END_RE = re.compile(r"[/?#]")

# Bounds on the readings of one value, which keep the work of checking it
# small; a value past any of them counts as flagged. Each layer of encoding
# a value carries adds a reading, so an ordinary value has a few, and 64
# leaves room for deliberate nesting. A reading can be longer than the
# value, since NFKC turns U+FDFA alone into 18 characters, so every
# reading is measured, not only the value. RFC 9110 recommends supporting
# URIs of 8,000 octets; no title, author, DOI or link needs eight times
# that. The total leaves room for the value plus three more readings of
# that length.
_RIS_MAX_READINGS = 64
_RIS_MAX_DECODED_LENGTH = 1 << 16
_RIS_MAX_DECODED_TOTAL_LENGTH = 4 * _RIS_MAX_DECODED_LENGTH

# The WHATWG URL parser deletes every tab, LF and CR from its input before
# it parses it: a browser reads ``ht<TAB>tps:/<LF>/user:pass@host`` as
# ``https://user:pass@host``. So the readings of a value include it with
# them deleted, or one that an entity or percent-escape spells would hide
# a credential URL once decoded: ``&Tab;`` splits the scheme of
# ``ht&Tab;tps:user:pass@host``, and ``%0A`` the slashes of
# ``https:/%0A/user:pass@host``.
_RIS_URL_DELETED_CHARACTERS = str.maketrans("", "", "\t\n\r")


def _ris_flatten(value: str) -> str:
    """``value`` as RIS serialization writes it: every character
    ``is_line_breaking_char`` matches is turned into a space, so only the
    exporter's own line breaks separate RIS fields."""
    return "".join(
        " " if is_line_breaking_char(char) else char for char in value
    )


def _ris_readings(value: str) -> set[str] | None:
    """``value`` and every form decoding turns it into; None past a bound.

    The decodings are HTML character references, NFKC normalization,
    percent-decoding, the deletion of every tab, LF and CR, as the WHATWG
    URL parser deletes them, and ``_ris_flatten``, which turns every
    control character, U+2028 and U+2029 into a space, as serialization
    writes a field. Each is applied to every reading until none yields a
    new one, so they compose in any order and repeat. An ASCII value
    without ``&``, ``%`` or a control character, which none of them can
    change, is its only reading. Any other value is measured, and so is
    each new reading as a decoding yields it: the result is None once one
    of them is longer than ``_RIS_MAX_DECODED_LENGTH``, once they are
    longer together than ``_RIS_MAX_DECODED_TOTAL_LENGTH``, or once there
    would be more than ``_RIS_MAX_READINGS`` of them.
    """
    if value.isascii() and not any(
        char in "&%" or is_line_breaking_char(char) for char in value
    ):
        return {value}  # None of the decodings can change it.
    if len(value) > _RIS_MAX_DECODED_LENGTH:
        return None
    readings = {value}
    total_length = len(value)
    pending = [value]
    while pending:
        form = pending.pop()
        for decoded in (
            html.unescape(form),
            unicodedata.normalize("NFKC", form),
            urllib.parse.unquote(form),
            form.translate(_RIS_URL_DELETED_CHARACTERS),
            _ris_flatten(form),
        ):
            if decoded in readings:
                continue
            total_length += len(decoded)
            if (
                len(readings) == _RIS_MAX_READINGS
                or len(decoded) > _RIS_MAX_DECODED_LENGTH
                or total_length > _RIS_MAX_DECODED_TOTAL_LENGTH
            ):
                return None
            readings.add(decoded)
            pending.append(decoded)
    return readings


def _ris_spells_userinfo(value: str) -> bool:
    """Whether some reading of ``value`` puts a credential in a URL authority.

    A credential is userinfo holding anything other than ``@`` signs; an @
    outside every authority, as in ``medium.com/@author``, is not one. The
    readings are ``value`` and its decoded forms (``_ris_readings``): a
    consumer that renders ``&commat;``, decodes ``%40`` or folds a
    full-width at sign (U+FF20) reads the @ they spell, and a browser
    deletes the tab, LF or CR that ``&Tab;``, ``&#10;`` or ``%0D`` spells,
    as one reading does. Another is the value as serialization writes it
    (``_ris_flatten``), so whatever the check passes is written in a form
    it passes too. The check is lexical, so no parse error can let a value
    through, and a value past the reading bounds counts as flagged.
    """
    readings = _ris_readings(value)
    if readings is None:
        return True
    for form in readings:
        whole = _RIS_WHOLE_URL_AUTHORITY_RE.match(form)
        if whole and "@" in whole.group(1).lstrip("@"):
            return True
        if any(
            "@" in match.group(1).lstrip("@")
            for match in _RIS_EMBEDDED_AUTHORITY_RE.finditer(form)
        ):
            return True
    return False


def _safe_ris_url(raw_url: str | None) -> str:
    """Return a source URL ready for a RIS field without its userinfo, or "".

    The literal userinfo of a parseable authority is removed and the rest
    of the URL kept. The URL is omitted instead when it contains a
    line-breaking character; when ``urlsplit`` cannot parse it, or finds no
    host or an empty or invalid port in its authority; when its authority
    holds a backslash; when it has a scheme but no authority, and the scheme
    is http(s) or the URL holds an @; and when ``_ris_spells_userinfo``
    flags what would be exported: an entity-, percent- or NFKC-spelled
    delimiter left in the authority; a credential URL with no authority
    ``urlsplit`` could strip, inside a wrapper such as ``<...>`` or
    ``[text](...)``, inside prose, after a scheme-less run of slashes and
    backslashes other than ``//``, after U+FEFF, or with its scheme or
    slashes split by an encoded tab, LF or CR; or a value past the bounds
    on its readings.
    """
    if not isinstance(raw_url, str):
        return ""
    candidate = raw_url.strip()
    if not candidate or any(is_line_breaking_char(char) for char in candidate):
        # urlsplit silently discards some controls while parsing, but RIS
        # consumers may read the original bytes as additional fields.
        return ""
    try:
        parsed = urlsplit(candidate)
        if parsed.netloc:
            if "\\" in parsed.netloc:
                # WHATWG parsers end a special authority at a backslash and
                # urlsplit does not, so the two disagree about the host.
                return ""
            authority = parsed.netloc.rpartition("@")[2]
            clean = parsed._replace(netloc=authority)
            if not clean.hostname or authority.endswith(":"):
                return ""
            _ = clean.port  # ValueError for malformed or out-of-range ports.
            candidate = urlunsplit(clean)
        elif parsed.scheme and (
            parsed.scheme.lower() in _LINKABLE_URL_SCHEMES or "@" in candidate
        ):
            # A scheme followed by user:password@host without // is not a
            # parseable authority; it must not survive as a raw RIS field.
            return ""
    except ValueError:
        return ""
    if _ris_spells_userinfo(candidate):
        return ""
    return candidate


def _ris_field_text(value: str) -> str:
    """``value`` for a free-text RIS field, or ``_safe_ris_url(value)`` when
    the credential check flags it ("" when no URL is kept)."""
    if _ris_spells_userinfo(value):
        return _safe_ris_url(value)
    return value


def _ris_value_starts_userinfo(value: str) -> bool:
    """Whether, in some reading of ``value``, a URL as a whole that starts
    at its start, or after a comma, ``and`` or ampersand in it
    (``_RIS_VALUE_URL_START_RE``), holds a credential: an @ in its
    authority after any leading @ signs, as ``_ris_spells_userinfo`` reads
    the authority of a value that is a URL as a whole. The authority runs
    to the first ``/``, ``?`` or ``#``. An authority that starts inside
    another ends where that one ends, so each is scanned once, and the work
    is linear in the length of the readings. A value past the reading
    bounds counts as holding one.
    """
    readings = _ris_readings(value)
    if readings is None:
        return True
    for form in readings:
        authority_end = last_at = -1
        for start in _RIS_VALUE_URL_START_RE.finditer(form):
            position = start.end()
            if position >= authority_end:
                end = _RIS_AUTHORITY_END_RE.search(form, position)
                authority_end = end.start() if end else len(form)
                last_at = form.rfind("@", position, authority_end)
            while position < authority_end and form[position] == "@":
                position += 1
            if last_at >= position:
                return True
    return False


# The labels of the lines whose value ``export_to_ris`` reads whole: the
# source URL from a ``URL:`` line and the DOI from a ``DOI:`` line, each
# matched as ``export_to_ris`` matches it.
_RIS_VALUE_LABEL_RE = re.compile(r"URL:|DOI:")


_RIS_SOURCE_VALUE_START = r"(?:\A|URL:|DOI:|by\s++|,|(?<=\s)and(?=\s)|&)"
_RIS_SOURCE_VALUE_AUTHORITY_RE = re.compile(
    rf"{_RIS_SOURCE_VALUE_START}"
    rf"{_RIS_TRIMMED}*+{_RIS_WHOLE_URL_START}([^/?#]*)",
    re.IGNORECASE,
)
# A source has metadata after its URL, so a host need not end the record.
# This relaxed tail applies only when userinfo crosses the checked physical
# line. A one-line prose title such as "HTTP: [email protected] explains"
# therefore keeps the field guard's documented prose exception.
_RIS_SOURCE_SPACED_AUTHORITY_RE = re.compile(
    rf"{_RIS_SOURCE_VALUE_START}{_RIS_TRIMMED}*+{_RIS_SPECIAL_SCHEME}:"
    r"\s++([^\s/?#\\]+\s*@[^\s/?#@\\]++)(?=[/?#\\]|\s|\Z)",
    re.IGNORECASE,
)


def _ris_multiline_line_carries_userinfo(text: str, position: int) -> bool:
    """Check a source line in its unsplit record, before cutting fields.

    A raw LF can cut the @ off a credential URL before a title, URL, DOI,
    author or year is checked. Track the line's span through the same
    decodings as the field guard, so unrelated lines keep their metadata.
    Prefix/suffix comparisons conservatively include a decoded token that
    crosses a span boundary (for example, ``%4<LF>0`` becoming ``@``).
    No raw source text is rewritten or used as a replacement field value.
    """
    if "\n" not in text:
        return False
    if text.isascii() and not any(char in text for char in "@%&"):
        return False
    if len(text) > _RIS_MAX_DECODED_LENGTH:
        return True

    start = text.rfind("\n", 0, position) + 1
    end = text.find("\n", position)
    if end == -1:
        end = len(text)
    pending = [(text, start, end)]
    seen = set(pending)
    total_length = len(text)
    decoders = (
        html.unescape,
        lambda value: unicodedata.normalize("NFKC", value),
        urllib.parse.unquote,
        lambda value: value.translate(_RIS_URL_DELETED_CHARACTERS),
        _ris_flatten,
    )

    def common_edge(left: str, right: str, *, reverse: bool = False) -> int:
        if reverse:
            left, right = left[::-1], right[::-1]
        if left.startswith(right):
            return len(right)
        return next(
            (i for i, (a, b) in enumerate(zip(left, right)) if a != b),
            min(len(left), len(right)),
        )

    while pending:
        form, start, end = pending.pop()
        for pattern in (
            _RIS_EMBEDDED_AUTHORITY_RE,
            _RIS_SOURCE_VALUE_AUTHORITY_RE,
            _RIS_SOURCE_SPACED_AUTHORITY_RE,
        ):
            for match in pattern.finditer(form):
                authority = match.group(1)
                if "@" not in authority.lstrip("@"):
                    continue
                credential_end = match.start(1) + authority.rfind("@")
                crosses_line = (
                    match.start(1) < start or credential_end + 1 >= end
                )
                if (
                    start < credential_end
                    and end > match.start()
                    and (
                        pattern is not _RIS_SOURCE_SPACED_AUTHORITY_RE
                        or crosses_line
                    )
                ):
                    return True

        for decode in decoders:
            decoded = decode(form)
            if decoded == form:
                continue
            if len(decoded) > _RIS_MAX_DECODED_LENGTH:
                return True
            before = common_edge(decoded, decode(form[:start]))
            after = len(decoded) - common_edge(
                decoded, decode(form[end:]), reverse=True
            )
            state = (decoded, min(before, after), max(before, after))
            if state in seen:
                continue
            total_length += len(decoded)
            if (
                len(seen) == _RIS_MAX_READINGS
                or len(decoded) > _RIS_MAX_DECODED_LENGTH
                or total_length > _RIS_MAX_DECODED_TOTAL_LENGTH
            ):
                return True
            seen.add(state)
            pending.append(state)
    return False


def _ris_line_carries_userinfo(
    text: str, position: int, value_starts: tuple[int, ...] = ()
) -> bool:
    """Whether the line of ``text`` that holds ``position`` carries a
    credential, so that no field may be cut out of it.

    The credential check reads the line itself, and each value read from
    the line from where it starts to the end of the line
    (``_ris_value_starts_userinfo``): the value after a ``URL:`` or ``DOI:``
    label that begins the line, which ``export_to_ris`` reads as the link
    or the DOI, and the values that start in the line at ``value_starts``,
    where the author and DOI patterns begin to read. In the line, a URL
    after a label or a word ends at whitespace, as in other text, and the
    author and DOI patterns end a value at a full stop, a comma, ``and``,
    an ampersand or whitespace, past any of which a URL as a whole can go
    on. So ``URL: https://user:by Smith@host/`` is not flagged as a line,
    but its value is, with the password ``by Smith``, and the author
    pattern would cut ``Smith@host/`` out of the line.
    """
    start = text.rfind("\n", 0, position) + 1
    end = text.find("\n", position)
    if end == -1:
        end = len(text)
    if _ris_spells_userinfo(text[start:end]):
        return True
    starts = [value for value in value_starts if start <= value <= end]
    stripped = text[start:end].lstrip()
    label = _RIS_VALUE_LABEL_RE.match(stripped)
    if label:
        starts.append(end - len(stripped) + label.end())
    return any(
        _ris_value_starts_userinfo(text[value:end]) for value in starts
    ) or _ris_multiline_line_carries_userinfo(text, position)


# Metadata clauses cut from a RIS title, applied in this order. Each one
# starts at its keyword: a leading ``\s*`` would retry from every position
# of a whitespace run before failing, which is quadratic in the run length.
# ``_cut_title_clause`` removes the whitespace before the keyword instead.
_RIS_TITLE_CLAUSES = (
    re.compile(r"DOI:\s*[^\s]+", re.IGNORECASE),
    re.compile(r"Published in.*", re.IGNORECASE),
    re.compile(r"Volume.*", re.IGNORECASE),
    re.compile(r"Pages.*", re.IGNORECASE),
)


def _cut_title_clause(clause: re.Pattern, text: str) -> str:
    r"""Remove every *clause* match together with the whitespace before it.

    Gives the same result as ``re.sub(r"\s*" + clause.pattern, "", text)``
    in linear time. ``rstrip()`` and ``\s`` treat the same characters as
    whitespace. The strip stops at the end of the previous match, which is
    where the leading ``\s*`` of the next match could start at the earliest.
    """
    pieces = []
    position = 0
    for match in clause.finditer(text):
        pieces.append(text[position : match.start()].rstrip())
        position = match.end()
    if not pieces:
        return text
    pieces.append(text[position:])
    return "".join(pieces)


class RISExporter:
    """Export references to RIS format for reference managers like Zotero."""

    def __init__(self):
        self.sources_pattern = re.compile(
            r"^\[(\d+(?:,\s*\d+)*)\]\s*(.+?)(?:\n\s*URL:\s*(.+?))?$",
            re.MULTILINE,
        )

    def export_to_ris(self, content: str) -> str:
        """
        Extract references from markdown and convert to RIS format.

        Args:
            content: Markdown content with sources

        Returns:
            RIS formatted references
        """
        # Find sources section
        sources_start, _on_sentinel = find_sources_section(content)
        if sources_start == -1:
            return ""

        # Find the end of the first sources section (before any other major section)
        sources_content = content[sources_start:]

        # Look for the next major section to avoid duplicates
        next_section_markers = [
            "\n## ALL SOURCES",
            "\n### ALL SOURCES",
            "\n## Research Metrics",
            "\n### Research Metrics",
            "\n## SEARCH QUESTIONS",
            "\n### SEARCH QUESTIONS",
            "\n## DETAILED FINDINGS",
            "\n### DETAILED FINDINGS",
            "\n---",  # Horizontal rule often separates sections
        ]

        sources_end = len(sources_content)
        for marker in next_section_markers:
            pos = sources_content.find(marker)
            if pos != -1 and pos < sources_end:
                sources_end = pos

        sources_content = sources_content[:sources_end]

        # Parse sources and generate RIS entries
        ris_entries = {}

        # Split sources into individual entries
        import re

        # Pattern to match each source entry. The opener is GROUP-AWARE
        # (``\d+(?:,\s*\d+)*``, the spelling ``_BIB_SOURCES_PATTERN`` above
        # uses for Sources lines; the inline ``comma_citation_pattern``,
        # ``\d+(?:\s*,\s*\d+)+``, also accepts whitespace before a comma
        # since #6944, while ``format_links_to_markdown`` joins a merged
        # opener's indices with ``", "``):
        # ``format_links_to_markdown`` collapses every citation of one source
        # onto a single merged ``[1, 3] Title`` line, which is routine for
        # library documents since per-document keying (#5685). A single-index
        # ``(\d+)`` capture did not merely drop such a line — it MIS-CITED
        # (#5687), because the lookahead did not terminate at a merged opener
        # either, so the PRECEDING entry swallowed the merged line and the
        # last-wins ``URL:`` scan below then handed that entry the merged
        # line's URL: one source's title against another source's link. Hence
        # the group spelling appears TWICE — once in the capture, once in the
        # lookahead — and the loop emits one record PER INDEX so that every
        # ``[N]`` in the body resolves to a reference of its own.
        #
        # Four properties here are deliberate; keep them when editing:
        #   1. This parser stays bounded to the FIRST Sources section by the
        #      ``next_section_markers`` scan above. Do not swap in the
        #      module-level ``_collect_bibliography_entries`` — that helper
        #      is deliberately not section-scoped, which is why #5687 notes
        #      RIS is not a mechanical swap even though BibTeX, Quarto and
        #      LaTeX were fixed by adopting it.
        #   2. Lenticular "【N】" openers/closers are accepted alongside
        #      ASCII "[N]": the inline citation patterns in this file already
        #      handle them (some LLMs emit them), so the source-list parser
        #      must stay consistent or it would silently drop those entries.
        #   3. Entries are split by LOOKAHEAD under ``DOTALL`` so continuation
        #      lines (``URL:``, ``DOI:``, ``Published in``) stay attached to
        #      the entry they belong to; a line-anchored ``$`` split would
        #      strip them.
        #   4. ``self.sources_pattern`` above is group-aware but UNUSED, and
        #      is not this fix — it is single-line and section-unaware, so
        #      wiring it in would lose properties 1 and 3.
        source_entry_pattern = re.compile(
            r"^[\[【](\d+(?:\s*,\s*\d+)*)[\]】]\s*(.+?)"
            r"(?=^[\[【]\d+(?:\s*,\s*\d+)*[\]】]|\Z)",
            re.MULTILINE | re.DOTALL,
        )

        for match in source_entry_pattern.finditer(sources_content):
            citation_group = match.group(1)
            entry_text = match.group(2).strip()

            lines = entry_text.split("\n")

            # Extract URL, DOI, and other metadata from subsequent lines
            url = ""
            metadata = {}
            value_positions = {}
            line_start = len(lines[0]) + 1
            for line in lines[1:]:
                position = line_start
                line_start += len(line) + 1
                line = line.strip()
                if line.startswith("URL:"):
                    url = line[4:].strip()
                    value_positions["url"] = position
                elif line.startswith("DOI:"):
                    metadata["doi"] = line[4:].strip()
                    value_positions["doi"] = position
                elif line.startswith("Published in"):
                    metadata["journal"] = line[12:].strip()
                # Add more metadata parsing as needed
                elif line:
                    # Store other lines as additional metadata
                    if "additional" not in metadata:
                        metadata["additional"] = []
                    additional = metadata["additional"]
                    if isinstance(additional, list):
                        additional.append(line)

            # A line split may already have removed the credential's @.
            # Check the selected values against the unsplit source before
            # the ordinary whole-field sanitizer handles parseable URLs.
            if (
                url
                and not _ris_spells_userinfo(url)
                and _ris_multiline_line_carries_userinfo(
                    entry_text, value_positions["url"]
                )
            ):
                url = ""
            if (
                metadata.get("doi")
                and not _ris_spells_userinfo(metadata["doi"])
                and _ris_multiline_line_carries_userinfo(
                    entry_text, value_positions["doi"]
                )
            ):
                metadata["doi"] = ""

            # Combine title with additional metadata lines for full context
            full_text = entry_text

            # One record per index, keyed on the INDIVIDUAL index rather than
            # the group text: a report repeats its Sources block, and the same
            # source may be written ``[1]`` in one block and ``[1, 3]`` in
            # another, so keying on the raw group would let ``ref1`` be emitted
            # twice. Later definitions replace earlier ones, as they do in
            # the inline citation map. ``metadata`` is shared across the
            # indices of one line; ``_create_ris_entry`` only reads it.
            for citation_num in _iter_citation_group(citation_group):
                ris_entries[citation_num] = self._create_ris_entry(
                    citation_num, full_text, url, metadata
                )

        return "\n".join(ris_entries.values())

    def _create_ris_entry(
        self,
        ref_id: str,
        full_text: str,
        url: str = "",
        metadata: dict | None = None,
    ) -> str:
        """Create a single RIS entry."""
        lines = []

        # Parse metadata from full text
        import re

        if metadata is None:
            metadata = {}

        # Extract title from first line. NB: split into a *separate* variable —
        # ``lines`` is the RIS-output accumulator initialized above and appended
        # to below; reusing it here previously overwrote it with the source
        # text, so every entry emitted the raw source body before the mandatory
        # leading ``TY  - `` tag and reference managers rejected the file.
        text_lines = full_text.split("\n")
        title = text_lines[0].strip()

        # The year, the author list, and the DOI when no ``DOI:`` line gave
        # one, are cut out of whatever line their match captures from, and
        # the title is cleaned. A cut can drop a credential URL's @ and keep
        # its userinfo (the title ``https://DOI:pass@host`` yields the DOI
        # ``pass@host``), and a password can hold a year or a name
        # (``https://admin:2024@host`` yields the year 2024), so none of the
        # three is cut from a line that carries a credential
        # (``_ris_line_carries_userinfo``), and a flagged title is sanitized
        # whole, not cleaned. A title that its cleaning joins into a
        # credential URL gives no year or DOI either (``flagged_title``).
        year_match = re.search(r"\b(19\d{2}|20\d{2})\b", full_text)
        authors_match = re.search(
            r"\bby\s+([^.\n]+?)(?:\.|\n|$)", full_text, re.IGNORECASE
        )
        doi = metadata.get("doi")
        doi_match = (
            None
            if doi
            else re.search(r"DOI:\s*([^\s\n]+)", full_text, re.IGNORECASE)
        )
        # Where the author and DOI patterns begin to read a value; a line
        # is checked from each of them too. Each line is checked once.
        value_starts = tuple(
            match.start(1)
            for match in (authors_match, doi_match)
            if match is not None
        )
        line_carries_userinfo: dict[int, bool] = {}

        def cut_is_safe(match: re.Match) -> bool:
            line_start = full_text.rfind("\n", 0, match.start(1)) + 1
            if line_start not in line_carries_userinfo:
                line_carries_userinfo[line_start] = _ris_line_carries_userinfo(
                    full_text, match.start(1), value_starts
                )
            return not line_carries_userinfo[line_start]

        # Extract year from full text (looks for 4-digit year)
        year = (
            year_match.group(1)
            if year_match and cut_is_safe(year_match)
            else None
        )

        # Extract authors if present (looks for "by Author1, Author2")
        authors = []
        if authors_match and cut_is_safe(authors_match):
            # The captured text and each author are checked as written too.
            authors_text = _ris_field_text(authors_match.group(1))
            # Split at delimiters only, then trim each author. Consuming
            # optional whitespace before a delimiter makes a long run with
            # no delimiter quadratic; lookarounds keep "and" word-scoped.
            author_parts = re.split(r",|(?<=\s)and(?=\s)|&", authors_text)
            authors = [
                author
                for author in (_ris_field_text(a.strip()) for a in author_parts)
                if author
            ]

        # Extract DOI from metadata or text
        if doi_match is not None:
            doi = doi_match.group(1) if cut_is_safe(doi_match) else None

        # Clean title - remove author and metadata info for cleaner title.
        # Every form a cut makes is kept for the credential check below.
        clean_title = title
        title_forms = [title]
        if authors_match and authors_match.start() < len(title):
            clean_title = (
                title[: authors_match.start()] + title[authors_match.end() :]
                if authors_match.end() < len(title)
                else title[: authors_match.start()]
            )
            title_forms.append(clean_title)
        for clause in _RIS_TITLE_CLAUSES:
            clean_title = _cut_title_clause(clause, clean_title)
            title_forms.append(clean_title)
        clean_title = clean_title.strip()
        title_forms.append(clean_title)

        # A title carries a credential when the check flags it as written or
        # in any form a cut makes of it: what a cut leaves can join into a
        # credential URL, and a later cut can cut that URL's @ away again,
        # leaving its userinfo. The first form the check flags is sanitized
        # whole, and the title gives no year and no DOI.
        flagged_title = next(
            (
                form
                for form in dict.fromkeys(title_forms)
                if _ris_spells_userinfo(form)
            ),
            None,
        )
        # Cleaning can remove a complete credential clause while leaving a
        # different fragment, or join a fragment to the continuation lines.
        # Check the title we would write together with the uncut remainder.
        fragmented_title = (
            flagged_title is None
            and _ris_multiline_line_carries_userinfo(
                (clean_title or title) + full_text[len(text_lines[0]) :], 0
            )
        )
        if flagged_title is not None or fragmented_title:
            title_end = len(text_lines[0])
            if year_match and year_match.start(1) < title_end:
                year = None
            if doi_match and doi_match.start(1) < title_end:
                doi = None

        # TY - Type of reference (ELEC for electronic source/website)
        lines.append("TY  - ELEC")

        # ID - Reference ID
        lines.append(f"ID  - ref{ref_id}")

        # TI - Title. A source's entire title can itself be a URL, or hold
        # one: a title the shared credential check flags is written as its
        # userinfo-free URL, or as a placeholder when ``_safe_ris_url``
        # keeps no URL for it. The title as written is checked first, since
        # cleaning can cut the @ out of a credential URL; each form a cut
        # makes is checked too, since joining what a cut leaves can spell
        # one (``flagged_title`` above).
        if fragmented_title:
            display_title = "[source URL omitted]"
        elif flagged_title is None:
            display_title = clean_title if clean_title else title
        else:
            display_title = (
                _safe_ris_url(flagged_title) or "[source URL omitted]"
            )
        lines.append(f"TI  - {display_title}")

        # AU - Authors
        for author in authors:
            lines.append(f"AU  - {author}")

        # DO - DOI. Often written as a doi.org URL, so it gets the same
        # credential check as the title; one it flags without a URL that
        # ``_safe_ris_url`` keeps is left out.
        if doi:
            doi = _ris_field_text(str(doi))
        if doi:
            lines.append(f"DO  - {doi}")

        # PY - Publication year (if one was found above)
        if year:
            lines.append(f"PY  - {year}")

        # UR - URL. Legacy reports and LLM-authored Sources may still carry
        # user:password@host even though new reports canonicalize their URLs.
        safe_url = _safe_ris_url(url)
        if safe_url:
            lines.append(f"UR  - {safe_url}")

            # Try to extract domain as publisher
            try:
                from urllib.parse import urlparse

                parsed = urlparse(safe_url)
                # The host alone. The netloc also carries userinfo and port,
                # so https://user:[email protected]/ wrote the token into the
                # .ris file as the publisher (#6837). The root dot of a fully
                # qualified name is dropped, as utilities/arxiv.py does.
                domain = (parsed.hostname or "").rstrip(".")
                if domain.startswith("www."):
                    domain = domain[4:]
                # Extract readable publisher name from domain
                if domain == "github.com" or domain.endswith(".github.com"):
                    lines.append("PB  - GitHub")
                elif domain == "arxiv.org" or domain.endswith(".arxiv.org"):
                    lines.append("PB  - arXiv")
                elif domain == "reddit.com" or domain.endswith(".reddit.com"):
                    lines.append("PB  - Reddit")
                elif (
                    domain == "youtube.com"
                    or domain == "m.youtube.com"
                    or domain.endswith(".youtube.com")
                ):
                    lines.append("PB  - YouTube")
                elif domain == "medium.com" or domain.endswith(".medium.com"):
                    lines.append("PB  - Medium")
                elif domain == "pypi.org" or domain.endswith(".pypi.org"):
                    lines.append("PB  - Python Package Index (PyPI)")
                else:
                    # Use domain as publisher
                    lines.append(f"PB  - {domain}")
            except (ValueError, AttributeError):
                pass

        # Y1 - Year accessed (current year)
        from datetime import UTC, datetime

        current_year = datetime.now(UTC).year
        lines.append(f"Y1  - {current_year}")

        # DA - Date accessed
        current_date = datetime.now(UTC).strftime("%Y/%m/%d")
        lines.append(f"DA  - {current_date}")

        # LA - Language
        lines.append("LA  - en")

        # ER - End of reference
        lines.append("ER  - ")

        # A field can contain bare CR or Unicode line separators even when
        # extracted from one LF-delimited source line. Flatten them at the
        # serialization boundary so only our separators create RIS fields.
        # The credential check reads every value flattened the same way.
        return "\n".join(_ris_flatten(line) for line in lines)


# Body prose is markdown, where "\$" is the escape for a literal
# dollar. The escaper therefore consumes a "\$" pair as ONE token and
# emits "\$" (a literal dollar in LaTeX too); every other special,
# every other backslash included, goes through the _escape_latex_text
# map. Pair-first alternation in a single regex pass means nothing is
# ever escaped twice: "\$" never becomes "\textbackslash{}\$" (which
# would print a stray backslash), and the output never holds "\\"
# (a line break) or a bare "$" (a live math shift).
_LATEX_BODY_TEXT_RE = re.compile(
    r"\\\$|[" + re.escape("".join(_LATEX_TEXT_SPECIALS)) + "]"
)


def _escape_latex_body_text(text: str) -> str:
    r"""Escape a prose segment of the export body in one pass.

    Identical to :func:`_escape_latex_text` except that a markdown
    ``\$`` (escaped dollar) becomes ``\$`` rather than
    ``\textbackslash{}\$``. A backslash run before a dollar pairs only
    its LAST backslash with the dollar; the others are literal
    backslashes (``\\$`` -> ``\textbackslash{}\$``).
    """
    return _LATEX_BODY_TEXT_RE.sub(
        lambda m: (
            "\\$" if m.group() == "\\$" else _LATEX_TEXT_SPECIALS[m.group()]
        ),
        text,
    )


# A blank line ends a block: two line breaks separated only by
# horizontal whitespace and carriage returns. Legacy report_content
# rows store CRLF newlines and LLM prose often leaves spaces or tabs
# on the otherwise blank line, so probing for a literal "\n\n" misses
# real paragraph boundaries; the boundary is matched structurally.
_BLOCK_END = re.compile(r"\r?\n[ \t\r]*\r?\n")

# Verdicts _split_math_segments assigns to each live "$" as the closer
# of the opener before it: acceptable; rejected because a digit follows
# it (a price: "$5-$10"); or rejected because whitespace precedes it.
_CLOSER_OK = 0
_CLOSER_DIGIT = 1
_CLOSER_SPACE = 2


def _split_math_segments(text: str) -> list[tuple[str, bool]]:
    r"""Split *text* into ``(segment, is_math)`` pairs, left to right.

    ``$$...$$`` display spans pair first, then ``$...$`` inline spans.
    Neither kind ever crosses a blank line (pandoc scopes math to a
    single block, so a stray ``$$`` or a price in one paragraph can
    never pair with a delimiter in another; an opener unpaired within
    its block is literal text). An inline span's opening ``$`` must
    not be followed by whitespace, and it closes at the FIRST live
    ``$`` after it in the block, as in pandoc: that closer must not be
    preceded by whitespace and must not be followed by a digit, and if
    it is, the OPENER fails and reads as prose (``$5-$10`` is two
    prices, not ``$5-$`` around ``10``). Rejected closers are never
    stepped over on the way to a farther one, which would emit a span
    holding a raw interior dollar. A closer rejected for the digit
    after it is itself a price and cannot open a span either; pandoc
    would let it open one, so ``$5-$10 per unit ($n$)`` would make
    ``$10 per unit ($`` math there, raw prose between two prices
    (whitespace-rejected closers still open: ``$5 so $x$`` keeps
    ``$x$``). Mistaking math for prose only escapes it; mistaking
    prose for math emits its ``%`` and ``&`` raw. (Mirror case: because
    the rejected closer cannot open, a later ``$`` glued to the text on
    its left can open instead and pair farther on, so
    ``$5-$10 per hour (US$), 50% more (US$)`` makes ``$), 50% more (US$``
    math; this is rarer than the cases the rule prevents.) A ``$``
    preceded by an odd run of backslashes is a literal dollar
    (as in ``\$5``), never an opener or a closer; after an even run
    (``\\$``: the backslashes escape each other) the dollar is as
    live as a bare one, in both directions. Every other dollar is a
    literal character inside a text segment. Math segments include their
    delimiters and are returned verbatim.
    """
    segments: list[tuple[str, bool]] = []
    start = 0  # start of the current text run
    i = 0
    n = len(text)
    # Whether a "$" can close inline math does not depend on the
    # opener, so every live candidate position and its verdict is
    # collected once up front; the pairing below advances one pointer
    # over them, left to right, and never rescans. A "$" ending an odd
    # backslash run is a literal dollar and never a delimiter in
    # either direction: excluded here so the walk cannot CLOSE a span
    # on it, exactly as the "\x" skip below already keeps it from
    # opening one. A "$" after an even run ("\\$": the backslashes
    # escape each other) is live and stays a closer candidate; a
    # single-character lookbehind excluded it too and left "$x\\$"
    # unpaired. That pattern's lookbehind stops it starting mid-run,
    # so each match spans the full run and the scan stays linear
    # even on backslash walls.
    odd_run_dollars = {
        m.end() - 1 for m in re.finditer(r"(?<!\\)(?:\\\\)*\\\$", text)
    }
    dollars = [
        m.start()
        for m in re.finditer(r"\$", text)
        if m.start() not in odd_run_dollars
    ]
    # Whitespace is checked first: a candidate with both flaws ("$fee
    # $5$") is not a price and may still open its own span.
    closer_verdict = [
        _CLOSER_SPACE
        if p > 0 and text[p - 1].isspace()
        else _CLOSER_DIGIT
        if p + 1 < n and text[p + 1] in "0123456789"
        else _CLOSER_OK
        for p in dollars
    ]
    cand = 0  # index into dollars: first candidate after the opener
    price_dollar = -1  # a digit-rejected closer: never an opener
    # First blank line at or after the current position.
    block_end = n
    block_end_known = False
    while i < n:
        if text[i] == "\\":
            # A backslash escapes the next character: "\$" is a
            # literal dollar, never a math delimiter.
            i += 2
            continue
        if text[i] != "$":
            i += 1
            continue
        if i + 1 < n and text[i + 1] == "$":
            # A display opener pairs only inside its own block, so a
            # stray "$$" in one paragraph cannot capture a genuine
            # display span in another (a blank line is never inside
            # math). The closer scan walks the block: "\x" pairs are
            # skipped (an interior "\$" is a literal dollar, and the
            # "$" of "\$$" is not the lead of a closer), the first
            # raw single "$" means the opener is unpaired (a display
            # span has no single-dollar interior), and the first raw
            # "$$" closes.
            if not block_end_known or i > block_end:
                boundary = _BLOCK_END.search(text, i)
                block_end = boundary.start() if boundary is not None else n
                block_end_known = True
            close = -1
            j = i + 2
            while j < block_end:
                if text[j] == "\\":
                    j += 2
                elif text[j] == "$":
                    if j + 1 < n and text[j + 1] == "$":
                        close = j
                    break
                else:
                    j += 1
            if close != -1:
                segments.append((text[start:i], False))
                segments.append((text[i : close + 2], True))
                i = close + 2
                start = i
            else:
                # Unpaired $$ within its block: literal text, like
                # any lone dollar.
                i += 2
            continue
        # Single '$': find a closing '$' the rules accept, without
        # leaving the paragraph (inline math never crosses a blank
        # line).
        if i == price_dollar or (i + 1 < n and text[i + 1].isspace()):
            i += 1
            continue
        # The first blank line at or after i only moves forward as i
        # does, so the search is cached until i passes its match.
        if not block_end_known or i > block_end:
            boundary = _BLOCK_END.search(text, i)
            block_end = boundary.start() if boundary is not None else n
            block_end_known = True
        # The closer is the first live "$" after the opener. Openers
        # only move right, so the pointer does too.
        while cand < len(dollars) and dollars[cand] <= i:
            cand += 1
        verdict = (
            closer_verdict[cand]
            if cand < len(dollars) and dollars[cand] < block_end
            else None
        )
        if verdict == _CLOSER_OK:
            closer = dollars[cand]
            segments.append((text[start:i], False))
            segments.append((text[i : closer + 1], True))
            i = closer + 1
            start = i
        else:
            # No closer in this block, or the first one is preceded
            # by whitespace or followed by a digit: the opener fails
            # (never stepped past to a farther "$") and is a literal
            # dollar. A digit-rejected closer is a price as well.
            if verdict == _CLOSER_DIGIT:
                price_dollar = dollars[cand]
            i += 1
    segments.append((text[start:], False))
    return segments


# Math in a report may come from retrieved pages through the LLM. TeX executes
# control sequences when a user compiles an exported .tex file, so preserving
# every matched $...$ span verbatim is unsafe. Only math commands that the
# LaTeX kernel itself defines are accepted, because the export preamble loads
# no math package: \text, \binom and \operatorname (amsmath) and \mathbb
# (amsfonts) would be undefined there, so spans using them are rendered as
# literal text. Each accepted command is a math symbol, delimiter
# or accent, or a TeX primitive or kernel macro that only typesets (boxes,
# spacing, font changes). None of them lets the report's text open or write
# a file, run a shell command, change a category code or define a macro.
# Every character in an argument is checked by the same scanner, so an
# allowed command cannot hide a second one.
_SAFE_MATH_COMMANDS = frozenset(
    {
        # Greek letters, lower case. There is no \omicron: it is "o".
        "alpha",
        "beta",
        "gamma",
        "delta",
        "epsilon",
        "varepsilon",
        "zeta",
        "eta",
        "theta",
        "vartheta",
        "iota",
        "kappa",
        "lambda",
        "mu",
        "nu",
        "xi",
        "pi",
        "varpi",
        "rho",
        "varrho",
        "sigma",
        "varsigma",
        "tau",
        "upsilon",
        "phi",
        "varphi",
        "chi",
        "psi",
        "omega",
        # Greek letters, upper case. The others (A, B, E, ...) are Latin.
        "Gamma",
        "Delta",
        "Theta",
        "Lambda",
        "Xi",
        "Pi",
        "Sigma",
        "Upsilon",
        "Phi",
        "Psi",
        "Omega",
        # Binary operators.
        "pm",
        "mp",
        "times",
        "div",
        "cdot",
        "ast",
        "star",
        "circ",
        "bullet",
        "setminus",
        "cap",
        "cup",
        "uplus",
        "sqcap",
        "sqcup",
        "vee",
        "wedge",
        "land",
        "lor",
        "oplus",
        "ominus",
        "otimes",
        "oslash",
        "odot",
        "dagger",
        "ddagger",
        "amalg",
        "diamond",
        "wr",
        "bigcirc",
        "triangleleft",
        "triangleright",
        "bigtriangleup",
        "bigtriangledown",
        # Relations, including the \le, \ge and \ne short forms and \not,
        # which overlays a slash on the relation after it.
        "leq",
        "le",
        "geq",
        "ge",
        "neq",
        "ne",
        "ll",
        "gg",
        "prec",
        "succ",
        "preceq",
        "succeq",
        "sim",
        "simeq",
        "approx",
        "cong",
        "equiv",
        "doteq",
        "propto",
        "asymp",
        "perp",
        "parallel",
        "mid",
        "models",
        "vdash",
        "dashv",
        "smile",
        "frown",
        "bowtie",
        "in",
        "ni",
        "owns",
        "notin",
        "subset",
        "supset",
        "subseteq",
        "supseteq",
        "sqsubseteq",
        "sqsupseteq",
        "not",
        # Arrows.
        "to",
        "gets",
        "leftarrow",
        "rightarrow",
        "leftrightarrow",
        "Leftarrow",
        "Rightarrow",
        "Leftrightarrow",
        "longleftarrow",
        "longrightarrow",
        "longleftrightarrow",
        "Longleftarrow",
        "Longrightarrow",
        "Longleftrightarrow",
        "iff",
        "mapsto",
        "longmapsto",
        "hookleftarrow",
        "hookrightarrow",
        "uparrow",
        "downarrow",
        "updownarrow",
        "Uparrow",
        "Downarrow",
        "Updownarrow",
        "nearrow",
        "searrow",
        "swarrow",
        "nwarrow",
        "leftharpoonup",
        "leftharpoondown",
        "rightharpoonup",
        "rightharpoondown",
        "rightleftharpoons",
        # Other symbols.
        "infty",
        "partial",
        "nabla",
        "forall",
        "exists",
        "neg",
        "lnot",
        "emptyset",
        "aleph",
        "hbar",
        "imath",
        "jmath",
        "ell",
        "wp",
        "Re",
        "Im",
        "prime",
        "top",
        "bot",
        "angle",
        "triangle",
        "surd",
        "flat",
        "natural",
        "sharp",
        "clubsuit",
        "diamondsuit",
        "heartsuit",
        "spadesuit",
        "colon",
        "ldots",
        "cdots",
        "vdots",
        "ddots",
        "dots",
        # Big operators.
        "sum",
        "prod",
        "coprod",
        "int",
        "oint",
        "smallint",
        "bigcap",
        "bigcup",
        "bigsqcup",
        "bigvee",
        "bigwedge",
        "bigodot",
        "bigoplus",
        "bigotimes",
        "biguplus",
        # Named operators, set upright like "log".
        "arccos",
        "arcsin",
        "arctan",
        "arg",
        "cos",
        "cosh",
        "cot",
        "coth",
        "csc",
        "deg",
        "det",
        "dim",
        "exp",
        "gcd",
        "hom",
        "inf",
        "ker",
        "lg",
        "lim",
        "liminf",
        "limsup",
        "ln",
        "log",
        "max",
        "min",
        "Pr",
        "sec",
        "sin",
        "sinh",
        "sup",
        "tan",
        "tanh",
        "bmod",
        "pmod",
        # Delimiters and the commands that size them (\middle is e-TeX).
        "left",
        "right",
        "middle",
        "big",
        "Big",
        "bigg",
        "Bigg",
        "bigl",
        "bigr",
        "Bigl",
        "Bigr",
        "biggl",
        "biggr",
        "Biggl",
        "Biggr",
        "bigm",
        "Bigm",
        "biggm",
        "Biggm",
        "langle",
        "rangle",
        "lfloor",
        "rfloor",
        "lceil",
        "rceil",
        "lbrace",
        "rbrace",
        "lbrack",
        "rbrack",
        "vert",
        "Vert",
        "backslash",
        "lgroup",
        "rgroup",
        "lmoustache",
        "rmoustache",
        "arrowvert",
        "Arrowvert",
        "bracevert",
        # Accents, and lines, braces and arrows set over or under a formula.
        "hat",
        "check",
        "tilde",
        "acute",
        "grave",
        "dot",
        "ddot",
        "breve",
        "bar",
        "vec",
        "mathring",
        "widehat",
        "widetilde",
        "overline",
        "underline",
        "overbrace",
        "underbrace",
        "overrightarrow",
        "overleftarrow",
        # Fractions and roots.
        "frac",
        "sqrt",
        # Math alphabets.
        "mathrm",
        "mathbf",
        "mathit",
        "mathsf",
        "mathtt",
        "mathcal",
        "mathnormal",
        # Math styles and the placement of limits.
        "displaystyle",
        "textstyle",
        "scriptstyle",
        "scriptscriptstyle",
        "limits",
        "nolimits",
        # Spacing. \medspace and \thickspace are left out: the kernel only
        # gained them in 2020, so older TeX installations lack them.
        "quad",
        "qquad",
        "thinspace",
        "negthinspace",
        "enspace",
    }
)
# Control symbols: a backslash and one non-letter. \$ and \\ are the
# literal-dollar and escaped-backslash spans the delimiter scanner already
# supports. \{, \} and \| are delimiters; \, \: \; \! and "\ " are spaces;
# \% \# \& and \_ print the character. "\^" stays out: it would let "\^^"
# hide a ^^ encoding from the check in _math_span_is_safe.
_SAFE_MATH_CONTROL_SYMBOLS = frozenset("$\\{}|,:;! %#&_")
_ASCII_MATH_LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
# "'" is the prime, as in f'(x). "\r" is handled in _math_span_is_safe.
_SAFE_MATH_CHARACTERS = frozenset(
    _ASCII_MATH_LETTERS + "0123456789 \t\n+-*/=.,:;!?(){}[]^_<>|'"
)


def _math_span_is_safe(segment: str) -> bool:
    """Accept only inert math syntax inside a matched inline/display span."""
    delimiter = "$$" if segment.startswith("$$") else "$"
    body = segment[len(delimiter) : -len(delimiter)]
    depth = 0
    position = 0
    while position < len(body):
        character = body[position]
        if character == "\\":
            position += 1
            if position == len(body):
                return False
            if body[position] in _ASCII_MATH_LETTERS:
                start = position
                while (
                    position < len(body)
                    and body[position] in _ASCII_MATH_LETTERS
                ):
                    position += 1
                if body[start:position] not in _SAFE_MATH_COMMANDS:
                    return False
                continue
            if body[position] not in _SAFE_MATH_CONTROL_SYMBOLS:
                return False
            position += 1
            continue
        if character == "\r":
            # Legacy report_content rows store CRLF newlines, and TeX reads a
            # CRLF pair as one line break. TeX also ends a line at a lone CR,
            # which _BLOCK_END does not see, so "\r\r" could hide a blank line
            # (a paragraph break) inside a span; a lone CR stays literal.
            if not body.startswith("\n", position + 1):
                return False
            position += 1
            continue
        if character not in _SAFE_MATH_CHARACTERS:
            return False
        # TeX turns ^^5c (and longer ^^ encodings) into a backslash before
        # it recognizes control sequences. A character-only allowlist would
        # otherwise accept an encoded \input with no literal backslash.
        if character == "^" and body.startswith("^^", position):
            return False
        if character == "{":
            depth += 1
        elif character == "}":
            depth -= 1
            if depth < 0:
                return False
        position += 1
    return depth == 0


# Pandoc's markdown reader treats a backslash before any ASCII punctuation
# character as that literal character (the ``all_symbols_escapable``
# extension, on by default), so escaping every punctuation character in a
# span renders it as text: a ``$`` no longer shifts into math
# (``tex_math_dollars`` needs an unescaped ``$``) and the backslash of a
# command such as ``\input`` becomes a literal backslash, not a control
# sequence, even while ``raw_tex`` is on. Letters and digits are left as
# they are; only the characters that could carry meaning are neutralised.
_MARKDOWN_PUNCTUATION_RE = re.compile(r"[!-/:-@\[-`{-~]")


def _escape_markdown_math_span(segment: str) -> str:
    r"""Render a rejected ``$...$``/``$$...$$`` span as inert Markdown text.

    Backslash-escapes every ASCII punctuation character, so Pandoc reads the
    span as literal characters rather than math or raw TeX.
    """
    return _MARKDOWN_PUNCTUATION_RE.sub(r"\\\g<0>", segment)


def _defuse_report_math_for_quarto(content: str) -> str:
    r"""Escape every unsafe math span in a Quarto report body.

    The Quarto front matter declares a ``pdf`` format, so ``quarto render``
    hands each ``$...$``/``$$...$$`` span to Pandoc's LaTeX writer, which
    emits math verbatim. A span is kept as math only when
    :func:`_math_span_is_safe` accepts it — the same allowlist the LaTeX
    export applies — and every other span is escaped to literal text so it
    never reaches the TeX engine. Prose between spans is returned untouched
    for the citation and cell passes that run after it.
    """
    parts: list[str] = []
    for segment, is_math in _split_math_segments(content):
        if is_math and not _math_span_is_safe(segment):
            parts.append(_escape_markdown_math_span(segment))
        else:
            parts.append(segment)
    return "".join(parts)


# The start of a citation link as CitationFormatter writes it: the label
# in double brackets, then the destination. Every hyperlinked mode uses this
# shape; only the label differs ([[1]], [[arxiv.org]], [[arxiv.org-2]],
# [[doi-1]]).
_CITATION_LINK_START_RE = re.compile(r"\[\[([^\[\]\n]+)\]\]\(")
_CITATION_GROUP_LABEL_RE = re.compile(r"\s*\d+(?:\s*,\s*\d+)+\s*")


def _link_destination_ends(text: str) -> array:
    """For every index, where a link destination starting there ends.

    ``_safe_link_destination`` percent-encodes spaces and any unbalanced
    parenthesis, so a destination it wrote ends at the first ``)`` that
    closes no ``(`` of its own, as in ``https://en.wikipedia.org/wiki/A_(b)``.
    ``ends[i]`` is the index of that ``)`` for a destination starting at
    ``i``, or -1 when whitespace or the end of the text comes first.

    One pass from the right answers every start at once. Scanning forward
    from each ``[[a]](`` instead costs quadratic time on a text full of
    destinations that never close: 20 000 of them took about 40 seconds.
    """
    ends = array("q", [-1]) * (len(text) + 1)
    for position in range(len(text) - 1, -1, -1):
        character = text[position]
        if character == ")":
            ends[position] = position
        elif character == "(":
            # This parenthesis is closed where a destination starting just
            # after it would end; the destination then carries on from there.
            inner = ends[position + 1]
            ends[position] = -1 if inner == -1 else ends[inner + 1]
        elif not character.isspace():
            ends[position] = ends[position + 1]
    return ends


class LaTeXExporter:
    """Export markdown documents to LaTeX format."""

    def __init__(self):
        # Also match Unicode lenticular brackets 【】 (U+3010 and U+3011) that LLMs sometimes generate
        self.citation_pattern = re.compile(r"[\[【](\d+)[\]】]")
        self.comma_citation_pattern = re.compile(
            r"[\[【](\d+(?:\s*,\s*\d+)+)[\]】]"  # (#6944) space allowed BEFORE the comma too — a hand-edited `[[2 ,3]]` must stay a group
        )
        self.heading_patterns = [
            (re.compile(r"^# (.+)$", re.MULTILINE), r"\\section{\1}"),
            (re.compile(r"^## (.+)$", re.MULTILINE), r"\\subsection{\1}"),
            (re.compile(r"^### (.+)$", re.MULTILINE), r"\\subsubsection{\1}"),
        ]
        self.emphasis_patterns = [
            (re.compile(r"\*\*(.+?)\*\*"), r"\\textbf{\1}"),
            (re.compile(r"\*(.+?)\*"), r"\\textit{\1}"),
            (re.compile(r"`(.+?)`"), r"\\texttt{\1}"),
        ]

    def export_to_latex(self, content: str) -> str:
        """
        Convert markdown document to LaTeX format.

        Args:
            content: Markdown content

        Returns:
            LaTeX formatted content
        """
        latex_content = self._create_latex_header()

        # Convert markdown to LaTeX. A saved report was citation-formatted
        # before it was stored, so its citations arrive as links.
        entries = self._sources_entries(content)
        body_content = self._unlink_citations(content, entries)

        # Escape special LaTeX characters while preserving safe math. A
        # left-to-right scanner pairs $$...$$ display spans and $...$
        # inline spans; accepted spans pass through verbatim and rejected
        # spans are rendered as literal text. Every other dollar
        # is prose. The previous whole-document split made ONE unpaired
        # dollar (a price in prose) invert the parity and silently
        # disable escaping for the rest of the report.
        escaped_parts: list[str] = []
        at_line_start = True
        for segment, is_math in _split_math_segments(body_content):
            if is_math and _math_span_is_safe(segment):
                escaped_parts.append(segment)
            else:
                lines = segment.split("\n")
                for j, line in enumerate(lines):
                    # Escape every LaTeX-special character outside math
                    # mode. Markdown markers (*, `, [n]) are not
                    # LaTeX-special and survive for their own
                    # conversions below.
                    heading = (
                        _HEADING_PREFIX_RE.match(line)
                        if j > 0 or at_line_start
                        else None
                    )
                    if heading:
                        # Keep the '#' markers intact for the heading
                        # conversion; escape the text after them so
                        # \section{...} receives literal text only. Only
                        # a TRUE line start qualifies: a text segment
                        # that resumes mid-line after a math span
                        # ("$x$ # y") is prose, and its "#" is escaped.
                        lines[j] = heading.group(1) + _escape_latex_body_text(
                            heading.group(2)
                        )
                    else:
                        lines[j] = _escape_latex_body_text(line)
                escaped_parts.append("\n".join(lines))
            if segment:
                at_line_start = segment.endswith("\n")
        body_content = "".join(escaped_parts)

        # Convert headings
        for pattern, replacement in self.heading_patterns:
            body_content = pattern.sub(replacement, body_content)

        # Convert emphasis
        for pattern, replacement in self.emphasis_patterns:
            body_content = pattern.sub(replacement, body_content)

        # Convert citations to LaTeX \cite{} format
        # A group becomes one \\cite only when the Sources section lists every
        # member, as CitationFormatter only links the members it can resolve;
        # otherwise it is prose such as "versions [4, 5]" and is left as written.
        def cite_group(match: re.Match[str]) -> str:
            nums = [num.strip() for num in match.group(1).split(",")]
            if all(num in entries for num in nums):
                return "\\cite{" + ",".join(nums) + "}"
            return match.group(0)

        def cite_single(match: re.Match[str]) -> str:
            num = match.group(1)
            if num in entries:
                return "\\cite{" + num + "}"
            return match.group(0)

        body_content = self.comma_citation_pattern.sub(cite_group, body_content)
        body_content = self.citation_pattern.sub(cite_single, body_content)

        # Convert lists
        body_content = self._convert_lists(body_content)

        # Add body content
        latex_content += body_content

        # Add bibliography section
        latex_content += self._create_bibliography(content)

        # Add footer
        latex_content += self._create_latex_footer()

        return latex_content

    def _sources_entries(self, content: str) -> dict:
        """The Sources entries, from the same slice the bibliography reads."""
        sources_start, _on_sentinel = find_sources_section(content)
        if sources_start == -1:
            return {}
        return _collect_bibliography_entries(content[sources_start:])

    def _unlink_citations(self, content: str, entries: dict) -> str:
        """Turn the formatter's ``[[label]](url)`` citations back into ``[N]``.

        A number label is the citation index. A group label such as ``1, 2``
        names every member, which its one URL cannot, so it becomes ``[1, 2]``
        when the Sources list has every member. Any other label
        (``arxiv.org``, ``arxiv.org-2``, ``doi-1``) says nothing reliable
        about the index, so the link's destination is looked up among the
        Sources entries instead; when two entries share a URL, the lower
        index is used, since both name the same document. A link that
        resolves to no entry is left as written.
        """
        # Keyed on the destination the formatter would have written. Two URLs
        # that differ only in how a character is spelled, such as `a(b` and
        # `a%28b`, share a key, and the lower index keeps it.
        index_by_destination: Dict[str, str] = {}
        for index in sorted(entries, key=_sort_key):
            destination = _safe_link_destination(entries[index][1])
            if destination:
                index_by_destination.setdefault(destination, index)

        parts = []
        position = 0
        ends = None
        for match in _CITATION_LINK_START_RE.finditer(content):
            if match.start() < position:
                continue
            if ends is None:
                ends = _link_destination_ends(content)
            end = ends[match.end()]
            if end == -1:
                continue
            label = match.group(1)
            if label.isdecimal():
                if label not in entries:
                    continue
                index = label
            elif _CITATION_GROUP_LABEL_RE.fullmatch(label):
                members = [member.strip() for member in label.split(",")]
                if not all(member in entries for member in members):
                    continue
                index = label.strip()
            else:
                index = index_by_destination.get(content[match.end() : end])
                if index is None:
                    continue
            parts.append(content[position : match.start()])
            parts.append(f"[{index}]")
            position = end + 1
        parts.append(content[position:])
        return "".join(parts)

    def _create_latex_header(self) -> str:
        """Create LaTeX document header."""
        return r"""\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\usepackage{cite}
\usepackage{url}

\title{Research Report}
\date{\today}

\begin{document}
\maketitle

"""

    def _create_latex_footer(self) -> str:
        """Create LaTeX document footer."""
        return "\n\\end{document}\n"

    def _escape_latex(self, text: str) -> str:
        """Escape special LaTeX characters in text."""
        return _escape_latex_text(text)

    def _convert_lists(self, content: str) -> str:
        """Convert markdown lists to LaTeX format."""
        # Simple conversion for bullet points
        content = re.sub(r"^- (.+)$", r"\\item \1", content, flags=re.MULTILINE)

        # Add itemize environment around list items
        lines = content.split("\n")
        result = []
        in_list = False

        for line in lines:
            if line.strip().startswith("\\item"):
                if not in_list:
                    result.append("\\begin{itemize}")
                    in_list = True
                result.append(line)
            else:
                if in_list and line.strip():
                    result.append("\\end{itemize}")
                    in_list = False
                result.append(line)

        if in_list:
            result.append("\\end{itemize}")

        return "\n".join(result)

    def _create_bibliography(self, content: str) -> str:
        """Extract sources and create LaTeX bibliography."""
        sources_start, _on_sentinel = find_sources_section(content)
        if sources_start == -1:
            return ""

        sources_content = content[sources_start:]
        entries = _collect_bibliography_entries(sources_content)

        # The argument is the widest label, which sets the hanging indent. It
        # is never narrower than the two digits it has always been.
        widest = "9" * max([2, *(len(key) for key in entries)])
        bibliography = f"\n\\begin{{thebibliography}}{{{widest}}}\n"

        for citation_num in sorted(entries, key=_sort_key):
            title, url = entries[citation_num]
            escaped_title = self._escape_latex(title)

            # thebibliography numbers entries by POSITION unless a label
            # is given, so without one a gap in the index sequence makes
            # \\cite{5} print [3]. The label is the index the report shows,
            # as written: 007 stays 007, and a non-digit key such as a 7a
            # sub-index would be printed as it is too.
            item = f"\\bibitem[{citation_num}]{{{citation_num}}}"
            safe_url = _safe_bibtex_url(url)
            if safe_url:
                bibliography += f"{item} {escaped_title}. \\url{{{safe_url}}}\n"
            else:
                bibliography += f"{item} {escaped_title}.\n"

        bibliography += "\\end{thebibliography}\n"

        return bibliography