Pure JavaScript syntax highlighter

Syntax Highlighter

Syntax Highlighting is a technique to make your code on web-pages look beautiful and to highlight syntax of any programming language code you will have to install syntax highlighter plugin on your website.

There are different syntax highlighter available like prism.js and highlighter.js and today in this article we will see pure JavaScript Syntax highlighter that can do the job of Syntax highlighting plugins.

Basically this is also a kind of syntax highlighter plugin that enables you to highlight the syntax of different programming languages.

Although it does not support many languages but the most commonly used programming languages that are supported by this syntax highlighter are CSS, JavaScript, HTML etc.

This is very lightweight syntax highlighter you can also make a separate JavaScript file and host it anywhere you want. You can host files on github for free.

I have created many other blogs where I have used this syntax highlighter. It is very lightweight and it has light color scheme that is good for the website which have light color schemes.

Languages Supported:

  • C
  • JAVA
  • Javascript
  • Python
  • HTML
  • C#
  • PHP
  • CSS

Now let's see how you can add it in blogger blog.

Steps To Follow

  1. Go to Blogger Dashboard
  2. Go to Theme/Template Section
  3. Click Edit HTML
  4. Now Search for </body>
  5. To search anything in blogger template section press Ctrl+F and then type term to search and press enter.
  6. Now copy the code provided below and paste it just above the tag which we have founded in step 4.
  7. <script>/*<![CDATA[*/window.Rainbow=function(){function e(e){var t,a=e.getAttribute&&e.getAttribute("data-language")||0;if(!a){for(e=e.attributes,t=0;t<e.length;++t)if("data-language"===e[t].nodeName)return e[t].nodeValue}return a}function t(e,t){return'<span class="'+e.replace(/\./g," ")+(s?" "+s:"")+'">'+t+"</span>"}function a(e){var t,a=[];for(t in e)e.hasOwnProperty(t)&&a.push(t);return a.sort(function(e,t){return t-e})}function n(e,r,s){var o=c[r]||[],f=c[l]||[];r=m[r]?o:o.concat(f),function e(r,s,o){++g,function s(c,m){var l,f;m<c.length?function r(s,o,c,m){if(null==s)m();else{var l=s.exec(c);if(l){++u,o.name||"string"!=typeof o.matches[0]||(o.name=o.matches[0],delete o.matches[0]);var d=l[0],f=l.index,h=l[0].length+f,b=function(){function e(){r(s,o,c,m)}0<u%100?e():setTimeout(e,0)};if(function e(t,a){for(var n in p[g])if((t==(n=parseInt(n,10))&&a==p[g][n]?0:t<=n&&a>=p[g][n])&&(delete p[g][n],delete i[g][n]),t>=n&&t<p[g][n]||a>n&&a<p[g][n])return!0;return!1}(f,h))b();else{var y=a(o.matches),w=function(a,r,s){if(a>=r.length)s(d);else{var i=l[r[a]];if(i){var p=o.matches[r[a]],c=p.language,m=p.name&&p.matches?p.matches:p,g=function(e,n,o){var i,p;for(p=1,i=0;p<r[a];++p)l[p]&&(i+=l[p].length);n=o?t(o,n):n,d=d.substr(0,i)+d.substr(i).replace(e,n),w(++a,r,s)};c?n(i,c,function(e){g(i,e)}):"string"==typeof p?g(i,i,p):e(i,m.length?m:[m],function(e){g(i,e,p.matches?p.name:0)})}else w(++a,r,s)}};w(0,y,function(e){o.name&&(e=t(o.name,e)),i[g]||(i[g]={},p[g]={}),i[g][f]={replace:l[0],with:e},p[g][f]=h,b()})}}else m()}}(c[m].pattern,c[m],r,function(){s(c,++m)}):(l=r,f=function(e){delete i[g],delete p[g],--g,o(e)},!function e(t,a,n,r){if(n<a.length){++d;var s=a[n],o=i[g][s];t=t.substr(0,s)+t.substr(s).replace(o.replace,o.with),s=function(){e(t,a,++n,r)},0<d%250?s():setTimeout(s,0)}else r(t)}(l,a(i[g]),0,f))}(s,0)}(e.replace(/</g,"<").replace(/>/g,">").replace(/&(?![\w\#]+;)/g,"&"),r,s)}function r(t,a){var r,s=(t=t&&"function"==typeof t.getElementsByTagName?t:document).getElementsByTagName("pre"),c=t.getElementsByTagName("code"),m=[],g=[];for(r=0;r<s.length;++r)s[r].getElementsByTagName("code").length?s[r].innerHTML=s[r].innerHTML.replace(/^\s+/,"").replace(/\s+$/,""):m.push(s[r]);for(r=0;r<c.length;++r)g.push(c[r]);!function t(a,r,s){if(r<a.length){var c=a[r],m=function t(a){var n=e(a)||e(a.parentNode);if(!n){var r=/\blang(?:uage)?-(\w+)/;(a=a.className.match(r)||a.parentNode.className.match(r))&&(n=a[1])}return n}(c);return -1<(" "+c.className+" ").indexOf(" rainbow ")||!m?t(a,++r,s):(m=m.toLowerCase(),c.className+=c.className?" rainbow":"rainbow",n(c.innerHTML,m,function(e){c.innerHTML=e,i={},p={},o&&o(c,m),setTimeout(function(){t(a,++r,s)},0)}))}s&&s()}(g.concat(m),0,a)}var s,o,i={},p={},c={},m={},g=0,l=0,u=0,d=0;return{extend:function(e,t,a){1==arguments.length&&(t=e,e=l),m[e]=a,c[e]=t.concat(c[e]||[])},c:function(e){o=e},a:function(e){s=e},color:function(e,t,a){return"string"==typeof e?n(e,t,a):"function"==typeof e?r(0,e):void r(e,t)}}}(),document.addEventListener?document.addEventListener("DOMContentLoaded",Rainbow.color,!1):window.attachEvent("onload",Rainbow.color),Rainbow.onHighlight=Rainbow.c,Rainbow.addClass=Rainbow.a,Rainbow.extend("c",[{name:"meta.preprocessor",matches:{1:[{matches:{1:"keyword.define",2:"entity.name"},pattern:/(\w+)\s(\w+)\b/g},{name:"keyword.define",pattern:/endif/g},{name:"constant.numeric",pattern:/\d+/g},{matches:{1:"keyword.include",2:"string"},pattern:/(include)\s(.*?)$/g}]},pattern:/\#([\S\s]*?)$/gm},{name:"keyword",pattern:/\b(do|goto|typedef)\b/g},{name:"entity.label",pattern:/\w+:/g},{matches:{1:"storage.type",3:"storage.type",4:"entity.name.function"},pattern:/\b((un)?signed|const)? ?(void|char|short|int|long|float|double)\*? +((\w+)(?= ?\())?/g},{matches:{2:"entity.name.function"},pattern:/(\w|\*) +((\w+)(?= ?\())/g},{name:"storage.modifier",pattern:/\b(static|extern|auto|register|volatile|inline)\b/g},{name:"support.type",pattern:/\b(struct|union|enum)\b/g}]),Rainbow.extend("java",[{name:"constant",pattern:/\b(false|null|true|[A-Z_]+)\b/g},{b:{1:"keyword",2:"support.namespace"},pattern:/(import|package)\s(.+)/g},{name:"keyword",pattern:/\b(abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|native|new|package|private|protected|public|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|void|volatile|while)\b/g},{name:"string",pattern:/(".*?")/g},{name:"char",pattern:/(')(.|\\.|\\u[\dA-Fa-f]{4})\1/g},{name:"integer",pattern:/\b(0x[\da-f]+|\d+)L?\b/g},{name:"comment",pattern:/\/\*[\s\S]*?\*\/|(\/\/).*?$/gm},{name:"support.annotation",pattern:/@\w+/g},{b:{1:"entity.function"},pattern:/([^@\.\s]+)\(/g},{name:"entity.class",pattern:/\b([A-Z]\w*)\b/g},{name:"operator",pattern:/(\+{1,2}|-{1,2}|~|!|\*|\/|%|(?:<){1,2}|(?:>){1,3}|instanceof|(?:&){1,2}|\^|\|{1,2}|\?|:|(?:=|!|\+|-|\*|\/|%|\^|\||(?:<){1,2}|(?:>){1,3})?=)/g}],!0),Rainbow.extend([{matches:{1:[{name:"keyword.operator",pattern:/\=|\+/g},{name:"keyword.dot",pattern:/\./g}],2:{name:"string",matches:{name:"constant.character.escape",pattern:/\\('|"){1}/g}}},pattern:/(\(|\s|\[|\=|:|\+|\.)(('|")([^\\\1]|\\.)*?(\3))/gm},{name:"comment",pattern:/\/\*[\s\S]*?\*\/|(\/\/|\#)[\s\S]*?$/gm},{name:"constant.numeric",pattern:/\b(\d+(\.\d+)?(e(\+|\-)?\d+)?(f|d)?|0x[\da-f]+)\b/gi},{matches:{1:"keyword"},pattern:/\b(and|array|as|b(ool(ean)?|reak)|c(ase|atch|har|lass|on(st|tinue))|d(ef|elete|o(uble)?)|e(cho|lse(if)?|xit|xtends|xcept)|f(inally|loat|or(each)?|unction)|global|if|import|int(eger)?|long|new|object|or|pr(int|ivate|otected)|public|return|self|st(ring|ruct|atic)|switch|th(en|is|row)|try|(un)?signed|var|void|while)(?=\(|\b)/gi},{name:"constant.language",pattern:/true|false|null/g},{name:"keyword.operator",pattern:/\+|\!|\-|&(gt|lt|amp);|\||\*|\=/g},{matches:{1:"function.call"},pattern:/(\w+?)(?=\()/g},{matches:{1:"storage.function",2:"entity.name.function"},pattern:/(function)\s(.*?)(?=\()/g}]),Rainbow.extend("javascript",[{name:"selector",pattern:/(\s|^)\$(?=\.|\()/g},{name:"support",pattern:/\b(window|document)\b/g},{matches:{1:"support.property"},pattern:/\.(length|node(Name|Value))\b/g},{matches:{1:"support.function"},pattern:/(setTimeout|setInterval)(?=\()/g},{matches:{1:"support.method"},pattern:/\.(getAttribute|push|getElementById|getElementsByClassName|log|setTimeout|setInterval)(?=\()/g},{name:"string.regexp",matches:{1:"string.regexp.open",2:{name:"constant.regexp.escape",pattern:/\\(.){1}/g},3:"string.regexp.close",4:"string.regexp.modifier"},pattern:/(\/)(?!\*)(.+)(\/)([igm]{0,3})/g},{matches:{1:"storage",3:"entity.function"},pattern:/(var)?(\s|^)(\S*)(?=\s?=\s?function\()/g},{matches:{1:"keyword",2:"entity.function"},pattern:/(new)\s+(.*)(?=\()/g},{name:"entity.function",pattern:/(\w+)(?=:\s{0,}function)/g}]),Rainbow.extend("python",[{name:"variable.self",pattern:/self/g},{name:"constant.language",pattern:/None|True|False|NotImplemented|\.\.\./g},{name:"support.object",pattern:/object/g},{name:"support.function.python",pattern:/\b(bs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|bin|file|iter|property|tuple|bool|filter|len|range|type|bytearray|float|list|raw_input|unichr|callable|format|locals|reduce|unicode|chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|__import__|complex|hash|min|set|apply|delattr|help|next|setattr|buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern)(?=\()/g},{matches:{1:"keyword"},pattern:/\b(pass|lambda|with|is|not|in|from|elif|raise|del)(?=\(|\b)/g},{matches:{1:"storage.class",2:"entity.name.class",3:"entity.other.inherited-class"},pattern:/(class)\s+(\w+)\((\w+?)\)/g},{matches:{1:"storage.function",2:"support.magic"},pattern:/(def)\s+(__\w+)(?=\()/g},{name:"support.magic",pattern:/__(name)__/g},{matches:{1:"keyword.control",2:"support.exception.type"},pattern:/(except) (\w+):/g},{matches:{1:"storage.function",2:"entity.name.function"},pattern:/(def)\s+(\w+)(?=\()/g},{name:"entity.name.function.decorator",pattern:/@([\w\.]+)/g},{name:"comment.docstring",pattern:/('{3}|"{3})[\s\S]*?\1/gm}]),Rainbow.extend("html",[{name:"source.php.embedded",matches:{2:{language:"php"}},pattern:/<\?=?(?!xml)(php)?([\s\S]*?)(\?>)/gm},{name:"source.css.embedded",matches:{1:{matches:{1:"support.tag.style",2:[{name:"entity.tag.style",pattern:/^style/g},{name:"string",pattern:/('|")(.*?)(\1)/g},{name:"entity.tag.style.attribute",pattern:/(\w+)/g}],3:"support.tag.style"},pattern:/(<\/?)(style.*?)(>)/g},2:{language:"css"},3:"support.tag.style",4:"entity.tag.style",5:"support.tag.style"},pattern:/(<style.*?>)([\s\S]*?)(<\/)(style)(>)/gm},{name:"source.js.embedded",matches:{1:{matches:{1:"support.tag.script",2:[{name:"entity.tag.script",pattern:/^script/g},{name:"string",pattern:/('|")(.*?)(\1)/g},{name:"entity.tag.script.attribute",pattern:/(\w+)/g}],3:"support.tag.script"},pattern:/(<\/?)(script.*?)(>)/g},2:{language:"javascript"},3:"support.tag.script",4:"entity.tag.script",5:"support.tag.script"},pattern:/(<script(?! src).*?>)([\s\S]*?)(<\/)(script)(>)/gm},{name:"comment.html",pattern:/<\!--[\S\s]*?-->/g},{matches:{1:"support.tag.open",2:"support.tag.close"},pattern:/(<)|(\/?\??>)/g},{name:"support.tag",matches:{1:"support.tag",2:"support.tag.special",3:"support.tag-name"},pattern:/(<\??)(\/|\!?)(\w+)/g},{matches:{1:"support.attribute"},pattern:/([a-z-]+)(?=\=)/gi},{matches:{1:"support.operator",2:"string.quote",3:"string.value",4:"string.quote"},pattern:/(=)('|")(.*?)(\2)/g},{matches:{1:"support.operator",2:"support.value"},pattern:/(=)([a-zA-Z\-0-9]*)\b/g},{matches:{1:"support.attribute"},pattern:/\s(\w+)(?=\s|>)(?![\s\S]*<)/g}],!0),Rainbow.extend("csharp",[{name:"constant",pattern:/\b(false|null|true)\b/g},{name:"keyword",pattern:/\b(abstract|add|alias|ascending|as|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|descending|double|do|dynamic|else|enum|event|explicit|extern|false|finally|fixed|float|foreach|for|from|get|global|goto|group|if|implicit|int|interface|internal|into|in|is|join|let|lock|long|namespace|new|object|operator|orderby|out|override|params|partial|private|protected|public|readonly|ref|remove|return|sbyte|sealed|select|set|short|sizeof|stackalloc|static|string|struct|switch|this|throw|try|typeof|uint|unchecked|ulong|unsafe|ushort|using|value|var|virtual|void|volatile|where|while|yield)\b/g},{matches:{1:"keyword",2:{name:"support.class",pattern:/\w+/g}},pattern:/(typeof)\s([^\$].*?)(\)|;)/g},{matches:{1:"keyword.namespace",2:{name:"support.namespace",pattern:/\w+/g}},pattern:/\b(namespace)\s(.*?);/g},{matches:{1:"storage.modifier",2:"storage.class",3:"entity.name.class",4:"storage.modifier.extends",5:"entity.other.inherited-class"},pattern:/\b(abstract|sealed)?\s?(class)\s(\w+)(\sextends\s)?([\w\\]*)?\s?\{?(\n|\})/g},{name:"keyword.static",pattern:/\b(static)\b/g},{matches:{1:"keyword.new",2:{name:"support.class",pattern:/\w+/g}},pattern:/\b(new)\s([^\$].*?)(?=\)|\(|;|&)/g},{name:"string",pattern:/(")(.*?)\1/g},{name:"integer",pattern:/\b(0x[\da-f]+|\d+)\b/g},{name:"comment",pattern:/\/\*[\s\S]*?\*\/|(\/\/)[\s\S]*?$/gm},{name:"operator",pattern:/(\+\+|\+=|\+|--|-=|-|<<=|<<|<=|=>|>>=|>>|>=|!=|!|~|\^|\|\||&&|&=|&|\?\?|::|:|\*=|\*|\/=|%=|\|=|==|=)/g},{name:"preprocessor",pattern:/(\#if|\#else|\#elif|\#endif|\#define|\#undef|\#warning|\#error|\#line|\#region|\#endregion|\#pragma)[\s\S]*?$/gm}],!0),Rainbow.extend("php",[{name:"support",pattern:/\becho\b/g},{matches:{1:"variable.dollar-sign",2:"variable"},pattern:/(\$)(\w+)\b/g},{name:"constant.language",pattern:/true|false|null/ig},{name:"constant",pattern:/\b[A-Z0-9_]{2,}\b/g},{name:"keyword.dot",pattern:/\./g},{name:"keyword",pattern:/\b(die|end(for(each)?|switch|if)|case|require(_once)?|include(_once)?)(?=\(|\b)/g},{matches:{1:"keyword",2:{name:"support.class",pattern:/\w+/g}},pattern:/(instanceof)\s([^\$].*?)(\)|;)/g},{matches:{1:"support.function"},pattern:/\b(array(_key_exists|_merge|_keys|_shift)?|isset|count|empty|unset|printf|is_(array|string|numeric|object)|sprintf|each|date|time|substr|pos|str(len|pos|tolower|_replace|totime)?|ord|trim|in_array|implode|end|preg_match|explode|fmod|define|link|list|get_class|serialize|file|sort|mail|dir|idate|log|intval|header|chr|function_exists|dirname|preg_replace|file_exists)(?=\()/g},{name:"variable.language.php-tag",pattern:/(<\?(php)?|\?>)/g},{matches:{1:"keyword.namespace",2:{name:"support.namespace",pattern:/\w+/g}},pattern:/\b(namespace|use)\s(.*?);/g},{matches:{1:"storage.modifier",2:"storage.class",3:"entity.name.class",4:"storage.modifier.extends",5:"entity.other.inherited-class",6:"storage.modifier.extends",7:"entity.other.inherited-class"},pattern:/\b(abstract|final)?\s?(class|interface|trait)\s(\w+)(\sextends\s)?([\w\\]*)?(\simplements\s)?([\w\\]*)?\s?\{?(\n|\})/g},{name:"keyword.static",pattern:/self::|static::/g},{matches:{1:"storage.function",2:"support.magic"},pattern:/(function)\s(__.*?)(?=\()/g},{matches:{1:"keyword.new",2:{name:"support.class",pattern:/\w+/g}},pattern:/\b(new)\s([^\$].*?)(?=\)|\(|;)/g},{matches:{1:{name:"support.class",pattern:/\w+/g},2:"keyword.static"},pattern:/([\w\\]*?)(::)(?=\b|\$)/g},{matches:{2:{name:"support.class",pattern:/\w+/g}},pattern:/(\(|,\s?)([\w\\]*?)(?=\s\$)/g}]),Rainbow.extend("css",[{name:"comment",pattern:/\/\*[\s\S]*?\*\//gm},{name:"constant.hex-color",pattern:/#([a-f0-9]{3}|[a-f0-9]{6})(?=;|\s|,|\))/gi},{matches:{1:"constant.numeric",2:"keyword.unit"},pattern:/(\d+)(px|em|cm|s|%)?/g},{name:"string",pattern:/('|")(.*?)\1/g},{name:"support.css-property",matches:{1:"support.vendor-prefix"},pattern:/(-o-|-moz-|-webkit-|-ms-)?[\w-]+(?=\s?:)(?!.*\{)/g},{matches:{1:[{name:"entity.name.sass",pattern:/&/g},{name:"direct-descendant",pattern:/>/g},{name:"entity.name.class",pattern:/\.[\w\-_]+/g},{name:"entity.name.id",pattern:/\#[\w\-_]+/g},{name:"entity.name.pseudo",pattern:/:[\w\-_]+/g},{name:"entity.name.tag",pattern:/\w+/g}]},pattern:/([\w\ ,\n:\.\#\&\;\-_]+)(?=.*\{)/g},{matches:{2:"support.vendor-prefix",3:"support.css-value"},pattern:/(:|,)\s*(-o-|-moz-|-webkit-|-ms-)?([a-zA-Z-]*)(?=\b)(?!.*\{)/g}],!0);/*]]>*/</script>
    
  8. Now Search For </head>
  9. Copy the css code provided below and paste it just above the tag we searched in above step.
  10. <style>
        pre {
            background: url(https://1bp.blogspot.com/-HvdODp1_1D4/UpifUhG5t9I/AAAAAAAABeM/niXqWfxP7RI/s1600/pre.png) repeat scroll 0 0 #fbf2f2;
            color: #888;
            display: block;
            font: 12px/19px Consolas, "Andale Mono", Courier, "Courier New", monospace;
            margin: 10px 0;
            overflow: auto;
            padding: 19px 19px 17px;
            white-space: pre-wrap;
            white-space: -moz-pre-wrap;
            white-space: -pre-wrap;
            white-space: -o-pre-wrap;
            word-wrap: break-word;
            user-select: all;
        }
    
        pre .comment {
            color: #a57a4c;
        }
    
        pre .variable.global,
        pre .variable.class,
        pre .variable.instance {
            color: #dc3958;
        }
    
        pre .constant.numeric,
        pre .constant.language,
        pre .constant.hex-color,
        pre .keyword.unit {
            color: #f79a32;
        }
    
        pre .constant,
        pre .entity,
        pre .entity.class,
        pre .support {
            color: #f06431;
        }
    
        pre .constant.symbol,
        pre .string {
            color: #889b4a;
        }
    
        pre .entity.function,
        pre .support.css-property,
        pre .selector {
            color: #8ab1b0;
        }
    
        pre .keyword,
        pre .storage {
            color: #98676a;
        }
    </style>
    
  11. Save Theme/Template

New syntax highlighter code in blogger template is added. You can also add this syntax highlighter in Wordpress but for that you need to add CSS and JavaScript code in header.php or footer.php

After adding these codes in your blogger blog now if you want to use this syntax highlighter you have to give class to every element where you want to use this syntax highlighter and that class will be the language name.

Below is the list to specify class of different languages.

ClassnameLanguage
data-language="c" C
data-language="java" JAVA
data-language="javascript" Javascript
data-language="python" Python
data-language="html" HTML
data-language="csharp" C# (C-Sharp)
data-language="php" PHP
data-language="css" CSS
data-language="" Universal Selector
If you want to see the demo of this syntax highlighter you can see it by clicking the button below. Demo

Conclusion:

So, I have explained how to use this pure javascript syntax highlighter in blogger or WordPress to highlight code snippets on your web pages.

Tags :

Related Posts

M.Muzammil

I am a web Designer & Graphics Designer. I love to program and design. Sharing knowledge is my passion & Programming is my Hobby. Want Help? Contact Me its free.!

Be The First To Comment

Add Comment