GitHub
· Extracted in 2022 ms
🐛 Use the CommonMark whitespace set, not the Python one (#433) · executablebooks/markdown-it-py@6f58654
Source: https://github.com/executablebooks/markdown-it-py/commit/6f586542653a56d2ee8549a0dccfaa6ba5ebe14a
Repository navigation
Commit 6f58654
Browse files
chrisjsewell
and
Nexory
authored
🐛 Use the CommonMark whitespace set, not the Python one ( #433 )
Supersedes #418 by @Nexory , whose commit is preserved as the first
commit here (the fork does not allow maintainer edits, so it could not
be brought up to date in place).
## Summary
`str.strip()` and `str.split()` without arguments use `str.isspace()`,
which treats U+001C, U+001D, U+001E, U+001F and U+0085 as whitespace.
CommonMark and `String.prototype.trim` do not, so upstream markdown-it
keeps those characters. Ten call sites relied on the Python behaviour,
with two visible consequences (both measured against
markdown-it@14.1.0):
- `normalizeReference` folded distinct labels together, so `[a\x85b]:
url` resolved a usage `[a b]` in Python and not in JavaScript.
- The characters were dropped from paragraphs, headings, table cells and
fence info strings.
This adds `MD_TRIM_CHARS` and `mdTrim()` to `common/utils` and uses them
at those sites; the fence renderer splits the info string on the same
set. `U+FEFF` is deliberately excluded, since `trim` removing it is the
same label-folding defect in the other direction. See #418 for the full
rationale, including what was deliberately left unchanged
(`validateLink`, the backticks edge rule).
## Changes on top of #418
- The per-call `re.sub("[" + re.escape(MD_TRIM_CHARS) + "]+", ...)` in
`normalizeReference` and `RendererHTML.fence` is hoisted to a
module-level compiled `MD_TRIM_RE`.
- Changelog entry added.
## Validation
- pre-commit (ruff, ruff format, mypy strict) clean.
- Full suite: 1032 passed (the 15 new cases in
`tests/test_port/test_whitespace.py` plus the existing 1017).
- Differential render of 47,936 corpus inputs across 7 presets (HTML,
inline HTML and token streams) is byte-identical to master; the corpus
contains none of the five affected characters, so the only behaviour
change is the one the new tests cover.
- Local Sphinx build with `-W` and nitpicky passes (only the usual
egress-blocked stdlib intersphinx refs).
---------
Co-authored-by: Nexory <St4yl3r30@hotmail.de>
1 parent 337c2d5 commit 6f58654
8 files changed
Lines changed: 125 additions & 14 deletions
File tree
Lines changed: 1 addition & 0 deletions
| Original file line number | Diff line number | Diff line change |
@@ -4,6 +4,7 @@
|
4 | 4 |
|
5 | 5 | * ✨ Add `--enable-tables` to the CLI for file, standard input and interactive parsing in [#422](https://github.com/executablebooks/markdown-it-py/pull/422)
|
6 | 6 | * 🐛 Fix CLI interactive mode joining input lines with an extra newline, which split every line into its own paragraph and broke hard line breaks, in [#172](https://github.com/executablebooks/markdown-it-py/issues/172)
|
| 7 | +* 🐛 Fix trimming and splitting with the Python whitespace set instead of the CommonMark one, which dropped U+001C-U+001F and U+0085 from paragraphs, headings, table cells and fence info strings and let distinct reference labels resolve each other, in [#418](https://github.com/executablebooks/markdown-it-py/pull/418), thanks to [@Nexory](https://github.com/Nexory)
|
7 | 8 | * 📚 Document the Python renderer constructor contract.
|
8 | 9 | * 🔧 Drop the optional dependency on the `commonmark` package and its benchmark, since the upstream package is unmaintained, in [#401](https://github.com/executablebooks/markdown-it-py/pull/401)
|
9 | 10 |
|
|
Lines changed: 26 additions & 1 deletion
| Original file line number | Diff line number | Diff line change |
@@ -191,6 +191,31 @@ def isWhiteSpace(code: int) -> bool:
|
191 | 191 | return code in MD_WHITESPACE
|
192 | 192 |
|
193 | 193 |
|
| 194 | +#: The characters ``String.prototype.trim`` removes in JavaScript, which is
|
| 195 | +#: what upstream markdown-it strips, minus U+FEFF.
|
| 196 | +#:
|
| 197 | +#: ``str.strip()`` without an argument uses :py:meth:`str.isspace`, which also
|
| 198 | +#: removes U+001C, U+001D, U+001E, U+001F and U+0085. Those are not whitespace
|
| 199 | +#: in CommonMark and are not removed by ``trim``, so relying on it drops them
|
| 200 | +#: from the output and makes two different reference labels compare equal.
|
| 201 | +#:
|
| 202 | +#: U+FEFF is deliberately excluded: ``trim`` does remove it, and that has the
|
| 203 | +#: very label folding effect this constant exists to avoid.
|
| 204 | +MD_TRIM_CHARS = "".join(
|
| 205 | + chr(code)
|
| 206 | + for code in sorted(MD_WHITESPACE | set(range(0x2000, 0x200B)) | {0x2028, 0x2029})
|
| 207 | +)
|
| 208 | +
|
| 209 | +
|
| 210 | +#: A run of one or more characters from :data:`MD_TRIM_CHARS`.
|
| 211 | +MD_TRIM_RE = re.compile("[" + re.escape(MD_TRIM_CHARS) + "]+")
|
| 212 | +
|
| 213 | +
|
| 214 | +def mdTrim(string: str) -> str:
|
| 215 | + """Strip leading and trailing whitespace, using the CommonMark set."""
|
| 216 | + return string.strip(MD_TRIM_CHARS)
|
| 217 | +
|
| 218 | +
|
194 | 219 | # //////////////////////////////////////////////////////////////////////////////
|
195 | 220 |
|
196 | 221 |
|
@@ -254,7 +279,7 @@ def normalizeReference(string: str) -> str:
|
254 | 279 | """Helper to unify [reference labels]."""
|
255 | 280 | # Trim and collapse whitespace
|
256 | 281 | #
|
257 | | - string = re.sub(r"\s+", " ", string.strip())
|
| 282 | + string = MD_TRIM_RE.sub(" ", mdTrim(string))
|
258 | 283 |
|
259 | 284 | # In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug
|
260 | 285 | # fixed in v12 (couldn't find any details).
|
|
Lines changed: 5 additions & 3 deletions
| Original file line number | Diff line number | Diff line change |
@@ -12,7 +12,7 @@ class Renderer
|
12 | 12 | import inspect
|
13 | 13 | from typing import Any, ClassVar, Protocol
|
14 | 14 |
|
15 | | -from .common.utils import escapeHtml, unescapeAll
|
| 15 | +from .common.utils import MD_TRIM_RE, escapeHtml, mdTrim, unescapeAll
|
16 | 16 | from .token import Token
|
17 | 17 | from .utils import EnvType, OptionsDict
|
18 | 18 |
|
@@ -268,12 +268,14 @@ def fence(
|
268 | 268 | env: EnvType,
|
269 | 269 | ) -> str:
|
270 | 270 | token = tokens[idx]
|
271 | | - info = unescapeAll(token.info).strip() if token.info else ""
|
| 271 | + info = mdTrim(unescapeAll(token.info)) if token.info else ""
|
272 | 272 | langName = ""
|
273 | 273 | langAttrs = ""
|
274 | 274 |
|
275 | 275 | if info:
|
276 | | - arr = info.split(maxsplit=1)
|
| 276 | + # Not ``str.split()``: it splits on the Python whitespace set,
|
| 277 | + # which is wider than the one upstream uses here.
|
| 278 | + arr = MD_TRIM_RE.split(info, maxsplit=1)
|
277 | 279 | langName = arr[0]
|
278 | 280 | if len(arr) == 2:
|
279 | 281 | langAttrs = arr[1]
|
|
Lines changed: 2 additions & 2 deletions
| Original file line number | Diff line number | Diff line change |
@@ -4,7 +4,7 @@
|
4 | 4 |
|
5 | 5 | import logging
|
6 | 6 |
|
7 | | -from ..common.utils import isStrSpace
|
| 7 | +from ..common.utils import isStrSpace, mdTrim
|
8 | 8 | from .state_block import StateBlock
|
9 | 9 |
|
10 | 10 | LOGGER = logging.getLogger(__name__)
|
@@ -62,7 +62,7 @@ def heading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bo
|
62 | 62 | token.map = [startLine, state.line]
|
63 | 63 |
|
64 | 64 | token = state.push("inline", "", 0)
|
65 | | - token.content = state.src[pos:maximum].strip()
|
| 65 | + token.content = mdTrim(state.src[pos:maximum])
|
66 | 66 | token.map = [startLine, state.line]
|
67 | 67 | token.children = []
|
68 | 68 |
|
|
Lines changed: 2 additions & 1 deletion
| Original file line number | Diff line number | Diff line change |
@@ -1,6 +1,7 @@
|
1 | 1 | # lheading (---, ==)
|
2 | 2 | import logging
|
3 | 3 |
|
| 4 | +from ..common.utils import mdTrim
|
4 | 5 | from .state_block import StateBlock
|
5 | 6 |
|
6 | 7 | LOGGER = logging.getLogger(__name__)
|
@@ -65,7 +66,7 @@ def lheading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> b
|
65 | 66 | # Didn't find valid underline
|
66 | 67 | return False
|
67 | 68 |
|
68 | | - content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
|
| 69 | + content = mdTrim(state.getLines(startLine, nextLine, state.blkIndent, False))
|
69 | 70 |
|
70 | 71 | state.line = nextLine + 1
|
71 | 72 |
|
|
Lines changed: 2 additions & 1 deletion
| Original file line number | Diff line number | Diff line change |
@@ -2,6 +2,7 @@
|
2 | 2 |
|
3 | 3 | import logging
|
4 | 4 |
|
| 5 | +from ..common.utils import mdTrim
|
5 | 6 | from .state_block import StateBlock
|
6 | 7 |
|
7 | 8 | LOGGER = logging.getLogger(__name__)
|
@@ -47,7 +48,7 @@ def paragraph(state: StateBlock, startLine: int, endLine: int, silent: bool) ->
|
47 | 48 |
|
48 | 49 | nextLine += 1
|
49 | 50 |
|
50 | | - content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
|
| 51 | + content = mdTrim(state.getLines(startLine, nextLine, state.blkIndent, False))
|
51 | 52 |
|
52 | 53 | state.line = nextLine
|
53 | 54 |
|
|
Lines changed: 6 additions & 6 deletions
| Original file line number | Diff line number | Diff line change |
@@ -3,7 +3,7 @@
|
3 | 3 |
|
4 | 4 | import re
|
5 | 5 |
|
6 | | -from ..common.utils import charStrAt, isStrSpace
|
| 6 | +from ..common.utils import charStrAt, isStrSpace, mdTrim
|
7 | 7 | from .state_block import StateBlock
|
8 | 8 |
|
9 | 9 | headerLineRe = re.compile(r"^:?-+:?$")
|
@@ -108,7 +108,7 @@ def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool
|
108 | 108 | columns = lineText.split("|")
|
109 | 109 | aligns = []
|
110 | 110 | for i in range(len(columns)):
|
111 | | - t = columns[i].strip()
|
| 111 | + t = mdTrim(columns[i])
|
112 | 112 | if not t:
|
113 | 113 | # allow empty columns before and after table, but not in between columns;
|
114 | 114 | # e.g. allow ` |---| `, disallow ` ---||--- `
|
@@ -126,7 +126,7 @@ def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool
|
126 | 126 | else:
|
127 | 127 | aligns.append("")
|
128 | 128 |
|
129 | | - lineText = getLine(state, startLine).strip()
|
| 129 | + lineText = mdTrim(getLine(state, startLine))
|
130 | 130 | if "|" not in lineText:
|
131 | 131 | return False
|
132 | 132 | if state.is_code_block(startLine):
|
@@ -171,7 +171,7 @@ def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool
|
171 | 171 | # note in markdown-it this map was removed in v12.0.0 however, we keep it,
|
172 | 172 | # since it is helpful to propagate to children tokens
|
173 | 173 | token.map = [startLine, startLine + 1]
|
174 | | - token.content = columns[i].strip()
|
| 174 | + token.content = mdTrim(columns[i])
|
175 | 175 | token.children = []
|
176 | 176 |
|
177 | 177 | token = state.push("th_close", "th", -1)
|
@@ -193,7 +193,7 @@ def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool
|
193 | 193 |
|
194 | 194 | if terminate:
|
195 | 195 | break
|
196 | | - lineText = getLine(state, nextLine).strip()
|
| 196 | + lineText = mdTrim(getLine(state, nextLine))
|
197 | 197 | if not lineText:
|
198 | 198 | break
|
199 | 199 | if state.is_code_block(nextLine):
|
@@ -227,7 +227,7 @@ def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool
|
227 | 227 | # since it is helpful to propagate to children tokens
|
228 | 228 | token.map = [nextLine, nextLine + 1]
|
229 | 229 | try:
|
230 | | - token.content = columns[i].strip() if columns[i] else ""
|
| 230 | + token.content = mdTrim(columns[i]) if columns[i] else ""
|
231 | 231 | except IndexError:
|
232 | 232 | token.content = ""
|
233 | 233 | token.children = []
|
|
Lines changed: 81 additions & 0 deletions
| Original file line number | Diff line number | Diff line change |
@@ -0,0 +1,81 @@
|
| 1 | +"""Whitespace handling must match upstream markdown-it, not Python's ``str``.
|
| 2 | +
|
| 3 | +``str.strip()`` and ``str.split()`` without arguments use :py:meth:`str.isspace`,
|
| 4 | +which additionally treats U+001C, U+001D, U+001E, U+001F and U+0085 as
|
| 5 | +whitespace. CommonMark and ``String.prototype.trim`` do not, so relying on them
|
| 6 | +drops those characters from the output and folds two distinct reference labels
|
| 7 | +into one.
|
| 8 | +
|
| 9 | +The expected values below are what ``markdown-it@14.1.0`` produces for the same
|
| 10 | +input.
|
| 11 | +"""
|
| 12 | +
|
| 13 | +import pytest
|
| 14 | +
|
| 15 | +from markdown_it import MarkdownIt
|
| 16 | +
|
| 17 | +#: Characters Python calls whitespace and CommonMark does not.
|
| 18 | +EXTRA = ["\x1c", "\x1d", "\x1e", "\x1f", "\x85"]
|
| 19 | +
|
| 20 | +
|
| 21 | +@pytest.mark.parametrize("char", EXTRA)
|
| 22 | +def test_reference_label_is_not_folded(char):
|
| 23 | + """A definition whose label differs must not supply a different usage.
|
| 24 | +
|
| 25 | + Before this was fixed, ``[a<char>b]`` and ``[a b]`` normalized to the same
|
| 26 | + label, so the definition resolved a usage that does not name it.
|
| 27 | + """
|
| 28 | + md = MarkdownIt("js-default")
|
| 29 | + assert md.render(f"[a b]\n\n[a{char}b]: http://example.com") == "<p>[a b]</p>\n"
|
| 30 | + assert (
|
| 31 | + md.render(f"[a{char}b]\n\n[a b]: http://example.com") == f"<p>[a{char}b]</p>\n"
|
| 32 | + )
|
| 33 | +
|
| 34 | +
|
| 35 | +def test_reference_label_still_collapses_real_whitespace():
|
| 36 | + """Control: labels differing only in real whitespace still match."""
|
| 37 | + md = MarkdownIt("js-default")
|
| 38 | + assert (
|
| 39 | + md.render("[a b]\n\n[a\tb]: http://example.com")
|
| 40 | + == '<p><a href="http://example.com">a b</a></p>\n'
|
| 41 | + )
|
| 42 | +
|
| 43 | +
|
| 44 | +@pytest.mark.parametrize("char", EXTRA)
|
| 45 | +def test_character_survives_in_output(char):
|
| 46 | + """The character is content, so it has to reach the output."""
|
| 47 | + md = MarkdownIt("js-default")
|
| 48 | + assert md.render(f"x{char}") == f"<p>x{char}</p>\n"
|
| 49 | + assert md.render(f"{char}x") == f"<p>{char}x</p>\n"
|
| 50 | + assert md.render(f"# h{char}") == f"<h1>h{char}</h1>\n"
|
| 51 | + assert md.render(f"h{char}\n===") == f"<h1>h{char}</h1>\n"
|
| 52 | +
|
| 53 | +
|
| 54 | +def test_real_whitespace_is_still_trimmed():
|
| 55 | + """Control: what CommonMark does call whitespace is still removed."""
|
| 56 | + md = MarkdownIt("js-default")
|
| 57 | + for char in ["\t", " ", "\xa0", " ", " "]:
|
| 58 | + assert md.render(f"# h{char}") == "<h1>h</h1>\n", repr(char)
|
| 59 | +
|
| 60 | +
|
| 61 | +def test_fence_info_is_not_split_on_it():
|
| 62 | + """``str.split()`` would split the info string on U+0085."""
|
| 63 | + md = MarkdownIt("js-default")
|
| 64 | + assert (
|
| 65 | + md.render("```py\x85rest\nx\n```")
|
| 66 | + == '<pre><code class="language-py\x85rest">x\n</code></pre>\n'
|
| 67 | + )
|
| 68 | +
|
| 69 | +
|
| 70 | +def test_fence_info_still_splits_on_whitespace():
|
| 71 | + """Control: a real space still separates language from attributes."""
|
| 72 | + md = MarkdownIt("js-default")
|
| 73 | + assert (
|
| 74 | + md.render("```py extra\nx\n```")
|
| 75 | + == '<pre><code class="language-py">x\n</code></pre>\n'
|
| 76 | + )
|
| 77 | +
|
| 78 | +
|
| 79 | +def test_table_cell_keeps_the_character():
|
| 80 | + md = MarkdownIt("js-default").enable("table")
|
| 81 | + assert "c\x85" in md.render("|a|\n|---|\n|c\x85|")
|
|
|