Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/jmrplens/phonometry. Standards-conformant acoustics library for Python: measurement and metrology, docs.jmrp.io/phonometry
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399#!/usr/bin/env python3r"""Refuse an em dash in the prose the project publishes.
The house style writes its prose without the em dash: a clause that would hangoff one is a sentence of its own, a parenthesis, a colon or a comma, chosen bywhat the sentence needs. The rule covers everything a reader sees under theproject's name, which is more than the pages of the site: the docs mirrors,the CHANGELOG, the README, the docstrings the API reference is generated from,and the titles, labels and annotations drawn into the figures.
What is NOT prose keeps its dash, and every exemption below says why:
- **A standard's title reproduced as printed.** ISO, IEC, EN and DIN write "Acoustics — Part 2: ..." and "Erschütterungen im Bauwesen — Teil 3: ..." with the dash, and a citation reproduces its source. The guard exempts a dash that sits in a frontmatter ``title:`` value, in an italic span, in a bibliographic entry (author and year first, the title after), inside quotation marks or guillemets, or on a line that reads ``— Part 3:``, ``— Teil 3:``, ``— Partie 3:`` or ``— Parte 3:``. A quotation long enough is wrapped by the paragraph that carries it, opening on one line and closing two lines below, so the open quotation is carried from line to line within a paragraph exactly as the italic span is.- **Code.** A fenced block, an inline code span and a string a test compares with are data, not prose, and a dash that fills a whole table cell, or a whole slash-separated item of one, is the placeholder of an empty cell, not a sentence. The glossary cards, the home page's text and the Spanish catalogue notes are prose in the site's data modules and are read as such.- **Two bare dashes** in a table row separator or a horizontal rule are hyphens, not em dashes; only U+2014 is looked for.
Exit status 0 when the prose is clean, 1 otherwise, naming every file and line."""
from __future__ import annotations
import argparseimport astimport ioimport jsonimport pathlibimport reimport sysimport tokenize
from markdown_fences import code_lines
EM_DASH = "—"
#: Where the published prose lives: the pages and their mirrors, the data#: modules the site's pages are built from (the glossary cards, the home page's#: text and examples, the Spanish catalogue notes), the package docstrings the#: API reference is generated from, and the text the figure and diagram#: generators draw. Tests are not published and keep their dashes, and the#: llms mirrors and the generated API pages are regenerated from what is listed#: here and need no scan of their own.DEFAULT_ROOTS = ( "docs", "site/src/content/docs", "site/src/data", "src/phonometry", "scripts/figures", "scripts/diagrams", "CHANGELOG.md", "README.md", "README_PYPI.md", "CONTRIBUTING.md", "AGENTS.md",)
#: Bold markers, which are not italics and are taken out before counting._BOLD = re.compile(r"\*\*")#: A list bullet written with an asterisk, which is not an italic marker#: either: left in, it opens a span that swallows the rest of the item._BULLET = re.compile(r"^\s*\*(?=\s)")#: A part number after the dash, which only a standard's title prints._PART_AFTER_DASH = re.compile(EM_DASH + r"\s*(?:Part|Teil|Partie|Parte)\s+\d")#: A dash inside quotation marks or guillemets: the text reproduces a source.#: Not an attribute value (``alt="..."``) nor a YAML value (``description:#: "..."``), which are prose of the page's own._QUOTED = re.compile(r"(?<!=)(?<!: )[\"«“][^\"»”\n]*" + EM_DASH + r"[^\"»”\n]*[\"»”]")#: The delimiter that closes each opening one. A quotation is closed by its#: own mark, so a straight quote inside guillemets does not end them._QUOTE_PAIRS = {'"': '"', "«": "»", "“": "”"}#: What may sit before a straight quote that opens a quotation. A straight#: quote is the one mark that opens and closes with the same character, so it#: is read as an opening one only where an opening one can stand._BEFORE_OPENING = ("", " ", "\t", "(", "[", "{")#: An inline code span._CODE_SPAN = re.compile(r"`[^`\n]*`")#: A row of a pipe table._TABLE_ROW = re.compile(r"^\s*\|.*\|")#: A dash that fills a whole cell, or a whole slash-separated item of one: the#: placeholder for "there is none", not a sentence. A parameter table writes#: the unit of a name that has none as ``—``, and the unit of a row that#: documents two names at once as ``— / h``, so the placeholder has to be read#: item by item or that one row ends up saying "none" where every other row of#: its column says ``—``._PLACEHOLDER_ITEM = re.compile(r"(?:^|(?<=/))\s*" + EM_DASH + r"\s*(?=/|$)")#: A frontmatter title, which reproduces the document's own title._TITLE_LINE = re.compile(r"^\s*(?:-\s*)?title:\s")#: The first line of a bibliographic entry, author and year: the lines of the#: entry reproduce a title as printed, dashes and all._REFERENCE_ENTRY = re.compile(r"^\s*(?:-|\d+\.)\s.*\(\d{4}[a-z]?\)")
def _outside_italics(line: str, *, italic_open: bool) -> tuple[str, bool]: """The characters of the line outside italic spans, and the state at its end.
A title in italics is a citation reproduced as printed, and the bibliography wraps a title over several lines, so the italic state is carried from one line to the next within a paragraph.
Only a citation, though: see :func:`_is_caption`, which is what tells the two italics of this corpus apart. """ text = _BULLET.sub(lambda m: " " * len(m.group()), _BOLD.sub("", line)) kept: list[str] = [] for char in text: if char == "*": italic_open = not italic_open elif not italic_open: kept.append(char) return "".join(kept), italic_open
def _opens_quotation(line: str, index: int) -> bool: """Whether the mark at ``index`` opens a quotation.
A guillemet and a curly quote say which end they are. A straight quote does not, so it opens a quotation only where an opening one can stand: after nothing, a space or an opening bracket, and before a character that is not a space. That also settles the two marks that are not quotation at all, an attribute value (``alt="..."``) and a YAML value (``description: "..."``): neither of their quotes opens anything, so the prose of the value is scanned like any other and the marks do not run on. """ if line[index] != '"': return True if line[index - 1 : index] == "=" or line[index - 2 : index] == ": ": return False return line[index - 1 : index] in _BEFORE_OPENING and line[ index + 1 : index + 2 ] not in ("", " ", "\t")
def _outside_quotations(line: str, *, closer: str | None) -> tuple[str, str | None]: """The characters of the line outside quotations, and the state at its end.
A citation is reproduced as printed, and a title long enough is wrapped by the paragraph that quotes it: the opening mark sits on one line and the closing one two lines below, with the dash of the title in between. A line-scoped match cannot see that such a dash is inside the quotation, so the open quotation is carried from one line to the next within a paragraph, as the italic state is. """ kept: list[str] = [] for index, char in enumerate(line): if closer is not None: if char == closer: closer = None continue if char in _QUOTE_PAIRS and _opens_quotation(line, index): closer = _QUOTE_PAIRS[char] continue kept.append(char) return "".join(kept), closer
def _is_caption(line: str) -> bool: """Whether the paragraph this line opens is one italic span, end to end.
The two italics of this corpus are not the same thing. A citation sets a title in italics *inside* a sentence, and the title carries whatever dash the document prints. A figure caption sets the whole paragraph in italics, and it is the maintainer's own prose, which the house style writes without the em dash like every other sentence. Exempting the second along with the first is what let 262 dashes stand in the published pages, one to a caption, where no other gate could see them.
The paragraph's first line is what says which: a caption opens with the ``*`` that opens the span, a citation opens with the text that introduces the title. Bold (``**``) and a list bullet (``* ``) are not italics at all. """ stripped = line.lstrip() return ( stripped.startswith("*") and not stripped.startswith("**") and not stripped.startswith("* ") )
def _strip_exempt_markdown( line: str, *, italic_open: bool, quote_closer: str | None, caption: bool = False) -> tuple[str, bool, str | None]: """The line with every exempt use of the dash removed, and the carried state.""" if _TITLE_LINE.match(line): return "", italic_open, quote_closer line = _CODE_SPAN.sub("", line) if _TABLE_ROW.match(line): line = "|".join(_PLACEHOLDER_ITEM.sub("", cell) for cell in line.split("|")) line, quote_closer = _outside_quotations(line, closer=quote_closer) if caption: # The whole paragraph is the span, so there is no "outside" to keep: # the state still has to be carried, because the closing ``*`` may be # several lines below. _, italic_open = _outside_italics(line, italic_open=italic_open) else: line, italic_open = _outside_italics(line, italic_open=italic_open) if _PART_AFTER_DASH.search(line): return "", italic_open, quote_closer return line, italic_open, quote_closer
def markdown_hits(text: str) -> list[int]: """The 1-based lines of a markdown or MDX page that carry a prose dash.""" hits: list[int] = [] italic_open = False quote_closer: str | None = None in_reference = False caption = False opening = True lines = text.splitlines() for number, (line, code) in enumerate( zip(lines, code_lines(lines), strict=True), start=1 ): if code: continue stripped = line.lstrip() if not stripped: italic_open = False quote_closer = None in_reference = False caption = False opening = True continue if _REFERENCE_ENTRY.match(line): in_reference = True elif not line.startswith((" ", "\t")): in_reference = False if opening: caption, opening = _is_caption(line), False prose, italic_open, quote_closer = _strip_exempt_markdown( line, italic_open=italic_open, quote_closer=quote_closer, caption=caption ) if EM_DASH in prose and not in_reference: hits.append(number) return hits
def _string_is_prose(value: str) -> bool: """Whether a string literal with a dash is prose and not a placeholder.""" if value.strip() == EM_DASH: return False if _PART_AFTER_DASH.search(value): return False return not _QUOTED.search(value)
def python_hits(text: str) -> list[int]: """The 1-based lines of a module whose docstrings, comments or strings carry a dash.""" hits: set[int] = set() try: tokens = list(tokenize.generate_tokens(io.StringIO(text).readline)) except (tokenize.TokenError, SyntaxError): return [n for n, line in enumerate(text.splitlines(), 1) if EM_DASH in line] for token in tokens: if EM_DASH not in token.string: continue if token.type == tokenize.COMMENT: hits.add(token.start[0]) elif token.type == tokenize.STRING: try: value = ast.literal_eval(token.string) except (ValueError, SyntaxError): value = token.string if isinstance(value, str) and _string_is_prose(value): for offset, line in enumerate(token.string.splitlines()): if EM_DASH in line: hits.add(token.start[0] + offset) elif token.type == getattr(tokenize, "FSTRING_MIDDLE", -1): hits.add(token.start[0]) return sorted(hits)
def data_hits(text: str) -> list[int]: """The 1-based lines of a data module (glossary, home page) whose text has a dash.
A comment is not published and keeps its dash; a standard's title is exempt as everywhere else. """ hits: list[int] = [] for number, line in enumerate(text.splitlines(), start=1): if EM_DASH not in line or line.lstrip().startswith(("//", "*", "/*")): continue if _PART_AFTER_DASH.search(line): continue hits.append(number) return hits
#: A JSON string literal, escapes included._JSON_STRING = re.compile(r'"(?:[^"\\\n]|\\.)*"')
def json_hits(text: str) -> list[int]: """The 1-based lines of a JSON data file whose strings carry a dash.
Every key and value of the file is a string, so each is read as a string literal of a module is: a dash alone is an empty cell, and a dash inside quotation marks reproduces what a source prints. """ hits: list[int] = [] for number, line in enumerate(text.splitlines(), start=1): if EM_DASH not in line: continue for literal in _JSON_STRING.findall(line): try: value = json.loads(literal) except json.JSONDecodeError: value = literal if EM_DASH in value and _string_is_prose(value): hits.append(number) break return hits
#: The suffixes the guard reads, each with the reader that knows its kind._READERS = { ".py": python_hits, ".md": markdown_hits, ".mdx": markdown_hits, ".mjs": data_hits, ".ts": data_hits, ".json": json_hits,}
def scan(path: pathlib.Path) -> list[int]: """The offending lines of one file, by its kind.""" reader = _READERS.get(path.suffix) if reader is None: return [] return reader(path.read_text(encoding="utf-8"))
#: Local working notes under docs/, gitignored and never published._UNPUBLISHED = ("docs/superpowers",)
def iter_files(roots: tuple[str, ...]) -> list[pathlib.Path]: files: list[pathlib.Path] = [] for root in roots: base = pathlib.Path(root) if base.is_file(): files.append(base) elif base.is_dir(): files.extend( p for p in sorted(base.rglob("*")) if p.suffix in _READERS and not any(str(p).startswith(u) for u in _UNPUBLISHED) ) return files
def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("paths", nargs="*", default=DEFAULT_ROOTS) parser.add_argument( "--count", action="store_true", help="print one line per file with its count" ) args = parser.parse_args() total = 0 files = 0 for path in iter_files(tuple(args.paths)): lines = scan(path) if not lines: continue files += 1 total += len(lines) if args.count: print(f"{path}: {len(lines)}") else: for number in lines: print(f"{path}:{number}: em dash in published prose") if total: print( f"{total} em dash(es) in the published prose of {files} file(s); " "rewrite each as a sentence, a parenthesis, a colon or a comma.", file=sys.stderr, ) return 1 print("No em dash in the published prose.") return 0
if __name__ == "__main__": sys.exit(main())