public function FilterSyntaxHighlighter::prepare in Syntax Highlighter 8
Escape the content text in preparation for filtering.
- Change all syntaxhighlighter <pre> tag pairs to {-_sYnTaXhIgHlIgHtEr_-} {/-_sYnTaXhIgHlIgHtEr_-} pair (so other filters would not mess with them.
Precondition: all the open/close tags much match because search is done on a pair by pair basis. If match is not even, do nothing.
All HTML tags and entities inside the SyntaxHighlighter must be properly escaped.
For example, in HTML code, change:
- '<' to '<': e.g. <pre> -> <pre>, <html> -> <html>
- neutralize & in entity: e.g.: > -> &gt;
Overrides FilterBase::prepare
File
- src/
Plugin/ Filter/ FilterSyntaxHighlighter.php, line 40
Class
- FilterSyntaxHighlighter
- Provides a filter to highlight source code.
Namespace
Drupal\syntaxhighlighter\Plugin\FilterCode
public function prepare($text, $langcode) {
$config = \Drupal::config('syntaxhighlighter.settings');
$tag_name = $config
->get('tagname');
$pattern = "#<{$tag_name}\\s*([^>]*)>|</\\s*{$tag_name}>#";
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
$output = '';
$at = 0;
$n = count($matches);
// Do nothing if open/close tag match is not even.
if ($n % 2 !== 0) {
return $text;
}
for ($i = 0; $i < $n; $i += 2) {
$open_tag = $matches[$i];
$close_tag = $matches[$i + 1];
if (strpos($open_tag[1][0], 'brush:')) {
$output .= substr($text, $at, $open_tag[0][1] - $at);
$begin = $open_tag[0][1] + strlen($open_tag[0][0]);
$length = $close_tag[0][1] - $begin;
$output .= '{' . SYNTAXHIGHLIGHTER_TAG_STRING . ' ' . $open_tag[1][0] . '}' . substr($text, $begin, $length) . '{/' . SYNTAXHIGHLIGHTER_TAG_STRING . '}';
$at = $close_tag[0][1] + strlen($close_tag[0][0]);
}
}
$output .= substr($text, $at);
return $output;
}