forked from dvcrn/obsidian-filename-heading-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
415 lines (365 loc) · 11.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
import {
App,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
EventRef,
MarkdownView,
TFile,
TAbstractFile,
Editor,
} from 'obsidian';
const stockIllegalSymbols = /[\\/:|#^[\]]/g;
interface LinePointer {
lineNumber: number;
text: string;
}
interface FilenameHeadingSyncPluginSettings {
userIllegalSymbols: string[];
ignoreRegex: string;
ignoredFiles: { [key: string]: null };
}
const DEFAULT_SETTINGS: FilenameHeadingSyncPluginSettings = {
userIllegalSymbols: [],
ignoredFiles: {},
ignoreRegex: '',
};
export default class FilenameHeadingSyncPlugin extends Plugin {
settings: FilenameHeadingSyncPluginSettings;
async onload() {
await this.loadSettings();
this.registerEvent(
this.app.vault.on('rename', (file, oldPath) =>
this.handleSyncFilenameToHeading(file, oldPath),
),
);
this.registerEvent(
this.app.vault.on('modify', (file) => this.handleSyncHeadingToFile(file)),
);
this.registerEvent(
this.app.workspace.on('file-open', (file) =>
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;
},
});
}
fileIsIgnored(path: string): boolean {
// 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.path)) {
return;
}
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) 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.path.replace(file.basename, sanitizedHeading);
this.app.fileManager.renameFile(file, newPath);
}
});
}
/**
* 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 (!(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(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;
}
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.replaceLineInFile(
file,
lines,
heading.lineNumber,
`# ${sanitizedHeading}`,
);
}
} else this.insertLineInFile(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),
};
}
}
return null; // no heading found
}
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, '');
this.settings.userIllegalSymbols.forEach(symbol => {
text = text.replace(symbol, '');
});
return text.trim();
}
/**
* 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 Charaters/Strings')
.setDesc(
'Type charaters/strings seperated 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);
}),
);
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();
});
});
}
}
}