-
Notifications
You must be signed in to change notification settings - Fork 30
/
main.ts
698 lines (630 loc) · 20.2 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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
import {
App,
Plugin,
PluginSettingTab,
Setting,
TAbstractFile,
TFile,
Editor,
MarkdownView,
} from 'obsidian';
import { isExcluded } from './exclusions';
const stockIllegalSymbols = /[\\/:|#^[\]]/g;
// Must be Strings unless settings dialog is updated.
const enum HeadingStyle {
Prefix = 'Prefix',
Underline = 'Underline',
}
interface LinePointer {
lineNumber: number;
text: string;
style: HeadingStyle;
}
interface FilenameHeadingSyncPluginSettings {
userIllegalSymbols: string[];
ignoreRegex: string;
ignoredFiles: { [key: string]: null };
useFileOpenHook: boolean;
useFileSaveHook: boolean;
newHeadingStyle: HeadingStyle;
replaceStyle: boolean;
underlineString: string;
}
const DEFAULT_SETTINGS: FilenameHeadingSyncPluginSettings = {
userIllegalSymbols: [],
ignoredFiles: {},
ignoreRegex: '',
useFileOpenHook: true,
useFileSaveHook: true,
newHeadingStyle: HeadingStyle.Prefix,
replaceStyle: false,
underlineString: '===',
};
export default class FilenameHeadingSyncPlugin extends Plugin {
isRenameInProgress: boolean = false;
settings: FilenameHeadingSyncPluginSettings;
async onload() {
await this.loadSettings();
this.registerEvent(
this.app.vault.on('rename', (file, oldPath) => {
if (this.settings.useFileSaveHook) {
return this.handleSyncFilenameToHeading(file, oldPath);
}
}),
);
this.registerEvent(
this.app.vault.on('modify', (file) => {
if (this.settings.useFileSaveHook) {
return this.handleSyncHeadingToFile(file);
}
}),
);
this.registerEvent(
this.app.workspace.on('file-open', (file) => {
if (this.settings.useFileOpenHook && file !== null) {
return this.handleSyncFilenameToHeading(file, file.path);
}
}),
);
this.addSettingTab(new FilenameHeadingSyncSettingTab(this.app, this));
this.addCommand({
id: 'page-heading-sync-ignore-file',
name: 'Ignore current file',
checkCallback: (checking: boolean) => {
let leaf = this.app.workspace.activeLeaf;
if (leaf) {
if (!checking) {
this.settings.ignoredFiles[
this.app.workspace.getActiveFile().path
] = null;
this.saveSettings();
}
return true;
}
return false;
},
});
this.addCommand({
id: 'sync-filename-to-heading',
name: 'Sync Filename to Heading',
editorCallback: (editor: Editor, view: MarkdownView) =>
this.forceSyncFilenameToHeading(view.file),
});
this.addCommand({
id: 'sync-heading-to-filename',
name: 'Sync Heading to Filename',
editorCallback: (editor: Editor, view: MarkdownView) =>
this.forceSyncHeadingToFilename(view.file),
});
}
fileIsIgnored(activeFile: TFile, path: string): boolean {
// check exclusions
if (isExcluded(this.app, activeFile)) {
return true;
}
// check manual ignore
if (this.settings.ignoredFiles[path] !== undefined) {
return true;
}
// check regex
try {
if (this.settings.ignoreRegex === '') {
return;
}
const reg = new RegExp(this.settings.ignoreRegex);
return reg.exec(path) !== null;
} catch {}
return false;
}
/**
* Renames the file with the first heading found
*
* @param {TAbstractFile} file The file
*/
handleSyncHeadingToFile(file: TAbstractFile) {
if (!(file instanceof TFile)) {
return;
}
if (file.extension !== 'md') {
// just bail
return;
}
// if currently opened file is not the same as the one that fired the event, skip
// this is to make sure other events don't trigger this plugin
if (this.app.workspace.getActiveFile() !== file) {
return;
}
// if ignored, just bail
if (this.fileIsIgnored(file, file.path)) {
return;
}
this.forceSyncHeadingToFilename(file);
}
forceSyncHeadingToFilename(file: TFile) {
this.app.vault.read(file).then(async (data) => {
const lines = data.split('\n');
const start = this.findNoteStart(lines);
const heading = this.findHeading(lines, start);
if (heading === null) return; // no heading found, nothing to do here
const sanitizedHeading = this.sanitizeHeading(heading.text);
if (
sanitizedHeading.length > 0 &&
this.sanitizeHeading(file.basename) !== sanitizedHeading
) {
const newPath = `${file.parent.path}/${sanitizedHeading}.md`;
this.isRenameInProgress = true;
await this.app.fileManager.renameFile(file, newPath);
this.isRenameInProgress = false;
}
});
}
/**
* Syncs the current filename to the first heading
* Finds the first heading of the file, then replaces it with the filename
*
* @param {TAbstractFile} file The file that fired the event
* @param {string} oldPath The old path
*/
handleSyncFilenameToHeading(file: TAbstractFile, oldPath: string) {
if (this.isRenameInProgress) {
return;
}
if (!(file instanceof TFile)) {
return;
}
if (file.extension !== 'md') {
// just bail
return;
}
// if oldpath is ignored, hook in and update the new filepath to be ignored instead
if (this.fileIsIgnored(file, oldPath.trim())) {
// if filename didn't change, just bail, nothing to do here
if (file.path === oldPath) {
return;
}
// If filepath changed and the file was in the ignore list before,
// remove it from the list and add the new one instead
if (this.settings.ignoredFiles[oldPath]) {
delete this.settings.ignoredFiles[oldPath];
this.settings.ignoredFiles[file.path] = null;
this.saveSettings();
}
return;
}
this.forceSyncFilenameToHeading(file);
}
forceSyncFilenameToHeading(file: TFile) {
const sanitizedHeading = this.sanitizeHeading(file.basename);
this.app.vault.read(file).then((data) => {
const lines = data.split('\n');
const start = this.findNoteStart(lines);
const heading = this.findHeading(lines, start);
if (heading !== null) {
if (this.sanitizeHeading(heading.text) !== sanitizedHeading) {
this.replaceHeading(
file,
lines,
heading.lineNumber,
heading.style,
sanitizedHeading,
);
}
} else this.insertHeading(file, lines, start, sanitizedHeading);
});
}
/**
* Finds the start of the note file, excluding frontmatter
*
* @param {string[]} fileLines array of the file's contents, line by line
* @returns {number} zero-based index of the starting line of the note
*/
findNoteStart(fileLines: string[]) {
// check for frontmatter by checking if first line is a divider ('---')
if (fileLines[0] === '---') {
// find end of frontmatter
// if no end is found, then it isn't really frontmatter and function will end up returning 0
for (let i = 1; i < fileLines.length; i++) {
if (fileLines[i] === '---') {
// end of frontmatter found, next line is start of note
return i + 1;
}
}
}
return 0;
}
/**
* Finds the first heading of the note file
*
* @param {string[]} fileLines array of the file's contents, line by line
* @param {number} startLine zero-based index of the starting line of the note
* @returns {LinePointer | null} LinePointer to heading or null if no heading found
*/
findHeading(fileLines: string[], startLine: number): LinePointer | null {
for (let i = startLine; i < fileLines.length; i++) {
if (fileLines[i].startsWith('# ')) {
return {
lineNumber: i,
text: fileLines[i].substring(2),
style: HeadingStyle.Prefix,
};
} else {
if (
fileLines[i + 1] !== undefined &&
fileLines[i + 1].match(/^=+$/) !== null
) {
return {
lineNumber: i,
text: fileLines[i],
style: HeadingStyle.Underline,
};
}
}
}
return null; // no heading found
}
regExpEscape(str: string): string {
return String(str).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
}
sanitizeHeading(text: string) {
// stockIllegalSymbols is a regExp object, but userIllegalSymbols is a list of strings and therefore they are handled separately.
text = text.replace(stockIllegalSymbols, '');
const userIllegalSymbolsEscaped = this.settings.userIllegalSymbols.map(
(str) => this.regExpEscape(str),
);
const userIllegalSymbolsRegExp = new RegExp(
userIllegalSymbolsEscaped.join('|'),
'g',
);
text = text.replace(userIllegalSymbolsRegExp, '');
return text.trim();
}
/**
* Insert the `heading` at `lineNumber` in `file`.
*
* @param {TFile} file the file to modify
* @param {string[]} fileLines array of the file's contents, line by line
* @param {number} lineNumber zero-based index of the line to replace
* @param {string} text the new text
*/
insertHeading(
file: TFile,
fileLines: string[],
lineNumber: number,
heading: string,
) {
const newStyle = this.settings.newHeadingStyle;
switch (newStyle) {
case HeadingStyle.Underline: {
this.insertLineInFile(file, fileLines, lineNumber, `${heading}`);
this.insertLineInFile(
file,
fileLines,
lineNumber + 1,
this.settings.underlineString,
);
break;
}
case HeadingStyle.Prefix: {
this.insertLineInFile(file, fileLines, lineNumber, `# ${heading}`);
break;
}
}
}
/**
* Modified `file` by replacing the heading at `lineNumber` with `newHeading`,
* updating the heading style according the user settings.
*
* @param {TFile} file the file to modify
* @param {string[]} fileLines array of the file's contents, line by line
* @param {number} lineNumber zero-based index of the line to replace
* @param {HeadingStyle} oldStyle the style of the original heading
* @param {string} text the new text
*/
replaceHeading(
file: TFile,
fileLines: string[],
lineNumber: number,
oldStyle: HeadingStyle,
newHeading: string,
) {
const newStyle = this.settings.newHeadingStyle;
const replaceStyle = this.settings.replaceStyle;
// If replacing the style
if (replaceStyle) {
switch (newStyle) {
// For underline style, replace heading line...
case HeadingStyle.Underline: {
this.replaceLineInFile(file, fileLines, lineNumber, `${newHeading}`);
//..., then add or replace underline.
switch (oldStyle) {
case HeadingStyle.Prefix: {
this.insertLineInFile(
file,
fileLines,
lineNumber + 1,
this.settings.underlineString,
);
break;
}
case HeadingStyle.Underline: {
// Update underline with setting.
this.replaceLineInFile(
file,
fileLines,
lineNumber + 1,
this.settings.underlineString,
);
break;
}
}
break;
}
// For prefix style, replace heading line, and possibly delete underline
case HeadingStyle.Prefix: {
this.replaceLineInFile(
file,
fileLines,
lineNumber,
`# ${newHeading}`,
);
switch (oldStyle) {
case HeadingStyle.Prefix: {
// nop
break;
}
case HeadingStyle.Underline: {
this.replaceLineInFile(file, fileLines, lineNumber + 1, '');
break;
}
}
break;
}
}
} else {
// If not replacing style, match
switch (oldStyle) {
case HeadingStyle.Underline: {
this.replaceLineInFile(file, fileLines, lineNumber, `${newHeading}`);
break;
}
case HeadingStyle.Prefix: {
this.replaceLineInFile(
file,
fileLines,
lineNumber,
`# ${newHeading}`,
);
break;
}
}
}
}
/**
* Modifies the file by replacing a particular line with new text.
*
* The function will add a newline character at the end of the replaced line.
*
* If the `lineNumber` parameter is higher than the index of the last line of the file
* the function will add a newline character to the current last line and append a new
* line at the end of the file with the new text (essentially a new last line).
*
* @param {TFile} file the file to modify
* @param {string[]} fileLines array of the file's contents, line by line
* @param {number} lineNumber zero-based index of the line to replace
* @param {string} text the new text
*/
replaceLineInFile(
file: TFile,
fileLines: string[],
lineNumber: number,
text: string,
) {
if (lineNumber >= fileLines.length) {
fileLines.push(text + '\n');
} else {
fileLines[lineNumber] = text;
}
const data = fileLines.join('\n');
this.app.vault.modify(file, data);
}
/**
* Modifies the file by inserting a line with specified text.
*
* The function will add a newline character at the end of the inserted line.
*
* @param {TFile} file the file to modify
* @param {string[]} fileLines array of the file's contents, line by line
* @param {number} lineNumber zero-based index of where the line should be inserted
* @param {string} text the text that the line shall contain
*/
insertLineInFile(
file: TFile,
fileLines: string[],
lineNumber: number,
text: string,
) {
if (lineNumber >= fileLines.length) {
fileLines.push(text + '\n');
} else {
fileLines.splice(lineNumber, 0, text);
}
const data = fileLines.join('\n');
this.app.vault.modify(file, data);
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class FilenameHeadingSyncSettingTab extends PluginSettingTab {
plugin: FilenameHeadingSyncPlugin;
app: App;
constructor(app: App, plugin: FilenameHeadingSyncPlugin) {
super(app, plugin);
this.plugin = plugin;
this.app = app;
}
display(): void {
let { containerEl } = this;
let regexIgnoredFilesDiv: HTMLDivElement;
const renderRegexIgnoredFiles = (div: HTMLElement) => {
// empty existing div
div.innerHTML = '';
if (this.plugin.settings.ignoreRegex === '') {
return;
}
try {
const files = this.app.vault.getFiles();
const reg = new RegExp(this.plugin.settings.ignoreRegex);
files
.filter((file) => reg.exec(file.path) !== null)
.forEach((el) => {
new Setting(div).setDesc(el.path);
});
} catch (e) {
return;
}
};
containerEl.empty();
containerEl.createEl('h2', { text: 'Filename Heading Sync' });
containerEl.createEl('p', {
text:
'This plugin will overwrite the first heading found in a file with the filename.',
});
containerEl.createEl('p', {
text:
'If no header is found, will insert a new one at the first line (after frontmatter).',
});
new Setting(containerEl)
.setName('Custom Illegal Characters/Strings')
.setDesc(
'Type characters/strings separated by a comma. This input is space sensitive.',
)
.addText((text) =>
text
.setPlaceholder('[],#,...')
.setValue(this.plugin.settings.userIllegalSymbols.join())
.onChange(async (value) => {
this.plugin.settings.userIllegalSymbols = value.split(',');
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Ignore Regex Rule')
.setDesc(
'Ignore rule in RegEx format. All files listed below will get ignored by this plugin.',
)
.addText((text) =>
text
.setPlaceholder('MyFolder/.*')
.setValue(this.plugin.settings.ignoreRegex)
.onChange(async (value) => {
try {
new RegExp(value);
this.plugin.settings.ignoreRegex = value;
} catch {
this.plugin.settings.ignoreRegex = '';
}
await this.plugin.saveSettings();
renderRegexIgnoredFiles(regexIgnoredFilesDiv);
}),
);
new Setting(containerEl)
.setName('Use File Open Hook')
.setDesc(
'Whether this plugin should trigger when a file is opened, and not just on save. Disable this when you notice conflicts with other plugins that also act on file open.',
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.useFileOpenHook)
.onChange(async (value) => {
this.plugin.settings.useFileOpenHook = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Use File Save Hook')
.setDesc(
'Whether this plugin should trigger when a file is saved. Disable this when you want to trigger sync only manually.',
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.useFileSaveHook)
.onChange(async (value) => {
this.plugin.settings.useFileSaveHook = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('New Heading Style')
.setDesc(
'Which Markdown heading style to use when creating new headings: Prefix ("# Heading") or Underline ("Heading\\n===").',
)
.addDropdown((cb) =>
cb
.addOption(HeadingStyle.Prefix, 'Prefix')
.addOption(HeadingStyle.Underline, 'Underline')
.setValue(this.plugin.settings.newHeadingStyle)
.onChange(async (value) => {
if (value === 'Prefix') {
this.plugin.settings.newHeadingStyle = HeadingStyle.Prefix;
}
if (value === 'Underline') {
this.plugin.settings.newHeadingStyle = HeadingStyle.Underline;
}
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Replace Heading Style')
.setDesc(
'Whether this plugin should replace existing heading styles when updating headings.',
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.replaceStyle)
.onChange(async (value) => {
this.plugin.settings.replaceStyle = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Underline String')
.setDesc(
'The string to use when insert Underline-style headings; should be some number of "="s.',
)
.addText((text) =>
text
.setPlaceholder('===')
.setValue(this.plugin.settings.underlineString)
.onChange(async (value) => {
this.plugin.settings.underlineString = value;
await this.plugin.saveSettings();
}),
);
containerEl.createEl('h2', { text: 'Ignored Files By Regex' });
containerEl.createEl('p', {
text: 'All files matching the above RegEx will get listed here',
});
regexIgnoredFilesDiv = containerEl.createDiv('test');
renderRegexIgnoredFiles(regexIgnoredFilesDiv);
containerEl.createEl('h2', { text: 'Manually Ignored Files' });
containerEl.createEl('p', {
text:
'You can ignore files from this plugin by using the "ignore this file" command',
});
// go over all ignored files and add them
for (let key in this.plugin.settings.ignoredFiles) {
const ignoredFilesSettingsObj = new Setting(containerEl).setDesc(key);
ignoredFilesSettingsObj.addButton((button) => {
button.setButtonText('Delete').onClick(async () => {
delete this.plugin.settings.ignoredFiles[key];
await this.plugin.saveSettings();
this.display();
});
});
}
}
}