UNPKG

@fink/snippet

Version:
48 lines (46 loc) 1.56 kB
import { pad_start } from "@fink/std-lib/str.js"; import { split } from "@fink/std-lib/regex.js"; import { map_ac, length, join, drop, take, insert_at } from "@fink/std-lib/iter.js"; import { clamp } from "@fink/std-lib/math.js"; export const default_opts = { lines: { before: 4, after: 3 } }; /* Highlight the `code` snippet at the given location `loc`. Optionally the number of lines before and after the highlighted location can be providerd by `options`. */ export const highlight_code_loc = (code, loc, options = default_opts) => { const { start, end } = loc; const { lines: { before, after } } = options; const min = before; const lines = split(code, `\n`); const max_lines = length(lines); const start_line = clamp(0, start.line - before, max_lines - min); const insert_line = start.line - start_line; const end_line = clamp(0, end.line + after, max_lines); const line_num_padding = length(`${end_line}`); const underline = pad_start(`^`, 3 + line_num_padding + start.column, ` `); { let ˆpipe_result_1 = lines; ˆpipe_result_1 = drop(start_line)(ˆpipe_result_1); ˆpipe_result_1 = take(end_line - start_line)(ˆpipe_result_1); ˆpipe_result_1 = map_ac((line, idx = 0) => { const line_num = pad_start(`${start_line + idx + 1}`, line_num_padding); return [`${line_num}| ${line}`, idx + 1]; })(ˆpipe_result_1); ˆpipe_result_1 = insert_at(insert_line, [underline])(ˆpipe_result_1); return ˆpipe_result_1 = join(`\n`)(ˆpipe_result_1); } };