Add line numbers to code snippets

TL;DR

Ease adding line numbers to pieces of code for illustrating the in the blog.

From time to time, I show snippets of code that carry some numbering, so that it’s then easier to point out different operations in different lines:

 1  sub get_some_sub {
 2      my $x = 0;
 3      return sub { ++$x };
 4  }
 5
 6  my $some_sub = get_some_sub();
 7  my $some_other_sub = get_some_sub();

Adding those numbers proved to have an interface I wasn’t really fond of:

  • first of all, empty lines (i.e. lines with only spaces, or just empty) are not numbered by default by the otherwise excellent nl. This requires the addition of a -ba options, which I will probably never remember;
  • then, nl just puts too many spaces before the numbers, for sake of indentation. I mean, they’re too many for my code snippets/examples, which should reasonably remain below 50 lines;
  • last, I usually want to add numbers so that I can put the result in the blog post, so I need that text to be put in the clipboard.

Considering that my Vim-fu is pretty weak, I resorted to a small script:

#!/bin/sh
nl -ba | sed 's/\t/ /;s/^    //' | xclip -sel clip

I know, xclip is probably something a bit too Linuxey, but I guess you can figure out how to substitute it with your command-line-to-clipboard feeder of choice 😇

Update: a gentle reader made me notice that nl has a few options that can help with formatting the output and avoid sed, so here’s an equivalent, shorter version:

#!/bin/sh
nl -ba -w 2 -s ' ' | xclip -sel clip

Thanks Julien!


Comments? Octodon, , GitHub, Reddit, or drop me a line!