Compare commits

...

115 Commits

Author SHA1 Message Date
Riccardo Ferretti
ee7a891976 v0.15.0 2021-10-04 10:05:46 +02:00
Riccardo Ferretti
680e317dbf Preparation for 0.15.0 2021-10-04 10:05:15 +02:00
Riccardo Ferretti
dbb46369a2 Added Project Manager to recommended extensions list (reported by @readingsnail) 2021-09-14 18:49:04 +02:00
Riccardo Ferretti
562da95f90 Bump fast-array-diff from 1.0.0 to 1.0.1 2021-09-14 18:37:32 +02:00
Riccardo Ferretti
fc03e07eeb removed extra file 2021-09-14 18:24:09 +02:00
Riccardo Ferretti
ccea5666bf fixed CI workflow (caching) 2021-09-14 18:23:39 +02:00
dannysemi
2a7a909ac5 Issue #530: Introduced DAT in dataviz view, and sending properties to it (#737)
* Introduced DAT.ui

* Sending properties and tags to graph for better data handling
2021-09-13 17:33:49 +02:00
Paul de Raaij
efac46174a Proposal and basic feature to include notes into a note (#741)
* Add the functionality to include notes in a note

* Add proposal of embedding

* Add tests for including notes

* Add documentation for inclusion feature
2021-09-13 17:23:40 +02:00
Riccardo Ferretti
4c5d996586 minor change in hash computation for CI 2021-09-13 17:17:28 +02:00
Jonas SPRENGER
6de0024b0b bugfix/705: replacing Indexable Types with Map (#729)
* bugfix/705: replacing Indexable Types with Map

* test for resources/placeholders named like JS proto properties

Co-authored-by: Jonas <jojo@srg.com>
2021-09-13 17:10:46 +02:00
allcontributors[bot]
70b0fae078 docs: add JonasSprenger as a contributor for code (#763)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-09-06 23:31:54 +02:00
Jonas SPRENGER
fd9bf8f04f Implement hover feature for wikilinks (#728)
* Implement hover feature for wikilinks

* Make hover configuration reactive
2021-09-06 23:31:04 +02:00
allcontributors[bot]
630a77782d docs: add ksprashu as a contributor for doc (#756)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-09-01 21:19:08 +02:00
Prashanth Subrahmanyam
6fdce389e9 Update recommended extensions based on template (#755) 2021-09-01 21:18:08 +02:00
allcontributors[bot]
9ce5a9528f docs: add theowenyoung as a contributor for doc, content (#753)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-08-31 19:51:03 +02:00
Owen Young
ca821d3928 Add another gatsby template (#752)
Add foam-template-gatsby-theme-primer-wiki
2021-08-31 19:49:05 +02:00
allcontributors[bot]
9dacadedfc docs: add Pearcekieser as a contributor for doc (#750)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-08-27 13:06:34 +02:00
Pearcekieser
0c07e7535e Add Recommended Extension: TODO Tree (#748)
issue: #740
2021-08-27 13:05:55 +02:00
Riccardo Ferretti
dddc379f2b fix 734: improved logging in markdown-provider 2021-07-28 11:51:38 +02:00
Riccardo
e83740d65a Tags improvements (#733)
* No longer parsing tags inside codeblocks

* fixed linting

* Using Tag data structure in Resource
2021-07-28 11:45:19 +02:00
Riccardo Ferretti
eddd9de665 foam-vscode to use latest foam-core 2021-07-25 15:57:31 +02:00
Riccardo Ferretti
7f6004dd6d v0.14.2 2021-07-24 10:20:31 +02:00
Riccardo Ferretti
1258cef04c Preparation for 0.14.2 2021-07-24 10:19:16 +02:00
Paul de Raaij
7adbffcfc2 Introduce autocompletion for tags (#708) 2021-07-24 00:10:42 +02:00
Michael Overmeyer
8395a408f2 Make navigating to a placeholder wikilink use the default template (#712) 2021-07-23 16:50:32 +02:00
Michael Overmeyer
721a6cc935 Standardize on wikilink, MediaWiki, and GitHub (#716)
* Standardize on `wikilink`

Not `wiki-link`, nor `wiki link`

https://en.wikipedia.org/wiki/Help:Link#Wikilinks

* Standardize on `MediaWiki`

Not `media-wiki`, nor `mediawiki`

https://www.mediawiki.org/wiki/MediaWiki

* Standardize on `GitHub`

Not `Github`

Co-authored-by: Riccardo <code@riccardoferretti.com>
2021-07-22 00:19:35 +02:00
Paul de Raaij
1659fe37d9 Respect the ignore globs when searching all files (#730) 2021-07-21 11:22:23 +02:00
Riccardo Ferretti
32f9120864 updated link to log output in bug template 2021-07-18 16:37:32 +02:00
Michael Overmeyer
cec0aecd06 Remove Markdown Notes from recommended extensions (#722) 2021-07-17 21:03:45 +02:00
Riccardo Ferretti
c59584d342 v0.14.1 2021-07-15 01:24:25 +02:00
Riccardo Ferretti
ea930d3d17 preparation for 0.14.1 2021-07-15 01:21:11 +02:00
Paul de Raaij
130b839ee9 Add a null check to prevent preview to break (#718) 2021-07-15 01:11:07 +02:00
Riccardo Ferretti
1b4dc8a8b1 v0.14.0 2021-07-13 13:50:25 +02:00
Riccardo Ferretti
7fcbf1acf1 Preparation for 0.14.0 2021-07-13 13:48:44 +02:00
Michael Overmeyer
011706904b Make daily notes use templates (#700) 2021-07-13 12:24:48 +02:00
Michael Overmeyer
c14e1e6349 Migrate create-from-template to use Foam's URI instead of VSCode's Uri (#709) 2021-07-12 23:24:21 +02:00
Paul de Raaij
97629a2ce6 Removes escape character of an alias when setting target (#697)
* Removes escape character of an alias when setting WikiLink target

* Alter tearDown of document-link-provider test

* Disable link reference defintion generation for all tests
2021-07-12 22:41:33 +02:00
Paul de Raaij
6b3eef43a8 Allows wikilinks to be opened in the editor again (#710) 2021-07-12 20:49:25 +02:00
Paul de Raaij
d4adce6730 Adds FAQ about enabling and disabling Foam (#706)
* Adss FAQ about enabling and disabling Foam

* Update frequently-asked-questions.md
2021-07-12 19:16:57 +02:00
allcontributors[bot]
ae65f53540 docs: add rafo as a contributor for doc (#703)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-07-06 12:57:30 +02:00
Rafael Riedel
8998204298 Update recommended-extensions.md (#702)
Changed "Mermaid Support for Preview" to the extensions new name: "Markdown Preview Mermaid Support"
2021-07-06 12:56:46 +02:00
Michael Overmeyer
92f6e001e5 Fix implicit insertion of FOAM_SELECTED_TEXT (#701)
* Only do the insertion when necessary.
* Insert using the correct whitespace.
2021-07-06 00:37:39 +02:00
Paul de Raaij
889f93a7e1 Move selected text into a new note and auto create a backlink (#666)
template and functionality to use selected text in a new note
2021-07-04 20:44:22 +02:00
Paul de Raaij
4db8c55969 Only remove link definition token that contain an alias divider (#698)
* be more conservative in removing link definitions

* Update packages/foam-vscode/src/features/preview-navigation.ts

Co-authored-by: Riccardo <code@riccardoferretti.com>

Co-authored-by: Riccardo <code@riccardoferretti.com>
2021-07-04 20:38:52 +02:00
Riccardo Ferretti
7e740fec0f v0.13.8 2021-07-02 20:02:27 +02:00
Riccardo Ferretti
beae852c21 Prepare for next release 2021-07-02 19:48:52 +02:00
Paul de Raaij
85e857d973 handle different capitalizations of wikilinks and files (#688) 2021-07-02 19:41:24 +02:00
José Duarte
667eee0e10 Add documentation to the dated-notes.ts file (#690)
* Add docs to `createDailyNoteDirectoryIfNotExists`

* Add docs to `createDailyNoteIfNotExists`

* Capitalize doc strings

* Add docs to `getDailyNoteFileName`

* Update the @configuration parameter docs

* Add docs to `getDailyNotePath`

* Add docs to `openDailyNoteFor`

* Update packages/foam-vscode/src/dated-notes.ts

Co-authored-by: Michael Overmeyer <michael.overmeyer@shopify.com>

* Update packages/foam-vscode/src/dated-notes.ts

Co-authored-by: Michael Overmeyer <michael.overmeyer@shopify.com>

* Polish some of the comments

Co-authored-by: José Duarte <jmg.duarte@campus.fct.unl.pt!>
Co-authored-by: Michael Overmeyer <michael.overmeyer@shopify.com>
2021-06-28 14:55:14 +02:00
dependabot[bot]
b6e68b3605 Bump glob-parent from 5.1.1 to 5.1.2 in /packages/foam-core (#678)
Bumps [glob-parent](https://github.com/gulpjs/glob-parent) from 5.1.1 to 5.1.2.
- [Release notes](https://github.com/gulpjs/glob-parent/releases)
- [Changelog](https://github.com/gulpjs/glob-parent/blob/main/CHANGELOG.md)
- [Commits](https://github.com/gulpjs/glob-parent/compare/v5.1.1...v5.1.2)

---
updated-dependencies:
- dependency-name: glob-parent
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-24 23:57:34 +02:00
Paul de Raaij
b9b0f9b515 Allow for dots in wikilinks (#689) 2021-06-24 23:20:03 +02:00
dependabot[bot]
95399977ec Bump hosted-git-info from 2.8.8 to 2.8.9 (#686)
Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](https://github.com/npm/hosted-git-info/compare/v2.8.8...v2.8.9)

---
updated-dependencies:
- dependency-name: hosted-git-info
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 18:15:13 +02:00
dependabot[bot]
f759e7cd6e Bump ws from 5.2.2 to 5.2.3 in /packages/foam-core (#685)
Bumps [ws](https://github.com/websockets/ws) from 5.2.2 to 5.2.3.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/5.2.2...5.2.3)

---
updated-dependencies:
- dependency-name: ws
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-06-21 18:14:46 +02:00
Riccardo Ferretti
5839455535 fixed bug in date snippet
thanks to @syndenham-chorea for reporting and directing the fix
see https://discord.com/channels/729975036148056075/729975036664086560/855628250414972998
2021-06-21 00:28:45 +02:00
Riccardo Ferretti
7e4ae82fe1 updated foam-core dependency 2021-06-21 00:25:13 +02:00
Scott Bronson
e47155424f doc: describe how to select launch configuration (#674) 2021-06-12 00:19:57 +02:00
allcontributors[bot]
903a191394 docs: add bronson as a contributor for doc (#677)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-06-12 00:17:33 +02:00
Scott Bronson
5c6212dc96 remove broken link to adding-a-new-command (#675)
This file was removed by deb77328c0 last Dec.
2021-06-12 00:16:05 +02:00
Paul de Raaij
bca9756e2b Revive support for basic link alias (#656)
* Add support for basic link aliases

* Refactor to future link model

* Refactor preview behavior for aliases

* Refactore use of NoteSource

* Remove references from ref block  before processing links

Co-authored-by: Jani Eväkallio <jani.evakallio@gmail.com>
2021-06-09 23:07:10 +02:00
Riccardo Ferretti
2e435a3828 v0.13.7 2021-06-05 15:53:16 +02:00
Riccardo Ferretti
a0f83e7510 refactored code to avoid circular dependency 2021-06-05 15:50:04 +02:00
Riccardo Ferretti
641024b01b added dependency on replace-ext (fix for #667 we hope..) 2021-06-05 15:49:34 +02:00
Riccardo Ferretti
c5a7d02656 include ES2019 library in tsconfig for vscode package 2021-06-05 15:30:35 +02:00
Riccardo Ferretti
b76196cd23 removed Foam local plugin experimental feature 2021-06-05 15:17:23 +02:00
Riccardo Ferretti
61ae468a70 v0.13.6 2021-06-05 14:58:22 +02:00
Riccardo Ferretti
6119278915 Removed support for Foam local plugins 2021-06-05 14:51:16 +02:00
Riccardo Ferretti
34c179123e v0.13.5 2021-06-05 00:30:24 +02:00
Riccardo Ferretti
c34394a0ea prepare for 0.13.5 2021-06-05 00:28:38 +02:00
Riccardo Ferretti
26c38a06ff fixes #665 - always access files in .foam/templates directory when looking for templates 2021-06-04 15:29:33 +02:00
Michael Overmeyer
d4623a2d91 Allow for YAML metadata in templates (#655)
* Add a frontmatter metadata parser

* Use the template metadata to determine the filepath to use

* Document template metadata

* Add name and description template metadata attributes

These are displayed in the template picker

* Document name and description template metadata attributes
2021-06-04 15:27:46 +02:00
dependabot[bot]
2f9507dc87 Bump ws from 7.3.1 to 7.4.6 in /packages/foam-vscode (#662)
Bumps [ws](https://github.com/websockets/ws) from 7.3.1 to 7.4.6.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/7.3.1...7.4.6)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-31 20:59:09 +02:00
Paul de Raaij
4db09070a8 Filter out tag references that are part of a nested tag (#661)
* Filter out tagreferences that are part fo a nested tag

* add test case for notes with parent and child tag
2021-05-31 20:57:40 +02:00
Riccardo Ferretti
5f99d9d5c6 v0.13.4 2021-05-26 13:39:18 +02:00
Riccardo Ferretti
9c1480197c Preparation for 0.13.4 2021-05-26 13:16:49 +02:00
Riccardo Ferretti
f1a6426046 updated documentation to reflect nested tags 2021-05-26 09:18:30 +02:00
Riccardo Ferretti
6de8baa6b5 updated yarn.lock 2021-05-26 09:18:01 +02:00
Riccardo Ferretti
27ff023a26 fix loading of markdownIt extensions 2021-05-26 09:12:14 +02:00
Paul de Raaij
690eb10856 Add support for nested tags (#643)
* Add support for nested tags

* Adds test for feature
2021-05-26 09:11:39 +02:00
Michael Overmeyer
1cb8174a9f Always ask for the note title when creating from template (#645)
* Fix snake_case to camelCase

* Always ask for the note title when creating from the default template

In the future, we'll make this conditional on whether the template provides the filepath to use in its metadata block
2021-05-22 21:46:47 +02:00
allcontributors[bot]
2141bac24a docs: add pderaaij as a contributor (#650)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-05-22 21:39:50 +02:00
Paul de Raaij
6abef8f8e7 Allow for optionality in title prop in frontmatter (#647) 2021-05-22 21:39:03 +02:00
dependabot[bot]
c797a00223 Bump nokogiri from 1.11.1 to 1.11.5 in /docs (#646)
Bumps [nokogiri](https://github.com/sparklemotion/nokogiri) from 1.11.1 to 1.11.5.
- [Release notes](https://github.com/sparklemotion/nokogiri/releases)
- [Changelog](https://github.com/sparklemotion/nokogiri/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sparklemotion/nokogiri/compare/v1.11.1...v1.11.5)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-20 15:35:51 +02:00
José Duarte
7c01fb13f0 Upgrade force-graph to 1.40.5 (#642) 2021-05-20 11:14:15 +02:00
dependabot[bot]
abbc2bbb14 Bump lodash from 4.17.19 to 4.17.21 in /packages/foam-core (#628)
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.19 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.19...4.17.21)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-14 11:28:11 +02:00
dependabot[bot]
bb7fee24bb Bump hosted-git-info from 2.8.8 to 2.8.9 in /packages/foam-core (#629)
Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](https://github.com/npm/hosted-git-info/compare/v2.8.8...v2.8.9)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-14 11:27:22 +02:00
dependabot[bot]
43ef3a3e2b Bump lodash from 4.17.20 to 4.17.21 in /packages/foam-vscode (#630)
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.20 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.20...4.17.21)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-14 11:26:59 +02:00
dependabot[bot]
da69a3057f Bump hosted-git-info from 2.8.8 to 2.8.9 in /packages/foam-vscode (#631)
Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](https://github.com/npm/hosted-git-info/compare/v2.8.8...v2.8.9)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-14 11:26:29 +02:00
Riccardo
2d06f26bbf fix #638 link to license page 2021-05-13 15:55:54 +02:00
Riccardo
edbe128e1e fix #546 - title yaml property can also be a number 2021-05-13 13:09:09 +02:00
Riccardo Ferretti
af0c2bbaa3 v0.13.3 2021-05-11 21:40:56 +02:00
Riccardo Ferretti
700bfc1b26 addressing windows issue with provider matching (related to #617) 2021-05-11 21:25:25 +02:00
Riccardo Ferretti
a6d5c04453 improve bootstrap performance
we wait to create the graph, as changes to the workspace will cause it to be recomputed.
so, first load all resources from the initial providers, then compute the graph.
2021-05-11 21:22:19 +02:00
Riccardo Ferretti
b0c42cead2 setting logging level to error for all tests 2021-05-11 21:12:38 +02:00
Riccardo Ferretti
6c643adb9d Prepare for 0.13.3 2021-05-09 23:13:27 +02:00
Riccardo Ferretti
ca7fdefaae improvemets in matcher and linting 2021-05-09 23:13:27 +02:00
Riccardo Ferretti
149d5f5a7c fix #617 - fixed error in file matching in MarkdownProvider 2021-05-09 22:50:42 +02:00
Michael Overmeyer
be80857fd1 Handle users cancelling "Create New Note" commands (#623) 2021-05-09 22:50:18 +02:00
Michael Overmeyer
611fa7359d Completely ignore unknown Foam variables (#622)
If we don't know it we shouldn't touch it
Previously it replaced the variable with the variables name
2021-05-09 18:23:06 +02:00
Riccardo Ferretti
08b7e7a231 fixed isMarkdown function to check the .md extension (related to #617) 2021-05-07 23:53:14 +02:00
Riccardo Ferretti
0a259168c7 fix #618: properly printing file name 2021-05-07 22:58:44 +02:00
Riccardo Ferretti
f3d0569c76 fixed Barabazs contributor name 2021-05-06 12:26:22 +02:00
Riccardo Ferretti
502129d5ac v0.13.2 2021-05-06 10:10:51 +02:00
Riccardo Ferretti
d29bf16db1 prepare 0.13.2 2021-05-06 10:10:22 +02:00
Riccardo Ferretti
d228c7cb18 fixed test 2021-05-06 10:04:00 +02:00
Riccardo Ferretti
78078cf338 improved foam settings 2021-05-06 10:04:00 +02:00
Riccardo Ferretti
fe65883bc5 fix #600 - clicking on notes in placeholder and orphan panels now navigates to them 2021-05-06 10:04:00 +02:00
allcontributors[bot]
20b5261c5c docs: add EngincanV as a contributor (#615)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-05-06 10:02:12 +02:00
Engincan VESKE
f91cfe5d0d Update capture-notes-with-shortcuts-and-github-actions.md (#613) 2021-05-06 10:01:42 +02:00
Michael Overmeyer
1ab9cc5f4a Add streamline "Create new note" command (#601)
* Add new `Create New Note` command
It is the streamlined counterpart to `Create New Note From Template`

* Simplify the variable Regex
\W is equivalent to [^A-Za-z0-9_]
2021-05-03 13:48:14 +02:00
allcontributors[bot]
02ff681700 docs: add Barabazs as a contributor (#610)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-05-03 13:20:26 +02:00
Barabas
2d9c3be0e6 Add support for stylable tags (#598) 2021-05-03 13:19:37 +02:00
Robin King
78cf602347 fix: (#592) extra autocomplete hints outside wiki-link brackets (#596) 2021-05-03 13:02:28 +02:00
dependabot[bot]
898c7b4387 Bump rexml from 3.2.4 to 3.2.5 in /docs (#607)
Bumps [rexml](https://github.com/ruby/rexml) from 3.2.4 to 3.2.5.
- [Release notes](https://github.com/ruby/rexml/releases)
- [Changelog](https://github.com/ruby/rexml/blob/master/NEWS.md)
- [Commits](https://github.com/ruby/rexml/compare/v3.2.4...v3.2.5)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-05-03 11:40:40 +02:00
Riccardo
7412d518d7 Spike on FoamWorkspace and DataStore refactor (#593)
* extracted graph from workspace

* refactored datastore

* dataviz to use URI for placeholder detection

* graph uses uris, not resources

* adding placeholder in graph

* link completion to use graph

* API v1 - Resource refactoring (#595)

* aside: tweaked jest extension configuration

* added provider for markdown

* removed file check in URI

the problem is that it makes the URI dependent on the disk, which makes testing harder.
The change was originally introduced to prevent Foam from treating directories ending in .md as markdown files, but the check needs to probably happen somewhere else, e.g. in `FileDataStore.list` - or directories should be expressed with a trailing slash (to check whether that breaks the URI convention)

* Various changes

- `resolveLink` now delegates to providers
- added `read` method in providers and `FoamWorkspace`
- improved `Matcher` API
- updated tests to use workspace with providers
- delegating more to workspace now it can read files (simplifies wiring and exposed API surface)
- provider init returns a promise, so it can be awaited on
- `IDataStore` now has `list` method, to encapsulate all access to FS

* improved windows support in URI and matcher

* improved grouped resources interface

* added readAsMarkdown in provider, useful for tooltip generation with preview in vscode
2021-04-30 16:50:16 +02:00
allcontributors[bot]
e6030ac562 docs: add daniel-vera-g as a contributor (#603)
* docs: update docs/index.md [skip ci]

* docs: update readme.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-04-25 23:58:47 +02:00
Daniel VG
d6d958bc92 Docs: Fix markdown formatting issues (#599)
* Fix: Right links and formatting

* Docs: Run markdownlint to automatically fix minor formatting errors

* Style: Format with markdownlint and not prettier
2021-04-25 23:58:02 +02:00
150 changed files with 8809 additions and 6130 deletions

View File

@@ -661,6 +661,97 @@
"contributions": [
"doc"
]
},
{
"login": "daniel-vera-g",
"name": "Daniel VG",
"avatar_url": "https://avatars.githubusercontent.com/u/28257108?v=4",
"profile": "https://github.com/daniel-vera-g",
"contributions": [
"doc"
]
},
{
"login": "Barabazs",
"name": "Barabas",
"avatar_url": "https://avatars.githubusercontent.com/u/31799121?v=4",
"profile": "https://github.com/Barabazs",
"contributions": [
"code"
]
},
{
"login": "EngincanV",
"name": "Engincan VESKE",
"avatar_url": "https://avatars.githubusercontent.com/u/43685404?v=4",
"profile": "http://enginveske@gmail.com",
"contributions": [
"doc"
]
},
{
"login": "pderaaij",
"name": "Paul de Raaij",
"avatar_url": "https://avatars.githubusercontent.com/u/495374?v=4",
"profile": "http://www.paulderaaij.nl",
"contributions": [
"code"
]
},
{
"login": "bronson",
"name": "Scott Bronson",
"avatar_url": "https://avatars.githubusercontent.com/u/1776?v=4",
"profile": "https://github.com/bronson",
"contributions": [
"doc"
]
},
{
"login": "rafo",
"name": "Rafael Riedel",
"avatar_url": "https://avatars.githubusercontent.com/u/41793?v=4",
"profile": "http://rafaelriedel.de",
"contributions": [
"doc"
]
},
{
"login": "Pearcekieser",
"name": "Pearcekieser",
"avatar_url": "https://avatars.githubusercontent.com/u/5055971?v=4",
"profile": "https://github.com/Pearcekieser",
"contributions": [
"doc"
]
},
{
"login": "theowenyoung",
"name": "Owen Young",
"avatar_url": "https://avatars.githubusercontent.com/u/62473795?v=4",
"profile": "https://github.com/theowenyoung",
"contributions": [
"doc",
"content"
]
},
{
"login": "ksprashu",
"name": "Prashanth Subrahmanyam",
"avatar_url": "https://avatars.githubusercontent.com/u/476729?v=4",
"profile": "http://www.prashu.com",
"contributions": [
"doc"
]
},
{
"login": "JonasSprenger",
"name": "Jonas SPRENGER",
"avatar_url": "https://avatars.githubusercontent.com/u/25108895?v=4",
"profile": "https://github.com/JonasSprenger",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7,

View File

@@ -20,4 +20,4 @@ labels: bug
Feel free to attach any of the following that might help with debugging the issue:
- screenshots
- a zip with a minimal repo to reproduce the issue
- the Foam log in VsCode (see [instructions](https://github.com/foambubble/foam/blob/master/docs/foam-logging-in-vscode.md))
- the Foam log in VsCode (see [instructions](https://github.com/foambubble/foam/blob/master/docs/features/foam-logging-in-vscode.md))

View File

@@ -27,7 +27,7 @@ jobs:
node_modules
*/*/node_modules
packages/foam-vscode/.vscode-test
key: ${{ runner.os }}-${{ hashFiles('**/yarn.lock') }}-${{ hashFiles('packages/foam-vscode/src/test/run-tests.ts') }}
key: ${{ runner.os }}-${{ hashFiles('**/yarn.lock', 'packages/foam-vscode/src/test/run-tests.ts') }}
- name: Install Dependencies
run: yarn
- name: Check Lint Rules
@@ -55,7 +55,7 @@ jobs:
node_modules
*/*/node_modules
packages/foam-vscode/.vscode-test
key: ${{ runner.os }}-${{ hashFiles('**/yarn.lock') }}-${{ hashFiles('packages/foam-vscode/src/test/run-tests.ts') }}
key: ${{ runner.os }}-${{ hashFiles('**/yarn.lock', 'packages/foam-vscode/src/test/run-tests.ts') }}
- name: Install Dependencies
run: yarn
- name: Build Packages

15
.vscode/settings.json vendored
View File

@@ -12,20 +12,21 @@
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off",
"foam.edit.linkReferenceDefinitions": "withExtensions",
"foam.files.ignore": [
"**/.vscode/**/*",
"**/_layouts/**/*",
"**/_site/**/*",
"**/node_modules/**/*"
"**/node_modules/**/*",
"packages/**/*"
],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"prettier.requireConfig": true,
"editor.formatOnSave": true,
"editor.tabSize": 2,
"jest.debugCodeLens.showWhenTestStateIn": [
"fail",
"unknown",
"pass"
],
"gitdoc.enabled": false
"jest.debugCodeLens.showWhenTestStateIn": ["fail", "unknown", "pass"],
"gitdoc.enabled": false,
"jest.autoEnable": false,
"jest.runAllTestsFirst": false,
"search.mode": "reuseEditor"
}

View File

@@ -14,9 +14,6 @@
// Tons of markdown goodies (lists, tables of content, so much more)
"yzhang.markdown-all-in-one",
// [[wiki-links]], backlinking etc
"kortina.vscode-markdown-notes",
// Graph visualizer
"tchayen.markdown-links",

View File

@@ -3,9 +3,10 @@
Well, that shouldn't have happened!
If you got here via a link from another document, please file an [issue](https://github.com/foambubble/foam/issues) on our GitHub repo including:
- the page you came from
- the link you followed
Thanks!
-The Foam Team
-The Foam Team

View File

@@ -203,14 +203,14 @@ GEM
rb-fsevent (~> 0.10, >= 0.10.3)
rb-inotify (~> 0.9, >= 0.9.10)
mercenary (0.3.6)
mini_portile2 (2.5.0)
mini_portile2 (2.5.1)
minima (2.5.1)
jekyll (>= 3.5, < 5.0)
jekyll-feed (~> 0.9)
jekyll-seo-tag (~> 2.1)
minitest (5.14.2)
multipart-post (2.1.1)
nokogiri (1.11.1)
nokogiri (1.11.5)
mini_portile2 (~> 2.5.0)
racc (~> 1.4)
octokit (4.19.0)
@@ -223,7 +223,7 @@ GEM
rb-fsevent (0.10.4)
rb-inotify (0.10.1)
ffi (~> 1.0)
rexml (3.2.4)
rexml (3.2.5)
rouge (3.23.0)
ruby-enum (0.8.0)
i18n

View File

@@ -19,21 +19,21 @@ window.addEventListener('DOMContentLoaded', (event) => {
document
.querySelectorAll(".markdown-body a[title]:not([href^=http])")
.forEach((a) => {
// filter to only wiki-links
// filter to only wikilinks
var prev = a.previousSibling;
var next = a.nextSibling;
if (
prev instanceof Text && prev.textContent.endsWith('[') &&
prev instanceof Text && prev.textContent.endsWith('[') &&
next instanceof Text && next.textContent.startsWith(']')
) {
// remove surrounding brackets
prev.textContent = prev.textContent.slice(0, -1);
next.textContent = next.textContent.slice(1);
// add CSS list for styling
a.classList.add('wikilink');
// replace page-link with "Page Title"...
a.innerText = a.title;

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

View File

@@ -12,7 +12,6 @@
- What use cases are we working towards?
-[[todo]] User round table
[//begin]: # "Autogenerated link references for markdown compatibility"
[todo]: dev/todo.md "Todo"
[//end]: # "Autogenerated link references"
[//end]: # "Autogenerated link references"

View File

@@ -118,7 +118,7 @@ the community.
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
<https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
@@ -126,7 +126,5 @@ enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
<https://www.contributor-covenant.org/faq>. Translations are available at
<https://www.contributor-covenant.org/translations>.

View File

@@ -2,18 +2,22 @@
tags: todo, good-first-task
---
# Contribution Guide
Foam is open to contributions of any kind, including but not limited to code, documentation, ideas, and feedback.
This guide aims to help guide new and seasoned contributors getting around the Foam codebase.
## Getting Up To Speed
Before you start contributing we recommend that you read the following links:
- [[principles]] - This document describes the guiding principles behind Foam.
- [[code-of-conduct]] - Rules we hope every contributor aims to follow, allowing everyone to participate in our community!
## Diving In
We understand that diving in an unfamiliar codebase may seem scary,
to make it easier for new contributors we provide some resources:
- [[architecture]] - This document describes the architecture of Foam and how the repository is structured.
You can also see [existing issues](https://github.com/foambubble/foam/issues) and help out!
@@ -41,6 +45,7 @@ You should now be ready to start working!
Code needs to come with tests.
We use the following convention in Foam:
- *.test.ts are unit tests
- *.spec.ts are integration tests
@@ -51,16 +56,12 @@ Tests in `foam-vscode` live alongside the code in `src`.
This guide assumes you read the previous instructions and you're set up to work on Foam.
1. Now we'll use the launch configuration defined at [`.vscode/launch.json`](https://github.com/foambubble/foam/blob/master/.vscode/launch.json) to start a new extension host of VS Code. From the root, or the `foam-vscode` workspace, press f5.
1. Now we'll use the launch configuration defined at [`.vscode/launch.json`](https://github.com/foambubble/foam/blob/master/.vscode/launch.json) to start a new extension host of VS Code. Open the "Run and Debug" Activity (the icon with the bug on the far left) and select "Run VSCode Extension" in the pop-up menu. Now hit F5 or click the green arrow "play" button to fire up a new copy of VS Code with your extension installed.
2. In the new extension host of VS Code that launched, open a Foam workspace (e.g. your personal one, or a test-specific one created from [foam-template](https://github.com/foambubble/foam-template)). This is strictly not necessary, but the extension won't auto-run unless it's in a workspace with a `.vscode/foam.json` file.
3. Test a command to make sure it's working as expected. Open the Command Palette (Ctrl/Cmd + Shift + P) and select "Foam: Update Markdown Reference List". If you see no errors, it's good to go!
For more resources related to the VS Code Extension, check out the links below:
- [[tutorial-adding-a-new-command-to-the-vs-code-extension]]
---
Feel free to modify and submit a PR if this guide is out-of-date or contains errors!

View File

@@ -6,11 +6,13 @@ tags: architecture
This document aims to provide a quick overview of the Foam architecture!
Foam code and documentation live in the monorepo at [foambubble/foam](https://github.com/foambubble/foam/).
- [/docs](https://github.com/foambubble/foam/tree/master/docs): documentation and [[recipes]].
- [/packages/foam-core](https://github.com/foambubble/foam/tree/master/packages/foam-core) - Powers the core functionality in Foam across all platforms.
- [/packages/foam-vscode](https://github.com/foambubble/foam/tree/master/packages/foam-vscode) - The core VSCode plugin.
Exceptions to the monorepo are:
- The starter template at [foambubble/foam-template](https://github.com/foambubble/)
- All other [[recommended-extensions]] live in their respective GitHub repos.
- [foam-cli](https://github.com/foambubble/foam-cli) - The Foam CLI tool.

View File

@@ -10,5 +10,3 @@ But there's also a bunch of roadmap items that are hard to implement this way, a
Overall, we should strive to build big things from small things. Focused, interoperable modules are better, because they allow users to pick and mix which features work for them. A good example of why this matters is the Markdown All In One extension we rely on: While it provides many of the things we need, a few of its features are incompatible with how I would like to work, and therefore it becomes a limiter of how well I can improve my own workflow.
However, there becomes a point where we may benefit from implementing a centralised solution, e.g. a syntax, an extension or perhaps a VSCode language server. As much as possible, we should allow users to operate in a decentralised manner.

View File

@@ -17,7 +17,7 @@
`foam-core`'s primary responsibility is to build an API on top of a workspace of markdown files, which allows us to:
- Treat files as a graph, based on links
- Can be either [[wiki-links]] or relative `[markdown](links.md)` style
- Can be either [[wikilinks]] or relative `[markdown](links.md)` style
- We need to know about the edges (connections) as well as nodes
- What link points to what other file, etc.
- Needs to have the exact link text, e.g. even if `[[some-page]]` or `[[some-page.md]]` or `[[Some Page]]` point to the same document (`./some-page.md`), we need to know which format was used, so [[link-reference-definitions]] can be generated correctly
@@ -61,7 +61,7 @@ Here are some example use cases that the core should support. They don't need to
- Adding and editing page content
- [[materialized-backlinks]]
- [[link-reference-definitions]] for [[wiki-links]]
- [[link-reference-definitions]] for [[wikilinks]]
- [Frontmatter](https://jekyllrb.com/docs/front-matter/)
- Finding all documents with `#tag`
- Finding all documents with instances of `[[link]]`
@@ -99,7 +99,7 @@ Useful for knowing what needs to be supported. See [[feature-comparison]].
[workspace-janitor]: ../features/workspace-janitor.md "Janitor"
[cli]: ../features/cli.md "Command Line Interface"
[build-vs-assemble]: build-vs-assemble.md "Build vs Assemble"
[wiki-links]: ../wiki-links.md "Wiki Links"
[wikilinks]: ../wikilinks.md "Wikilinks"
[link-reference-definitions]: ../features/link-reference-definitions.md "Link Reference Definitions"
[materialized-backlinks]: materialized-backlinks.md "Materialized Backlinks (stub)"
[todo]: todo.md "Todo"

View File

@@ -1,16 +1,16 @@
# Foam File Format
This file is an example of a valid Foam file. Essentially it's just a markdown file with a bit of additional support for mediawiki-style `[[wiki-links]]`.
This file is an example of a valid Foam file. Essentially it's just a markdown file with a bit of additional support for MediaWiki-style `[[wikilinks]]`.
Here are a few specific constraints, mainly because our tooling is a bit fragmented. Most of these should be eventually lifted, and our requirement should just be "Markdown with `[[wiki-links]]`:
Here are a few specific constraints, mainly because our tooling is a bit fragmented. Most of these should be eventually lifted, and our requirement should just be "Markdown with `[[wikilinks]]`:
- **The first top level `# Heading` will be used as title for the note.**
- If not available, we will use the file name
- **File name should have extension `.md`**
- This is a temporary limitation and will be lifted in future versions.
- At least `.mdx` will be supported, but ideally we'll support any file that you can map to `Markdown` language mode in VS Code
- **In addition to normal Markdown Links syntax you can use `[[media-wiki]]` links.** See [[wiki-links]] for more details.
- **In addition to normal Markdown Links syntax you can use `[[MediaWiki]]` links.** See [[wikilinks]] for more details.
[//begin]: # "Autogenerated link references for markdown compatibility"
[wiki-links]: ../wiki-links.md "Wiki Links"
[wikilinks]: ../wikilinks.md "Wikilinks"
[//end]: # "Autogenerated link references"

View File

@@ -4,13 +4,13 @@
### File-by-file Insertion
For the time being, if you want to get [[wiki-links]] into all files within the workspace, you'll need to generate the link reference definitions yourself file-by-file (with the assistance of Foam).
For the time being, if you want to get [[wikilinks]] into all files within the workspace, you'll need to generate the link reference definitions yourself file-by-file (with the assistance of Foam).
### Wikilinks don't work on GitHub
> **TL;DR;** [workaround](#workaround) in the end of the chapter.
If you click any of the wiki-links on GitHub web UI (such as the `README.md` of a project), you'll notice that the links break with a 404 error.
If you click any of the wikilinks on GitHub web UI (such as the `README.md` of a project), you'll notice that the links break with a 404 error.
At the time of writing (June 28 2020) this is a known, but unsolved error. To understand why this is the case, we need to understand what we are trading off.
@@ -59,7 +59,7 @@ Problem space in essence:
- may clutter the search results
- During build-time (when converting markdown to html for publishing purposes)
- link reference definitions are needed, if the files are published via such tools (or to such platforms) that don't understand wikilinks
- link reference definitions might have to be in different formats depending on the publish target (e.g. Github pages vs Github UI)
- link reference definitions might have to be in different formats depending on the publish target (e.g. GitHub pages vs GitHub UI)
The potential solution:
@@ -72,6 +72,7 @@ The potential solution:
- This would be a GitHub action (or a local script, ran via foam-cli) that outputs publish-friendly markdown format for static site generators and other publishing tools
- This build step should be pluggable, so that other transformations could be ran during it
- Have publish targets defined in settings, that support both turning the link reference definitions on/off and defining their format (.md or not). Example draft (including also edit-time aspect):
```typescript
// settings json
// see enumerations below for explanations on values
@@ -120,8 +121,9 @@ The potential solution:
}
```
- With Foam repo, just use edit-time link reference definitions with '.md' extension - this makes the links work in the Github UI
- Have publish target defined for Github pages, that doesn't use '.md' extension, but still has the link reference definitions. Generate the output into gh-pages branch (or separate repo) with automation.
- With Foam repo, just use edit-time link reference definitions with '.md' extension - this makes the links work in the GitHub UI
- Have publish target defined for GitHub pages, that doesn't use '.md' extension, but still has the link reference definitions. Generate the output into gh-pages branch (or separate repo) with automation.
- This naturally requires first removing the existing link reference definitions during the build
- Other
- To clean up the search results, remove link reference definition section guards (assuming that these are not defined by the markdown spec). Use unifiedjs parse trees to identify if there's missing (or surplus) definitions (check if they are identified properly by the library), and just add the needed definitions to the bottom of the file (without guards) AND remove them if they are not needed (anywhere from the file).
@@ -135,7 +137,7 @@ UI-wise, the publish targets could be picked in some similar fashion as the run/
- [tracking issue on GitHub](https://github.com/foambubble/foam/issues/16)
[//begin]: # "Autogenerated link references for markdown compatibility"
[wiki-links]: ../wiki-links.md "Wiki Links"
[wikilinks]: ../wikilinks.md "Wikilinks"
[link-reference-definitions]: ../features/link-reference-definitions.md "Link Reference Definitions"
[backlinking]: ../features/backlinking.md "Backlinking"
[//end]: # "Autogenerated link references"

View File

@@ -11,8 +11,7 @@ The idea would be to automatically generate lists of backlinks (and optionally,
- Make every link two-way navigable in published sites
- Make Foam notes more portable to different apps and long-term storage
[//begin]: # "Autogenerated link references for markdown compatibility"
[todo]: todo.md "Todo"
[roadmap]: roadmap.md "Roadmap"
[//end]: # "Autogenerated link references"
[//end]: # "Autogenerated link references"

View File

@@ -25,7 +25,7 @@ If a roadmap item is a stub, **consider** opening a [GitHub issue](https://githu
- [[improve-default-workspace-settings]]
- Discussion: [foam#270](https://github.com/foambubble/foam/issues/270)
- Improve [[git-integration]]
- Fix [[wiki-links]] compatibility issues
- Fix [[wikilinks]] compatibility issues
- Simplify [[foam-file-format]]
### Core features
@@ -87,7 +87,7 @@ The community is working on a number of automated scripts to help you migrate to
[recipes]: ../recipes/recipes.md "Recipes"
[contribution-guide]: ../contribution-guide.md "Contribution Guide"
[git-integration]: ../features/git-integration.md "Git Integration"
[wiki-links]: ../wiki-links.md "Wiki Links"
[wikilinks]: ../wikilinks.md "Wikilinks"
[foam-file-format]: foam-file-format.md "Foam File Format"
[unlinked-references]: unlinked-references.md "Unlinked references (stub)"
[make-backlinks-more-prominent]: ../recipes/make-backlinks-more-prominent.md "Make Backlinks More Prominent"

View File

@@ -1,6 +1,6 @@
# Backlinking
When using [[wiki-links]], you can find all notes that link to a specific note in the [VS Code Markdown Notes](https://marketplace.visualstudio.com/items?itemName=kortina.vscode-markdown-notes) **Backlinks Explorer**
When using [[wikilinks]], you can find all notes that link to a specific note in the [VS Code Markdown Notes](https://marketplace.visualstudio.com/items?itemName=kortina.vscode-markdown-notes) **Backlinks Explorer**
- Run `Cmd` + `Shift` + `P` (`Ctrl` + `Shift` + `P` for Windows), type "backlinks" and run the **Explorer: Focus on Backlinks** view.
- Keep this pane always visible to discover relationships between your thoughts
@@ -8,7 +8,7 @@ When using [[wiki-links]], you can find all notes that link to a specific note i
- Finding backlinks in published Foam workspaces via [[materialized-backlinks]] is on the [[roadmap]] but not yet implemented.
[//begin]: # "Autogenerated link references for markdown compatibility"
[wiki-links]: ../wiki-links.md "Wiki Links"
[wikilinks]: ../wikilinks.md "Wikilinks"
[make-backlinks-more-prominent]: ../recipes/make-backlinks-more-prominent.md "Make Backlinks More Prominent"
[materialized-backlinks]: ../dev/materialized-backlinks.md "Materialized Backlinks (stub)"
[roadmap]: ../dev/roadmap.md "Roadmap"

View File

@@ -1,12 +1,14 @@
# Creating New Notes
- Write out a new `[[wiki-link]]` and `Cmd` + `Click` to create a new file and enter it.
- Write out a new `[[wikilink]]` and `Cmd` + `Click` to create a new file and enter it.
- For keyboard navigation, use the 'Follow Definition' key `F12` (or [remap key binding](https://code.visualstudio.com/docs/getstarted/keybindings) to something more ergonomic)
- `Cmd` + `Shift` + `P` (`Ctrl` + `Shift` + `P` for Windows), execute `New Note` from [VS Code Markdown Notes](https://marketplace.visualstudio.com/items?itemName=kortina.vscode-markdown-notes) and enter a **Title Case Name** to create `title-case-name.md`
- `Cmd` + `Shift` + `P` (`Ctrl` + `Shift` + `P` for Windows), execute `Foam: Create New Note` and enter a **Title Case Name** to create `Title Case Name.md`
- Add a keyboard binding to make creating new notes easier.
- The [[note-templates]] used by this command can be customized.
- You shouldn't worry too much about categorizing your notes. You can always [[search-for-notes]], and explore them using the [[graph-visualisation]].
[//begin]: # "Autogenerated link references for markdown compatibility"
[search-for-notes]: ../recipes/search-for-notes.md "Search for Notes"
[graph-visualisation]: graph-visualisation.md "Graph Visualisation"
[note-templates]: note-templates "Note Templates"
[search-for-notes]: ../recipes/search-for-notes "Search for Notes"
[graph-visualisation]: graph-visualisation "Graph Visualisation"
[//end]: # "Autogenerated link references"

View File

@@ -13,3 +13,19 @@ For example, to load a stylesheet called `Style.css`, we can update `settings.js
"markdown.styles": ["Style.css"]
}
```
## Foam elements
### Foam note & placeholder links
It is possible to custom style the links to a note or placeholder. The links are an `<a>` tag. For notes use the class `foam-note-link`, for placeholders use `foam-placeholder-link`.
### Cyclic inclusion warnings
Foams offers the functionality to include other notes in your note. This will be displayed in the preview tab. Foam recognises a cyclic inclusion of notes and will display a warning when detected. The following html is used and can be custom styled using the class `foam-cyclic-link-warning`.
```html
<div class="foam-cyclic-link-warning">
Cyclic link detected for wikilink: ${wikilink}
</div>
```

View File

@@ -25,9 +25,9 @@ The above configuration would create a file `journal/note-2020-07-25.mdx`, with
## Daily Note Templates
In the future, Foam may provide a functionality for specifying a template for new Daily Notes and other types of documents.
Daily notes can also make use of [templates](note-templates.md), by defining a special `.foam/templates/daily-note.md` template.
In the meantime, you can use [VS Code Snippets](https://code.visualstudio.com/docs/editor/userdefinedsnippets) for defining your own Daily Note template.
See [Note Templates](note-templates.md) for details of the features available in templates.
## Roam-style Automatic Daily Notes

View File

@@ -1,60 +0,0 @@
# Foam Local Plugins
Foam can use workspace plugins to provide customization for users.
## ATTENTION
This feature is experimental and its API subject to change.
**Local plugins can execute arbitrary code on your machine** - ensure you trust the content of the repo.
## Goal
Here are some of the things that we could enable with local plugins in Foam:
- extend the document syntax to support roam style attributes (e.g. `stage:: seedling`)
- automatically add tags to my notes based on the location in the repo (e.g. notes in `/areas/finance` will automatically get the `#finance` tag)
- add a new CLI command to support some internal use case or automate import/export
- extend the VSCode experience to support one's own workflow, e.g. weekly note, templates, extra panels, foam model derived TOC, ... all without having to write/deploy a VSCode extension
## How to enable local plugins
Plugins can execute arbitrary code on the client's machine.
For this reason this feature is disabled by default, and needs to be explicitly enabled.
To enable the feature:
- create a `~/.foam/config.json` file
- add the following content to the file
```
{
"experimental": {
"localPlugins": {
"enabled": true
}
}
}
```
For security reasons this setting can only be defined in the user settings file.
(otherwise a malicious repo could set it via its `./foam/config.json`)
- [[todo]] an additional security mechanism would involve having an explicit list of whitelisted repo paths where plugins are allowed. This would provide finer grain control over when to enable or disable the feature.
## Technical approach
When Foam is loaded it will check whether the experimental local plugin feature is enabled, and in such case it will:
- check `.foam/plugins` directory.
- each directory in there is considered a plugin
- the layout of each directory is
- `index.js` contains the main info about the plugin, specifically it exports:
- `name: string` the name of the plugin
- `description?: string` the description of the plugin
- `parser?: ParserPlugin` an object that interacts with the markdown parsing phase
Currently for simplicity we keep everything in one file. We might in the future split the plugin by domain (e.g. vscode, cli, core, ...)
[//begin]: # 'Autogenerated link references for markdown compatibility'
[todo]: ../dev/todo.md 'Todo'
[//end]: # 'Autogenerated link references'

View File

@@ -1,19 +1,21 @@
# Foam logging in VsCode
## Find the Foam log
The Foam log can be found in the `Output` tab.
1. To show the tab, click on `View > Output`.
2. In the dropdown on the right of the tab, select `Foam`.
![Find the foam log](../assets/images/foam-log.png)
## Change the default logging level
1. Open workspace settings (`cmd+,`, or execute the `Preferences: Open Workspace Settings` command)
2. Look for the entry `Foam > Logging: Level`
Set to debug when reporting an issue
## Change the log level for the session
Execute the command `Foam: Set log level`.

View File

@@ -3,6 +3,7 @@
Foam comes with a graph visualisation of your notes. To see the graph execute the `Foam: Show Graph` command.
The graph will:
- allow you to highlight a node by hovering on it, to quickly see how it's connected to the rest of your notes
- allow you to select one or more (by keeping `SHIFT` pressed while selecting) nodes by clicking on them, to better understand the structure of your notes
- allow you to navigate to a note by clicking on it while pressing `CTRL` or `CMD`
@@ -32,6 +33,7 @@ A sample configuration object is provided below:
```
### Style nodes by type
It is possible to customize the style of a node based on the `type` property in the YAML frontmatter of the corresponding document.
For example the following `backlinking.md` note:
@@ -46,6 +48,7 @@ type: feature
```
And the following `settings.json`:
```json
"foam.graph.style": {
"node": {
@@ -57,6 +60,3 @@ And the following `settings.json`:
Will result in the following graph:
![Style node by type](../assets/images/style-node-by-type.png)

View File

@@ -0,0 +1,20 @@
# Including notes in a note
In some situations it might be useful to include the content of another note in your current note. Foam supports this displaying within the vscode environment. Note, this does not work out-of-the-box for your publishing solutions.
## Including a note
Including a note can be done by adding an `!` before a wikilink defintion. For example `![[wikilink]]`.
## Custom styling
Displaying the inclusion of notes allows for some custom styling, see [[custom-markdown-preview-styles]]
## Future possibilities
Work on this feature is evolving and progressing. See the [[inclusion-of-notes]] proposal for the current discussion.
[//begin]: # "Autogenerated link references for markdown compatibility"
[custom-markdown-preview-styles]: custom-markdown-preview-styles.md "Custom Markdown Preview Styles"
[inclusion-of-notes]: ../proposals/inclusion-of-notes.md "Inclusion of notes Proposal "
[//end]: # "Autogenerated link references"

View File

@@ -2,27 +2,31 @@
## Introduction
When you use `[[wiki-links]]`, the [foam-vscode](https://github.com/foambubble/foam/tree/master/packages/foam-vscode) extension will automatically generate [Markdown Link Reference Definitions](https://spec.commonmark.org/0.29/#link-reference-definitions) at the bottom of the file. This is done to make the content of the file compatible with various Markdown tools (e.g. parsers, static site generators, VS code plugins etc), which don't support `[[wiki-links]]`.
When you use `[[wikilinks]]`, the [foam-vscode](https://github.com/foambubble/foam/tree/master/packages/foam-vscode) extension will automatically generate [Markdown Link Reference Definitions](https://spec.commonmark.org/0.29/#link-reference-definitions) at the bottom of the file. This is done to make the content of the file compatible with various Markdown tools (e.g. parsers, static site generators, VS code plugins etc), which don't support `[[wikilinks]]`.
## Example
The following example:
```md
- [[wiki-links]]
- [[wikilinks]]
- [[github-pages]]
```
...generates the following link reference definitions to the bottom of the file:
```md
[wiki-links]: wiki-links "Wiki Links"
[github-pages]: github-pages "Github Pages"
[wikilinks]: wikilinks "Wikilinks"
[github-pages]: github-pages "GitHub Pages"
```
You can open the [raw markdown](https://foambubble.github.io/foam/features/link-reference-definitions.md) to see them at the bottom of this file
## Specification
The three components of a link reference definition are `[link-label]: link-target "Link Title"`
- **link label:** The link text to match in the surrounding markdown document. This matches the inner bracket of the double-bracketed `[[wiki-link]]` notation
- **link label:** The link text to match in the surrounding markdown document. This matches the inner bracket of the double-bracketed `[[wikilink]]` notation
- **link destination** The target of the matched link
- By default we generate links without extension. This can be overridden, see [Configuration](#configuration) below
- **"Link Title"** Optional title for link (The Foam template has a snippet of JavaScript to replace this on the website at runtime)
@@ -67,7 +71,6 @@ After changing the setting in your workspace, you can run the [[workspace-janito
See [[link-reference-definition-improvements]] for further discussion on current problems and potential solutions.
[//begin]: # "Autogenerated link references for markdown compatibility"
[workspace-janitor]: workspace-janitor.md "Janitor"
[todo]: ../dev/todo.md "Todo"

View File

@@ -1,27 +1,158 @@
# Note Templates
Foam supports note templates.
Foam supports note templates. Templates are a way to customize the starting content for your notes (instead of always starting from an empty note).
Note templates live in `.foam/templates`. Run the `Foam: Create New Template` command from the command palette or create a regular `.md` file there to add a template.
Note templates are files located in the special `.foam/templates` directory.
## Quickstart
Create a template:
* Run the `Foam: Create New Template` command from the command palette
* OR manually create a regular `.md` file in the `.foam/templates` directory
![Create new template GIF](../assets/images/create-new-template.gif)
_Theme: Ayu Light_
To create a note from a template, execute the `Foam: Create New Note From Template` command and follow the instructions. Don't worry if you've not created a template yet! You'll be prompted to create a new template if none exist.
To create a note from a template:
* Run the `Foam: Create New Note From Template` command and follow the instructions. Don't worry if you've not created a template yet! You'll be prompted to create a new template if none exist.
* OR run the `Foam: Create New Note` command, which uses the special default template (`.foam/templates/new-note.md`, if it exists)
![Create new note from template GIF](../assets/images/create-new-note-from-template.gif)
_Theme: Ayu Light_
### Variables
## Special templates
### Default template
The `.foam/templates/new-note.md` template is special in that it is the template that will be used by the `Foam: Create New Note` command.
Customize this template to contain content that you want included every time you create a note.
### Default daily note template
The `.foam/templates/daily-note.md` template is special in that it is the template that will be used when creating daily notes (e.g. by using `Foam: Open Daily Note`).
Customize this template to contain content that you want included every time you create a daily note.
## Variables
Templates can use all the variables available in [VS Code Snippets](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables).
In addition, you can also use variables provided by Foam:
| Name | Description |
| ------------ | ----------------------------------------------------------------------------------- |
| `FOAM_TITLE` | The title of the note. If used, Foam will prompt you to enter a title for the note. |
| Name | Description |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `FOAM_SELECTED_TEXT` | Foam will fill it with selected text when creating a new note, if any text is selected. Selected text will be replaced with a wikilink to the new note. |
| `FOAM_TITLE` | The title of the note. If used, Foam will prompt you to enter a title for the note. |
**Note:** neither the defaulting feature (eg. `${variable:default}`) nor the format feature (eg. `${variable/(.*)/${1:/upcase}/}`) (available to other variables) are available for these Foam-provided variables.
## Metadata
Templates can also contain metadata about the templates themselves. The metadata is defined in YAML "Frontmatter" blocks within the templates.
| Name | Description |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `filepath` | The filepath to use when creating the new note. If the filepath is a relative filepath, it is relative to the current workspace. |
| `name` | A human readable name to show in the template picker. |
| `description` | A human readable description to show in the template picker. |
Foam-specific variables (e.g. `$FOAM_TITLE`) can be used within template metadata. However, VS Code snippet variables are ([currently](https://github.com/foambubble/foam/pull/655)) not supported.
### `filepath` attribute
The `filepath` metadata attribute allows you to define a relative or absolute filepath to use when creating a note using the template.
If the filepath is a relative filepath, it is relative to the current workspace.
**Note:** While you can make use of the `filepath` attribute in [daily note](daily-notes.md) templates (`.foam/templates/daily-note.md`), there is currently no way to have `filepath` vary based on the date. This will be improved in the future. For now, you can customize the location of daily notes using the [`foam.openDailyNote` settings](daily-notes.md).
#### Example of relative `filepath`
For example, `filepath` can be used to customize `.foam/templates/new-note.md`, overriding the default `Foam: Create New Note` behaviour of opening the file in the same directory as the active file:
```yaml
---
# This will create the note in the "journal" subdirectory of the current workspace,
# regardless of which file is the active file.
foam_template:
filepath: 'journal/$FOAM_TITLE.md'
---
```
#### Example of absolute `filepath`
`filepath` can be an absolute filepath, so that the notes get created in the same location, regardless of which file or workspace the editor currently has open.
The format of an absolute filepath may vary depending on the filesystem used.
```yaml
---
foam_template:
# Unix / MacOS filesystems
filepath: '/Users/john.smith/foam/journal/$FOAM_TITLE.md'
# Windows filesystems
filepath: 'C:\Users\john.smith\Documents\foam\journal\$FOAM_TITLE.md'
---
```
### `name` and `description` attributes
These attributes provide a human readable name and description to be shown in the template picker (e.g. When a user uses the `Foam: Create New Note From Template` command):
![Template Picker annotated with attributes](../assets/images/template-picker-annotated.png)
### Adding template metadata to an existing YAML Frontmatter block
If your template already has a YAML Frontmatter block, you can add the Foam template metadata to it.
#### Limitations
Foam only supports adding the template metadata to *YAML* Frontmatter blocks. If the existing Frontmatter block uses some other format (e.g. JSON), you will have to add the template metadata to its own YAML Frontmatter block.
Further, the template metadata must be provided as a [YAML block mapping](https://yaml.org/spec/1.2/spec.html#id2798057), with the attributes placed on the lines immediately following the `foam_template` line:
```yaml
---
existing_frontmatter: "Existing Frontmatter block"
foam_template: # this is a YAML "Block" mapping ("Flow" mappings aren't supported)
name: My Note Template # Attributes must be on the lines immediately following `foam_template`
description: This is my note template
filepath: `journal/$FOAM_TITLE.md`
---
This is the rest of the template
```
Due to the technical limitations of parsing the complex YAML format, unless the metadata is provided this specific form, Foam is unable to correctly remove the template metadata before creating the resulting note.
If this limitation proves inconvenient to you, please let us know. We may be able to extend our parsing capabilities to cover your use case. In the meantime, you can add the template metadata without this limitation by providing it in its own YAML Frontmatter block.
### Adding template metadata to its own YAML Frontmatter block
You can add the template metadata to its own YAML Frontmatter block at the start of the template:
```yaml
---
foam_template:
name: My Note Template
description: This is my note template
filepath: `journal/$FOAM_TITLE.md`
---
This is the rest of the template
```
If the note already has a Frontmatter block, a Foam-specific Frontmatter block can be added to the start of the template. The Foam-specific Frontmatter block must always be placed at the very beginning of the file, and only whitespace can separate the two Frontmatter blocks.
```yaml
---
foam_template:
name: My Note Template
description: This is my note template
filepath: `journal/$FOAM_TITLE.md`
---
---
existing_frontmatter: "Existing Frontmatter block"
---
This is the rest of the template
```

View File

@@ -3,15 +3,22 @@
Foam supports tags.
## Creating a tag
There are two ways of creating a tag:
- adding a `#tag` anywhere in the text of the note
- using the `tags: tag1, tag2` property in frontmatter
Tags can also be hierarchical, so you can have `#parent/child`.
## Navigating tags
It's possible to navigate tags via the Tag Explorer panel.
In the future it will be possible to explore tags via the graph as well.
## Styling tags
Inline tags can be styled using custom CSS with the selector `.foam-tag`.
## An alternative to tags
Given the power of backlinks, some people prefer to use them also as tags.

View File

@@ -5,10 +5,12 @@ To store your personal knowledge graph in markdown files instead of a database,
**Foam Janitor** (inspired by Andy Matuschak's [note-link-janitor](https://github.com/andymatuschak/note-link-janitor)) helps you migrate existing notes to Foam, and maintain your Foam's health over time.
Currently, Foam's Janitor helps you to:
- Ensure your [[link-reference-definitions]] are up to date
- Ensure every document has a well-formatted title (required for Markdown Links, Markdown Notes, and Foam Gatsby Template compatibility)
In the future, Janitor can help you with
- Updating [[materialized-backlinks]]
- Lint, format and structure notes
- Rename and move notes around while keeping their references up to date.

View File

@@ -4,15 +4,19 @@
- [Frequently Asked Questions](#frequently-asked-questions)
- [Links/Graphs/BackLinks don't work. How do I enable them?](#linksgraphsbacklinks-dont-work-how-do-i-enable-them)
- [I don't want Foam enabled for all my workspaces](#i-dont-want-foam-enabled-for-all-my-workspaces)
## Links/Graphs/BackLinks don't work. How do I enable them?
- Ensure that you have all the [[recommended-extensions]] installed in Visual Studio Code
- Reload Visual Studio Code by running `Cmd` + `Shift` + `P` (`Ctrl` + `Shift` + `P` for Windows), type "reload" and run the **Developer: Reload Window** command to for the updated extensions take effect
- Check the formatting rules for links on [[foam-file-format]], [[wiki-links]] and [[link-formatting-and-autocompletion]]
- Check the formatting rules for links on [[foam-file-format]], [[wikilinks]] and [[link-formatting-and-autocompletion]]
## I don't want Foam enabled for all my workspaces
Any extension you install in Visual Studio Code is enabled by default. Give the philosophy of Foam it works out of the box without doing any configuration upfront. In case you want to disable Foam for a specific workspace, or disable Foam by default and enable it for specific workspaces, it is advised to follow the best practices as [documented by Visual Studio Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_manage-extensions)
[//begin]: # "Autogenerated link references for markdown compatibility"
[recommended-extensions]: recommended-extensions.md "Recommended Extensions"
[foam-file-format]: dev/foam-file-format.md "Foam File Format"
[wiki-links]: wiki-links.md "Wiki Links"
[wikilinks]: wikilinks.md "Wikilinks"
[//end]: # "Autogenerated link references"

View File

@@ -5,7 +5,7 @@ Uncategorised thoughts, to be added
- Release notes
- Markdown Preview
- It's possible to customise the markdown preview styling. **Maybe make it use local foam workspace styles for live preview of the site??**
- See: https://marketplace.visualstudio.com/items?itemName=bierner.markdown-preview-github-styles
- See: <https://marketplace.visualstudio.com/items?itemName=bierner.markdown-preview-github-styles>
- Use VS Code [CodeTour](https://marketplace.visualstudio.com/items?itemName=vsls-contrib.codetour) for onboarding
- Investigate other similar extensions:
- [Unotes](https://marketplace.visualstudio.com/items?itemName=ryanmcalister.Unotes)
@@ -16,10 +16,10 @@ Uncategorised thoughts, to be added
- Every Foam could have a different theme even in the editor, so you'll see it like they see it
- UI and layout design of your workspace can become a thing
- VS Code Notebooks API
- https://code.visualstudio.com/api/extension-guides/notebook
- <https://code.visualstudio.com/api/extension-guides/notebook>
- Future architecture
- Could we do publish-related settings as a pre-push git hook, e.g. generating footnote labels
- Running them on Github Actions to edit stuff as it comes in
- Running them on GitHub Actions to edit stuff as it comes in
- Ideally, we shouldn't have to touch files, should be just markdown
- Looking at the errors/warnings/output panes makes me think, what kind of automated quality tools could we write.
- Deduplication, finding similarities...
@@ -32,5 +32,3 @@ Uncategorised thoughts, to be added
- Maps have persistent topologies. As the graph grows, you should be able to visualise where an idea belongs. Maybe a literal map? And island? A DeckGL visualisation?
Testing: This file is served from the /docs directory.

View File

@@ -37,7 +37,7 @@ Whether you want to build a [Second Brain](https://www.buildingasecondbrain.com/
1. Create a single **Foam** workspace for all your knowledge and research following the [Getting started](#getting-started) guide.
2. Write your thoughts in markdown documents (I like to call them **Bubbles**, but that might be more than a little twee). These documents should be atomic: Put things that belong together into a single document, and limit its content to that single topic. ([source](https://zettelkasten.de/posts/overview/#principles))
3. Use Foam's shortcuts and autocompletions to link your thoughts together with `[[wiki-links]]`, and navigate between them to explore your knowledge graph.
3. Use Foam's shortcuts and autocompletions to link your thoughts together with `[[wikilinks]]`, and navigate between them to explore your knowledge graph.
4. Get an overview of your **Foam** workspace using a [[graph-visualisation]] (⚠️ WIP), and discover relationships between your thoughts with the use of [[backlinking]].
Foam is a like a bathtub: _What you get out of it depends on what you put into it._
@@ -198,6 +198,18 @@ If that sounds like something you're interested in, I'd love to have you along o
</tr>
<tr>
<td align="center"><a href="http://twitter.com/deegovee"><img src="https://avatars.githubusercontent.com/u/4730170?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Dheepak </b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=dheepakg" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/daniel-vera-g"><img src="https://avatars.githubusercontent.com/u/28257108?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Daniel VG</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=daniel-vera-g" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/Barabazs"><img src="https://avatars.githubusercontent.com/u/31799121?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Barabas</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=Barabazs" title="Code">💻</a></td>
<td align="center"><a href="http://enginveske@gmail.com"><img src="https://avatars.githubusercontent.com/u/43685404?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Engincan VESKE</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=EngincanV" title="Documentation">📖</a></td>
<td align="center"><a href="http://www.paulderaaij.nl"><img src="https://avatars.githubusercontent.com/u/495374?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Paul de Raaij</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=pderaaij" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/bronson"><img src="https://avatars.githubusercontent.com/u/1776?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Scott Bronson</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=bronson" title="Documentation">📖</a></td>
<td align="center"><a href="http://rafaelriedel.de"><img src="https://avatars.githubusercontent.com/u/41793?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Rafael Riedel</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=rafo" title="Documentation">📖</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/Pearcekieser"><img src="https://avatars.githubusercontent.com/u/5055971?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Pearcekieser</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=Pearcekieser" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/theowenyoung"><img src="https://avatars.githubusercontent.com/u/62473795?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Owen Young</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=theowenyoung" title="Documentation">📖</a> <a href="#content-theowenyoung" title="Content">🖋</a></td>
<td align="center"><a href="http://www.prashu.com"><img src="https://avatars.githubusercontent.com/u/476729?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Prashanth Subrahmanyam</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=ksprashu" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/JonasSprenger"><img src="https://avatars.githubusercontent.com/u/25108895?v=4?s=60" width="60px;" alt=""/><br /><sub><b>Jonas SPRENGER</b></sub></a><br /><a href="https://github.com/foambubble/foam/commits?author=JonasSprenger" title="Code">💻</a></td>
</tr>
</table>

View File

@@ -13,6 +13,7 @@ Present: @jevakallio, @riccardoferretti
- Land work to master
- Create a foam-core package
-
### Open questions

View File

@@ -37,7 +37,7 @@ This principle may seem like it contradicts [Foam wants you to own your thoughts
- **Foam is a collection of ideas.** Foam was released to the public not to share the few good ideas in it, but to learn many good ideas from others. As you improve your own workflow, share your work on your own Foam blog.
- **Foam is open for contributions.** If you use a tool or workflow that you like that fits these principles, please contribute them back to the Foam template as [[recipes]], [[recommended-extensions]] or documentation in [this workspace](https://github.com/foambubble/foam). See also: [[contribution-guide]].
- **Foam is open source.** Feel free to fork it, improve it and remix it. Just don't sell it, as per our [license](license).
- **Foam is open source.** Feel free to fork it, improve it and remix it. Just don't sell it, as per our [license](LICENSE.txt).
- **Foam is not Roam.** This project was inspired by Roam Research, but we're not limited by what Roam does. No idea is too big (though if it doesn't fit with Foam's core workflow, we might make it a [[recipes]] page instead).
## Foam is for hackers, not only for programmers
@@ -48,7 +48,6 @@ While Foam uses tools popular among computer programmers, Foam should be inclusi
- **Foam is not just for programmers.** If you're a programmer, feel free to write scripts and extensions to support your own workflow, and publish them for others to use, but the out of the box Foam experience should not require you to know how to do so. You should, however, be curious and open to adopting new tools that are unfamiliar to you, and evaluate whether they could work for you.
- **Foam is for everyone** As a foam user, you support everyone's quest for knowledge and self-improvement, not only your own, or folks' who look like you. All participants in Foam repositories, discussion forums, physical and virtual meeting spaces etc are expected to respect each other as described in our [[code-of-conduct]]. **Foam is not for toxic tech bros.**
[//begin]: # "Autogenerated link references for markdown compatibility"
[recipes]: recipes/recipes.md "Recipes"
[recommended-extensions]: recommended-extensions.md "Recommended Extensions"

View File

@@ -0,0 +1,48 @@
# Inclusion of notes Proposal <!-- omit in TOC -->
Currently it is not possible within Foam to include other notes into a note. Next to including a full note it could be interesting to add functionalities that allow for greater flexibility. This proposal discusses some functionalities around inclusion of notes.
**IMPORTANT: This design is merely a proposal of a design that could be implemented. It DOES NOT represent a commitment by `Foam` developers to implement the features outlined in this document. This document is merely a mechanism to facilitate discussion of a possible future direction for `Foam`.**
- [Introduction](#introduction)
- [New features](#new-features)
- [Including a note](#including-a-note)
- [Include a section of a note](#include-a-section-of-a-note)
- [Include an attribute of a file (note property or frontmatter)](#include-an-attribute-of-a-file-note-property-or-frontmatter)
## Introduction
Initial work and thought on including a note was ignited by issue [#652](https://github.com/foambubble/foam/issues/652). Requested by a user was a likewise functionality as offered in Obsidian. This was simply the ability to include a note.
Whilst researching digital gardening for my own setup, I came across an in-depth overview by [Maggie Appleton](https://maggieappleton.com/roam-garden). Showing examples of her personal Roam Research I see valuable possibilites to connect more information, if we would add additional functionalities to the possibility of including a note. This proposal displays these possible functionalities and markup.
## New features
### Including a note
The minimal functionality is the ability to fully include a note. Markup used in Obsidian for this is `![[wikilink]]`. For Foam I would suggest to follow this syntax. Benefits being:
- Adds minimal amount of knowledge required as syntax is based on the syntax of creating a wikilink.
- Makes the auto-complete work ouf-of-the-box, without any additional code and listeners required.
**Important**. A risk exists that a loop of including the same notes arises. E.g. Note A includes note B which includes note A. This needs to be prevented by the implementation and made visible to the user.
### Include a section of a note
It could be interesting to only include a section of a note instead of the entire note. In order to do so thse user should be able to use the following syntax:
`![[wikilink#section-b]]`
As a result it will include the section title + section content until the next section *or* end of file.
### Include an attribute of a file (note property or frontmatter)
As a user I could be interested in collecting the value of any given proeprty for a note. For example, I might want to include the tags as defined in the frontmatter of note A. This should be possible via the syntax:
`![[wikilink:<property>]]`
The property value should be lookedup by foam defined properties, e.g. title, **or** any property defined in the frontmatter of a note.
So, the example of including the tags of a note should be:
`![[wikilink:tags]]`

View File

@@ -42,6 +42,7 @@ The current capabilities of templates is limited in some important ways. This do
Creating of new notes in Foam is too cumbersome and slow. Despite their power, Foam templates can currently only be used in very limited scenarios.
This proposal aims to address these issues by streamlining note creation and by allowing templates to be used everywhere.
## Limitations of current templating
### Too much friction to create a new note
@@ -162,14 +163,16 @@ This would open use the template found at `.foam/templates/new-note.md` to creat
#### Case 1: `.foam/templates/new-note.md` doesn't exist
If `.foam/templates/new-note.md` doesn't exist, it behaves the same as `Markdown Notes: New Note`:
* it would ask for a title and create the note in the current directory. It would open a note with the note containing the title.
* it would ask for a title and create the note in the current directory. It would open a note with the note containing the title.
**Note:** this would use an implicit default template, making use of the `${title}` variable.
#### Case 2: `.foam/templates/new-note.md` exists
If `.foam/templates/new-note.md` exists:
* it asks for the note title and creates the note in the current directory
* it asks for the note title and creates the note in the current directory
**Progress:** At this point, we have a faster way to create new notes from templates.

View File

@@ -2,20 +2,22 @@
## Using foam-gatsby-template
You can use [foam-gatsby-template](https://github.com/mathieudutour/foam-gatsby-template) to generate a static site to host it online on Github or [Vercel](https://vercel.com).
You can use [foam-gatsby-template](https://github.com/mathieudutour/foam-gatsby-template) to generate a static site to host it online on GitHub or [Vercel](https://vercel.com).
### Publishing your foam to GitHub pages
It comes configured with Github actions to auto deploy to Github pages when changes are pushed to your main branch.
It comes configured with GitHub actions to auto deploy to GitHub pages when changes are pushed to your main branch.
### Publishing your foam to Vercel
When you're ready to publish, run a local build.
```bash
cd _layouts
npm run build
```
Remove `public` from your .gitignore file then commit and push your public folder in `_layouts` to Github.
Remove `public` from your .gitignore file then commit and push your public folder in `_layouts` to GitHub.
Log into your Vercel account. (Create one if you don't have it already.)
@@ -26,3 +28,7 @@ That's it!
## Using foam-template-gatsby-kb
You can use another template [foam-template-gatsby-kb](https://github.com/hikerpig/foam-template-gatsby-kb), and host it on [Vercel](https://vercel.com) or [Netlify](https://www.netlify.com/).
## Using foam-template-gatsby-theme-primer-wiki
You can use another template [foam-template-gatsby-theme-primer-wiki](https://github.com/theowenyoung/foam-template-gatsby-theme-primer-wiki), ([Demo](https://demo-wiki.owenyoung.com/)), and host it on Github Pages, [Vercel](https://vercel.com) or [Netlify](https://www.netlify.com/).

View File

@@ -11,14 +11,15 @@ The following recipe is written with the assumption that you already have an [Az
1. Generate a Foam workspace using the [foam-template project](https://github.com/foambubble/foam-template).
2. Change the remote to a git repository in Azure DevOps (Repos -> Import a Repository -> Add Clone URL with Authentication), or copy all the files into a new Azure DevOps git repository.
3. Define which document will be the wiki home page. To do that, create a file called `.order` in the Foam workspace root folder, with first line being the document filename without `.md` extension. For a project created from the Foam template, the file would look like this:
```
readme
```
4. Push the repository to remote in Azure DevOps.
## Publish repository to a wiki
1. Navigate to your Azure DevOps project in a web browser.
2. Choose **Overview** > **Wiki**. If you don't have wikis for your project, choose **Publish code as a wiki** on welcome page.
3. Choose repository with your Foam workspace, branch (usually `master` or `main`), folder (for workspace created from foam-template it is `/`), and wiki name, and press **Publish**.
@@ -40,6 +41,7 @@ While you are pushing changes to GitHub, you won't see the wiki updated if you d
3. You can then add the remote for your second remote repository, in this case, Azure. e.g `git remote add azure https://<YOUR_ID>@dev.azure.com/<YOUR_ID>/foam-notes/_git/foam-notes`. You can get it from: Repos->Files->Clone and copy the URL.
4. Now, you need to set up your origin remote to push to both of these. So run: `git config -e` and edit it.
5. Add the `remote origin` section to the bottom of the file with the URLs from each remote repository you'd like to push to. You'll see something like that:
```bash
[core]
...
@@ -58,6 +60,7 @@ While you are pushing changes to GitHub, you won't see the wiki updated if you d
url = git@github.com:username/repo.git
url = https://<YOUR_ID>@dev.azure.com/<YOUR_ID>/foam-notes/_git/foam-notes
```
6. You can then push to both repositories by: `git push origin master` or a single one using: `git push github master` or `git push azure master`
For more information, read the [Azure DevOps documentation](https://docs.microsoft.com/en-us/azure/devops/project/wiki/publish-repo-to-wiki).

View File

@@ -1,4 +1,4 @@
# Github Pages
# GitHub Pages
- In VSCode workspace settings set `"foam.edit.linkReferenceDefinitions": "withoutExtensions"`
- Execute the “Foam: Run Janitor” command from the command palette.
@@ -9,36 +9,41 @@
## How to publish locally
If you want to test your published foam, follow the instructions:
- https://docs.github.com/en/free-pro-team@latest/github/working-with-github-pages/creating-a-github-pages-site-with-jekyll
- https://docs.github.com/en/free-pro-team@latest/github/working-with-github-pages/testing-your-github-pages-site-locally-with-jekyll
- <https://docs.github.com/en/free-pro-team@latest/github/working-with-github-pages/creating-a-github-pages-site-with-jekyll>
- <https://docs.github.com/en/free-pro-team@latest/github/working-with-github-pages/testing-your-github-pages-site-locally-with-jekyll>
Assuming you have installed ruby/jekyll and the rest:
- `touch Gemfile`
- open the file and paste the following:
```
source 'https://rubygems.org'
gem "github-pages", "VERSION"
```
replacing `VERSION` with the latest from https://rubygems.org/gems/github-pages (e.g. `gem "github-pages", "209"`)
replacing `VERSION` with the latest from <https://rubygems.org/gems/github-pages> (e.g. `gem "github-pages", "209"`)
- `bundle`
- `bundle exec jekyll 3.9.0 new .`
- edit the `Gemfile` according to the instructions at [Creating Your Site](https://docs.github.com/en/free-pro-team@latest/github/working-with-github-pages/creating-a-github-pages-site-with-jekyll#creating-your-site) Point n.8
- `bundle exec jekyll serve`
## Other templates
There are many other templates which also support publish your foam workspace to github pages
* gatsby-digital-garden
* [repo](https://github.com/mathieudutour/gatsby-digital-garden)
* [demo-website](https://mathieudutour.github.io/gatsby-digital-garden/)
* [repo](https://github.com/mathieudutour/gatsby-digital-garden)
* [demo-website](https://mathieudutour.github.io/gatsby-digital-garden/)
* foam-mkdocs-template
* [repo](https://github.com/Jackiexiao/foam-mkdocs-template)
* [demo-website](https://jackiexiao.github.io/foam/)
* [repo](https://github.com/Jackiexiao/foam-mkdocs-template)
* [demo-website](https://jackiexiao.github.io/foam/)
* foam-jekyll-template
* [repo](https://github.com/hikerpig/foam-jekyll-template)
* [demo-website](https://hikerpig.github.io/foam-jekyll-template/)
* [repo](https://github.com/hikerpig/foam-jekyll-template)
* [demo-website](https://hikerpig.github.io/foam-jekyll-template/)
[[todo]] [[good-first-task]] Improve this documentation

View File

@@ -5,11 +5,13 @@ The standard [foam-template](https://github.com/foambubble/foam-template) is rea
## Enable navigation in GitHub
To allow navigation from within the GitHub repo, make sure to generate the link references, by setting
- `Foam Edit: Link Reference Definitions` -> `withExtensions`
See [[link-reference-definitions]] for more information.
## Customising the style
You can edit `assets/css/style.scss` to change how published pages look.
[//begin]: # "Autogenerated link references for markdown compatibility"

View File

@@ -11,6 +11,7 @@ Generate a solution using the [Foam template].
Change the remote to GitLab, or copy all the files into a new GitLab repo.
### Add a _config.yaml
Add another file to the root directory (the one with `readme.md` in it) called `_config.yaml` (no extension)
```yaml

View File

@@ -3,6 +3,7 @@
You can use [foam-eleventy-template](https://github.com/juanfrank77/foam-eleventy-template) to generate a static site with [Eleventy](https://www.11ty.dev/), and host it online on [Netlify](https://www.netlify.com/).
With this template you can
- Have control over what to publish and what to keep private
- Customize the styling of the site to your own liking
@@ -12,8 +13,6 @@ When you're ready to publish, import the GitHub repository you created with **fo
Once that's done, all you have to do is make changes to your workspace in VS Code and push them to the main branch on GitHub. Netlify will recognize the changes, deploy them automatically and give you a link where your Foam is published.
That's it!
You can now see it online and use that link to share it with your friends, so that they can see it too.

View File

@@ -82,6 +82,6 @@ Finally, if all is successful, Vercel will show the detected framework: Jekyll.
And now, Vercel will take care of building and rendering our foam workspace each time on push. Vercel will publish our site to `xxx.vercel.app`, we can also define a custom domain name for our Vercel website.
[//begin]: # "Autogenerated link references for markdown compatibility"
[publish-to-github-pages]: publish-to-github-pages.md "Github Pages"
[publish-to-github-pages]: publish-to-github-pages.md "GitHub Pages"
[math-support-with-katex]: math-support-with-katex.md "Katex Math Rendering"
[//end]: # "Autogenerated link references"

View File

@@ -5,8 +5,6 @@
- [VSCode Extensions Packs](https://code.visualstudio.com/blogs/2017/03/07/extension-pack-roundup) [[todo]] Evaluate for deployment
- [Dark mode](https://css-tricks.com/dark-modes-with-css/)
[//begin]: # "Autogenerated link references for markdown compatibility"
[todo]: dev/todo.md "Todo"
[//end]: # "Autogenerated link references"

View File

@@ -5,7 +5,7 @@ You can also easily manipulate the git history to reduce clutter.
## Required Extensions
- [GitDoc](https://marketplace.visualstudio.com/items?itemName=vsls-contrib.gitdoc)
- [GitDoc](https://marketplace.visualstudio.com/items?itemName=vsls-contrib.gitdoc)
## Instructions
@@ -18,9 +18,6 @@ __For Foam specific needs, you can add a comment here by following the [[contrib
- Feedback and issues with the extension should be reported to the authors themselves
- Feedback and issues with the integration of the extension in Foam can be reported in our [issue tracker](https://github.com/foambubble/foam/issues)
[//begin]: # "Autogenerated link references for markdown compatibility"
[contribution-guide]: ../contribution-guide.md "Contribution Guide"
[//end]: # "Autogenerated link references"

View File

@@ -4,7 +4,7 @@ With this #recipe you can convert a link to a fully-formed Markdown link, using
## Required Extensions
- [Markdown Link Expander](https://marketplace.visualstudio.com/items?itemName=skn0tt.markdown-link-expander) (not included in template)
- [Markdown Link Expander](https://marketplace.visualstudio.com/items?itemName=skn0tt.markdown-link-expander) (not included in template)
Markdown Link Expander will scrape your URL's `<title>` tag to create a nice Markdown-style link.
@@ -22,4 +22,3 @@ Tip: If you paste a lot of links, give the action a custom [key binding](https:/
## Feedback and issues
Have an idea for the extension? [Feel free to share! 🎉](https://github.com/Skn0tt/markdown-link-expander/issues)

View File

@@ -30,7 +30,7 @@ With this #recipe you can create notes on your iOS device, which will automatica
2. the repository name of your Foam repo
3. the GitHub access token from step 7
4. An author name
11. Check your Github repo for a commit
11. Check your GitHub repo for a commit
12. If you are publishing your Foam to the web you may want to edit your publishing configuration to exclude inbox files - as publishing (and method) is a user choice that is beyond the scope of this recipe
## Code for Drafts Action

View File

@@ -15,8 +15,7 @@ With this #recipe you can create notes on your iOS device, which will automatica
## Instructions
1. Setup the [`foam-capture-action`]() in your GitHub Repository, to be triggered by "Workflow dispatch" events.
1. Setup the [`foam-capture-action`]() in your GitHub Repository, to be triggered by "Workflow dispatch" events.
```
name: Manually triggered workflow
@@ -26,15 +25,17 @@ on:
data:
description: 'What information to put in the knowledge base.'
required: true
jobs:
store_data:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- uses: anglinb/foam-capture-action@main
with:
with:
{% raw %}
capture: ${{ github.event.inputs.data }}
{% endraw %}
- run: |
git config --local user.email "example@gmail.com"
git config --local user.name "Your name"
@@ -44,14 +45,16 @@ jobs:
2. In GitHub [create a Personal Access Token](https://github.com/settings/tokens) and give it `repo` scope - make a note of the token
3. Run this command to find your `workflow-id` to be used in the Shortcut.
```bash
curl \
-H "Accept: application/vnd.github.v3+json" \
-H "Authorization: Bearer <GITHUB_TOKEN>" \
https://api.github.com/repos/<owner>/<repository>/actions/workflows
```
4. Copy this [Shortcut](https://www.icloud.com/shortcuts/57d2ed90c40e43a5badcc174ebfaaf1d) to your iOS devices and edit the contents of the last step, `GetContentsOfURL`
- Make sure you update the URL of the shortcut step with the `owner`, `repository`, `workflow-id` (from the previous step)
- Make sure you update the headers of the shortcut step, replaceing `[GITHUB_TOKEN]` with your Personal Access Token (from step 2)
- Make sure you update the headers of the shortcut step, replaceing `[GITHUB_TOKEN]` with your Personal Access Token (from step 2)
5. Run the shortcut & celebrate! ✨ (You should see a GitHub Action run start and the text you entered show up in `inbox.md` in your repository.)

View File

@@ -7,7 +7,6 @@ We have two alternative #recipe for displaying diagrams in markdown:
- [Draw.io](#drawio)
- [Using Draw.io](#using-drawio)
## Mermaid
You can use [Mermaid](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-mermaid) plugin to draw and preview diagrams in your content.
@@ -27,7 +26,6 @@ You can use [Mermaid](https://marketplace.visualstudio.com/items?itemName=bierne
3. Start drawing your diagram. Once you done, save it.
4. Embed the diagram file as you embedding the image file, for example: `![My Diagram](my-diagram.drawio.svg)`
[//begin]: # "Autogenerated link references for markdown compatibility"
[publish-to-github-pages]: ../publishing/publish-to-github-pages.md "Github Pages"
[publish-to-github-pages]: ../publishing/publish-to-github-pages.md "GitHub Pages"
[//end]: # "Autogenerated link references"

View File

@@ -3,6 +3,7 @@
This is an example of how to structure a Recipe. The first paragraph or two should explain the purpose of the recipe succinctly, including why it's useful, if that's not obvious.
Recipes are intended to document:
- How to use Foam's basic features
- Power user pro-tips
- Useful customisations of the default Foam environment
@@ -10,8 +11,8 @@ Recipes are intended to document:
## Required Extensions
- **[Hacker Typer](https://marketplace.visualstudio.com/items?itemName=jevakallio.vscode-hacker-typer)** (not really required for this recipe, just an example)
- [Foam for VSCode](https://marketplace.visualstudio.com/items?itemName=foam.foam-vscode) (installed by default)
- **[Hacker Typer](https://marketplace.visualstudio.com/items?itemName=jevakallio.vscode-hacker-typer)** (not really required for this recipe, just an example)
- [Foam for VSCode](https://marketplace.visualstudio.com/items?itemName=foam.foam-vscode) (installed by default)
The first section should be a bulleted list of extensions required to use this recipe. At a minimum, this section should list all additional, non-standard extensions.

View File

@@ -16,11 +16,6 @@ In the future we'll want to improve this feature by
- Make back links editable using [VS Code Search Editors](https://code.visualstudio.com/updates/v1_43#_search-editors)
- [Suggested by @Jash on Discord](https://discordapp.com/channels/729975036148056075/729978910363746315/730999992419876956)
[//begin]: # "Autogenerated link references for markdown compatibility"
[materialized-backlinks]: ../dev/materialized-backlinks.md "Materialized Backlinks (stub)"
[//end]: # "Autogenerated link references"

View File

@@ -4,7 +4,6 @@
If you're interested in working on it, please start a conversation in [GitHub issues](https://github.com/foambubble/foam/issues).
[//begin]: # "Autogenerated link references for markdown compatibility"
[todo]: ../dev/todo.md "Todo"
[roadmap]: ../dev/roadmap.md "Roadmap"

View File

@@ -56,6 +56,3 @@ in `keybindings.json` (Code|File > Preferences > Keyboard Shortcuts) add binding
If you have any issues or questions please look at the [README.md](https://github.com/kneely/note-macros#note-macros) on the [note-macros](https://github.com/kneely/note-macros) GitHub.
If you run into any issues that are not fixed by referring to the README or feature requests please open an [issue](https://github.com/kneely/note-macros/issues).

View File

@@ -1,4 +1,3 @@
# Real-time Collaboration
This #recipe is here to just tell you that VS Code Live Share will allow you to collaborate live on your notes.

View File

@@ -26,15 +26,18 @@ A #recipe is a guide, tip or strategy for getting the most out of your Foam work
- Clip webpages with [[web-clipper]]
## Discover
- Explore your notes using [[graph-visualisation]]
- Discover relationships with [[backlinking]]
- Simulating [[unlinked-references]]
## Organise
- Using [[backlinking]] for reference lists.
## Write
- Link documents with [[wiki-links]].
- Link documents with [[wikilinks]].
- Use shortcuts for [[creating-new-notes]]
- Instantly create and access your [[daily-notes]]
- Add and explore [[tags]]
@@ -53,6 +56,7 @@ A #recipe is a guide, tip or strategy for getting the most out of your Foam work
- _More..._
- VS Code Advanced Features [[todo]] [[good-first-task]]
- Focus with Zen Mode
- Display content of other notes in the preview tab by [[including-notes]]
## Version control
@@ -109,7 +113,7 @@ _See [[contribution-guide]] and [[how-to-write-recipes]]._
[graph-visualisation]: ../features/graph-visualisation.md "Graph Visualisation"
[backlinking]: ../features/backlinking.md "Backlinking"
[unlinked-references]: ../dev/unlinked-references.md "Unlinked references (stub)"
[wiki-links]: ../wiki-links.md "Wiki Links"
[wikilinks]: ../wikilinks.md "Wikilinks"
[creating-new-notes]: ../features/creating-new-notes.md "Creating New Notes"
[daily-notes]: ../features/daily-notes.md "Daily notes"
[tags]: ../features/tags.md "Tags"
@@ -122,9 +126,10 @@ _See [[contribution-guide]] and [[how-to-write-recipes]]._
[add-images-to-notes]: add-images-to-notes.md "Add images to your notes"
[shows-image-preview-on-hover]: shows-image-preview-on-hover.md "Shows Image Preview on Hover"
[good-first-task]: ../dev/good-first-task.md "Good First Task"
[including-notes]: ../features/including-notes.md "Including notes in a note"
[git-integration]: ../features/git-integration.md "Git Integration"
[write-your-notes-in-github-gist]: write-your-notes-in-github-gist.md "Write your notes in GitHub Gist"
[publish-to-github-pages]: ../publishing/publish-to-github-pages.md "Github Pages"
[publish-to-github-pages]: ../publishing/publish-to-github-pages.md "GitHub Pages"
[publish-to-gitlab-pages]: ../publishing/publish-to-gitlab-pages.md "GitLab Pages"
[publish-to-azure-devops-wiki]: ../publishing/publish-to-azure-devops-wiki.md "Publish to Azure DevOps Wiki"
[publish-to-vercel]: ../publishing/publish-to-vercel.md "Publish to Vercel"

View File

@@ -9,16 +9,18 @@ The most promising options are:
### [GitJournal](https://gitjournal.io/)
Pros
- Open source
- Already a usable solution.
- Provides functionality to edit, create, and browser markdown files.
- Support journal mode, todo lists, and free writing
- Syncs to GitHub repo
- Supports Wiki Links
- Supports Wikilinks
- Supports Backlinks
- Developer is happy to prioritize Foam compatibility
Cons
- Doesn't generate link reference lists (but this is ok, since [[workspace-janitor]] as a GitHub action can solve this)
- Not as sleek as Apple/Google notes, some keyboard state glitching on Android, etc.
- Lack of control over roadmap. Established product with a paid plan, so may not be open to Foam-supportive changes and additions that don't benefit most users.
@@ -28,13 +30,15 @@ Verdict: Good. By far best effort/outcome ratio would be to help improve GitJour
### GitHub Codespaces
Pros
- Works out of the box just like the desktop app
Cons
- not generally available quite yet
- [Pricing](https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/about-billing-for-codespaces)
For a quick demo, see https://www.youtube.com/watch?v=KI5m4Uy8_4I.
For a quick demo, see <https://www.youtube.com/watch?v=KI5m4Uy8_4I>.
Verdict: Good. Pricing should be reasonable for taking notes on the fly. Harder to assess for people who would constantly use Foam from mobile phone.
@@ -54,7 +58,6 @@ If such an app was worth building, it would have to have the following features:
Given the effort vs reward ratio, it's a low priority for core team, but if someone wants to work on this, we can provide support! Talk to us on the #mobile-apps channel on [Foam Discord](https://foambubble.github.io/join-discord/w).
[//begin]: # "Autogenerated link references for markdown compatibility"
[build-vs-assemble]: ../dev/build-vs-assemble.md "Build vs Assemble"
[workspace-janitor]: ../features/workspace-janitor.md "Janitor"

View File

@@ -5,10 +5,9 @@ These extensions defined in `.vscode/extensions.json` are automatically installe
This list is subject to change. Especially the Git ones.
- [Foam for VSCode](https://marketplace.visualstudio.com/items?itemName=foam.foam-vscode) (alpha)
- [Markdown Notes](https://marketplace.visualstudio.com/items?itemName=kortina.vscode-markdown-notes)
- [Markdown Links](https://marketplace.visualstudio.com/items?itemName=tchayen.markdown-links)
- [Markdown All In One](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one)
- [Paste Image](https://marketplace.visualstudio.com/items?itemName=mushan.vscode-paste-image)
- [Spell Right](https://marketplace.visualstudio.com/items?itemName=ban.spellright)
## Extensions For Additional Features
@@ -16,10 +15,11 @@ These extensions are not (yet?) defined in `.vscode/extensions.json`, but have b
- [Emojisense](https://marketplace.visualstudio.com/items?itemName=bierner.emojisense)
- [Markdown Emoji](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-emoji) (adds `:smile:` syntax, works with emojisense to provide autocomplete for this syntax)
- [Mermaid Support for Preview](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-mermaid)
- [Markdown Preview Mermaid Support](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-mermaid)
- [Mermaid Markdown Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=bpruitt-goddard.mermaid-markdown-syntax-highlighting)
- [VSCode PDF Viewing](https://marketplace.visualstudio.com/items?itemName=tomoki1207.pdf)
- [Git Lens](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens)
- [Markdown Extended](https://marketplace.visualstudio.com/items?itemName=jebbs.markdown-extended) (with `kbd` option disabled, `kbd` turns wiki-links into non-clickable buttons)
- [Project Manager](https://marketplace.visualstudio.com/items?itemName=alefragnani.project-manager) (to quickly switch between projects)
- [Markdown Extended](https://marketplace.visualstudio.com/items?itemName=jebbs.markdown-extended) (with `kbd` option disabled, `kbd` turns wikilinks into non-clickable buttons)
- [GitDoc](https://marketplace.visualstudio.com/items?itemName=vsls-contrib.gitdoc) (easy version management via git auto commits)
- [Markdown Footnotes](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-footnotes) (Adds [^footnote] syntax support to VS Code's built-in markdown preview)
- [Todo Tree](https://marketplace.visualstudio.com/items?itemName=Gruntfuggly.todo-tree) (Searches workspace for TODO and related comments and summarizes those lines in vs-code gutter)

View File

@@ -17,4 +17,3 @@ Also happens to sound quite a lot like Home. Funny, that.
## Bubble
Individual Foam note, written in Markdown.

View File

@@ -1,27 +1,30 @@
# Wiki Links
# Wikilinks
Foam enables you to Link pages together using `[[file-name]]` annotations (i.e. `[[media-wiki]]` links).
Foam enables you to Link pages together using `[[file-name]]` annotations (i.e. `[[MediaWiki]]` links).
- Type `[[` and start typing a file name for autocompletion.
- Note that your file names should be in `lower-dash-case.md`, and your wiki links should reference file names exactly: `[[lower-dash-case]]`, not `[[Lower Dash Case]]`.
- Note that your file names should be in `lower-dash-case.md`, and your wikilinks should reference file names exactly: `[[lower-dash-case]]`, not `[[Lower Dash Case]]`.
- See [[link-formatting-and-autocompletion]] for more information, and how to setup your link autocompletions to make this easier.
- `Cmd` + `Click` ( `Ctrl` + `Click` on Windows ) on file name to navigate to file (`F12` also works while your cursor is on the file name)
- `Cmd` + `Click` ( `Ctrl` + `Click` on Windows ) on non-existent file to create that file in the workspace.
- The note creation makes use of the special [`new-note.md` note template](features/note-templates)
> If the `F12` shortcut feels unnatural you can rebind it at File > Preferences > Keyboard Shortcuts by searching for `editor.action.revealDefinition`.
## Markdown compatibility
The [Foam for VSCode](https://marketplace.visualstudio.com/items?itemName=foam.foam-vscode) extension automatically generates [[link-reference-definitions]] at the bottom of the file to make wiki-links compatible with Markdown tools and parsers.
The [Foam for VSCode](https://marketplace.visualstudio.com/items?itemName=foam.foam-vscode) extension automatically generates [[link-reference-definitions]] at the bottom of the file to make wikilinks compatible with Markdown tools and parsers.
## Read more
- [[foam-file-format]]
- [[note-templates]]
- [[link-formatting-and-autocompletion]]
- See [[link-reference-definition-improvements]] for further discussion on current problems and potential solutions.
[//begin]: # "Autogenerated link references for markdown compatibility"
[link-reference-definitions]: features/link-reference-definitions.md "Link Reference Definitions"
[foam-file-format]: dev/foam-file-format.md "Foam File Format"
[note-templates]: features/note-templates.md "Note Templates"
[link-reference-definition-improvements]: dev/link-reference-definition-improvements.md "Link Reference Definition Improvements"
[//end]: # "Autogenerated link references"

View File

@@ -4,5 +4,5 @@
],
"npmClient": "yarn",
"useWorkspaces": true,
"version": "0.13.1"
"version": "0.15.0"
}

View File

@@ -40,5 +40,6 @@
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
}
},
"dependencies": {}
}

View File

@@ -1,7 +1,7 @@
{
"name": "foam-core",
"repository": "https://github.com/foambubble/foam",
"version": "0.13.1",
"version": "0.15.0",
"license": "MIT",
"files": [
"dist"
@@ -30,14 +30,15 @@
},
"dependencies": {
"detect-newline": "^3.1.0",
"fast-array-diff": "^1.0.0",
"fast-array-diff": "^1.0.1",
"github-slugger": "^1.3.0",
"glob": "^7.1.6",
"lodash": "^4.17.19",
"lodash": "^4.17.21",
"micromatch": "^4.0.2",
"remark-frontmatter": "^2.0.0",
"remark-parse": "^8.0.2",
"remark-wiki-link": "^0.0.4",
"replace-ext": "^2.0.0",
"title-case": "^3.0.2",
"unified": "^9.0.0",
"unist-util-visit": "^2.0.2",

View File

@@ -1,56 +0,0 @@
import { createMarkdownParser } from './markdown-provider';
import { FoamConfig, Foam, IDataStore } from './index';
import { loadPlugins } from './plugins';
import { isSome } from './utils';
import { Logger } from './utils/log';
import { URI } from './model/uri';
import { FoamWorkspace } from './model/workspace';
export const bootstrap = async (config: FoamConfig, dataStore: IDataStore) => {
const plugins = await loadPlugins(config);
const parserPlugins = plugins.map(p => p.parser).filter(isSome);
const parser = createMarkdownParser(parserPlugins);
const workspace = new FoamWorkspace();
const files = await dataStore.listFiles();
await Promise.all(
files.map(async uri => {
Logger.info('Found: ' + uri);
if (URI.isMarkdownFile(uri)) {
const content = await dataStore.read(uri);
if (isSome(content)) {
workspace.set(parser.parse(uri, content));
}
}
})
);
workspace.resolveLinks(true);
const listeners = [
dataStore.onDidChange(async uri => {
const content = await dataStore.read(uri);
isSome(content) && workspace.set(await parser.parse(uri, content));
}),
dataStore.onDidCreate(async uri => {
const content = await dataStore.read(uri);
isSome(content) && workspace.set(await parser.parse(uri, content));
}),
dataStore.onDidDelete(uri => {
workspace.delete(uri);
}),
];
return {
workspace: workspace,
config: config,
services: {
dataStore,
parser,
},
dispose: () => {
listeners.forEach(l => l.dispose());
workspace.dispose();
},
} as Foam;
};

View File

@@ -74,7 +74,8 @@ export const isElectronSandboxed = isElectronRenderer && nodeProcess?.sandboxed;
// Web environment
if (typeof navigator === 'object' && !isElectronRenderer) {
_userAgent = navigator.userAgent;
_isWindows = _userAgent.indexOf('Windows') >= 0;
_isWindows =
_userAgent.indexOf('Windows') >= 0 || _userAgent.indexOf('win32') >= 0;
_isMacintosh = _userAgent.indexOf('Macintosh') >= 0;
_isIOS =
(_userAgent.indexOf('Macintosh') >= 0 ||

View File

@@ -70,6 +70,6 @@ const parseConfig = (path: URI) => {
try {
return JSON.parse(readFileSync(URI.toFsPath(path), 'utf8'));
} catch {
Logger.debug('Could not read configuration from ' + path);
Logger.debug('Could not read configuration from ' + URI.toString(path));
}
};

View File

@@ -1,37 +1,39 @@
import {
Resource,
Attachment,
Placeholder,
Note,
NoteLink,
isNote,
ResourceLink,
NoteLinkDefinition,
isPlaceholder,
isAttachment,
getTitle,
NoteParser,
ResourceParser,
Tag,
} from './model/note';
import { FoamConfig } from './config';
import { IDataStore, FileDataStore } from './services/datastore';
import {
IDataStore,
FileDataStore,
Matcher,
IMatcher,
} from './services/datastore';
import { ILogger } from './utils/log';
import { IDisposable, isDisposable } from './common/lifecycle';
import { FoamWorkspace } from './model/workspace';
import { FoamGraph } from '../src/model/graph';
import { URI } from './model/uri';
import { FoamTags } from '../src/model/tags';
export { Position } from './model/position';
export { Range } from './model/range';
export { IDataStore, FileDataStore };
export { IDataStore, FileDataStore, Matcher, IMatcher };
export { ILogger };
export { LogLevel, LogLevelThreshold, Logger, BaseLogger } from './utils/log';
export { Event, Emitter } from './common/event';
export { FoamConfig };
export { ResourceProvider } from './model/provider';
export { IDisposable, isDisposable };
export {
createMarkdownReferences,
stringifyMarkdownLinkReferenceDefinition,
createMarkdownParser,
MarkdownResourceProvider,
} from './markdown-provider';
export {
@@ -47,31 +49,16 @@ export { applyTextEdit } from './janitor/apply-text-edit';
export { createConfigFromFolders } from './config';
export { bootstrap } from './bootstrap';
export { Foam, Services, bootstrap } from './model/foam';
export {
Resource,
Attachment,
Placeholder,
Note,
NoteLink,
ResourceLink,
URI,
Tag,
FoamWorkspace,
FoamGraph,
FoamTags,
NoteLinkDefinition,
NoteParser,
isNote,
isPlaceholder,
isAttachment,
getTitle,
ResourceParser,
};
export interface Services {
dataStore: IDataStore;
parser: NoteParser;
}
export interface Foam extends IDisposable {
services: Services;
workspace: FoamWorkspace;
config: FoamConfig;
}

View File

@@ -1,5 +1,5 @@
import GithubSlugger from 'github-slugger';
import { Note } from '../model/note';
import { Resource } from '../model/note';
import { Range } from '../model/range';
import {
createMarkdownReferences,
@@ -20,7 +20,7 @@ export interface TextEdit {
}
export const generateLinkReferences = (
note: Note,
note: Resource,
workspace: FoamWorkspace,
includeExtensions: boolean
): TextEdit | null => {
@@ -75,7 +75,7 @@ export const generateLinkReferences = (
}
};
export const generateHeading = (note: Note): TextEdit | null => {
export const generateHeading = (note: Resource): TextEdit | null => {
if (!note) {
return null;
}

View File

@@ -10,10 +10,10 @@ import detectNewline from 'detect-newline';
import os from 'os';
import {
NoteLinkDefinition,
Note,
NoteParser,
isWikilink,
getTitle,
Resource,
ResourceLink,
WikiLink,
ResourceParser,
} from './model/note';
import { Position } from './model/position';
import { Range } from './model/range';
@@ -24,10 +24,134 @@ import {
isNone,
isSome,
} from './utils';
import { ParserPlugin } from './plugins';
import { Logger } from './utils/log';
import { URI } from './model/uri';
import { FoamWorkspace } from './model/workspace';
import { ResourceProvider } from 'model/provider';
import { IDataStore, FileDataStore, IMatcher } from './services/datastore';
import { IDisposable } from 'common/lifecycle';
const ALIAS_DIVIDER_CHAR = '|';
export interface ParserPlugin {
name?: string;
visit?: (node: Node, note: Resource, noteSource: string) => void;
onDidInitializeParser?: (parser: unified.Processor) => void;
onWillParseMarkdown?: (markdown: string) => string;
onWillVisitTree?: (tree: Node, note: Resource) => void;
onDidVisitTree?: (tree: Node, note: Resource) => void;
onDidFindProperties?: (properties: any, note: Resource, node: Node) => void;
}
export class MarkdownResourceProvider implements ResourceProvider {
private disposables: IDisposable[] = [];
constructor(
private readonly matcher: IMatcher,
private readonly watcherInit?: (triggers: {
onDidChange: (uri: URI) => void;
onDidCreate: (uri: URI) => void;
onDidDelete: (uri: URI) => void;
}) => IDisposable[],
private readonly parser: ResourceParser = createMarkdownParser([]),
private readonly dataStore: IDataStore = new FileDataStore()
) {}
async init(workspace: FoamWorkspace) {
const filesByFolder = await Promise.all(
this.matcher.include.map(glob =>
this.dataStore.list(glob, this.matcher.exclude)
)
);
const files = this.matcher
.match(filesByFolder.flat())
.filter(this.supports);
await Promise.all(
files.map(async uri => {
Logger.info('Found: ' + URI.toString(uri));
const content = await this.dataStore.read(uri);
if (isSome(content)) {
workspace.set(this.parser.parse(uri, content));
}
})
);
this.disposables =
this.watcherInit?.({
onDidChange: async uri => {
if (this.matcher.isMatch(uri) && this.supports(uri)) {
const content = await this.dataStore.read(uri);
isSome(content) &&
workspace.set(await this.parser.parse(uri, content));
}
},
onDidCreate: async uri => {
if (this.matcher.isMatch(uri) && this.supports(uri)) {
const content = await this.dataStore.read(uri);
isSome(content) &&
workspace.set(await this.parser.parse(uri, content));
}
},
onDidDelete: uri => {
this.supports(uri) && workspace.delete(uri);
},
}) ?? [];
}
supports(uri: URI) {
return URI.isMarkdownFile(uri);
}
read(uri: URI): Promise<string | null> {
return this.dataStore.read(uri);
}
readAsMarkdown(uri: URI): Promise<string | null> {
return this.dataStore.read(uri);
}
async fetch(uri: URI) {
const content = await this.read(uri);
return isSome(content) ? this.parser.parse(uri, content) : null;
}
resolveLink(
workspace: FoamWorkspace,
resource: Resource,
link: ResourceLink
) {
let targetUri: URI | undefined;
switch (link.type) {
case 'wikilink':
const definitionUri = resource.definitions.find(
def => def.label === link.target
)?.url;
if (isSome(definitionUri)) {
const definedUri = URI.resolve(definitionUri, resource.uri);
targetUri =
workspace.find(definedUri, resource.uri)?.uri ??
URI.placeholder(definedUri.path);
} else {
targetUri =
workspace.find(link.target, resource.uri)?.uri ??
URI.placeholder(link.target);
}
break;
case 'link':
targetUri =
workspace.find(link.target, resource.uri)?.uri ??
URI.placeholder(URI.resolve(link.target, resource.uri).path);
break;
}
return targetUri;
}
dispose() {
this.disposables.forEach(d => d.dispose());
}
}
/**
* Traverses all the children of the given node, extracts
@@ -47,29 +171,50 @@ const getTextFromChildren = (root: Node): string => {
const tagsPlugin: ParserPlugin = {
name: 'tags',
onWillVisitTree: (tree, note) => {
note.tags = extractHashtags(note.source.text);
onDidFindProperties: (props, note, node) => {
if (isSome(props.tags)) {
const yamlTags = extractTagsFromProp(props.tags);
yamlTags.forEach(t => {
note.tags.push({
label: t,
range: astPositionToFoamRange(node.position!),
});
});
}
},
onDidFindProperties: (props, note) => {
const yamlTags = extractTagsFromProp(props.tags);
yamlTags.forEach(tag => note.tags.add(tag));
visit: (node, note) => {
if (node.type === 'text') {
const tags = extractHashtags((node as any).value);
tags.forEach(tag => {
let start = astPointToFoamPosition(node.position!.start);
start.character = start.character + tag.offset;
const end: Position = {
line: start.line,
character: start.character + tag.label.length + 1,
};
note.tags.push({
label: tag.label,
range: Range.createFromPosition(start, end),
});
});
}
},
};
const titlePlugin: ParserPlugin = {
name: 'title',
visit: (node, note) => {
if (note.title == null && node.type === 'heading' && node.depth === 1) {
if (note.title === '' && node.type === 'heading' && node.depth === 1) {
note.title =
((node as Parent)!.children?.[0]?.value as string) || note.title;
}
},
onDidFindProperties: (props, note) => {
// Give precendence to the title from the frontmatter if it exists
note.title = props.title ?? note.title;
note.title = props.title?.toString() ?? note.title;
},
onDidVisitTree: (tree, note) => {
if (note.title == null) {
if (note.title === '') {
note.title = URI.getBasename(note.uri);
}
},
@@ -77,12 +222,29 @@ const titlePlugin: ParserPlugin = {
const wikilinkPlugin: ParserPlugin = {
name: 'wikilink',
visit: (node, note) => {
visit: (node, note, noteSource) => {
if (node.type === 'wikiLink') {
const text = node.value as string;
const alias = node.data?.alias as string;
const literalContent = noteSource.substring(
node.position!.start.offset!,
node.position!.end.offset!
);
const hasAlias =
literalContent !== text && literalContent.includes(ALIAS_DIVIDER_CHAR);
note.links.push({
type: 'wikilink',
slug: node.value as string,
target: node.value as string,
rawText: literalContent,
label: hasAlias
? alias.trim()
: literalContent.substring(2, literalContent.length - 2),
target: hasAlias
? literalContent
.substring(2, literalContent.indexOf(ALIAS_DIVIDER_CHAR))
.replace(/\\/g, '')
.trim()
: text.trim(),
range: astPositionToFoamRange(node.position!),
});
}
@@ -128,16 +290,20 @@ const handleError = (
): void => {
const name = plugin.name || '';
Logger.warn(
`Error while executing [${fnName}] in plugin [${name}] for file [${uri?.path}]`,
`Error while executing [${fnName}] in plugin [${name}]. ${
uri ? 'for file [' + URI.toString(uri) : ']'
}.`,
e
);
};
export function createMarkdownParser(extraPlugins: ParserPlugin[]): NoteParser {
export function createMarkdownParser(
extraPlugins: ParserPlugin[]
): ResourceParser {
const parser = unified()
.use(markdownParse, { gfm: true })
.use(frontmatterPlugin, ['yaml'])
.use(wikiLinkPlugin);
.use(wikiLinkPlugin, { aliasDivider: ALIAS_DIVIDER_CHAR });
const plugins = [
titlePlugin,
@@ -155,9 +321,9 @@ export function createMarkdownParser(extraPlugins: ParserPlugin[]): NoteParser {
}
});
const foamParser: NoteParser = {
parse: (uri: URI, markdown: string): Note => {
Logger.debug('Parsing:', uri);
const foamParser: ResourceParser = {
parse: (uri: URI, markdown: string): Resource => {
Logger.debug('Parsing:', URI.toString(uri));
markdown = plugins.reduce((acc, plugin) => {
try {
return plugin.onWillParseMarkdown?.(acc) || acc;
@@ -169,12 +335,12 @@ export function createMarkdownParser(extraPlugins: ParserPlugin[]): NoteParser {
const tree = parser.parse(markdown);
const eol = detectNewline(markdown) || os.EOL;
var note: Note = {
var note: Resource = {
uri: uri,
type: 'note',
properties: {},
title: null,
tags: new Set(),
title: '',
tags: [],
links: [],
definitions: [],
source: {
@@ -200,8 +366,6 @@ export function createMarkdownParser(extraPlugins: ParserPlugin[]): NoteParser {
...note.properties,
...yamlProperties,
};
// Give precendence to the title from the frontmatter if it exists
note.title = note.properties.title ?? note.title;
// Update the start position of the note by exluding the metadata
note.source.contentStart = Position.create(
node.position!.end.line! + 2,
@@ -210,19 +374,22 @@ export function createMarkdownParser(extraPlugins: ParserPlugin[]): NoteParser {
for (let i = 0, len = plugins.length; i < len; i++) {
try {
plugins[i].onDidFindProperties?.(yamlProperties, note);
plugins[i].onDidFindProperties?.(yamlProperties, note, node);
} catch (e) {
handleError(plugins[i], 'onDidFindProperties', uri, e);
}
}
} catch (e) {
Logger.warn(`Error while parsing YAML for [${uri}]`, e);
Logger.warn(
`Error while parsing YAML for [${URI.toString(uri)}]`,
e
);
}
}
for (let i = 0, len = plugins.length; i < len; i++) {
try {
plugins[i].visit?.(node, note);
plugins[i].visit?.(node, note, markdown);
} catch (e) {
handleError(plugins[i], 'visit', uri, e);
}
@@ -286,7 +453,9 @@ export function createMarkdownReferences(
// Should never occur since we're already in a file,
if (source?.type !== 'note') {
console.warn(
`Note ${noteUri} note found in workspace when attempting to generate markdown reference list`
`Note ${URI.toString(
noteUri
)} note found in workspace when attempting to generate markdown reference list`
);
return [];
}
@@ -297,7 +466,11 @@ export function createMarkdownReferences(
const targetUri = workspace.resolveLink(source, link);
const target = workspace.find(targetUri);
if (isNone(target)) {
Logger.warn(`Link ${targetUri} in ${noteUri} is not valid.`);
Logger.warn(
`Link ${URI.toString(targetUri)} in ${URI.toString(
noteUri
)} is not valid.`
);
return null;
}
if (target.type === 'placeholder') {
@@ -310,8 +483,15 @@ export function createMarkdownReferences(
? relativePath
: dropExtension(relativePath);
// [wiki-link-text]: path/to/file.md "Page title"
return { label: link.slug, url: pathToNote, title: getTitle(target) };
// [wikilink-text]: path/to/file.md "Page title"
return {
label:
link.rawText.indexOf('[[') > -1
? link.rawText.substring(2, link.rawText.length - 2)
: link.rawText || link.label,
url: pathToNote,
title: target.title,
};
})
.filter(isSome)
.sort();
@@ -338,3 +518,7 @@ const astPositionToFoamRange = (pos: AstPosition): Range =>
pos.end.line - 1,
pos.end.column - 1
);
const isWikilink = (link: ResourceLink): link is WikiLink => {
return link.type === 'wikilink';
};

View File

@@ -0,0 +1,59 @@
import { IDisposable } from '../common/lifecycle';
import { IDataStore, IMatcher, Matcher } from '../services/datastore';
import { FoamConfig } from '../config';
import { FoamWorkspace } from './workspace';
import { FoamGraph } from './graph';
import { ResourceParser } from './note';
import { ResourceProvider } from './provider';
import { createMarkdownParser } from '../markdown-provider';
import { FoamTags } from './tags';
export interface Services {
dataStore: IDataStore;
parser: ResourceParser;
matcher: IMatcher;
}
export interface Foam extends IDisposable {
services: Services;
workspace: FoamWorkspace;
graph: FoamGraph;
config: FoamConfig;
tags: FoamTags;
}
export const bootstrap = async (
config: FoamConfig,
dataStore: IDataStore,
initialProviders: ResourceProvider[]
) => {
const parser = createMarkdownParser([]);
const matcher = new Matcher(
config.workspaceFolders,
config.includeGlobs,
config.ignoreGlobs
);
const workspace = new FoamWorkspace();
await Promise.all(initialProviders.map(p => workspace.registerProvider(p)));
const graph = FoamGraph.fromWorkspace(workspace, true);
const tags = FoamTags.fromWorkspace(workspace, true);
const foam: Foam = {
workspace,
graph,
tags,
config,
services: {
dataStore,
parser,
matcher,
},
dispose: () => {
workspace.dispose();
graph.dispose();
},
};
return foam;
};

View File

@@ -0,0 +1,240 @@
import { diff } from 'fast-array-diff';
import { isEqual } from 'lodash';
import { Resource, ResourceLink } from './note';
import { URI } from './uri';
import { IDisposable } from '../index';
import { FoamWorkspace, uriToResourceName } from './workspace';
import { Range } from './range';
export type Connection = {
source: URI;
target: URI;
link: ResourceLink;
};
const pathToPlaceholderId = (value: string) => value;
const uriToPlaceholderId = (uri: URI) => pathToPlaceholderId(uri.path);
export class FoamGraph implements IDisposable {
/**
* Placehoders by key / slug / value
*/
public readonly placeholders: Map<string, URI> = new Map();
/**
* Maps the connections starting from a URI
*/
public readonly links: Map<string, Connection[]> = new Map();
/**
* Maps the connections arriving to a URI
*/
public readonly backlinks: Map<string, Connection[]> = new Map();
/**
* List of disposables to destroy with the workspace
*/
private disposables: IDisposable[] = [];
constructor(private readonly workspace: FoamWorkspace) {}
public contains(uri: URI): boolean {
return this.getConnections(uri).length > 0;
}
public getAllNodes(): URI[] {
return [
...Array.from(this.placeholders.values()),
...this.workspace.list().map(r => r.uri),
];
}
public getAllConnections(): Connection[] {
return Array.from(this.links.values()).flat();
}
public getConnections(uri: URI): Connection[] {
return [
...(this.links.get(uri.path) || []),
...(this.backlinks.get(uri.path) || []),
];
}
public getLinks(uri: URI): Connection[] {
return this.links.get(uri.path) ?? [];
}
public getBacklinks(uri: URI): Connection[] {
return this.backlinks.get(uri.path) ?? [];
}
/**
* Computes all the links in the workspace, connecting notes and
* creating placeholders.
*
* @param workspace the target workspace
* @param keepMonitoring whether to recompute the links when the workspace changes
* @returns the FoamGraph
*/
public static fromWorkspace(
workspace: FoamWorkspace,
keepMonitoring: boolean = false
): FoamGraph {
let graph = new FoamGraph(workspace);
workspace.list().forEach(resource => graph.resolveResource(resource));
if (keepMonitoring) {
graph.disposables.push(
workspace.onDidAdd(resource => {
graph.updateLinksRelatedToAddedResource(resource);
}),
workspace.onDidUpdate(change => {
graph.updateLinksForResource(change.old, change.new);
}),
workspace.onDidDelete(resource => {
graph.updateLinksRelatedToDeletedResource(resource);
})
);
}
return graph;
}
private updateLinksRelatedToAddedResource(resource: Resource) {
// check if any existing connection can be filled by new resource
const name = uriToResourceName(resource.uri);
const placeholder = this.placeholders.get(name);
if (placeholder) {
this.placeholders.delete(name);
const resourcesToUpdate = this.backlinks.get(placeholder.path) ?? [];
resourcesToUpdate.forEach(res =>
this.resolveResource(this.workspace.get(res.source))
);
}
// resolve the resource
this.resolveResource(resource);
}
private updateLinksForResource(oldResource: Resource, newResource: Resource) {
if (oldResource.uri.path !== newResource.uri.path) {
throw new Error(
'Unexpected State: update should only be called on same resource ' +
{
old: oldResource,
new: newResource,
}
);
}
if (oldResource.type === 'note' && newResource.type === 'note') {
const patch = diff(oldResource.links, newResource.links, isEqual);
patch.removed.forEach(link => {
const target = this.workspace.resolveLink(oldResource, link);
return this.disconnect(oldResource.uri, target, link);
}, this);
patch.added.forEach(link => {
const target = this.workspace.resolveLink(newResource, link);
return this.connect(newResource.uri, target, link);
}, this);
}
return this;
}
private updateLinksRelatedToDeletedResource(resource: Resource) {
const uri = resource.uri;
// remove forward links from old resource
const resourcesPointedByDeletedNote = this.links.get(uri.path) ?? [];
this.links.delete(uri.path);
resourcesPointedByDeletedNote.forEach(connection =>
this.disconnect(uri, connection.target, connection.link)
);
// recompute previous links to old resource
const notesPointingToDeletedResource = this.backlinks.get(uri.path) ?? [];
this.backlinks.delete(uri.path);
notesPointingToDeletedResource.forEach(link =>
this.resolveResource(this.workspace.get(link.source))
);
return this;
}
private connect(source: URI, target: URI, link: ResourceLink) {
const connection = { source, target, link };
if (!this.links.has(source.path)) {
this.links.set(source.path, []);
}
this.links.get(source.path)?.push(connection);
if (!this.backlinks.get(target.path)) {
this.backlinks.set(target.path, []);
}
this.backlinks.get(target.path)?.push(connection);
if (URI.isPlaceholder(target)) {
this.placeholders.set(uriToPlaceholderId(target), target);
}
return this;
}
/**
* Removes a connection, or all connections, between the source and
* target resources
*
* @param workspace the Foam workspace
* @param source the source resource
* @param target the target resource
* @param link the link reference, or `true` to remove all links
* @returns the updated Foam workspace
*/
private disconnect(source: URI, target: URI, link: ResourceLink | true) {
const connectionsToKeep =
link === true
? (c: Connection) =>
!URI.isEqual(source, c.source) || !URI.isEqual(target, c.target)
: (c: Connection) => !isSameConnection({ source, target, link }, c);
this.links.set(
source.path,
this.links.get(source.path)?.filter(connectionsToKeep) ?? []
);
if (this.links.get(source.path)?.length === 0) {
this.links.delete(source.path);
}
this.backlinks.set(
target.path,
this.backlinks.get(target.path)?.filter(connectionsToKeep) ?? []
);
if (this.backlinks.get(target.path)?.length === 0) {
this.backlinks.delete(target.path);
if (URI.isPlaceholder(target)) {
this.placeholders.delete(uriToPlaceholderId(target));
}
}
return this;
}
public resolveResource(resource: Resource) {
this.links.delete(resource.uri.path);
// prettier-ignore
resource.links.forEach(link => {
const targetUri = this.workspace.resolveLink(resource, link);
this.connect(resource.uri, targetUri, link);
});
return this;
}
public dispose(): void {
this.disposables.forEach(d => d.dispose());
this.disposables = [];
}
}
// TODO move these utility fns to appropriate places
const isSameConnection = (a: Connection, b: Connection) =>
URI.isEqual(a.source, b.source) &&
URI.isEqual(a.target, b.target) &&
isSameLink(a.link, b.link);
const isSameLink = (a: ResourceLink, b: ResourceLink) =>
a.type === b.type && Range.isEqual(a.range, b.range);

View File

@@ -11,8 +11,9 @@ export interface NoteSource {
export interface WikiLink {
type: 'wikilink';
slug: string;
target: string;
label: string;
rawText: string;
range: Range;
}
@@ -23,7 +24,7 @@ export interface DirectLink {
range: Range;
}
export type NoteLink = WikiLink | DirectLink;
export type ResourceLink = WikiLink | DirectLink;
export interface NoteLinkDefinition {
label: string;
@@ -32,53 +33,45 @@ export interface NoteLinkDefinition {
range?: Range;
}
export interface BaseResource {
export interface Tag {
label: string;
range: Range;
}
export interface Resource {
uri: URI;
}
export interface Attachment extends BaseResource {
type: 'attachment';
}
export interface Placeholder extends BaseResource {
type: 'placeholder';
}
export interface Note extends BaseResource {
type: 'note';
title: string | null;
type: string;
title: string;
properties: any;
// sections: NoteSection[]
tags: Set<string>;
links: NoteLink[];
tags: Tag[];
links: ResourceLink[];
// TODO to remove
definitions: NoteLinkDefinition[];
source: NoteSource;
}
export type Resource = Note | Attachment | Placeholder;
export interface NoteParser {
parse: (uri: URI, text: string) => Note;
export interface ResourceParser {
parse: (uri: URI, text: string) => Resource;
}
export const isWikilink = (link: NoteLink): link is WikiLink => {
return link.type === 'wikilink';
};
export abstract class Resource {
public static sortByTitle(a: Resource, b: Resource) {
return a.title.localeCompare(b.title);
}
export const getTitle = (resource: Resource): string => {
return resource.type === 'note'
? resource.title ?? URI.getBasename(resource.uri)
: URI.getBasename(resource.uri);
};
export const isNote = (resource: Resource): resource is Note => {
return resource.type === 'note';
};
export const isPlaceholder = (resource: Resource): resource is Placeholder => {
return resource.type === 'placeholder';
};
export const isAttachment = (resource: Resource): resource is Attachment => {
return resource.type === 'attachment';
};
public static isResource(thing: any): thing is Resource {
if (!thing) {
return false;
}
return (
URI.isUri((thing as Resource).uri) &&
typeof (thing as Resource).title === 'string' &&
typeof (thing as Resource).type === 'string' &&
typeof (thing as Resource).properties === 'object' &&
typeof (thing as Resource).tags === 'object' &&
typeof (thing as Resource).links === 'object'
);
}
}

View File

@@ -0,0 +1,17 @@
import { IDisposable } from 'common/lifecycle';
import { ResourceLink, URI } from 'index';
import { Resource } from './note';
import { FoamWorkspace } from './workspace';
export interface ResourceProvider extends IDisposable {
init: (workspace: FoamWorkspace) => Promise<void>;
supports: (uri: URI) => boolean;
read: (uri: URI) => Promise<string | null>;
readAsMarkdown: (uri: URI) => Promise<string | null>;
fetch: (uri: URI) => Promise<Resource | null>;
resolveLink: (
workspace: FoamWorkspace,
resource: Resource,
link: ResourceLink
) => URI;
}

View File

@@ -65,4 +65,8 @@ export abstract class Range {
Position.isEqual(r1.start, r2.start) && Position.isEqual(r1.end, r2.end)
);
}
static isBefore(a: Range, b: Range): number {
return a.start.line - b.start.line || a.start.character - b.start.character;
}
}

View File

@@ -0,0 +1,81 @@
import { FoamWorkspace } from './workspace';
import { URI } from './uri';
import { IDisposable } from '../index';
import { Resource } from './note';
export class FoamTags implements IDisposable {
public readonly tags: Map<string, URI[]> = new Map();
/**
* List of disposables to destroy with the tags
*/
private disposables: IDisposable[] = [];
/**
* Computes all tags in the workspace and keep them up-to-date
*
* @param workspace the target workspace
* @param keepMonitoring whether to recompute the links when the workspace changes
* @returns the FoamTags
*/
public static fromWorkspace(
workspace: FoamWorkspace,
keepMonitoring: boolean = false
): FoamTags {
let tags = new FoamTags();
workspace
.list()
.forEach(resource => tags.addResourceFromTagIndex(resource));
if (keepMonitoring) {
tags.disposables.push(
workspace.onDidAdd(resource => {
tags.addResourceFromTagIndex(resource);
}),
workspace.onDidUpdate(change => {
tags.updateResourceWithinTagIndex(change.old, change.new);
}),
workspace.onDidDelete(resource => {
tags.removeResourceFromTagIndex(resource);
})
);
}
return tags;
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
this.disposables = [];
}
updateResourceWithinTagIndex(oldResource: Resource, newResource: Resource) {
this.removeResourceFromTagIndex(oldResource);
this.addResourceFromTagIndex(newResource);
}
addResourceFromTagIndex(resource: Resource) {
new Set(resource.tags.map(t => t.label)).forEach(tag => {
const tagMeta = this.tags.get(tag) ?? [];
tagMeta.push(resource.uri);
this.tags.set(tag, tagMeta);
});
}
removeResourceFromTagIndex(resource: Resource) {
resource.tags.forEach(t => {
const tag = t.label;
if (this.tags.has(tag)) {
const remainingLocations = this.tags
.get(tag)
?.filter(uri => !URI.isEqual(uri, resource.uri));
if (remainingLocations && remainingLocations.length > 0) {
this.tags.set(tag, remainingLocations);
} else {
this.tags.delete(tag);
}
}
});
}
}

View File

@@ -1,8 +1,10 @@
// Some code in this file coming from https://github.com/microsoft/vscode/
// `URI` is mostly compatible with VSCode's `Uri`.
// Having a Foam-specific URI object allows for easier maintenance of the API.
// See https://github.com/foambubble/foam/pull/537 for more context.
// Some code in this file comes from https://github.com/microsoft/vscode/main/src/vs/base/common/uri.ts
// See LICENSE for details
import * as paths from 'path';
import { statSync } from 'fs';
import { CharCode } from '../common/charCode';
import { isWindows } from '../common/platform';
@@ -149,6 +151,10 @@ export abstract class URI {
return URI.file(posix.dirname(uri.path));
}
static getFileNameWithoutExtension(uri: URI) {
return URI.getBasename(uri).replace(/\.[^.]+$/, '');
}
/**
* Uses a placeholder URI, and a reference directory, to generate
* the URI of the corresponding resource
@@ -250,7 +256,7 @@ export abstract class URI {
);
}
static isMarkdownFile(uri: URI): boolean {
return uri.path.endsWith('md') && statSync(URI.toFsPath(uri)).isFile();
return uri.path.endsWith('.md');
}
}

View File

@@ -1,18 +1,10 @@
import { diff } from 'fast-array-diff';
import { isEqual } from 'lodash';
import * as path from 'path';
import { Resource, NoteLink, Note } from './note';
import { Range } from './range';
import { Resource, ResourceLink } from './note';
import { URI } from './uri';
import { isSome, isNone } from '../utils';
import { Emitter } from '../common/event';
import { IDisposable } from '../index';
export type Connection = {
source: URI;
target: URI;
link: NoteLink;
};
import { ResourceProvider } from './provider';
export function getReferenceType(
reference: URI | string
@@ -34,11 +26,9 @@ const pathToResourceId = (pathValue: string) => {
};
const uriToResourceId = (uri: URI) => pathToResourceId(uri.path);
const pathToResourceName = (pathValue: string) => path.parse(pathValue).name;
const uriToResourceName = (uri: URI) => pathToResourceName(uri.path);
const pathToPlaceholderId = (value: string) => value;
const uriToPlaceholderId = (uri: URI) => pathToPlaceholderId(uri.path);
const pathToResourceName = (pathValue: string) =>
path.parse(pathValue).name.toLowerCase();
export const uriToResourceName = (uri: URI) => pathToResourceName(uri.path);
export class FoamWorkspace implements IDisposable {
private onDidAddEmitter = new Emitter<Resource>();
@@ -48,207 +38,68 @@ export class FoamWorkspace implements IDisposable {
onDidUpdate = this.onDidUpdateEmitter.event;
onDidDelete = this.onDidDeleteEmitter.event;
private providers: ResourceProvider[] = [];
/**
* Resources by key / slug
*/
private resourcesByName: { [key: string]: string[] } = {};
private resourcesByName: Map<string, string[]> = new Map();
/**
* Resources by URI
*/
private resources: { [key: string]: Resource } = {};
/**
* Placehoders by key / slug / value
*/
private placeholders: { [key: string]: Resource } = {};
private resources: Map<string, Resource> = new Map();
/**
* Maps the connections starting from a URI
*/
private links: { [key: string]: Connection[] } = {};
/**
* Maps the connections arriving to a URI
*/
private backlinks: { [key: string]: Connection[] } = {};
/**
* List of disposables to destroy with the workspace
*/
disposables: IDisposable[] = [];
registerProvider(provider: ResourceProvider) {
this.providers.push(provider);
return provider.init(this);
}
exists(uri: URI) {
return FoamWorkspace.exists(this, uri);
}
list() {
return FoamWorkspace.list(this);
}
get(uri: URI) {
return FoamWorkspace.get(this, uri);
}
find(uri: URI | string) {
return FoamWorkspace.find(this, uri);
}
set(resource: Resource) {
return FoamWorkspace.set(this, resource);
}
delete(uri: URI) {
return FoamWorkspace.delete(this, uri);
}
resolveLink(note: Note, link: NoteLink) {
return FoamWorkspace.resolveLink(this, note, link);
}
resolveLinks(keepMonitoring: boolean = false) {
return FoamWorkspace.resolveLinks(this, keepMonitoring);
}
getAllConnections() {
return FoamWorkspace.getAllConnections(this);
}
getConnections(uri: URI) {
return FoamWorkspace.getConnections(this, uri);
}
getLinks(uri: URI) {
return FoamWorkspace.getLinks(this, uri);
}
getBacklinks(uri: URI) {
return FoamWorkspace.getBacklinks(this, uri);
}
dispose(): void {
this.onDidAddEmitter.dispose();
this.onDidDeleteEmitter.dispose();
this.onDidUpdateEmitter.dispose();
this.disposables.forEach(d => d.dispose());
}
public static resolveLink(
workspace: FoamWorkspace,
note: Note,
link: NoteLink
): URI {
let targetUri: URI | undefined;
switch (link.type) {
case 'wikilink':
const definitionUri = note.definitions.find(
def => def.label === link.slug
)?.url;
if (isSome(definitionUri)) {
const definedUri = URI.resolve(definitionUri, note.uri);
targetUri =
FoamWorkspace.find(workspace, definedUri, note.uri)?.uri ??
URI.placeholder(definedUri.path);
} else {
targetUri =
FoamWorkspace.find(workspace, link.slug, note.uri)?.uri ??
URI.placeholder(link.slug);
}
break;
case 'link':
targetUri =
FoamWorkspace.find(workspace, link.target, note.uri)?.uri ??
URI.placeholder(URI.resolve(link.target, note.uri).path);
break;
}
return targetUri;
}
/**
* Computes all the links in the workspace, connecting notes and
* creating placeholders.
*
* @param workspace the target workspace
* @param keepMonitoring whether to recompute the links when the workspace changes
* @returns the resolved workspace
*/
public static resolveLinks(
workspace: FoamWorkspace,
keepMonitoring: boolean = false
): FoamWorkspace {
workspace.links = {};
workspace.backlinks = {};
workspace.placeholders = {};
workspace = Object.values(workspace.list()).reduce(
(w, resource) => FoamWorkspace.resolveResource(w, resource),
workspace
);
if (keepMonitoring) {
workspace.disposables.push(
workspace.onDidAdd(resource => {
FoamWorkspace.updateLinksRelatedToAddedResource(workspace, resource);
}),
workspace.onDidUpdate(change => {
FoamWorkspace.updateLinksForResource(
workspace,
change.old,
change.new
);
}),
workspace.onDidDelete(resource => {
FoamWorkspace.updateLinksRelatedToDeletedResource(
workspace,
resource
);
})
);
}
return workspace;
}
public static getAllConnections(workspace: FoamWorkspace): Connection[] {
return Object.values(workspace.links).flat();
}
public static getConnections(
workspace: FoamWorkspace,
uri: URI
): Connection[] {
return [
...(workspace.links[uri.path] || []),
...(workspace.backlinks[uri.path] || []),
];
}
public static getLinks(workspace: FoamWorkspace, uri: URI): Connection[] {
return workspace.links[uri.path] ?? [];
}
public static getBacklinks(workspace: FoamWorkspace, uri: URI): Connection[] {
return workspace.backlinks[uri.path] ?? [];
}
public static set(
workspace: FoamWorkspace,
resource: Resource
): FoamWorkspace {
if (resource.type === 'placeholder') {
workspace.placeholders[uriToPlaceholderId(resource.uri)] = resource;
return workspace;
}
const id = uriToResourceId(resource.uri);
const old = FoamWorkspace.find(workspace, resource.uri);
const old = this.find(resource.uri);
const name = uriToResourceName(resource.uri);
workspace.resources[id] = resource;
workspace.resourcesByName[name] = workspace.resourcesByName[name] ?? [];
workspace.resourcesByName[name].push(id);
this.resources.set(id, resource);
if (!this.resourcesByName.has(name)) {
this.resourcesByName.set(name, []);
}
this.resourcesByName.get(name)?.push(id);
isSome(old)
? workspace.onDidUpdateEmitter.fire({ old: old, new: resource })
: workspace.onDidAddEmitter.fire(resource);
return workspace;
? this.onDidUpdateEmitter.fire({ old: old, new: resource })
: this.onDidAddEmitter.fire(resource);
return this;
}
public static exists(workspace: FoamWorkspace, uri: URI): boolean {
return isSome(workspace.resources[uriToResourceId(uri)]);
delete(uri: URI) {
const id = uriToResourceId(uri);
const deleted = this.resources.get(id);
this.resources.delete(id);
const name = uriToResourceName(uri);
this.resourcesByName.set(
name,
this.resourcesByName.get(name)?.filter(resId => resId !== id) ?? []
);
if (this.resourcesByName.get(name)?.length === 0) {
this.resourcesByName.delete(name);
}
isSome(deleted) && this.onDidDeleteEmitter.fire(deleted);
return deleted ?? null;
}
public static list(workspace: FoamWorkspace): Resource[] {
return [
...Object.values(workspace.resources),
...Object.values(workspace.placeholders),
];
public exists(uri: URI): boolean {
return (
!URI.isPlaceholder(uri) &&
isSome(this.resources.get(uriToResourceId(uri)))
);
}
public static get(workspace: FoamWorkspace, uri: URI): Resource {
const note = FoamWorkspace.find(workspace, uri);
public list(): Resource[] {
return Array.from(this.resources.values());
}
public get(uri: URI): Resource {
const note = this.find(uri);
if (isSome(note)) {
return note;
} else {
@@ -256,44 +107,36 @@ export class FoamWorkspace implements IDisposable {
}
}
public static find(
workspace: FoamWorkspace,
resourceId: URI | string,
reference?: URI
): Resource | null {
public find(resourceId: URI | string, reference?: URI): Resource | null {
const refType = getReferenceType(resourceId);
switch (refType) {
case 'uri':
const uri = resourceId as URI;
if (uri.scheme === 'placeholder') {
return uri.path in workspace.placeholders
? { type: 'placeholder', uri: uri }
: null;
} else {
return FoamWorkspace.exists(workspace, uri)
? workspace.resources[uriToResourceId(uri)]
: null;
}
return this.exists(uri)
? this.resources.get(uriToResourceId(uri)) ?? null
: null;
case 'key':
const name = pathToResourceName(resourceId as string);
const paths = workspace.resourcesByName[name];
let paths = this.resourcesByName.get(name);
if (isNone(paths) || paths.length === 0) {
const placeholderId = pathToPlaceholderId(resourceId as string);
return workspace.placeholders[placeholderId] ?? null;
paths = this.resourcesByName.get(resourceId as string);
}
if (isNone(paths) || paths.length === 0) {
return null;
}
// prettier-ignore
const sortedPaths = paths.length === 1
? paths
: paths.sort((a, b) => a.localeCompare(b));
return workspace.resources[sortedPaths[0]];
return this.resources.get(sortedPaths[0]) ?? null;
case 'absolute-path':
const resourceUri = URI.file(resourceId as string);
return (
workspace.resources[uriToResourceId(resourceUri)] ??
workspace.placeholders[uriToPlaceholderId(resourceUri)]
);
return this.resources.get(uriToResourceId(resourceUri)) ?? null;
case 'relative-path':
if (isNone(reference)) {
@@ -301,185 +144,35 @@ export class FoamWorkspace implements IDisposable {
}
const relativePath = resourceId as string;
const targetUri = URI.computeRelativeURI(reference, relativePath);
return (
workspace.resources[uriToResourceId(targetUri)] ??
workspace.placeholders[pathToPlaceholderId(resourceId as string)]
);
return this.resources.get(uriToResourceId(targetUri)) ?? null;
default:
throw new Error('Unexpected reference type: ' + refType);
}
}
public static delete(workspace: FoamWorkspace, uri: URI): Resource | null {
const id = uriToResourceId(uri);
const deleted = workspace.resources[id];
delete workspace.resources[id];
const name = uriToResourceName(uri);
workspace.resourcesByName[name] =
workspace.resourcesByName[name]?.filter(resId => resId !== id) ?? [];
if (workspace.resourcesByName[name].length === 0) {
delete workspace.resourcesByName[name];
}
isSome(deleted) && workspace.onDidDeleteEmitter.fire(deleted);
return deleted ?? null;
}
public static resolveResource(workspace: FoamWorkspace, resource: Resource) {
if (resource.type === 'note') {
delete workspace.links[resource.uri.path];
// prettier-ignore
resource.links.forEach(link => {
const targetUri = FoamWorkspace.resolveLink(workspace, resource, link);
workspace = FoamWorkspace.connect(workspace, resource.uri, targetUri, link);
});
}
return workspace;
}
private static updateLinksForResource(
workspace: FoamWorkspace,
oldResource: Resource,
newResource: Resource
) {
if (oldResource.uri.path !== newResource.uri.path) {
throw new Error(
'Unexpected State: update should only be called on same resource ' +
{
old: oldResource,
new: newResource,
}
);
}
if (oldResource.type === 'note' && newResource.type === 'note') {
const patch = diff(oldResource.links, newResource.links, isEqual);
workspace = patch.removed.reduce((ws, link) => {
const target = ws.resolveLink(oldResource, link);
return FoamWorkspace.disconnect(ws, oldResource.uri, target, link);
}, workspace);
workspace = patch.added.reduce((ws, link) => {
const target = ws.resolveLink(newResource, link);
return FoamWorkspace.connect(ws, newResource.uri, target, link);
}, workspace);
}
return workspace;
}
private static updateLinksRelatedToAddedResource(
workspace: FoamWorkspace,
resource: Resource
) {
// check if any existing connection can be filled by new resource
const name = uriToResourceName(resource.uri);
if (name in workspace.placeholders) {
const placeholder = workspace.placeholders[name];
delete workspace.placeholders[name];
const resourcesToUpdate = workspace.backlinks[placeholder.uri.path] ?? [];
workspace = resourcesToUpdate.reduce(
(ws, res) => FoamWorkspace.resolveResource(ws, ws.get(res.source)),
workspace
);
}
// resolve the resource
workspace = FoamWorkspace.resolveResource(workspace, resource);
}
private static updateLinksRelatedToDeletedResource(
workspace: FoamWorkspace,
resource: Resource
) {
const uri = resource.uri;
// remove forward links from old resource
const resourcesPointedByDeletedNote = workspace.links[uri.path] ?? [];
delete workspace.links[uri.path];
workspace = resourcesPointedByDeletedNote.reduce(
(ws, connection) =>
FoamWorkspace.disconnect(ws, uri, connection.target, connection.link),
workspace
public resolveLink(resource: Resource, link: ResourceLink): URI {
// TODO add tests
const provider = this.providers.find(p => p.supports(resource.uri));
return (
provider?.resolveLink(this, resource, link) ??
URI.placeholder(link.target)
);
// recompute previous links to old resource
const notesPointingToDeletedResource = workspace.backlinks[uri.path] ?? [];
delete workspace.backlinks[uri.path];
workspace = notesPointingToDeletedResource.reduce(
(ws, link) => FoamWorkspace.resolveResource(ws, ws.get(link.source)),
workspace
);
return workspace;
}
private static connect(
workspace: FoamWorkspace,
source: URI,
target: URI,
link: NoteLink
) {
if (URI.isPlaceholder(target)) {
// we can only add placeholders when links are being resolved
workspace = FoamWorkspace.set(workspace, {
type: 'placeholder',
uri: target,
});
}
const connection = { source, target, link };
workspace.links[source.path] = workspace.links[source.path] ?? [];
workspace.links[source.path].push(connection);
workspace.backlinks[target.path] = workspace.backlinks[target.path] ?? [];
workspace.backlinks[target.path].push(connection);
return workspace;
public read(uri: URI): Promise<string | null> {
const provider = this.providers.find(p => p.supports(uri));
return provider?.read(uri) ?? Promise.resolve(null);
}
/**
* Removes a connection, or all connections, between the source and
* target resources
*
* @param workspace the Foam workspace
* @param source the source resource
* @param target the target resource
* @param link the link reference, or `true` to remove all links
* @returns the updated Foam workspace
*/
private static disconnect(
workspace: FoamWorkspace,
source: URI,
target: URI,
link: NoteLink | true
) {
const connectionsToKeep =
link === true
? (c: Connection) =>
!URI.isEqual(source, c.source) || !URI.isEqual(target, c.target)
: (c: Connection) => !isSameConnection({ source, target, link }, c);
public readAsMarkdown(uri: URI): Promise<string | null> {
const provider = this.providers.find(p => p.supports(uri));
return provider?.readAsMarkdown(uri) ?? Promise.resolve(null);
}
workspace.links[source.path] =
workspace.links[source.path]?.filter(connectionsToKeep) ?? [];
if (workspace.links[source.path].length === 0) {
delete workspace.links[source.path];
}
workspace.backlinks[target.path] =
workspace.backlinks[target.path]?.filter(connectionsToKeep) ?? [];
if (workspace.backlinks[target.path].length === 0) {
delete workspace.backlinks[target.path];
if (URI.isPlaceholder(target)) {
delete workspace.placeholders[uriToPlaceholderId(target)];
}
}
return workspace;
public dispose(): void {
this.onDidAddEmitter.dispose();
this.onDidDeleteEmitter.dispose();
this.onDidUpdateEmitter.dispose();
}
}
// TODO move these utility fns to appropriate places
const isSameConnection = (a: Connection, b: Connection) =>
URI.isEqual(a.source, b.source) &&
URI.isEqual(a.target, b.target) &&
isSameLink(a.link, b.link);
const isSameLink = (a: NoteLink, b: NoteLink) =>
a.type === b.type && Range.isEqual(a.range, b.range);

View File

@@ -1,86 +0,0 @@
import * as fs from 'fs';
import path from 'path';
import { Node } from 'unist';
import { isNotNull } from '../utils';
import { Note } from '../model/note';
import unified from 'unified';
import { FoamConfig } from '../config';
import { Logger } from '../utils/log';
import { URI } from '../model/uri';
export interface FoamPlugin {
name: string;
description?: string;
parser?: ParserPlugin;
}
export interface ParserPlugin {
name?: string;
visit?: (node: Node, note: Note) => void;
onDidInitializeParser?: (parser: unified.Processor) => void;
onWillParseMarkdown?: (markdown: string) => string;
onWillVisitTree?: (tree: Node, note: Note) => void;
onDidVisitTree?: (tree: Node, note: Note) => void;
onDidFindProperties?: (properties: any, note: Note) => void;
}
export interface PluginConfig {
enabled?: boolean;
pluginFolders?: string[];
}
export const SETTINGS_PATH = 'experimental.localPlugins';
export async function loadPlugins(config: FoamConfig): Promise<FoamPlugin[]> {
const pluginConfig = config.get<PluginConfig>(SETTINGS_PATH, {});
const isFeatureEnabled = pluginConfig.enabled ?? false;
if (!isFeatureEnabled) {
return [];
}
const pluginDirs: URI[] =
pluginConfig.pluginFolders?.map(URI.file) ??
findPluginDirs(config.workspaceFolders);
const plugins = await Promise.all(
pluginDirs
.filter(dir => fs.statSync(URI.toFsPath(dir)).isDirectory)
.map(async dir => {
try {
const pluginFile = path.join(URI.toFsPath(dir), 'index.js');
fs.accessSync(pluginFile);
Logger.info(`Found plugin at [${pluginFile}]. Loading..`);
const plugin = validate(await import(pluginFile));
return plugin;
} catch (e) {
Logger.error(`Error while loading plugin at [${dir}] - skipping`, e);
return null;
}
})
);
return plugins.filter(isNotNull);
}
function findPluginDirs(workspaceFolders: URI[]) {
return workspaceFolders
.map(root => URI.joinPath(root, '.foam', 'plugins'))
.reduce((acc, pluginDir) => {
try {
const content = fs
.readdirSync(URI.toFsPath(pluginDir))
.map(dir => URI.joinPath(pluginDir, dir));
return [
...acc,
...content.filter(c => fs.statSync(URI.toFsPath(c)).isDirectory()),
];
} catch {
return acc;
}
}, [] as URI[]);
}
function validate(plugin: any): FoamPlugin {
if (!plugin.name) {
throw new Error('Plugin must export `name` string property');
}
return plugin;
}

View File

@@ -1,141 +1,87 @@
import glob from 'glob';
import { promisify } from 'util';
import micromatch from 'micromatch';
import fs from 'fs';
import { Event, Emitter } from '../common/event';
import { URI } from '../model/uri';
import { FoamConfig } from '../config';
import { Logger } from '../utils/log';
import { isSome } from '../utils';
import { IDisposable } from '../common/lifecycle';
import glob from 'glob';
import { promisify } from 'util';
import { isWindows } from '../common/platform';
const findAllFiles = promisify(glob);
export interface IWatcher {
export interface IMatcher {
/**
* An event which fires on file creation.
*/
onDidCreate: Event<URI>;
/**
* An event which fires on file change.
*/
onDidChange: Event<URI>;
/**
* An event which fires on file deletion.
*/
onDidDelete: Event<URI>;
}
/**
* Represents a source of files and content
*/
export interface IDataStore {
/**
* List the files available in the store
*/
listFiles: () => Promise<URI[]>;
/**
* Read the content of the file from the store
* Filters the given list of URIs, keepin only the ones that
* are matched by this Matcher
*
* Returns `null` in case of errors while reading
* @param files the URIs to check
*/
read: (uri: URI) => Promise<string | null>;
match(files: URI[]): URI[];
/**
* Returns whether the given URI is a match in
* this data store
* Returns whether this URI is matched by this Matcher
*
* @param uri the URI to check
*/
isMatch: (uri: URI) => boolean;
isMatch(uri: URI): boolean;
/**
* An event which fires on file creation.
* The include globs
*/
onDidCreate: Event<URI>;
include: string[];
/**
* An event which fires on file change.
* The exclude lobs
*/
onDidChange: Event<URI>;
/**
* An event which fires on file deletion.
*/
onDidDelete: Event<URI>;
exclude: string[];
}
/**
* File system based data store
* The matcher requires the path to be in unix format, so if we are in windows
* we convert the fs path on the way in and out
*/
export class FileDataStore implements IDataStore, IDisposable {
readonly onDidChangeEmitter = new Emitter<URI>();
readonly onDidCreateEmitter = new Emitter<URI>();
readonly onDidDeleteEmitter = new Emitter<URI>();
readonly onDidCreate: Event<URI> = this.onDidCreateEmitter.event;
readonly onDidChange: Event<URI> = this.onDidChangeEmitter.event;
readonly onDidDelete: Event<URI> = this.onDidDeleteEmitter.event;
export const toMatcherPathFormat = isWindows
? (uri: URI) => URI.toFsPath(uri).replace(/\\/g, '/')
: (uri: URI) => URI.toFsPath(uri);
private _folders: readonly string[];
private _includeGlobs: string[] = [];
private _ignoreGlobs: string[] = [];
private _disposables: IDisposable[] = [];
export const toFsPath = isWindows
? (path: string): string => path.replace(/\//g, '\\')
: (path: string): string => path;
constructor(config: FoamConfig, watcher?: IWatcher) {
this._folders = config.workspaceFolders.map(f =>
URI.toFsPath(f).replace(/\\/g, '/')
);
Logger.info('Workspace folders: ', this._folders);
export class Matcher implements IMatcher {
public readonly folders: string[];
public readonly include: string[] = [];
public readonly exclude: string[] = [];
this._folders.forEach(folder => {
constructor(
baseFolders: URI[],
include: string[] = ['**/*'],
exclude: string[] = []
) {
this.folders = baseFolders.map(toMatcherPathFormat);
Logger.info('Workspace folders: ', this.folders);
this.folders.forEach(folder => {
const withFolder = folderPlusGlob(folder);
this._includeGlobs.push(
...config.includeGlobs.map(glob => {
if (glob.endsWith('*')) {
glob = `${glob}\\.(md|mdx|markdown)`;
}
this.include.push(
...include.map(glob => {
return withFolder(glob);
})
);
this._ignoreGlobs.push(...config.ignoreGlobs.map(withFolder));
this.exclude.push(...exclude.map(withFolder));
});
Logger.info('Glob patterns', {
includeGlobs: this._includeGlobs,
ignoreGlobs: this._ignoreGlobs,
includeGlobs: this.include,
ignoreGlobs: this.exclude,
});
if (isSome(watcher)) {
this._disposables.push(
watcher.onDidCreate(uri => {
if (this.isMatch(uri)) {
Logger.info(`Created: ${uri.path}`);
this.onDidCreateEmitter.fire(uri);
}
}),
watcher.onDidChange(uri => {
if (this.isMatch(uri)) {
Logger.info(`Updated: ${uri.path}`);
this.onDidChangeEmitter.fire(uri);
}
}),
watcher.onDidDelete(uri => {
if (this.isMatch(uri)) {
Logger.info(`Deleted: ${uri.path}`);
this.onDidDeleteEmitter.fire(uri);
}
})
);
}
}
match(files: URI[]) {
const matches = micromatch(
files.map(f => URI.toFsPath(f)),
this._includeGlobs,
this.include,
{
ignore: this._ignoreGlobs,
ignore: this.exclude,
nocase: true,
format: toFsPath,
}
);
return matches.map(URI.file);
@@ -144,17 +90,35 @@ export class FileDataStore implements IDataStore, IDisposable {
isMatch(uri: URI) {
return this.match([uri]).length > 0;
}
}
async listFiles() {
const files = (
await Promise.all(
this._folders.map(async folder => {
const res = await findAllFiles(folderPlusGlob(folder)('**/*'));
return res.map(URI.file);
})
)
).flat();
return this.match(files);
/**
* Represents a source of files and content
*/
export interface IDataStore {
/**
* List the files matching the given glob from the
* store
*/
list: (glob: string, ignoreGlob?: string | string[]) => Promise<URI[]>;
/**
* Read the content of the file from the store
*
* Returns `null` in case of errors while reading
*/
read: (uri: URI) => Promise<string | null>;
}
/**
* File system based data store
*/
export class FileDataStore implements IDataStore {
async list(glob: string, ignoreGlob?: string | string[]): Promise<URI[]> {
const res = await findAllFiles(glob, {
ignore: ignoreGlob,
});
return res.map(URI.file);
}
async read(uri: URI) {
@@ -167,18 +131,14 @@ export class FileDataStore implements IDataStore, IDisposable {
return null;
}
}
dispose() {
this._disposables.forEach(d => d.dispose());
}
}
const folderPlusGlob = (folder: string) => (glob: string): string => {
export const folderPlusGlob = (folder: string) => (glob: string): string => {
if (folder.substr(-1) === '/') {
folder = folder.slice(0, -1);
}
if (glob.startsWith('/')) {
glob = glob.slice(1);
}
return `${folder}/${glob}`;
return folder.length > 0 ? `${folder}/${glob}` : glob;
};

View File

@@ -1,16 +1,21 @@
import { isSome } from './core';
const HASHTAG_REGEX = /(^|\s)#([0-9]*[\p{L}_-][\p{L}\p{N}_-]*)/gmu;
const WORD_REGEX = /(^|\s)([0-9]*[\p{L}_-][\p{L}\p{N}_-]*)/gmu;
const HASHTAG_REGEX = /(?<=^|\s)#([0-9]*[\p{L}/_-][\p{L}\p{N}/_-]*)/gmu;
const WORD_REGEX = /(?<=^|\s)([0-9]*[\p{L}/_-][\p{L}\p{N}/_-]*)/gmu;
export const extractHashtags = (text: string): Set<string> => {
export const extractHashtags = (
text: string
): Array<{ label: string; offset: number }> => {
return isSome(text)
? new Set(Array.from(text.matchAll(HASHTAG_REGEX), m => m[2].trim()))
: new Set();
? Array.from(text.matchAll(HASHTAG_REGEX)).map(m => ({
label: m[1],
offset: m.index!,
}))
: [];
};
export const extractTagsFromProp = (prop: string | string[]): Set<string> => {
export const extractTagsFromProp = (prop: string | string[]): string[] => {
const text = Array.isArray(prop) ? prop.join(' ') : prop;
return isSome(text)
? new Set(Array.from(text.matchAll(WORD_REGEX)).map(m => m[2].trim()))
: new Set();
? Array.from(text.matchAll(WORD_REGEX)).map(m => m[1])
: [];
};

View File

@@ -1,3 +1,3 @@
# Roam Document
[[Second Roam Document]]
[[Second Roam Document]]

View File

@@ -1 +1 @@
# Second Roam Document
# Second Roam Document

View File

@@ -9,4 +9,4 @@ All the link references are correct in this file.
[//begin]: # "Autogenerated link references for markdown compatibility"
[first-document]: first-document "First Document"
[second-document]: second-document "Second Document"
[//end]: # "Autogenerated link references"
[//end]: # "Autogenerated link references"

View File

@@ -1,5 +1,8 @@
import path from 'path';
import { NoteLinkDefinition, Note, Attachment } from '../src/model/note';
import { FoamWorkspace } from '../src';
import { NoteLinkDefinition, Resource } from '../src/model/note';
import { IDataStore, Matcher } from '../src/services/datastore';
import { MarkdownResourceProvider } from '../src/markdown-provider';
import { Range } from '../src/model/range';
import { URI } from '../src/model/uri';
import { Logger } from '../src/utils/log';
@@ -19,11 +22,22 @@ const eol = '\n';
*/
export const strToUri = URI.file;
export const createAttachment = (params: { uri: string }): Attachment => {
return {
uri: strToUri(params.uri),
type: 'attachment',
};
export const noOpDataStore = (): IDataStore => ({
read: _ => Promise.resolve(''),
list: _ => Promise.resolve([]),
});
export const createTestWorkspace = () => {
const workspace = new FoamWorkspace();
const matcher = new Matcher([URI.file('/')], ['**/*']);
const provider = new MarkdownResourceProvider(
matcher,
undefined,
undefined,
noOpDataStore()
);
workspace.registerProvider(provider);
return workspace;
};
export const createTestNote = (params: {
@@ -33,7 +47,8 @@ export const createTestNote = (params: {
links?: Array<{ slug: string } | { to: string }>;
text?: string;
root?: URI;
}): Note => {
tags?: string[];
}): Resource => {
const root = params.root ?? URI.file('/');
return {
uri: URI.resolve(params.uri, root),
@@ -41,7 +56,11 @@ export const createTestNote = (params: {
properties: {},
title: params.title ?? path.parse(strToUri(params.uri).path).base,
definitions: params.definitions ?? [],
tags: new Set(),
tags:
params.tags?.map(t => ({
label: t,
range: Range.create(0, 0, 0, 0),
})) ?? [],
links: params.links
? params.links.map((link, index) => {
const range = Range.create(
@@ -53,10 +72,10 @@ export const createTestNote = (params: {
return 'slug' in link
? {
type: 'wikilink',
slug: link.slug,
target: link.slug,
label: link.slug,
range: range,
text: 'link text',
rawText: 'link text',
}
: {
type: 'link',

View File

@@ -1,72 +1,93 @@
import { createConfigFromObject } from '../src/config';
import { Logger } from '../src/utils/log';
import { URI } from '../src/model/uri';
import { FileDataStore } from '../src';
import { FileDataStore, Matcher } from '../src';
import { toMatcherPathFormat } from '../src/services/datastore';
Logger.setLevel('error');
const testFolder = URI.joinPath(URI.file(__dirname), 'test-datastore');
function makeConfig(params: { include: string[]; ignore: string[] }) {
return createConfigFromObject(
[testFolder],
params.include,
params.ignore,
{}
);
}
describe('Datastore', () => {
it('defaults to including nothing and exclude nothing', async () => {
const ds = new FileDataStore(
makeConfig({
include: [],
ignore: [],
})
);
expect(await ds.listFiles()).toHaveLength(0);
describe('Matcher', () => {
it('generates globs with the base dir provided', () => {
const matcher = new Matcher([testFolder], ['*'], []);
expect(matcher.folders).toEqual([toMatcherPathFormat(testFolder)]);
expect(matcher.include).toEqual([
toMatcherPathFormat(URI.joinPath(testFolder, '*')),
]);
});
it('returns only markdown files', async () => {
const ds = new FileDataStore(
makeConfig({
include: ['**/*'],
ignore: [],
})
);
const res = toStringSet(await ds.listFiles());
expect(res).toEqual(
makeAbsolute([
'/file-a.md',
'/info/file-b.md',
'/docs/file-in-nm.md',
'/info/docs/file-in-sub-nm.md',
])
);
it('defaults to including everything and excluding nothing', () => {
const matcher = new Matcher([testFolder]);
expect(matcher.exclude).toEqual([]);
expect(matcher.include).toEqual([
toMatcherPathFormat(URI.joinPath(testFolder, '**', '*')),
]);
});
it('supports excludes', async () => {
const ds = new FileDataStore(
makeConfig({
include: ['**/*'],
ignore: ['**/docs/**'],
})
);
const res = toStringSet(await ds.listFiles());
expect(res).toEqual(makeAbsolute(['/file-a.md', '/info/file-b.md']));
it('supports multiple includes', () => {
const matcher = new Matcher([testFolder], ['g1', 'g2'], []);
expect(matcher.exclude).toEqual([]);
expect(matcher.include).toEqual([
toMatcherPathFormat(URI.joinPath(testFolder, 'g1')),
toMatcherPathFormat(URI.joinPath(testFolder, 'g2')),
]);
});
it('has a match method to filter strings', () => {
const matcher = new Matcher([testFolder], ['*.md'], []);
const files = [
URI.joinPath(testFolder, 'file1.md'),
URI.joinPath(testFolder, 'file2.md'),
URI.joinPath(testFolder, 'file3.mdx'),
URI.joinPath(testFolder, 'sub', 'file4.md'),
];
expect(matcher.match(files)).toEqual([
URI.joinPath(testFolder, 'file1.md'),
URI.joinPath(testFolder, 'file2.md'),
]);
});
it('has a isMatch method to see whether a file is matched or not', () => {
const matcher = new Matcher([testFolder], ['*.md'], []);
const files = [
URI.joinPath(testFolder, 'file1.md'),
URI.joinPath(testFolder, 'file2.md'),
URI.joinPath(testFolder, 'file3.mdx'),
URI.joinPath(testFolder, 'sub', 'file4.md'),
];
expect(matcher.isMatch(files[0])).toEqual(true);
expect(matcher.isMatch(files[1])).toEqual(true);
expect(matcher.isMatch(files[2])).toEqual(false);
expect(matcher.isMatch(files[3])).toEqual(false);
});
it('happy path', () => {
const matcher = new Matcher([URI.file('/')], ['**/*'], ['**/*.pdf']);
expect(matcher.isMatch(URI.file('/file.md'))).toBeTruthy();
expect(matcher.isMatch(URI.file('/file.pdf'))).toBeFalsy();
expect(matcher.isMatch(URI.file('/dir/file.md'))).toBeTruthy();
expect(matcher.isMatch(URI.file('/dir/file.pdf'))).toBeFalsy();
});
it('ignores files in the exclude list', () => {
const matcher = new Matcher([testFolder], ['*.md'], ['file1.*']);
const files = [
URI.joinPath(testFolder, 'file1.md'),
URI.joinPath(testFolder, 'file2.md'),
URI.joinPath(testFolder, 'file3.mdx'),
URI.joinPath(testFolder, 'sub', 'file4.md'),
];
expect(matcher.isMatch(files[0])).toEqual(false);
expect(matcher.isMatch(files[1])).toEqual(true);
expect(matcher.isMatch(files[2])).toEqual(false);
expect(matcher.isMatch(files[3])).toEqual(false);
});
});
function toStringSet(URI: URI[]) {
return new Set(URI.map(uri => uri.path.toLocaleLowerCase()));
}
function makeAbsolute(files: string[]) {
return new Set(
files.map(f =>
URI.joinPath(testFolder, f)
.path.toLocaleLowerCase()
.replace(/\\/g, '/')
)
);
}
describe('Datastore', () => {
it('uses the matcher to get the file list', async () => {
const matcher = new Matcher([testFolder], ['**/*.md'], []);
const ds = new FileDataStore();
expect((await ds.list(matcher.include[0])).length).toEqual(4);
});
});

View File

@@ -1,29 +1,36 @@
import * as path from 'path';
import { generateHeading } from '../../src/janitor';
import { bootstrap } from '../../src/bootstrap';
import { createConfigFromFolders } from '../../src/config';
import { Note } from '../../src';
import { FileDataStore } from '../../src/services/datastore';
import { Resource } from '../../src/model/note';
import { FileDataStore, Matcher } from '../../src/services/datastore';
import { Logger } from '../../src/utils/log';
import { FoamWorkspace } from '../../src/model/workspace';
import { URI } from '../../src/model/uri';
import { Range } from '../../src/model/range';
import { MarkdownResourceProvider, bootstrap } from '../../src';
Logger.setLevel('error');
describe('generateHeadings', () => {
let _workspace: FoamWorkspace;
const findBySlug = (slug: string): Note => {
const findBySlug = (slug: string): Resource => {
return _workspace
.list()
.find(res => URI.getBasename(res.uri) === slug) as Note;
.find(res => URI.getBasename(res.uri) === slug) as Resource;
};
beforeAll(async () => {
const config = createConfigFromFolders([
URI.file(path.join(__dirname, '..', '__scaffold__')),
]);
const foam = await bootstrap(config, new FileDataStore(config));
const mdProvider = new MarkdownResourceProvider(
new Matcher(
config.workspaceFolders,
config.includeGlobs,
config.ignoreGlobs
)
);
const foam = await bootstrap(config, new FileDataStore(), [mdProvider]);
_workspace = foam.workspace;
});

View File

@@ -1,30 +1,37 @@
import * as path from 'path';
import { generateLinkReferences } from '../../src/janitor';
import { bootstrap } from '../../src/bootstrap';
import { createConfigFromFolders } from '../../src/config';
import { Note, Range } from '../../src';
import { FileDataStore } from '../../src/services/datastore';
import { FileDataStore, Matcher } from '../../src/services/datastore';
import { Logger } from '../../src/utils/log';
import { FoamWorkspace } from '../../src/model/workspace';
import { URI } from '../../src/model/uri';
import { Resource } from '../../src/model/note';
import { Range } from '../../src/model/range';
import { MarkdownResourceProvider, bootstrap } from '../../src';
Logger.setLevel('error');
describe('generateLinkReferences', () => {
let _workspace: FoamWorkspace;
const findBySlug = (slug: string): Note => {
const findBySlug = (slug: string): Resource => {
return _workspace
.list()
.find(res => URI.getBasename(res.uri) === slug) as Note;
.find(res => URI.getBasename(res.uri) === slug) as Resource;
};
beforeAll(async () => {
const config = createConfigFromFolders([
URI.file(path.join(__dirname, '..', '__scaffold__')),
]);
_workspace = await bootstrap(config, new FileDataStore(config)).then(
foam => foam.workspace
const mdProvider = new MarkdownResourceProvider(
new Matcher(
config.workspaceFolders,
config.includeGlobs,
config.ignoreGlobs
)
);
const foam = await bootstrap(config, new FileDataStore(), [mdProvider]);
_workspace = foam.workspace;
});
it('initialised test graph correctly', () => {
@@ -107,6 +114,6 @@ describe('generateLinkReferences', () => {
* @param note the note we are adjusting for
* @param text starting text, using a \n line separator
*/
function textForNote(note: Note, text: string): string {
function textForNote(note: Resource, text: string): string {
return text.split('\n').join(note.source.eol);
}

View File

@@ -1,13 +1,15 @@
import {
createMarkdownParser,
createMarkdownReferences,
ParserPlugin,
} from '../src/markdown-provider';
import { DirectLink } from '../src/model/note';
import { ParserPlugin } from '../src/plugins';
import { DirectLink, WikiLink } from '../src/model/note';
import { Logger } from '../src/utils/log';
import { uriToSlug } from '../src/utils/slug';
import { URI } from '../src/model/uri';
import { FoamWorkspace } from '../src/model/workspace';
import { FoamGraph } from '../src/model/graph';
import { createTestWorkspace } from './core.test';
import { Range } from '../src/model/range';
Logger.setLevel('error');
@@ -43,7 +45,7 @@ const createNoteFromMarkdown = (path: string, content: string) =>
describe('Markdown loader', () => {
it('Converts markdown to notes', () => {
const workspace = new FoamWorkspace();
const workspace = createTestWorkspace();
workspace.set(createNoteFromMarkdown('/page-a.md', pageA));
workspace.set(createNoteFromMarkdown('/page-b.md', pageB));
workspace.set(createNoteFromMarkdown('/page-c.md', pageC));
@@ -104,7 +106,7 @@ this is a [link to intro](#introduction)
});
it('Parses wikilinks correctly', () => {
const workspace = new FoamWorkspace();
const workspace = createTestWorkspace();
const noteA = createNoteFromMarkdown('/page-a.md', pageA);
const noteB = createNoteFromMarkdown('/page-b.md', pageB);
const noteC = createNoteFromMarkdown('/page-c.md', pageC);
@@ -116,19 +118,73 @@ this is a [link to intro](#introduction)
.set(noteB)
.set(noteC)
.set(noteD)
.set(noteE)
.resolveLinks();
.set(noteE);
const graph = FoamGraph.fromWorkspace(workspace);
expect(workspace.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(workspace.getLinks(noteA.uri).map(l => l.target)).toEqual([
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([
noteB.uri,
noteC.uri,
noteD.uri,
noteE.uri,
]);
});
it('Parses backlinks with an alias', () => {
const note = createNoteFromMarkdown(
'/path/to/page-a.md',
'this is [[link|link alias]]. A link with spaces [[other link | spaced]]'
);
expect(note.links.length).toEqual(2);
let link = note.links[0] as WikiLink;
expect(link.type).toEqual('wikilink');
expect(link.rawText).toEqual('[[link|link alias]]');
expect(link.label).toEqual('link alias');
expect(link.target).toEqual('link');
link = note.links[1] as WikiLink;
expect(link.type).toEqual('wikilink');
expect(link.rawText).toEqual('[[other link | spaced]]');
expect(link.label).toEqual('spaced');
expect(link.target).toEqual('other link');
});
it('Skips wikilinks in codeblocks', () => {
const noteA = createNoteFromMarkdown(
'/dir1/page-a.md',
`
this is some text with our [[first-wikilink]].
\`\`\`
this is inside a [[codeblock]]
\`\`\`
this is some text with our [[second-wikilink]].
`
);
expect(noteA.links.map(l => l.label)).toEqual([
'first-wikilink',
'second-wikilink',
]);
});
it('Skips wikilinks in inlined codeblocks', () => {
const noteA = createNoteFromMarkdown(
'/dir1/page-a.md',
`
this is some text with our [[first-wikilink]].
this is \`inside a [[codeblock]]\`
this is some text with our [[second-wikilink]].
`
);
expect(noteA.links.map(l => l.label)).toEqual([
'first-wikilink',
'second-wikilink',
]);
});
});
describe('Note Title', () => {
@@ -170,6 +226,26 @@ date: 20-12-12
expect(note.title).toBe('Note Title');
});
it('should support numbers', () => {
const note1 = createNoteFromMarkdown('/157.md', `hello`);
expect(note1.title).toBe('157');
const note2 = createNoteFromMarkdown('/157.md', `# 158`);
expect(note2.title).toBe('158');
const note3 = createNoteFromMarkdown(
'/157.md',
`
---
title: 159
---
# 158
`
);
expect(note3.title).toBe('159');
});
it('should not break on empty titles (see #276)', () => {
const note = createNoteFromMarkdown(
'/Hello Page.md',
@@ -233,7 +309,7 @@ title: - one
describe('wikilinks definitions', () => {
it('can generate links without file extension when includeExtension = false', () => {
const workspace = new FoamWorkspace();
const workspace = createTestWorkspace();
const noteA = createNoteFromMarkdown('/dir1/page-a.md', pageA);
workspace
.set(noteA)
@@ -245,7 +321,7 @@ describe('wikilinks definitions', () => {
});
it('can generate links with file extension when includeExtension = true', () => {
const workspace = new FoamWorkspace();
const workspace = createTestWorkspace();
const noteA = createNoteFromMarkdown('/dir1/page-a.md', pageA);
workspace
.set(noteA)
@@ -257,7 +333,7 @@ describe('wikilinks definitions', () => {
});
it('use relative paths', () => {
const workspace = new FoamWorkspace();
const workspace = createTestWorkspace();
const noteA = createNoteFromMarkdown('/dir1/page-a.md', pageA);
workspace
.set(noteA)
@@ -277,13 +353,51 @@ describe('tags plugin', () => {
const noteA = createNoteFromMarkdown(
'/dir1/page-a.md',
`
# this is a heading
this is some #text that includes #tags we #care-about.
# this is a #heading
#this is some #text that includes #tags we #care-about.
`
);
expect(noteA.tags).toEqual(new Set(['text', 'tags', 'care-about']));
expect(noteA.tags).toEqual([
{ label: 'heading', range: Range.create(1, 12, 1, 20) },
{ label: 'this', range: Range.create(2, 0, 2, 5) },
{ label: 'text', range: Range.create(2, 14, 2, 19) },
{ label: 'tags', range: Range.create(2, 34, 2, 39) },
{ label: 'care-about', range: Range.create(2, 43, 2, 54) },
]);
});
it('will skip tags in codeblocks', () => {
const noteA = createNoteFromMarkdown(
'/dir1/page-a.md',
`
this is some #text that includes #tags we #care-about.
\`\`\`
this is a #codeblock
\`\`\`
`
);
expect(noteA.tags.map(t => t.label)).toEqual([
'text',
'tags',
'care-about',
]);
});
it('will skip tags in inlined codeblocks', () => {
const noteA = createNoteFromMarkdown(
'/dir1/page-a.md',
`
this is some #text that includes #tags we #care-about.
this is a \`inlined #codeblock\`
`
);
expect(noteA.tags.map(t => t.label)).toEqual([
'text',
'tags',
'care-about',
]);
});
it('can find tags as text in yaml', () => {
const noteA = createNoteFromMarkdown(
'/dir1/page-a.md',
@@ -295,9 +409,14 @@ tags: hello, world this_is_good
this is some #text that includes #tags we #care-about.
`
);
expect(noteA.tags).toEqual(
new Set(['text', 'tags', 'care-about', 'hello', 'world', 'this_is_good'])
);
expect(noteA.tags.map(t => t.label)).toEqual([
'hello',
'world',
'this_is_good',
'text',
'tags',
'care-about',
]);
});
it('can find tags as array in yaml', () => {
@@ -311,9 +430,34 @@ tags: [hello, world, this_is_good]
this is some #text that includes #tags we #care-about.
`
);
expect(noteA.tags).toEqual(
new Set(['text', 'tags', 'care-about', 'hello', 'world', 'this_is_good'])
expect(noteA.tags.map(t => t.label)).toEqual([
'hello',
'world',
'this_is_good',
'text',
'tags',
'care-about',
]);
});
it('provides rough range for tags in yaml', () => {
// For now it's enough to just get the YAML block range
// in the future we might want to be more specific
const noteA = createNoteFromMarkdown(
'/dir1/page-a.md',
`
---
tags: [hello, world, this_is_good]
---
# this is a heading
this is some text
`
);
expect(noteA.tags[0]).toEqual({
label: 'hello',
range: Range.create(1, 0, 3, 3),
});
});
});

View File

@@ -1,63 +0,0 @@
import path from 'path';
import { loadPlugins } from '../src/plugins';
import { createMarkdownParser } from '../src/markdown-provider';
import { FoamConfig, createConfigFromObject } from '../src/config';
import { URI } from '../src/model/uri';
import { Logger } from '../src/utils/log';
Logger.setLevel('error');
const config: FoamConfig = createConfigFromObject([], [], [], {
experimental: {
localPlugins: {
enabled: true,
pluginFolders: [path.join(__dirname, 'test-plugin')],
},
},
});
describe('Foam plugins', () => {
it('will not load if feature is not explicitly enabled', async () => {
let plugins = await loadPlugins(createConfigFromObject([], [], [], {}));
expect(plugins.length).toEqual(0);
plugins = await loadPlugins(
createConfigFromObject([], [], [], {
experimental: {
localPlugins: {},
},
})
);
expect(plugins.length).toEqual(0);
plugins = await loadPlugins(
createConfigFromObject([], [], [], {
experimental: {
localPlugins: {
enabled: false,
},
},
})
);
expect(plugins.length).toEqual(0);
});
it('can load', async () => {
const plugins = await loadPlugins(config);
expect(plugins.length).toEqual(1);
expect(plugins[0].name).toEqual('Test Plugin');
});
it('supports parser extension', async () => {
const plugins = await loadPlugins(config);
const parserPlugin = plugins[0].parser;
expect(parserPlugin).not.toBeUndefined();
const parser = createMarkdownParser([parserPlugin!]);
const note = parser.parse(
URI.file('/path/to/a'),
`
# This is a note with header
and some content`
);
expect(note.properties.hasHeading).toBeTruthy();
});
});

View File

@@ -0,0 +1,138 @@
import { FoamTags } from '../src/model/tags';
import { createTestNote, createTestWorkspace } from './core.test';
describe('FoamTags', () => {
it('Collects tags from a list of resources', () => {
const ws = createTestWorkspace();
const pageA = createTestNote({
uri: '/page-a.md',
title: 'Page A',
links: [{ slug: 'placeholder-link' }],
tags: ['primary', 'secondary'],
});
const pageB = createTestNote({
uri: '/page-b.md',
title: 'Page B',
links: [{ slug: 'placeholder-link' }],
tags: ['primary', 'third'],
});
ws.set(pageA);
ws.set(pageB);
const tags = FoamTags.fromWorkspace(ws);
expect(tags.tags).toEqual(
new Map([
['primary', [pageA.uri, pageB.uri]],
['secondary', [pageA.uri]],
['third', [pageB.uri]],
])
);
});
it('Updates an existing tag when a note is tagged with an existing tag', () => {
const ws = createTestWorkspace();
const page = createTestNote({
uri: '/page-a.md',
title: 'Page A',
links: [{ slug: 'placeholder-link' }],
tags: ['primary'],
});
const taglessPage = createTestNote({
uri: '/page-b.md',
title: 'Page B',
});
ws.set(page);
ws.set(taglessPage);
const tags = FoamTags.fromWorkspace(ws);
expect(tags.tags).toEqual(new Map([['primary', [page.uri]]]));
const newPage = createTestNote({
uri: '/page-b.md',
title: 'Page B',
tags: ['primary'],
});
tags.updateResourceWithinTagIndex(taglessPage, newPage);
expect(tags.tags).toEqual(new Map([['primary', [page.uri, newPage.uri]]]));
});
it('Replaces the tag when a note is updated with an altered tag', () => {
const ws = createTestWorkspace();
const page = createTestNote({
uri: '/page-a.md',
title: 'Page A',
links: [{ slug: 'placeholder-link' }],
tags: ['primary'],
});
ws.set(page);
const tags = FoamTags.fromWorkspace(ws);
expect(tags.tags).toEqual(new Map([['primary', [page.uri]]]));
const pageEdited = createTestNote({
uri: '/page-a.md',
title: 'Page A',
links: [{ slug: 'placeholder-link' }],
tags: ['new'],
});
tags.updateResourceWithinTagIndex(page, pageEdited);
expect(tags.tags).toEqual(new Map([['new', [page.uri]]]));
});
it('Updates the metadata of a tag when the note is moved', () => {
const ws = createTestWorkspace();
const page = createTestNote({
uri: '/page-a.md',
title: 'Page A',
links: [{ slug: 'placeholder-link' }],
tags: ['primary'],
});
ws.set(page);
const tags = FoamTags.fromWorkspace(ws);
expect(tags.tags).toEqual(new Map([['primary', [page.uri]]]));
const pageEdited = createTestNote({
uri: '/new-place/page-a.md',
title: 'Page A',
links: [{ slug: 'placeholder-link' }],
tags: ['primary'],
});
tags.updateResourceWithinTagIndex(page, pageEdited);
expect(tags.tags).toEqual(new Map([['primary', [pageEdited.uri]]]));
});
it('Updates the metadata of a tag when a note is delete', () => {
const ws = createTestWorkspace();
const page = createTestNote({
uri: '/page-a.md',
title: 'Page A',
links: [{ slug: 'placeholder-link' }],
tags: ['primary'],
});
ws.set(page);
const tags = FoamTags.fromWorkspace(ws);
expect(tags.tags).toEqual(new Map([['primary', [page.uri]]]));
tags.removeResourceFromTagIndex(page);
expect(tags.tags).toEqual(new Map());
});
});

View File

@@ -1,20 +0,0 @@
const middleware = next => ({
setNote: note => {
note.properties['injectedByMiddleware'] = true;
return next.setNote(note);
},
});
const parser = {
visit: (node, note) => {
if (node.type === 'heading') {
note.properties.hasHeading = true;
}
},
};
module.exports = {
name: 'Test Plugin',
graphMiddleware: middleware,
parser: parser,
};

View File

@@ -1,6 +1,9 @@
import { Logger } from '../src';
import { URI } from '../src/model/uri';
import { uriToSlug } from '../src/utils/slug';
Logger.setLevel('error');
describe('Foam URIs', () => {
describe('URI parsing', () => {
const base = URI.file('/path/to/file.md');

View File

@@ -4,35 +4,55 @@ import { Logger } from '../src/utils/log';
Logger.setLevel('error');
describe('hashtag extraction', () => {
it('returns empty list if no tags are present', () => {
expect(extractHashtags('hello world')).toEqual([]);
});
it('works with simple strings', () => {
expect(extractHashtags('hello #world on #this planet')).toEqual(
new Set(['world', 'this'])
);
expect(
extractHashtags('hello #world on #this planet').map(t => t.label)
).toEqual(['world', 'this']);
});
it('detects the offset of the tag', () => {
expect(extractHashtags('#hello')).toEqual([{ label: 'hello', offset: 0 }]);
expect(extractHashtags(' #hello')).toEqual([{ label: 'hello', offset: 1 }]);
expect(extractHashtags('to #hello')).toEqual([
{ label: 'hello', offset: 3 },
]);
});
it('works with tags at beginning or end of text', () => {
expect(extractHashtags('#hello world on this #planet')).toEqual(
new Set(['hello', 'planet'])
);
expect(
extractHashtags('#hello world on this #planet').map(t => t.label)
).toEqual(['hello', 'planet']);
});
it('supports _ and -', () => {
expect(extractHashtags('#hello-world on #this_planet')).toEqual(
new Set(['hello-world', 'this_planet'])
);
expect(
extractHashtags('#hello-world on #this_planet').map(t => t.label)
).toEqual(['hello-world', 'this_planet']);
});
it('supports nested tags', () => {
expect(
extractHashtags('#parent/child on #planet').map(t => t.label)
).toEqual(['parent/child', 'planet']);
});
it('ignores tags that only have numbers in text', () => {
expect(
extractHashtags('this #123 tag should be ignore, but not #123four')
).toEqual(new Set(['123four']));
extractHashtags('this #123 tag should be ignore, but not #123four').map(
t => t.label
)
).toEqual(['123four']);
});
it('supports unicode letters like Chinese charaters', () => {
expect(
extractHashtags(`
this #tag_with_unicode_letters_汉字, pure Chinese tag like #纯中文标签 and
other mixed tags like #标签1 #123四 should work
`)
).toEqual(
new Set(['tag_with_unicode_letters_汉字', '纯中文标签', '标签1', '123四'])
);
`).map(t => t.label)
).toEqual([
'tag_with_unicode_letters_汉字',
'纯中文标签',
'标签1',
'123四',
]);
});
it('ignores hashes in plain text urls and links', () => {
@@ -42,8 +62,8 @@ describe('hashtag extraction', () => {
https://site.com/home/#section3a
[link](https://site.com/#section4) with [link2](https://site.com/home#section5) #control
hello world
`)
).toEqual(new Set(['control']));
`).map(t => t.label)
).toEqual(['control']);
});
it('ignores hashes in links to sections', () => {
@@ -52,6 +72,6 @@ describe('hashtag extraction', () => {
this is a wikilink to [[#section1]] in the file and a [[link#section2]] in another
this is a [link](#section3) to a section
`)
).toEqual(new Set());
).toEqual([]);
});
});

View File

@@ -1,6 +1,7 @@
import { FoamWorkspace, getReferenceType } from '../src/model/workspace';
import { getReferenceType } from '../src/model/workspace';
import { FoamGraph } from '../src/model/graph';
import { Logger } from '../src/utils/log';
import { createTestNote, createAttachment } from './core.test';
import { createTestNote, createTestWorkspace } from './core.test';
import { URI } from '../src/model/uri';
Logger.setLevel('error');
@@ -25,7 +26,7 @@ describe('Reference types', () => {
describe('Workspace resources', () => {
it('Adds notes to workspace', () => {
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(createTestNote({ uri: '/page-a.md' }));
ws.set(createTestNote({ uri: '/page-b.md' }));
ws.set(createTestNote({ uri: '/page-c.md' }));
@@ -38,25 +39,24 @@ describe('Workspace resources', () => {
).toEqual(['/page-a.md', '/page-b.md', '/page-c.md']);
});
it('Listing resources includes notes, attachments and placeholders', () => {
const ws = new FoamWorkspace();
it('Listing resources includes all notes', () => {
const ws = createTestWorkspace();
ws.set(createTestNote({ uri: '/page-a.md' }));
ws.set(createAttachment({ uri: '/file.pdf' }));
ws.set({ type: 'placeholder', uri: URI.placeholder('place-holder') });
ws.set(createTestNote({ uri: '/file.pdf' }));
expect(
ws
.list()
.map(n => n.uri.path)
.sort()
).toEqual(['/file.pdf', '/page-a.md', 'place-holder']);
).toEqual(['/file.pdf', '/page-a.md']);
});
it('Fails if getting non-existing note', () => {
const noteA = createTestNote({
uri: '/path/to/page-a.md',
});
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA);
const uri = URI.file('/path/to/another/page-b.md');
@@ -64,9 +64,36 @@ describe('Workspace resources', () => {
expect(ws.find(uri)).toBeNull();
expect(() => ws.get(uri)).toThrow();
});
it('Should work with a resource named like a JS prototype property', () => {
const ws = createTestWorkspace();
const noteA = createTestNote({ uri: '/somewhere/constructor.md' });
ws.set(noteA);
expect(ws.list()).toEqual([noteA]);
});
});
describe('Workspace links', () => {
describe('Graph', () => {
it('contains notes and placeholders', () => {
const ws = createTestWorkspace();
ws.set(
createTestNote({
uri: '/page-a.md',
links: [{ slug: 'placeholder-link' }],
})
);
ws.set(createTestNote({ uri: '/file.pdf' }));
const graph = FoamGraph.fromWorkspace(ws);
expect(
graph
.getAllNodes()
.map(uri => uri.path)
.sort()
).toEqual(['/file.pdf', '/page-a.md', 'placeholder-link']);
});
it('Supports multiple connections between the same resources', () => {
const noteA = createTestNote({
uri: '/path/to/note-a.md',
@@ -75,11 +102,11 @@ describe('Workspace links', () => {
uri: '/note-b.md',
links: [{ to: noteA.uri.path }, { to: noteA.uri.path }],
});
const ws = new FoamWorkspace();
ws.set(noteA)
.set(noteB)
.resolveLinks();
expect(ws.getBacklinks(noteA.uri)).toEqual([
const ws = createTestWorkspace()
.set(noteA)
.set(noteB);
const graph = FoamGraph.fromWorkspace(ws);
expect(graph.getBacklinks(noteA.uri)).toEqual([
{
source: noteB.uri,
target: noteA.uri,
@@ -100,21 +127,22 @@ describe('Workspace links', () => {
uri: '/note-b.md',
links: [{ to: noteA.uri.path }, { to: noteA.uri.path }],
});
const ws = new FoamWorkspace();
ws.set(noteA)
.set(noteB)
.resolveLinks(true);
const ws = createTestWorkspace()
.set(noteA)
.set(noteB);
const graph = FoamGraph.fromWorkspace(ws, true);
expect(ws.getBacklinks(noteA.uri).length).toEqual(2);
expect(graph.getBacklinks(noteA.uri).length).toEqual(2);
const noteBBis = createTestNote({
uri: '/note-b.md',
links: [{ to: noteA.uri.path }],
});
ws.set(noteBBis);
expect(ws.getBacklinks(noteA.uri).length).toEqual(1);
expect(graph.getBacklinks(noteA.uri).length).toEqual(1);
ws.dispose();
graph.dispose();
});
});
@@ -135,16 +163,16 @@ describe('Wikilinks', () => {
{ slug: 'placeholder-test' },
],
});
const ws = new FoamWorkspace();
ws.set(noteA)
const ws = createTestWorkspace()
.set(noteA)
.set(createTestNote({ uri: '/somewhere/page-b.md' }))
.set(createTestNote({ uri: '/path/another/page-c.md' }))
.set(createTestNote({ uri: '/absolute/path/page-d.md' }))
.set(createTestNote({ uri: '/absolute/path/page-e.md' }))
.resolveLinks();
.set(createTestNote({ uri: '/absolute/path/page-e.md' }));
const graph = FoamGraph.fromWorkspace(ws);
expect(
ws
graph
.getLinks(noteA.uri)
.map(link => link.target.path)
.sort()
@@ -162,8 +190,8 @@ describe('Wikilinks', () => {
uri: '/path/to/page-a.md',
links: [{ slug: 'page-b' }],
});
const ws = new FoamWorkspace();
ws.set(noteA)
const ws = createTestWorkspace()
.set(noteA)
.set(
createTestNote({
uri: '/somewhere/page-b.md',
@@ -181,11 +209,11 @@ describe('Wikilinks', () => {
uri: '/absolute/path/page-d.md',
links: [{ slug: '../to/page-a.md' }],
})
)
.resolveLinks();
);
const graph = FoamGraph.fromWorkspace(ws);
expect(
ws
graph
.getBacklinks(noteA.uri)
.map(link => link.source.path)
.sort()
@@ -193,7 +221,7 @@ describe('Wikilinks', () => {
});
it('Uses wikilink definitions when available to resolve target', () => {
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
const noteA = createTestNote({
uri: '/somewhere/from/page-a.md',
links: [{ slug: 'page-b' }],
@@ -205,14 +233,13 @@ describe('Wikilinks', () => {
const noteB = createTestNote({
uri: '/somewhere/to/page-b.md',
});
ws.set(noteA)
.set(noteB)
.resolveLinks();
ws.set(noteA).set(noteB);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getAllConnections()[0]).toEqual({
expect(graph.getAllConnections()[0]).toEqual({
source: noteA.uri,
target: noteB.uri,
link: expect.objectContaining({ type: 'wikilink', slug: 'page-b' }),
link: expect.objectContaining({ type: 'wikilink', label: 'page-b' }),
});
});
@@ -224,13 +251,13 @@ describe('Wikilinks', () => {
const noteB1 = createTestNote({ uri: '/path/to/another/page-b.md' });
const noteB2 = createTestNote({ uri: '/path/to/more/page-b.md' });
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA)
.set(noteB1)
.set(noteB2)
.resolveLinks();
.set(noteB2);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri)).toEqual([
expect(graph.getLinks(noteA.uri)).toEqual([
{
source: noteA.uri,
target: noteB1.uri,
@@ -248,14 +275,14 @@ describe('Wikilinks', () => {
const noteB2 = createTestNote({ uri: '/path/to/more/page-b.md' });
const noteB3 = createTestNote({ uri: '/path/to/yet/page-b.md' });
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA)
.set(noteB1)
.set(noteB2)
.set(noteB3)
.resolveLinks();
.set(noteB3);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([
noteB2.uri,
noteB3.uri,
]);
@@ -271,22 +298,22 @@ describe('Wikilinks', () => {
{ slug: 'attachment-b' },
],
});
const attachmentA = createAttachment({
const attachmentA = createTestNote({
uri: '/path/to/more/attachment-a.pdf',
});
const attachmentB = createAttachment({
const attachmentB = createTestNote({
uri: '/path/to/more/attachment-b.pdf',
});
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA)
.set(attachmentA)
.set(attachmentB)
.resolveLinks();
.set(attachmentB);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getBacklinks(attachmentA.uri).map(l => l.source)).toEqual([
expect(graph.getBacklinks(attachmentA.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(ws.getBacklinks(attachmentB.uri).map(l => l.source)).toEqual([
expect(graph.getBacklinks(attachmentB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
});
@@ -296,19 +323,19 @@ describe('Wikilinks', () => {
uri: '/path/to/page-a.md',
links: [{ slug: 'attachment-a' }],
});
const attachmentA = createAttachment({
const attachmentA = createTestNote({
uri: '/path/to/more/attachment-a.pdf',
});
const attachmentABis = createAttachment({
const attachmentABis = createTestNote({
uri: '/path/to/attachment-a.pdf',
});
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA)
.set(attachmentA)
.set(attachmentABis)
.resolveLinks();
.set(attachmentABis);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([
attachmentABis.uri,
]);
});
@@ -318,22 +345,67 @@ describe('Wikilinks', () => {
uri: '/path/to/page-a.md',
links: [{ slug: 'attachment-a' }],
});
const attachmentA = createAttachment({
const attachmentA = createTestNote({
uri: '/path/to/more/attachment-a.pdf',
});
const attachmentABis = createAttachment({
const attachmentABis = createTestNote({
uri: '/path/to/attachment-a.pdf',
});
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA)
.set(attachmentABis)
.set(attachmentA)
.resolveLinks();
.set(attachmentA);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([
attachmentABis.uri,
]);
});
it('Allows for dendron-style wikilinks, including a dot', () => {
const noteA = createTestNote({
uri: '/path/to/page-a.md',
links: [{ slug: 'dendron.style' }],
});
const noteB1 = createTestNote({ uri: '/path/to/another/dendron.style.md' });
const ws = createTestWorkspace();
ws.set(noteA).set(noteB1);
const graph = FoamGraph.fromWorkspace(ws);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB1.uri]);
});
it('Handles capatalization of files and wikilinks correctly', () => {
const noteA = createTestNote({
uri: '/path/to/page-a.md',
links: [
// uppercased filename, lowercased slug
{ slug: 'page-b' },
// lowercased filename, camelcased wikilink
{ slug: 'Page-C' },
// lowercased filename, lowercased wikilink
{ slug: 'page-d' },
],
});
const ws = createTestWorkspace()
.set(noteA)
.set(createTestNote({ uri: '/somewhere/PAGE-B.md' }))
.set(createTestNote({ uri: '/path/another/page-c.md' }))
.set(createTestNote({ uri: '/path/another/page-d.md' }));
const graph = FoamGraph.fromWorkspace(ws);
expect(
graph
.getLinks(noteA.uri)
.map(link => link.target.path)
.sort()
).toEqual([
'/path/another/page-c.md',
'/path/another/page-d.md',
'/somewhere/PAGE-B.md',
]);
});
});
describe('markdown direct links', () => {
@@ -349,22 +421,24 @@ describe('markdown direct links', () => {
const noteC = createTestNote({
uri: '/path/to/more/page-c.md',
});
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA)
.set(noteB)
.set(noteC)
.resolveLinks();
.set(noteC);
const graph = FoamGraph.fromWorkspace(ws);
expect(
ws
graph
.getLinks(noteA.uri)
.map(link => link.target.path)
.sort()
).toEqual(['/path/to/another/page-b.md', '/path/to/more/page-c.md']);
expect(ws.getLinks(noteB.uri).map(l => l.target)).toEqual([noteA.uri]);
expect(ws.getBacklinks(noteA.uri).map(l => l.source)).toEqual([noteB.uri]);
expect(ws.getConnections(noteA.uri)).toEqual([
expect(graph.getLinks(noteB.uri).map(l => l.target)).toEqual([noteA.uri]);
expect(graph.getBacklinks(noteA.uri).map(l => l.source)).toEqual([
noteB.uri,
]);
expect(graph.getConnections(noteA.uri)).toEqual([
{
source: noteA.uri,
target: noteB.uri,
@@ -386,19 +460,20 @@ describe('markdown direct links', () => {
describe('Placeholders', () => {
it('Treats direct links to non-existing files as placeholders', () => {
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
const noteA = createTestNote({
uri: '/somewhere/from/page-a.md',
links: [{ to: '../page-b.md' }, { to: '/path/to/page-c.md' }],
});
ws.set(noteA).resolveLinks();
ws.set(noteA);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getAllConnections()[0]).toEqual({
expect(graph.getAllConnections()[0]).toEqual({
source: noteA.uri,
target: URI.placeholder('/somewhere/page-b.md'),
link: expect.objectContaining({ type: 'link' }),
});
expect(ws.getAllConnections()[1]).toEqual({
expect(graph.getAllConnections()[1]).toEqual({
source: noteA.uri,
target: URI.placeholder('/path/to/page-c.md'),
link: expect.objectContaining({ type: 'link' }),
@@ -406,21 +481,22 @@ describe('Placeholders', () => {
});
it('Treats wikilinks without matching file as placeholders', () => {
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
const noteA = createTestNote({
uri: '/somewhere/page-a.md',
links: [{ slug: 'page-b' }],
});
ws.set(noteA).resolveLinks();
ws.set(noteA);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getAllConnections()[0]).toEqual({
expect(graph.getAllConnections()[0]).toEqual({
source: noteA.uri,
target: URI.placeholder('page-b'),
link: expect.objectContaining({ type: 'wikilink' }),
});
});
it('Treats wikilink with definition to non-existing file as placeholders', () => {
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
const noteA = createTestNote({
uri: '/somewhere/page-a.md',
links: [{ slug: 'page-b' }, { slug: 'page-c' }],
@@ -433,21 +509,39 @@ describe('Placeholders', () => {
label: 'page-c',
url: '/path/to/page-c.md',
});
ws.set(noteA)
.set(createTestNote({ uri: '/different/location/for/note-b.md' }))
.resolveLinks();
ws.set(noteA).set(
createTestNote({ uri: '/different/location/for/note-b.md' })
);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getAllConnections()[0]).toEqual({
expect(graph.getAllConnections()[0]).toEqual({
source: noteA.uri,
target: URI.placeholder('/somewhere/page-b.md'),
link: expect.objectContaining({ type: 'wikilink' }),
});
expect(ws.getAllConnections()[1]).toEqual({
expect(graph.getAllConnections()[1]).toEqual({
source: noteA.uri,
target: URI.placeholder('/path/to/page-c.md'),
link: expect.objectContaining({ type: 'wikilink' }),
});
});
it('Should work with a placeholder named like a JS prototype property', () => {
const ws = createTestWorkspace();
const noteA = createTestNote({
uri: '/page-a.md',
links: [{ slug: 'constructor' }],
});
ws.set(noteA);
const graph = FoamGraph.fromWorkspace(ws);
expect(
graph
.getAllNodes()
.map(uri => uri.path)
.sort()
).toEqual(['/page-a.md', 'constructor']);
});
});
describe('Updating workspace happy path', () => {
@@ -463,15 +557,19 @@ describe('Updating workspace happy path', () => {
const noteC = createTestNote({
uri: '/path/to/more/page-c.md',
});
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA)
.set(noteB)
.set(noteC)
.resolveLinks();
.set(noteC);
let graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([noteA.uri]);
expect(ws.getBacklinks(noteC.uri).map(l => l.source)).toEqual([noteB.uri]);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(graph.getBacklinks(noteC.uri).map(l => l.source)).toEqual([
noteB.uri,
]);
// update the note
const noteABis = createTestNote({
@@ -480,16 +578,20 @@ describe('Updating workspace happy path', () => {
});
ws.set(noteABis);
// change is not propagated immediately
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([noteA.uri]);
expect(ws.getBacklinks(noteC.uri).map(l => l.source)).toEqual([noteB.uri]);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(graph.getBacklinks(noteC.uri).map(l => l.source)).toEqual([
noteB.uri,
]);
// recompute the links
ws.resolveLinks();
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteC.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([]);
graph = FoamGraph.fromWorkspace(ws);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteC.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([]);
expect(
ws
graph
.getBacklinks(noteC.uri)
.map(link => link.source.path)
.sort()
@@ -504,21 +606,22 @@ describe('Updating workspace happy path', () => {
const noteB = createTestNote({
uri: '/path/to/another/page-b.md',
});
const ws = new FoamWorkspace();
ws.set(noteA)
.set(noteB)
.resolveLinks();
const ws = createTestWorkspace();
ws.set(noteA).set(noteB);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([noteA.uri]);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(ws.get(noteB.uri).type).toEqual('note');
// remove note-b
ws.delete(noteB.uri);
ws.resolveLinks();
const graph2 = FoamGraph.fromWorkspace(ws);
expect(() => ws.get(noteB.uri)).toThrow();
expect(ws.get(URI.placeholder('page-b')).type).toEqual('placeholder');
expect(graph2.contains(URI.placeholder('page-b'))).toBeTruthy();
});
it('Adding note should replace placeholder for wikilinks', () => {
@@ -526,13 +629,14 @@ describe('Updating workspace happy path', () => {
uri: '/path/to/page-a.md',
links: [{ slug: 'page-b' }],
});
const ws = new FoamWorkspace();
ws.set(noteA).resolveLinks();
const ws = createTestWorkspace();
ws.set(noteA);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([
URI.placeholder('page-b'),
]);
expect(ws.get(URI.placeholder('page-b')).type).toEqual('placeholder');
expect(graph.contains(URI.placeholder('page-b'))).toBeTruthy();
// add note-b
const noteB = createTestNote({
@@ -540,7 +644,7 @@ describe('Updating workspace happy path', () => {
});
ws.set(noteB);
ws.resolveLinks();
FoamGraph.fromWorkspace(ws);
expect(() => ws.get(URI.placeholder('page-b'))).toThrow();
expect(ws.get(noteB.uri).type).toEqual('note');
@@ -554,23 +658,24 @@ describe('Updating workspace happy path', () => {
const noteB = createTestNote({
uri: '/path/to/another/page-b.md',
});
const ws = new FoamWorkspace();
ws.set(noteA)
.set(noteB)
.resolveLinks();
const ws = createTestWorkspace();
ws.set(noteA).set(noteB);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([noteA.uri]);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(ws.get(noteB.uri).type).toEqual('note');
// remove note-b
ws.delete(noteB.uri);
ws.resolveLinks();
const graph2 = FoamGraph.fromWorkspace(ws);
expect(() => ws.get(noteB.uri)).toThrow();
expect(ws.get(URI.placeholder('/path/to/another/page-b.md')).type).toEqual(
'placeholder'
);
expect(
graph2.contains(URI.placeholder('/path/to/another/page-b.md'))
).toBeTruthy();
});
it('Adding note should replace placeholder for direct links', () => {
@@ -578,15 +683,16 @@ describe('Updating workspace happy path', () => {
uri: '/path/to/page-a.md',
links: [{ to: '/path/to/another/page-b.md' }],
});
const ws = new FoamWorkspace();
ws.set(noteA).resolveLinks();
const ws = createTestWorkspace();
ws.set(noteA);
const graph = FoamGraph.fromWorkspace(ws);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([
URI.placeholder('/path/to/another/page-b.md'),
]);
expect(ws.get(URI.placeholder('/path/to/another/page-b.md')).type).toEqual(
'placeholder'
);
expect(() =>
ws.get(URI.placeholder('/path/to/another/page-b.md'))
).toThrow();
// add note-b
const noteB = createTestNote({
@@ -594,7 +700,7 @@ describe('Updating workspace happy path', () => {
});
ws.set(noteB);
ws.resolveLinks();
FoamGraph.fromWorkspace(ws);
expect(() => ws.get(URI.placeholder('page-b'))).toThrow();
expect(ws.get(noteB.uri).type).toEqual('note');
@@ -605,22 +711,23 @@ describe('Updating workspace happy path', () => {
uri: '/path/to/page-a.md',
links: [{ to: '/path/to/another/page-b.md' }],
});
const ws = new FoamWorkspace();
ws.set(noteA).resolveLinks();
expect(ws.get(URI.placeholder('/path/to/another/page-b.md')).type).toEqual(
'placeholder'
);
const ws = createTestWorkspace().set(noteA);
const graph = FoamGraph.fromWorkspace(ws);
expect(
graph.contains(URI.placeholder('/path/to/another/page-b.md'))
).toBeTruthy();
// update the note
const noteABis = createTestNote({
uri: '/path/to/page-a.md',
links: [],
});
ws.set(noteABis).resolveLinks();
ws.set(noteABis);
const graph2 = FoamGraph.fromWorkspace(ws);
expect(() =>
ws.get(URI.placeholder('/path/to/another/page-b.md'))
).toThrow();
expect(
graph2.contains(URI.placeholder('/path/to/another/page-b.md'))
).toBeFalsy();
});
});
@@ -637,15 +744,19 @@ describe('Monitoring of workspace state', () => {
const noteC = createTestNote({
uri: '/path/to/more/page-c.md',
});
const ws = new FoamWorkspace();
const ws = createTestWorkspace();
ws.set(noteA)
.set(noteB)
.set(noteC)
.resolveLinks(true);
.set(noteC);
const graph = FoamGraph.fromWorkspace(ws, true);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([noteA.uri]);
expect(ws.getBacklinks(noteC.uri).map(l => l.source)).toEqual([noteB.uri]);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(graph.getBacklinks(noteC.uri).map(l => l.source)).toEqual([
noteB.uri,
]);
// update the note
const noteABis = createTestNote({
@@ -654,15 +765,16 @@ describe('Monitoring of workspace state', () => {
});
ws.set(noteABis);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteC.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([]);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteC.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([]);
expect(
ws
graph
.getBacklinks(noteC.uri)
.map(link => link.source.path)
.sort()
).toEqual(['/path/to/another/page-b.md', '/path/to/page-a.md']);
ws.dispose();
graph.dispose();
});
it('Removing target note should produce placeholder for wikilinks', () => {
@@ -673,21 +785,22 @@ describe('Monitoring of workspace state', () => {
const noteB = createTestNote({
uri: '/path/to/another/page-b.md',
});
const ws = new FoamWorkspace();
ws.set(noteA)
.set(noteB)
.resolveLinks(true);
const ws = createTestWorkspace();
ws.set(noteA).set(noteB);
const graph = FoamGraph.fromWorkspace(ws, true);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([noteA.uri]);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(ws.get(noteB.uri).type).toEqual('note');
// remove note-b
ws.delete(noteB.uri);
expect(() => ws.get(noteB.uri)).toThrow();
expect(ws.get(URI.placeholder('page-b')).type).toEqual('placeholder');
ws.dispose();
graph.dispose();
});
it('Adding note should replace placeholder for wikilinks', () => {
@@ -695,13 +808,13 @@ describe('Monitoring of workspace state', () => {
uri: '/path/to/page-a.md',
links: [{ slug: 'page-b' }],
});
const ws = new FoamWorkspace();
ws.set(noteA).resolveLinks(true);
const ws = createTestWorkspace();
ws.set(noteA);
const graph = FoamGraph.fromWorkspace(ws, true);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([
URI.placeholder('page-b'),
]);
expect(ws.get(URI.placeholder('page-b')).type).toEqual('placeholder');
// add note-b
const noteB = createTestNote({
@@ -713,6 +826,7 @@ describe('Monitoring of workspace state', () => {
expect(() => ws.get(URI.placeholder('page-b'))).toThrow();
expect(ws.get(noteB.uri).type).toEqual('note');
ws.dispose();
graph.dispose();
});
it('Removing target note should produce placeholder for direct links', () => {
@@ -723,23 +837,25 @@ describe('Monitoring of workspace state', () => {
const noteB = createTestNote({
uri: '/path/to/another/page-b.md',
});
const ws = new FoamWorkspace();
ws.set(noteA)
.set(noteB)
.resolveLinks(true);
const ws = createTestWorkspace();
ws.set(noteA).set(noteB);
const graph = FoamGraph.fromWorkspace(ws, true);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(ws.getBacklinks(noteB.uri).map(l => l.source)).toEqual([noteA.uri]);
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([noteB.uri]);
expect(graph.getBacklinks(noteB.uri).map(l => l.source)).toEqual([
noteA.uri,
]);
expect(ws.get(noteB.uri).type).toEqual('note');
// remove note-b
ws.delete(noteB.uri);
expect(() => ws.get(noteB.uri)).toThrow();
expect(ws.get(URI.placeholder('/path/to/another/page-b.md')).type).toEqual(
'placeholder'
);
expect(
graph.contains(URI.placeholder('/path/to/another/page-b.md'))
).toBeTruthy();
ws.dispose();
graph.dispose();
});
it('Adding note should replace placeholder for direct links', () => {
@@ -747,15 +863,16 @@ describe('Monitoring of workspace state', () => {
uri: '/path/to/page-a.md',
links: [{ to: '/path/to/another/page-b.md' }],
});
const ws = new FoamWorkspace();
ws.set(noteA).resolveLinks(true);
const ws = createTestWorkspace();
ws.set(noteA);
const graph = FoamGraph.fromWorkspace(ws, true);
expect(ws.getLinks(noteA.uri).map(l => l.target)).toEqual([
expect(graph.getLinks(noteA.uri).map(l => l.target)).toEqual([
URI.placeholder('/path/to/another/page-b.md'),
]);
expect(ws.get(URI.placeholder('/path/to/another/page-b.md')).type).toEqual(
'placeholder'
);
expect(
graph.contains(URI.placeholder('/path/to/another/page-b.md'))
).toBeTruthy();
// add note-b
const noteB = createTestNote({
@@ -767,6 +884,7 @@ describe('Monitoring of workspace state', () => {
expect(() => ws.get(URI.placeholder('page-b'))).toThrow();
expect(ws.get(noteB.uri).type).toEqual('note');
ws.dispose();
graph.dispose();
});
it('removing link to placeholder should remove placeholder', () => {
@@ -774,11 +892,12 @@ describe('Monitoring of workspace state', () => {
uri: '/path/to/page-a.md',
links: [{ to: '/path/to/another/page-b.md' }],
});
const ws = new FoamWorkspace();
ws.set(noteA).resolveLinks(true);
expect(ws.get(URI.placeholder('/path/to/another/page-b.md')).type).toEqual(
'placeholder'
);
const ws = createTestWorkspace();
ws.set(noteA);
const graph = FoamGraph.fromWorkspace(ws, true);
expect(
graph.contains(URI.placeholder('/path/to/another/page-b.md'))
).toBeTruthy();
// update the note
const noteABis = createTestNote({
@@ -786,9 +905,10 @@ describe('Monitoring of workspace state', () => {
links: [],
});
ws.set(noteABis);
expect(() =>
ws.get(URI.placeholder('/path/to/another/page-b.md'))
).toThrow();
expect(
graph.contains(URI.placeholder('/path/to/another/page-b.md'))
).toBeFalsy();
ws.dispose();
graph.dispose();
});
});

View File

@@ -3741,9 +3741,9 @@ github-slugger@^1.3.0:
emoji-regex ">=6.0.0 <=6.1.1"
glob-parent@^5.0.0:
version "5.1.1"
resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.1.tgz#b6c1ef417c4e5663ea498f1c45afac6916bbc229"
integrity sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==
version "5.1.2"
resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4"
integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==
dependencies:
is-glob "^4.0.1"
@@ -3870,9 +3870,9 @@ has@^1.0.3:
function-bind "^1.1.1"
hosted-git-info@^2.1.4:
version "2.8.8"
resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.8.tgz#7539bd4bc1e0e0a895815a2e0262420b12858488"
integrity sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg==
version "2.8.9"
resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9"
integrity sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==
html-encoding-sniffer@^1.0.2:
version "1.0.2"
@@ -4944,10 +4944,10 @@ lodash.sortby@^4.7.0:
resolved "https://registry.yarnpkg.com/lodash.sortby/-/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438"
integrity sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=
lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.4:
version "4.17.19"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b"
integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ==
lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.21, lodash@^4.17.4:
version "4.17.21"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c"
integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
log-symbols@^2.2.0:
version "2.2.0"
@@ -5924,6 +5924,11 @@ replace-ext@1.0.0:
resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-1.0.0.tgz#de63128373fcbf7c3ccfa4de5a480c45a67958eb"
integrity sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=
replace-ext@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-2.0.0.tgz#9471c213d22e1bcc26717cd6e50881d88f812b06"
integrity sha512-UszKE5KVK6JvyD92nzMn9cDapSk6w/CaFZ96CnmDMUqH9oowfxF/ZjRITD25H4DnOQClLA4/j7jLGXXLVKxAug==
request-promise-core@1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/request-promise-core/-/request-promise-core-1.1.3.tgz#e9a3c081b51380dfea677336061fea879a829ee9"
@@ -7220,9 +7225,9 @@ write@1.0.3:
mkdirp "^0.5.1"
ws@^5.2.0:
version "5.2.2"
resolved "https://registry.yarnpkg.com/ws/-/ws-5.2.2.tgz#dffef14866b8e8dc9133582514d1befaf96e980f"
integrity sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA==
version "5.2.3"
resolved "https://registry.yarnpkg.com/ws/-/ws-5.2.3.tgz#05541053414921bc29c63bee14b8b0dd50b07b3d"
integrity sha512-jZArVERrMsKUatIdnLzqvcfydI85dvd/Fp1u/VOpfdDWQ4c9qWXe+VIeAbQ5FrDwciAkr+lzofXLz3Kuf26AOA==
dependencies:
async-limiter "~1.0.0"

View File

@@ -4,6 +4,117 @@ All notable changes to the "foam-vscode" extension will be documented in this fi
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
## [0.15.0] - 2021-10-04
Features:
- Preview on hover for wikilinks (#728 - thanks @JonasSprenger)
- Added tags and controls to graph dataviz (#737 - thanks @dannysemi)
Fixes and Improvements:
- Improved tags parsing (#708 - thanks @pderaaij)
- Fixed support for resources named like JS Object methods (#729 - thanks @JonasSprenger)
## [0.14.2] - 2021-07-24
Features:
- Autocompletion for tags (#708 - thanks @pderaaij)
- Use templates for new note created from wikilink (#712 - thanks @movermeyer)
Fixes and Improvements:
- Improved performance of initial file loading (#730 - thanks @pderaaij)
## [0.14.1] - 2021-07-14
Fixes and Improvements:
- Fixed NPE that would cause markdown preview to render incorrectly (#718 - thanks @pderaaij)
## [0.14.0] - 2021-07-13
Features:
- Create new note from selection (#666 - thanks @pderaaij)
- Use templates for daily notes (#700 - thanks @movermeyer)
Fixes and Improvements:
- Fixed for wikilink aliases in tables (#697 - thanks @pderaaij)
- Fixed link definition generation in presence of aliased wikilinks (#698 - thanks @pderaaij)
- Fixed template insertion of selected text (#701 - thanks @movermeyer)
- Fixed preview navigation (#710 - thanks @pderaaij)
## [0.13.8] - 2021-07-02
Fixes and Improvements:
- Improved handling of capitalization in wikilinks (#688 - thanks @pderaaij)
- This update will make wikilinks with different capitalization, such as `[[wikilink]]` and `[[WikiLink]]` point to the same file. Please note that means that files that only differ in capitalization across the workspace would now be treated as having the same name
- Allow dots in wikilinks (#689 - thanks @pderaaij)
- Fixed a bug in the expansion of date snippets (thanks @syndenham-chorea)
- Added support for wikilink alias syntax, like `[[wikilink|label]]` (#689 - thanks @pderaaij)
## [0.13.7] - 2021-06-05
Fixes and Improvements:
- Fixed #667, incorrect resolution of foam-core library
Internal:
- BREAKING CHANGE: Removed Foam local plugins
If you were previously using the alpha feature of Foam local plugins you will soon be able to migrate the functionality to the V1 API
## [0.13.6] - 2021-06-05
Fixes and Improvements:
- Fixed #667, incorrect resolution of foam-core library
## [0.13.5] - 2021-06-05
Fixes and Improvements:
- Improved support for nested tags (#661 - thanks @pderaaij)
- Allow YAML metadata in templates (#655 - thanks @movermeyer)
- Fixed template exclusion globs (#665)
## [0.13.4] - 2021-05-26
Fixes and Improvements:
- Added support for nested tags (#643 - thanks @pderaaij)
- Improved the flow of creating note from template (#645 - thanks @movermeyer)
- Fixed handling of title property in YAML (#647 - thanks @pderaaij and #546)
Internal:
- Updated various dependencies
## [0.13.3] - 2021-05-09
Fixes and Improvements:
- Improved Foam template variables resolution: unknown variables are now ignored (#622 - thanks @movermeyer)
- Fixed file matching in MarkdownProvider (#617)
- Fixed cancelling `Foam: Create New Note` and `Foam: Create New Note From Template` behavior (#623 - thanks @movermeyer)
## [0.13.2] - 2021-05-06
Fixes and Improvements:
- Fixed wikilink completion bug (#592 - thanks @RobinKing)
- Added support for stylable tags (#598 - thanks @Barabazs)
- Added "Create new note" command (#601 - thanks @movermeyer)
- Fixed navigation from placeholder and orphan panel (#600)
Internal:
- Refactored data model representation of resources: `Resource` (#593)
## [0.13.1] - 2021-04-21
Fixes and Improvements:

View File

@@ -5,9 +5,7 @@
[![Installs](https://img.shields.io/visual-studio-marketplace/i/foam.foam-vscode)](https://marketplace.visualstudio.com/items?itemName=foam.foam-vscode)
[![Ratings](https://img.shields.io/visual-studio-marketplace/r/foam.foam-vscode)](https://marketplace.visualstudio.com/items?itemName=foam.foam-vscode)
> ⚠️ This is an early stage software. Use at your own peril.
> You can join the Foam Community on the [Foam Discord](https://foambubble.github.io/join-discord/e)
[Foam](https://foambubble.github.io/foam) is a note-taking tool that lives within VsCode, which means you can pair it with your favorite extensions for a great editing experience.
@@ -30,8 +28,8 @@ You really, _really_, **really** should read [Foam documentation](https://foambu
## Features
- Connect your notes using [`[[wiki-links]]`](https://foambubble.github.io/foam/features/backlinking)
- Create markdown [references](https://foambubble.github.io/foam/features/link-reference-definitions) for `[[wiki-links]]`, to use your notes in a non-foam workspace
- Connect your notes using [`[[wikilinks]]`](https://foambubble.github.io/foam/features/backlinking)
- Create markdown [references](https://foambubble.github.io/foam/features/link-reference-definitions) for `[[wikilinks]]`, to use your notes in a non-foam workspace
- See how your notes are connected via a [graph](https://foambubble.github.io/foam/features/graph-visualisation) with the `Foam: Show Graph` command
- Tag your notes and navigate them with the [Tag Explorer](https://foambubble.github.io/foam/features/tags)
- Make your notes navigable both in GitHub UI as well as GitHub Pages

View File

@@ -8,7 +8,7 @@
"type": "git"
},
"homepage": "https://github.com/foambubble/foam",
"version": "0.13.1",
"version": "0.15.0",
"license": "MIT",
"publisher": "foam",
"engines": {
@@ -28,7 +28,8 @@
"onCommand:foam-vscode.copy-without-brackets",
"onCommand:foam-vscode.show-graph",
"onCommand:foam-vscode.create-new-template",
"onCommand:foam-vscode.create-note-from-template"
"onCommand:foam-vscode.create-note-from-template",
"onCommand:foam-vscode.create-note-from-default-template"
],
"main": "./out/extension.js",
"contributes": {
@@ -161,6 +162,10 @@
"command": "foam-vscode.create-note-from-template",
"title": "Foam: Create New Note From Template"
},
{
"command": "foam-vscode.create-note-from-default-template",
"title": "Foam: Create New Note"
},
{
"command": "foam-vscode.open-resource",
"title": "Foam: Open Resource"
@@ -235,6 +240,11 @@
"type": "boolean",
"default": true
},
"foam.links.hover.enable": {
"description": "Enable displaying note content on hover links",
"type": "boolean",
"default": true
},
"foam.decorations.links.enable": {
"description": "Enable decorations for links",
"type": "boolean",
@@ -390,7 +400,7 @@
},
"dependencies": {
"dateformat": "^3.0.3",
"foam-core": "^0.13.1",
"foam-core": "^0.15.0",
"gray-matter": "^4.0.2",
"markdown-it-regex": "^0.2.0",
"micromatch": "^4.0.2",

View File

@@ -1,4 +1,4 @@
import { Uri, workspace } from 'vscode';
import { workspace } from 'vscode';
import { getDailyNotePath } from './dated-notes';
import { URI } from 'foam-core';
import { isWindows } from './utils';
@@ -13,7 +13,7 @@ describe('getDailyNotePath', () => {
test('Adds the root directory to relative directories', async () => {
const config = 'journal';
const expectedPath = Uri.joinPath(
const expectedPath = URI.joinPath(
workspace.workspaceFolders[0].uri,
config,
`${isoDate}.md`
@@ -25,7 +25,7 @@ describe('getDailyNotePath', () => {
const foamConfiguration = workspace.getConfiguration('foam');
expect(URI.toFsPath(getDailyNotePath(foamConfiguration, date))).toEqual(
expectedPath.fsPath
URI.toFsPath(expectedPath)
);
});

Some files were not shown because too many files have changed in this diff Show More