Adding Line Numbering At Prism Syntax Highlighter
Updated on April 03, 2016
I will share how to add line numbering on Prism's syntax highlighter to make it look more tidy and provide another view of the earlier Prism syntax highlighter that you already use.
If you have previously been using Prism syntax highlighter from posting Kang Ismet, then you only need to add some code to add line numbering at Prism syntax highlighter.
If you have previously been using Prism syntax highlighter from posting Kang Ismet, then you only need to add some code to add line numbering at Prism syntax highlighter.
Author: Adhy Suriady
For Prism demo of Kang Ismet syntax highlighter can be seen on the demo link below.
Please use the code below to Prism syntax highlighter that you've used automatically have numbering on its line syntax.
CSS Code
pre.line-numbers {
position: relative;
padding-left: 3.8em;
counter-reset: linenumber;
}
pre.line-numbers > code {
position: relative;
}
.line-numbers .line-numbers-rows {
position: absolute;
pointer-events: none;
top: 0;
font-size: 100%;
left: -3.8em;
width: 3em; /* works for line-numbers below 1000 lines */
letter-spacing: -1px;
border-right: 1px solid #999;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.line-numbers-rows > span {
pointer-events: none;
display: block;
counter-increment: linenumber;
}
.line-numbers-rows > span:before {
content: counter(linenumber);
color: #999;
display: block;
padding-right: 0.8em;
text-align: right;
}
Javascript Code
<script>
$('pre').attr('class', 'line-numbers');
Prism.hooks.add("after-highlight",function(e){var t=e.element.parentNode;if(!t||!/pre/i.test(t.nodeName)||t.className.indexOf("line-numbers")===-1){return}var n=1+e.code.split("\n").length;var r;lines=new Array(n);lines=lines.join("<span></span>");r=document.createElement("span");r.className="line-numbers-rows";r.innerHTML=lines;if(t.hasAttribute("data-start")){t.style.counterReset="linenumber "+(parseInt(t.getAttribute("data-start"),10)-1)}e.element.appendChild(r)})
</script>
Prism syntax highlighter you've already published previously on the posting does not need to be changed because it will automatically be added class="line-number" by code $('pre').attr('class', 'line-numbers'); the javascript above. So you just need to add CSS and Javascript code above and all Prism syntax that you have created will automatically have the line numbering.