forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
121 lines (102 loc) · 2.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import jsTokens from "js-tokens";
import esutils from "esutils";
import chalk from "chalk";
/**
* Chalk styles for token types.
*/
let defs = {
string: chalk.red,
punctuator: chalk.bold,
curly: chalk.green,
parens: chalk.blue.bold,
square: chalk.yellow,
keyword: chalk.cyan,
number: chalk.magenta,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.inverse
};
/**
* RegExp to test for newlines in terminal.
*/
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
/**
* Get the type of token, specifying punctuator type.
*/
function getTokenType(match) {
let token = jsTokens.matchToToken(match);
if (token.type === "name" && esutils.keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (token.type === "punctuator") {
switch (token.value) {
case "{":
case "}":
return "curly";
case "(":
case ")":
return "parens";
case "[":
case "]":
return "square";
}
}
return token.type;
}
/**
* Highlight `text`.
*/
function highlight(text: string) {
return text.replace(jsTokens, function (...args) {
let type = getTokenType(args);
let colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map((str) => colorize(str)).join("\n");
} else {
return args[0];
}
});
}
/**
* Create a code frame, adding line numbers, code highlighting, and pointing to a given position.
*/
export default function (
rawLines: string,
lineNumber: number,
colNumber: ?number,
opts: Object = {},
): string {
colNumber = Math.max(colNumber, 0);
let highlighted = opts.highlightCode && chalk.supportsColor;
if (highlighted) rawLines = highlight(rawLines);
let linesAbove = opts.linesAbove || 2;
let linesBelow = opts.linesBelow || 3;
let lines = rawLines.split(NEWLINE);
let start = Math.max(lineNumber - (linesAbove + 1), 0);
let end = Math.min(lines.length, lineNumber + linesBelow);
if (!lineNumber && !colNumber) {
start = 0;
end = lines.length;
}
let numberMaxWidth = String(end).length;
let frame = lines.slice(start, end).map((line, index) => {
let number = start + 1 + index;
let paddedNumber = ` ${number}`.slice(-numberMaxWidth);
let gutter = ` ${paddedNumber} | `;
if (number === lineNumber) {
let markerLine = "";
if (colNumber) {
let markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " ");
markerLine = `\n ${gutter.replace(/\d/g, " ")}${markerSpacing}^`;
}
return `>${gutter}${line}${markerLine}`;
} else {
return ` ${gutter}${line}`;
}
}).join("\n");
if (highlighted) {
return chalk.reset(frame);
} else {
return frame;
}
}