generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
553 lines (476 loc) · 19.8 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
import {
App,
Plugin,
PluginSettingTab,
Setting,
editorLivePreviewField,
Notice,
} from 'obsidian';
import {
EditorView,
Decoration,
DecorationSet,
WidgetType,
} from "@codemirror/view";
import { syntaxTree } from "@codemirror/language";
import { Range, StateField, Transaction, Extension } from '@codemirror/state';
function indexOfGroup(match: RegExpMatchArray, n: number) {
var ix = match.index ?? 0;
for (var i = 1; i < (n-1); i++)
ix += match[i].length;
return ix;
}
function regEscape(string: string) {
// https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
// $& means the whole matched string
return string.replace(/[-.*+?^${}()|[\]\\]/g, '\\$&');
}
interface NiceKBDsSettings {
useAutoFormat: boolean;
useManualFormat: boolean;
usePluginStyles: string; // 'all', 'plugin', 'none'
triggerCharacters: string; // Any one of these characters will trigger a key combo even if not wrapped in \b.
triggerWords: string; // These words will trigger a key combo, must be wrapped in \b. Case insensitive.
additionalCharacters: string; // These characters are allowed in keys after a key combo has been triggered.
kbdWrapperForce: string; // Characters to force a <kbd> tag. Separate open and close with a comma.
}
const DEFAULT_SETTINGS: NiceKBDsSettings = {
//https://wincent.com/wiki/Unicode_representations_of_modifier_keys
useAutoFormat: true,
useManualFormat: true,
usePluginStyles: 'plugin',
triggerCharacters: '⌘⇧⇪⇥⎋⌃⌥⎇␣⏎⌫⌦⇱⇲⇞⇟⌧⇭⌤⏏⌽',
triggerWords: 'ctrl',
additionalCharacters: '\\`<>[]{}↑⇡↓⇣←⇠→⇢|~!@#$%^&*_+-=;:,./?',
kbdWrapperForce: '«,»',
}
class NiceKBDsSettingsTab extends PluginSettingTab {
plugin: NiceKBDsPlugin;
constructor(app: App, plugin: NiceKBDsPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Auto Format')
.setDesc('Automatically format key combos.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.useAutoFormat)
.onChange(async (value) => {
this.plugin.settings.useAutoFormat = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Manual Format')
.setDesc('Allow manual format of key combos, see below for wrapper character config.')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.useManualFormat)
.onChange(async (value) => {
this.plugin.settings.useManualFormat = value;
await this.plugin.saveSettings();
}));
// new Setting(containerEl)
// .setName('Styles')
// .setDesc('Use Nice KBDs styles. Only applies to <kbd>s generated by this plugin.')
// .addToggle(toggle => toggle
// .setValue(this.plugin.settings.useStyles)
// .onChange(async (value) => {
// this.plugin.settings.useStyles = value;
// await this.plugin.saveSettings();
// }));
new Setting(containerEl)
.setName('Styles')
.setDesc('Use Nice KBDs styles for all kbds, just the ones generated by this plugin, or none.')
.addDropdown(dropdown => dropdown
.addOptions({
'all': 'All',
'plugin': 'Plugin',
'none': 'None',
})
.setValue(this.plugin.settings.usePluginStyles)
.onChange(async (value) => {
this.plugin.settings.usePluginStyles = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Characters')
.setDesc('Any of these characters will trigger a <kbd> tag.')
.addText(text => text
.setPlaceholder(DEFAULT_SETTINGS.triggerCharacters)
.setValue(this.plugin.settings.triggerCharacters)
.onChange(async (value) => {
this.plugin.settings.triggerCharacters = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Additional Characters')
.setDesc('These characters are allowed in keys after a key combo has been triggered.')
.addText(text => text
.setPlaceholder(DEFAULT_SETTINGS.additionalCharacters)
.setValue(this.plugin.settings.additionalCharacters)
.onChange(async (value) => {
this.plugin.settings.additionalCharacters = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Words')
.setDesc('These words will trigger a key combo. Case insensitive. Separate with commas.')
.addText(text => text
.setPlaceholder(DEFAULT_SETTINGS.triggerWords)
.setValue(this.plugin.settings.triggerWords)
.onChange(async (value) => {
this.plugin.settings.triggerWords = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Force KBD Wrapper')
.setDesc('Characters to force a <kbd> tag. Separate open and close with a comma. We recommend the use of a plugin like Smart Typography.')
.addText(text => text
.setPlaceholder(DEFAULT_SETTINGS.kbdWrapperForce)
.setValue(this.plugin.settings.kbdWrapperForce)
.onChange(async (value) => {
this.plugin.settings.kbdWrapperForce = value;
await this.plugin.saveSettings();
}));
}
}
class KBDWidget extends WidgetType {
constructor(private key: string, private settings: NiceKBDsSettings) {
super();
}
toDOM() {
return new KBDFactory(this.settings).getElement(this.key);
}
}
class KBDFactory {
constructor(private settings: NiceKBDsSettings) {}
getClassName() {
const usePluginStyles = this.settings.usePluginStyles.toLowerCase()
if (usePluginStyles === 'all' || usePluginStyles === 'plugin') {
return 'nice-kbd'
} else {
return ''
}
}
getMark() {
return Decoration.mark({
inclusive: true,
class: this.getClassName(),
tagName: 'kbd',
})
}
getWidget(key: string) {
return new KBDWidget(key, this.settings);
}
getElement(key: string) {
const element = document.createElement('kbd');
element.className = this.getClassName();
element.innerText = key;
return element;
}
getHTML(key: string) {
return this.getElement(key).outerHTML;
}
}
// The StateField handles live editing (except for some special cases like callouts, which use post-processing).
const getNiceKBDsStateField = (settings: NiceKBDsSettings) => StateField.define<DecorationSet>({
create() {
return Decoration.none;
},
update(prev: DecorationSet, transaction: Transaction): DecorationSet {
const R = getNiceKBDsRegexes(settings);
// No decorations if we're in source mode.
const isSourceMode = !transaction.state.field(editorLivePreviewField);
if (isSourceMode) return Decoration.none;
const decorations: Range<Decoration>[] = [];
const indices: Record<number, Range<Decoration>[]> = {}; // This will hold decorations mapped by combo.
const excludeIndices = new Set<string>(); // For excluding nodes like <code> or <tag>s.
syntaxTree(transaction.state).iterate({enter(node){
// Ignore formatting and other troublesome nodes.
/* The `^list` is important; remember that list child nodes also have `list` in their name.
* - If you use just `list`, key combos in child ignore blocks (like <code>) will be matched,
* because the <code> block will never be processed and detected by excludeIndices.
* - If you remove `list` entirely, list-items will cause conflicts with child elements,
* e.g. `- ⌘ + \\` will fail because the escaped character `\\` will not be part of
* the base list-item, and therefore the key combo will first be matched as
* just `⌘ +`, excluding the escaped character.
* EDIT: This also applies to ^quote, etc.
*/
if (node.name.match(/^hmd-table-sep|^header|^quote|^list|formatting/)) return;
const nodeText = transaction.state.doc.sliceString(node.from, node.to);
walkThroughKeyCombos(nodeText, R, settings,
(combo) => {
const docFrom = node.from + combo.from;
indices[docFrom] = [];
if (node.name.match(/comment|hashtag|code|escape|strikethrough/)) {
excludeIndices.add(docFrom.toString());
return;
}
},
(key) => {
const comboDocFrom = node.from + key.comboFrom;
const comboDocTo = node.from + key.comboTo;
const keyDocFrom = comboDocFrom + key.comboOffset;
let mode = 'read'
const selectionRanges = transaction.state.selection.ranges;
for (const range of selectionRanges) {
if ((comboDocFrom <= range.to && comboDocTo >= range.from) || (comboDocFrom >= range.from && comboDocTo <= range.to)) {
mode = 'edit';
break;
}
}
// If we have special markdown formatting...
if (key.trimmedText.match(new RegExp(`[${regEscape(R.formattingCharacters)}]`))) {
if (mode === 'read') { // And we're in read mode...
// Use a replace widget to avoid conflict with Obsidian's live formatting.
indices[comboDocFrom].push(
Decoration.replace({
widget: new KBDFactory(settings).getWidget(key.trimmedText.replace(/\\(.{1})/g, '$1')), // Unescape formatting characters, sort of. TODO: This is not perfect.
}).range(keyDocFrom, keyDocFrom + key.wholeText.length),
)
}
} else {
// Otherwise, just use a kbd tag.
indices[comboDocFrom].push(new KBDFactory(settings).getMark().range(keyDocFrom, keyDocFrom + key.wholeText.length));
// And hide the wrapper characters if we're in read mode.
// In the formatting char case, we don't need to do this because the widget is replacing the whole thing.
// let wrapperMatch = key.wholeText.match(R.wrappedKey)
if (mode === 'read' && key.openWrapperOffsets && key.closeWrapperOffsets) {
indices[comboDocFrom].push(Decoration.replace({
inclusive: true,
}).range(comboDocFrom + key.openWrapperOffsets[0], comboDocFrom + key.openWrapperOffsets[1]))
indices[comboDocFrom].push(Decoration.replace({
inclusive: true,
}).range(comboDocFrom + key.closeWrapperOffsets[0], comboDocFrom + key.closeWrapperOffsets[1]))
}
}
}
)
}})
// Go back over our combos and add them to the decorations array unless they're excluded.
for (const [index, _decorations] of Object.entries(indices)) {
if (excludeIndices.has(index)) continue;
decorations.push(..._decorations);
}
return Decoration.set(decorations, true);
},
provide(field: StateField<DecorationSet>): Extension {
return EditorView.decorations.from(field); // This connects the decorations to the editor.
}
})
// The post-processor handles reading view and live edit callouts.
const getNiceKBDsPostProcessor = (settings: NiceKBDsSettings) => (element: HTMLElement, context: any) => {
const replaceInnerHTMLForKBD = (el: HTMLElement) => {
const R = getNiceKBDsRegexes(settings, true); // true: Different mode for pre-processing.
// Recurse through child nodes and perform find-replace on TEXT_NODEs.
const processNode = (node: HTMLElement) => {
// Ignore code, strikethrough, tags, comments (not technically needed since they are hidden in read mode, but better to be explicit)
const ignoreElements = ['CODE', 'PRE', 'DEL'];
if (ignoreElements.includes(node.nodeName) || node.classList.contains('tag') || node.classList.contains('cm-comment')) return node.outerHTML;
let newInnerHTML = '';
for (let childNode of Array.from(node.childNodes)) {
if (childNode.nodeType === Node.TEXT_NODE) {
const text = childNode.textContent ?? '';
let newText = '';
const lastIndex = walkThroughKeyCombos(text, R, settings,
(combo) => {
newText += text.slice(combo.lastIndex, combo.from);
},
(key) => {
// const keyText = key.wholeText.replace(new RegExp(`^${R.openWrapper}|${R.closeWrapper}$`, 'gi'), '').trim();
newText += key.sep;
newText += new KBDFactory(settings).getHTML(key.trimmedText);
}
);
newText += text.slice(lastIndex);
newInnerHTML += newText;
} else if (childNode.nodeType === Node.ELEMENT_NODE) {
newInnerHTML += processNode(childNode as HTMLElement);
}
}
node.innerHTML = newInnerHTML; // This might be bad.
return node.outerHTML;
}
/* We iterate through childNodes and build newInnerHTML with find-replace done on TEXT_NODEs.
* This is because we want to avoid matching across sibling elements.
*/
el.innerHTML = processNode(el);
}
const selector = 'p,div.callout-title-inner,td,div.table-cell-wrapper,li,h1,h2,h3,h4,h5,h6'
if (element.matches(selector)) {
replaceInnerHTMLForKBD(element);
} else {
for (const el of element.findAll(selector)) {
if (el.innerText) {
replaceInnerHTMLForKBD(el);
}
}
}
}
const getNiceKBDsRegexes = (settings: NiceKBDsSettings, postProcessing: boolean = false) => {
// Formmating characters need special handling to avoid conflict w/ Obsidian live Markdown formatting.
const formattingCharacters = '\\`[]<>*'
// Triggers are how we know to auto-match a key combo.
const triggerCharacters = settings.triggerCharacters;
const triggerWords = settings.triggerWords.split(',').map(w => '\\b' + w + '\\b').join('|'); // \b = word boundary // TODO: \b doesn't catch e.g. `Ctrl~` because ~ is not a word character.
const triggers = `[${triggerCharacters}]|${triggerWords}`;
// Wrapper characters are how we know to force a <kbd> tag.
const openWrapper = settings.kbdWrapperForce.split(',')[0];
const closeWrapper = settings.kbdWrapperForce.split(',')[1];
// Additional characters are allowed in keys after a key combo has been triggered.
let additionalCharacters = regEscape(settings.additionalCharacters)
// In post-processing, there's no such thing as escaped characters;
// see the way we're splitting NODE_TEXTs out in the post-processor.
const escapedFormattingCharacters = []
if (!postProcessing) {
// If we're NOT post-processing, we sneakily replace the formatting characters with their escaped versions.
// This way we will not attempt to match an unescaped formatting character and conflict with Obsidian's live formatting.
for (const char of settings.additionalCharacters) {
if (formattingCharacters.includes(char)) {
escapedFormattingCharacters.push(regEscape(`\\${char}`))
}
}
// And then we remove the formatting characters from the additional characters so we don't match them twice.
additionalCharacters = regEscape(settings.additionalCharacters.replace(new RegExp(`[${regEscape(formattingCharacters)}]`, 'gi'), ''))
}
const formattingCharactersMatch =
escapedFormattingCharacters.length > 0
? '|' + escapedFormattingCharacters.join('|')
: '';
// For non-trigger characters, we allow any of the additional characters, word characters, or formatting characters.
const allCharacters = `[${triggerCharacters}${additionalCharacters}\\w]${formattingCharactersMatch}`
// Wrapped keys can include almost any character.
const inWrapper = postProcessing
? `([^\\n])+?` // In post-processing, we don't need to worry about escaped characters.
: `([^\\n${regEscape(formattingCharacters)}]${formattingCharactersMatch})+?`
const wrappedKey = `(${openWrapper}[^\\S\\r\\n]*)(${inWrapper})([^\\S\\r\\n]*${closeWrapper})`
// Initial keys must start with a trigger character or word, or be wrapped.
let initialKeyParts = [];
if (settings.useAutoFormat) {
initialKeyParts.push(`((${triggers})(${allCharacters})*)`)
}
if (settings.useManualFormat) {
initialKeyParts.push(wrappedKey)
}
const initialKey = initialKeyParts.join('|')
// Additional keys can be any of the allowed characters, or be wrapped.
const additionalKeyParts = [];
if (settings.useAutoFormat) {
additionalKeyParts.push('\\w+')
additionalKeyParts.push(`(${allCharacters}){1}`)
}
if (settings.useManualFormat) {
additionalKeyParts.push(wrappedKey)
}
const additionalKey = additionalKeyParts.join('|')
// We allow multiple additional keys, separated by a plus sign.
const addKeys = `(?<sep> *\\+ *)(?<key>${additionalKey})`
// The whole regex is an initial key, followed by 0+ additional keys w/sep.
const wholeRegex = settings.useAutoFormat
? new RegExp(`(?<initialKey>${initialKey})(${addKeys})*`, 'gi')
: new RegExp(`(?<initialKey>${initialKey})`, 'gi')
return {
formattingCharacters,
openWrapper,
closeWrapper,
initialKey: new RegExp(initialKey, 'gi'),
wrappedKey: new RegExp(wrappedKey, 'i'),
addKeys: new RegExp(addKeys, 'gi'),
wholeRegex,
}
}
const walkThroughKeyCombos = (
string: string,
R: ReturnType<typeof getNiceKBDsRegexes>,
settings: NiceKBDsSettings,
processCombo: (...args: any[]) => void,
processKey: (...args: any[]) => void
) => {
let wholeMatch;
let lastIndex = 0;
// I'm sure there's a way to make this cleaner. I'll get there.
// Probably using `yield` or something.
// Also interfaces.
while ((wholeMatch = R.wholeRegex.exec(string))) {
const comboFrom: number = wholeMatch.index;
const comboTo: number = wholeMatch.index + wholeMatch[0].length;
const trimRegex = settings.useManualFormat ? `^${R.openWrapper}|${R.closeWrapper}$` : ''
processCombo({
lastIndex,
from: comboFrom,
to: comboTo,
});
// Todo: DRY out initial vs additional key code.
// First we add the initial key, stripped and trimmed.
let wrapperMatch = wholeMatch[0].match(R.wrappedKey)
let openWrapperOffsets;
let closeWrapperOffsets;
if (wrapperMatch?.index !== undefined && settings.useManualFormat) {
openWrapperOffsets = [indexOfGroup(wrapperMatch, 1), indexOfGroup(wrapperMatch, 1) + wrapperMatch[1].length]
closeWrapperOffsets = [indexOfGroup(wrapperMatch, 4), indexOfGroup(wrapperMatch, 4) + wrapperMatch[4].length]
}
processKey({
wholeText: wholeMatch.groups?.initialKey,
trimmedText: wholeMatch.groups?.initialKey.replace(new RegExp(trimRegex, 'gi'), '').trim(),
sep: '',
comboFrom,
comboTo,
comboOffset: 0,
openWrapperOffsets,
closeWrapperOffsets,
})
if (settings.useAutoFormat) {
let addKeysMatch; // Then we add any additional keys, stripped and trimmed.
while (addKeysMatch = R.addKeys.exec(wholeMatch[0].slice(wholeMatch.groups?.initialKey?.length))) {
let wrapperMatch = addKeysMatch[0].match(R.wrappedKey)
let openWrapperOffsets = null;
let closeWrapperOffsets = null;
if (wrapperMatch?.index !== undefined && settings.useManualFormat) {
openWrapperOffsets = [(wholeMatch.groups?.initialKey?.length ?? 0) + indexOfGroup(wrapperMatch, 1), (wholeMatch.groups?.initialKey?.length ?? 0) + indexOfGroup(wrapperMatch, 1) + wrapperMatch[1].length]
closeWrapperOffsets = [(wholeMatch.groups?.initialKey?.length ?? 0) + indexOfGroup(wrapperMatch, 4), (wholeMatch.groups?.initialKey?.length ?? 0) + indexOfGroup(wrapperMatch, 4) + wrapperMatch[4].length]
}
processKey({
wholeText: addKeysMatch.groups?.key,
trimmedText: addKeysMatch.groups?.key.replace(new RegExp(trimRegex, 'gi'), '').trim(),
sep: addKeysMatch.groups?.sep,
comboFrom,
comboTo,
comboOffset: (wholeMatch.groups?.initialKey?.length ?? 0) + addKeysMatch.index + (addKeysMatch.groups?.sep?.length ?? 0),
openWrapperOffsets,
closeWrapperOffsets,
});
}
}
lastIndex = wholeMatch.index + wholeMatch[0].length;
}
return lastIndex;
};
export default class NiceKBDsPlugin extends Plugin {
settings: NiceKBDsSettings;
async onload() {
await this.loadSettings();
this.addSettingTab(new NiceKBDsSettingsTab(this.app, this));
if (!this.settings.useAutoFormat && !this.settings.useManualFormat) {
new Notice('Nice KBDs: You must enable at least one of Auto Format or Manual Format.');
return;
}
const usePluginStyles = this.settings.usePluginStyles.toLowerCase()
if (usePluginStyles === 'all' || usePluginStyles === 'plugin') {
(this.app as any).dom.appContainerEl.classList.add('nice-kbds--styles-' + usePluginStyles)
}
// The editor extension handles live editing.
this.registerEditorExtension(getNiceKBDsStateField(this.settings))
// The post-processor handles reading view and live edit callouts.
this.registerMarkdownPostProcessor(getNiceKBDsPostProcessor(this.settings));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}