Skip to content

Commit

Permalink
Add support for surrogate pairs and full width characters
Browse files Browse the repository at this point in the history
Fixes chalk#10 and chalk#11.
  • Loading branch information
kevva committed Jul 21, 2017
1 parent fc4430c commit 0feb955
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
18 changes: 13 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,21 @@ const wordLengths = str => str.split(' ').map(s => stringWidth(s));
// Wrap a long word across multiple rows
// Ansi escape codes do not count towards length
const wrapWord = (rows, word, cols) => {
const arr = Array.from(word);

let insideEscape = false;
let visible = stripAnsi(rows[rows.length - 1]).length;
let visible = stringWidth(stripAnsi(rows[rows.length - 1]));

for (const item of Array.from(word).entries()) {
for (const item of arr.entries()) {
const i = item[0];
const x = item[1];
const charLength = stringWidth(x);

rows[rows.length - 1] += x;
if (visible + charLength <= cols) {
rows[rows.length - 1] += x;
} else {
rows.push(x);
}

if (ESCAPES.indexOf(x) !== -1) {
insideEscape = true;
Expand All @@ -66,9 +73,9 @@ const wrapWord = (rows, word, cols) => {
continue;
}

visible++;
visible += charLength;

if (visible >= cols && i < word.length - 1) {
if (visible >= cols && i < arr.length - 1) {
rows.push('');
visible = 0;
}
Expand Down Expand Up @@ -167,6 +174,7 @@ const exec = (str, cols, opts) => {
// For each newline, invoke the method separately
module.exports = (str, cols, opts) => {
return String(str)
.normalize()
.split('\n')
.map(line => exec(line, cols, opts))
.join('\n');
Expand Down
4 changes: 2 additions & 2 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ test('no word-wrapping', t => {
});

// https://github.com/chalk/wrap-ansi/issues/10
test.failing('supports fullwidth characters', t => {
test('supports fullwidth characters', t => {
t.is(m('안녕하세', 4, {hard: true}), '안녕\n하세');
});

// https://github.com/chalk/wrap-ansi/issues/11
test.failing('supports unicode surrogate pairs', t => {
test('supports unicode surrogate pairs', t => {
t.is(m('a\ud83c\ude00bc', 2, {hard: true}), 'a\n\ud83c\ude00\nbc');
});

0 comments on commit 0feb955

Please sign in to comment.