forked from mii-key/obsidian-links
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
377 lines (325 loc) · 11.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
import { App, Editor, MarkdownFileInfo, MarkdownView, Notice, Plugin, PluginManifest, TAbstractFile, htmlToMarkdown, requestUrl, moment, RequestUrlParam, RequestUrlResponsePromise } from 'obsidian';
import { findLink, replaceAllHtmlLinks, LinkData, replaceMarkdownTarget, removeExtension, InternalWikilinkWithoutTextAction, findLinks, LinkTypes, getLinkTitles, getFileName } from './utils';
import { LinkTextSuggest } from 'suggesters/LinkTextSuggest';
import { ILinkTextSuggestContext } from 'suggesters/ILinkTextSuggestContext';
import { ReplaceLinkModal } from 'ui/ReplaceLinkModal';
import { ObsidianProxy } from 'commands/ObsidianProxy';
import { DEFAULT_SETTINGS, IObsidianLinksSettings } from 'settings';
import { ObsidianLinksSettingTab } from 'ObsidianLinksSettingTab';
import { getContextMenuCommands, getPaletteCommands } from 'commands/Commands';
import { UiFactory } from 'ui/UiFactory';
// import { MarkLinkState } from 'extensions/markLinkState';
export default class ObsidianLinksPlugin extends Plugin {
settings: IObsidianLinksSettings;
obsidianProxy: ObsidianProxy;
readonly EmailScheme: string = "mailto:";
linkTextSuggestContext: ILinkTextSuggestContext;
constructor(app: App, manifest: PluginManifest) {
super(app, manifest)
this.linkTextSuggestContext = {
app: app,
titleSeparator: " • ",
titles: [],
provideSuggestions: false,
setLinkData(linkData: LinkData, titles: string[]) {
this.linkData = linkData;
this.titles = titles;
this.provideSuggestions = true;
},
clearLinkData() {
this.provideSuggestions = false;
this.linkData = undefined;
this.titles = [];
}
};
// this.obsidianProxy = new ObsidianProxy(this.linkTextSuggestContext, this.settings);
}
createNotice(message: string | DocumentFragment, timeout?: number): Notice {
return new Notice(message, timeout);
}
requestUrl(request: RequestUrlParam | string): RequestUrlResponsePromise {
return requestUrl(request);
}
measurePerformance(func: () => void): number {
// @ts-ignore
const start = moment();
try {
func();
}
finally {
// @ts-ignore
// eslint-disable-next-line no-unsafe-finally
return moment().diff(start);
}
}
async onload() {
await this.loadSettings();
//TODO:
this.obsidianProxy = new ObsidianProxy(this.app, this.linkTextSuggestContext, this.settings, new UiFactory(this.app));
//TODO: remove
if (this.settings.removeLinksFromHeadingsInternalWikilinkWithoutTextAction === InternalWikilinkWithoutTextAction.None) {
switch (this.settings.removeLinksFromHeadingsInternalWikilinkWithoutTextReplacement) {
case "Destination":
this.settings.removeLinksFromHeadingsInternalWikilinkWithoutTextAction = InternalWikilinkWithoutTextAction.ReplaceWithDestination;
break;
case "LowestNoteHeading":
this.settings.removeLinksFromHeadingsInternalWikilinkWithoutTextAction = InternalWikilinkWithoutTextAction.ReplaceWithLowestNoteHeading;
break;
default:
this.settings.removeLinksFromHeadingsInternalWikilinkWithoutTextAction = InternalWikilinkWithoutTextAction.ReplaceWithDestination;
}
await this.saveSettings();
}
this.addSettingTab(new ObsidianLinksSettingTab(this.app, this));
this.registerEditorSuggest(new LinkTextSuggest(this.linkTextSuggestContext));
const commands = getPaletteCommands(this.obsidianProxy, this.settings);
for (let cmd of commands) {
this.addCommand({
id: cmd.id,
name: cmd.displayNameCommand,
icon: cmd.icon,
editorCheckCallback: (checking, editor, ctx) => cmd.handler(editor, checking)
});
}
if (this.settings.ffReplaceLink) {
this.addCommand({
id: 'editor-replace-external-link-with-internal',
name: 'Replace link',
icon: "pencil",
editorCheckCallback: (checking, editor, ctx) => this.replaceExternalLinkUnderCursorHandler(editor, checking)
});
}
if (this.settings.ffReplaceLink) {
this.registerEvent(
this.app.workspace.on("file-open", (file) => this.replaceMarkdownTargetsInNote())
)
this.registerEvent(
this.app.vault.on("delete", (file) => this.deleteFileHandler(file))
);
this.registerEvent(
this.app.vault.on("rename", (file, oldPath) => this.renameFileHandler(file, oldPath))
);
this.registerEvent(
this.app.workspace.on('editor-paste', (evt, editor, view) => this.onEditorPaste(evt, editor, view))
);
// this.registerEvent(
// this.app.workspace.on('editor-paste', (evt, editor, view) => this.processObsidianLink(evt, editor, view))
// );
if (this.settings.ffReplaceLink) {
//TODO: temp command.
this.addCommand({
id: 'editor-replace-markdown-targets-in-note',
name: '#Replace markdown link in notes',
editorCallback: (editor: Editor, view: MarkdownView) => this.replaceMarkdownTargetsInNote()
});
}
}
this.registerEvent(
this.app.workspace.on("editor-menu", (menu, editor, view) => {
const linkData = this.getLink(editor);
let addTopSeparator = function () {
menu.addSeparator();
addTopSeparator = function () { };
}
const commands = getContextMenuCommands(this.obsidianProxy, this.settings);
for (const cmd of commands) {
if (cmd == null) {
addTopSeparator();
} else {
if (cmd.handler(editor, true)) {
menu.addItem((item) => {
item
.setTitle(cmd.displayNameContextMenu)
.setIcon(cmd.icon)
.onClick(async () => {
cmd.handler(editor, false);
});
});
}
}
}
if (linkData) {
if (this.settings.ffReplaceLink && this.settings.contexMenu.replaceLink) {
menu.addItem((item) => {
item
.setTitle("Replace link")
.setIcon("pencil")
.onClick(async () => {
this.replaceExternalLink(linkData, editor);
});
});
}
}
})
);
//TODO:
// this.registerEditorExtension(MarkLinkState);
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.linkTextSuggestContext.titleSeparator = this.settings.titleSeparator;
}
async saveSettings() {
await this.saveData(this.settings);
this.linkTextSuggestContext.titleSeparator = this.settings.titleSeparator;
}
getLink(editor: Editor): LinkData | undefined {
const text = editor.getValue();
const cursorOffset = editor.posToOffset(editor.getCursor('from'));
return findLink(text, cursorOffset, cursorOffset)
}
convertHtmlLinksToMdLinks = () => {
const mdView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (mdView && mdView.getViewData()) {
const text = mdView.getViewData();
const result = replaceAllHtmlLinks(text)
mdView.setViewData(result, false);
}
}
replaceExternalLinkUnderCursorHandler(editor: Editor, checking: boolean): boolean | void {
const linkData = this.getLink(editor);
if (checking) {
return !!linkData;
}
if (linkData) {
this.replaceExternalLink(linkData, editor);
}
}
replaceExternalLink(linkData: LinkData, editor: Editor) {
new ReplaceLinkModal(this.app, async (path) => {
if (path) {
let target = path;
if (path.startsWith('[')) {
const links = findLinks(path, LinkTypes.Wiki);
if (links.length > 0 && links[0].destination?.content) {
target = links[0].destination?.content;
}
}
this.settings.linkReplacements.push({
source: linkData.destination!.content,
target: target
})
await this.saveSettings();
this.replaceMarkdownTargetsInNote();
}
}).open();
}
escapeRegex(str: string): string {
return str.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
replaceMarkdownTargetsInNote() {
const e = this.measurePerformance(() => {
const mdView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (mdView && mdView.getViewData()) {
const text = mdView.getViewData();
const [result, count] = this.replaceLinksInText(text)
if (count) {
mdView.setViewData(result, false);
new Notice(`Links: ${count} items replaced.`);
}
}
});
if (this.settings.showPerformanceNotification) {
new Notice(`${e} ms`);
}
}
replaceLinksInText(text: string): [string, number] {
let targetText = text;
let totalCount = 0;
this.settings.linkReplacements.forEach(e => {
const [newText, count] = replaceMarkdownTarget(targetText, e.source, e.target);
targetText = newText;
totalCount += count;
});
return [targetText, totalCount];
}
onEditorPaste(evt: ClipboardEvent, editor: Editor, view: MarkdownView | MarkdownFileInfo) {
const html = evt.clipboardData?.getData('text/html');
if (html && html.indexOf('<a') > 0) {
const markdown = htmlToMarkdown(html);
const [text, count] = this.replaceLinksInText(markdown);
if (count) {
evt.preventDefault();
const fromOffset = editor.posToOffset(editor.getCursor('from'));
if (editor.getSelection()) {
editor.replaceSelection(text);
} else {
editor.replaceRange(text, editor.getCursor('from'));
}
editor.setCursor(editor.offsetToPos(fromOffset + text.length));
}
}
}
//TOOD: refactor
processObsidianLink(evt: ClipboardEvent, editor: Editor, view: MarkdownView | MarkdownFileInfo) {
const text = evt.clipboardData?.getData('text/plain');
if (!text?.startsWith('obsidian://open?vault=')) {
return;
}
evt.preventDefault();
const url = new URL(text)
const targetVaultName = url.searchParams.get('vault')
const vaultName = this.app.vault.getName()
let link = text;
if (targetVaultName === vaultName) {
const file = url.searchParams.get('file');
if (file) {
const destination = decodeURI(file);
const hashIdx = destination.lastIndexOf('#');
let text = null;
if (hashIdx >= 0) {
if (hashIdx + 1 < destination.length - 1) {
text = destination.substring(hashIdx + 1)
}
} else {
text = getFileName(destination);
}
link = `[[${decodeURI(file)} ${(text && text != destination ? '|' + text : '')}]]`
}
}
const selection = editor.getSelection();
if (selection.length > 0) {
editor.replaceSelection(link);
} else {
const fromPos = editor.getCursor('from')
editor.replaceRange(link, fromPos)
editor.setCursor(editor.offsetToPos(editor.posToOffset(fromPos) + link.length));
}
}
deleteFileHandler(file: TAbstractFile) {
const [pathWithoutExtension, success] = removeExtension(file.path);
if (!success) {
return;
}
const replacements = this.settings.linkReplacements.filter(r => {
const hashIdx = r.target.indexOf('#');
return hashIdx > 0 ?
r.target.substring(0, hashIdx) !== pathWithoutExtension
: r.target !== pathWithoutExtension;
});
this.settings.linkReplacements = replacements;
this.saveSettings();
}
renameFileHandler(file: TAbstractFile, oldPath: string) {
const [oldPathWithoutExtension, success] = removeExtension(oldPath);
if (!success) {
return;
}
let settingsChanged = false;
this.settings.linkReplacements.forEach(r => {
const hashIdx = r.target.indexOf('#');
const targetPath = hashIdx > 0 ? r.target.substring(0, hashIdx) : r.target;
if (targetPath === oldPathWithoutExtension) {
const [newPathWithoutExtension] = removeExtension(file.path);
r.target = hashIdx > 0 ?
newPathWithoutExtension + r.target.substring(hashIdx) : newPathWithoutExtension;
settingsChanged = true;
}
});
if (settingsChanged) {
this.saveSettings();
}
}
}