generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
58 lines (55 loc) · 1.6 KB
/
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { Plugin, MarkdownView, Menu, Editor } from 'obsidian';
const addRubyTag = (editor: Editor, selected: string) => {
const cursor = editor.getCursor();
const lineText = editor.getLine(cursor.line);
const rubyTagMatch = lineText.match(/<ruby\>(.*)<\/ruby>/);
let alreadyInRuby = (
rubyTagMatch &&
rubyTagMatch.index &&
rubyTagMatch.index < cursor.ch &&
rubyTagMatch.index + rubyTagMatch[0].length > cursor.ch
);
let head = `${selected}<rt>`;
let tail = "</rt>";
if (!alreadyInRuby) {
head = `<ruby>${head}`;
tail = `${tail}</ruby>`;
}
editor.replaceSelection(head + tail, "end");
const { line, ch } = editor.getCursor();
editor.setCursor({ line, ch: ch - tail.length });
};
export default class AliasPlugin extends Plugin {
async onload() {
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor: Editor, view: MarkdownView) => {
const selectedText = editor.getSelection();
if (!selectedText || selectedText.trim() === "") {
return;
}
menu.addItem((item) => {
item.setTitle("Add <ruby> tag")
.onClick(() => addRubyTag(editor, selectedText));
});
})
);
this.addCommand({
id: 'add-ruby',
name: 'Add <ruby> tag for selected text',
checkCallback: (checking: boolean) => {
let view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
return false;
}
const editor = view.editor;
if (!checking) {
const selected = editor.getSelection();
addRubyTag(editor, selected);
}
return true;
}
});
}
onunload() {
}
}