22 Commits
0.8.0 ... 0.9.1

Author SHA1 Message Date
daniel
b10656c2c3 chore: fix code formatting 2024-12-23 11:05:34 +01:00
daniel
cc078fae6a bump version 2024-12-23 11:04:24 +01:00
daniel
b6cdf6cb47 chore: update preview gif 2024-12-23 11:04:24 +01:00
daniel
5bfb3116bc feat: render suggestions similar to dataview render 2024-12-23 10:02:02 +01:00
daniel
dac07242cd chore: remove unused import 2024-12-23 09:09:54 +01:00
daniel
c3f44af074 bump version 2024-12-23 01:16:06 +01:00
daniel
57be38b005 chore: add prettier write script 2024-12-23 01:12:41 +01:00
daniel
e744b48536 add highlighting and suggestion note 2024-12-23 01:11:44 +01:00
daniel
b79d363c9f fix: inserted value should not use display value if display value is undefined 2024-12-23 00:46:19 +01:00
Daniel Bauer
2d9194265a fix: typo 2024-12-21 12:37:34 +01:00
Daniel Bauer
27f2e64884 Update README.md 2024-12-20 22:36:28 +01:00
Daniel Bauer
779bd0bd68 Merge pull request #2 from dnlbauer/dnlbauer-patch-1
Feat: Update Readme
2024-12-19 13:45:12 +01:00
Daniel Bauer
910d343948 Feat: Update Readme 2024-12-19 13:36:27 +01:00
Daniel Bauer
5802a6cd5d chore: remove debug statements 2024-12-18 11:11:17 +01:00
Daniel Bauer
d85c07126f bump version 2024-12-18 11:07:11 +01:00
Daniel Bauer
020054857b feat: remove lookbehinds, make compatible with iOS 2024-12-18 11:07:06 +01:00
Daniel Bauer
f58f736df4 feat: replace innerHTML call with createEL (obsidian plugin guidelines) 2024-12-18 10:34:00 +01:00
Daniel Bauer
1644899116 bump version 2024-12-17 19:46:30 +01:00
Daniel Bauer
1debbb51f2 remove unused styles.css 2024-12-17 19:46:30 +01:00
Daniel Bauer
dd86b55bed chore: remove debug statements 2024-12-17 19:43:32 +01:00
Daniel Bauer
8240045641 fix: index not building on plugin enabling 2024-12-17 19:36:20 +01:00
Daniel Bauer
2dae1175f8 fix: indexing not working if there are non-markdown files 2024-12-17 18:47:41 +01:00
10 changed files with 138 additions and 64 deletions

View File

@@ -3,9 +3,23 @@
This is a plugin for Obsidian (https://obsidian.md).
Obsidian Dataview Autocomplete enhances the functionality of the popular [Dataview plugin](https://github.com/blacksmithgu/obsidian-dataview)
by providing autocomplete suggestions for metadata fields in the editor.
by providing autocomplete suggestions for metadata fields in the editor. This makes it easy to reuse existing fields and reduces typing errors.
![Demo](./assets/demo.gif)
<img src="./assets/demo.gif" alt="Demo" width="400" >
## Features
- Provides autocomplete suggestions for inline metadata fields used by Dataview.
- Customizable ignored fields and files for suggestions.
## Installation
While plugin is [waiting](https://github.com/obsidianmd/obsidian-releases/pull/4913) to be reviewed and added to the community plugin list, you can install it manually following the steps below:
1. Download the latest release files (manifest.json, styles.css, main.js) from the Releases page.
2. Create a folder named "dataview-autocompletion" in the Obsidian plugins folder (.obsidian/plugins).
3. Copy the files from step 1 into the new folder.
4. Enable the plugin in the Obsidian settings under the "Community plugins" section. You might have to restart Obsidian to rsee the plugin.
## License

Binary file not shown.

Before

Width:  |  Height:  |  Size: 853 KiB

After

Width:  |  Height:  |  Size: 1.5 MiB

View File

@@ -1,7 +1,7 @@
{
"id": "dataview-autocompletion",
"name": "Dataview Autocompletion",
"version": "0.8.0",
"version": "0.9.1",
"minAppVersion": "0.15.0",
"description": "Adds autocompletion to Dataview metadata fields",
"author": "Daniel Bauer",

View File

@@ -1,13 +1,15 @@
{
"name": "obsidian-dataview-autocompletion",
"version": "0.8",
"version": "0.9.1",
"description": "This is a plugin for Obsidian that provides autocompletion for Dataview metadata fields",
"main": "main.js",
"scripts": {
"dev": "npx rollup --config rollup.config.js -w",
"build": "npx rollup --config rollup.config.js --environment BUILD:production",
"check-format": "npx prettier --check src",
"fix-format": "npx prettier --write src",
"test": "npx jest",
"bdd": "npx jest -i --watch --no-cache",
"version": "node ersion-bump.mjs && git add manifest.json versions.json"
},
"keywords": [

View File

@@ -5,6 +5,9 @@ import {
EditorSuggest,
EditorSuggestContext,
EditorSuggestTriggerInfo,
htmlToMarkdown,
MarkdownRenderer,
MarkdownView,
TFile,
} from "obsidian";
import { getTriggerText } from "./trigger";
@@ -67,21 +70,57 @@ export class DataviewSuggester extends EditorSuggest<String> {
return [];
}
renderMarkdownSuggestion(value: string, el: HTMLElement): void {
// render markdown preview of inline dataview metadata field
let suggestionText = this.context!.editor.getLine(this.context!.start.line).slice(
this.context!.start.ch - 1,
this.context!.start.ch,
)!;
suggestionText += value.replace(/<mark>(.*?)<\/mark>/g, "$1");
suggestionText += suggestionText.startsWith("(") ? ")" : "]";
MarkdownRenderer.render(
this.app,
htmlToMarkdown(suggestionText),
el,
this.context!.file.path,
this.app.workspace.getActiveViewOfType(MarkdownView)!,
);
}
renderSourceSuggestion(value: string, el: HTMLElement): void {
// render source text with highlights
// replaces <mark>...</mark> with <span>...</span>
const parts = value.split(/(<mark>.*?<\/mark>)/g);
parts.forEach((textPart) => {
if (textPart.startsWith("<mark>") && textPart.endsWith("</mark>")) {
const text = textPart.slice(6, -7); // Remove <mark> and </mark>
el.createEl("span", { text, cls: "dataview-suggestion-highlight" });
} else {
el.appendText(textPart);
}
});
}
renderSuggestion(value: string, el: HTMLElement): void {
// replace marks with bold
const formattedHtml = value.replace(/<mark>(.*?)<\/mark>/g, '<span style="font-weight: bold;">$1</span>');
el.innerHTML = formattedHtml;
const container = el.createDiv("dataview-suggestion-content");
const titleDiv = container.createDiv("dataview-suggestion-title");
const noteDiv = container.createDiv("dataview-suggestion-note");
this.renderMarkdownSuggestion(value, titleDiv);
this.renderSourceSuggestion(value, noteDiv);
}
selectSuggestion(value: string, evt: MouseEvent | KeyboardEvent): void {
const { editor, start, end } = this.context!;
// remove marks from selection
value = value.replace(/<mark>(.*?)<\/mark>/g, "$1");
const { editor, start, end } = this.context!;
editor.replaceRange(value, start, end);
const newCursorPos = {
line: end.line + 1,
ch: 0,
line: end.line,
ch: start.ch + value.length + 1,
};
editor.setCursor(newCursorPos);
}
@@ -112,14 +151,16 @@ export class DataviewSuggester extends EditorSuggest<String> {
// If the value is a string, number or boolean, we can simply convert it to a string
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
stringValue = value.toString();
} else if (dataviewAPI.value.typeOf(value) === "link" && value.type === "file" && value.display !== undefined) {
// value.toString always adds a display value to wiki-style links.
// parse wiki-style links without display value manually here to prevent this from happening for [[filename]]
stringValue = `[[${value.path.split("/").pop().replace(".md", "")}]]`;
} else if (dataviewAPI.value.typeOf(value) === "link" && value.type === "file") {
// parse wiki-style links
if (value.display !== undefined) {
stringValue = `[[${value.path.split("/").pop().replace(".md", "")}|${value.display}]]`;
} else {
stringValue = `[[${value.path.split("/").pop().replace(".md", "")}]]`;
}
} else {
stringValue = dataviewAPI.value.toString(value);
}
return `${key}:: ${stringValue}`;
}
@@ -159,6 +200,8 @@ export class DataviewSuggester extends EditorSuggest<String> {
}
const page = dataviewApi.page(file.path);
if (page === undefined) continue; // not a markdown file
const fields = Object.keys(page)
.filter((k) => k !== "file")
.map((k) => [k, page[k]]);
@@ -218,6 +261,8 @@ export class DataviewSuggester extends EditorSuggest<String> {
const updateCompositeValues = [];
const page = getAPI(this.app).page(file.path);
if (page === undefined) return; // not a markdown file
const fields = Object.keys(page)
.filter((k) => k !== "file")
.map((k) => [k, page[k]]);
@@ -297,13 +342,12 @@ export class DataviewSuggester extends EditorSuggest<String> {
for (const value of this.suggestionsRefs.get(file.path)!) {
this.suggestionsRefCount.set(value, this.suggestionsRefCount.get(value)! - 1);
if (this.suggestionsRefCount.get(value) === 0) {
console.debug("deleting value from suggestion index", value);
this.suggestionsList.splice(this.suggestionsList.indexOf(value), 1);
}
}
this.suggestionsRefs.delete(file.path);
} else {
console.warn("Unknown update type:", type, file, oldPath);
console.debug("Unknown update type:", type, file, oldPath);
}
}
}

View File

@@ -1,6 +1,6 @@
import { App, Plugin, PluginSettingTab, Setting, TFile } from "obsidian";
import { DataviewSuggester } from "./DataviewSuggester";
import { getAPI } from "obsidian-dataview";
import { getAPI, isPluginEnabled } from "obsidian-dataview";
import { SettingsTab } from "./SettingsTab";
interface DataviewAutocompleteSettings {
@@ -15,18 +15,19 @@ const DEFAULT_SETTINGS: DataviewAutocompleteSettings = {
export default class DataviewAutocompletePlugin extends Plugin {
settings: DataviewAutocompleteSettings;
suggester: DataviewSuggester | undefined;
suggester: DataviewSuggester;
async onload() {
await this.loadSettings();
this.addSettingTab(new SettingsTab(this.app, this));
this.suggester = new DataviewSuggester(this, 10, true, true);
this.registerEditorSuggest(this.suggester);
this.registerEvent(
// @ts-ignore
this.app.metadataCache.on("dataview:index-ready", () => {
if (this.suggester !== undefined) {
this.suggester.onDataviewIndexReady();
}
this.suggester.onDataviewIndexReady();
}),
);
@@ -35,24 +36,14 @@ export default class DataviewAutocompletePlugin extends Plugin {
// @ts-ignore
"dataview:metadata-change",
(type: string, file: TFile, oldPath?: string) => {
if (this.suggester !== undefined) {
this.suggester.onDataviewMetadataChange(type, file, oldPath);
}
this.suggester.onDataviewMetadataChange(type, file, oldPath);
},
),
);
this.app.workspace.onLayoutReady(() => {
// @ts-ignore
if (!Object.keys(this.app.plugins.plugins).includes("dataview")) {
console.warn("Dataview plugin not installed. Dataview Autocompletion plugin will not work.");
} else {
// register suggester, requires dataview to be loaded first.
console.log("Registering dataview autocompletion suggester");
this.suggester = new DataviewSuggester(this, 10, true, true);
this.registerEditorSuggest(this.suggester);
}
});
if (isPluginEnabled(this.app) && getAPI(this.app)?.index.initialized) {
this.suggester.onDataviewIndexReady();
}
}
onunload() {}

View File

@@ -3,29 +3,28 @@
* and captures the enclosed text
* If the brackets start a markdown link, they are ignored.
* Wiki links don't need to be ignored since Obsidian overwrites suggestions for them.
* We are not allowd to use lookbehinds, because iOS does not support them in older versions.
*/
const filledRegex = new RegExp(
"(" +
[
// pattern for parantheses
// pos. lookbehind for opening parantheses; no closing square bracket before to exlude markdown links
/(?<=^\(|[^\]]\()/,
/.+?/,
// pos. lookahead for closing paranthesis; not followed by another one for nested ((test))
/(?=\)$|\)[^\)])/,
[
// pattern for parantheses
// look for opening parantheses; no closing or opening square bracket before to exlude markdown links, etc.
/(?:^\(|[^\[\]]\()/,
/(.+?)/,
// pos. lookahead for closing paranthesis; not followed by another one for nested ((test))
/(?=\)$|\)[^\)])/,
/|/,
/|/,
// pattern for square brackets
// pos. lookbehind for opening square bracket
/(?<=\[)/,
/.+?/,
// pos. lookahead for closing bracket; not followed by another one ([[test]]) or an opening paranthese (markdown link!)
/(?=\]$|\][^\]\(])/,
]
.map((s) => s.source)
.join("") +
")",
// pattern for square brackets
// look for opening square brackets
/(?:\[)/,
/(.+?)/,
// pos. lookahead for closing bracket; not followed by another one ([[test]]) or an opening paranthese (markdown link!)
/(?=\]$|\][^\]\(])/,
]
.map((s) => s.source)
.join(""),
"g",
);
@@ -57,12 +56,13 @@ function getTriggerTextFromRegex(line: string, cursorPos: number, regex: RegExp)
continue;
}
const matchStart = match!.index;
const matchEnd = matchStart + match[1].length;
const matchText = match[1] || match[2];
const matchStart = match!.index + match[0].indexOf(matchText);
const matchEnd = matchStart + matchText.length;
const cursorInMatch = cursorPos >= matchStart && cursorPos <= matchEnd;
if (cursorInMatch) {
return [match[1], matchStart, matchEnd];
return [matchText, matchStart, matchEnd];
}
}
return null;

View File

@@ -1,8 +1,29 @@
/*
div.dataview-suggestion-content {
display: flex;
flex-direction: column;
overflow: hidden;
text-overflow: ellipsis;
margin-inline-end: auto;
}
This CSS file will be included with your plugin, and
available in the app when your plugin is enabled.
div.dataview-suggestion-title {
overflow-wrap: break-word;
}
If your plugin does not need CSS, delete this file.
div.dataview-suggestion-title p {
margin-block: 0px;
}
div.dataview-suggestion-note{
font-size: 0.8em;
color: var(--text-muted);
width: 100%;
flex-basis: 100%;
overflow-wrap: break-word;
padding-left: 8px;
}
span.dataview-suggestion-highlight {
font-weight: bold;
}
*/

View File

@@ -1,5 +1,6 @@
[
"sample-plugin",
"dataview",
"obsidian-dataview-autocompletion"
"obsidian-dataview-autocompletion",
"dataview-autocompletion"
]

View File

@@ -0,0 +1 @@
{"test": "this is a test file"}