I agree! But a more elegant solution would be adding a “Search current file in Search” command–either to the command palette, file context menu or both. This command would open the Search pane and input file:current-file.md
into the search field for you
Actually, all of this can be easily accomplished w/ Templater and Commander:
Templater script
Search-in-File.md (3.1 KB)
<%*
/**
* Template Name: Search Current File
* Description: Opens search pane and adds current file path to search query. If existing path queries are found, appends the new path using OR operator within parentheses (path:"file1.md" OR path:"file2.md"). Preserves all other search terms in their original position.
* Version: 2.3
* Author: Created via Claude
* Source: https://forum.obsidian.md/t/search-operator-for-current-active-note/5224/5
* Last Updated: 2024-10-28
*/
// Store current selection
const selection = tp.file.selection();
function parseSearchQuery(query) {
const paths = [];
// Match both quoted and unquoted paths
const pathRegex = /path:(?:"[^"]+"|[^\s)]+)/g;
let match;
while ((match = pathRegex.exec(query)) !== null) {
// If path is not quoted, add quotes
const path = match[0];
if (!path.includes('"')) {
const pathValue = path.replace('path:', '');
paths.push(`path:"${pathValue}"`);
} else {
paths.push(path);
}
}
if (paths.length === 0) {
return {
beforeQuery: query,
paths: [],
afterQuery: ''
};
}
const firstPathIndex = query.indexOf(paths[0]);
const lastPathIndex = query.lastIndexOf(paths[paths.length - 1]) + paths[paths.length - 1].length;
const beforeQuery = query.substring(0, firstPathIndex).replace(/\(\s*$/, '').trim();
const afterQuery = query.substring(lastPathIndex).replace(/^\s*\)/, '').trim();
return { beforeQuery, paths, afterQuery };
}
async function searchInCurrentFile() {
const activeFile = app.workspace.getActiveFile();
if (!activeFile) {
new Notice('No active file found');
return;
}
let searchLeaf = app.workspace.getLeavesOfType('search')[0];
if (!searchLeaf) {
searchLeaf = await app.workspace.getRightLeaf(false);
await searchLeaf.setViewState({
type: 'search',
active: true
});
}
await app.workspace.revealLeaf(searchLeaf);
const searchView = searchLeaf.view;
const searchInput = searchView.searchComponent.inputEl;
const currentQuery = searchInput.value.trim();
const newPathQuery = `path:"${activeFile.path}"`;
if (currentQuery.includes(newPathQuery)) {
return;
}
if (!currentQuery) {
searchInput.value = newPathQuery;
} else {
const { beforeQuery, paths, afterQuery } = parseSearchQuery(currentQuery);
paths.push(newPathQuery);
const pathSection = paths.length > 1
? `(${paths.join(' OR ')})`
: paths[0];
searchInput.value = [beforeQuery, pathSection, afterQuery]
.filter(Boolean)
.join(' ');
}
const inputEvent = new Event('input');
searchInput.dispatchEvent(inputEvent);
searchInput.focus();
searchInput.setSelectionRange(searchInput.value.length, searchInput.value.length);
}
await searchInCurrentFile();
// Restore selection
tR = selection;
-%>