Skip to content

Commit 653663d

Browse files
NginxLclaude
andcommitted
review 6: a CRLF code body sliced by its own end; each bare address from its own start; code fenced past its backticks; a mark written in the text is no mask
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 251e2a0 commit 653663d

2 files changed

Lines changed: 31 additions & 7 deletions

File tree

‎core/openmate_core/markup.py‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@
3838
MASK = "\x01" # stands for code's words, an address: never markup, wherever the stars are
3939
IMAGE_MASK = "\x03" # stands for an image, its text and address: words, never a link
4040
LINK_MASK = "\x04" # stands for a link's address (LINK's, http or https in lower case): its link's
41+
MASKS = (MASK, "\x02", IMAGE_MASK, LINK_MASK)
42+
SCHEME = re.compile(r"(?i)https?://")
4143
# on a line masked (_masked): `code`, **bold** (no space just inside the stars), [words](its address, masked)
4244
INLINE = re.compile(r"`([^`\n]+)`|\*\*(?=\S)(.+?)(?<=\S)\*\*|(?<!!)\[([^\[\]\n]+)\]\((\x04+)\)")
4345
MD_SPECIAL = re.compile(r"([\\`*_~\[\]<>|&])")
@@ -63,7 +65,7 @@ class Run(NamedTuple):
6365
def _masked(line: str) -> str:
6466
"""The line with code's words, images and bare addresses as MASK: what no markup is read in (a "**" in code, in
6567
an address, closes no bold; an image is no link)."""
66-
m = list(line)
68+
m = ["\x00" if c in MASKS else c for c in line] # (a mark written in the text is none of these)
6769

6870
def blank(a: int, b: int, mark: str = MASK) -> None:
6971
m[a:b] = mark * (b - a)
@@ -76,8 +78,14 @@ def blank(a: int, b: int, mark: str = MASK) -> None:
7678
once = "".join(m)
7779
# a bare address that starts outside any "[words](address)" and runs through one keeps it: the link is in its words
7880
candidates = [(x.start(), x.end()) for x in LINK.finditer(once)]
79-
bare = [(u.start(), u.start() + len(_trim_url(u.group()))) for u in URL.finditer(once)
80-
if not any(a <= u.start() < b for a, b in candidates)]
81+
bare: List[Tuple[int, int]] = []
82+
for st in SCHEME.finditer(once): # each address from its own start (one inside a link takes none after it)
83+
p = st.start()
84+
if any(a <= p < b for a, b in candidates) or (bare and p < bare[-1][1]):
85+
continue
86+
u = URL.match(once, p)
87+
if u:
88+
bare.append((p, p + len(_trim_url(u.group()))))
8189
hidden = list(once) # the links whole as MASK: no bare address starts in one, nor runs on from one
8290
for x in LINK.finditer(once):
8391
if any(a < x.start() < b for a, b in bare):
@@ -148,8 +156,10 @@ def _md_line(runs: List[Run]) -> str:
148156
for bold, group in itertools.groupby(runs, key=lambda r: r.bold):
149157
parts = []
150158
for r in group:
151-
if r.kind == "code":
152-
parts.append("`%s`" % r.words)
159+
if r.kind == "code": # (fenced by more backticks than any run in its words)
160+
ticks = "`" * (max([len(t) for t in re.findall(r"`+", r.words)] + [0]) + 1)
161+
pad = " " if r.words.startswith("`") or r.words.endswith("`") else ""
162+
parts.append("%s%s%s%s%s" % (ticks, pad, r.words, pad, ticks))
153163
elif r.kind == "link":
154164
parts.append("[%s](%s)" % (_md_escape(r.words), r.url.replace("&", "\\&"))) # (no entity: "&copy;")
155165
elif r.kind == "url":
@@ -203,7 +213,10 @@ def markdown(self, src: Optional[str] = None) -> str:
203213
runs'."""
204214
k = self.kind
205215
if k == "code":
206-
body = self["body"] if src is None else src[self["body_at"]:self["body_at"] + len(self["body"])]
216+
body = self["body"]
217+
if src is not None: # (as written: a name in it too; a CRLF as an LF, as the body reads)
218+
body = "\n".join(line[:-1] if line.endswith("\r") else line
219+
for line in src[self["body_at"]:self["body_end"]].split("\n")) if body else ""
207220
ticks = max([len(t) for t in re.findall(r"`{3,}", body)] + [2]) + 1 # a fence the body never closes
208221
return "%s%s\n%s%s%s" % ("`" * ticks, self.get("lang") or "", body, "\n" if body else "", "`" * ticks)
209222
# a line of only - = * _ is words, in a quote or a list too (never a heading's underline)
@@ -254,7 +267,8 @@ def end_of(j: int) -> int:
254267
body = "\n".join(lines[i + 1:j])
255268
last = min(j, n - 1) # not closed: it runs to the end
256269
out.append(Block(kind="code", lang=fence.group(2).lower(), body=body, start=offs[i], end=end_of(last),
257-
body_at=offs[i + 1] if i + 1 < n else end_of(i)))
270+
body_at=offs[i + 1] if i + 1 < n else end_of(i),
271+
body_end=(offs[j] - 1) if j < n else len(text or "")))
258272
i = j + 1
259273
continue
260274
if not line.strip():

‎tests/test_markup.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,16 @@ def test_fourth_review(self):
130130
[("link", "https://a.com"), ("link", "https://b.com"), ("link", "https://c.com")])
131131
self.assertFalse(markup.formatted("见 [文档](HTTPS://e.org/d)"), "a link's address in lower case only")
132132

133+
def test_sixth_review(self):
134+
t = "```\r\nabc\r\ndef\r\n```"
135+
self.assertEqual(markup.blocks(t)[0].markdown(t), "```\nabc\ndef\n```")
136+
self.assertEqual([(r.kind, r.url) for r in markup.inline("[A](https://a.org)和https://b.org/?q=[B](https://c.org)")],
137+
[("link", "https://a.org"), ("text", ""), ("url", "https://b.org/?q=[B](https://c.org)")])
138+
self.assertFalse(markup.formatted('"[x](\u0004)"'), "a mark written in the text is none of the masks")
139+
name = "@A`B\n\n`@A`B`"
140+
md = markup.blocks(markup.without_names(name, ["A`B"]))[1].markdown(name)
141+
self.assertEqual(md, "``@A`B``", "code fenced by more backticks than are in it")
142+
133143
def test_words_that_stay_words(self):
134144
for text in ("*****", '![**map**](map.png "Map")'):
135145
self.assertFalse(markup.formatted(text), text)

0 commit comments

Comments
 (0)