]> git.immae.eu Git - github/shaarli/Shaarli.git/blobdiff - application/formatter/BookmarkMarkdownFormatter.php
Support search highlights when matching URL content
[github/shaarli/Shaarli.git] / application / formatter / BookmarkMarkdownFormatter.php
index ee4e8dca4f993b9a6c02894e674150615e182315..d4dccee6231bbcaded94d215ca343b8be9ba6d0f 100644 (file)
@@ -3,6 +3,7 @@
 namespace Shaarli\Formatter;
 
 use Shaarli\Config\ConfigManager;
+use Shaarli\Formatter\Parsedown\ShaarliParsedown;
 
 /**
  * Class BookmarkMarkdownFormatter
@@ -42,7 +43,7 @@ class BookmarkMarkdownFormatter extends BookmarkDefaultFormatter
     {
         parent::__construct($conf, $isLoggedIn);
 
-        $this->parsedown = new \Parsedown();
+        $this->parsedown = new ShaarliParsedown();
         $this->escape = $conf->get('security.markdown_escape', true);
         $this->allowedProtocols = $conf->get('security.allowed_protocols', []);
     }
@@ -128,6 +129,9 @@ class BookmarkMarkdownFormatter extends BookmarkDefaultFormatter
     protected function formatHashTags($description)
     {
         $indexUrl = ! empty($this->contextData['index_url']) ? $this->contextData['index_url'] : '';
+        $tokens = '(?:' . BookmarkDefaultFormatter::SEARCH_HIGHLIGHT_OPEN . ')' .
+            '(?:' . BookmarkDefaultFormatter::SEARCH_HIGHLIGHT_CLOSE . ')'
+        ;
 
         /*
          * To support unicode: http://stackoverflow.com/a/35498078/1484919
@@ -136,8 +140,15 @@ class BookmarkMarkdownFormatter extends BookmarkDefaultFormatter
          * \p{L} - letter from any language
          * \p{Mn} - any non marking space (accents, umlauts, etc)
          */
-        $regex = '/(^|\s)#([\p{Pc}\p{N}\p{L}\p{Mn}]+)/mui';
-        $replacement = '$1[#$2](' . $indexUrl . './add-tag/$2)';
+        $regex = '/(^|\s)#([\p{Pc}\p{N}\p{L}\p{Mn}' . $tokens . ']+)/mui';
+        $replacement = function (array $match) use ($indexUrl): string {
+            $cleanMatch = str_replace(
+                BookmarkDefaultFormatter::SEARCH_HIGHLIGHT_OPEN,
+                '',
+                str_replace(BookmarkDefaultFormatter::SEARCH_HIGHLIGHT_CLOSE, '', $match[2])
+            );
+            return $match[1] . '[#' . $match[2] . '](' . $indexUrl . './add-tag/' . $cleanMatch . ')';
+        };
 
         $descriptionLines = explode(PHP_EOL, $description);
         $descriptionOut = '';
@@ -156,7 +167,7 @@ class BookmarkMarkdownFormatter extends BookmarkDefaultFormatter
             }
 
             if (!$codeBlockOn && !$codeLineOn) {
-                $descriptionLine = preg_replace($regex, $replacement, $descriptionLine);
+                $descriptionLine = preg_replace_callback($regex, $replacement, $descriptionLine);
             }
 
             $descriptionOut .= $descriptionLine;