Skip to content

Commit 6e6993b

Browse files
authored
Add countAnsiEscapeCodes option (#48)
1 parent f85812f commit 6e6993b

File tree

5 files changed

+24
-5
lines changed

5 files changed

+24
-5
lines changed

index.d.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,14 @@ export type Options = {
44
55
@default true
66
*/
7-
readonly ambiguousIsNarrow: boolean;
7+
readonly ambiguousIsNarrow?: boolean;
8+
9+
/**
10+
Whether [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) should be counted.
11+
12+
@default false
13+
*/
14+
readonly countAnsiEscapeCodes?: boolean;
815
};
916

1017
/**

index.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,13 @@ export default function stringWidth(string, options) {
1818

1919
options = {
2020
ambiguousIsNarrow: true,
21+
countAnsiEscapeCodes: false,
2122
...options,
2223
};
2324

24-
string = stripAnsi(string);
25+
if (!options.countAnsiEscapeCodes) {
26+
string = stripAnsi(string);
27+
}
2528

2629
if (string.length === 0) {
2730
return 0;

index.test-d.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@ import {expectType} from 'tsd';
22
import stringWidth from './index.js';
33

44
expectType<number>(stringWidth('古'));
5-
6-
expectType<number>(stringWidth('★', {ambiguousIsNarrow: true}));
5+
expectType<number>(stringWidth('★', {}));
6+
expectType<number>(stringWidth('★', {ambiguousIsNarrow: false}));
7+
expectType<number>(stringWidth('\u001B[31m\u001B[39m', {countAnsiEscapeCodes: true}));

readme.md

+8-1
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,17 @@ Type: `object`
4444
##### ambiguousIsNarrow
4545

4646
Type: `boolean`\
47-
Default: `false`
47+
Default: `true`
4848

4949
Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2).
5050

51+
##### countAnsiEscapeCodes
52+
53+
Type: `boolean`\
54+
Default: `false`
55+
56+
Whether [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) should be counted.
57+
5158
## Related
5259

5360
- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module

test.js

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ test('main', t => {
1313
t.is(stringWidth('안녕하세요'), 10);
1414
t.is(stringWidth('A\uD83C\uDE00BC'), 5, 'surrogate');
1515
t.is(stringWidth('\u001B[31m\u001B[39m'), 0);
16+
t.is(stringWidth('\u001B[31m\u001B[39m', {countAnsiEscapeCodes: true}), 8);
1617
t.is(stringWidth('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'), 5);
1718
t.is(stringWidth('\u{231A}'), 2, '⌚ default emoji presentation character (Emoji_Presentation)');
1819
t.is(stringWidth('\u{2194}\u{FE0F}'), 2, '↔️ default text presentation character rendered as emoji');

0 commit comments

Comments
 (0)