-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.ts
433 lines (376 loc) · 13.9 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
import {
Plugin,
CachedMetadata,
TFile,
Notice,
debounce,
TAbstractFile,
App,
PluginSettingTab,
Setting,
} from 'obsidian';
function basename(path: string): string {
const base = new String(path).substring(path.lastIndexOf('/') + 1);
return base;
}
export interface VaultLike {
getMarkdownFiles(): TFile[];
read(file: TFile): Promise<string>;
modify(file: TFile, content: string): Promise<void>;
on(name: string, callback: (file: TFile | TAbstractFile, oldPath?: string) => void): void;
}
export interface MetadataCacheLike {
getFileCache(file: TFile): CachedMetadata | null;
getCache(path: string): CachedMetadata | null;
getFirstLinkpathDest(linkpath: string, sourcePath: string): TFile | null;
on(name: string, callback: (file: TFile) => void): void;
}
export interface TitleAsLinkTextSettings {
debounceDelay: number;
similarityThreshold: number;
}
const DEFAULT_SETTINGS: Partial<TitleAsLinkTextSettings> = {
debounceDelay: 1000,
similarityThreshold: 0.65
};
export class LinkUpdater {
private settings: TitleAsLinkTextSettings;
constructor(
private vault: VaultLike,
private metadataCache: MetadataCacheLike,
settings: TitleAsLinkTextSettings
) {
this.settings = settings;
}
async updateAllLinks() {
const markdownFiles = this.vault.getMarkdownFiles();
let updatedBacklinksCount = 0;
for (const file of markdownFiles) {
const oldPath = file.path;
const backLinks = await this.updateBackLinks(file, oldPath, false);
if (backLinks) {
updatedBacklinksCount = backLinks + updatedBacklinksCount;
}
}
return updatedBacklinksCount;
}
async updateLinksInNote(file: TFile): Promise<number> {
const fileContent = await this.vault.read(file);
const fileCache = this.metadataCache.getFileCache(file);
if (!fileCache) {
return 0;
}
let updatedCount = 0;
// Markdown link regex breakdown:
// \[ - Match opening square bracket
// ([^\]\n]+) - Group 1: Match link text
// [^\]\n] = any char except ] or newline
// + = one or more (greedy)
// \] - Match closing square bracket
// \( - Match opening parenthesis
// ([^)\n]+) - Group 2: Match URL/path
// [^)\n] = any char except ) or newline
// + = one or more (greedy)
// \) - Match closing parenthesis
// g - Global flag: match all occurrences
const markdownLinkRegex = /\[([^\]\n]+)\]\(([^)\n]+)\)/g;
let newFileContent = fileContent.replace(
markdownLinkRegex,
(match, linkText, linkUrl) => {
// Skip if this is a checkbox pattern
if (match.startsWith('[ ]') || match.startsWith('[x]')) {
return match;
}
const linkUrlDecoded = decodeURIComponent(linkUrl);
// Remove any #subheading from the link before looking up the file
const baseLinkUrl = linkUrlDecoded.split('#')[0];
const linkedFile = this.metadataCache.getFirstLinkpathDest(baseLinkUrl, file.path);
if (linkedFile) {
const linkedCache = this.metadataCache.getFileCache(linkedFile);
if (linkedCache) {
const aliases = this.getAliases(linkedCache);
// Find the most similar alias if one exists
const similarAlias = this.findMostSimilarAlias(linkText, aliases);
if (similarAlias && similarAlias !== linkText) {
updatedCount++;
return `[${similarAlias}](${linkUrl})`;
}
// Only use title if no similar alias exists
if (!similarAlias) {
const title = this.getPageTitle(linkedCache, linkedFile.path);
if (linkText !== title) {
updatedCount++;
return `[${title}](${linkUrl})`;
}
}
}
}
return `[${linkText}](${linkUrl})`;
}
);
// Wikilinks regex breakdown:
// \[\[ - Match literal opening double brackets
// ([^\]\[\n]+?) - Group 1: Match one or more chars that aren't brackets or newline (non-greedy)
// This captures the main link path
// (?: - Start non-capturing group for optional subheading
// #([^\]\[\n]+?) - Group 2: Match # followed by one or more non-bracket/newline chars (non-greedy)
// )? - End optional subheading group
// (?: - Start non-capturing group for optional alias
// \|([^\]\[\n]+?) - Group 3: Match | followed by one or more non-bracket/newline chars (non-greedy)
// )? - End optional alias group
// \]\] - Match literal closing double brackets
const wikilinkRegex = /\[\[([^\][\n]+?)(?:#([^\][\n]+?))?(?:\|([^\][\n]+?))?]]/g;
newFileContent = newFileContent.replace(
wikilinkRegex,
(match, linkPath, subheading, linkText) => {
const linkedFile = this.metadataCache.getFirstLinkpathDest(linkPath, file.path);
if (linkedFile) {
const linkedCache = this.metadataCache.getFileCache(linkedFile);
if (linkedCache) {
const title = this.getPageTitle(linkedCache, linkedFile.path);
const subheadingPart = subheading ? `#${subheading}` : '';
const linkPart = `${linkPath}${subheadingPart}`;
if (linkText) {
// If the current link text matches the title exactly, don't try to find an alias
if (linkText === title) {
return match;
}
// Handle links with existing display text
const aliases = this.getAliases(linkedCache);
const similarAlias = this.findMostSimilarAlias(linkText, aliases);
if (similarAlias && similarAlias !== linkText) {
updatedCount++;
return `[[${linkPart}|${similarAlias}]]`;
}
if (!similarAlias && linkText !== title) {
updatedCount++;
return linkPart !== title ? `[[${linkPart}|${title}]]` : `[[${linkPart}]]`;
}
} else {
// Handle links without display text
const baseLinkName = linkPath.split('/').pop()?.replace('.md', '') || '';
if (title && title !== baseLinkName) {
updatedCount++;
return linkPart !== title ? `[[${linkPart}|${title}]]` : `[[${linkPart}]]`;
}
}
}
}
return match;
}
);
if (fileContent !== newFileContent) {
await this.vault.modify(file, newFileContent);
}
return updatedCount;
}
async updateBackLinks(file: TFile, oldPath: string, notify: boolean) {
if (
!oldPath ||
!file.path.toLocaleLowerCase().endsWith('.md') ||
!(file instanceof TFile)
) {
return;
}
const notes = this.getCachedNotesThatHaveLinkToFile(oldPath);
let updatedBacklinksCount = 0;
// Update backlinks in other notes
for (const note of notes) {
const count = await this.updateLinksInNote(note);
updatedBacklinksCount += count;
}
// Also update links in the changed file itself
const selfCount = await this.updateLinksInNote(file);
updatedBacklinksCount += selfCount;
if (notify && updatedBacklinksCount > 0) {
new Notice(
`Updated the link text of ${updatedBacklinksCount} Markdown link(s).`
);
}
return updatedBacklinksCount;
}
private getCachedNotesThatHaveLinkToFile(filePath: string): TFile[] {
const notesWithBacklinks: TFile[] = [];
const allNotes = this.vault.getMarkdownFiles();
if (allNotes) {
for (const note of allNotes) {
const notePath = note.path;
if (note.path == filePath) {
continue;
}
const noteCache = this.metadataCache.getCache(notePath);
const embedsAndLinks = [
...(noteCache?.embeds || []),
...(noteCache?.links || []),
];
if (embedsAndLinks) {
for (const link_data of embedsAndLinks) {
// getFirstLinkpathDest = Get the best match for a linkpath.
// https://marcus.se.net/obsidian-plugin-docs/reference/typescript/classes/MetadataCache
const firstLinkPath = this.metadataCache.getFirstLinkpathDest(
link_data.link,
note.path
);
if (firstLinkPath && firstLinkPath.path == filePath) {
notesWithBacklinks.push(note);
}
}
}
}
}
return notesWithBacklinks;
}
private getPageTitle(cache: CachedMetadata, filePath: string): string {
const frontMatterTitle =
cache.frontmatter && cache.frontmatter.title;
const firstHeading =
cache.headings && cache.headings.length > 0 && cache.headings[0].heading;
return (
frontMatterTitle || firstHeading || basename(filePath).replace('.md', '')
);
}
private getAliases(cache: CachedMetadata): string[] {
if (!cache.frontmatter || !cache.frontmatter.aliases) {
return [];
}
const aliases = cache.frontmatter.aliases;
if (Array.isArray(aliases)) {
return aliases;
} else if (typeof aliases === 'string') {
return [aliases];
}
return [];
}
private findMostSimilarAlias(text: string, aliases: string[]): string | null {
for (const alias of aliases) {
if (alias.toLowerCase().includes(text.toLowerCase()) ||
text.toLowerCase().includes(alias.toLowerCase())) {
return alias;
}
}
// Fall back to Levenshtein distance for fuzzy matching
let mostSimilarAlias = null;
let highestSimilarity = 0;
for (const alias of aliases) {
const similarity = this.calculateSimilarity(text, alias);
if (similarity > highestSimilarity && similarity >= this.settings.similarityThreshold) {
highestSimilarity = similarity;
mostSimilarAlias = alias;
}
}
return mostSimilarAlias;
}
private calculateSimilarity(str1: string, str2: string): number {
const matrix: number[][] = [];
for (let i = 0; i <= str1.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= str2.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= str1.length; i++) {
for (let j = 1; j <= str2.length; j++) {
if (str1[i - 1] === str2[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1, // substitution
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1 // deletion
);
}
}
}
const distance = matrix[str1.length][str2.length];
const maxLength = Math.max(str1.length, str2.length);
return 1 - (distance / maxLength);
}
}
export default class TitleAsLinkTextPlugin extends Plugin {
settings: TitleAsLinkTextSettings;
private linkUpdater: LinkUpdater;
private debouncedUpdateBackLinks: (file: TFile, oldPath: string, notify: boolean) => void;
async onload() {
await this.loadSettings();
this.linkUpdater = new LinkUpdater(
this.app.vault,
this.app.metadataCache,
this.settings
);
this.debouncedUpdateBackLinks = debounce(
this.linkUpdater.updateBackLinks.bind(this.linkUpdater),
this.settings.debounceDelay,
true
);
this.registerEvent(
this.app.vault.on('rename', async (file: TAbstractFile, oldPath: string) => {
if (file instanceof TFile) {
this.debouncedUpdateBackLinks(file, oldPath, true);
}
})
);
this.registerEvent(
this.app.metadataCache.on('changed', async (file: TFile) => {
this.debouncedUpdateBackLinks(file, file.path, true);
})
);
this.addCommand({
id: 'update-all-links',
name: 'Update All Links',
callback: async () => {
const count = await this.linkUpdater.updateAllLinks();
new Notice(`Updated the link text of ${count} Markdown link(s).`);
},
});
this.addSettingTab(new TitleAsLinkTextSettingTab(this.app, this));
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
// Recreate debounced function with new delay
this.debouncedUpdateBackLinks = debounce(
this.linkUpdater.updateBackLinks.bind(this.linkUpdater),
this.settings.debounceDelay,
true
);
}
}
class TitleAsLinkTextSettingTab extends PluginSettingTab {
plugin: TitleAsLinkTextPlugin;
constructor(app: App, plugin: TitleAsLinkTextPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName('Debounce delay')
.setDesc('How long to wait (in milliseconds) before updating links after a change')
.addText(text => text
.setPlaceholder('1000')
.setValue(String(this.plugin.settings.debounceDelay))
.onChange(async (value) => {
const delay = Number(value);
if (!isNaN(delay) && delay > 0) {
this.plugin.settings.debounceDelay = delay;
await this.plugin.saveSettings();
}
}));
new Setting(containerEl)
.setName('Similarity threshold')
.setDesc('Minimum similarity score (0.0 to 1.0) required for alias matching. Higher values require closer matches.')
.addText(text => text
.setPlaceholder('0.65')
.setValue(String(this.plugin.settings.similarityThreshold))
.onChange(async (value) => {
const threshold = Number(value);
if (!isNaN(threshold) && threshold >= 0 && threshold <= 1) {
this.plugin.settings.similarityThreshold = threshold;
await this.plugin.saveSettings();
}
}));
}
}