generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
89 lines (74 loc) · 2.03 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { App, Editor, Plugin, PluginSettingTab, Setting } from "obsidian";
interface PluginSettings {
respectHeadings: boolean;
}
const DEFAULT_SETTINGS: PluginSettings = {
respectHeadings: true,
};
export default class InstantAboveDividerPlugin extends Plugin {
settings: PluginSettings;
async onload() {
await this.loadSettings();
this.addCommand({
id: "add-section",
name: "Add Section",
editorCallback: (editor: Editor) => {
if (!this.settings.respectHeadings) {
editor.setCursor(0, 0);
const newContent = "\n\n---\n\n";
editor.replaceRange(newContent, { line: 0, ch: 0 });
return;
}
const cursorPos = editor.getCursor();
const content = editor.getValue();
const lines = content.split("\n");
let insertLine = cursorPos.line;
// 查找光标之前的最近标题
for (let i = cursorPos.line - 1; i >= 0; i--) {
if (lines[i].match(/^#{1,6}\s/)) {
insertLine = i + 1;
break;
}
}
const newContent = "\n\n\n---\n";
editor.replaceRange(newContent, { line: insertLine, ch: 0 });
editor.setCursor(insertLine + 1, 0);
},
});
this.addSettingTab(new InstantAboveDividerSettingTab(this.app, this));
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class InstantAboveDividerSettingTab extends PluginSettingTab {
plugin: InstantAboveDividerPlugin;
constructor(app: App, plugin: InstantAboveDividerPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName("Respect Headings")
.setDesc(
"When enabled, new sections will be inserted above the nearest heading"
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.respectHeadings)
.onChange(async (value) => {
this.plugin.settings.respectHeadings = value;
await this.plugin.saveSettings();
})
);
}
}