Compare commits

..
22 Commits
Author SHA1 Message Date
scambier 921a72b015 buggy Arabic diacritics removal 2025-07-11 18:57:07 +02:00
scambier 92a7af6ec5 useless var 2025-07-11 18:56:24 +02:00
scambier 52ada90150 useless file 2025-07-11 18:55:56 +02:00
scambier d3c7e7ea8e Fixed date "bug" 2025-07-11 18:22:44 +02:00
scambier 99fd363c22 database down to dbVersion 1
no need it to keep it at 10 like Omnisearch, this is a v1
2025-07-11 18:22:30 +02:00
scambier dd7d7a367d readme 2025-07-11 18:22:05 +02:00
scambier 282fd1be13 Fixed icons bug 2025-06-25 21:49:52 +02:00
scambier 46a5d3d114 cleaning custom icons 2025-06-25 21:49:48 +02:00
scambier d821344ade remove stopwords 2025-06-25 21:29:15 +02:00
scambier 960b0260f9 cleaning 2025-06-21 15:34:05 +02:00
scambier d34c06e57a removed badges 2025-06-21 14:36:28 +02:00
scambier a008b15a6a readme update 2025-06-21 14:34:28 +02:00
scambier ba535966ab Removed in-file search 2025-06-21 14:03:33 +02:00
scambier 325933f538 removed notice setting 2025-06-21 13:59:21 +02:00
scambier fc847b02b5 Removed a circular dependency 2025-06-21 13:56:38 +02:00
scambier 833d89dea8 removed useless split camelcase option 2025-06-21 13:47:04 +02:00
scambier b460f1bee5 Removed ai image analyzer 2025-06-21 13:44:39 +02:00
scambier 5d50f9cb82 Removed url tokenization 2025-06-21 13:40:11 +02:00
scambier 080805f714 always highlight tokens 2025-06-21 13:38:42 +02:00
scambier 88923910aa Removed forced cache saving 2025-06-21 13:35:59 +02:00
scambier d85a132e50 removed disabling option 2025-06-21 13:32:56 +02:00
scambier f0c16d5905 Always remove diacritics 2025-06-21 13:29:37 +02:00
33 changed files with 216 additions and 1367 deletions

No files matched your search

-32
View File
@@ -1,32 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG] "
labels: ''
assignees: ''
---
<!-- PLEASE FILL THIS TEMPLATE -->
<!-- If you don't fill it, I'll ask you to fill it before looking at your issue -->
**Problem description:**
<!-- Describe your problem in details. -->
<!-- If applicable, you can copy-paste the console logs (ctrl+shift+i in Obsidian) -->
<!-- and attach screenshots -->
**Your environment:**
<!-- Please, if possible and before filing an issue, -->
<!-- make sure that you have the latest available version of Omnisearch. -->
- Omnisearch version:
- Obsidian version:
- Operating system:
- Number of indexed documents in your vault (approx.):
**Things to try:**
- Does the problem occur when Omnisearch is the only active community plugin:
- Does the problem occur when you _don't_ index PDFs, images, or other non-notes files:
- Does the problem occur after a cache reset:
-20
View File
@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[Feature request]"
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->
**Describe alternatives you've considered**
<!-- A clear and concise description of any alternative solutions or features you've considered. -->
**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->
+1 -1
View File
@@ -6,7 +6,7 @@ on:
- "*"
env:
PLUGIN_NAME: omnisearch
PLUGIN_NAME: locator
DIST_FOLDER: ./dist
jobs:
+7
View File
@@ -0,0 +1,7 @@
{
"detectiveOptions": {
"ts": {
"skipTypeImports": true
}
}
}
+1 -241
View File
@@ -1,243 +1,3 @@
# Omnisearch Changelog
# Locator Changelog
This changelog is not exhaustive.
## 1.27.x
- Updated Svelte from v3 to v5
- Highlighting improvements
## 1.26.x
- Allow `# headings` as display titles in search results
- Added an experimental recency boost
- Added lazy loading for the vault modal items
## 1.25.x
- Added basic support for embed references in Vault Search results
- Added support for [Iconize](https://github.com/FlorianWoelki/obsidian-iconize)
- Weights are now 1-10 (instead of 1-5)
- Small performance improvements
## 1.24.x
- Added support for [AI Image Analyzer](https://github.com/Swaggeroo/obsidian-ai-image-analyzer)
## 1.23.x
- Updated Chinese tokenizer
- Added user-defined boosted fields
- No more freezes when loading large caches (hopefully)
- Large refactoring to properly clean up several older warnings
## 1.22.x
- Improved highlighting
## 1.21.x
- Added support for .docx and .xlsx
## 1.20.x
- Refactored indexing tokenization process to correctly take diacritics into account
- Added highlighting in the note's path
- Improved the selection of the chosen excerpt in the results list
## 1.19.x
- Various bugfixes and improvements
## 1.18.x
- Added a localhost server to use Omnisearch's API from outside Obsidian
## 1.17.x
- Added a shortcut to open files without closing Omnisearch
- Prefill the search field with selected text
- Improved highlighting
## 1.16.x
- Various indexing/tokenization improvements
## 1.15.x
- Added support of webp images
- Configurable fuzziness
- Added support for DataLoom plugin files
- Unsupported files are now indexed by their path
- Unmarked tags are now slightly boosted
## 1.14.x
- Added a `path:` option
- Bugfixes
## 1.13.x
- CamelCaseWords are now indexed as 3 words
- Reduced search freezes in some cases
## 1.12.x
- You can filter files by their extension
- Refreshed UI
- New API functions
- Fixed some tokenization issues
## 1.10.x - 1.11.x
- Added support for Text Extractor; Omnisearch no longer extracts text itself
- Added canvas indexing
- Improved tags indexing
## 1.9.x
- PDFs are no longer indexed on mobile
- Performance improvements
- Various bugfixes
## 1.8.x
- Added OCR for images
- OCR and PDF indexing are now restricted to desktop. They either don't work or consume too much resources during indexing of big vaults. Too many headaches.
- Notes caching is deactivated on iOS because of crashes: memory usage too high during (de)serializing.
- Added an URL scheme for integration with external tools: `obsidian://omnisearch?query=foo bar`
## 1.7.x
### New
- PDF Indexing https://github.com/scambier/obsidian-omnisearch/issues/58
### Improved
- Code refactor to better scale and handle PDFs as smoothly as possible
### Fixed
- Search history https://github.com/scambier/obsidian-omnisearch/issues/104
- Text in search input was not always correctly selected https://github.com/scambier/obsidian-omnisearch/issues/105
- Padding issue https://github.com/scambier/obsidian-omnisearch/issues/113
### Removed
- Caching data https://github.com/scambier/obsidian-omnisearch/issues/92#issuecomment-1287647725
## 1.6.x
### New
- Omnisearch can now index other plaintext files ~~and PDFs~~ https://github.com/scambier/obsidian-omnisearch/issues/58
- Search history, navigable with <code>alt+up/down</code> https://github.com/scambier/obsidian-omnisearch/issues/90
- Added a setting to toggle the visibility of the note excerpt in results https://github.com/scambier/obsidian-omnisearch/issues/70
### Improved
- You can now create a new note in a new pane https://github.com/scambier/obsidian-omnisearch/issues/87
- Added a setting to show a "create note" button https://github.com/scambier/obsidian-omnisearch/issues/96
### Fixed
- Fixed layout issues https://github.com/scambier/obsidian-omnisearch/issues/97
## 1.5.x
### New
* Added a toggleable sidebar button to open Omnisearch: https://github.com/scambier/obsidian-omnisearch/issues/60
* Added a cache-clearing mechanism in case of corruption: https://github.com/scambier/obsidian-omnisearch/issues/83
### Improved
* Notes created by Omnisearch now honour the default note location https://github.com/scambier/obsidian-omnisearch/pull/81
* Ctrl+click now opens the note in a new pane https://github.com/scambier/obsidian-omnisearch/issues/61
* Improved highlighting https://github.com/scambier/obsidian-omnisearch/issues/85
### Fixed
* Fixed some edge cases when opening an already open/pinned note https://github.com/scambier/obsidian-omnisearch/issues/51 https://github.com/scambier/obsidian-omnisearch/issues/80
* Fixed nested tags searching https://github.com/scambier/obsidian-omnisearch/issues/79
* Fixed a silent crash when clicking on In-File search results https://github.com/scambier/obsidian-omnisearch/issues/84
## 1.4.x
### New
- Opt-in support for Vim navigation keys: https://github.com/scambier/obsidian-omnisearch/issues/26
- Opt-in display of "short form" links: https://github.com/scambier/obsidian-omnisearch/issues/59
- Opt-in search index serialization, for faster loading times: https://github.com/scambier/obsidian-omnisearch/pull/64 by @mnaoumov
- Opt-out: diacritics can now be ignored
- Added support for `#tag` searches: https://github.com/scambier/obsidian-omnisearch/issues/48
- Added a basic public API for integration with other plugins: https://github.com/scambier/obsidian-omnisearch/issues/22 https://github.com/scambier/obsidian-omnisearch/issues/69
- Use `alt+enter` to inject a link to the currently selected search result item: https://github.com/scambier/obsidian-omnisearch/issues/32
### Improved
- You can now switch between "Vault" and "In-File" modals with `tab`
- Search index updates are now done only when Omnisearch is invoked: https://github.com/scambier/obsidian-omnisearch/issues/57
- New files are now created empty: https://github.com/scambier/obsidian-omnisearch/issues/77
### Fixed
- Opening a pinned note would open it a second time: https://github.com/scambier/obsidian-omnisearch/issues/51
- Fixed an issue that would index "non-existing notes" multiple times: https://github.com/scambier/obsidian-omnisearch/issues/68
- Fixed a visual bug for Obsidian 0.15.3: https://github.com/scambier/obsidian-omnisearch/issues/76
- Fixed the diacritics normalization of the note's title: https://github.com/scambier/obsidian-omnisearch/issues/72
## 1.3.x
### New
* Chinese support by @aidenlx in https://github.com/scambier/obsidian-omnisearch/pull/37
* You need to install https://github.com/aidenlx/cm-chs-patch to enable this feature
* Settings page https://github.com/scambier/obsidian-omnisearch/issues/41
* Do not show indexing Notice by default by @chrisgrieser in https://github.com/scambier/obsidian-omnisearch/pull/46
* Include notes that don't exist https://github.com/scambier/obsidian-omnisearch/issues/14
### Improved
* Better accessibility https://github.com/scambier/obsidian-omnisearch/issues/50
* Note aliases are now scored as high as the filename in search results https://github.com/scambier/obsidian-omnisearch/issues/34
* By default, reindexing is now done when the app is out of focus, and not after each save https://github.com/scambier/obsidian-omnisearch/issues/57
* On mobile, indexing is only done at startup
### Fixed
* Showing an error when a note can't be created https://github.com/scambier/obsidian-omnisearch/issues/52
## 1.2.x
### New
* #42 Files that are present in Obsidian's "Excluded Files" list are downranked by a factor of 3 (_desktop only_)
## 1.1.1
### Fixes
* Fixed a crash when no results were returned
## 1.1.0
### New
* #25 Search filters: expressions in quotes and exclusions
* Added support for beta versions with [BRAT](https://github.com/TfTHacker/obsidian42-brat)
This works as a "post-search" filter and does not allow for partial words searches (see #35)
### Fixes
* #39 Fixed key events not correctly prevented in the search input
**Full Changelog**: https://github.com/scambier/obsidian-omnisearch/compare/1.0.1...1.1.0
## 1.0.1
## 1.0.0
* First non-beta release
* Includes Vault search and In-File search
+16 -30
View File
@@ -1,38 +1,30 @@
# Omnisearch for Obsidian
> [!CAUTION]
> This project is a heavy work-in-progress, there are bugs, and features may change or disappear.
# Locator for Obsidian
[![Sponsor me](https://img.shields.io/badge/%E2%9D%A4%20Like%20this%20plugin%3F-Sponsor%20me!-ff69b4)](https://github.com/sponsors/scambier)
![Obsidian plugin](https://img.shields.io/endpoint?url=https%3A%2F%2Fscambier.xyz%2Fobsidian-endpoints%2Fomnisearch.json)
![GitHub release (latest by date and asset)](https://img.shields.io/github/downloads/scambier/obsidian-omnisearch/latest/main.js)
![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/scambier/obsidian-omnisearch)
![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/scambier/obsidian-omnisearch?include_prereleases&label=BRAT%20beta)
> 🏆 Winner of the _[2023 Gems of the Year](https://obsidian.md/blog/2023-goty-winners/)_ in the "Existing plugin" category 🏆
---
**Omnisearch** is a search engine that "_just works_".
**Locator** is an Obsidian plugin that lets you locate your files in a few keystrokes. It is an experimental fork of Omnisearch.
It always instantly shows you the most relevant results, thanks to its smart weighting algorithm.
Under the hood, it uses the excellent [MiniSearch](https://github.com/lucaong/minisearch) library. This free plugin is totally unrelated to the omnisearch.ai paid product.
Under the hood, it uses the excellent [MiniSearch](https://github.com/lucaong/minisearch) library.
![](https://raw.githubusercontent.com/scambier/obsidian-omnisearch/master/images/omnisearch.gif)
## Documentation
https://publish.obsidian.md/omnisearch/Index
## Installation
- Omnisearch is available on [the official Community Plugins repository](https://obsidian.md/plugins?search=Omnisearch).
- Beta releases can be installed through [BRAT](https://github.com/TfTHacker/obsidian42-brat). **Be advised that those
versions can be buggy and break things.**
- Locator can be installed through [BRAT](https://github.com/TfTHacker/obsidian42-brat).
You can check the [CHANGELOG](./CHANGELOG.md) for more information on the different versions.
## Features
> Omnisearch's first goal is to _locate_ files instantly. You can see it as a _Quick Switcher_ on steroids.
> Locator's first goal is to _locate_ files instantly. You can see it as a _Quick Switcher_ on steroids.
- Find your **📝notes, 📄Office documents, 📄PDFs, and 🖼images** faster than ever
- Images, documents, and PDF indexing is available
@@ -45,31 +37,25 @@ You can check the [CHANGELOG](./CHANGELOG.md) for more information on the differ
- Workflow similar to the "Quick Switcher" core plugin
- Opt-in local HTTP server to query Omnisearch from outside of Obsidian
- Resistance to typos
- Switch between Vault and In-file search to quickly skim multiple results in a single note
- Supports `"expressions in quotes"` and `-exclusions`
- Filters file types with `.jpg` or `.md`
- Directly Insert a `[[link]]` from the search results
- Supports Vim navigation keys
**Note:** support of Chinese depends
on [this additional plugin](https://github.com/aidenlx/cm-chs-patch) (also you may need to clear search cache data to apply new Chinese index). Please read its documentation for more
information.
## Projects that use Omnisearch
## Issues & Feature Requests
_Submit a PR to add your own project!_
Locator is a personal hobby project, tailored for my own needs. It is publicly available because you may find it useful too, but I'm not interested in your issues or pull requests.
- [Omnisearch Companion](https://github.com/ALegendsTale/omnisearch-companion), an extension for your browser ([Firefox](https://addons.mozilla.org/en-US/firefox/addon/omnisearch-companion/), [Chrome](https://chromewebstore.google.com/detail/omnisearch-companion/kcjcnnlpfbilodfnnkpioijobpjhokkd))
- [Actions for Obsidian](https://actions.work/actions-for-obsidian)
- [Userscripts](https://publish.obsidian.md/omnisearch/Inject+Omnisearch+results+into+your+search+engine) to inject Omnisearch into your favorite web search engine
If you'd like to participate in a similar project (thank you!), I'll be glad to review your pull requests for [**Omnisearch**](https://github.com/scambier/obsidian-omnisearch)
Thank you for your understanding.
## LICENSE
Omnisearch is licensed under [GPL-3](https://tldrlegal.com/license/gnu-general-public-license-v3-(gpl-3)).
Locator is licensed under [GPL-3](https://tldrlegal.com/license/gnu-general-public-license-v3-(gpl-3)).
## Thanks
To all people who donate through [Ko-Fi](https://ko-fi.com/scambier)
or [Github Sponsors](https://github.com/sponsors/scambier) ❤
![JetBrains logo](https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.svg)
+22 -22
View File
@@ -1,7 +1,7 @@
.omnisearch-modal {
.locator-modal {
}
.omnisearch-result {
.locator-result {
white-space: normal;
display: flex;
flex-direction: row;
@@ -9,7 +9,7 @@
flex-wrap: nowrap;
}
.omnisearch-result__title-container {
.locator-result__title-container {
display: flex;
align-items: center;
justify-content: space-between;
@@ -17,17 +17,17 @@
flex-wrap: wrap;
}
.omnisearch-result__title {
.locator-result__title {
white-space: pre-wrap;
align-items: center;
display: flex;
gap: 5px;
}
.omnisearch-result__title > span {
.locator-result__title > span {
}
.omnisearch-result__folder-path {
.locator-result__folder-path {
font-size: 0.75rem;
align-items: center;
display: flex;
@@ -35,17 +35,17 @@
color: var(--text-muted);
}
.omnisearch-result__extension {
.locator-result__extension {
font-size: 0.7rem;
color: var(--text-muted);
}
.omnisearch-result__counter {
.locator-result__counter {
font-size: 0.7rem;
color: var(--text-muted);
}
.omnisearch-result__body {
.locator-result__body {
white-space: normal;
font-size: small;
word-wrap: normal;
@@ -59,20 +59,20 @@
margin-inline-start: 0.5em;
}
.omnisearch-result__embed {
.locator-result__embed {
margin-left: 1em;
}
.omnisearch-result__image-container {
.locator-result__image-container {
flex-basis: 20%;
text-align: end;
}
.omnisearch-highlight {
.locator-highlight {
}
.omnisearch-default-highlight {
.locator-default-highlight {
text-decoration: underline;
text-decoration-color: var(--text-highlight-bg);
text-decoration-thickness: 3px;
@@ -80,14 +80,14 @@
text-decoration-skip-ink: none;
}
.omnisearch-input-container {
.locator-input-container {
display: flex;
align-items: center;
flex-direction: row;
gap: 5px;
}
.omnisearch-result__icon {
.locator-result__icon {
display: inline-block;
vertical-align: middle;
width: 16px;
@@ -95,41 +95,41 @@
margin-right: 4px;
}
.omnisearch-result__icon svg {
.locator-result__icon svg {
width: 100%;
height: 100%;
}
.omnisearch-result__icon--emoji {
.locator-result__icon--emoji {
font-size: 16px;
vertical-align: middle;
margin-right: 4px;
}
@media only screen and (max-width: 600px) {
.omnisearch-input-container {
.locator-input-container {
flex-direction: column;
}
.omnisearch-input-container__buttons {
.locator-input-container__buttons {
display: flex;
flex-direction: row;
width: 100%;
padding: 0 1em 0 1em;
gap: 1em;
}
.omnisearch-input-container__buttons > button {
.locator-input-container__buttons > button {
flex-grow: 1;
}
}
@media only screen and (min-width: 600px) {
.omnisearch-input-container__buttons {
.locator-input-container__buttons {
margin-inline-end: 1em;
}
}
.omnisearch-input-field {
.locator-input-field {
position: relative;
flex-grow: 1;
}
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "scambier.obsidian-locator",
"version": "1.27.1",
"version": "0.1.0",
"description": "Locate your notes in a few keystrokes",
"main": "dist/main.js",
"scripts": {
@@ -22,6 +22,7 @@
"@types/lodash-es": "^4.17.12",
"@types/node": "^16.18.126",
"@types/pako": "^2.0.3",
"@types/stopword": "^2.0.3",
"babel-jest": "^27.5.1",
"builtin-modules": "^3.3.0",
"esbuild": "0.17.19",
@@ -48,7 +49,7 @@
"minisearch": "7.1.0",
"pure-md5": "^0.1.14",
"search-query-parser": "^1.6.0",
"svelte-multiselect": "github:janosh/svelte-multiselect"
"stopword": "^3.1.5"
},
"pnpm": {
"overrides": {
+16 -73
View File
@@ -32,9 +32,9 @@ importers:
search-query-parser:
specifier: ^1.6.0
version: 1.6.0
svelte-multiselect:
specifier: github:janosh/svelte-multiselect
version: https://codeload.github.com/janosh/svelte-multiselect/tar.gz/91f22d0cafdf931607288d18c5268badd358d83b
stopword:
specifier: ^3.1.5
version: 3.1.5
devDependencies:
'@babel/preset-env':
specifier: ^7.26.9
@@ -60,6 +60,9 @@ importers:
'@types/pako':
specifier: ^2.0.3
version: 2.0.3
'@types/stopword':
specifier: ^2.0.3
version: 2.0.3
babel-jest:
specifier: ^27.5.1
version: 27.5.1(@babel/core@7.26.10)
@@ -1140,6 +1143,9 @@ packages:
'@types/stack-utils@2.0.3':
resolution: {integrity: sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==}
'@types/stopword@2.0.3':
resolution: {integrity: sha512-hioMj0lOvISM+EDevf7ijG8EMbU+J3pj4SstCyfQC1t39uPYpAe7beSfBdU6c1d9jeECTQQtR3UJWtVoUO8Weg==}
'@types/tern@0.23.9':
resolution: {integrity: sha512-ypzHFE/wBzh+BlH6rrBgS5I/Z7RD21pGhZ2rltb/+ZrVM1awdZwjx7hE5XfuYgHWk9uvV5HLZN3SloevCAp3Bw==}
@@ -1424,9 +1430,6 @@ packages:
resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==}
engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'}
code-red@1.0.4:
resolution: {integrity: sha512-7qJWqItLA8/VPVlKJlFXU+NBlo/qyfs39aJcuMT/2ere32ZqvF5OSxgdM5xOfJJ7O429gg2HM47y8v9P+9wrNw==}
collect-v8-coverage@1.0.2:
resolution: {integrity: sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==}
@@ -1471,10 +1474,6 @@ packages:
css-select@5.1.0:
resolution: {integrity: sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==}
css-tree@2.3.1:
resolution: {integrity: sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==}
engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
css-what@6.1.0:
resolution: {integrity: sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==}
engines: {node: '>= 6'}
@@ -1836,9 +1835,6 @@ packages:
estree-walker@2.0.2:
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
estree-walker@3.0.3:
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
esutils@2.0.3:
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
engines: {node: '>=0.10.0'}
@@ -2376,9 +2372,6 @@ packages:
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
mdn-data@2.0.30:
resolution: {integrity: sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==}
merge-stream@2.0.0:
resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}
@@ -2542,9 +2535,6 @@ packages:
resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==}
engines: {node: '>=8'}
periscopic@3.1.0:
resolution: {integrity: sha512-vKiQ8RRtkl9P+r/+oefh25C3fhybptkHKCZSPlcXiJux2tJF55GnEj3BVn4A5gKfq9NWWXXrxkHBwVPUfH0opw==}
picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -2802,6 +2792,9 @@ packages:
resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==}
engines: {node: '>=10'}
stopword@3.1.5:
resolution: {integrity: sha512-OgLYGVFCNa430WOrj9tYZhQge5yg6vd6JsKredveAqEhdLVQkfrpnQIGjx0L9lLqzL4Kq4J8yNTcfQR/MpBwhg==}
stream-to-array@2.3.0:
resolution: {integrity: sha512-UsZtOYEn4tWU2RGLOXr/o/xjRBftZRlG3dEWoaHr8j4GuypJ3isitGbVyjQKAuMu+xbiop8q224TjiZWc4XTZA==}
@@ -2887,10 +2880,6 @@ packages:
jest: '>= 27'
svelte: '>= 3'
svelte-multiselect@https://codeload.github.com/janosh/svelte-multiselect/tar.gz/91f22d0cafdf931607288d18c5268badd358d83b:
resolution: {tarball: https://codeload.github.com/janosh/svelte-multiselect/tar.gz/91f22d0cafdf931607288d18c5268badd358d83b}
version: 11.0.0-rc.1
svelte-preprocess@6.0.3:
resolution: {integrity: sha512-PLG2k05qHdhmRG7zR/dyo5qKvakhm8IJ+hD2eFRQmMLHp7X3eJnjeupUtvuRpbNiF31RjVw45W+abDwHEmP5OA==}
engines: {node: '>= 18.0.0'}
@@ -2928,10 +2917,6 @@ packages:
typescript:
optional: true
svelte@4.2.12:
resolution: {integrity: sha512-d8+wsh5TfPwqVzbm4/HCXC783/KPHV60NvwitJnyTA5lWn1elhXMNWhXGCJ7PwPa8qFUnyJNIyuIRt2mT0WMug==}
engines: {node: '>=16'}
svelte@5.23.2:
resolution: {integrity: sha512-PHP1o0aYJNMatiZ+0nq1W/Z1W1/l5Z94B9nhMIo7gsuTBbxC454g4O5SQMjQpZBUZi5ANYUrXJOE4gPzcN/VQw==}
engines: {node: '>=18'}
@@ -4375,6 +4360,8 @@ snapshots:
'@types/stack-utils@2.0.3': {}
'@types/stopword@2.0.3': {}
'@types/tern@0.23.9':
dependencies:
'@types/estree': 1.0.6
@@ -4714,14 +4701,6 @@ snapshots:
co@4.6.0: {}
code-red@1.0.4:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.0
'@types/estree': 1.0.6
acorn: 8.14.1
estree-walker: 3.0.3
periscopic: 3.1.0
collect-v8-coverage@1.0.2: {}
color-convert@2.0.1:
@@ -4764,11 +4743,6 @@ snapshots:
domutils: 3.2.2
nth-check: 2.1.1
css-tree@2.3.1:
dependencies:
mdn-data: 2.0.30
source-map-js: 1.2.1
css-what@6.1.0: {}
css.escape@1.5.1: {}
@@ -5099,10 +5073,6 @@ snapshots:
estree-walker@2.0.2: {}
estree-walker@3.0.3:
dependencies:
'@types/estree': 1.0.6
esutils@2.0.3: {}
execa@5.1.1:
@@ -5885,8 +5855,6 @@ snapshots:
math-intrinsics@1.1.0: {}
mdn-data@2.0.30: {}
merge-stream@2.0.0: {}
merge2@1.4.1: {}
@@ -6034,12 +6002,6 @@ snapshots:
path-type@4.0.0: {}
periscopic@3.1.0:
dependencies:
'@types/estree': 1.0.6
estree-walker: 3.0.3
is-reference: 3.0.3
picocolors@1.1.1: {}
picomatch@2.3.1: {}
@@ -6283,6 +6245,8 @@ snapshots:
dependencies:
escape-string-regexp: 2.0.0
stopword@3.1.5: {}
stream-to-array@2.3.0:
dependencies:
any-promise: 1.3.0
@@ -6364,10 +6328,6 @@ snapshots:
jest: 27.5.1
svelte: 5.23.2
svelte-multiselect@https://codeload.github.com/janosh/svelte-multiselect/tar.gz/91f22d0cafdf931607288d18c5268badd358d83b:
dependencies:
svelte: 4.2.12
svelte-preprocess@6.0.3(@babel/core@7.26.10)(postcss@8.5.3)(sass@1.86.0)(svelte@5.23.2)(typescript@5.8.2):
dependencies:
svelte: 5.23.2
@@ -6377,23 +6337,6 @@ snapshots:
sass: 1.86.0
typescript: 5.8.2
svelte@4.2.12:
dependencies:
'@ampproject/remapping': 2.3.0
'@jridgewell/sourcemap-codec': 1.5.0
'@jridgewell/trace-mapping': 0.3.25
'@types/estree': 1.0.6
acorn: 8.14.1
aria-query: 5.3.2
axobject-query: 4.1.0
code-red: 1.0.4
css-tree: 2.3.1
estree-walker: 3.0.3
is-reference: 3.0.3
locate-character: 3.0.0
magic-string: 0.30.17
periscopic: 3.1.0
svelte@5.23.2:
dependencies:
'@ampproject/remapping': 2.3.0
-223
View File
@@ -1,223 +0,0 @@
<script lang="ts">
import InputSearch from './InputSearch.svelte'
import {
Action,
eventBus,
excerptAfter,
type ResultNote,
type SearchMatch,
} from '../globals'
import { getCtrlKeyLabel, loopIndex } from '../tools/utils'
import { onDestroy, onMount, tick } from 'svelte'
import { MarkdownView, Platform } from 'obsidian'
import ModalContainer from './ModalContainer.svelte'
import {
LocatorInFileModal,
LocatorVaultModal,
} from '../components/modals'
import ResultItemInFile from './ResultItemInFile.svelte'
import { Query } from '../search/query'
import { openNote } from '../tools/notes'
import type LocatorPlugin from '../main'
export let plugin: LocatorPlugin
export let modal: LocatorInFileModal
export let parent: LocatorVaultModal | null = null
export let singleFilePath = ''
export let previousQuery: string | undefined
let searchQuery: string
let groupedOffsets: number[] = []
let selectedIndex = 0
let note: ResultNote | undefined
let query: Query
$: searchQuery = previousQuery ?? ''
onMount(() => {
eventBus.enable('infile')
eventBus.on('infile', Action.Enter, openSelection)
eventBus.on('infile', Action.OpenInNewPane, openSelectionInNewTab)
eventBus.on('infile', Action.ArrowUp, () => moveIndex(-1))
eventBus.on('infile', Action.ArrowDown, () => moveIndex(1))
eventBus.on('infile', Action.Tab, switchToVaultModal)
})
onDestroy(() => {
eventBus.disable('infile')
})
$: (async () => {
if (searchQuery) {
query = new Query(searchQuery, {
ignoreDiacritics: plugin.settings.ignoreDiacritics,
ignoreArabicDiacritics: plugin.settings.ignoreArabicDiacritics,
})
note =
(
await plugin.searchEngine.getSuggestions(query, {
singleFilePath,
})
)[0] ?? null
}
selectedIndex = 0
await scrollIntoView()
})()
$: {
if (note) {
let groups = getGroups(note.matches)
// If there are quotes in the search,
// only show results that match at least one of the quotes
const exactTerms = query.getExactTerms()
if (exactTerms.length) {
groups = groups.filter(group =>
exactTerms.every(exact =>
group.some(match => match.match.includes(exact))
)
)
}
groupedOffsets = groups.map(group => Math.round(group.first()!.offset))
}
}
/**
* Group together close matches to reduce the number of results
*/
function getGroups(matches: SearchMatch[]): SearchMatch[][] {
const groups: SearchMatch[][] = []
let lastOffset = -1
let count = 0 // Avoid infinite loops
while (++count < 100) {
const group = getGroupedMatches(matches, lastOffset, excerptAfter)
if (!group.length) break
lastOffset = group.last()!.offset
groups.push(group)
}
return groups
}
function getGroupedMatches(
matches: SearchMatch[],
offsetFrom: number,
maxLen: number
): SearchMatch[] {
const first = matches.find(m => m.offset > offsetFrom)
if (!first) return []
return matches.filter(
m => m.offset > offsetFrom && m.offset <= first.offset + maxLen
)
}
function moveIndex(dir: 1 | -1): void {
selectedIndex = loopIndex(selectedIndex + dir, groupedOffsets.length)
scrollIntoView()
}
async function scrollIntoView(): Promise<void> {
await tick()
const elem = document.querySelector(`[data-result-id="${selectedIndex}"]`)
elem?.scrollIntoView({ behavior: 'auto', block: 'nearest' })
}
async function openSelectionInNewTab(): Promise<void> {
return openSelection(true)
}
async function openSelection(newTab = false): Promise<void> {
if (note) {
modal.close()
if (parent) parent.close()
// Open (or switch focus to) the note
const reg = plugin.textProcessor.stringsToRegex(note.foundWords)
reg.exec(note.content)
await openNote(plugin.app, note, reg.lastIndex, newTab)
// Move cursor to the match
const view = plugin.app.workspace.getActiveViewOfType(MarkdownView)
if (!view) {
// Not an editable document, so no cursor to place
return
// throw new Error('OmniSearch - No active MarkdownView')
}
const offset = groupedOffsets[selectedIndex] ?? 0
const pos = view.editor.offsetToPos(offset)
pos.ch = 0
view.editor.setCursor(pos)
view.editor.scrollIntoView({
from: { line: pos.line - 10, ch: 0 },
to: { line: pos.line + 10, ch: 0 },
})
}
}
function switchToVaultModal(): void {
new LocatorVaultModal(plugin, searchQuery ?? previousQuery).open()
modal.close()
}
</script>
<InputSearch
plugin="{plugin}"
on:input="{e => (searchQuery = e.detail)}"
placeholder="Locator - File"
initialValue="{previousQuery}">
<div class="omnisearch-input-container__buttons">
{#if Platform.isMobile}
<button on:click="{switchToVaultModal}">Vault search</button>
{/if}
</div>
</InputSearch>
<ModalContainer>
{#if groupedOffsets.length && note}
{#each groupedOffsets as offset, i}
<ResultItemInFile
{plugin}
offset="{offset}"
note="{note}"
index="{i}"
selected="{i === selectedIndex}"
on:mousemove="{_e => (selectedIndex = i)}"
on:click="{evt => openSelection(evt.ctrlKey)}"
on:auxclick="{evt => {
if (evt.button == 1) openSelection(true)
}}" />
{/each}
{:else}
<div style="text-align: center;">
We found 0 results for your search here.
</div>
{/if}
</ModalContainer>
<div class="prompt-instructions">
<div class="prompt-instruction">
<span class="prompt-instruction-command">↑↓</span><span>to navigate</span>
</div>
<div class="prompt-instruction">
<span class="prompt-instruction-command">↵</span><span>to open</span>
</div>
<div class="prompt-instruction">
<span class="prompt-instruction-command">tab</span>
<span>to switch to Vault Search</span>
</div>
<div class="prompt-instruction">
<span class="prompt-instruction-command">esc</span>
{#if !!parent}
<span>to go back to Vault Search</span>
{:else}
<span>to close</span>
{/if}
</div>
<div class="prompt-instruction">
<span class="prompt-instruction-command">{getCtrlKeyLabel()} ↵</span>
<span>to open in a new pane</span>
</div>
</div>
+17 -51
View File
@@ -1,34 +1,32 @@
<script lang="ts">
import { MarkdownView, Notice, Platform, TFile } from 'obsidian'
import { cancelable, CancelablePromise } from 'cancelable-promise'
import { debounce } from 'lodash-es'
import { MarkdownView, Notice } from 'obsidian'
import { onDestroy, onMount, tick } from 'svelte'
import InputSearch from './InputSearch.svelte'
import ModalContainer from './ModalContainer.svelte'
import {
type LocatorVaultModal,
} from '../components/modals'
import {
Action,
eventBus,
indexingStep,
IndexingStepType,
type ResultNote,
SPACE_OR_PUNCTUATION,
Action,
} from '../globals'
import type LocatorPlugin from '../main'
import { Query } from '../search/query'
import { createNote, openNote } from '../tools/notes'
import {
getCtrlKeyLabel,
getAltKeyLabel,
getCtrlKeyLabel,
getExtension,
isFilePDF,
loopIndex,
loopIndex
} from '../tools/utils'
import {
LocatorInFileModal,
type LocatorVaultModal,
} from '../components/modals'
import ResultItemVault from './ResultItemVault.svelte'
import { Query } from '../search/query'
import { cancelable, CancelablePromise } from 'cancelable-promise'
import { debounce } from 'lodash-es'
import type LocatorPlugin from '../main'
import InputSearch from './InputSearch.svelte'
import LazyLoader from './lazy-loader/LazyLoader.svelte'
import ModalContainer from './ModalContainer.svelte'
import ResultItemVault from './ResultItemVault.svelte'
let {
modal,
@@ -107,7 +105,6 @@
eventBus.on('vault', Action.CreateNote, createNoteAndCloseModal)
eventBus.on('vault', Action.OpenInNewPane, openNoteInNewPane)
eventBus.on('vault', Action.InsertLink, insertLink)
eventBus.on('vault', Action.Tab, switchToInFileModal)
eventBus.on('vault', Action.ArrowUp, () => moveIndex(-1))
eventBus.on('vault', Action.ArrowDown, () => moveIndex(1))
eventBus.on('vault', Action.PrevSearchHistory, prevSearchHistory)
@@ -149,8 +146,8 @@
cancelableQuery = null
}
query = new Query(searchQuery, {
ignoreDiacritics: plugin.settings.ignoreDiacritics,
ignoreArabicDiacritics: plugin.settings.ignoreArabicDiacritics,
ignoreDiacritics: true,
ignoreArabicDiacritics: true,
})
cancelableQuery = cancelable(
new Promise(resolve => {
@@ -271,34 +268,6 @@
modal.close()
}
function switchToInFileModal(): void {
// Do nothing if the selectedNote is a PDF,
// or if there is 0 match (e.g indexing in progress)
if (
selectedNote &&
(isFilePDF(selectedNote?.path) || !selectedNote?.matches.length)
) {
return
}
saveCurrentQuery()
modal.close()
if (selectedNote) {
// Open in-file modal for selected search result
const file = plugin.app.vault.getAbstractFileByPath(selectedNote.path)
if (file && file instanceof TFile) {
new LocatorInFileModal(plugin, file, searchQuery).open()
}
} else {
// Open in-file modal for active file
const view = plugin.app.workspace.getActiveViewOfType(MarkdownView)
if (view?.file) {
new LocatorInFileModal(plugin, view.file, searchQuery).open()
}
}
}
function moveIndex(dir: 1 | -1): void {
selectedIndex = loopIndex(selectedIndex + dir, resultNotes.length)
scrollIntoView()
@@ -323,10 +292,7 @@
placeholder="Locator - Vault">
<div class="omnisearch-input-container__buttons">
{#if plugin.settings.showCreateButton}
<button on:click={onClickCreateNote}>Create note</button>
{/if}
{#if Platform.isMobile}
<button on:click={switchToInFileModal}>In-File search</button>
<button onclick={onClickCreateNote}>Create note</button>
{/if}
</div>
</InputSearch>
-24
View File
@@ -1,24 +0,0 @@
<script lang="ts">
import type { ResultNote } from '../globals'
import ResultItemContainer from './ResultItemContainer.svelte'
import type LocatorPlugin from '../main'
export let plugin: LocatorPlugin
export let offset: number
export let note: ResultNote
export let index = 0
export let selected = false
$: cleanedContent = plugin.textProcessor.makeExcerpt(note?.content ?? '', offset)
</script>
<ResultItemContainer
id="{index.toString()}"
on:auxclick
on:click
on:mousemove
selected="{selected}">
<div class="omnisearch-result__body">
{@html plugin.textProcessor.highlightText(cleanedContent, note.matches)}
</div>
</ResultItemContainer>
+16 -67
View File
@@ -1,6 +1,10 @@
<script lang="ts">
import { showExcerpt } from '../settings/index'
import { setIcon, TFile } from 'obsidian'
import { showExcerpt } from 'src/settings/utils'
import { onMount } from 'svelte'
import type { ResultNote } from '../globals'
import type LocatorPlugin from '../main'
import { getDefaultIconSVG } from '../tools/icon-utils'
import {
getExtension,
isFileCanvas,
@@ -10,18 +14,6 @@
pathWithoutFilename,
} from '../tools/utils'
import ResultItemContainer from './ResultItemContainer.svelte'
import type LocatorPlugin from '../main'
import { setIcon, TFile } from 'obsidian'
import { onMount } from 'svelte'
// Import icon utility functions
import {
loadIconData,
initializeIconPacks,
getIconNameForPath,
loadIconSVG,
getDefaultIconSVG,
} from '../tools/icon-utils'
export let selected = false
export let note: ResultNote
@@ -30,19 +22,12 @@
let imagePath: string | null = null
let title = ''
let notePath = ''
let iconData = {}
let folderIconSVG: string | null = null
let fileIconSVG: string | null = null
let prefixToIconPack: { [prefix: string]: string } = {}
let iconsPath: string
const folderIconSVG = getDefaultIconSVG('folder')
const fileIconSVG = getDefaultIconSVG(note.path)
let iconDataLoaded = false // Flag to indicate iconData is loaded
// Initialize icon data and icon packs once when the component mounts
onMount(async () => {
iconData = await loadIconData(plugin)
const iconPacks = await initializeIconPacks(plugin)
prefixToIconPack = iconPacks.prefixToIconPack
iconsPath = iconPacks.iconsPath
iconDataLoaded = true // Set the flag after iconData is loaded
})
@@ -52,40 +37,9 @@
// Update title and notePath before loading icons
title = note.displayTitle || note.basename
notePath = pathWithoutFilename(note.path)
await loadIcons()
})()
}
async function loadIcons() {
// Load folder icon
const folderIconName = getIconNameForPath(notePath, iconData)
if (folderIconName) {
folderIconSVG = await loadIconSVG(
folderIconName,
plugin,
iconsPath,
prefixToIconPack
)
} else {
// Fallback to default folder icon
folderIconSVG = getDefaultIconSVG('folder', plugin)
}
// Load file icon
const fileIconName = getIconNameForPath(note.path, iconData)
if (fileIconName) {
fileIconSVG = await loadIconSVG(
fileIconName,
plugin,
iconsPath,
prefixToIconPack
)
} else {
// Fallback to default icons based on file type
fileIconSVG = getDefaultIconSVG(note.path, plugin)
}
}
// Svelte action to render SVG content with dynamic updates
function renderSVG(node: HTMLElement, svgContent: string) {
node.innerHTML = svgContent
@@ -148,26 +102,23 @@
</script>
<ResultItemContainer
glyph="{glyph}"
id="{note.path}"
{glyph}
id={note.path}
cssClass=" {note.isEmbed ? 'omnisearch-result__embed' : ''}"
on:auxclick
on:click
on:mousemove
selected="{selected}">
{selected}>
<div>
<div class="omnisearch-result__title-container">
<span class="omnisearch-result__title">
{#if note.isEmbed}
<span
bind:this="{elEmbedIcon}"
title="The document above is embedded in this note"></span>
bind:this={elEmbedIcon}
title="The document above is embedded in this note" />
{:else}
<!-- File Icon -->
{#if fileIconSVG}
<span class="omnisearch-result__icon" use:renderSVG="{fileIconSVG}"
></span>
{/if}
<span class="omnisearch-result__icon" use:renderSVG={fileIconSVG} />
{/if}
<span>
{@html plugin.textProcessor.highlightText(title, matchesTitle)}
@@ -193,10 +144,8 @@
{#if notePath}
<div class="omnisearch-result__folder-path">
<!-- Folder Icon -->
{#if folderIconSVG}
<span class="omnisearch-result__icon" use:renderSVG="{folderIconSVG}"
></span>
{/if}
<span class="omnisearch-result__icon" use:renderSVG={folderIconSVG} />
<span>
{@html plugin.textProcessor.highlightText(notePath, matchesNotePath)}
</span>
@@ -218,7 +167,7 @@
<!-- Image -->
{#if imagePath}
<div class="omnisearch-result__image-container">
<img style="width: 100px" src="{imagePath}" alt="" />
<img style="width: 100px" src={imagePath} alt="" />
</div>
{/if}
</div>
+5 -41
View File
@@ -1,10 +1,9 @@
import { MarkdownView, Modal, TFile } from 'obsidian'
import type { Modifier } from 'obsidian'
import ModalVault from './ModalVault.svelte'
import ModalInFile from './ModalInFile.svelte'
import { MarkdownView, Modal } from 'obsidian'
import { mount, unmount } from 'svelte'
import { Action, eventBus, EventNames, isInputComposition } from '../globals'
import type LocatorPlugin from '../main'
import { mount, unmount } from 'svelte'
import ModalVault from './ModalVault.svelte'
abstract class LocatorModal extends Modal {
protected constructor(plugin: LocatorPlugin) {
@@ -165,10 +164,8 @@ export class LocatorVaultModal extends LocatorModal {
?.editor.getSelection()
plugin.searchHistory.getHistory().then(history => {
// Previously searched query (if enabled in settings)
const previous = plugin.settings.showPreviousQueryResults
? history[0]
: null
// Previously searched query
const previous = history[0]
// Instantiate and display the Svelte component
const cmp = mount(ModalVault, {
@@ -188,36 +185,3 @@ export class LocatorVaultModal extends LocatorModal {
})
}
}
export class LocatorInFileModal extends LocatorModal {
constructor(
plugin: LocatorPlugin,
file: TFile,
searchQuery: string = '',
parent?: LocatorModal
) {
super(plugin)
const cmp = mount(ModalInFile, {
target: this.modalEl,
props: {
plugin,
modal: this,
singleFilePath: file.path,
parent: parent,
previousQuery: searchQuery,
},
})
if (parent) {
// Hide the parent vault modal, and show it back when this one is closed
parent.containerEl.toggleVisibility(false)
}
this.onClose = () => {
if (parent) {
parent.containerEl.toggleVisibility(true)
}
unmount(cmp)
}
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { Notice } from 'obsidian'
import type LocatorPlugin from './main'
export class Database extends Dexie {
public static readonly dbVersion = 10
public static readonly dbVersion = 1
searchHistory!: Dexie.Table<{ id?: number; query: string }, number>
minisearch!: Dexie.Table<
{
-2
View File
@@ -11,8 +11,6 @@ export const regexExtensions = /(?:^|\s)\.(\w+)/g
export const excerptBefore = 100
export const excerptAfter = 300
export const K_DISABLE_OMNISEARCH = 'locator-disabled'
export const eventBus = new EventBus()
export const EventNames = {
+12 -45
View File
@@ -6,37 +6,26 @@ import {
type PluginManifest,
TFile,
} from 'obsidian'
import {
LocatorInFileModal,
LocatorVaultModal,
} from './components/modals'
import {
getDefaultSettings,
loadSettings,
SettingsTab,
showExcerpt,
} from './settings'
import type { LocatorSettings } from './settings/utils'
import { isCacheEnabled } from './settings/utils'
import { saveSettings } from './settings/utils'
import { isPluginDisabled } from './settings/utils'
import { LocatorVaultModal } from './components/modals'
import { Database } from './database'
import {
eventBus,
EventNames,
indexingStep,
IndexingStepType,
type TextExtractorApi,
type AIImageAnalyzerAPI,
} from './globals'
import { notifyOnIndexed, registerAPI } from './tools/api'
import { Database } from './database'
import { SearchEngine } from './search/search-engine'
import { DocumentsRepository } from './repositories/documents-repository'
import { logVerbose } from './tools/utils'
import { NotesIndexer } from './notes-indexer'
import { TextProcessor } from './tools/text-processing'
import { DocumentsRepository } from './repositories/documents-repository'
import { EmbedsRepository } from './repositories/embeds-repository'
import { SearchEngine } from './search/search-engine'
import { SearchHistory } from './search/search-history'
import { getDefaultSettings, loadSettings, SettingsTab } from './settings'
import type { LocatorSettings } from './settings/utils'
import { isCacheEnabled, saveSettings, showExcerpt } from './settings/utils'
import { notifyOnIndexed, registerAPI } from './tools/api'
import { TextProcessor } from './tools/text-processing'
import { logVerbose } from './tools/utils'
export default class LocatorPlugin extends Plugin {
// FIXME: fix the type
@@ -70,11 +59,6 @@ export default class LocatorPlugin extends Plugin {
)
}
if (isPluginDisabled(this.app)) {
console.debug('Plugin disabled')
return
}
await cleanOldCacheFiles(this.app)
await this.database.clearOldDatabases()
@@ -100,16 +84,6 @@ export default class LocatorPlugin extends Plugin {
},
})
this.addCommand({
id: 'show-modal-infile',
name: 'In-file search',
editorCallback: (_editor, view) => {
if (view.file) {
new LocatorInFileModal(this, view.file).open()
}
},
})
const searchEngine = this.searchEngine
this.app.workspace.onLayoutReady(async () => {
@@ -229,14 +203,6 @@ export default class LocatorPlugin extends Plugin {
return (this.app as any).plugins?.plugins?.['text-extractor']?.api
}
/**
* Plugin dependency - Ai Image Analyzer
* @returns
*/
public getAIImageAnalyzer(): AIImageAnalyzerAPI | undefined {
return (this.app as any).plugins?.plugins?.['ai-image-analyzer']?.api
}
private async populateIndex(): Promise<void> {
console.time('Indexing total time')
indexingStep.set(IndexingStepType.ReadingFiles)
@@ -291,7 +257,7 @@ export default class LocatorPlugin extends Plugin {
// Disable settings.useCache while writing the cache, in case it freezes
const cacheEnabled = this.settings.useCache
if (cacheEnabled && !this.settings.DANGER_forceSaveCache) {
if (cacheEnabled) {
this.settings.useCache = false
await saveSettings(this)
}
@@ -308,6 +274,7 @@ export default class LocatorPlugin extends Plugin {
}
console.timeEnd('Indexing total time')
console.log(`Indexed ${diff.toAdd.length} files, removed ${diff.toRemove.length} files`)
if (diff.toAdd.length >= 1000 && isCacheEnabled()) {
new Notice(`Your files have been indexed.`)
}
+2 -5
View File
@@ -1,7 +1,7 @@
import type { TAbstractFile } from 'obsidian'
import type { IndexedDocument } from './globals'
import type LocatorPlugin from './main'
import { removeAnchors } from './tools/notes'
import type { IndexedDocument } from './globals'
import {
isFileCanvas,
isFileFromDataloom,
@@ -44,17 +44,14 @@ export class NotesIndexer {
public isContentIndexable(path: string): boolean {
const settings = this.plugin.settings
const hasTextExtractor = !!this.plugin.getTextExtractor()
const hasAIImageAnalyzer = !!this.plugin.getAIImageAnalyzer()
const canIndexPDF = hasTextExtractor && settings.PDFIndexing
const canIndexImages = hasTextExtractor && settings.imagesIndexing
const canIndexImagesAI = hasAIImageAnalyzer && settings.aiImageIndexing
return (
this.isFilePlaintext(path) ||
isFileCanvas(path) ||
isFileFromDataloom(path) ||
(canIndexPDF && isFilePDF(path)) ||
(canIndexImages && isFileImage(path)) ||
(canIndexImagesAI && isFileImage(path))
(canIndexImages && isFileImage(path))
)
}
+6 -16
View File
@@ -1,5 +1,8 @@
import { normalizePath, Notice, TFile } from 'obsidian'
import { normalizePath, TFile } from 'obsidian'
import type { CanvasData } from 'obsidian/canvas'
import type { IndexedDocument } from '../globals'
import type LocatorPlugin from '../main'
import { getNonExistingNotes } from '../tools/notes'
import {
countError,
extractHeadingsFromCache,
@@ -14,9 +17,6 @@ import {
removeDiacritics,
stripMarkdownCharacters,
} from '../tools/utils'
import type { CanvasData } from 'obsidian/canvas'
import type LocatorPlugin from '../main'
import { getNonExistingNotes } from '../tools/notes'
export class DocumentsRepository {
/**
@@ -96,7 +96,6 @@ export class DocumentsRepository {
let content: string | null = null
const extractor = this.plugin.getTextExtractor()
const aiImageAnalyzer = this.plugin.getAIImageAnalyzer()
// ** Plain text **
// Just read the file content
@@ -151,10 +150,8 @@ export class DocumentsRepository {
// ** Image **
else if (
isFileImage(path) &&
((this.plugin.settings.imagesIndexing &&
extractor?.canFileBeExtracted(path)) ||
(this.plugin.settings.aiImageIndexing &&
aiImageAnalyzer?.canBeAnalyzed(file)))
(this.plugin.settings.imagesIndexing &&
extractor?.canFileBeExtracted(path))
) {
if (
this.plugin.settings.imagesIndexing &&
@@ -162,13 +159,6 @@ export class DocumentsRepository {
) {
content = await extractor.extractText(file)
}
if (
this.plugin.settings.aiImageIndexing &&
aiImageAnalyzer?.canBeAnalyzed(file)
) {
content = (await aiImageAnalyzer.analyzeImage(file)) + (content ?? '')
}
}
// ** PDF **
else if (
+7 -17
View File
@@ -190,15 +190,16 @@ export class SearchEngine {
}
const mtime = storedFields?.mtime as number
const now = new Date().valueOf()
const daysElapsed = (now - mtime) / (24 * 3600)
const daysElapsed = (now - mtime) / (24 * 3600_000)
// Documents boost
const cutoff = {
[RecencyCutoff.Day]: -3,
[RecencyCutoff.Week]: -0.3,
[RecencyCutoff.Month]: -0.1,
} as const
return 1 + Math.exp(cutoff[settings.recencyBoost] * daysElapsed)
return (
1 + Math.exp(cutoff[settings.recencyBoost] * (daysElapsed / 1000))
)
},
})
@@ -331,9 +332,7 @@ export class SearchEngine {
results.map(async result => {
const doc = await this.plugin.documentsRepository.getDocument(result.id)
if (!doc) {
console.warn(
`Locator - Note "${result.id}" not in the live cache`
)
console.warn(`Locator - Note "${result.id}" not in the live cache`)
countError(true)
}
return doc
@@ -349,12 +348,7 @@ export class SearchEngine {
const title = document?.path.toLowerCase() ?? ''
const content = (document?.cleanedContent ?? '').toLowerCase()
return exactTerms.every(
q =>
content.includes(q) ||
removeDiacritics(
title,
this.plugin.settings.ignoreArabicDiacritics
).includes(q)
q => content.includes(q) || removeDiacritics(title).includes(q)
)
})
}
@@ -524,11 +518,7 @@ export class SearchEngine {
}
return (doc as any)[fieldName]
},
processTerm: (term: string) =>
(this.plugin.settings.ignoreDiacritics
? removeDiacritics(term, this.plugin.settings.ignoreArabicDiacritics)
: term
).toLowerCase(),
processTerm: (term: string) => removeDiacritics(term).toLowerCase(),
idField: 'path',
fields: [
'basename',
+17 -28
View File
@@ -1,7 +1,8 @@
import type { QueryCombination } from 'minisearch'
import { removeStopwords } from 'stopword'
import { BRACKETS_AND_SPACE, chsRegex, SPACE_OR_PUNCTUATION } from '../globals'
import { logVerbose, splitCamelCase, splitHyphens } from '../tools/utils'
import type LocatorPlugin from '../main'
import { getStopWords, splitCamelCase, splitHyphens } from '../tools/utils'
const markdownLinkExtractor = require('markdown-link-extractor')
@@ -16,30 +17,18 @@ export class Tokenizer {
*/
public tokenizeForIndexing(text: string): string[] {
try {
const words = this.tokenizeWords(text)
let urls: string[] = []
if (this.plugin.settings.tokenizeUrls) {
try {
urls = markdownLinkExtractor(text)
} catch (e) {
logVerbose('Error extracting urls', e)
}
}
let words = this.tokenizeIntoWords(text)
words = removeStopwords(words, getStopWords())
let tokens = this.tokenizeIntoTokens(text, { skipChs: true })
let tokens = this.tokenizeTokens(text, { skipChs: true })
tokens = [...tokens.flatMap(token => [
token,
...splitHyphens(token),
...splitCamelCase(token),
]), ...words]
// Add urls
if (urls.length) {
tokens = [...tokens, ...urls]
}
// Remove duplicates
tokens = [...new Set(tokens)]
tokens = [
...tokens.flatMap(token => [
token,
...splitHyphens(token),
...splitCamelCase(token),
]),
...words,
]
return tokens
} catch (e) {
@@ -59,7 +48,7 @@ export class Tokenizer {
const urls: string[] = markdownLinkExtractor(text)
text = urls.reduce((acc, url) => acc.replace(url, ''), text)
const tokens = [...this.tokenizeTokens(text), ...urls].filter(Boolean)
const tokens = [...this.tokenizeIntoTokens(text), ...urls].filter(Boolean)
return {
combineWith: 'OR',
@@ -67,7 +56,7 @@ export class Tokenizer {
{ combineWith: 'AND', queries: tokens },
{
combineWith: 'AND',
queries: this.tokenizeWords(text).filter(Boolean),
queries: this.tokenizeIntoWords(text).filter(Boolean),
},
{ combineWith: 'AND', queries: tokens.flatMap(splitHyphens) },
{ combineWith: 'AND', queries: tokens.flatMap(splitCamelCase) },
@@ -75,13 +64,13 @@ export class Tokenizer {
}
}
private tokenizeWords(text: string, { skipChs = false } = {}): string[] {
private tokenizeIntoWords(text: string, { skipChs = false } = {}): string[] {
const tokens = text.split(BRACKETS_AND_SPACE)
if (skipChs) return tokens
return this.tokenizeChsWord(tokens)
}
private tokenizeTokens(text: string, { skipChs = false } = {}): string[] {
private tokenizeIntoTokens(text: string, { skipChs = false } = {}): string[] {
const tokens = text.split(SPACE_OR_PUNCTUATION)
if (skipChs) return tokens
return this.tokenizeChsWord(tokens)
+7 -38
View File
@@ -1,26 +1,14 @@
// noinspection CssUnresolvedCustomProperty
import {
App,
Plugin,
PluginSettingTab,
Setting,
} from 'obsidian'
import { writable } from 'svelte/store'
import { K_DISABLE_OMNISEARCH, RecencyCutoff } from '../globals'
import { App, Plugin, PluginSettingTab, Setting } from 'obsidian'
import { RecencyCutoff } from '../globals'
import type LocatorPlugin from '../main'
import { enableVerboseLogging } from '../tools/utils'
import { injectSettingsIndexing } from './settings-indexing'
import { type LocatorSettings, saveSettings } from './utils'
import { injectSettingsBehavior } from './settings-behavior'
import { injectSettingsDanger } from './settings-danger'
import { injectSettingsHttp } from './settings-http'
import { injectSettingsIndexing } from './settings-indexing'
import { injectSettingsUserInterface } from './settings-ui'
import { injectSettingsWeighting } from './settings-weighting'
import { injectSettingsHttp } from './settings-http'
import { injectSettingsDanger } from './settings-danger'
/**
* A store to reactively toggle the `showExcerpt` setting on the fly
*/
export const showExcerpt = writable(false)
import { type LocatorSettings, saveSettings, showExcerpt } from './utils'
export class SettingsTab extends PluginSettingTab {
plugin: LocatorPlugin
@@ -37,15 +25,9 @@ export class SettingsTab extends PluginSettingTab {
display(): void {
const { containerEl } = this
const database = this.plugin.database
containerEl.empty()
if (this.app.loadLocalStorage(K_DISABLE_OMNISEARCH) == '1') {
const span = containerEl.createEl('span')
span.innerHTML = `<strong style="color: var(--text-accent)">⚠️ OMNISEARCH IS DISABLED ⚠️</strong>`
}
// Settings main title
containerEl.createEl('h1', { text: 'Locator' })
@@ -81,7 +63,6 @@ export class SettingsTab extends PluginSettingTab {
.addToggle(toggle =>
toggle.setValue(settings.verboseLogging).onChange(async v => {
settings.verboseLogging = v
enableVerboseLogging(v)
await saveSettings(this.plugin)
})
)
@@ -100,16 +81,12 @@ export function getDefaultSettings(app: App): LocatorSettings {
hideExcluded: false,
recencyBoost: RecencyCutoff.Disabled,
downrankedFoldersFilters: [] as string[],
ignoreDiacritics: true,
ignoreArabicDiacritics: false,
indexedFileTypes: [] as string[],
displayTitle: '',
PDFIndexing: false,
officeIndexing: false,
imagesIndexing: false,
aiImageIndexing: false,
unsupportedFilesIndexing: 'default',
splitCamelCase: false,
openInNewPane: false,
vimLikeNavigationShortcut: app.vault.getConfig('vimMode') as boolean,
@@ -118,10 +95,7 @@ export function getDefaultSettings(app: App): LocatorSettings {
maxEmbeds: 5,
renderLineReturnInExcerpts: true,
showCreateButton: false,
highlight: true,
showPreviousQueryResults: true,
simpleSearch: false,
tokenizeUrls: false,
fuzziness: '1',
weightBasename: 10,
@@ -134,13 +108,11 @@ export function getDefaultSettings(app: App): LocatorSettings {
httpApiEnabled: false,
httpApiPort: '51361',
httpApiNotice: true,
welcomeMessage: '',
verboseLogging: false,
DANGER_httpHost: null,
DANGER_forceSaveCache: false,
}
}
@@ -156,15 +128,12 @@ export let settings: LocatorSettings
// return settings
// }
export async function loadSettings(
plugin: Plugin
): Promise<LocatorSettings> {
export async function loadSettings(plugin: Plugin): Promise<LocatorSettings> {
settings = Object.assign(
{},
getDefaultSettings(plugin.app),
await plugin.loadData()
)
showExcerpt.set(settings.showExcerpt)
enableVerboseLogging(settings.verboseLogging)
return settings
}
-44
View File
@@ -27,17 +27,6 @@ export function injectSettingsBehavior(
})
)
// Show previous query results
new Setting(containerEl)
.setName('Show previous query results')
.setDesc('Re-executes the previous query when opening Locator.')
.addToggle(toggle =>
toggle.setValue(settings.showPreviousQueryResults).onChange(async v => {
settings.showPreviousQueryResults = v
await saveSettings(plugin)
})
)
// Respect excluded files
new Setting(containerEl)
.setName('Respect Obsidian\'s "Excluded Files"')
@@ -70,22 +59,6 @@ export function injectSettingsBehavior(
})
})
// Split CamelCaseWords
new Setting(containerEl)
.setName('Split CamelCaseWords')
.setDesc(
htmlDescription(`Enable this if you want to be able to search for CamelCaseWords as separate words.<br/>
⚠️ <span style="color: var(--text-accent)">Changing this setting will clear the cache.</span><br>
${needsARestart}`)
)
.addToggle(toggle =>
toggle.setValue(settings.splitCamelCase).onChange(async v => {
await database.clearCache()
settings.splitCamelCase = v
await saveSettings(plugin)
})
)
// Simpler search
new Setting(containerEl)
.setName('Simpler search')
@@ -100,23 +73,6 @@ export function injectSettingsBehavior(
})
)
// Extract URLs
// Crashes on iOS
if (!Platform.isIosApp) {
new Setting(containerEl)
.setName('Tokenize URLs')
.setDesc(
`Enable this if you want to be able to search for URLs as separate words.
This setting has a strong impact on indexing performance, and can crash Obsidian under certain conditions.`
)
.addToggle(toggle =>
toggle.setValue(settings.tokenizeUrls).onChange(async v => {
settings.tokenizeUrls = v
await saveSettings(plugin)
})
)
}
// Open in new pane
new Setting(containerEl)
.setName('Open in new pane')
+3 -69
View File
@@ -1,10 +1,7 @@
import { Notice, Setting } from 'obsidian'
import type { LocatorSettings } from './utils'
import { isCacheEnabled } from './utils'
import { saveSettings } from './utils'
import { htmlDescription, isPluginDisabled, needsARestart } from './utils'
import { Setting } from 'obsidian'
import type LocatorPlugin from 'src/main'
import { K_DISABLE_OMNISEARCH } from 'src/globals'
import type { LocatorSettings } from './utils'
import { htmlDescription, isCacheEnabled, needsARestart } from './utils'
export function injectSettingsDanger(
plugin: LocatorPlugin,
@@ -15,69 +12,6 @@ export function injectSettingsDanger(
new Setting(containerEl).setName('Danger Zone').setHeading()
// Ignore diacritics
new Setting(containerEl)
.setName('Ignore diacritics')
.setDesc(
htmlDescription(`Normalize diacritics in search terms. Words like "brûlée" or "žluťoučký" will be indexed as "brulee" and "zlutoucky".<br/>
⚠️ <span style="color: var(--text-accent)">You probably should <strong>NOT</strong> disable this.</span><br>
⚠️ <span style="color: var(--text-accent)">Changing this setting will clear the cache.</span><br>
${needsARestart}`)
)
.addToggle(toggle =>
toggle.setValue(settings.ignoreDiacritics).onChange(async v => {
await database.clearCache()
settings.ignoreDiacritics = v
await saveSettings(plugin)
})
)
new Setting(containerEl)
.setName('Ignore Arabic diacritics (beta)')
.addToggle(toggle =>
toggle.setValue(settings.ignoreArabicDiacritics).onChange(async v => {
await database.clearCache()
settings.ignoreArabicDiacritics = v
await saveSettings(plugin)
})
)
// Disable Locator
const disableDesc = new DocumentFragment()
disableDesc.createSpan({}, span => {
span.innerHTML = `Disable Locator on this device only.<br>
${needsARestart}`
})
new Setting(containerEl)
.setName('Disable on this device')
.setDesc(disableDesc)
.addToggle(toggle =>
toggle.setValue(isPluginDisabled(plugin.app)).onChange(async v => {
if (v) {
plugin.app.saveLocalStorage(K_DISABLE_OMNISEARCH, '1')
new Notice('Locator - Disabled. Please restart Obsidian.')
} else {
plugin.app.saveLocalStorage(K_DISABLE_OMNISEARCH) // No value = unset
new Notice('Locator - Enabled. Please restart Obsidian.')
}
})
)
// Force save cache
new Setting(containerEl)
.setName('Force save the cache')
.setDesc(
htmlDescription(`Locator has a security feature that automatically disables cache writing if it cannot fully perform the operation.<br>
Use this option to force the cache to be saved, even if it causes a crash.<br>
⚠️ <span style="color: var(--text-accent)">Enabling this setting could lead to crash loops</span>`)
)
.addToggle(toggle =>
toggle.setValue(settings.DANGER_forceSaveCache).onChange(async v => {
settings.DANGER_forceSaveCache = v
await saveSettings(plugin)
})
)
// Clear cache data
if (isCacheEnabled()) {
new Setting(containerEl)
-12
View File
@@ -50,17 +50,5 @@ export function injectSettingsHttp(
await saveSettings(plugin)
})
})
new Setting(containerEl)
.setName('Show a notification when the server starts')
.setDesc(
'Will display a notification if the server is enabled, at Obsidian startup.'
)
.addToggle(toggle =>
toggle.setValue(settings.httpApiNotice).onChange(async v => {
settings.httpApiNotice = v
await saveSettings(plugin)
})
)
}
}
+1 -24
View File
@@ -11,7 +11,6 @@ export function injectSettingsIndexing(
containerEl: HTMLElement
) {
const textExtractor = plugin.getTextExtractor()
const aiImageAnalyzer = plugin.getAIImageAnalyzer()
const database = plugin.database
const clearCacheDebounced = debounce(async () => {
@@ -28,11 +27,6 @@ export function injectSettingsIndexing(
? `👍 You have installed <a href="https://github.com/scambier/obsidian-text-extractor">Text Extractor</a>, Locator can use it to index PDFs and images contents.
<br />Text extraction only works on desktop, but the cache can be synchronized with your mobile device.`
: `⚠️ Locator requires <a href="https://github.com/scambier/obsidian-text-extractor">Text Extractor</a> to index PDFs and images.`
}
${
aiImageAnalyzer
? `<br/>👍 You have installed <a href="https://github.com/Swaggeroo/obsidian-ai-image-analyzer">AI Image Analyzer</a>, Locator can use it to index images contents with ai.`
: `<br/>⚠️ Locator requires <a href="https://github.com/Swaggeroo/obsidian-ai-image-analyzer">AI Image Analyzer</a> to index images with ai.`
}`)
)
@@ -87,23 +81,6 @@ export function injectSettingsIndexing(
)
.setDisabled(!textExtractor)
// AI Images Indexing
const aiIndexImagesDesc = new DocumentFragment()
aiIndexImagesDesc.createSpan({}, span => {
span.innerHTML = `Locator will use AI Image Analyzer to index the content of your images with ai.`
})
new Setting(containerEl)
.setName(`Images AI indexing ${aiImageAnalyzer ? '' : '⚠️ Disabled'}`)
.setDesc(aiIndexImagesDesc)
.addToggle(toggle =>
toggle.setValue(settings.aiImageIndexing).onChange(async v => {
await database.clearCache()
settings.aiImageIndexing = v
await saveSettings(plugin)
})
)
.setDisabled(!aiImageAnalyzer)
// Index filenames of unsupported files
new Setting(containerEl)
.setName('Index paths of unsupported files')
@@ -115,7 +92,7 @@ export function injectSettingsIndexing(
)
.addDropdown(dropdown => {
dropdown
.addOptions({ yes: 'Yes', no: 'No', default: 'Obsidian setting' })
.addOptions({ yes: 'Yes', no: 'No', default: 'Obsidian default' })
.setValue(settings.unsupportedFilesIndexing)
.onChange(async v => {
await clearCacheDebounced()
+1 -16
View File
@@ -1,9 +1,7 @@
import { Setting } from 'obsidian'
import type LocatorPlugin from 'src/main'
import { showExcerpt } from '.'
import type { LocatorSettings } from './utils'
import { saveSettings } from './utils'
import { htmlDescription } from './utils'
import { htmlDescription, saveSettings, showExcerpt } from './utils'
export function injectSettingsUserInterface(
plugin: LocatorPlugin,
@@ -82,17 +80,4 @@ export function injectSettingsUserInterface(
await saveSettings(plugin)
})
)
// Highlight results
new Setting(containerEl)
.setName('Highlight matching words in results')
.setDesc(
'Will highlight matching results when enabled. See README for more customization options.'
)
.addToggle(toggle =>
toggle.setValue(settings.highlight).onChange(async v => {
settings.highlight = v
await saveSettings(plugin)
})
)
}
+8 -17
View File
@@ -1,7 +1,13 @@
import { App, Platform, Plugin } from 'obsidian'
import { K_DISABLE_OMNISEARCH, RecencyCutoff } from 'src/globals'
import { Platform, Plugin } from 'obsidian'
import { RecencyCutoff } from 'src/globals'
import { writable } from 'svelte/store'
import { settings } from '.'
/**
* A store to reactively toggle the `showExcerpt` setting on the fly
*/
export const showExcerpt = writable(false)
export function htmlDescription(innerHTML: string): DocumentFragment {
const desc = new DocumentFragment()
desc.createSpan({}, span => {
@@ -20,9 +26,6 @@ export interface WeightingSettings {
weightH3: number
weightUnmarkedTags: number
}
export function isPluginDisabled(app: App): boolean {
return app.loadLocalStorage(K_DISABLE_OMNISEARCH) === '1'
}
export async function saveSettings(plugin: Plugin): Promise<void> {
await plugin.saveData(settings)
@@ -41,9 +44,6 @@ export interface LocatorSettings extends WeightingSettings {
recencyBoost: RecencyCutoff
/** downrank files in the given folders */
downrankedFoldersFilters: string[]
/** Ignore diacritics when indexing files */
ignoreDiacritics: boolean
ignoreArabicDiacritics: boolean
/** Extensions of plain text files to index, in addition to .md */
indexedFileTypes: string[]
@@ -55,8 +55,6 @@ export interface LocatorSettings extends WeightingSettings {
imagesIndexing: boolean
/** Enable Office documents indexing */
officeIndexing: boolean
/** Enable image ai indexing */
aiImageIndexing: boolean
/** Enable indexing of unknown files */
unsupportedFilesIndexing: 'yes' | 'no' | 'default'
@@ -70,23 +68,16 @@ export interface LocatorSettings extends WeightingSettings {
renderLineReturnInExcerpts: boolean
/** Enable a "create note" button in the Vault Search modal */
showCreateButton: boolean
/** Re-execute the last query when opening Locator */
showPreviousQueryResults: boolean
/** Key for the welcome message when Obsidian is updated. A message is only shown once. */
welcomeMessage: string
/** If a query returns 0 result, try again with more relax conditions */
simpleSearch: boolean
tokenizeUrls: boolean
highlight: boolean
splitCamelCase: boolean
openInNewPane: boolean
verboseLogging: boolean
vimLikeNavigationShortcut: boolean
fuzziness: '0' | '1' | '2'
httpApiEnabled: boolean
httpApiPort: string
httpApiNotice: boolean
DANGER_httpHost: string | null
DANGER_forceSaveCache: boolean
}
+10 -5
View File
@@ -48,10 +48,15 @@ export function getServer(plugin: LocatorPlugin) {
},
() => {
console.log(`Locator - Started HTTP server on port ${port}`)
if (plugin.settings.DANGER_httpHost && plugin.settings.DANGER_httpHost !== 'localhost') {
new Notice(`Locator - Started non-localhost HTTP server at ${plugin.settings.DANGER_httpHost}:${port}`, 120_000)
}
else if (plugin.settings.httpApiNotice) {
if (
plugin.settings.DANGER_httpHost &&
plugin.settings.DANGER_httpHost !== 'localhost'
) {
new Notice(
`Locator - Started non-localhost HTTP server at ${plugin.settings.DANGER_httpHost}:${port}`,
120_000
)
} else {
new Notice(`Locator - Started HTTP server on port ${port}`)
}
}
@@ -67,7 +72,7 @@ export function getServer(plugin: LocatorPlugin) {
close() {
server.close()
console.log(`Locator - Terminated HTTP server`)
if (plugin.settings.httpApiEnabled && plugin.settings.httpApiNotice) {
if (plugin.settings.httpApiEnabled) {
new Notice(`Locator - Terminated HTTP server`)
}
},
+2 -2
View File
@@ -87,8 +87,8 @@ export function getApi(plugin: LocatorPlugin) {
return {
async search(q: string): Promise<ResultNoteApi[]> {
const query = new Query(q, {
ignoreDiacritics: plugin.settings.ignoreDiacritics,
ignoreArabicDiacritics: plugin.settings.ignoreArabicDiacritics,
ignoreDiacritics: true,
ignoreArabicDiacritics: true,
})
const raw = await plugin.searchEngine.getSuggestions(query)
return mapResults(plugin, raw)
+14 -183
View File
@@ -1,189 +1,20 @@
import { getIcon, normalizePath } from 'obsidian'
import type LocatorPlugin from '../main'
import {
isFileImage,
isFilePDF,
isFileCanvas,
isFileExcalidraw,
warnVerbose,
} from './utils'
import { escapeHTML } from './text-processing'
import { getIcon } from 'obsidian'
import { isFileCanvas, isFileExcalidraw, isFileImage, isFilePDF } from './utils'
export interface IconPacks {
prefixToIconPack: { [prefix: string]: string }
iconsPath: string
}
export async function loadIconData(plugin: LocatorPlugin): Promise<any> {
const app = plugin.app
// Check if the 'obsidian-icon-folder' plugin is installed and enabled
// Casting 'app' to 'any' here to avoid TypeScript errors since 'plugins' might not be defined on 'App'
const iconFolderPlugin = (app as any).plugins.getPlugin(
'obsidian-icon-folder'
)
if (!iconFolderPlugin) {
return {}
}
const dataJsonPath = `${app.vault.configDir}/plugins/obsidian-icon-folder/data.json`
try {
const dataJsonContent = await app.vault.adapter.read(dataJsonPath)
const rawIconData = JSON.parse(dataJsonContent)
// Normalize keys
const iconData: any = {}
for (const key in rawIconData) {
const normalizedKey = normalizePath(key)
iconData[normalizedKey] = rawIconData[key]
}
return iconData
} catch (e) {
warnVerbose('Failed to read data.json:', e)
return {}
}
}
export async function initializeIconPacks(
plugin: LocatorPlugin
): Promise<IconPacks> {
// Add 'Li' prefix for Lucide icons
const prefixToIconPack: { [prefix: string]: string } = { Li: 'lucide-icons' }
let iconsPath = 'icons'
const app = plugin.app
// Access the obsidian-icon-folder plugin
const iconFolderPlugin = (app as any).plugins.getPlugin(
'obsidian-icon-folder'
)
if (iconFolderPlugin) {
// Get the icons path from the plugin's settings
const iconFolderSettings = iconFolderPlugin.settings
iconsPath = iconFolderSettings?.iconPacksPath || 'icons'
const iconsDir = `${app.vault.configDir}/${iconsPath}`
try {
const iconPackDirs = await app.vault.adapter.list(iconsDir)
if (iconPackDirs.folders && iconPackDirs.folders.length > 0) {
for (const folderPath of iconPackDirs.folders) {
const pathParts = folderPath.split('/')
const iconPackName = pathParts[pathParts.length - 1]
const prefix = createIconPackPrefix(iconPackName)
prefixToIconPack[prefix] = iconPackName
}
}
} catch (e) {
warnVerbose('Failed to list icon packs:', e)
}
}
return { prefixToIconPack, iconsPath }
}
function createIconPackPrefix(iconPackName: string): string {
if (iconPackName.includes('-')) {
const splitted = iconPackName.split('-')
let result = splitted[0].charAt(0).toUpperCase()
for (let i = 1; i < splitted.length; i++) {
result += splitted[i].charAt(0).toLowerCase()
}
return result
}
return (
iconPackName.charAt(0).toUpperCase() + iconPackName.charAt(1).toLowerCase()
)
}
export function getIconNameForPath(path: string, iconData: any): string | null {
const normalizedPath = normalizePath(path)
const iconEntry = iconData[normalizedPath]
if (iconEntry) {
if (typeof iconEntry === 'string') {
return iconEntry
} else if (typeof iconEntry === 'object' && iconEntry.iconName) {
return iconEntry.iconName
}
}
return null
}
export function parseIconName(iconName: string): {
prefix: string
name: string
} {
const prefixMatch = iconName.match(/^[A-Z][a-z]*/)
if (prefixMatch) {
const prefix = prefixMatch[0]
const name = iconName.substring(prefix.length)
return { prefix, name }
} else {
// No prefix, treat the entire iconName as the name
return { prefix: '', name: iconName }
}
}
export async function loadIconSVG(
iconName: string,
plugin: LocatorPlugin,
iconsPath: string,
prefixToIconPack: { [prefix: string]: string }
): Promise<string | null> {
const parsed = parseIconName(iconName)
const { prefix, name } = parsed
if (!prefix) {
// No prefix, assume it's an emoji or text
return `<span class="locator-result__icon--emoji">${escapeHTML(
name
)}</span>`
}
const iconPackName = prefixToIconPack[prefix]
if (!iconPackName) {
warnVerbose(`No icon pack found for prefix: ${prefix}`)
return null
}
if (iconPackName === 'lucide-icons') {
// Convert CamelCase to dash-case for Lucide icons
const dashedName = name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
const iconEl = getIcon(dashedName)
if (iconEl) {
return iconEl.outerHTML
} else {
warnVerbose(`Lucide icon not found: ${dashedName}`)
return null
}
} else {
if (!iconsPath) {
warnVerbose('Icons path is not set. Cannot load icon SVG.')
return null
}
const iconPath = `${plugin.app.vault.configDir}/${iconsPath}/${iconPackName}/${name}.svg`
try {
const svgContent = await plugin.app.vault.adapter.read(iconPath)
return svgContent
} catch (e) {
warnVerbose(`Failed to load icon SVG for ${iconName} at ${iconPath}:`, e)
return null
}
}
}
export function getDefaultIconSVG(
notePath: string,
plugin: LocatorPlugin
): string {
export function getDefaultIconSVG(notePath: string): string {
// Return SVG content for default icons based on file type
let iconName = 'file'
if (isFileImage(notePath)) {
iconName = 'image'
} else if (isFilePDF(notePath)) {
iconName = 'file-text'
} else if (isFileCanvas(notePath) || isFileExcalidraw(notePath)) {
iconName = 'layout-dashboard'
if (notePath === 'folder') {
iconName = 'folder'
} else {
if (isFileImage(notePath)) {
iconName = 'image'
} else if (isFilePDF(notePath)) {
iconName = 'file-text'
} else if (isFileCanvas(notePath) || isFileExcalidraw(notePath)) {
iconName = 'layout-dashboard'
}
}
const iconEl = getIcon(iconName)
return iconEl ? iconEl.outerHTML : ''
+2 -6
View File
@@ -15,9 +15,7 @@ export class TextProcessor {
* @returns The html string with the matches highlighted
*/
public highlightText(text: string, matches: SearchMatch[]): string {
const highlightClass = `suggestion-highlight locator-highlight ${
this.plugin.settings.highlight ? 'locator-default-highlight' : ''
}`
const highlightClass = 'suggestion-highlight locator-highlight locator-default-highlight'
if (!matches.length) {
return text
@@ -68,9 +66,7 @@ export class TextProcessor {
const reg = this.stringsToRegex(words)
const originalText = text
// text = text.toLowerCase().replace(new RegExp(SEPARATORS, 'gu'), ' ')
if (this.plugin.settings.ignoreDiacritics) {
text = removeDiacritics(text, this.plugin.settings.ignoreArabicDiacritics)
}
text = removeDiacritics(text)
const startTime = new Date().getTime()
let match: RegExpExecArray | null = null
let matches: SearchMatch[] = []
+19 -10
View File
@@ -1,3 +1,4 @@
import { type BinaryLike, createHash } from 'crypto'
import {
type CachedMetadata,
getAllTags,
@@ -5,9 +6,10 @@ import {
parseFrontMatterAliases,
Platform,
} from 'obsidian'
import { isSearchMatch, type SearchMatch } from '../globals'
import { type BinaryLike, createHash } from 'crypto'
import { md5 } from 'pure-md5'
import { eng, fra } from 'stopword'
import { isSearchMatch, type SearchMatch } from '../globals'
import { settings } from 'src/settings'
export function pathWithoutFilename(path: string): string {
const split = path.split('/')
@@ -115,16 +117,17 @@ const diacriticsRegex = new RegExp(`(?!${regexpExclude})\\p{Diacritic}`, 'gu')
/**
* https://stackoverflow.com/a/37511463
*/
export function removeDiacritics(str: string, arabic = false): string {
export function removeDiacritics(str: string, arabic = true): string {
if (str === null || str === undefined) {
return ''
}
// TODO: add a global setting to toggle this, this impacts performances
if (arabic) {
// Arabic diacritics
// https://stackoverflow.com/a/40959537
str = str
.replace(/([^\u0621-\u063A\u0641-\u064A\u0660-\u0669a-zA-Z 0-9])/g, '')
// .replace(/([^\u0621-\u063A\u0641-\u064A\u0660-\u0669a-zA-Z 0-9])/g, '')
.replace(/(آ|إ|أ)/g, 'ا')
.replace(/(ة)/g, 'ه')
.replace(/(ئ|ؤ)/g, 'ء')
@@ -143,6 +146,7 @@ export function removeDiacritics(str: string, arabic = false): string {
str = str.normalize('NFD').replace(diacriticsRegex, '').normalize('NFC')
str = str.replaceAll('[__locator__backtick__]', '`')
str = str.replaceAll('[__locator__caret__]', '^')
return str
}
@@ -249,13 +253,8 @@ export function warnVerbose(...args: any[]): void {
printVerbose(console.warn, ...args)
}
let verboseLoggingEnabled = false
export function enableVerboseLogging(enable: boolean): void {
verboseLoggingEnabled = enable
}
function printVerbose(fn: (...args: any[]) => any, ...args: any[]): void {
if (verboseLoggingEnabled) {
if (settings.verboseLogging) {
fn(...args)
}
}
@@ -279,3 +278,13 @@ export const countError = (() => {
}
}
})()
let stopWords: string[] = []
export function getStopWords(): string[] {
if (!stopWords.length) {
stopWords = [...eng, ...fra]
// Remove duplicates
stopWords = [...new Set(stopWords)]
}
return stopWords
}