improved lookup of non-Markdown files by relative path

This commit is contained in:
Amy G. Bowersox 2024-08-14 23:21:29 -06:00
parent a4ddb02bfe
commit 4a6f14c32b
2 changed files with 10 additions and 3 deletions

View File

@ -254,7 +254,7 @@ class ObsidianImages(Extension):
str: The image's link target value, or ``None`` if the image was not found.
"""
assert self._context.src_index is not None
node, _ = self._context.src_index.lookup(name)
node, _ = self._context.src_index.lookup(self._context.current_node, name)
if node:
return node.link_target(self._context.url_prefix,
self._context.current_node if self._context.relative_links else None)
@ -425,7 +425,7 @@ class ObsidianLinks(Extension):
contents = t[0]
assert self._context.src_index is not None
node, _ = self._context.src_index.lookup(contents)
node, _ = self._context.src_index.lookup(self._context.current_node, contents)
if not text:
text = contents
if node:

View File

@ -216,11 +216,13 @@ class SourceIndex:
Args:
nodelist (list[SourceNode]): The list of nodes to be indexed.
"""
self._bypath: dict[str, SourceNode] = {}
self._byname: dict[str, SourceNode] = {}
self._byalias: dict[str, SourceNode] = {}
for node in nodelist:
if node.is_dir:
continue
self._bypath[node.path.as_posix()] = node
if node.is_md:
tmp = node.path.with_suffix('')
key = tmp.name
@ -238,11 +240,12 @@ class SourceIndex:
self._byname[key] = node
self._byname[node.path.as_posix()] = node
def lookup(self, reference: str) -> tuple[SourceNode | None, str | None]:
def lookup(self, from_node: SourceNode, reference: str) -> tuple[SourceNode | None, str | None]:
"""
Looks up a reference in the index and returns the corresponding node if it exists.
Args:
from_node (SourceNode): The "current" node; used to look up a node by relative path.
reference (str): The reference to look up.
Returns:
@ -254,4 +257,8 @@ class SourceIndex:
elif reference in self._byalias:
return self._byalias[reference], 'ALIAS'
else:
new_path = from_node.path.parent / reference
s = new_path.as_posix()
if s in self._bypath:
return self._bypath[s], 'PATH'
return None, None