2019-10-12 23:49:23 +00:00
|
|
|
const range: number = 2
|
|
|
|
|
|
|
|
export function generateCodeFrame(
|
|
|
|
source: string,
|
2019-12-13 23:01:04 +00:00
|
|
|
start = 0,
|
2019-12-19 20:42:53 +00:00
|
|
|
end = source.length
|
2019-10-12 23:49:23 +00:00
|
|
|
): string {
|
|
|
|
const lines = source.split(/\r?\n/)
|
|
|
|
let count = 0
|
2019-11-09 02:32:22 +00:00
|
|
|
const res: string[] = []
|
2019-10-12 23:49:23 +00:00
|
|
|
for (let i = 0; i < lines.length; i++) {
|
|
|
|
count += lines[i].length + 1
|
|
|
|
if (count >= start) {
|
|
|
|
for (let j = i - range; j <= i + range || end > count; j++) {
|
|
|
|
if (j < 0 || j >= lines.length) continue
|
2019-12-19 20:42:53 +00:00
|
|
|
const line = j + 1
|
2020-08-12 19:52:28 +00:00
|
|
|
res.push(
|
|
|
|
`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${
|
|
|
|
lines[j]
|
|
|
|
}`
|
|
|
|
)
|
2019-10-12 23:49:23 +00:00
|
|
|
const lineLength = lines[j].length
|
|
|
|
if (j === i) {
|
|
|
|
// push underline
|
|
|
|
const pad = start - (count - lineLength) + 1
|
2019-11-14 16:50:16 +00:00
|
|
|
const length = Math.max(
|
2019-12-19 20:42:53 +00:00
|
|
|
1,
|
2019-11-14 16:50:16 +00:00
|
|
|
end > count ? lineLength - pad : end - start
|
|
|
|
)
|
2019-10-12 23:49:23 +00:00
|
|
|
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length))
|
|
|
|
} else if (j > i) {
|
|
|
|
if (end > count) {
|
2019-12-19 20:42:53 +00:00
|
|
|
const length = Math.max(Math.min(end - count, lineLength), 1)
|
2019-10-12 23:49:23 +00:00
|
|
|
res.push(` | ` + '^'.repeat(length))
|
|
|
|
}
|
|
|
|
count += lineLength + 1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res.join('\n')
|
|
|
|
}
|