diff --git a/src/Renderers/CodeNodeRenderer.php b/src/Renderers/CodeNodeRenderer.php index e554407d..fc54b415 100644 --- a/src/Renderers/CodeNodeRenderer.php +++ b/src/Renderers/CodeNodeRenderer.php @@ -62,7 +62,8 @@ public function render(): string $languages = array_unique([$language, $languageMapping]); if ('text' === $language) { - $highlightedCode = $code; + // Highlighter escapes correctly the code, we need to manually escape only for "text" code + $highlightedCode = $this->escapeForbiddenCharactersInsideCodeBlock($code); } else { $this->configureHighlighter(); @@ -117,23 +118,6 @@ public static function isLanguageSupported(string $lang): bool return \in_array($lang, $supportedLanguages, true); } - private function getLines(string $code): array - { - $lines = preg_split('/\r\n|\r|\n/', $code); - $reversedLines = array_reverse($lines); - - // trim empty lines at the end of the code - foreach ($reversedLines as $key => $line) { - if ('' !== trim($line)) { - break; - } - - unset($reversedLines[$key]); - } - - return array_reverse($reversedLines); - } - private function configureHighlighter() { if (false === self::$isHighlighterConfigured) { @@ -143,4 +127,15 @@ private function configureHighlighter() self::$isHighlighterConfigured = true; } + + /** + * Code blocks are displayed in "
" tags, which has some reserved characters: + * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre + */ + private function escapeForbiddenCharactersInsideCodeBlock(string $code): string + { + $codeEscaped = preg_replace('/&(?!amp;|lt;|gt;|quot;)/', '&', $code); + + return strtr($codeEscaped, ['<' => '<', '>' => '>', '"' => '"']); + } } diff --git a/tests/fixtures/expected/blocks/code-blocks/text.html b/tests/fixtures/expected/blocks/code-blocks/text.html index a30c3ed7..fe77dea1 100644 --- a/tests/fixtures/expected/blocks/code-blocks/text.html +++ b/tests/fixtures/expected/blocks/code-blocks/text.html @@ -1,6 +1,6 @@diff --git a/tests/fixtures/source/blocks/code-blocks/text.rst b/tests/fixtures/source/blocks/code-blocks/text.rst index 823ef77d..50774bb1 100644 --- a/tests/fixtures/source/blocks/code-blocks/text.rst +++ b/tests/fixtures/source/blocks/code-blocks/text.rst @@ -1,3 +1,3 @@ .. code-block:: text - some text + some text with special chars < > " & and some text with special chars already escaped < > " &1-+some text
some text with special chars < > " & and some text with special chars already escaped < > " &