From e8212b66447a611cfda7dda56dbdd9cc869f42f3 Mon Sep 17 00:00:00 2001 From: Eric Rykwalder Date: Sat, 5 Mar 2022 21:13:13 -0500 Subject: [PATCH] add parsing for hashtags --- __tests__/extensions.ts | 13 +++++++++++++ src/extensions.ts | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/__tests__/extensions.ts b/__tests__/extensions.ts index e2567ad..d636f63 100644 --- a/__tests__/extensions.ts +++ b/__tests__/extensions.ts @@ -12,6 +12,9 @@ const specParser = new SpecParser(parser, { t: "TaskMarker", EM: "Embed", eM: "EmbedMark", + H: "Hashtag", + hm: "HashtagMark", + hl: "HashtagLabel", IL: "InternalLink", iM: "InternalMark", iP: "InternalPath", @@ -244,4 +247,14 @@ Line 5} {HR:---} ` ); + + test( + "Hashtag", + ` +{P:Some text. {H:{hm:#}{hl:tag}} {H:{hm:#}{hl:other-tag9}}^not part +{H:{hm:#}{hl:ñáø√}}} + +{P:Test number #1234} + ` + ); }); diff --git a/src/extensions.ts b/src/extensions.ts index 27e53ed..b300b41 100644 --- a/src/extensions.ts +++ b/src/extensions.ts @@ -1,4 +1,4 @@ -import { Input, PartialParse, Tree } from "@lezer/common"; +import { Input } from "@lezer/common"; import { BlockContext, Element, @@ -61,6 +61,36 @@ export const TaskList: MarkdownConfig = { }; /* End Copyright */ +const hashtagRE = + /^[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s]+/; + +export const Hashtag: MarkdownConfig = { + defineNodes: ["Hashtag", "HashtagMark", "HashtagLabel"], + parseInline: [ + { + name: "Hashtag", + parse(cx, next, pos) { + if (next != 35 /* # */) { + return -1; + } + const start = pos; + pos += 1; + const match = hashtagRE.exec(cx.text.slice(pos - cx.offset)); + if (match && /\D/.test(match[0])) { + pos += match[0].length; + return cx.addElement( + cx.elt("Hashtag", start, pos, [ + cx.elt("HashtagMark", start, start + 1), + cx.elt("HashtagLabel", start + 1, pos), + ]) + ); + } + return -1; + }, + }, + ], +}; + function parseInternalLink(cx: InlineContext, pos: number): Element | null { if ( cx.char(pos) != 91 /* [ */ || @@ -322,11 +352,12 @@ export const YAMLFrontMatter: MarkdownConfig = { export const ObsidianMDExtensions = [ Footnote, - YAMLFrontMatter, + Hashtag, InternalLink, Strikethrough, Table, TaskList, + YAMLFrontMatter, ]; export const parser = defParser.configure(ObsidianMDExtensions);