Github markdown 公式渲染

Render equations in markdown with katex.

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Github markdown 公式渲染
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Render equations in markdown with katex.
// @author       flaribbit
// @match        https://github.com/*.md
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js
// @resource     customCSS https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css
// @grant        GM_addStyle
// @grant        GM_getResourceText
// ==/UserScript==

(function() {
    'use strict';
    GM_addStyle(GM_getResourceText("customCSS").replace(/url\(/g,"url(https://cdn.jsdelivr.net/npm/[email protected]/dist/"));
    let convert=function(str){
        let flag=false;
        let strs=str.replace(/\\\n/g,"\\\\").replace(/\\left{/g,"\\left\\{").split("$");
        let out="";
        for(let i=0;i<strs.length;i++){
            if(flag){
                if(!strs[i]){
                    console.log(strs[i+1]);
                    out+="</p>"+katex.renderToString(strs[i+1], {throwOnError: false})+"<p>";
                    i+=2;
                }else{
                    out+=katex.renderToString(strs[i], {throwOnError: false});
                }
            }else{
                out+=strs[i];
            }
            flag=!flag;
        }
        return out;
    }
    let elements=document.querySelectorAll("p");
    for(let i=0;i<elements.length;i++){
        elements[i].innerHTML=convert(elements[i].textContent);
    }
})();