-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.ts
194 lines (163 loc) · 5.25 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { App, FuzzySuggestModal, MarkdownView, Plugin, PluginSettingTab, Setting } from 'obsidian';
import { Command, SuggestModal } from "obsidian";
interface KeySequenceShortcutSettings {
kssrc_file_path: string
}
const DEFAULT_SETTINGS: Partial<KeySequenceShortcutSettings> = {
kssrc_file_path: "kssrc.md"
};
export class KeySequenceShortcutSettingTab extends PluginSettingTab {
plugin: KeySequenceShortcutPlugin;
constructor(app: App, plugin: KeySequenceShortcutPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName("Config File")
.addText((text) =>
text
.setPlaceholder("")
.setValue(this.plugin.settings.kssrc_file_path)
.onChange(async (value) => {
this.plugin.settings.kssrc_file_path= value;
await this.plugin.saveSettings();
})
);
}
}
interface KeyItem {
key_sequence: string;
command: string;
description: string,
}
let g_all_key_items: KeyItem[] = [];
export class KeySequenceModal extends SuggestModal<KeyItem> {
// Returns all available suggestions.
getSuggestions(query: string): KeyItem[] {
const result = g_all_key_items.find((key_item) => {
return key_item.key_sequence == query;
})
if (result != null) {
this.close();
this.delay(100).then(data => {this.execute(result);} )
}
return g_all_key_items.filter((key_item) =>
key_item.key_sequence.startsWith(query)
);
}
// Renders each suggestion item.
renderSuggestion(key_item: KeyItem, el: HTMLElement) {
el.createEl("div", { text: key_item.key_sequence + ": " + (key_item.description == "" ? key_item.command : key_item.description) });
}
// Perform action on the selected suggestion.
onChooseSuggestion(key_item: KeyItem, evt: MouseEvent | KeyboardEvent) {
this.execute(key_item);
}
execute(key_item: KeyItem) {
console.log(`Execute ${key_item.key_sequence}: ${key_item.command}`);
(this.app as any).commands.executeCommandById(key_item.command);
}
async delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
export class InsertCommandIdModel extends FuzzySuggestModal<Command> {
getItems(): Command[] {
return Object.values((this.app as any).commands.commands);
}
getItemText(item: Command): string {
return item.name + " -> " + item.id;
}
onChooseItem(item: Command, evt: MouseEvent | KeyboardEvent): void {
console.log(this.getItemText(item));
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
const editor = view.editor;
const pos = editor.getCursor();
editor.replaceRange(`${item.id}\t${item.name}`, pos);
pos.ch += item.id.length;
editor.setCursor(pos);
}
}
}
export default class KeySequenceShortcutPlugin extends Plugin {
settings: KeySequenceShortcutSettings;
settingTab: KeySequenceShortcutSettingTab;
readKssInit(kss_config: string) {
g_all_key_items = [];
kss_config.split("\n").forEach(
(line: string, index: number) => {
line = line.trim();
if (line.length > 0 && line[0] != '"') {
const split = line.split("\t");
if ((split.length != 2) && (split.length != 3) ) {
console.log(`Skip line ${index} "${line}": the format should be "key-sequence<TAB>command-id<TAB>description", the last field "description" is optional.`)
return
}
// FIXME: We can't check when loading the plugin, at this time, the commands list is not complete
// if(! (split[1] in (this.app as any).commands.commands))
// {
// console.log(`Skip line ${index} "${line}": ${split[1]} is not a valid command id.`);
// return
// }
const key_item: KeyItem = { key_sequence: split[0], command: split[1], description: split.length == 3 ? split[2] : ""}
g_all_key_items.push(key_item);
}
}
)
}
async onload() {
await this.loadSettings();
this.load_kssrc_file();
this.addCommand({
id: 'open-key-sequence-palette',
name: 'Open Key Sequence Palette (Menu)',
icon: 'any-key',
hotkeys: [{ modifiers: ['Ctrl'], key: 'm' }],
callback: () => {
new KeySequenceModal(this.app).open();
}
});
this.addCommand({
id: 'insert-command-id',
name: 'Insert Command Id and Name',
hotkeys: [{ modifiers: ['Ctrl', 'Shift'], key: '8' }],
icon: "duplicate-glyph",
callback: () => {
new InsertCommandIdModel(this.app).open();
}
});
this.addCommand({
id: 'reload-kssrc',
name: 'Reload Key Sequence Shortcut Config File',
icon: "play-audio-glyph",
callback: async () => {
await this.load_kssrc_file();
}
});
this.settingTab = new KeySequenceShortcutSettingTab(this.app, this);
this.addSettingTab(this.settingTab);
console.log("KeySequenceShortcutPlugin load successfully.")
}
private async load_kssrc_file() {
try {
const lines = await this.app.vault.adapter.read(this.settings.kssrc_file_path);
this.readKssInit(lines);
} catch (error)
{
console.log('Error loading kssrc file', this.settings.kssrc_file_path, 'from the vault root', error);
}
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
this.load_kssrc_file();
}
onunload() {
}
}