Skip to content

Adding word-wrap support #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 34 additions & 12 deletions src/highlightjs-line-numbers.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,39 @@

for (var i in blocks) {
if (blocks.hasOwnProperty(i)) {
lineNumbersBlock(blocks[i]);
lineNumbersBlock(blocks[i], true);
}
}

$( window ).resize(function() {
for (var i in blocks) {
if (blocks.hasOwnProperty(i)) {
lineNumbersBlock(blocks[i], false);
}
}
});
} catch (e) {
console.error('LineNumbers error: ', e);
}
}

function lineNumbersBlock (element) {
//Add a second parameter to know if triggered by resizing
function lineNumbersBlock (element, resize) {
if (typeof element !== 'object') return;

var parent = element.parentNode;
var lines = getCountLines(parent.textContent);

var lines = getCountLines(element, resize);
if (lines > 1) {
var l = '';
for (var i = 0; i < lines; i++) {
l += (i + 1) + '\n';
}

$('.hljs-line').each(function(i) {
l += (i + 1) + '\n';
//add a empty line if word wrap is detected (if div's height if > than the line-height)
var height = Math.round(parseInt($(this).height())/parseInt($(this).css('line-height')));
if( height > 1){
l += '\n'.repeat(height-1);
}
});
$('.hljs-line-numbers').remove();
var linesPanel = document.createElement('code');
linesPanel.className = 'hljs hljs-line-numbers';
linesPanel.style.float = 'left';
Expand All @@ -51,17 +64,26 @@
}
}

function getCountLines(text) {
function getCountLines(el, resize) {
var text = el.innerHTML;
if (text.length === 0) return 0;

var regExp = /\r\n|\r|\n/g;
var lines = text.match(regExp);
lines = lines ? lines.length : 0;

if (!text[text.length - 1].match(regExp)) {
lines += 1;
}

// Don't wrap in div if resize, we have already it
if(resize === true){
//wrap each line in a div
var textLines = text.split(regExp);
var textResult = "";
textLines.forEach(function(element) {
textResult += "<div class='hljs-line'>"+element+"</div>\n";
});
el.innerHTML = textResult;
}
return lines;
}
}(window));
}(window));