Skip to content

Commit 0240cd6

Browse files
committed
Ignore out-of-range part of ranges
1 parent a94d6a5 commit 0240cd6

File tree

2 files changed

+13
-19
lines changed

2 files changed

+13
-19
lines changed

plugins/line-highlight/prism-line-highlight.js

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
var LINE_NUMBERS_CLASS = 'line-numbers';
88
var LINKABLE_LINE_NUMBERS_CLASS = 'linkable-line-numbers';
9+
var NEW_LINE_EXP = /\n(?!$)/g;
910

1011
/**
1112
* @param {string} selector
@@ -136,7 +137,8 @@
136137
var codeElement = pre.querySelector('code');
137138
var parentElement = hasLineNumbers ? pre : codeElement || pre;
138139
var mutateActions = /** @type {(() => void)[]} */ ([]);
139-
140+
var lineBreakMatch = codeElement.textContent.match(NEW_LINE_EXP);
141+
var numberOfLines = lineBreakMatch ? lineBreakMatch.length + 1 : 1;
140142
/**
141143
* The top offset between the content box of the <code> element and the content box of the parent element of
142144
* the line highlight element (either `<pre>` or `<code>`).
@@ -154,6 +156,11 @@
154156

155157
var start = +range[0];
156158
var end = +range[1] || start;
159+
end = Math.min(numberOfLines, end);
160+
161+
if (end < start) {
162+
return;
163+
}
157164

158165
/** @type {HTMLElement} */
159166
var line = pre.querySelector('.line-highlight[data-range="' + currentRange + '"]') || document.createElement('div');
@@ -168,13 +175,6 @@
168175
if (hasLineNumbers && Prism.plugins.lineNumbers) {
169176
var startNode = Prism.plugins.lineNumbers.getLine(pre, start);
170177
var endNode = Prism.plugins.lineNumbers.getLine(pre, end);
171-
// endNode is the `nthChild` th child of its parent node
172-
var nthChild = 1;
173-
var element = endNode;
174-
while (element.previousSibling) {
175-
element = element.previousSibling;
176-
nthChild++;
177-
}
178178

179179
if (startNode) {
180180
var top = startNode.offsetTop + codePreOffset + 'px';
@@ -184,16 +184,10 @@
184184
}
185185

186186
if (endNode) {
187-
// Ignore the line if it exceed range
188-
if (start === end && end > nthChild) {
189-
mutateActions.pop();
190-
return;
191-
} else {
192-
var height = (endNode.offsetTop - startNode.offsetTop) + endNode.offsetHeight + 'px';
193-
mutateActions.push(function () {
194-
line.style.height = height;
195-
});
196-
}
187+
var height = (endNode.offsetTop - startNode.offsetTop) + endNode.offsetHeight + 'px';
188+
mutateActions.push(function () {
189+
line.style.height = height;
190+
});
197191
}
198192
} else {
199193
mutateActions.push(function () {

plugins/line-highlight/prism-line-highlight.min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)