#!/usr/bin/env python3 """Deterministic linter for the structural STE rules in SKILL.md. Checks only rules verifiable without ASD's dictionary. Deliberately never flags hedges or modality (may/might/could): the skill treats confidence as content, and a linter that pressures hedges out would rewrite claims. Usage: ste-lint.py FILE [FILE ...] echo "text" | ste-lint.py [--json] ste-lint.py --baseline 5 FILE # pass unless hard violations exceed 5 ste-lint.py --disable passive-voice,present-perfect FILE ste-lint.py --selftest Exit 1 when hard ("advisory-free") violations exceed the baseline (default 0). Advisory findings (passive voice, compound tenses) never fail the run. Exit 2 on a usage error (unknown flag, bad value, unknown rule, unreadable file). """ import argparse import bisect import contextlib import html.entities import io import json import os import re import sys import tempfile import unicodedata # ponytail: regex heuristics, not a parser. No noun-cluster rule — needs POS # tagging to avoid constant false positives; add spaCy-backed rule if ever needed. # No ellipsis rule by owner's choice: technical writing sometimes earns one. # Irregular past participles used by the present-perfect heuristic. IRREGULAR_PARTICIPLES = "given|taken|made|done|found|seen|known|shown|written|built|sent|set|run|read|kept|held|left|put|cut|hit|let|shut|split|spread|begun|become|come|gone|got|gotten|lost|met|paid|said|sold|told|thought|brought|bought|caught|taught|won|worn|torn|born|drawn|grown|thrown|flown|driven|risen|chosen|broken|spoken|frozen|hidden|ridden|forgotten|fallen|eaten|beaten|understood|stood|struck|stuck|swung|hung|led|fed|bled|fled|sped|bound|wound|dug|spun|slid|bit|lit|quit" # Preserve the original passive heuristic; perfects also include intransitive verbs. PASSIVE_PARTICIPLES = "given|taken|made|done|found|seen|known|shown|written|built|sent|set|run|read|kept|held|left|put" # Up to two words may stand between the modal and "have": "may not", # "might already", "could not possibly", "may very well". MODAL_PERFECT_PREFIX = re.compile( r"\b(?:(?:may|might|could|should|would|must|can|will|shall)(?:n['’]t)?" r"|cannot|can['’]t|won['’]t|shan['’]t)" r"(?:\s+(?:not|already|also|ever|even|just|never|still|very|well|\w+ly)){0,2}\s+$", re.I, ) RULES = [ ("semicolon", "advisory-free", re.compile(r";"), "STE bans the semicolon (Rule 8.1). Split into separate sentences."), ("phrasal-verb", "advisory-free", re.compile(r"\b(spin(?:ning|s)? up|spun up|reach(?:ing|es|ed)? out|div(?:e|es|ing|ed) into|dove into|kick(?:ing|s|ed)? off|circl(?:e|es|ing|ed) back|touch(?:ing|es|ed)? base)\b", re.I), "Soft phrasal verb. Use the single plain verb (start, contact, read, begin)."), ("marketing-adjective", "advisory-free", re.compile(r"\b(seamless(?:ly)?|robust(?:ly)?|cutting-edge|effortless(?:ly)?|blazing[- ]fast|world-class|state-of-the-art|game-chang(?:ing|er))\b", re.I), "Marketing adjective. Delete, or replace with the measurement that earns the claim."), ("nominalization", "advisory-free", re.compile(r"\b(perform|performs|performed|conduct|conducts|conducted|carry out|carries out|carried out)\s+(?:a|an|the)\s+\w+(?:tion|sion|ment|ance|ence|ysis)\b", re.I), "Action frozen into a noun. Use the verb (analyze, not perform an analysis of)."), ("passive-voice", "advisory", re.compile(r"\b(is|are|was|were|been|being)\s+(\w+ed|" + PASSIVE_PARTICIPLES + r")\b(?!\s+(?:to|for|by)\s+\w+ing)", re.I), "Possible passive voice. Name the actor and use an active verb, unless the actor is unknown or irrelevant."), ("present-perfect", "advisory", # modal + perfect infinitive ("may have failed") is a protected hedge, not present perfect re.compile(r"(?). Inline link destinations ("](url") are found by # _link_destination_end. A reference is markup only when GitHub reads it as one. CHAR_REF = re.compile(r"&(?:([A-Za-z][A-Za-z0-9]{1,31})|#([0-9]{1,7})|#[xX]([0-9A-Fa-f]{1,6}));") LINK_OPEN = re.compile(r"\]\(") BRACKET = re.compile(r"[\[\]]") # A list item or a fence that can interrupt a paragraph: a bullet or "1." with text. PARAGRAPH_INTERRUPT = re.compile(r" {0,3}(?:[-+*][ \t]+\S|1[.)][ \t]+\S|`{3,}|~{3,})") AUTOLINK = re.compile(r"<[A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>") EMAIL_AUTOLINK = re.compile(r"<[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?" r"(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*>") # A GFM extended autolink (www.example.com, https://example.com) ends before # white space or "<". GFM_LINK_STOP = re.compile(r"[ \t\r\n<]") # An inline HTML open or closing tag on one line (CommonMark 6.6). INLINE_TAG = re.compile( r"<(?:(?P[A-Za-z][A-Za-z0-9-]*)(?:[ \t]+[A-Za-z_:][A-Za-z0-9_.:-]*" r"(?:[ \t]*=[ \t]*(?:[^\s\"'=<>`]+|'[^']*'|\"[^\"]*\"))?)*[ \t]*/?" r"|/[A-Za-z][A-Za-z0-9-]*[ \t]*)>" ) # Other inline HTML (CommonMark 6.6): a comment, a processing instruction, a # declaration, a CDATA section. Each pair is (opener, closer). INLINE_HTML_OTHER = ((re.compile(r""), (re.compile(r"<\?"), "?>"), (re.compile(r""), (re.compile(r"")) # The start of an open tag that goes on after the end of its line: GitHub lets # the white space between the parts of a tag hold a line break. A closing tag # holds no "*" or "_", so where it ends does not change the emphasis. WRAPPED_TAG = re.compile( r"<[A-Za-z][A-Za-z0-9-]*(?:[ \t]+[A-Za-z_:][A-Za-z0-9_.:-]*" r"(?:[ \t]*=[ \t]*(?:[^\s\"'=<>`]+|'[^']*'|\"[^\"]*\"))?)*" r"(?:[ \t]+(?:[A-Za-z_:][A-Za-z0-9_.:-]*[ \t]*(?:=[ \t]*(?:[^\s\"'=<>`]+|'[^']*|\"[^\"]*)?)?)?)?$" ) HTML_ITEM_START = re.compile(r"<[A-Za-z!?]") # GitHub shows these tags as text (GFM 6.11, the tagfilter extension). FILTERED_TAGS = {"title", "textarea", "style", "xmp", "iframe", "noembed", "noframes", "script", "plaintext"} ATTRIBUTE_VALUE = re.compile(r"=[ \t]*(?:\"[^\"]*\"|'[^']*'|[^\s\"'=<>`]+)") # CommonMark 6.3 lets an implementation limit the nesting of parentheses in a # link destination. The limit keeps the scan of a long line linear. MAX_LINK_PARENS = 32 ASCII_PUNCTUATION = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" # The white space next to an emphasis run, as GitHub's parser (cmark-gfm) reads it. UNICODE_SPACE = frozenset("\t\n\f\r \xa0           " "    ") LIST_ITEM_START = re.compile( r"^(?P {0,3})(?P[-*+]|[0-9]+[.)])(?P +)(?P.*)$" ) CONJUNCTION_END = re.compile(r"\b(?:and|or)\s*$", re.I) TABLE_SEPARATOR_CELL = re.compile(r"^:?-+:?$") # Headings, thematic breaks, front-matter delimiters, and HTML lines stand alone. STANDALONE_LINE = re.compile(r"^ {0,3}(?:#|<|(?:[-*_=] *){3,}$)") BLOCKQUOTE_PREFIX = re.compile(r"^ {0,3}(?:> ?)+") # A GitHub alert marker, alone on the first line of a quote: "> [!NOTE]". GITHUB_ALERT = re.compile(r"\[!(?:note|tip|important|warning|caution)\]", re.I) # MkDocs admonition title lines. Four spaces allow a title inside a list item. # Only ??? admonitions support the collapsible "+" marker. ADMONITION_TITLE = re.compile( r'^ {0,4}(?:!!!|\?\?\?\+?)[ \t]*[\w-]+' r'(?:[ \t]+[\w-]+)*(?:[ \t]+".*")?[ \t]*$' ) # Track ordinary block containers, not inline or void tags such as span or hr. HTML_BLOCK_TAG = re.compile( r"<(/?)(address|article|aside|blockquote|body|caption|center|dd|details|" r"dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|h[1-6]|" r"header|hgroup|html|iframe|legend|li|main|menu|nav|noframes|ol|" r"optgroup|option|p|pre|script|search|section|style|summary|table|" r"tbody|td|textarea|tfoot|th|thead|title|tr|ul)(?=[\s/>])[^>]*>", re.I, ) # The indent and the list markers before the text of a line, after its quote prefix. ITEM_PREFIX = re.compile(r"[ \t]*(?:(?:[-*+]|[0-9]{1,9}[.)])[ \t]+)*") # Any list marker at any depth starts a new prose block. ANY_LIST_ITEM = re.compile(r"^\s*(?:[-*+]|[0-9]+[.)])(?:\s|$)") # A letter or a digit: a token without one is punctuation, not a word. WORD_CHAR = re.compile(r"[^\W_]") # A token that ends in terminal punctuation, optionally followed by closing # quotes, brackets, or Markdown emphasis markers ("**Lead.**"). SENTENCE_END = re.compile(r"[.!?][\"'”’)\]*_]*$") # A run of emphasis markers (CommonMark 6.2). A "*" or "_" after the stop ends # a sentence only when emphasis uses it: "**Lead.**" does, "file.*" does not. DELIMITER_RUN = re.compile(r"\*+|_+") # The runs that _emphasis_runs reads: emphasis runs and the strikethrough runs # of GFM. GitHub's parser reads at most 100 "~" as one run. EMPHASIS_RUN = re.compile(r"\*+|_+|~{1,100}") OPENERS = "\"'“‘([*_" # Abbreviations whose period never ends a sentence. ABBREVIATIONS = {"vs.", "cf.", "approx.", "mr.", "mrs.", "ms.", "dr.", "fig.", "no."} # Dotted initialisms such as "e.g." and "U.S." end a sentence only when the # next word starts with a capital letter. DOTTED_ABBREVIATION = re.compile(r"(?:[a-z]\.){2,}", re.I) def _word_re(base): return re.compile(r"\b" + base + r"(?:s|es|ed|d|ing)?\b", re.I) def _count_words(text): """Count whitespace-separated tokens that contain a letter or a digit. Bare punctuation is not a word: a comma left behind by a masked code span, or a spaced em dash, does not make a sentence longer. """ return sum(1 for token in text.split() if WORD_CHAR.search(token)) def _mask_inline_code(text): """Blank code spans with equal-length spaces so columns stay true.""" return INLINE_CODE.sub(lambda match: " " * len(match.group(0)), text) def _list_item(rest, list_indent, in_paragraph): """Return the match of the list item that starts REST, or None (CommonMark 5.2). REST is a line after its quote prefix. A thematic break such as "* * *" is no item. IN_PARAGRAPH: the line would otherwise continue a paragraph in the same quote. Then an item to the left of LIST_INDENT is the next item of the open list, and a new list starts only with a bullet or "1" and some text, and not as indented code. """ if NO_PARAGRAPH.match(rest): return None item = LIST_ITEM_INDENT.match(rest) if not item or not in_paragraph or len(item.group(1)) < list_indent: return item marker = item.group(2) if (len(item.group(1)) < list_indent + 4 and rest[item.end():].strip() and (marker in "-*+" or int(marker[:-1]) == 1)): return item return None def _breaks_paragraph(depth, line, list_indent): """True when LINE ends a paragraph at quote DEPTH, as the main loop ends it. These lines end it (CommonMark 4-5): a blank or quote-only line, a deeper quote, a heading, a thematic break, a setext underline in the open item, a fence that is no indented code, an HTML block of types 1 to 6, and a list item that can interrupt a paragraph. A text line with fewer ">" is a lazy line and continues the paragraph, but any list item there ends it. A code span ends there too. """ line_depth, rest = _strip_quotes(line.expandtabs(4)) in_item = _indent_width(rest) >= list_indent return (not rest.strip() or line_depth > depth or bool(NO_PARAGRAPH.match(rest) or (_fence_step(None, line)[0] and _indent_width(rest) < list_indent + 4) or (line_depth == depth and in_item and SETEXT_UNDERLINE.match(rest)) or any(start.match(rest) for start, _ in HTML_BLOCK_KINDS) or _list_item(rest, list_indent, line_depth == depth))) def _paragraph_runs(lines, start, depth, list_indent): """Return (end, last) for the paragraph that continues at LINES[START]. END is the index of the line that ends it. LAST maps each backtick run length to the index of its last line before END. One scan serves every run in the paragraph, so the cost stays linear in the line count. """ last, end = {}, start while end < len(lines) and not _breaks_paragraph(depth, lines[end], list_indent): for run in BACKTICK_RUN.finditer(lines[end]): last[len(run.group())] = end end += 1 return end, last def _mask_code_spans(line, open_run, closes_later, lines=(), next_index=0, depth=0, skip=0, carry=None, brackets=None, hidden=None): """Blank the code spans in LINE, also a span that wraps across lines. OPEN_RUN is the backtick run length of a span still open from an earlier line, or 0. LINES[NEXT_INDEX:] are the lines after LINE. As in CommonMark 6.1, a span ends at the next run of the same length, and a run that no later run in the paragraph closes is literal text. Outside code spans, fill inline link destinations with underscores, blank link titles, and fill the inline HTML that GitHub does not show. What starts first wins: a code span that opens before "](" hides the link, and a backtick in a link, an autolink or inline HTML is text. DEPTH is the quote depth of the paragraph that LINE is in, or None when no paragraph goes on after LINE, so a link must close in it. SKIP is where a link from an earlier line ends in LINE. When a link goes on in a later line, CARRY gets [lines ahead, column after its ")"]. BRACKETS carries the open "[" marks from line to line of a paragraph. HIDDEN, when it is a list, gets the (start, end) of each underscore fill and of each autolink and inline HTML item, all of it: GitHub reads no emphasis run in one, also where it shows a part (a tag name, an attribute name). Return (masked line, open run). """ masked = list(line) start = 0 if open_run else None runs = list(BACKTICK_RUN.finditer(line)) last = {len(run.group()): i for i, run in enumerate(runs)} # last run of each length opens = [m.end() for m in LINK_OPEN.finditer(line) if not _escaped(line, m.start())] # Autolinks and inline HTML tags: a code span or a link in one is text. # An item is (start, end, the parts of it that GitHub does not show). atoms = [(m.start(), m.end(), ()) for m in AUTOLINK.finditer(line)] for m in INLINE_TAG.finditer(line): # GitHub shows no attribute value. A bare word stays, as in the # placeholder "". hide = () if m.group("name") and m.group("name").lower() not in FILTERED_TAGS: hide = [value.span() for value in ATTRIBUTE_VALUE.finditer(line, m.end("name"), m.end())] atoms.append((m.start(), m.end(), hide)) atoms += _inline_html_other(line) atoms.sort(key=lambda atom: atom[:2]) atoms = [atom for atom in atoms if not _escaped(line, atom[0])] marks = [m.start() for m in BRACKET.finditer(line) if not _escaped(line, m.start())] if brackets is None: brackets = [[], 0] # BRACKETS[0] holds the "[" marks of the paragraph that no "]" closed yet, # True for an image "![". A "[" below BRACKETS[1] is in a link, so it # opens no link (CommonMark 6.3); an image "![" can still open an image. stack = brackets[0] a = 0 b = 0 k = 0 done = skip # the end of the last code span or link _blank_title(masked, line, 0, skip) # a link title from an earlier line def pop_bracket(): image = stack.pop() active = image or len(stack) >= brackets[1] brackets[1] = min(brackets[1], len(stack)) return image, active def take_brackets(limit): # Read the "[" and "]" marks before LIMIT, outside code, links and tags. nonlocal b while b < len(marks) and marks[b] < limit: pos = marks[b] b += 1 if pos < done: continue if line[pos] == "[": stack.append(pos > 0 and line[pos - 1] == "!" and not _escaped(line, pos - 1)) elif line[pos + 1:pos + 2] != "(" and stack: pop_bracket() # mask_links reads a "](" mark def take_atoms(limit): # Let the autolinks and tags that start before LIMIT start first. nonlocal a, done while a < len(atoms) and atoms[a][0] < limit: begin, end, hide = atoms[a] a += 1 if begin < done: continue take_brackets(begin) done = end if hidden is not None: hidden.append((begin, end)) # Keep the spaces, so the token count stays. for left, right in hide: masked[left:right] = [c if c.isspace() else "_" for c in line[left:right]] def mask_links(limit): # Fill the destinations after the "](" marks before LIMIT. nonlocal k, done while k < len(opens) and opens[k] <= limit: pos = opens[k] k += 1 take_atoms(pos - 2) take_brackets(pos - 2) if pos - 2 < done or not stack: continue # no "[" opens link text, so "](" is text image, active = pop_bracket() if not active: continue later = (lines[index] for index in range(next_index, len(lines))) link = _link_destination_end(line, pos, later, depth) if link is None or (link[0] == pos and line[pos:link[1]].strip() != ")"): continue # with no destination, a "title" is the destination: a gap this reads as no link if not image: brackets[1] = len(stack) # a link holds no link masked[pos:link[0]] = "_" * (link[0] - pos) if hidden is not None: hidden.append((pos, link[0])) _blank_title(masked, line, link[0], link[1]) done = link[1] if carry is not None and link[2]: carry[:] = link[2] for i, run in enumerate(runs): n = len(run.group()) if start is not None: if n == open_run: masked[start:run.end()] = " " * (run.end() - start) start, open_run = None, 0 done = run.end() continue mask_links(run.start()) take_atoms(run.start()) if run.start() < done: continue # a backtick in a link, an autolink or a tag is text first = run.start() if _escaped(line, first): first, n = first + 1, n - 1 # an escaped backtick is text if n and (last.get(n, -1) > i or closes_later(n)): take_brackets(first) start, open_run = first, n if start is not None: masked[start:] = " " * (len(line) - start) else: mask_links(len(line)) take_atoms(len(line)) take_brackets(len(line)) # a "[" that a later line can close return "".join(masked), open_run def _inline_html_other(line): """Return (start, end, hidden parts) for each comment, processing instruction, declaration and CDATA section that starts and ends in LINE. GitHub shows none of a comment or a declaration. Its HTML sanitizer reads a processing instruction and CDATA as a comment that ends at the first ">", so it shows the text after that ">". """ found = [] for opener, closer in INLINE_HTML_OTHER: for m in opener.finditer(line): if closer == "-->" and line.startswith(("", ""), m.start()): end = line.index(">", m.end()) + 1 found.append((m.start(), end, [(m.start(), end)])) continue end = line.find(closer, m.end()) if end < 0: break # no later opener closes either end += len(closer) shown = end if closer in ("-->", ">") else line.index(">", m.start()) + 1 found.append((m.start(), end, [(m.start(), shown)])) return found def _html_item_wraps(source, masked, hidden, start): """True when an inline HTML item can start in SOURCE and end on a later line. MASKED is SOURCE masked, at the same length. HIDDEN holds the (start, end) of the items that end in SOURCE. An open tag can go on after the end of the line, also a comment, a processing instruction, a declaration or a CDATA section without its closer in SOURCE. A "<" in a code span, in a hidden range, after a backslash or before START starts no item. """ items = sorted(hidden) item = 0 last = {closer: source.rfind(closer) for _, closer in INLINE_HTML_OTHER} for m in HTML_ITEM_START.finditer(source, start): pos = m.start() while item < len(items) and items[item][1] <= pos: item += 1 if (item < len(items) and items[item][0] <= pos) or masked[pos] != "<" or _escaped(source, pos): continue if WRAPPED_TAG.match(source, pos): return True for opener, closer in INLINE_HTML_OTHER: other = opener.match(source, pos) if other and last[closer] < other.end(): return True return False def _escaped(line, pos): """True when an odd number of backslashes comes right before LINE[POS].""" start = pos while start and line[start - 1] == "\\": start -= 1 return (pos - start) % 2 == 1 def _blank_title(masked, line, start, end): """Blank the link title in MASKED[START:END] with spaces, but keep its ")". GitHub shows a title in no text, so it is not prose. The ")" stays, so the link stays one token for the word count, as it is when it has no title. """ if start < end: masked[start:end] = " " * (end - start) if line[end - 1] == ")": masked[end - 1] = ")" def _char_ref_is_markup(match): """True when the character reference MATCH renders as one character. A named reference counts only when its name is in the HTML5 list. A reference that renders as a semicolon is prose: GitHub shows a semicolon. """ name, decimal, hexadecimal = match.groups() if name is not None: return name + ";" in html.entities.html5 and name != "semi" value = int(decimal) if decimal is not None else int(hexadecimal, 16) return value != ord(";") def _paragraph_lines(later_lines, depth): """Yield (text, column, lines ahead) for the lines that continue the paragraph. TEXT is the line without its quote prefix, which ends at COLUMN. DEPTH is the quote depth of the paragraph, or None when no paragraph goes on. A blank line, a deeper quote and a line that starts a block end the paragraph (CommonMark 4.1 to 4.6, 5.1 and 5.2). A line with fewer ">" is a lazy line and continues it. """ if depth is None: return for ahead, line in enumerate(later_lines, 1): levels, rest = _strip_quotes(line) if (levels > depth or not rest.strip() or NO_PARAGRAPH.match(rest) or SETEXT_UNDERLINE.match(rest) or PARAGRAPH_INTERRUPT.match(rest) or any(start.match(rest) for start, _ in HTML_BLOCK_KINDS)): return yield rest, len(line) - len(rest), ahead def _skip_link_gap(item, pos, rest): """Skip spaces and tabs from POS, with at most one line ending. ITEM is (text, column, lines ahead), and REST yields the next items of the paragraph. Return (item, pos, crossed), or None when the paragraph ends. """ while pos < len(item[0]) and item[0][pos] in " \t": pos += 1 if pos < len(item[0]): return item, pos, False item = next(rest, None) if item is None: return None pos = 0 while pos < len(item[0]) and item[0][pos] in " \t": pos += 1 return item, pos, True def _skip_link_title(item, pos, rest): """Return (item, pos) after a link title that starts at POS, or None. ITEM is (text, column, lines ahead). The title can go on in the next lines of the paragraph (REST), but it must close before the paragraph ends. """ line = item[0] closer = {'"': '"', "'": "'", "(": ")"}[line[pos]] pos += 1 while True: while pos < len(line): if line[pos] == "\\" and pos + 1 < len(line) and line[pos + 1] in ASCII_PUNCTUATION: pos += 2 continue if line[pos] == closer: return item, pos + 1 if closer == ")" and line[pos] == "(": return None pos += 1 item, pos = next(rest, None), 0 if item is None: return None line = item[0] def _link_destination_end(text, start, later_lines=(), depth=None): """Return (destination end, link end, carry) for the destination at START, or None. START is after "](". CommonMark 6.3: the destination is in <...>, or it has no space or control character and its parentheses are balanced. An optional title and ")" must follow, in the same paragraph. LATER_LINES are the lines after TEXT, and DEPTH is the quote depth of the paragraph (see _paragraph_lines). Each gap of spaces and tabs may hold one line ending, and the title may span lines. The link end is after ")" when the link closes in TEXT, else the end of TEXT, and CARRY is then (lines ahead, column after ")") of the line where it closes, else None. """ pos = start if pos < len(text) and text[pos] == "<": pos += 1 while pos < len(text) and text[pos] not in "<>": pos += 2 if text[pos] == "\\" and pos + 1 < len(text) else 1 if pos >= len(text) or text[pos] != ">": return None end = pos + 1 else: parens = 0 while pos < len(text): char = text[pos] if char == "\\" and pos + 1 < len(text) and text[pos + 1] in ASCII_PUNCTUATION: pos += 2 continue if char <= " " or char == "\x7f": break if char == "(": parens += 1 if parens > MAX_LINK_PARENS: return None elif char == ")": if parens == 0: break parens -= 1 pos += 1 if parens: return None end = pos rest = _paragraph_lines(later_lines, depth) gap = _skip_link_gap((text, 0, 0), end, rest) if gap is None: return None item, pos, crossed = gap if (crossed or pos > end) and item[0][pos] in "\"'(": title = _skip_link_title(item, pos, rest) if title is None: return None gap = _skip_link_gap(*title, rest) if gap is None: return None item, pos, _ = gap if item[0][pos] != ")": return None if item[2] == 0: return end, pos + 1, None return end, len(text), (item[2], item[1] + pos + 1) def _mask_non_prose(text, hidden=None): """Fill character references and autolinks. The fill is underscores, not spaces, so a token stays one token and word counts do not change. An underscore is not a word character for _count_words. Code spans and link destinations are blanked by _mask_code_spans. HIDDEN, when it is a list, gets the (start, end) of each fill. """ out = [] pos = done = 0 while pos < len(text): end = None if text[pos] == "&": ref = CHAR_REF.match(text, pos) if ref and _char_ref_is_markup(ref): end = ref.end() if end is None and text[pos] == "<": link = AUTOLINK.match(text, pos) if link: end = link.end() if end is None: pos += 1 continue out.append(text[done:pos]) out.append("_" * (end - pos)) if hidden is not None: hidden.append((pos, end)) pos = done = end out.append(text[done:]) return "".join(out) def _gfm_autolinks(source, masked, start, depth, hidden): """Add the (start, end) of each autolink in SOURCE[START:] to HIDDEN, for the emphasis view. These are the links that _mask_non_prose leaves: an email autolink (), and a GFM extended autolink (www.example.com, https://example.com). GitHub reads a "*" or "_" in a link as text. MASKED is SOURCE masked: a link starts only where the two agree, and not in a range that HIDDEN already holds, so not in code, a link destination, an autolink or inline HTML (all of it, also the text of a processing instruction after its first ">"). START is where the text of the line starts, after a quote or list marker. As on GitHub (cmark-gfm), no extended autolink starts after a "[" that no "]" closed yet. DEPTH is the number of such "[" marks before the line. Return the number after the line. """ items = [] # the ranges in HIDDEN, merged for begin, end in sorted(hidden): if items and begin <= items[-1][1]: items[-1][1] = max(items[-1][1], end) else: items.append([begin, end]) item = 0 pos = start while pos < len(source): while item < len(items) and items[item][1] <= pos: item += 1 if item < len(items) and items[item][0] <= pos: pos = items[item][1] continue char = masked[pos] if char != source[pos] or (char in "[]<" and _escaped(source, pos)): pos += 1 continue link = None if char == "[": depth += 1 elif char == "]": depth = max(depth - 1, 0) elif char == "<": email = EMAIL_AUTOLINK.match(source, pos) link = email and email.span() elif depth == 0 and char in "w:": link = _gfm_extended_autolink(source, pos, start) if link: hidden.append(link) pos = link[1] else: pos += 1 return depth def _gfm_extended_autolink(text, pos, start): """Return (start, end) of the GFM extended autolink at the "w" or ":" at TEXT[POS], or None. This follows www_match and url_match of GitHub's parser (cmark-gfm). A "www." link starts after white space, "*", "_", "~" or "(", or at START. A ":" ends the scheme http, https or ftp, which starts the link. The domain must pass _gfm_domain. The link ends before white space or "<", without its trailing punctuation (_gfm_link_end). An escaped ":" has a backslash before it, so no scheme. """ if text[pos] == "w": if pos > start and text[pos - 1] not in "*_~( \t\r\n": return None if not text.startswith("www.", pos) or not _gfm_domain(text, pos): return None begin = pos else: begin = pos while begin > start and text[begin - 1].isascii() and text[begin - 1].isalpha(): begin -= 1 if (text[begin:pos].lower() not in ("http", "https", "ftp") or not text.startswith("://", pos) or pos + 3 >= len(text) or _flanking(text[pos + 3]) != "other" or not _gfm_domain(text, pos + 3)): return None stop = GFM_LINK_STOP.search(text, pos) end = _gfm_link_end(text, pos, stop.start() if stop else len(text)) return (begin, end) if end > pos else None def _gfm_domain(text, start): """True when GitHub reads the domain at TEXT[START:] as the domain of a link (cmark-gfm check_domain). The domain ends at the first character that is not a letter, a digit, "-", "_", "." or one after a backslash. An underscore in one of its last two parts makes it no domain, unless it has more than ten dots. (cmark-gfm also wants a dot in the domain of a "www." link: the dot of "www." counts, unless the paragraph ends there, and then the link holds no "*" or "_".) cmark-gfm reads the domain byte by byte, so it ends after the first character that is not ASCII. """ dots = before_last = in_last = 0 # the dots, the underscores in the last two parts pos = start + 1 if text[start].isascii() else len(text) while pos < len(text): char = text[pos] if char == "\\" and pos + 1 < len(text): pos += 1 char = text[pos] if char == "_": in_last += 1 elif char == ".": before_last, in_last = in_last, 0 dots += 1 elif not char.isascii() or (char != "-" and _flanking(char) != "other"): break pos += 1 return not (before_last or in_last) or dots > 10 def _gfm_link_end(text, start, end): """Return END without the trailing punctuation that GitHub leaves out of a link (cmark-gfm autolink_delim). TEXT[START:END] is the link from its "w" or ":". The punctuation is ? ! . , : * _ ~ ' ", a character reference such as "&", and a ")" that has no "(" in the link. """ opening, closing = text.count("(", start, end), text.count(")", start, end) while end > start: char = text[end - 1] if char == ")": if closing <= opening: break closing -= 1 elif char == ";": ref = end - 2 while ref > start and text[ref].isascii() and text[ref].isalpha(): ref -= 1 if ref < end - 2 and text[ref] == "&": end = ref continue elif char not in "?!.,:*_~'\"": break end -= 1 return end def _emphasis_view(source, masked, hidden): """Return SOURCE with each "*", "_" and "~" that the masking hid shown as "x". MASKED is SOURCE masked, at the same length. HIDDEN holds the (start, end) of each underscore fill, where a "_" stays the same, of each autolink and inline HTML item, and of each autolink that _gfm_autolinks finds. The emphasis runs are read in this view, as GitHub reads them: a code span next to "**" is a backtick there, and a "*" or "_" in a code span, a link destination, an autolink or inline HTML is no run. """ view = ["x" if original in "*_~" and char != original else original for char, original in zip(masked, source)] for start, end in hidden: for index in range(start, end): if view[index] in "*_~": view[index] = "x" return "".join(view) def _flanking(char): """Classify CHAR next to a delimiter run: "space", "punct", or "other". The classes are those of GitHub's parser (cmark-gfm): punctuation is ASCII punctuation or a Unicode P* character, so a symbol such as "→" is "other". """ if char in UNICODE_SPACE: return "space" if char in ASCII_PUNCTUATION or (char > "\x7f" and unicodedata.category(char)[0] == "P"): return "punct" return "other" def _emphasis_runs(text): """Return the end offsets of the "*" and "_" runs in TEXT that emphasis uses. TEXT is one prose block. This follows the delimiter run rules of CommonMark 6.2 and its "process emphasis" procedure. A left-flanking run can open, and a right-flanking run can close. An "_" run that is both opens only after punctuation and closes only before punctuation, so an underscore inside a word does neither. A run closes when an open run of the same character comes before it anywhere in the block, also in an earlier sentence. The rule of 3 applies: when one of the two runs can both open and close, their lengths must not add up to a multiple of 3, unless both are multiples of 3. The open runs between the two close with them, and their markers stay text. Emphasis uses a run when it uses one or more of its markers, to open or to close. A backslash makes the first marker of a run text. As in GitHub's parser (cmark-gfm), the strikethrough runs ("~" and "~~") are in the same stack: a closing one removes its opener and the runs between. A "~" next to a "*" or "_" run is skipped when the run is classified. BOTTOMS keeps the cost linear: after a search for an opener fails, the next search for a closer of the same character and length modulo 3 stops there. """ ends = set() stack = [] # [character, length left, length, can close, end offset] of each open run bottoms = {} # (character, length % 3) of a closer -> stack size below which no opener fits def cut(size): del stack[size:] for key in bottoms: bottoms[key] = min(bottoms[key], size) for run in EMPHASIS_RUN.finditer(text): start = run.start() + _escaped(text, run.start()) # a backslash makes the first marker text if start == run.end(): continue char, length = run.group()[0], run.end() - start if char == "~" and length > 2: continue # a strikethrough run has one or two markers left, right = start, run.end() while char != "~" and left and text[left - 1] == "~": left -= 1 while char != "~" and right < len(text) and text[right] == "~": right += 1 before = _flanking(text[left - 1]) if left else "space" after = _flanking(text[right]) if right < len(text) else "space" can_open = after != "space" and (after != "punct" or before != "other") can_close = before != "space" and (before != "punct" or after != "other") if char == "_": can_open, can_close = (can_open and (not can_close or before == "punct"), can_close and (not can_open or after == "punct")) full = length while can_close and length: key = (char, full % 3) for index in range(len(stack) - 1, bottoms.get(key, 0) - 1, -1): open_char, open_left, open_full, open_close, open_end = stack[index] if open_char == char and not ((open_close or can_open) and (open_full + full) % 3 == 0 and (open_full % 3 or full % 3)): break else: bottoms[key] = len(stack) break if char == "~": cut(index) # the strikethrough closes, with both runs and all runs between length = 0 break ends.update((run.end(), open_end)) used = 2 if length >= 2 and open_left >= 2 else 1 length -= used if open_left > used: stack[index][1] -= used cut(index + 1) else: cut(index) if can_open and length: stack.append([char, length, full, can_close, run.end()]) return ends def _sentence_starts(text, view=None, emphasis=None): """Return the offset of each sentence start in text. A sentence ends at a word that ends in terminal punctuation, after any closing quotes or brackets. Known abbreviations do not end a sentence. VIEW is TEXT as _emphasis_view gives it, where the emphasis runs are read. A "*" or "_" after the stop ends the sentence only when emphasis uses it, as GitHub shows it. An underscore that the masking put there is no run. EMPHASIS holds the end offsets of the runs that emphasis uses. When it is None, the runs are read in VIEW. One pass over the words keeps the cost linear in the text length. """ words = list(re.finditer(r"\S+", text)) if not words: return [0] view = text if view is None else view if emphasis is None: emphasis = _emphasis_runs(view) starts = [words[0].start()] for word, next_word in zip(words, words[1:]): end = SENTENCE_END.search(word.group()) if not end: continue if not all(run.end() in emphasis for run in DELIMITER_RUN.finditer(view, word.start() + end.start(), word.end())): continue core = word.group()[:end.start() + 1].lstrip(OPENERS) if core.lower() in ABBREVIATIONS: continue if (DOTTED_ABBREVIATION.fullmatch(core) and not next_word.group().lstrip(OPENERS)[:1].isupper()): continue starts.append(next_word.start()) return starts def _long_sentence_findings(pieces, filename, emphasis=None): """Flag long sentences in one prose block. pieces is a list of (lineno, source_column, text, view, ...) tuples. TEXT is the line with code spans and links masked. VIEW is the line as _emphasis_view gives it, at the same length. The texts are joined with spaces, so a sentence wrapped across source lines is counted once, and each finding points at the line and column where it starts. EMPHASIS holds the end offsets of the runs that emphasis uses in the joined views, or None. """ offsets, position = [], 0 for piece in pieces: offsets.append(position) position += len(piece[2]) + 1 joined = " ".join(piece[2] for piece in pieces) view = " ".join(piece[3] for piece in pieces) findings = [] starts = _sentence_starts(joined, view, emphasis) for start, end in zip(starts, starts[1:] + [len(joined)]): n = _count_words(joined[start:end]) if n <= MAX_WORDS: continue index = bisect.bisect_right(offsets, start) - 1 offset = offsets[index] lineno, source_column = pieces[index][:2] findings.append({"file": filename, "line": lineno, "col": source_column + start - offset + 1, "rule": "long-sentence", "level": "advisory-free", "match": f"{n} words", "message": f"Sentence has {n} words (cap {MAX_WORDS}). Split it."}) return findings def _block_emphasis(blocks): """Return, for each block in BLOCKS, the end offsets of the runs that emphasis uses. A block is a list of (lineno, source_column, text, view, paragraph, wraps, unsure) pieces, and the offsets are in its views joined with spaces. GitHub reads the emphasis of a paragraph as a whole, and a paragraph can hold more than one block: a lazy line after a quote line starts a new block, for example. So the runs are read in the joined views of all pieces of a PARAGRAPH. WRAPS is True when an inline HTML item can start in the piece and end on a later line. The view does not show where that item ends. UNSURE is True when GitHub can put the line in another paragraph than the main loop does. So when a piece other than the last piece of a paragraph wraps, or when a piece is unsure, each run of that paragraph counts as used, as before this check. """ flat = [piece for block in blocks for piece in block] paragraphs = {} # paragraph -> the indexes of its pieces in FLAT for index, piece in enumerate(flat): paragraphs.setdefault(piece[4], []).append(index) used = [None] * len(flat) # the run ends of each piece, in its view for indexes in paragraphs.values(): view = " ".join(flat[index][3] for index in indexes) if any(flat[index][5] for index in indexes[:-1]) or any(flat[index][6] for index in indexes): ends = [run.end() for run in DELIMITER_RUN.finditer(view)] else: ends = sorted(_emphasis_runs(view)) offset = 0 for index in indexes: size = len(flat[index][3]) low = bisect.bisect_right(ends, offset) high = bisect.bisect_right(ends, offset + size) used[index] = [end - offset for end in ends[low:high]] offset += size + 1 result, index = [], 0 for block in blocks: ends, offset = set(), 0 for piece in block: ends.update(offset + end for end in used[index]) offset += len(piece[3]) + 1 index += 1 result.append(ends) return result # One blockquote level: up to three spaces, ">", and one optional space. QUOTE_LEVEL = re.compile(r" {0,3}> ?") def _strip_quotes(line, depth=None): """Return (levels, rest): the blockquote levels that start LINE and the text after them. With DEPTH, remove at most DEPTH levels: a deeper ">" is content. """ levels, pos = 0, 0 while depth is None or levels < depth: level = QUOTE_LEVEL.match(line, pos) if not level: break levels, pos = levels + 1, level.end() return levels, line[pos:] def _indent_width(text): """Columns of the spaces and tabs that start TEXT, with a tab stop of 4.""" return len(text[:len(text) - len(text.lstrip(" \t"))].expandtabs(4)) def _fence_ends_with_quote(fence, line): """True when LINE has fewer blockquote levels than the open FENCE.""" return fence is not None and _strip_quotes(line.expandtabs(4), fence[1])[0] < fence[1] def _fence_step(fence, line): """Return (is_fence_line, open_fence) after LINE. FENCE is None, or the open fence as (run, quote depth, indent). This follows CommonMark 4.5 for blockquotes and for the fence itself: a fence in a blockquote ends when its quote ends. Only a run of the same character, at least as long, with only spaces or tabs after it, closes the block. A backtick fence has no backtick in its info string. List items are not tracked, so the indent of a fence is not limited to three columns. A closing fence may have at most three columns more indent than the opening fence, also at the top level. """ # Tabs become spaces from the real column, so a tab after ">" counts correctly. line = line.expandtabs(4) if fence is None: depth, rest = _strip_quotes(line) content = rest.lstrip(" \t") marker = CODE_FENCE.match(content) if not marker: return False, None run = marker.group(1) if run[0] == "`" and "`" in content[marker.end():]: return False, None return True, (run, depth, _indent_width(rest)) if _fence_ends_with_quote(fence, line): # The quote that holds the fence ended, so the fence ended too. return _fence_step(None, line) run, depth, indent = fence rest = _strip_quotes(line, depth)[1] content = rest.lstrip(" \t") marker = CODE_FENCE.match(content) if (marker and marker.group(1)[0] == run[0] and len(marker.group(1)) >= len(run) and _indent_width(rest) <= indent + 3 and not content[marker.end():].strip(" \t")): return True, None return False, fence # CommonMark 4.6: how each kind of HTML block starts, and the text that ends it. # None: the block ends at a blank line (types 6 and 7). _BLOCK_TAGS = ( "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|" "details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|" "h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|" "optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|" "tr|track|ul" ) HTML_BLOCK_KINDS = [ (re.compile(r"^ {0,3}<(?:script|pre|style|textarea)(?:[ \t]|>|$)", re.I), re.compile(r"", re.I)), (re.compile(r"^ {0,3}")), (re.compile(r"^ {0,3}<\?"), re.compile(r"\?>")), (re.compile(r"^ {0,3}")), (re.compile(r"^ {0,3}")), (re.compile(rf"^ {{0,3}}|$)", re.I), None), ] HTML_COMMENT_END = HTML_BLOCK_KINDS[1][1] # Type 7: one complete open or closing tag alone on its line (CommonMark 6.6 grammar). # It cannot interrupt a paragraph. In one line, CommonMark whitespace is a space or a # tab: a no-break space or another Unicode space is text, so the line is no tag. _ATTRIBUTE = (r"[ \t]+[A-Za-z_:][A-Za-z0-9_.:-]*" r"(?:[ \t]*=[ \t]*(?:[^ \t\"'=<>`]+|'[^']*'|\"[^\"]*\"))?") # The names of type 1 (pre, script, style, textarea) never start a type 7 block, # as an open tag or as a closing tag. A custom name such as pre-x is no type 1 name. _TYPE1_NAME = r"(?!(?i:pre|script|style|textarea)(?![A-Za-z0-9-]))" HTML_TYPE7 = re.compile( rf"^ {{0,3}}(?:<{_TYPE1_NAME}[A-Za-z][A-Za-z0-9-]*(?:{_ATTRIBUTE})*[ \t]*/?>" rf"|)[ \t]*$") # Lines that end a paragraph and are no paragraph line, after the quote prefix: an ATX # heading and a thematic break of one repeated character. A quote line with no text # also ends a paragraph. NO_PARAGRAPH = re.compile( r"^ {0,3}(?:#{1,6}(?:[ \t]|$)|(?:-[ \t]*){3,}$|(?:\*[ \t]*){3,}$|(?:_[ \t]*){3,}$)") # A setext underline. It ends a paragraph only when a paragraph is open at the same # quote depth. Else it is text, also as a lazy line after a quote (CommonMark 4.3). SETEXT_UNDERLINE = re.compile(r"^ {0,3}(?:=+|-+)[ \t]*$") def _html_block_step(block, line, in_paragraph): """Return (in_html_block, open_block) for LINE. BLOCK is None, False (an HTML block that ends at a blank line), or the pattern that ends the open block. IN_PARAGRAPH: a paragraph is open before LINE. A ">" in an HTML block is text, so it opens no fence. """ if block is None: for start, end in HTML_BLOCK_KINDS: if start.match(line): block = False if end is None else end break else: if in_paragraph or not HTML_TYPE7.match(line): return False, None block = False if block is False: return bool(line.strip()), (block if line.strip() else None) return True, (None if block.search(line) else block) # GitHub shows the text of an HTML block of type 6 or 7. It also shows the text of a #