### Search Endpoint Request Example Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Example of how to make a GET request to the /search endpoint to query the vault index. Ensure the server is enabled and running on the correct port. ```http GET http://localhost:8080/search?q=typescript+interface ``` -------------------------------- ### Query Constructor Examples Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/query.md Demonstrates creating Query instances for basic, advanced, and quoted searches. ```typescript // Basic search const q1 = new Query('typescript', { ignoreDiacritics: false }) // Advanced search with filters and exclusions const q2 = new Query( 'interface -"internal api" ext:.md path:src', { ignoreDiacritics: true, ignoreArabicDiacritics: false } ) // With quoted expressions const q3 = new Query('"search query parser" filter:value') ``` -------------------------------- ### Search Endpoint Response Example Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Example JSON response body for a successful search query to the /search endpoint. It includes relevance scores, file paths, and details about matched words. ```json [ { "score": 15.234, "vault": "My Vault", "path": "notes/typescript/interfaces.md", "basename": "interfaces", "foundWords": ["typescript", "interface"], "matches": [ { "match": "typescript", "offset": 12 }, { "match": "interface", "offset": 24 } ], "excerpt": "...TypeScript interface design patterns include singleton, factory, and decorator patterns..." } ] ``` -------------------------------- ### Initialize TextProcessor Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/text-processor.md Instantiate the TextProcessor by passing the OmnisearchPlugin instance to its constructor. This is the initial setup required before using other methods. ```typescript export class TextProcessor { constructor(private plugin: OmnisearchPlugin) } ``` -------------------------------- ### Token Examples: Indexing Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/tokenizer.md Demonstrates the output of tokenizeForIndexing for a string containing hyphens and camel case. ```plaintext ['TypeScript', 'interface', 'or', 'CamelCase', 'type', 'script', 'camel', 'case', 'typescript', 'camelcase'] ``` -------------------------------- ### Token Examples: URL Tokenization (Enabled) Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/tokenizer.md Shows tokenization results when the tokenizeUrls setting is enabled, including the full URL as a token. ```plaintext ['https', 'example', 'com', 'API', 'https://example.com'] ``` -------------------------------- ### Dataview Integration Example Source: https://github.com/scambier/obsidian-omnisearch/blob/master/Doc Omnisearch/Public API & URL Scheme.md This DataviewJS snippet demonstrates how to use the Omnisearch API to fetch search results and display them in a table. ```javascript const results = await omnisearch.search('your query') const arr = dv.array(results).sort(r => r.score, 'desc') dv.table(['File', 'Score'], arr.map(o => [dv.fileLink(o.path), Math.round(o.score)])) ``` -------------------------------- ### Integrate Omnisearch API into Obsidian Plugin Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Access and utilize the Omnisearch API from within another Obsidian plugin. This example demonstrates how to get the Omnisearch plugin instance and perform a search. ```typescript // In another Obsidian plugin import type OmnisearchPlugin from 'obsidian-omnisearch' export default class MyPlugin extends Plugin { onload() { const omnisearch = this.app.plugins.plugins.omnisearch if (omnisearch) { // Use omnisearch API omnisearch.api.search('query').then(results => { console.log(results) }) } } } ``` -------------------------------- ### Token Examples: URL Tokenization (Disabled) Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/tokenizer.md Shows tokenization results when the tokenizeUrls setting is disabled, excluding the URL as a token. ```plaintext ['API'] ``` -------------------------------- ### Error Response Example Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Example of an error response from the HTTP API, typically indicating an internal server error. ```text {error message} ``` -------------------------------- ### Search with File Filters Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Execute a search query that includes filters for file extensions and paths. This example limits the search to markdown files within the 'src' directory. ```typescript // Search only markdown files in src folder const results = await window.omnisearch.search('function ext:.md path:src') ``` -------------------------------- ### Search with JavaScript Fetch API Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Implement a JavaScript function to search Omnisearch using the Fetch API. This example demonstrates how to construct the request, handle the JSON response, and log the results. ```javascript async function search(query) { const params = new URLSearchParams({ q: query }) const response = await fetch(`http://localhost:8080/search?${params}`) const results = await response.json() return results } const results = await search('typescript interface') console.log(`Found ${results.length} results`) results.forEach(r => { console.log(`${r.basename}: ${r.score}`) }) ``` -------------------------------- ### Get Search Suggestions Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/search-engine.md Provides formatted search results as `ResultNote` objects, including excerpts and highlighted matches. This method wraps the core `search()` functionality. ```typescript public async getSuggestions(query: Query): Promise ``` ```typescript const query = new Query('search term') const suggestions = await searchEngine.getSuggestions(query) suggestions.forEach(note => { console.log(`${note.basename} - Score: ${note.score}`) console.log(`Excerpt: ${note.content.substring(0, 100)}`) }) ``` -------------------------------- ### makeExcerpt Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/text-processor.md Generates a contextual excerpt from text centered around a match position. It extracts a specified number of characters before and after the match, falls back to the start of the text if the offset is invalid, and handles multi-line text. ```APIDOC ## makeExcerpt() ### Description Generates a contextual excerpt from text centered around a match position. ### Method Signature ```typescript public makeExcerpt( text: string, matchOffset: number = -1 ): string ``` ### Parameters #### Parameters - **text** (string) - Required - Full text to excerpt from - **matchOffset** (number) - Optional - Character offset of the match (-1 for start) ### Returns Excerpt string with context around the match. ### Example ```typescript const text = 'Lorem ipsum dolor sit amet. The important interface design pattern...' const matches = [{ match: 'interface', offset: 30 }] const excerpt = processor.makeExcerpt(text, 30) // Returns: '...dolor sit amet. The important interface design pattern...' ``` ``` -------------------------------- ### Public API Reference Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/INDEX.md Access the programmatic API for searching and interacting with Omnisearch. This section links to detailed documentation on exported classes, methods, properties, and includes code examples. ```APIDOC ## Public API ### Description Provides programmatic access to Omnisearch functionalities, including searching, querying, and document extraction. ### Documentation → [public-api.md](api-reference/public-api.md) → [QUICKSTART.md](QUICKSTART.md) ``` -------------------------------- ### Get Match Locations (Browser Console) Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Retrieves detailed information about each match within search results, including the file path, the matched text, and its offset within the file. ```APIDOC ## Get Match Locations (Browser Console) ### Description Retrieves detailed information about each match within search results, including the file path, the matched text, and its offset within the file. ### Method JavaScript (in-browser) ### Endpoint `window.omnisearch.search(query: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const results = await window.omnisearch.search('interface') results.forEach(result => { console.log(`File: ${result.path}`) result.matches.forEach(match => { console.log(` Match: "${match.match}" at position ${match.offset}`) }) }) ``` ### Response #### Success Response - **results** (Array) - An array of search result objects, each containing a `matches` array. - **matches** (Array) - An array of match objects. - **match** (string) - The exact text that matched the query. - **offset** (number) - The starting character position of the match within the file content. #### Response Example ```json [ { "path": "path/to/file.md", "basename": "file", "excerpt": "...content with match...", "score": 0.85, "matches": [ { "match": "interface", "offset": 10 }, { "match": "interface", "offset": 55 } ] } ] ``` ``` -------------------------------- ### Get Notes Embedding a File Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/embeds-repository.md Retrieves a list of all notes that embed a specific file. This is useful for understanding the usage and context of a particular file within the vault. ```typescript const embedsImage = repository.getEmbeds('assets/banner.png') console.log(`Image is embedded in ${embedsImage.length} notes`) // ['page1.md', 'page2.md', 'gallery.md'] ``` -------------------------------- ### SearchEngine Constructor Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/search-engine.md Initializes the SearchEngine with a given plugin instance. This sets up the MiniSearch engine with default BM25 weighting options. ```APIDOC ## Constructor SearchEngine ### Description Initializes MiniSearch with default BM25 weighting options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ### Method Signature ```typescript constructor(plugin: OmnisearchPlugin) ``` ### Parameters - **plugin** (OmnisearchPlugin) - Required - Plugin instance for accessing settings and repositories ``` -------------------------------- ### Execute First Launch Tasks Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Performs version-specific upgrade tasks on the first load. This includes displaying welcome messages and feature announcements. ```typescript private async executeFirstLaunchTasks(): Promise ``` -------------------------------- ### OmnisearchPlugin onload Method Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Handles plugin initialization tasks upon loading. This includes loading settings, registering UI elements, setting up event listeners, and populating the search index. ```typescript async onload(): Promise ``` -------------------------------- ### OmnisearchPlugin Constructor Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Initializes the OmnisearchPlugin, setting up core repositories and services. It takes the Obsidian app instance and plugin manifest as arguments. ```APIDOC ## Constructor OmnisearchPlugin ### Description Initializes the plugin and creates instances of core repositories and services. The `documentsRepository` is created in the constructor. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **app** (App) - Required - Obsidian app instance - **manifest** (PluginManifest) - Required - Plugin manifest metadata ``` -------------------------------- ### onload() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Called when the plugin is loaded. It handles settings loading, registers UI elements, initializes the HTTP API server, sets up event listeners, and populates the search index. ```APIDOC ## onload() ### Description Called when the plugin is loaded. Performs initialization tasks: loads settings, registers settings tab, initializes HTTP API server (desktop only), registers vault event listeners, populates the search index, adds ribbon button if configured, and sets up command palette commands. ### Method async ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (void) Returns a Promise that resolves when the plugin is fully loaded. #### Response Example None ``` -------------------------------- ### Get Serialized Indexed Documents Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/search-engine.md Returns an array of `DocumentRef` objects, each containing the path and modification time of an indexed document. ```typescript public getSerializedIndexedDocuments(): DocumentRef[] ``` -------------------------------- ### Get AI Image Analyzer Plugin API Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Retrieves the AI Image Analyzer plugin API for image analysis. ```typescript public getAIImageAnalyzer(): AIImageAnalyzerAPI | undefined ``` -------------------------------- ### OmnisearchPlugin Constructor Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Initializes the OmnisearchPlugin, setting up core repositories and services. The `documentsRepository` is instantiated here. ```typescript constructor(app: App, manifest: PluginManifest) ``` -------------------------------- ### GET /search Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Searches the vault index with a query string. This endpoint allows external applications to perform searches against the Omnisearch index. ```APIDOC ## GET /search ### Description Searches the vault index with a query string. ### Method GET ### Endpoint /search ### Parameters #### Query Parameters - **q** (string) - Required - Search query string ### Request Example ``` GET http://localhost:8080/search?q=typescript+interface ``` ### Response #### Success Response (200) - **score** (number) - BM25 relevance score - **vault** (string) - Name of the vault - **path** (string) - File path relative to vault root - **basename** (string) - Filename without extension - **foundWords** (string[]) - Query terms found in this result - **matches** (SearchMatchApi[]) - Specific matches with positions - **excerpt** (string) - Contextual text excerpt around match #### Response Example ```json [ { "score": 15.234, "vault": "My Vault", "path": "notes/typescript/interfaces.md", "basename": "interfaces", "foundWords": ["typescript", "interface"], "matches": [ { "match": "typescript", "offset": 12 }, { "match": "interface", "offset": 24 } ], "excerpt": "...TypeScript interface design patterns include singleton, factory, and decorator patterns..." } ] ``` ### Error Response #### Internal Server Error (500) - **error message** (string) - Description of the error ``` -------------------------------- ### Load Plugin Settings Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/configuration.md This asynchronous function demonstrates how to load plugin settings using `loadSettings()`. The loaded settings are then made available at `this.settings`. ```typescript async onload() { this.settings = await loadSettings(this) // Settings now available at this.settings } ``` -------------------------------- ### Query Constructor Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/query.md Initializes a new Query instance. It parses the raw search string and extracts all components automatically. ```APIDOC ## Constructor ```typescript constructor( text: string = '', options: { ignoreDiacritics: boolean; ignoreArabicDiacritics: boolean } ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **text** (string) - Raw search query string - **options.ignoreDiacritics** (boolean) - Remove diacritical marks from query - **options.ignoreArabicDiacritics** (boolean) - Also remove Arabic diacritical marks Parses the query string and extracts all components automatically. ### Request Example ```typescript // Basic search const q1 = new Query('typescript', { ignoreDiacritics: false }) // Advanced search with filters and exclusions const q2 = new Query( 'interface -"internal api" ext:.md path:src', { ignoreDiacritics: true, ignoreArabicDiacritics: false } ) // With quoted expressions const q3 = new Query('"search query parser" filter:value') ``` ### Response None ``` -------------------------------- ### Get Document from Cache Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/documents-repository.md Retrieves a document from the cache or adds it if it's not present. Logs errors if the document cannot be read but continues operation. ```typescript public async getDocument(path: string): Promise ``` ```typescript const doc = await repository.getDocument('notes/my-note.md') console.log(doc.basename) // 'my-note' console.log(doc.content) // Full file content console.log(doc.aliases) // Aliases from frontmatter ``` -------------------------------- ### Get Chinese Segmenter Plugin API Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Retrieves the Chinese word segmentation plugin API if available. Use this for enhanced Chinese text tokenization. ```typescript public getChsSegmenter(): any | undefined ``` ```typescript const segmenter = plugin.getChsSegmenter() if (segmenter) { // Use segmenter for Chinese text tokenization } ``` -------------------------------- ### Global Variables and Stores Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/types.md Initializes global event bus and Svelte stores for managing indexing status and excerpt visibility. ```typescript const eventBus = new EventBus() const indexingStep = writable(IndexingStepType.Done) // Svelte store const showExcerpt = writable(true) // Svelte store ``` -------------------------------- ### SearchMatch Type Definition Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/types.md Defines a single occurrence of a matched term within search results, including the matched text and its starting character offset. ```typescript type SearchMatch = { match: string offset: number } ``` -------------------------------- ### Get Match Locations from Search Results Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Iterate through search results to access file paths and detailed information about each match, including the matched text and its offset. ```javascript const results = await window.omnisearch.search('interface') results.forEach(result => { console.log(`File: ${result.path}`) result.matches.forEach(match => { console.log(` Match: "${match.match}" at position ${match.offset}`) }) }) ``` -------------------------------- ### Registering an Index Load Callback Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Use this to ensure your index is loaded before performing searches. This is crucial for troubleshooting 'No Results Found' issues. ```javascript window.omnisearch.registerOnIndexed(...) ``` -------------------------------- ### Database Constructor Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/database.md Initializes the Dexie database with tables for search history, minisearch cache, and embeds. The plugin instance is used for application ID and settings. ```typescript constructor(plugin: OmnisearchPlugin) ``` -------------------------------- ### getSuggestions() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/search-engine.md Provides search suggestions by executing a query and formatting the results into `ResultNote` objects, including excerpts and match highlighting. ```APIDOC ## getSuggestions() ### Description High-level search method that wraps `search()` and formats results into `ResultNote` objects with excerpts and match highlighting. ### Parameters #### Path Parameters - **query** (Query) - Required - Parsed search query ### Returns Array of `ResultNote` with formatted results, match locations, and excerpts. ### Example ```typescript const query = new Query('search term') const suggestions = await searchEngine.getSuggestions(query) suggestions.forEach(note => { console.log(`${note.basename} - Score: ${note.score}`) console.log(`Excerpt: ${note.content.substring(0, 100)}`) }) ``` ``` -------------------------------- ### HTTP Server Search Endpoint Source: https://github.com/scambier/obsidian-omnisearch/blob/master/Doc Omnisearch/Public API & URL Scheme.md Query Omnisearch from external applications using this HTTP GET request. Ensure the HTTP Server is enabled in Omnisearch settings. ```http GET http://localhost:51361/search?q=your%20query ``` -------------------------------- ### NotesIndexer Constructor Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/notes-indexer.md Initializes a new instance of the NotesIndexer class. ```APIDOC ## Constructor ```typescript constructor(plugin: OmnisearchPlugin) ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | plugin | OmnisearchPlugin | Plugin instance for settings and app access | ``` -------------------------------- ### Omnisearch Plugin Architecture Overview Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/README.md Illustrates the main components of the Omnisearch plugin and their relationships. Key modules include the Search Engine, Document Repository, Database, and various utility tools. ```plaintext OmnisearchPlugin (main.ts) ├── SearchEngine (search/search-engine.ts) │ ├── MiniSearch (external library) │ ├── Tokenizer (search/tokenizer.ts) │ └── IndexedDocuments Map ├── DocumentsRepository (repositories/documents-repository.ts) │ └── IndexedDocument Map (live cache) ├── Database (database.ts) │ ├── searchHistory table │ ├── minisearch table (cached index) │ └── embeds table ├── NotesIndexer (notes-indexer.ts) │ └── notesToReindex Set ├── TextProcessor (tools/text-processing.ts) ├── SearchHistory (search/search-history.ts) ├── EmbedsRepository (repositories/embeds-repository.ts) ├── EventBus (tools/event-bus.ts) └── HTTP API Server (tools/api-server.ts) └── GET /search endpoint ``` -------------------------------- ### Search with Filters (Browser Console) Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Demonstrates advanced search capabilities using filters for file extensions, exclusion patterns, specific folders, and exact phrase matching. ```APIDOC ## Search with Filters (Browser Console) ### Description Demonstrates advanced search capabilities using filters for file extensions, exclusion patterns, specific folders, and exact phrase matching. ### Method JavaScript (in-browser) ### Endpoint `window.omnisearch.search(query: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Search only markdown files await window.omnisearch.search('interface ext:.md') // Exclude archived notes await window.omnisearch.search('project -archived') // Search specific folder await window.omnisearch.search('function path:src/') // Quoted exact phrase await window.omnisearch.search('"design pattern"') ``` ### Response #### Success Response - **results** (Array) - An array of search result objects matching the specified filters. #### Response Example ```json [ { "path": "path/to/file.md", "basename": "file", "excerpt": "...content with match...", "score": 0.9, "matches": [ { "match": "interface", "offset": 5 } ] } ] ``` ``` -------------------------------- ### Get Text Extractor Plugin API Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Retrieves the Text Extractor plugin API for PDF and document text extraction. Check if a file can be extracted before calling the extraction method. ```typescript public getTextExtractor(): TextExtractorApi | undefined ``` ```typescript const extractor = plugin.getTextExtractor() if (extractor?.canFileBeExtracted(filePath)) { const text = await extractor.extractText(file) } ``` -------------------------------- ### getBestStringForExcerpt() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/query.md Returns the most suitable term for generating excerpts, prioritizing quoted phrases. ```APIDOC ## getBestStringForExcerpt() ### Description Returns the most suitable term to use as the anchor for generating excerpts. Prioritizes quoted phrases, then falls back to the query text. ### Method ```typescript public getBestStringForExcerpt(): string ``` ### Parameters None ### Returns Best term for excerpt extraction. ### Request Example ```typescript const q = new Query('"introduction section" other terms') const excerptAnchor = q.getBestStringForExcerpt() // Returns: 'introduction section' ``` ### Response None ``` -------------------------------- ### Check Index Status with JavaScript Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Use this JavaScript snippet to get the number of indexed documents and view recent search history. It accesses the Omnisearch API via the window object. ```javascript const results = await window.omnisearch.search('') console.log(`Index loaded`) const history = await omnisearch.searchHistory.getHistory() console.log('Recent searches:', history) ``` -------------------------------- ### Search with Filters Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Utilize various filters in your searches, such as file extensions, exclusion terms, specific folders, and exact phrases. ```javascript // Search only markdown files await window.omnisearch.search('interface ext:.md') // Exclude archived notes await window.omnisearch.search('project -archived') // Search specific folder await window.omnisearch.search('function path:src/') // Quoted exact phrase await window.omnisearch.search('"design pattern"') ``` -------------------------------- ### Get Minisearch Cache Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/database.md Retrieves the cached search index from the minisearch table. Returns null if the cache is missing or invalid. Handles cache corruption by logging errors and notifying the user. ```typescript public async getMinisearchCache(): Promise<{ paths: DocumentRef[] data: AsPlainObject } | null> ``` ```typescript const cache = await database.getMinisearchCache() if (cache) { const minisearch = await MiniSearch.loadJSAsync(cache.data, options) console.log(`Loaded ${cache.paths.length} indexed documents`) ``` -------------------------------- ### Search with Python Requests Library Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Utilize the Python `requests` library to query the Omnisearch HTTP API. This snippet shows how to send a GET request with query parameters and process the JSON response. ```python import requests def search_omnisearch(query): url = "http://localhost:8080/search" params = {"q": query} response = requests.get(url, params=params) return response.json() results = search_omnisearch("typescript") for result in results: print(f"{result['basename']}: {result['score']}") ``` -------------------------------- ### Accessing Omnisearch API Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Demonstrates the two primary ways to access the Omnisearch API: through the global `window.omnisearch` object or via the `plugin.api` property within a plugin instance. ```typescript window.omnisearch.search(...) // or app.plugins.plugins.omnisearch.api.search(...) ``` -------------------------------- ### Perform a Search Query Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Use this snippet to search for content. Check the results length to determine if any matches were found or if the index is not yet ready. ```typescript const results = await window.omnisearch.search('query') if (results.length === 0) { // No results found, or index not ready } ``` -------------------------------- ### EventBus.on() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/event-bus.md Subscribes to an event within a specific context. If a subscription for the same event and context already exists, it will be overwritten. ```APIDOC ## on() ### Description Subscribes to an event in a specific context. If a subscription already exists for the same event in the same context, it is overwritten. ### Method Signature ```typescript public on(context: string, event: string, callback: EventBusCallback): void ``` ### Parameters #### Path Parameters - **context** (string) - Required - Context namespace (e.g., 'vault', 'infile', 'global') - **event** (string) - Required - Event name - **callback** (EventBusCallback) - Required - Function to call when event is emitted ### Throws Error if context or event name contains the `@` character. ### Example ```typescript eventBus.on('vault', 'search-results', (results) => { console.log(`Found ${results.length} results`) }) eventBus.on('infile', 'note-selected', (notePath) => { console.log(`Selected: ${notePath}`) }) ``` ``` -------------------------------- ### canIndexUnsupportedFiles(): boolean Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/notes-indexer.md Checks if unsupported file types should be indexed based on settings and Obsidian configuration. ```APIDOC ## Method: canIndexUnsupportedFiles() Checks if unsupported file types should be indexed based on settings and Obsidian configuration. ```typescript public canIndexUnsupportedFiles(): boolean ``` Returns: `true` if unsupported files can be indexed. Decision logic: - If `unsupportedFilesIndexing: 'yes'` → always true - If `unsupportedFilesIndexing: 'no'` → always false - If `unsupportedFilesIndexing: 'default'` → follows Obsidian's "Show unsupported files" setting ### Example ```typescript if (indexer.canIndexUnsupportedFiles()) { // Files like .zip, .exe will be indexed by filename } ``` ``` -------------------------------- ### Save Plugin Settings Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/configuration.md This code snippet shows how to modify a setting and then persist the changes using `saveSettings()`. The change to `this.settings.highlight` is saved to disk. ```typescript this.settings.highlight = false await saveSettings(this) // Change is now saved ``` -------------------------------- ### loadFromCache Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/embeds-repository.md Loads embed data from IndexedDB cache on startup. This method restores embed tracking information, improving performance by avoiding re-parsing on every launch. ```APIDOC ## loadFromCache ### Description Loads embed data from IndexedDB cache on startup. ### Method ```typescript public async loadFromCache(): Promise ``` ### Behavior - Queries cache database - Reconstructs embed map from cache entries - Shows error notice if cache is corrupted - Clears cache if loading fails ### Returns Promise that resolves when cache is loaded. ### Request Example ```typescript await repository.loadFromCache() // Embed tracking is now restored from cache ``` ``` -------------------------------- ### Simple Search with cURL Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Perform a basic search query using cURL against the Omnisearch HTTP API. Ensure the API is enabled and accessible at the specified host and port. ```bash # Simple search curl "http://localhost:8080/search?q=typescript" ``` -------------------------------- ### Trigger Omnisearch with URL Scheme Source: https://github.com/scambier/obsidian-omnisearch/blob/master/Doc Omnisearch/Public API & URL Scheme.md Use this URL scheme to open Omnisearch and initiate a search from external applications or other Obsidian plugins. ```url obsidian://omnisearch?query=foo bar ``` -------------------------------- ### WeightingSettings Interface Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/types.md Configures search result weighting parameters. Used to boost matches based on file name, directory, headings, and tags. ```typescript interface WeightingSettings { weightBasename: number weightDirectory: number weightH1: number weightH2: number weightH3: number weightUnmarkedTags: number } ``` -------------------------------- ### Search Query with Filters Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Use this snippet to combine search terms with file extension and path filters. ```HTTP /search?q=search+ext:.md+path:src ``` -------------------------------- ### Register On Indexed Callback (Browser Console) Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Registers a callback function to be executed once the Omnisearch index is ready, useful for ensuring search operations are performed on a fully indexed vault. ```APIDOC ## Register On Indexed Callback (Browser Console) ### Description Registers a callback function to be executed once the Omnisearch index is ready, useful for ensuring search operations are performed on a fully indexed vault. ### Method JavaScript (in-browser) ### Endpoint `window.omnisearch.registerOnIndexed(callback: () => void)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript window.omnisearch.registerOnIndexed(() => { console.log('Index ready!') }) ``` ### Response #### Success Response None (executes callback) #### Response Example None ``` -------------------------------- ### Plugin Integration Search Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Demonstrates how to access and use the Omnisearch API from within another Obsidian plugin. ```APIDOC ## Omnisearch API via Plugin ### Description Accesses the Omnisearch API from another Obsidian plugin to perform searches. ### Method `omnisearch.api.search(query: string): Promise`` ### Parameters #### Query Parameters - **query** (string) - Required - The search term or query string. ### Response #### Success Response - **results** (ResultNoteApi[]) - An array of search results. ### Request Example ```typescript // In another Obsidian plugin import type OmnisearchPlugin from 'obsidian-omnisearch' export default class MyPlugin extends Plugin { onload() { const omnisearch = this.app.plugins.plugins.omnisearch if (omnisearch) { // Use omnisearch API omnisearch.api.search('query').then(results => { console.log(results) }) } } } ``` ``` -------------------------------- ### Wait for Index Before Searching Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Ensure the Omnisearch index is fully ready before initiating a search. Register a callback to be notified when indexing is complete. ```typescript // Ensure index is ready before searching await new Promise(resolve => { window.omnisearch.registerOnIndexed(resolve) }) const results = await window.omnisearch.search('my query') ``` -------------------------------- ### getBestStringForExcerpt() Method Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/query.md Returns the most suitable term for generating excerpts, prioritizing quoted phrases. Falls back to the general query text if no quoted phrases are found. Essential for creating relevant search result snippets. ```typescript public getBestStringForExcerpt(): string ``` ```typescript const q = new Query('"introduction section" other terms') const excerptAnchor = q.getBestStringForExcerpt() // Returns: 'introduction section' ``` -------------------------------- ### Configure Indexed File Types Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/configuration.md Specify additional plain text file extensions to be indexed by Omnisearch. Ensure these extensions correspond to files that contain plain text content. ```typescript settings: { indexedFileTypes: ['txt', 'md', 'markdown', 'rst'] } ``` -------------------------------- ### registerOnIndexed() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Registers a callback function to be executed once the search index has finished loading. If the index is already loaded, the callback is invoked immediately. ```APIDOC ## registerOnIndexed() ### Description Registers a callback function to be executed once the search index has finished loading. If the index is already loaded, the callback is invoked immediately. Multiple callbacks can be registered. ### Method `registerOnIndexed(callback: () => void): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **callback** (() => void) - Required - Function to call when the search index is ready ### Request Example ```typescript window.omnisearch.registerOnIndexed(() => { console.log('Search index is ready!') // Now safe to call search() }) ``` ### Response #### Success Response (200) `void` - This method does not return a value. #### Response Example None ``` -------------------------------- ### Checking for Port Usage Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Use this command in your terminal to check if a specific port is already in use, which can help troubleshoot HTTP API startup issues. ```bash lsof -i :8080 ``` -------------------------------- ### Enable Omnisearch HTTP API Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Configure the Omnisearch settings to enable the HTTP API. This involves setting the `httpApiEnabled` flag to true and optionally configuring the port and notice. ```typescript const settings: OmnisearchSettings = { httpApiEnabled: true, httpApiPort: '8080', httpApiNotice: true, DANGER_httpHost: null, DANGER_forceSaveCache: false } ``` -------------------------------- ### Execute Search Query Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/search-engine.md Executes a search query against the indexed documents with options for prefix length and filtering by a single file path. Supports various search behaviors including fuzziness, path/extension filtering, and recency boosts. ```typescript public async search( query: Query, options: { prefixLength: number; singleFilePath?: string } ): Promise ``` ```typescript const query = new Query('typescript interface', { ignoreDiacritics: false }) const results = await searchEngine.search(query, { prefixLength: 2 }) results.forEach(r => { console.log(`${r.id}: ${r.score}`) }) ``` -------------------------------- ### Monitor Indexing Progress with JavaScript Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Subscribe to indexing progress updates using this JavaScript code. It logs the current status of the indexing process, such as loading cache, reading files, indexing, or writing cache. ```javascript import { indexingStep, IndexingStepType } from 'omnisearch/globals' indexingStep.subscribe(step => { const steps = { 0: 'Done', 1: 'Loading cache', 2: 'Reading files', 3: 'Indexing', 4: 'Writing cache' } console.log(`Status: ${steps[step]}`) }) ``` -------------------------------- ### Search and Display Results with JavaScript Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md This JavaScript function searches for a given query and displays the results, including the filename, path, score, and an excerpt. It handles cases where no results are found. ```javascript async function displayResults(query) { const results = await window.omnisearch.search(query) if (results.length === 0) { console.log('No results found') return } console.log(`Found ${results.length} results:`) results.forEach((r, idx) => { console.log(` ${idx + 1}. ${r.basename} (${r.path})`) console.log(` Score: ${r.score.toFixed(2)}`) console.log(` Excerpt: ${r.excerpt.substring(0, 100)}...`) }) } displayResults('typescript interface') ``` -------------------------------- ### Project File Organization Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/MANIFEST.md This tree structure shows the organization of files within the Omnisearch project, detailing the purpose of each markdown file and directory. ```text /workspace/home/output/ ├── INDEX.md # Navigation index ├── MANIFEST.md # This file ├── README.md # Architecture overview ├── QUICKSTART.md # Quick reference guide ├── configuration.md # 50+ settings documentation ├── types.md # Type definitions ├── endpoints.md # HTTP API reference ├── errors.md # Error handling └── api-reference/ # 13 API reference files ├── omnisearch-plugin.md ├── search-engine.md ├── documents-repository.md ├── database.md ├── notes-indexer.md ├── query.md ├── tokenizer.md ├── text-processor.md ├── search-history.md ├── embeds-repository.md ├── event-bus.md └── public-api.md ``` -------------------------------- ### search() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/search-engine.md Executes a search query against the indexed documents, supporting prefix matching, filtering by file path, and various relevance tuning options. Returns an array of search results sorted by relevance. ```APIDOC ## search() ### Description Executes a search query against the indexed documents. ### Parameters #### Path Parameters - **query** (Query) - Required - Parsed search query object - **options.prefixLength** (number) - Required - Minimum term length for prefix matching (typically 2) - **options.singleFilePath** (string | undefined) - Optional - If set, only search within this file ### Returns Array of `SearchResult` objects from MiniSearch, sorted by relevance. ### Search Behavior - Returns empty array if query is empty - Applies fuzziness based on settings (0%, 10%, or 20%) - Filters results by file extension if `ext:` filter used - Filters by path if `path:` filter used - Downranks results in excluded folders - Applies recency boost if configured - Excludes paths matching exclusion filters - Performs "simple search" fallback if no results found ### Example ```typescript const query = new Query('typescript interface', { ignoreDiacritics: false }) const results = await searchEngine.search(query, { prefixLength: 2 }) results.forEach(r => { console.log(`${r.id}: ${r.score}`) }) ``` ``` -------------------------------- ### Wait for Index Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Registers a callback to be executed once the Omnisearch index is ready. This is useful to ensure searches are performed only after the index is available. ```APIDOC ## registerOnIndexed ### Description Registers a callback function to be invoked when the Omnisearch index has finished indexing. ### Method `window.omnisearch.registerOnIndexed(callback: () => void): void`` ### Parameters #### Query Parameters - **callback** (function) - Required - The function to execute once the index is ready. ### Request Example ```typescript await new Promise(resolve => { window.omnisearch.registerOnIndexed(resolve) }) const results = await window.omnisearch.search('my query') ``` ``` -------------------------------- ### Wait for Index and Search with JavaScript Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md This JavaScript function ensures that a search query is only executed after the Omnisearch index has been fully loaded. It uses a promise-based approach to register a callback for indexing completion. ```javascript async function safeSearch(query) { return new Promise((resolve) => { window.omnisearch.registerOnIndexed(async () => { const results = await window.omnisearch.search(query) resolve(results) }) }) } const results = await safeSearch('my query') ``` -------------------------------- ### Configure Custom Property Weights for Search Ranking Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/configuration.md Define custom frontmatter fields to influence search result ranking. Assign a numerical weight to each custom property to boost its importance. ```yaml # In a note's frontmatter priority: high custom_field: important ``` ```typescript settings: { weightCustomProperties: [ { name: 'priority', weight: 8 }, { name: 'custom_field', weight: 5 } ] } ``` -------------------------------- ### Register Callback on Index Load Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Use `registerOnIndexed` to execute a callback function once the search index has finished loading. If the index is already loaded, the callback runs immediately. Multiple callbacks can be registered. ```typescript registerOnIndexed(callback: () => void): void ``` ```typescript window.omnisearch.registerOnIndexed(() => { console.log('Search index is ready!') // Now safe to call search() }) ``` -------------------------------- ### onunload() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md Called when the plugin is unloaded. It performs cleanup tasks such as removing global API references, event listeners, clearing cache, and closing the HTTP API server. ```APIDOC ## onunload() ### Description Called when the plugin is unloaded. Performs cleanup tasks: removes global Omnisearch API reference, removes event listeners, clears cache (in production mode), and closes HTTP API server. ### Method async ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (void) Returns a Promise that resolves when cleanup is complete. #### Response Example None ``` -------------------------------- ### URL Scheme Invocation Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/public-api.md Explains how to invoke Omnisearch using the Obsidian URI scheme to open the search modal with a pre-filled query. ```APIDOC ## URL Scheme ### Description Opens the Vault Search modal with the query pre-filled by using the `obsidian://omnisearch` URI. ### Endpoint `obsidian://omnisearch?query=[search_term]` ### Parameters #### Query Parameters - **query** (string) - Required - The search term to pre-fill in the search modal. ### Request Example `obsidian://omnisearch?query=search+term` ``` -------------------------------- ### Populate Search Index Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/omnisearch-plugin.md The main routine for indexing vault files. It loads cache, determines file changes, indexes files in the background, and manages cache writes. ```typescript private async populateIndex(): Promise ``` -------------------------------- ### URL Scheme Source: https://github.com/scambier/obsidian-omnisearch/blob/master/Doc Omnisearch/Public API & URL Scheme.md Open Omnisearch and trigger a search using a custom URL scheme. This will bring Omnisearch to the foreground and execute the specified query. ```APIDOC ## URL Scheme You can open Omnisearch and trigger a search with the following scheme: `obsidian://omnisearch?query=foo bar`. This will switch the focus to Obsidian, open Omnisearch, and execute the query "foo bar". ``` -------------------------------- ### Database Class Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/database.md The Database class extends Dexie to manage IndexedDB tables for search cache and embeds tracking. It provides methods for interacting with the database. ```APIDOC ## Class: Database Extends Dexie to manage IndexedDB tables for search cache and embeds tracking. ```typescript export class Database extends Dexie { public static readonly dbVersion = 10 searchHistory!: Dexie.Table<{ id?: number; query: string }, number> minisearch!: Dexie.Table<{ date: string; paths: DocumentRef[]; data: AsPlainObject }, string> embeds!: Dexie.Table<{ embedded: string; referencedBy: string[] }, string> constructor(private plugin: OmnisearchPlugin) } ``` ``` -------------------------------- ### Search Vault from Browser Console Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/QUICKSTART.md Use this snippet to perform searches directly within the Obsidian browser console. It also shows how to wait for the index to be ready and refresh the index. ```javascript // Search the vault const results = await window.omnisearch.search('typescript') // Wait for index to be ready window.omnisearch.registerOnIndexed(() => { console.log('Index ready!') }) // Refresh the index await window.omnisearch.refreshIndex() ``` -------------------------------- ### EventBus.enable() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/event-bus.md Re-enables a previously disabled context, allowing events within that context to be triggered again. ```APIDOC ## enable() ### Description Re-enables a previously disabled context. ### Method Signature ```typescript public enable(context: string): void ``` ### Parameters #### Path Parameters - **context** (string) - Required - Context to enable ### Example ```typescript eventBus.enable('infile') // infile events are now active again ``` ``` -------------------------------- ### Search with Filters using cURL Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/endpoints.md Execute a search query with filters, such as file extensions, using cURL. This allows for more targeted searches within your Omnisearch vault. ```bash # With filters curl "http://localhost:8080/search?q=interface+ext:.ts" ``` -------------------------------- ### Load Search Cache Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/search-engine.md Loads the search index and cached embeds from IndexedDB. Returns true if the cache was successfully loaded and is valid, otherwise false. ```typescript async loadCache(): Promise ``` ```typescript const hasCache = await searchEngine.loadCache() if (hasCache) { console.log('Index loaded from cache') } ``` -------------------------------- ### Querying Search Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/INDEX.md Information on how to parse and construct search queries for Omnisearch, detailing the query syntax and related functionalities. ```APIDOC ## Query Parsing ### Description Details on how to parse and construct search queries for Omnisearch, including syntax and related functionalities. ### Documentation → [query.md](api-reference/query.md) ``` -------------------------------- ### EventBus.emit() Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/event-bus.md Triggers all callbacks for a given event across all enabled contexts, passing any provided arguments to the callbacks. ```APIDOC ## emit() ### Description Triggers all callbacks for a given event across all enabled contexts. ### Method Signature ```typescript public emit(event: string, ...args: any[]): void ``` ### Parameters #### Path Parameters - **event** (string) - Required - Event name to emit - **args** (any[]) - Optional - Arguments to pass to callbacks ### Behavior - Only calls handlers in enabled contexts. - Passes all `args` to the callback function. - Ignores handlers in disabled contexts. - Callbacks can throw errors without affecting others. ### Example ```typescript // Emit with data eventBus.emit('search-complete', results, query) // Emit without data eventBus.emit('modal-closed') // All listeners in enabled contexts will receive the arguments ``` ``` -------------------------------- ### Private tokenizeWords Method Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/tokenizer.md Extracts individual words from text using word boundary detection. Supports Chinese segmentation, Japanese tokenization, and standard splitting. ```typescript private tokenizeWords(text: string): string[] ``` -------------------------------- ### isFileIndexable(path: string): boolean Source: https://github.com/scambier/obsidian-omnisearch/blob/master/_autodocs/api-reference/notes-indexer.md Determines whether a file should be indexed based on all criteria (exclusions, file type, settings). ```APIDOC ## Method: isFileIndexable() Determines whether a file should be indexed based on all criteria (exclusions, file type, settings). ```typescript public isFileIndexable(path: string): boolean ``` ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | path | string | File path to check | Returns: `true` if file should be indexed, `false` otherwise. Checks: 1. If file is in excluded folders and `hideExcluded` is enabled 2. If filename is indexable via `isFilenameIndexable()` 3. If content is indexable via `isContentIndexable()` ### Example ```typescript if (plugin.notesIndexer.isFileIndexable('notes/my-note.md')) { // File will be indexed await searchEngine.addFromPaths(['notes/my-note.md']) } ``` ```