md文檔後臺用mistune轉html,前臺用MathJax.js把LaTex公式可視化,發現mistune把_轉爲了<em>或</em>,導致很多公式可視化失敗。後來發現該包可以擴展,就參考官方文檔擴展了一個子類,後臺轉換md爲html時,碰到$$包起來的部分啥都不做。
LaTex可視化有轉爲html的,也有轉爲SVG的(例子: http://maxiang.info/),我傾向於後者,但是沒有找到可用的python包,誰看到了告訴我。
1. md文件,含LaTex代碼
$$
\varGamma(x)=\frac{\int_{\alpha}^{\beta}g(t)(x-t)^2\text{d}t}{\phi(x)\sum_{i=0}^{N-1}\omega_i}\tag{2}
$$
$\alpha+\beta=\gamma$
2. python會把md轉爲LaTex
import re
from mistune import Renderer, Markdown, InlineLexer
# define new sub class
#讓mistune不後臺處理$$和$$之間的LaTex代碼,交給前臺的js處理成數學公式
class LaTexRenderer(Renderer):
#def LaTex(self, alt, link):
def LaTex(self, text):
return '$$%s$$' % (text)
class LaTexInlineLexer(InlineLexer):
def enable_LaTex(self):
# add LaTex rules
self.rules.LaTex = re.compile(
r'\$\$' # $$
r'([\s\S]+?)' # ***
r'\$\$(?!\])' # $$
)
# Add LaTex parser to default rules
# you can insert it some place you like
# but place matters, maybe 3 is not good
self.default_rules.insert(3, 'LaTex')
def output_LaTex(self, m):
text = m.group(1)
#alt, link = text.split('|')
# you can create an custom render
# you can also return the html if you like
#return self.renderer.LaTex(alt, link)
return self.renderer.LaTex(text)
#
renderer = LaTexRenderer()
inline = LaTexInlineLexer(renderer)
# enable the feature
inline.enable_LaTex()
markdown = Markdown(renderer, inline=inline)
# the end of sub class
#讀取md文件
fpath="../data/Python/ReadMe.markdown";
fr=open(fpath, 'r', encoding="utf-8")
text=fr.read()
fr.close()
#md to html(leave LaTex alone)
md=markdown(text)
rs=md;
#html to LaTex
js3='<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"></script>';
js3+='<script src="../static/js/showLaTex.js"></script>\n\n';
rs=rs+js3;
fw=open("index4.html",'w',encoding="utf-8")
fw.write(rs);
fw.close();
print("end", len(rs));
那個showLaTex.js文件是設置文件:
/*
* name showLaTex.js
* 依賴於 MathJax.js
* varsion: v0.1
*ES6*/
let isMathjaxConfig = false; // 防止重複調用Config,造成性能損耗
const initMathjaxConfig = () => {
if (!window.MathJax) {
return;
}
window.MathJax.Hub.Config({
showProcessingMessages: false, //關閉js加載過程信息
messageStyle: "none", //不顯示信息
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [["$", "$"], ["\\(", "\\)"]], //行內公式選擇符
displayMath: [["$$", "$$"], ["\\[", "\\]"]], //段內公式選擇符
skipTags: ["script", "noscript", "style", "textarea", "pre", "code", "a"] //避開某些標籤
},
"HTML-CSS": {
availableFonts: ["STIX", "TeX"], //可選字體
showMathMenu: false //關閉右擊菜單顯示
}
});
isMathjaxConfig = true; //
};
if (isMathjaxConfig === false) { // 如果:沒有配置MathJax
initMathjaxConfig();
}
// 如果,不傳入第三個參數,則渲染整個document
window.MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
// 因爲使用的Vuejs,所以指明#app,以提高速度
//window.MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById('app')]);