Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Adjust string length for fullwidth characters when end is undefined #27

Merged
merged 1 commit into from
Feb 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ module.exports = (string, begin, end) => {
const characters = [...string.normalize()];
const ansiCodes = [];

end = typeof end === 'number' ? end : characters.length;

let stringEnd = typeof end === 'number' ? end : characters.length;
let isInsideEscape = false;
let ansiCode;
let visible = 0;
Expand All @@ -64,7 +63,7 @@ module.exports = (string, begin, end) => {
if (ESCAPES.includes(character)) {
const code = /\d[^m]*/.exec(string.slice(index, index + 18));
ansiCode = code && code.length > 0 ? code[0] : undefined;
if (visible < end) {
if (visible < stringEnd) {
isInsideEscape = true;
if (ansiCode !== undefined) {
ansiCodes.push(ansiCode);
Expand All @@ -81,13 +80,17 @@ module.exports = (string, begin, end) => {

if (!astralRegex({exact: true}).test(character) && isFullwidthCodePoint(character.codePointAt())) {
++visible;

if (typeof end !== 'number') {
++stringEnd;
}
}

if (visible > begin && visible <= end) {
if (visible > begin && visible <= stringEnd) {
output += character;
} else if (visible === begin && !isInsideEscape && ansiCode !== undefined) {
output = checkAnsi(ansiCodes);
} else if (visible >= end) {
} else if (visible >= stringEnd) {
output += checkAnsi(ansiCodes, true, ansiCode);
break;
}
Expand Down
2 changes: 1 addition & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,6 @@ test('doesn\'t add extra escapes', t => {
});

// See https://github.com/chalk/slice-ansi/issues/26
test.failing('does not lose fullwidth characters', t => {
test('does not lose fullwidth characters', t => {
t.is(sliceAnsi('古古test', 0), '古古test');
});