in src/o-tree.ts [260:309]
public toString() {
// Strip trailing whitespace from every line, and empty lines from the start and end
return this.fragments
.map((item, index, fragments) => {
if (typeof item !== 'object') {
return item;
}
const ignore = '';
const leading = fragments.slice(0, index).reverse();
for (const fragment of leading) {
if (typeof fragment === 'object') {
// We don't emit if there was already a conditional newline just before
return ignore;
}
// If there's a trailing newline, then we don't emit this one
if (/\n\s*$/m.exec(fragment)) {
return ignore;
}
// If it contained non-whitespace characters, we need to check trailing data...
if (/[^\s]/.exec(fragment)) {
break;
}
}
const newlineAndIndent = `\n${this.indentChar.repeat(item.conditionalNewLine.indent)}`;
const trailing = fragments.slice(index + 1);
for (const fragment of trailing) {
if (typeof fragment === 'object') {
// We're the first of a sequence, so we must emit (unless we returned earlier, of course)
return newlineAndIndent;
}
// If there's a leading newline, then we don't emit this one
if (/^\s*\n/m.exec(fragment)) {
return ignore;
}
// If it contained non-whitespace characters, we emit this one
if (/[^\s]/.exec(fragment)) {
return newlineAndIndent;
}
}
return ignore;
})
.join('')
.replace(/[ \t]+$/gm, '')
.replace(/^\n+/, '')
.replace(/\n+$/, '');
}