Skip to content

Commit

Permalink
Improve worst-case performance of inline.text regex
Browse files Browse the repository at this point in the history
The old regex may take quadratic time to scan for potential line
breaks or email addresses starting at every point.  Fix it to avoid
scanning from points that would have been in the middle of a previous
scan.

Signed-off-by: Anders Kaseorg <[email protected]>
  • Loading branch information
andersk committed Apr 3, 2019
1 parent ba1de1e commit 18dbc0b
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 8 deletions.
9 changes: 3 additions & 6 deletions lib/marked.js
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ var inline = {
code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
br: /^( {2,}|\\)\n(?!\s*$)/,
del: noop,
text: /^(`+|[^`])[\s\S]*?(?=[\\<!\[`*]|\b_| {2,}\n|$)/
text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/
};

// list of punctuation marks from common mark spec
Expand Down Expand Up @@ -615,10 +615,7 @@ inline.gfm = merge({}, inline.normal, {
url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
_backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
del: /^~+(?=\S)([\s\S]*?\S)~+/,
text: edit(inline.text)
.replace(']|', '~]|')
.replace('|$', '|https?://|ftp://|www\\.|[a-zA-Z0-9.!#$%&\'*+/=?^_`{\\|}~-]+@|$')
.getRegex()
text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))|(?= {2,}\n|[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))/
});

inline.gfm.url = edit(inline.gfm.url, 'i')
Expand All @@ -630,7 +627,7 @@ inline.gfm.url = edit(inline.gfm.url, 'i')

inline.breaks = merge({}, inline.gfm, {
br: edit(inline.br).replace('{2,}', '*').getRegex(),
text: edit(inline.gfm.text).replace('{2,}', '*').getRegex()
text: edit(inline.gfm.text).replace('{2,}', '*').replace('{2,}', '*').getRegex()
});

/**
Expand Down
3 changes: 1 addition & 2 deletions test/specs/gfm/gfm.0.28.json
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,7 @@
"section": "Autolinks",
"html": "<p><a href=\"mailto:[email protected]\">[email protected]</a></p>\n<p><a href=\"mailto:[email protected]\">[email protected]</a>.</p>\n<p>[email protected]</p>\n<p>[email protected]_</p>",
"markdown": "[email protected]\n\n[email protected].\n\n[email protected]\n\n[email protected]_",
"example": 607,
"shouldFail": true
"example": 607
},
{
"section": "Disallowed Raw HTML",
Expand Down

0 comments on commit 18dbc0b

Please sign in to comment.