diff --git a/README.md b/README.md index c3ef0ca..7e11a49 100644 --- a/README.md +++ b/README.md @@ -22,8 +22,8 @@ This is the Python implementation. The full spec — all locales, all rules, worked examples in each — lives in [polytypo/polytypo](https://github.com/polytypo/polytypo). This runtime supports -the `text` and `html` modes fully, and `markdown` for the `commonmark` dialect only — `mdx` -raises `POLYTYPO_INVALID_DIALECT` (no MDX/JSX parser is available for Python; see +the `text`, `html` and `yaml` modes fully, and `markdown` for the `commonmark` dialect only — +`mdx` raises `POLYTYPO_INVALID_DIALECT` (no MDX/JSX parser is available for Python; see [Supported dialects](#supported-dialects)). ## Install @@ -59,11 +59,12 @@ transform('Wait... she said "go on."', locale="en-US # Wait… she said “go on.” ``` -`polytypo.text`, `polytypo.html` and `polytypo.markdown` each exclude the parser dependency the -other modes don't need (importing `polytypo.text` never imports `html.parser`-based span -extraction or tree-sitter). The aggregate `polytypo` module supports every mode via a `mode` -keyword, defaulting to `"text"`. `locale` has no default anywhere and must always be passed -explicitly — there is no silent fallback to English. +`polytypo.text`, `polytypo.html`, `polytypo.markdown` and `polytypo.yaml` each exclude the +parser dependency the other modes don't need (importing `polytypo.text` never imports +`html.parser`-based span extraction or tree-sitter; `polytypo.yaml` needs no parser at all). The +aggregate `polytypo` module supports every mode via a `mode` keyword, defaulting to `"text"`. +`locale` has no default anywhere and must always be passed explicitly — there is no silent +fallback to English. ```python import polytypo @@ -71,9 +72,29 @@ import polytypo polytypo.transform("...", locale="fr", mode="markdown", dialect="commonmark") ``` +`yaml` mode is the one that asks something of you, and it asks for a reason. YAML is a data +format with prose in some of it, so you name the keys whose values are prose; there is no default +and no guess: + +```python +from polytypo.yaml import transform + +transform( + "summary: Rates -- all of them...\nrun: git diff -- a--b\n", locale="en-US", keys=["summary"] +) +# summary: Rates—all of them… +# run: git diff -- a--b +``` + +Nothing in YAML's syntax separates a sentence from a shell script: `description` holds one and +`run` holds the other, spelled identically. Quoting, indentation, anchors and a block scalar's +chomping indicator are never decoded and rewritten — the file is located, not re-emitted — so the +trailing newlines of a `|+` block come back exactly as you wrote them. An empty `keys` list is +legal and processes nothing. + `analyze()` runs the same pipeline and reports what it would do instead of doing it — one record per edit, each with the rule that made it and code-point offsets into the input you passed (into -the **document**, in `html` and `markdown` mode, not into a span): +the **document**, in `html`, `markdown` and `yaml` mode, not into a span): ```python import polytypo diff --git a/src/polytypo/__init__.py b/src/polytypo/__init__.py index f3700e5..ce3066f 100644 --- a/src/polytypo/__init__.py +++ b/src/polytypo/__init__.py @@ -1,10 +1,11 @@ """polytypo -- locale-correct quotes, dashes, ellipses and no-break spaces. The aggregate entry point. Its module graph includes every mode's dependencies (`html.parser` -and tree-sitter): it is the only pipeline module that imports all three mode-specific ones. -`polytypo.text`, `polytypo.html` and `polytypo.markdown` each call their own mode-specific -pipeline directly and never import this module (mirrors polytypo-js's `polytypo`/`polytypo/text` -/`polytypo/html`/`polytypo/markdown` split).""" +and tree-sitter): it is the only pipeline module that imports all four mode-specific ones. +`polytypo.text`, `polytypo.html`, `polytypo.markdown` and `polytypo.yaml` each call their own +mode-specific pipeline directly and never import this module (mirrors polytypo-js's +`polytypo`/`polytypo/text`/`polytypo/html`/`polytypo/markdown`/`polytypo/yaml` split). `yaml` +needs no parser at all (modes.md 3.8.1), so it is the lightest of the four.""" from __future__ import annotations @@ -12,9 +13,11 @@ analyze_html_pipeline, analyze_markdown_pipeline, analyze_text_pipeline, + analyze_yaml_pipeline, run_html_pipeline, run_markdown_pipeline, run_text_pipeline, + run_yaml_pipeline, ) from polytypo._engine.origin import Change from polytypo.errors import POLYTYPO_INVALID_MODE, PolytypoError @@ -27,10 +30,11 @@ def _resolve_mode(mode: str | None) -> str: if mode is None or mode == "text": return "text" - if mode in ("html", "markdown"): + if mode in ("html", "markdown", "yaml"): return mode raise PolytypoError( - POLYTYPO_INVALID_MODE, f'Unknown mode "{mode}". Expected "text", "html" or "markdown".' + POLYTYPO_INVALID_MODE, + f'Unknown mode "{mode}". Expected "text", "html", "markdown" or "yaml".', ) @@ -40,18 +44,27 @@ def transform( locale: str, mode: str | None = None, dialect: str | None = None, + keys: object = None, rules: dict[str, bool] | None = None, narrow_nbsp: str | None = None, ) -> str: """`narrow_nbsp="nbsp"` makes the engine emit U+00A0 everywhere it would emit U+202F (nbsp.md 3.1a). It moves the rule's target rather than post-processing the output, so the result stays a fixed point. Validation order is mode -> narrow_nbsp -> rules -> locale -> - dialect, and the check runs whether or not `nbsp` is enabled.""" + dialect -> keys, and the check runs whether or not `nbsp` is enabled. + + `keys` is required when `mode="yaml"` and ignored otherwise (modes.md 3.8.2): YAML is a data + format with islands of prose in it, so the caller names the mapping keys whose values are + prose and the library never guesses. An empty sequence is legal and processes nothing.""" resolved_mode = _resolve_mode(mode) if resolved_mode == "text": return run_text_pipeline(input, locale=locale, rules=rules, narrow_nbsp=narrow_nbsp) if resolved_mode == "html": return run_html_pipeline(input, locale=locale, rules=rules, narrow_nbsp=narrow_nbsp) + if resolved_mode == "yaml": + return run_yaml_pipeline( + input, locale=locale, keys=keys, rules=rules, narrow_nbsp=narrow_nbsp + ) return run_markdown_pipeline( input, locale=locale, dialect=dialect, rules=rules, narrow_nbsp=narrow_nbsp ) @@ -63,6 +76,7 @@ def analyze( locale: str, mode: str | None = None, dialect: str | None = None, + keys: object = None, rules: dict[str, bool] | None = None, narrow_nbsp: str | None = None, ) -> list[Change]: @@ -79,6 +93,10 @@ def analyze( return analyze_text_pipeline(input, locale=locale, rules=rules, narrow_nbsp=narrow_nbsp) if resolved_mode == "html": return analyze_html_pipeline(input, locale=locale, rules=rules, narrow_nbsp=narrow_nbsp) + if resolved_mode == "yaml": + return analyze_yaml_pipeline( + input, locale=locale, keys=keys, rules=rules, narrow_nbsp=narrow_nbsp + ) return analyze_markdown_pipeline( input, locale=locale, dialect=dialect, rules=rules, narrow_nbsp=narrow_nbsp ) diff --git a/src/polytypo/_engine/mode_pipelines.py b/src/polytypo/_engine/mode_pipelines.py index fddb8ce..7d97cf4 100644 --- a/src/polytypo/_engine/mode_pipelines.py +++ b/src/polytypo/_engine/mode_pipelines.py @@ -1,11 +1,11 @@ -"""The three mode-specific top-level pipelines, one per public entry point -(`polytypo`/`polytypo.text`/`polytypo.html`/`polytypo.markdown`). Mirrors polytypo-js's +"""The four mode-specific top-level pipelines, one per public entry point +(`polytypo` and `polytypo.text`/`.html`/`.markdown`/`.yaml`). Mirrors polytypo-js's text-pipeline.ts/html-pipeline.ts/markdown-pipeline.ts split: each function imports only what its mode needs, so `polytypo.text` never imports the HTML or Markdown parsers, and `polytypo.html` never imports tree-sitter-markdown. -Validation order is public, tested behaviour and is identical across all three: `rules` (an -unknown rule id) before `locale` (an unknown locale) before `dialect`/parsing -- see +Validation order is public, tested behaviour and is identical across all four: `rules` (an +unknown rule id) before `locale` (an unknown locale) before `dialect`/`keys`/parsing -- see `pipeline.prepare`'s own docstring.""" from __future__ import annotations @@ -16,6 +16,7 @@ from polytypo._engine.pipeline import prepare, run_rules, run_rules_recording from polytypo._engine.registry import RuleContext from polytypo._engine.span_runner import analyze_over_spans, run_over_spans +from polytypo._engine.yaml_keys import resolve_yaml_keys from polytypo._modes.spans import normalize_spans @@ -82,6 +83,34 @@ def run_markdown_pipeline( return run_over_spans(input_text, spans, plan, locale_data, ctx) +def run_yaml_pipeline( + input_text: str, + *, + locale: object, + keys: object, + rules: dict[str, bool] | None, + narrow_nbsp: str | None = None, +) -> str: + """`yaml` mode only, and the only mode pipeline with **no parser dependency at all** -- span + selection is the specified scan of modes.md 3.8, not a library. There is likewise no + POLYTYPO_MALFORMED_INPUT counterpart here: with no declared grammar to violate, a file that is + not YAML yields few spans or none and comes back byte for byte (modes.md 3.8.3). The only + throw this mode adds is `keys`, which is about the call and not the input.""" + from polytypo._modes.yaml import yaml_spans + + narrow_target = resolve_narrow_target(narrow_nbsp) + resolved_locale, locale_data, plan = prepare(locale, rules) + resolved_keys = resolve_yaml_keys(keys) + ctx: RuleContext = { + "mode": "yaml", + "dialect": None, + "locale": resolved_locale, + "narrow_target": narrow_target, + } + spans = normalize_spans(yaml_spans(input_text, resolved_keys)) + return run_over_spans(input_text, spans, plan, locale_data, ctx) + + def analyze_text_pipeline( input_text: str, *, @@ -150,3 +179,28 @@ def analyze_markdown_pipeline( } spans = normalize_spans(markdown_spans(input_text, dialect)) return analyze_over_spans(input_text, spans, plan, locale_data, ctx) + + +def analyze_yaml_pipeline( + input_text: str, + *, + locale: object, + keys: object, + rules: dict[str, bool] | None, + narrow_nbsp: str | None = None, +) -> list[Change]: + """analyze.md section 1, `yaml` mode: offsets are into the document, not into a span + (analyze.md section 6).""" + from polytypo._modes.yaml import yaml_spans + + narrow_target = resolve_narrow_target(narrow_nbsp) + resolved_locale, locale_data, plan = prepare(locale, rules) + resolved_keys = resolve_yaml_keys(keys) + ctx: RuleContext = { + "mode": "yaml", + "dialect": None, + "locale": resolved_locale, + "narrow_target": narrow_target, + } + spans = normalize_spans(yaml_spans(input_text, resolved_keys)) + return analyze_over_spans(input_text, spans, plan, locale_data, ctx) diff --git a/src/polytypo/_engine/yaml_keys.py b/src/polytypo/_engine/yaml_keys.py new file mode 100644 index 0000000..06a16b6 --- /dev/null +++ b/src/polytypo/_engine/yaml_keys.py @@ -0,0 +1,32 @@ +"""modes.md 3.8.2: ``yaml`` mode's ``keys`` option, resolved once at the call boundary. + +It has **no default**, for the reason ``dialect`` has none. YAML is a data format with islands of +prose in it, and nothing in its syntax marks them -- ``description`` holds a sentence and ``run`` +holds a shell script, spelled identically -- so a default would be a guess about the schema above +the document. An **empty list is legal**: "process nothing" is a choice a caller may make, not an +error. + +Checked after ``locale``, last of the option checks, alongside ``dialect`` (ARCHITECTURE.md +section 7). The two never both apply, since each belongs to a different mode.""" + +from __future__ import annotations + +from collections.abc import Sequence + +from polytypo.errors import POLYTYPO_INVALID_OPTION, PolytypoError + + +def resolve_yaml_keys(value: object) -> frozenset[str]: + if isinstance(value, str) or not isinstance(value, Sequence): + raise PolytypoError( + POLYTYPO_INVALID_OPTION, + '"keys" is required when mode is "yaml" and must be a sequence of strings ' + f"(modes.md 3.8.2). Received {'nothing' if value is None else repr(value)}.", + ) + for key in value: + if not isinstance(key, str): + raise PolytypoError( + POLYTYPO_INVALID_OPTION, + f'"keys" must contain only strings; received {key!r}.', + ) + return frozenset(value) diff --git a/src/polytypo/_modes/spans.py b/src/polytypo/_modes/spans.py index 6f172bc..9beea8f 100644 --- a/src/polytypo/_modes/spans.py +++ b/src/polytypo/_modes/spans.py @@ -14,6 +14,9 @@ LINE_TERMINATORS = frozenset({0x0A, 0x0D, 0x0B, 0x0C, 0x85, 0x2028, 0x2029}) +#: U+0020, the one emitted code point whose meaning is positional (modes.md 3.4, 5 item 2). +SPACE = 0x20 + @dataclass(frozen=True, slots=True) class Span: @@ -99,8 +102,12 @@ def filter_boundary_edits(cp: list[int], edits: list[Edit], ranges: list[SpanRan 1. No edit may contain a marker -- one that does is a bug, discarded rather than redistributed. 2. The edge-growth rule: an edit is discarded if it would place code points at an extremity - of its span that were not there before (p = s0 and r > d, or q = s1 and r > d, with - d = q - p + 1 the replaced length and r the replacement length). + of its span that were not there before. That sentence is the rule; "r > d" alone is an + incorrect formalisation of it and misses r == d. dashes P3 admits a run of THREE dashes, + so "---" -> U+0020 en-dash U+0020 is 3 -> 3: the length test sees nothing while U+0020 + lands on both extremities anyway. The second clause tests the CHARACTER, and only U+0020 + needs testing -- it is the one code point any rule emits whose meaning comes from its + position rather than from itself (modes.md 5 item 2). Deletion at an edge is NOT restricted here -- r > d is always false for a deletion, so this filter never sees one; that case is spaces.md 3.2 step 4's own edge-as-NONE clause instead. @@ -115,8 +122,13 @@ def filter_boundary_edits(cp: list[int], edits: list[Edit], ranges: list[SpanRan d = edit.end - edit.start r = len(edit.replacement) span = _span_containing(ranges, p) - if span is not None and r > d and (p == span.first or q == span.last): - continue + if span is not None and (p == span.first or q == span.last): + if r > d: + continue + if r > 0 and p == span.first and edit.replacement[0] == SPACE and cp[p] != SPACE: + continue + if r > 0 and q == span.last and edit.replacement[r - 1] == SPACE and cp[q] != SPACE: + continue out.append(edit) return out diff --git a/src/polytypo/_modes/yaml.py b/src/polytypo/_modes/yaml.py new file mode 100644 index 0000000..af5d426 --- /dev/null +++ b/src/polytypo/_modes/yaml.py @@ -0,0 +1,326 @@ +"""spec/rules/modes.md 3.8. ``yaml`` differs from the other two document modes twice over. + +It uses **no parser** (3.8.1): two of the five ecosystems' YAML libraries cannot report the source +offsets the round-trip guarantee needs, so the scan below is specified rather than delegated and +is written the same way in every runtime. + +And the caller names the keys (3.8.2). YAML is a data format with islands of prose in it -- the +inverse of HTML and Markdown -- and nothing in its syntax separates ``description:`` from +``run:``. A keyless draft of this file rewrote ``if !`` as ``if!`` inside a workflow's shell +script; there is no content test that would not, because shell and template expressions are +written in words. + +It also **skips by default** -- the inverse of 3.6's closed skip list. A construct this scan does +not recognise with certainty yields no spans, so the worst outcome of a gap in it is prose left +untypeset, never a changed byte.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from polytypo._modes.spans import Span + +TAB = "\t" +LF = "\n" +CR = "\r" +SPACE = " " + + +@dataclass(frozen=True, slots=True) +class _Line: + start: int + #: Index of the line terminator, or of the end of the source -- never inside a span. + end: int + + +def _split_lines(source: str) -> list[_Line]: + """3.8.4: a line ends at U+000A, and **a U+000D immediately before it is not part of the + line** -- it is a terminator like the U+000A itself, so it lies outside every span and comes + back untouched. Without that clause a CRLF file behaves differently from the same bytes with + LF: the block header reads as ``|\\r`` and is unrecognised, and a plain scalar carries the + carriage return inside its span. Five runtimes split lines with five different standard-library + calls, so the treatment has to be stated rather than inherited.""" + lines: list[_Line] = [] + start = 0 + + def end_of(i: int) -> int: + return i - 1 if i > start and source[i - 1] == CR else i + + for i, ch in enumerate(source): + if ch == LF: + lines.append(_Line(start, end_of(i))) + start = i + 1 + if start < len(source): + lines.append(_Line(start, end_of(len(source)))) + return lines + + +def _first_non_space(source: str, line: _Line) -> int: + i = line.start + while i < line.end and source[i] == SPACE: + i += 1 + return i + + +def _is_blank(source: str, line: _Line) -> bool: + return _first_non_space(source, line) == line.end + + +def _has_tab(source: str, line: _Line) -> bool: + return TAB in source[line.start : line.end] + + +def _is_document_marker(source: str, from_: int, end: int) -> bool: + """3.8.4 step 3. ``---`` and ``...`` at the head of a line, bare or introducing a node: the + trailing-content form is declined too, so ``--- key: value`` never yields a key of + ``--- key``.""" + if end - from_ < 3: + return False + c = source[from_] + if c not in ("-", "."): + return False + if source[from_ + 1] != c or source[from_ + 2] != c: + return False + return from_ + 3 == end or source[from_ + 3] == SPACE + + +def _is_indicator_colon(source: str, j: int, end: int) -> bool: + """A colon that ends the line or is followed by U+0020 -- the only colon YAML reads as an + indicator.""" + if source[j] != ":": + return False + return j + 1 == end or source[j + 1] == SPACE + + +def _is_sequence_dash(source: str, j: int, end: int) -> bool: + if source[j] != "-": + return False + return j + 1 == end or source[j + 1] == SPACE + + +def _value_run_end(source: str, lines: list[_Line], li: int, indent: int) -> int: + """The value run of 3.8.4 step 7: every following line that is blank or indented more than + the key line. **Those lines are never scanned again** -- without that, a multi-line quoted + scalar, a multi-line flow collection and a folded plain scalar all leak their continuation + lines back into the scan as if they were mappings, and a span can end up holding a scalar's + own closing delimiter.""" + k = li + 1 + while k < len(lines): + nxt = lines[k] + if not _is_blank(source, nxt) and _first_non_space(source, nxt) - nxt.start <= indent: + break + k += 1 + return k + + +def yaml_spans(source: str, keys: frozenset[str]) -> list[Span]: + lines = _split_lines(source) + spans: list[Span] = [] + li = 0 + while li < len(lines): + li = _scan_line(source, lines, li, keys, spans) + return spans + + +def _scan_line( + source: str, lines: list[_Line], li: int, keys: frozenset[str], spans: list[Span] +) -> int: + """One step of 3.8.4. Returns the index of the next line to scan.""" + line = lines[li] + skip_line = li + 1 + + # step 1 -- blank, or a tab anywhere, which makes indentation undecidable. + start = _first_non_space(source, line) + if start == line.end or _has_tab(source, line): + return skip_line + indent = start - line.start + + # steps 2 and 3 -- comment, directive, document marker. + if source[start] in ("#", "%"): + return skip_line + if _is_document_marker(source, start, line.end): + return skip_line + + # step 4 -- block sequence entries are consumed, not skipped; `- - key: v` nests. + i = start + while i < line.end and _is_sequence_dash(source, i, line.end): + i += 2 + while i < line.end and source[i] == SPACE: + i += 1 + if i >= line.end: + return skip_line + + # step 5 -- find the key. A colon NOT followed by U+0020 or the line end is an ordinary key + # character, so `a:b: v` has the key `a:b`; stating that is what keeps five scanners agreeing. + key_start = i + colon = -1 + for j in range(i, line.end): + if source[j] in ('"', "'", "{", "[", "&", "*", "!", "#"): + return skip_line + if _is_indicator_colon(source, j, line.end): + colon = j + break + if colon < 0: + return skip_line + key_end = colon + while key_end > key_start and source[key_end - 1] == SPACE: + key_end -= 1 + if key_end <= key_start: + return skip_line + + # step 6 -- an empty value means a nested node, whose lines ARE scanned on their own. + v = colon + 1 + while v < line.end and source[v] == SPACE: + v += 1 + if v >= line.end: + return skip_line + + # step 7 -- the line carries an inline value, so its continuation lines belong to that value. + nxt = _value_run_end(source, lines, li, indent) + + # step 8 -- the key must be listed. Checked before the value's form, so an unlisted key costs + # nothing to decline: this is what makes `run:`, `if:` and `image:` unreachable. + if source[key_start:key_end] not in keys: + return nxt + + # step 9 -- the scalar form. + value = source[v] + if value in ("#", "&", "*", "!", "{", "["): + return nxt + if value in ("|", ">"): + _block_scalar(source, lines, li, nxt, indent, v, spans) + return nxt + if value in ('"', "'"): + if nxt == li + 1: + _quoted_scalar(source, line, v, spans) + return nxt + if nxt == li + 1: + _plain_scalar(source, line, v, spans) + return nxt + + +def _block_scalar( + source: str, + lines: list[_Line], + li: int, + run_end: int, + indent: int, + v: int, + spans: list[Span], +) -> None: + """3.8.5. One span per non-blank content line, starting after the block's own indentation. The + header, the indentation and every line terminator lie outside every span -- including the run + of line terminators at the end that the chomping indicator governs, which is why ``|``, ``|-``, + ``|+``, ``>``, ``>-`` and ``>+`` are handled identically here.""" + line = lines[li] + + # The header: at most one chomping indicator and at most one indentation indicator, in either + # order, then optional spaces and an optional comment. Anything else is unrecognised. + h = v + 1 + explicit_indent = 0 + chomping = False + while h < line.end: + c = source[h] + if c in ("-", "+") and not chomping: + chomping = True + h += 1 + continue + if "1" <= c <= "9" and explicit_indent == 0: + explicit_indent = ord(c) - ord("0") + h += 1 + continue + break + while h < line.end and source[h] == SPACE: + h += 1 + if h < line.end and source[h] != "#": + return + + # One definition of the run, and three conditions that make the whole block yield no spans. + content: list[_Line] = [] + content_indent = -1 + for k in range(li + 1, run_end): + nxt = lines[k] + if _is_blank(source, nxt): + continue # blank lines belong to the block and yield no span + if _has_tab(source, nxt): + return + next_indent = _first_non_space(source, nxt) - nxt.start + if content_indent < 0: + content_indent = indent + explicit_indent if explicit_indent > 0 else next_indent + # An explicit indicator that disagrees with the block as written, or a later line dedented + # inside it, is ambiguous rather than guessable -- bail rather than choose. + if next_indent < content_indent: + return + content.append(nxt) + if content_indent <= 0: + return + + for c_line in content: + from_ = c_line.start + content_indent + if c_line.end > from_: + spans.append(Span(from_, c_line.end)) + + +def _quoted_scalar(source: str, line: _Line, v: int, spans: list[Span]) -> None: + """3.8.6. The span is the content between the quotes. Both bails exist so that source + characters and content characters are the same thing, which the offset model of 3.1 requires -- + the same constraint that makes an HTML character reference an opaque unit in 3.6. No colon test + applies here: quoting neutralises the colon, and applying the plain-scalar test would decline + ``title: "Chapter 1: the beginning"``.""" + quote = source[v] + close = -1 + j = v + 1 + while j < line.end: + c = source[j] + if quote == '"' and c == "\\": + return + if quote == "'" and c == "'" and j + 1 < line.end and source[j + 1] == "'": + return + if c == quote: + close = j + break + j += 1 + if close < 0: + return + + after = close + 1 + while after < line.end and source[after] == SPACE: + after += 1 + if after < line.end and source[after] != "#": + return + + if close > v + 1: + spans.append(Span(v + 1, close)) + + +def _plain_scalar(source: str, line: _Line, v: int, spans: list[Span]) -> None: + """3.8.6. In a plain scalar ``:`` and ``#`` are still live: U+0020 beside either of them is + what turns a scalar into a mapping indicator or a comment, and ``dashes`` emits U+0020 in every + ``-spaced`` locale. Lifting both out as opaque units puts the dash token at a span extremity, + where the edge-growth rule of 3.4 discards the replacement that emits one.""" + # The scalar ends before a trailing comment, so a colon inside that comment is not the + # scalar's and must not decline it. + end = line.end + for j in range(v, line.end): + if source[j] == "#" and j > v and source[j - 1] == SPACE: + end = j - 1 + break + while end > v and source[end - 1] == SPACE: + end -= 1 + if end <= v: + return + + # Compact nesting is not a value: `key: - item` opens a sequence, and `key: a .:` is a mapping + # whose key is `a .` -- a plain scalar can never contain a colon in that position. + if _is_sequence_dash(source, v, line.end): + return + for j in range(v, end): + if _is_indicator_colon(source, j, line.end): + return + + segment = v + for j in range(v, end + 1): + if j == end or source[j] in (":", "#"): + if j > segment: + spans.append(Span(segment, j)) + segment = j + 1 diff --git a/src/polytypo/yaml.py b/src/polytypo/yaml.py new file mode 100644 index 0000000..3e80512 --- /dev/null +++ b/src/polytypo/yaml.py @@ -0,0 +1,47 @@ +"""``polytypo.yaml`` -- YAML-only entry point, and the lightest of the four: ``yaml`` mode uses no +parser at all (spec/rules/modes.md 3.8.1), so this module's graph excludes ``html.parser``-based +span extraction and tree-sitter for the same reason ``polytypo.text``'s does -- it has nothing to +import. + +``mode`` and ``dialect`` are absent from this entry's ``transform``; ``keys`` goes the other way. +It is optional on the aggregate entry because the other three modes ignore it, and **required** +here, where the mode is fixed and the option always applies.""" + +from __future__ import annotations + +from collections.abc import Sequence + +from polytypo._engine.mode_pipelines import analyze_yaml_pipeline, run_yaml_pipeline +from polytypo._engine.origin import Change +from polytypo.errors import PolytypoError + +__all__ = ["Change", "PolytypoError", "analyze", "transform"] + + +def transform( + input: str, + *, + locale: str, + keys: Sequence[str], + rules: dict[str, bool] | None = None, + narrow_nbsp: str | None = None, +) -> str: + """`keys` names the mapping keys whose scalar values are processable (modes.md 3.8.2). It has + no default: YAML is a data format with islands of prose in it, and nothing in its syntax + separates `description:` from `run:`. An empty sequence is legal and processes nothing.""" + return run_yaml_pipeline(input, locale=locale, keys=keys, rules=rules, narrow_nbsp=narrow_nbsp) + + +def analyze( + input: str, + *, + locale: str, + keys: Sequence[str], + rules: dict[str, bool] | None = None, + narrow_nbsp: str | None = None, +) -> list[Change]: + """The same pipeline as this entry's `transform`, reporting instead of applying + (spec/rules/analyze.md). Offsets are code-point offsets into `input`, not into a span.""" + return analyze_yaml_pipeline( + input, locale=locale, keys=keys, rules=rules, narrow_nbsp=narrow_nbsp + ) diff --git a/tests/conformance/test_fixtures.py b/tests/conformance/test_fixtures.py index 5c0d41b..2fb3d81 100644 --- a/tests/conformance/test_fixtures.py +++ b/tests/conformance/test_fixtures.py @@ -66,6 +66,8 @@ def test_fixture_case(file_name: str, locale: str, case: dict[str, Any]) -> None kwargs["rules"] = case["rules"] if case.get("narrowNbsp") is not None: kwargs["narrow_nbsp"] = case["narrowNbsp"] + if case.get("keys") is not None: + kwargs["keys"] = case["keys"] if "throws" in case: with pytest.raises(PolytypoError) as excinfo: @@ -78,8 +80,9 @@ def test_fixture_case(file_name: str, locale: str, case: dict[str, Any]) -> None assert _escape_non_ascii(got) == _escape_non_ascii(expected) # Free coverage, and the most common port bug (ARCHITECTURE.md 6.1). The re-run carries the - # case's OWN options: a case with `narrowNbsp` is a fixed point under that option and not - # under the defaults, so passing `**kwargs` here is contract, not convenience. + # case's OWN options: a case with `narrowNbsp` or `keys` is a fixed point under those and not + # under the defaults, so passing `**kwargs` here is contract, not convenience -- and for + # `keys` the re-run would not even run without it, since the option has no default. twice = polytypo.transform(expected, **kwargs) assert _escape_non_ascii(twice) == _escape_non_ascii(expected) diff --git a/tests/engine/test_analyze.py b/tests/engine/test_analyze.py index 554f50d..0aa204f 100644 --- a/tests/engine/test_analyze.py +++ b/tests/engine/test_analyze.py @@ -43,7 +43,7 @@ def test_unknown_rule_wins_over_unknown_locale(self) -> None: def test_unknown_mode(self) -> None: with pytest.raises(PolytypoError) as excinfo: - polytypo.analyze("x", locale="en-US", mode="yaml") + polytypo.analyze("x", locale="en-US", mode="asciidoc") assert excinfo.value.code == "POLYTYPO_INVALID_MODE" def test_markdown_requires_a_dialect(self) -> None: @@ -85,6 +85,8 @@ def test_agrees_with_transform_on_every_canonical_fixture(self) -> None: kwargs: dict[str, Any] = {"locale": data["locale"], "mode": case["mode"]} if case.get("dialect") is not None: kwargs["dialect"] = case["dialect"] + if case.get("keys") is not None: + kwargs["keys"] = case["keys"] if case.get("rules") is not None: kwargs["rules"] = case["rules"] changed = polytypo.transform(case["in"], **kwargs) != case["in"] diff --git a/tests/modes/test_edge_growth.py b/tests/modes/test_edge_growth.py new file mode 100644 index 0000000..88d0558 --- /dev/null +++ b/tests/modes/test_edge_growth.py @@ -0,0 +1,56 @@ +"""spec/rules/modes.md 3.4 -- the edge-growth rule's character clause (spec 1.3.0). + +Its normative sentence has always been "an edit is discarded if it would place code points at an +extremity of its span that were not there before". The formalisation `r > d` is not that rule: it +misses `r == d`. `dashes` P3 admits a run of two OR THREE, so `---` -> U+0020 en-dash U+0020 is +3 -> 3 and lands U+0020 on both extremities while the length test sees nothing. In `html` and +`markdown`, both shipped at v1.0.0, that produced an element beginning and ending with a space it +never held, and a de-flanked emphasis delimiter.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +import polytypo + +_LOCALES_DIR = Path(__file__).resolve().parents[2] / "vendor" / "polytypo-spec" / "locales" + + +def _spaced_locales() -> list[str]: + """Read from the locale data rather than named here: a hardcoded list rots silently as + locales are added, and it would also admit `el`, whose `dash.parenthetical` is "none".""" + out: list[str] = [] + for path in sorted(_LOCALES_DIR.glob("*.json")): + if path.name == "registry.json": + continue + data = json.loads(path.read_text("utf-8")) + if str(data.get("dash", {}).get("parenthetical", "none")).endswith("-spaced"): + out.append(path.stem) + return out + + +@pytest.mark.parametrize("locale", _spaced_locales()) +def test_three_dashes_at_a_span_edge_are_declined(locale: str) -> None: + assert polytypo.transform("a---b", locale=locale, mode="html") == "a---b" + + +def test_the_same_edit_interior_to_a_span_still_applies() -> None: + assert polytypo.transform("

a---b

", locale="de-DE", mode="html") == "

a – b

" + + +def test_an_em_tight_locale_still_converts_at_the_edge() -> None: + # It emits no U+0020 at all, so the character clause does not fire. + assert polytypo.transform("a---b", locale="en-US", mode="html") == "a—b" + + +def test_a_spaced_edit_that_replaces_a_space_with_a_space_still_applies() -> None: + assert ( + polytypo.transform("ax --- yb", locale="de-DE", mode="html") == "ax – yb" + ) + + +def test_two_dashes_at_an_edge_are_still_declined_by_the_length_clause() -> None: + assert polytypo.transform("a--b", locale="de-DE", mode="html") == "a--b" diff --git a/tests/modes/test_yaml.py b/tests/modes/test_yaml.py new file mode 100644 index 0000000..68b8f2b --- /dev/null +++ b/tests/modes/test_yaml.py @@ -0,0 +1,246 @@ +"""spec/rules/modes.md 3.8 -- the `yaml` mode's span selection, its required `keys` option, and +the accepted misses of section 7.11. Mirrors polytypo-js's tests/modes/yaml.test.ts: the scan is +specified rather than delegated (3.8.1), so a test here is one of the few things standing between +five hand-written scanners and five different answers.""" + +from __future__ import annotations + +import pytest + +import polytypo +from polytypo._modes.yaml import yaml_spans +from polytypo.errors import PolytypoError + +PROSE_KEYS = ["description", "summary", "title", "a", "b", "c", "k", "n", "inner", "use"] + + +def yaml(source: str, locale: str = "en-US", keys: list[str] | None = None) -> str: + return polytypo.transform( + source, locale=locale, mode="yaml", keys=PROSE_KEYS if keys is None else keys + ) + + +def span_text(source: str, keys: list[str] | None = None) -> list[str]: + chosen = frozenset(PROSE_KEYS if keys is None else keys) + return [source[s.start : s.end] for s in yaml_spans(source, chosen)] + + +class TestKeysOption: + """modes.md 3.8.2.""" + + def test_is_required_with_no_default(self) -> None: + def code_of(**kwargs: object) -> str: + try: + polytypo.transform("a: one two\n", **kwargs) # type: ignore[arg-type] + except PolytypoError as error: + return error.code + return "NO THROW" + + assert code_of(locale="en-US", mode="yaml") == "POLYTYPO_INVALID_OPTION" + assert code_of(locale="en-US", mode="yaml", keys="description") == "POLYTYPO_INVALID_OPTION" + assert code_of(locale="en-US", mode="yaml", keys=["ok", 7]) == "POLYTYPO_INVALID_OPTION" + + def test_empty_list_is_legal_and_processes_nothing(self) -> None: + assert yaml("description: one...two\n", keys=[]) == "description: one...two\n" + + def test_processes_a_listed_key_and_leaves_an_unlisted_one(self) -> None: + source = "description: one...two\nrun: three...four\n" + assert yaml(source, keys=["description"]) == "description: one…two\nrun: three...four\n" + + def test_matches_at_any_depth(self) -> None: + source = "description: one...\nnested:\n description: two...\n" + assert ( + yaml(source, keys=["description"]) + == "description: one…\nnested:\n description: two…\n" + ) + + def test_matches_code_point_for_code_point_with_no_case_folding(self) -> None: + assert span_text("Description: one two\n", keys=["description"]) == [] + assert span_text("Description: one two\n", keys=["Description"]) == ["one two"] + + def test_ignores_trailing_spaces_before_the_colon(self) -> None: + assert span_text("description : one two\n", keys=["description"]) == ["one two"] + + def test_never_matches_a_key_carrying_a_declining_character(self) -> None: + assert span_text('"description": one two\n', keys=["description"]) == [] + assert span_text("a!b: one two\n", keys=["a!b"]) == [] + + def test_a_colon_not_followed_by_a_space_is_an_ordinary_key_character(self) -> None: + assert span_text("a:b: one two\n", keys=["a:b"]) == ["one two"] + assert span_text("a:b: one two\n", keys=["a"]) == [] + + def test_is_ignored_in_the_other_three_modes(self) -> None: + assert polytypo.transform("a...b", locale="en-US", keys=["a"]) == "a…b" + + +class TestWhatIsProcessable: + """modes.md 3.8.4.""" + + def test_the_three_scalar_forms(self) -> None: + source = 'a: one two\nb: "three four"\nc: |\n five six\n' + assert span_text(source) == ["one two", "three four", "five six"] + + def test_a_key_is_never_processed(self) -> None: + assert yaml("a...b: one...two\n", keys=["a...b"]) == "a...b: one…two\n" + + def test_block_sequence_entries_are_consumed_and_nest(self) -> None: + assert span_text("- a: one two\n- - b: three four\n") == ["one two", "three four"] + + def test_comments_directives_and_both_document_marker_forms(self) -> None: + assert span_text("%YAML 1.2\n---\n# a comment\na: one two\n...\n") == ["one two"] + assert span_text("--- a: one two\n") == [] + + def test_a_nested_node_is_scanned_but_a_continuation_is_not(self) -> None: + assert span_text("a:\n b: one two\n") == ["one two"] + assert span_text("a: inline value\n b: one two\n") == [] + + +@pytest.mark.parametrize( + "name,source", + [ + ("a multi-line quoted scalar", 'a: "hello\n b: some prose "word" here"\n'), + ("a multi-line flow mapping", "a: {\n b: hello world,\n c: x\n}\n"), + ("a multi-line flow sequence", "a: [\n one two...,\n three\n]\n"), + ("a multi-line plain scalar", "a: one two...\n b: three four...\n"), + ], +) +def test_continuation_lines_are_consumed_never_rescanned(name: str, source: str) -> None: + """modes.md 3.8.4 step 7. Without it a span can hold a quoted scalar's own closing delimiter, + and `quotes` can then leave the scalar unterminated.""" + assert span_text(source) == [], name + assert yaml(source) == source, name + + +@pytest.mark.parametrize( + "name,source", + [ + ("a bare sequence item", "- Some prose here...\n"), + ("a flow sequence", "a: [one two..., three]\n"), + ("a flow mapping", "a: {b: one two...}\n"), + ("an anchor", "a: &anchor one two...\n"), + ("an alias", "a: *anchor\n"), + ("a tag", "a: !!str one two...\n"), + ("a double-quoted scalar with an escape", 'a: "one \\"two\\"... three"\n'), + ("a single-quoted scalar with an escaped quote", "a: 'it''s one two...'\n"), + ("a tab anywhere on the line", "a:\tone two...\n"), + ("a compact nested sequence", "a: - one two...\n"), + ("a compact nested mapping", "a: one two .:\n"), + ("an unterminated quoted scalar", 'a: "one two...\n'), + ("a value that is only a comment", "a: # one two...\n"), + ], +) +def test_skip_by_default(name: str, source: str) -> None: + """modes.md 3.8.3: a construct the scan does not recognise yields no spans, byte for byte.""" + assert span_text(source) == [], name + assert yaml(source) == source, name + + +def test_a_file_that_is_not_yaml_comes_back_unchanged_and_never_throws() -> None: + source = "{{ not yaml at all ... }}\n\t\tmixed\tindentation\n" + assert yaml(source) == source + + +class TestBlockScalars: + """modes.md 3.8.5.""" + + @pytest.mark.parametrize("header", ["|", "|-", "|+", ">", ">-", ">+"]) + def test_every_chomping_indicator_gives_identical_spans_and_trailing_bytes( + self, header: str + ) -> None: + source = f"a: {header}\n one two...\n\n\nz: 1\n" + assert span_text(source) == ["one two..."], header + assert yaml(source) == f"a: {header}\n one two…\n\n\nz: 1\n", header + + def test_a_trailing_comment_on_the_header(self) -> None: + assert span_text("a: | # note\n one two\n") == ["one two"] + + def test_indentation_is_outside_the_span_and_extra_indentation_inside_it(self) -> None: + assert span_text("a: |\n one two\n three four\n") == ["one two", " three four"] + + def test_leading_spaces_of_a_content_line_are_never_collapsed(self) -> None: + assert yaml("a: |\n one two\n three four\n") == "a: |\n one two\n three four\n" + + def test_an_explicit_indentation_indicator(self) -> None: + assert span_text("a: |2\n one two\n") == [" one two"] + + @pytest.mark.parametrize( + "name,source", + [ + ("an explicit indicator disagreeing with the block", "a: |4\n one two\n"), + ("a tab on a content line", "a: |\n one two\n three\tfour\n"), + ("a later line dedented inside the block", "a: |\n deep one two\n shallow three\n"), + ("an unrecognised header", "a: |x\n one two\n"), + ], + ) + def test_the_whole_block_bails(self, name: str, source: str) -> None: + assert span_text(source) == [], name + assert yaml(source) == source, name + + def test_the_block_ends_at_the_first_line_indented_no_more_than_the_key(self) -> None: + assert span_text("a: |\n one two\nb: three four\n") == ["one two", "three four"] + + def test_quotes_pair_across_block_scalar_lines(self) -> None: + assert yaml('a: |\n He said "hi"\n and left\n') == "a: |\n He said “hi”\n and left\n" + + def test_crlf_yields_the_same_spans_as_lf_and_keeps_its_carriage_returns(self) -> None: + assert span_text("a: |\r\n one two...\r\n") == ["one two..."] + assert yaml("a: |\r\n one two...\r\n") == "a: |\r\n one two…\r\n" + + +class TestQuotedAndPlainScalars: + """modes.md 3.8.6.""" + + def test_no_colon_test_applies_to_a_quoted_scalar(self) -> None: + assert span_text('a: "Chapter 1: the beginning"\n') == ["Chapter 1: the beginning"] + + def test_a_trailing_comment_is_stripped_before_the_colon_test(self) -> None: + assert span_text("a: some prose # note: here\n") == ["some prose"] + + def test_a_plain_scalar_splits_at_a_colon_and_at_a_hash(self) -> None: + assert span_text("a: one:two three\n") == ["one", "two three"] + assert span_text("a: one#two three\n") == ["one", "two three"] + + def test_the_split_declines_a_growing_replacement_against_a_colon_or_hash(self) -> None: + # Without the split a -spaced locale emits `a: – b`, which reparses as a nested mapping, + # and `a – #b`, where everything from the hash becomes a comment. + assert yaml("k: a:--b\n", "de-DE") == "k: a:--b\n" + assert yaml("k: a--#b\n", "de-DE") == "k: a--#b\n" + + def test_a_contraction_at_the_same_position_still_applies(self) -> None: + # 2 -> 1 cannot emit U+0020, and U+0020 is the whole of what the split protects. + assert yaml("k: a--#b\n", "en-US") == "k: a—#b\n" + assert yaml("k: a:--b\n", "en-US") == "k: a:—b\n" + + def test_three_dashes_are_declined_by_the_character_clause(self) -> None: + # modes.md 3.4: `---` -> ` – ` is 3 -> 3, so the length clause misses it entirely. + assert yaml("k: a:---b\n", "de-DE") == "k: a:---b\n" + assert yaml("k: a---#b\n", "de-DE") == "k: a---#b\n" + + +class TestSpanPartitionStability: + """modes.md 5 item 2.""" + + def test_a_span_is_not_lost_because_a_rule_changed_what_is_inside_it(self) -> None: + source = "a: ${{ steps.pin.outputs.sha }}\n" + once = yaml(source) + assert len(yaml_spans(once, frozenset(PROSE_KEYS))) == len( + yaml_spans(source, frozenset(PROSE_KEYS)) + ) + assert yaml(once) == once + + +class TestRoundTrip: + """modes.md 4.""" + + def test_a_document_needing_no_changes_comes_back_byte_for_byte(self) -> None: + source = "a: one two\nb: 'it''s'\nc: [x, y]\n#comment\n" + assert yaml(source) == source + + def test_quoting_indentation_and_non_ascii_survive_an_edit(self) -> None: + assert yaml('a: "Une note... précise"\n', "fr") == 'a: "Une note… précise"\n' + + def test_it_is_idempotent_on_a_document_it_does_change(self) -> None: + source = 'a: The "book"... and more\nb: |\n He said -- loudly\n' + once = yaml(source) + assert once != source + assert yaml(once) == once diff --git a/tests/test_rules/test_narrow_nbsp.py b/tests/test_rules/test_narrow_nbsp.py index 23d7278..c13028c 100644 --- a/tests/test_rules/test_narrow_nbsp.py +++ b/tests/test_rules/test_narrow_nbsp.py @@ -77,7 +77,7 @@ def code_of(**kwargs: object) -> str: return error.code return "NO THROW" - assert code_of(locale="fr", mode="yaml", narrow_nbsp="wide") == "POLYTYPO_INVALID_MODE" + assert code_of(locale="fr", mode="asciidoc", narrow_nbsp="wide") == "POLYTYPO_INVALID_MODE" assert ( code_of(locale="fr", narrow_nbsp="wide", rules={"nope": True}) == "POLYTYPO_INVALID_OPTION" diff --git a/vendor/polytypo-spec/VERSION b/vendor/polytypo-spec/VERSION index 867e524..f0bb29e 100644 --- a/vendor/polytypo-spec/VERSION +++ b/vendor/polytypo-spec/VERSION @@ -1 +1 @@ -1.2.0 \ No newline at end of file +1.3.0 diff --git a/vendor/polytypo-spec/fixtures/cs.json b/vendor/polytypo-spec/fixtures/cs.json new file mode 100644 index 0000000..652720c --- /dev/null +++ b/vendor/polytypo-spec/fixtures/cs.json @@ -0,0 +1,161 @@ +{ + "spec": "1.3.0", + "locale": "cs", + "cases": [ + { + "id": "cs-quotes-primary", + "rule": "quotes", + "mode": "text", + "in": "Řekl \"ahoj\".", + "out": "Řekl „ahoj“.", + "note": "quotes.primary = U+201E/U+201C, tedy «uvozovky typu 99 66» podle IJP." + }, + { + "id": "cs-quotes-not-polish", + "rule": "quotes", + "mode": "text", + "in": "„ahoj”", + "out": "„ahoj“", + "note": "ROZLIŠUJÍCÍ PŘÍPAD: zavírací znaménko je U+201C, ne polské U+201D. Vstup je polský pár; výstup ukazuje, že se přesází na českou podobu. V sazbě je ten rozdíl skoro neviditelný, proto má vlastní fixture." + }, + { + "id": "cs-quotes-nested", + "rule": "quotes", + "mode": "text", + "in": "\"Toto je 'citát' v citátu\"", + "out": "„Toto je ‚citát‘ v citátu“", + "note": "Druhý stupeň jsou jednoduché uvozovky, protože IJP je řadí «v první řadě» pro uvozovky v uvozovkách. Kódy U+201A/U+2018 jsou rozhodnutí operátora (18. 9. 2026) — označení «99 66» zdroj uvádí jen pro dvojité, a tabulka H.1 normy ČSN je placená. V témže případě je vidět N3: jednopísmenné «v» se váže k následujícímu slovu." + }, + { + "id": "cs-ellipsis-three-dots", + "rule": "ellipsis", + "mode": "text", + "in": "Počkej... co?", + "out": "Počkej… co?", + "note": "IJP «Tři tečky»: výpustka je jeden znak U+2026, nikoli tři samostatné tečky." + }, + { + "id": "cs-ellipsis-not-abbreviated", + "rule": "ellipsis", + "mode": "text", + "in": "Opravdu?.. ano", + "out": "Opravdu?… ano", + "note": "ZRCADLOVÝ PŘÍPAD k ukrajinskému uk-ellipsis-abbreviated-after-question, zařazený proto, že analogie mezi slovanskými jazyky je tu svůdná a mylná: čeština má abbreviatedAfterTerminal = false, takže dvě tečky po «?» se doplní na plnou výpustku, zatímco ukrajinština je zkracuje." + }, + { + "id": "cs-dashes-parenthetical", + "rule": "dashes", + "mode": "text", + "in": "Tato kniha - vydaná ještě před válkou - je opravdu úžasná.", + "out": "Tato kniha – vydaná ještě před válkou – je opravdu úžasná.", + "note": "Vlastní příklad IJP. dash.parenthetical = en-spaced: krátká pomlčka U+2013 s mezerami. Délku tu rozhoduje sám zdroj (definiční glyf stránky), na rozdíl od polštiny, kde ji musel rozhodnout operátor." + }, + { + "id": "cs-ranges-en-tight", + "rule": "ranges", + "mode": "text", + "rules": { + "ranges": true + }, + "in": "strana 23-26", + "out": "strana 23⁠–⁠26", + "note": "ranges.md §3: dash.range = en-tight, příklad z IJP «strana 23–26». Potvrzeno i dokumentem ÚJČ k ČSN 01 6910, který mezery v rozsahu popisuje jako výjimku pro víceslovné výrazy." + }, + { + "id": "cs-hyphen-noop", + "rule": "hyphen", + "mode": "text", + "in": "česko-slovenský", + "out": "česko-slovenský", + "note": "hyphen.md §2: tři prázdné seznamy, tedy dokazatelný no-op. Uzavřený výčet IJP o zalomení řádků spojovník neuvádí — doložená nepřítomnost, ne nenalezená citace. Rozdíl proti ukrajinštině, kde § 64 п. 4 takový seznam má." + }, + { + "id": "cs-nbsp-short-words", + "rule": "nbsp", + "mode": "text", + "in": "v Plzni a u babičky", + "out": "v Plzni a u babičky", + "note": "N3 afterShortWords: neslabičné předložky k, s, v, z a slabičné o, u se spojkami a, i. Příklady jsou z IJP. Na rozdíl od polštiny je zákaz v prameni bezpodmínečný." + }, + { + "id": "cs-nbsp-units", + "rule": "nbsp", + "mode": "text", + "in": "10 ha, 14 % a 19 °C", + "out": "10 ha, 14 % a 19 °C", + "note": "N5 na třech značkách z vlastních příkladů IJP. Zároveň je vidět N3 na spojce «a»." + }, + { + "id": "cs-nbsp-percent-adjective-inert", + "rule": "nbsp", + "mode": "text", + "in": "20% roztok", + "out": "20% roztok", + "note": "Povolená varianta IJP: «20% = 20procentní» se píše bez mezery. N5 existující mezeru pouze nahrazuje a nikdy ji nevkládá, takže jeden seznam obslouží obě doložené podoby." + }, + { + "id": "cs-nbsp-paragraph-sign", + "rule": "nbsp", + "mode": "text", + "in": "§ 23", + "out": "§ 23", + "note": "N6 afterSymbols. Ze stejného citovaného bodu byly vynechány «*», «†» a «#»: «* 1921» je bajt po bajtu odrážka seznamu následovaná číslicí, což by v režimu markdown byl falešný zásah." + }, + { + "id": "cs-nbsp-abbreviations", + "rule": "nbsp", + "mode": "text", + "in": "a. s. a s. r. o.", + "out": "a. s. a s. r. o.", + "note": "N4 na obou zkratkách. Zároveň fixuje interakci s N3, která je opačná než u polského «i in.»: po jednopísmenném «a» následuje tečka, ne mezera, takže N3 index nenárokuje a obě mezery dostane N4 — kdežto samostatné «a» uprostřed věty N3 váže." + }, + { + "id": "cs-nbsp-before-word", + "rule": "nbsp", + "mode": "text", + "in": "tzv. odborník", + "out": "tzv. odborník", + "note": "N10 beforeWord: tj., tzv., tzn. jsou uzavřený a doslovně citovaný seznam." + }, + { + "id": "cs-nbsp-initial-single", + "rule": "nbsp", + "mode": "text", + "in": "M. Těšitelová", + "out": "M. Těšitelová", + "note": "initialBinding = single. Vlastní příklady zdroje (Fr. Daneš, M. Těšitelová) mají JEDNO zkrácené křestní jméno, takže «chain» by citované pravidlo nechal nenaplněné." + }, + { + "id": "cs-nbsp-no-space-before-question", + "rule": "nbsp", + "mode": "text", + "in": "Opravdu?", + "out": "Opravdu?", + "note": "Čeština není francouzština: beforePunctuation i narrowBeforePunctuation jsou prázdné a zdroj odstup před «?» výslovně upírá." + }, + { + "id": "cs-spaces-brackets-and-final-stop", + "rule": "spaces", + "mode": "text", + "in": "Text ( běžný ) se nemění .", + "out": "Text (běžný) se nemění.", + "note": "spaces.md §3: pravidlo nezávislé na locale, případ je tu proto, aby cs mělo po jednom pro každé kanonické pravidlo." + }, + { + "id": "cs-symbols-copyright-and-dimensions", + "rule": "symbols", + "mode": "text", + "in": "Copyright (c) 2026, formát 40x60 cm", + "out": "Copyright © 2026, formát 40×60 cm", + "note": "symbols.md: «(c)» se stane U+00A9 a «x» mezi číslicemi U+00D7. U+00A0 před «cm» vkládá nbsp N5." + }, + { + "id": "cs-apostrophe-elision", + "rule": "apostrophe", + "mode": "text", + "in": "Šel do McDonald's a zpět", + "out": "Šel do McDonald’s a zpět", + "note": "Pravidlo apostrophe nečte data locale: U+0027 mezi písmeny se stane U+2019. V téže větě je vidět N3, které váže spojku «a» k následujícímu slovu — dvě nezávislá pravidla na jednom řádku." + } + ] +} diff --git a/vendor/polytypo-spec/fixtures/de-CH.json b/vendor/polytypo-spec/fixtures/de-CH.json index 9b35c23..49a5d96 100644 --- a/vendor/polytypo-spec/fixtures/de-CH.json +++ b/vendor/polytypo-spec/fixtures/de-CH.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "de-CH", "cases": [ { diff --git a/vendor/polytypo-spec/fixtures/de-DE.json b/vendor/polytypo-spec/fixtures/de-DE.json index 9797bae..ac4d1bc 100644 --- a/vendor/polytypo-spec/fixtures/de-DE.json +++ b/vendor/polytypo-spec/fixtures/de-DE.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "de-DE", "cases": [ { @@ -452,16 +452,32 @@ "rule": "nbsp", "mode": "text", "in": "siehe § 12 und Nr. 5", - "out": "siehe § 12 und Nr. 5", - "note": "Two halves with different evidence. `§` is in afterSymbols and binds through N6. `Nr.` binds through nothing: it was removed from the de-DE locale file entirely, because no consulted source states a spacing rule for it — the Schreibweisungen never mention it (it is absent from Rz. 439's closed list of Begriffszeichen and from the Sachregister), Duden classifies it as an abbreviation, which refutes afterSymbols but prescribes no spacing, and DIN 5008 is paywalled and unread. Under PLAN.md §6.1 an entry whose citation does not cover it does not ship. The gap is evidentiary, not typographic." + "out": "siehe § 12 und Nr. 5", + "note": "Two halves with different evidence. `§` is in afterSymbols and binds through N6. `Nr.` binds through nothing: it was removed from the de-DE locale file entirely, because no consulted source states a spacing rule for it — the Schreibweisungen never mention it (it is absent from Rz. 439's closed list of Begriffszeichen and from the Sachregister), Duden classifies it as an abbreviation, which refutes afterSymbols but prescribes no spacing, and DIN 5008 is paywalled and unread. Under PLAN.md §6.1 an entry whose citation does not cover it does not ship. The gap is evidentiary, not typographic. Seit Spec 1.3.0 bindet auch `Nr.` (nbsp.md §3.11 N9, nbsp.beforeNumber), sodass beide Bindungen in einem Satz sichtbar sind." }, { - "id": "de-de-nbsp-nr-unbound-pending-citation", + "id": "de-de-nbsp-nr-binds-number", "rule": "nbsp", "mode": "text", "in": "siehe Nr. 5", - "out": "siehe Nr. 5", - "note": "Pinned on its own so it is easy to find and easy to flip: if a contributor obtains DIN 5008 and it states the binding, `Nr.` goes into de-DE's nbsp.beforeNumber (NOT afterSymbols — Duden calls it an abbreviation, and Rz. 439's Begriffszeichen list excludes it) and this case's `out` becomes `siehe Nr.` + U+00A0 + `5`. Until then the space stays breakable, because moving it on class membership alone would be inference dressed as citation." + "out": "siehe Nr. 5", + "note": "nbsp.md §3.11 N9: `Nr.` steht seit Spec 1.3.0 in de-DEs nbsp.beforeNumber und bindet an die folgende Zahl. Die Zeile ist eine vereinheitlichte Schreibung, kein Zitat — DIN 5008 ist kostenpflichtig und ungelesen, Duden und Amtliches Regelwerk sprechen keine Abstandsregel aus; die Begründung steht im sources-Eintrag von spec/locales/de-DE.json." + }, + { + "id": "de-de-nbsp-nr-needs-a-digit", + "rule": "nbsp", + "mode": "text", + "in": "siehe Nr. fünf", + "out": "siehe Nr. fünf", + "note": "nbsp.md §3.11 N9 Schritt 4: „eine folgende Zahl“ heißt, dass cp[a+k+1] in DIGIT liegt. Ein ausgeschriebenes Zahlwort ist keine Ziffer, also bleibt der Abstand trennbar." + }, + { + "id": "de-de-nbsp-nr-after-hyphen-unbound", + "rule": "nbsp", + "mode": "text", + "in": "Tarif-Nr. 7", + "out": "Tarif-Nr. 7", + "note": "nbsp.md §3.11 N9 Schritt 2: die linke Grenze muss NONE, SPACELIKE, OPENISH oder SENTENCE-DASH sein; ein Bindestrich fällt durch, eine Abkürzung kann nicht unmittelbar nach einem wortinternen Bindestrich beginnen." }, { "id": "de-de-nbsp-before-word-sankt", @@ -574,6 +590,179 @@ "in": "„Er sagte ‚Hans'“ und ging.", "out": "„Er sagte ‚Hans‘“ und ging.", "note": "apostrophe.md §3.3 case 3a (spec 1.2.0): the same shape with the outer pair and the opening single quote already curly. `quotes` still pairs the straight closing single quote with ‚, so case 3a never sees it." + }, + { + "id": "de-de-ranges-closed-up-currency", + "rule": "ranges", + "mode": "text", + "in": "€15-€20", + "out": "€15⁠–⁠€20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): the closed-up walk is locale-independent shape logic — it reads code points, not a currency list, so `de-DE` gets it on the same terms as `en-US`. Note that German normally sets the sign AFTER the amount (`30 EUR`), which is a spaced symbol and therefore out of scope by §7.8; this row asserts the mechanism, not that the shape is idiomatic German." + }, + { + "id": "de-de-dashes-closed-up-range-declined", + "rule": "dashes", + "mode": "text", + "in": "$15 - $20", + "out": "$15 - $20", + "note": "ranges.md §3.2a and dashes.md §1 (spec 1.3.0): the accepted cost, pinned in a locale whose `dash.parenthetical` is SPACED rather than tight — through spec 1.2.0 this input gave `$15 – $20` with default options, and the loss is the same shape in both kinds of locale." + }, + { + "id": "de-de-dashes-t1-closed-up-symbol-adjacent", + "rule": "dashes", + "mode": "text", + "in": "a—$15-$20", + "out": "a—$15-$20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a, via dashes.md §3.2 step 8 (spec 1.3.0): T1's reach is transparent to one CLOSED-SYMBOL between the token and the digit run. THE IDEMPOTENCY WITNESS — before the amendment T1 read the U+0024 as the neighbour, did not fire, and `dashes` converted the em dash to a spaced en dash; that U+0020 replaced the range's `before`, and the range converted on the SECOND pass. `a—15-20` was inert all along and this input now matches it. de-DE because T1 only applies where `dash.parenthetical` is spaced, which is exactly why the cluster guard's alphabet was NOT widened instead — that guard is unconditional and would have taken em-tight locales with it. To be precise about \"before the amendment\": the drift is a property of the INTERMEDIATE state — ranges.md §3.2a's widened candidacy without T1's transparency — which never shipped. Under spec 1.2.0 this input was stable, because the token was not a range candidate at all." + }, + { + "id": "de-de-dashes-t1-closed-up-symbol-right", + "rule": "dashes", + "mode": "text", + "in": "a--15% - 20%", + "out": "a--15% - 20%", + "rules": { + "ranges": true + }, + "note": "dashes.md §3.2 step 8 (spec 1.3.0): T1's outward walk from the digit run steps over one CLOSED-SYMBOL. The cluster guard cannot catch this one — a cluster ends at the U+0020 — so before the amendment the `--` became a spaced en dash and the range converted on the next pass. To be precise about \"before the amendment\": the drift is a property of the INTERMEDIATE state — ranges.md §3.2a's widened candidacy without T1's transparency — which never shipped. Under spec 1.2.0 this input was stable, because the token was not a range candidate at all." + }, + { + "id": "de-de-dashes-t1-closed-up-symbol-left", + "rule": "dashes", + "mode": "text", + "in": "$1 - $1--a", + "out": "$1 - $1--a", + "rules": { + "ranges": true + }, + "note": "dashes.md §3.2 step 8 (spec 1.3.0): the mirror of the T1 case, with the symbol between the token and the digit run rather than beyond it — `cp[L]` is `1` here but the walk outward from the run meets `$` before the space and the dash. Both steps of the transparency are needed; each of these two cases fails without its own. To be precise about \"before the amendment\": the drift is a property of the INTERMEDIATE state — ranges.md §3.2a's widened candidacy without T1's transparency — which never shipped. Under spec 1.2.0 this input was stable, because the token was not a range candidate at all." + }, + { + "id": "de-de-dashes-t1-closed-up-symbol-cost", + "rule": "dashes", + "mode": "text", + "in": "Anstieg--50%--war", + "out": "Anstieg--50%--war", + "note": "dashes.md §3.2 step 8 (spec 1.3.0): THE ACCEPTED COST of T1's CLOSED-SYMBOL transparency, with DEFAULT options — no `rules` key here, because the cost lands on `dashes`, which is on by default. Through spec 1.2.0 this gave `Anstieg – 50% – war`; T1 now fires, because the U+0025 no longer hides the far dash from its outward walk. `Anstieg--50--war` has always been left alone, so the two shapes agree. The cost is confined to locales whose `dash.parenthetical` is spaced — see en-us-dashes-t1-closed-up-symbol-unaffected for the other side of that line." + }, + { + "id": "de-de-dashes-t1-joiner-and-closed-up-symbol", + "rule": "dashes", + "mode": "text", + "in": "a--$15⁠-⁠$20", + "out": "a--$15⁠-⁠$20", + "rules": { + "ranges": true + }, + "note": "dashes.md §3.2 step 8 and §3.2b (spec 1.3.0): T1's RIGHT branch reads effective neighbours, not raw indices. Through spec 1.2.0 the branch required a DIGIT flank, which put the token, the digit run, the U+2060 pair and the far dash in one cluster, so step 7 declined before step 8 could disagree with §3.2b; §3.2a's p1 admits a CLOSED-SYMBOL flank, CLOSED-SYMBOL is deliberately not in the cluster alphabet, and step 8 now stands alone. A port transcribing the pre-1.3.0 raw reading does not fire T1 here, converts `--` to a spaced en dash, and the range converts on the SECOND pass. Nothing else in the suite separates the two readings." + }, + { + "id": "de-de-dashes-t1-joiner-only", + "rule": "dashes", + "mode": "text", + "in": "a--15⁠ - 20", + "out": "a--15⁠ - 20", + "rules": { + "ranges": true + }, + "note": "dashes.md §3.2 step 8 and §3.2b: T1's right branch reads effective neighbours, pinned WITHOUT any closed-up symbol involved. The U+0020 ends the cluster before the far dash, so step 7 never declined this shape and the raw-index reading of the right branch was always wrong here — it is spec 1.3.0 that says so out loud (the text carried the raw reading through 1.2.0 while the reference implementation read effective neighbours). Companion to de-de-dashes-t1-joiner-and-closed-up-symbol, which covers the same divergence on the symbol path." + }, + { + "id": "de-de-yaml-colon-split-declines-growth", + "rule": "dashes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: a:--b\n", + "out": "description: a:--b\n", + "note": "modes.md §3.8.6: `:` is an opaque unit inside a plain scalar, so the dash token sits at a span extremity and the `-spaced` replacement (2 → 3) is discarded by the edge-growth rule of §3.4. Without the split this becomes `a: – b`, which no longer parses as one scalar." + }, + { + "id": "de-de-yaml-hash-split-declines-growth", + "rule": "dashes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: a--#b\n", + "out": "description: a--#b\n", + "note": "modes.md §3.8.6: `#` is an opaque unit inside a plain scalar for the same reason. Without the split this becomes `a – #b`, and everything from the hash becomes a comment." + }, + { + "id": "de-de-yaml-block-prose", + "rule": "quotes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |\n Er sagte \"hallo\" und ging\n", + "out": "description: |\n Er sagte „hallo“ und ging\n", + "note": "modes.md §8 item 4: the same construct in a locale whose quote glyphs are structurally different from en-US, so a fixture is not the same English output with a different locale field." + }, + { + "id": "de-de-yaml-unlisted-key-untouched", + "rule": "dashes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "run: git diff -- a--b\n", + "out": "run: git diff -- a--b\n", + "note": "modes.md §3.8.2: the measured case. A keyless draft rewrote shell inside `run:`; `keys` is what makes it unreachable." + }, + { + "id": "de-de-modes-three-dash-span-edge-html", + "rule": "dashes", + "mode": "html", + "in": "a---b", + "out": "a---b", + "note": "modes.md §3.4, character clause (spec 1.3.0): `---` → `␣–␣` is 3 → 3, so the length clause misses it while U+0020 lands on both span extremities. Before the character clause this produced `a – b` — an element beginning and ending with a space it never held, which is the harm §7.3 exists to prevent. Two dashes were already declined here; three now are too." + }, + { + "id": "de-de-modes-three-dash-span-edge-markdown", + "rule": "dashes", + "mode": "markdown", + "dialect": "commonmark", + "in": "x *---* y", + "out": "x *---* y", + "note": "modes.md §3.4, character clause, and §5 item 2: before it this produced `x * – * y`, which de-flanks the asterisks so that on the next run they are literal content rather than emphasis delimiters — the span partition was not stable." + }, + { + "id": "de-de-modes-three-dash-interior-html", + "rule": "dashes", + "mode": "html", + "in": "

a---b

", + "out": "

a – b

", + "note": "modes.md §3.4: the companion to de-de-modes-three-dash-span-edge-html. Interior to a span the same edit applies — the clause restricts extremities only, and a fixture set without this pair cannot tell the two apart." + }, + { + "id": "de-de-yaml-three-dash-against-colon", + "rule": "dashes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: a:---b\n", + "out": "description: a:---b\n", + "note": "modes.md §3.8.6 with §3.4's character clause: without it this became `description: a: – b`, which no longer parses — `: ` is a mapping indicator. The two-dash companion de-de-yaml-colon-split-declines-growth is caught by the length clause; only this one needs the character clause." + }, + { + "id": "de-de-yaml-three-dash-against-hash", + "rule": "dashes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: a---#b\n", + "out": "description: a---#b\n", + "note": "modes.md §3.8.6 with §3.4's character clause: without it this became `description: a – #b`, and everything from the hash became a comment — the value silently truncated to `a –`." } ] } diff --git a/vendor/polytypo-spec/fixtures/el.json b/vendor/polytypo-spec/fixtures/el.json index 294d44f..ef5b786 100644 --- a/vendor/polytypo-spec/fixtures/el.json +++ b/vendor/polytypo-spec/fixtures/el.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "el", "cases": [ { diff --git a/vendor/polytypo-spec/fixtures/en-GB.json b/vendor/polytypo-spec/fixtures/en-GB.json index 9d6a5c9..8f63347 100644 --- a/vendor/polytypo-spec/fixtures/en-GB.json +++ b/vendor/polytypo-spec/fixtures/en-GB.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "en-GB", "cases": [ { @@ -1285,6 +1285,17 @@ "in": "dell'“arte” moderna", "out": "dell’‘arte’ moderna", "note": "apostrophe.md §3.3 case 3a (spec 1.2.0), §6 row 16: `quotes` re-typesets the curly pair as en-GB's primary single quotes, and the elision before the opening glyph converts to U+2019." + }, + { + "id": "en-gb-ranges-closed-up-pound", + "rule": "ranges", + "mode": "text", + "in": "£15-£20", + "out": "£15⁠–⁠£20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): U+00A3, pinned in the locale that actually writes it. The closed-up walk is locale-independent shape logic; `en-GB` shares `en-US`'s `range: \"en-tight\"`." } ] } diff --git a/vendor/polytypo-spec/fixtures/en-US.json b/vendor/polytypo-spec/fixtures/en-US.json index af5aebe..fda2919 100644 --- a/vendor/polytypo-spec/fixtures/en-US.json +++ b/vendor/polytypo-spec/fixtures/en-US.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "en-US", "cases": [ { @@ -1866,6 +1866,631 @@ "in": "Use .NET today", "out": "Use.NET today", "note": "spaces.md §3.4 word-start clause (spec 1.2.0): the code point after the dot is the −1 span boundary marker, which is neither a LETTER nor an ASCII digit (modes.md §3.3), so the dot counts as terminal and the space before it is deleted." + }, + { + "id": "en-us-markdown-mdx-frontmatter", + "rule": "quotes", + "mode": "markdown", + "dialect": "mdx", + "in": "---\ntitle: \"Une note\"\n---\n\nBody \"quotes\" here\n", + "out": "---\ntitle: \"Une note\"\n---\n\nBody “quotes” here\n", + "note": "modes.md §3.7.3: frontmatter is skipped whole under \"mdx\" too, not only under \"commonmark\" (compare en-us-markdown-commonmark-frontmatter, the same block in the other dialect). Frontmatter followed by JSX is the realistic MDX document shape, and the JSX element's children are processable prose per the same section." + }, + { + "id": "en-us-markdown-mdx-frontmatter-abuts-content", + "rule": "quotes", + "mode": "markdown", + "dialect": "mdx", + "in": "---\ntitle: \"Une note\"\n---\nBody \"quotes\" here\n", + "out": "---\ntitle: \"Une note\"\n---\nBody “quotes” here\n", + "note": "modes.md §3.7.3: the skipped block ends at its closing delimiter, so content on the very next line with no blank line between is ordinary MDX and converts. Pins that the skip is delimited by the block itself and not by a following blank line." + }, + { + "id": "en-us-markdown-commonmark-frontmatter-toml", + "rule": "quotes", + "mode": "markdown", + "dialect": "commonmark", + "in": "+++\ntitle = \"Une note\"\n+++\n\nBody \"quotes\" here.\n", + "out": "+++\ntitle = \"Une note\"\n+++\n\nBody “quotes” here.\n", + "note": "modes.md §3.7.3 names both delimiters: a frontmatter block is delimited by --- (YAML) or +++ (TOML) and is skipped whole either way. The machine-read TOML field keeps its straight quotes while body prose converts." + }, + { + "id": "en-us-markdown-commonmark-frontmatter-unterminated", + "rule": "quotes", + "mode": "markdown", + "dialect": "commonmark", + "in": "---\ntitle: \"Unclosed\"\n\nBody \"quotes\" here.\n", + "out": "---\ntitle: “Unclosed”\n\nBody “quotes” here.\n", + "note": "modes.md §3.7.3 skips a frontmatter block; an opening delimiter with no closing one is not a block. The leading --- is then an ordinary thematic break and everything after it is prose, so the metadata-looking line converts like any other paragraph. Pinned so the skip cannot be widened into \"anything after a leading ---\"." + }, + { + "id": "en-us-ranges-closed-up-currency", + "rule": "ranges", + "mode": "text", + "in": "$15-$20", + "out": "$15⁠–⁠$20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): both members repeat the same closed-up symbol, so the walk consumes the U+0024 on the right flank and the token is a range candidate. Chicago 9.19 — \"an abbreviation or symbol is repeated if it is closed up to the number\" — makes `$15–$20` the form, and before 1.3.0 this input was left with a hyphen, which no reading of that source allows. The U+2060 pair is ranges.md §3.3.1's tight binding and is invisible on screen: review this row in spec/fixtures/.escaped/." + }, + { + "id": "en-us-ranges-closed-up-percent", + "rule": "ranges", + "mode": "text", + "in": "35%-50%", + "out": "35%⁠–⁠50%", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): the mirror of the currency case — the closed-up symbol is a SUFFIX, so the walk moves the LEFT flank and matches it against the outer symbol after Rrun. `35%–50%` is the literal example in the Chicago sentence §3.2a quotes; the rule is closed-up versus spaced, not currency versus unit." + }, + { + "id": "en-us-ranges-closed-up-degree", + "rule": "ranges", + "mode": "text", + "in": "15°-20°", + "out": "15°⁠–⁠20°", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): U+00B0 is in CLOSED-SYMBOL on the same ground as U+0024 and U+0025 — a symbol conventionally written closed up to a number. Pinned because the set is a literal enumeration, not a Unicode category test, so every member needs a case or the enumeration drifts per runtime." + }, + { + "id": "en-us-ranges-closed-up-mismatched", + "rule": "ranges", + "mode": "text", + "in": "$15-€20", + "out": "$15-€20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): the symbols must be the SAME code point. This is a currency conversion, not a range, and converting its hyphen would assert something false. The walk is not taken, so the right flank stays a non-DIGIT and the token is not a range candidate at all — it remains `dashes`' concern, exactly as before 1.3.0." + }, + { + "id": "en-us-ranges-closed-up-half-written", + "rule": "ranges", + "mode": "text", + "in": "15-$20", + "out": "15-$20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): an inner symbol with no matching outer symbol on the opposite member. Declined for the same reason as the mismatched case, and this is the row that proves the match is required in BOTH directions rather than only when both members carry a symbol." + }, + { + "id": "en-us-ranges-closed-up-multi-code-point", + "rule": "ranges", + "mode": "text", + "in": "US$15-US$20", + "out": "US$15-US$20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a and §7.7 (spec 1.3.0): the walk consumes at most one code point per side, and the mechanism here is CANDIDACY, not a guard — `cp[R]` is `U`, which is not in CLOSED-SYMBOL, so no walk is taken and the flank is simply not a DIGIT. The half-written `US$15-$20` IS a candidate and is declined by G1 instead, because `before` reads past the matched U+0024 and finds `S`; see en-us-ranges-closed-up-letter-prefix for that half." + }, + { + "id": "en-us-ranges-closed-up-elided-unchanged", + "rule": "ranges", + "mode": "text", + "in": "$15-20 and 15-20%", + "out": "$15⁠–⁠20 and 15⁠–⁠20%", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): the elided forms, where the symbol is written once. They converted before 1.3.0 and must keep converting — the Chicago answer §3.2a quotes calls them acceptable variants, and this row is the regression witness that adding the closed-up walk did not make the outer symbol a requirement." + }, + { + "id": "en-us-ranges-closed-up-spaced-token", + "rule": "ranges", + "mode": "text", + "in": "$15 - $20", + "out": "$15⁠–⁠$20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): the spaced form of the same token. Before 1.3.0 this was `dashes`' token and became `$15—$20` (en-US's em-tight parenthetical form) with DEFAULT options; now it is a range candidate, so it converts to the range form when `ranges` is on and is a no-op when it is off. See en-us-dashes-closed-up-range-declined for the other half of that pair." + }, + { + "id": "en-us-dashes-closed-up-range-declined", + "rule": "dashes", + "mode": "text", + "in": "$15 - $20", + "out": "$15 - $20", + "note": "ranges.md §3.2a and dashes.md §1 (spec 1.3.0): the ACCEPTED COST of widening range candidacy. With default options this input produced `$15—$20` through spec 1.2.0; a range candidate is declined by `dashes` unconditionally, whether or not `ranges` is enabled, so it is now a no-op. That is the behaviour `$15 - 20` has had since spec 0.5.0 — the change makes the two consistent." + }, + { + "id": "en-us-ranges-closed-up-letter-prefix", + "rule": "ranges", + "mode": "text", + "in": "US$15-$20", + "out": "US$15-$20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): the other half of the multi-code-point case. Here the right walk DOES match — the outer symbol in front of `15` is the same U+0024 — so the token is a range candidate and reaches the guards, where G1 declines it: `before` reads past the matched symbol and finds `S`, a LETTER. Pinned because §3.2a claims two different mechanisms for two inputs that look alike." + }, + { + "id": "en-us-ranges-closed-up-joiner-wrapped-hyphen", + "rule": "ranges", + "mode": "text", + "in": "$15⁠-⁠$20", + "out": "$15⁠–⁠$20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.1 and §3.2a, via dashes.md §3.2a (spec 1.3.0): the ONLY input that separates the amended re-entry condition from the unamended one. ranges.md §3.1 borrows the joiner-crossing walk from dashes.md §3.2a, and before 1.3.0 that walk required DIGIT on both effective neighbours — with a symbol there, a hyphen an author typed between an existing U+2060 pair fell through to \"joiner crossed in any other configuration: emit nothing\". Without this case a port could skip the amendment and pass the whole suite." + }, + { + "id": "en-us-ranges-closed-up-both-flanks", + "rule": "ranges", + "mode": "text", + "in": "%15%-%20%", + "out": "%15%⁠–⁠%20%", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): both flanks are in CLOSED-SYMBOL, which is the shape that makes the evaluation order observable. §3.2a decides both sides from the ORIGINAL L and R simultaneously, so both walks are taken and both match; a left-then-right or right-then-left reading would leave one side's `Lrun` undefined and decline. Not idiomatic text — pinned purely to make the evaluation model conformance-testable." + }, + { + "id": "en-us-ranges-closed-up-symbol-set-cents-pounds", + "rule": "ranges", + "mode": "text", + "in": "¢15-¢20 and ¤15-¤20 and ¥15-¥20", + "out": "¢15⁠–⁠¢20 and ¤15⁠–⁠¤20 and ¥15⁠–⁠¥20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): CLOSED-SYMBOL is a literal enumeration, not a Unicode category test, so each member needs a case or a port enumerating only the obvious few passes the whole suite. U+00A2, U+00A4 and U+00A5; U+0024 and U+20AC have their own cases, U+00A3 is pinned in en-GB." + }, + { + "id": "en-us-ranges-closed-up-symbol-set-permille", + "rule": "ranges", + "mode": "text", + "in": "15‰-20‰ and 15‱-20‱", + "out": "15‰⁠–⁠20‰ and 15‱⁠–⁠20‱", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): U+2030 and U+2031, the per-mille and per-ten-thousand signs, in the suffix position. Same reason as the currency case — the set is an enumeration and every member is part of the contract." + }, + { + "id": "en-us-dashes-t1-closed-up-symbol-unaffected", + "rule": "dashes", + "mode": "text", + "in": "price--$50--drop", + "out": "price—$50—drop", + "note": "dashes.md §3.2 step 8 (spec 1.3.0): the boundary of the accepted cost, with DEFAULT options. T1 applies only when the chosen form is `-spaced`; `en-US` sets `em-tight`, so this input is untouched by the amendment and still converts exactly as it did through spec 1.2.0. Pinned because the alternative repair — putting CLOSED-SYMBOL in the cluster guard's alphabet (§3.2 step 7) — is unconditional and would have made this a no-op in every locale. Without this case a port could take that shortcut and pass the suite." + }, + { + "id": "en-us-ranges-closed-up-block-member", + "rule": "ranges", + "mode": "text", + "in": "₹15-₹20 and ₴100-₴200", + "out": "₹15⁠–⁠₹20 and ₴100⁠–⁠₴200", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): U+20B9 and U+20B4, members of the U+20A0–U+20CF block that are NOT among the code points any other fixture names. CLOSED-SYMBOL is the whole block by its bounds, so a port that enumerates only the symbols it saw in fixtures — dollar, euro, the Latin-1 four — passes every other case and fails this one." + }, + { + "id": "en-us-ranges-closed-up-not-a-member", + "rule": "ranges", + "mode": "text", + "in": "֏15-֏20 and ¥15-¥20", + "out": "֏15-֏20 and ¥15-¥20", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): the NEGATIVE side of the enumeration. U+058F (Armenian dram) and U+FFE5 (fullwidth yen) are currency signs in Unicode's own classification and are deliberately NOT in CLOSED-SYMBOL, which is a literal code-point set precisely so that no runtime has to agree with another about a Unicode category. A port implementing the set as an Sc test — the implementation §3.2a forbids — converts these and fails here." + }, + { + "id": "en-us-yaml-plain-value", + "rule": "quotes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: He said \"hi\" to us\n", + "out": "description: He said “hi” to us\n", + "note": "modes.md §3.8.4: a plain scalar under a listed key is a processable span and converts exactly as text mode does." + }, + { + "id": "en-us-yaml-unlisted-key-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: one...two\nrun: three...four\n", + "out": "description: one…two\nrun: three...four\n", + "note": "modes.md §3.8.2: `keys` is the whole of what makes a scalar processable. A port that processes every string scalar changes the `run:` value too, which is the defect this option exists to prevent." + }, + { + "id": "en-us-yaml-empty-keys-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [], + "in": "description: one...two\n", + "out": "description: one...two\n", + "note": "modes.md §3.8.2: an empty `keys` list is legal and yields no spans — \"process nothing\" is a choice a caller may make, not an error." + }, + { + "id": "en-us-yaml-key-never-processed", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "a...b" + ], + "in": "a...b: one...two\n", + "out": "a...b: one…two\n", + "note": "modes.md §3.8.4 step 5: keys are never processable, including the key that was matched against `keys`." + }, + { + "id": "en-us-yaml-colon-inside-key", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "a:b" + ], + "in": "a:b: one...two\n", + "out": "a:b: one…two\n", + "note": "modes.md §3.8.4 step 5: a colon not followed by U+0020 or the line end is an ordinary key character, so the key here is `a:b`. A port that stops at the first colon finds no key and yields no spans." + }, + { + "id": "en-us-yaml-quoted-scalar-with-colon", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "title" + ], + "in": "title: \"Chapter 1: one...two\"\n", + "out": "title: \"Chapter 1: one…two\"\n", + "note": "modes.md §3.8.6: the plain-scalar colon test does not apply to a quoted scalar — quoting neutralises the colon. A port that applies it declines this line." + }, + { + "id": "en-us-yaml-block-literal-lines", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |\n one...two\n three...four\n", + "out": "description: |\n one…two\n three…four\n", + "note": "modes.md §3.8.5: one span per content line, beginning after the block indentation; indentation beyond that is content and stays inside the span." + }, + { + "id": "en-us-yaml-chomping-clip", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |\n one...two\n\n\nz: 1\n", + "out": "description: |\n one…two\n\n\nz: 1\n", + "note": "modes.md §3.8.5: the trailing line terminators the chomping indicator governs are outside every span. Compare en-us-yaml-chomping-strip and en-us-yaml-chomping-keep: three indicators, identical content edit, identical trailing bytes." + }, + { + "id": "en-us-yaml-chomping-strip", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |-\n one...two\n\n\nz: 1\n", + "out": "description: |-\n one…two\n\n\nz: 1\n", + "note": "modes.md §3.8.5: `|-` differs from `|` only in bytes the mode never touches. A port that decodes the block and re-encodes it produces a different byte count here than for en-us-yaml-chomping-clip." + }, + { + "id": "en-us-yaml-chomping-keep", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |+\n one...two\n\n\nz: 1\n", + "out": "description: |+\n one…two\n\n\nz: 1\n", + "note": "modes.md §3.8.5: `|+` keeps every trailing line terminator, and they are outside every span. This is the case the reported corruption in §3.8.1 failed." + }, + { + "id": "en-us-yaml-quotes-pair-across-block-lines", + "rule": "quotes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |\n He said \"hi\n there\" and left\n", + "out": "description: |\n He said “hi\n there” and left\n", + "note": "modes.md §3.2 model C: a block scalar's content lines are separate spans joined by a −2 marker, so a quotation opened on one line pairs with a mark on the next. A port that runs each line independently leaves both marks straight." + }, + { + "id": "en-us-yaml-multiline-quoted-untouched", + "rule": "quotes", + "mode": "yaml", + "keys": [ + "a", + "b" + ], + "in": "a: \"open here\n b: some prose \"word\" close\"\n", + "out": "a: \"open here\n b: some prose \"word\" close\"\n", + "note": "modes.md §3.8.4 step 7: a quoted scalar that does not close on its opening line consumes its continuation lines, which are never rescanned. A port that rescans them puts the scalar's own closing quote inside a span, and `quotes` can then leave the scalar unterminated." + }, + { + "id": "en-us-yaml-multiline-flow-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "a", + "b", + "c" + ], + "in": "a: {\n b: one...two,\n c: x\n}\n", + "out": "a: {\n b: one...two,\n c: x\n}\n", + "note": "modes.md §3.8.4 step 7: a flow collection spanning several lines consumes them all. A port that bails only on the opening line processes the interior and can edit next to the structural comma." + }, + { + "id": "en-us-yaml-block-ambiguous-indent-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |\n deep one...two\n shallow three...four\n", + "out": "description: |\n deep one...two\n shallow three...four\n", + "note": "modes.md §3.8.5: a later content line dedented inside the block is ambiguous, so the whole block yields no spans rather than the scan guessing which line the author meant as content." + }, + { + "id": "en-us-yaml-not-yaml-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "{{ not yaml at all ... }}\n\t\tmixed\tindentation...\n", + "out": "{{ not yaml at all ... }}\n\t\tmixed\tindentation...\n", + "note": "modes.md §3.8.3: a construct the scan does not recognise yields no spans and the input comes back byte for byte. `transform` never throws on input in this mode." + }, + { + "id": "en-us-yaml-document-marker-prefix-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description", + "--- description" + ], + "in": "--- description: one...two\n", + "out": "--- description: one...two\n", + "note": "modes.md §3.8.4 step 3: a document marker introducing a node is declined along with the bare form, so no key of `--- description` can ever be formed." + }, + { + "id": "en-us-yaml-astral-preserved", + "rule": "quotes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: A rocket 🚀 and a \"quote\"\n", + "out": "description: A rocket 🚀 and a “quote”\n", + "note": "modes.md §4: offsets are code points, not code units. A runtime indexing UTF-16 code units mis-slices the span after the astral character." + }, + { + "id": "en-us-modes-three-dash-span-edge-html", + "rule": "dashes", + "mode": "html", + "in": "a---b", + "out": "a—b", + "note": "modes.md §3.4: an em-tight locale emits no U+0020, so the character clause does not fire and the edit applies at the extremity. The clause tests the character, not the length — this is the case that shows why." + }, + { + "id": "en-us-yaml-folded-clip", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: >\n one...two\n\n\nz: 1\n", + "out": "description: >\n one…two\n\n\nz: 1\n", + "note": "modes.md §3.8.5: `>` is handled identically to `|` because the difference between them lives entirely in bytes the mode never touches. Companion to en-us-yaml-folded-strip and en-us-yaml-folded-keep." + }, + { + "id": "en-us-yaml-folded-strip", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: >-\n one...two\n\n\nz: 1\n", + "out": "description: >-\n one…two\n\n\nz: 1\n", + "note": "modes.md §3.8.5: identical content edit and identical trailing bytes to en-us-yaml-folded-clip and en-us-yaml-folded-keep — a port that decodes the block and re-encodes it produces three different byte counts." + }, + { + "id": "en-us-yaml-folded-keep", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: >+\n one...two\n\n\nz: 1\n", + "out": "description: >+\n one…two\n\n\nz: 1\n", + "note": "modes.md §3.8.5: `>+` keeps every trailing line terminator, and they lie outside every span. Completes the six chomping indicators with en-us-yaml-chomping-clip, -strip and -keep." + }, + { + "id": "en-us-yaml-quoted-key-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "\"description\": one...two\n", + "out": "\"description\": one...two\n", + "note": "modes.md §3.8.4 step 5 and §7.11: a key containing a quote is declined before it is ever compared against `keys`, so a document that quotes its keys gets nothing from this mode. An accepted cost, pinned so it is a decision rather than a surprise." + }, + { + "id": "en-us-yaml-bang-in-key-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "a!b" + ], + "in": "a!b: one...two\n", + "out": "a!b: one...two\n", + "note": "modes.md §3.8.4 step 5: the character test applies at every position of the key, not only the first, so a key merely containing `!` is declined too. A port testing only the first position processes this line and diverges." + }, + { + "id": "en-us-yaml-same-key-two-depths", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: one...two\nnested:\n inner:\n description: three...four\n", + "out": "description: one…two\nnested:\n inner:\n description: three…four\n", + "note": "modes.md §3.8.2: `keys` matches a bare name at any depth and nothing narrower. Both occurrences convert; a port that matches only at the top level converts one." + }, + { + "id": "en-us-yaml-crlf-block", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |\r\n one...two\r\n", + "out": "description: |\r\n one…two\r\n", + "note": "modes.md §3.8.4: a U+000D immediately before the U+000A is a terminator, not part of the line, so a CRLF file yields the same spans as the same bytes with LF and the carriage returns come back untouched. A port splitting lines on U+000A alone reads the header as `|` + U+000D and yields nothing." + }, + { + "id": "en-us-yaml-sequence-entry", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "- description: one...two\n- - description: three...four\n", + "out": "- description: one…two\n- - description: three…four\n", + "note": "modes.md §3.8.4 step 4: block sequence entries are consumed rather than skipped, and they nest." + }, + { + "id": "en-us-yaml-single-quoted", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: 'one...two'\n", + "out": "description: 'one…two'\n", + "note": "modes.md §3.8.6: a single-quoted scalar's content is one span; the quotes themselves are outside it." + }, + { + "id": "en-us-yaml-single-quoted-escape-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: 'it''s one...two'\n", + "out": "description: 'it''s one...two'\n", + "note": "modes.md §3.8.6: `''` makes the source spell the content with more characters than it has, so the offset model of §3.1 cannot hold and the scalar yields no spans." + }, + { + "id": "en-us-yaml-double-quoted-escape-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: \"one \\\"two\\\"... three\"\n", + "out": "description: \"one \\\"two\\\"... three\"\n", + "note": "modes.md §3.8.6: a backslash in a double-quoted scalar means the same thing — source characters and content characters stop being the same, exactly as an HTML character reference does in §3.6." + }, + { + "id": "en-us-yaml-anchor-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description", + "use" + ], + "in": "description: &anchor one...two\nuse: *anchor\n", + "out": "description: &anchor one...two\nuse: *anchor\n", + "note": "modes.md §3.8.4 step 9: an anchored or aliased value is not a construct this scan claims, listed key or not." + }, + { + "id": "en-us-yaml-tag-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: !!str one...two\n", + "out": "description: !!str one...two\n", + "note": "modes.md §3.8.4 step 9: a tagged value is declined for the same reason as an anchored one." + }, + { + "id": "en-us-yaml-comment-only-value", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "# a comment...here\n%TAG ! tag:example.com,2000:\ndescription: # one...two\n", + "out": "# a comment...here\n%TAG ! tag:example.com,2000:\ndescription: # one...two\n", + "note": "modes.md §3.8.4 steps 2 and 9: a comment line, a directive line, and a value that is only a comment all yield no spans." + }, + { + "id": "en-us-yaml-document-markers", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "---\ndescription: one...two\n...\n", + "out": "---\ndescription: one…two\n...\n", + "note": "modes.md §3.8.4 step 3: the bare document markers are declined as lines, and the mapping between them is scanned normally." + }, + { + "id": "en-us-yaml-flow-one-line-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description", + "inner" + ], + "in": "description: [one...two, three]\ninner: {a: four...five}\n", + "out": "description: [one...two, three]\ninner: {a: four...five}\n", + "note": "modes.md §3.8.4 step 9: a flow collection is declined whole, on one line as much as across several." + }, + { + "id": "en-us-yaml-explicit-indent-indicator", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |2\n one...two\n", + "out": "description: |2\n one…two\n", + "note": "modes.md §3.8.5: an explicit indentation indicator sets `bi` to `indent + n`, so the leading space here is content and stays inside the span." + }, + { + "id": "en-us-yaml-empty-value-nested-node", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "outer:\n description: one...two\n", + "out": "outer:\n description: one…two\n", + "note": "modes.md §3.8.4 step 6: a key with no inline value introduces a nested node whose lines ARE scanned on their own — the one case where following lines are not consumed by step 7." + }, + { + "id": "en-us-yaml-multiline-plain-untouched", + "rule": "ellipsis", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: one...two\n three...four\n", + "out": "description: one...two\n three...four\n", + "note": "modes.md §3.8.6: a multi-line plain scalar's folding is a construct this scan does not claim, so the whole value yields no spans — including its first line." } ] } diff --git a/vendor/polytypo-spec/fixtures/es.json b/vendor/polytypo-spec/fixtures/es.json new file mode 100644 index 0000000..32bc07e --- /dev/null +++ b/vendor/polytypo-spec/fixtures/es.json @@ -0,0 +1,193 @@ +{ + "spec": "1.3.0", + "locale": "es", + "cases": [ + { + "id": "es-quotes-primary", + "rule": "quotes", + "mode": "text", + "in": "Ha dicho \"buenos días\" y salió.", + "out": "Ha dicho «buenos días» y salió.", + "note": "quotes.primary = U+00AB/U+00BB con innerSpace \"none\" (DPD «comillas» 1: «se recomienda utilizar en primera instancia las comillas angulares»; «pegadas a la primera y la última palabra»)." + }, + { + "id": "es-quotes-nested", + "rule": "quotes", + "mode": "text", + "in": "Escribió: \"Me dijo 'llego enseguida' y desapareció.\"", + "out": "Escribió: «Me dijo “llego enseguida” y desapareció.»", + "note": "Nivel 1 angulares, nivel 2 inglesas, según el orden que fija el DPD. El tercer nivel del DPD (simples) no es expresable en el esquema." + }, + { + "id": "es-quotes-inner-space-deleted", + "rule": "quotes", + "mode": "text", + "in": "Ha dicho « buenos días » y salió.", + "out": "Ha dicho «buenos días» y salió.", + "note": "innerSpace \"none\": N8 elimina el espacio interior que un texto copiado de una fuente francesa trae consigo." + }, + { + "id": "es-ellipsis-three-dots", + "rule": "ellipsis", + "mode": "text", + "in": "Espera... ¿qué?", + "out": "Espera… ¿qué?", + "note": "Tres U+002E pasan a U+2026 (DPD «puntos suspensivos» 1: «tres puntos consecutivos ―y solo tres―»)." + }, + { + "id": "es-ellipsis-not-abbreviated-after-terminal", + "rule": "ellipsis", + "mode": "text", + "in": "¿De verdad?..", + "out": "¿De verdad?…", + "note": "abbreviatedAfterTerminal = false: la forma de dos puntos tras «?» que usa el ruso no existe en español, así que los dos puntos se completan a U+2026 en vez de conservarse." + }, + { + "id": "es-dashes-parenthetical-none", + "rule": "dashes", + "mode": "text", + "in": "El plan - si existe - fracasa.", + "out": "El plan - si existe - fracasa.", + "note": "dash.parenthetical = \"none\": el DPD prescribe raya con espacios FUERA del par y ninguno dentro, asimetría que el enum no expresa; mientras tanto la regla no toca nada. Véase la voz dashes de es.json." + }, + { + "id": "es-ranges-guion-none", + "rule": "ranges", + "mode": "text", + "in": "las páginas 23-45", + "out": "las páginas 23-45", + "note": "ranges.md §3: el token no se convierte porque dash.range es \"none\" — el signo español del intervalo es el guion U+002D, que ya está escrito (DPD «guion» 3 b), y el enum no tiene un valor para él. El caso se genera con ranges activado explícitamente, ya que la regla está desactivada por defecto.", + "rules": { + "ranges": true + } + }, + { + "id": "es-hyphen-noop", + "rule": "hyphen", + "mode": "text", + "in": "un estudio teórico-práctico", + "out": "un estudio teórico-práctico", + "note": "Las tres listas de hyphen están vacías, así que la regla es un no-op total demostrable para el español (hyphen.md §2)." + }, + { + "id": "es-nbsp-inverted-marks-untouched", + "rule": "nbsp", + "mode": "text", + "in": "¿Qué hora es? ¡Vaya!", + "out": "¿Qué hora es? ¡Vaya!", + "note": "beforePunctuation y narrowBeforePunctuation vacías: el español no pone espacio antes de «?» ni de «!», y U+00BF/U+00A1 no son miembros de CLOSEISH, así que la restricción Q-P impediría expresarlo aunque la fuente lo pidiera." + }, + { + "id": "es-nbsp-degree-tight", + "rule": "nbsp", + "mode": "text", + "in": "Hacía 27° a la sombra", + "out": "Hacía 27° a la sombra", + "note": "El DPD «símbolo» 5.4 pega «°» a la cifra cuando no se especifica la escala, por eso «°» a secas NO está en beforeUnits y aquí no se inserta nada." + }, + { + "id": "es-nbsp-percent", + "rule": "nbsp", + "mode": "text", + "in": "Aprobó un 8 % de los alumnos", + "out": "Aprobó un 8 % de los alumnos", + "note": "N5 beforeUnits: el espacio pasa a U+00A0. RAE, Duda lingüística: «El símbolo del porcentaje se separa con espacio de la cifra que lo precede: 50 %»; la indivisibilidad la impone el DPD «símbolo» 5.6." + }, + { + "id": "es-nbsp-celsius", + "rule": "nbsp", + "mode": "text", + "in": "La temperatura es de 27 °C", + "out": "La temperatura es de 27 °C", + "note": "«°C» sí está en beforeUnits, citado literalmente por el DPD «símbolo» 5.4 («27° […] pero 27 °C»). Contrasta con es-nbsp-degree-tight." + }, + { + "id": "es-nbsp-abbreviation-internal-space", + "rule": "nbsp", + "mode": "text", + "in": "Viajó a los EE. UU. el lunes", + "out": "Viajó a los EE. UU. el lunes", + "note": "N4 abbreviations: el espacio interior de una abreviatura de varios elementos pasa a U+00A0 (DPD «abreviatura»: «Cuando la abreviatura se compone de varios elementos, estos no deben separarse en líneas diferentes»)." + }, + { + "id": "es-nbsp-abbreviation-p-ej", + "rule": "nbsp", + "mode": "text", + "in": "algunos casos, p. ej. este", + "out": "algunos casos, p. ej. este", + "note": "La misma subrregla sobre «p. ej.», forma atestiguada en la Lista de abreviaturas de El buen uso del español." + }, + { + "id": "es-nbsp-before-number", + "rule": "nbsp", + "mode": "text", + "in": "véase la pág. 23", + "out": "véase la pág. 23", + "note": "N9 beforeNumber: «⊗15 / págs.» es el ejemplo del propio DPD «abreviatura» para este caso." + }, + { + "id": "es-nbsp-before-word", + "rule": "nbsp", + "mode": "text", + "in": "El Sr. Pérez llegó tarde", + "out": "El Sr. Pérez llegó tarde", + "note": "N10 beforeWord: «⊗Sr. / Pérez» es el segundo ejemplo de la misma entrada. La lista se limita a los tratamientos de cortesía, por el riesgo de falsos positivos de esta subrregla." + }, + { + "id": "es-nbsp-initials-chain", + "rule": "nbsp", + "mode": "text", + "in": "Lo escribió J. A. Pérez ayer", + "out": "Lo escribió J. A. Pérez ayer", + "note": "initialBinding = \"chain\": la cadena completa se liga, incluido el espacio que precede a la primera inicial, igual que en en-US y ru. Decisión del operador (18.09.2026) ante una fuente que no distingue entre una inicial y dos; véase la voz nbsp correspondiente." + }, + { + "id": "es-nbsp-lone-initial-not-bound", + "rule": "nbsp", + "mode": "text", + "in": "La ley N. Roma decidió", + "out": "La ley N. Roma decidió", + "note": "El reverso del caso anterior y la razón de elegir \"chain\": una sola mayúscula con punto seguida de un nombre propio NO se liga, de modo que un final de frase no se confunde con una inicial." + }, + { + "id": "es-nbsp-ac-guard", + "rule": "nbsp", + "mode": "text", + "in": "en el año 33 a. C. Roma era una república", + "out": "en el año 33 a. C. Roma era una república", + "note": "N4 liga el espacio interior de «a. C.» y la guarda C1-a (nbsp.md §3.9) impide que C1 lea «C.» como inicial y «Roma» como apellido. Equivalente español del alemán «z. B. Berlin»." + }, + { + "id": "es-apostrophe-foreign-name", + "rule": "apostrophe", + "mode": "text", + "in": "L'Hospitalet de Llobregat", + "out": "L’Hospitalet de Llobregat", + "note": "U+0027 pasa a U+2019. El DPD «apóstrofo» limita el signo en español a textos antiguos, habla reproducida y nombres de otras lenguas: este es el tercer caso, y es el que un texto español encuentra de verdad." + }, + { + "id": "es-roundtrip-noop", + "rule": "quotes", + "mode": "text", + "in": "Ha dicho «buenos días» y salió…", + "out": "Ha dicho «buenos días» y salió…", + "note": "modes.md §4: un texto ya compuesto vuelve byte a byte." + }, + { + "id": "es-spaces-brackets-and-final-stop", + "rule": "spaces", + "mode": "text", + "in": "Dijo ( sin dudar ) que sí .", + "out": "Dijo (sin dudar) que sí.", + "note": "spaces.md §3: los espacios interiores de los paréntesis se eliminan y la serie anterior al punto final se colapsa. Regla independiente de la locale, presente aquí para que es tenga un caso por cada regla canónica." + }, + { + "id": "es-symbols-copyright-and-dimensions", + "rule": "symbols", + "mode": "text", + "in": "Copyright (c) 2026, tamaño 40x60 cm", + "out": "Copyright © 2026, tamaño 40×60 cm", + "note": "symbols.md: «(c)» pasa a U+00A9 y la «x» entre cifras a U+00D7. El U+00A0 ante «cm» lo pone nbsp N5, no symbols; se deja en el mismo caso porque así se ve que las dos reglas componen." + } + ] +} diff --git a/vendor/polytypo-spec/fixtures/fi.json b/vendor/polytypo-spec/fixtures/fi.json index 07cd4df..5c3e9e4 100644 --- a/vendor/polytypo-spec/fixtures/fi.json +++ b/vendor/polytypo-spec/fixtures/fi.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "fi", "cases": [ { diff --git a/vendor/polytypo-spec/fixtures/fr-CA.json b/vendor/polytypo-spec/fixtures/fr-CA.json index f279d06..d0c26da 100644 --- a/vendor/polytypo-spec/fixtures/fr-CA.json +++ b/vendor/polytypo-spec/fixtures/fr-CA.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "fr-CA", "cases": [ { @@ -288,6 +288,30 @@ "in": "l'\"idée\" est simple", "out": "l’« idée » est simple", "note": "apostrophe.md §3.3 case 3a (spec 1.2.0): same as `fr`." + }, + { + "id": "fr-ca-nbsp-numero-binds-number", + "rule": "nbsp", + "mode": "text", + "in": "voir n° 5", + "out": "voir n° 5", + "note": "nbsp.md §3.11 N9 : « n° » figure dans nbsp.beforeNumber depuis la spec 1.3.0 et se lie au nombre qui suit. La forme retenue est « n » + U+00B0, l'usage le plus répandu ; voir l'entrée sources de la locale, la source (OQLF) prescrivant un tracé et non un code point." + }, + { + "id": "fr-ca-nbsp-numero-capital-is-its-own-entry", + "rule": "nbsp", + "mode": "text", + "in": "N° 5 de la revue", + "out": "N° 5 de la revue", + "note": "nbsp.md §3.11 N9 étape 1 : aucune tolérance de casse, « N° » est donc une entrée distincte de « n° » dans nbsp.beforeNumber." + }, + { + "id": "fr-ca-nbsp-numero-needs-a-digit", + "rule": "nbsp", + "mode": "text", + "in": "le n° cinq", + "out": "le n° cinq", + "note": "nbsp.md §3.11 N9 étape 4 : il faut un DIGIT après le séparateur. Un nombre écrit en toutes lettres n'en est pas un, l'espace reste sécable." } ] } diff --git a/vendor/polytypo-spec/fixtures/fr.json b/vendor/polytypo-spec/fixtures/fr.json index 6fc8fcb..e390eed 100644 --- a/vendor/polytypo-spec/fixtures/fr.json +++ b/vendor/polytypo-spec/fixtures/fr.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "fr", "cases": [ { @@ -704,6 +704,181 @@ "in": "Voir http://x.org", "out": "Voir http ://x.org", "note": "nbsp.md §3.3 step 2 (spec 1.2.0): the second stated cost of accepting the marker. Step 2 cannot see the `/` in the next span, so the colon is treated as sentence punctuation and N1 inserts U+00A0." + }, + { + "id": "fr-nbsp-numero-binds-number", + "rule": "nbsp", + "mode": "text", + "in": "voir n° 5", + "out": "voir n° 5", + "note": "nbsp.md §3.11 N9 : « n° » figure dans nbsp.beforeNumber depuis la spec 1.3.0 et se lie au nombre qui suit. La forme retenue est « n » + U+00B0, l'usage le plus répandu ; voir l'entrée sources de la locale, la source (OQLF) prescrivant un tracé et non un code point." + }, + { + "id": "fr-nbsp-numero-capital-is-its-own-entry", + "rule": "nbsp", + "mode": "text", + "in": "N° 5 de la revue", + "out": "N° 5 de la revue", + "note": "nbsp.md §3.11 N9 étape 1 : aucune tolérance de casse, « N° » est donc une entrée distincte de « n° » dans nbsp.beforeNumber." + }, + { + "id": "fr-nbsp-numero-needs-a-digit", + "rule": "nbsp", + "mode": "text", + "in": "le n° cinq", + "out": "le n° cinq", + "note": "nbsp.md §3.11 N9 étape 4 : il faut un DIGIT après le séparateur. Un nombre écrit en toutes lettres n'en est pas un, l'espace reste sécable." + }, + { + "id": "fr-markdown-commonmark-frontmatter-nbsp", + "rule": "nbsp", + "mode": "markdown", + "dialect": "commonmark", + "in": "---\ntitle: Une note ; suite\n---\n\nEst-ce vrai ?\n", + "out": "---\ntitle: Une note ; suite\n---\n\nEst-ce vrai ?\n", + "note": "modes.md §3.7.3 gives this exact reason for skipping frontmatter: without it `fr` would put U+00A0 before the colon of a machine-read field and U+202F before its semicolon. The body sentence shows the rule is otherwise active in the same document, so the untouched field proves the skip rather than an inactive rule." + }, + { + "id": "fr-markdown-mdx-frontmatter-nbsp", + "rule": "nbsp", + "mode": "markdown", + "dialect": "mdx", + "in": "---\ntitle: Une note ; suite\n---\n\nEst-ce vrai ?\n", + "out": "---\ntitle: Une note ; suite\n---\n\nEst-ce vrai ?\n", + "note": "modes.md §3.7.3: the same guarantee under \"mdx\", where frontmatter plus JSX is the ordinary document shape. This is the case the polytypo-js source comment above its frontmatter skip entry described as a spec gap." + }, + { + "id": "fr-nbsp-character-reference-numeric", + "rule": "nbsp", + "mode": "text", + "in": "Bonjour : oui", + "out": "Bonjour : oui", + "note": "nbsp.md §3.3 step 4 (spec 1.3.0): the `;` closes ` `, so N2 emits nothing and the reference survives. The `:` takes nothing either — step 1's run guard sees a mark to its left. Before 1.3.0 this produced `Bonjour ` + U+202F + `: oui`, which is no longer a character reference." + }, + { + "id": "fr-nbsp-character-reference-named", + "rule": "nbsp", + "mode": "text", + "in": "Tom & Jerry", + "out": "Tom & Jerry", + "note": "nbsp.md §3.3 step 4 (spec 1.3.0): the same guard on a named reference. Before 1.3.0 `text` mode destroyed every character reference in French input, and only in locales whose nbsp data puts a space before `;`." + }, + { + "id": "fr-nbsp-character-reference-shape-not-table", + "rule": "nbsp", + "mode": "text", + "in": "a ¬aname; b", + "out": "a ¬aname; b", + "note": "nbsp.md §3.3 step 4 (spec 1.3.0): the guard tests the shape of a reference, not membership of the HTML named-reference table, which five runtimes would otherwise have to carry identically. Declining here costs nothing." + }, + { + "id": "fr-nbsp-ordinary-semicolon-still-binds", + "rule": "nbsp", + "mode": "text", + "in": "Oui ; non", + "out": "Oui ; non", + "note": "nbsp.md §3.3 step 4 (spec 1.3.0) is not a blanket refusal of `;`: an ordinary semicolon still takes U+202F under N2. Pinned next to the reference cases so the guard cannot be widened into one." + }, + { + "id": "fr-nbsp-semicolon-after-digit-binds", + "rule": "nbsp", + "mode": "text", + "in": "Section 4; suite", + "out": "Section 4 ; suite", + "note": "nbsp.md §3.3 step 4 (spec 1.3.0): the left walk finds the digit run but no `&` before it, so the guard does not fire." + }, + { + "id": "fr-nbsp-narrow-substituted", + "rule": "nbsp", + "mode": "text", + "narrowNbsp": "nbsp", + "in": "Un délai ? Vraiment ! Et puis ; voilà.", + "out": "Un délai ? Vraiment ! Et puis ; voilà.", + "note": "nbsp.md §3.1a (spec 1.3.0): `narrowNbsp: \"nbsp\"` moves N2's target from U+202F to U+00A0. The same indices are claimed by the same sub-rule under the same guards — only the character written changes. Compare fr-nbsp-narrow-default, which is this input with the option absent." + }, + { + "id": "fr-nbsp-narrow-default", + "rule": "nbsp", + "mode": "text", + "in": "Un délai ? Vraiment ! Et puis ; voilà.", + "out": "Un délai ? Vraiment ! Et puis ; voilà.", + "note": "nbsp.md §3.1a: the control for fr-nbsp-narrow-substituted. No `narrowNbsp` key means \"narrow\", so every case written before spec 1.3.0 keeps its meaning and a runtime that ignores the option unknowingly still passes this one — which is why the substituted case above is the one that proves the feature." + }, + { + "id": "fr-nbsp-narrow-substituted-authored", + "rule": "nbsp", + "mode": "text", + "narrowNbsp": "nbsp", + "in": "Oui ? Non !", + "out": "Oui ? Non !", + "note": "nbsp.md §3.1a: an authored U+202F at an index N2 claims is normalised to the substituted target, exactly as an authored U+00A0 is normalised to U+202F in the default configuration — the rule normalises a claimed index to its target, and the target has moved. This is the case that separates a target rewrite from post-processing: a caller's replaceAll would also produce this output, but would not be a fixed point when its own output is fed back in." + }, + { + "id": "fr-nbsp-narrow-substituted-authored-default", + "rule": "nbsp", + "mode": "text", + "in": "Oui ? Non !", + "out": "Oui ? Non !", + "note": "nbsp.md §3.1a: the control for the case above — with the default target an authored U+202F is already correct and nothing is emitted." + }, + { + "id": "fr-nbsp-narrow-substituted-with-quotes", + "rule": "nbsp", + "mode": "text", + "narrowNbsp": "nbsp", + "in": "Il a dit : « oui » ; puis ?", + "out": "Il a dit : « oui » ; puis ?", + "note": "nbsp.md §3.1a with N1, N2 and N8 all claiming indices in one string. N1 (the colon) and N8 (`fr`'s primary pair, whose innerSpace is \"nbsp\") already wrote U+00A0 and are untouched by the option; N2 (`;` and `?`) moves. With the substitution on, all three want the same character — the option can only ever make N2's target EQUAL to N1's, never different, which is why §5's clause 0 needs no new case." + }, + { + "id": "fr-nbsp-narrow-substituted-guards-unchanged", + "rule": "nbsp", + "mode": "text", + "narrowNbsp": "nbsp", + "in": "12:30 et http://x ; oui", + "out": "12:30 et http://x ; oui", + "note": "nbsp.md §3.1a: the option changes what the rule writes, never what it reads or which indices it claims. N1's right-context guard still protects the time and the URL — the colon in `12:30` and in `http://` takes nothing, under the substitution exactly as under the default." + }, + { + "id": "fr-nbsp-quote-inner-space-authored-narrow", + "rule": "nbsp", + "mode": "text", + "in": "Il a dit « mot ».", + "out": "Il a dit « mot ».", + "note": "nbsp.md §3.10 and §6 rows 3-4, corrected in spec 1.3.0. `fr.json` sets the primary pair's innerSpace to \"nbsp\", so N8's target is U+00A0 and an authored U+202F inside the quotation marks is CONVERTED, not already correct. Through spec 1.2.0 the worked-example table claimed both the narrow space and a fixed point here — a claim about a locale file the file never supported, and nothing pinned it. This case pins it." + }, + { + "id": "fr-yaml-narrow-space-in-quoted", + "rule": "nbsp", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: \"Une note !\"\n", + "out": "description: \"Une note !\"\n", + "note": "modes.md §3.8.6: a quoted scalar's content is one span, and French spacing applies inside it exactly as in text mode." + }, + { + "id": "fr-yaml-no-space-across-colon-split", + "rule": "nbsp", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: prose:more prose\n", + "out": "description: prose:more prose\n", + "note": "modes.md §3.8.6: the `:` is outside every span, so the insertion `nbsp` would make before it lands on a span edge and is discarded by §3.4. This is the accepted cost of the split, and it is what keeps the scalar parseable." + }, + { + "id": "fr-yaml-guillemets-across-block-lines", + "rule": "quotes", + "mode": "yaml", + "keys": [ + "description" + ], + "in": "description: |\n Il a dit \"bonjour\n monsieur\" et il est parti\n", + "out": "description: |\n Il a dit « bonjour\n monsieur » et il est parti\n", + "note": "modes.md §3.2 model C in a locale whose quotation output is guillemets plus U+00A0 rather than curly quotes — structurally different from the en-US case of the same shape." } ] } diff --git a/vendor/polytypo-spec/fixtures/it.json b/vendor/polytypo-spec/fixtures/it.json new file mode 100644 index 0000000..173428f --- /dev/null +++ b/vendor/polytypo-spec/fixtures/it.json @@ -0,0 +1,161 @@ +{ + "spec": "1.3.0", + "locale": "it", + "cases": [ + { + "id": "it-quotes-primary", + "rule": "quotes", + "mode": "text", + "in": "Ha detto \"buongiorno\" ed è uscito.", + "out": "Ha detto «buongiorno» ed è uscito.", + "note": "quotes.primary = U+00AB/U+00BB, innerSpace \"none\" (Manuale interistituzionale 4.2.3 livello 1; Parte quarta 10.1.7 «Le virgolette non richiedono spazio né in apertura né in chiusura»). Contrasto diretto con fr, che qui inserisce U+00A0 all'interno." + }, + { + "id": "it-quotes-nested", + "rule": "quotes", + "mode": "text", + "in": "Scrisse: \"Mi disse 'arrivo subito' e sparì.\"", + "out": "Scrisse: «Mi disse “arrivo subito” e sparì.»", + "note": "Livello 1 caporali, livello 2 virgolette alte. Il livello 3 del Manuale non è rappresentabile nello schema." + }, + { + "id": "it-quotes-inner-space-deleted", + "rule": "quotes", + "mode": "text", + "in": "Ha detto « buongiorno » ed è uscito.", + "out": "Ha detto «buongiorno» ed è uscito.", + "note": "Con innerSpace \"none\" la regola CANCELLA lo spazio interno: un testo italiano copiato da una fonte francese si normalizza." + }, + { + "id": "it-quotes-elision-before-quotation", + "rule": "quotes", + "mode": "text", + "in": "il titolo dell'\"amico\" ritrovato", + "out": "il titolo dell’«amico» ritrovato", + "note": "Il caso di maggiore impatto reale per l'italiano, che elide molto più del francese: l'apostrofo di elisione diventa U+2019 (apostrophe.md caso 3a, spec 1.2.0) e non viene rivendicato come segno di apertura, mentre le virgolette restano prive di spazio interno." + }, + { + "id": "it-dashes-parenthetical-em-spaced", + "rule": "dashes", + "mode": "text", + "in": "La casa - se casa si poteva definire quel rudere - sorgeva ai piedi del colle.", + "out": "La casa — se casa si poteva definire quel rudere — sorgeva ai piedi del colle.", + "note": "dash.parenthetical = \"em-spaced\": U+2014 con U+0020 su ciascun lato. Frase dell'esempio stampato al punto 10.1.10 del Manuale." + }, + { + "id": "it-dashes-compound-hyphen", + "rule": "dashes", + "mode": "text", + "in": "un trattato italo-francese", + "out": "un trattato italo-francese", + "note": "Guardia P1 di dashes.md §3.2: un trattino nudo e non spaziato è una parola composta. Esempio stampato al punto 10.1.11." + }, + { + "id": "it-dashes-date-range-accepted-cost", + "rule": "dashes", + "mode": "text", + "in": "25 maggio - 10 giugno 1985", + "out": "25 maggio — 10 giugno 1985", + "note": "COSTO ACCETTATO, verificato sul motore e fissato qui perché non venga riscoperto come bug. Il punto 10.1.11 del Manuale prescrive il trattino spaziato per collegare due date di mesi diversi, ma la guardia P1 converte qualunque trattino isolato e spaziato fra parole. Non è una particolarità italiana: fr, ru, de-DE e en-GB, già pubblicate, fanno lo stesso su questa identica stringa." + }, + { + "id": "it-ranges-none-years", + "rule": "ranges", + "mode": "text", + "in": "anno accademico 2010-2011", + "out": "anno accademico 2010-2011", + "note": "ranges.md §3: il token non viene convertito perché dash.range è \"none\" — il punto 10.3.1 del Manuale prescrive il trattino U+002D, già presente, e l'enum non ha un valore per esso. Il caso è generato con ranges attivato esplicitamente, dato che la regola è disattivata per impostazione predefinita.", + "rules": { + "ranges": true + } + }, + { + "id": "it-ellipsis-three-dots", + "rule": "ellipsis", + "mode": "text", + "in": "Ti chiami Leone... ma sei un coniglio.", + "out": "Ti chiami Leone… ma sei un coniglio.", + "note": "Tre U+002E diventano U+2026. Frase dell'esempio stampato al punto 10.1.8." + }, + { + "id": "it-ellipsis-not-abbreviated-after-terminal", + "rule": "ellipsis", + "mode": "text", + "in": "Davvero?..", + "out": "Davvero?…", + "note": "abbreviatedAfterTerminal = false: la forma a due punti del russo non esiste in italiano (10.1.8 «costituito da tre punti»; Crusca «sempre nel numero di tre»)." + }, + { + "id": "it-hyphen-noop", + "rule": "hyphen", + "mode": "text", + "in": "un porta-finestra e un maxi-schermo", + "out": "un porta-finestra e un maxi-schermo", + "note": "Le tre liste di hyphen sono vuote, quindi la regola è un no-op totale e dimostrabile. Composti tratti da Treccani, «Trattino [prontuario]»." + }, + { + "id": "it-nbsp-no-space-before-punctuation", + "rule": "nbsp", + "mode": "text", + "in": "Che cosa dici ? Nulla ! Davvero ; sì : nulla.", + "out": "Che cosa dici? Nulla! Davvero; sì: nulla.", + "note": "IL CASO CHE FISSA LA DIFFERENZA CON IL FRANCESE: spaces elimina lo spazio ordinario prima dei segni e nbsp non lo reinserisce, perché entrambe le liste sono vuote. Lo stesso input in fr produce U+202F prima di ? ! ; e U+00A0 prima di :." + }, + { + "id": "it-nbsp-percent", + "rule": "nbsp", + "mode": "text", + "in": "un aumento del 45 % quest'anno", + "out": "un aumento del 45 % quest’anno", + "note": "N5 beforeUnits: lo spazio diventa U+00A0 (BIPM). L'apostrofo è opera della regola apostrophe, non di nbsp." + }, + { + "id": "it-nbsp-celsius", + "rule": "nbsp", + "mode": "text", + "in": "una temperatura di 20 °C", + "out": "una temperatura di 20 °C", + "note": "Stessa subrregola su «°C», che è U+00B0 seguito da U+0043." + }, + { + "id": "it-nbsp-before-number", + "rule": "nbsp", + "mode": "text", + "in": "il regolamento n. 3600 e cfr. pag. 2064", + "out": "il regolamento n. 3600 e cfr. pag. 2064", + "note": "N9 beforeNumber su «n.» e «pag.». Riga accettata come INFERENZA DICHIARATA e non come citazione piena: il riquadro «Spazi vuoti protetti» del punto 4.2.3 non è marcato come italiano, ma «pag.» è forma italiana. Si noti che «cfr.» non è in elenco e il suo spazio resta U+0020." + }, + { + "id": "it-apostrophe-elision", + "rule": "apostrophe", + "mode": "text", + "in": "un'utopia, un'assurda aspirazione dell'Unione", + "out": "un’utopia, un’assurda aspirazione dell’Unione", + "note": "U+0027 diventa U+2019. Parole tratte dalla prosa del Manuale. La regola non legge dati di locale, ma l'elisione è la forma che il motore incontra più spesso in italiano." + }, + { + "id": "it-roundtrip-noop", + "rule": "quotes", + "mode": "text", + "in": "Ha detto «buongiorno» ed è uscito…", + "out": "Ha detto «buongiorno» ed è uscito…", + "note": "modes.md §4: un documento già composto torna byte per byte." + }, + { + "id": "it-spaces-brackets-and-final-stop", + "rule": "spaces", + "mode": "text", + "in": "Disse ( senza dubbio ) di sì .", + "out": "Disse (senza dubbio) di sì.", + "note": "spaces.md §3: gli spazi interni alle parentesi spariscono e la serie prima del punto finale si riduce. Regola indipendente dalla locale, presente qui perché it abbia un caso per ogni regola canonica." + }, + { + "id": "it-symbols-copyright-and-dimensions", + "rule": "symbols", + "mode": "text", + "in": "Copyright (c) 2026, formato 40x60 cm", + "out": "Copyright © 2026, formato 40×60 cm", + "note": "symbols.md: «(c)» diventa U+00A9 e la «x» fra cifre U+00D7. L'U+00A0 davanti a «cm» è opera di nbsp N5, non di symbols: i due casi stanno insieme per mostrare che le regole si compongono." + } + ] +} diff --git a/vendor/polytypo-spec/fixtures/locale-resolution.json b/vendor/polytypo-spec/fixtures/locale-resolution.json index 60a787d..4c68a20 100644 --- a/vendor/polytypo-spec/fixtures/locale-resolution.json +++ b/vendor/polytypo-spec/fixtures/locale-resolution.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "cases": [ { "id": "exact-en-us", @@ -152,10 +152,10 @@ "note": "section 4: nb must not resolve to the nearest language sv" }, { - "id": "unknown-es", - "tag": "es", + "id": "unknown-ja", + "tag": "ja", "throws": "POLYTYPO_UNKNOWN_LOCALE", - "note": "a language polytypo does not carry yet is an error, not a default" + "note": "a language polytypo does not carry yet is an error, not a default. This case named `es` until spec 1.3.0 added that locale; a fixture asserting a registry member is unknown contradicts section 3.4 step 1 and would fail every runtime the moment the registry was vendored." }, { "id": "invalid-three-letter", @@ -204,6 +204,78 @@ "tag": "en-US-POSIX", "throws": "POLYTYPO_UNKNOWN_LOCALE", "note": "section 3.3: length 11. Section 7 open question 7: region is the only supported variation, so extra subtags are rejected rather than ignored." + }, + { + "id": "exact-es", + "tag": "es", + "resolves": "es", + "note": "section 3.4 step 1. Added with the locale in spec 1.3.0 — the eight locales carried since 1.2.0 had no resolution case at all, so nothing proved a registry member resolved rather than threw." + }, + { + "id": "exact-it", + "tag": "it", + "resolves": "it", + "note": "section 3.4 step 1." + }, + { + "id": "exact-nl", + "tag": "nl", + "resolves": "nl", + "note": "section 3.4 step 1." + }, + { + "id": "exact-pl", + "tag": "pl", + "resolves": "pl", + "note": "section 3.4 step 1." + }, + { + "id": "exact-uk", + "tag": "uk", + "resolves": "uk", + "note": "section 3.4 step 1." + }, + { + "id": "exact-cs", + "tag": "cs", + "resolves": "cs", + "note": "section 3.4 step 1." + }, + { + "id": "exact-pt-pt", + "tag": "pt-PT", + "resolves": "pt-PT", + "note": "section 3.4 step 1: a language+region member is matched exactly, before any stripping." + }, + { + "id": "exact-pt-br", + "tag": "pt-BR", + "resolves": "pt-BR", + "note": "section 3.4 step 1: pt-BR is its own locale, not a region strip of pt-PT." + }, + { + "id": "alias-pt", + "tag": "pt", + "resolves": "pt-PT", + "note": "section 3.4 step 2: the third declared alias, alongside en and de." + }, + { + "id": "strip-es-mx", + "tag": "es-MX", + "resolves": "es", + "note": "section 3.4 step 3a: an unlisted region strips to the base language once." + }, + { + "id": "strip-nl-be", + "tag": "nl-BE", + "resolves": "nl", + "note": "section 3.4 step 3a." + }, + { + "id": "strip-pt-ao", + "tag": "pt-AO", + "resolves": "pt-PT", + "note": "section 3.4 step 3b: the strip lands on an alias key, so the alias is followed — the one path through step 3 that steps 1 and 2 cannot reach." } ] } diff --git a/vendor/polytypo-spec/fixtures/nl.json b/vendor/polytypo-spec/fixtures/nl.json new file mode 100644 index 0000000..4118036 --- /dev/null +++ b/vendor/polytypo-spec/fixtures/nl.json @@ -0,0 +1,121 @@ +{ + "spec": "1.3.0", + "locale": "nl", + "cases": [ + { + "id": "nl-quotes-primary", + "rule": "quotes", + "mode": "text", + "in": "Hij zei \"dag\" en vertrok.", + "out": "Hij zei “dag” en vertrok.", + "note": "quotes.primary = U+201C/U+201D. De Taalunie rangschikt de vormen NIET («Er zijn geen vaste regels»); de keuze is een beslissing van de operator, vastgelegd in de sources-ingang, en volgt de variant die de Taalunie «traditioneel» aan het letterlijke citaat verbindt." + }, + { + "id": "nl-quotes-nested", + "rule": "quotes", + "mode": "text", + "in": "De koning zei: \"Ik hoorde iemand 'hoera' roepen.\"", + "out": "De koning zei: “Ik hoorde iemand ‘hoera’ roepen.”", + "note": "Voorbeeld (4a) van de Taalunie zelf: dubbele tekens op het eerste niveau, enkele op het tweede." + }, + { + "id": "nl-quotes-apostrophe-not-a-quote", + "rule": "apostrophe", + "mode": "text", + "in": "Hij kocht twee auto's.", + "out": "Hij kocht twee auto’s.", + "note": "Het Nederlands staat vol apostroffen (auto's, 's-Hertogenbosch, A4'tje) en die worden U+2019 — hetzelfde codepunt als het sluitende enkele aanhalingsteken. Gecontroleerd vóór de keuze van de aanhalingstekens: het maakt voor deze zinnen geen verschil welke variant het eerste niveau krijgt." + }, + { + "id": "nl-dashes-parenthetical", + "rule": "dashes", + "mode": "text", + "in": "Het nieuws - volgens de kranten - is niet bekend.", + "out": "Het nieuws – volgens de kranten – is niet bekend.", + "note": "dash.parenthetical = «en-spaced»: het halve kastlijntje U+2013 met een spatie aan weerszijden, precies het voorbeeld van de Taalunie." + }, + { + "id": "nl-dashes-already-correct", + "rule": "dashes", + "mode": "text", + "in": "Het nieuws – volgens de kranten – is niet bekend.", + "out": "Het nieuws – volgens de kranten – is niet bekend.", + "note": "dashes.md §3.4 P5 laat een reeks van precies één U+2013 met rust, dus correct gezet Nederlands blijft ongemoeid." + }, + { + "id": "nl-ranges-hyphen-kept", + "rule": "ranges", + "mode": "text", + "rules": { + "ranges": true + }, + "in": "de categorie 30-45 jaar", + "out": "de categorie 30-45 jaar", + "note": "ranges.md §2: met dash.range = «none» emitteert de regel niets — ook niet de U+2060 die een omgezet bereik in andere locales meekrijgt. Het Nederlandse bereikteken is het koppelteken U+002D dat er al staat (Onze Taal: «1940-1945, de categorie 30-45 jaar»). Het geval draait met ranges expliciet aan, want de regel staat standaard uit." + }, + { + "id": "nl-ellipsis-three-dots", + "rule": "ellipsis", + "mode": "text", + "in": "Hou je van jazz, blues, soul ...?", + "out": "Hou je van jazz, blues, soul …?", + "note": "Het voorbeeld van de Taalunie zelf. Let op de spatie VÓÓR het beletselteken: die hoort in het Nederlands en spaces.md §3.4 laat hem in elk locale staan — hier zijn bron en motor het eens." + }, + { + "id": "nl-hyphen-noop", + "rule": "hyphen", + "mode": "text", + "in": "een auto-ongeluk en mee-eten", + "out": "een auto-ongeluk en mee-eten", + "note": "hyphen.md §2: drie lege lijsten, dus een aantoonbare no-op. Bij afbreking valt het Nederlandse koppelteken juist wég, het omgekeerde van een claim op U+2011." + }, + { + "id": "nl-nbsp-currency", + "rule": "nbsp", + "mode": "text", + "in": "De vaas kostte € 179.", + "out": "De vaas kostte € 179.", + "note": "N6 afterSymbols: in het Nederlands gaat het valutateken aan het getal VOORAF, dus het hoort in afterSymbols en niet in beforeUnits zoals in fr, waar «2 €» geschreven wordt." + }, + { + "id": "nl-nbsp-unit", + "rule": "nbsp", + "mode": "text", + "in": "De afstand was 15 cm.", + "out": "De afstand was 15 cm.", + "note": "N5 beforeUnits, voorbeeld (28) van de Taalunie." + }, + { + "id": "nl-nbsp-compound-untouched", + "rule": "nbsp", + "mode": "text", + "in": "Ze hanteerde de 15cm-norm.", + "out": "Ze hanteerde de 15cm-norm.", + "note": "Voorbeeld (29) van dezelfde pagina: in een samenstelling staat geen spatie. N5 zet alleen een bestaande spatie om en voegt er nooit een in, dus de samenstelling is veilig." + }, + { + "id": "nl-nbsp-abbreviation", + "rule": "nbsp", + "mode": "text", + "in": "prof. dr. Jansen", + "out": "prof. dr. Jansen", + "note": "N4 abbreviations op «prof. dr.». De spatie vóór de achternaam blijft gewoon: beforeWord is leeg, en initialBinding is «none»." + }, + { + "id": "nl-spaces-brackets-and-final-stop", + "rule": "spaces", + "mode": "text", + "in": "De tekst ( gewoon ) verandert niet .", + "out": "De tekst (gewoon) verandert niet.", + "note": "spaces.md §3: locale-onafhankelijke regel, hier aanwezig zodat nl voor elke canonieke regel een geval heeft." + }, + { + "id": "nl-symbols-copyright-and-dimensions", + "rule": "symbols", + "mode": "text", + "in": "Copyright (c) 2026, formaat 40x60 cm", + "out": "Copyright © 2026, formaat 40×60 cm", + "note": "symbols.md: «(c)» wordt U+00A9 en de «x» tussen cijfers U+00D7. De U+00A0 vóór «cm» is het werk van nbsp N5." + } + ] +} diff --git a/vendor/polytypo-spec/fixtures/pl.json b/vendor/polytypo-spec/fixtures/pl.json new file mode 100644 index 0000000..592a450 --- /dev/null +++ b/vendor/polytypo-spec/fixtures/pl.json @@ -0,0 +1,137 @@ +{ + "spec": "1.3.0", + "locale": "pl", + "cases": [ + { + "id": "pl-quotes-primary", + "rule": "quotes", + "mode": "text", + "in": "Powiedział \"dzień dobry\".", + "out": "Powiedział „dzień dobry”.", + "note": "quotes.primary = U+201E otwierający i U+201D zamykający (PWN, Zasady, §98). Uwaga: zamykający to U+201D, nie U+201C jak w niemieckim — różnica w składzie prawie niewidoczna, dlatego fixture." + }, + { + "id": "pl-quotes-nested", + "rule": "quotes", + "mode": "text", + "in": "Powiedział \"cytat 'w cytacie' koniec\".", + "out": "Powiedział „cytat »w cytacie« koniec”.", + "note": "Drugi stopień to para o ostrzach skierowanych do środka: U+00BB otwierający, U+00AB zamykający — kierunek odwrotny niż francuski. W tym samym przypadku widać N3: jednoliterowe «w» wiąże się z następnym wyrazem przez U+00A0 (afterShortWords)." + }, + { + "id": "pl-dashes-parenthetical", + "rule": "dashes", + "mode": "text", + "in": "Wtrącenie - tak jest - kończy zdanie.", + "out": "Wtrącenie – tak jest – kończy zdanie.", + "note": "dash.parenthetical = «en-spaced»: półpauza U+2013 ze spacjami po obu stronach. Wybór długości kreski jest decyzją operatora (18.09.2026) — PWN normuje odstępy, nie długość; zob. wpis sources." + }, + { + "id": "pl-dashes-already-correct", + "rule": "dashes", + "mode": "text", + "in": "Wtrącenie – tak jest – kończy zdanie.", + "out": "Wtrącenie – tak jest – kończy zdanie.", + "note": "dashes.md §3.4 P5 odrzuca ciąg dokładnie jednej U+2013, więc tekst już złożony półpauzą pozostaje nietknięty. To jest ta połowa decyzji o «en-spaced», która nic nie psuje w istniejących tekstach." + }, + { + "id": "pl-ranges-en-tight", + "rule": "ranges", + "mode": "text", + "rules": { + "ranges": true + }, + "in": "W latach 1756-1763 toczyła się wojna.", + "out": "W latach 1756⁠–⁠1763 toczyła się wojna.", + "note": "ranges.md §3: dash.range = «en-tight» daje półpauzę bez spacji, owiniętą w U+2060 (łączniki wyrazów), zgodnie z [408] UWAGA: «1914–1918». Wielka litera «W» wiąże się przez N3, bo dopasowanie pierwszej litery jest niewrażliwe na wielkość." + }, + { + "id": "pl-ellipsis-three-dots", + "rule": "ellipsis", + "mode": "text", + "in": "Czekaj... co?", + "out": "Czekaj… co?", + "note": "ellipsis.md §6: trzy U+002E stają się U+2026." + }, + { + "id": "pl-ellipsis-before-terminal", + "rule": "ellipsis", + "mode": "text", + "in": "Jak strasznie gorąco…!", + "out": "Jak strasznie gorąco…!", + "note": "[396] 92.4: wykrzyknik stoi PO wielokropku i oba się zachowują. abbreviatedAfterTerminal = false, więc rosyjska forma dwukropkowa nie powstaje." + }, + { + "id": "pl-hyphen-noop", + "rule": "hyphen", + "mode": "text", + "in": "biało-czerwona flaga", + "out": "biało-czerwona flaga", + "note": "hyphen.md §2: trzy puste listy czynią regułę dowodliwym no-opem. [196] każe dzielić wiersz w miejscu łącznika, czyli dokładnie odwrotnie niż U+2011." + }, + { + "id": "pl-nbsp-short-words", + "rule": "nbsp", + "mode": "text", + "in": "Mieszkam w Warszawie i pracuję.", + "out": "Mieszkam w Warszawie i pracuję.", + "note": "N3 afterShortWords: jednoliterowe przyimki i spójniki (a, i, o, u, w, z) nie zostają na końcu wiersza. Podstawa doradcza (Wolański), przyjęta decyzją operatora 18.09.2026 — «Zasady» [204] są łagodniejsze i uzależniają regułę od szerokości łamu, czego silnik nie widzi." + }, + { + "id": "pl-nbsp-paragraph-sign", + "rule": "nbsp", + "mode": "text", + "in": "Zgodnie z § 5 ustawy.", + "out": "Zgodnie z § 5 ustawy.", + "note": "Dwie subreguły w jednym zdaniu. N6 wiąże «§» z cyfrą (afterSymbols). N3 NIE wiąże «z», bo po nim stoi «§», które nie należy ani do ALNUM, ani do OPENISH (nbsp.md §3.5 krok 4) — przypadek istnieje właśnie po to, żeby to pokazać." + }, + { + "id": "pl-nbsp-unit", + "rule": "nbsp", + "mode": "text", + "in": "Waży 5 kg.", + "out": "Waży 5 kg.", + "note": "N5 beforeUnits: istniejąca spacja staje się U+00A0." + }, + { + "id": "pl-nbsp-unit-tight-untouched", + "rule": "nbsp", + "mode": "text", + "in": "Wzrost o 5%.", + "out": "Wzrost o 5%.", + "note": "N5 nigdy nie WSTAWIA spacji, więc «5%» — forma zgodna z polską tradycją ortotypograficzną — zostaje nietknięta, mimo że «%» jest na liście. Wiąże się natomiast «o» przez N3. Ten przypadek pokazuje, że jedna lista obsługuje obie poświadczone formy («5 %» i «5%»)." + }, + { + "id": "pl-nbsp-abbreviation", + "rule": "nbsp", + "mode": "text", + "in": "lek. med. Kowalski", + "out": "lek. med. Kowalski", + "note": "N4 abbreviations: wewnętrzna spacja skrótu wielowyrazowego staje się U+00A0 (21.1.3). Spacja przed nazwiskiem pozostaje zwykła — beforeWord jest puste." + }, + { + "id": "pl-spaces-brackets-and-final-stop", + "rule": "spaces", + "mode": "text", + "in": "Tekst ( bieżący ) nie zmienia się .", + "out": "Tekst (bieżący) nie zmienia się.", + "note": "spaces.md §3: reguła niezależna od locale, obecna po to, by pl miało przypadek dla każdej reguły kanonicznej." + }, + { + "id": "pl-symbols-copyright-and-dimensions", + "rule": "symbols", + "mode": "text", + "in": "Copyright (c) 2026, format 40x60 cm", + "out": "Copyright © 2026, format 40×60 cm", + "note": "symbols.md: «(c)» staje się U+00A9, a «x» między cyframi U+00D7. U+00A0 przed «cm» to robota nbsp N5, nie symbols." + }, + { + "id": "pl-apostrophe-foreign-name", + "rule": "apostrophe", + "mode": "text", + "in": "d'Artagnan", + "out": "d’Artagnan", + "note": "U+0027 staje się U+2019. Reguła nie czyta danych locale; przypadek ją dla polskiego poświadcza." + } + ] +} diff --git a/vendor/polytypo-spec/fixtures/pt-BR.json b/vendor/polytypo-spec/fixtures/pt-BR.json new file mode 100644 index 0000000..3540472 --- /dev/null +++ b/vendor/polytypo-spec/fixtures/pt-BR.json @@ -0,0 +1,156 @@ +{ + "spec": "1.3.0", + "locale": "pt-BR", + "cases": [ + { + "id": "pt-br-quotes-primary", + "rule": "quotes", + "mode": "text", + "in": "Ele disse \"bom dia\" e saiu.", + "out": "Ele disse “bom dia” e saiu.", + "note": "quotes.primary com innerSpace \"none\". O uso brasileiro atestado pelo Manual de Redação da Presidência da República compõe as citações com aspas curvas duplas e nunca com angulares. É a diferença central em relação a pt-PT." + }, + { + "id": "pt-br-quotes-nested", + "rule": "quotes", + "mode": "text", + "in": "Escreveu: \"Disse-me 'chego já' e desapareceu.\"", + "out": "Escreveu: “Disse-me ‘chego já’ e desapareceu.”", + "note": "Primeiro e segundo níveis de aspas. O terceiro nível que as fontes descrevem não é exprimível no esquema, que só tem primary e secondary." + }, + { + "id": "pt-br-dashes-parenthetical", + "rule": "dashes", + "mode": "text", + "in": "As condições - ordenado e subvenções - eram boas.", + "out": "As condições – ordenado e subvenções – eram boas.", + "note": "dash.parenthetical = \"en-spaced\": o travessão substitui parênteses e leva um espaço ordinário de cada lado. A largura foi verificada extraindo a camada de texto do PDF da fonte, não julgada a olho sobre a página rasterizada." + }, + { + "id": "pt-br-ranges-hyphen-kept", + "rule": "ranges", + "mode": "text", + "rules": { + "ranges": true + }, + "in": "o programa para 1996-1997", + "out": "o programa para 1996-1997", + "note": "ranges.md §2: com dash.range = \"none\" a regra não emite nada — nem sequer os U+2060 que um intervalo convertido carrega noutras locales — e o U+002D escrito pelo autor sobrevive byte a byte." + }, + { + "id": "pt-br-ranges-slash-untouched", + "rule": "ranges", + "mode": "text", + "rules": { + "ranges": true + }, + "in": "o ano letivo de 1990/1991", + "out": "o ano letivo de 1990/1991", + "note": "ranges.md §3: a barra não é um token de intervalo para esta regra. Fica fixado que o outro ramo da convenção portuguesa — período que não abrange os dois anos completos — também não é tocado." + }, + { + "id": "pt-br-ellipsis-three-dots", + "rule": "ellipsis", + "mode": "text", + "in": "Espere... o quê?", + "out": "Espere… o quê?", + "note": "ellipsis.md §6: três U+002E passam a U+2026. Nada acontece antes de «?», porque beforePunctuation e narrowBeforePunctuation estão vazios — ao contrário de fr." + }, + { + "id": "pt-br-ellipsis-not-abbreviated-after-terminal", + "rule": "ellipsis", + "mode": "text", + "in": "É o dianho!..", + "out": "É o dianho!…", + "note": "abbreviatedAfterTerminal = false: a forma abreviada de dois pontos que o russo usa não existe em português, pelo que «!..» é um lapso por «!…». A fonte europeia imprime exatamente «É o dianho!…»." + }, + { + "id": "pt-br-hyphen-noop-compounds", + "rule": "hyphen", + "mode": "text", + "in": "Uma reunião na segunda-feira sobre o salmão-do-atlântico.", + "out": "Uma reunião na segunda-feira sobre o salmão-do-atlântico.", + "note": "hyphen.md §2: as três listas estão vazias porque o Acordo Ortográfico (Base XX) manda QUEBRAR a linha no hífen do composto e repeti-lo na linha seguinte. Um port que ligue compostos portugueses com U+2011 falha este caso." + }, + { + "id": "pt-br-hyphen-noop-enclisis", + "rule": "hyphen", + "mode": "text", + "in": "far-se-á e exigem-lhe", + "out": "far-se-á e exigem-lhe", + "note": "Ênclise e mesóclise, exemplos literais do Manual de Redação da Presidência da República, que prescreve a mesma repetição do hífen na translineação." + }, + { + "id": "pt-br-nbsp-percent", + "rule": "nbsp", + "mode": "text", + "in": "7 % do volume de negócios", + "out": "7 % do volume de negócios", + "note": "N5 converte um espaço já escrito. O português escreve «7 %» com espaço, ao contrário do grego, que o escreve colado." + }, + { + "id": "pt-br-nbsp-celsius", + "rule": "nbsp", + "mode": "text", + "in": "a temperatura atingiu hoje os 39 °C", + "out": "a temperatura atingiu hoje os 39 °C", + "note": "Exemplo literal do ponto 10.9.1 do Código de Redação Interinstitucional." + }, + { + "id": "pt-br-nbsp-hour-is-not-a-unit", + "rule": "nbsp", + "mode": "text", + "in": "eram as 18h30", + "out": "eram as 18h30", + "note": "O reparo citado: «h» escreve-se «sempre sem ponto, sem espaços» (ponto 10.9.1), pelo que está deliberadamente ausente de beforeUnits. Este caso fixa essa ausência para que ninguém a preencha por analogia." + }, + { + "id": "pt-br-nbsp-abbreviation", + "rule": "nbsp", + "mode": "text", + "in": "p. ex. isto", + "out": "p. ex. isto", + "note": "N4 liga o espaço interno da abreviatura listada «p. ex.», que o anexo A3 manda preferir a «e. g.»." + }, + { + "id": "pt-br-nbsp-before-number", + "rule": "nbsp", + "mode": "text", + "in": "ver p. 24", + "out": "ver p. 24", + "note": "N9: «p. 24» é o exemplo impresso. «n.º» NÃO está na lista, e por citação e não por esquecimento — a nota (3) do ponto 6.4 prescreve um «o» sobrescrito e recusa expressamente U+00BA e U+00B0." + }, + { + "id": "pt-br-nbsp-no-space-before-colon", + "rule": "nbsp", + "mode": "text", + "in": "As principais cidades de Portugal são: Lisboa, Porto e Coimbra.", + "out": "As principais cidades de Portugal são: Lisboa, Porto e Coimbra.", + "note": "beforePunctuation e narrowBeforePunctuation vazios: nada é inserido antes de «:». Frase literal do ponto 10.4.4. Um port que aplique a prática francesa a todas as locales falha aqui." + }, + { + "id": "pt-br-spaces-brackets-and-final-stop", + "rule": "spaces", + "mode": "text", + "in": "O texto ( corrente ) não muda .", + "out": "O texto (corrente) não muda.", + "note": "spaces.md §3: os espaços interiores dos parênteses desaparecem e a série anterior ao ponto final reduz-se. Regra independente da locale, presente para que esta tenha um caso por cada regra canónica." + }, + { + "id": "pt-br-symbols-copyright-and-dimensions", + "rule": "symbols", + "mode": "text", + "in": "Copyright (c) 2026, formato 40x60 cm", + "out": "Copyright © 2026, formato 40×60 cm", + "note": "symbols.md: «(c)» passa a U+00A9 e o «x» entre algarismos a U+00D7. O U+00A0 antes de «cm» é obra de nbsp N5, não de symbols." + }, + { + "id": "pt-br-apostrophe-elision", + "rule": "apostrophe", + "mode": "text", + "in": "pinga d'água", + "out": "pinga d’água", + "note": "U+0027 passa a U+2019. A regra não lê dados de locale; o caso certifica-a para esta locale." + } + ] +} diff --git a/vendor/polytypo-spec/fixtures/pt-PT.json b/vendor/polytypo-spec/fixtures/pt-PT.json new file mode 100644 index 0000000..65c35e2 --- /dev/null +++ b/vendor/polytypo-spec/fixtures/pt-PT.json @@ -0,0 +1,156 @@ +{ + "spec": "1.3.0", + "locale": "pt-PT", + "cases": [ + { + "id": "pt-pt-quotes-primary", + "rule": "quotes", + "mode": "text", + "in": "Ele disse \"bom dia\" e saiu.", + "out": "Ele disse «bom dia» e saiu.", + "note": "quotes.primary com innerSpace \"none\". O primeiro nível é o das aspas angulares (ponto 10.4.10 do Código de Redação Interinstitucional). É a diferença central em relação a pt-BR, que usa aspas curvas duplas." + }, + { + "id": "pt-pt-quotes-nested", + "rule": "quotes", + "mode": "text", + "in": "Escreveu: \"Disse-me 'chego já' e desapareceu.\"", + "out": "Escreveu: «Disse-me “chego já” e desapareceu.»", + "note": "Primeiro e segundo níveis de aspas. O terceiro nível que as fontes descrevem não é exprimível no esquema, que só tem primary e secondary." + }, + { + "id": "pt-pt-dashes-parenthetical", + "rule": "dashes", + "mode": "text", + "in": "As condições - ordenado e subvenções - eram boas.", + "out": "As condições — ordenado e subvenções — eram boas.", + "note": "dash.parenthetical = \"em-spaced\": o travessão substitui parênteses e leva um espaço ordinário de cada lado. A largura foi verificada extraindo a camada de texto do PDF da fonte, não julgada a olho sobre a página rasterizada." + }, + { + "id": "pt-pt-ranges-hyphen-kept", + "rule": "ranges", + "mode": "text", + "rules": { + "ranges": true + }, + "in": "o programa para 1996-1997", + "out": "o programa para 1996-1997", + "note": "ranges.md §2: com dash.range = \"none\" a regra não emite nada — nem sequer os U+2060 que um intervalo convertido carrega noutras locales — e o U+002D escrito pelo autor sobrevive byte a byte." + }, + { + "id": "pt-pt-ranges-slash-untouched", + "rule": "ranges", + "mode": "text", + "rules": { + "ranges": true + }, + "in": "o ano letivo de 1990/1991", + "out": "o ano letivo de 1990/1991", + "note": "ranges.md §3: a barra não é um token de intervalo para esta regra. Fica fixado que o outro ramo da convenção portuguesa — período que não abrange os dois anos completos — também não é tocado." + }, + { + "id": "pt-pt-ellipsis-three-dots", + "rule": "ellipsis", + "mode": "text", + "in": "Espere... o quê?", + "out": "Espere… o quê?", + "note": "ellipsis.md §6: três U+002E passam a U+2026. Nada acontece antes de «?», porque beforePunctuation e narrowBeforePunctuation estão vazios — ao contrário de fr." + }, + { + "id": "pt-pt-ellipsis-not-abbreviated-after-terminal", + "rule": "ellipsis", + "mode": "text", + "in": "É o dianho!..", + "out": "É o dianho!…", + "note": "abbreviatedAfterTerminal = false: a forma abreviada de dois pontos que o russo usa não existe em português, pelo que «!..» é um lapso por «!…». A fonte europeia imprime exatamente «É o dianho!…»." + }, + { + "id": "pt-pt-hyphen-noop-compounds", + "rule": "hyphen", + "mode": "text", + "in": "Uma reunião na segunda-feira sobre o salmão-do-atlântico.", + "out": "Uma reunião na segunda-feira sobre o salmão-do-atlântico.", + "note": "hyphen.md §2: as três listas estão vazias porque o Acordo Ortográfico (Base XX) manda QUEBRAR a linha no hífen do composto e repeti-lo na linha seguinte. Um port que ligue compostos portugueses com U+2011 falha este caso." + }, + { + "id": "pt-pt-hyphen-noop-enclisis", + "rule": "hyphen", + "mode": "text", + "in": "far-se-á e exigem-lhe", + "out": "far-se-á e exigem-lhe", + "note": "Ênclise e mesóclise, exemplos literais do Manual de Redação da Presidência da República, que prescreve a mesma repetição do hífen na translineação." + }, + { + "id": "pt-pt-nbsp-percent", + "rule": "nbsp", + "mode": "text", + "in": "7 % do volume de negócios", + "out": "7 % do volume de negócios", + "note": "N5 converte um espaço já escrito. O português escreve «7 %» com espaço, ao contrário do grego, que o escreve colado." + }, + { + "id": "pt-pt-nbsp-celsius", + "rule": "nbsp", + "mode": "text", + "in": "a temperatura atingiu hoje os 39 °C", + "out": "a temperatura atingiu hoje os 39 °C", + "note": "Exemplo literal do ponto 10.9.1 do Código de Redação Interinstitucional." + }, + { + "id": "pt-pt-nbsp-hour-is-not-a-unit", + "rule": "nbsp", + "mode": "text", + "in": "eram as 18h30", + "out": "eram as 18h30", + "note": "O reparo citado: «h» escreve-se «sempre sem ponto, sem espaços» (ponto 10.9.1), pelo que está deliberadamente ausente de beforeUnits. Este caso fixa essa ausência para que ninguém a preencha por analogia." + }, + { + "id": "pt-pt-nbsp-abbreviation", + "rule": "nbsp", + "mode": "text", + "in": "p. ex. isto", + "out": "p. ex. isto", + "note": "N4 liga o espaço interno da abreviatura listada «p. ex.», que o anexo A3 manda preferir a «e. g.»." + }, + { + "id": "pt-pt-nbsp-before-number", + "rule": "nbsp", + "mode": "text", + "in": "ver p. 24", + "out": "ver p. 24", + "note": "N9: «p. 24» é o exemplo impresso. «n.º» NÃO está na lista, e por citação e não por esquecimento — a nota (3) do ponto 6.4 prescreve um «o» sobrescrito e recusa expressamente U+00BA e U+00B0." + }, + { + "id": "pt-pt-nbsp-no-space-before-colon", + "rule": "nbsp", + "mode": "text", + "in": "As principais cidades de Portugal são: Lisboa, Porto e Coimbra.", + "out": "As principais cidades de Portugal são: Lisboa, Porto e Coimbra.", + "note": "beforePunctuation e narrowBeforePunctuation vazios: nada é inserido antes de «:». Frase literal do ponto 10.4.4. Um port que aplique a prática francesa a todas as locales falha aqui." + }, + { + "id": "pt-pt-spaces-brackets-and-final-stop", + "rule": "spaces", + "mode": "text", + "in": "O texto ( corrente ) não muda .", + "out": "O texto (corrente) não muda.", + "note": "spaces.md §3: os espaços interiores dos parênteses desaparecem e a série anterior ao ponto final reduz-se. Regra independente da locale, presente para que esta tenha um caso por cada regra canónica." + }, + { + "id": "pt-pt-symbols-copyright-and-dimensions", + "rule": "symbols", + "mode": "text", + "in": "Copyright (c) 2026, formato 40x60 cm", + "out": "Copyright © 2026, formato 40×60 cm", + "note": "symbols.md: «(c)» passa a U+00A9 e o «x» entre algarismos a U+00D7. O U+00A0 antes de «cm» é obra de nbsp N5, não de symbols." + }, + { + "id": "pt-pt-apostrophe-elision", + "rule": "apostrophe", + "mode": "text", + "in": "pinga d'água", + "out": "pinga d’água", + "note": "U+0027 passa a U+2019. A regra não lê dados de locale; o caso certifica-a para esta locale." + } + ] +} diff --git a/vendor/polytypo-spec/fixtures/ru.json b/vendor/polytypo-spec/fixtures/ru.json index e6677b1..cc85689 100644 --- a/vendor/polytypo-spec/fixtures/ru.json +++ b/vendor/polytypo-spec/fixtures/ru.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "ru", "cases": [ { @@ -715,6 +715,28 @@ "in": "Он живёт в Москве", "out": "Он живёт в Москве", "note": "nbsp.md §3.1, §7 item 12 (spec 1.2.0); modes.md §3.3: the −1 span boundary marker is not in `nbsp`'s OPENISH, so N3's following-token guard does not accept it and the space after `в` stays U+0020. This pins the membership split itself: a port that also put the marker in OPENISH would bind here." + }, + { + "id": "ru-ranges-closed-up-percent", + "rule": "ranges", + "mode": "text", + "in": "35%-50%", + "out": "35%⁠—⁠50%", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a (spec 1.3.0): the suffix form in a locale whose `dash.range` is em-tight, so the same token produces U+2014 here and U+2013 in `en-US`. The closed-up walk decides candidacy; the locale still decides the glyph." + }, + { + "id": "ru-dashes-t1-closed-up-symbol-suffix", + "rule": "dashes", + "mode": "text", + "in": "35%-50%—b", + "out": "35%-50%—b", + "rules": { + "ranges": true + }, + "note": "ranges.md §3.2a, via dashes.md §3.2 step 8 (spec 1.3.0): the same witness in the suffix direction and in an em-dash locale — the disturbed guard is the range's `after` rather than its `before`. Pinned separately because the two directions are separate code paths in every port. To be precise about \"before the amendment\": the drift is a property of the INTERMEDIATE state — ranges.md §3.2a's widened candidacy without T1's transparency — which never shipped. Under spec 1.2.0 this input was stable, because the token was not a range candidate at all." } ] } diff --git a/vendor/polytypo-spec/fixtures/sv.json b/vendor/polytypo-spec/fixtures/sv.json index 95a9748..8dcbed0 100644 --- a/vendor/polytypo-spec/fixtures/sv.json +++ b/vendor/polytypo-spec/fixtures/sv.json @@ -1,5 +1,5 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "locale": "sv", "cases": [ { diff --git a/vendor/polytypo-spec/fixtures/uk.json b/vendor/polytypo-spec/fixtures/uk.json new file mode 100644 index 0000000..a5063e0 --- /dev/null +++ b/vendor/polytypo-spec/fixtures/uk.json @@ -0,0 +1,153 @@ +{ + "spec": "1.3.0", + "locale": "uk", + "cases": [ + { + "id": "uk-quotes-primary", + "rule": "quotes", + "mode": "text", + "in": "Він сказав: \"Це мій Кобзар\".", + "out": "Він сказав: «Це мій Кобзар».", + "note": "§ 164 п. 3 правопису: зовнішні лапки — «ялинки» U+00AB/U+00BB, innerSpace = none." + }, + { + "id": "uk-quotes-nested", + "rule": "quotes", + "mode": "text", + "in": "\"Це мій 'Кобзар'\", — сказав він.", + "out": "«Це мій “Кобзар”», — сказав він.", + "note": "Приклад із самого § 164 п. 3. Внутрішні лапки — U+201C/U+201D, а НЕ „…“: останню той-таки пункт відносить до рукописних текстів. Фікстура існує саме для того, щоб форму не «виправили» на російську за аналогією." + }, + { + "id": "uk-ellipsis-abbreviated-after-question", + "rule": "ellipsis", + "mode": "text", + "in": "а щоб селяни?...", + "out": "а щоб селяни?..", + "note": "abbreviatedAfterTerminal = true. § 162, Примітка: після знака питання ставимо ДВІ крапки. Приклад із того ж параграфа (К. Гордієнко). Українська — друга після російської локаль із цим значенням." + }, + { + "id": "uk-ellipsis-abbreviated-after-exclamation", + "rule": "ellipsis", + "mode": "text", + "in": "Рокочуть ріки ясноводі!...", + "out": "Рокочуть ріки ясноводі!..", + "note": "Другий приклад тієї самої Примітки (М. Рильський): після знака оклику так само дві крапки." + }, + { + "id": "uk-ellipsis-ordinary", + "rule": "ellipsis", + "mode": "text", + "in": "Літак... Димки...", + "out": "Літак… Димки…", + "note": "Поза постпозицією до ?/! три крапки стають U+2026, як в усіх локалях." + }, + { + "id": "uk-dashes-parenthetical", + "rule": "dashes", + "mode": "text", + "in": "Це - наш дім.", + "out": "Це — наш дім.", + "note": "dash.parenthetical = em-spaced: U+2014 з відбивкою. Довжина з заголовка § 161 «ТИРЕ (—)»; відбивка — з протиставлення в Примітці п. 14, і це в файлі позначено як висновок, а не як цитата." + }, + { + "id": "uk-ranges-em-tight", + "rule": "ranges", + "mode": "text", + "rules": { + "ranges": true + }, + "in": "на сторінках 1-10", + "out": "на сторінках 1⁠—⁠10", + "note": "ranges.md §3: dash.range = em-tight дає U+2014 без відступів, загорнуте в U+2060. Приклад із § 161 I п. 14, Примітка: «на сторінках 1—10»." + }, + { + "id": "uk-hyphen-compound-preposition", + "rule": "hyphen", + "mode": "text", + "in": "з-під столу і будь-хто", + "out": "з‑під столу і будь‑хто", + "note": "hyphen: складений прийменник (§ 42 п. 2) і частка (§ 44 п. 3) зв'язуються через U+2011. Для ЦИХ класів нерозривність — рішення проєкту, а не норма: §§ 63—64 про них мовчать. Пор. наступний випадок, де норма пряма." + }, + { + "id": "uk-hyphen-graphic-shortening", + "rule": "hyphen", + "mode": "text", + "in": "вид-во та ін-т", + "out": "вид‑во та ін‑т", + "note": "Тут нерозривність САМА Є НОРМОЮ: § 64 п. 4 прямо забороняє розривати графічні скорочення, а § 62 п. 2 закриває клас переліком. Цим українська відрізняється від польської, де поділ у місці дефіса приписаний." + }, + { + "id": "uk-nbsp-units-and-year", + "rule": "nbsp", + "mode": "text", + "in": "150 га і 2008 р.", + "out": "150 га і 2008 р.", + "note": "N5: обидва приклади дослівні з § 64 п. 2. «р.» безпечне там, де російське «г.» не було: українське «р.» означає тільки «рік» і зв'язується вліво." + }, + { + "id": "uk-nbsp-initials-chain", + "rule": "nbsp", + "mode": "text", + "in": "Т. Г. Шевченко", + "out": "Т. Г. Шевченко", + "note": "initialBinding = chain, приклад із § 64 п. 1. Значення взято з того, що пункт наводить послідовність ДВОХ ініціалів і не дає прикладу одного." + }, + { + "id": "uk-nbsp-before-word", + "rule": "nbsp", + "mode": "text", + "in": "проф. Гончаренко", + "out": "проф. Гончаренко", + "note": "N10 beforeWord із § 64 п. 1. «п.» і «гр.» з того самого пункту свідомо НЕ внесено: «п.» — також «пункт», «гр.» — також «градус»." + }, + { + "id": "uk-nbsp-abbreviation", + "rule": "nbsp", + "mode": "text", + "in": "і т. д.", + "out": "і т. д.", + "note": "N4: обидва внутрішні пробіли скорочення стають U+00A0 (§ 64 п. 4). Колізії з N3 немає, бо afterShortWords для української порожній." + }, + { + "id": "uk-nbsp-short-word-inert", + "rule": "nbsp", + "mode": "text", + "in": "у Києві", + "out": "у Києві", + "note": "НЕГАТИВНА ФІКСТУРА, і вона тут найважливіша. afterShortWords порожній: § 64 — закритий перелік із п'яти пунктів, і правила про однобуквені прийменники в ньому немає. Випадок стоїть на сторожі, щоб список із ru.json не перенесли сюди за аналогією спорідненої мови." + }, + { + "id": "uk-nbsp-percent", + "rule": "nbsp", + "mode": "text", + "in": "зростання на 5 %", + "out": "зростання на 5 %", + "note": "«%» внесено як РІШЕННЯ, а не як цитата: його немає ні в § 62, ні в § 64, ні в скороченому викладі BIPM, але відбивка відсотка є в усіх інших локалях проєкту. Див. запис sources." + }, + { + "id": "uk-spaces-brackets-and-final-stop", + "rule": "spaces", + "mode": "text", + "in": "Текст ( поточний ) не змінюється .", + "out": "Текст (поточний) не змінюється.", + "note": "spaces.md §3: правило не залежить від локалі, випадок потрібен, щоб uk мала по кейсу на кожне канонічне правило." + }, + { + "id": "uk-symbols-copyright-and-dimensions", + "rule": "symbols", + "mode": "text", + "in": "Copyright (c) 2026, формат 40x60 см", + "out": "Copyright © 2026, формат 40×60 см", + "note": "symbols.md: «(c)» стає U+00A9, «x» між цифрами — U+00D7. U+00A0 перед «см» ставить nbsp N5." + }, + { + "id": "uk-apostrophe-orthographic", + "rule": "apostrophe", + "mode": "text", + "in": "п'ять об'єктів", + "out": "п’ять об’єктів", + "note": "ВАЖЛИВИЙ ВИПАДОК для української, і перевірений на рушії, а не припущений: апостроф у «п'ять», «об'єкт» — частина орфографії слова, а не пунктуація, і правило apostrophe перетворює прямий U+0027 на U+2019 саме там, де він і має бути в друкованому тексті. Спершу цей випадок був написаний як no-op — рушій показав протилежне, і показав правильно." + } + ] +} diff --git a/vendor/polytypo-spec/locales/cs.json b/vendor/polytypo-spec/locales/cs.json new file mode 100644 index 0000000..24db0ba --- /dev/null +++ b/vendor/polytypo-spec/locales/cs.json @@ -0,0 +1,90 @@ +{ + "locale": "cs", + "name": "Czech", + "quotes": { + "primary": { + "open": "„", + "close": "“", + "innerSpace": "none" + }, + "secondary": { + "open": "‚", + "close": "‘", + "innerSpace": "none" + }, + "elisionIdioms": [] + }, + "dash": { + "parenthetical": "en-spaced", + "range": "en-tight" + }, + "ellipsis": { + "abbreviatedAfterTerminal": false + }, + "hyphen": { + "prefixes": [], + "suffixes": [], + "compounds": [] + }, + "nbsp": { + "beforePunctuation": [], + "narrowBeforePunctuation": [], + "afterShortWords": ["a", "i", "k", "o", "s", "u", "v", "z"], + "abbreviations": ["a. s.", "s. r. o."], + "beforeUnits": ["%", "°C", "ha", "kg", "km", "cm", "mm", "m²", "kWh", "km/h", "str.", "hod."], + "beforeNumber": [], + "beforeWord": ["tj.", "tzv.", "tzn."], + "afterSymbols": ["§"], + "initialBinding": "single" + }, + "sources": [ + { + "rule": "quotes", + "cite": "Ústav pro jazyk český AV ČR, Internetová jazyková příručka, «Uvozovky»: «V češtině užíváme různé varianty uvozovek: dvojité „ “, jednoduché ‚ ‘ a boční » «»; «Jako základní se doporučují uvozovky typu 99 66, tj. dvojité „ “»; «Ostatní typy uvozovek (v první řadě jednoduché, až v druhé řadě boční) se užívají především tehdy, pokud potřebujeme do uvozeného textu vložit ještě další uvozovky»; «Uvozovky přiléhají vždy těsně k výrazům, které ohraničují (tedy „takto“)»", + "url": "https://prirucka.ujc.cas.cz/?id=162", + "note": "První stupeň: U+201E otevírací, U+201C zavírací — NIKOLI U+201D jako v polštině, a právě to je rozdíl, který se v sazbě přehlédne. Kódy nebyly odečteny z markdownové konverze stránky, která se u uvozovek ukázala jako nespolehlivá; rozhodující je vlastní označení zdroje «uvozovky typu 99 66»: první znaménko má tvar devítky u paty řádku (U+201E), druhé tvar šestky vyzdvižený nahoru (U+201C). Polský pár PWN naproti tomu označuje jako 99 99. Druhý stupeň: jednoduché uvozovky, protože zdroj je výslovně řadí «v první řadě» pro uvozovky v uvozovkách. OMEZENÁ JISTOTA, řečená naplno: označení «99 66» je ve zdroji uvedeno pouze pro dvojité uvozovky, takže kódy jednoduchých (U+201A … U+2018) vycházejí ze stejného vzorce a z vysázených glyfů, ne z doslovného tvrzení. Rozhodla by tabulka H.1 normy ČSN 01 6910:2014, která je však placená (ČSN online od 1 000 Kč/rok). ROZHODNUTÍ OPERÁTORA, 18. 9. 2026: leží-li pravidlo za placenou normou, projekt je formuluje podle převládajícího úzu a označí to jako rozhodnutí, nikoli jako citaci — stejně jako u německého «Nr.». Padne-li placená stěna, nahradí znění normy tento řádek. Q-W platí v obou případech: U+201A, U+2018 i U+2019 patří do NARROW. Ověřeno 18. 9. 2026." + }, + { + "rule": "dashes", + "cite": "Ústav pro jazyk český AV ČR, Internetová jazyková příručka, «Pomlčka»: «Pomlčku oddělujeme z obou stran mezerami, komplikovanější situace je pouze tehdy, pokud toto znaménko vystupuje ve funkci výrazů a, až, od … do … nebo proti (versus)»; «pomlčka místo čárky: Tato kniha – vydaná ještě před válkou – je opravdu úžasná»; «Pomlčka (–) je dlouhá vodorovná čárka»; «Vedle krátké pomlčky (–) se v textu někdy používá také pomlčka dlouhá (—)»", + "url": "https://prirucka.ujc.cas.cz/?id=165", + "note": "Odůvodňuje dash.parenthetical = «en-spaced». Vsuvka není žádná ze čtyř vyjmenovaných výjimek, takže platí obecné pravidlo o mezerách z obou stran. DÉLKA je na rozdíl od polštiny rozhodnuta samotným zdrojem: definiční glyf stránky je krátká pomlčka U+2013 a dlouhá U+2014 je popsána jako to, co se používá «někdy» navíc. U polštiny musel o délce rozhodnout operátor, protože PWN si v korpusu protiřečil; tady stačí číst. PŘÍPUSTNÁ VARIANTA, zaznamenána: U+2014. Ověřeno 18. 9. 2026." + }, + { + "rule": "ranges", + "cite": "Ústav pro jazyk český AV ČR, Internetová jazyková příručka, «Pomlčka», vyjádření rozsahu (s významem ‚až‘ či ‚od … do‘): «strana 23–26, v letech 1945–1948, 9–16 h»; ÚJČ (P. Lozan, M. Pravdová), «Otázky a odpovědi k ČSN 01 6910 (2014)», otázka 2: «norma umožňuje i psaní mezery kolem pomlčky v rozsazích a ve významu „a“ a „versus“, jestliže je alespoň jeden z výrazů kolem pomlčky víceslovný»", + "url": "https://prirucka.ujc.cas.cz/?id=165", + "note": "Odůvodňuje dash.range = «en-tight»: krátká pomlčka U+2013 bez mezer. Potvrzeno ze dvou stran: příručka sází rozsahy těsně, a dokument ÚJČ k normě popisuje mezery v rozsahu jako povolenou VÝJIMKU pro víceslovné výrazy, což těsnou sazbu předpokládá jako pravidlo. Text samotné ČSN 01 6910 čten nebyl (je placený); citován je výklad jejích vlastních zpracovatelů, což je nejsilnější veřejně dostupná náhrada. Stránka rovněž uvádí, že pomlčka vyjadřující rozsah nemá stát na konci ani na začátku řádku — požadavek, pro který locale.schema.json nemá pole. Pravidlo ranges je ve výchozím stavu vypnuté (spec 0.5.0). Ověřeno 18. 9. 2026." + }, + { + "rule": "ellipsis", + "cite": "Ústav pro jazyk český AV ČR, Internetová jazyková příručka, «Tři tečky»: «jedná se totiž o jeden znak, nikoli tři samostatné tečky»; «Za třemi tečkami často následují další interpunkční znaménka, která se za tři tečky připojují bez mezery, ale nikdy se však nepřipojuje další tečka (nikoli tedy čtyři tečky vedle sebe)»", + "url": "https://prirucka.ujc.cas.cz/?id=166", + "note": "Odůvodňuje abbreviatedAfterTerminal = false. Výpustka je jeden znak U+2026 a otazník či vykřičník stojí ZA ní — ruská dvoutečková forma «?..» není v žádném konzultovaném českém zdroji předvídána. Bylo to ověřeno záměrně: ukrajinština, zkoumaná v témže průchodu, tu formu MÁ, takže analogie mezi slovanskými jazyky by tu byla svůdná a mylná. Ověřeno 18. 9. 2026." + }, + { + "rule": "hyphen", + "cite": "Ústav pro jazyk český AV ČR, Internetová jazyková příručka, «Spojovník»: «píše se bez mezer mezi výrazy, které spojuje»; «Spojovník na začátku dalšího řádku neopakujeme, naznačuje-li rozdělení slova (např. žong- | -lér)»; táž příručka, «Zalomení řádků a nevhodné výrazy na jejich konci», jejíž uzavřený výčet míst, kde k zalomení dojít nemá, spojovník neuvádí", + "url": "https://prirucka.ujc.cas.cz/?id=164", + "note": "Odůvodňuje tři prázdné seznamy. Čeština spojovník na konci řádku ani nezakazuje, ani — na rozdíl od polštiny — dělení v jeho místě nepředepisuje; neexistuje uzavřený normativní seznam tvarů, jejichž spojovník se nesmí lámat. To, že jej třináctibodový výčet stránky o zalomení řádků neobsahuje, je doložená nepřítomnost, ne nenalezená citace — a je to zároveň rozdíl proti ukrajinštině, kde § 64 п. 4 takový seznam má. Ověřeno 18. 9. 2026." + }, + { + "rule": "nbsp", + "cite": "Ústav pro jazyk český AV ČR, Internetová jazyková příručka, «Zalomení řádků a nevhodné výrazy na jejich konci»: k zalomení nemá dojít «ve spojení neslabičných předložek k, s, v, z s následujícím slovem, např. k mostu, s bratrem, v Plzni, z nádraží»; «ve spojení slabičných předložek o, u a spojek a, i s výrazem, který po nich následuje, např. u babičky, o páté»; «ve složených zkratkách a kódech, např. a. s., s. r. o.»; «mezi zkratkami tj., tzv., tzn. a následujícím výrazem»; «mezi zkratkou jména a příjmením»; «mezi číslem a značkou, např. 50 %, § 23»; «V textovém procesoru vkládáme tam, kde nemá dojít k zalomení řádku, místo běžné mezislovní mezery mezeru pevnou»", + "url": "https://prirucka.ujc.cas.cz/?id=880", + "note": "Pět polí z jednoho uzavřeného výčtu, který se odvolává na ČSN 01 6910. (1) afterShortWords: osm jednopísmenných výrazů, citovaných doslova. Na rozdíl od polštiny je zákaz v prameni BEZPODMÍNEČNÝ — není vázán na šířku sloupce ani na to, zda jde o titulek — takže zde nebylo co rozhodovat. (2) abbreviations: «a. s.» a «s. r. o.». Interakce s N3 ověřena a je opačná než u polského «i in.»: N3 vyžaduje, aby po jednopísmenném výrazu následovala mezera, a po «a» následuje tečka, takže N3 index nenárokuje a obě mezery dostane N4. «ČSN 01 6910» z výčtu vypuštěno: číslo normy není fakt o jazyce. (3) beforeWord: «tj.», «tzv.», «tzn.». Bod o «zkratce titulu» populován není, protože zdroj u něj žádný seznam neuvádí. (4) afterSymbols = [«§»]. Ze stejného citovaného bodu byly ZÁMĚRNĚ vynechány «*», «†» a «#»: řetězec «* 1921» je bajt po bajtu totožný s odrážkou seznamu následovanou číslicí, takže v režimu markdown by šlo o falešný zásah bez vyvažujícího přínosu. (5) initialBinding = «single»: pramen váže «zkratku jména» k příjmení a jeho vlastní příklady jsou Fr. Daneš a M. Těšitelová, tedy JEDNA zkrácená křestní jméno; «chain» by na ani jednom z nich nezabral a citované pravidlo by zůstalo nenaplněné. Expozici, kterou schéma u «single» samo pojmenovává, přijímáme na základě citace, stejně jako u fr. beforeNumber zůstává prázdné: jediným kandidátem je «strana 2», ale «strana» je víceznačné plnovýznamové slovo, nikoli zkratka — týž argument, jakým ru.json vylučuje «г.». Ověřeno 18. 9. 2026." + }, + { + "rule": "nbsp", + "cite": "Ústav pro jazyk český AV ČR, Internetová jazyková příručka, «Značky, čísla a číslice»: «Značky se od číselné hodnoty oddělují mezerou, číslo a značka se umísťují na stejný řádek», «např. 10 ha = 10 hektarů, 3 kg = 3 kilogramy, 14 % = 14 procent», «100 kWh», «rychlost 50 km/h», «teplota 12–15 °C»; BIPM, The International System of Units (SI), 9th ed., concise summary: «A single space is always left between the number and the unit»", + "url": "https://prirucka.ujc.cas.cz/?id=785", + "note": "Rozdělení rolí jako v en-US, fi, sv, es, pt a pl: BIPM říká, které řetězce jsou značkami jednotek SI, ÚJČ říká, jaká je česká konvence. České znění je přitom silnější, než nbsp.md §2.1 od locale vyžaduje: uvádí nejen mezeru, ale i to, že «číslo a značka se umísťují na stejný řádek». PŘÍPUSTNÁ VARIANTA, zaznamenána: «V případě, že pomocí číslice a značky vyjadřujeme přídavné jméno, mezeru nevkládáme: 8km = 8kilometrový, 20% = 20procentní». Rozpor není třeba řešit: N5 existující mezeru pouze nahrazuje a nikdy ji nevkládá (nbsp.md §3.7), takže «14 %» dostane U+00A0 a «20%» zůstane nedotčeno. Jednoznakové značky vypuštěny, a pro češtinu z konkrétního důvodu, ne ze stylové opatrnosti: «s» je zároveň vyjmenovaná jednopísmenná předložka, takže ve větě «Přišel v 5 s bratrem» by se «5» svázala se «s». Ověřeno 18. 9. 2026." + }, + { + "rule": "nbsp", + "cite": "Ústav pro jazyk český AV ČR, Internetová jazyková příručka, «Otazník»: «Stejně jako naprostá většina interpunkčních znamének se připojuje k předcházejícímu slovu (zkratce, značce) bez mezery, za ním následuje mezera»; táž příručka, «Tři tečky»: «tři tečky následující za slovem se připojují bez mezery»", + "url": "https://prirucka.ujc.cas.cz/?id=171", + "note": "Odůvodňuje prázdné beforePunctuation i narrowBeforePunctuation. Čeština před «:», «;», «!», «?» nestaví ani U+00A0, ani U+202F, a zdroj jim odstup výslovně upírá — je to zápor, ne mlčení. Q-P je tím splněno triviálně. Ověřeno 18. 9. 2026." + } + ] +} diff --git a/vendor/polytypo-spec/locales/de-DE.json b/vendor/polytypo-spec/locales/de-DE.json index c476748..986ae26 100644 --- a/vendor/polytypo-spec/locales/de-DE.json +++ b/vendor/polytypo-spec/locales/de-DE.json @@ -32,7 +32,7 @@ "afterShortWords": [], "abbreviations": ["z. B.", "d. h.", "u. a.", "u. Ä.", "z. T.", "i. d. R."], "beforeUnits": ["%", "‰", "€", "°C", "km", "cm", "mm", "kg", "km/h", "kWh"], - "beforeNumber": ["S."], + "beforeNumber": ["Nr.", "S."], "beforeWord": ["St."], "afterSymbols": ["§", "§§"], "initialBinding": "chain" @@ -64,13 +64,18 @@ "rule": "nbsp", "cite": "Schweizerische Bundeskanzlei, Schreibweisungen, Rz. 251: der Festabstand verhindert, dass Zusammengehöriges beim Zeilensprung auseinandergerissen wird — Beispiele „20 km“, „St. Gallen“, „Artikel 35“, „S. 17 f.“, „20. November“; Rz. 438: Entsprechendes gilt für die eingliedrige Abkürzung „St.“ für „Sankt“ in Ortsnamen („St. Gallen“, „St. Moritz“); Rz. 439: abschliessende Aufzählung der Begriffszeichen (Ziffern, %, ‰, Gedankenstrich, Schrägstrich, §, Währungszeichen, mathematische Zeichen, Einheitenzeichen)", "url": "https://www.bk.admin.ch/dam/de/sd-web/YVHazXZRkqKn/schreibweisungen.pdf", - "note": "Wortlaut im PDF selbst geprüft. Für Deutschland regelt dieselbe Konstruktion die DIN 5008 (Schreib- und Gestaltungsregeln), die kostenpflichtig ist und deren Wortlaut hier nicht geprüft werden konnte; deshalb steht die schweizerische Weisung als überprüfbarer Beleg — dasselbe Vorgehen wie bei der Quelle zu Rz. 234 in diesem File. Die Übertragung auf de-DE ist insofern eine Ableitung, keine deutschlandspezifische Weisung. „S.“ ist mit „S. 17 f.“ wörtlich belegt und deckt die von docs/PLAN.md §7 geforderte Schreibung „S.“ + Zahl. „Nr.“ ist aus afterSymbols ersatzlos gestrichen und wurde NICHT nach beforeNumber übernommen: die Aufzählung der Begriffszeichen in Rz. 439 ist abschliessend und enthält „Nr.“ nicht (im Sachregister unter N stehen nur „NGO“, „Normen“, „Null“), der Duden führt „Nr.“ als Abkürzung, spricht aber weder im Wörterbucheintrag noch im Sprachratgeber zu Abkürzungen eine Abstandsregel aus. Damit ist afterSymbols nachweislich falsch und beforeNumber unbelegt; nach docs/PLAN.md §6.1 fährt ein Eintrag ohne deckende Quelle nicht mit. Zurückholen lässt sich „Nr.“ durch eine Lesung der DIN 5008 — die Zugehörigkeit zur Klasse allein genügt nicht, das wäre eine als Zitat ausgegebene Ableitung. Die von docs/PLAN.md §7 geforderte Schreibung „Nr.“ + Zahl bleibt damit vorerst offen." + "note": "Wortlaut im PDF selbst geprüft. Für Deutschland regelt dieselbe Konstruktion die DIN 5008 (Schreib- und Gestaltungsregeln), die kostenpflichtig ist und deren Wortlaut hier nicht geprüft werden konnte; deshalb steht die schweizerische Weisung als überprüfbarer Beleg — dasselbe Vorgehen wie bei der Quelle zu Rz. 234 in diesem File. Die Übertragung auf de-DE ist insofern eine Ableitung, keine deutschlandspezifische Weisung. „S.“ ist mit „S. 17 f.“ wörtlich belegt und deckt die von docs/PLAN.md §7 geforderte Schreibung „S.“ + Zahl. „Nr.“ gehört nicht hierher, sondern zu den Abkürzungen: die Aufzählung der Begriffszeichen in Rz. 439 ist abschliessend und enthält „Nr.“ nicht (im Sachregister unter N stehen nur „NGO“, „Normen“, „Null“). Aus afterSymbols ist es deshalb ersatzlos gestrichen. In beforeNumber steht es seit Spec 1.3.0 — nicht als Zitat, sondern als vereinheitlichte Schreibung; die Begründung steht im nächsten Eintrag." }, { "rule": "hyphen", "cite": "Schweizerische Bundeskanzlei, Schreibweisungen, Rz. 223 und 224: der Bindestrich wird als Ergänzungsstrich für einen eingesparten Wortteil verwendet („Papierproduktion und -handel“); mit dem geschützten Ergänzungsstrich wird verhindert, dass der Ergänzungsstrich am Zeilenende auf der oberen Zeile bleibt, während der zugehörige zweite Wortbestandteil auf die nächste Zeile rutscht", "url": "https://www.bk.admin.ch/dam/de/sd-web/YVHazXZRkqKn/schreibweisungen.pdf", "note": "Beleg dafür, dass die drei Listen leer bleiben. Das Deutsche kennt keine geschlossene Liste von Morphemen mit unteilbarem Bindestrich; die Trennung am Bindestrich ist zulässig. Der einzige belegte Fall eines geschützten Bindestrichs ist der Ergänzungsstrich (Rz. 224), und der ist offen: er betrifft jedes beliebige Zweitglied nach „und -“ und lässt sich als literale Wortliste nicht abbilden." + }, + { + "rule": "nbsp", + "cite": "Keine frei prüfbare Normquelle für „Nr.“ + Zahl: DIN 5008:2020-03 ist kostenpflichtig und wurde nicht gelesen; Duden und das Amtliche Regelwerk 2024 sprechen keine Abstandsregel aus. Vereinheitlicht nach vorherrschendem Gebrauch (Operatorentscheid, 18.09.2026)", + "note": "Diese Zeile ist ausdrücklich kein Beleg, sondern eine Festlegung, und wird als solche geführt. Geprüft und ergebnislos: Duden, Rechtschreibregeln „Abkürzungen“ (D 1–D 4, nur der Abkürzungspunkt); Duden, Sprachratgeber „Worttrennung am Zeilenende“; Amtliches Regelwerk 2024, Kapitel F (§§ 84–90, nur Worttrennung) und der Kasten „Sonderzeichen“ auf S. 153, der Typografie ausdrücklich den Konventionen bzw. den DIN-, ÖNORM- und SNV-Normen zuweist, also ausserhalb des Regelwerks. Entscheiden könnte nur DIN 5008:2020-03. Der Projektentscheid dazu: liegt eine Regel hinter einer Bezahlschranke, formuliert polytypo sie nach dem verbreitetsten Gebrauch und hält sie in allen Runtimes gleich — Einheitlichkeit geht hier vor Kanontreue, und die Festlegung wird offen als solche gekennzeichnet statt als Zitat ausgegeben. Der verbreitetste Gebrauch bindet „Nr.“ an die folgende Zahl; die Sekundärquellen, die DIN 5008 referieren, sagen dasselbe. Fällt die Schranke, tritt der Wortlaut der Norm an die Stelle dieser Zeile — auch wenn er ihr widerspricht." } ] } diff --git a/vendor/polytypo-spec/locales/en-US.json b/vendor/polytypo-spec/locales/en-US.json index 0aa9e00..c3af3b0 100644 --- a/vendor/polytypo-spec/locales/en-US.json +++ b/vendor/polytypo-spec/locales/en-US.json @@ -125,9 +125,9 @@ }, { "rule": "nbsp", - "cite": "The Chicago Manual of Style — CMOS Shop Talk, “Navigating Spaces in Manuscripts and Beyond”, 15 June 2021 (exhaustive list of recommended nonbreaking spaces)", - "url": "https://cmosshoptalk.com/2021/06/15/navigating-spaces-in-manuscripts-and-beyond/", - "note": "`beforeNumber` and `beforeWord` are empty. Chicago enumerates exactly four places where it recommends a nonbreaking space — the middle dot of a spaced ellipsis, between initials in a name, between adjacent single and double quotation marks, and between a numeral and an abbreviated unit of measure. Reference abbreviations before a numeral (p. 12, fig. 3, chap. 4, vol. 2) are not among them, and no other consulted Chicago material requires the binding, so they are left out rather than inferred. `beforeWord` is empty for the same reason plus PLAN.md §7: the Mr./Dr. + name binding is an optional rule defaulting off, and no normative source requires it — locale data must not turn an opt-in preference into a default." + "cite": "The Chicago Manual of Style Online, Q&A, topic “Word Division”: “we don’t include any recommendation that says you must carry an abbreviation that ends in a period over to the next line when the sentence continues beyond the abbreviation. So a line is allowed to end with an ‘a.m.’ or ‘Jr.’ or the like that occurs in the middle of a sentence.”", + "url": "https://www.chicagomanualofstyle.org/qanda/data/faq/topics/WordDivision/faq0007.html", + "note": "`beforeNumber` and `beforeWord` are empty, and Chicago does not merely omit reference abbreviations from its nonbreaking-space guidance — it states positively that no such rule exists, so `No. 5`, `p. 12` and `pp. 12–14` are refused on the source’s own words rather than on an argument from silence (issue #30). The same answer attributes the practice to typesetters rather than to Chicago: “some typesetters will use a nonbreaking space to prevent a compound like ‘St. Louis’ or ‘Dr. Smith’ from breaking at the end of a line” — which is why `beforeWord` stays empty too; the named exception is initials in a name, carried by `initialBinding`. CMOS Shop Talk, “Navigating Spaces in Manuscripts and Beyond” (15 June 2021), cited above for `initialBinding` and `beforeUnits`, introduces its four contexts with “can be helpful in the following contexts, among others”, so it must not be described as an exhaustive list." } ] } diff --git a/vendor/polytypo-spec/locales/es.json b/vendor/polytypo-spec/locales/es.json new file mode 100644 index 0000000..a0379ff --- /dev/null +++ b/vendor/polytypo-spec/locales/es.json @@ -0,0 +1,111 @@ +{ + "locale": "es", + "name": "Spanish", + "quotes": { + "primary": { + "open": "«", + "close": "»", + "innerSpace": "none" + }, + "secondary": { + "open": "“", + "close": "”", + "innerSpace": "none" + }, + "elisionIdioms": [] + }, + "dash": { + "parenthetical": "none", + "range": "none" + }, + "ellipsis": { + "abbreviatedAfterTerminal": false + }, + "hyphen": { + "prefixes": [], + "suffixes": [], + "compounds": [] + }, + "nbsp": { + "beforePunctuation": [], + "narrowBeforePunctuation": [], + "afterShortWords": [], + "abbreviations": [ + "p. ej.", + "a. C.", + "d. C.", + "EE. UU.", + "FF. AA.", + "N. del T.", + "q. e. p. d.", + "et al." + ], + "beforeUnits": ["%", "‰", "°C", "km", "cm", "mm", "kg", "mg", "mL", "min", "dB", "kW", "kWh"], + "beforeNumber": ["art.", "cap.", "núm.", "nro.", "pág.", "págs."], + "beforeWord": ["Sr.", "Sra.", "Srta."], + "afterSymbols": [], + "initialBinding": "chain" + }, + "sources": [ + { + "rule": "quotes", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «comillas», apartado 1: «En los textos impresos, se recomienda utilizar en primera instancia las comillas angulares, reservando los otros tipos para cuando deban entrecomillarse partes de un texto ya entrecomillado. En este caso, las comillas simples se emplearán en último lugar»; «Las comillas inglesas y las simples se escriben en la parte alta del renglón, mientras que las angulares se escriben centradas»", + "url": "https://www.rae.es/dpd/comillas", + "note": "El DPD establece QUÉ CLASE de signo corresponde a cada nivel y el orden de anidamiento; no nombra ningún punto de código. La identidad U+201C/U+201D procede de Unicode, autoridad para eso y para nada más. Contra las comillas rectas de máquina de escribir el DPD aporta una descripción de trazado — «en la parte alta del renglón» — y locale.schema.json las prohíbe además por su cuenta. El tercer nivel que el DPD describe (‘ ’) no es expresable: el esquema tiene primary y secondary, no tres; límite del esquema, no laguna de la fuente, igual que en el. ADVERTENCIA DE OBTENCIÓN: rae.es devuelve HTTP 403 a un cliente automático — obstáculo técnico, no obra de pago — y el texto se leyó por un proxy de extracción sobre esta URL canónica; el mismo proxy devolvió la abreviatura de «número» de dos formas distintas en dos pasadas, por lo que ningún campo de este archivo afirma un punto de código no ASCII que no se haya podido fijar por otra vía. Consultado el 18.09.2026." + }, + { + "rule": "quotes", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «comillas», apartado 1: «Las comillas se escriben pegadas a la primera y la última palabra del periodo que enmarcan, y separadas por un espacio de las palabras o signos que las preceden o las siguen»", + "url": "https://www.rae.es/dpd/comillas", + "note": "Justifica innerSpace = \"none\" en los dos pares: «pegadas» excluye todo espacio interior, ni U+00A0 ni U+202F. El español no sigue aquí el uso francés. elisionIdioms queda vacío porque el español no tiene ningún modismo de la forma {left, elided, right}: la entrada «apóstrofo» del mismo DPD afirma que el signo «apenas se usa en el español actual» y lo limita a textos antiguos, al habla reproducida y a nombres de otras lenguas. Consultado el 18.09.2026." + }, + { + "rule": "dashes", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «raya», apartado 2: «Como el resto de los signos dobles, se escriben pegadas a la primera y a la última palabra del periodo que enmarcan, y separadas por un espacio de la palabra o signo que las precede o las sigue»", + "url": "https://www.rae.es/dpd/raya", + "note": "parenthetical = \"none\" POR UN LÍMITE DEL ESQUEMA, no por falta de fuente: la fuente es explícita y prescribe espacios ORDINARIOS FUERA del par y ninguno en los bordes interiores («Llegó —por fin— a casa»). El enum no expresa esa asimetría: \"em-spaced\" pone un espacio a cada lado de CADA raya, que es lo que la frase prohíbe, y \"em-tight\" suprime los exteriores que la frase exige. Mismo caso que el griego (dashes.md §6) y que el italiano de este mismo lote; al repetirse en tres idiomas independientes deja de ser una rareza y pasa a ser una carencia del esquema, registrada aparte para resolverse en su propia versión. Mientras tanto \"none\" es lo único que el archivo puede decir con verdad, y no autoriza a aproximar. Consultado el 18.09.2026." + }, + { + "rule": "ranges", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «guion», apartado 3 b): «Indica intervalos expresados tanto en números arábigos como en romanos: las páginas 23-45; durante los siglos x-xii»; apartado 1: «Signo ortográfico en forma de pequeña línea horizontal (-)»", + "url": "https://www.rae.es/dpd/guion", + "note": "range = \"none\" por una razón DISTINTA de la de parenthetical, y confundirlas tergiversaría las fuentes. El signo español del intervalo es el guion, U+002D — el carácter que el autor ya escribió —, y el enum solo ofrece em, en o none: «no sustituir nada» es aquí a la vez lo honesto y lo correcto, porque «23-45» ya está bien escrito. El enum sí podría expresar un valor equivocado: \"en-tight\" convertiría esa forma en una que el DPD no prescribe. Consultado el 18.09.2026." + }, + { + "rule": "ellipsis", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «puntos suspensivos», apartado 1: «Signo de puntuación formado por tres puntos consecutivos (…) ―y solo tres―»", + "url": "https://www.rae.es/dpd/puntos%20suspensivos", + "note": "Justifica abbreviatedAfterTerminal = false: «y solo tres» es una exigencia expresa de número, y el español no dispone en ningún apartado de la forma de dos puntos tras «?» o «!» que sí usa el ruso. El apartado 3.4 de la misma entrada regula el ORDEN de los signos, no su número. La fuente no se pronuncia sobre U+2026 frente a tres U+002E: esa elección es del motor y es igual en todas las locales. Consultado el 18.09.2026." + }, + { + "rule": "hyphen", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «guion», apartados 1, 2 y 3: el guion une palabras y segmentos, divide la palabra al final de línea, indica intervalos y separa grupos de cifras", + "url": "https://www.rae.es/dpd/guion", + "note": "Justifica las tres listas vacías. La entrada enumera los usos del guion y en ninguno define una clase cerrada de formas morfológicas cuyo guion no deba partirse al final de línea, que es lo único que consume esta regla; al contrario, en español el guion es el signo del propio corte de línea. Con las listas vacías la regla es un no-op total demostrable (hyphen.md §2), que es el caso normal y no una carencia. Consultado el 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «signos de interrogación y exclamación», apartado 1: «Se escriben pegados a la primera y la última palabra del periodo que enmarcan, y separados por un espacio de las palabras que los preceden o los siguen»", + "url": "https://www.rae.es/dpd/signos%20de%20interrogaci%C3%B3n%20y%20exclamaci%C3%B3n", + "note": "Justifica beforePunctuation y narrowBeforePunctuation vacíos por dos motivos independientes. PRIMERO, la fuente: no hay espacio antes de «?» ni de «!», ni después de «¿» ni de «¡»; el uso francés queda descartado por la norma, no por silencio. SEGUNDO, y con independencia de lo anterior, el esquema no podría expresar lo contrario: la restricción Q-P exige que todo punto de código de estas listas pertenezca a CLOSEISH, y U+00BF y U+00A1 no lo son — son puntuación de APERTURA, y el único mecanismo de «espacio tras un signo de apertura» del esquema es quotes.innerSpace. NO ES EXPRESABLE, que es distinto de no estar atestiguado. afterShortWords queda vacío por una razón más débil y se dice cuál: ninguna fuente consultada exige que una palabra breve no quede al final de línea; lo resolvería el capítulo «División de palabras al final de línea» de la Ortografía, no consultado. afterSymbols vacío: ninguna fuente española consultada liga «§» a un número. Consultado el 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «símbolo», apartado 5.4: «Los símbolos deben escribirse pospuestos a la cifra a la que acompañan y dejando un blanco de separación: 33 dB, 125 m², 4 H»; «se separa de ella y se pega al símbolo de la escala si esta se especifica: 27° (por veintisiete grados), pero 27 °C»; apartado 5.6: «No deben escribirse en líneas diferentes la cifra y el símbolo que la acompaña: ⊗3 / $, ⊗7 / km»", + "url": "https://www.rae.es/dpd/s%C3%ADmbolo", + "note": "Justifica beforeUnits, y el apartado 5.6 es además la base normativa de la INDIVISIBILIDAD, dicha por la RAE y en español. El apartado 5.4 impone una exclusión que el archivo respeta: «°» a secas NO figura, porque «27°» va pegado; solo «°C». Dos advertencias de alcance. (1) La lista es MÁS ESTRECHA QUE LA FUENTE: se omiten los símbolos de una sola letra (m, g, s, h, L, A, H), que no se desambiguan sin contexto — criterio de fr —, pese a que el ejemplo del propio apartado es «4 H». (2) No se incluye ningún símbolo monetario, y no por prudencia sino por cita: el apartado 5.5 distingue expresamente el uso de España («3 £», pospuesto y con blanco) del de América («£3», antepuesto y sin blanco), y esta locale no lleva subetiqueta de región. Ese apartado se cita también en POSITIVO: el DPD sabe marcar la divergencia regional donde existe, luego los campos sobre los que no la marca son seguros para un «es» regionalmente neutro. Consultado el 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "BIPM, The International System of Units (SI), 9th ed. (2019), concise summary: «A single space is always left between the number and the unit»", + "url": "https://www.bipm.org/documents/20126/41483022/SI-Brochure-9-concise-EN.pdf", + "note": "Autoridad sobre la COMPOSICIÓN de la lista de unidades, igual que en en-US, en-GB, fi y sv; el DPD «símbolo» 5.4 y 5.6 es la autoridad sobre la convención española y sobre la indivisibilidad. El BIPM no se invoca como autoridad sobre el español — no lo es —, sino sobre qué cadenas son símbolos de unidad del SI. Si ambas fuentes discreparan sobre el español mandaría la RAE; no discrepan. Consultado el 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "RAE y ASALE, Diccionario panhispánico de dudas, entrada «abreviatura»: «Tampoco deben aparecer en renglones diferentes la abreviatura y el término del que esta depende: ⊗15 / págs., ⊗Sr. / Pérez»; «Cuando la abreviatura corresponde a una expresión compleja, se separan mediante un espacio las letras que representan cada una de las palabras que la integran»; «Las iniciales de los componentes del nombre propio de una persona son también abreviaturas formadas por truncamiento»", + "url": "https://www.rae.es/dpd/abreviatura", + "note": "Una sola cita para cuatro campos, porque una sola regla los gobierna. abbreviations: la fuente exige el espacio interior y prohíbe partirlo; las formas listadas están atestiguadas en esta entrada o en la Lista de abreviaturas de El buen uso del español. beforeNumber y beforeWord: «⊗15 / págs.» y «⊗Sr. / Pérez» son los dos ejemplos de la propia fuente, uno en cada orden. beforeWord se limita a la clase cerrada de los tratamientos de cortesía: la regla vale para CUALQUIER abreviatura, pero enumerarlas todas dispararía falsos positivos en la subrregla de mayor riesgo del esquema (nbsp.md §3.12). NO SE INCLUYEN «n.º», «D.ª» ni «Sr.ª»: la RAE prescribe una «o volada», es decir un TRAZADO y no un punto de código, y el texto obtenido devolvió dos formas distintas en dos pasadas; adivinar sería peor que omitir. initialBinding = \"chain\" ES UNA DECISIÓN DEL OPERADOR (18.09.2026), NO UNA CITA: el DPD no contiene ninguna calificación de «dos o más» — enuncia la regla general y establece que las iniciales SON abreviaturas, lo que apunta más bien a \"single\" —, pero su único ejemplo con iniciales es «J. A. Pérez», de dos, y ante una fuente que no decide se eligió el valor mayoritario en este proyecto (en-US, de-DE, de-CH, ru) y el de menor superficie de falsos positivos, porque \"chain\" no liga una mayúscula con punto aislada. En «J. A. Pérez» ambos valores dan el mismo resultado; solo difieren ante un inicial suelto. Consultado el 18.09.2026." + } + ] +} diff --git a/vendor/polytypo-spec/locales/fr-CA.json b/vendor/polytypo-spec/locales/fr-CA.json index 809aed7..5c59318 100644 --- a/vendor/polytypo-spec/locales/fr-CA.json +++ b/vendor/polytypo-spec/locales/fr-CA.json @@ -32,7 +32,7 @@ "afterShortWords": [], "abbreviations": ["p. ex."], "beforeUnits": ["%", "‰", "€", "°C", "km", "cm", "mm", "kg", "km/h", "kWh"], - "beforeNumber": ["art.", "fig."], + "beforeNumber": ["art.", "fig.", "n°", "N°"], "beforeWord": ["M.", "MM.", "Mme", "Mmes", "Mlle", "Mlles"], "afterSymbols": ["§"], "initialBinding": "single" @@ -73,6 +73,12 @@ "cite": "Jacques André, Petites leçons de typographie, tableau 1 — voir spec/locales/fr.json pour la citation complète", "url": "http://jacques-andre.fr/faqtypo/lessons.pdf", "note": "Repris tel quel de fr : aucune source consultée n'impose un trait d'union insécable pour une classe fermée de formes morphologiques françaises, en France comme au Québec." + }, + { + "rule": "nbsp", + "cite": "Office québécois de la langue française, Banque de dépannage linguistique, « Abréviation de numéro » : « L'abréviation courante du nom numéro est no ou No, avec la lettre o minuscule en exposant » ; « On n'abrège le mot numéro que s'il suit immédiatement le nom qu'il détermine » ; exemple : « C'est le billet no 852410 qui a valu le gros lot à sa détentrice »", + "url": "https://vitrinelinguistique.oqlf.gouv.qc.ca/25450/les-abreviations-et-les-symboles/les-abreviations/cas-particuliers-dabreviations/abreviation-de-numero", + "note": "Deux choses distinctes, et il faut les tenir séparées. Ce que la source établit : « n° » est une abréviation, pas un symbole, d'où beforeNumber et non afterSymbols — l'argument est aussi mécanique, un « ° » seul placé dans afterSymbols serait inerte puisque N6 exige que le code point précédent ne soit pas ALNUM, or c'est la lettre « n » (nbsp.md §3.8). Ce que la source n'établit pas : la séquence exacte de code points. L'OQLF prescrit un o minuscule en exposant, un tracé et non un code point, et ne nomme nulle part le signe de degré ni la ligature « numéro » (U+2116). Pour la France, rien : le § 5.1.3 de Jacques André, relu intégralement, ne mentionne ni « numéro » ni « no », et le Lexique de l'Imprimerie nationale est un ouvrage imprimé qui n'a pas pu être consulté. Décision de l'opérateur (18.09.2026) : quand la règle est derrière une source payante, polytypo retient l'usage le plus répandu et l'applique de la même façon partout, l'uniformité primant la conformité au canon, et la décision est signalée comme telle au lieu d'être présentée comme une citation. L'usage le plus répandu est « n » + U+00B0, c'est ce que l'on tape et ce que l'on trouve dans les textes en ligne ; N9 n'ayant aucune tolérance de casse, « n° » et « N° » sont deux entrées. La phrase « on ne sépare pas les numéros par des espacements » de la même page vise les tranches de chiffres à l'intérieur du nombre (« billet no 852410 »), pas l'espace entre l'abréviation et le nombre." } ] } diff --git a/vendor/polytypo-spec/locales/fr.json b/vendor/polytypo-spec/locales/fr.json index 82648ed..41a7c70 100644 --- a/vendor/polytypo-spec/locales/fr.json +++ b/vendor/polytypo-spec/locales/fr.json @@ -32,7 +32,7 @@ "afterShortWords": [], "abbreviations": ["p. ex."], "beforeUnits": ["%", "‰", "€", "°C", "km", "cm", "mm", "kg", "km/h", "kWh"], - "beforeNumber": ["art.", "fig."], + "beforeNumber": ["art.", "fig.", "n°", "N°"], "beforeWord": ["M.", "MM.", "Mme", "Mmes", "Mlle", "Mlles"], "afterSymbols": ["§"], "initialBinding": "single" @@ -79,6 +79,12 @@ "cite": "Jacques André, Petites leçons de typographie, tableau 1 (p. 32), ligne « trait d'union » : la saisie est « mmm-mmm », sans espace ni marque d'insécabilité, alors que le même tableau note explicitement l'insécable pour les ponctuations doubles, les guillemets et les tirets d'incise", "url": "http://jacques-andre.fr/faqtypo/lessons.pdf", "note": "Justification des trois listes vides. Aucune source normative consultée n'impose un trait d'union insécable pour une classe fermée de formes morphologiques françaises ; le § 5.1.3, qui énumère les cas d'insécabilité, ne mentionne aucun trait d'union. Le champ hyphen est donc sans objet en français." + }, + { + "rule": "nbsp", + "cite": "Office québécois de la langue française, Banque de dépannage linguistique, « Abréviation de numéro » : « L'abréviation courante du nom numéro est no ou No, avec la lettre o minuscule en exposant » ; « On n'abrège le mot numéro que s'il suit immédiatement le nom qu'il détermine » ; exemple : « C'est le billet no 852410 qui a valu le gros lot à sa détentrice »", + "url": "https://vitrinelinguistique.oqlf.gouv.qc.ca/25450/les-abreviations-et-les-symboles/les-abreviations/cas-particuliers-dabreviations/abreviation-de-numero", + "note": "Deux choses distinctes, et il faut les tenir séparées. Ce que la source établit : « n° » est une abréviation, pas un symbole, d'où beforeNumber et non afterSymbols — l'argument est aussi mécanique, un « ° » seul placé dans afterSymbols serait inerte puisque N6 exige que le code point précédent ne soit pas ALNUM, or c'est la lettre « n » (nbsp.md §3.8). Ce que la source n'établit pas : la séquence exacte de code points. L'OQLF prescrit un o minuscule en exposant, un tracé et non un code point, et ne nomme nulle part le signe de degré ni la ligature « numéro » (U+2116). Pour la France, rien : le § 5.1.3 de Jacques André, relu intégralement, ne mentionne ni « numéro » ni « no », et le Lexique de l'Imprimerie nationale est un ouvrage imprimé qui n'a pas pu être consulté. Décision de l'opérateur (18.09.2026) : quand la règle est derrière une source payante, polytypo retient l'usage le plus répandu et l'applique de la même façon partout, l'uniformité primant la conformité au canon, et la décision est signalée comme telle au lieu d'être présentée comme une citation. L'usage le plus répandu est « n » + U+00B0, c'est ce que l'on tape et ce que l'on trouve dans les textes en ligne ; N9 n'ayant aucune tolérance de casse, « n° » et « N° » sont deux entrées. La phrase « on ne sépare pas les numéros par des espacements » de la même page vise les tranches de chiffres à l'intérieur du nombre (« billet no 852410 »), pas l'espace entre l'abréviation et le nombre." } ] } diff --git a/vendor/polytypo-spec/locales/it.json b/vendor/polytypo-spec/locales/it.json new file mode 100644 index 0000000..2928f71 --- /dev/null +++ b/vendor/polytypo-spec/locales/it.json @@ -0,0 +1,95 @@ +{ + "locale": "it", + "name": "Italian", + "quotes": { + "primary": { + "open": "«", + "close": "»", + "innerSpace": "none" + }, + "secondary": { + "open": "“", + "close": "”", + "innerSpace": "none" + }, + "elisionIdioms": [] + }, + "dash": { + "parenthetical": "em-spaced", + "range": "none" + }, + "ellipsis": { + "abbreviatedAfterTerminal": false + }, + "hyphen": { + "prefixes": [], + "suffixes": [], + "compounds": [] + }, + "nbsp": { + "beforePunctuation": [], + "narrowBeforePunctuation": [], + "afterShortWords": [], + "abbreviations": [], + "beforeUnits": ["%", "‰", "€", "°C", "km", "cm", "mm", "kg", "km/h", "kWh"], + "beforeNumber": ["n.", "pag."], + "beforeWord": [], + "afterSymbols": [], + "initialBinding": "none" + }, + "sources": [ + { + "rule": "quotes", + "cite": "Ufficio delle pubblicazioni dell'Unione europea, Manuale interistituzionale di convenzioni redazionali, ed. 2011 (IT), punto 4.2.3, riquadro «Virgolette»: «Nella lingua italiana esistono tre livelli di virgolette […]: livello 1 (citazione principale) «…» (Alt 0171/Alt 0187); livello 2 (citazione nella citazione) “…” (Alt 0147/Alt 0148); livello 3 (citazione nella citazione nella citazione) ‘…’ (Alt 0145/Alt 0146)»", + "url": "https://op.europa.eu/it/publication-detail/-/publication/e774ea2a-ef84-4bf6-be92-c9ebebf91c1b", + "note": "L'attribuzione è per LIVELLO DI ANNIDAMENTO, cioè esattamente la forma che lo schema sa esprimere. Il terzo livello non è rappresentabile: lo schema prevede primary e secondary, non tre — limite dello schema, non lacuna della fonte, come già in el. INFERENZA DICHIARATA sull'identità dei code point: la guida fornisce un «codice alfanumerico» per Windows, non un code point Unicode; Alt 0171/0187/0147/0148 sono CP1252 0xAB/0xBB/0x93/0x94, da cui U+00AB/U+00BB/U+201C/U+201D. Riscontro indipendente: Treccani, Enciclopedia dell'Italiano (2011), voce «Virgolette» (Luca Cignetti): «è consuetudine fare ricorso a tipi diversi di virgoletta, solitamente bassa per la prima citazione e alta per gli altri usi». POSIZIONE CONTRARIA, registrata: l'Accademia della Crusca («La punteggiatura», 16 luglio 2004) rifiuta di ordinare i due segni al primo livello — «Alte e basse si usano indifferentemente» — ma non tratta l'annidamento, quindi non c'è conflitto: la scelta del segno di primo livello è una variante permessa che questo file compie, l'ordine dei livelli è ciò che le altre due fonti stabiliscono. Consultati il 18.09.2026." + }, + { + "rule": "quotes", + "cite": "Manuale interistituzionale di convenzioni redazionali, ed. 2011 (IT), Parte quarta, punto 10.1.7 «Virgolette»: «Le virgolette non richiedono spazio né in apertura né in chiusura»", + "url": "https://op.europa.eu/it/publication-detail/-/publication/e774ea2a-ef84-4bf6-be92-c9ebebf91c1b", + "note": "Giustifica innerSpace = \"none\" su entrambe le coppie, ed è il punto che separa l'italiano dal francese. LETTURA DICHIARATA COME TALE: «né in apertura né in chiusura» va inteso come «né dal lato di apertura né dal lato di chiusura del testo racchiuso», cioè nessuno spazio interno; la lettura alternativa è impossibile, perché lo spazio fra la parola precedente e il segno di apertura non è facoltativo. La tabella del punto 6.4 disambiguerebbe la frase ma NON è invocata: il suo preambolo la qualifica come accordo interistituzionale adottato «a vantaggio di una convenzione comune» al posto dei codici tipografici nazionali divergenti, cioè prassi editoriale e non norma italiana — la stessa lettura già applicata in el.json. Conseguenza pratica: l'elisione italiana è al sicuro, perché dell'«amico» non richiede spazio interno. elisionIdioms resta vuoto: l'elisione italiana è un fenomeno clitico, non un idioma della forma {left, elided, right}. Consultati il 18.09.2026." + }, + { + "rule": "dashes", + "cite": "Manuale interistituzionale di convenzioni redazionali, ed. 2011 (IT), punto 4.2.3, riquadro «Trattini»: «In italiano utilizzare il trattino lungo come eventuale alternativa alle parentesi»; Parte quarta, punto 10.1.10 «Lineetta», con l'esempio stampato «La casa — se casa si poteva definire quel rudere — sorgeva ai piedi del colle»", + "url": "https://op.europa.eu/it/publication-detail/-/publication/e774ea2a-ef84-4bf6-be92-c9ebebf91c1b", + "note": "Giustifica dash.parenthetical = \"em-spaced\": U+2014 con uno spazio ordinario su CIASCUN lato di CIASCUNA lineetta. La spaziatura è simmetrica, quindi — a differenza dello spagnolo e del greco — l'enum la esprime senza forzature. INFERENZA DICHIARATA sul code point: Alt 0151 è CP1252 0x97, da cui U+2014. Riscontro sulla SPAZIATURA, non sul code point: Treccani, «Trattino [prontuario]» (Stefano Telve, 2011), che del trattino breve scrive «A differenza della lineetta, non è preceduto né seguito da spazi». COSTO ACCETTATO, verificato sul motore e registrato qui perché non venga riscoperto come bug: il punto 10.1.11 prescrive il trattino spaziato per collegare due date di mesi diversi («25 maggio - 10 giugno 1985»), e la guardia P1 di dashes.md §3.2 converte qualunque trattino isolato e spaziato fra parole, quindi il motore produce una lineetta lì. Non è una particolarità italiana: fr, ru, de-DE e en-GB, già pubblicate, si comportano allo stesso modo sulla stessa stringa. Consultati il 18.09.2026." + }, + { + "rule": "ranges", + "cite": "Manuale interistituzionale di convenzioni redazionali, ed. 2011 (IT), Parte quarta, punto 10.3.1 «Numeri arabi»: «I numeri arabi non richiedono la lineetta (lineato) bensì il trattino (divisione)», con l'esempio stampato «la sessione del 15-19 giugno 1985»; punto 10.1.11: «Il trattino è anche impiegato, senza alcuno spazio, per collegare due anni civili o due date di uno stesso mese: 1971-1972, 10-15 settembre 1985»", + "url": "https://op.europa.eu/it/publication-detail/-/publication/e774ea2a-ef84-4bf6-be92-c9ebebf91c1b", + "note": "Giustifica dash.range = \"none\", e lo fa in POSITIVO, non per assenza di citazione: la fonte prescrive il trattino U+002D — il carattere che l'autore ha già digitato — ed esclude la lineetta per nome. L'enum non ha un valore «trattino»: \"none\" è la codifica esatta di ciò che la fonte richiede. Riscontro: Treccani, «Trattino [prontuario]» (Telve 2011), esempi «il fascicolo del 2-3 luglio», «anno accademico 2010-2011». Voce separata da quella di dashes benché entrambe le regole leggano il campo dash: la citazione è distinta e più forte. Consultati il 18.09.2026." + }, + { + "rule": "ellipsis", + "cite": "Manuale interistituzionale di convenzioni redazionali, ed. 2011 (IT), Parte quarta, punto 10.1.8 «Punti di sospensione»: «Segno d'interpunzione costituito da tre punti»; Accademia della Crusca, Consulenza linguistica, «La punteggiatura» (Mara Marzullo, 16 luglio 2004): «I puntini di sospensione si usano sempre nel numero di tre»", + "url": "https://accademiadellacrusca.it/it/consulenza/la-punteggiatura/143", + "note": "Giustifica abbreviatedAfterTerminal = false. Due fonti indipendenti affermano che i puntini sono sempre tre, e nessuna prevede la forma a due punti dopo U+003F o U+0021 che usa il russo: il ramo russo di ellipsis.md resta spento per l'italiano. Nessuna delle due si pronuncia su U+2026 contro tre U+002E; quella scelta è del motore ed è identica in ogni locale. DIVERGENZA NOTA, registrata: gli esempi stampati del Manuale non lasciano spazio prima dei puntini, mentre spaces.md §3.4 conserva in ogni locale lo spazio che precede una sequenza di punti; è deliberata e argomentata in spaces.md §7.9, identica a quella già registrata per el. Il Manuale è consultabile all'indirizzo op.europa.eu (cfr. le altre voci di questo file); l'url di questa voce punta alla fonte Crusca, poiché lo schema ne ammette uno solo. Consultati il 18.09.2026." + }, + { + "rule": "hyphen", + "cite": "Manuale interistituzionale di convenzioni redazionali, ed. 2011 (IT), Parte quarta, punto 10.1.11 «Trattino»: «Il trattino («divisione» in linguaggio tipografico) […] si impiega principalmente per dividere la parola in fin di riga»; «Si può anche usare per unire due parole contraendo la prima: trattato italo-francese»", + "url": "https://op.europa.eu/it/publication-detail/-/publication/e774ea2a-ef84-4bf6-be92-c9ebebf91c1b", + "note": "Giustifica le tre liste vuote. La fonte enumera gli impieghi del trattino — e il primo che nomina è l'OPPOSTO dell'insecabilità — senza definire alcuna classe chiusa di forme morfologiche il cui trattino debba resistere all'andata a capo, che è l'unica cosa che questa regola consuma. Riscontro: Treccani, «Trattino [prontuario]» (Telve 2011), che elenca le funzioni di unione (afro-cubano, porta-finestra, maxi-schermo) senza definire neppure essa un elenco chiuso. La famiglia di prefissi (ex-, anti-, maxi-) è stata verificata espressamente perché è l'unica che lo schema saprebbe contenere: le fonti la trattano come schema produttivo e aperto, e un insieme aperto non è esprimibile in wordList. Consultati il 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "BIPM, The International System of Units (SI), 9th ed. (2019), concise summary: «A single space is always left between the number and the unit»", + "url": "https://www.bipm.org/documents/20126/41483022/SI-Brochure-9-concise-EN.pdf", + "note": "Autorità per l'ELENCO delle unità, non per il legame: che lo spazio sia insecabile e che sia U+00A0 è deciso da nbsp.md §2.1, che una locale non può variare. Stessa impostazione di en-US, en-GB, fi e sv. L'elenco segue la forma prudente di fr e de-DE ed esclude deliberatamente i simboli di una sola lettera (m, g, l, s, A), che non si possono disambiguare senza contesto. La tabella del punto 6.4 del Manuale darebbe lo stesso risultato per «%» e «°C» ma non è invocata, per la ragione detta nella voce quotes. Consultati il 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "Manuale interistituzionale di convenzioni redazionali, ed. 2011 (IT), punto 4.2.3, riquadro «Spazi vuoti protetti»: «Consentono di evitare la troncatura a fine riga di elementi che devono rimanere uniti»; «Da usare solo nei casi seguenti […]: n.• JO L• 10•000 / pag.• JO C• C.•M. Dupont», dove «•» indica lo spazio fisso", + "url": "https://op.europa.eu/it/publication-detail/-/publication/e774ea2a-ef84-4bf6-be92-c9ebebf91c1b", + "note": "INFERENZA DICHIARATA, accettata per decisione dell'operatore il 18.09.2026, non citazione piena — ed è esattamente la distinzione che questo campo esiste per non far sparire. I riquadri «Virgolette» e «Trattini» dello stesso punto 4.2.3 dicono «Nella lingua italiana» e «In italiano»: questo riquadro NON lo dice, ed è in parte non adattato, poiché «JO L» e «JO C» sono il Journal officiel francese e «Dupont» è un cognome francese, in un'edizione italiana il cui testo originale era in francese. Ciò che l'italiano c'è davvero: «pag.» è italiano (il francese scrive «p.») e «n.» è uso italiano corrente, quindi il riquadro è stato localizzato almeno in parte — su questo poggia beforeNumber. La sequenza «C.•M. Dupont» non contiene invece alcun materiale italiano, e initialBinding resta perciò \"none\", il valore pulito da citazione. Nessuna tolleranza di caso: N9 non ne ha, e sono stampate solo le forme minuscole «n.» e «pag.». «10•000» è raggruppamento delle migliaia e «JO L•» una serie della Gazzetta ufficiale: nessuno dei due è esprimibile in questo schema. Consultati il 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "Nessuna fonte normativa italiana esaminata prescrive uno spazio prima di un segno d'interpunzione, né un legame per abbreviazioni con spazio interno, simboli o parole seguenti; liste deliberatamente vuote", + "note": "beforePunctuation e narrowBeforePunctuation sono vuote, e va detto con esattezza su che cosa poggiano: sull'ASSENZA di una fonte italiana che richieda quello spazio, NON su una fonte che lo neghi. A differenza del capitolo greco, che respinge la prassi francese nominandola, la Parte quarta italiana non la nomina mai: i punti 10.1.3 e 10.1.4 descrivono la funzione dei segni e tacciono sulla spaziatura. Il vincolo Q-P rende comunque la lista vuota la scelta strutturalmente sicura. afterShortWords, abbreviations, beforeWord e afterSymbols sono vuote per la stessa ragione: nessuna fonte esaminata le attesta per l'italiano. SEGNALAZIONE ALL'OPERATORE, non risolta qui: la Parte quarta si apre, al punto 10.1, con «Per la spaziatura dei segni d'interpunzione, cfr. punto 6.4», cioè il capitolo squalificato come prassi editoriale in el.json; se quel rinvio si leggesse come un'adozione, la tabella diventerebbe evidenza italiana e rafforzerebbe queste liste vuote. Consultati il 18.09.2026." + } + ] +} diff --git a/vendor/polytypo-spec/locales/nl.json b/vendor/polytypo-spec/locales/nl.json new file mode 100644 index 0000000..e731ded --- /dev/null +++ b/vendor/polytypo-spec/locales/nl.json @@ -0,0 +1,84 @@ +{ + "locale": "nl", + "name": "Dutch", + "quotes": { + "primary": { + "open": "“", + "close": "”", + "innerSpace": "none" + }, + "secondary": { + "open": "‘", + "close": "’", + "innerSpace": "none" + }, + "elisionIdioms": [] + }, + "dash": { + "parenthetical": "en-spaced", + "range": "none" + }, + "ellipsis": { + "abbreviatedAfterTerminal": false + }, + "hyphen": { + "prefixes": [], + "suffixes": [], + "compounds": [] + }, + "nbsp": { + "beforePunctuation": [], + "narrowBeforePunctuation": [], + "afterShortWords": [], + "abbreviations": ["prof. dr."], + "beforeUnits": ["%", "‰", "°C", "km", "cm", "mm", "kg", "km/h", "kWh"], + "beforeNumber": [], + "beforeWord": [], + "afterSymbols": ["€", "$"], + "initialBinding": "none" + }, + "sources": [ + { + "rule": "quotes", + "cite": "Nederlandse Taalunie, Taaladvies.net, «Dubbele of enkele aanhalingstekens bij een citaat»: «Er zijn geen vaste regels voor het gebruik van enkele of dubbele aanhalingstekens. Traditioneel werd aangeraden om bij letterlijk citeren dubbele aanhalingstekens te gebruiken […] We raden aan om consequent voor één systeem te kiezen», met voorbeeld (4a): «De koning zei: [U+201C]Ik herinner me nog dat iemand [U+2018]Vive la république[U+2019] riep[U+201D]»", + "url": "https://taaladvies.net/dubbele-of-enkele-aanhalingstekens-bij-een-citaat/", + "note": "BESLISSING VAN DE OPERATOR, 18.09.2026, en uitdrukkelijk geen citaat: de Taalunie WEIGERT te rangschikken — «Er zijn geen vaste regels» — en noemt drie mogelijke nestingen zonder er één te verkiezen. Het schema kent maar één paar per niveau, dus er moet gekozen worden. Gekozen is variant (4a) van de Taalunie zelf: U+201C/U+201D als eerste niveau, U+2018/U+2019 als tweede. Twee gronden, allebei genoemd omdat geen van beide een voorschrift is: het is de vorm die de Taalunie «traditioneel» aan het letterlijke citaat verbindt, en het is de vorm die elk ander locale in dit project al heeft. TEGENGESTELDE AANWIJZING, niet verzwegen: «Aanhalingstekens (algemeen)» merkt op dat «Enkele aanhalingstekens […] het meest gebruikt» worden — een waarneming over frequentie, geen voorschrift, maar hij wijst de andere kant op. GECONTROLEERD, want het was het enige technische argument dat de keuze had kunnen beslissen: de vrees dat U+2019 als sluitteken zou botsen met de Nederlandse apostrof (auto's, 's-Hertogenbosch, A4'tje) blijkt ONGEGROND — beide varianten geven op die zinnen hetzelfde, correcte resultaat. De keuze berust dus op de bron en op eenvormigheid, niet op een motoreigenschap. innerSpace = «none»: geen geraadpleegde bron vraagt om een spatie binnen de tekens. Geraadpleegd op 18.09.2026." + }, + { + "rule": "dashes", + "cite": "Nederlandse Taalunie, Taaladvies.net, «Wel of geen spaties voor en na leestekens en symbolen (algemeen)» (12 mei 2021): «Voor een gedachtestreepje komt altijd een spatie, en ook erna»; en «Gedachtestreepje»: «Als gedachtestreepje wordt doorgaans het zogeheten halve kastlijntje (–) gebruikt. Het halve kastlijntje is wat langer dan het koppelteken of het afbreekteken (-)»", + "url": "https://taaladvies.net/wel-of-geen-spaties-voor-en-na-leestekens-en-symbolen-algemeen/", + "note": "Onderbouwt dash.parenthetical = «en-spaced»: een spatie aan weerszijden en een streepje ter lengte van een halve kastlijn, dus U+2013 en niet U+2014. AFLEIDING, als zodanig gemarkeerd: de Taalunie noemt de lengte, niet het codepunt. De toewijzing aan U+2013 steunt op Genootschap Onze Taal, Taalloket, «kort streepje (-) of lang streepje (–)», dat de twee tekens expliciet tegenover elkaar zet en het «hele kastlijntje» (—) als vooral Engels en «in Nederland […] minder gebruikelijk» beschrijft. Rangorde, want de bronnen zijn niet gelijkwaardig: de Taalunie is het officiële taalorgaan, Onze Taal een taalvereniging, en Onze Taal wordt hier alleen gebruikt om vast te stellen welk van twee met name genoemde tekens de term van de Taalunie aanduidt. Geraadpleegd op 18.09.2026." + }, + { + "rule": "ranges", + "cite": "Genootschap Onze Taal, Taalloket, «kort streepje (-) of lang streepje (–)»: het korte streepje geeft tussen getallen «tot en met» aan — «1940-1945, de categorie 30-45 jaar, pagina 10-12»; Nederlandse Taalunie, «20 tot 30-jarigen of 20-30-jarigen?» (12 mei 2021), dat overal U+002D toont zonder over het streepjestype iets voor te schrijven", + "url": "https://onzetaal.nl/taalloket/streepje-kort-of-lang", + "note": "Onderbouwt dash.range = «none» als een keuze en niet als een leemte: het Nederlandse bereikteken is het koppelteken U+002D, dat de auteur al heeft getypt, en het schema kent daarvoor geen enum-waarde. «none» laat de invoer ongemoeid, wat precies is wat de bron beschrijft; «en-tight» zou er een vorm van maken die geen enkele Nederlandse bron voorschrijft. Aparte ingang van die van dashes, omdat de twee velden op verschillende bronnen rusten. De regel «ranges» staat standaard uit (spec 0.5.0). Geraadpleegd op 18.09.2026." + }, + { + "rule": "ellipsis", + "cite": "Nederlandse Taalunie, Taaladvies.net, «Punt na enz. of beletselteken aan het einde van een zin» (12 mei 2021): «na een afkorting met een punt of na een beletselteken aan het eind van een zin, komt geen extra punt», met het voorbeeld «Hou je van jazz, blues, soul …?»", + "url": "https://taaladvies.net/punt-na-enz-of-beletselteken-aan-het-einde-van-een-zin/", + "note": "Onderbouwt abbreviatedAfterTerminal = false. Het beletselteken is «een vaste eenheid van drie punten» en het vraagteken volgt erop; voor de Russische tweepuntsvorm «?..» geeft geen geraadpleegde Nederlandse bron een grondslag. Anders dan bij het Grieks valt hier niets af te wijken: het Nederlands schrijft juist wél een spatie vóór het beletselteken, en spaces.md §3.4 laat die spatie in elk locale staan — bron en motor zijn het hier eens. Geraadpleegd op 18.09.2026." + }, + { + "rule": "hyphen", + "cite": "Nederlandse Taalunie, Taaladvies.net, «Auto-ongeluk (afbreking)» (12 mei 2021): «Bij woordafbreking valt een koppelteken weg als wordt afgebroken op de plaats waar dat koppelteken in de grondvorm staat»", + "url": "https://taaladvies.net/auto-ongeluk-afbreking/", + "note": "Onderbouwt drie lege lijsten. Het Nederlands staat afbreking op het koppelteken niet alleen toe, het laat het koppelteken daarbij wégvallen — het omgekeerde van een claim op U+2011. Geen geraadpleegde bron omschrijft een gesloten klasse vormen waarvan het koppelteken een regelovergang moet weerstaan, en dat is het enige wat deze regel leest. Geraadpleegd op 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "Nederlandse Taalunie, Taaladvies.net, «Wel of geen spaties voor en na leestekens en symbolen (algemeen)» (12 mei 2021): «Vóór een punt, een komma, een dubbele punt, een puntkomma, een uitroepteken en een vraagteken komt geen spatie»; «Bij toevallige, niet-conventionele combinaties van een getal en een afgekorte eenheid […] komt er een spatie tussen het getal en de eenheid»; «Tussen een valutateken en het bijbehorende getal staat een spatie, tenzij het geheel deel uitmaakt van een samenstelling» — «De vaas kostte € 179,–»; BIPM, The International System of Units (SI), 9th ed., concise summary — uitsluitend voor de samenstelling van de symbolenlijst", + "url": "https://taaladvies.net/wel-of-geen-spaties-voor-en-na-leestekens-en-symbolen-algemeen/", + "note": "Drie velden uit één pagina. beforePunctuation en narrowBeforePunctuation leeg: alle zes leestekens worden bij name genoemd en krijgen geen spatie — een ontkenning, geen stilzwijgen. beforeUnits: BIPM levert welke reeksen SI-symbolen zijn, de Taalunie de Nederlandse conventie; eenletterige symbolen blijven weg zoals in fr.json. afterSymbols = [«€», «$»]: LET OP BIJ HET OVERNEMEN VAN fr.json — in het Nederlands gaat het valutateken aan het getal vooraf («€ 179»), in het Frans volgt het erop («2 €»), dus het hoort hier in afterSymbols en niet in beforeUnits. De twee leden zijn die welke het kopje «Valutatekens (€, $)» zelf noemt: een klasse-afleiding over een MET NAME GENOEMDE tweeledige klasse, gemarkeerd naar het voorbeeld van fr.json bij M., MM., Mmes. TOEGESTANE VARIANTEN, vastgelegd: voor het procentteken laat de Taalunie zowel «25 %» als «25%» toe, en bij °C schrijft zij dat er «meestal geen spatie» staat terwijl ISO er één voorschrijft. Dat hoeft niet beslecht te worden: N5 zet alleen een bestaande spatie om en voegt er nooit een in (nbsp.md §3.7). afterShortWords, beforeNumber en beforeWord zijn leeg: deze pagina loopt de leestekens en symbolen één voor één langs en zegt daarover niets, en het Nederlands kent geen tegenhanger van de Poolse sierotka-regel. Geraadpleegd op 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "Nederlandse Taalunie, Taaladvies.net, «Prof.( )dr.» (12 mei 2021): «Ja, tussen bijvoorbeeld prof. dr. komt een spatie»; «Alleen als de afgekorte woorden tezamen een afkorting vormen, vervalt de spatie: a.s., a.u.b., m.b.v., n.a.v., z.o.z.»; «In verzorgd zetwerk wordt tussen voorletters en in afkortingen als v.d. bij voorkeur een halve spatie (of dunspatie) geplaatst»", + "url": "http://taaladvies.net/legacylink.php?id=vraag/678", + "note": "Onderbouwt abbreviations = [«prof. dr.»] — de enige Nederlandse afkorting met een interne U+0020 die letterlijk is aangetroffen. De gesloten vormen (a.s., a.u.b.) hebben geen interne spatie, zodat N4 daar niets te bevorderen heeft; dáárom telt de lijst één ingang en is hij niet leeg. initialBinding = «none»: de enige Nederlandse uitspraak hierover vraagt om een DUNNE spatie, een waarde die het schema niet kent terwijl N7 U+00A0 invoegt — en, belangrijker, geen geraadpleegde bron zegt dat een voorletter niet door een regelovergang van de achternaam gescheiden mag worden, en dát is wat N7 werkelijk doet. Geraadpleegd op 18.09.2026." + } + ] +} diff --git a/vendor/polytypo-spec/locales/pl.json b/vendor/polytypo-spec/locales/pl.json new file mode 100644 index 0000000..b4970bd --- /dev/null +++ b/vendor/polytypo-spec/locales/pl.json @@ -0,0 +1,96 @@ +{ + "locale": "pl", + "name": "Polish", + "quotes": { + "primary": { + "open": "„", + "close": "”", + "innerSpace": "none" + }, + "secondary": { + "open": "»", + "close": "«", + "innerSpace": "none" + }, + "elisionIdioms": [] + }, + "dash": { + "parenthetical": "en-spaced", + "range": "en-tight" + }, + "ellipsis": { + "abbreviatedAfterTerminal": false + }, + "hyphen": { + "prefixes": [], + "suffixes": [], + "compounds": [] + }, + "nbsp": { + "beforePunctuation": [], + "narrowBeforePunctuation": [], + "afterShortWords": ["a", "i", "o", "u", "w", "z"], + "abbreviations": ["lek. med.", "inż. górn.", "bp sufr."], + "beforeUnits": ["%", "‰", "°C", "km", "cm", "mm", "kg", "km/h", "kWh"], + "beforeNumber": [], + "beforeWord": [], + "afterSymbols": ["§"], + "initialBinding": "none" + }, + "sources": [ + { + "rule": "quotes", + "cite": "Słownik języka polskiego PWN, «Zasady pisowni i interpunkcji», §98 «Cudzysłów», wstęp: «W druku i w rękopisach używa się najczęściej cudzysłowu o postaci: [U+201E] [U+201D] (tzw. cudzysłów apostrofowy)»; «W specyficznych zastosowaniach pojawia się też cudzysłów ostrokątny: [U+00BB] [U+00AB] lub [U+00AB] [U+00BB]. Cudzysłów o ostrzach skierowanych do środka jest używany […] w przypadku, gdy występuje cudzysłów w cudzysłowie»", + "url": "https://sjp.pwn.pl/zasady/Cudzyslow;629866.html", + "note": "Pierwszy stopień: U+201E otwierający, U+201D zamykający — nie U+201C, jak w niemieckim. Drugi stopień: para «o ostrzach skierowanych do środka», czyli U+00BB otwierający i U+00AB zamykający; para U+00AB…U+00BB jest w tym samym paragrafie przypisana do wyodrębniania znaczeń i do dialogów, a nie do cudzysłowu w cudzysłowie — kierunek jest więc odwrotny do tego, czego spodziewa się czytelnik znający francuskie «…». Kody znaków ustalono, pytając o U+XXXX dla każdego glifu z osobna, a nie na oko. innerSpace = «none»: żadne źródło nie żąda odstępu wewnątrz cudzysłowu. WARIANT DOPUSZCZALNY, odnotowany: Wolański, Poradnia Językowa PWN, «Cudzysłowy drugiego stopnia» (26.05.2020) dopuszcza na drugim stopniu zarówno »…«, jak i «…»; Poradnia jest źródłem doradczym niższej rangi niż «Zasady», więc wybrano formę, którą §98 wiąże wprost z cudzysłowem w cudzysłowie. Trzeci stopień zagnieżdżenia nie jest wyrażalny w locale.schema.json. Konsultowano 18.09.2026." + }, + { + "rule": "dashes", + "cite": "Słownik języka polskiego PWN, «Zasady pisowni i interpunkcji», [403] 93.7: «Wtrącenia ujmujemy w dwa myślniki»; [408] 93.12, UWAGA: «Półpauza używana w funkcji myślnika ma po bokach spacje»; 21.4, z przykładem «Wyrazy: czarny – biały to antonimy»", + "url": "https://sjp.pwn.pl/zasady/408-93-12-Myslnik-wyznaczajacy-relacje-miedzy-dwoma-wyrazami-lub-wartosciami;629831.html", + "note": "Uzasadnia dash.parenthetical = «en-spaced». Odstępy są w źródłach jednomyślne — myślnik ma spacje po obu stronach — natomiast DŁUGOŚĆ kreski nie jest przez PWN rozstrzygnięta: korpus [408] składa myślnik jako U+2014, przykład w 21.4 jako U+2013, a Bańko («przedziały liczbowe», 28.02.2012) pisze wprost, że myślnik «określany jest przez obecność pauz po bokach, a nie przez długość kreski». DECYZJA OPERATORA, 18.09.2026, a nie cytat: wybrano półpauzę U+2013, bo to ona jest w UWADZE [408] nazwana po imieniu w funkcji myślnika i bo taką samą wartość mają już de-DE, en-GB, fi i sv — przy źródle, które nie rozstrzyga, jednolitość w obrębie projektu jest lepszym kryterium niż preferencja. Skutek uboczny, odnotowany: dashes.md §3.4 P5 odrzuca ciąg dokładnie jednej U+2013 w każdym locale, więc istniejące polskie wtrącenia z półpauzą pozostają nietknięte, a zamieniane są U+002D i U+2014. Konsultowano 18.09.2026." + }, + { + "rule": "ranges", + "cite": "Słownik języka polskiego PWN, «Zasady pisowni i interpunkcji», [408] 93.12, UWAGA: «W druku liczby arabskie oznaczające przedział od — do rozdziela się półpauzą, czyli kreseczką średniej wielkości, niemającą po bokach odstępów, np. 1914–1918»", + "url": "https://sjp.pwn.pl/zasady/408-93-12-Myslnik-wyznaczajacy-relacje-miedzy-dwoma-wyrazami-lub-wartosciami;629831.html", + "note": "Uzasadnia dash.range = «en-tight»: półpauza U+2013 bez spacji. Potwierdzone dwukrotnie: Wolański, «Zakres liczbowy» (1.01.2024) — «Spacje wokół znaku przedziału […] to po prostu błąd ortotypograficzny»; oraz Bańko (28.02.2012), który przywołuje «Edycję tekstów» Wolańskiego w tym samym duchu — przywołanie jest cudze, samej książki nie konsultowano i nie jest tu cytowana. Reguła «ranges» jest domyślnie wyłączona (spec 0.5.0). Konsultowano 18.09.2026." + }, + { + "rule": "ellipsis", + "cite": "Słownik języka polskiego PWN, «Zasady pisowni i interpunkcji», [396] 92.4: gdy wielokropek zbiega się z pytajnikiem lub wykrzyknikiem, «znaki te w tekście umieszczamy», np. «Czy jest ona tu z wami…?», «Jak strasznie gorąco…!»", + "url": "https://sjp.pwn.pl/zasady/Wielokropek-obok-innych-znakow-interpunkcyjnych;629818.html", + "note": "Uzasadnia abbreviatedAfterTerminal = false. Wielokropek to zawsze trzy kropki, a pytajnik i wykrzyknik stoją PO nim — rosyjska forma dwukropkowa «?..» nie jest w polszczyźnie przewidziana przez żadne konsultowane źródło. Sprawdzono to celowo: gdyby polski tę formę miał, byłby drugim po rosyjskim locale z wartością true. Konsultowano 18.09.2026." + }, + { + "rule": "hyphen", + "cite": "Słownik języka polskiego PWN, «Zasady pisowni i interpunkcji», [196]: łącznik przenosi się do następnego wiersza, a na końcu poprzedniego stawia się znak podziału, np. «czarno- / -białe fotografie», «województwo warmińsko- / -mazurskie»", + "url": "https://sjp.pwn.pl/zasady/Podzial-wyrazu-w-miejscu-lacznika;629553.html", + "note": "Uzasadnia trzy puste listy. Polszczyzna nie tylko dopuszcza podział w miejscu łącznika — ona go normuje, co jest przeciwieństwem żądania U+2011. Puste listy czynią regułę dowodliwym no-opem dla polskiego (hyphen.md §2). Konsultowano 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "Słownik języka polskiego PWN, «Zasady pisowni i interpunkcji», 21.4: «Między literą kończącą wyraz a znakiem interpunkcyjnym […] nie stosujemy spacji»; 21.1.3: «w skrótach od nazw osób […] np. lek. med., inż. górn., bp sufr.»; 21.2: «Spację pomijamy […] między inicjałami, np. J.K. Bielecki»", + "url": "https://sjp.pwn.pl/zasady/Stosowanie-spacji-w-skrotach-od-dwoch-i-wiecej-wyrazow;4836486.html", + "note": "Trzy rzeczy z trzech sąsiadujących paragrafów. (1) beforePunctuation i narrowBeforePunctuation puste: polszczyzna nie stawia przed «:», «;», «!», «?» ani U+00A0, ani U+202F, a źródło odmawia im odstępu wprost — to zaprzeczenie, nie milczenie. (2) abbreviations: trzy skróty zacytowane dosłownie wraz z wewnętrzną spacją, czyli twierdzenie o PRZYNALEŻNOŚCI w rozumieniu nbsp.md §2.1. Świadomie pominięto «i in.» i «z d.»: N3 zajmuje te spacje pierwszy (nbsp.md §3.2), więc wpisy byłyby martwe, nie błędne. (3) initialBinding = «none»: polskie inicjały pisze się bez odstępu («J.K. Bielecki»), więc N7 nie ma czego zamieniać; to rzadki przypadek, w którym «none» opiera się na twierdzeniu pozytywnym, a nie na niecytowalnym zaprzeczeniu. beforeNumber i beforeWord pozostają puste: 21.1, 21.2 i 21.4 przeczytano w całości i żaden nie wiąże skrótu z następującą liczbą ani z wyrazem. Konsultowano 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "dr hab. Adam Wolański, Poradnia Językowa PWN, «Sieroty na końcu wiersza» (8.06.2018): «W wierszach tekstu, które liczą powyżej 40 znaków, nie należy zasadniczo pozostawiać na końcu wiersza jednoliterowych spójników i przyimków (a, i, o, u, w, z, A, I, O, U, W, Z)»", + "url": "https://sjp.pwn.pl/poradnia/haslo/Sieroty-na-koncu-wiersza;18684.html", + "note": "Uzasadnia afterShortWords. Lista jest zamknięta i zacytowana dosłownie; wersaliki pominięto, bo N3 dopasowuje pierwszą literę bez względu na wielkość (nbsp.md §3.5 krok 1). RANGA ŹRÓDŁA, powiedziana wprost, bo jest tu słabsza niż gdzie indziej w tym pliku: bezwarunkowy zakaz pochodzi z Poradni, która jest źródłem doradczym, natomiast «Zasady» [204] 54.8.1 są ŁAGODNIEJSZE — «W wąskich łamach jednoliterowe spójniki i przyimki mogą pozostawać na końcu wiersza w tekście ciągłym, natomiast w tytułach […] zawsze powinny być przenoszone» — a Bańko («słowa jednoliterowe na końcu wiersza», 16.02.2003) dodaje, że pozostawienie ich «nie stanowi błędu ortograficznego». Obie kwalifikacje — szerokość łamu i to, czy tekst jest tytułem — są dla silnika niewidoczne. DECYZJA OPERATORA, 18.09.2026: reguła jedzie bezwarunkowo, jak rosyjska afterShortWords, ponieważ wiązanie jednoliterowego przyimka jest w polskim składzie praktyką powszechną, a koszt błędnego zadziałania to jeden U+00A0 tam, gdzie i tak nikt nie chce złamania wiersza. Konsultowano 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "Główny Urząd Miar, «Zasady stosowania oznaczeń i nazw jednostek miar», akapit «Spacja»: «należy zostawiać spację między wartością liczbową a oznaczeniem jednostki» (100 g, 2 L; ale nie: 100g); pkt 12: «pomiędzy [symbolem %] a wartością liczbową wielkości pozostawia się spację»; BIPM, The International System of Units (SI), 9th ed., concise summary — dla składu samej listy symboli", + "url": "https://www.bipm.org/documents/20126/41483022/SI-Brochure-9-concise-EN.pdf", + "note": "Podział ról taki sam jak w en-US, fi, sv, es i pt: BIPM mówi, które łańcuchy są symbolami jednostek SI, a GUM i rozporządzenie — jaka jest polska konwencja odstępu. ZASTRZEŻENIE CO DO ŹRÓDŁA: dobór reguł w dokumencie GUM jest zawężony do towarów paczkowanych, natomiast akapit «Spacja» i pkt 12 powołują się na § 15 i § 8 ust. 4 rozporządzenia, które są prawem powszechnym. WARIANT DOPUSZCZALNY, odnotowany, bo dotyczy najczęstszego wpisu: polska tradycja ortotypograficzna pisze procent bez spacji, co Wolański («Jeszcze raz o spacji lub jej braku po znaku %», 26.11.2021) uznaje za równie poprawne. Rozbieżność nie wymaga rozstrzygnięcia: N5 wyłącznie ZAMIENIA istniejącą spację i nigdy jej nie wstawia (nbsp.md §3.7), więc «5 %» dostaje U+00A0, a «5%» zostaje nietknięte — jedna lista obsługuje obie poświadczone formy. Symbole jednoliterowe (m, g, l, s, A) pominięto zgodnie z praktyką fr.json. Konsultowano 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "dr hab. Adam Wolański, Poradnia Językowa PWN, «Symbol paragrafu i wyróżnienia tytułów aktów prawnych» (20.02.2019): «Symbol §, zastępujący wyraz paragraf, może być użyty tylko przed liczbą zapisaną cyframi. Należy go oddzielać od liczby spacją»", + "url": "https://sjp.pwn.pl/poradnia/haslo/Symbol-paragrafu-i-wyroznienia-tytulow-aktow-prawnych;19239.html", + "note": "Uzasadnia afterSymbols = [«§»]. Warunek «tylko przed liczbą zapisaną cyframi» pokrywa się co do joty z własnym strażnikiem N6, który wymaga, by cp[a+k+1] należało do klasy DIGIT (nbsp.md §3.8). Poradnia jest źródłem doradczym; «Zasady» kwestii nie poruszają, więc nie ma sprzeczności. Konsultowano 18.09.2026." + } + ] +} diff --git a/vendor/polytypo-spec/locales/pt-BR.json b/vendor/polytypo-spec/locales/pt-BR.json new file mode 100644 index 0000000..b87ad41 --- /dev/null +++ b/vendor/polytypo-spec/locales/pt-BR.json @@ -0,0 +1,82 @@ +{ + "locale": "pt-BR", + "name": "Portuguese (Brazil)", + "quotes": { + "primary": { + "open": "“", + "close": "”", + "innerSpace": "none" + }, + "secondary": { + "open": "‘", + "close": "’", + "innerSpace": "none" + }, + "elisionIdioms": [] + }, + "dash": { + "parenthetical": "en-spaced", + "range": "none" + }, + "ellipsis": { + "abbreviatedAfterTerminal": false + }, + "hyphen": { + "prefixes": [], + "suffixes": [], + "compounds": [] + }, + "nbsp": { + "beforePunctuation": [], + "narrowBeforePunctuation": [], + "afterShortWords": [], + "abbreviations": ["p. ex."], + "beforeUnits": ["%", "‰", "°C", "km", "cm", "mm", "kg", "kW", "kWh", "Hz"], + "beforeNumber": ["p."], + "beforeWord": [], + "afterSymbols": [], + "initialBinding": "none" + }, + "sources": [ + { + "rule": "quotes", + "cite": "Brasil, Presidência da República, Manual de Redação da Presidência da República, 2.ª ed. rev. e atual., Brasília 2002, §9.1.3.2 «Aspas»: «As aspas têm os seguintes empregos: a) usam-se antes e depois de uma citação textual», com os exemplos impressos «A Constituição […] afirma: “Todo o poder emana do povo, que o exerce por meio de representantes eleitos ou diretamente”», «publicado no “Jornal do Brasil”», «a alínea “a” do artigo 146 da Constituição»", + "url": "https://legis.sigepe.gov.br/sigepe-bgp-ws-legis/legis-service/download/?id=0000356386-ALPDF%2F2018", + "note": "Primário U+201C/U+201D, secundário U+2018/U+2019, ambos colados ao texto. FONTE DE NÍVEL INFERIOR, dito sem rodeios: é o manual de redação de um editor estatal, não uma academia — a Academia Brasileira de Letras publica um vocabulário ortográfico, que é lexical e não trata de pontuação, e não foi encontrada fonte brasileira de nível académico que enuncie o par primário. O manual nunca usa aspas angulares em nenhuma das páginas lidas e o seu capítulo III declara-se derivado das gramáticas brasileiras (Bechara, Cegalla, Luft, Kury). DECISÃO DO OPERADOR, 18.9.2026: perante um uso regional atestado mas sem fonte de nível académico, ficheiro próprio com a fonte que existe, claramente identificada, em vez de deixar o Brasil cair no fallback de pt-PT e receber aspas angulares que não usa — a mesma decisão registada na issue #29, «corrige-se acrescentando locales». O nível secundário assenta no exemplo de citação dentro de citação, não numa frase de regra, e é por isso a afirmação mais fraca deste ficheiro. Consultado em 18.9.2026." + }, + { + "rule": "dashes", + "cite": "Manual de Redação da Presidência da República (2.ª ed., 2002), §9.1.3.4 «Travessão»: «O travessão, que é um hífen prolongado (–), é empregado nos seguintes casos: a) substitui parênteses, vírgulas, dois-pontos: O controle inflacionário – meta prioritária do Governo – será ainda mais rigoroso»", + "url": "https://legis.sigepe.gov.br/sigepe-bgp-ws-legis/legis-service/download/?id=0000356386-ALPDF%2F2018", + "note": "Justifica dash.parenthetical = \"en-spaced\", e é aqui que pt-BR diverge de pt-PT de forma mensurável. A LARGURA não foi julgada a olho: extraiu-se a camada de texto do PDF e o carácter do exemplo é U+2013, ao passo que o mesmo exemplo estrutural no guia europeu dá U+2014. O papel e o espaçamento coincidem nas duas regiões — o travessão substitui parênteses e leva um espaço de cada lado —, diverge a largura. Consultado em 18.9.2026." + }, + { + "rule": "ranges", + "cite": "Nenhuma fonte brasileira consultada prescreve um sinal de intervalo diferente do hífen já escrito; o Manual de Redação da Presidência da República nada diz sobre intervalos", + "note": "dash.range = \"none\" por ausência de prescrição, e não por prescrição positiva como em pt-PT — a diferença de fundamento fica registada em vez de ser dissimulada. «none» preserva o que o autor escreveu, que é o comportamento seguro quando nenhuma fonte fala. Consultado em 18.9.2026." + }, + { + "rule": "ellipsis", + "cite": "Acordo Ortográfico da Língua Portuguesa (1990) e Código de Redação Interinstitucional (PT, 2022), ponto 10.4.7 «Reticências»: as reticências completas seguem-se imediatamente a «!» e a «?» («É o dianho!…», «porque não vais ter com o padre?…»); o Manual de Redação da Presidência da República não tem secção sobre reticências — o seu capítulo de pontuação (§9.2.4) trata apenas da vírgula, do ponto-e-vírgula, dos dois-pontos e dos pontos de interrogação e exclamação", + "url": "https://op.europa.eu/pt/publication-detail/-/publication/01ed788a-d266-11ec-a95f-01aa75ed71a1", + "note": "Justifica abbreviatedAfterTerminal = false. O passo citado escreve as reticências completas imediatamente a seguir a «!» e a «?» — «!…» e «?…» —, e nenhuma fonte consultada prevê a forma abreviada de dois pontos que o russo usa, pelo que esse ramo de ellipsis.md fica desligado para o português. Nenhuma fonte se pronuncia sobre U+2026 contra três U+002E: essa escolha é do motor e é igual em todas as locales. Consultado em 18.9.2026. A fonte brasileira cala-se sobre as reticências, pelo que o valor vem do lado europeu; não há divergência a registar, há silêncio." + }, + { + "rule": "hyphen", + "cite": "Acordo Ortográfico da Língua Portuguesa (1990), Base XX: «deve, por clareza gráfica, repetir-se o hífen no início da linha imediata»; Manual de Redação da Presidência da República (2.ª ed., 2002), §9.1.3.1, Observação: «Hífen de composição vocabular ou de ênclise e mesóclise é repetido quando coincide com translineação: decreto-/-lei, exigem-/-lhe, far-/-se-á»", + "url": "http://www.portaldalinguaportuguesa.org/?action=acordo&version=1990", + "note": "Justifica as três listas vazias, e justifica-as pela positiva, não por ausência de fonte. O português não só permite como PRESCREVE a quebra de linha sobre o hífen de um composto, repetindo-o na linha seguinte: uma forma que é normativamente quebrada nesse ponto não pode ser uma forma cujo hífen tenha de resistir à quebra, que é a única coisa que esta regra consome. A regra é, portanto, um no-op total demonstrável para o português (hyphen.md §2), e qualquer runtime que ligue compostos portugueses com U+2011 está errado. Corroborado pelo Código de Redação Interinstitucional (PT, 2022), ponto 10.2 e ponto 10.4.12 («segunda-/-feira», «salmão-do-/-atlântico»), e pelo Manual de Redação da Presidência da República (Brasil, 2.ª ed., 2002), §9.1.3.1 («decreto-/-lei», «far-/-se-á»). É o campo em que Portugal, o Brasil e o próprio Acordo dizem explicitamente a mesma coisa. Consultado em 18.9.2026." + }, + { + "rule": "nbsp", + "cite": "BIPM, The International System of Units (SI), 9.ª ed., resumo conciso: «A single space is always left between the number and the unit»; Código de Redação Interinstitucional (PT, 2022), anexo A3, pontos 2 e 3, para a lista de símbolos", + "url": "https://www.bipm.org/documents/20126/41483022/SI-Brochure-9-concise-EN.pdf", + "note": "Justifica nbsp.beforeUnits. A locale atesta a PERTENÇA — que estes símbolos são unidades e que se escrevem depois do número com um espaço; o mecanismo (converter esse espaço em U+00A0, nunca o inserir) é da regra e está fixado em nbsp.md §2.1. REPARO CITADO, mais importante do que qualquer inclusão: o ponto 10.9.1 exclui «h» por nome — «horas (o símbolo «h» escreve-se sempre sem ponto, sem espaços): eram as 18h30» —, pelo que «h» NÃO entra na lista e há um caso de conformidade a fixá-lo. Os símbolos de uma só letra (m, g, l, t, s, A, W, V, K) ficam igualmente de fora, embora atestados, pela mesma razão que em fr: não são desambiguáveis sem contexto. Note-se que o português escreve «7 %» com espaço, ao contrário do grego. Consultado em 18.9.2026. Para pt-BR a lista é a mesma: nenhuma fonte brasileira consultada a contradiz, e o BIPM não é uma autoridade sobre o português mas sobre que cadeias são símbolos de unidade do SI." + }, + { + "rule": "nbsp", + "cite": "Nenhuma fonte brasileira consultada exige espaço antes de pontuação dupla, nem ligação de abreviaturas a palavras ou iniciais; listas deliberadamente vazias", + "note": "Justifica as listas vazias e initialBinding = \"none\", e diz com exatidão em que se apoiam: ao contrário do guia grego, a parte portuguesa NÃO contém nenhuma frase que negue pelo nome o uso francês do espaço antes da pontuação dupla. A posição é «nenhuma fonte o exige», e não «uma fonte o proíbe»; o que se observa é que nenhum exemplo do capítulo o escreve, e isso é uma observação, assinalada como tal. beforeNumber contém apenas «p.»: o ponto 10.9.1 atesta a ligação («p. 24», «Lei n.º 123»), mas «n.º» NÃO pode ser listado, porque a nota (3) do ponto 6.4 do mesmo guia prescreve um «o» sobrescrito e RECUSA expressamente tanto U+00BA como U+00B0 — listar «n.º» seria citar uma fonte que proíbe esse mesmo carácter. A decisão do operador de 18.9.2026 sobre o «n°» francês cobre uma fonte SILENCIOSA e não se estende a uma que fala e recusa. beforeWord fica vazio: o anexo A3 enumera «Sr.», «Dr.», «Prof.», mas limita-se a expandi-los e nenhuma fonte os mostra ligados ao nome seguinte. GAP REGISTADO, não resolvido: o ponto 10.9.1 exige espaço protegido DENTRO dos grupos de algarismos («um total de 12 345 euros»; «este espaço é protegido»), e locale.schema.json não tem campo para isso. Consultado em 18.9.2026." + } + ] +} diff --git a/vendor/polytypo-spec/locales/pt-PT.json b/vendor/polytypo-spec/locales/pt-PT.json new file mode 100644 index 0000000..137703c --- /dev/null +++ b/vendor/polytypo-spec/locales/pt-PT.json @@ -0,0 +1,84 @@ +{ + "locale": "pt-PT", + "name": "Portuguese (Portugal)", + "quotes": { + "primary": { + "open": "«", + "close": "»", + "innerSpace": "none" + }, + "secondary": { + "open": "“", + "close": "”", + "innerSpace": "none" + }, + "elisionIdioms": [] + }, + "dash": { + "parenthetical": "em-spaced", + "range": "none" + }, + "ellipsis": { + "abbreviatedAfterTerminal": false + }, + "hyphen": { + "prefixes": [], + "suffixes": [], + "compounds": [] + }, + "nbsp": { + "beforePunctuation": [], + "narrowBeforePunctuation": [], + "afterShortWords": [], + "abbreviations": ["p. ex."], + "beforeUnits": ["%", "‰", "°C", "km", "cm", "mm", "kg", "kW", "kWh", "Hz"], + "beforeNumber": ["p."], + "beforeWord": [], + "afterSymbols": [], + "initialBinding": "none" + }, + "sources": [ + { + "rule": "quotes", + "cite": "Serviço das Publicações da União Europeia, Código de Redação Interinstitucional (edição PT, 2022, ISBN 978-92-78-42820-4), Quarta parte «Convenções próprias da língua portuguesa», ponto 10.4.10 «Aspas», N. B.: «O primeiro nível de aspas a utilizar corresponde às aspas angulares («»). Quando necessário, utilizam-se três níveis de aspas devidamente hierarquizadas: «…» — as aspas angulares, “…” — as aspas curvas duplas ou vírgulas dobradas, ‘…’ — as aspas curvas simples ou vírgulas simples»", + "url": "https://op.europa.eu/pt/publication-detail/-/publication/01ed788a-d266-11ec-a95f-01aa75ed71a1", + "note": "Primário U+00AB/U+00BB, secundário U+201C/U+201D. O terceiro nível descrito pela fonte não é exprimível em locale.schema.json, que só tem primary e secondary — limite do esquema, não lacuna da fonte, como já consta de el.json. innerSpace = \"none\": todos os exemplos do ponto 10.4.10 escrevem o texto colado às aspas e a secção nunca pede espaço interior. A Quarta parte é o capítulo específico da língua portuguesa; a Terceira parte do mesmo guia é deliberadamente NÃO invocada, porque o seu §6.4 declara que as suas regras «são o resultado de um acordo interinstitucional» e que «certas escolhas foram feitas em prol de uma convenção comum» — estilo de editor, não prova sobre o português, a mesma desqualificação que el.json regista. É POR ISTO que esta locale é pt-PT e não pt: o uso brasileiro diverge e tem ficheiro próprio (pt-BR), em vez de ser apanhado por um fallback que lhe daria aspas que não usa. Consultado em 18.9.2026." + }, + { + "rule": "dashes", + "cite": "Código de Redação Interinstitucional (PT, 2022), Quarta parte, ponto 10.4.8 «Travessão»: «O travessão (traço horizontal maior que o hífen) emprega-se: […] d) No lugar de parênteses: As condições — ordenado e subvenções — eram boas»", + "url": "https://op.europa.eu/pt/publication-detail/-/publication/01ed788a-d266-11ec-a95f-01aa75ed71a1", + "note": "Justifica dash.parenthetical = \"em-spaced\". O papel (substitui parênteses) e o espaçamento (um espaço ordinário de cada lado de CADA travessão) estão no exemplo impresso; ao contrário do grego, do espanhol e do italiano, o português não usa o padrão «espaços fora do par, colado por dentro», pelo que o enum exprime a convenção sem forçar nada. A LARGURA foi verificada extraindo a camada de texto do PDF, não julgada a olho sobre a página rasterizada: o carácter é U+2014. Esta é a segunda divergência regional do português — o Manual de Redação da Presidência da República (Brasil) define o travessão como «um hífen prolongado» e o seu texto extraído dá U+2013 —, e é a segunda razão para pt-PT e pt-BR serem ficheiros distintos. Consultado em 18.9.2026." + }, + { + "rule": "ranges", + "cite": "Código de Redação Interinstitucional (PT, 2022), ponto 10.4.11: «Quando se trata de dois anos completos ou de um período de vários anos usa-se o hífen: o programa para 1996-1997; o período de 1993-1996»; ponto 10.9.1: «Para qualquer período que decorra entre dois anos consecutivos, estes são separados por um hífen, se o período abrange a totalidade dos dois anos (1990-1991), e por uma barra, em caso contrário (ano letivo de 1990/1991)»", + "url": "https://op.europa.eu/pt/publication-detail/-/publication/01ed788a-d266-11ec-a95f-01aa75ed71a1", + "note": "Justifica dash.range = \"none\" pela positiva. A regra é enunciada duas vezes, em dois capítulos da parte específica da língua, e as duas vezes nomeia o hífen; a barra fica reservada para o período que não abrange os dois anos completos. «none» é o único valor do enum que respeita a fonte, porque `ranges` não emite nada nesse modo (ranges.md §2) e o U+002D escrito pelo autor sobrevive — substituí-lo por U+2013 contrariaria a citação. Consultado em 18.9.2026." + }, + { + "rule": "ellipsis", + "cite": "Código de Redação Interinstitucional (PT, 2022), ponto 10.4.7 «Reticências», com o exemplo impresso «É o dianho!… É o dianho!… E, olha lá, porque não vais ter com o padre?…» (Aquilino Ribeiro)", + "url": "https://op.europa.eu/pt/publication-detail/-/publication/01ed788a-d266-11ec-a95f-01aa75ed71a1", + "note": "Justifica abbreviatedAfterTerminal = false. O passo citado escreve as reticências completas imediatamente a seguir a «!» e a «?» — «!…» e «?…» —, e nenhuma fonte consultada prevê a forma abreviada de dois pontos que o russo usa, pelo que esse ramo de ellipsis.md fica desligado para o português. Nenhuma fonte se pronuncia sobre U+2026 contra três U+002E: essa escolha é do motor e é igual em todas as locales. Consultado em 18.9.2026." + }, + { + "rule": "hyphen", + "cite": "Acordo Ortográfico da Língua Portuguesa (1990), Base XX «Da divisão silábica»: «Na translineação de uma palavra composta ou de uma combinação de palavras em que há um hífen, ou mais, se a partição coincide com o final de um dos elementos ou membros, deve, por clareza gráfica, repetir-se o hífen no início da linha imediata: ex- -alferes»", + "url": "http://www.portaldalinguaportuguesa.org/?action=acordo&version=1990", + "note": "Justifica as três listas vazias, e justifica-as pela positiva, não por ausência de fonte. O português não só permite como PRESCREVE a quebra de linha sobre o hífen de um composto, repetindo-o na linha seguinte: uma forma que é normativamente quebrada nesse ponto não pode ser uma forma cujo hífen tenha de resistir à quebra, que é a única coisa que esta regra consome. A regra é, portanto, um no-op total demonstrável para o português (hyphen.md §2), e qualquer runtime que ligue compostos portugueses com U+2011 está errado. Corroborado pelo Código de Redação Interinstitucional (PT, 2022), ponto 10.2 e ponto 10.4.12 («segunda-/-feira», «salmão-do-/-atlântico»), e pelo Manual de Redação da Presidência da República (Brasil, 2.ª ed., 2002), §9.1.3.1 («decreto-/-lei», «far-/-se-á»). É o campo em que Portugal, o Brasil e o próprio Acordo dizem explicitamente a mesma coisa. Consultado em 18.9.2026." + }, + { + "rule": "nbsp", + "cite": "Código de Redação Interinstitucional (PT, 2022), anexo A3 «Abreviaturas e símbolos», pontos 2 e 3, com as Observações «Todos os números são acompanhados dos respetivos símbolos: de 4 m em 4 m; de 1 kg, 6 kg a 15 kg», e Quarta parte, ponto 10.9.1: «As percentagens, pesos e medidas escrevem-se numericamente: 7 % do volume de negócios», «a temperatura atingiu hoje os 39 °C»; BIPM, The International System of Units (SI), 9.ª ed., resumo conciso: «A single space is always left between the number and the unit»", + "url": "https://www.bipm.org/documents/20126/41483022/SI-Brochure-9-concise-EN.pdf", + "note": "Justifica nbsp.beforeUnits. A locale atesta a PERTENÇA — que estes símbolos são unidades e que se escrevem depois do número com um espaço; o mecanismo (converter esse espaço em U+00A0, nunca o inserir) é da regra e está fixado em nbsp.md §2.1. REPARO CITADO, mais importante do que qualquer inclusão: o ponto 10.9.1 exclui «h» por nome — «horas (o símbolo «h» escreve-se sempre sem ponto, sem espaços): eram as 18h30» —, pelo que «h» NÃO entra na lista e há um caso de conformidade a fixá-lo. Os símbolos de uma só letra (m, g, l, t, s, A, W, V, K) ficam igualmente de fora, embora atestados, pela mesma razão que em fr: não são desambiguáveis sem contexto. Note-se que o português escreve «7 %» com espaço, ao contrário do grego. Consultado em 18.9.2026." + }, + { + "rule": "nbsp", + "cite": "Código de Redação Interinstitucional (PT, 2022), anexo A3, ponto 4 «Obras»: «p. ex. por exemplo»; «e. g. exempli gratia (por exemplo). Utilizar de preferência p. ex.»; Quarta parte, ponto 10.9.1: «paginação corrente, parágrafos, artigos: artigo 2.º, terceiro parágrafo, alínea b), p. 24»; nota (3) do ponto 6.4: «Para o «º» ordinal (1.º, 2.º…) ou em «n.º», utilizar a terminação «o» após o ponto e em posição superior à linha [não utilizar o sinal «º» do teclado Azerty nem a sequência Alt 0176 (símbolo do grau «°»)]»", + "url": "https://op.europa.eu/pt/publication-detail/-/publication/01ed788a-d266-11ec-a95f-01aa75ed71a1", + "note": "Justifica as listas vazias e initialBinding = \"none\", e diz com exatidão em que se apoiam: ao contrário do guia grego, a parte portuguesa NÃO contém nenhuma frase que negue pelo nome o uso francês do espaço antes da pontuação dupla. A posição é «nenhuma fonte o exige», e não «uma fonte o proíbe»; o que se observa é que nenhum exemplo do capítulo o escreve, e isso é uma observação, assinalada como tal. beforeNumber contém apenas «p.»: o ponto 10.9.1 atesta a ligação («p. 24», «Lei n.º 123»), mas «n.º» NÃO pode ser listado, porque a nota (3) do ponto 6.4 do mesmo guia prescreve um «o» sobrescrito e RECUSA expressamente tanto U+00BA como U+00B0 — listar «n.º» seria citar uma fonte que proíbe esse mesmo carácter. A decisão do operador de 18.9.2026 sobre o «n°» francês cobre uma fonte SILENCIOSA e não se estende a uma que fala e recusa. beforeWord fica vazio: o anexo A3 enumera «Sr.», «Dr.», «Prof.», mas limita-se a expandi-los e nenhuma fonte os mostra ligados ao nome seguinte. GAP REGISTADO, não resolvido: o ponto 10.9.1 exige espaço protegido DENTRO dos grupos de algarismos («um total de 12 345 euros»; «este espaço é protegido»), e locale.schema.json não tem campo para isso. Consultado em 18.9.2026." + } + ] +} diff --git a/vendor/polytypo-spec/locales/registry.json b/vendor/polytypo-spec/locales/registry.json index a680b67..c053496 100644 --- a/vendor/polytypo-spec/locales/registry.json +++ b/vendor/polytypo-spec/locales/registry.json @@ -1,9 +1,29 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "$comment": "Locale resolution input. Algorithm is specified in spec/rules/locale-resolution.md and is identical in every runtime — never delegate it to a platform locale-negotiation library. \"spec\" here must track spec/VERSION exactly — it is not itself the global version source; scripts/validate-spec.mjs enforces the match.", - "locales": ["en-US", "en-GB", "de-DE", "de-CH", "fr", "fr-CA", "ru", "fi", "sv", "el"], + "locales": [ + "en-US", + "en-GB", + "de-DE", + "de-CH", + "fr", + "fr-CA", + "ru", + "fi", + "sv", + "el", + "es", + "it", + "pt-PT", + "pt-BR", + "nl", + "pl", + "uk", + "cs" + ], "aliases": { "en": "en-US", - "de": "de-DE" + "de": "de-DE", + "pt": "pt-PT" } } diff --git a/vendor/polytypo-spec/locales/ru.json b/vendor/polytypo-spec/locales/ru.json index 81bc303..cf8e861 100644 --- a/vendor/polytypo-spec/locales/ru.json +++ b/vendor/polytypo-spec/locales/ru.json @@ -94,13 +94,13 @@ "rule": "nbsp", "cite": "Мильчин А. Э., Чельцова Л. К. «Справочник издателя и автора»: неразрывный пробел ставится между инициалами и между инициалами и фамилией («А. С. Пушкин»), после однобуквенных предлогов и союзов, между знаками № и § и относящимися к ним числами, между числом и относящейся к нему единицей измерения или счётным словом («1981 г.», «5 млн»), а также внутри сокращений «и т. д.», «и т. п.», «т. е.»", "url": "https://orfogrammka.ru/%D1%82%D0%B8%D0%BF%D0%BE%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D0%BA%D0%B0/%D0%BF%D1%80%D0%BE%D0%B1%D0%B5%D0%BB_%D0%B8_%D0%B8%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D1%8B/", - "note": "Список afterShortWords сознательно ограничен однобуквенными предлогами и союзами (а, в, и, к, о, с, у) и однозначными двухбуквенными предлогами (во, до, за, из, ко, на, об, от, по, со). Частицы и союзы «не», «ни», «но», «же», «ли», «бы» не включены: правило для них — рекомендация вёрстки, а не норма, и связывание их даёт заметный риск ложных срабатываний. Префиксные сокращения «г. Москва», «ул. Ленина» (docs/PLAN.md §7) выразить нельзя: afterSymbols по описанию схемы связывает символ со следующим ЧИСЛОМ, а не со словом; «г.» здесь помещено в beforeUnits в значении «год» после числа («2020 г.»)." + "note": "Список afterShortWords сознательно ограничен однобуквенными предлогами и союзами (а, в, и, к, о, с, у) и однозначными двухбуквенными предлогами (во, до, за, из, ко, на, об, от, по, со). Частицы и союзы «не», «ни», «но», «же», «ли», «бы» не включены: правило для них — рекомендация вёрстки, а не норма, и связывание их даёт заметный риск ложных срабатываний. Префиксные сокращения из строки «ru» в docs/PLAN.md §7 («г.», «ул.») с появлением beforeWord и N10 стали выразимы: «ул.» и «пл.» перечислены там, обоснование — в следующей записи. «г.» остаётся невыразимым, но не из-за формы поля: здесь оно помещено в beforeUnits в значении «год» после числа («2020 г.»), а в значении «город» связывается вправо, и литеральный список эти два смысла не различает." }, { "rule": "nbsp", "cite": "«Технические правила набора», раздел «Общие требования к набору», п. 5: «Отбиваются слова от имен собственных, к которым они относятся (ул. Советская)»; раздел «Переносы», п. 4: «Не должны быть отделены при переносе из одной строки в другую: а) фамилии от инициалов или один инициал от другого; б) сокращенные слова имен собственных, к которым они относятся, например: тов. Сергеева, г. Гомель, пл. Ленина; … г) арабские или римские цифры от их сокращенных или полных наименований, например: 2010 г., 800 руб., 50 куб. см, XX век; д) знаки и обозначения (№, §, % и т. п.) от следующих за ними цифр»", "url": "https://old.gsu.by/pages/izdat/2023/tehnicheskie_pravila_nabora.pdf", - "note": "Текст сверен по самому PDF; это издательский свод технических правил набора (Гомельский госуниверситет), то есть опубликованное изложение отраслевых правил (Мильчин, ОСТ 29.115-88), а не первоисточник: главу «Технические правила набора и вёрстки» у Мильчина проверить онлайн не удалось (доступное издание 1998 г. содержит только части 1—3 без этой главы). Пункт 4б — единственное найденное нормативное основание для beforeWord. «г.» в этот список сознательно НЕ включено: «г.» нормативно связывается и влево как «год» (п. 4г, «2010 г.», уже отражено в beforeUnits), и вправо как «город» (п. 4б, «г. Гомель»), а литеральный список без контекста эти два случая не различает — во фразе «в 1147 г. Москва была основана» правило beforeWord склеило бы «г.» с «Москва» через границу оборота. Различить их можно, только посмотрев влево на цифру и вправо на топоним, то есть по контексту, чего декларативный список не выражает. По той же причине не включены «гг.», «в.», «вв.». Оставлены «ул.» и «пл.» — однозначные топонимические сокращения, и обе формы процитированы дословно: «пл. Ленина» в «Переносах» п. 4б, «ул. Советская» в «Общих требованиях к набору» п. 5. «д.», «стр.», «корп.», «кв.» относятся к следующему ЧИСЛУ, а не к слову, поэтому в beforeWord им не место. beforeNumber пуст, и это подтверждённое отсутствие правила, а не ненайденная цитата: перечень «Переносов» п. 4 закрытый и исчерпывающий, он содержит обратное направление (п. 4г, «2010 г.») и знаки (п. 4д, «№ 75»), но конструкции «сокращение + следующее число» в нём нет. Мильчин, «Справочник издателя и автора», § 9.1.1 («Употребление в ссылках сокращений слов и условных сокращений»: «Книговедческие термины при цифровых номерах или литерах рекомендуется для экономии места сокращать») нормирует, КАКОЕ сокращение писать перед числом, но о пробеле не говорит ничего. Страница «Орфограммки» с примером «гл. IV» отвергнута: она ссылается только на Википедию и Хабр." + "note": "Текст сверен по самому PDF; это издательский свод технических правил набора (Гомельский госуниверситет), то есть опубликованное изложение отраслевых правил (Мильчин, ОСТ 29.115-88), а не первоисточник: главу «Технические правила набора и вёрстки» у Мильчина проверить онлайн не удалось (доступное издание 1998 г. содержит только части 1—3 без этой главы). Пункт 4б — единственное найденное нормативное основание для beforeWord. «г.» в этот список сознательно НЕ включено: «г.» нормативно связывается и влево как «год» (п. 4г, «2010 г.», уже отражено в beforeUnits), и вправо как «город» (п. 4б, «г. Гомель»), а литеральный список без контекста эти два случая не различает — во фразе «в 1147 г. Москва была основана» правило beforeWord склеило бы «г.» с «Москва» через границу оборота. Различить их можно, только посмотрев влево на цифру и вправо на топоним, то есть по контексту, чего декларативный список не выражает. По той же причине не включены «гг.», «в.», «вв.». Оставлены «ул.» и «пл.» — однозначные топонимические сокращения, и обе формы процитированы дословно: «пл. Ленина» в «Переносах» п. 4б, «ул. Советская» в «Общих требованиях к набору» п. 5. «д.», «стр.», «корп.», «кв.» относятся к следующему ЧИСЛУ, а не к слову, поэтому в beforeWord им не место. Для «стр.» есть и более сильное основание, проверенное по изданию 1998 г. при разборе issue #30: § 4.4.4 («Сокращения при внутритекстовых ссылках и сопоставлениях») пишет дословно: «Ранее широко применявшееся сокращение стр. (страница) рекомендуется заменять сокращением с., поскольку оно закреплено ГОСТ 7.12—93, а две формы сокращения одного слова нарушают принцип единообразия». То есть источник не просто молчит о пробеле — он не рекомендует саму форму. Там же: «Все сокращения, кроме см. и ср., употребляются только в сочетании с цифрами или буквами», что подтверждает состав списка, но о самой отбивке по-прежнему не говорит. beforeNumber пуст, и это подтверждённое отсутствие правила, а не ненайденная цитата: перечень «Переносов» п. 4 закрытый и исчерпывающий, он содержит обратное направление (п. 4г, «2010 г.») и знаки (п. 4д, «№ 75»), но конструкции «сокращение + следующее число» в нём нет. Мильчин, «Справочник издателя и автора», § 9.1.1 («Употребление в ссылках сокращений слов и условных сокращений»: «Книговедческие термины при цифровых номерах или литерах рекомендуется для экономии места сокращать») нормирует, КАКОЕ сокращение писать перед числом, но о пробеле не говорит ничего. Страница «Орфограммки» с примером «гл. IV» отвергнута: она ссылается только на Википедию и Хабр." }, { "rule": "hyphen", diff --git a/vendor/polytypo-spec/locales/uk.json b/vendor/polytypo-spec/locales/uk.json new file mode 100644 index 0000000..f2eed85 --- /dev/null +++ b/vendor/polytypo-spec/locales/uk.json @@ -0,0 +1,130 @@ +{ + "locale": "uk", + "name": "Ukrainian", + "quotes": { + "primary": { + "open": "«", + "close": "»", + "innerSpace": "none" + }, + "secondary": { + "open": "“", + "close": "”", + "innerSpace": "none" + }, + "elisionIdioms": [] + }, + "dash": { + "parenthetical": "em-spaced", + "range": "em-tight" + }, + "ellipsis": { + "abbreviatedAfterTerminal": true + }, + "hyphen": { + "prefixes": ["будь-", "казна-", "хтозна-", "бозна-"], + "suffixes": ["-бо", "-но", "-от", "-то", "-таки", "-будь", "-небудь"], + "compounds": [ + "вид-во", + "гр-н", + "ін-т", + "р-н", + "ун-т", + "ф-ка", + "т-во", + "з-за", + "із-за", + "з-над", + "з-перед", + "з-під", + "із-під", + "з-поза", + "з-поміж", + "з-понад", + "з-попід", + "з-посеред", + "з-проміж" + ] + }, + "nbsp": { + "beforePunctuation": [], + "narrowBeforePunctuation": [], + "afterShortWords": [], + "abbreviations": ["і т. д.", "і т. ін.", "та ін.", "куб. см"], + "beforeUnits": [ + "%", + "га", + "год", + "дм", + "кБ", + "кВт", + "кг", + "км", + "мм", + "см", + "хв", + "Вт", + "км/год", + "м/с", + "млн", + "млрд", + "трлн", + "грн", + "р." + ], + "beforeNumber": [], + "beforeWord": ["акад.", "доц.", "проф."], + "afterSymbols": [], + "initialBinding": "chain" + }, + "sources": [ + { + "rule": "quotes", + "cite": "Український правопис (2019), схвалений Кабінетом Міністрів України (Постанова № 437 від 22.05.2019), § 164 «ЛАПКИ (« », “ ”, „ “, рідше „ ”)», п. 3: «У функції перших рекомендовано вживати кутові лапки, або «лапки-ялинки» («…»), у функції внутрішніх — «лапки-лапки» (“…” та ін.): «Це мій “Кобзар”», — сказав він»; там само: «На письмі (у рукописних текстах) «лапки-лапки» традиційно використовують у формі „…“»", + "url": "https://www.ulif.org.ua/system/files/pravopus-new.pdf", + "note": "Зовнішні лапки — U+00AB і U+00BB, внутрішні — U+201C і U+201D. Код кожного знака встановлено за друкованим зображенням с. 247 офіційного видання, а не за текстовою конверсією: у прикладі § 164 п. 3 обидва внутрішні знаки підняті до верху рядка, відкривальний має форму 6, закривальний — форму 9. ЦЕ СПРОСТОВУЄ поширене припущення, що українська бере всередину „…“: заголовок § 164 справді дозволяє чотири пари, але саме п. 3 відносить „…“ до РУКОПИСНИХ текстів, а для друкованого рекомендує “…”. innerSpace = «none»: жодне джерело не вимагає відступу всередині лапок. Третій рівень вкладення в locale.schema.json невиразний. Звірено 18.09.2026." + }, + { + "rule": "dashes", + "cite": "Український правопис (2019), § 161 «ТИРЕ (—)», I, п. 10—11 і Примітка 2: тире ставимо перед відокремленим зворотом або вставленою конструкцією — «Топольський — молодий чоловік, але — на думку пана посла — незвичайно талановитий і солідний» (О. Маковей)", + "url": "https://www.ulif.org.ua/system/files/pravopus-new.pdf", + "note": "Обґрунтовує dash.parenthetical = «em-spaced». ДОВЖИНА встановлена прямо: заголовок параграфа — «ТИРЕ (—)», тобто U+2014, і цей самий знак стоїть у кожному прикладі §§ 161, 166, 167. ВІДБИВКА встановлена протиставленням, а не прозовим формулюванням: правопис ніде не пише «тире відбивається пробілами», але Примітка до п. 14 каже «тире ставимо без відступів між знаками» саме для випадку між цифрами, а «без відступів» має сенс лише як відхилення від відбитого за замовчуванням. Це єдиний запис цього файлу, що спирається на висновок із тексту джерела, і він позначений як такий свідомо. Звірено 18.09.2026." + }, + { + "rule": "ranges", + "cite": "Український правопис (2019), § 161 «ТИРЕ (—)», I, п. 14, Примітка: «Між цифрами в таких випадках тире ставимо без відступів між знаками: у 2010—2018 роках; пам'ятки української мови XVI—XVIII ст.; на сторінках 1—10; у 1—4 томах, але, напр.: наприкінці XX — на початку XXI ст.»", + "url": "https://www.ulif.org.ua/system/files/pravopus-new.pdf", + "note": "Обґрунтовує dash.range = «em-tight»: довге тире U+2014 без відбивки. Протиставлення в самій Примітці («на сторінках 1—10» без відступів, але «наприкінці XX — на початку XXI ст.» з відступами) показує, що безвідступна форма стосується рівно того, що робить правило ranges. Правило вимкнене за замовчуванням (spec 0.5.0). Звірено 18.09.2026." + }, + { + "rule": "ellipsis", + "cite": "Український правопис (2019), § 162 «ТРИ КРАПКИ, АБО КРАПКИ (…)», Примітка: «у постпозиції — після знака питання і знака оклику — ставимо дві крапки: Стражники на людей стріляли, це відомо, а щоб селяни?.. (К. Гордієнко); Встає народ, гудуть мости, Рокочуть ріки ясноводі!.. (М. Рильський)»; § 166 «КОМБІНОВАНЕ ВЖИВАННЯ РОЗДІЛОВИХ ЗНАКІВ», п. 2, що перелічує допустимі поєднання як «…?; …!; ?..; !..»", + "url": "https://www.ulif.org.ua/system/files/pravopus-new.pdf", + "note": "Обґрунтовує abbreviatedAfterTerminal = true. Українська — друга після російської локаль із цим значенням, і це перевірено окремо за двома параграфами, а не перенесено за аналогією зі спорідненої мови. Звірено 18.09.2026." + }, + { + "rule": "hyphen", + "cite": "Український правопис (2019), § 64 «Технічні правила переносу», п. 4: «Не можна розривати умовні (графічні) скорочення на зразок вид-во, і т. д., і т. ін., та ін., т-во тощо»; § 62, п. 2: «У графічних скороченнях пропущену середню частину слова позначаємо дефісом: вид-во (видавництво), гр-н (громадянин), ін-т (інститут), р-н (район), ун-т (університет), ф-ка (фабрика)»", + "url": "https://www.ulif.org.ua/system/files/pravopus-new.pdf", + "note": "Це єдина частина hyphen для української, де НЕРОЗРИВНІСТЬ САМА Є НОРМОЮ, а не рішенням проєкту: § 64 п. 4 прямо забороняє розривати цей клас, а § 62 п. 2 закриває його літеральним переліком, бо «тощо» в § 64 залишає клас відкритим. Українська цим відрізняється від польської, де PWN [196] поділ у місці дефіса саме ПРИПИСУЄ, через що pl.json має три порожні списки. Звірено 18.09.2026." + }, + { + "rule": "hyphen", + "cite": "Український правопис (2019), § 42 «Прийменники», п. 2: «З дефісом пишемо складені прийменники, утворені з простих прийменників з, із та інших прийменників: з-за (із-за), з-над, з-перед, з-під (із-під), з-поза, з-поміж, з-понад, з-попід, з-посеред, з-проміж»; § 44 «Частки», п. 3: «З дефісом пишемо: 1) частки -бо, -но, -от, -то, -таки … 2) частки будь-, -будь, -небудь, казна-, хтозна-, бозна- із займенниками і прислівниками»", + "url": "https://www.ulif.org.ua/system/files/pravopus-new.pdf", + "note": "Ці параграфи нормативні для СКЛАДУ форм, але не для заборони переносу, і змішувати це не можна — так само, як у ru.json. §§ 63 і 64 прочитано повністю: § 63 нормує поділ за складами, § 64 забороняє розривати ініціали, назви мір, нарощення й графічні скорочення, але про дефіс у формах §§ 42 і 44 не каже нічого. Отже, для цих класів зв'язування через U+2011 — рішення проєкту (docs/PLAN.md §3.3), а не орфографічна норма, і це записано прямо. НЕ ВНЕСЕНО, свідомо: § 64 п. 3 («Граматичні закінчення, поєднані із цифрами дефісом, не можна відривати й переносити: 2-й, 4-го, 10-му») нормативно нерозривний, але це форма «цифра-дефіс-літера»; чи є це членством у hyphen.suffixes, чи вже алгоритмом, має вирішити spec-guardian. Звірено 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "Український правопис (2019), § 64 «Технічні правила переносу», п. 1: «Не можна переносити прізвища, залишаючи в кінці попереднього рядка ініціали або інші умовні скорочення, що належать до них: Т. Г. Шевченко (не Т. Г. // Шевченко), гр. Іваненко, акад. (доц., проф.) Гончаренко, п. Гнатюк»; п. 4: «Не можна розривати умовні (графічні) скорочення на зразок вид-во, і т. д., і т. ін., та ін., т-во тощо»; п. 5: «Не можна переносити в наступний рядок розділові знаки (крім тире), дужку або лапки, що закривають попередній рядок»", + "url": "https://www.ulif.org.ua/system/files/pravopus-new.pdf", + "note": "§ 64 — ЗАКРИТИЙ перелік із п'яти пунктів, і це важливо не лише тим, що він містить, а й тим, чого в ньому немає. (1) initialBinding = «chain»: п. 1 наводить послідовність ДВОХ ініціалів і не дає прикладу одного ініціала перед прізвищем. (2) beforeWord: з п. 1 взято лише «акад.», «доц.», «проф.». «п.» і «гр.» свідомо НЕ внесено за тією самою дисципліною, з якої ru.json виключає «г.»: «п.» — це також «пункт» («п. 3»), «гр.» — також «градус» і «графа», а літеральний список цих напрямків не розрізняє. (3) beforePunctuation і narrowBeforePunctuation порожні: п. 5 прив'язує розділовий знак до ПОПЕРЕДНЬОГО слова — це заперечення, а не мовчання. (4) afterShortWords ПОРОЖНІЙ, і це підтверджена відсутність норми: перелік § 64 закритий, правила про однобуквені прийменники в ньому немає, а в самому правописі «і», «у», «в», «з» регулярно стоять у кінці рядка. Список ru.json сюди НЕ переноситься за аналогією, хоча мови споріднені. (5) afterSymbols і beforeNumber порожні: конструкцій «символ + число» і «скорочення + число» § 64 не містить. Звірено 18.09.2026." + }, + { + "rule": "nbsp", + "cite": "Український правопис (2019), § 64, п. 2: «Не можна відривати скорочені назви мір від цифр, до яких вони належать: 2008 р. (не 2008 // р.), 150 га (не 150 // га), 20 см³ або 20 куб. см, 5 г (не 5 // г)»; § 62: «Скорочені назви одиниць вимірювання пишемо без крапок: Б — байт, Вт — ват, г — грам, га — гектар, год — година, дм — дециметр, кБ — кілобайт, кВт — кіловат, кг — кілограм, км — кілометр, л — літр, м — метр, мм — міліметр, с — секунда, см — сантиметр, т — тонна, хв — хвилина, ц — центнер»; BIPM, The International System of Units (SI), 9th ed., concise summary: «A single space is always left between the number and the unit»", + "url": "https://www.bipm.org/documents/20126/41483022/SI-Brochure-9-concise-EN.pdf", + "note": "Розподіл ролей тут ІНШИЙ, ніж у pl, fi, sv і en-US: там BIPM дає перелік символів, а національне джерело — конвенцію відступу; для української національне джерело дає і те, і те, бо § 64 п. 2 нормує саме невідривність. BIPM наведено як підтвердження загального принципу, а не як несуча цитата. Однобуквені позначення (г, л, м, с, т, ц, Б) свідомо пропущено: правий кордон N5 вимагає лише, щоб cp[a+k] не належав ALNUM, і пробіл цю умову задовольняє, тож однобуквений запис зв'язував би звичайну прозу. «р.» внесено: на відміну від російського «г.», українське «р.» означає тільки «рік» і зв'язується вліво після числа. «%» внесено ЯК РІШЕННЯ, а не як цитата: його немає ні в § 62, ні в § 64, ні в скороченому викладі брошури BIPM (правило про % — у § 5.4.7 повного видання, яке не діставалося), але відбивка відсотка від числа є і в російській локалі, і в усіх інших локалях цього проєкту, а розбіжність тут дала б українській вужчу поведінку без жодної підстави в джерелі. Звірено 18.09.2026." + } + ] +} diff --git a/vendor/polytypo-spec/rules/dashes.md b/vendor/polytypo-spec/rules/dashes.md index 45821b3..1051e33 100644 --- a/vendor/polytypo-spec/rules/dashes.md +++ b/vendor/polytypo-spec/rules/dashes.md @@ -1,8 +1,10 @@ # Rule: `dashes` -**Order:** 30. **Default:** on. **Modes:** text, html, markdown. +**Order:** 30. **Default:** on. **Modes:** text, html, markdown, yaml. **Spec version:** 0.6.0 (0.2.0 for everything except the 0.5.0/0.6.0 changes noted inline and in -§8 History). +§8 History), amended in **1.3.0**: §1 and §3.4's statement of what belongs to `ranges`, §3.2a's +re-entry condition, and §3.2 steps 7 and 8, all for [ranges.md](ranges.md) §3.2a's closed-up +symbols. --- @@ -25,9 +27,13 @@ a retired one. `dashes` does not touch the ordinary hyphen inside a compound word — which, in the few morphological forms where the hyphen must additionally be protected from a line break, belongs -to `hyphen` at order 35 — and does not touch a digit-flanked stroke at all: that shape belongs to +to `hyphen` at order 35 — and does not touch a **range candidate** at all: that shape belongs to `ranges` exclusively, and `dashes` declines it **unconditionally**, whether or not `ranges` is enabled (operator decision, spec 0.5.0; see §3.2's note after step 7, and ranges.md §3.2's G1-G5). +"Range candidate" is [ranges.md](ranges.md) §3.2's term, and as of spec 1.3.0 it is wider than +"digit-flanked": a closed-up symbol on a flank is walked over first (ranges.md §3.2a), so +`$15-$20` and `35%-50%` are `ranges`' tokens too, and a token `dashes` used to convert by default +is now one nothing touches unless the caller enables `ranges`. `dashes` never reinterprets a digit-flanked hyphen as a parenthetical dash — that was already true in every prior spec version, since the two branches were always mutually exclusive per token; the 0.5.0 split makes that exclusivity a boundary between two rules instead of two branches of one. @@ -80,6 +86,7 @@ Input is a code-point array `cp[0 … n-1]`. | `ROMAN` | the seven uppercase Roman-numeral letters only: U+0049 `I`, U+0056 `V`, U+0058 `X`, U+004C `L`, U+0043 `C`, U+0044 `D`, U+004D `M`. Lower-case forms are **not** members — see §3.4 P4 | | `INERT-DASH` | U+00AD (soft hyphen), U+2011 (non-breaking hyphen), U+2012 (figure dash), U+2015 (horizontal bar), U+FE58, U+FE63, U+FF0D | | `JOINER` | U+2060 (word joiner) only. As of spec 0.5.0, produced exclusively by `ranges` (ranges.md §3.3.1) — `dashes` itself never emits one, but still reads through an adjacent run of them (§3.2a, §3.2b), since a `ranges`-produced joiner can sit next to a `dashes` candidate token | +| `CLOSED-SYMBOL` | **Defined normatively in [ranges.md](ranges.md) §3.2a** (spec 1.3.0), not here: the symbols conventionally written closed up to a number. `dashes` never emits one and never reads one as a candidate, but §3.2 steps 7-8 and §3.4 depend on the class, so it is listed here for a reader transcribing this table. There is exactly one enumeration of it, in ranges.md — do not restate it | `INERT-DASH` members are **never** candidates and are **never** produced. Two of the seven are protective markers owned by someone else — U+00AD is invisible formatting, and U+2011 is @@ -183,8 +190,8 @@ U+2011 they meant it. something this rule should be rewriting. 7. **Cluster guard.** Define a **dash cluster** as a maximal span of code points every one of which is in `DASH` ∪ `INERT-DASH` ∪ `DIGIT` ∪ `JOINER` (§3.2b — a joiner `ranges` emitted on - an earlier pass must not split a cluster it sits inside). (Spaces, letters and punctuation all end a - cluster.) Let `C` be the cluster containing this token's run. **If `C` contains two or more + an earlier pass must not split a cluster it sits inside). (Spaces, letters and punctuation all + end a cluster.) Let `C` be the cluster containing this token's run. **If `C` contains two or more maximal runs of `DASH` ∪ `INERT-DASH`, emit nothing for every token in `C`** — the whole cluster is inert. This covers idempotency defect (a), §8.2: the classification of a range token reads @@ -193,6 +200,13 @@ U+2011 they meant it. verdict on the next run. `2026-08-15`, `978-3-16-148410-0`, `212-555-1234`, `a—0–0` and `1914-1918—annexation` are all single clusters with more than one dash run, and are all inert in their entirety. + **`CLOSED-SYMBOL` is deliberately not in this alphabet (spec 1.3.0).** Widening a range + member (ranges.md §3.2a) does reach this guard — `a—$15-$20` is two clusters where `a—15-20` + is one — but the resulting defect is closed by step 8 instead, and at a strictly smaller cost: + the cluster guard is unconditional, so adding `CLOSED-SYMBOL` here would also make + `price--$50--drop` inert in an `em-tight` locale that has no such defect to fix. Step 8 fires + only on the tight-to-spaced transition that can actually disturb a neighbour. See §3.2 step 8 + and [ranges.md](ranges.md) §3.2a. **This guard is not sufficient on its own, and it does not subsume G2.** A cluster ends at the first space-like code point, so a _spaced_ token's cluster contains only its own run: its `cp[L]` is a digit in a neighbouring cluster and its `before` is a dash in a third one, @@ -206,14 +220,65 @@ U+2011 they meant it. - the chosen form is `em-spaced` or `en-spaced` — the replacement will insert a U+0020 on each side. - In that case, for each side independently: + In that case, for each side independently — reading `L`/`R` and the outward walk as + **`CLOSED-SYMBOL`-transparent**, per the amendment immediately below: - **left:** if `cp[L]` is in `DIGIT`, let `D` be the maximal `DIGIT` run ending at `L` and starting at index `d`. Reading **effective neighbours** (§3.2b) outward from `d`: if the first is in `DASH` ∪ `INERT-DASH`, **or** the first is in `SPACE` ∪ `NOBREAK-SPACE` and the second is in `DASH` ∪ `INERT-DASH`, emit nothing for this token. - **right:** if `cp[R]` is in `DIGIT`, let `D` be the maximal `DIGIT` run starting at `R` - and ending at index `d`. If `cp[d+1]` is in `DASH` ∪ `INERT-DASH`, **or** `cp[d+1]` is in - `SPACE` ∪ `NOBREAK-SPACE` and `cp[d+2]` is in `DASH` ∪ `INERT-DASH`, emit nothing. + and ending at index `d`. Reading **effective neighbours** (§3.2b) outward from `d` — the + same reading the left branch uses, and the one §3.2b already requires of "the two-code-point + reach of T1"; through spec 1.2.0 this branch was written with raw `cp[d+1]`/`cp[d+2]`, which + disagreed with §3.2b and with every shipped implementation (see below) — if the first is in + `DASH` ∪ `INERT-DASH`, + **or** the first is in `SPACE` ∪ `NOBREAK-SPACE` and the second is in `DASH` ∪ `INERT-DASH`, + emit nothing. + + **`CLOSED-SYMBOL` transparency (spec 1.3.0).** [ranges.md](ranges.md) §3.2a made a symbol + written closed up to a digit run part of a **range member**, so the digit run whose verdict + this guard protects can now sit one code point further out than it used to — on either end. + At **two** positions per side, one `CLOSED-SYMBOL` is therefore stepped over rather than read: + + - **p1, between the token and the run.** If `cp[L]` (resp. `cp[R]`) is in `CLOSED-SYMBOL` and + the code point beyond it is in `DIGIT`, the branch proceeds as though `L` (resp. `R`) were + that digit. Without p1 the branch is skipped outright, because its gate is `cp[L]`/`cp[R]` + ∈ `DIGIT`: `a--$1 - $1` is the witness. + - **p2, at the far end of the run.** The outward walk from `d` steps over one `CLOSED-SYMBOL` + before reading its first and second neighbours. Witness: `a--15% - 20%`, where the walk + from `d` finds `%` and the dash it exists to find is one code point further out. + + The two compose on a single side (`a--$15% - $20%` exercises p1 and p2 at once) and are + independent across sides. + + **The right branch's raw reading, and what §3.2a changed about it.** The raw text disagreed + with §3.2b from the start, and the disagreement was always live on the **second** sub-branch: + a U+0020 ends a cluster, so step 7 never declined `a--15⁠ - 20`, and a port reading raw + `cp[d+1]` sees the joiner, does not fire, and drifts. (It was unreachable on the first + sub-branch only — with no space, the token, the digit run, the joiner and the far dash all sat + inside one cluster, since step 7's alphabet contains `JOINER` and `DIGIT`.) What §3.2a added + is a second way in: p1 admits `cp[R]` ∈ `CLOSED-SYMBOL`, which is deliberately **not** in the + cluster alphabet, so `a--$15⁠-⁠$20` splits into two clusters and step 8 stands alone there too. + Both shapes are now pinned by fixtures, for the same reason §3.2a's re-entry amendment needed + one: nothing else in the suite separates the two readings. Every shipped implementation + already read effective neighbours — this is the text catching up, not a behaviour change. + + **Why two positions are enough, and there is no third.** §3.2a consumes **at most one** + `CLOSED-SYMBOL` per side — a two-code-point prefix such as `US$` defeats candidacy rather + than the guard — so each position can hold at most one symbol. A `-spaced` replacement inserts + exactly one U+0020, so the "first or second neighbour" reach is unchanged in length; the + symbol shifts *where* that reach starts, never how far it goes. p1 and p2 are the only two + places a symbol can sit between this token and the far dash, so the amended reach is closed. + + **The cost, and why it is this guard rather than step 7.** In a locale whose + `dash.parenthetical` is **spaced**, a tight token next to a closed-up range member no longer + converts: `Anstieg--50%--war` is left alone in `de-DE`, where spec 1.2.0 produced + `Anstieg – 50% – war`. That is precisely what the all-digit `Anstieg--50--war` has always + done, so the two shapes agree, and the cost stops there — a locale with a **tight** + parenthetical form never reaches this guard at all, so `price--$50--drop` still becomes + `price—$50—drop` in `en-US`. Putting `CLOSED-SYMBOL` in step 7's cluster alphabet would have + closed the same defect and taken the `en-US` case with it, because that guard is + unconditional; it was tried and rejected for exactly that reason. Read plainly: **a tight token must not become spaced when doing so would insert a space between itself and a digit run that has another dash on its far side.** That inserted space @@ -279,12 +344,18 @@ A `JOINER` adjacent to the token is examined before the branch is chosen: across a maximal run of `JOINER`. If either walk runs off the array, emit nothing. - If no joiner was crossed, `L* = L` and `R* = R` and nothing about the rest of the algorithm changes. -- If a joiner **was** crossed and `cp[L*]` and `cp[R*]` are both in `DIGIT`, the token is a - bound range `ranges` produced on an earlier pass ([ranges.md](ranges.md) §3.3.1): continue with - `L*`/`R*` in place of `L`/`R`, and extend the token's span to cover the crossed joiners. `dashes` - itself never reaches this shape as a candidate — extending the span here only ever feeds the - digit-flanked check that routes the token to `ranges`' exclusive territory (§1, §3.3), never to - this rule's own parenthetical branch. +- If a joiner **was** crossed and `cp[L*]` and `cp[R*]` are both in `DIGIT` — **or, as of spec + 1.3.0, are `DIGIT` after `ranges`' closed-up-symbol walk** ([ranges.md](ranges.md) §3.2a), so + that `$15⁠–⁠$20` and `35%⁠–⁠50%` reach this clause the same way `1914⁠–⁠1918` does — the token is + a bound range `ranges` produced on an earlier pass ([ranges.md](ranges.md) §3.3.1): continue + with `L*`/`R*` in place of `L`/`R`, and extend the token's span to cover the crossed joiners. + `dashes` itself never reaches this shape as a candidate — extending the span here only ever + feeds the flank check that routes the token to `ranges`' exclusive territory (§1, §3.3), never + to this rule's own parenthetical branch. **Without the 1.3.0 clause a bound range carrying + symbols would fall to the fourth bullet below and be declined by both rules** — stable, but + wrong in one observable way: a hyphen an author typed between an existing joiner pair, + `$15⁠-⁠$20`, would never convert. The amendment is what makes that input reach `ranges`, and a + conformance case pins it, because nothing else in the suite separates the two readings. - If a joiner was crossed in any other configuration, **emit nothing**. An author who typed U+2060 next to a dash meant it, exactly as with `INERT-DASH` (§3.1). @@ -340,9 +411,10 @@ is [ranges.md](ranges.md) §3.2-§3.3.1 in full** — the admissibility test (`c verbatim, still reading the same `dash.range` locale field under the same key. **What stays true here, restated because it is `dashes`' own contract now rather than a -consequence of one rule's two branches:** a digit-flanked dash token (`cp[L]` and `cp[R]` both -`DIGIT`) is never processed by `dashes` — not converted, not declined-and-then-reconsidered, -simply never reached. This holds **unconditionally**, whether `ranges` is enabled or not (§1). +consequence of one rule's two branches:** a range candidate (`cp[L']` and `cp[R']` both `DIGIT`, +after ranges.md §3.2a's closed-up-symbol walk — through spec 1.2.0 this read `cp[L]`/`cp[R]` and +meant digit-flanked) is never processed by `dashes` — not converted, not +declined-and-then-reconsidered, simply never reached. This holds **unconditionally**, whether `ranges` is enabled or not (§1). `ranges` disabled does not mean the token falls back to parenthetical treatment; it means nothing in the pipeline touches it at all, and `5-10`, `Figure 5-10`, `9-11` and `7-11` are all byte-identical no-ops with default options. @@ -356,10 +428,10 @@ still occupies its number costs less than a renumbering would. ### 3.4 Parenthetical branch -Reached for every token this rule sees — a digit-flanked token (both `cp[L]` and `cp[R]` in -`DIGIT`) is never handed to `dashes` at all (§3.3, §1), not merely excluded from this branch, so -"is not a range candidate" (i.e. at least one of `cp[L]`, `cp[R]` is not a `DIGIT`) is true of -every token that reaches here by construction. Additional guards: +Reached for every token this rule sees — a range candidate (ranges.md §3.2, §3.2a) is never +handed to `dashes` at all (§3.3, §1), not merely excluded from this branch, so "is not a range +candidate" (i.e. at least one flank is not a `DIGIT`, and is not a closed-up symbol matched to +its opposite member) is true of every token that reaches here by construction. Additional guards: - **P5 (spec 0.6.0) — authored en-dash mark-identity veto.** If `k = 1` and `cp[s]` is U+2013, emit nothing — **unconditionally**: every locale, tight or spaced, regardless of @@ -525,10 +597,14 @@ of being falsified by another rule, which is then named. - **[P] A negative number.** `-5` has no space to the left of the digit and a letter/space to the left of the hyphen → asymmetric → rejected. This holds for U+002D, U+2010 and U+2212 alike — the same asymmetry guard, not a glyph-specific one. -- **[P] Every digit-flanked stroke, unconditionally** — `5-10`, `Figure 5-10`, `9-11`: never - reached by `dashes` at all, let alone reinterpreted as parenthetical (§1, §3.3). This holds - regardless of whether `ranges`' own guards would have accepted or declined the token — - `dashes` does not evaluate them and does not need to. +- **[P] Every range candidate, unconditionally** — `5-10`, `Figure 5-10`, `9-11`, and since + spec 1.3.0 also `$15-$20`, `$15 - $20` and `35%-50%`, where a matched `CLOSED-SYMBOL` sits + between the stroke and a digit run (ranges.md §3.2a): never reached by `dashes` at all, let + alone reinterpreted as parenthetical (§1, §3.3). This holds regardless of whether `ranges`' + own guards would have accepted or declined the token — `dashes` does not evaluate them and + does not need to. **`$15 - $20` is the one shape this cost anything**: through spec 1.2.0 it + was `dashes`' token and converted with default options; it is `ranges`' now, and `ranges` is + off by default. - **[P] URLs, code spans, fenced code, HTML attributes.** Removed by the mode adapter before this rule sees them. This rule has no notion of a URL and must not grow one. - **[P] Line terminators**, which are never inserted, deleted or crossed. @@ -537,8 +613,9 @@ of being falsified by another rule, which is then named. ## 5. Idempotency argument -Write `T` for `dashes`. `T` edits only **parenthetical dash tokens**: at least one of `cp[L]`, -`cp[R]` is not `DIGIT` (§1, §3.3) — a digit-flanked token is never reached by `T` on any pass, so +Write `T` for `dashes`. `T` edits only **parenthetical dash tokens**: tokens that are not range +candidates (§1, §3.3) — at least one flank is neither a `DIGIT` nor a `CLOSED-SYMBOL` matched on +the opposite member (ranges.md §3.2a). A range candidate is never reached by `T` on any pass, so nothing below needs to reason about one. Each edit `T` makes replaces a span consisting of one maximal `DASH` run plus at most one space-like code point on each side, with a span of the same shape (`space? dash space?`). So every edit is one of: @@ -566,9 +643,10 @@ U+2013/U+2014 no token-level special case, §3.2 step 2a, so this holds regardle glyph the token holds). A spaced form is re-admitted the same way, with `lsp = rsp = 1` read back by §3.2 step 3. A token `nbsp` has since promoted (`ru`: U+00A0 before an em dash) is not recomputed at all — §3.2 step 3 makes a no-break-space neighbour space-like, so the isolation -guard (step 6) declines it and nothing is emitted (§3.6). A digit-flanked token stays outside `T`'s +guard (step 6) declines it and nothing is emitted (§3.6). A range candidate stays outside `T`'s domain on every pass, by construction, so it is trivially a fixed point of `T` regardless of what -`ranges` does to it. +`ranges` does to it — including after `ranges` has bound it, since the binding leaves the flanks +(and any `CLOSED-SYMBOL` on them) exactly where they were. ### 5.2 A declined token stays declined @@ -619,17 +697,25 @@ them, and all three are current: Range binding ([ranges.md](ranges.md) §3.3.1) is exclusively `ranges`' emission; an interrupting parenthetical dash is exactly where a line *may* break, so there is nothing for `dashes` to bind (§3.6). -- **A digit-flanked token is never reinterpreted as parenthetical, on any pass.** The `isDigit` - test that routes a token to `ranges` instead of `dashes` (§1, §3.3) is evaluated after the - joiner-crossing walk (§3.2a), so a token `ranges` bound on an earlier pass — where the walk - re-enters across the `JOINER` pair and finds `DIGIT` on both effective neighbours — presents to - `dashes` with digit-flanked `leftCp`/`rightCp` exactly as an unbound one would, and `dashes` - declines it on the same unconditional test. `dashes` cannot strip a binding it never - reconsiders, and cannot create one, since it never emits `JOINER`. +- **A range candidate is never reinterpreted as parenthetical, on any pass.** The candidacy test + that routes a token to `ranges` instead of `dashes` (§1, §3.3, [ranges.md](ranges.md) §3.2, + §3.2a) is evaluated after the joiner-crossing walk (§3.2a), so a token `ranges` bound on an + earlier pass — where the walk re-enters across the `JOINER` pair and finds a candidate on both + effective neighbours — presents to `dashes` exactly as an unbound one would, and `dashes` + declines it on the same unconditional test. Since spec 1.3.0 that test reads `cp[L']`/`cp[R']`, + so a bound range carrying closed-up symbols re-enters on the same footing as an all-digit one. + `dashes` cannot strip a binding it never reconsiders, and cannot create one, since it never + emits `JOINER`. - **`dashes`' own edits cannot flip a *neighbouring* range token's guard verdict on the next pass, even though `dashes` itself never reads that token's guards.** The one edit shape that could — a tight token becoming spaced, inserting a U+0020 next to a digit run that has another dash on its far side — is exactly what the spacing-transition guard (T1, §3.2 step 8) declines. + **This clause is true of spec 1.3.0 only because step 8 was amended with it**: ranges.md §3.2a + widened "next to a digit run" to "next to a range member", which may carry one `CLOSED-SYMBOL` + at either end, and an unamended T1 reads that symbol as the neighbour and stops one code point + short of the dash. Four witnesses made the gap concrete — `a—$15-$20`, `35%-50%—b`, `a--15% - 20%` and + `$1 - $1--a`, one per position and side — each of which drifted on the second pass before the + amendment and each of which now behaves exactly as its all-digit analogue always has. This is `dashes`' composition obligation *toward* `ranges`, symmetric to the rule-order argument in [ranges.md](ranges.md) §4: `ranges` must not see an adjacency `dashes` disturbed, and T1 is how `dashes` upholds that on every subsequent pass. The full historical derivation of why this @@ -1097,7 +1183,12 @@ form to be `-spaced`. In other words: `A` is tight, `A` is about to become space only, the configuration T1 (§3.2 step 8) declares inert. The mirrored argument gives the `after` side. T1's two-code-point reach is exactly what the case requires and no more: `T`'s dash sits at distance 1 from `Lrun` if `T` is tight and distance 2 if `T` is spaced, and a `-spaced` replacement -inserts exactly one U+0020, so no other distance is reachable. The reverse flip — `before` going +inserts exactly one U+0020, so no other distance is reachable. **Spec 1.3.0 leaves that reach at +two code points and makes it transparent to one `CLOSED-SYMBOL` at each of two positions** +(§3.2 step 8): the symbol moves where the reach starts, never how far it goes, because +ranges.md §3.2a consumes at most one symbol per side. `JOINER` does not add a position either: +it is transparent to this reach by §3.2b, on both branches, so a joiner run between the symbol +and the dash collapses rather than counting. The reverse flip — `before` going from a space to a dash — is benign and needs no guard: it turns a G2 admission into a G2 rejection, and a rejection emits nothing, so a token converted on an earlier pass simply keeps the form it was given. diff --git a/vendor/polytypo-spec/rules/order.json b/vendor/polytypo-spec/rules/order.json index fa2a5b4..488bfe4 100644 --- a/vendor/polytypo-spec/rules/order.json +++ b/vendor/polytypo-spec/rules/order.json @@ -1,12 +1,12 @@ { - "spec": "1.2.0", + "spec": "1.3.0", "$comment": "Single source of truth for pipeline order. Rules run in ascending `order`. Disabling a rule removes it from the sequence and never reorders the rest. Rule ids are public API (see docs/ARCHITECTURE.md section 5). \"spec\" here must track spec/VERSION exactly — it is not itself the global version source; scripts/validate-spec.mjs enforces the match.", "rules": [ { "id": "spaces", "order": 10, "default": "on", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": [], "summary": "Collapse repeated spaces, strip spaces before punctuation, normalize spacing inside brackets." }, @@ -14,7 +14,7 @@ "id": "ellipsis", "order": 20, "default": "on", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": ["ellipsis"], "summary": "Three dots to U+2026; locale-dependent abbreviated forms after terminal punctuation." }, @@ -22,7 +22,7 @@ "id": "ranges", "order": 25, "default": "off", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": ["dash"], "summary": "Numeric/date range dash per locale convention (dash.range). Explicit opt-in (spec 0.5.0): a genuine range and a compound label sharing the same digit-hyphen-digit shape (`Figure 5-10`) cannot be told apart without the preceding word, which this project's rules are built never to consult. Off by default; enable with `{ rules: { ranges: true } }`." }, @@ -30,15 +30,15 @@ "id": "dashes", "order": 30, "default": "on", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": ["dash"], - "summary": "Parenthetical dash per locale convention (dash.parenthetical). Never reinterprets a digit-flanked hyphen as a parenthetical dash — that shape belongs to `ranges` alone, whether or not `ranges` is enabled (spec 0.5.0; range detection moved out of this rule)." + "summary": "Parenthetical dash per locale convention (dash.parenthetical). Never reinterprets a range candidate as a parenthetical dash — that shape belongs to `ranges` alone, whether or not `ranges` is enabled (spec 0.5.0; range detection moved out of this rule). A candidate is digit-flanked, or flanked by a closed-up symbol matched on the opposite member (spec 1.3.0; ranges.md §3.2a)." }, { "id": "hyphen", "order": 35, "default": "on", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": ["hyphen"], "summary": "Bind morphological hyphen forms with U+2011 (non-breaking hyphen) so they cannot be broken across lines. Runs after `dashes`, which has already declined every letter-adjacent hyphen. A no-op for locales whose hyphen lists are empty." }, @@ -46,7 +46,7 @@ "id": "quotes", "order": 40, "default": "on", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": ["quotes"], "summary": "Straight quotes to locale primary/secondary pairs with nesting resolution. Runs before `apostrophe` so that a straight apostrophe is still available as quote evidence. Declines to pair a medial single-quoted `n` (spec 1.1.0, every locale) or a span matching a cited `quotes.elisionIdioms` entry, so that `apostrophe` converts both marks instead." }, @@ -54,7 +54,7 @@ "id": "apostrophe", "order": 50, "default": "on", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": [], "summary": "Remaining straight apostrophes to U+2019 without corrupting contractions. Reads no locale data: spec 0.5.0's `quotes.elisionIdioms` lookup existed only for the preserve set withdrawn in spec 1.1.0, so every mark `quotes` declined to claim now reaches this rule's ordinary structural case ladder." }, @@ -62,7 +62,7 @@ "id": "symbols", "order": 60, "default": "on", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": [], "summary": "(c)/(r)/(tm) to the corresponding signs; multiplication sign between numerals." }, @@ -70,7 +70,7 @@ "id": "nbsp", "order": 70, "default": "on", - "modes": ["text", "html", "markdown"], + "modes": ["text", "html", "markdown", "yaml"], "localeData": ["nbsp", "quotes"], "summary": "Insert no-break and narrow no-break spaces per locale. Runs last so that every other rule has already settled the surrounding characters." } diff --git a/vendor/polytypo-spec/schema/fixtures.schema.json b/vendor/polytypo-spec/schema/fixtures.schema.json index c2a015a..c57f47e 100644 --- a/vendor/polytypo-spec/schema/fixtures.schema.json +++ b/vendor/polytypo-spec/schema/fixtures.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://polytypo.org/schema/fixtures.schema.json", "title": "polytypo conformance fixtures", - "description": "Executable form of the rule semantics. Every case is also an idempotency case: a runner must additionally assert transform(out) == out.", + "description": "Executable form of the rule semantics. Every case is also an idempotency case: a runner must additionally assert transform(out) == out, passing the case's own options (mode, dialect, keys, rules, narrowNbsp) on that second call exactly as on the first — a case is a fixed point under its own options, not under the defaults.", "type": "object", "additionalProperties": false, "required": ["spec", "locale", "cases"], @@ -24,6 +24,11 @@ "if": { "properties": { "mode": { "const": "markdown" } }, "required": ["mode"] }, "then": { "required": ["dialect"] }, "else": { "not": { "required": ["dialect"] } } + }, + { + "if": { "properties": { "mode": { "const": "yaml" } }, "required": ["mode"] }, + "then": { "required": ["keys"] }, + "else": { "not": { "required": ["keys"] } } } ], "oneOf": [{ "required": ["out"] }, { "required": ["throws"] }], @@ -47,11 +52,16 @@ ], "description": "The rule under test. Required so a runtime can report partial conformance honestly." }, - "mode": { "enum": ["text", "html", "markdown"] }, + "mode": { "enum": ["text", "html", "markdown", "yaml"] }, "dialect": { "enum": ["commonmark", "mdx"], "description": "Required when mode is \"markdown\" — spec/rules/modes.md §3.7.1 forbids detection, so a fixture must name the dialect exactly as a caller would. Meaningless for the other modes." }, + "keys": { + "type": "array", + "items": { "type": "string" }, + "description": "Required when mode is \"yaml\" — spec/rules/modes.md §3.8.2 gives the option no default, so a fixture must name the processable keys exactly as a caller would. An empty array is legal and processes nothing. Meaningless for the other modes." + }, "in": { "type": "string" }, "out": { "type": "string" }, "throws": { @@ -62,7 +72,8 @@ "POLYTYPO_UNKNOWN_RULE", "POLYTYPO_MALFORMED_LOCALE_DATA", "POLYTYPO_RULE_CONTRACT", - "POLYTYPO_MALFORMED_INPUT" + "POLYTYPO_MALFORMED_INPUT", + "POLYTYPO_INVALID_OPTION" ], "description": "Expected error code instead of an output string. Messages are not part of the contract; codes are." }, @@ -71,6 +82,10 @@ "type": "object", "additionalProperties": { "type": "boolean" }, "description": "Optional rule overrides for this case, same shape as the public `rules` option." + }, + "narrowNbsp": { + "enum": ["narrow", "nbsp"], + "description": "Optional, spec 1.3.0. Same shape as the public `narrowNbsp` option (spec/rules/nbsp.md §3.1a): \"nbsp\" makes the engine emit U+00A0 wherever it would emit U+202F. Omitted means \"narrow\", the default, so every pre-1.3.0 case keeps its meaning. A runner passes this through to transform() exactly as it passes `rules`." } } }