Adding Line Numbers in IPython (or IJulia) Notebooks

By: randyzwitch - Articles

Re-posted from: http://randyzwitch.com/line-numbers-ipython-notebook/

Lately, I’ve been using IPython Notebooks for all of my Python and Julia coding. The ability to develop and submit small snippets of code and create plots inline is just so useful that it has broken the stranglehold of using an IDE while I’m coding. However, the one thing that was missing for a smooth transition was line numbers in the cells; luckily, this can be achieved in two ways.

Keyboard Shortcut

The easiest way to add line numbers to an IPython Notebook is to use the keyboard shortcut, which is ctrl-m-l. Just highlight the cell you are interested in adding line numbers to, then hit the keyboard shortcut to toggle the line numbers.

ipython-notebook-line-numbers

Add Line Numbers to All Cells at Startup

While the keyboard shortcut is great for toggling line numbers on/off, I prefer having line numbers always on. Luckily, the IPython Dev folks on Twitter were kind enough to explain how to do this:

I use OSX with the default ‘profile_default’ profile, so the path for my custom.js file for IPython is:

/Users/randyzwitch/.ipython/profile_default/static/custom/

Similarly, you can do the same for IJulia:

/Users/randyzwitch/.ipython/profile_julia/static/custom

If you are using a different operating system than OSX, or you are using OSX and you don’t see a custom.js file in these locations, a quick search for custom.js will get you to the right file location. Once you open up the custom.js file, you can place the line of JavaScript anywhere in the file, as long as it’s not inside any of any pre-existing functions in the file.

Once you place the line of JavaScript in your file, you’ll need to restart IPython/IJulia completely for the change to take effect. After that, you’ll have line numbers in each cell, each Notebook!