pretext icon indicating copy to clipboard operation
pretext copied to clipboard

normalizeWhitespacePreWrap fast-path runs a no-op replace on every pre-wrap prepare() call

Open beeegee opened this issue 7 months ago • 1 comments

Bug description

normalizeWhitespacePreWrap in src/analysis.ts has a fast-path that runs a regex replace that can never match:

function normalizeWhitespacePreWrap(text: string): string {
  if (!/[\r\f]/.test(text)) return text.replace(/\r\n/g, '\n')  // ← no-op
  return text
    .replace(/\r\n/g, '\n')
    .replace(/[\r\f]/g, '\n')
}

The fast-path fires when the text contains neither \r nor \f. But without a \r character there can be no \r\n sequence. The replace(/\r\n/g, '\n') on the fast-path return value is therefore always a no-op — the pattern can never match.

This runs on every prepare() call in whiteSpace: 'pre-wrap' mode, which includes the common case of user-typed textarea text that contains only \n newlines.

Minimal repro

// Every prepare() call in pre-wrap mode on typical text goes through this:
prepare("line one\nline two\nline three", font, { whiteSpace: 'pre-wrap' })
// normalizeWhitespacePreWrap:
//   !/[\r\f]/.test(text) → true   (fast path)
//   → returns text.replace(/\r\n/g, '\n')   ← regex scans entire string for no reason

Suggested fix

function normalizeWhitespacePreWrap(text: string): string {
  if (!/[\r\f]/.test(text)) return text   // no \r means no \r\n — skip the replace
  return text
    .replace(/\r\n/g, '\n')
    .replace(/[\r\f]/g, '\n')
}

One-character change. All existing behaviour is preserved; the redundant regex scan is removed.

beeegee avatar Apr 08 '26 06:04 beeegee

Fixed in #118 — simplified the fast-path to a plain return text. No \r means no \r\n, so the replace was scanning every pre-wrap string for nothing. All pre-wrap tests still pass.

beeegee avatar Apr 08 '26 10:04 beeegee