Skip to content

Instantly share code, notes, and snippets.

@amadanmath
Last active August 29, 2015 14:07
Show Gist options
  • Save amadanmath/6eaf4cc850f38b78562f to your computer and use it in GitHub Desktop.
Save amadanmath/6eaf4cc850f38b78562f to your computer and use it in GitHub Desktop.
KaTeX for Gists user extension
// ==UserScript==
// @name KaTeX for Gists
// @author Goran Topić
// @homepage http://github.com/amadanmath/
// @include *://gist.github.com/*
// @version 0.1.1
// @updateURL https://gist.github.com/amadanmath/6eaf4cc850f38b78562f/raw/KaTeX_for_Gists.user.js
// @downloadURL https://gist.github.com/amadanmath/6eaf4cc850f38b78562f/raw/KaTeX_for_Gists.user.js
// @description Shows LaTeX in <tt> tags on Github Gist pages
// ==/UserScript==
(function() {
var cdnBase = "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.1.0/";
function katexify(math) {
var mathtext = math.innerHTML,
block = false,
mathtext, mathhtml;
try {
mathhtml = katex.renderToString(mathtext);
math.innerHTML = mathhtml;
if (mathtext.match(/^\s*\\displaystyle/)) {
math.className += " block";
}
} catch (e) {
console.error(e.message);
}
}
function loadKatexStyle() {
GM_xmlhttpRequest({
method: "GET",
url: cdnBase + "katex.min.css",
headers: {
"Content-Type": "application/javascript"
},
onload: function katexStyleLoaded(response) {
var head, style, styletext;
head = document.getElementsByTagName('head')[0];
style = document.createElement('style');
style.type = 'text/css';
styletext = response.responseText.replace(
/url\((.*?)\)/g,
"url(" + cdnBase + "$1)"
);
styletext += "\n tt.block { display: inline-block; }"
style.innerHTML = styletext;
head.appendChild(style);
}
});
}
function loadKatexCode() {
GM_xmlhttpRequest({
method: "GET",
url: cdnBase + "katex.min.js",
headers: {
"Content-Type": "application/javascript"
},
onload: function katexCodeLoaded(response) {
eval(response.responseText);
for (var i = 0, len = maths.length; i < len; i++) {
katexify(maths[i]);
}
}
});
}
var maths = document.querySelectorAll('tt');
if (maths.length) {
loadKatexStyle();
loadKatexCode();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment