Skip to content

Instantly share code, notes, and snippets.

@mscuthbert
Created October 9, 2015 13:57
Show Gist options
  • Save mscuthbert/6411762f98f3536712e0 to your computer and use it in GitHub Desktop.
Save mscuthbert/6411762f98f3536712e0 to your computer and use it in GitHub Desktop.
Markdown links in Jupyter/IPython
// Allow sphinx rst references in markdown cells
// TODO: Markdown cells will only be reevaluated when a notebook is dirty
// (i.e. you have made changes). If you save it before reevaluating MD cells,
// they will show the old value.
define([
'base/js/namespace',
'jquery',
'notebook/js/cell',
'base/js/security',
'components/marked/lib/marked',
'base/js/events',
'notebook/js/textcell'
], function(IPython, $, cell, security, marked, events,textcell) {
"use strict";
/*
* Find Sphinx expressions and add to text as <a href> tags
*
* @method execute_sphinx
* @param cell {Cell} notebook cell
* @param text {String} text in cell
*/
var execute_sphinx = function(cell,text) {
/* always clear stored variables if notebook is dirty */
if (IPython.notebook.dirty === true ) delete cell.metadata.sphinx_links;
// search for code in mangled <code> blocks
var found = false;
var newtext = text.replace(/:ref:<code>(.*?)\s*&lt;(.*?)\&gt;<\/code>/g, function(match, info, link, cha){
found = true;
link = link.replace(/\.html$/, '');
if (link.indexOf('.') == -1) {
link = link + ".ipynb";
}
console.log(link);
return '<a href="' + link + '" target=_new>' + info + '</a>';
});
if (found) {
if (typeof cell.metadata.sphinx_links === "undefined") {
cell.metadata.sphinx_links = {any: true}
}
}
return newtext
};
/*
* Render markdown cell and replace {{...}} with python code
*
*/
var render_cell = function(cell) {
var element = cell.element.find('div.text_cell_render');
var text = execute_sphinx(cell, element[0].innerHTML);
if (text !== undefined) {
element[0].innerHTML = text;
MathJax.Hub.Queue(["Typeset",MathJax.Hub,element[0]]);
}
};
/* force rendering of markdown cell if notebook is dirty */
var original_render = textcell.MarkdownCell.prototype.render;
textcell.MarkdownCell.prototype.render = function() {
if (IPython.notebook.dirty === true) {
this.rendered = false
}
return original_render.apply(this)
};
var load_ipython_extension = function() {
events.on("rendered.MarkdownCell", function (event, data) {
render_cell(data.cell)
});
/* show values stored in metadata on reload */
events.on("kernel_ready.Kernel", function () {
var ncells = IPython.notebook.ncells();
var cells = IPython.notebook.get_cells();
for (var i = 0; i < ncells; i++) {
var cell = cells[i];
if (cell.metadata.hasOwnProperty('sphinx_links')) {
render_cell(cell);
}
}
});
};
return {
load_ipython_extension : load_ipython_extension
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment