(string, width)
| 10602 | // Note: a long line without a suitable break point will exceed the width limit. |
| 10603 | // Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. |
| 10604 | function foldString(string, width) { |
| 10605 | // In folded style, $k$ consecutive newlines output as $k+1$ newlines— |
| 10606 | // unless they're before or after a more-indented line, or at the very |
| 10607 | // beginning or end, in which case $k$ maps to $k$. |
| 10608 | // Therefore, parse each chunk as newline(s) followed by a content line. |
| 10609 | var lineRe = /(\n+)([^\n]*)/g; |
| 10610 | |
| 10611 | // first line (possibly an empty line) |
| 10612 | var result = (function () { |
| 10613 | var nextLF = string.indexOf('\n'); |
| 10614 | nextLF = nextLF !== -1 ? nextLF : string.length; |
| 10615 | lineRe.lastIndex = nextLF; |
| 10616 | return foldLine(string.slice(0, nextLF), width); |
| 10617 | }()); |
| 10618 | // If we haven't reached the first content line yet, don't add an extra \n. |
| 10619 | var prevMoreIndented = string[0] === '\n' || string[0] === ' '; |
| 10620 | var moreIndented; |
| 10621 | |
| 10622 | // rest of the lines |
| 10623 | var match; |
| 10624 | while ((match = lineRe.exec(string))) { |
| 10625 | var prefix = match[1], line = match[2]; |
| 10626 | moreIndented = (line[0] === ' '); |
| 10627 | result += prefix |
| 10628 | + (!prevMoreIndented && !moreIndented && line !== '' |
| 10629 | ? '\n' : '') |
| 10630 | + foldLine(line, width); |
| 10631 | prevMoreIndented = moreIndented; |
| 10632 | } |
| 10633 | |
| 10634 | return result; |
| 10635 | } |
| 10636 | |
| 10637 | // Greedy line breaking. |
| 10638 | // Picks the longest line under the limit each time, |
no test coverage detected