1 |
|
2 |
|
3 | const range = 2
|
4 |
|
5 | export function generateCodeFrame (
|
6 | source: string,
|
7 | start: number = 0,
|
8 | end: number = source.length
|
9 | ): string {
|
10 | const lines = source.split(/\r?\n/)
|
11 | let count = 0
|
12 | const res = []
|
13 | for (let i = 0; i < lines.length; i++) {
|
14 | count += lines[i].length + 1
|
15 | if (count >= start) {
|
16 | for (let j = i - range; j <= i + range || end > count; j++) {
|
17 | if (j < 0 || j >= lines.length) continue
|
18 | res.push(`${j + 1}${repeat(` `, 3 - String(j + 1).length)}| ${lines[j]}`)
|
19 | const lineLength = lines[j].length
|
20 | if (j === i) {
|
21 |
|
22 | const pad = start - (count - lineLength) + 1
|
23 | const length = end > count ? lineLength - pad : end - start
|
24 | res.push(` | ` + repeat(` `, pad) + repeat(`^`, length))
|
25 | } else if (j > i) {
|
26 | if (end > count) {
|
27 | const length = Math.min(end - count, lineLength)
|
28 | res.push(` | ` + repeat(`^`, length))
|
29 | }
|
30 | count += lineLength + 1
|
31 | }
|
32 | }
|
33 | break
|
34 | }
|
35 | }
|
36 | return res.join('\n')
|
37 | }
|
38 |
|
39 | function repeat (str, n) {
|
40 | let result = ''
|
41 | if (n > 0) {
|
42 | while (true) {
|
43 | if (n & 1) result += str
|
44 | n >>>= 1
|
45 | if (n <= 0) break
|
46 | str += str
|
47 | }
|
48 | }
|
49 | return result
|
50 | }
|