From 824f4335fbeed73ebc2d09f3fb370a1993c2e478 Mon Sep 17 00:00:00 2001 From: Richard Dern Date: Mon, 22 Apr 2024 17:04:46 +0200 Subject: [PATCH] Fix: Empty lines in code blocks --- app/Services/Markdown/Formatter.php | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/app/Services/Markdown/Formatter.php b/app/Services/Markdown/Formatter.php index ec32a5f..5b75689 100644 --- a/app/Services/Markdown/Formatter.php +++ b/app/Services/Markdown/Formatter.php @@ -3,6 +3,7 @@ namespace App\Services\Markdown; use App\Services\Markdown\Renderers\LinkRenderer; +use DOMDocument; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Cache; use League\CommonMark\Environment\Environment; @@ -58,6 +59,7 @@ public function render(): string // Perform final adjustments like inserting non-breaking spaces $result = $this->insertNonBreakingSpaces($converted->getContent()); + $result = $this->removeEmptyCodeLines($result); // Cache::put($cacheKey, $result, now()->addMonth()); @@ -122,4 +124,32 @@ protected function insertNonBreakingSpaces(string $html): string // Perform the replacements and return the modified HTML return preg_replace($patterns, $replacements, $html); } + + /** + * For some reason, to date (04-2024), HighlightCodeExtension appends empty + * lines at the end of a code block. We need to get rid of them. + */ + protected function removeEmptyCodeLines(string $html): string + { + $body = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'); + + libxml_use_internal_errors(true); + + $dom = new DOMDocument('1.0', 'UTF-8'); + + $dom->loadHtml($body); + + libxml_clear_errors(); + + $xpath = new \DOMXPath($dom); + $spans = $xpath->query('//pre/code/span[@class="line" and not(node())]'); + + foreach ($spans as $span) { + if ($span->isSameNode($span->parentNode->lastChild)) { + $span->parentNode->removeChild($span); + } + } + + return $dom->saveHTML(); + } }