# HG changeset patch # User HIROSE Yuuji # Date 1635345901 -32400 # Node ID b7f9c4ce8cbd64fe6549f9407d15e9553bdfe98c # Parent 420ad90116e661af1b85b75f009125a791235bd5 Add auto-completion of \begin\end diff -r 420ad90116e6 -r b7f9c4ce8cbd s4-main.js --- a/s4-main.js Tue Oct 26 13:16:29 2021 +0900 +++ b/s4-main.js Wed Oct 27 23:45:01 2021 +0900 @@ -616,8 +616,33 @@ e.preventDefault(); } } - function textInsert(area, pos, string) { - + function textInsert(area, string, pos1, pos2) { + console.log("str="+string); + area.setRangeText(string, pos1||area.selectionStart, + pos2||pos1||area.selectionStart); + area.selectionStart += string.length; + } + function beginningOfLine(area, pos) { + pos = pos||area.selectionStart; + let b = area.value.lastIndexOf("\n", pos); + if (pos>1 && area.value.charCodeAt(pos)==10) + b = area.value.lastIndexOf("\n", pos-1);; + return b>=0 ? b : 0; + } + function isInBeginEnd(area, pos){ + pos = pos||area.selectionStart; + let bol = beginningOfLine(area, pos); + let thisline = area.value.substr(bol); + console.log("curchar="+area.value.charCodeAt(pos)); + console.log("prechar="+area.value.charCodeAt(pos-1)); + console.log("bol="+bol+", thisline="+thisline); + let match = thisline.search(/\\(begin|end){([A-Za-z]*)/), lm, be; + if (match >= 0) { + lm = RegExp.lastMatch; + be = RegExp.$1; + return RegExp.$2 + } + return null; } function helpMarkdownBrace(e) { if (!mathjax) return; @@ -629,14 +654,32 @@ if (beg >= 0) { let env = text.substr(beg).search(/\\begin{(.*?)}/); if (env >= 0) { - let endenv = "{"+RegExp.$1+"}"; - area.setRangeText(endenv, pos, pos); - area.selectionStart += endenv.length; + textInsert(area, "{"+RegExp.$1+"}", pos); e.preventDefault(); } } } } + function helpMarkdownBraceClose(e) { + if (!mathjax) return; + let area = e.target, pos = area.selectionStart, text = area.value, + begin = "\\begin", end = "\\end"; + if (text.substr(pos).startsWith("}")) { + area.setRangeText("", pos, pos+1); + // e.preventDefault(); + } + let inbegend = isInBeginEnd(area, pos); + let nextendpos = text.substr(pos).indexOf("\\end{"); + let nextcurend = text.substr(pos).indexOf("\\end{"+inbegend+"}"); + console.log("ib="+inbegend+", nepos="+nextendpos+", ncur="+nextcurend); + if (nextcurend<0 || nextendpos!=nextcurend) { + area.setRangeText("}\n\n\\end{"+inbegend+"}", pos, pos); + area.selectionStart = pos+2; + e.preventDefault(); + } + console.log(inbegend); + + } function helpMarkdownPreview(area) { if (!mathjax) { alert("no"+e.target) @@ -677,6 +720,7 @@ case "(": helpMarkdownParen(e); break; case "p": if (e.metaKey) helpMarkdownPreview(e.target); break; case "{": helpMarkdownBrace(e); break; + case "}": helpMarkdownBraceClose(e); break; } } /* Init event listeners */