forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetCodeFrame.ts
36 lines (28 loc) · 888 Bytes
/
getCodeFrame.ts
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
import repeat from './repeat';
function tabsToSpaces(str: string) {
return str.replace(/^\t+/, match => match.split('\t').join(' '));
}
export default function getCodeFrame(
source: string,
line: number,
column: number
) {
const lines = source.split('\n');
const frameStart = Math.max(0, line - 2);
const frameEnd = Math.min(line + 3, lines.length);
const digits = String(frameEnd + 1).length;
return lines
.slice(frameStart, frameEnd)
.map((str, i) => {
const isErrorLine = frameStart + i === line;
let lineNum = String(i + frameStart + 1);
while (lineNum.length < digits) lineNum = ` ${lineNum}`;
if (isErrorLine) {
const indicator =
repeat(' ', digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
}
return `${lineNum}: ${tabsToSpaces(str)}`;
})
.join('\n');
}