Skip to content

Instantly share code, notes, and snippets.

@adrn
Created September 18, 2014 20:27
Show Gist options
  • Save adrn/8422a6b8f70cd5b42542 to your computer and use it in GitHub Desktop.
Save adrn/8422a6b8f70cd5b42542 to your computer and use it in GitHub Desktop.
Custom cell macros in IPython Notebook
$([IPython.events]).on('app_initialized.NotebookApp', function(){
// Try to read JSON file specifying cell macros
$.getJSON("/static/custom/macros.json", function(data) {
var pickTemplateLabel = $("<span></span>")
.attr("class", "navbar-text")
.text("Cell Macro:");
var pickTemplate = $("<select></select>").attr("id", "pick_template");
$.each(data['cells'], function(key, cell) {
var option = $("<option></option>")
.attr("value", cell['name'])
.text(cell['name'])
.attr("code", cell['lines'].join('\n'));
pickTemplate.append(option);
});
$("div#maintoolbar-container").append(pickTemplateLabel);
$("div#maintoolbar-container").append(pickTemplate);
// Add a button to the toolbar for inserting a macro cell
IPython.toolbar.add_buttons_group([
{
'label' : 'Insert cell macro.',
'icon' : 'icon-coffee',
'callback': function () {
var code = $("select#pick_template").find(":selected").attr("code");
var new_cell = IPython.notebook.insert_cell_above('code');
new_cell.set_text(code);
new_cell.focus_cell();
}
}
]);
});
});
{
"cells" : [
{
"name" : "mpl+numpy",
"lines" : [
"import numpy as np",
"import matplotlib.pyplot as plt",
"%matplotlib inline"
]
},
{
"name" : "mpl+numpy+units",
"lines" : [
"import astropy.units as u",
"import numpy as np",
"import matplotlib.pyplot as plt",
"%matplotlib inline"
]
},
{
"name" : "future",
"lines" : [
"from __future__ import division, print_function",
"",
"# Standard library",
"import time",
"",
"# Third-party",
"from astropy import log as logger",
"import emcee",
"import matplotlib.pyplot as plt",
"import numpy as np",
"%matplotlib inline"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment