From 67c2777d9bfdd5a8775491f945d2c6defa822321 Mon Sep 17 00:00:00 2001 From: Vishesh Handa Date: Mon, 8 Jun 2020 00:51:13 +0200 Subject: [PATCH] Parse links in wiki syntax [[term]] This way we can use this faster syntax which is also supported by Obsidian. --- lib/core/link.dart | 22 ++++++++++++++++++++++ lib/core/note.dart | 6 ++++++ test/note_test.dart | 20 ++++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/lib/core/link.dart b/lib/core/link.dart index 36232599..e3ad3f05 100644 --- a/lib/core/link.dart +++ b/lib/core/link.dart @@ -51,6 +51,14 @@ class LinkExtractor implements md.NodeVisitor { var url = el.attributes['href']; var link = Link(term: title, filePath: url); links.add(link); + return; + } + + if (tag == 'wikiLink') { + var value = el.attributes['value']; + var link = Link(term: value, filePath: null); + links.add(link); + return; } } @@ -61,3 +69,17 @@ class LinkExtractor implements md.NodeVisitor { return links; } } + +class MetaLinkSyntax extends md.InlineSyntax { + static final String _pattern = '\\[\\[([^\\[\\]]+)\\]\\]'; + + MetaLinkSyntax() : super(_pattern); + + @override + bool onMatch(md.InlineParser parser, Match match) { + md.Element el = md.Element.withTag('wikiLink'); + el.attributes['value'] = '${match[1].trim()}'; + parser.addNode(el); + return true; + } +} diff --git a/lib/core/note.dart b/lib/core/note.dart index 6ebf5bc6..a60df64f 100644 --- a/lib/core/note.dart +++ b/lib/core/note.dart @@ -450,6 +450,7 @@ class Note with NotesNotifier { final doc = md.Document( encodeHtml: false, extensionSet: md.ExtensionSet.gitHubFlavored, + inlineSyntaxes: [MetaLinkSyntax()], ); var lines = body.replaceAll('\r\n', '\n').split('\n'); @@ -459,6 +460,11 @@ class Note with NotesNotifier { var links = []; for (var l in possibleLinks) { var path = l.filePath; + if (path == null) { + links.add(l); + continue; + } + var isLocal = (path.startsWith('/') || path.startsWith('.')) && !path.contains('://'); if (isLocal) { diff --git a/test/note_test.dart b/test/note_test.dart index b62d9ef9..4398140a 100644 --- a/test/note_test.dart +++ b/test/note_test.dart @@ -140,6 +140,26 @@ title: Foo expect(links.length, 2); }); + test('Should parse wiki style links', () async { + var content = "[[GitJournal]] needs some [[Wild Fire]]"; + + var notePath = p.join(tempDir.path, "note63.md"); + await File(notePath).writeAsString(content); + + var parentFolder = NotesFolderFS(null, tempDir.path); + var note = Note(parentFolder, notePath); + await note.load(); + + var links = await note.fetchLinks(); + expect(links[0].filePath, null); + expect(links[0].term, "GitJournal"); + + expect(links[1].filePath, null); + expect(links[1].term, "Wild Fire"); + + expect(links.length, 2); + }); + test('Should detect file format', () async { var content = """--- title: Foo