Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

performance: faster line wrap pt. 2 #476

Merged
merged 3 commits into from
Nov 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 20 additions & 16 deletions src/mdformat/renderer/_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@
PRESERVE_CHAR = "\x00"
RE_PRESERVE_CHAR = re.compile(re.escape(PRESERVE_CHAR))

RE_UNICODE_WS_OR_WRAP_POINT = re.compile(
rf"[{re.escape(''.join(codepoints.UNICODE_WHITESPACE))}]"
"|"
rf"{re.escape(WRAP_POINT)}+"
)


def make_render_children(separator: str) -> Render:
def render_children(
Expand Down Expand Up @@ -350,29 +356,27 @@ def _wrap(text: str, *, width: int | Literal["no"]) -> str:
return wrapped


def _prepare_wrap(text: str) -> tuple[str, str]:
def _prepare_wrap(text: str) -> tuple[str, list[str]]:
"""Prepare text for wrap.

Convert `WRAP_POINT`s to spaces. Convert whitespace to
`PRESERVE_CHAR`s. Return a tuple with the prepared string, and
another string consisting of replacement characters for
`PRESERVE_CHAR`s.
`PRESERVE_CHAR`s. Return a tuple with the prepared string, and a
list consisting of replacement characters for `PRESERVE_CHAR`s.
"""
result = ""
replacements = ""
for c in text:
if c == WRAP_POINT:
if not result or result[-1] != " ":
result += " "
elif c in codepoints.UNICODE_WHITESPACE:
result += PRESERVE_CHAR
replacements += c
else:
result += c
replacements = []

def replacer(match: re.Match[str]) -> str:
first_char = match.group()[0]
if first_char == WRAP_POINT:
return " "
replacements.append(first_char)
return PRESERVE_CHAR

result = RE_UNICODE_WS_OR_WRAP_POINT.sub(replacer, text)
return result, replacements


def _recover_preserve_chars(text: str, replacements: str) -> str:
def _recover_preserve_chars(text: str, replacements: Iterable[str]) -> str:
iter_replacements = iter(replacements)
return RE_PRESERVE_CHAR.sub(lambda _: next(iter_replacements), text)

Expand Down