forked from apachecn/doctool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
process-tex.js
74 lines (56 loc) · 1.83 KB
/
process-tex.js
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
var fs = require('fs')
var crypto = require('crypto')
var request = require('sync-request')
var path = require('path')
function processTex(html, isMD=false) {
var re = /\\\((.+?)\\\)|\\\[([\s\S]+?)\\\]|\$(.+?)\$|\$\$([\s\S]+?)\$\$/g
var rm;
while(rm = re.exec(html)){
var tex = rm[1] || rm[2] || rm[3] || rm[4]
tex = tex.replace(/&#x\d+;/g, s => {
var code = s.slice(3, -1)
return String.fromCharCode(Number.parseInt(code, 16))
}).replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/&/g, '&')
.replace(/ /g, ' ')
var encoTex = encodeURIComponent(tex)
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/"/g, '%22')
var url = 'https://www.zhihu.com/equation?tex=' + encoTex
// replace_all
if(isMD)
html = html.split(rm[0]).join(`![${encoTex}](${url})`)
else
html = html.split(rm[0]).join(`<img alt="${encoTex}" src="${url}" />`)
}
return html
}
function processFile(fname) {
if(!fname.endsWith('.html') && !fname.endsWith('.md'))
return
console.log(fname)
var co = fs.readFileSync(fname, 'utf-8')
co = processTex(co, fname.endsWith('.md'))
fs.writeFileSync(fname, co)
}
function processDir(docDir) {
var flist = fs.readdirSync(docDir)
.filter(s => s.endsWith('.html') || s.endsWith('.md'))
for(var fname of flist) {
fname = path.join(docDir, fname)
processFile(fname)
}
}
function main() {
var fname = process.argv[2]
if(fs.statSync(fname).isDirectory())
processDir(fname)
else
processFile(fname)
console.log('done')
}
main()