Skip to content

Commit 34fc8e2

Browse files
committed
Improve InlineHilite pattern parsing
1 parent 5dfef3f commit 34fc8e2

3 files changed

Lines changed: 71 additions & 16 deletions

File tree

‎docs/src/markdown/about/changelog.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ icon: lucide/scroll-text
33
---
44
# Changelog
55

6+
## 11.0.2
7+
8+
- **FIX**: InlineHilite: Improve performance of inline code matching.
9+
610
## 11.0.1
711

812
- **FIX**: BetterEm: Fix regex pattern inefficiencies.

‎pymdownx/__meta__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,5 +193,5 @@ def parse_version(ver: str) -> Version:
193193
return Version(major, minor, micro, release, pre, post, dev)
194194

195195

196-
__version_info__ = Version(11, 0, 1, "final")
196+
__version_info__ = Version(11, 0, 2, "final")
197197
__version__ = __version_info__._get_canonical()

‎pymdownx/inlinehilite.py‎

Lines changed: 66 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,11 @@
2020
from markdown import util as md_util
2121
import xml.etree.ElementTree as etree
2222
import functools
23+
import re
2324

25+
BACKTICK_CODE_RE = r'(?:(?<!\\)((?:\\{2})+)(?=`+)|(?<!\\)`)'
2426
ESCAPED_BSLASH = '{}{}{}'.format(md_util.STX, ord('\\'), md_util.ETX)
2527
DOUBLE_BSLASH = '\\\\'
26-
BACKTICK_CODE_RE = r'''(?x)
27-
(?:
28-
(?<!\\)(?P<escapes>(?:\\{2})+)(?=`+) | # Process code escapes before code
29-
(?<!\\)(?P<tic>`+)
30-
((?:\:{3,}|\#!)(?P<lang>[\w#.+-]*)\s+)? # Optional language
31-
(?P<code>.+?) # Code
32-
(?<!`)(?P=tic)(?!`) # Closing
33-
)
34-
'''
3528

3629

3730
class InlineHiliteException(Exception):
@@ -62,6 +55,8 @@ def _formatter(src="", language="", md=None, class_name="", fmt=None):
6255
class InlineHilitePattern(InlineProcessor):
6356
"""Handle the inline code patterns."""
6457

58+
RE_LANG = re.compile(r'^((?:\:{3,}|\#!)(?P<lang>[\w#.+-]*)\s+)')
59+
6560
def __init__(self, pattern, config, md):
6661
"""Initialize."""
6762

@@ -170,21 +165,77 @@ def handle_code(self, lang, src):
170165
value = self.md.htmlStash.store(value)
171166
return value
172167

168+
def find_code_spans(self, start: int, text: str) -> tuple[int, int] | None:
169+
"""Find code spans."""
170+
171+
last = len(text)
172+
173+
# Get the maximum starting ticks
174+
max_ticks = 0
175+
while start < last and text[start] == '`':
176+
max_ticks += 1
177+
start += 1
178+
179+
if not max_ticks: # pragma: no cover
180+
# This is not ever expected to happen.
181+
return None
182+
183+
longest_span = 0
184+
end = 0
185+
186+
# Find an ending span of backticks that matches our opening
187+
i = start
188+
while i < last:
189+
span_length = 0
190+
while i < last and text[i] == '`':
191+
span_length += 1
192+
i += 1
193+
continue
194+
if not span_length:
195+
i += 1
196+
continue
197+
198+
# Did we find the end?
199+
if max_ticks == span_length:
200+
return start, i - span_length
201+
202+
# Track the longest span of backticks we find as a fallback.
203+
if span_length > longest_span:
204+
longest_span = span_length
205+
end = i
206+
207+
# Since we didn't find an exact matching start and end,
208+
# adjust start to match the largest end we could calculate.
209+
if longest_span:
210+
return start - (max_ticks - longest_span), end - longest_span
211+
212+
# We could not find a suitable pairing
213+
return None
214+
173215
def handleMatch(self, m, data):
174216
"""Handle the pattern match."""
175217

176-
if m.group('escapes'):
177-
return m.group('escapes').replace(DOUBLE_BSLASH, ESCAPED_BSLASH), m.start(0), m.end(0)
178-
else:
179-
lang = m.group('lang') if m.group('lang') else ''
180-
src = m.group('code').strip()
218+
if m.group(1):
219+
return m.group(1).replace(DOUBLE_BSLASH, ESCAPED_BSLASH), m.start(0), m.end(0)
220+
221+
begin = m.start(0)
222+
result = self.find_code_spans(begin, data)
223+
if result is not None:
224+
start, end = result
225+
src = data[start:end]
226+
m2 = self.RE_LANG.match(src)
227+
lang = ''
228+
if m2:
229+
lang = m2.group('lang')
230+
src = src[m2.end('lang'):]
181231
self.get_settings()
182232
try:
183-
return self.handle_code(lang, src), m.start(0), m.end(0)
233+
return self.handle_code(lang, src.strip()), begin, result[1] + (start - begin)
184234
except InlineHiliteException:
185235
raise
186236
except Exception:
187237
return m.group(0), None, None
238+
return None, None, None
188239

189240

190241
class InlineHiliteExtension(Extension):

0 commit comments

Comments
 (0)