diff --git a/src/Plugin/Filter/MathjaxFilter.php b/src/Plugin/Filter/MathjaxFilter.php index a123d4b..06a573d 100644 --- a/src/Plugin/Filter/MathjaxFilter.php +++ b/src/Plugin/Filter/MathjaxFilter.php @@ -2,6 +2,7 @@ namespace Drupal\mathjax\Plugin\Filter; +use Drupal\Component\Serialization\Json; use Drupal\filter\Plugin\FilterBase; use Drupal\filter\FilterProcessResult; use Drupal\Core\Url; @@ -27,6 +28,11 @@ class MathjaxFilter extends FilterBase { * {@inheritdoc} */ public function process($text, $langcode) { + // Do nothing if the text has no formulas. + if (!$this->hasMathFormulas($text)) { + return new FilterProcessResult($text); + } + $wrapped = strip_tags($text) !== 'TEST' ? '
' . $text . '
' : $text; $result = new FilterProcessResult($wrapped); $config = \Drupal::config('mathjax.settings'); @@ -49,6 +55,35 @@ class MathjaxFilter extends FilterBase { return $result; } + /** + * Returns a flag whether given text contains math formulas. + * + * @param string $text + * The text to process. + * + * @return bool + * Returns TRUE if the given text contains formulas. Otherwise, FALSE. + */ + public function hasMathFormulas($text) { + $config = \Drupal::config('mathjax.settings'); + $default_configuration = Json::decode($config->get('default_config_string')); + $delimiters = isset($default_configuration['tex2jax']['inlineMath']) ? $default_configuration['tex2jax']['inlineMath'] : []; + $default_delimiters = [['$$', '$$'], ['\[', '\]']]; + $delimiters = array_merge($delimiters, $default_delimiters); + + foreach ($delimiters as $delimiter) { + list($start, $end) = $delimiter; + if (mb_strpos($text, $start) !== FALSE) { + return TRUE; + } + elseif ($end != $start && mb_strpos($text, $end) !== FALSE) { + return TRUE; + } + } + + return FALSE; + } + /** * {@inheritdoc} */