Improvement to greedy-flag This patch expands the idea of the greedy flag and significantly improves it, by matching against the whole text instead of just the next couple of tokens. This does not only improve the results, but it should also slightly improve performance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
diff --git a/components/prism-core.js b/components/prism-core.js
index b7087ca..aee751b 100644
--- a/components/prism-core.js
+++ b/components/prism-core.js
@@ -280,9 +280,15 @@ var _ = _self.Prism = {
lookbehindLength = 0,
alias = pattern.alias;
+ if (greedy && !pattern.pattern.global) {
+ // Without the global flag, lastIndex won't work
+ pattern.pattern = RegExp(pattern.pattern.source, pattern.pattern.flags + "g");
+ }
+
pattern = pattern.pattern || pattern;
- for (var i=0; i<strarr.length; i++) { // Don’t cache length as it changes during the loop
+ // Don’t cache length as it changes during the loop
+ for (var i=0, pos = 0; i<strarr.length; pos += (strarr[i].matchedStr || strarr[i]).length, ++i) {
var str = strarr[i];
@@ -302,40 +308,38 @@ var _ = _self.Prism = {
// Greedy patterns can override/remove up to two previously matched tokens
if (!match && greedy && i != strarr.length - 1) {
- // Reconstruct the original text using the next two tokens
- var nextToken = strarr[i + 1].matchedStr || strarr[i + 1],
- combStr = str + nextToken;
-
- if (i < strarr.length - 2) {
- combStr += strarr[i + 2].matchedStr || strarr[i + 2];
+ pattern.lastIndex = pos;
+ match = pattern.exec(text);
+ if (!match) {
+ break;
}
- // Try the pattern again on the reconstructed text
- pattern.lastIndex = 0;
- match = pattern.exec(combStr);
- if (!match) {
- continue;
+ var from = match.index + (lookbehind ? match[1].length : 0),
+ to = match.index + match[0].length,
+ k = i,
+ p = pos;
+
+ for (var len = strarr.length; k < len && p < to; ++k) {
+ p += (strarr[k].matchedStr || strarr[k]).length;
+ // Move the index i to the element in strarr that is closest to from
+ if (from >= p) {
+ ++i;
+ pos = p;
+ }
}
- var from = match.index + (lookbehind ? match[1].length : 0);
- // To be a valid candidate, the new match has to start inside of str
- if (from >= str.length) {
+ /*
+ * If strarr[i] is a Token, then the match starts inside another Token, which is invalid
+ * If strarr[k - 1] is greedy we are in conflict with another greedy pattern
+ */
+ if (strarr[i] instanceof Token || strarr[k - 1].greedy) {
continue;
}
- var to = match.index + match[0].length,
- len = str.length + nextToken.length;
// Number of tokens to delete and replace with the new match
- delNum = 3;
-
- if (to <= len) {
- if (strarr[i + 1].greedy) {
- continue;
- }
- delNum = 2;
- combStr = combStr.slice(0, len);
- }
- str = combStr;
+ delNum = k - i;
+ str = text.slice(pos, p);
+ match.index -= pos;
}
if (!match) {
diff --git a/components/prism-core.min.js b/components/prism-core.min.js
index d804000..625a184 100644
--- a/components/prism-core.min.js
+++ b/components/prism-core.min.js
@@ -1 +1 @@
-var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(){var e=/\blang(?:uage)?-(\w+)\b/i,t=0,n=_self.Prism={util:{encode:function(e){return e instanceof a?new a(e.type,n.util.encode(e.content),e.alias):"Array"===n.util.type(e)?e.map(n.util.encode):e.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},objId:function(e){return e.__id||Object.defineProperty(e,"__id",{value:++t}),e.__id},clone:function(e){var t=n.util.type(e);switch(t){case"Object":var a={};for(var r in e)e.hasOwnProperty(r)&&(a[r]=n.util.clone(e[r]));return a;case"Array":return e.map&&e.map(function(e){return n.util.clone(e)})}return e}},languages:{extend:function(e,t){var a=n.util.clone(n.languages[e]);for(var r in t)a[r]=t[r];return a},insertBefore:function(e,t,a,r){r=r||n.languages;var l=r[e];if(2==arguments.length){a=arguments[1];for(var i in a)a.hasOwnProperty(i)&&(l[i]=a[i]);return l}var o={};for(var s in l)if(l.hasOwnProperty(s)){if(s==t)for(var i in a)a.hasOwnProperty(i)&&(o[i]=a[i]);o[s]=l[s]}return n.languages.DFS(n.languages,function(t,n){n===r[e]&&t!=e&&(this[t]=o)}),r[e]=o},DFS:function(e,t,a,r){r=r||{};for(var l in e)e.hasOwnProperty(l)&&(t.call(e,l,e[l],a||l),"Object"!==n.util.type(e[l])||r[n.util.objId(e[l])]?"Array"!==n.util.type(e[l])||r[n.util.objId(e[l])]||(r[n.util.objId(e[l])]=!0,n.languages.DFS(e[l],t,l,r)):(r[n.util.objId(e[l])]=!0,n.languages.DFS(e[l],t,null,r)))}},plugins:{},highlightAll:function(e,t){var a={callback:t,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};n.hooks.run("before-highlightall",a);for(var r,l=a.elements||document.querySelectorAll(a.selector),i=0;r=l[i++];)n.highlightElement(r,e===!0,a.callback)},highlightElement:function(t,a,r){for(var l,i,o=t;o&&!e.test(o.className);)o=o.parentNode;o&&(l=(o.className.match(e)||[,""])[1].toLowerCase(),i=n.languages[l]),t.className=t.className.replace(e,"").replace(/\s+/g," ")+" language-"+l,o=t.parentNode,/pre/i.test(o.nodeName)&&(o.className=o.className.replace(e,"").replace(/\s+/g," ")+" language-"+l);var s=t.textContent,u={element:t,language:l,grammar:i,code:s};if(n.hooks.run("before-sanity-check",u),!u.code||!u.grammar)return n.hooks.run("complete",u),void 0;if(n.hooks.run("before-highlight",u),a&&_self.Worker){var c=new Worker(n.filename);c.onmessage=function(e){u.highlightedCode=e.data,n.hooks.run("before-insert",u),u.element.innerHTML=u.highlightedCode,r&&r.call(u.element),n.hooks.run("after-highlight",u),n.hooks.run("complete",u)},c.postMessage(JSON.stringify({language:u.language,code:u.code,immediateClose:!0}))}else u.highlightedCode=n.highlight(u.code,u.grammar,u.language),n.hooks.run("before-insert",u),u.element.innerHTML=u.highlightedCode,r&&r.call(t),n.hooks.run("after-highlight",u),n.hooks.run("complete",u)},highlight:function(e,t,r){var l=n.tokenize(e,t);return a.stringify(n.util.encode(l),r)},tokenize:function(e,t){var a=n.Token,r=[e],l=t.rest;if(l){for(var i in l)t[i]=l[i];delete t.rest}e:for(var i in t)if(t.hasOwnProperty(i)&&t[i]){var o=t[i];o="Array"===n.util.type(o)?o:[o];for(var s=0;s<o.length;++s){var u=o[s],c=u.inside,g=!!u.lookbehind,h=!!u.greedy,f=0,d=u.alias;u=u.pattern||u;for(var p=0;p<r.length;p++){var m=r[p];if(r.length>e.length)break e;if(!(m instanceof a)){u.lastIndex=0;var y=u.exec(m),v=1;if(!y&&h&&p!=r.length-1){var b=r[p+1].matchedStr||r[p+1],k=m+b;if(p<r.length-2&&(k+=r[p+2].matchedStr||r[p+2]),u.lastIndex=0,y=u.exec(k),!y)continue;var w=y.index+(g?y[1].length:0);if(w>=m.length)continue;var _=y.index+y[0].length,P=m.length+b.length;if(v=3,P>=_){if(r[p+1].greedy)continue;v=2,k=k.slice(0,P)}m=k}if(y){g&&(f=y[1].length);var w=y.index+f,y=y[0].slice(f),_=w+y.length,S=m.slice(0,w),A=m.slice(_),O=[p,v];S&&O.push(S);var j=new a(i,c?n.tokenize(y,c):y,d,y,h);O.push(j),A&&O.push(A),Array.prototype.splice.apply(r,O)}}}}}return r},hooks:{all:{},add:function(e,t){var a=n.hooks.all;a[e]=a[e]||[],a[e].push(t)},run:function(e,t){var a=n.hooks.all[e];if(a&&a.length)for(var r,l=0;r=a[l++];)r(t)}}},a=n.Token=function(e,t,n,a,r){this.type=e,this.content=t,this.alias=n,this.matchedStr=a||null,this.greedy=!!r};if(a.stringify=function(e,t,r){if("string"==typeof e)return e;if("Array"===n.util.type(e))return e.map(function(n){return a.stringify(n,t,e)}).join("");var l={type:e.type,content:a.stringify(e.content,t,r),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:r};if("comment"==l.type&&(l.attributes.spellcheck="true"),e.alias){var i="Array"===n.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(l.classes,i)}n.hooks.run("wrap",l);var o="";for(var s in l.attributes)o+=(o?" ":"")+s+'="'+(l.attributes[s]||"")+'"';return"<"+l.tag+' class="'+l.classes.join(" ")+'" '+o+">"+l.content+"</"+l.tag+">"},!_self.document)return _self.addEventListener?(_self.addEventListener("message",function(e){var t=JSON.parse(e.data),a=t.language,r=t.code,l=t.immediateClose;_self.postMessage(n.highlight(r,n.languages[a],a)),l&&_self.close()},!1),_self.Prism):_self.Prism;var r=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return r&&(n.filename=r.src,document.addEventListener&&!r.hasAttribute("data-manual")&&("loading"!==document.readyState?requestAnimationFrame(n.highlightAll,0):document.addEventListener("DOMContentLoaded",n.highlightAll))),_self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism);
\ No newline at end of file
+var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(){var e=/\blang(?:uage)?-(\w+)\b/i,t=0,n=_self.Prism={util:{encode:function(e){return e instanceof a?new a(e.type,n.util.encode(e.content),e.alias):"Array"===n.util.type(e)?e.map(n.util.encode):e.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},objId:function(e){return e.__id||Object.defineProperty(e,"__id",{value:++t}),e.__id},clone:function(e){var t=n.util.type(e);switch(t){case"Object":var a={};for(var r in e)e.hasOwnProperty(r)&&(a[r]=n.util.clone(e[r]));return a;case"Array":return e.map&&e.map(function(e){return n.util.clone(e)})}return e}},languages:{extend:function(e,t){var a=n.util.clone(n.languages[e]);for(var r in t)a[r]=t[r];return a},insertBefore:function(e,t,a,r){r=r||n.languages;var l=r[e];if(2==arguments.length){a=arguments[1];for(var i in a)a.hasOwnProperty(i)&&(l[i]=a[i]);return l}var o={};for(var s in l)if(l.hasOwnProperty(s)){if(s==t)for(var i in a)a.hasOwnProperty(i)&&(o[i]=a[i]);o[s]=l[s]}return n.languages.DFS(n.languages,function(t,n){n===r[e]&&t!=e&&(this[t]=o)}),r[e]=o},DFS:function(e,t,a,r){r=r||{};for(var l in e)e.hasOwnProperty(l)&&(t.call(e,l,e[l],a||l),"Object"!==n.util.type(e[l])||r[n.util.objId(e[l])]?"Array"!==n.util.type(e[l])||r[n.util.objId(e[l])]||(r[n.util.objId(e[l])]=!0,n.languages.DFS(e[l],t,l,r)):(r[n.util.objId(e[l])]=!0,n.languages.DFS(e[l],t,null,r)))}},plugins:{},highlightAll:function(e,t){var a={callback:t,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};n.hooks.run("before-highlightall",a);for(var r,l=a.elements||document.querySelectorAll(a.selector),i=0;r=l[i++];)n.highlightElement(r,e===!0,a.callback)},highlightElement:function(t,a,r){for(var l,i,o=t;o&&!e.test(o.className);)o=o.parentNode;o&&(l=(o.className.match(e)||[,""])[1].toLowerCase(),i=n.languages[l]),t.className=t.className.replace(e,"").replace(/\s+/g," ")+" language-"+l,o=t.parentNode,/pre/i.test(o.nodeName)&&(o.className=o.className.replace(e,"").replace(/\s+/g," ")+" language-"+l);var s=t.textContent,u={element:t,language:l,grammar:i,code:s};if(n.hooks.run("before-sanity-check",u),!u.code||!u.grammar)return n.hooks.run("complete",u),void 0;if(n.hooks.run("before-highlight",u),a&&_self.Worker){var c=new Worker(n.filename);c.onmessage=function(e){u.highlightedCode=e.data,n.hooks.run("before-insert",u),u.element.innerHTML=u.highlightedCode,r&&r.call(u.element),n.hooks.run("after-highlight",u),n.hooks.run("complete",u)},c.postMessage(JSON.stringify({language:u.language,code:u.code,immediateClose:!0}))}else u.highlightedCode=n.highlight(u.code,u.grammar,u.language),n.hooks.run("before-insert",u),u.element.innerHTML=u.highlightedCode,r&&r.call(t),n.hooks.run("after-highlight",u),n.hooks.run("complete",u)},highlight:function(e,t,r){var l=n.tokenize(e,t);return a.stringify(n.util.encode(l),r)},tokenize:function(e,t){var a=n.Token,r=[e],l=t.rest;if(l){for(var i in l)t[i]=l[i];delete t.rest}e:for(var i in t)if(t.hasOwnProperty(i)&&t[i]){var o=t[i];o="Array"===n.util.type(o)?o:[o];for(var s=0;s<o.length;++s){var u=o[s],c=u.inside,g=!!u.lookbehind,h=!!u.greedy,f=0,d=u.alias;h&&!u.pattern.global&&(u.pattern=RegExp(u.pattern.source,u.pattern.flags+"g")),u=u.pattern||u;for(var p=0,m=0;p<r.length;m+=(r[p].matchedStr||r[p]).length,++p){var y=r[p];if(r.length>e.length)break e;if(!(y instanceof a)){u.lastIndex=0;var v=u.exec(y),b=1;if(!v&&h&&p!=r.length-1){if(u.lastIndex=m,v=u.exec(e),!v)break;for(var k=v.index+(g?v[1].length:0),w=v.index+v[0].length,_=p,P=m,S=r.length;S>_&&w>P;++_)P+=(r[_].matchedStr||r[_]).length,k>=P&&(++p,m=P);if(r[p]instanceof a||r[_-1].greedy)continue;b=_-p,y=e.slice(m,P),v.index-=m}if(v){g&&(f=v[1].length);var k=v.index+f,v=v[0].slice(f),w=k+v.length,A=y.slice(0,k),x=y.slice(w),O=[p,b];A&&O.push(A);var j=new a(i,c?n.tokenize(v,c):v,d,v,h);O.push(j),x&&O.push(x),Array.prototype.splice.apply(r,O)}}}}}return r},hooks:{all:{},add:function(e,t){var a=n.hooks.all;a[e]=a[e]||[],a[e].push(t)},run:function(e,t){var a=n.hooks.all[e];if(a&&a.length)for(var r,l=0;r=a[l++];)r(t)}}},a=n.Token=function(e,t,n,a,r){this.type=e,this.content=t,this.alias=n,this.matchedStr=a||null,this.greedy=!!r};if(a.stringify=function(e,t,r){if("string"==typeof e)return e;if("Array"===n.util.type(e))return e.map(function(n){return a.stringify(n,t,e)}).join("");var l={type:e.type,content:a.stringify(e.content,t,r),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:r};if("comment"==l.type&&(l.attributes.spellcheck="true"),e.alias){var i="Array"===n.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(l.classes,i)}n.hooks.run("wrap",l);var o="";for(var s in l.attributes)o+=(o?" ":"")+s+'="'+(l.attributes[s]||"")+'"';return"<"+l.tag+' class="'+l.classes.join(" ")+'" '+o+">"+l.content+"</"+l.tag+">"},!_self.document)return _self.addEventListener?(_self.addEventListener("message",function(e){var t=JSON.parse(e.data),a=t.language,r=t.code,l=t.immediateClose;_self.postMessage(n.highlight(r,n.languages[a],a)),l&&_self.close()},!1),_self.Prism):_self.Prism;var r=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return r&&(n.filename=r.src,document.addEventListener&&!r.hasAttribute("data-manual")&&("loading"!==document.readyState?requestAnimationFrame(n.highlightAll,0):document.addEventListener("DOMContentLoaded",n.highlightAll))),_self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism);
\ No newline at end of file
diff --git a/prism.js b/prism.js
index 8eb46c7..3a3c7f7 100644
--- a/prism.js
+++ b/prism.js
@@ -285,9 +285,15 @@ var _ = _self.Prism = {
lookbehindLength = 0,
alias = pattern.alias;
+ if (greedy && !pattern.pattern.global) {
+ // Without the global flag, lastIndex won't work
+ pattern.pattern = RegExp(pattern.pattern.source, pattern.pattern.flags + "g");
+ }
+
pattern = pattern.pattern || pattern;
- for (var i=0; i<strarr.length; i++) { // Don’t cache length as it changes during the loop
+ // Don’t cache length as it changes during the loop
+ for (var i=0, pos = 0; i<strarr.length; pos += (strarr[i].matchedStr || strarr[i]).length, ++i) {
var str = strarr[i];
@@ -307,40 +313,38 @@ var _ = _self.Prism = {
// Greedy patterns can override/remove up to two previously matched tokens
if (!match && greedy && i != strarr.length - 1) {
- // Reconstruct the original text using the next two tokens
- var nextToken = strarr[i + 1].matchedStr || strarr[i + 1],
- combStr = str + nextToken;
-
- if (i < strarr.length - 2) {
- combStr += strarr[i + 2].matchedStr || strarr[i + 2];
+ pattern.lastIndex = pos;
+ match = pattern.exec(text);
+ if (!match) {
+ break;
}
- // Try the pattern again on the reconstructed text
- pattern.lastIndex = 0;
- match = pattern.exec(combStr);
- if (!match) {
- continue;
+ var from = match.index + (lookbehind ? match[1].length : 0),
+ to = match.index + match[0].length,
+ k = i,
+ p = pos;
+
+ for (var len = strarr.length; k < len && p < to; ++k) {
+ p += (strarr[k].matchedStr || strarr[k]).length;
+ // Move the index i to the element in strarr that is closest to from
+ if (from >= p) {
+ ++i;
+ pos = p;
+ }
}
- var from = match.index + (lookbehind ? match[1].length : 0);
- // To be a valid candidate, the new match has to start inside of str
- if (from >= str.length) {
+ /*
+ * If strarr[i] is a Token, then the match starts inside another Token, which is invalid
+ * If strarr[k - 1] is greedy we are in conflict with another greedy pattern
+ */
+ if (strarr[i] instanceof Token || strarr[k - 1].greedy) {
continue;
}
- var to = match.index + match[0].length,
- len = str.length + nextToken.length;
// Number of tokens to delete and replace with the new match
- delNum = 3;
-
- if (to <= len) {
- if (strarr[i + 1].greedy) {
- continue;
- }
- delNum = 2;
- combStr = combStr.slice(0, len);
- }
- str = combStr;
+ delNum = k - i;
+ str = text.slice(pos, p);
+ match.index -= pos;
}
if (!match) {
diff --git a/tests/languages/javascript/regex_feature.test b/tests/languages/javascript/regex_feature.test
index 04d3742..c79397e 100644
--- a/tests/languages/javascript/regex_feature.test
+++ b/tests/languages/javascript/regex_feature.test
@@ -4,6 +4,7 @@
/foo"test"bar/
/foo\//
1 / 4 + "/, not a regex";
+/ '1' '2' '3' '4' '5' /
----------------------------------------------------
@@ -13,7 +14,8 @@
["regex", "/[\\[\\]]{2,4}(?:foo)*/"], ["punctuation", ";"],
["regex", "/foo\"test\"bar/"],
["regex", "/foo\\//"],
- ["number", "1"], ["operator", "/"], ["number", "4"], ["operator", "+"], ["string", "\"/, not a regex\""], ["punctuation", ";"]
+ ["number", "1"], ["operator", "/"], ["number", "4"], ["operator", "+"], ["string", "\"/, not a regex\""], ["punctuation", ";"],
+ ["regex", "/ '1' '2' '3' '4' '5' /"]
]
----------------------------------------------------
diff --git a/tests/languages/javascript/template-string_feature.test b/tests/languages/javascript/template-string_feature.test
index 753374e..33de8b3 100644
--- a/tests/languages/javascript/template-string_feature.test
+++ b/tests/languages/javascript/template-string_feature.test
@@ -3,6 +3,7 @@
bar`
`40+2=${40+2}`
`${foo()}`
+"foo `a` `b` `c` `d` bar"
----------------------------------------------------
@@ -34,7 +35,8 @@ bar`
["interpolation-punctuation", "}"]
]],
["string", "`"]
- ]]
+ ]],
+ ["string", "\"foo `a` `b` `c` `d` bar\""]
]
----------------------------------------------------