Advertisement
Alantag26

Markdown enhanced parser

May 16th, 2021
783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { parse } = require("mathjs");
  2.  
  3. const commands = {
  4.   "\\cfrac": [2, `($1)/($2)`],
  5.   "\\frac": [2, `($1)/($2)`],
  6.   "\\cancel": [1, `*1`],
  7.   "\\text": [1, `$1`],
  8.   "\\div": [0, `/`],
  9.   "\\cdot": [0, `*`],
  10.   "\\times": [0, `*`],
  11.   "\\large": [0, ``],
  12.   "\\log_": [2, `Math.log10($2)/Math.log10($1)`],
  13.   "\\log": [1, `Math.log10($1)`],
  14.   "\\arcsin": [1, `Math.asin($1)`],
  15.   "\\arccos": [1, `Math.acos($1)`],
  16.   "\\mod": [0, `%`],
  17.   "\\sqrt": [1, `Math.sqrt($1)`],
  18.   "\\pi": [0, `Math.PI`],
  19.   "\\floor": [1, `Math.floor($1)`]
  20. }
  21.  
  22. let title;
  23. let globalVariables;
  24.  
  25. function Fact(num)
  26. {
  27.     var rval=1;
  28.     for (var i = 2; i <= num; i++)
  29.         rval = rval * i;
  30.     return rval;
  31. }
  32.  
  33. function findCmd(str, start) {
  34.   let brackets = 1;
  35.   let betweenBrackets = '';
  36.   let end = 0;
  37.  
  38.   for (let i = start; i < str.length; i++) {
  39.  
  40.     if (str[i] == '}') {
  41.       brackets -= 1;
  42.     } else if (str[i] == '{') {
  43.       brackets += 1;
  44.     }
  45.  
  46.     if (brackets <= 0) {
  47.       break;
  48.     }
  49.  
  50.     betweenBrackets += str[i];
  51.     end = i;
  52.   }
  53.  
  54.   if (brackets > 0) return;
  55.  
  56.   return [betweenBrackets, end];
  57. }
  58.  
  59. function latexToMath(line) {
  60.   let currentIndex;
  61.   while (true) {
  62.     let brackets = [];
  63.  
  64.     let firstCmd = line.match(/\\.+?(?={|}|\\|\W|$)/gm);
  65.     if (!firstCmd)
  66.       break;
  67.     firstCmd = firstCmd[0];
  68.  
  69.     let commandArgs = commands[firstCmd];
  70.     if (!commandArgs) {
  71.       line = line.replace(firstCmd, '');
  72.       continue;
  73.     }
  74.  
  75.     console.log(firstCmd)
  76.  
  77.     if (commandArgs[0] != 0) {
  78.       currentIndex = line.indexOf(firstCmd) + firstCmd.length + 1;
  79.  
  80.       for (let i = 0; i < commandArgs[0]; i++) {
  81.         let betweenBrackets = findCmd(line, currentIndex);
  82.         currentIndex = betweenBrackets[1] + (i == 0 ? 3 : 0);
  83.         brackets.push(betweenBrackets[0]);
  84.       }
  85.       // currentIndex -= 1;
  86.  
  87.     }
  88.  
  89.     if (brackets.length != 0) {
  90.       let text = commands[firstCmd][1];
  91.  
  92.       for (let [i, content] of brackets.entries()) {
  93.         content = content.replace(/(?<=\^){(-?\d+)}/gm, '**$1')
  94.        
  95.         // console.log(content.replace(/(?<=\^){(-?\d+)}/gm, '$1'))
  96.  
  97.         text = text.replace('$' + (i + 1), content)
  98.       }
  99.       console.log(line.substr(line.indexOf(firstCmd), currentIndex - line.indexOf(firstCmd) + (commandArgs[0] > 1 ? 2 : -1)))
  100.       // console.log(line.indexOf(firstCmd))
  101.       line = line.replace(line.substr(line.indexOf(firstCmd), currentIndex - line.indexOf(firstCmd) + (commandArgs[0] > 1 ? 2 : -1)), text);
  102.       // console.log(line)
  103.     } else {
  104.       line = line.replace(firstCmd, commands[firstCmd][1]);
  105.     }
  106.   }
  107.  
  108.   return line;
  109. }
  110.  
  111. function parseLine(subMath, variables) {
  112.   let count = -1;
  113.   for ([name, value] of Object.entries(variables)) {
  114.     let regexString = `\(?<!^\)@\\[${name}\(:\(?<index>.+?\)\)?\\]\(\(?<args>.{1,3}\(?=!\)\)?\(?<calc>!\)\)?`
  115.     let regex = new RegExp(regexString);
  116.     let globalregex = new RegExp(regexString, 'g');
  117.     count++;
  118.     let realName = Object.keys(variables)[count]
  119.    
  120.     if (subMath.match(regex)) {
  121.       let allVars = subMath.match(globalregex)
  122.      
  123.       for(let i = 0; i < allVars.length; i++){
  124.         let outValue = variables[realName];
  125.         let text = allVars[i]
  126.  
  127.         let index = subMath.match(regex).groups.index
  128.         if(index){
  129.           let indexes = index.split(',');
  130.           let separator = indexes.length > 1 ? indexes[1] : '*';
  131.  
  132.           if(value.split(separator).length>0){
  133.             outValue = variables[realName].split(separator)[parseInt(indexes[0])]
  134.             // value = indexes.length
  135.           }
  136.  
  137.         }
  138.         if(subMath.match(regex).groups.calc){
  139.           let args = subMath.match(regex).groups.args
  140.           if(args){
  141.             subMath = subMath.replace(text, parseLine(`\\calc{${outValue}}[${args}]`, variables)[0])
  142.           }else{
  143.             subMath = subMath.replace(text, parseLine(`\\calc{${outValue}}`, variables)[0])
  144.           }
  145.         }else{
  146.           subMath = subMath.replace(text, outValue)
  147.         }
  148.       }
  149.     }
  150.   }
  151.  
  152.   let calcCmd = subMath.match(/\\calc\{/)
  153.   if (calcCmd) {
  154.     // subMath = subMath.replace(/\^{(-?[^\}]+)}/gm, '**($1)')
  155.     // console.log(latexToMath(insideCalc))
  156.    
  157.     try {
  158.       let calcCmd = [...subMath.matchAll(/\\calc{/gm)];
  159.       let allCalcs = [];
  160.  
  161.       for(let calc of calcCmd){
  162.         let calcCmdLastIndex = calc.index + calc[0].length
  163.         let insideCalc = findCmd(subMath, calcCmdLastIndex)[0]
  164.         let extra = subMath.substring(calcCmdLastIndex).match(/(?<=})\[.+?\]/)
  165.         extra = extra ? extra[0] : ""
  166.         // subMath=subMath[calcCmdLastIndex]
  167.         allCalcs.push([`\\calc{${insideCalc}}`, insideCalc, extra]);
  168.       }
  169.      
  170.       for(let calc of allCalcs){
  171.         let args = calc[2].substring(1, calc[2].length-1).split(',')
  172.  
  173.         if(calc[2] != ''){
  174.           if(args[0].search("raw") != -1){
  175.             subMath = subMath.replace(calc[0]+calc[2], eval(calc[1]));
  176.             continue;
  177.           }
  178.         }
  179.  
  180.         calc[1] = calc[1].replace(/\bsin\b/, 'Math.sin')
  181.                          .replace(/\bcos\b/, 'Math.cos')
  182.                          .replace(/\^{(-?[^\}]+)}/gm, '**($1)')
  183.  
  184.         // calc[1].replace(',', '.')
  185.  
  186.  
  187.         if(calc[2] != ""){
  188.           let isCientific = args[0].search("d") != -1 ? true : false;
  189.  
  190.           if(isCientific){
  191.             const splitAt = (x, index) => [x.slice(0, index), x.slice(index)]
  192.             let evaluated = eval(latexToMath(calc[1]))
  193.             let str = evaluated.toString();
  194.             let delimiter = parseInt(args[0]) != NaN ? parseInt(args[0]) : 0;
  195.  
  196.             if(evaluated > 1){
  197.               if(delimiter > 0){
  198.                 if(str.search(/\./) != -1){
  199.                   let negative = str[0] == '-' ? true : false
  200.                     if(negative)
  201.                       str = str.substr(1)
  202.                    
  203.                   let add = str.split('.')[0].length > 3 ? str.search(/\./) - delimiter : 0
  204.                     console.log(str)
  205.                     if(add != 0){
  206.                       let noDot = str.replace('.', '')
  207.                         let decimalSplit = splitAt(noDot,delimiter)
  208.                         decimalSplit[1] = decimalSplit[1].substr(0,delimiter)
  209.                         var res = `${negative ? '-' : ''}${decimalSplit.join('.')}*10^{${add}}`
  210.                     }else{
  211.                       var res = `${negative ? '-' : ''}${str.substring(0,str.search(/\./)+delimiter+1)}`
  212.                     }
  213.                 }else{
  214.                   let decimalSplit = splitAt(str, delimiter);
  215.                   let rightNums = decimalSplit[1].match(/.*[^0](?=0)?/)
  216.                   let zeros = decimalSplit[1].match(/0+$/)
  217.                   let right = rightNums ? `,${rightNums}` : ''
  218.                   console.log(decimalSplit)
  219.                   var res = `${decimalSplit[0]}${right}${rightNums ? `*10^{${decimalSplit[1].length}}` : (zeros ? `*10^{${zeros[0].length}}` : '')}`;
  220.                 }
  221.               }else{
  222.                 if(str.search(/\./) != -1){
  223.                   let delimiter = 2;
  224.                     let negative = str[0] == '-' ? true : false
  225.                     if(negative)
  226.                       str = str.substr(1)
  227.                    
  228.                   let add = str.split('.')[0].length > 3 ? str.search(/\./) - delimiter : 0
  229.                     console.log(str)
  230.                     if(add != 0){
  231.                       let noDot = str.replace('.', '')
  232.                         let decimalSplit = splitAt(noDot,delimiter)
  233.                         var res = `${negative ? '-' : ''}${decimalSplit.join('.')}*10^{${add}}`
  234.                     }else{
  235.                       var res = `${negative ? '-' : ''}${str.substring(0,str.search(/\./)+delimiter+1)}`
  236.                     }
  237.                 }else{
  238.                   let firstZero = str.match(/0(?![^0])/)
  239.                   if(firstZero){
  240.                     let decimalSplit = splitAt(str, firstZero.index);
  241.                     var res = `${decimalSplit[0]}*10^{${decimalSplit[1].length}}`;
  242.                   }else{
  243.                     var res = str
  244.                   }
  245.                 }
  246.               }
  247.             }else if(1 > evaluated > 0){
  248.               if(delimiter > 0){
  249.                 let negative = str[0] == "-" ? true : false
  250.                 let firstNums = str.match(/(?<=0|\.)[^0\.]/).index+delimiter
  251.                 let decimalSplit = splitAt(str, firstNums);
  252.                 let numOfZeros = decimalSplit[0].substr(negative ? 3 : 2)
  253.                 let right = decimalSplit[1].length > 0 ? `.${decimalSplit[1]}` : ''
  254.                 var res = `${negative ? "-" : ""}${parseInt(numOfZeros)}${right.substring(0,delimiter+1)}*10^{-${numOfZeros.toString().length}}`
  255.               }else{
  256.                 let negative = str[0] == "-" ? true : false
  257.                 let firstNums = str.match(/(?<=0|\.)[^0\.]/).index
  258.                 let decimalSplit = splitAt(str, firstNums);
  259.                 let right = decimalSplit[1].match(/.+[^0](?=0)/) ? decimalSplit[1].match(/.+[^0](?=0)/)[0] : decimalSplit[1]
  260.                 let numOfZeros = decimalSplit[0].match(/0/g).length
  261.                 var res = `${negative ? "-" : ""}${right.substring(0, 5)}*10^{-${numOfZeros+right.length-1}}`
  262.               }
  263.             }
  264.             if(res.match(/^[^@]/))
  265.               res = res.replace(',', '.')
  266.  
  267.             subMath = subMath.replace(calc[0]+calc[2], res);
  268.           }else{
  269.             subMath = subMath.replace(calc[0]+calc[2], eval(latexToMath(calc[1])).toFixed(args[0]));
  270.           }
  271.         }else{
  272.           subMath = subMath.replace(calc[0], eval(latexToMath(calc[1])).toString());
  273.         }
  274.       }
  275.     } catch (e) {
  276.       // console.log(e)
  277.     }
  278.   }
  279.  
  280.   let beginVar = subMath.match(/^@\[(?<name>.+)](?<rendered>[^\s]{0,6})=(?<value>.+)(?<equals>\=*$)/)
  281.   if (beginVar && beginVar.groups.equals.length == 0) {
  282.     let value = beginVar.groups.value
  283.     let newValue = value
  284.     if(value.search('sel{') != -1){
  285.       newValue = findCmd(value, value.search('sel{')+4)[0]
  286.     }
  287.     variables[beginVar.groups.name] = newValue
  288.     if (beginVar.groups.rendered.length > 0) {
  289.       subMath = subMath.replace(beginVar[0], `${beginVar.groups.rendered}=${value.replace(`\\sel{${newValue}}`, newValue)}`)
  290.     } else {
  291.       subMath = subMath.replace(beginVar[0], ``)
  292.     }
  293.   }
  294.  
  295.   return [subMath, variables];
  296. }
  297.  
  298. function customParseMarkdown(markdown, outVars=false) {
  299.   let variables = {}
  300.  
  301.   let allMaths = [...markdown.matchAll(/\$\$.*?\$\$/gms)];
  302.  
  303.   if (allMaths) {
  304.     for (math of allMaths) {
  305.       let parsed = math[0].match(/(?<=\$\$).*?(?=\$\$)/gms)[0];
  306.       let allSubMaths = [...parsed.matchAll(/^.+/gm)]
  307.  
  308.       for (subMath of allSubMaths) {
  309.         subMath = subMath[0];
  310.         oldSubMath = subMath;
  311.         let subVariables = variables
  312.  
  313.         let line = parseLine(subMath, variables)
  314.  
  315.         subMath = subMath.replace(/^(.+=)?(.+)==$/gm, ($1, $2, $3) => {
  316.           line=parseLine(`${$2??''}${$3}=\\calc{${$3}}`, variables)
  317.           variables=parseLine(`@[tmp]=\\calc{${$3}}`,variables)[1];
  318.           return `${$2??''}${$3}=\\calc{${$3}}`
  319.         })
  320.  
  321.         let nextLine = ''
  322.         subMath = subMath.replace(/^(.+=)(.+)_=$/gm, ($1, $2, $3) => {
  323.           line = parseLine($2+$3, variables)
  324.           nextLine=parseLine(`\\calc{${$3}}`, variables)[0];
  325.           variables = parseLine(`@[tmp]=${nextLine}`,variables)[1];
  326.           nextLine = $2+nextLine;
  327.           return $2+$3
  328.         })
  329.  
  330.  
  331.         if(nextLine){
  332.           // variables=subVariables
  333.           parsed = parsed.replace(oldSubMath, line[0]+'\n'+nextLine);
  334.         }else{
  335.           parsed = parsed.replace(oldSubMath, line[0]);
  336.           variables = line[1]
  337.         }
  338.  
  339.       }
  340.  
  341.  
  342.       // parsed = parsed.replace(/--\>/gm, '\n');
  343.       // parsed = parsed.replace(/\=\=\>/gm, '\n');
  344.       // parsed = parsed.replace(/\=\=\=/gm, '\n');
  345.       // parsed = parsed.replace(/[^\s].*[^\s]/gm, ($0) => `${$0}\n`);
  346.       // // parsed = parsed.replace(/.$/gm, ($0) => `${$0} \\\\ `);  
  347.  
  348.       // parsed = parsed.replace(/\.\./gm, '')
  349.       // parsed = parsed.replace(/__/gm, '')
  350.       // parsed = parsed.replace(/\\\\.*\n/gm, '\n')
  351.  
  352.       // parsed = parsed.replace(/\\cfrac\{(.+?)\}\{/gm, ($1) => `(${$1.slice(7,-2)})/(`);
  353.       // parsed = parsed.replace(/\{/gm, '(');
  354.       // parsed = parsed.replace(/\}/gm, ') ');
  355.  
  356.       // parsed = parsed.replace(/\\v\|.*?\|/gm, ($1) => `\\begin{gathered} ${$1.slice(3,-1)} \\end{gathered}`)
  357.       markdown = markdown.replace(math[0], `${parsed}`);
  358.       console.log(variables)
  359.     }
  360.   }
  361.  
  362.   globalVariables = variables;
  363.  
  364.   if(outVars === true){
  365.     return [markdown, variables];
  366.   }else{
  367.     return markdown;
  368.   }
  369.  
  370. }
  371.  
  372. module.exports = {
  373.   onWillParseMarkdown: function (markdown) {
  374.     return new Promise((resolve, reject) => {
  375.  
  376.       const superRawMarkdown = markdown;
  377.  
  378.       //gnuplot
  379.       markdown = markdown.replace(
  380.         /```gnuplot/gm, ($0) =>
  381.         `${$0}{cmd output="html" hide=true}
  382. set terminal svg
  383. set border 15 lt rgb "gray75"
  384. set key left tc rgb "gray75"`,
  385.       );
  386.  
  387.       //mermaid
  388.       if (/graph/s.exec(markdown)) {
  389.         let allGraphs = /```mermaid.*graph.../gs.exec(markdown)[0];
  390.         markdown = markdown.replace(
  391.           /```mermaid.*graph.../gs, "@@@");
  392.  
  393.         allGraphs = allGraphs.replace(/graph.*/gm, ($0) =>
  394.           `${$0}
  395. classDef default fill:#4f5259, color:#abb2bf, stroke:transparent
  396. classDef none fill:transparent, stroke:transparent, color:transparent`
  397.         );
  398.  
  399.         markdown = markdown.replace("@@@", allGraphs);
  400.       }
  401.  
  402.       //math
  403.       let allMaths = [...markdown.matchAll(/\$\$.*?\$\$/gms)];
  404.  
  405.       allMaths = allMaths.map(item => {
  406.         return [item[0], item.index]
  407.       })
  408.  
  409.       if (allMaths) {
  410.         for ([index, math] of allMaths.entries()) {
  411.  
  412.           let center = false;
  413.           let codeblock = false;
  414.          
  415.           let parsed = math[0].match(/(?<=\$\$).*?(?=\$\$)/gms)[0];
  416.           parsed = customParseMarkdown(`$$${parsed}$$`, true)[0]
  417.  
  418.           if (parsed.slice(0,2) == '^^') {
  419.             center = true;
  420.             parsed = '\n'+parsed.slice(2)
  421.           }
  422.  
  423.           if (parsed[0] == '>') {
  424.             codeblock = true;
  425.             parsed = parsed.slice(1)
  426.           }
  427.  
  428.           if (parsed[0] == '!') {
  429.             parsed = parsed.slice(1)
  430.             markdown = markdown.replace(math[0], `$$${parsed}$$`);
  431.             continue;
  432.           }
  433.  
  434.  
  435.           parsed = parsed.replace(/^\>/gm, '\\qquad ')
  436.  
  437.           if(codeblock){
  438.             parsed = parsed.replace(/[^\s].*[^\s]/gm, ($0) => `>$${$0}$\\`);
  439.           }else{
  440.             parsed = parsed.replace(/[^\s].*[^\s]/gm, ($0) => `$${$0}$\n`);
  441.           }
  442.          
  443.           let allsubmaths = [...parsed.matchAll(/\$.*?\$\\?/gm)];
  444.  
  445.           for([i, submath] of Object.entries(allsubmaths)){
  446.             submath=submath[0]
  447.             let newSubmath = submath
  448.  
  449.             try{
  450.               for(i of submath.matchAll(/\\mcolor\{(.+?)\}\{/g)){
  451.                 newSubmath=newSubmath.replace(newSubmath.match(/\\mcolor\{(.+?)\}\{/)[0]+findCmd(newSubmath, newSubmath.match(/\\mcolor\{(.+?)\}\{/).index+newSubmath.match(/\\mcolor\{(.+?)\}\{/)[0].length)[0]+'}',
  452.                 `\\color{${newSubmath.match(/\\mcolor\{(.+?)\}\{/)[1]}}${findCmd(newSubmath, newSubmath.match(/\\mcolor\{(.+?)\}\{/).index+newSubmath.match(/\\mcolor\{(.+?)\}\{/)[0].length)[0]}\\color{a}`
  453.                 )
  454.                 // '$1}$2\\color{a}'
  455.               }
  456.  
  457.               for(i of submath.matchAll(/\\floor\{/g)){
  458.                 newSubmath=newSubmath.replace('\\floor{'+findCmd(newSubmath, newSubmath.match(/\\floor\{/).index+7)[0]+'}',
  459.                 `\\text{floor}(${findCmd(newSubmath, newSubmath.match(/\\floor\{/).index+7)[0]})`
  460.                 )
  461.                 // '$1}$2\\color{a}'
  462.               }
  463.  
  464.               for(i of submath.matchAll(/\\size\{(.+?)\}\{/g)){
  465.                 newSubmath=newSubmath.replace(newSubmath.match(/\\size\{(.+?)\}\{/)[0]+findCmd(newSubmath, newSubmath.match(/\\size\{(.+?)\}\{/).index+newSubmath.match(/\\size\{(.+?)\}\{/)[0].length)[0]+'}',
  466.                 `\\${newSubmath.match(/\\size\{(.+?)\}\{/)[1]} ${findCmd(newSubmath, newSubmath.match(/\\size\{(.+?)\}\{/).index+newSubmath.match(/\\size\{(.+?)\}\{/)[0].length)[0]}\\normalsize `
  467.                 )
  468.                 // '$1}$2\\color{a}'
  469.               }
  470.               if(i==allsubmaths.length-1 && codeblock){
  471.                 newSubmath=newSubmath.replace(/\$\\/, '$')
  472.               }
  473.               parsed = parsed.replace(submath, newSubmath)
  474.             }catch(err){
  475.               console.log(err)
  476.             }
  477.  
  478.           }
  479.  
  480.  
  481.           let wordCompatible = true
  482.          
  483.          
  484.           if(wordCompatible){
  485.             parsed = parsed.replace(/\.\./gm, '\\hspace{4px}')
  486.                            .replace(/\$\\\\\$$/gm, '$\\hspace{1mm}$')
  487.                            .replace(/^\$\@(.+)\$/gm, ($1, $2) => parseLine(`\\calc{${$2}}`, globalVariables)[0])
  488.                            .replace(/__/gm, '\\hspace{20px}')
  489.                            .replace(/={3}\>/gm, '\\xRightarrow{\\hspace{6mm}}')
  490.                            .replace(/-{3}\>/gm, '\\xrightarrow{\\hspace{6mm}}')
  491.                            .replace(/--\>/gm, ' \\rightarrow ')
  492.                            .replace(/\s-\>/gm, ' \\rightarrow ')
  493.                            .replace(/\s=\>/gm, ' \\Rightarrow ')
  494.                            .replace(/\s\<=\>/gm, ' \\Leftrightarrow ')
  495.                            .replace(/\s\<==\>/gm, ' \\Longleftrightarrow ')
  496.                            .replace(/\=\=\>/gm, ' \\Rightarrow ')
  497.                            .replace(/\=\=\=/gm, ' \\text{ -------- }')
  498.                            .replace(/\\va\|(.*?)\|/gm, `\\begin{aligned} $1 \\end{aligned}`)
  499.                            .replace(/\\v\|(.*?)\|/gm, `\\begin{gathered} $1 \\end{gathered}`)
  500.                            .replace(/\\mod/gm, `\\text{ mod }`)
  501.                            .replace(/\bblue\b/gm,    `lightskyblue`)
  502.                            .replace(/\bred\b/gm,     `tomato`)
  503.                            .replace(/\bgreen\b/gm,   `darkseagreen`)
  504.                            .replace(/\bmagenta\b/gm, `hotpink`)
  505.                            .replace(/\[\[(.+?)\]\]/gm, `\\boxed{$1}`)
  506.                            .replace(/\s\=-\s/gm, '\\equiv ')
  507.                            .replace(/=~/gm, `\\approx`)
  508.                            .replace(/\s\.\s/gm, '\\cdot ')
  509.                            .replace(/\\cfrac/gm, '\\frac ')
  510.                           //  .replace(/\*/gm, '\\cdot ')
  511.           }else{
  512.             parsed = parsed.replace(/\.\./gm, '\\hspace{4px}')
  513.                            .replace(/\$\\\\\$$/gm, '$\\hspace{1mm}$')
  514.                            .replace(/^\$\@(.+)\$/gm, ($1, $2) => parseLine(`\\calc{${$2}}`, globalVariables)[0])
  515.                            .replace(/__/gm, '\\hspace{20px}')
  516.                            .replace(/\s\.\s/gm, '\\cdot ')
  517.                            .replace(/\s\=-\s/gm, '\\equiv ')
  518.                            .replace(/={3}\>/gm, '\\xRightarrow{\\hspace{6mm}}')
  519.                            .replace(/-{3}\>/gm, '\\xrightarrow{\\hspace{6mm}}')
  520.                            .replace(/--\>/gm, '\\hspace{5mm}\\rightarrow\\hspace{5mm}')
  521.                            .replace(/\s-\>/gm, '\\space\\rightarrow\\space')
  522.                            .replace(/\s=\>/gm, '\\space\\Rightarrow\\space')
  523.                            .replace(/\s\<=\>/gm, '\\space\\Leftrightarrow\\space')
  524.                            .replace(/\s\<==\>/gm, '\\space\\Longleftrightarrow\\space')
  525.                            .replace(/\=\=\>/gm, '\\hspace{5mm}\\Rightarrow\\hspace{5mm}')
  526.                            .replace(/\=\=\=/gm, ' \\text{ -------- }')
  527.                            .replace(/\\va\|(.*?)\|/gm, `\\begin{aligned} $1 \\end{aligned}`)
  528.                            .replace(/\\v\|(.*?)\|/gm, `\\begin{gathered} $1 \\end{gathered}`)
  529.                            .replace(/\\mod/gm, `\\text{ mod }`)
  530.                            .replace(/\bblue\b/gm,    `lightskyblue`)
  531.                            .replace(/\bred\b/gm,     `tomato`)
  532.                            .replace(/\bgreen\b/gm,   `darkseagreen`)
  533.                            .replace(/\bmagenta\b/gm, `hotpink`)
  534.                            .replace(/\[\[(.+?)\]\]/gm, `\\boxed{$1}`)
  535.                            .replace(/=~/gm, `\\approx`)
  536.                           //  .replace(/\*/gm, ` \\cdot `)
  537.           }
  538.  
  539.  
  540.                                
  541.          
  542.           // parsed.replace(/\\mcolor\{(.+?)\}\{(.+?)\}/gm, '\\color{$1}$2\\color{a}')
  543.  
  544.             markdown = markdown.replace(math[0], center ? `<center>${parsed}</center>` : `${parsed}`);
  545.  
  546.           let allInlineMaths = [...markdown.matchAll(/!\$(?!(\$|\s)).+?\$/gms)]
  547.  
  548.           for(let i = 0; i < allInlineMaths.length; i++){
  549.             let item = allInlineMaths[i]
  550.  
  551.             let inlineMath = item[0].slice(2,-1)
  552.  
  553.             let parsed = parseLine(' '+inlineMath, globalVariables)
  554.  
  555.             let parsedInlineMath = parsed[0]
  556.          
  557.             markdown = markdown.replace(`!$${inlineMath}$`, parsedInlineMath)
  558.           }
  559.  
  560.         }
  561.       }
  562.  
  563.  
  564.       // nonMath commands
  565.       let nonMath = [...markdown.matchAll(/^(?!$)(?!.*(\$.*?\$)).+/gm)];
  566.      
  567.       for(let text of nonMath){
  568.         let newText = text[0]
  569.  
  570.         let parseColor = (color) => {
  571.           let replaceList = [
  572.             ['blue', 'lightskyblue'],
  573.             ['red', 'tomato'],
  574.             ['green', 'darkseagreen'],
  575.             ['magenta', 'hotpink'],
  576.           ]
  577.  
  578.           let newColor = color
  579.  
  580.           for(let item of replaceList){
  581.             newColor = newColor.replace(item[0], item[1])
  582.           }
  583.  
  584.           return newColor
  585.         }
  586.  
  587.         newText = newText
  588.         .replace(/\(\[(\w+)\](.+?)\)/gm, ($0, $1, $2) => `<span style="color: ${parseColor($1)}">${$2}</span>`)
  589.         .replace(/\_((\w|\d|[0-9])+)\_/gm, '<ins>$1</ins>')
  590.  
  591.         markdown = markdown.replace(text[0], newText);
  592.       }
  593.      
  594.  
  595.       //variables
  596.  
  597.  
  598.       //images
  599.       if (markdown.matchAll(/!\[(.*?)\]\((.*?)\)\{(.+)?\}/gm)) {
  600.         let allImgs = [...markdown.matchAll(/!\[(.*?)\]\((.*?)\)\{(.+)?\}/gm)];
  601.  
  602.         for (img of allImgs) {
  603.           let linkMd = `
  604. ${`[${img[1]}.md](${encodeURI(img[2])})`}
  605. \`\`\`python {cmd hide output="markdown"}\n
  606. import os\n
  607. import re\n
  608. from subprocess import PIPE, run\n
  609. \n
  610. text = '''
  611. <input id="input" type="checkbox">\n
  612. <h3><strong>+Veja mais</strong></h3>\n
  613. <div class="collapse">\n
  614. &&1
  615. '''\n
  616. batcmd = r'cat "&&2"'\n
  617. def out(command):\n
  618.     result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True, check=True)\n
  619.     return result.stdout\n
  620. output = re.sub(r'\\\`{3}.+?\\\`{3}', '', out(batcmd), flags=re.DOTALL)\n
  621. output = re.sub(r'^#\\s(.+)', '\<h1\>\\g\<1\>\<\/h1\>', output, flags=re.MULTILINE)\n
  622. text = text.replace('&&1', output)\n
  623. print(text)\n
  624. \`\`\`
  625. `
  626.  
  627.           if(img[2].indexOf(".md") != -1){
  628.             linkMd = linkMd.replace('&&2', img[2].toString().replace('\\', '/'))
  629.  
  630.             markdown = markdown.replace(img[0], linkMd);
  631.             continue
  632.           }
  633.  
  634.           if(img[3].toString().length <= 0)
  635.             continue
  636.  
  637.           let isCenter = img[3].split(',').length > 1;
  638.  
  639.           let output = `<img src="${img[2]}" width="${isCenter ? img[3].split(',')[0] : img[3]}">`;
  640.  
  641.           markdown = markdown.replace(img[0], isCenter ? `<center>${output}</center>` : output);
  642.           // markdown = markdown.replace(img[0], "alan");          
  643.         }
  644.       }
  645.  
  646.       markdown = markdown.replace(/\\\(.*?\\\)/gm, ($0) => `$${$0.slice(2, -2)}$`);
  647.       // markdown = markdown.replace(/\_([^\s])+\_/gm, `<ins>$1</ins>`);
  648.      
  649.       title = '';
  650.       let match = markdown.match(/#\s(.+$)/m)
  651.      
  652.       if(markdown[0]+markdown[1] == "# " && match){
  653.         title = match[1]
  654.         title = title.replace(":", "-")
  655.         let date = new Date;
  656.         let parsedDate = date.toLocaleDateString().replace(/\//g,"-");
  657.         markdown = `---
  658. title: ${title}
  659. output:
  660.   word_document:
  661.         path: ${`${title} - (${parsedDate}) Alan José 3D.docx`}
  662. ---\n`+markdown.substr(match[0].length)
  663.  
  664.       }else if(markdown[0] != "-"){        
  665.         markdown = "---\noutput: word_document\n---\n"+markdown;
  666.       }
  667.  
  668.      
  669.      
  670.       //raw out
  671.       // markdown = `\`\`\`\n${markdown.replace(/\`/g, '\'')}`
  672.  
  673.       return resolve(markdown)
  674.       // return resolve(superRawMarkdown)
  675.     })
  676.   },
  677.   onDidParseMarkdown: function (html) {
  678.     return new Promise((resolve, reject) => {
  679.       if(title != ''){
  680.         html = `<h1>${title}</h1>`+html
  681.       }
  682.       return resolve(html)
  683.     })
  684.   }
  685. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement