Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* internal function to do nasty character splitting if we can't split on space */
var splitOnChars = function(longStr) {
var arr = longStr.split('');
var count = 0;
var str = '';
for(var n=0; n < arr.length; n++) {
str += arr[n];
if(count==spBook.Settings.fixedLine) {
str+=spBook.Settings.breakInsert;
count=0;
}
count++;
}
return str;
}
/* add the line-breaking character to long lines in code. */
var initLineBreaks = function() {
// find all code blocks
var codeList = document.querySelectorAll("code pre");
forEach(codeList, function (index, value) {
var thisBlock = value.innerHTML;
var thisBlockLines = thisBlock.split("\n");
var codeOut = '';
for(var i=0; i < thisBlockLines.length; i++) {
trimLine = thisBlockLines[i].trim();
// is the line longer than the fixedLine value?
if(trimLine.length > spBook.Settings.fixedLine) {
// is there a space in the line or is this just a jumbo unbroken line?
var spaceChar = trimLine.lastIndexOf(' ');
if(spaceChar == -1) {
// do nasty character split
codeOut+= splitOnChars(trimLine);
} else {
// we have the promise of a space, let us see if we can do something nicer.
//split on space
var words = trimLine.split(' ');
// loop through test whether adding item would make string longer than fixedLine.length
var str = '';
for(var n=0; n < words.length; n++) {
if(str.length+words[n].length > spBook.Settings.fixedLine) {
// split after str, don't add item, item becomes new str
str+=spBook.Settings.breakInsert;
codeOut+=str;
str = words[n];
} else {
// add this item to str
str+= ' '+words[n];
}
}
// add any remaining characters to str.
codeOut+=str + "\n";
}
} else {
// just pass this back out unaltered.
codeOut+=thisBlockLines[i] + "\n";
}
}
value.innerHTML = codeOut;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment