@fink/snippet
Version:
68 lines (61 loc) • 1.67 kB
JavaScript
const {
pad_start
} = require("@fink/std-lib/str.js");
const {
split
} = require("@fink/std-lib/regex.js");
const {
map_ac,
length,
join,
drop,
take,
insert_at
} = require("@fink/std-lib/iter.js");
const {
clamp
} = require("@fink/std-lib/math.js");
const default_opts = {
lines: {
before: 4,
after: 3
}
};
exports.default_opts = default_opts;
/*
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`.
*/
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);
}
};
exports.highlight_code_loc = highlight_code_loc;