
Untitled
By: a guest on
May 8th, 2012 | syntax:
None | size: 2.73 KB | hits: 10 | expires: Never
<!DOCTYPE html>
<title>small syntax highlighting</title>
<style>
/* syntax highlighting styles, shameless ripoff off github ;-) */
body{font-family:sans-serif;}
pre{color:#333;font-size:120%;background:#fff;width:100%;overflow-x:auto;padding:5px;}
/* regexp */
.f-1, .f-1 * {color:#092;}
/* string */
.f1,.f1 * {color:#d14;}
/* comment */
.f2,.f2 * {color:#999;font-style:italic;}
/* keyword */
.f3,.f3 * {color:#000;font-weight: 700;}
/* predefined object */
.f4,.f4 * {color:#08B;}
/* number */
.f5,.f5 * {color:#099;}
/* bracket, operator */
.f6 {color:#000;}
</style>
<div>
<h2>Code with syntax highlighting:</h2>
<pre id="ret">/* index.js */
function(c,r){return c.replace(r,function(f,i){for(i=7;~i*!arguments[i--];);return i?'<t class=f'+i+'>'+f.replace('<','<')+'</t>':''})}
/* annotated.js */
function(
c, // code
r // regexp
){
return c.replace(r,
// use a replace callback
function(
f, // full match
i // counter
){
for(
// initialize counter (with count of regexp arguments)
i=6;
// only continue until i is other than -1 (~i becomes 0)
// and arguments[i] is not present (!'' becomes true coerces to 1),
// decrease counter
~i * !arguments[i--]
// found something?
return f ?
// encapsulate it with a t-tag adding the corresponding class name
'<t class=f' + i + '>' +
// replace "<" so it will not be interpreted as a tag
f.replace('<','<') +
'</t>' :
// otherwise return empty string
'';
})
}
</pre>
</div>
<script>
// RegExp to detect regexp, strings, comments, keywords, predefined object, numbers and operators
var re = /(?![\d\w]\s*)(\/[^\/\*][^\n\/]*\/[gi])|(".*?"|'.*?')|(\/\/.*?\n|\/\*[\x00-\xff\u00\uffff]*?\*\/)|(?:\b)(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|void|volatile|while|with)(?:\b)|(?:\b)(Array|Boolean|Date|Function|Math|Number|Object|RegExp|String|document|window|arguments)(?:\b)|(\d[\d\.eE]*)|([\x28-\x2b\x2d\x3a-\x3f\x5b\x5d\x5e\x7b-\x7e]+|\x2f|(?=\D)\.(?=\D))/g;
// syntax highlighting filter
var myFunction = function(c,r){return c.replace(r,function(f,i){for(i=7;~i*!arguments[i--];);return i?'<t class=f'+i+'>'+f.replace('<','<')+'</t>':''})}
// test it on the textual contents of the pre tag with the id "ret"
var ret = document.getElementById( "ret" );
ret.innerHTML = myFunction(ret.firstChild.data.replace(/&/g,'&'),re);
</script>