From 3407885b2cb14eab059a58ea158bf14ca57a5165 Mon Sep 17 00:00:00 2001 From: Nicolas PHILIPPE Date: Thu, 29 Dec 2022 11:35:27 +0100 Subject: [PATCH] fix: escape special chars in code text --- src/Renderers/CodeNodeRenderer.php | 31 ++++++++----------- .../expected/blocks/code-blocks/text.html | 2 +- .../source/blocks/code-blocks/text.rst | 2 +- 3 files changed, 15 insertions(+), 20 deletions(-) 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 @@
 
1
-
some text
+
some text with special chars < > " & and some text with special chars already escaped < > " &
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 < > " &