Adding custom controls in the notebook toolbar
The CSS and JavaScript of the HTML notebook can be customized through the files in ~/.ipython/profile_default/static/custom
, where ~
is your home directory, and default
is your IPython profile.
In this recipe, we will use these customization options to add a new button in the notebook toolbar that linearly renumbers all code cells.
How to do it...
- First, we are going to inject JavaScript code directly in the notebook. This is useful for testing purposes, or if we don't want the changes to be permanent. The JavaScript code will be loaded with that notebook only. To do this, we can just use the
%%javascript
cell magic as follows:In [1]: %%javascript // This function allows us to add buttons // to the notebook toolbar. IPython.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': 'icon-list-ol', // The callback function. 'callback': function () { // We retrieve the lists of all cells. var cells = IPython.notebook.get_cells(); // We only keep the code cells. cells = cells.filter(function(c) { return c instanceof IPython.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 the preceding code cell adds a button in the toolbar as shown in the following screenshot. Clicking on this button automatically updates the prompt numbers of all code cells.
Adding a Renumber toolbar button
- To make these changes permanent, that is, to add this button on every notebook in the current profile, we can open the
~/.ipython/profile_default/static/custom/custom.js
file and add the following lines of code:$([IPython.events]).on('app_initialized.NotebookApp', function(){ // Copy the JavaScript code (in step 1) here. });
The preceding code will be automatically loaded in the notebook, and the renumber button will appear on top of every notebook in the current profile.
There's more...
The IPython notebook JavaScript API that allowed us to add a button to the notebook toolbar is still unstable at the time of writing. It may change at any time, and it is not well documented. This recipe has only been tested with IPython 2.0. You may nevertheless find a not-so-official and partial API documentation on this page: http://ipjsdoc.herokuapp.com.
We should expect a more stable API in the future.
See also
- The Customizing the CSS style in the notebook recipe