mathfence 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mathfence/regions.py ADDED
@@ -0,0 +1,264 @@
1
+ """Find the regions of a Markdown text that must be copied byte for byte.
2
+
3
+ Protected regions are fenced code, indented code, code spans, HTML blocks,
4
+ inline HTML tags, autolinks and bare URLs. Everything is a plain line/regex
5
+ scan (no full CommonMark parser), tuned to be *conservative*: when unsure the
6
+ text is left alone.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from bisect import bisect_right
13
+ from dataclasses import dataclass
14
+
15
+ from . import rules
16
+
17
+ # A paragraph break: a blank line, or a line holding only quote markers.
18
+ PARA = re.compile(r"\n[ \t>\r]*\n")
19
+
20
+ _LIST_MARK = re.compile(r"^ {0,3}(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)")
21
+ _FENCE = re.compile(
22
+ r"^(?P<prefix>(?:[ \t]*>)*[ \t]*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)*)"
23
+ r"(?P<fence>`{3,}|~{3,})(?P<info>.*)$"
24
+ )
25
+ _BLOCK_TAGS = (
26
+ "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|"
27
+ "details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|"
28
+ "h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|"
29
+ "noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|"
30
+ "thead|title|tr|track|ul"
31
+ )
32
+ _HTML_START = re.compile(
33
+ r"^ {0,3}(?:(?P<raw><(?P<rawname>pre|script|style|textarea)(?:[ \t>]|$))"
34
+ r"|(?P<comment><!--)|(?P<pi><\?)|(?P<decl><![A-Za-z])|(?P<cdata><!\[CDATA\[)"
35
+ r"|</?(?:" + _BLOCK_TAGS + r")(?:[ \t]|/?>|$))",
36
+ re.IGNORECASE,
37
+ )
38
+ _AUTOLINK = re.compile(r"<[A-Za-z][A-Za-z0-9+.-]{1,31}:[^\s<>]*>")
39
+ _URL = re.compile(r"(?<![\w/])(?:https?|ftp)://[^\s<>]+")
40
+ _HTML_TAG = re.compile(
41
+ r"</?[A-Za-z][A-Za-z0-9-]*"
42
+ r"(?:[ \t\r\n]+[A-Za-z_:][\w.:-]*(?:[ \t\r\n]*=[ \t\r\n]*(?:[^\s\"'=<>`]+|'[^']*'|\"[^\"]*\"))?)*"
43
+ r"[ \t\r\n]*/?>"
44
+ )
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Region:
49
+ """A half-open ``[start, end)`` slice that is copied unchanged."""
50
+
51
+ start: int
52
+ end: int
53
+ kind: str # "code" | "url" | "html"
54
+ rule: str # one of the rule ids in :mod:`mathfence.rules`
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Scan:
59
+ """Result of :func:`scan`."""
60
+
61
+ regions: tuple[Region, ...]
62
+ #: Offsets that start a line right after a blank line, outside every block
63
+ #: construct. Text can be split there without changing the result.
64
+ boundaries: tuple[int, ...]
65
+
66
+
67
+ class RegionIndex:
68
+ """Fast "which region contains offset i" lookups over sorted regions."""
69
+
70
+ def __init__(self, regions: tuple[Region, ...]) -> None:
71
+ self.regions = regions
72
+ self._starts = [r.start for r in regions]
73
+
74
+ def at(self, i: int) -> Region | None:
75
+ k = bisect_right(self._starts, i) - 1
76
+ if k >= 0 and self.regions[k].end > i:
77
+ return self.regions[k]
78
+ return None
79
+
80
+
81
+ def _leading_spaces(prefix: str) -> int:
82
+ return len(prefix) - len(prefix.lstrip(" "))
83
+
84
+
85
+ def _scan_blocks(text: str) -> tuple[list[Region], list[int]]:
86
+ lines = text.split("\n")
87
+ starts: list[int] = []
88
+ pos = 0
89
+ for ln in lines:
90
+ starts.append(pos)
91
+ pos += len(ln) + 1
92
+ n = len(lines)
93
+ regions: list[Region] = []
94
+ boundaries: list[int] = []
95
+ i = 0
96
+ prev_blank = True
97
+ list_active = False
98
+ while i < n:
99
+ line = lines[i]
100
+ # --- fenced code (also inside quotes and list items) ---
101
+ m = _FENCE.match(line)
102
+ if m:
103
+ prefix, fence, info = m.group("prefix"), m.group("fence"), m.group("info")
104
+ has_container = ">" in prefix or bool(prefix.strip())
105
+ plain_indent = not has_container and _leading_spaces(prefix) >= 4 and not list_active
106
+ if not plain_indent and not (fence[0] == "`" and "`" in info):
107
+ j = i + 1
108
+ end = len(text)
109
+ while j < n:
110
+ stripped = re.sub(r"^[ \t>]*", "", lines[j]).strip()
111
+ if len(stripped) >= len(fence) and set(stripped) == {fence[0]}:
112
+ end = starts[j] + len(lines[j])
113
+ break
114
+ j += 1
115
+ regions.append(Region(starts[i], end, "code", rules.CODE_FENCE))
116
+ i = j + 1
117
+ prev_blank = True
118
+ if re.search(r"[-*+]|\d[.)]", prefix.replace(">", "")) and prefix.strip(" >\t"):
119
+ list_active = True
120
+ elif _leading_spaces(prefix) < 2:
121
+ list_active = False
122
+ continue
123
+ # --- blank line ---
124
+ if not line.strip():
125
+ if not list_active and starts[i] + len(line) + 1 <= len(text):
126
+ boundaries.append(starts[i] + len(line) + 1)
127
+ prev_blank = True
128
+ i += 1
129
+ continue
130
+ # --- HTML block (top level only) ---
131
+ hm = _HTML_START.match(line) if not line.lstrip().startswith(">") else None
132
+ if hm and not line.startswith(" "):
133
+ j = i
134
+ if hm.group("raw"):
135
+ closer = "</" + hm.group("rawname").lower() + ">"
136
+ while j < n and closer not in lines[j].lower():
137
+ j += 1
138
+ elif hm.group("comment"):
139
+ while j < n and "-->" not in lines[j]:
140
+ j += 1
141
+ elif hm.group("pi"):
142
+ while j < n and "?>" not in lines[j]:
143
+ j += 1
144
+ elif hm.group("cdata"):
145
+ while j < n and "]]>" not in lines[j]:
146
+ j += 1
147
+ elif hm.group("decl"):
148
+ while j < n and ">" not in lines[j]:
149
+ j += 1
150
+ else:
151
+ while j + 1 < n and lines[j + 1].strip():
152
+ j += 1
153
+ j = min(j, n - 1)
154
+ regions.append(Region(starts[i], starts[j] + len(lines[j]), "html", rules.HTML_BLOCK))
155
+ i = j + 1
156
+ prev_blank = False
157
+ continue
158
+ # --- indented code ---
159
+ if prev_blank and not list_active and (line.startswith(" ") or line.startswith("\t")):
160
+ j = i
161
+ k = i + 1
162
+ while k < n:
163
+ if lines[k].startswith(" ") or lines[k].startswith("\t"):
164
+ j = k
165
+ elif lines[k].strip():
166
+ break
167
+ k += 1
168
+ regions.append(Region(starts[i], starts[j] + len(lines[j]), "code", rules.INDENTED_CODE))
169
+ i = j + 1
170
+ prev_blank = False
171
+ continue
172
+ # --- ordinary line: track list context ---
173
+ # A top-level list item that starts a new block can settle everything
174
+ # before it, but only when no math marker (``$`` or a backslash) could
175
+ # pair across the cut; otherwise full-document results could differ.
176
+ if i > 0 and _LIST_MARK.match(line) and not line[0].isspace():
177
+ seg_from = boundaries[-1] if boundaries else 0
178
+ segment = text[seg_from : starts[i]]
179
+ if "$" not in segment and "\\" not in segment and segment.strip():
180
+ boundaries.append(starts[i])
181
+ if _LIST_MARK.match(line):
182
+ list_active = True
183
+ elif prev_blank and _leading_spaces(line) < 2 and not line.startswith("\t"):
184
+ list_active = False
185
+ prev_blank = False
186
+ i += 1
187
+ return regions, boundaries
188
+
189
+
190
+ def _inline_regions(text: str, lo: int, hi: int, streaming: bool) -> list[Region]:
191
+ found: list[Region] = []
192
+ k = lo
193
+ while k < hi:
194
+ c = text[k]
195
+ if c == "\\":
196
+ k += 2
197
+ continue
198
+ if c != "`":
199
+ k += 1
200
+ continue
201
+ n = 1
202
+ while k + n < hi and text[k + n] == "`":
203
+ n += 1
204
+ closer = re.compile(r"(?<!`)" + "`" * n + r"(?!`)").search(text, k + n, hi)
205
+ if closer and not PARA.search(text, k, closer.start()):
206
+ found.append(Region(k, closer.end(), "code", rules.CODE_SPAN))
207
+ k = closer.end()
208
+ continue
209
+ if streaming and hi == len(text) and not PARA.search(text, k, hi):
210
+ # Still-open span at the end of a stream: hold it back unchanged.
211
+ found.append(Region(k, hi, "code", rules.STREAM_PENDING))
212
+ break
213
+ k += n
214
+ for m in _AUTOLINK.finditer(text, lo, hi):
215
+ found.append(Region(m.start(), m.end(), "url", rules.AUTOLINK))
216
+ for m in _URL.finditer(text, lo, hi):
217
+ end = m.end()
218
+ while end > m.start() and text[end - 1] in ".,;:!?'\"*_~":
219
+ end -= 1
220
+ while end > m.start() and text[end - 1] in ")]" and (
221
+ text.count(text[end - 1], m.start(), end) > text.count("(" if text[end - 1] == ")" else "[", m.start(), end)
222
+ ):
223
+ end -= 1
224
+ if end > m.start() + 8:
225
+ found.append(Region(m.start(), end, "url", rules.BARE_URL))
226
+ for m in _HTML_TAG.finditer(text, lo, hi):
227
+ if not PARA.search(m.group(0)):
228
+ found.append(Region(m.start(), m.end(), "html", rules.HTML_TAG))
229
+ return found
230
+
231
+
232
+ def _merge(regions: list[Region]) -> tuple[Region, ...]:
233
+ merged: list[Region] = []
234
+ for r in sorted(regions, key=lambda r: (r.start, -r.end)):
235
+ if merged and r.start < merged[-1].end:
236
+ last = merged[-1]
237
+ if r.end > last.end:
238
+ merged[-1] = Region(last.start, r.end, last.kind, last.rule)
239
+ else:
240
+ merged.append(r)
241
+ return tuple(merged)
242
+
243
+
244
+ def scan(text: str, *, streaming: bool = False) -> Scan:
245
+ """Find protected regions and safe split points in ``text``.
246
+
247
+ With ``streaming=True`` an unclosed inline code span at the very end is
248
+ also protected (it is probably about to be closed).
249
+ """
250
+ blocks, boundaries = _scan_blocks(text)
251
+ blocks.sort(key=lambda r: r.start)
252
+ found: list[Region] = list(blocks)
253
+ cursor = 0
254
+ for b in blocks:
255
+ if cursor < b.start:
256
+ found.extend(_inline_regions(text, cursor, b.start, streaming))
257
+ cursor = max(cursor, b.end)
258
+ if cursor < len(text):
259
+ found.extend(_inline_regions(text, cursor, len(text), streaming))
260
+ merged = _merge(found)
261
+ safe = tuple(
262
+ b for b in boundaries if not any(r.start < b <= r.end and r.rule != rules.STREAM_PENDING for r in merged)
263
+ )
264
+ return Scan(merged, safe)
mathfence/rules.py ADDED
@@ -0,0 +1,123 @@
1
+ """Rule ids and the "does this body look like math?" judgement.
2
+
3
+ Every decision mathfence makes carries one of the ids below, so the CLI
4
+ (``--explain``) can say *why* a ``$`` was kept or escaped.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import NamedTuple
11
+
12
+ # --- decisions about `$` ---
13
+ MATH_PAIR = "math-pair"
14
+ CLOSE_FOLLOWED_BY_DIGIT = "close-followed-by-digit"
15
+ CLOSE_FOLLOWED_BY_DOLLAR = "close-followed-by-dollar"
16
+ BODY_EMPTY = "body-empty"
17
+ BODY_EDGE_SPACE = "body-edge-space"
18
+ BODY_WORDS = "body-words"
19
+ BODY_ENDS_OPERATOR = "body-ends-operator"
20
+ BODY_BLOCK_BOUNDARY = "body-block-boundary"
21
+ NO_CLOSING = "no-closing"
22
+ DOUBLE_CURRENCY = "double-currency"
23
+ DOLLAR_RUN = "dollar-run"
24
+ STREAM_PENDING = "stream-pending"
25
+ DISPLAY_OWN_LINE = "display-own-line"
26
+
27
+ # --- decisions about `\(` and `\[` ---
28
+ BRACKET_INLINE = "bracket-inline"
29
+ BRACKET_INLINE_DOUBLE = "bracket-inline-double"
30
+ BRACKET_DISPLAY = "bracket-display"
31
+ BRACKET_HAS_DOLLAR = "bracket-has-dollar"
32
+ BRACKET_AMBIGUOUS = "bracket-ambiguous"
33
+
34
+ # --- protected regions ---
35
+ CODE_FENCE = "code-fence"
36
+ CODE_SPAN = "code-span"
37
+ INDENTED_CODE = "indented-code"
38
+ AUTOLINK = "autolink"
39
+ BARE_URL = "bare-url"
40
+ HTML_BLOCK = "html-block"
41
+ HTML_TAG = "html-tag"
42
+
43
+ ALL_RULES: tuple[str, ...] = (
44
+ MATH_PAIR,
45
+ CLOSE_FOLLOWED_BY_DIGIT,
46
+ CLOSE_FOLLOWED_BY_DOLLAR,
47
+ BODY_EMPTY,
48
+ BODY_EDGE_SPACE,
49
+ BODY_WORDS,
50
+ BODY_ENDS_OPERATOR,
51
+ BODY_BLOCK_BOUNDARY,
52
+ NO_CLOSING,
53
+ DOUBLE_CURRENCY,
54
+ DOLLAR_RUN,
55
+ STREAM_PENDING,
56
+ DISPLAY_OWN_LINE,
57
+ BRACKET_INLINE,
58
+ BRACKET_INLINE_DOUBLE,
59
+ BRACKET_DISPLAY,
60
+ BRACKET_HAS_DOLLAR,
61
+ BRACKET_AMBIGUOUS,
62
+ CODE_FENCE,
63
+ CODE_SPAN,
64
+ INDENTED_CODE,
65
+ AUTOLINK,
66
+ BARE_URL,
67
+ HTML_BLOCK,
68
+ HTML_TAG,
69
+ )
70
+
71
+ # Characters or commands that only appear in formulas.
72
+ _TEX = re.compile(r"\\[A-Za-z]+|[\^_{}=<>+]|\\\\")
73
+ # Two consecutive words of 2+ letters (English, accented Latin, Hangul).
74
+ _WORDS = re.compile(r"[A-Za-z\u00c0-\u024f\uac00-\ud7a3]{2,}[ \t]+[A-Za-z\u00c0-\u024f\uac00-\ud7a3]{2,}")
75
+ # A newline followed by something that starts a new Markdown block.
76
+ _BLOCK_START = re.compile(r"\n[ \t]*(?:[-*+][ \t]|\d{1,9}[.)][ \t]|>|#|\|)")
77
+ _OPERATORS = "+-*/=,.;:"
78
+
79
+
80
+ def has_tex(body: str) -> bool:
81
+ """True if ``body`` contains a TeX command or a formula-only character."""
82
+ return _TEX.search(body) is not None
83
+
84
+
85
+ def judge_single(body: str, after: str) -> str | None:
86
+ """Judge the body of a single-``$`` pair.
87
+
88
+ ``body`` is the text between the dollars, ``after`` the character that
89
+ follows the closing dollar (``""`` at the end of the text). Returns
90
+ ``None`` when the pair is math, otherwise the id of the failing rule.
91
+ """
92
+ if not body.strip():
93
+ return BODY_EMPTY
94
+ if body[0].isspace() or body[-1].isspace():
95
+ return BODY_EDGE_SPACE
96
+ if _BLOCK_START.search(body):
97
+ return BODY_BLOCK_BOUNDARY
98
+ if body[-1] in _OPERATORS:
99
+ return BODY_ENDS_OPERATOR
100
+ if "\\" not in body and _WORDS.search(body):
101
+ return BODY_WORDS
102
+ if after[:1].isdigit():
103
+ return CLOSE_FOLLOWED_BY_DIGIT
104
+ return None
105
+
106
+
107
+ def judge_double(body: str) -> str | None:
108
+ """Judge the body of a ``$$ … $$`` pair (``None`` means math)."""
109
+ if not body.strip():
110
+ return BODY_EMPTY
111
+ if body.lstrip()[0].isdigit() and not has_tex(body):
112
+ return DOUBLE_CURRENCY
113
+ return None
114
+
115
+
116
+ class Raw(NamedTuple):
117
+ """A decision before line/column are resolved (offset is in the text it was made on)."""
118
+
119
+ offset: int
120
+ source: str
121
+ action: str
122
+ kind: str
123
+ rule: str
mathfence/stream.py ADDED
@@ -0,0 +1,76 @@
1
+ """Incremental normalization for token streams."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from . import regions
8
+ from .core import check_input, run
9
+
10
+
11
+ @dataclass
12
+ class StreamStats:
13
+ """Work counters of a :class:`StreamNormalizer`."""
14
+
15
+ #: Characters passed through the normalizer so far (all feeds summed).
16
+ reprocessed_chars: int = 0
17
+ #: Characters already settled and never looked at again.
18
+ committed_chars: int = 0
19
+
20
+
21
+ class StreamNormalizer:
22
+ """Normalize a growing answer chunk by chunk.
23
+
24
+ ``feed(chunk)`` returns the text to show *now*. It never shows math that
25
+ the finished answer would not contain: a closing ``$`` at the very end is
26
+ held back (written as ``\\$``) until the next character arrives, and an
27
+ unclosed code span is left alone. Text before the last paragraph break
28
+ that is outside code, HTML and lists is settled and not processed again.
29
+
30
+ >>> sn = StreamNormalizer()
31
+ >>> sn.feed("Pay $5 if $")
32
+ 'Pay \\\\$5 if \\\\$'
33
+ """
34
+
35
+ def __init__(self, *, profile: str = "remark") -> None:
36
+ check_input("", profile)
37
+ self.profile = profile
38
+ self.stats = StreamStats()
39
+ self._raw: list[str] = []
40
+ self._committed = "" # normalized text of settled paragraphs
41
+ self._tail = "" # raw text not settled yet
42
+ self._finished = False
43
+
44
+ @property
45
+ def text(self) -> str:
46
+ """All raw text received so far."""
47
+ return "".join(self._raw)
48
+
49
+ def feed(self, chunk: str) -> str:
50
+ """Add ``chunk`` and return the normalized text of everything received.
51
+
52
+ Raises:
53
+ RuntimeError: ``finish()`` was already called.
54
+ TypeError: ``chunk`` is not a ``str``.
55
+ """
56
+ if self._finished:
57
+ raise RuntimeError("feed() called after finish(); create a new StreamNormalizer for the next answer")
58
+ if not isinstance(chunk, str):
59
+ raise TypeError(f"chunk must be str, got {type(chunk).__name__}")
60
+ self._raw.append(chunk)
61
+ self._tail += chunk
62
+ if "\n" in chunk:
63
+ boundaries = regions.scan(self._tail, streaming=True).boundaries
64
+ if boundaries:
65
+ cut = boundaries[-1]
66
+ settled, self._tail = self._tail[:cut], self._tail[cut:]
67
+ self._committed += run(settled, self.profile, False).text
68
+ self.stats.reprocessed_chars += len(settled)
69
+ self.stats.committed_chars += len(settled)
70
+ self.stats.reprocessed_chars += len(self._tail)
71
+ return self._committed + run(self._tail, self.profile, True).text
72
+
73
+ def finish(self) -> str:
74
+ """Return the final normalized text (equal to ``normalize(self.text)``)."""
75
+ self._finished = True
76
+ return run(self.text, self.profile, False).text