generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.ts
655 lines (589 loc) · 19.4 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import {
App,
Notice,
Plugin,
Modal,
PluginSettingTab,
Setting,
MarkdownView,
ButtonComponent,
ExtraButtonComponent,
ToggleComponent,
} from 'obsidian';
const {spawn, Buffer, ChildProcess} = require('child_process');
interface LegacyShortcutEntry {
regex: string;
command?: string;
replacement?: string;
}
interface LegacyTextExpanderPluginSettings {
shortcuts: Array<LegacyShortcutEntry>;
shell: string;
}
interface SnippetEntry {
trigger: string;
replacement: string;
}
interface FormatEntry {
pattern: string;
cut_start: number;
cut_end: number;
}
interface TextExpanderPluginSettings {
snippets: Array<SnippetEntry>;
formats: Array<FormatEntry>;
handler_command: string;
is_custom_handler_enabled: boolean;
is_migration_manager_enabled: boolean;
legacy_settings: string | null;
shell?: string;
shortcuts?: Array<LegacyShortcutEntry>;
}
interface Context {
vault_path: string;
file_name: string;
file_path: string;
scripts_path: string;
}
const DEFAULT_SNIPPETS = [
{
trigger: "",
replacement: ""
}
];
const DEFAULT_FORMATS: Array<FormatEntry> = [
{
pattern: '{{(?:(?!{{|}}).)*?}}',
cut_start: 2,
cut_end: 2
},
{
pattern: ':[^\\s]*',
cut_start: 1,
cut_end: 0
}
]
const DEFAULT_SETTINGS: TextExpanderPluginSettings = {
snippets: DEFAULT_SNIPPETS,
formats: DEFAULT_FORMATS,
handler_command: 'python3 <scripts_path>/main.py',
is_custom_handler_enabled: false,
is_migration_manager_enabled: false,
legacy_settings: null,
};
export default class TextExpanderPlugin extends Plugin {
settings: TextExpanderPluginSettings;
private codemirrorEditor: CodeMirror.Editor;
private snippetLine: number;
private snippetStart: number;
private snippetEnd: number;
private waiting: Boolean;
private child: typeof ChildProcess;
async onload() {
await this.loadSettings();
this.addSettingTab(new TextExpanderSettingTab(this.app, this));
this.registerCodeMirror((codemirrorEditor: CodeMirror.Editor) => {
codemirrorEditor.on('keydown', this.handleKeyDown);
});
this.spawnHandler();
}
onunload() {
console.log("[Text Expander Plugin]", 'unloading');
this.killHandler();
}
async loadSettings() {
this.settings = Object.assign({...DEFAULT_SETTINGS }, await this.loadData());
this.loadLegacy()
}
async loadLegacy() {
if (this.settings.legacy_settings != null) {
return;
}
let legacy_settings: LegacyTextExpanderPluginSettings = {shortcuts: [], shell: ""};
if (this.settings.shortcuts) {
legacy_settings.shortcuts = this.settings.shortcuts;
}
if (this.settings.shell) {
legacy_settings.shell = this.settings.shell;
}
this.settings.legacy_settings = JSON.stringify(legacy_settings, null, '\t');
delete this.settings.shortcuts;
delete this.settings.shell;
this.saveSettings()
}
// async migrateSettings() {
// if (this.settings.shortcuts) {
// for (let item of this.settings.shortcuts) {
// let newEntry: SnippetEntry = {trigger: "", replacement: ""};
// if (item.regex) {
// newEntry.trigger = item.regex;
// }
// if (item.replacement) {
// newEntry.replacement = item.replacement;
// }
// this.settings.snippets.push(newEntry);
// }
// delete this.settings.shortcuts;
// }
// }
async saveSettings() {
await this.saveData(this.settings);
}
spawnHandler() {
if (!this.settings.is_custom_handler_enabled) {
return;
}
let handler_command = this.replaceContext(this.settings.handler_command);
let argv = handler_command.split(RegExp('\\s+'));
console.log("[Text Expander Plugin]", "spawning handler:", argv)
this.child = spawn(argv[0], argv.slice(1));
this.child.stdin.setEncoding('utf-8');
this.child.stdout.on('data', this.handleSubprocessStdout);
this.child.stderr.on('data', this.handleSubprocessStderr);
this.child.on('close', (code: number) => {
console.log("[Text Expander Plugin]", `child process closed all stdio with code ${code}`);
// this.spawnHandler();
});
this.child.on('exit', (code: number) => {
console.log("[Text Expander Plugin]", `child process exited with code ${code}`);
// this.spawnHandler();
});
this.child.on('error', (err: Error) => {
console.log(`"[Text Expander Plugin]", child process: error ${err}`);
// this.spawnHandler();
});
process.on("exit", function() {
this.killHandler()
})
}
killHandler() {
this.child.kill();
}
private readonly handleSubprocessStdout = (data: Buffer): void => {
let response = JSON.parse(data.toString());
if (this.waiting) {
this.replaceRange(this.snippetLine, this.snippetStart, this.snippetEnd, response.replacement, this.codemirrorEditor);
this.waiting = false;
}
};
private readonly handleSubprocessStderr = (data: Buffer): void => {
new Notice(data.toString());
};
private readonly handleKeyDown = (
cm: CodeMirror.Editor,
event: KeyboardEvent
): void => {
for (let entry of this.settings.formats) {
let pattern = entry.pattern;
const regex = RegExp(pattern, 'g');
if (event.key === 'Tab') {
const cursor = cm.getCursor();
const {line} = cursor;
const lineString = cm.getLine(line);
let match;
while ((match = regex.exec(lineString)) !== null) {
const start = match.index;
const end = match.index + match[0].length;
if (start <= cursor.ch && cursor.ch <= end) {
event.preventDefault();
this.replaceSnippet(line, start, end, cm, entry);
}
}
}
}
};
replaceRange(
line: number,
start: number,
end: number,
replacement: string,
cm: CodeMirror.Editor
) {
let start_indent = cm.getRange(
{line: line, ch: 0},
{line: line, ch: start}
);
replacement = this.replaceAll(replacement, "<keepindent>", start_indent);
let cursorRegex = RegExp("<cursor>");
let lineStartRegex = RegExp("^", "gm");
let n_lines = replacement.match(lineStartRegex).length;
let setCursorPosition = cursorRegex.test(replacement);
let cursor_start = null;
let cursor_absolute_line = null;
if (setCursorPosition) {
let cursor_relative_line = null;
let lines = replacement.split(lineStartRegex);
for (let cursor_line = 0; cursor_line < n_lines; cursor_line++) {
let current_line = lines[cursor_line];
let cursor_match = current_line.match(cursorRegex);
if (cursor_match !== null) {
cursor_start = cursor_match.index;
cursor_relative_line = cursor_line;
if (cursor_line == 0) {
cursor_start += start_indent.length;
}
}
}
cursor_absolute_line = line + cursor_relative_line;
replacement = this.replaceAll(replacement, "<cursor>", "");
}
cm.replaceRange(
replacement,
{ch: start, line: line},
{ch: end, line: line}
);
if (setCursorPosition) {
cm.setCursor({ch: cursor_start, line: cursor_absolute_line});
}
}
replaceSnippet(
line: number,
start: number,
end: number,
cm: CodeMirror.Editor,
entry: FormatEntry
) {
const content = cm.getRange(
{line: line, ch: start + entry.cut_start},
{line: line, ch: end - entry.cut_end}
);
let not_replaced_with_snippets = this.settings.snippets.every(
(value: SnippetEntry): Boolean => {
if (content == value.trigger) {
this.replaceRange(line, start, end, value.replacement, cm);
return false;
}
return true;
}
);
if (!this.settings.is_custom_handler_enabled) {
return;
}
if (not_replaced_with_snippets) {
this.waiting = true;
this.codemirrorEditor = cm;
this.snippetLine = line;
this.snippetStart = start;
this.snippetEnd = end;
let request = {
"id": 0,
"text": content,
"context": this.getContext()
}
this.child.stdin.write(JSON.stringify(request) + '\n');
}
}
getContext(): Context {
const active_view = this.app.workspace.getActiveViewOfType(
MarkdownView
);
const vault_path = this.app.vault.adapter.basePath;
var inner_path = null;
var file_name = null;
var file_path = null;
if (active_view != null) {
inner_path = active_view.file.parent.path;
file_name = active_view.file.name;
file_path = require('path').join(
vault_path,
inner_path,
file_name
);
}
const scripts_path = require('path').join(
vault_path,
'.obsidian',
'scripts'
);
const result: Context = {
"vault_path": vault_path,
"file_name": file_name,
"file_path": file_path,
"scripts_path": scripts_path,
}
return result;
}
replaceContext(s: string): string {
const context: Context = this.getContext();
const contextKeys = [
"vault_path",
"file_name",
"file_path",
"scripts_path"
] as const;
for (let key of contextKeys) {
let value = context[key as typeof contextKeys[number]];
s = this.replaceAll(s, "<" + key + ">", value);
}
return s;
}
replaceAll(s: string, search: string, replacement: string): string {
const regex = RegExp(search, 'g');
return s.replace(regex, replacement);
}
}
class TextExpanderSettingTab extends PluginSettingTab {
plugin: TextExpanderPlugin;
constructor(app: App, plugin: TextExpanderPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
this.renderFields();
}
renderFields() {
const {containerEl} = this;
containerEl.empty();
let basicSettingsHeader = containerEl.createEl("h2").innerText = "Basic Settings";
let snippetsHeader = containerEl.createEl("h3").innerText = "Snippets";
let snippetsEl = containerEl.createEl("div");
snippetsEl.setAttribute("class", "text-expander-options text-expander-snippets");
snippetsEl.createEl("div").innerText = "Trigger";
snippetsEl.createEl("div").innerText = "Replacement";
snippetsEl.createEl("div");
for (let key in this.plugin.settings.snippets) {
new Setting(snippetsEl)
.addText(text => {
text
.setPlaceholder("trigger")
.setValue(this.plugin.settings.snippets[key]["trigger"])
.onChange(async value => {
this.plugin.settings.snippets[key]["trigger"] = value;
await this.plugin.saveSettings();
});
});
new Setting(snippetsEl)
.addTextArea(text => {
text
.setPlaceholder("replacement")
.setValue(this.plugin.settings.snippets[key]["replacement"])
.onChange(async value => {
this.plugin.settings.snippets[key]["replacement"] = value;
await this.plugin.saveSettings();
});
text.inputEl.cols = 40;
});
new ExtraButtonComponent(snippetsEl)
.setIcon("cross")
.onClick(() => {
new SnippetRemovalConfirmationModal(this.plugin.app, this.plugin, this, +key).open();
})
}
let addSnippetButtonWrapper = containerEl.createEl("div");
addSnippetButtonWrapper.setAttribute("style", "display: flex; justify-content: center;");
new ButtonComponent(addSnippetButtonWrapper)
.setButtonText("New snippet")
.setCta()
.onClick(async () => {
let newEntry: SnippetEntry = {trigger: "", replacement: ""};
this.plugin.settings.snippets.push(newEntry);
this.renderFields();
await this.plugin.saveSettings();
})
containerEl.createEl("hr");
let advancedSettingsHeader = containerEl.createEl("h2").innerText = "Advanced Settings";
let formatsHeader = containerEl.createEl("h3").innerText = "Formats";
let formatsEl = containerEl.createEl("div");
formatsEl.setAttribute("class", "text-expander-options text-expander-formats");
formatsEl.createEl("div").innerText = "Format";
formatsEl.createEl("div").innerText = "Cut start";
formatsEl.createEl("div").innerText = "Cut end";
formatsEl.createEl("div");
for (let key in this.plugin.settings.formats) {
new Setting(formatsEl)
.addText(text => {
text
.setPlaceholder("pattern")
.setValue(this.plugin.settings.formats[key]["pattern"])
.onChange(async value => {
this.plugin.settings.formats[key]["pattern"] = value;
await this.plugin.saveSettings();
});
});
new Setting(formatsEl)
.addText(text => {
text
.setPlaceholder("0")
.setValue(String(this.plugin.settings.formats[key]["cut_start"]))
.onChange(async value => {
this.plugin.settings.formats[key]["cut_start"] = +value;
await this.plugin.saveSettings();
});
});
new Setting(formatsEl)
.addText(text => {
text
.setPlaceholder("0")
.setValue(String(this.plugin.settings.formats[key]["cut_end"]))
.onChange(async value => {
this.plugin.settings.formats[key]["cut_end"] = +value;
await this.plugin.saveSettings();
});
});
new ExtraButtonComponent(formatsEl)
.setIcon("cross")
.onClick(() => {
new FormatRemovalConfirmationModal(this.plugin.app, this.plugin, this, +key).open();
})
}
let addFormatButtonWrapper = containerEl.createEl("div");
addFormatButtonWrapper.setAttribute("style", "display: flex; justify-content: center;");
new ButtonComponent(addFormatButtonWrapper)
.setButtonText("New format")
.setCta()
.onClick(async () => {
let newEntry: FormatEntry = {pattern: "", cut_start: 0, cut_end: 0};
this.plugin.settings.formats.push(newEntry);
this.renderFields();
await this.plugin.saveSettings();
})
containerEl.createEl("hr");
containerEl.createEl("h3").innerText = "Custom handler";
let enableCustomHandlerSetting = new Setting(containerEl)
.setName('Enable custom handler')
.addToggle(toggle => {
toggle
.setValue(this.plugin.settings.is_custom_handler_enabled)
.onChange(async value => {
this.plugin.settings.is_custom_handler_enabled = value;
this.renderFields()
await this.plugin.saveSettings();
});
});
enableCustomHandlerSetting.settingEl.setAttribute("style", "border: none;");
if (this.plugin.settings.is_custom_handler_enabled) {
let customHandlerSetting = new Setting(containerEl)
.setName('Handler command')
.addTextArea(text => {
text
.setPlaceholder(DEFAULT_SETTINGS.handler_command)
.setValue(this.plugin.settings.handler_command)
.onChange(async value => {
this.plugin.settings.handler_command = value;
await this.plugin.saveSettings();
});
text.inputEl.style.fontFamily = 'monospace';
text.inputEl.cols = 40;
});
customHandlerSetting.settingEl.setAttribute("style", "border: none;");
}
containerEl.createEl("hr");
containerEl.createEl("h3").innerText = "Migration manager";
let enableMigrationManagerSetting = new Setting(containerEl)
.setName('Enable migration manager')
.addToggle(toggle => {
toggle
.setValue(this.plugin.settings.is_migration_manager_enabled)
.onChange(async value => {
this.plugin.settings.is_migration_manager_enabled = value;
this.renderFields()
await this.plugin.saveSettings();
});
});
enableMigrationManagerSetting.settingEl.setAttribute("style", "border: none;");
if (this.plugin.settings.is_migration_manager_enabled) {
let legacySettingsField = new Setting(containerEl)
.setName('Legacy settings')
.addTextArea(text => {
text.setValue(this.plugin.settings.legacy_settings)
text.inputEl.style.fontFamily = 'monospace';
text.inputEl.cols = 60;
text.inputEl.rows = 30;
})
.setDisabled(true);
legacySettingsField.settingEl.setAttribute("style", "border: none;");
let migrateButtonWrapper = containerEl.createEl("div");
migrateButtonWrapper.setAttribute("style", "display: flex; justify-content: center;");
new ButtonComponent(migrateButtonWrapper)
.setButtonText("Migrate replacements")
.setCta()
.onClick(async () => {
new Notice("Migration manager is not implemented yet")
// this.renderFields();
// await this.plugin.saveSettings();
})
}
}
}
class SnippetRemovalConfirmationModal extends Modal {
plugin: TextExpanderPlugin;
settingsTab: TextExpanderSettingTab;
snippetId: number;
constructor(app: App, plugin: TextExpanderPlugin, settingsTab: TextExpanderSettingTab, snippetId: number) {
super(app);
this.plugin = plugin;
this.settingsTab = settingsTab;
this.snippetId = snippetId;
}
onOpen() {
let {contentEl} = this;
let wrapperEl = contentEl
.createEl("div")
wrapperEl.setAttribute("style", "display: flex; flex-direction: column;")
let promptEl = wrapperEl
.createEl("div")
.setText(`Are you sure you want to remove the snippet "${this.plugin.settings.snippets[this.snippetId]['trigger']}"?`);
let buttonContainerEl = wrapperEl
.createEl("div")
buttonContainerEl.setAttribute("style", "margin-top: 1em; display: flex; justify-content: center;")
new ButtonComponent(buttonContainerEl)
.setButtonText("Cancel")
.setCta()
.onClick(() => {
this.close();
})
new ButtonComponent(buttonContainerEl)
.setButtonText("Remove")
.onClick(async () => {
this.plugin.settings.snippets.splice(this.snippetId, 1);
this.close();
this.settingsTab.renderFields();
await this.plugin.saveSettings();
})
}
onClose() {
let {contentEl} = this;
contentEl.empty();
}
}
class FormatRemovalConfirmationModal extends Modal {
plugin: TextExpanderPlugin;
settingsTab: TextExpanderSettingTab;
formatId: number;
constructor(app: App, plugin: TextExpanderPlugin, settingsTab: TextExpanderSettingTab, formatId: number) {
super(app);
this.plugin = plugin;
this.settingsTab = settingsTab;
this.formatId = formatId;
}
onOpen() {
let {contentEl} = this;
let wrapperEl = contentEl
.createEl("div")
wrapperEl.setAttribute("style", "display: flex; flex-direction: column;")
let promptEl = wrapperEl
.createEl("div")
.setText(`Are you sure you want to remove the format "${this.plugin.settings.formats[this.formatId]['pattern']}"?`);
let buttonContainerEl = wrapperEl
.createEl("div")
buttonContainerEl.setAttribute("style", "margin-top: 1em; display: flex; justify-content: center;")
new ButtonComponent(buttonContainerEl)
.setButtonText("Cancel")
.setCta()
.onClick(() => {
this.close();
})
new ButtonComponent(buttonContainerEl)
.setButtonText("Remove")
.onClick(async () => {
this.plugin.settings.formats.splice(this.formatId, 1);
this.close();
this.settingsTab.renderFields();
await this.plugin.saveSettings();
})
}
onClose() {
let {contentEl} = this;
contentEl.empty();
}
}