Skip to content

Line Numbering Plugin for Prism

Updated 2013-12-09 to use much simpler code

One thing that is nice about Prism is that it provides hooks to extend the syntax highlighting, so it is straightforward to create a plugin that adds features like my line numbering, so I can do things like:

<pre><code class="language-javascript" data-linenumber=4>
function foo(arg){
  console.log('You said: '+arg);

Download the code.

Download the CSS (the linenumbering parts are at the bottom).

See an example (working together with the line highlighting plugin)(note that Chrome requires an explicit line-height on the <pre> to work).

You use the plugin simply by including the script after loading Prism, then adding the data-linenumber attribute to the code element, as in <code class="language-javascript" data-linenumber><code>. The default first line is 0 (we're computer scientists after all!). Change it by assigning a value to the data-linenumber attribute, as in <code class="language-javascript" data-linenumber=4><code>.

As I discussed before, the code element must have a style of counter-reset: something and each line is wrapped in a <span class="line"> element, and those must have a style of counter-increment: something. Then the span.line:before selector needs a style of content: counter(something).

Hope this helps someone!


{ 3 } Comments

  1. Vahid | April 5, 2013 at 4:02 am | Permalink

    Thanks for sharing.
    I need it.

  2. Cretu Eusebiu | April 7, 2013 at 6:36 am | Permalink

    Hi, this plugin is great but I have one problem, if I have more than one commented line this happens: Any idea how I could fix that ?

  3. Danny | April 7, 2013 at 2:51 pm | Permalink

    @Cretu Eusebiu:
    Yes, that’s an odd bug I’ve noted but haven’t figured out yet. It seems to show up only if the first line is a comment; then subsequent comments that start on the first character aren’t counted. Simple workaround: add a space before the comment.

{ 2 } Trackbacks

  1. Prism Syntax Highlighter | HazzardWeb | April 8, 2013 at 3:43 pm | Permalink

    […] am inclus plugin-ul Line Numbering, pentru a genera și o numerotare a liniilor, dar are mici probleme și de accea l-am dezactivat […]

  2. […] back at my line numbering plugin for Prism, I realized that it's working too hard by manipulating the DOM. Prism works by string manipulation […]

Post a Comment

Your email is never published nor shared. Required fields are marked *