« get me outta code hell

replacer, wiki-data: factor out matchMarkdownLinks - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/common-util
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2025-05-01 12:24:51 -0300
committer(quasar) nebula <qznebula@protonmail.com>2025-05-06 12:29:02 -0300
commit99c00eb298b9fb4ff9454250ff474a67d0713c13 (patch)
tree191651014f9c3d163eb84c1fc28346e53ea84ca9 /src/common-util
parenta46f1171c0e63ea670e14bf796f42642646d3ae7 (diff)
replacer, wiki-data: factor out matchMarkdownLinks
Diffstat (limited to 'src/common-util')
-rw-r--r--src/common-util/wiki-data.js27
1 files changed, 27 insertions, 0 deletions
diff --git a/src/common-util/wiki-data.js b/src/common-util/wiki-data.js
index c993f4ac..b21af786 100644
--- a/src/common-util/wiki-data.js
+++ b/src/common-util/wiki-data.js
@@ -523,3 +523,30 @@ export function combineWikiDataArrays(arrays) {
     return combined;
   }
 }
+
+// Markdown stuff
+
+export function* matchMarkdownLinks(markdownSource, {marked}) {
+  const plausibleLinkRegexp = /\[.*?\)/g;
+
+  let plausibleMatch = null;
+  while (plausibleMatch = plausibleLinkRegexp.exec(markdownSource)) {
+    // Pedantic rules use more particular parentheses detection in link
+    // destinations - they allow one level of balanced parentheses, and
+    // otherwise, parentheses must be escaped. This allows for entire links
+    // to be wrapped in parentheses, e.g below:
+    //
+    //   This is so cool. ([You know??](https://example.com))
+    //
+    const definiteMatch =
+      marked.Lexer.rules.inline.pedantic.link
+        .exec(markdownSource.slice(plausibleMatch.index));
+
+    if (definiteMatch) {
+      const [{length}, label, href] = definiteMatch;
+      const index = plausibleMatch.index + definiteMatch.index;
+
+      yield {label, href, index, length};
+    }
+  }
+}