Skip to content

Commit eb3230f

Browse files
tanhauhaunicolo-ribaudo
authored andcommitted
fix code-frame marker with highlighting (#10211)
1 parent 7dc5fdb commit eb3230f

File tree

2 files changed

+44
-4
lines changed

2 files changed

+44
-4
lines changed

packages/babel-code-frame/src/index.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ function getMarkerLines(
7676
} else if (i === 0) {
7777
const sourceLength = source[lineNumber - 1].length;
7878

79-
markerLines[lineNumber] = [startColumn, sourceLength - startColumn];
79+
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
8080
} else if (i === lineDiff) {
8181
markerLines[lineNumber] = [0, endColumn];
8282
} else {
@@ -112,15 +112,16 @@ export function codeFrameColumns(
112112
const maybeHighlight = (chalkFn, string) => {
113113
return highlighted ? chalkFn(string) : string;
114114
};
115-
if (highlighted) rawLines = highlight(rawLines, opts);
116-
117115
const lines = rawLines.split(NEWLINE);
118116
const { start, end, markerLines } = getMarkerLines(loc, lines, opts);
119117
const hasColumns = loc.start && typeof loc.start.column === "number";
120118

121119
const numberMaxWidth = String(end).length;
122120

123-
let frame = lines
121+
const highlightedLines = highlighted ? highlight(rawLines, opts) : rawLines;
122+
123+
let frame = highlightedLines
124+
.split(NEWLINE)
124125
.slice(start, end)
125126
.map((line, index) => {
126127
const number = start + 1 + index;

packages/babel-code-frame/test/index.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,45 @@ describe("@babel/code-frame", function() {
102102
);
103103
});
104104

105+
test("opts.highlightCode with multiple columns and lines", function() {
106+
// prettier-ignore
107+
const rawLines = [
108+
"function a(b, c) {",
109+
" return b + c;",
110+
"}"
111+
].join("\n");
112+
113+
const result = codeFrameColumns(
114+
rawLines,
115+
{
116+
start: {
117+
line: 1,
118+
column: 1,
119+
},
120+
end: {
121+
line: 3,
122+
column: 1,
123+
},
124+
},
125+
{
126+
highlightCode: true,
127+
message: "Message about things",
128+
},
129+
);
130+
const stripped = stripAnsi(result);
131+
expect(stripped).toEqual(
132+
// prettier-ignore
133+
[
134+
"> 1 | function a(b, c) {",
135+
" | ^^^^^^^^^^^^^^^^^^",
136+
"> 2 | return b + c;",
137+
" | ^^^^^^^^^^^^^^^",
138+
"> 3 | }",
139+
" | ^ Message about things",
140+
].join('\n'),
141+
);
142+
});
143+
105144
test("opts.linesAbove", function() {
106145
const rawLines = [
107146
"/**",

0 commit comments

Comments
 (0)