In praise of defined terms

Defined terms, defined

Defined terms relieve the drafter and the reviewer from having to redefine with every use.

“Business Day” means any day other than a Saturday, a Sunday, or a day on which commercial banks in New York City are authorized or required by law or executive order to close.

By convention, these are identified by the use of title case.

Challenges

As a deal lawyer, you find yourself doing a lot of drafting of agreements. Drafting is one of those legal terms of art. It means, usually, starting not from a blank sheet but from an example. There are four principal starting points, from simplest to most complex.

As anyone who has ever struggled through one knows, there are some hazards to navigate.

Differing starting points raise different challenges. The form and model should be good, and it’s just a matter of taking care not to introduce errors. Freewriting still poses issues because you seldom start from a blank piece of paper — you usually are assembling bits and pieces.1 The most challenging is the markup.

Depending on your style, editing for defined terms may involve a lot of page flipping or searches, and can take some interim cold reads to get right.

Figure 1: Got defined terms?

AI is the wrong tool

You might think to turn to AI. That’s neither necessary or even desirable. For example, I gave ChatGPT 5.6-Luna medium effort the following: a short services contract and a prompt

Find defined terms (title cased words and phrases) that are undefined, multiply defined, or defined but never used.

I got

Undefined or insufficiently defined

  • Consultant IP — used repeatedly, but its operative definition is only attributed to Agreement § (a)(iii)(b); the letter does not state the complete definition.
  • Fees — capitalized in “agreed-upon Fees,” but never defined in the letter.
  • Task ID — used in “Task ID: 6119019,” but not defined.
  • Work Item — used with several numerical identifiers, but not defined.
  • Ready for Delivery — presented as a contractual/platform status, but not expressly defined.
  • Client Warranties — the letter refers to “client warranties of clean title and non-infringement,” without identifying or defining those warranties.
  • Prong B — used as shorthand for the statutory ABC-test prong, but not explained or defined.

Multiply defined

  • Agreement — defined twice:

    1. “Independent Contractor Agreement (the ‘Agreement’)”
    2. “LinkedIn Consulting Agreement (AI Trainer) dated September 9, 2026 (the ‘Agreement’)”

    These may refer to the same contract, but the letter’s wording makes the duplicate definition ambiguous.

Defined but apparently never used

  • No clear defined term is completely unused.

The first long-form label, Independent Contractor Agreement, is not reused, but the defined term Agreement is used extensively. Similarly, the later long-form title LinkedIn Consulting Agreement (AI Trainer) is not reused independently, but its defined term Agreement is used.

Compare and contrast

Defined-term scan: sample_contract.docx

Page numbers from: Word’s cached layout (lastRenderedPageBreak). Section references are taken from numbering typed in the text.

CheckCount
Defined terms found49
Used but not defined (likely terms)15
Used but not defined (likely proper nouns)9
Defined but not used4
Defined more than once2
Used only inside the definitions2

1. Used but not defined

Likely terms
TermUsesPagesSectionsNote
Subscription Fees82, 3, 6, 8, 9, 11§1.11, §1.17, §4.1, §7.2, §8.1, §10.2, §10.4contains defined: Fees
Bellevue11Preamble
Cascadia Regional Logistics Group11Preamble
Data Analytics Agreement112§11.7contains defined: Agreement
God12§1.12
Intellectual Property15§2.2near defined term “Intellectual Property Rights”
Invoice14§1.30
Master Enterprise Software-as-a-Service112§11.7
Parquet111§10.4
Seattle11Preamble
Trojan13§1.16
Type II17§6.1
Usage Restrictions110§9.3
Vanguard Predictive Systems11Preamble
Vanguard RouteCore™13§1.20
Bellevue11Preamble
Cascadia Regional Logistics Group11Preamble
Data Analytics Agreement112§11.7contains defined: Agreement
God12§1.12
Intellectual Property15§2.2near defined term “Intellectual Property Rights”
Invoice14§1.30
Master Enterprise Software-as-a-Service112§11.7
Parquet111§10.4
Seattle11Preamble
Trojan13§1.16
Type II17§6.1
Usage Restrictions110§9.3
Vanguard Predictive Systems11Preamble
Vanguard RouteCore™13§1.20
Likely proper nouns, names and statutes (review, then add to the allow list)
TermUsesPagesSectionsNote
Washington41, 11Preamble, §11.1
Bellevue Way NE11Preamble
California Consumer Privacy Act13§1.19
Delaware11Preamble
Fifth Avenue11Preamble
King County111§11.1
State of Washington111§11.1
United States Dollars16§4.1
Washington My Health My Data Act13§1.19
Compounds of defined terms (not themselves defined)
PhraseUsesPagesSectionsNote
Professional Services Fees52, 4, 5, 6§1.11, §1.24, §2.3, §3.1, §4.1

2. Defined but not used

TermDefined atPage
How definedSLA§1.23
4glossaryUndated
§1.304glossary
Net 30§4.16
parentheticalTerm§10.1
10parenthetical

3. Other findings

Defined more than once
TermDefinitions atPages
SOW§1.24, §2.34, 5
Updates§1.28, §1.294
Glossary entries with no operative verb (“means”)
Undated§1.30, p. 4
Used only inside the definitions
TermUsesSections
Entity4§1.2
Personal Data2§1.3, §1.7
Defined multi-word terms appearing without full capitalization (may be intentional)
Defined termAs writtenPagesSections
Intellectual Property RightsIntellectual Property rights5§2.2
Statement of Workstatement of work5§2.3
Confidential Informationconfidential information8§6.3
Effective Dateeffective date11§10.4
Exhibits and schedules referenced
AttachmentReferencesPagesHeading found in this file
Exhibit A14NO
Exhibit B11NO

4. All defined terms

TermDefined atDef. pageHow definedUsesPages used
Acceptable Use Policy§1.11glossary24, 9
Affiliate§1.21glossary53, 8, 9, 12
Aggregated De-Identified Data§1.32glossary37
AgreementPreamble1parenthetical401, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12
Authorized User§1.42glossary132, 3, 4, 5, 7
Change Order§1.52glossary16
Claim§8.19parenthetical69, 10
Confidential Information§1.62glossary82, 8
control§1.21in-text41, 2, 10, 12
CustomerPreamble1parenthetical731, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Customer Data§1.72glossary162, 3, 7, 9, 11
Deliverables§1.82glossary42, 4, 5, 9
Disclosing Party§1.62parenthetical68
Documentation§1.92glossary92, 4, 5, 7, 8
Effective DatePreamble1parenthetical210, 12
Entity§1.102glossary41
Excluded Claims§9.310parenthetical210
Feedback§5.47parenthetical27
Fees§1.112glossary202, 3, 4, 5, 6, 8, 9, 10, 11
Force Majeure Event§1.122glossary211
General Liability Cap§9.210parenthetical110
Hosted Services§1.133glossary331, 2, 3, 4, 5, 6, 7, 8, 9
Intellectual Property Rights§1.143glossary47, 9
Law§1.153glossary103, 5, 6, 8, 9, 11
Malicious Code§1.163glossary25, 8
Net 30§4.16parenthetical0
Order Form§1.173glossary172, 3, 4, 6, 8, 9, 10, 11, 12
PartiesPreamble1in-text121, 2, 3, 4, 7, 11, 12
PartyPreamble1in-text342, 3, 8, 9, 10, 11, 12
Permitted Affiliate§1.183glossary42, 5, 7
Personal Data§1.193glossary22
Platform§1.203glossary102, 3, 5, 7, 9
Professional Services§1.213glossary102, 4, 5, 6, 7
ProviderPreamble1parenthetical701, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Receiving Party§1.62parenthetical58
Renewal Term§10.210parenthetical24, 11
Retrieval Period§10.411parenthetical111
Security Incident§1.223glossary47, 8, 10
Service Level Agreement§1.234glossary14
SLA§1.234glossary0
SOW§1.24, §2.34, 5glossary66, 11, 12
Statement of Work§1.244glossary82, 3, 5, 6, 10, 12
Subscription Term§1.254glossary152, 3, 4, 5, 7, 8, 9, 10, 11
System Administrator§1.264glossary22, 5
Taxes§4.36parenthetical16
Term§10.110parenthetical0
Third-Party Integrations§1.274glossary56, 9
Undated§1.304glossary0
Updates§1.28, §1.294glossary23, 7

5. Excluded tokens

Sentence-initial stop words (capitalized only at the start of a sentence)

All (4), Any (1), As (2), Each (3), Either (1), Following (1), For (2), If (6), In (2), NOW (1), Neither (2), No (2), Nothing (1), Notwithstanding (1), Subject (1), The (4), This (4), Undisputed (1), Unless (2), Upon (2), WHEREAS (2)

Acronyms and all-caps tokens (not treated as terms)

AES-256 (1), API (3), APIs (3), CSV (1), ERP (1), ISO/IEC (1), JSON (1), SOC (1), THEREFORE (1), TLS (1), WMS (1)

Built-in allow list

Annex, Annexes, Appendices, Appendix, April, Article, Articles, August, By, Clause, Clauses, Co, Co., Corp, Corp., Date, December, Dr, Exhibit, Exhibits, February, Friday, I, Inc, Inc., January, July, June, L.L.C., LLC, LLP, Ltd, Ltd., March, May, Monday, Mr, Mrs, Ms, N.A., Name, November, October, Paragraph, Paragraphs, Recital, Recitals, Saturday, Schedule, Schedules, Section, Sections, September, Subsection, Subsections, Suite, Sunday, Thursday, Title, Tuesday, Wednesday

It’s not perfect

This is a time-savings approach, not a complete solution. Its purpose is to serve as a checklist. One unfortunate side effect is that it reduces the time that a lawyer in training spends reading and rereading a form of agreement over, and over again, until by a mysterious process of osmosis the substantive underpinning is assimilated.

But it does save time

Programmatic methods like this don’t have to be perfect to be helpful. For example, a competent administrative assistant should be able to produce the report and also return the included annotated docx file, freeing you to do more interesting work.

Figure 2: Annotated Word file

How it’s done

A script in the Python programming language produces this from a docx (Word) document, in no time to speak of.

Wait! Lawyers are supposed to be programmers now?

If any of you could add, subtract, multiply or divided, you would be across campus at the B. school. Wm Daniel Fessler to my Contracts class in 1L at King Hall

The good news is twofold:

How I summoned this from the vasty deep

Prompt to Claude Fable 5.2, Medium: I would like to do a contract scan for defined terms to find page references in a docx for the following:

Used but not defined

defined but not used page references to both comments inline for both

A defined term is assumed to be one or more words in title case either in a separate section of the contract such as defined terms where it is usually in quotation marks but may not be, or in a parenthetical or clause in the text, such as (hereinafter the “Company”). The routine should exclude initial caps following whitespace such as “The” and should return a list of such stop words.

This could be done as a lex/yacc grammar to be compiled for very long (300 page) documents if required for speed, otherwise Python is fine.

Have I missed anything?

The advice I received

Your spec covers the core, but it has one structural gap (page numbers) and several smaller ones.

The main gap: a .docx has no pages

Pagination is computed at render time, so “page references” needs a decision:

Render to PDF and map terms to pages. This is the reliable route, but LibreOffice pagination can drift from Word’s by a page or more over 300 pages. Having Word itself produce the PDF gives the pages a reader will actually see. Read Word’s cached page-break markers (lastRenderedPageBreak). This is fast but only present if Word last saved the file, and they are not always accurate. Report section references as well (e.g., § 4.2(b)). They survive repagination and are what a drafter will cite. Section numbers are usually auto-numbering rather than text, so they have to be computed.

You also need to choose between the physical page and the displayed page number (roman-numeral front matter, exhibits that restart numbering).

Definition patterns beyond the two you named Other forms: “X means / shall mean / has the meaning set forth in Section Y”; (each, a “Lender” and collectively, the “Lenders”); and terms defined by bold, italic, or underline without quotation marks, which requires reading run formatting. Incorporation by reference: “Capitalized terms not defined herein have the meanings given in the [Pooling and Servicing Agreement].” Without handling this, the used-but-not-defined list fills with false positives. Term shapes: lowercase connectors (“Change of Control”), digits and hyphens (“Class A-1 Certificates”), and all-caps acronyms (“REMIC”). Matching rules: plurals and possessives, and longest-match for nested terms (“Closing Date” vs. “Closing”). Additional report categories Defined more than once, especially with different definitions. Used only inside its own or other definitions, which is effectively unused. Used in lowercase where a defined term exists (“the agreement” vs. “Agreement”). This is noisy, so make it optional. Noise control beyond sentence-initial words Sentence-initial words: these cannot simply be dropped, because defined terms often start sentences (“Borrower shall…”). Treat a sentence-initial capital as a stop-word candidate only if it never appears capitalized mid-sentence. This also produces your stop-word list empirically. Proper nouns and structure: proper nouns and statutes (Delaware, Securities Act), months and days, cross-reference words (Section, Article, Exhibit, Schedule), headings, the table of contents, the cover page, signature blocks, and all-caps disclaimer paragraphs. Allow-list: a user-editable list alongside the stop list, so the second run is cleaner than the first. Docx mechanics Split runs: terms are often split across multiple runs in the XML, so matching has to happen on reassembled paragraph text and then map back to runs for comment anchoring. Tracked changes: exclude deleted text and include insertions. Scope: decide whether footnotes, tables, text boxes, headers and footers, exhibits, and schedules are in or out. Comment density: a comment on every occurrence of an undefined term will bury a 300-page document. I suggest a comment at the first occurrence listing the other pages, and at the definition for unused terms, written to a copy with existing comments preserved. Lex/yacc

It is not needed. A 300-page contract is about 150,000 words, and a two-pass Python scan (harvest definitions, then match with one compiled alternation) runs in seconds. The slow step is rendering for page numbers, which a compiled scanner does not help. The problem is also not really grammatical: definitions are a handful of local patterns, and usage detection is dictionary matching.

Voilà!

The following script produces the helpful tables above. The hardest part may be getting permission from the IT gods to install the programming language on your PC if it is locked down. If you have so much autonomy as to be able to install yourself, or want to do this on your own equipment, setup is not hard and any competent chat app can walk you through it.

#!/usr/bin/env python3
"""
defterms.py -- defined-term scan for contracts in .docx

Reports
  1. terms used but not defined
  2. terms defined but not used
  3. page (and section) references for both
  4. Word comments anchored inline for both (written to a copy)
plus: duplicate definitions, definitions with no operative verb, terms used
only inside the definitions, near-miss capitalisation, and the list of
sentence-initial stop words that were excluded.

Usage
  python3 defterms.py contract.docx [-o OUTDIR] [--pages auto|word|pdf|none]
                      [--comments first|all|none] [--allow FILE] [--stop FILE]

Requires python-docx >= 1.2 (comments API) and lxml.  --pages pdf needs
LibreOffice (soffice) and pdftotext on PATH.
"""
import argparse, copy, difflib, os, re, shutil, subprocess, sys, tempfile, unicodedata
from collections import Counter, defaultdict, OrderedDict

from docx import Document
from docx.text.run import Run
from docx.text.paragraph import Paragraph

W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
XML = "http://www.w3.org/XML/1998/namespace"
def q(tag): return "{%s}%s" % (W, tag)

# ----------------------------------------------------------------- lexicon
CONNECTORS = {"of", "and", "the", "for", "to", "in", "or", "a", "an", "on", "by", "with"}
ALLOW_BUILTIN = set("""
Section Sections Article Articles Exhibit Exhibits Schedule Schedules Annex Annexes
Appendix Appendices Clause Clauses Paragraph Paragraphs Subsection Subsections Recital Recitals
January February March April May June July August September October November December
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Inc Inc. LLC L.L.C. LLP Ltd Ltd. Corp Corp. Co Co. N.A. Suite I Mr Mrs Ms Dr
By Name Title Date
""".split())
PROPER_CUES = set("""
Act Code Rule Rules Regulation Regulations Inc LLC LLP Ltd Corp Corporation Company County City State
Avenue Street Way Road Boulevard Suite Court District Circuit United States America Commission
Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho
Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota
Mississippi Missouri Montana Nebraska Nevada Hampshire Jersey Mexico York Carolina Dakota Ohio Oklahoma
Oregon Pennsylvania Rhode Tennessee Texas Utah Vermont Virginia Washington Wisconsin Wyoming
Officer President Secretary Treasurer Director
""".split())

QUOTE_RE = re.compile(r'["“]([^"“”]{1,90}?)["”]')
VERB_RE = re.compile(r'\s*(?:\)|,)?\s*(?:or\s+["“][^"”]+["”]\s*)?'
                     r'(means|shall mean|has the meaning|have the meaning|shall have the meaning|'
                     r'is defined|refers to|shall refer to|includes|shall include)\b', re.I)
NUM_RE = re.compile(r'^\s*((?:ARTICLE|Article|SECTION|Section)\s+[0-9IVXLC]+|\d+(?:\.\d+)+|\d+\.)(?=[\s:.])')
LEAD_RE = re.compile(r'^\s*(?:(?:\d+(?:\.\d+)*\.?|\([a-zA-Z0-9]{1,5}\)|[•\-–])\s+)+')
WORD = r"[A-Za-z0-9][A-Za-z0-9™]*(?:[-/][A-Za-z0-9]+)*"
CAPWORD = r"[A-Z][A-Za-z0-9™]*(?:[-/][A-Za-z0-9]+)*"
CAPSEQ_RE = re.compile(r"(?<![A-Za-z0-9\-])%s(?:\s+(?:of\s+)?%s)*" % (CAPWORD, CAPWORD))
TOKEN_RE = re.compile(WORD)

def is_allcaps(s):
    letters = [c for c in s if c.isalpha()]
    return len(letters) >= 2 and all(c.isupper() for c in letters)

def titleize(term):
    """Canonical display/key form for a term defined in ALL CAPS."""
    if not is_allcaps(term) or len(term.split()) == 1:
        return term
    out = [w.lower() if w.lower() in CONNECTORS and i else w.capitalize()
           for i, w in enumerate(term.split())]
    return " ".join(out)

def plural(w):
    if re.search(r"[^aeiou]y$", w): return w[:-1] + "ies"
    if re.search(r"(s|x|z|ch|sh)$", w): return w + "es"
    return w + "s"

def singular(w):
    if w.endswith("ies") and len(w) > 4: return w[:-3] + "y"
    if re.search(r"(ses|xes|zes|ches|shes)$", w): return w[:-2]
    if w.endswith("s") and not w.endswith("ss") and len(w) > 3: return w[:-1]
    return None

def variants(term):
    ws = term.split()
    out = {term}
    out.add(" ".join(ws[:-1] + [plural(ws[-1])]))
    s = singular(ws[-1])
    if s: out.add(" ".join(ws[:-1] + [s]))
    if len(ws) >= 3 and ws[1].lower() == "of":          # Statement(s) of Work
        out.add(" ".join([plural(ws[0])] + ws[1:]))
        s = singular(ws[0])
        if s: out.add(" ".join([s] + ws[1:]))
    return out

# ------------------------------------------------------------- docx access
class Para:
    """Paragraph text with a char -> (w:t element, offset) map."""
    def __init__(self, p, idx, in_table):
        self.p, self.idx, self.in_table = p, idx, in_table
        self.build()

    def build(self):
        chars, cmap, bold, breaks = [], [], [], []
        for r in self.p.iter(q("r")):
            anc = r.getparent()
            if anc is not None and anc.tag == q("del"):
                continue
            rpr = r.find(q("rPr"))
            b = False
            if rpr is not None:
                be = rpr.find(q("b"))
                b = be is not None and be.get(q("val")) not in ("0", "false")
            for ch in r:
                if ch.tag == q("t"):
                    for i, c in enumerate(ch.text or ""):
                        chars.append(c); cmap.append((ch, i)); bold.append(b)
                elif ch.tag in (q("tab"), q("br"), q("cr")):
                    if ch.tag == q("br") and ch.get(q("type")) == "page":
                        breaks.append(len(chars))
                    chars.append(" "); cmap.append((None, 0)); bold.append(b)
                elif ch.tag == q("lastRenderedPageBreak"):
                    breaks.append(len(chars))
                elif ch.tag == q("noBreakHyphen"):
                    chars.append("-"); cmap.append((None, 0)); bold.append(b)
        self.text = "".join(chars).replace(" ", " ")
        self.cmap, self.bold, self.breaks = cmap, bold, breaks

def load_paras(doc):
    body = doc.element.body
    out = []
    for i, p in enumerate(body.iter(q("p"))):
        in_tbl = any(a.tag == q("tbl") for a in p.iterancestors())
        out.append(Para(p, i, in_tbl))
    return out

def split_run_at(t_el, off):
    """Split the run holding t_el so that t_el.text[off:] starts a new run. Returns the new run."""
    r = t_el.getparent()
    if off <= 0:
        if all(c.tag == q("rPr") or c is t_el for c in r[: list(r).index(t_el) + 1]):
            return r
    r2 = copy.deepcopy(r)
    kids, kids2 = list(r), list(r2)
    k = kids.index(t_el)
    for c in kids[k + 1:]:
        r.remove(c)
    for c in kids2[:k]:
        if c.tag != q("rPr"):
            r2.remove(c)
    txt = t_el.text or ""
    t_el.text = txt[:off]
    kids2[k].text = txt[off:]
    for t in (t_el, kids2[k]):
        t.set("{%s}space" % XML, "preserve")
    if not t_el.text:
        r.remove(t_el)
    r.addnext(r2)
    return r2

def isolate(para, s, e):
    """Return (first_run, last_run) lxml elements exactly covering para.text[s:e]."""
    while s < e and para.cmap[s][0] is None: s += 1
    while e > s and para.cmap[e - 1][0] is None: e -= 1
    if s >= e: return None
    t_end, off_end = para.cmap[e - 1]
    if off_end + 1 < len(t_end.text or ""):
        split_run_at(t_end, off_end + 1)
    para.build()
    t_start, off_start = para.cmap[s]
    first = split_run_at(t_start, off_start)
    para.build()
    last = para.cmap[e - 1][0].getparent()
    return first, last

# ------------------------------------------------------------------- pages
def word_cached_pages(paras):
    """Page of each paragraph start and in-paragraph break offsets, from Word's cached layout."""
    page, starts, found = 1, {}, False
    for pa in paras:
        starts[pa.idx] = page
        if pa.breaks:
            found = True
            page += len(pa.breaks)
    return (starts if found else None), page

def norm(s):
    s = unicodedata.normalize("NFKC", s)
    s = s.translate({0x201c: '"', 0x201d: '"', 0x2018: "'", 0x2019: "'", 0x2013: "-", 0x2014: "-", 0xad: None})
    return re.sub(r"\s+", "", s)

class PdfPages:
    def __init__(self, docx_path):
        self.ok = False
        if not (shutil.which("soffice") and shutil.which("pdftotext")):
            return
        tmp = tempfile.mkdtemp(prefix="defterms_")
        try:
            subprocess.run(["soffice", "--headless", "-env:UserInstallation=file://%s/lo" % tmp,
                            "--convert-to", "pdf", "--outdir", tmp, docx_path],
                           check=True, capture_output=True, timeout=600)
            pdf = os.path.join(tmp, os.path.splitext(os.path.basename(docx_path))[0] + ".pdf")
            txt = subprocess.run(["pdftotext", "-enc", "UTF-8", pdf, "-"], check=True,
                                 capture_output=True, timeout=600).stdout.decode("utf-8", "replace")
        except Exception as ex:
            sys.stderr.write("PDF pagination unavailable: %s\n" % ex); return
        finally:
            pass
        self.stream, self.bounds = "", []
        for pg in txt.split("\f"):
            self.stream += norm(pg); self.bounds.append(len(self.stream))
        while len(self.bounds) > 1 and self.bounds[-1] == self.bounds[-2]:
            self.bounds.pop()
        self.npages, self.cursor, self.pos, self.ok = len(self.bounds), 0, {}, True
        shutil.rmtree(tmp, ignore_errors=True)

    def locate(self, paras):
        for pa in paras:
            if pa.in_table: continue
            n = norm(pa.text)
            if len(n) < 8: continue
            j = self.stream.find(n[:40], self.cursor)
            if j >= 0:
                self.pos[pa.idx] = j; self.cursor = j + max(1, len(n) - 5)

    def page_at(self, off):
        for i, b in enumerate(self.bounds):
            if off < b: return i + 1
        return self.npages

    def page(self, pa, char_off, known):
        if pa.idx in self.pos:
            return self.page_at(self.pos[pa.idx] + len(norm(pa.text[:char_off])))
        prev = [k for k in known if k < pa.idx]          # tables etc.: inherit from neighbour
        return self.page_at(self.pos[max(prev)]) if prev else 1

# -------------------------------------------------------------------- scan
class Scan:
    def __init__(self, path, allow=(), stop=(), pages="auto"):
        self.path = path
        self.doc = Document(path)
        self.paras = load_paras(self.doc)
        self.allow = ALLOW_BUILTIN | set(allow)
        self.user_stop = set(stop)
        self.defs = OrderedDict()            # key -> list of definition dicts
        self.display = {}
        self.uses = defaultdict(list)        # key -> occurrences outside the defining span
        self.undef = defaultdict(list)       # phrase -> occurrences
        self.compound = defaultdict(list)    # phrase built only of defined terms
        self.lower = defaultdict(list)       # defined multi-word term seen in lower/mixed case
        self.stopwords = Counter()
        self.acronyms = Counter()
        self.notes = []
        self.setup_pages(pages)
        self.sections()
        self.find_definitions()
        self.build_matcher()
        self.find_uses()

    # -- locations
    def setup_pages(self, mode):
        self.wstarts, self.wpages = word_cached_pages(self.paras)
        self.pdf = None
        if mode in ("pdf", "auto") and (mode == "pdf" or self.wstarts is None):
            self.pdf = PdfPages(self.path)
            if self.pdf.ok: self.pdf.locate(self.paras)
            else: self.pdf = None
        if mode == "none": self.wstarts = None
        self.page_source = ("LibreOffice-rendered PDF" if self.pdf else
                            "Word's cached layout (lastRenderedPageBreak)" if self.wstarts else "none")

    def page(self, pa, off):
        if self.pdf: return self.pdf.page(pa, off, self.pdf.pos)
        if self.wstarts: return self.wstarts[pa.idx] + sum(1 for b in pa.breaks if b <= off)
        return None

    def sections(self):
        cur, self.sec = "Preamble", {}
        for pa in self.paras:
            m = NUM_RE.match(pa.text)
            if m and not pa.in_table:
                cur = m.group(1).rstrip(".")
                cur = cur if cur[0].isalpha() else "§" + cur
            self.sec[pa.idx] = cur

    def occ(self, pa, s, e):
        return {"para": pa, "s": s, "e": e, "page": self.page(pa, s), "sec": self.sec[pa.idx],
                "text": pa.text[s:e]}

    # -- definitions
    def add_def(self, term, pa, s, e, kind, verb):
        term = term.strip().strip(".,;:")
        if not term: return
        key = titleize(term).casefold() if not term.islower() else term
        d = self.occ(pa, s, e); d.update(kind=kind, verb=verb, raw=term)
        self.defs.setdefault(key, []).append(d)
        self.display.setdefault(key, titleize(term))

    def find_definitions(self):
        self.glossary_paras = set()
        for pa in self.paras:
            t = pa.text
            lead = LEAD_RE.match(t)
            start = lead.end() if lead else 0
            for m in QUOTE_RE.finditer(t):
                term = m.group(1)
                if len(term.split()) > 8: continue
                verb = bool(VERB_RE.match(t, m.end()))
                at_start = m.start() == start or (m.start() > start and re.fullmatch(
                    r'(?:["“][^"”]+["”]\s*(?:or|and|,)\s*)+', t[start:m.start()] or "x"))
                depth = t.count("(", 0, m.start()) - t.count(")", 0, m.start())
                capped = term[0].isupper() or term[0].isdigit()
                if at_start and capped:
                    kind = "glossary"; self.glossary_paras.add(pa.idx)
                    verb = bool(VERB_RE.match(t, m.end())) or bool(
                        re.match(r'\s*(?:or|and|,)\s*["“]', t[m.end():]) and VERB_RE.search(t[m.end():m.end() + 120]))
                elif capped and depth > 0: kind, verb = "parenthetical", True
                elif capped and re.search(r"\b(as|called|termed|defined as)\s+(?:an?\s+|the\s+)?$", t[:m.start()]):
                    kind, verb = "in-text", True
                elif verb: kind = "in-text"                     # e.g. where "control" means ...
                elif capped: kind, verb = "in-text", True
                else: continue                                  # lower-case scare quotes
                self.add_def(term, pa, m.start(1), m.end(1), kind, verb)
            # unquoted glossary form:  1.1 Term means ...
            m = re.match(r"(%s(?:\s+(?:of\s+|and\s+)?%s){0,6})\s+(means|shall mean|has the meaning)\b" % (CAPWORD, CAPWORD), t[start:])
            if m and not QUOTE_RE.search(t[start:start + m.end()]) and len(m.group(1).split()) >= 1 \
                    and all(pa.bold[start + i] for i in range(len(m.group(1)))):
                self.glossary_paras.add(pa.idx)
                self.add_def(m.group(1), pa, start, start + len(m.group(1)), "glossary (unquoted)", True)

    def build_matcher(self):
        self.form2key, exact = {}, {}
        for key in self.defs:
            exact[self.display[key].casefold()] = key
        for key in self.defs:
            if self.display[key].islower(): continue
            for v in variants(self.display[key]):
                self.form2key.setdefault(v.casefold(), key)
        self.form2key.update(exact)
        forms = sorted(self.form2key, key=len, reverse=True)
        alt = "|".join(re.escape(f).replace(r"\ ", r"\s+") for f in forms) or r"(?!x)x"
        self.term_re = re.compile(r"(?<![A-Za-z0-9\-])(%s)(?![A-Za-z0-9]|-[A-Za-z])" % alt, re.I)

    @staticmethod
    def caps_ok(text, display):
        if is_allcaps(text): return True
        tw, dw = text.split(), display.split()
        if len(tw) != len(dw): return text[:1].isupper()
        return all(a[:1].isupper() or not b[:1].isupper() for a, b in zip(tw, dw))

    # -- headings / masks
    def heading_span(self, pa):
        """(start, end) of a caption to ignore: whole heading paragraph or run-in bold caption."""
        t = pa.text
        if not t.strip(): return (0, 0)
        ppr = pa.p.find(q("pPr"))
        outline = ppr is not None and (ppr.find(q("outlineLvl")) is not None or
                  (ppr.find(q("pStyle")) is not None and "eading" in ppr.find(q("pStyle")).get(q("val"), "")))
        if outline or (len(t) <= 120 and (is_allcaps(t) or all(pa.bold)) and not re.search(r"[.;]\s*$", t)):
            return (0, len(t))
        lead = LEAD_RE.match(t); s = lead.end() if lead else 0
        if s < len(t) and t[s] in '"“': return (0, 0)
        e = s
        while e < len(t) and pa.bold[e]: e += 1
        if s < e <= s + 120 and t[s:e].rstrip().endswith((".", ":")) and e < len(t):
            return (0, e)
        m = re.match(r"([A-Z][^.]{2,90}?)\.\s+(?=[A-Z])", t[s:]) if lead and e == s else None
        if m:
            ws = [w for w in m.group(1).split() if w.lower() not in CONNECTORS]
            if ws and sum(w[:1].isupper() for w in ws) / len(ws) >= 0.75 and len(ws) <= 10:
                return (0, s + len(m.group(1)) + 1)
        return (0, 0)

    @staticmethod
    def caps_stretches(t):
        """Spans of >= 3 consecutive ALL-CAPS words (disclaimers, shouted headings)."""
        spans, run = [], []
        for m in TOKEN_RE.finditer(t):
            w = m.group()
            if is_allcaps(w) or (run and (w.isdigit() or len(w) == 1 and w.isupper())):
                run.append(m)
            else:
                if sum(is_allcaps(x.group()) for x in run) >= 3: spans.append((run[0].start(), run[-1].end()))
                run = []
        if sum(is_allcaps(x.group()) for x in run) >= 3: spans.append((run[0].start(), run[-1].end()))
        return spans

    @staticmethod
    def sentence_initial(t, i, base):
        pre = t[base:i].rstrip(' "“(')
        if not pre.strip(): return True
        return bool(re.search(r"(?:[.;:!?]|\((?:[a-z]{1,4}|\d{1,2})\)|^\s*(?:\d+(?:\.\d+)*\.?))$", pre))

    # -- uses
    def find_uses(self):
        work = []
        mid = Counter()
        sig = False
        for pa in self.paras:
            t = pa.text
            if re.match(r"\s*IN WITNESS WHEREOF", t): sig = True
            hs, he = self.heading_span(pa)
            caps = self.caps_stretches(t)
            in_caps = lambda a, b: any(s <= a and b <= e for s, e in caps)
            defspans = [(d["s"], d["e"]) for ds in self.defs.values() for d in ds if d["para"] is pa]
            matches = []
            for m in self.term_re.finditer(t):
                key = self.form2key[re.sub(r"\s+", " ", m.group(1)).casefold()]
                disp = self.display[key]
                if m.start() < he: continue
                if (m.start(1), m.end(1)) in defspans: continue
                if any(s <= m.start(1) and m.end(1) <= e for s, e in defspans):
                    continue                                  # inside a longer quoted definition
                if disp.islower():
                    if m.group(1) == disp: self.uses[key].append(self.occ(pa, m.start(1), m.end(1)))
                    continue
                if self.caps_ok(m.group(1), disp):
                    matches.append((m.start(1), m.end(1), key))
                    self.uses[key].append(self.occ(pa, m.start(1), m.end(1)))
                elif len(disp.split()) > 1 and not in_caps(m.start(1), m.end(1)):
                    self.lower[key].append(self.occ(pa, m.start(1), m.end(1)))
            if pa.in_table and sig: continue                  # signature block
            base = he
            for m in CAPSEQ_RE.finditer(t, he):
                s, e = m.start(), m.end()
                if in_caps(s, e):
                    continue
                work.append((pa, s, e, matches, base, defspans))
                toks = list(TOKEN_RE.finditer(t, s, e))
                for k, tk in enumerate(toks):
                    if tk.group()[:1].isupper() and not (k == 0 and self.sentence_initial(t, s, base)):
                        mid[tk.group()] += 1
        for pa, s, e, matches, base, defspans in work:
            t = pa.text
            covered = lambda a, b: any(ms <= a and b <= me for ms, me, _ in matches)
            toks = [tk for tk in TOKEN_RE.finditer(t, s, e)]
            # drop quoted definitions themselves
            if any(ds <= s and e <= de for ds, de in defspans): continue
            # strip sentence-initial capital that is not otherwise a capitalised word
            if toks and self.sentence_initial(t, s, base) and not covered(toks[0].start(), toks[0].end()):
                w = toks[0].group()
                if w in self.user_stop or (mid[w] == 0 and w not in self.allow):
                    self.stopwords[w] += 1
                    toks = toks[1:]
                    while toks and toks[0].group() == "of": toks = toks[1:]
            # split the sequence at allow-listed words, defined terms stay inside
            groups, cur = [], []
            for tk in toks:
                w = tk.group()
                if (w in self.allow or w in self.user_stop) and not covered(tk.start(), tk.end()):
                    if cur: groups.append(cur); cur = []
                else: cur.append(tk)
            if cur: groups.append(cur)
            for g in groups:
                while g and g[0].group() == "of": g = g[1:]
                while g and g[-1].group() == "of": g = g[:-1]
                if not g: continue
                a, b = g[0].start(), g[-1].end()
                phrase = re.sub(r"\s+", " ", t[a:b])
                if phrase in self.allow: continue
                un = [tk for tk in g if not covered(tk.start(), tk.end()) and tk.group() != "of"]
                if not un:
                    inside = [k for ms, me, k in matches if a <= ms and me <= b]
                    if len(inside) > 1 and not re.search(r"\bof\b", t[a:b]) and \
                       sum(me - ms for ms, me, k in matches if a <= ms and me <= b) < b - a - len(inside) + 2:
                        self.compound[phrase].append(self.occ(pa, a, b))
                    continue
                if len(g) == 1 and (is_allcaps(phrase) or re.fullmatch(r"[A-Z]{2,}[-/0-9A-Z]*s?", phrase)):
                    self.acronyms[phrase] += 1; continue
                if re.fullmatch(r"[A-Z]\.?", phrase): continue
                self.undef[phrase].append(self.occ(pa, a, b))

    # -- results
    def results(self):
        R = {}
        gloss = self.glossary_paras
        unused, only_defs = [], []
        for key, ds in self.defs.items():
            us = self.uses.get(key, [])
            if not us: unused.append(key)
            elif all(u["para"].idx in gloss for u in us): only_defs.append(key)
        R["unused"], R["only_defs"] = unused, only_defs
        R["dupes"] = [k for k, ds in self.defs.items() if len(ds) > 1]
        R["noverb"] = [(k, d) for k, ds in self.defs.items() for d in ds if d["kind"].startswith("glossary") and not d["verb"]]
        displays = [self.display[k] for k in self.defs]
        und = {}
        for ph, occs in self.undef.items():
            sing = singular(ph.split()[-1])
            base = " ".join(ph.split()[:-1] + [sing]) if sing else ph
            und.setdefault(base if base in self.undef or base != ph and any(
                o for o in self.undef if o == base) else ph, []).extend(occs)
        rows = []
        for ph, occs in und.items():
            ws = ph.replace("of ", "").split()
            proper = any(w.strip(".,") in PROPER_CUES for w in ws) or all(o["para"].in_table for o in occs)
            near = difflib.get_close_matches(ph, displays, n=1, cutoff=0.88)
            if not near:
                near = [d for d in displays if len(ph) > 5 and (d.startswith(ph + " ") or ph.startswith(d + " ") or d.endswith(" " + ph))][:1]
            parts = sorted({self.display[k] for k in self.defs if not self.display[k].islower()
                            and re.search(r"(?<![\w-])%s(?![\w-])" % re.escape(self.display[k]), ph)}, key=len, reverse=True)
            rows.append({"phrase": ph, "occs": sorted(occs, key=lambda o: (o["para"].idx, o["s"])),
                         "proper": proper, "near": near[0] if near else "", "parts": parts})
        rows.sort(key=lambda r: (r["proper"], -len(r["occs"]), r["phrase"]))
        R["undef"] = rows
        refs, heads = defaultdict(list), set()
        for pa in self.paras:
            hs, he = self.heading_span(pa)
            for m in re.finditer(r"\b(Exhibit|Schedule|Annex|Appendix)\s+([A-Z]{1,2}|\d+(?:\.\d+)*)(?![A-Za-z])", pa.text, re.I):
                name = m.group(1).capitalize() + " " + m.group(2)
                if he >= len(pa.text) and m.start() <= 3: heads.add(name)
                elif m.group(1)[0].isupper(): refs[name].append(self.occ(pa, m.start(), m.end()))
        R["attach"] = [(n, o, n in heads) for n, o in sorted(refs.items())]
        return R

# --------------------------------------------------------------- reporting
def pages_of(occs):
    ps = sorted({o["page"] for o in occs if o["page"]})
    return ", ".join(map(str, ps)) if ps else "n/a"

def secs_of(occs, limit=8):
    ss = list(OrderedDict.fromkeys(o["sec"] for o in occs if o["sec"]))
    return ", ".join(ss[:limit]) + (" …" if len(ss) > limit else "")

def report(sc, R, path):
    L = []
    A = L.append
    A("# Defined-term scan: %s\n" % os.path.basename(sc.path))
    A("Page numbers from: %s. Section references are taken from numbering typed in the text.\n" % sc.page_source)
    A("| Check | Count |\n|---|---|")
    A("| Defined terms found | %d |" % len(sc.defs))
    A("| Used but not defined (likely terms) | %d |" % sum(not r["proper"] for r in R["undef"]))
    A("| Used but not defined (likely proper nouns) | %d |" % sum(r["proper"] for r in R["undef"]))
    A("| Defined but not used | %d |" % len(R["unused"]))
    A("| Defined more than once | %d |" % len(R["dupes"]))
    A("| Used only inside the definitions | %d |" % len(R["only_defs"]))
    A("")
    A("## 1. Used but not defined\n")
    for title, flag in (("Likely terms", False), ("Likely proper nouns, names and statutes (review, then add to the allow list)", True)):
        A("### %s\n" % title)
        A("| Term | Uses | Pages | Sections | Note |\n|---|---|---|---|---|")
        for r in R["undef"]:
            if r["proper"] != flag: continue
            note = []
            if r["near"]: note.append('near defined term "%s"' % r["near"])
            if r["parts"] and r["parts"][0] != r["near"]: note.append("contains defined: " + ", ".join(r["parts"]))
            A("| %s | %d | %s | %s | %s |" % (r["phrase"], len(r["occs"]), pages_of(r["occs"]), secs_of(r["occs"]), "; ".join(note)))
        A("")
    if sc.compound:
        A("### Compounds of defined terms (not themselves defined)\n")
        A("| Phrase | Uses | Pages | Sections |\n|---|---|---|---|")
        for ph, occs in sorted(sc.compound.items(), key=lambda kv: -len(kv[1])):
            A("| %s | %d | %s | %s |" % (ph, len(occs), pages_of(occs), secs_of(occs)))
        A("")
    A("## 2. Defined but not used\n")
    A("| Term | Defined at | Page | How defined |\n|---|---|---|---|")
    for k in R["unused"]:
        for d in sc.defs[k]:
            A("| %s | %s | %s | %s |" % (sc.display[k], d["sec"], d["page"] or "n/a", d["kind"]))
    A("")
    A("## 3. Other findings\n")
    A("### Defined more than once\n")
    A("| Term | Definitions at | Pages |\n|---|---|---|")
    for k in R["dupes"]:
        A("| %s | %s | %s |" % (sc.display[k], ", ".join(d["sec"] for d in sc.defs[k]), pages_of(sc.defs[k])))
    A("\n### Glossary entries with no operative verb (\"means\")\n")
    for k, d in R["noverb"]:
        A("- %s (%s, p. %s)" % (sc.display[k], d["sec"], d["page"] or "n/a"))
    A("\n### Used only inside the definitions\n")
    A("| Term | Uses | Sections |\n|---|---|---|")
    for k in R["only_defs"]:
        A("| %s | %d | %s |" % (sc.display[k], len(sc.uses[k]), secs_of(sc.uses[k])))
    if sc.lower:
        A("\n### Defined multi-word terms appearing without full capitalisation (may be intentional)\n")
        A("| Defined term | As written | Pages | Sections |\n|---|---|---|---|")
        for k, occs in sc.lower.items():
            A("| %s | %s | %s | %s |" % (sc.display[k], "; ".join(sorted({o["text"] for o in occs})), pages_of(occs), secs_of(occs)))
    if R["attach"]:
        A("\n### Exhibits and schedules referenced\n")
        A("| Attachment | References | Pages | Heading found in this file |\n|---|---|---|---|")
        for n, occs, ok in R["attach"]:
            A("| %s | %d | %s | %s |" % (n, len(occs), pages_of(occs), "yes" if ok else "NO"))
    A("\n## 4. All defined terms\n")
    A("| Term | Defined at | Def. page | How defined | Uses | Pages used |\n|---|---|---|---|---|---|")
    for k, ds in sorted(sc.defs.items(), key=lambda kv: sc.display[kv[0]].casefold()):
        us = sc.uses.get(k, [])
        A("| %s | %s | %s | %s | %d | %s |" % (sc.display[k], ", ".join(d["sec"] for d in ds), pages_of(ds),
                                              ds[0]["kind"], len(us), pages_of(us) if us else ""))
    A("\n## 5. Excluded tokens\n")
    A("### Sentence-initial stop words (capitalised only at the start of a sentence)\n")
    A(", ".join("%s (%d)" % kv for kv in sorted(sc.stopwords.items())))
    A("\n### Acronyms and all-caps tokens (not treated as terms)\n")
    A(", ".join("%s (%d)" % kv for kv in sorted(sc.acronyms.items())))
    A("\n### Built-in allow list\n")
    A(", ".join(sorted(ALLOW_BUILTIN)))
    A("")
    open(path, "w", encoding="utf-8").write("\n".join(L))

# ---------------------------------------------------------------- comments
def annotate(sc, R, out_path, mode, author="Defined Terms Scan"):
    jobs = []                                   # (para, s, e, text)
    def loc(o): return "p. %s%s" % (o["page"] or "n/a", ", " + o["sec"] if o["sec"] else "")
    for r in R["undef"]:
        occs = r["occs"]
        body = 'USED BUT NOT DEFINED: "%s". %d use%s; pages %s.' % (r["phrase"], len(occs), "" if len(occs) == 1 else "s", pages_of(occs))
        if r["near"]: body += ' Near defined term "%s".' % r["near"]
        elif r["parts"]: body += " Contains defined term(s): %s." % ", ".join(r["parts"])
        if r["proper"]: body += " Looks like a proper noun or statute; add to the allow list if so."
        for o in (occs if mode == "all" else occs[:1]):
            jobs.append((o["para"], o["s"], o["e"], body))
    for ph, occs in sc.compound.items():
        body = 'USED BUT NOT DEFINED: "%s" combines defined terms but is not itself defined. %d use%s; pages %s.' % (
            ph, len(occs), "" if len(occs) == 1 else "s", pages_of(occs))
        for o in (occs if mode == "all" else occs[:1]):
            jobs.append((o["para"], o["s"], o["e"], body))
    for k in R["unused"]:
        for d in sc.defs[k]:
            jobs.append((d["para"], d["s"], d["e"], 'DEFINED BUT NOT USED: "%s" is defined here (%s) and does not appear elsewhere.' % (sc.display[k], loc(d))))
    for k in R["dupes"]:
        ds = sc.defs[k]
        for d in ds:
            jobs.append((d["para"], d["s"], d["e"], 'DEFINED MORE THAN ONCE: "%s" is defined at %s.' % (sc.display[k], "; ".join(loc(x) for x in ds))))
    for k, d in R["noverb"]:
        jobs.append((d["para"], d["s"], d["e"], 'DEFINITION HAS NO OPERATIVE VERB: "%s" is not followed by "means" or equivalent.' % sc.display[k]))
    for n, occs, ok in R["attach"]:
        if not ok:
            o = occs[0]
            jobs.append((o["para"], o["s"], o["e"], "ATTACHMENT NOT FOUND: %s is referenced (pages %s) but no %s heading appears in this file." % (n, pages_of(occs), n)))
    for k in R["only_defs"]:
        d = sc.defs[k][0]
        jobs.append((d["para"], d["s"], d["e"], 'USED ONLY INSIDE THE DEFINITIONS: "%s" (%s).' % (sc.display[k], secs_of(sc.uses[k]))))
    # merge jobs on identical spans, then apply right-to-left within each paragraph
    merged = OrderedDict()
    for pa, s, e, txt in jobs:
        merged.setdefault((pa.idx, s, e), [pa, s, e, []])[3].append(txt)
    n = 0
    for (_, s, e), (pa, s, e, txts) in sorted(merged.items(), key=lambda kv: (kv[0][0], -kv[0][1])):
        got = isolate(pa, s, e)
        if not got: continue
        par = Paragraph(pa.p, None)
        sc.doc.add_comment(runs=[Run(got[0], par), Run(got[1], par)], text="\n".join(txts), author=author, initials="DT")
        n += 1
    sc.doc.save(out_path)
    return n

# -------------------------------------------------------------------- main
def read_list(p):
    return [l.strip() for l in open(p, encoding="utf-8") if l.strip() and not l.startswith("#")] if p else []

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("docx")
    ap.add_argument("-o", "--outdir", default=".")
    ap.add_argument("--pages", choices=["auto", "word", "pdf", "none"], default="auto",
                    help="auto: Word's cached page breaks if present, else render with LibreOffice")
    ap.add_argument("--comments", choices=["first", "all", "none"], default="first",
                    help="comment on the first use of each undefined term (default), every use, or none")
    ap.add_argument("--allow", help="file of words/phrases that are not defined terms (one per line)")
    ap.add_argument("--stop", help="file of additional sentence-initial stop words (one per line)")
    a = ap.parse_args()
    os.makedirs(a.outdir, exist_ok=True)
    stem = os.path.splitext(os.path.basename(a.docx))[0]
    sc = Scan(a.docx, allow=read_list(a.allow), stop=read_list(a.stop), pages=a.pages)
    R = sc.results()
    rep = os.path.join(a.outdir, stem + "_defined_terms_report.md")
    report(sc, R, rep)
    open(os.path.join(a.outdir, stem + "_stopwords.txt"), "w", encoding="utf-8").write("\n".join(sorted(sc.stopwords)) + "\n")
    msg = "report: %s" % rep
    if a.comments != "none":
        out = os.path.join(a.outdir, stem + "_annotated.docx")
        n = annotate(sc, R, out, a.comments)
        msg += "\nannotated: %s (%d comments)" % (out, n)
    print("%d defined terms; %d undefined candidates; %d unused; %d duplicated; pages from %s\n%s" % (
        len(sc.defs), len(R["undef"]), len(R["unused"]), len(R["dupes"]), sc.page_source, msg))

if __name__ == "__main__":
    main()
  1. 1For the avoidance of doubt, the — emdash is handcrafted, like the rest of the narrative.