This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
The CSS and Javascript of the HTML notebook can be customized through the files in ~/.jupyter/custom
directory, where ~
is your HOME
directory, (if you are using IPython < 4.x, the location is ~/.ipython/profile_default/static/custom
, where default
is your IPython profile). In this short recipe, we will use this feature to add a new button in the notebook toolbar on top of every notebook. Specifically, this button renumbers linearly all code cells.
%%javascript
cell magic.%%javascript
// This function allows us to add buttons
// to the notebook toolbar.
// If using IPython < 4.x, replace 'Jupyter' everywhere below
// with 'IPython'
Jupyter.toolbar.add_buttons_group([
{
// The button's label.
'label': 'renumber all code cells',
// The button's icon.
// See a list of Font-Awesome icons here:
// http://fortawesome.github.io/Font-Awesome/icons/
'icon': 'fa-list-ol', // 'icon-list-ol' for older IPython
// The callback function.
'callback': function () {
// We retrieve the lists of all cells.
var cells = Jupyter.notebook.get_cells();
// We only keep the code cells.
cells = cells.filter(function(c)
{
return c instanceof Jupyter.CodeCell;
})
// We set the input prompt of all code cells.
for (var i = 0; i < cells.length; i++) {
cells[i].set_input_prompt(i + 1);
}
}
}]);
Running this code cell adds a button in the toolbar. Clicking on this button automatically updates the prompt numbers of all code cells.
~/.jupyter/custom/custom.js
and add the code below. For IPython before 3.x and older, use file ~/.ipython/profile_default/static/custom/custom.js
and replace all occurences of Jupyter
in the code with IPython
.$([Jupyter.events]).on('app_initialized.NotebookApp',
function(){
// Copy of the Javascript code above (step 1).
Jupyter.toolbar.add_buttons_group([
{
// The button's label.
'label': 'renumber all code cells',
// The button's icon.
// See a list of Font-Awesome icons here:
// http://fortawesome.github.io/Font-Awesome/icons/
'icon': 'fa-list-ol', // 'icon-list-ol' for older IPython
// The callback function.
'callback': function () {
// We retrieve the lists of all cells.
var cells = Jupyter.notebook.get_cells();
// We only keep the code cells.
cells = cells.filter(function(c)
{
return c instanceof Jupyter.CodeCell;
})
// We set the input prompt of all code cells.
for (var i = 0; i < cells.length; i++) {
cells[i].set_input_prompt(i + 1);
}
}
}]);
});
The code put here will be automatically loaded as soon as a notebook page is loaded.
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).