|
6 | 6 |
|
7 | 7 | var LINE_NUMBERS_CLASS = 'line-numbers'; |
8 | 8 | var LINKABLE_LINE_NUMBERS_CLASS = 'linkable-line-numbers'; |
| 9 | + var NEW_LINE_EXP = /\n(?!$)/g; |
9 | 10 |
|
10 | 11 | /** |
11 | 12 | * @param {string} selector |
|
136 | 137 | var codeElement = pre.querySelector('code'); |
137 | 138 | var parentElement = hasLineNumbers ? pre : codeElement || pre; |
138 | 139 | var mutateActions = /** @type {(() => void)[]} */ ([]); |
139 | | - |
| 140 | + var lineBreakMatch = codeElement.textContent.match(NEW_LINE_EXP); |
| 141 | + var numberOfLines = lineBreakMatch ? lineBreakMatch.length + 1 : 1; |
140 | 142 | /** |
141 | 143 | * The top offset between the content box of the <code> element and the content box of the parent element of |
142 | 144 | * the line highlight element (either `<pre>` or `<code>`). |
|
154 | 156 |
|
155 | 157 | var start = +range[0]; |
156 | 158 | var end = +range[1] || start; |
| 159 | + end = Math.min(numberOfLines, end); |
| 160 | + |
| 161 | + if (end < start) { |
| 162 | + return; |
| 163 | + } |
157 | 164 |
|
158 | 165 | /** @type {HTMLElement} */ |
159 | 166 | var line = pre.querySelector('.line-highlight[data-range="' + currentRange + '"]') || document.createElement('div'); |
|
168 | 175 | if (hasLineNumbers && Prism.plugins.lineNumbers) { |
169 | 176 | var startNode = Prism.plugins.lineNumbers.getLine(pre, start); |
170 | 177 | 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 | | - } |
178 | 178 |
|
179 | 179 | if (startNode) { |
180 | 180 | var top = startNode.offsetTop + codePreOffset + 'px'; |
|
184 | 184 | } |
185 | 185 |
|
186 | 186 | 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 | + }); |
197 | 191 | } |
198 | 192 | } else { |
199 | 193 | mutateActions.push(function () { |
|
0 commit comments