Skip to content

Instantly share code, notes, and snippets.

@dcgithub
Forked from agibsonsw/tidy.js
Created February 12, 2023 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcgithub/891ad326a63260f786d4a3a82c89fe69 to your computer and use it in GitHub Desktop.
Save dcgithub/891ad326a63260f786d4a3a82c89fe69 to your computer and use it in GitHub Desktop.
JS to tidy/align spaces
function tidySpaces() {
var olCode, spans, i, span_textnode, span_text, span_next, offLeft, newLeft;
if (document.getElementsByClassName) {
spans = document.getElementsByClassName('tidy');
if (spans != 'undefined' && spans.length) {
for ( i = 0; i < spans.length; i++ )
spans[i].style.paddingLeft = (spans[i].style.paddingLeft == '0px') ?
spans[i].prevValue : '0px';
return;
}
}
olCode = document.getElementById('olCode');
spans = olCode.getElementsByTagName('span');
for (i = 0; i < spans.length; i++) {
if ( spans[i].previousSibling ) {
if ( spans[i].className && spans[i].className == 'comment')
continue;
span_textnode = spans[i].firstChild;
span_text = span_textnode.data;
tidied = span_text.replace(/\s{2,}$/,'');
if (span_text.length && (span_text.length > tidied.length)) {
if ( spans[i].nextSibling ) {
span_next = spans[i];
while ( (span_next = span_next.nextSibling) && span_next.className
&& span_next.className == 'comment' && span_next.nextSibling )
; // do nothing, get next span (or 'a' tag)
if ( span_next ) {
offLeft = span_next.offsetLeft;
newLeft = (parseInt(offLeft / 60)) * 60 + 60;
span_next.style.paddingLeft = (newLeft - offLeft) + 'px';
span_next.className = 'tidy';
span_next.prevValue = span_next.style.paddingLeft;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment