-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
99 lines (83 loc) · 2.33 KB
/
main.ts
File metadata and controls
99 lines (83 loc) · 2.33 KB
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
import {
Editor,
MarkdownView,
Menu,
MenuItem,
Notice,
Plugin,
TAbstractFile,
TFile,
WorkspaceLeaf,
} from "obsidian";
interface DeepNotesSettings {
mySetting: string;
}
const DEFAULT_SETTINGS: DeepNotesSettings = {
mySetting: "default",
};
export default class DeepNotes extends Plugin {
settings: DeepNotesSettings;
async onload() {
await this.loadSettings();
this.addCommand({
id: "create-note-from-selection",
name: "Create New Note from Selection",
editorCallback: (editor: Editor, view: MarkdownView) =>
this.createNoteFromSelection(editor, view),
});
this.registerEvent(
this.app.workspace.on(
"editor-menu",
(menu: Menu, editor: Editor, view: MarkdownView) => {
menu.addItem((item: MenuItem) => {
item.setTitle("Create new note")
.setIcon("document")
.onClick(() =>
this.createNoteFromSelection(editor, view)
);
});
}
)
);
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
async createNoteFromSelection(editor: Editor, view: MarkdownView) {
const selectedText: string = editor.getSelection();
if (!selectedText) return;
// Replace or remove invalid characters for the filename, but keep spaces
const sanitizedFileName: string = selectedText
.trim()
.replace(/[\\/:*?"<>|#%&{}[\]@!$'+=]/g, " ");
const newNoteName: string = selectedText.trim(); // Keep spaces for the title
const newNotePath: string = sanitizedFileName + ".md";
const newNoteContent = `# ${newNoteName}`;
try {
// Create the new note
await this.app.vault.create(newNotePath, newNoteContent);
// Replace selected text with link to the new note
const linkToNewNote = `[[${sanitizedFileName}]]`;
editor.replaceSelection(linkToNewNote);
// Notify user about the new note creation
new Notice(`New note created: ${newNoteName}`);
// Open the new note in a new tab (leaf)
const newFile: TAbstractFile | null =
this.app.vault.getAbstractFileByPath(newNotePath);
if (newFile && newFile instanceof TFile) {
const newLeaf: WorkspaceLeaf = this.app.workspace.getLeaf(true);
newLeaf.openFile(newFile);
}
} catch (error) {
new Notice(`Error creating note: ${error.message}`);
}
}
}