@@ -57,12 +57,15 @@ public function render(): string
5757 return $ code ;
5858 }
5959
60+ $ savedCode = $ code ;
61+
6062 $ language = $ this ->codeNode ->getLanguage () ?? 'php ' ;
6163 $ languageMapping = self ::LANGUAGES_MAPPING [$ language ] ?? $ language ;
6264 $ languages = array_unique ([$ language , $ languageMapping ]);
6365
6466 if ('text ' === $ language ) {
65- $ highlightedCode = $ code ;
67+ // Highlighter escapes correctly the code, we need to manually escape only for "text" code
68+ $ highlightedCode = $ this ->escapeForbiddenCharactersInsideCodeBlock ($ code );
6669 } else {
6770 $ this ->configureHighlighter ();
6871
@@ -117,23 +120,6 @@ public static function isLanguageSupported(string $lang): bool
117120 return \in_array ($ lang , $ supportedLanguages , true );
118121 }
119122
120- private function getLines (string $ code ): array
121- {
122- $ lines = preg_split ('/\r\n|\r|\n/ ' , $ code );
123- $ reversedLines = array_reverse ($ lines );
124-
125- // trim empty lines at the end of the code
126- foreach ($ reversedLines as $ key => $ line ) {
127- if ('' !== trim ($ line )) {
128- break ;
129- }
130-
131- unset($ reversedLines [$ key ]);
132- }
133-
134- return array_reverse ($ reversedLines );
135- }
136-
137123 private function configureHighlighter ()
138124 {
139125 if (false === self ::$ isHighlighterConfigured ) {
@@ -143,4 +129,15 @@ private function configureHighlighter()
143129
144130 self ::$ isHighlighterConfigured = true ;
145131 }
132+
133+ /**
134+ * Code blocks are displayed in "<pre>" tags, which has some reserved characters:
135+ * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
136+ */
137+ private function escapeForbiddenCharactersInsideCodeBlock (string $ code ): string
138+ {
139+ $ codeEscaped = preg_replace ('/&(?!amp;|lt;|gt;|quot;)/ ' , '& ' , $ code );
140+
141+ return strtr ($ codeEscaped , ['< ' => '< ' , '> ' => '> ' , '" ' => '" ' ]);
142+ }
146143}
0 commit comments