Skip to content

Instantly share code, notes, and snippets.

@luikore
Created June 9, 2011 04:40
Show Gist options
  • Save luikore/1016075 to your computer and use it in GitHub Desktop.
Save luikore/1016075 to your computer and use it in GitHub Desktop.
bookmarklet for latex formula wrapped with [;...;], \[...\], $$...$$, $...$
javascript:(function(){
var R = /\[;.+?;\]|\\\[.+?\\\]|\$\$.+?\$\$|\$.+?\$|./g;
/* var R = /\[;.+?;\]|\\\[.+?\\\]|\$\$.+?\$\$|./g; */
var spanClick = function(){
this.nextElementSibling.style.display = 'inline';
this.style.display = 'none'
};
var imgClick = function() {
this.previousElementSibling.style.display = 'inline';
this.style.display = 'none'
};
var split = function(text) {
var arr = text.replace(/\r?\n/, ' ').match(R);
if (!arr) return;
var changed = false;
var res = [];
var tmpText = '';
for (var i = 0; i < arr.length; i++) {
var s = arr[i];
if (s.length == 1) {
tmpText += s
} else {
if (s[0] === '$' && (s[1] !== '$' || s[s.length - 2] !== '$'))
s = s.slice(1, s.length - 1);
else
s = s.slice(2, s.length - 2);
changed = true;
if (tmpText) {
res.push(document.createTextNode(tmpText));
tmpText = ''
}
var span = document.createElement('span');
span.style.display = 'none';
span.onclick = spanClick;
span.innerHTML = s;
res.push(span);
var img = document.createElement('img');
img.src = "http://latex.codecogs.com/gif.latex?" + s;
img.title = "click to show source";
img.onclick = imgClick;
res.push(img)
}
}
if (changed) {
if (tmpText) {
res.push(document.createTextNode(tmpText))
}
return res
}
};
var traverse = function(node) {
if (!node) return;
if (node.nodeType == 3) {
if (!/^\s*$/.test(node.nodeValue)) {
var parent = node.parentNode;
if (!parent) return;
var newNodes = split(node.textContent);
if (newNodes) {
for(var i = 0; i < newNodes.length; i++){
parent.insertBefore(newNodes[i], node);
};
parent.removeChild(node)
}
}
} else if (! /^script|style|link|img|input|textarea|select$/i.test(node.nodeName)) {
/* pre contains \n that can't be ignored */
if (/^pre$/i.test(node.nodeName)) {
node.innerHTML = node.innerHTML.replace(/\r?\n/g, '<br>')
}
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
traverse(node.childNodes[i])
}
}
};
traverse(document.getElementsByTagName('body')[0])
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment