def analyze_quotations(text: str) -> QuotationResult:
"""Find outer quoted spans and nearby English reporting verbs.
Supports straight and curly quotes and guillemets. Quoted titles and scare
quotes are included alongside speech.
Args:
text: Prepared body whose character offsets should be preserved.
Returns:
Quotations and diagnostics for unmatched quotes or normalized delimiters.
Raises:
TypeError: If `text` is not a string.
"""
if not isinstance(text, str):
raise TypeError("text must be str")
spans, issues = [], []
index = 0
while index < len(text):
opening = text[index]
if (
opening not in _PAIRS
or _escaped(text, index)
or (opening in {"'", "‘"} and index and text[index - 1].isalnum())
):
index += 1
continue
closing = index + 1
while closing < len(text):
if text[closing] == _PAIRS[opening] and not _escaped(text, closing):
if opening not in {"'", "‘"} or not _apostrophe(text, closing):
break
closing += 1
if closing == len(text):
issues.append(QuotationIssue(index, len(text), "unclosed_quote"))
index += 1
continue
start, end = index + 1, closing
while start < end and text[start].isspace():
start += 1
while end > start and text[end - 1].isspace():
end -= 1
if start < end:
spans.append((index, closing, start, end))
index = closing + 1
mentions = []
for position, (opening_offset, closing, start, end) in enumerate(spans):
quote = text[start:end]
if not text_component(quote, separators="#|"):
issues.append(QuotationIssue(start, end, "empty_after_normalization"))
continue
if any(c in quote for c in "#|"):
issues.append(QuotationIssue(start, end, "normalized_delimiter"))
previous_end = spans[position - 1][1] + 1 if position else 0
next_start = spans[position + 1][0] if position + 1 < len(spans) else len(text)
mentions.append(
QuotationMention(
quote, start, end, _verb(text, opening_offset, closing, previous_end, next_start)
)
)
return QuotationResult(tuple(mentions), tuple(sorted(issues, key=lambda issue: issue.start)))