diff --git a/docs/queries.md b/docs/queries.md index f1e69f2..926edbe 100644 --- a/docs/queries.md +++ b/docs/queries.md @@ -21,7 +21,10 @@ All operators are **case insensitive**. ### Notes on `linkedfrom` -- Obsidian heading and block links are supported: `[[Trip to Italy#Hotels]]` matches only front-matter markers or inline markers within that heading or block. +- Scope the source note to a heading with `linkedfrom:"Trip to Italy#Hotels"`. This includes inline locations and outgoing links under that heading, including its subheadings, up to the next heading of the same or higher level. A block ID also works: `linkedfrom:"Trip to Italy#^hotel-list"`. +- Scoped queries exclude the source note's front-matter location and front-matter links. A missing heading or block matches nothing. Without a heading or block, the whole source note is included as before. +- Links inside the source note can also target headings or blocks. For example, if `Planner` contains `[[Trip to Italy#Hotels]]`, `linkedfrom:"Planner"` includes the linked note's front-matter location and inline markers within `Hotels`. +- To show only inline locations physically inside a source heading, excluding locations in linked notes, combine the scope with `path:`, e.g. `linkedfrom:"Trip to Italy#Hotels" AND path:"Trip to Italy.md"`. - The [Copy Block Link](https://github.com/mgmeyers/obsidian-copy-block-link) plugin makes block-level `linkedfrom` queries especially useful. - Anything that resolves to a legal Obsidian link works (note name or full path), but partial names do not. diff --git a/src/query.ts b/src/query.ts index 1d55526..1b2f73c 100644 --- a/src/query.ts +++ b/src/query.ts @@ -1,4 +1,4 @@ -import { App } from 'obsidian'; +import { App, parseLinktext, resolveSubpath } from 'obsidian'; import * as leaflet from 'leaflet'; import * as regex from 'src/regex'; @@ -124,14 +124,26 @@ export class Query { ) return true; } else if (value.startsWith('linkedfrom:')) { - const query = value.replace('linkedfrom:', '').toLowerCase(); + const { path, subpath } = parseLinktext( + value.replace('linkedfrom:', ''), + ); const fileMatch = this.app.metadataCache.getFirstLinkpathDest( - query, + path, '', ); if (fileMatch) { const linksFrom = this.app.metadataCache.getFileCache(fileMatch); + const sourceRange = + subpath && linksFrom + ? resolveSubpath(linksFrom, subpath) + : null; + if (subpath && !sourceRange) return false; + const inSourceRange = (offset?: number) => + !sourceRange || + (offset != null && + offset >= sourceRange.start.offset && + (!sourceRange.end || offset < sourceRange.end.offset)); const allLinks = [ ...(linksFrom?.links ?? []), ...(linksFrom?.frontmatterLinks ?? []), @@ -139,10 +151,16 @@ export class Query { ]; // Check if the given layer is linked from 'fileMatch' for (const link of allLinks) { + const offset = + 'position' in link + ? link.position.start.offset + : undefined; + if (!inSourceRange(offset)) continue; if (isLayerLinkedFrom(layer, link, this.app)) return true; } - // Also include the 'linked from' file itself - if (fileMatch.basename === layer.file.basename) return true; + // Include the source note's own markers, restricted to the same section. + if (fileMatch.path === layer.file.path) + return inSourceRange(layer.fileLocation); } } else if (value.startsWith('distancefrom:')) { const match = value.match( diff --git a/tests/query.test.ts b/tests/query.test.ts index 456db4b..a7bb51d 100644 --- a/tests/query.test.ts +++ b/tests/query.test.ts @@ -1,5 +1,7 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { Query, normalizePropertyValues, unquote } from 'src/query'; +import * as obsidian from 'obsidian'; +import * as fileMarker from 'src/fileMarker'; // Helper to create a minimal mock layer function mockLayer(overrides: Record = {}): any { @@ -134,6 +136,154 @@ describe('Query.testLayer', () => { expect(q.testLayer(mockLayer())).toBe(false); }); + describe('linkedfrom queries', () => { + let app: any; + let metadata: any; + + beforeEach(() => { + metadata = {}; + app = { + metadataCache: { + getFirstLinkpathDest: vi + .fn() + .mockReturnValue(mockLayer().file), + getFileCache: vi.fn().mockReturnValue(metadata), + }, + }; + vi.spyOn(obsidian, 'parseLinktext').mockReturnValue({ + path: 'test', + subpath: '#A', + }); + vi.spyOn(obsidian, 'resolveSubpath').mockReturnValue({ + start: { offset: 10 }, + end: { offset: 20 }, + } as any); + vi.spyOn(fileMarker, 'isLayerLinkedFrom').mockReturnValue(false); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it.each(['#A', '#^block'])( + 'resolves the source subpath %s', + (subpath) => { + vi.mocked(obsidian.parseLinktext).mockReturnValue({ + path: 'test', + subpath, + }); + const q = new Query(app, `linkedfrom:"test${subpath}"`); + expect(q.testLayer(mockLayer({ fileLocation: 15 }))).toBe(true); + expect(obsidian.parseLinktext).toHaveBeenCalledWith( + `test${subpath}`, + ); + expect( + app.metadataCache.getFirstLinkpathDest, + ).toHaveBeenCalledWith('test', ''); + expect(obsidian.resolveSubpath).toHaveBeenCalledWith( + metadata, + subpath, + ); + }, + ); + + it.each([ + [9, false], + [10, true], + [19, true], + [20, false], + [undefined, false], + ])('matches source offset %s: %s', (fileLocation, expected) => { + const q = new Query(app, 'linkedfrom:"test#A"'); + expect(q.testLayer(mockLayer({ fileLocation }))).toBe(expected); + }); + + it('includes offset zero and an open-ended source range', () => { + vi.mocked(obsidian.resolveSubpath).mockReturnValue({ + start: { offset: 0 }, + end: null, + } as any); + const q = new Query(app, 'linkedfrom:"test#A"'); + expect(q.testLayer(mockLayer({ fileLocation: 0 }))).toBe(true); + expect(q.testLayer(mockLayer({ fileLocation: 100 }))).toBe(true); + }); + + it('does not match another source file with the same basename', () => { + const q = new Query(app, 'linkedfrom:"test#A"'); + const file = { ...mockLayer().file, path: 'other/test.md' }; + expect( + q.testLayer(mockLayer({ file, fileLocation: 15 })), + ).toBeFalsy(); + }); + + it('does not match when the source section is missing', () => { + vi.mocked(obsidian.resolveSubpath).mockReturnValue(null); + const q = new Query(app, 'linkedfrom:"test#A"'); + expect(q.testLayer(mockLayer({ fileLocation: 15 }))).toBe(false); + }); + + it('does not match when source metadata is unavailable', () => { + app.metadataCache.getFileCache.mockReturnValue(null); + const q = new Query(app, 'linkedfrom:"test#A"'); + expect(q.testLayer(mockLayer({ fileLocation: 15 }))).toBe(false); + }); + + it.each([ + ['links', 9, true, false], + ['links', 10, true, true], + ['links', 10, false, false], + ['links', 20, true, false], + ['embeds', 15, true, true], + ['embeds', 20, true, false], + ] as const)( + 'filters %s at offset %s with target match %s: %s', + (type, offset, linked, expected) => { + metadata[type] = [{ position: { start: { offset } } }]; + vi.mocked(fileMarker.isLayerLinkedFrom).mockReturnValue(linked); + const q = new Query(app, 'linkedfrom:"test#A"'); + expect( + q.testLayer(mockLayer({ file: { path: 'target.md' } })), + ).toBe(expected); + }, + ); + + it('excludes front-matter links from a source section', () => { + metadata.frontmatterLinks = [{}]; + vi.mocked(fileMarker.isLayerLinkedFrom).mockReturnValue(true); + const q = new Query(app, 'linkedfrom:"test#A"'); + expect( + q.testLayer(mockLayer({ file: { path: 'target.md' } })), + ).toBeFalsy(); + }); + + it('keeps whole-note source markers without metadata or offsets', () => { + vi.mocked(obsidian.parseLinktext).mockReturnValue({ + path: 'test', + subpath: '', + }); + app.metadataCache.getFileCache.mockReturnValue(null); + const q = new Query(app, 'linkedfrom:"test"'); + expect(q.testLayer(mockLayer())).toBe(true); + expect(obsidian.resolveSubpath).not.toHaveBeenCalled(); + }); + + it.each(['links', 'embeds', 'frontmatterLinks'])( + 'keeps whole-note %s', + (type) => { + vi.mocked(obsidian.parseLinktext).mockReturnValue({ + path: 'test', + subpath: '', + }); + metadata[type] = [{}]; + vi.mocked(fileMarker.isLayerLinkedFrom).mockReturnValue(true); + const q = new Query(app, 'linkedfrom:"test"'); + expect( + q.testLayer(mockLayer({ file: { path: 'target.md' } })), + ).toBe(true); + }, + ); + }); + it('lines query matches layer with fileLine in range', () => { const q = new Query(null as any, 'lines:5-10'); expect(q.testLayer(mockLayer({ fileLine: 7 }))).toBe(true);