forked from twibiral/obsidian-execute-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
332 lines (276 loc) · 9.9 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
import {FileSystemAdapter, MarkdownRenderer, MarkdownView, Notice, Plugin} from 'obsidian';
import * as fs from "fs";
import * as os from "os"
import * as child_process from "child_process";
import {Outputter} from "./Outputter";
import {ExecutorSettings, SettingsTab} from "./SettingsTab";
import {
addInlinePlotsToPython,
addMagicToJS,
addMagicToPython,
insertNotePath,
insertNoteTitle,
insertVaultPath
} from "./Magic";
// @ts-ignore
import * as JSCPP from "JSCPP";
// @ts-ignore
import * as prolog from "tau-prolog";
const supportedLanguages = ["js", "javascript", "python", "cpp", "prolog", "shell", "bash", "groovy"];
const buttonText = "Run";
const runButtonClass = "run-code-button";
const runButtonDisabledClass = "run-button-disabled";
const hasButtonClass = "has-run-code-button";
const DEFAULT_SETTINGS: ExecutorSettings = {
timeout: 10000,
nodePath: "node",
nodeArgs: "",
pythonPath: "python",
pythonArgs: "",
pythonEmbedPlots: true,
shellPath: "bash",
shellArgs: "",
shellFileExtension: "sh",
groovyPath: "groovy",
groovyArgs: "",
groovyFileExtension: "groovy",
maxPrologAnswers: 15,
}
export default class ExecuteCodePlugin extends Plugin {
settings: ExecutorSettings;
async onload() {
await this.loadSettings();
this.addSettingTab(new SettingsTab(this.app, this));
this.addRunButtons(document.body);
this.registerMarkdownPostProcessor((element, _context) => {
this.addRunButtons(element);
});
// live preview renderers
supportedLanguages.forEach(l => {
console.log(`registering renderer for ${l}`)
this.registerMarkdownCodeBlockProcessor(`run-${l}`, async (src, el, _ctx) => {
await MarkdownRenderer.renderMarkdown('```' + l + '\n' + src + '\n```', el, '', null)
})
})
}
onunload() {
document
.querySelectorAll("pre > code")
.forEach((codeBlock: HTMLElement) => {
const pre = codeBlock.parentElement as HTMLPreElement;
const parent = pre.parentElement as HTMLDivElement;
if (parent.hasClass(hasButtonClass)) {
parent.removeClass(hasButtonClass);
}
});
document
.querySelectorAll("." + runButtonClass)
.forEach((button: HTMLButtonElement) => button.remove());
document
.querySelectorAll("." + runButtonDisabledClass)
.forEach((button: HTMLButtonElement) => button.remove());
document
.querySelectorAll(".clear-button")
.forEach((button: HTMLButtonElement) => button.remove());
document
.querySelectorAll(".language-output")
.forEach((out: HTMLElement) => out.remove());
console.log("Unloaded plugin: Execute Code");
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
private addRunButtons(element: HTMLElement) {
element.querySelectorAll("code")
.forEach((codeBlock: HTMLElement) => {
const pre = codeBlock.parentElement as HTMLPreElement;
const parent = pre.parentElement as HTMLDivElement;
const language = codeBlock.className.toLowerCase();
let srcCode = codeBlock.getText(); // get source code and perform magic to insert title etc
const vars = this.getVaultVariables();
srcCode = insertVaultPath(srcCode, vars.vaultPath);
srcCode = insertNotePath(srcCode, vars.filePath);
srcCode = insertNoteTitle(srcCode, vars.fileName);
if (supportedLanguages.some((lang) => language.contains(`language-${lang}`))
&& !parent.classList.contains(hasButtonClass)) { // unsupported language
parent.classList.add(hasButtonClass);
const button = this.createRunButton();
pre.appendChild(button);
const out = new Outputter(codeBlock);
// Add button:
if (language.contains("language-js") || language.contains("language-javascript")) {
srcCode = addMagicToJS(srcCode);
button.addEventListener("click", () => {
button.className = runButtonDisabledClass;
this.runCode(srcCode, out, button, this.settings.nodePath, this.settings.nodeArgs, "js");
});
} else if (language.contains("language-python")) {
button.addEventListener("click", async () => {
button.className = runButtonDisabledClass;
if (this.settings.pythonEmbedPlots) // embed plots into html which shows them in the note
srcCode = addInlinePlotsToPython(srcCode);
srcCode = addMagicToPython(srcCode);
this.runCode(srcCode, out, button, this.settings.pythonPath, this.settings.pythonArgs, "py");
});
} else if (language.contains("language-shell") || language.contains("language-bash")) {
button.addEventListener("click", () => {
button.className = runButtonDisabledClass;
this.runCode(srcCode, out, button, this.settings.shellPath, this.settings.shellArgs, this.settings.shellFileExtension);
});
} else if (language.contains("language-cpp")) {
button.addEventListener("click", () => {
button.className = runButtonDisabledClass;
out.clear();
this.runCpp(srcCode, out);
button.className = runButtonClass;
})
} else if (language.contains("language-prolog")) {
button.addEventListener("click", () => {
button.className = runButtonDisabledClass;
out.clear();
const prologCode = srcCode.split(/\n+%+\s*query\n+/);
if (prologCode.length < 2) return; // no query found
this.runPrologCode(prologCode, out);
button.className = runButtonClass;
})
} else if (language.contains("language-groovy")) {
button.addEventListener("click", () => {
button.className = runButtonDisabledClass;
this.runCode(srcCode, out, button, this.settings.groovyPath, this.settings.groovyArgs, this.settings.groovyFileExtension);
});
}
}
})
}
private getVaultVariables() {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView == null) {
return null;
}
const adapter = app.vault.adapter as FileSystemAdapter;
const vaultPath = adapter.getBasePath();
const folder = activeView.file.parent.path;
const fileName = activeView.file.name
const filePath = activeView.file.path
return {
vaultPath: vaultPath,
folder: folder,
fileName: fileName,
filePath: filePath,
}
}
private runCpp(cppCode: string, out: Outputter) {
new Notice("Running...");
const config = {
stdio: {
write: (s: string) => out.write(s)
},
unsigned_overflow: "warn", // can be "error"(default), "warn" or "ignore"
maxTimeout: this.settings.timeout,
};
const exitCode = JSCPP.run(cppCode, 0, config);
console.log("C++ exit code: " + exitCode);
out.write("\nprogram stopped with exit code " + exitCode);
new Notice(exitCode === 0 ? "Done" : "Error");
}
private createRunButton() {
console.log("Add run button");
const button = document.createElement("button");
button.classList.add(runButtonClass);
button.setText(buttonText);
return button;
}
private getTempFile(ext: string) {
return `${os.tmpdir()}/temp_${Date.now()}.${ext}`
}
private runCode(codeBlockContent: string, outputter: Outputter, button: HTMLButtonElement, cmd: string, cmdArgs: string, ext: string) {
new Notice("Running...");
const tempFileName = this.getTempFile(ext)
console.log(`${tempFileName}`);
fs.promises.writeFile(tempFileName, codeBlockContent)
.then(() => {
console.log(`Execute ${this.settings.nodePath} ${tempFileName}`);
const args = cmdArgs ? cmdArgs.split(" ") : [];
args.push(tempFileName);
var opts = {}
if (ext === "groovy") {
opts = {shell:true}
}
const child = child_process.spawn(cmd, args, opts);
this.handleChildOutput(child, outputter, button, tempFileName);
})
.catch((err) => {
console.log("Error in 'Obsidian Execute Code' Plugin while executing: " + err);
});
}
private runPrologCode(prologCode: string[], out: Outputter) {
new Notice("Running...");
const session = prolog.create();
session.consult(prologCode[0]
, {
success: () => {
session.query(prologCode[1]
, {
success: async (goal: any) => {
console.log(goal)
let answersLeft = true;
let counter = 0;
while (answersLeft && counter < this.settings.maxPrologAnswers) {
await session.answer({
success: function (answer: any) {
new Notice("Done!");
console.log(session.format_answer(answer));
out.write(session.format_answer(answer) + "\n");
},
fail: function () {
/* No more answers */
answersLeft = false;
},
error: function (err: any) {
new Notice("Error!");
console.error(err);
answersLeft = false;
},
limit: function () {
answersLeft = false;
}
});
counter++;
}
},
error: (err: any) => {
new Notice("Error!");
out.writeErr("Query failed.\n")
out.writeErr(err.toString());
}
}
)
},
error: (err: any) => {
out.writeErr("Adding facts failed.\n")
out.writeErr(err.toString());
}
}
);
}
private handleChildOutput(child: child_process.ChildProcessWithoutNullStreams, outputter: Outputter, button: HTMLButtonElement, fileName: string) {
outputter.clear();
child.stdout.on('data', (data) => {
outputter.write(data.toString());
});
child.stderr.on('data', (data) => {
outputter.writeErr(data.toString());
});
child.on('close', (code) => {
button.className = runButtonClass;
new Notice(code === 0 ? "Done!" : "Error!");
fs.promises.rm(fileName)
.catch((err) => {
console.log("Error in 'Obsidian Execute Code' Plugin while removing file: " + err);
});
});
}
}