generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
613 lines (552 loc) · 18 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
import {
App,
Editor,
EditorTransaction,
MarkdownView,
Notice,
Plugin,
PluginSettingTab,
Setting,
} from "obsidian";
interface CarryForwardPluginSettings {
linkText: string;
copiedLinkText: string;
lineFormatFrom: string;
lineFormatTo: string;
removeLeadingWhitespace: boolean;
displayCopiedNotice: boolean;
}
const DEFAULT_SETTINGS: CarryForwardPluginSettings = {
linkText: "",
copiedLinkText: "(see {{LINK}})",
lineFormatFrom: "\\s*$",
lineFormatTo: " (see {{LINK}})",
removeLeadingWhitespace: true,
displayCopiedNotice: true,
};
const genID = (length = 5) => {
const characters = "abcdefghijklmnopqrstuvwxyz-0123456789";
let id = "";
while (id.length < length) {
id += characters[Math.floor(Math.random() * characters.length)];
}
return id.slice(0, length);
};
enum CopyTypes {
SeparateLines,
CombinedLines,
LinkOnly,
LinkOnlyEmbed,
}
enum Mode {
LinkTextFromSettings,
LinkTextFromSelection,
LinkTextFromClipboard,
}
// This was previously `/(?<=[\s^])\^[a-zA-Z0-9-]+$/u`.
// However, iOS apparently does not support negative lookbehind, and so
// would not successfully load the plugin.
// Thus, this regex was re-written not to use negative lookbehind.
const blockIDRegex = /(?:^| +)(?<blockID>\^[a-zA-Z0-9-]+)$/u;
const copyForwardLines = async (
editor: Editor,
view: MarkdownView,
settings: CarryForwardPluginSettings,
copy: CopyTypes = CopyTypes.SeparateLines,
mode: Mode = Mode.LinkTextFromSettings
) => {
const regexValidation = validateRegex(settings.lineFormatFrom);
if (regexValidation.valid !== true) {
new Notice(
`Error: 'From' setting is invalid:\n\n${regexValidation.string}\n\nPlease update the Carry-Forward settings and try again.`,
1000 * 30 // 30 seconds
);
return;
}
const selections = editor.listSelections();
const transaction: EditorTransaction = {
changes: [],
};
const copiedLines: string[] = [];
const file = view.file;
for (const selection of selections) {
const cursorFrom = selection.anchor;
const cursorTo = selection.head;
const minLine = Math.min(cursorFrom.line, cursorTo.line);
const maxLine = Math.max(cursorFrom.line, cursorTo.line);
const maxLineLength = editor.getLine(maxLine).length;
const updatedLines: string[] = [];
let newID = "";
for (let lineNumber = minLine; lineNumber <= maxLine; lineNumber++) {
let line = editor.getLine(lineNumber);
let copiedLine = line;
if (
settings.removeLeadingWhitespace === true &&
lineNumber === minLine &&
cursorFrom.ch === cursorTo.ch
) {
// Remove leading whitespace if the user is copying a full line without
// having selected a specific part of the line:
copiedLine = copiedLine.replace(/^\s*/, "");
}
if (
(
selections.length > 1 && (
lineNumber === minLine || lineNumber === maxLine
) && !(
minLine === maxLine && cursorFrom.ch === cursorTo.ch
)
) || (
(selections.length === 1) &&
minLine === maxLine && cursorFrom.ch !== cursorTo.ch
)
) {
copiedLine = line.slice(
lineNumber === minLine ? Math.min(cursorFrom.ch, cursorTo.ch) : 0,
lineNumber === maxLine ? Math.max(cursorFrom.ch, cursorTo.ch) : line.length - 1
);
}
if (
editor.getLine(lineNumber).match(/^\s*$/) &&
!(lineNumber === minLine && minLine === maxLine)
) {
copiedLines.push(copiedLine);
updatedLines.push(line);
continue;
}
let linkText = settings.linkText;
if (mode === Mode.LinkTextFromSelection) {
linkText = editor.getRange(selection.anchor, selection.head);
}
if (mode === Mode.LinkTextFromClipboard) {
linkText = await navigator.clipboard.readText();
}
if (copy === CopyTypes.SeparateLines || lineNumber === minLine) {
// Does the line already have a block ID?
const blockIDMatch = line.match(blockIDRegex)?.groups.blockID;
let blockID =
blockIDMatch === undefined ? null : String(blockIDMatch);
let link = "";
const newChangeBlockIDs = transaction.changes?.filter(
(change) =>
change.from.line === minLine &&
change.from.ch === 0 &&
change.to.line === maxLine &&
change.to.ch === maxLineLength
);
let newChangeBlockID = null;
if (newChangeBlockIDs.length > 0) {
newChangeBlockID = String(
newChangeBlockIDs[0].text.match(blockIDRegex)?.groups.blockID
);
}
if (blockID === null && newChangeBlockID === null) {
// There is NOT an existing line ID:
newID = `^${genID()}`;
link = view.app.fileManager.generateMarkdownLink(
file,
"/",
`#${newID}`,
linkText
);
line = line.replace(/\s*?$/, ` ${newID}`);
if (copy === CopyTypes.LinkOnly || copy === CopyTypes.LinkOnlyEmbed) {
link = (copy === CopyTypes.LinkOnlyEmbed ? "!" : "") + link;
copiedLine =
copy === CopyTypes.LinkOnlyEmbed
? link
: settings.copiedLinkText.replace("{{LINK}}", link);
} else {
copiedLine = copiedLine.replace(
new RegExp(settings.lineFormatFrom, "u"),
settings.lineFormatTo.replace("{{LINK}}", link)
);
}
} else {
// There IS an existing line ID:
if (blockID === null) {
blockID = newChangeBlockID;
}
link = view.app.fileManager.generateMarkdownLink(
file,
"/",
`#${blockID}`,
linkText
);
if (copy === CopyTypes.LinkOnly || copy === CopyTypes.LinkOnlyEmbed) {
link = (copy === CopyTypes.LinkOnlyEmbed ? "!" : "") + link;
copiedLine =
copy === CopyTypes.LinkOnlyEmbed
? link
: settings.copiedLinkText.replace("{{LINK}}", link);
} else {
copiedLine = copiedLine
.replace(blockIDRegex, "")
.replace(
new RegExp(settings.lineFormatFrom, "u"),
settings.lineFormatTo.replace("{{LINK}}", link)
);
}
}
}
if (
!(
(copy === CopyTypes.LinkOnly || copy === CopyTypes.LinkOnlyEmbed) &&
lineNumber !== minLine
)
) {
copiedLines.push(copiedLine);
}
updatedLines.push(line);
}
if (
// Avoid setting repeat changes (e.g., from multiple cursors on the same
// line):
transaction.changes.filter(
(change) =>
change.from.line === minLine &&
change.from.ch === 0 &&
change.to.line === maxLine &&
change.to.ch === maxLineLength
).length === 0
) {
transaction.changes?.push({
from: { line: minLine, ch: 0 },
to: { line: maxLine, ch: maxLineLength },
text: updatedLines.join("\n"),
});
}
}
await navigator.clipboard.writeText(copiedLines.join("\n"));
if (settings.displayCopiedNotice || false) {
new Notice("Copied");
}
transaction.selections = selections.map((selection) => {
return { from: selection.anchor, to: selection.head };
});
editor.transaction(transaction);
};
export default class CarryForwardPlugin extends Plugin {
settings: CarryForwardPluginSettings;
async onload() {
console.log("loading carry-forward-line plugin");
await this.loadSettings();
this.addCommand({
id: "carry-line-forward-separate-lines",
icon: "pin",
name: "Copy selection with each line linked to its copied source (default link text)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.SeparateLines
);
},
});
this.addCommand({
id: "carry-line-forward-combined-lines",
icon: "pin",
name: "Copy selection with first line linked to its copied source (default link text)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.CombinedLines
);
},
});
this.addCommand({
id: "carry-line-forward-link-only",
icon: "pin",
name: "Copy link to line (default link text)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.LinkOnly
);
},
});
this.addCommand({
id: "carry-line-forward-embed-link-only",
icon: "pin",
name: "Copy embed link to line (default link text)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.LinkOnlyEmbed
);
},
});
this.addCommand({
id: "carry-line-forward-separate-lines-selection",
icon: "pin",
name: "Copy selection with each line linked to its copied source (link text from selection)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.SeparateLines,
Mode.LinkTextFromSelection
);
},
});
this.addCommand({
id: "carry-line-forward-combined-lines-selection",
icon: "pin",
name: "Copy selection with first line linked to its copied source (link text from selection)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.CombinedLines,
Mode.LinkTextFromSelection
);
},
});
this.addCommand({
id: "carry-line-forward-link-only-selection",
icon: "pin",
name: "Copy link to line (link text from selection)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.LinkOnly,
Mode.LinkTextFromSelection
);
},
});
this.addCommand({
id: "carry-line-forward-embed-link-only-selection",
icon: "pin",
name: "Copy embed link to line (link text from selection)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.LinkOnlyEmbed,
Mode.LinkTextFromSelection
);
},
});
this.addCommand({
id: "carry-line-forward-separate-lines-clipboard",
icon: "pin",
name: "Copy selection with each line linked to its copied source (link text from clipboard)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.SeparateLines,
Mode.LinkTextFromClipboard
);
},
});
this.addCommand({
id: "carry-line-forward-combined-lines-clipboard",
icon: "pin",
name: "Copy selection with first line linked to its copied source (link text from clipboard)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.CombinedLines,
Mode.LinkTextFromClipboard
);
},
});
this.addCommand({
id: "carry-line-forward-link-only-clipboard",
icon: "pin",
name: "Copy link to line (link text from clipboard)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.LinkOnly,
Mode.LinkTextFromClipboard
);
},
});
this.addCommand({
id: "carry-line-forward-embed-link-only-clipboard",
icon: "pin",
name: "Copy embed link to line (link text from clipboard)",
editorCallback: async (editor: Editor, view: MarkdownView) => {
return await copyForwardLines(
editor,
view,
this.settings,
CopyTypes.LinkOnlyEmbed,
Mode.LinkTextFromClipboard
);
},
});
this.addSettingTab(new CarryForwardSettingTab(this.app, this));
}
onunload() {
console.log("unloading carry-forward-line plugin");
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
const validateRegex = (
regexString: string
): { valid: boolean | null; string: string } => {
let updatedRegexString = regexString
// Because the plugin's settings are stored in JSON, characters like
// \n get double-escaped, and then do not get replaced automatically
// on use. This was causing To strings not to parse \n, etc.
.replace(/\\n/g, "\n")
.replace(/\\t/g, "\t")
.replace(/\\r/g, "\r");
try {
new RegExp(updatedRegexString, "u");
return { valid: true, string: updatedRegexString };
} catch (e) {
return {
valid: false,
string: `"${updatedRegexString}": "${e}"`,
};
}
};
class CarryForwardSettingTab extends PluginSettingTab {
plugin: CarryForwardPlugin;
constructor(app: App, plugin: CarryForwardPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
let { containerEl } = this;
containerEl.empty();
containerEl.createEl("h1", { text: "Carry-forward" });
new Setting(containerEl)
.setName("Default link text")
.setDesc(
'The default text that "{{LINK}}" in the settings below will be replaced with. Leaving this blank will display the actual text of the link.'
)
.addText((text) => {
const settings = this.plugin.settings;
text.setValue(settings.linkText).onChange(async (value) => {
settings.linkText = value;
await this.plugin.saveSettings();
});
});
const copiedLinksEl = containerEl.createEl("div");
copiedLinksEl.createEl("h2", { text: "Copied references" });
copiedLinksEl.createEl("p", {
text: 'Settings relating to "Copy link to line..." and "Copy embed link to line..." commands.',
cls: "setting-item-description",
});
new Setting(copiedLinksEl)
.setName("Copied references")
.setDesc(
"The full text of copied references. Use {{LINK}} to place the link."
)
.addText((text) => {
const settings = this.plugin.settings;
text.setValue(settings.copiedLinkText).onChange(async (value) => {
settings.copiedLinkText = value;
await this.plugin.saveSettings();
});
});
const copiedLinesEl = containerEl.createEl("div");
copiedLinesEl.createEl("h2", { text: "Copied lines" });
copiedLinesEl.createEl("p", {
text: 'Settings relating to "Copy selection..." commands.',
cls: "setting-item-description",
});
const fromToEl = copiedLinesEl.createEl("div");
fromToEl.addClass("from-to-rule");
if (validateRegex(this.plugin.settings.lineFormatFrom).valid !== true) {
fromToEl.addClass("invalid");
}
new Setting(fromToEl)
.setName("From")
.setDesc(
"Find the first match of a Regular Expression in each copied line"
)
.addText((text) =>
text
.setPlaceholder(DEFAULT_SETTINGS.lineFormatFrom)
.setValue(this.plugin.settings.lineFormatFrom)
.onChange(async (value) => {
if (value === "") {
this.plugin.settings.lineFormatFrom =
DEFAULT_SETTINGS.lineFormatFrom;
} else {
if (validateRegex(value).valid !== true) {
fromToEl.addClass("invalid");
} else {
fromToEl.removeClass("invalid");
}
this.plugin.settings.lineFormatFrom = value;
}
await this.plugin.saveSettings();
})
);
new Setting(fromToEl)
.setName("To")
.setDesc(
"Replace the first match in each copied line with text. Use {{LINK}} to place the link."
)
.addText((text) =>
text
.setPlaceholder(DEFAULT_SETTINGS.lineFormatTo)
.setValue(this.plugin.settings.lineFormatTo)
.onChange(async (value) => {
if (value === "") {
this.plugin.settings.lineFormatTo = DEFAULT_SETTINGS.lineFormatTo;
} else {
this.plugin.settings.lineFormatTo = value;
}
await this.plugin.saveSettings();
})
);
new Setting(copiedLinesEl)
.setName("Remove leading whitespace from first line")
.setDesc(
"When copying a line without having selected a specific part of that line, remove any whitespace at the beginning of the copied line."
)
.addToggle((toggle) => {
const settings = this.plugin.settings;
toggle
.setValue(settings.removeLeadingWhitespace)
.onChange(async (value) => {
settings.removeLeadingWhitespace = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Notify on successful copy")
.setDesc(
'Display a "Copied" notice upon successfully copying text to the clipboard.'
)
.addToggle((toggle) => {
const settings = this.plugin.settings;
toggle
.setValue(settings.displayCopiedNotice)
.onChange(async (value) => {
settings.displayCopiedNotice = value;
await this.plugin.saveSettings();
});
});
}
}