.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / stylelint / node_modules / slice-ansi / index.js
1 'use strict';
2 const isFullwidthCodePoint = require('is-fullwidth-code-point');
3
4 const ESCAPES = [
5         '\u001B',
6         '\u009B'
7 ];
8
9 const END_CODE = 39;
10 const ASTRAL_REGEX = /[\uD800-\uDBFF][\uDC00-\uDFFF]/;
11
12 const ESCAPE_CODES = new Map([
13         [0, 0],
14         [1, 22],
15         [2, 22],
16         [3, 23],
17         [4, 24],
18         [7, 27],
19         [8, 28],
20         [9, 29],
21         [30, 39],
22         [31, 39],
23         [32, 39],
24         [33, 39],
25         [34, 39],
26         [35, 39],
27         [36, 39],
28         [37, 39],
29         [90, 39],
30         [40, 49],
31         [41, 49],
32         [42, 49],
33         [43, 49],
34         [44, 49],
35         [45, 49],
36         [46, 49],
37         [47, 49]
38 ]);
39
40 const wrapAnsi = code => `${ESCAPES[0]}[${code}m`;
41
42 module.exports = (str, begin, end) => {
43         const arr = Array.from(str.normalize());
44
45         end = typeof end === 'number' ? end : arr.length;
46
47         let insideEscape = false;
48         let escapeCode;
49         let visible = 0;
50         let output = '';
51
52         for (const item of arr.entries()) {
53                 const i = item[0];
54                 const x = item[1];
55
56                 let leftEscape = false;
57
58                 if (ESCAPES.indexOf(x) !== -1) {
59                         insideEscape = true;
60                         const code = /\d[^m]*/.exec(str.slice(i, i + 4));
61                         escapeCode = code === END_CODE ? null : code;
62                 } else if (insideEscape && x === 'm') {
63                         insideEscape = false;
64                         leftEscape = true;
65                 }
66
67                 if (!insideEscape && !leftEscape) {
68                         ++visible;
69                 }
70
71                 if (!ASTRAL_REGEX.test(x) && isFullwidthCodePoint(x.codePointAt())) {
72                         ++visible;
73                 }
74
75                 if (visible > begin && visible <= end) {
76                         output += x;
77                 } else if (visible === begin && !insideEscape && escapeCode !== undefined && escapeCode !== END_CODE) {
78                         output += wrapAnsi(escapeCode);
79                 } else if (visible >= end) {
80                         if (escapeCode !== undefined) {
81                                 output += wrapAnsi(ESCAPE_CODES.get(parseInt(escapeCode, 10)) || END_CODE);
82                         }
83                         break;
84                 }
85         }
86
87         return output;
88 };