forked from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.ts
More file actions
99 lines (80 loc) · 2.43 KB
/
main.ts
File metadata and controls
99 lines (80 loc) · 2.43 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 {App, Editor, Plugin, PluginSettingTab, Setting} from 'obsidian';
const hljs = require('highlight.js/lib/common');
interface CodeBlockPluginSettings {
languages: string[];
}
const DEFAULT_SETTINGS: CodeBlockPluginSettings = {
languages: hljs.listLanguages()
}
export default class CodeBlockPlugin extends Plugin {
settings: CodeBlockPluginSettings;
async onload() {
await this.loadSettings();
this.addCommand({
id: 'Add code block',
name: 'Add code block',
editorCallback: (editor: Editor) => {
const selection = editor.getSelection();
if (selection.length == 0) {
const pos = editor.getCursor();
editor.replaceRange('```\n\n```\n', pos);
editor.setCursor(pos.line + 1);
return;
}
editor.replaceSelection(CodeBlockPlugin.addCodeBlock(this.getLanguage(selection), selection));
}
});
this.addCommand({
id: 'Paste code block',
name: 'Paste code block',
editorCallback: (editor: Editor) => {
navigator.clipboard.readText().then(text => {
editor.replaceSelection(CodeBlockPlugin.addCodeBlock(this.getLanguage(text), text));
});
}
});
this.addSettingTab(new CodeBlockTab(this.app, this));
}
private static addCodeBlock(language: string, selection: string) {
return '```' + language + '\n' + selection + '\n```' + '\n';
}
private getLanguage(selection: string) {
return hljs.highlightAuto(selection, this.settings.languages).language;
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class CodeBlockTab extends PluginSettingTab {
plugin: CodeBlockPlugin;
constructor(app: App, plugin: CodeBlockPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Select active programming languages' });
hljs.listLanguages().sort().forEach((language: string) => {
const index = this.plugin.settings.languages.indexOf(language);
const active = index !== -1;
return new Setting(containerEl)
.setName(language)
.addToggle(toggle => toggle
.setValue(active)
.onChange(async () => {
if (active) {
this.plugin.settings.languages.splice(index, 1);
} else {
this.plugin.settings.languages.push(language);
}
await this.plugin.saveSettings();
}));
});
}
}