changeset 947:b7f9c4ce8cbd draft

Add auto-completion of \begin\end
author HIROSE Yuuji <yuuji@gentei.org>
date Wed, 27 Oct 2021 23:45:01 +0900
parents 420ad90116e6
children 1310b29b6ab1
files s4-main.js
diffstat 1 files changed, 49 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- 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 */

yatex.org