1 // -* coding: utf-8; -*
6 UnknownError: "unknown-error",
7 WrongArgument: "wrong-argument",
9 InvalidInteger: "invalid-integer",
10 TermTypeInvalid: "term-type-invalid",
11 FunctionConflict: "function-conflict",
12 VariableTypeConflict: "variable-type-conflict",
13 VariableRangeConflict: "variable-range-conflict",
14 VariableWrongRange: "variable-wrong-range",
15 VariableWrongValue: "variable-wrong-value",
17 UnknownFunction: "unknown-function",
18 MacroExpansionError: "macro-expansion-error",
19 NoVariableName: "no-variable-name",
20 NoFunctionName: "no-funcion-name",
23 ArithmeticError: "arithmetic-error",
24 WrongType: "wrong-type",
25 IndexOutOfRange: "index-out-of-range",
26 ValueOutOfRange: "value-out-of-range",
27 NoLoopToBreak: "no-loop-to-break",
28 UncaughtThrow: "uncaught-throw"
31 Xex.Variable = function (domain, name, desc, val, range)
40 Xex.Variable.prototype.clone = function ()
42 return new Xex.Variable (this.domain, this.name, this.desc,
43 this.val, this.range);
46 Xex.Variable.prototype.Equals = function (obj)
48 return ((obj instanceof Xex.Variable)
49 && obj.name == this.name);
52 Xex.Variable.prototype.SetValue = function (term)
58 Xex.Function = function (name, with_var, min_args, max_args)
61 this.with_var = with_var;
62 this.min_args = min_args;
63 this.max_args = max_args;
66 Xex.Subrountine = function (builtin, name, with_var, min_args, max_args)
69 this.with_var = with_var;
70 this.min_args = min_args;
71 this.max_args = max_args;
72 this.builtin = builtin;
75 Xex.Subrountine.prototype.Call = function (domain, vari, args)
77 newargs = new Array ();
78 for (var i = 0; i < args.length; i++)
80 newargs[i] = args[i].Eval (domain);
84 return this.builtin (domain, vari, newargs)
87 Xex.SpecialForm = function (builtin, name, with_var, min_args, max_args)
90 this.with_var = with_var;
91 this.min_args = min_args;
92 this.max_args = max_args;
93 this.builtin = builtin;
96 Xex.SpecialForm.prototype.Call = function (domain, vari, args)
98 return this.builtin (domain, vari, args)
101 Xex.Lambda = function (name, min_args, max_args, args, body)
104 this.min_args = min_args;
105 this.max_args = max_args;
110 Xex.Lambda.prototype.Call = function (domain, vari, args)
112 var current = domain.bindings;
113 var result = Xex.Zero;
114 var limit = max_args >= 0 ? args.length : args.length - 1;
118 for (i = 0; i < limit; i++)
120 result = args[i].Eval (domain);
121 if (domain.Thrown ())
123 domain.Bind (this.args[i], result);
127 var list = new Array ();
128 for (i = 0; i < args[limit].length; i++)
130 result = args[limit].Eval (domain);
131 if (domain.Thrown ())
135 domain.Bind (this.args[limit], list);
138 domain.Catch (Xex.CatchTag.Return);
139 for (var term in this.body)
141 result = term.Eval (domain);
142 if (domain.Thrown ())
149 domain.UnboundTo (current);
154 Xex.Macro = function (name, min_args, max_args, args, body)
157 this.min_args = min_args;
158 this.max_args = max_args;
163 Xex.Macro.prototype.Call = function (domain, vari, args)
165 var current = domain.bindings;
166 var result = Xex.Zero;
170 for (i = 0; i < args.length; i++)
171 domain.Bind (this.args[i], args[i]);
173 domain.Catch (Xex.CatchTag.Return);
174 for (var term in body)
176 result = term.Eval (domain);
177 if (domain.Thrown ())
184 domain.UnboundTo (current);
189 Xex.Bindings = function (vari)
192 this.old_value = vari.val;
195 Xex.Bindings.prototype.UnboundTo = function (boundary)
197 for (var b = this; b != boundary; b = b.next)
198 b.vari.val = b.old_value;
202 Xex.Bind = function (bindings, vari, val)
204 var b = new Xex.Bindings (vari);
215 Xex.Domain = function (name, parent, context)
218 this.context = context;
221 if (name != 'basic' && ! parent)
222 parent = Xex.BasicDomain
223 this.parent = parent;
230 for (elt in parent.termtypes)
231 this.termtypes[elt] = parent.termtypes[elt];
232 for (elt in parent.functions)
233 this.functions[elt] = parent.functions[elt];
234 for (elt in parent.variables)
235 this.variables[elt] = parent.variables[elt];
238 this.call_stack = new Array ();
239 this.bindings = null;
240 this.catch_stack = new Array ();
241 this.catch_count = 0;
245 Xex.Domain.prototype = {
246 CallStackCount: function () { return this.call_stack.length; },
247 CallStackPush: function (term) { this.call_stack.push (term); },
248 CallStackPop: function () { this.call_stack.pop (); },
249 Bind: function (vari, val)
251 this.bindings = Xex.Bind (this.bindings, vari, val);
253 UnboundTo: function (boundary)
256 this.bindings = this.bindings.UnboundTo (boundary);
258 Catch: function (tag) { this.catch_stack.push (tag); this.catch_count++; },
261 this.catch_stack.pop ();
262 if (this.catch_count > this.catch_stack.length)
267 if (this.catch_count < this.catch_stack.length)
269 this.caught = (this.catch_count == this.catch_stack.length - 1);
275 ThrowReturn: function ()
277 for (var i = this.catch_stack.length - 1; i >= 0; i--)
280 if (this.catch_stack[i] == Xex.CatchTag.Return)
284 ThrowBreak: function ()
286 if (this.catch_stack[this.catch_stack.length - 1] != Xex.CatchTag.Break)
287 throw new Xex.ErrTerm (Xex.Error.NoLoopToBreak,
288 "No surrounding loop to break");
291 ThrowSymbol: function (tag)
293 var i = this.catch_count;
294 for (var j = this.catch_stack.length - 1; j >= 0; j--)
297 if (Xex.CatchTag.Matches (this.catch_stack[i], tag))
299 this.catch_count = i;
303 throw new Xex.ErrTerm (Xex.Error.UncaughtThrow,
304 "No corresponding catch: " + tag);
306 DefType: function (obj)
309 if (this.termtypes[type])
310 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
311 "Already defined: " + type);
312 if (this.functions[type])
313 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
314 "Already defined as a funciton or a macro: "
316 this.termtypes[type] = obj.Parser;
318 DefSubr: function (builtin, name, with_var, min_args, max_args)
320 this.functions[name] = new Xex.Subrountine (builtin, name, with_var,
323 DefSpecial: function (builtin, name, with_var, min_args, max_args)
325 this.functions[name] = new Xex.SpecialForm (builtin, name, with_var,
328 Defun: function (name, min_args, max_args, args, body)
330 this.functions[name] = new Xex.Lambda (name, min_args, max_args,
333 DefunByFunc: function (func) { this.functions[func.name] = func; },
334 Defmacro: function (name, min_args, max_args, args, body)
336 this.functions[name] = new Xex.Macro (name, min_args, max_args,
339 DefAlias: function (alias, fname)
341 var func = this.functions[fname];
344 throw new Xex.ErrTerm (Xex.Error.UnknownFunction, fname);
345 if (this.termtypes[alias])
346 throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
347 "Already defined as a term type: " + alias);
348 if (this.functions[alias])
349 throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
350 "Already defined as a function: " + alias);
351 this.functions[alias] = func;
353 Defvar: function (name, desc, val, range)
355 var vari = new Xex.Variable (this, name, desc, val, range);
356 this.variables[name] = vari;
359 GetFunc: function (name)
361 var func = this.functions[name];
363 throw new Xex.ErrTerm (Xex.Error.UnknownFunction,
364 "Unknown function: " + name);
367 CopyFunc: function (domain, name)
369 var func = this.functions[name];
370 domain.DefunByFunc (func);
373 CopyFuncAll: function (domain)
375 for (var elt in this.functions)
376 domain.DefunByFunc (this.functions[elt]);
378 GetVarCreate: function (name)
380 var vari = this.variables[name];
382 vari = this.variables[name] = new Xex.Variable (this, name, null,
386 GetVar: function (name) { return this.variables[name]; },
387 SaveValues: function ()
390 for (var elt in this.variables)
392 //if (! this.variables[elt].val)
393 //alert ('unknown value of ' + elt);
395 values[elt] = this.variables[elt].val.Clone ();
399 RestoreValues: function (values)
404 var vari = this.variables[name];
405 vari.val = values[name];
409 Trace: function () {}
412 Xex.Term = function (type) { this.type = type; }
413 Xex.Term.prototype = {
414 IsTrue: function () { return true; },
415 Eval: function (domain) { return this.Clone (); },
416 Clone: function (domain) { return this; },
417 Equals: function (obj)
419 return (this.type == obj.type
421 && obj.val == this.val);
423 Matches: function (obj) { return this.Equals (obj); },
424 toString: function ()
426 if (this.val != undefined)
427 return '<' + this.type + '>' + this.val + '</' + this.type + '>';
428 return '<' + this.type + '/>';
430 Intval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
431 "Not an integer"); },
432 Strval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
436 Node.prototype.firstElement = function ()
438 for (var n = this.firstChild; n; n = n.nextSibling)
444 Node.prototype.nextElement = function ()
446 for (var n = this.nextSibling; n; n = n.nextSibling)
453 function parse_defvar (domain, node)
455 var name = node.attributes['vname'].nodeValue;
457 throw new Xex.ErrTerm (Xex.Error.NoVariableName, node, '');
458 var vari = domain.variables[name];
459 var desc, val, range;
462 desc = vari.description;
466 node = node.firstElement ();
467 if (node && node.nodeName == 'description')
469 desc = node.firstChild.nodeValue;
470 node = node.nextElement ();
474 val = Xex.Term.Parse (domain, node);
475 node = node.nextElement ();
476 if (node && node.nodeName == 'possible-values')
477 for (node = node.firstElement (); node; node = node.nextElement ())
480 if (node.nodeName == 'range')
483 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
484 'Range not allowed for ' + name);
486 for (var n = node.firstElement (); n; n = n.nextElement ())
488 var v = Xex.Term.Parse (domain, n);
490 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
491 'Invalid range value: ' + val);
497 pval = Xex.Term.Parse (domain, node);
498 if (val.type != pval.type)
499 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
500 'Invalid possible value: ' + pval);
503 range = new Array ();
509 domain.Defvar (name, desc, val, range);
513 function parse_defun_head (domain, node)
515 var name = node.attributes['fname'].nodeValue;
517 throw new Xex.ErrTerm (Xex.Error.NoFunctionName, node, '');
518 var args = new Array ();
519 var nfixed = 0, noptional = 0, nrest = 0;
521 node = node.firstElement ();
522 if (node && node.nodeName == 'args')
525 for (n = n.firstElement (); n; n = n.nextElement ())
527 if (n.nodeName == 'fixed')
529 else if (n.nodeName == 'optional')
531 else if (n.nodeName == 'rest')
534 throw new Xex.ErrTerm (Xex.Error.WrongType, n, n.nodeName);
537 throw new Xex.ErrTerm (Xex.Error.WrongType, n, 'Too many <rest>');
538 for (n = node.firstElement (); n; n = n.nextElement ())
539 args.push (domain.DefVar (n.attributes['vname'].nodeValue));
541 args.min_args = nfixed;
542 args.max_args = nrest == 0 ? nfixed + noptional : -1;
544 if (node.nodeName == 'defun')
545 domain.Defun (name, args, null);
547 domain.Defmacro (name, args, null);
551 function parse_defun_body (domain, node)
553 var name = node.attributes['fname'].nodeValue;
554 var func = domain.GetFunc (name);
556 for (node = node.firstElement (); node; node = node.nextElement ())
557 if (node.nodeName != 'description' && node.nodeName != 'args')
559 body = Xex.Term.Parse (domain, node, null);
563 Xex.Term.Parse = function (domain, node, stop)
565 if (arguments.length == 2)
567 var name = node.nodeName;
568 var parser = domain.termtypes[name];
571 return parser (domain, node);
572 if (name == 'defun' || name == 'defmacro')
574 name = parse_defun_head (domain, node);
575 parse_defun_body (domain, node);
576 return new Xex.StrTerm (name);
578 if (name == 'defvar')
580 name = parse_defvar (domain, node);
581 return new Xex.StrTerm (name);
583 return new Xex.Funcall.prototype.Parser (domain, node);
585 for (var n = node; n && n != stop; n = n.nextElement ())
586 if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
587 parse_defun_head (domain, n);
589 for (var n = node; n && n != stop; n = n.nextElement ())
591 if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
592 parse_defun_body (domain, n);
593 else if (n.nodeName == 'defvar')
594 parse_defvar (domain, n);
598 terms = new Array ();
599 terms.push (Xex.Term.Parse (domain, n));
606 Xex.Varref = function (vname)
612 var proto = new Xex.Term ('varref');
614 proto.Clone = function () { return new Xex.Varref (this.val); }
615 proto.Eval = function (domain)
617 if (! this.vari || this.vari.domain != domain)
618 this.vari = domain.GetVarCreate (this.val);
619 return this.vari.val;
622 proto.Parser = function (domain, node)
624 return new Xex.Varref (node.attributes['vname'].nodeValue);
627 Xex.Varref.prototype = proto;
630 var null_args = new Array ();
632 Xex.Funcall = function (func, vari, args)
636 this.args = args || null_args;
640 var proto = new Xex.Term ('funcall');
642 proto.Parser = function (domain, node)
644 var fname = node.nodeName;
647 if (fname == 'funcall')
648 fname = node.attributes['fname'].nodeValue;
649 var func = domain.GetFunc (fname);
651 attr = node.attributes['vname'];
652 vari = attr != undefined ? domain.GetVarCreate (attr.nodeValue) : false;
653 var args = Xex.Term.Parse (domain, node.firstElement (), null);
654 return new Xex.Funcall (func, vari, args);
657 proto.New = function (domain, fname, vname, args)
659 var func = domain.GetFunc (fname);
660 var vari = vname ? domain.GetVarCreate (vname) : null;
661 var funcall = new Xex.Funcall (func, vari, args);
662 if (func instanceof Xex.Macro)
663 funcall = funcall.Eval (domain);
667 proto.Eval = function (domain)
672 var result = this.func.Call (domain, this.vari, this.args);
675 domain.Trace (' => ' + result + "\n");
680 proto.Clone = function ()
682 return new Xex.Funcall (this.func, this.vari, this.args);
685 proto.Equals = function (obj)
687 return (obj.type == 'funcall'
688 && obj.func == this.func
689 && obj.vari.Equals (this.vari)
690 && obj.args.length == this.func.length);
693 proto.toString = function ()
696 var len = this.args.length;
698 return '<' + this.func.name + '/>';
699 for (var i = 0; i < len; i++)
700 arglist += this.args[i].toString ();
701 return '<' + this.func.name + '>' + arglist + '</' + this.func.name + '>';
704 Xex.Funcall.prototype = proto;
707 Xex.ErrTerm = function (ename, message, stack)
710 this.message = message;
715 var proto = new Xex.Term ('error');
717 proto.IsError = true;
719 proto.Parser = function (domain, node)
721 return new Xex.ErrTerm (node.attributes['ename'].nodeValue,
722 node.innerText, false);
725 proto.CallStack = function () { return stack; }
727 proto.SetCallStack = function (value) { statck = value; }
729 proto.Clone = function ()
731 return new Xex.ErrTerm (ename, message, false);
734 proto.Equals = function (obj)
737 && obj.ename == ename && obj.message == message
738 && (obj.stack ? (stack && stack.length == obj.stack.length)
742 proto.Matches = function (obj)
744 return (obj.IsError && obj.ename == ename);
747 proto.toString = function ()
749 return '<error ename="' + this.ename + '">' + this.message + '</error>';
752 Xex.ErrTerm.prototype = proto;
755 Xex.IntTerm = function (num) { this.val = num; };
757 var proto = new Xex.Term ('integer');
759 proto.Intval = function () { return this.val; };
760 proto.IsTrue = function () { return this.val != 0; }
761 proto.Clone = function () { return new Xex.IntTerm (this.val); }
762 proto.Parser = function (domain, node)
764 var str = node.firstChild.nodeValue;
766 if (str.charAt (0) == '?' && str.length == 2)
767 return new Xex.IntTerm (str.charCodeAt (1));
768 return new Xex.IntTerm (parseInt (node.firstChild.nodeValue));
770 Xex.IntTerm.prototype = proto;
773 Xex.StrTerm = function (str) { this.val = str; };
775 var proto = new Xex.Term ('string');
777 proto.Strval = function () { return this.val; };
778 proto.IsTrue = function () { return this.val.length > 0; }
779 proto.Clone = function () { return new Xex.StrTerm (this.val); }
780 proto.Parser = function (domain, node)
782 return new Xex.StrTerm (node.firstChild.nodeValue);
784 Xex.StrTerm.prototype = proto;
787 Xex.SymTerm = function (str) { this.val = str; };
789 var proto = new Xex.Term ('symbol');
790 proto.IsSymbol = true;
791 proto.IsTrue = function () { return this.val != 'nil'; }
792 proto.Clone = function () { return new Xex.SymTerm (this.val); }
793 proto.Parser = function (domain, node)
795 return new Xex.SymTerm (node.firstChild.nodeValue);
797 Xex.SymTerm.prototype = proto;
800 Xex.LstTerm = function (list) { this.val = list; };
802 var proto = new Xex.Term ('list');
804 proto.IsTrue = function () { return this.val.length > 0; }
805 proto.Clone = function () { return new Xex.LstTerm (this.val.slice (0)); }
807 proto.Equals = function (obj)
809 if (obj.type != 'list' || obj.val.length != this.val.length)
811 var i, len = this.val.length;
812 for (i = 0; i < len; i++)
813 if (! this.val[i].Equals (obj.val[i]))
818 proto.Parser = function (domain, node)
820 var list = Xex.Term.Parse (domain, node.firstElement (), null);
821 return new Xex.LstTerm (list);
824 proto.toString = function ()
826 var len = this.val.length;
831 for (var i = 0; i < len; i++)
832 str += this.val[i].toString ();
833 return str + '</list>';
835 Xex.LstTerm.prototype = proto;
839 var basic = new Xex.Domain ('basic', null, null);
841 function Fset (domain, vari, args)
843 return vari.SetValue (args[0]);
846 function maybe_set_intvar (vari, n)
848 var term = new Xex.IntTerm (n);
850 vari.SetValue (term);
854 function Fset (domain, vari, args)
857 throw new Xex.ErrTerm (Xex.Error.NoVariableName,
858 'No variable name to set');
859 vari.SetValue (args[0]);
863 function maybe_set_intvar (vari, n)
865 var term = new IntTerm (n);
867 vari.SetValue (term);
871 function Fadd (domain, vari, args)
873 var n = vari ? vari.val.Intval () : 0;
874 var len = args.length;
876 for (var i = 0; i < len; i++)
877 n += args[i].Intval ();
878 return maybe_set_intvar (vari, n);
881 function Fmul (domain, vari, args)
883 var n = vari ? vari.val.Intval () : 1;
884 for (var i = 0; i < args.length; i++)
886 return maybe_set_intvar (vari, n);
889 function Fsub (domain, vari, args)
895 n = args[0].Intval ();
900 n = vari.val.Intval ();
903 while (i < args.length)
904 n -= args[i++].Intval ();
905 return maybe_set_intvar (vari, n);
908 function Fdiv (domain, vari, args)
914 n = args[0].Intval ();
919 n = vari.val.Intval ();
922 while (i < args.length)
923 n /= args[i++].Intval ();
924 return maybe_set_intvar (vari, n);
927 function Fmod (domain, vari, args)
929 return maybe_set_intvar (vari, args[0].Intval () % args[1].Intval ());
932 function Flogior (domain, vari, args)
934 var n = vari == null ? 0 : vari.val;
935 for (var i = 0; i < args.length; i++)
937 return maybe_set_intvar (vari, n);
940 function Fand (domain, vari, args)
942 var len = args.length;
943 for (var i = 0; i < len; i++)
945 var result = args[i].Eval (domain);
946 if (domain.Thrown ())
948 if (! result.IsTrue ())
954 function For (domain, vari, args)
956 var len = args.length;
957 for (var i = 0; i < len; i++)
959 var result = args[i].Eval (domain);
960 if (domain.Thrown ())
962 if (result.IsTrue ())
968 function Feq (domain, vari, args)
970 for (var i = 1; i < args.length; i++)
971 if (! args[i - 1].Equals (args[i]))
976 function Flt (domain, vari, args)
978 var n = args[0].Intval;
980 for (var i = 1; i < args.length; i++)
982 var n1 = args[i].Intval;
990 function Fle (domain, vari, args)
992 var n = args[0].Intval;
993 for (var i = 1; i < args.length; i++)
995 var n1 = args[i].Intval;
1003 function Fgt (domain, vari, args)
1005 var n = args[0].Intval;
1006 for (var i = 1; i < args.length; i++)
1008 var n1 = args[i].Intval;
1016 function Fge (domain, vari, args)
1018 var n = args[0].Intval;
1019 for (var i = 1; i < args.Length; i++)
1021 var n1 = args[i].Intval;
1029 function Fprogn (domain, vari, args)
1031 var result = Xex.One;
1032 var len = args.length;
1034 for (var i = 0; i < len; i++)
1036 result = args[i].Eval (domain);
1037 if (domain.Thrown ())
1043 function Fif (domain, vari, args)
1045 var result = args[0].Eval (domain);
1047 if (domain.Thrown ())
1049 if (result.IsTrue ())
1050 return args[1].Eval (domain);
1051 if (args.length == 2)
1053 return args[2].Eval (domain);
1056 function Fcond (domain, vari, args)
1058 for (var i = 0; i < args.length; i++)
1060 var list = args[i].val;
1061 var result = list.val[0].Eval (doamin);
1062 if (result.isTrue ())
1064 for (var j = 1; j < list.val.length; j++)
1067 result = list.val[j].Eval (domain);
1069 if (domain.Thrown ())
1078 function eval_terms (domain, terms, idx)
1080 var result = Xex.Zero;
1081 domain.caught = false;
1082 for (var i = idx; i < terms.length; i++)
1084 result = terms[i].Eval (domain);
1085 if (domain.Thrown ())
1091 function Fcatch (domain, vari, args)
1096 if (args[0].IsError)
1099 result = eval_terms (domain, args, 1);
1101 if (e instanceof Xex.ErrTerm)
1103 if (! args[0].Matches (e))
1111 else if (args[0].IsSymbol)
1114 domain.Catch (args[0].val);
1115 result = eval_terms (domain, args, 1);
1119 vari.SetValue (result);
1127 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1128 "Not a symbol nor an error: " + args[0]);
1131 function Fthrow (domain, vari, args)
1133 if (args[0].IsSymbl)
1135 domain.ThrowSymbol (args[0]);
1136 return (args[args.length - 1]);
1138 if (args[0].IsError)
1142 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1143 "Not a symbol nor an error:" + args[0]);
1146 Xex.BasicDomain = basic;
1148 basic.DefSubr (Fset, "set", true, 1, 1);
1149 if (basic.functions['='])
1150 alert (basic.functions['=']);
1151 basic.DefAlias ("=", "set");
1152 //basic.DefSubr (Fnot, "not", false, 1, 1);
1153 //basic.DefAlias ("!", "not");
1154 basic.DefSubr (Fadd, "add", true, 1, -1);
1155 basic.DefSubr (Fmul, "mul", true, 1, -1);
1156 basic.DefAlias ("*", "mul");
1157 basic.DefSubr (Fsub, "sub", true, 1, -1);
1158 basic.DefAlias ("-", "sub");
1159 basic.DefSubr (Fdiv, "div", true, 1, -1);
1160 basic.DefAlias ("/", "div");
1161 basic.DefSubr (Fmod, "mod", true, 1, 2);
1162 basic.DefAlias ("%", "mod");
1163 basic.DefSubr (Flogior, "logior", true, 1, -1);
1164 basic.DefAlias ('|', "logior");
1165 //basic.DefSubr (Flogand, "logand", true, 1, -1);
1166 //basic.DefAlias ("&", "logand");
1167 //basic.DefSubr (Flsh, "lsh", true, 1, 2);
1168 //basic.DefAlias ("<<", "lsh");
1169 //basic.DefSubr (Frsh, "rsh", true, 1, 2);
1170 //basic.DefAlias (">>", "rsh");
1171 basic.DefSubr (Feq, "eq", false, 2, -1);
1172 basic.DefAlias ("==", "eq");
1173 //basic.DefSubr (Fnoteq, "noteq", false, 2, 2);
1174 //basic.DefAlias ("!=", "noteq");
1175 basic.DefSubr (Flt, "lt", false, 2, -1);
1176 basic.DefAlias ("<", "lt");
1177 basic.DefSubr (Fle, "le", false, 2, -1);
1178 basic.DefAlias ("<=", "le");
1179 basic.DefSubr (Fgt, "gt", false, 2, -1);
1180 basic.DefAlias (">", "gt");
1181 basic.DefSubr (Fge, "ge", false, 2, -1);
1182 basic.DefAlias (">=", "ge");
1183 basic.DefSubr (Fthrow, "throw", false, 1, 2);
1185 //basic.DefSubr (Fappend, "append", true, 0, -1);
1186 //basic.DefSubr (Fconcat, "concat", true, 0, -1);
1187 //basic.DefSubr (Fnth, "nth", false, 2, 2);
1188 //basic.DefSubr (Fcopy, "copy", false, 1, 1);
1189 //basic.DefSubr (Fins, "ins", true, 2, 2);
1190 //basic.DefSubr (Fdel, "del", true, 2, 2);
1191 //basic.DefSubr (Feval, "eval", false, 1, 1);
1192 //basic.DefSubr (Fbreak, "break", false, 0, 1);
1193 //basic.DefSubr (Freturn, "return", false, 0, 1);
1194 //basic.DefSubr (Fthrow, "throw", false, 1, 2);
1196 basic.DefSpecial (Fand, "and", false, 1, -1);
1197 basic.DefAlias ("&&", "and");
1198 basic.DefSpecial (For, "or", false, 1, -1);
1199 basic.DefAlias ("||", "or");
1200 basic.DefSpecial (Fprogn, "progn", false, 1, -1);
1201 basic.DefAlias ("expr", "progn");
1202 basic.DefSpecial (Fif, "if", false, 2, 3);
1203 //basic.DefSpecial (Fwhen, "when", false, 1, -1);
1204 //basic.DefSpecial (Floop, "loop", false, 1, -1);
1205 //basic.DefSpecial (Fwhile, "while", false, 1, -1);
1206 basic.DefSpecial (Fcond, "cond", false, 1, -1);
1207 //basic.DefSpecial (Fforeach, "foreach", true, 2, -1);
1208 //basic.DefSpecial (Fquote, "quote", false, 1, 1);
1209 //basic.DefSpecial (Ftype, "type", false, 1, 1);
1210 basic.DefSpecial (Fcatch, "catch", true, 2, -1);
1212 basic.DefType (Xex.Funcall.prototype);
1213 basic.DefType (Xex.Varref.prototype);
1214 basic.DefType (Xex.ErrTerm.prototype);
1215 basic.DefType (Xex.IntTerm.prototype);
1216 basic.DefType (Xex.StrTerm.prototype);
1217 basic.DefType (Xex.SymTerm.prototype);
1218 basic.DefType (Xex.LstTerm.prototype);
1222 Xex.Zero = new Xex.IntTerm (0);
1223 Xex.One = new Xex.IntTerm (1);
1224 Xex.nil = new Xex.SymTerm ('nil');
1226 Xex.Load = function (server, file)
1228 var obj = new XMLHttpRequest ();
1229 var url = server ? server + '/' + file : file;
1230 obj.open ('GET', url, false);
1231 obj.overrideMimeType ('text/xml');
1233 return obj.responseXML.firstChild;
1237 // URL of the input method server.
1238 server: "http://www.m17n.org/common/mim-js",
1239 // Boolean flag to tell if MIM is active or not.
1241 // Boolean flag to tell if MIM is running in debug mode or not.
1243 // List of main input methods.
1245 // List of extra input methods;
1247 // Global input method data
1249 // Currently selected input method.
1253 LoadStatus: { NotLoaded:0, Loading:1, Loaded:2, Error:-1 },
1260 CandidateIndex:0x10,
1262 Preedit: 0x06, // PreeditText | CursorPos
1263 Candidate: 0x38 // CandidateList | CandidateIndex | CandidateShow
1285 ParseError: "parse-error"
1290 var keysyms = new Array ();
1291 keysyms["bs"] = "backspace";
1292 keysyms["lf"] = "linefeed";
1293 keysyms["cr"] = keysyms["enter"] = "return";
1294 keysyms["esc"] = "escape";
1295 keysyms["spc"] = "space";
1296 keysyms["del"] = "delete";
1298 function decode_keysym (str) {
1299 var parts = str.split ("-");
1300 var len = parts.length, i;
1301 var has_modifier = len > 1;
1303 for (i = 0; i < len - 1; i++)
1304 if (! MIM.KeyModifier.hasOwnProperty (parts[i]))
1306 var key = parts[len - 1];
1309 key = keysyms[key.toLowerCase ()];
1315 for (i = 1; i < len - 1; i++)
1316 str += '-' + parts[i];
1325 parts = new Array ();
1332 MIM.Key = function (val)
1335 this.has_modifier = false;
1336 if (typeof val == 'string' || val instanceof String)
1338 this.key = decode_keysym (val);
1340 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1341 if (this.key instanceof Array)
1343 this.key = this.key[0];
1344 this.has_modifier = true;
1347 else if (typeof val == 'number' || val instanceof Number)
1348 this.key = String.fromCharCode (val);
1350 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1353 MIM.Key.prototype.toString = function () { return this.key; };
1357 MIM.KeySeq = function (seq)
1359 this.val = new Array ();
1360 this.has_modifier = false;
1366 var len = seq.val.length;
1367 for (var i = 0; i < len; i++)
1370 if (v.type != 'string' && v.type != 'integer'
1371 && v.type != 'symbol')
1372 throw new Xex.ErrTerm (MIM.Error.ParseError,
1373 "Invalid key: " + v);
1374 var key = new MIM.Key (v.val);
1375 this.val.push (key);
1376 if (key.has_modifier)
1377 this.has_modifier = true;
1382 var len = seq.val.length;
1383 for (var i = 0; i < len; i++)
1384 this.val.push (new MIM.Key (seq.val.charCodeAt (i)));
1387 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + seq);
1391 var proto = new Xex.Term ('keyseq');
1392 proto.Clone = function () { return this; }
1393 proto.Parser = function (domain, node)
1395 var seq = new Array ();
1396 for (node = node.firstChild; node; node = node.nextSibling)
1397 if (node.nodeType == 1)
1399 var term = Xex.Term.Parse (domain, node);
1400 return new MIM.KeySeq (term);
1402 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid keyseq");
1404 proto.toString = function ()
1406 var len = this.val.length;
1410 var str = '<keyseq>';
1411 for (var i = 0; i < len; i++)
1415 else if (this.has_modifier)
1417 str += this.val[i].toString ();
1419 return str + '</keyseq>';
1422 MIM.KeySeq.prototype = proto;
1426 MIM.Marker = function () { }
1427 MIM.Marker.prototype = new Xex.Term ('marker');
1428 MIM.Marker.prototype.CharAt = function (ic)
1430 var p = this.Position (ic);
1432 return ic.GetSurroundingChar (p);
1433 else if (p >= ic.preedit.length)
1434 return ic.GetSurroundingChar (p - ic.preedit.length);
1435 return ic.preedit.charCodeAt (p);
1438 MIM.NamedMarker = function (name) { this.val = name; }
1439 MIM.NamedMarker.prototype = new MIM.Marker ();
1440 MIM.NamedMarker.prototype.Position = function (ic)
1442 var p = ic.marker_positions[this.val];
1443 return (p == undefined ? 0 : p);
1445 MIM.NamedMarker.prototype.Mark = function (ic)
1447 ic.marker_positions[this.val] = ic.cursor_pos;
1450 MIM.PredefinedMarker = function (name) { this.val = name; }
1451 MIM.PredefinedMarker.prototype = new MIM.Marker ();
1452 MIM.PredefinedMarker.prototype.Position = function (ic)
1454 if (typeof this.pos == 'number')
1456 return this.pos (ic);
1459 var predefined = { }
1461 function def_predefined (name, position)
1463 predefined[name] = new MIM.PredefinedMarker (name);
1464 predefined[name].pos = position;
1467 def_predefined ('@<', 0);
1468 def_predefined ('@>', function (ic) { return ic.preedit.length; });
1469 def_predefined ('@-', function (ic) { return ic.cursor_pos - 1; });
1470 def_predefined ('@+', function (ic) { return ic.cursor_pos + 1; });
1471 def_predefined ('@[', function (ic) {
1472 if (ic.cursor_pos > 0)
1474 var pos = ic.cursor_pos;
1475 return ic.preedit.FindProp ('candidates', pos - 1).from;
1479 def_predefined ('@]', function (ic) {
1480 if (ic.cursor_pos < ic.preedit.length - 1)
1482 var pos = ic.cursor_pos;
1483 return ic.preedit.FindProp ('candidates', pos).to;
1485 return ic.preedit.length;
1487 for (var i = 0; i < 10; i++)
1488 def_predefined ("@" + i, i);
1489 predefined['@first'] = predefined['@<'];
1490 predefined['@last'] = predefined['@>'];
1491 predefined['@previous'] = predefined['@-'];
1492 predefined['@next'] = predefined['@+'];
1493 predefined['@previous-candidate-change'] = predefined['@['];
1494 predefined['@next-candidate-change'] = predefined['@]'];
1496 MIM.SurroundMarker = function (name)
1499 this.distance = parseInt (name.slice (2));
1500 if (isNaN (this.distance))
1501 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid marker: " + name);
1503 MIM.SurroundMarker.prototype = new MIM.Marker ();
1504 MIM.SurroundMarker.prototype.Position = function (ic)
1506 return ic.cursor_pos + this.distance;
1509 MIM.Marker.prototype.Parser = function (domain, node)
1511 var name = node.firstChild.nodeValue;
1512 if (name.charAt (0) == '@')
1514 var n = predefined[name];
1517 if (name.charAt (1) == '-')
1518 return new MIM.SurroundMarker (name);
1519 throw new Xex.ErrTerm (MIM.Error.ParseError,
1520 "Invalid marker: " + name);
1522 return new MIM.NamedMarker (name);
1526 MIM.Selector = function (name)
1530 MIM.Selector.prototype = new Xex.Term ('selector');
1534 selectors["@<"] = selectors["@first"] = new MIM.Selector ('@<');
1535 selectors["@="] = selectors["@current"] = new MIM.Selector ('@=');
1536 selectors["@>"] = selectors["@last"] = new MIM.Selector ('@>');
1537 selectors["@-"] = selectors["@previous"] = new MIM.Selector ('@-');
1538 selectors["@+"] = selectors["@next"] = new MIM.Selector ('@+');
1539 selectors["@["] = selectors["@previous-candidate-change"]
1540 = new MIM.Selector ('@[');
1541 selectors["@]"] = selectors["@next-candidate-change"]
1542 = new MIM.Selector ('@]');
1544 MIM.Selector.prototype.Parser = function (domain, node)
1546 var name = node.firstChild.nodeValue;
1547 var s = selectors[name];
1549 throw new Xex.ErrTerm (MIM.Error.ParseError,
1550 "Invalid selector: " + name);
1555 MIM.Rule = function (keyseq, actions)
1557 this.keyseq = keyseq;
1558 this.actions = actions;
1560 MIM.Rule.prototype = new Xex.Term ('rule');
1561 MIM.Rule.prototype.Parser = function (domain, node)
1564 for (n = node.firstChild; n && n.nodeType != 1; n = n.nextSibling);
1566 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1567 var keyseq = Xex.Term.Parse (domain, n);
1568 if (keyseq.type != 'keyseq')
1569 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1570 var actions = Xex.Term.Parse (domain, n.nextElement (), null);
1571 return new MIM.Rule (keyseq, actions);
1573 MIM.Rule.prototype.toString = function ()
1578 MIM.Map = function (name)
1581 this.rules = new Array ();
1585 var proto = new Xex.Term ('map');
1587 proto.Parser = function (domain, node)
1589 var name = node.attributes['mname'].nodeValue;
1591 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1592 var map = new MIM.Map (name);
1593 for (var n = node.firstChild; n; n = n.nextSibling)
1594 if (n.nodeType == 1)
1595 map.rules.push (Xex.Term.Parse (domain, n));
1599 proto.toString = function ()
1601 var str = '<map mname="' + this.name + '">';
1602 var len = this.rules.length;
1603 for (i = 0; i < len; i++)
1604 str += this.rules[i];
1605 return str + '</map>';
1608 MIM.Map.prototype = proto;
1611 Xex.CatchTag._mimtag = new Xex.SymTerm ('@mimtag');
1613 MIM.Action = function (domain, terms)
1615 var args = new Array ();
1616 args.push (Xex.CatchTag_.mimtag);
1617 for (var i = 0; i < terms.length; i++)
1618 args.push (terms[i]);
1619 this.action = Xex.Funcall.prototype.New (domain, 'catch', null, args);
1622 MIM.Action.prototype.Run = function (domain)
1624 var result = this.action.Eval (domain);
1625 if (result.type == 'error')
1627 domain.context.Error = result.toString ();
1630 return (result != Xex.CatchTag._mimtag);
1633 MIM.Keymap = function ()
1636 this.submaps = null;
1637 this.actions = null;
1643 function add_rule (keymap, rule)
1645 var keyseq = rule.keyseq;
1646 var len = keyseq.val.length;
1649 for (var i = 0; i < len; i++)
1651 var key = keyseq.val[i];
1655 if (! keymap.submaps)
1656 keymap.submaps = {};
1658 sub = keymap.submaps[key.key];
1660 keymap.submaps[key.key] = sub = new MIM.Keymap ();
1664 keymap.actions = rule.actions;
1667 proto.Add = function (map)
1669 var rules = map.rules;
1670 var len = rules.length;
1672 for (var i = 0; i < len; i++)
1673 add_rule (this, rules[i]);
1675 proto.Lookup = function (keys, index)
1679 if (index < keys.val.length && this.submaps
1680 && (sub = this.submaps[keys.val[index].key]))
1683 return sub.Lookup (keys, index);
1685 return { map: this, index: index };
1688 MIM.Keymap.prototype = proto;
1691 MIM.State = function (name)
1694 this.keymap = new MIM.Keymap ();
1698 var proto = new Xex.Term ('state');
1700 proto.Parser = function (domain, node)
1702 var map_list = domain.map_list;
1703 var name = node.attributes['sname'].nodeValue;
1705 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1706 var state = new MIM.State (name);
1707 for (node = node.firstElement (); node; node = node.nextElement ())
1709 if (node.nodeName == 'title')
1710 state.title = node.firstChild.nodeValue;
1713 var n = node.firstElement ();
1714 if (node.nodeName == 'branch')
1716 state.keymap.Add (map_list[node.attributes['mname'].nodeValue]);
1717 state.keymap.actions = Xex.Term.Parse (domain, n, null);
1719 else if (node.nodeName == 'state-hook')
1720 state.enter_actions = Xex.Term.Parse (domain, n, null);
1721 else if (node.nodeName == 'catch-all-branch')
1722 state.fallback_actions = Xex.Term.Parse (domain, n, null);
1728 proto.toString = function ()
1730 return '<state sname="' + this.name + '">' + this.keymap + '</state>';
1733 MIM.State.prototype = proto;
1737 function Block (index, term)
1741 this.Data = term.val;
1742 else if (term.IsList)
1744 this.Data = new Array ();
1745 for (var i = 0; i < term.val.length; i++)
1746 this.Data.push (term.val[i].val);
1750 Block.prototype.Count = function () { return this.Data.length; }
1751 Block.prototype.get = function (i)
1753 return (this.Data instanceof Array ? this.Data[i] : this.Data.charAt (i));
1756 MIM.Candidates = function (candidates, column)
1758 this.column = column;
1762 this.blocks = new Array ();
1764 for (var i = 0; i < candidates.length; i++)
1766 var block = new Block (this.total, candidates[i]);
1767 this.blocks.push (block);
1768 this.total += block.Count ();
1774 return (this.column > 0 ? this.index % this.column
1775 : this.index - this.blocks[this.row].Index);
1778 function prev_group ()
1780 var col = get_col.call (this);
1782 if (this.column > 0)
1784 this.index -= this.column;
1785 if (this.index >= 0)
1786 nitems = this.column;
1789 var lastcol = (this.total - 1) % this.column;
1790 this.index = (col < lastcol ? this.total - lastcol + col
1792 this.row = this.blocks.length - 1;
1793 nitems = lastcol + 1;
1795 while (this.blocks[this.row].Index > this.index)
1800 this.row = this.row > 0 ? this.row - 1 : this.blocks.length - 1;
1801 nitems = this.blocks[this.row].Count ();
1802 this.index = (this.blocks[this.row].Index
1803 + (col < nitems ? col : nitems - 1));
1808 function next_group ()
1810 var col = get_col.call (this);
1812 if (this.column > 0)
1814 this.index += this.column - col;
1815 if (this.index < this.total)
1817 if (this.index + col >= this.total)
1819 nitems = this.total - this.index;
1820 this.index = this.total - 1;
1824 nitems = this.column;
1833 while (this.blocks[this.row].Index > this.index)
1838 this.row = this.row < this.blocks.length - 1 ? this.row + 1 : 0;
1839 nitems = this.blocks[this.row].Count ();
1840 this.index = (this.blocks[this.row].Index
1841 + (col < nitems ? col : nitems - 1));
1848 if (this.index == 0)
1850 this.index = this.total - 1;
1851 this.row = this.blocks.length - 1;
1856 if (this.blocks[this.row].Index > this.index)
1864 if (this.index == this.total)
1871 var b = this.blocks[this.row];
1872 if (this.index == b.Index + b.Count ())
1879 this.index -= get_col.call (this);
1880 while (this.blocks[this.row].Index > this.index)
1886 var b = this.blocks[this.row];
1887 if (this.column > 0)
1889 if (this.index + 1 < this.total)
1891 this.index += this.column - get_col.call (this) + 1;
1892 while (b.Index + b.Count () <= this.index)
1893 b = this.blocks[++this.row];
1897 this.index = b.Index + b.Count () - 1;
1900 MIM.Candidates.prototype.Current = function ()
1902 var b = this.blocks[this.row];
1903 return b.get (this.index - b.Index);
1906 MIM.Candidates.prototype.Select = function (selector)
1908 if (selector.type == 'selector')
1910 switch (selector.val)
1912 case '@<': first.call (this); break;
1913 case '@>': last.call (this); break;
1914 case '@-': prev.call (this); break;
1915 case '@+': next.call (this); break;
1916 case '@[': prev_group.call (this); break;
1917 case '@]': next_group.cal (this); break;
1920 return this.Current ();
1923 if (this.column > 0)
1925 col = this.index % this.column;
1926 start = this.index - col;
1927 end = start + this.column;
1931 start = this.blocks[this.row].Index;
1932 col = this.index - start;
1933 end = start + this.blocks[this.row].Count;
1935 if (end > this.total)
1937 this.index += selector.val - col;
1938 if (this.index >= end)
1939 this.index = end - 1;
1940 if (this.column > 0)
1942 if (selector.val > col)
1943 while (this.blocks[this.row].Index + this.blocks[this.row].Count
1947 while (this.blocks[this.row].Index > this.index)
1950 return this.Current ();
1954 MIM.im_domain = new Xex.Domain ('input-method', null, null);
1955 MIM.im_domain.DefType (MIM.KeySeq.prototype);
1956 MIM.im_domain.DefType (MIM.Marker.prototype);
1957 MIM.im_domain.DefType (MIM.Selector.prototype);
1958 MIM.im_domain.DefType (MIM.Rule.prototype);
1959 MIM.im_domain.DefType (MIM.Map.prototype);
1960 MIM.im_domain.DefType (MIM.State.prototype);
1962 MIM.im_domain.Trace = function (arg)
1964 var node = document.getElementById ('log');
1966 node.value = "" + arg + node.value;
1970 var im_domain = MIM.im_domain;
1972 function Finsert (domain, vari, args)
1975 if (args[0].type == 'integer')
1976 text = String.fromCharCode (args[0].val);
1979 domain.context.insert (text, null);
1982 function Finsert_candidates (domain, vari, args)
1984 var ic = domain.context;
1985 var gsize = domain.variables['candidates_group_size'];
1986 var candidates = new MIM.Candidates (args, gsize ? gsize.Intval : 0);
1987 ic.insert (candidates.Current (), candidates);
1991 function Fdelete (domain, vari, args)
1993 var ic = domain.context;
1994 var pos = args[0].IsInt ? args[0].Intval : args[0].Position (ic);
1996 return new Xex.Term (ic.del (pos));
1999 function Fselect (domain, vari, args)
2001 var ic = domain.context;
2002 var can = ic.candidates;
2006 var candidate = can.Current ();
2008 ic.del (ic.cursor_pos - candidate.length);
2009 candidate = can.Select (args[0]);
2010 ic.insert (candidate, can);
2015 function Fchar_at (domain, vari, args)
2017 return new Xex.Term (args[0].CharAt (domain.context));
2020 function Fmove (domain, vari, args)
2022 var ic = domain.context;
2023 var pos = args[0].IsInt ? args[0].val : args[0].Position (ic);
2028 function Fmark (domain, vari, args)
2030 args[0].Mark (domain.context);
2034 function Fpushback (domain, vari, args)
2036 var arg = (args[0].IsInt ? args[0].Intval
2037 : args[0].IsStr ? new KeySeq (args[0])
2039 domain.context.pushback (arg)
2043 function Fundo (domain, vari, args)
2045 var ic = domain.context;
2046 var n = args.length == 0 ? -2 : args[0].val;
2048 ic.keys.val.splice (ic.keys.length + n, -n);
2050 ic.keys.val.splice (n, ic.keys.length);
2055 function Fcommit (domain, vari, args)
2057 domain.context.commit ();
2061 function Funhandle (domain, vari, args)
2063 domain.context.commit ();
2064 return Xex.Fthrow (domain, vari, Xex.CatchTag._mimtag);
2067 function Fshift (domain, vari, args)
2069 var ic = domain.context;
2070 var state_name = args[0].val;
2071 var state = ic.im.state_list[state_name];
2073 throw ("Unknown state: " + state_name);
2078 function Fsurrounding_flag (domain, vari, args)
2080 return new Xex.IntTerm (-1);
2083 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
2084 im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, 1);
2085 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
2086 im_domain.DefSubr (Fselect, "select", false, 1, 1);
2087 //im_domain.DefSubr (Fshow, "show-candidates", false, 0, 0);
2088 //im_domain.DefSubr (Fhide, "hide-candidates", false, 0, 0);
2089 im_domain.DefSubr (Fmove, "move", false, 1, 1);
2090 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
2091 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
2092 //im_domain.DefSubr (Fpop, "pop", false, 0, 0);
2093 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
2094 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
2095 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
2096 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
2097 //im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
2098 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
2099 //im_domain.DefSubr (Fkey_count, "key-count", false, 0, 0);
2100 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag", false, 0, 0);
2105 function get_global_var (vname)
2107 if (MIM.im_global.load_status == MIM.LoadStatus.NotLoaded)
2108 MIM.im_global.Load ()
2109 return MIM.im_global.domain.variables[vname];
2112 function include (node)
2114 node = node.firstElement ();
2115 if (node.nodeName != 'tags')
2118 var lang = null, name = null, extra = null;
2119 for (node = node.firstElement (); node; node = node.nextElement ())
2121 if (node.nodeName == 'language')
2122 lang = node.firstChild.nodeValue;
2123 else if (node.nodeName == 'name')
2124 name = node.firstChild.nodeValue;
2125 else if (node.nodeName == 'extra-id')
2126 extra = node.firstChild.nodeValue;
2128 if (! lang || ! MIM.imlist[lang])
2132 if (! name || ! (im = MIM.imlist[lang][name]))
2137 if (! (im = MIM.imextra[lang][extra]))
2140 if (im.load_status != MIM.LoadStatus.Loaded
2141 && (im.load_status != MIM.LoadStatus.NotLoaded || ! im.Load ()))
2148 parsers['description'] = function (node)
2150 this.description = node.firstChild.nodeValue;
2152 parsers['variable-list'] = function (node)
2154 for (node = node.firstElement (); node; node = node.nextElement ())
2156 var vname = node.attributes['vname'].nodeValue;
2157 if (this != MIM.im_global)
2159 var vari = get_global_var (vname);
2161 this.domain.Defvar (vname);
2163 vname = Xex.Term.Parse (this.domain, node)
2166 parsers['command-list'] = function (node)
2169 parsers['macro-list'] = function (node)
2171 for (var n = node.firstElement (); n; n = n.nextElement ())
2172 if (n.nodeName == 'xi:include')
2174 var im = include (n);
2176 alert ('inclusion fail');
2178 for (var macro in im.domain.functions)
2180 var func = im.domain.functions[macro];
2181 if (func instanceof Xex.Macro)
2182 im.domain.CopyFunc (this.domain, macro);
2184 n = n.previousSibling;
2185 node.removeChild (n.nextSibling);
2187 Xex.Term.Parse (this.domain, node.firstElement (), null);
2189 parsers['title'] = function (node)
2191 this.title = node.firstChild.nodeValue;
2193 parsers['map-list'] = function (node)
2195 for (node = node.firstElement (); node; node = node.nextElement ())
2197 if (node.nodeName == 'xi:include')
2199 var im = include (node);
2202 alert ('inclusion fail');
2205 for (var mapname in im.map_list)
2206 this.map_list[mapname] = im.map_list[mapname];
2210 var map = Xex.Term.Parse (this.domain, node);
2211 this.map_list[map.name] = map;
2215 parsers['state-list'] = function (node)
2217 this.domain.map_list = this.map_list;
2218 for (node = node.firstElement (); node; node = node.nextElement ())
2220 if (node.nodeName == 'state')
2222 var state = Xex.Term.Parse (this.domain, node);
2224 state.title = this.title;
2225 if (! this.initial_state)
2226 this.initial_state = state;
2227 this.state_list[state.name] = state;
2230 delete this.domain.map_list;
2233 MIM.IM = function (lang, name, extra_id, file)
2237 this.extra_id = extra_id;
2239 this.load_status = MIM.LoadStatus.NotLoaded;
2240 this.domain = new Xex.Domain (this.lang + '-'
2241 + (this.name != 'nil'
2242 ? this.name : this.extra_id),
2243 MIM.im_domain, null);
2249 var node = Xex.Load (null, this.file);
2252 this.load_status = MIM.LoadStatus.Error;
2256 this.initial_state = null;
2257 this.state_list = {};
2258 for (node = node.firstElement (); node; node = node.nextElement ())
2260 var name = node.nodeName;
2261 var parser = parsers[name];
2263 parser.call (this, node);
2265 this.load_status = MIM.LoadStatus.Loaded;
2270 MIM.IM.prototype = proto;
2272 MIM.IC = function (im, target)
2274 if (im.load_status == MIM.LoadStatus.NotLoaded)
2276 if (im.load_status != MIM.LoadStatus.Loaded)
2277 alert ('im:' + im.name + ' error:' + im.load_status);
2279 this.target = target;
2280 this.domain = new Xex.Domain ('context', im.domain, this);
2286 MIM.CandidateTable = function ()
2288 this.table = new Array ();
2291 MIM.CandidateTable.prototype.get = function (from)
2293 for (var i = 0; i < this.table.length; i++)
2295 var elt = this.table[i];
2296 if (elt.from <= from && elt.to > from)
2301 MIM.CandidateTable.prototype.put = function (from, to, candidates)
2303 for (var i = 0; i < this.table.length; i++)
2305 var elt = this.table[i];
2306 if (elt.from >= from && elt.from < to
2307 || elt.to >= from && elt.to < to)
2311 elt.val = candidates;
2315 this.table.push ({ from: from, to: to, val: candidates });
2318 MIM.CandidateTable.prototype.adjust = function (from, to, inserted)
2320 var diff = inserted - (to - from);
2321 for (var i = 0; i < this.table.length; i++)
2323 var elt = this.table[i];
2332 MIM.CandidateTable.prototype.clear = function ()
2334 this.table.length = 0;
2337 function detach_candidates (ic)
2339 ic.candidate_table.clear ();
2340 ic.candidates = null;
2341 ic.changed |= (MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos
2342 | ChangedStatus.CandidateList
2343 | ChangedStatus.CandidateIndex
2344 | ChangedStatus.CandidateShow);
2347 function set_cursor (prefix, pos)
2349 this.cursor_pos = pos;
2351 this.candidates = this.candidate_table.get (pos - 1);
2353 this.candidates = null;
2356 function save_state ()
2358 this.state_var_values = this.domain.SaveValues ();
2359 this.state_preedit = this.preedit;
2360 this.state_key_head = this.key_head;
2361 this.state_pos = this.cursor_pos;
2364 function restore_state ()
2366 this.domain.RestoreValues (this.state_var_values);
2367 this.preedit = this.state_preedit;
2368 set_cursor.call (this, "restore", this.state_pos);
2371 function handle_key ()
2373 var out = this.keymap.Lookup (this.keys, this.key_head);
2375 var branch_actions = this.state.keymap.actions;
2377 this.domain.Trace ('handling ' + this.keys.val[this.key_head]
2378 + ' in ' + this.state.name + ':'
2379 + this.keymap.name + "\n");
2380 this.key_head = out.index;
2381 if (sub != this.keymap)
2384 restore_state.call (this);
2386 this.domain.Trace ('submap found\n');
2387 if (this.keymap.actions)
2389 this.domain.Trace ('taking map actions:\n');
2390 if (! this.take_actions (this.keymap.actions))
2393 else if (this.keymap.submaps)
2395 MIM.log ('no map actions');
2396 for (var i = this.state_key_head; i < this.key_head; i++)
2398 MIM.log ('inserting key:' + this.keys.val[i].key);
2399 this.insert (this.keys.val[i].key, null);
2402 if (! this.keymap.submaps)
2404 MIM.log ('terminal:');
2405 if (this.keymap.branch_actions != null)
2407 MIM.log ('branch actions:');
2408 if (! this.take_actions (branch_actions))
2411 if (this.keymap != this.state.keymap)
2412 this.shift (this.state);
2417 MIM.log ('no submap');
2418 var current_state = this.state;
2419 var map = this.keymap;
2423 MIM.log ('branch actions');
2424 if (! this.take_actions (this.keymap.branch_actions))
2428 if (map == this.keymap)
2430 MIM.log ('no state change');
2431 if (map == this.initial_state.keymap
2432 && this.key_head < this.keys.val.length)
2434 MIM.log ('unhandled');
2437 if (this.keymap != current_state.keymap)
2438 this.shift (current_state);
2439 else if (this.keymap.actions == null)
2440 this.shift (this.initial_state);
2449 this.produced = null;
2451 this.preedit_saved = '';
2452 this.cursor_pos = 0;
2453 this.marker_positions = {};
2454 this.candidates = null;
2455 this.candidate_show = false;
2457 this.prev_state = null;
2458 this.initial_state = this.im.initial_state;
2459 this.title = this.initial_state.title;
2460 this.state_preedit = '';
2461 this.state_key_head = 0;
2462 this.state_var_values = {};
2465 this.keys = new MIM.KeySeq ();
2467 this.key_unhandled = false;
2468 this.unhandled_key = null;
2469 this.changed = MIM.ChangedStatus.None;
2470 this.error_message = '';
2471 this.title = this.initial_state.title;
2474 this.preedit_saved = '';
2475 this.marker_positions = {};
2476 this.candidate_table = new MIM.CandidateTable ();
2477 this.candidates = null;
2478 this.candidate_show = false;
2479 this.shift (this.initial_state);
2482 catch_args: new Array (Xex.CatchTag._mimtag, null),
2484 take_actions: function (actions)
2486 var func_progn = this.domain.GetFunc ('progn');
2487 var func_catch = this.domain.GetFunc ('catch');
2488 this.catch_args[1] = new Xex.Funcall (func_progn, null, actions);
2489 var term = new Xex.Funcall (func_catch, null, this.catch_args);
2490 term = term.Eval (this.domain);
2491 return (! term.IsSymbol || term.val != '@mimtag');
2494 GetSurroundingChar: function (pos)
2496 if (pos < 0 ? this.caret_pos < - pos : this.target.value.length < pos)
2498 return this.target.value.charCodeAt (this.caret_pos + pos);
2501 adjust_markers: function (from, to, inserted)
2503 var diff = inserted - (to - from);
2505 for (var m in this.marker_positions)
2506 if (this.marker_positions[m] > from)
2507 this.marker_positions[m] = (this.marker_positions[m] >= to
2508 ? pos + diff : from);
2509 if (this.cursor_pos >= to)
2510 set_cursor.call (this, 'adjust', this.cursor_pos + diff);
2511 else if (this.cursor_pos > from)
2512 set_cursor.call (this, 'adjust', from)
2515 preedit_replace: function (from, to, text, candidates)
2517 this.preedit = (this.preedit.substring (0, from)
2518 + text + this.preedit.substring (to));
2519 this.adjust_markers (from, to, text.length);
2520 this.candidate_table.adjust (from, to, text.length);
2522 this.candidate_table.put (from, from + text.length, candidates)
2525 insert: function (text, candidates)
2527 this.preedit_replace (this.cursor_pos, this.cursor_pos, text, candidates);
2528 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2533 var deleted = pos - this.cursor_pos;
2536 this.DelSurroundText (pos);
2539 else if (pos > this.preedit.length)
2541 this.DelSurroundText (pos - this.preedit.length);
2542 pos = this.preedit.length;
2544 if (pos < this.cursor_pos)
2545 this.preedit = (this.predit.substring (0, pos)
2546 + this.preedit.substring (this.cursor_pos));
2548 this.preedit = (this.preedit.substring (0, this.cursor_pos)
2549 + this.predit.substring (pos));
2555 this.candidate_show = true;
2556 this.changed |= MIM.ChangedStatus.CandidateShow;
2561 this.candidate_show = false;
2562 this.changed |= MIM.ChangedStatus.CandidateShow;
2565 move: function (pos)
2569 else if (pos > this.preedit.length)
2570 pos = this.preedit.length;
2571 if (pos != this.cursor_pos)
2573 set_cursor.call (this, 'move', pos);
2574 this.changed |= MIM.ChangedStatus.Preedit;
2578 pushback: function (n)
2580 if (n instanceof MIM.KeySeq)
2582 if (this.key_head > 0)
2584 if (this.key_head < this.keys.val.length)
2585 this.keys.val.splice (this.key_head,
2586 this.keys.val.length - this.key_head);
2587 for (var i = 0; i < n.val.length; i++)
2588 this.keys.val.push (n.val[i]);
2594 if (this.key_head < 0)
2601 this.key_head = - n;
2602 if (this.key_head > this.keys.val.length)
2603 this.key_head = this.keys.val.length;
2609 if (this.key_head < this.keys.val.length)
2610 this.keys.val.splice (this.key_head, 1);
2615 if (this.preedit.length > 0)
2617 this.candidate_table.clear ();
2618 this.produced += this.preedit;
2619 this.preedit_replace.call (this, 0, this.preedit.length, '', null);
2623 shift: function (state)
2627 MIM.log ("shifting back to previous");
2628 if (this.prev_state == null)
2630 state = this.prev_state;
2633 MIM.log ("shifting to " + state.name);
2635 if (state == this.initial_state)
2640 this.keys.val.splice (0, this.key_head);
2642 this.prev_state = null;
2647 if (state != this.state)
2648 this.prev_state = this.state;
2650 if (state != this.state && state.enter_actions)
2651 this.take_actions (state.enter_actions);
2652 if (! this.state || this.state.title != state.title)
2653 this.changed |= MIM.ChangedStatus.StateTitle;
2655 this.keymap = state.keymap;
2656 this.state_key_head = this.key_head;
2657 save_state.call (this);
2660 Filter: function (key)
2664 this.key_unhandled = true;
2665 this.unhandled_key = key;
2668 if (key.key == '_reload')
2670 this.changed = MIM.ChangedStatus.None;
2672 this.key_unhandled = false;
2673 this.keys.val.push (key);
2675 while (this.key_head < this.keys.val.length)
2677 if (! handle_key.call (this))
2679 if (this.key_head < this.keys.val.length)
2681 this.unhandled_key = this.keys.val[this.key_head];
2682 this.keys.val.splice (this.key_head, this.key_head + 1);
2684 this.key_unhandled = true;
2690 this.key_unhandled = true;
2694 if (this.key_unhandled)
2696 this.keys.val.length = 0;
2697 this.key_head = this.state_key_head = this.commit_key_head = 0;
2699 return (! this.key_unhandled
2700 && this.produced.length == 0
2701 && this.preedit.length == 0);
2705 MIM.IC.prototype = proto;
2707 var node = Xex.Load (null, "imlist.xml");
2708 for (node = node.firstChild; node; node = node.nextSibling)
2709 if (node.nodeName == 'input-method')
2711 var lang = null, name = null, extra_id = null, file = null;
2713 for (var n = node.firstChild; n; n = n.nextSibling)
2715 if (n.nodeName == 'language')
2716 lang = n.firstChild.nodeValue;
2717 else if (n.nodeName == 'name')
2718 name = n.firstChild.nodeValue;
2719 else if (n.nodeName == 'extra-id')
2720 extra_id = n.firstChild.nodeValue;
2721 else if (n.nodeName == 'filename')
2722 file = n.firstChild.nodeValue;
2724 if (name && name != 'nil')
2726 if (! MIM.imlist[lang])
2727 MIM.imlist[lang] = {};
2728 MIM.imlist[lang][name] = new MIM.IM (lang, name, extra_id, file);
2730 else if (extra_id && extra_id != 'nil')
2732 if (! MIM.imextra[lang])
2733 MIM.imextra[lang] = {};
2734 MIM.imextra[lang][extra_id] = new MIM.IM (lang, name, extra_id, file);
2737 if (MIM.imextra.t && MIM.imextra.t.global)
2738 MIM.im_global = MIM.imextra.t.global;
2741 MIM.im_global = new MIM.IM ('t', 'nil', 'global', null);
2742 MIM.im_global.load_status = MIM.LoadStatus.Error;
2748 var keys = new Array ();
2750 keys[0x08] = 'backspace';
2751 keys[0x0D] = 'return';
2752 keys[0x1B] = 'escape';
2753 keys[0x20] = 'space';
2754 keys[0x21] = 'pageup';
2755 keys[0x22] = 'pagedown';
2757 keys[0x24] = 'home';
2758 keys[0x25] = 'left';
2760 keys[0x27] = 'right';
2761 keys[0x28] = 'down';
2762 keys[0x2D] = 'insert';
2763 keys[0x2E] = 'delete';
2764 for (var i = 1; i <= 12; i++)
2765 keys[111 + i] = "f" + i;
2766 keys[0x90] = "numlock";
2767 keys[0xF0] = "capslock";
2769 MIM.decode_key_event = function (event)
2771 var key = ((event.type == 'keydown' || event.keyCode) ? event.keyCode
2772 : event.charCode ? event.charCode
2776 if (event.type == 'keydown')
2781 if (event.shiftKey) key = "S-" + key ;
2784 key = String.fromCharCode (key);
2785 if (event.altKey) key = "A-" + key ;
2786 if (event.ctrlKey) key = "C-" + key ;
2787 return new MIM.Key (key);
2791 MIM.add_event_listener
2792 = (window.addEventListener
2793 ? function (target, type, listener) {
2794 target.addEventListener (type, listener, false);
2796 : window.attachEvent
2797 ? function (target, type, listener) {
2798 target.attachEvent ('on' + type,
2800 listener.call (target, window.event);
2803 : function (target, type, listener) {
2805 = function (e) { listener.call (target, e || window.event); };
2808 MIM.log = function (msg)
2810 var node = document.getElementById ('log');
2811 node.value = msg + "\n" + node.value;
2814 MIM.debug_print = function (event, ic)
2818 if (! MIM.debug_nodes)
2820 MIM.debug_nodes = new Array ();
2821 MIM.debug_nodes['keydown'] = document.getElementById ('keydown');
2822 MIM.debug_nodes['keypress'] = document.getElementById ('keypress');
2823 MIM.debug_nodes['status0'] = document.getElementById ('status0');
2824 MIM.debug_nodes['status1'] = document.getElementById ('status1');
2825 MIM.debug_nodes['keymap0'] = document.getElementById ('keymap0');
2826 MIM.debug_nodes['keymap1'] = document.getElementById ('keymap1');
2827 MIM.debug_nodes['preedit0'] = document.getElementById ('preedit0');
2828 MIM.debug_nodes['preedit1'] = document.getElementById ('preedit1');
2830 var target = event.target;
2831 var code = event.keyCode;
2832 var ch = event.type == 'keydown' ? 0 : event.charCode;
2833 var key = MIM.decode_key_event (event);
2836 MIM.debug_nodes[event.type].innerHTML = "" + code + "/" + ch + " : " + key;
2837 index = (event.type == 'keydown' ? '0' : '1');
2839 MIM.debug_nodes['status' + index].innerHTML = ic.im.load_status;
2841 MIM.debug_nodes['status' + index].innerHTML = 'no IM';
2842 MIM.debug_nodes['keymap' + index].innerHTML = ic.state.name;
2843 MIM.debug_nodes['preedit' + index].innerHTML = ic.preedit;
2846 MIM.get_range = function (target, range)
2848 if (target.selectionStart != null) // for Mozilla
2850 range[0] = target.selectionStart;
2851 range[1] = target.selectionEnd;
2855 var r = document.selection.createRange ();
2856 var rr = r.duplicate ();
2858 rr.moveToElementText (target);
2859 rr.setEndPoint ('EndToEnd', range);
2860 range[0] = rr.text.length - r.text.length;
2861 range[1] = rr.text.length;
2865 MIM.set_caret = function (target, ic)
2867 if (target.setSelectionRange) // Mozilla
2869 var scrollTop = target.scrollTop;
2870 target.setSelectionRange (ic.spot, ic.spot + ic.preedit.length);
2871 target.scrollTop = scrollTop;
2875 var range = target.createTextRange ();
2876 range.moveStart ('character', ic.spot);
2877 range.moveEnd ('character', ic.spot + ic.preedit.length);
2883 var range = new Array ();
2885 MIM.check_range = function (target, ic)
2887 MIM.get_range (target, range);
2888 if (range[0] != ic.spot || range[1] - range[0] != ic.preedit.length
2889 || target.value.substring (range[0], range[1]) != ic.preedit)
2891 MIM.log ('reset:' + ic.spot + '-' + (ic.spot + ic.preedit.length)
2892 + '/' + range[0] + '-' + range[1]);
2895 target.value = (target.value.substring (0, range[0])
2896 + target.value.substring (range[1]));
2901 MIM.update = function (target, ic)
2903 var text = target.value;
2904 target.value = (text.substring (0, ic.spot)
2907 + text.substring (ic.spot));
2908 ic.spot += ic.produced.length;
2909 MIM.set_caret (target, ic);
2912 MIM.reset_ic = function (event)
2914 if (event.target.mim_ic)
2916 var ic = event.target.mim_ic;
2917 var pos = ic.spot + ic.preedit.length;
2920 event.target.setSelectionRange (pos, pos);
2924 MIM.keydown = function (event)
2926 var target = event.target;
2927 if (! (target.type == "text" || target.type == "textarea"))
2930 var ic = target.mim_ic;
2931 if (! ic || ic.im != MIM.current)
2933 MIM.log ('creating IC');
2934 ic = new MIM.IC (MIM.current, target);
2936 MIM.add_event_listener (target, 'blur', MIM.reset_ic);
2938 if (ic.im.load_status != MIM.LoadStatus.Loaded)
2940 MIM.check_range (target, ic);
2941 MIM.debug_print (event, ic);
2942 ic.key = MIM.decode_key_event (event);
2945 MIM.keypress = function (event)
2947 if (! (event.target.type == "text" || event.target.type == "textarea"))
2950 var ic = event.target.mim_ic;
2954 if (ic.im.load_status != MIM.LoadStatus.Loaded)
2957 ic.key = MIM.decode_key_event (event);
2964 MIM.log ("filtering " + ic.key);
2965 var result = ic.Filter (ic.key);
2966 MIM.update (event.target, ic);
2967 if (! ic.key_unhandled)
2968 event.preventDefault ();
2970 MIM.debug_print (event, ic);
2975 MIM.select_im = function (event)
2977 var target = event.target.parentNode;
2978 while (target.tagName != "SELECT")
2979 target = target.parentNode;
2982 for (var lang in MIM.imlist)
2983 for (var name in MIM.imlist[lang])
2984 if (idx++ == target.selectedIndex)
2986 im = MIM.imlist[lang][name];
2989 document.getElementsByTagName ('body')[0].removeChild (target);
2990 target.target.focus ();
2991 if (im && im != MIM.current)
2994 MIM.log ('select IM: ' + im.name);
2998 MIM.destroy_menu = function (event)
3000 if (event.target.tagName == "SELECT")
3001 document.getElementsByTagName ('body')[0].removeChild (event.target);
3004 MIM.select_menu = function (event)
3006 var target = event.target;
3008 if (! ((target.type == "text" || target.type == "textarea")
3009 && event.which == 1 && event.ctrlKey))
3012 var sel = document.createElement ('select');
3013 sel.onclick = MIM.select_im;
3014 sel.onmouseout = MIM.destroy_menu;
3015 sel.style.position='absolute';
3016 sel.style.left = (event.clientX - 10) + "px";
3017 sel.style.top = (event.clientY - 10) + "px";
3018 sel.target = target;
3020 for (var lang in MIM.imlist)
3021 for (var name in MIM.imlist[lang])
3023 var option = document.createElement ('option');
3024 var imname = lang + "-" + name;
3025 option.appendChild (document.createTextNode (imname));
3026 option.value = imname;
3027 sel.appendChild (option);
3028 if (MIM.imlist[lang][name] == MIM.current)
3029 sel.selectedIndex = idx;
3033 document.getElementsByTagName ('body')[0].appendChild (sel);
3036 MIM.test = function ()
3038 var im = MIM.imlist['t']['latn-post'];
3039 var ic = new MIM.IC (im, null);
3041 ic.Filter (new MIM.Key ('a'));
3042 ic.Filter (new MIM.Key ("'"));
3045 document.getElementById ('text').value = ic.produced + ic.preedit;
3048 document.getElementById ('text').value
3049 = Xex.Term.Parse (domain, body).Eval (domain).toString ();
3051 if (e instanceof Xex.ErrTerm)
3059 MIM.init = function ()
3061 MIM.add_event_listener (window, 'keydown', MIM.keydown);
3062 MIM.add_event_listener (window, 'keypress', MIM.keypress);
3063 MIM.add_event_listener (window, 'mousedown', MIM.select_menu);
3064 if (window.location == 'http://localhost/mim/index.html')
3065 MIM.server = 'http://localhost/mim';
3066 MIM.current = MIM.imlist['vi']['telex'];
3069 MIM.init_debug = function ()