generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.ts
32 lines (24 loc) · 1004 Bytes
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { Editor, MarkdownView, Plugin } from "obsidian";
export default class BetterLinkInserterPlugin extends Plugin {
async onload() {
this.addCommand({
id: "use-selected-word-as-alias",
name: "Insert an internal link (using selected word as alias if possible)",
editorCallback: this.insertInternalLinkWithAlias,
});
}
onunload() {}
private insertInternalLinkWithAlias = (editor: Editor, view: MarkdownView) => {
const selectedWord = editor.getSelection();
const hasSelectedWord = selectedWord !== "";
const linkText = hasSelectedWord ? `|${selectedWord}` : "";
const cursorOffset = hasSelectedWord ? 3 + selectedWord.length : 2;
this.replaceSelectionAndMoveCursor(editor, `[[${linkText}]]`, cursorOffset);
};
private replaceSelectionAndMoveCursor = (editor: Editor, text: string, cursorOffset: number) => {
editor.replaceSelection(text);
const cursorPosition = editor.getCursor();
cursorPosition.ch -= cursorOffset;
editor.setCursor(cursorPosition);
};
}