forked from fenjalien/obsidian-latex-render
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.ts
506 lines (453 loc) · 13.6 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
import {
App,
FileSystemAdapter,
MarkdownPostProcessorContext,
Plugin,
PluginSettingTab,
SectionCache,
Setting,
TFile,
TFolder,
} from "obsidian";
import { Md5 } from "ts-md5";
import * as fs from "fs";
import * as temp from "temp";
import * as path from "path";
import { exec } from "child_process";
interface LatexRendererSettings {
command: string;
timeout: number;
enableCache: boolean;
cache: Array<[string, Set<string>]>;
cacheFolder: string;
additionalPackages: string;
pngCopy: boolean;
pngScale: string;
}
const DEFAULT_SETTINGS: LatexRendererSettings = {
command: ``,
timeout: 10000,
enableCache: true,
cache: [],
cacheFolder: "svg-cache",
additionalPackages: "",
pngCopy: false,
pngScale: "1",
};
export default class LatexRenderer extends Plugin {
settings: LatexRendererSettings;
cacheFolderPath: string;
cache: Map<string, Set<string>>; // Key: md5 hash of latex source. Value: Set of file path names.
async onload() {
await this.loadSettings();
// console.log("Loaded settings", this.settings);
if (this.settings.enableCache) await this.loadCache();
this.addSettingTab(new LatexRendererSettingTab(this.app, this));
this.registerMarkdownCodeBlockProcessor("latex", (source, el, ctx) =>
this.renderLatexToElement(source, el, ctx)
);
}
onunload() {
// if (this.settings.enableCache) this.unloadCache();
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
async loadCache() {
// console.log("Loading cache", this.settings.cacheFolder);
if (this.app.vault.adapter instanceof FileSystemAdapter) {
this.cacheFolderPath = path.join(
this.app.vault.adapter.getBasePath(),
this.settings.cacheFolder
);
}
if (!fs.existsSync(this.cacheFolderPath)) {
fs.mkdirSync(this.cacheFolderPath);
this.cache = new Map();
} else {
this.cache = new Map(this.settings.cache);
// For some reason `this.cache` at this point is actually `Map<string, Array<string>>`
for (const [k, v] of this.cache) {
this.cache.set(k, new Set(v));
}
}
}
unloadCache() {
fs.rmdirSync(this.cacheFolderPath, { recursive: true });
}
formatLatexSource(source: string) {
return (
"\\documentclass{standalone}\n" +
this.settings.additionalPackages +
source
);
}
hashLatexSource(source: string) {
return Md5.hashStr(source.trim());
}
addRandomPrefixToIds(svgStr: string) {
function generateRandomPrefix() {
let letters = "abcdefghijklmnopqrstuvwxyz";
letters += letters.toUpperCase();
let prefix = "";
for (let i = 0; i < 4; i++) {
prefix += letters[Math.floor(Math.random() * letters.length)];
}
return prefix;
}
// Generate a random 4-letter prefix
const randomPrefix = generateRandomPrefix();
// Replace the id substrings
let updatedSvgStr = svgStr
.toString()
.replace(/xlink:href='#g/g, `xlink:href='#g${randomPrefix}`);
updatedSvgStr = updatedSvgStr
.toString()
.replace(/<path id='g/g, `<path id='g${randomPrefix}`);
const encoder = new TextEncoder();
const updatedArrayBuffer = encoder.encode(updatedSvgStr);
return updatedSvgStr;
}
async renderLatexToElement(
source: string,
el: HTMLElement,
ctx: MarkdownPostProcessorContext
) {
return new Promise<void>((resolve, reject) => {
let md5Hash = this.hashLatexSource(source);
let svgPath = path.join(this.cacheFolderPath, `${md5Hash}.svg`);
// SVG file has already been cached
// Could have a case where svgCache has the key but the cached file has been deleted
if (
this.settings.enableCache &&
this.cache.has(md5Hash) &&
fs.existsSync(svgPath)
) {
// console.log("Using cached SVG: ", md5Hash);
//skip - the DOM API or the Obsidian helper functions don't seem to have a way to insert an SVG element
el.innerHTML = fs.readFileSync(svgPath).toString();
this.addFileToCache(md5Hash, ctx.sourcePath);
resolve();
} else {
// console.log("Rendering SVG: ", md5Hash);
this.renderLatexToSVG(source, md5Hash, svgPath)
.then((v: string) => {
if (this.settings.enableCache)
this.addFileToCache(md5Hash, ctx.sourcePath);
//skip - the DOM API or the Obsidian helper functions don't seem to have a way to insert an SVG element
el.innerHTML = v;
resolve();
})
.catch((err) => {
//skip - the DOM API or the Obsidian helper functions don't seem to have a way to insert an SVG element
el.innerHTML = err;
reject(err);
});
}
}).then(() => {
if (this.settings.enableCache)
setTimeout(() => this.cleanUpCache(), 1000);
});
}
renderLatexToSVG(source: string, md5Hash: string, svgPath: string) {
return new Promise(async (resolve, reject) => {
source = this.formatLatexSource(source);
temp.mkdir("obsidian-latex-renderer", (err, dirPath) => {
if (err) reject(err);
fs.writeFileSync(path.join(dirPath, md5Hash + ".tex"), source);
exec(
this.settings.command.replace(/{file-path}/g, md5Hash),
{ timeout: this.settings.timeout, cwd: dirPath },
async (err, stdout, stderr) => {
if (err) reject([err, stdout, stderr]);
else {
let svgData = fs.readFileSync(
path.join(dirPath, md5Hash + ".svg")
);
let pngData = await this.svgStringToPngArrayBuffer(
svgData.toString()
);
if (this.settings.pngCopy) {
fs.writeFileSync(
path.join(
this.cacheFolderPath,
md5Hash + ".png"
),
Buffer.from(pngData)
);
}
let svgDataStr = this.addRandomPrefixToIds(
svgData.toString()
);
if (this.settings.enableCache) {
fs.writeFileSync(svgPath, svgDataStr);
}
resolve(svgDataStr);
}
}
);
});
});
}
async saveCache() {
let temp = new Map();
for (const [k, v] of this.cache) {
temp.set(k, [...v]);
}
this.settings.cache = [...temp];
await this.saveSettings();
}
addFileToCache(hash: string, file_path: string) {
if (!this.cache.has(hash)) {
this.cache.set(hash, new Set());
}
this.cache.get(hash)?.add(file_path);
}
async cleanUpCache() {
let file_paths = new Set<string>();
for (const fps of this.cache.values()) {
for (const fp of fps) {
file_paths.add(fp);
}
}
for (const file_path of file_paths) {
let file = this.app.vault.getAbstractFileByPath(file_path);
if (file == null) {
this.removeFileFromCache(file_path);
} else {
if (file instanceof TFile) {
await this.removeUnusedCachesForFile(file);
}
}
}
await this.saveCache();
}
async removeUnusedCachesForFile(file: TFile) {
let hashes_in_file = await this.getLatexHashesFromFile(file);
let hashes_in_cache = this.getLatexHashesFromCacheForFile(file);
for (const hash of hashes_in_cache) {
if (!hashes_in_file.contains(hash)) {
this.cache.get(hash)?.delete(file.path);
if (this.cache.get(hash)?.size == 0) {
this.removeSVGFromCache(hash);
}
}
}
}
removeSVGFromCache(key: string) {
this.cache.delete(key);
fs.rmSync(path.join(this.cacheFolderPath, `${key}.svg`));
}
removeFileFromCache(file_path: string) {
for (const hash of this.cache.keys()) {
this.cache.get(hash)?.delete(file_path);
if (this.cache.get(hash)?.size == 0) {
this.removeSVGFromCache(hash);
}
}
}
async svgStringToPngArrayBuffer(svgString: string): Promise<ArrayBuffer> {
return new Promise<ArrayBuffer>((resolve, reject) => {
// Create a new image element
const img = new Image();
// Encode the SVG string into a data URL
const svgBlob = new Blob([svgString], { type: "image/svg+xml" });
const url = URL.createObjectURL(svgBlob);
// Set up the image load handler to draw on canvas
img.onload = () => {
// Create a canvas element
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
if (!context) {
reject(new Error("Unable to get canvas 2D context"));
return;
}
// Set canvas dimensions to match the image
canvas.width = img.width * parseFloat(this.settings.pngScale);
canvas.height = img.height * parseFloat(this.settings.pngScale);
// Draw the SVG image on the canvas
context.drawImage(img, 0, 0, canvas.width, canvas.height);
// Revoke the object URL
URL.revokeObjectURL(url);
// Convert the canvas content to a Blob (PNG format)
canvas.toBlob((blob) => {
if (!blob) {
reject(
new Error("Canvas toBlob() resulted in a null blob")
);
return;
}
// Create a FileReader to convert the Blob to an ArrayBuffer
const reader = new FileReader();
reader.onloadend = () => {
if (reader.result) {
resolve(reader.result as ArrayBuffer);
} else {
reject(
new Error("FileReader failed to read the blob")
);
}
};
reader.readAsArrayBuffer(blob);
}, "image/png");
};
// Handle image load error
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error("Failed to load SVG string as an image"));
};
// Set the image source to the data URL
img.src = url;
});
}
getLatexHashesFromCacheForFile(file: TFile) {
let hashes: string[] = [];
let path = file.path;
for (const [k, v] of this.cache.entries()) {
if (v.has(path)) {
hashes.push(k);
}
}
return hashes;
}
async getLatexHashesFromFile(file: TFile) {
let hashes: string[] = [];
let sections = this.app.metadataCache.getFileCache(file)?.sections;
if (sections != undefined) {
let lines = (await this.app.vault.read(file)).split("\n");
for (const section of sections) {
if (
section.type != "code" &&
lines[section.position.start.line].match("``` *latex") ==
null
)
continue;
let source = lines
.slice(
section.position.start.line + 1,
section.position.end.line
)
.join("\n");
let hash = this.hashLatexSource(source);
hashes.push(hash);
}
}
return hashes;
}
}
class LatexRendererSettingTab extends PluginSettingTab {
plugin: LatexRenderer;
constructor(app: App, plugin: LatexRenderer) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl
.createEl("p", {
text: 'This plugin uses latex to render SVGs. The SVGs are cached and automatically removed if they are not being used. The key thing is to find a command that will work on your system. Example: `export LIBGS=/opt/homebrew/lib/libgs.dylib && latex -interaction=nonstopmode -halt-on-error -shell-escape "{file-path}" && dvisvgm --no-fonts "{file-path}"`. For more information please see the ',
})
.createEl("a", {
text: "README",
href: "https://github.com/jvsteiner/obsidian-latex-render",
});
new Setting(containerEl)
.setName("Command to generate SVG")
.setDesc(
"The command to generate SVG from latex source. Use `{file-path}` as a placeholder for the file path."
)
.setClass("latex-render-settings")
.addTextArea((text) =>
text
.setValue(this.plugin.settings.command.toString())
.onChange(async (value) => {
this.plugin.settings.command = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Enable caching of SVGs")
.setDesc(
"SVGs rendered by this plugin will be kept in `svg-cache`. The plugin will automatically keep track of used svgs and remove any that aren't being used"
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.enableCache)
.onChange(async (value) => {
this.plugin.settings.enableCache = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Make a PNG copy of cached SVGs")
.setDesc(
"Cached SVGs rendered by this plugin will be rendered in PNG format in the cache directory."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.pngCopy)
.onChange(async (value) => {
this.plugin.settings.pngCopy = value;
await this.plugin.saveSettings();
this.plugin.unloadCache();
this.plugin.loadCache();
})
);
new Setting(containerEl)
.setName("PNG scale factor")
.setDesc(
"If enabled above, PNG format copies will be scaled by the factor below."
)
.addText((text) => {
text.setValue(this.plugin.settings.pngScale).onChange(
async (value) => {
this.plugin.settings.pngScale = value;
await this.plugin.saveSettings();
this.plugin.unloadCache();
this.plugin.loadCache();
}
);
});
new Setting(containerEl)
.setName("Cache folder path")
.setDesc(
"SVGs rendered by this plugin will be kept in this folder, if set. The default is `svg-cache`. The plugin will automatically keep track of used svgs and remove any that aren't being used"
)
.addText((text) =>
text
.setValue(this.plugin.settings.cacheFolder)
.onChange(async (value) => {
this.plugin.settings.cacheFolder = value;
await this.plugin.saveSettings();
this.plugin.unloadCache();
this.plugin.loadCache();
})
);
new Setting(containerEl)
.setName("Additional packages")
.setDesc(
"Latex packages typed here will be added to the standard latex source. This can be used to add custom packages or configurations to the latex source"
)
.setClass("latex-render-settings")
.addTextArea((text) =>
text
.setValue(
this.plugin.settings.additionalPackages.toString()
)
.onChange(async (value) => {
this.plugin.settings.additionalPackages = value;
await this.plugin.saveSettings();
this.plugin.unloadCache();
this.plugin.loadCache();
})
);
}
}