Fix: correct relative links within embedded notes

Links within an embedded note would point to other local resources
relative to the filesystem location of the note being embedded.

When a note inside a different directory would embed such a note, these
links would point to invalid locations.

Now these links are calculated relative to the top note, which ensures
these links will point to the right path.
This commit is contained in:
Nick Groenen 2020-12-22 12:37:04 +01:00
parent 207ca1124e
commit 6245c9a31d
No known key found for this signature in database
GPG Key ID: 4F0AD019928AE098
4 changed files with 21 additions and 1 deletions

View File

@ -124,6 +124,16 @@ impl Context {
.expect("Context not initialized properly, file_tree is empty") .expect("Context not initialized properly, file_tree is empty")
} }
/// Return the path of the root file.
///
/// Typically this will yield the same element as `current_file`, but when a note is embedded
/// within another note, this will return the outer-most note.
fn root_file(&self) -> &PathBuf {
self.file_tree
.first()
.expect("Context not initialized properly, file_tree is empty")
}
/// Return the note depth (nesting level) for this context. /// Return the note depth (nesting level) for this context.
fn note_depth(&self) -> usize { fn note_depth(&self) -> usize {
self.file_tree.len() self.file_tree.len()
@ -440,10 +450,13 @@ impl<'a> Exporter<'a> {
]; ];
} }
let target_file = target_file.unwrap(); let target_file = target_file.unwrap();
// We use root_file() rather than current_file() here to make sure links are always
// relative to the outer-most note, which is the note which this content is inserted into
// in case of embedded notes.
let rel_link = diff_paths( let rel_link = diff_paths(
target_file, target_file,
&context &context
.current_file() .root_file()
.parent() .parent()
.expect("obsidian content files should always have a parent"), .expect("obsidian content files should always have a parent"),
) )

View File

@ -0,0 +1,3 @@
This note embeds `subdir/note-in-subdir.md`:
This note in `subdir/` links back to [pure-markdown-examples](pure-markdown-examples.md).

View File

@ -0,0 +1,3 @@
This note embeds `subdir/note-in-subdir.md`:
![[note-in-subdir]]

View File

@ -0,0 +1 @@
This note in `subdir/` links back to [[pure-markdown-examples]].