wordwrap.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Simplified version of https://github.com/substack/node-wordwrap
  2. 'use strict';
  3. module.exports = function (start, stop) {
  4. if (!stop) {
  5. stop = start;
  6. start = 0;
  7. }
  8. var re = /(\S+\s+)/;
  9. return function (text) {
  10. var chunks = text.toString().split(re);
  11. return chunks.reduce(function (lines, rawChunk) {
  12. if (rawChunk === '') return lines;
  13. var chunk = rawChunk.replace(/\t/g, ' ');
  14. var i = lines.length - 1;
  15. if (lines[i].length + chunk.length > stop) {
  16. lines[i] = lines[i].replace(/\s+$/, '');
  17. chunk.split(/\n/).forEach(function (c) {
  18. lines.push(
  19. new Array(start + 1).join(' ')
  20. + c.replace(/^\s+/, '')
  21. );
  22. });
  23. }
  24. else if (chunk.match(/\n/)) {
  25. var xs = chunk.split(/\n/);
  26. lines[i] += xs.shift();
  27. xs.forEach(function (c) {
  28. lines.push(
  29. new Array(start + 1).join(' ')
  30. + c.replace(/^\s+/, '')
  31. );
  32. });
  33. }
  34. else {
  35. lines[i] += chunk;
  36. }
  37. return lines;
  38. }, [ new Array(start + 1).join(' ') ]).join('\n');
  39. };
  40. };