Reference

Hexo博客(13)添加MathJax数学公式渲染

Init mathejax.ejs

首先在 \themes\Vateral\layout 中新建 mathejax.ejs 用于行内以及行间公式渲染。

<!-- MathJax配置,可通过单美元符号书写行内公式等 -->
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
    "HTML-CSS": { 
        preferredFont: "TeX", 
        availableFonts: ["STIX","TeX"], 
        linebreaks: { automatic:true }, 
        EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50) 
    },
    tex2jax: { 
        inlineMath: [ ["$", "$"], ["\\(","\\)"] ], 
        processEscapes: true, 
        ignoreClass: "tex2jax_ignore|dno",
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {  
        equationNumbers: { autoNumber: "AMS" },
        noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" } }, 
        Macros: { href: "{}" } 
    },
    messageStyle: "none"
    }); 
</script>
<!-- 给MathJax元素添加has-jax class -->
<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<!-- 通过连接CDN加载MathJax的js代码 -->
<script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML">
</script>

Edit marked.js

Latex 中部分符号和 Markdown 冲突了,所以需要 Markdown 去掉一些字符的转义。

编辑node_modules\marked\lib\marked.js 脚本,

  • 第一步,将451行的escape: /^\([\*{}\[\]()# +\-.!_>])/, 替换为 escape: /^\\([*[]()# +-.!_>])/,
    这一步取消了对\,{,}的转义(escape)
  • 第二步,将459行的em: /^\b((?:[^]|_)+?)\b|^*((?:**|[\s\S])+?)*(?!*)/,
    替换为
    em:/^*((?:**|[\s\S])+?)*(?!*)/,
    这一步取消了对斜体标记_的转义

Edit post.ejs

之后要让页面引用到 mathjax.ets,而每个页面在生成的时候都会调用 post.ejs,所以在 post.ejs中加入:

<!-- 根据页面mathjax变量决定是否加载MathJax数学公式js -->
<% if (page.mathjax){ %>
<%- partial('mathjax') %>
<% } %>

之后如果没有 pjax 的话就引入成功了,之后在文件头使用 mathjax: true 就可以启用 mathjax

Edit pjax

但是在我这里只有第一次进入才会调用到 post.ejs,之后退出再进入就不会调用了。同时发现强制刷新也可以调用 post.ejs 。查看 network 发现是因为有一个 pjax 阻止了 post.ejs 的调用,因此需要编辑 pjax。

全局搜索 pjax,发现在 layout.ets 中使用了 pjax:

$(document).pjax('a:not(.nopjax)', '#content-inner', {fragment:'#content-inner', timeout:8000});
$(document).on('pjax:start', NProgress.start).on('pjax:end', NProgress.done)
    .on('pjax:end', () => {
        dowmdiv();
        lazy();
        toc();
        links();
        menu();
    });

暂时只能先禁用 pjax 保证 Latex 正常显示 ……

终于,$ \text{Latex} $ 以及行内公式终于可以正常加载了:

2019.3.21 Update

注意到:

$(document).pjax('a:not(.nopjax)', '#content-inner', {fragment:'#content-inner', timeout:8000});

是排除 nopjax 类的,于是修改 partials/recent-posts.ejs:

<a class="recent-post-link" href="<%=config.root + post.path%>" style="min-height: 150px">

加入 nopjax 类

<a class="nopjax recent-post-link" href="<%=config.root + post.path%>" style="min-height: 150px">

这样可以正常加载了【可是这和禁用PJAX有什么区别.....

$$ \text{Goodby}^{\text{pjax}} \quad \text{Hello}^{\text{latex}} $$


Time and Tide wait for no man.