-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
163 lines (140 loc) · 4.26 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
import {
Plugin,
HeadingCache,
FrontMatterCache,
CachedMetadata,
TFile,
Notice,
debounce
} from "obsidian";
function basename(path: string): string {
let base = new String(path).substring(path.lastIndexOf("/") + 1);
return base;
}
export default class TitleAsLinkTextPlugin extends Plugin {
private debouncedUpdateBackLinks: (
file: TFile,
oldPath: string,
notify: boolean
) => void;
async onload() {
this.debouncedUpdateBackLinks = debounce(
this.updateBackLinks.bind(this),
1000,
true
);
this.registerEvent(
this.app.vault.on("rename", async (file: TFile, oldPath) => {
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 () => {
await this.updateAllLinks();
},
});
}
async updateAllLinks() {
const markdownFiles = this.app.vault.getMarkdownFiles();
var updatedBacklinksCount = 0;
for (const file of markdownFiles) {
const oldPath = file.path;
const backLinks = await this.updateBackLinks(file, oldPath, false);
if (backLinks) {
updatedBacklinksCount = backLinks + updatedBacklinksCount;
}
}
new Notice(
`Updated the link text of ${updatedBacklinksCount} Markdown link(s).`
);
}
async updateBackLinks(file: TFile, oldPath: string, notify: boolean) {
if (
!oldPath ||
!file.path.toLocaleLowerCase().endsWith(".md") ||
!(file instanceof TFile)
) {
return;
}
const cachedFile = this.app.metadataCache.getFileCache(file);
if (!cachedFile) {
return;
}
const title = this.getPageTitle(cachedFile, file.path);
const notes = this.getCachedNotesThatHaveLinkToFile(oldPath);
if (notes.length == 0) {
return;
}
let updatedBacklinksCount = 0;
for (let note of notes) {
const fileContent = await this.app.vault.read(note);
const newFileContent = fileContent.replace(
/\[(.*?)\]\((.*?)\)/g,
(_, linkText, linkUrl) => {
const linkUrlDecoded = decodeURIComponent(linkUrl);
if (basename(linkUrlDecoded) === basename(oldPath)) {
return `[${title}](${linkUrl})`;
}
return `[${linkText}](${linkUrl})`;
}
);
if (fileContent !== newFileContent) {
await this.app.vault.modify(note, newFileContent);
updatedBacklinksCount++;
}
}
if (notify && updatedBacklinksCount > 0) {
new Notice(
`Updated the link text of ${updatedBacklinksCount} Markdown link(s).`
);
}
return updatedBacklinksCount;
}
getCachedNotesThatHaveLinkToFile(filePath: string): TFile[] {
let notesWithBacklinks: TFile[] = [];
let allNotes = this.app.vault.getMarkdownFiles();
if (allNotes) {
for (let note of allNotes) {
let notePath = note.path;
if (note.path == filePath) {
continue;
}
const noteCache = this.app.metadataCache.getCache(notePath);
const embedsAndLinks = [
...(noteCache?.embeds || []),
...(noteCache?.links || []),
];
if (embedsAndLinks) {
for (let 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 = app.metadataCache.getFirstLinkpathDest(
link_data.link,
note.path
);
if (firstLinkPath && firstLinkPath.path == filePath) {
notesWithBacklinks.push(note);
}
}
}
}
}
return notesWithBacklinks;
}
getPageTitle(cache: CachedMetadata, filePath: string): string {
const frontMatterTitle =
cache.frontmatter && (cache.frontmatter as FrontMatterCache).title;
const firstHeading =
cache.headings && (cache.headings[0] as HeadingCache).heading;
return (
frontMatterTitle || firstHeading || basename(filePath).replace(".md", "")
);
}
}