PrismHighlight/prism/plugins/prism-line-highlight.js

94 lines
2.1 KiB
JavaScript

(function(){
if(!window.Prism) {
return;
}
function $$(expr, con) {
return Array.prototype.slice.call((con || document).querySelectorAll(expr));
}
var CRLF = crlf = /\r?\n|\r/g;
function highlightLines(pre, lines, classes) {
var ranges = lines.replace(/\s+/g, '').split(','),
offset = +pre.getAttribute('data-line-offset') || 0;
var lineHeight = parseFloat(getComputedStyle(pre).lineHeight);
for (var i=0, range; range = ranges[i++];) {
range = range.split('-');
var start = +range[0],
end = +range[1] || start;
var line = document.createElement('div');
line.textContent = Array(end - start + 2).join(' \r\n');
line.className = (classes || '') + ' line-highlight';
line.setAttribute('data-start', start);
if(end > start) {
line.setAttribute('data-end', end);
}
line.style.top = (start - offset - 1) * lineHeight + 'px';
(pre.querySelector('code') || pre).appendChild(line);
}
}
function applyHash() {
var hash = location.hash.slice(1);
// Remove pre-existing temporary lines
$$('.temporary.line-highlight').forEach(function (line) {
line.parentNode.removeChild(line);
});
var range = (hash.match(/\.([\d,-]+)$/) || [,''])[1];
if (!range || document.getElementById(hash)) {
return;
}
var id = hash.slice(0, hash.lastIndexOf('.')),
pre = document.getElementById(id);
if (!pre) {
return;
}
if (!pre.hasAttribute('data-line')) {
pre.setAttribute('data-line', '');
}
highlightLines(pre, range, 'temporary ');
document.querySelector('.temporary.line-highlight').scrollIntoView();
}
var fakeTimer = 0; // Hack to limit the number of times applyHash() runs
Prism.hooks.add('after-highlight', function(env) {
var pre = env.element.parentNode;
var lines = pre && pre.getAttribute('data-line');
if (!pre || !lines || !/pre/i.test(pre.nodeName)) {
return;
}
clearTimeout(fakeTimer);
$$('.line-highlight', pre).forEach(function (line) {
line.parentNode.removeChild(line);
});
highlightLines(pre, lines);
fakeTimer = setTimeout(applyHash, 1);
});
addEventListener('hashchange', applyHash);
})();