+function keyval(n)
+{
+ if (n == null) return 'undefined';
+ var s= '' + n;
+ if (n >= 32 && n < 127) s+= ' (' + String.fromCharCode(n) + ')';
+ while (s.length < 9) s+= ' ';
+ return s;
+}
+
+function string_of_key(n)
+{
+ if (n == null) return 'undefined';
+ return String.fromCharCode(n);
+}
+
+function pressmesg(w,e)
+{
+ debug(w + ' keyCode=' + keyval(e.keyCode) +
+ ' which=' + keyval(e.which) +
+ ' charCode=' + keyval(e.charCode) +
+ '\n shiftKey='+e.shiftKey
+ + ' ctrlKey='+e.ctrlKey
+ + ' altKey='+e.altKey
+ + ' metaKey='+e.metaKey);
+}
+
+function suppressdefault(e,flag)
+{
+ if (flag)
+ {
+ if (e.preventDefault) e.preventDefault();
+ if (e.stopPropagation) e.stopPropagation();
+ }
+ return !flag;
+}
+
+function restoreSelection(adjust) {
+ unlocked.focus();
+ if (savedRange != null) {
+ if (window.getSelection)//non IE and there is already a selection
+ {
+ var s = window.getSelection();
+ if (s.rangeCount > 0)
+ s.removeAllRanges();
+ range = document.createRange();
+ range.setStart(savedsc,savedso + adjust);
+ range.collapse(true);
+ s.addRange(range);
+ }
+ else
+ if (document.createRange)//non IE and no selection
+ {
+ window.getSelection().addRange(savedRange);
+ }
+ else
+ if (document.selection)//IE
+ {
+ savedRange.select();
+ }
+ }
+}
+
+function lookup_tex(texmacro)
+{
+ texmacro = texmacro.substring(1);
+ return unescape(macro2utf8[texmacro]);
+}
+
+function keypress(e)
+{
+ if (!e) e= event;
+ pressmesg('keypress',e);
+ var s = string_of_key(e.charCode);
+ if (s == " ") {
+ j = getCursorPos();
+ i = unlocked.innerHTML.lastIndexOf('\\',j);
+ if (i >= 0) {
+ match = unlocked.innerHTML.substring(i,j);
+ pre = unlocked.innerHTML.substring(0,i);
+ post = unlocked.innerHTML.substring(j);
+
+ sym = lookup_tex(match);
+ if (typeof sym != "undefined") {
+ len1 = unlocked.innerText.length;
+ unlocked.innerHTML = pre + sym + post;
+ len2 = unlocked.innerText.length;
+ restoreSelection(len2 - len1);
+ return suppressdefault(e,true);
+ }
+ else {
+ // restoreSelection(0);
+ return suppressdefault(e,false);
+ }
+ }
+ else return suppressdefault(e,false);
+ } else {
+ return suppressdefault(e,false);
+ }
+}
+