Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: chalk/wrap-ansi
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: a731af5a3461d92f2af302e81e05ea698a3c8c1a
Choose a base ref
...
head repository: chalk/wrap-ansi
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: bf27a9b1ee28cfe21d148942850028cda848f14d
Choose a head ref
  • 15 commits
  • 10 files changed
  • 4 contributors

Commits on Apr 27, 2017

  1. Fix tests (#15)

    SamVerschueren authored and sindresorhus committed Apr 27, 2017

    Unverified

    This user has not yet uploaded their public signing key.
    Copy the full SHA
    e910f82 View commit details

Commits on Jul 21, 2017

  1. Copy the full SHA
    02ad690 View commit details
  2. 1
    Copy the full SHA
    3483a30 View commit details

Commits on Jul 22, 2017

  1. Copy the full SHA
    f16f943 View commit details

Commits on Jul 23, 2017

  1. Copy the full SHA
    a8c3423 View commit details
  2. 3.0.0

    sindresorhus committed Jul 23, 2017
    Copy the full SHA
    c0b4bfd View commit details
  3. Copy the full SHA
    1bcb5fd View commit details
  4. 3.0.1

    sindresorhus committed Jul 23, 2017
    Copy the full SHA
    165504b View commit details

Commits on Jul 24, 2017

  1. Use escape codes from ansi-styles (#22)

    kevva authored and sindresorhus committed Jul 24, 2017
    Copy the full SHA
    b5fc35e View commit details

Commits on Nov 6, 2017

  1. Bump dev dependencies

    sindresorhus committed Nov 6, 2017
    Copy the full SHA
    14f3af7 View commit details

Commits on Aug 31, 2018

  1. Require Node.js 6

    sindresorhus committed Aug 31, 2018
    Copy the full SHA
    76d163e View commit details
  2. 4.0.0

    sindresorhus committed Aug 31, 2018
    Copy the full SHA
    8640dc3 View commit details

Commits on Mar 3, 2019

  1. Fix a bunch of issues (#30)

    Fixes #23
    Fixes #24
    Fixes #25
    Fixes #26
    Fixes #27
    stroncium authored and sindresorhus committed Mar 3, 2019
    Copy the full SHA
    c084e3e View commit details
  2. Copy the full SHA
    cf78036 View commit details
  3. 5.0.0

    sindresorhus committed Mar 3, 2019
    Copy the full SHA
    bf27a9b View commit details
Showing with 276 additions and 233 deletions.
  1. +1 −1 .editorconfig
  2. +1 −1 .gitattributes
  3. +1 −0 .gitignore
  4. +1 −0 .npmrc
  5. +5 −3 .travis.yml
  6. +98 −104 index.js
  7. +4 −16 license
  8. +59 −66 package.json
  9. +19 −3 readme.md
  10. +87 −39 test.js
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
@@ -7,6 +7,6 @@ charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[{package.json,*.yml}]
[*.yml]
indent_style = space
indent_size = 2
2 changes: 1 addition & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1 +1 @@
* text=auto
* text=auto eol=lf
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
yarn.lock
.nyc_output
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
8 changes: 5 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
language: node_js
node_js:
- '4'
- 'node'
after_success: npm run coveralls
- '10'
- '8'
- '6'
after_success:
- './node_modules/.bin/nyc report --reporter=text-lcov | ./node_modules/.bin/coveralls'
202 changes: 98 additions & 104 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,42 @@
'use strict';
var stringWidth = require('string-width');
var stripAnsi = require('strip-ansi');

var ESCAPES = [
'\u001b',
'\u009b'
];

var END_CODE = 39;

var ESCAPE_CODES = {
0: 0,
1: 22,
2: 22,
3: 23,
4: 24,
7: 27,
8: 28,
9: 29,
30: 39,
31: 39,
32: 39,
33: 39,
34: 39,
35: 39,
36: 39,
37: 39,
90: 39,
40: 49,
41: 49,
42: 49,
43: 49,
44: 49,
45: 49,
46: 49,
47: 49
};
const stringWidth = require('string-width');
const stripAnsi = require('strip-ansi');
const ansiStyles = require('ansi-styles');

const ESCAPES = new Set([
'\u001B',
'\u009B'
]);

const END_CODE = 39;

function wrapAnsi(code) {
return ESCAPES[0] + '[' + code + 'm';
}
const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`;

// calculate the length of words split on ' ', ignoring
// the extra characters added by ansi escape codes.
function wordLengths(str) {
return str.split(' ').map(function (s) {
return stringWidth(s);
});
}
// Calculate the length of words split on ' ', ignoring
// the extra characters added by ansi escape codes
const wordLengths = string => string.split(' ').map(character => stringWidth(character));

// wrap a long word across multiple rows.
// ansi escape codes do not count towards length.
function wrapWord(rows, word, cols) {
var insideEscape = false;
var visible = stripAnsi(rows[rows.length - 1]).length;
// Wrap a long word across multiple rows
// Ansi escape codes do not count towards length
const wrapWord = (rows, word, columns) => {
const characters = [...word];

for (var i = 0; i < word.length; i++) {
var x = word[i];
let insideEscape = false;
let visible = stringWidth(stripAnsi(rows[rows.length - 1]));

rows[rows.length - 1] += x;
for (const [index, character] of characters.entries()) {
const characterLength = stringWidth(character);

if (visible + characterLength <= columns) {
rows[rows.length - 1] += character;
} else {
rows.push(character);
visible = 0;
}

if (ESCAPES.indexOf(x) !== -1) {
if (ESCAPES.has(character)) {
insideEscape = true;
} else if (insideEscape && x === 'm') {
} else if (insideEscape && character === 'm') {
insideEscape = false;
continue;
}
@@ -71,98 +45,118 @@ function wrapWord(rows, word, cols) {
continue;
}

visible++;
visible += characterLength;

if (visible >= cols && i < word.length - 1) {
if (visible === columns && index < characters.length - 1) {
rows.push('');
visible = 0;
}
}

// it's possible that the last row we copy over is only
// ansi escape characters, handle this edge-case.
// It's possible that the last row we copy over is only
// ansi escape characters, handle this edge-case
if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
rows[rows.length - 2] += rows.pop();
}
}
};

// the wrap-ansi module can be invoked
// in either 'hard' or 'soft' wrap mode.
// The wrap-ansi module can be invoked
// in either 'hard' or 'soft' wrap mode
//
// 'hard' will never allow a string to take up more
// than cols characters.
// than columns characters
//
// 'soft' allows long words to expand past the column length.
function exec(str, cols, opts) {
var options = opts || {};
// 'soft' allows long words to expand past the column length
const exec = (string, columns, options = {}) => {
if (options.trim !== false && string.trim() === '') {
return '';
}

let pre = '';
let ret = '';
let escapeCode;

const lengths = wordLengths(string);
const rows = [''];

var pre = '';
var ret = '';
var escapeCode;
for (const [index, word] of string.split(' ').entries()) {
if (options.trim !== false) {
rows[rows.length - 1] = rows[rows.length - 1].trimLeft();
}

var lengths = wordLengths(str);
var words = str.split(' ');
var rows = [''];
let rowLength = stringWidth(rows[rows.length - 1]);

for (var i = 0, word; (word = words[i]) !== undefined; i++) {
var rowLength = stringWidth(rows[rows.length - 1]);
if (index !== 0) {
if (rowLength === columns && (options.wordWrap === false || options.trim === false)) {
// If we start with a new word but the current row length equals the length of the columns, add a new row
rows.push('');
rowLength = 0;
}

if (rowLength) {
rows[rows.length - 1] += ' ';
rowLength++;
}

// in 'hard' wrap mode, the length of a line is
// never allowed to extend past 'cols'.
if (lengths[i] > cols && options.hard) {
if (rowLength) {
// In 'hard' wrap mode, the length of a line is
// never allowed to extend past 'columns'
if (options.hard && lengths[index] > columns) {
const remainingColumns = (columns - rowLength);
const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
if (breaksStartingNextLine < breaksStartingThisLine) {
rows.push('');
}
wrapWord(rows, word, cols);

wrapWord(rows, word, columns);
continue;
}

if (rowLength + lengths[i] > cols && rowLength > 0) {
if (options.wordWrap === false && rowLength < cols) {
wrapWord(rows, word, cols);
if (rowLength + lengths[index] > columns && rowLength > 0) {
if (options.wordWrap === false && rowLength < columns) {
wrapWord(rows, word, columns);
continue;
}

rows.push('');
}

if (rowLength + lengths[index] > columns && options.wordWrap === false) {
wrapWord(rows, word, columns);
continue;
}

rows[rows.length - 1] += word;
}

pre = rows.map(function (r) {
return r.trim();
}).join('\n');

for (var j = 0; j < pre.length; j++) {
var y = pre[j];
pre = rows.map(row => options.trim === false ? row : row.trim()).join('\n');

ret += y;
for (const [index, character] of [...pre].entries()) {
ret += character;

if (ESCAPES.indexOf(y) !== -1) {
var code = parseFloat(/[0-9][^m]*/.exec(pre.slice(j, j + 4)));
if (ESCAPES.has(character)) {
const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4)));
escapeCode = code === END_CODE ? null : code;
}

if (escapeCode && ESCAPE_CODES[escapeCode]) {
if (pre[j + 1] === '\n') {
ret += wrapAnsi(ESCAPE_CODES[escapeCode]);
} else if (y === '\n') {
const code = ansiStyles.codes.get(Number(escapeCode));

if (escapeCode && code) {
if (pre[index + 1] === '\n') {
ret += wrapAnsi(code);
} else if (character === '\n') {
ret += wrapAnsi(escapeCode);
}
}
}

return ret;
}
};

// for each line break, invoke the method separately.
module.exports = function (str, cols, opts) {
return String(str).split('\n').map(function (substr) {
return exec(substr, cols, opts);
}).join('\n');
// For each newline, invoke the method separately
module.exports = (string, columns, options) => {
return String(string)
.normalize()
.split('\n')
.map(line => exec(line, columns, options))
.join('\n');
};
20 changes: 4 additions & 16 deletions license
Original file line number Diff line number Diff line change
@@ -1,21 +1,9 @@
The MIT License (MIT)
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Loading