code: function foldLine(line, width) {
    if (line === '' || line[0] === ' ') return line;
  
    // Since a more-indented line adds a \n, breaks can't be followed by a space.
    var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
    var match;
    // start is an inclusive index. end, curr, and next are exclusive.
    var start = 0,
        end,
        curr = 0,
        next = 0;
    var result = '';
  
    // Invariants: 0 <= start <= length-1.
    //   0 <= curr <= next <= max(0, length-2). curr - start <= width.
    // Inside the loop:
    //   A match implies length >= 2, so curr and next are <= length-2.
    while (match = breakRe.exec(line)) {
      next = match.index;
      // maintain invariant: curr - start <= width
      if (next - start > width) {
        end = curr > start ? curr : next; // derive end <= length-2
        result += '\n' + line.slice(start, end);
        // skip the space that was output as \n
        start = end + 1; // derive start <= length-1
      }
      curr = next;
    }
  
    // By the invariants, start <= length-1, so there is something left over.
    // It is either the whole string or a part starting from non-whitespace.
    result += '\n';
    // Insert a break if the remainder is too long and there is a break available.
    if (line.length - start > width && curr > start) {
      result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
    } else {
      result += line.slice(start);
    }
  
    return result.slice(1); // drop extra \n joiner
  }
docs: Greedy line breaking. Picks the longest line under the limit each time, otherwise settles for the shortest line over the limit. NB. More-indented lines *cannot* be folded, as that would add an extra \n.