Skip to content

Commit d44defc

Browse files
jrfnlgrogy
authored andcommitted
Highlighter::getCodeSnippet(): bug fix - too many lines retrieved at start of file
When a code snippet in the middle of code is retrieved, the target snippet length calculation `$length = $linesAfter + $linesBefore + 1;` functions correctly, displaying the target line in the middle, padded by x number of lines before and after. Given `$linesBefore` and `$linesAfter` both being set to two, this would display as: ``` before before target after after ``` Similarly, when a code snippet at the end of the code is retrieved, it will work correctly as well, the target line is displayed with x number of lines before. The number of lines _after_ is limited automatically by the length of the `$tokenLines` array. Given `$linesBefore` and `$linesAfter` both being set to two, this would display as: ``` before before target ``` However, when a code snippet at the _start_ of the code is retrieved, the number of lines retrieved was incorrect. The target line would display with `($linesBefore + $linesAfter)` lines _after_ the target line. Given `$linesBefore` and `$linesAfter` both being set to two, this currently displays as: ``` target after after after after ``` ... while it should be: ``` target after after ``` The change in this commit fixes this bug.
1 parent 27dcb1d commit d44defc

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/Highlighter.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,13 @@ public function getCodeSnippet($source, $lineNumber, $linesBefore = 2, $linesAft
103103

104104
$offset = $lineNumber - $linesBefore - 1;
105105
$offset = max($offset, 0);
106-
$length = $linesAfter + $linesBefore + 1;
106+
107+
if ($lineNumber <= $linesBefore) {
108+
$length = $lineNumber + $linesAfter;
109+
} else {
110+
$length = $linesAfter + $linesBefore + 1;
111+
}
112+
107113
$tokenLines = array_slice($tokenLines, $offset, $length, $preserveKeys = true);
108114

109115
$lines = $this->colorLines($tokenLines);

0 commit comments

Comments
 (0)