codemirror

            function _set(k) {
                let pos1 = editor.getCursor(); // { line: Infinity }
                if (k == "h1") {
                    editor.replaceRange("# ", pos1);
                }

                if (k == "h2") {
                    editor.replaceRange("## ", pos1);
                }

                if (k == "h3") {
                    editor.replaceRange("### ", pos1);
                }
                render();
            }

            function _setnum(num) {
                let pos1 = editor.getCursor();
                editor.replaceRange(num, pos1);
                render();
            }



            function _setlink() {
                let pos1 = editor.getCursor();
                editor.replaceRange("[text](url)", pos1);
                render();
            }
            function _setimg() {
                let pos1 = editor.getCursor();
                editor.replaceRange("![img-text](img-url)", pos1);
                render();
            }





            function _setbold() {
                let pos1 = editor.getCursor();
                var old = editor.getSelection();
                editor.replaceSelection("**" + old + "**");
                render();
            }

            function _setita() {
                let pos1 = editor.getCursor();
                var old = editor.getSelection();
                editor.replaceSelection("*" + old + "*");
                render();
            }


            function _setref(k) {
                let pos1 = editor.getCursor();
                editor.replaceRange("> ", pos1);
                render();
            }



            function _setinlinecode() {
                let pos1 = editor.getCursor();
                var old = editor.getSelection();
                editor.replaceSelection("`" + old + "`");
                render();
            }



            function _setblockcode() {
                let pos1 = editor.getCursor();
                var old = editor.getSelection();
                editor.replaceSelection("``` \n" + old + "\n```");
                render();
            }





            function _setunorderlist() {
                let pos1 = editor.getCursor();
                editor.replaceRange("\n* item 1  \n* item 2 \n* item 3", pos1);
                render();
            }

            function _setorderlist() {
                let pos1 = editor.getCursor();
                editor.replaceRange("\n1. item 1  \n2. item 2 \n3. item 3", pos1);
                render();
            }




        </script>




        <script>







            const lute = Lute.New();
            lute.SetInlineMathAllowDigitAfterOpenMarker(true);


            var editor = CodeMirror.fromTextArea(document.getElementById("txt_init"), {
                mode: "text/x-markdown",
                lineNumbers: true,
                width: "100%",
                height: "600px",
                autoCloseBrackets: true,
                matchBrackets: true,
                lineWrapping: true,
                inMathMode: true,
                extraKeys: {
                    "Ctrl-J": "autocomplete"
                }
            });

            CodeMirror.registerHelper("hint", "stex", (cm) => LaTeXHint(cm, MACROS));





            var scrollContainer = document.querySelector('.CodeMirror-scroll');
            var ShowContainer = document.getElementById("preview");







            var timer;


            editor.on("change", function (_cm, changeObj) {

                timer = setTimeout(function () {
                    clearTimeout(timer);
                    render();
                    timer = null;
                }, 1000);

            });


          
             
            function findAllOccurrences(str, charToFind) {
                let indices = [];
                let index = str.indexOf(charToFind);

                while (index > -1) {
                    indices.push(index);
                    index = str.indexOf(charToFind, index + 1);
                }

                return indices;
            }

            function render() {
                 
                if (timer === null) {
                    return;
                } 

                document.getElementById('preview').innerHTML = "";

                var text = editor.getValue();
                var gs2 = []; 
                var reg = /(\$\$([\s\S]*?)\$\$)|(\$([\s\S]*?)\$)/igm; 
                text = text.replace(reg, function (a, b,idx1) {
                    gs2.push({ a: a, b: b, idx1: idx1 }); 
                    return "▒";
                });
                 

                var txts = text.split('\n');   

                var total = 0;
                var IDX = 0;
                for (var txt of txts) {

                    var poss = findAllOccurrences(txt, "▒"); 
                    total += poss.length;   
                    if (poss.length!= 0) {
                        var subs = txt.split('▒');
                        var subr2 = "";
                        var sublength = subs.length;
                        for (var j = 0; j < subs.length-1; j++) { 
                            subr2 += subs[j] + gs2[total-sublength+j+1].a;
                        }
                        txt = subr2 ;
                    } 
                     
                    IDX = IDX + 1;
                    const result = lute.MarkdownStr("", txt);
                    document.getElementById('preview').innerHTML += "<span data-index="+IDX+">"+result+"</span>";

                }



             



                $("#preview .language-math").each(function () {
                    var tex = $(this);
                    var input = $(tex).text();


                    var output = tex[0];
                    output.innerHTML = ''
                    MathJax.texReset();
                    var options = MathJax.getMetricsFor(output);
                    options.display = false;

                    MathJax.tex2svgPromise(input, options).then(function (node) {
                        output.appendChild(node);
                        MathJax.startup.document.clear();
                        MathJax.startup.document.updateDocument();
                    }).catch(function (err) {

                        output.appendChild(document.createElement('pre')).appendChild(document.createTextNode(err.message));
                    }).then(function () {

                    });

                });

                $("#preview img").each(function () {
                    let imgElement = this;




                    let next = imgElement.nextSibling;

                    if (next != null) {
                        let hello = next.textContent;

                        var start = hello.indexOf("{")
                        var end = hello.indexOf("}")
                        var width = "0";
                        if (start == 0 && end > 0) {
                            var sub = hello.substring(start + 1, end);
                            width = sub.split('=')[1].trim();
                            imgElement.setAttribute("width", width);
                            //REMOVE START
                            let next2 = next.nextSibling;
                            if (next2 != null) {
                                next.remove();
                            } else {
                                next.remove();
                                var remain = hello.substring(end + 1);
                                imgElement.after(remain);
                            }
                            // REMOVE END
                        }
                    }
                });



                //const dom = ShowContainer.querySelector(`[data-index="${index}"]`)
                //if (dom != null) {
                //    dom.scrollIntoView();
                //}
            }
posted @ 2024-09-25 11:52  启明星工作室  阅读(35)  评论(0)    收藏  举报