In my last post, I covered math-symbol prettification in Emacs. While writing it, I got interested in doing the same thing in Javascript for the code samples in this blog. So I wrote some code!
var replaceAll = function(str, replacements) {
_.each(replacements, function(replacement, pattern) {
str = str.replace(pattern, replacement);
});
return str;
};
var prettifySymbols = {
coq: {
'forall': '∀',
'->': '→',
'exists': '∃',
'=>': '⇒',
'False': '⊥',
'True': '⊤'
}
};
$(function() {
_.each(prettifySymbols, function(replacements, lang) {
$('code.' + lang).each(function() {
var code = $(this);
if (code.hasClass('nopretty')) return;
code.children('span').each(function() {
var span = $(this);
var originalText = span.text();
var replacementText = replaceAll(originalText, replacements);
if (originalText !== replacementText) {
span.bind('pretty-replace', function() {
span.text(replacementText);
});
span.bind('pretty-original', function() {
span.text(originalText);
});
};
});
code.bind('copy', function() {
code.children('span').trigger('pretty-original');
setTimeout(function() {
code.children('span').trigger('pretty-replace');
}, 0);
});
code.children('span').trigger('pretty-replace');
});
});
});
The tricky thing here is ensuring that if you copy a code sample, you get the original text instead of the prettified text.
The code above uses Underscore and jQuery, and is designed to work with Jekyll code-blocks. Should be pretty easy to modify it for other code-sample formats, but your mileage may vary.