Skip to content

Commit

Permalink
enh(parser) better regular expression detection (#2380)
Browse files Browse the repository at this point in the history
* enh(parser) better regular expression detection

- fewer false positives
- Uses a look-ahead to make sure we have a WHOLE regex and not
  just a partial (which is more likely a math expression)
  • Loading branch information
joshgoebel committed Feb 6, 2020
1 parent 98b9cec commit 11fcaea
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 11 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Expand Up @@ -10,6 +10,7 @@ New themes:

Core Changes:

- improve regular expression detect (less false-positives) (#2380) [Josh Goebel][]
- make `noHighlightRe` and `languagePrefixRe` configurable (#2374) [Josh Goebel][]

Language Improvements:
Expand Down
31 changes: 20 additions & 11 deletions src/highlight.js
Expand Up @@ -1102,17 +1102,26 @@ https://highlightjs.org/
relevance: 0
};
hljs.REGEXP_MODE = {
className: 'regexp',
begin: /\//, end: /\/[gimuy]*/,
illegal: /\n/,
contains: [
hljs.BACKSLASH_ESCAPE,
{
begin: /\[/, end: /\]/,
relevance: 0,
contains: [hljs.BACKSLASH_ESCAPE]
}
]
// this outer rule makes sure we actually have a WHOLE regex and not simply
// an expression such as:
//
// 3 / something
//
// (which will then blow up when regex's `illegal` sees the newline)
begin: /(?=\/[^\/\n]*\/)/,
contains: [{
className: 'regexp',
begin: /\//, end: /\/[gimuy]*/,
illegal: /\n/,
contains: [
hljs.BACKSLASH_ESCAPE,
{
begin: /\[/, end: /\]/,
relevance: 0,
contains: [hljs.BACKSLASH_ESCAPE]
}
]
}]
};
hljs.TITLE_MODE = {
className: 'title',
Expand Down
5 changes: 5 additions & 0 deletions test/markup/javascript/regex.expect.txt
@@ -0,0 +1,5 @@
<span class="hljs-comment">// examples that have proven problematic in the past</span>
<span class="hljs-string">`Bad <span class="hljs-subst">${foo / <span class="hljs-number">1000</span>}</span>`</span>
foo = <span class="hljs-number">2</span> / <span class="hljs-number">2</span> + <span class="hljs-number">2</span> / <span class="hljs-number">2</span>;
foo = <span class="hljs-regexp">/ 2 + 2 /</span>;
b = a++ / <span class="hljs-number">2</span>;
5 changes: 5 additions & 0 deletions test/markup/javascript/regex.txt
@@ -0,0 +1,5 @@
// examples that have proven problematic in the past
`Bad ${foo / 1000}`
foo = 2 / 2 + 2 / 2;
foo = / 2 + 2 /;
b = a++ / 2;

0 comments on commit 11fcaea

Please sign in to comment.