1 // -* coding: utf-8; -*
5 Log: function (arg, indent)
10 Xex.LogNode.value = '';
14 if (indent != undefined)
15 for (var i = 0; i <= indent; i++)
17 Xex.LogNode.value = str + arg + "\n" + Xex.LogNode.value;
23 UnknownError: "unknown-error",
24 WrongArgument: "wrong-argument",
26 InvalidInteger: "invalid-integer",
27 TermTypeInvalid: "term-type-invalid",
28 FunctionConflict: "function-conflict",
29 VariableTypeConflict: "variable-type-conflict",
30 VariableRangeConflict: "variable-range-conflict",
31 VariableWrongRange: "variable-wrong-range",
32 VariableWrongValue: "variable-wrong-value",
34 UnknownFunction: "unknown-function",
35 MacroExpansionError: "macro-expansion-error",
36 NoVariableName: "no-variable-name",
37 NoFunctionName: "no-funcion-name",
40 ArithmeticError: "arithmetic-error",
41 WrongType: "wrong-type",
42 IndexOutOfRange: "index-out-of-range",
43 ValueOutOfRange: "value-out-of-range",
44 NoLoopToBreak: "no-loop-to-break",
45 UncaughtThrow: "uncaught-throw"
48 Xex.Variable = function (domain, name, desc, val, range)
57 Xex.Variable.prototype.clone = function ()
59 return new Xex.Variable (this.domain, this.name, this.desc,
60 this.val, this.range);
63 Xex.Variable.prototype.Equals = function (obj)
65 return ((obj instanceof Xex.Variable)
66 && obj.name == this.name);
69 Xex.Variable.prototype.SetValue = function (term)
75 Xex.Function = function (name, with_var, min_args, max_args)
78 this.with_var = with_var;
79 this.min_args = min_args;
80 this.max_args = max_args;
83 Xex.Subrountine = function (builtin, name, with_var, min_args, max_args)
86 this.with_var = with_var;
87 this.min_args = min_args;
88 this.max_args = max_args;
89 this.builtin = builtin;
92 Xex.Subrountine.prototype.Call = function (domain, vari, args)
94 var newargs = new Array ();
95 for (var i = 0; i < args.length; i++)
97 newargs[i] = args[i].Eval (domain);
101 return this.builtin (domain, vari, newargs)
104 Xex.SpecialForm = function (builtin, name, with_var, min_args, max_args)
107 this.with_var = with_var;
108 this.min_args = min_args;
109 this.max_args = max_args;
110 this.builtin = builtin;
113 Xex.SpecialForm.prototype.Call = function (domain, vari, args)
115 return this.builtin (domain, vari, args)
118 Xex.Lambda = function (name, min_args, max_args, args, body)
121 this.min_args = min_args;
122 this.max_args = max_args;
127 Xex.Lambda.prototype.Call = function (domain, vari, args)
129 var current = domain.bindings;
130 var result = Xex.Zero;
131 var limit = max_args >= 0 ? args.length : args.length - 1;
135 for (i = 0; i < limit; i++)
137 result = args[i].Eval (domain);
138 if (domain.Thrown ())
140 domain.Bind (this.args[i], result);
144 var list = new Array ();
145 for (i = 0; i < args[limit].length; i++)
147 result = args[limit].Eval (domain);
148 if (domain.Thrown ())
152 domain.Bind (this.args[limit], list);
155 domain.Catch (Xex.CatchTag.Return);
156 for (var term in this.body)
158 result = term.Eval (domain);
159 if (domain.Thrown ())
166 domain.UnboundTo (current);
171 Xex.Macro = function (name, min_args, max_args, args, body)
174 this.min_args = min_args;
175 this.max_args = max_args;
180 Xex.Macro.prototype.Call = function (domain, vari, args)
182 var current = domain.bindings;
183 var result = Xex.Zero;
187 for (i = 0; i < args.length; i++)
188 domain.Bind (this.args[i], args[i]);
190 domain.Catch (Xex.CatchTag.Return);
191 for (var i in this.body)
193 result = this.body[i].Eval (domain);
194 if (domain.Thrown ())
201 domain.UnboundTo (current);
206 Xex.Bindings = function (vari)
209 this.old_value = vari.val;
212 Xex.Bindings.prototype.UnboundTo = function (boundary)
214 for (var b = this; b != boundary; b = b.next)
215 b.vari.val = b.old_value;
219 Xex.Bind = function (bindings, vari, val)
221 var b = new Xex.Bindings (vari);
232 Xex.Domain = function (name, parent, context)
235 this.context = context;
238 if (name != 'basic' && ! parent)
239 parent = Xex.BasicDomain
240 this.parent = parent;
247 for (elt in parent.termtypes)
248 this.termtypes[elt] = parent.termtypes[elt];
249 for (elt in parent.functions)
250 this.functions[elt] = parent.functions[elt];
251 for (elt in parent.variables)
252 this.variables[elt] = parent.variables[elt];
255 this.call_stack = new Array ();
256 this.bindings = null;
257 this.catch_stack = new Array ();
258 this.catch_count = 0;
262 Xex.Domain.prototype = {
263 CallStackCount: function () { return this.call_stack.length; },
264 CallStackPush: function (term) { this.call_stack.push (term); },
265 CallStackPop: function () { this.call_stack.pop (); },
266 Bind: function (vari, val)
268 this.bindings = Xex.Bind (this.bindings, vari, val);
270 UnboundTo: function (boundary)
273 this.bindings = this.bindings.UnboundTo (boundary);
275 Catch: function (tag) { this.catch_stack.push (tag); this.catch_count++; },
278 this.catch_stack.pop ();
279 if (this.catch_count > this.catch_stack.length)
284 if (this.catch_count < this.catch_stack.length)
286 this.caught = (this.catch_count == this.catch_stack.length - 1);
292 ThrowReturn: function ()
294 for (var i = this.catch_stack.length - 1; i >= 0; i--)
297 if (this.catch_stack[i] == Xex.CatchTag.Return)
301 ThrowBreak: function ()
303 if (this.catch_stack[this.catch_stack.length - 1] != Xex.CatchTag.Break)
304 throw new Xex.ErrTerm (Xex.Error.NoLoopToBreak,
305 "No surrounding loop to break");
308 ThrowSymbol: function (tag)
310 var i = this.catch_count;
311 for (var j = this.catch_stack.length - 1; j >= 0; j--)
314 if (Xex.CatchTag.Matches (this.catch_stack[i], tag))
316 this.catch_count = i;
320 throw new Xex.ErrTerm (Xex.Error.UncaughtThrow,
321 "No corresponding catch: " + tag);
323 DefType: function (obj)
326 if (this.termtypes[type])
327 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
328 "Already defined: " + type);
329 if (this.functions[type])
330 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
331 "Already defined as a funciton or a macro: "
333 this.termtypes[type] = obj.Parser;
335 DefSubr: function (builtin, name, with_var, min_args, max_args)
337 this.functions[name] = new Xex.Subrountine (builtin, name, with_var,
340 DefSpecial: function (builtin, name, with_var, min_args, max_args)
342 this.functions[name] = new Xex.SpecialForm (builtin, name, with_var,
345 Defun: function (name, min_args, max_args, args, body)
347 this.functions[name] = new Xex.Lambda (name, min_args, max_args,
350 DefunByFunc: function (func) { this.functions[func.name] = func; },
351 Defmacro: function (name, min_args, max_args, args, body)
353 this.functions[name] = new Xex.Macro (name, min_args, max_args,
356 DefAlias: function (alias, fname)
358 var func = this.functions[fname];
361 throw new Xex.ErrTerm (Xex.Error.UnknownFunction, fname);
362 if (this.termtypes[alias])
363 throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
364 "Already defined as a term type: " + alias);
365 if (this.functions[alias])
366 throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
367 "Already defined as a function: " + alias);
368 this.functions[alias] = func;
370 Defvar: function (name, desc, val, range)
372 var vari = new Xex.Variable (this, name, desc, val, range);
373 this.variables[name] = vari;
376 GetFunc: function (name)
378 var func = this.functions[name];
380 throw new Xex.ErrTerm (Xex.Error.UnknownFunction,
381 "Unknown function: " + name);
384 CopyFunc: function (domain, name)
386 var func = this.functions[name];
387 domain.DefunByFunc (func);
390 CopyFuncAll: function (domain)
392 for (var elt in this.functions)
393 domain.DefunByFunc (this.functions[elt]);
395 GetVarCreate: function (name)
397 var vari = this.variables[name];
399 vari = this.variables[name] = new Xex.Variable (this, name, null,
403 GetVar: function (name) { return this.variables[name]; },
404 SaveValues: function ()
407 for (var elt in this.variables)
408 values[elt] = this.variables[elt].val.Clone ();
411 RestoreValues: function (values)
416 var vari = this.variables[name];
417 vari.val = values[name];
422 Xex.Term = function (type) { this.type = type; }
423 Xex.Term.prototype = {
424 IsTrue: function () { return true; },
425 Eval: function (domain) { return this.Clone (); },
426 Clone: function (domain) { return this; },
427 Equals: function (obj)
429 return (this.type == obj.type
431 && obj.val == this.val);
433 Matches: function (obj) { return this.Equals (obj); },
434 toString: function ()
436 if (this.val != undefined)
437 return '<' + this.type + '>' + this.val + '</' + this.type + '>';
438 return '<' + this.type + '/>';
440 Intval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
441 "Not an integer"); },
442 Strval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
446 Node.prototype.firstElement = function ()
448 for (var n = this.firstChild; n; n = n.nextSibling)
454 Node.prototype.nextElement = function ()
456 for (var n = this.nextSibling; n; n = n.nextSibling)
463 function parse_defvar (domain, node)
465 var name = node.attributes['vname'].nodeValue;
467 throw new Xex.ErrTerm (Xex.Error.NoVariableName, node, '');
468 var vari = domain.variables[name];
469 var desc, val, range;
472 desc = vari.description;
476 node = node.firstElement ();
477 if (node && node.nodeName == 'description')
479 desc = node.firstChild.nodeValue;
480 node = node.nextElement ();
484 val = Xex.Term.Parse (domain, node);
485 node = node.nextElement ();
486 if (node && node.nodeName == 'possible-values')
487 for (node = node.firstElement (); node; node = node.nextElement ())
490 if (node.nodeName == 'range')
493 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
494 'Range not allowed for ' + name);
496 for (var n = node.firstElement (); n; n = n.nextElement ())
498 var v = Xex.Term.Parse (domain, n);
500 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
501 'Invalid range value: ' + val);
507 pval = Xex.Term.Parse (domain, node);
508 if (val.type != pval.type)
509 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
510 'Invalid possible value: ' + pval);
513 range = new Array ();
519 domain.Defvar (name, desc, val, range);
523 function parse_defun_head (domain, node)
525 var name = node.attributes['fname'].nodeValue;
527 throw new Xex.ErrTerm (Xex.Error.NoFunctionName, node, '');
528 var args = new Array ();
529 var nfixed = 0, noptional = 0, nrest = 0;
531 node = node.firstElement ();
532 if (node && node.nodeName == 'args')
535 for (n = n.firstElement (); n; n = n.nextElement ())
537 if (n.nodeName == 'fixed')
539 else if (n.nodeName == 'optional')
541 else if (n.nodeName == 'rest')
544 throw new Xex.ErrTerm (Xex.Error.WrongType, n, n.nodeName);
547 throw new Xex.ErrTerm (Xex.Error.WrongType, n, 'Too many <rest>');
548 for (n = node.firstElement (); n; n = n.nextElement ())
549 args.push (domain.DefVar (n.attributes['vname'].nodeValue));
551 args.min_args = nfixed;
552 args.max_args = nrest == 0 ? nfixed + noptional : -1;
554 if (node.nodeName == 'defun')
555 domain.Defun (name, args, null);
557 domain.Defmacro (name, args, null);
561 function parse_defun_body (domain, node)
563 var name = node.attributes['fname'].nodeValue;
564 var func = domain.GetFunc (name);
566 for (node = node.firstElement (); node; node = node.nextElement ())
567 if (node.nodeName != 'description' && node.nodeName != 'args')
569 body = Xex.Term.Parse (domain, node, null);
573 Xex.Term.Parse = function (domain, node, stop)
575 if (arguments.length == 2)
577 var name = node.nodeName;
578 var parser = domain.termtypes[name];
581 return parser (domain, node);
582 if (name == 'defun' || name == 'defmacro')
584 name = parse_defun_head (domain, node);
585 parse_defun_body (domain, node);
586 return new Xex.StrTerm (name);
588 if (name == 'defvar')
590 name = parse_defvar (domain, node);
591 return new Xex.StrTerm (name);
593 return new Xex.Funcall.prototype.Parser (domain, node);
595 for (var n = node; n && n != stop; n = n.nextElement ())
596 if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
597 parse_defun_head (domain, n);
599 for (var n = node; n && n != stop; n = n.nextElement ())
601 if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
602 parse_defun_body (domain, n);
603 else if (n.nodeName == 'defvar')
604 parse_defvar (domain, n);
608 terms = new Array ();
609 terms.push (Xex.Term.Parse (domain, n));
616 Xex.Varref = function (vname)
622 var proto = new Xex.Term ('varref');
624 proto.Clone = function () { return new Xex.Varref (this.val); }
625 proto.Eval = function (domain)
627 if (! this.vari || this.vari.domain != domain)
628 this.vari = domain.GetVarCreate (this.val);
629 Xex.Log (this.ToString () + '=>' + this.vari.val, domain.depth);
630 return this.vari.val;
633 proto.Parser = function (domain, node)
635 return new Xex.Varref (node.attributes['vname'].nodeValue);
638 proto.ToString = function ()
640 return '<varref vname="' + this.val + '"/>';
643 Xex.Varref.prototype = proto;
646 var null_args = new Array ();
648 Xex.Funcall = function (func, vari, args)
652 this.args = args || null_args;
656 var proto = new Xex.Term ('funcall');
658 proto.Parser = function (domain, node)
660 var fname = node.nodeName;
663 if (fname == 'funcall')
664 fname = node.attributes['fname'].nodeValue;
665 var func = domain.GetFunc (fname);
667 attr = node.attributes['vname'];
668 vari = attr != undefined ? domain.GetVarCreate (attr.nodeValue) : false;
669 var args = Xex.Term.Parse (domain, node.firstElement (), null);
670 return new Xex.Funcall (func, vari, args);
673 proto.New = function (domain, fname, vname, args)
675 var func = domain.GetFunc (fname);
676 var vari = vname ? domain.GetVarCreate (vname) : null;
677 var funcall = new Xex.Funcall (func, vari, args);
678 if (func instanceof Xex.Macro)
679 funcall = funcall.Eval (domain);
683 proto.Eval = function (domain)
685 if (! (this.func instanceof Xex.Subrountine))
686 Xex.Log (this, domain.depth);
690 result = this.func.Call (domain, this.vari, this.args);
692 Xex.Log (this + ' => ' + result, --domain.depth);
697 proto.Clone = function ()
699 return new Xex.Funcall (this.func, this.vari, this.args);
702 proto.Equals = function (obj)
704 return (obj.type == 'funcall'
705 && obj.func == this.func
706 && obj.vari.Equals (this.vari)
707 && obj.args.length == this.func.length);
710 proto.toString = function ()
713 var len = this.args.length;
714 var str = '<' + this.func.name;
716 str += ' vname="' + this.vari.name + '"';
719 if (this.func instanceof Xex.Subrountine)
720 for (var i = 0; i < len; i++)
721 arglist += this.args[i].toString ();
723 for (var i = 0; i < len; i++)
725 return str + '>' + arglist + '</' + this.func.name + '>';
728 Xex.Funcall.prototype = proto;
731 Xex.ErrTerm = function (ename, message, stack)
734 this.message = message;
739 var proto = new Xex.Term ('error');
741 proto.IsError = true;
743 proto.Parser = function (domain, node)
745 return new Xex.ErrTerm (node.attributes['ename'].nodeValue,
746 node.innerText, false);
749 proto.CallStack = function () { return stack; }
751 proto.SetCallStack = function (value) { statck = value; }
753 proto.Clone = function ()
755 return new Xex.ErrTerm (ename, message, false);
758 proto.Equals = function (obj)
761 && obj.ename == ename && obj.message == message
762 && (obj.stack ? (stack && stack.length == obj.stack.length)
766 proto.Matches = function (obj)
768 return (obj.IsError && obj.ename == ename);
771 proto.toString = function ()
773 return '<error ename="' + this.ename + '">' + this.message + '</error>';
776 Xex.ErrTerm.prototype = proto;
779 Xex.IntTerm = function (num) { this.val = num; };
781 var proto = new Xex.Term ('integer');
783 proto.Intval = function () { return this.val; };
784 proto.IsTrue = function () { return this.val != 0; }
785 proto.Clone = function () { return new Xex.IntTerm (this.val); }
786 proto.Parser = function (domain, node)
788 var str = node.firstChild.nodeValue;
790 if (str.charAt (0) == '?' && str.length == 2)
791 return new Xex.IntTerm (str.charCodeAt (1));
792 return new Xex.IntTerm (parseInt (node.firstChild.nodeValue));
794 Xex.IntTerm.prototype = proto;
797 Xex.StrTerm = function (str) { this.val = str; };
799 var proto = new Xex.Term ('string');
801 proto.Strval = function () { return this.val; };
802 proto.IsTrue = function () { return this.val.length > 0; }
803 proto.Clone = function () { return new Xex.StrTerm (this.val); }
804 proto.Parser = function (domain, node)
806 return new Xex.StrTerm (node.firstChild.nodeValue);
808 Xex.StrTerm.prototype = proto;
811 Xex.SymTerm = function (str) { this.val = str; };
813 var proto = new Xex.Term ('symbol');
814 proto.IsSymbol = true;
815 proto.IsTrue = function () { return this.val != 'nil'; }
816 proto.Clone = function () { return new Xex.SymTerm (this.val); }
817 proto.Parser = function (domain, node)
819 return new Xex.SymTerm (node.firstChild.nodeValue);
821 Xex.SymTerm.prototype = proto;
824 Xex.LstTerm = function (list) { this.val = list; };
826 var proto = new Xex.Term ('list');
828 proto.IsTrue = function () { return this.val.length > 0; }
829 proto.Clone = function () { return new Xex.LstTerm (this.val.slice (0)); }
831 proto.Equals = function (obj)
833 if (obj.type != 'list' || obj.val.length != this.val.length)
835 var i, len = this.val.length;
836 for (i = 0; i < len; i++)
837 if (! this.val[i].Equals (obj.val[i]))
842 proto.Parser = function (domain, node)
844 var list = Xex.Term.Parse (domain, node.firstElement (), null);
845 return new Xex.LstTerm (list);
848 proto.toString = function ()
850 var len = this.val.length;
855 for (var i = 0; i < len; i++)
856 str += this.val[i].toString ();
857 return str + '</list>';
859 Xex.LstTerm.prototype = proto;
863 var basic = new Xex.Domain ('basic', null, null);
865 function Fset (domain, vari, args)
868 throw new Xex.ErrTerm (Xex.Error.NoVariableName,
869 'No variable name to set');
870 vari.SetValue (args[0]);
874 function maybe_set_intvar (vari, n)
876 var term = new Xex.IntTerm (n);
878 vari.SetValue (term);
882 function Fadd (domain, vari, args)
884 var n = vari ? vari.val.Intval () : 0;
885 var len = args.length;
887 for (var i = 0; i < len; i++)
888 n += args[i].Intval ();
889 return maybe_set_intvar (vari, n);
892 function Fmul (domain, vari, args)
894 var n = vari ? vari.val.Intval () : 1;
895 for (var i = 0; i < args.length; i++)
897 return maybe_set_intvar (vari, n);
900 function Fsub (domain, vari, args)
906 n = args[0].Intval ();
911 n = vari.val.Intval ();
914 while (i < args.length)
915 n -= args[i++].Intval ();
916 return maybe_set_intvar (vari, n);
919 function Fdiv (domain, vari, args)
925 n = args[0].Intval ();
930 n = vari.val.Intval ();
933 while (i < args.length)
934 n /= args[i++].Intval ();
935 return maybe_set_intvar (vari, n);
938 function Fmod (domain, vari, args)
940 return maybe_set_intvar (vari, args[0].Intval () % args[1].Intval ());
943 function Flogior (domain, vari, args)
945 var n = vari == null ? 0 : vari.val;
946 for (var i = 0; i < args.length; i++)
948 return maybe_set_intvar (vari, n);
951 function Fand (domain, vari, args)
953 var len = args.length;
954 for (var i = 0; i < len; i++)
956 var result = args[i].Eval (domain);
957 if (domain.Thrown ())
959 if (! result.IsTrue ())
965 function For (domain, vari, args)
967 var len = args.length;
968 for (var i = 0; i < len; i++)
970 var result = args[i].Eval (domain);
971 if (domain.Thrown ())
973 if (result.IsTrue ())
979 function Feq (domain, vari, args)
981 for (var i = 1; i < args.length; i++)
982 if (! args[i - 1].Equals (args[i]))
987 function Flt (domain, vari, args)
989 var n = args[0].Intval;
991 for (var i = 1; i < args.length; i++)
993 var n1 = args[i].Intval;
1001 function Fle (domain, vari, args)
1003 var n = args[0].Intval;
1004 for (var i = 1; i < args.length; i++)
1006 var n1 = args[i].Intval;
1014 function Fgt (domain, vari, args)
1016 var n = args[0].Intval;
1017 for (var i = 1; i < args.length; i++)
1019 var n1 = args[i].Intval;
1027 function Fge (domain, vari, args)
1029 var n = args[0].Intval;
1030 for (var i = 1; i < args.Length; i++)
1032 var n1 = args[i].Intval;
1040 function Fprogn (domain, vari, args)
1042 var result = Xex.One;
1043 var len = args.length;
1045 for (var i = 0; i < len; i++)
1047 result = args[i].Eval (domain);
1048 if (domain.Thrown ())
1054 function Fif (domain, vari, args)
1056 var result = args[0].Eval (domain);
1058 if (domain.Thrown ())
1060 if (result.IsTrue ())
1061 return args[1].Eval (domain);
1062 if (args.length == 2)
1064 return args[2].Eval (domain);
1067 function Fcond (domain, vari, args)
1069 for (var i = 0; i < args.length; i++)
1072 var result = list.val[0].Eval (domain);
1073 if (result.IsTrue ())
1075 for (var j = 1; j < list.val.length; j++)
1078 result = list.val[j].Eval (domain);
1080 if (domain.Thrown ())
1089 function eval_terms (domain, terms, idx)
1091 var result = Xex.Zero;
1092 domain.caught = false;
1093 for (var i = idx; i < terms.length; i++)
1095 result = terms[i].Eval (domain);
1096 if (domain.Thrown ())
1102 function Fcatch (domain, vari, args)
1107 if (args[0].IsError)
1110 result = eval_terms (domain, args, 1);
1112 if (e instanceof Xex.ErrTerm)
1114 if (! args[0].Matches (e))
1122 else if (args[0].IsSymbol)
1125 domain.Catch (args[0].val);
1126 result = eval_terms (domain, args, 1);
1130 vari.SetValue (result);
1138 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1139 "Not a symbol nor an error: " + args[0]);
1142 function Fthrow (domain, vari, args)
1144 if (args[0].IsSymbl)
1146 domain.ThrowSymbol (args[0]);
1147 return (args[args.length - 1]);
1149 if (args[0].IsError)
1153 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1154 "Not a symbol nor an error:" + args[0]);
1157 Xex.BasicDomain = basic;
1159 basic.DefSubr (Fset, "set", true, 1, 1);
1160 basic.DefAlias ("=", "set");
1161 //basic.DefSubr (Fnot, "not", false, 1, 1);
1162 //basic.DefAlias ("!", "not");
1163 basic.DefSubr (Fadd, "add", true, 1, -1);
1164 basic.DefSubr (Fmul, "mul", true, 1, -1);
1165 basic.DefAlias ("*", "mul");
1166 basic.DefSubr (Fsub, "sub", true, 1, -1);
1167 basic.DefAlias ("-", "sub");
1168 basic.DefSubr (Fdiv, "div", true, 1, -1);
1169 basic.DefAlias ("/", "div");
1170 basic.DefSubr (Fmod, "mod", true, 1, 2);
1171 basic.DefAlias ("%", "mod");
1172 basic.DefSubr (Flogior, "logior", true, 1, -1);
1173 basic.DefAlias ('|', "logior");
1174 //basic.DefSubr (Flogand, "logand", true, 1, -1);
1175 //basic.DefAlias ("&", "logand");
1176 //basic.DefSubr (Flsh, "lsh", true, 1, 2);
1177 //basic.DefAlias ("<<", "lsh");
1178 //basic.DefSubr (Frsh, "rsh", true, 1, 2);
1179 //basic.DefAlias (">>", "rsh");
1180 basic.DefSubr (Feq, "eq", false, 2, -1);
1181 basic.DefAlias ("==", "eq");
1182 //basic.DefSubr (Fnoteq, "noteq", false, 2, 2);
1183 //basic.DefAlias ("!=", "noteq");
1184 basic.DefSubr (Flt, "lt", false, 2, -1);
1185 basic.DefAlias ("<", "lt");
1186 basic.DefSubr (Fle, "le", false, 2, -1);
1187 basic.DefAlias ("<=", "le");
1188 basic.DefSubr (Fgt, "gt", false, 2, -1);
1189 basic.DefAlias (">", "gt");
1190 basic.DefSubr (Fge, "ge", false, 2, -1);
1191 basic.DefAlias (">=", "ge");
1192 basic.DefSubr (Fthrow, "throw", false, 1, 2);
1194 //basic.DefSubr (Fappend, "append", true, 0, -1);
1195 //basic.DefSubr (Fconcat, "concat", true, 0, -1);
1196 //basic.DefSubr (Fnth, "nth", false, 2, 2);
1197 //basic.DefSubr (Fcopy, "copy", false, 1, 1);
1198 //basic.DefSubr (Fins, "ins", true, 2, 2);
1199 //basic.DefSubr (Fdel, "del", true, 2, 2);
1200 //basic.DefSubr (Feval, "eval", false, 1, 1);
1201 //basic.DefSubr (Fbreak, "break", false, 0, 1);
1202 //basic.DefSubr (Freturn, "return", false, 0, 1);
1203 //basic.DefSubr (Fthrow, "throw", false, 1, 2);
1205 basic.DefSpecial (Fand, "and", false, 1, -1);
1206 basic.DefAlias ("&&", "and");
1207 basic.DefSpecial (For, "or", false, 1, -1);
1208 basic.DefAlias ("||", "or");
1209 basic.DefSpecial (Fprogn, "progn", false, 1, -1);
1210 basic.DefAlias ("expr", "progn");
1211 basic.DefSpecial (Fif, "if", false, 2, 3);
1212 //basic.DefSpecial (Fwhen, "when", false, 1, -1);
1213 //basic.DefSpecial (Floop, "loop", false, 1, -1);
1214 //basic.DefSpecial (Fwhile, "while", false, 1, -1);
1215 basic.DefSpecial (Fcond, "cond", false, 1, -1);
1216 //basic.DefSpecial (Fforeach, "foreach", true, 2, -1);
1217 //basic.DefSpecial (Fquote, "quote", false, 1, 1);
1218 //basic.DefSpecial (Ftype, "type", false, 1, 1);
1219 basic.DefSpecial (Fcatch, "catch", true, 2, -1);
1221 basic.DefType (Xex.Funcall.prototype);
1222 basic.DefType (Xex.Varref.prototype);
1223 basic.DefType (Xex.ErrTerm.prototype);
1224 basic.DefType (Xex.IntTerm.prototype);
1225 basic.DefType (Xex.StrTerm.prototype);
1226 basic.DefType (Xex.SymTerm.prototype);
1227 basic.DefType (Xex.LstTerm.prototype);
1231 Xex.Zero = new Xex.IntTerm (0);
1232 Xex.One = new Xex.IntTerm (1);
1233 Xex.nil = new Xex.SymTerm ('nil');
1235 Xex.Load = function (server, file)
1237 var obj = new XMLHttpRequest ();
1238 var url = server ? server + '/' + file : file;
1239 obj.open ('GET', url, false);
1240 obj.overrideMimeType ('text/xml');
1242 return obj.responseXML.firstChild;
1246 // URL of the input method server.
1247 server: "http://www.m17n.org/common/mim-js",
1248 // Boolean flag to tell if MIM is active or not.
1250 // Boolean flag to tell if MIM is running in debug mode or not.
1252 // List of main input methods.
1254 // List of extra input methods;
1256 // Global input method data
1258 // Currently selected input method.
1262 LoadStatus: { NotLoaded:0, Loading:1, Loaded:2, Error:-1 },
1269 CandidateIndex:0x10,
1271 Preedit: 0x06, // PreeditText | CursorPos
1272 Candidate: 0x38 // CandidateList | CandidateIndex | CandidateShow
1294 ParseError: "parse-error"
1299 var keysyms = new Array ();
1300 keysyms["bs"] = "backspace";
1301 keysyms["lf"] = "linefeed";
1302 keysyms["cr"] = keysyms["enter"] = "return";
1303 keysyms["esc"] = "escape";
1304 keysyms["spc"] = "space";
1305 keysyms["del"] = "delete";
1307 function decode_keysym (str) {
1308 var parts = str.split ("-");
1309 var len = parts.length, i;
1310 var has_modifier = len > 1;
1312 for (i = 0; i < len - 1; i++)
1313 if (! MIM.KeyModifier.hasOwnProperty (parts[i]))
1315 var key = parts[len - 1];
1318 key = keysyms[key.toLowerCase ()];
1324 for (i = 1; i < len - 1; i++)
1325 str += '-' + parts[i];
1334 parts = new Array ();
1341 MIM.Key = function (val)
1344 this.has_modifier = false;
1345 if (typeof val == 'string' || val instanceof String)
1347 this.key = decode_keysym (val);
1349 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1350 if (this.key instanceof Array)
1352 this.key = this.key[0];
1353 this.has_modifier = true;
1356 else if (typeof val == 'number' || val instanceof Number)
1357 this.key = String.fromCharCode (val);
1359 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1362 MIM.Key.prototype.toString = function () { return this.key; };
1366 MIM.KeySeq = function (seq)
1368 this.val = new Array ();
1369 this.has_modifier = false;
1375 var len = seq.val.length;
1376 for (var i = 0; i < len; i++)
1379 if (v.type != 'string' && v.type != 'integer'
1380 && v.type != 'symbol')
1381 throw new Xex.ErrTerm (MIM.Error.ParseError,
1382 "Invalid key: " + v);
1383 var key = new MIM.Key (v.val);
1384 this.val.push (key);
1385 if (key.has_modifier)
1386 this.has_modifier = true;
1391 var len = seq.val.length;
1392 for (var i = 0; i < len; i++)
1393 this.val.push (new MIM.Key (seq.val.charCodeAt (i)));
1396 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + seq);
1400 var proto = new Xex.Term ('keyseq');
1401 proto.Clone = function () { return this; }
1402 proto.Parser = function (domain, node)
1404 var seq = new Array ();
1405 for (node = node.firstChild; node; node = node.nextSibling)
1406 if (node.nodeType == 1)
1408 var term = Xex.Term.Parse (domain, node);
1409 return new MIM.KeySeq (term);
1411 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid keyseq");
1413 proto.toString = function ()
1415 var len = this.val.length;
1419 var str = '<keyseq>';
1420 for (var i = 0; i < len; i++)
1424 else if (this.has_modifier)
1426 str += this.val[i].toString ();
1428 return str + '</keyseq>';
1431 MIM.KeySeq.prototype = proto;
1435 MIM.Marker = function () { }
1436 MIM.Marker.prototype = new Xex.Term ('marker');
1437 MIM.Marker.prototype.CharAt = function (ic)
1439 var p = this.Position (ic);
1440 if (p < 0 || p >= ic.preedit.length)
1442 return ic.preedit.charCodeAt (p);
1445 MIM.FloatingMarker = function (name) { this.val = name; };
1446 var proto = new MIM.Marker ();
1447 MIM.FloatingMarker.prototype = proto;
1448 proto.Position = function (ic) { return ic.marker_positions[this.val]; };
1449 proto.Mark = function (ic) { ic.marker_positions[this.val] = ic.cursor_pos; };
1451 MIM.PredefinedMarker = function (name) { this.val = name; }
1452 MIM.PredefinedMarker.prototype = new MIM.Marker ();
1453 MIM.PredefinedMarker.prototype.Position = function (ic)
1455 if (typeof this.pos == 'number')
1457 return this.pos (ic);
1460 var predefined = { }
1462 function def_predefined (name, position)
1464 predefined[name] = new MIM.PredefinedMarker (name);
1465 predefined[name].pos = position;
1468 def_predefined ('@<', 0);
1469 def_predefined ('@>', function (ic) { return ic.preedit.length; });
1470 def_predefined ('@-', function (ic) { return ic.cursor_pos - 1; });
1471 def_predefined ('@+', function (ic) { return ic.cursor_pos + 1; });
1472 def_predefined ('@[', function (ic) {
1473 if (ic.cursor_pos > 0)
1475 var pos = ic.cursor_pos;
1476 return ic.preedit.FindProp ('candidates', pos - 1).from;
1480 def_predefined ('@]', function (ic) {
1481 if (ic.cursor_pos < ic.preedit.length - 1)
1483 var pos = ic.cursor_pos;
1484 return ic.preedit.FindProp ('candidates', pos).to;
1486 return ic.preedit.length;
1488 for (var i = 0; i < 10; i++)
1489 def_predefined ("@" + i, i);
1490 predefined['@first'] = predefined['@<'];
1491 predefined['@last'] = predefined['@>'];
1492 predefined['@previous'] = predefined['@-'];
1493 predefined['@next'] = predefined['@+'];
1494 predefined['@previous-candidate-change'] = predefined['@['];
1495 predefined['@next-candidate-change'] = predefined['@]'];
1497 MIM.SurroundMarker = function (name)
1500 this.distance = parseInt (name.slice (1));
1501 if (isNaN (this.distance))
1502 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid marker: " + name);
1504 MIM.SurroundMarker.prototype = new MIM.Marker ();
1505 MIM.SurroundMarker.prototype.Position = function (ic)
1507 return ic.cursor_pos + this.distance;
1509 MIM.SurroundMarker.prototype.CharAt = function (ic)
1511 if (this.val == '@-0')
1513 var p = this.Position (ic);
1515 return ic.GetSurroundingChar (p);
1516 else if (p >= ic.preedit.length)
1517 return ic.GetSurroundingChar (p - ic.preedit.length);
1518 return ic.preedit.charCodeAt (p);
1521 MIM.Marker.prototype.Parser = function (domain, node)
1523 var name = node.firstChild.nodeValue;
1524 if (name.charAt (0) == '@')
1526 var n = predefined[name];
1529 if (name.charAt (1) == '-')
1530 return new MIM.SurroundMarker (name);
1531 throw new Xex.ErrTerm (MIM.Error.ParseError,
1532 "Invalid marker: " + name);
1534 return new MIM.FloatingMarker (name);;
1538 MIM.Selector = function (name)
1542 MIM.Selector.prototype = new Xex.Term ('selector');
1546 selectors["@<"] = selectors["@first"] = new MIM.Selector ('@<');
1547 selectors["@="] = selectors["@current"] = new MIM.Selector ('@=');
1548 selectors["@>"] = selectors["@last"] = new MIM.Selector ('@>');
1549 selectors["@-"] = selectors["@previous"] = new MIM.Selector ('@-');
1550 selectors["@+"] = selectors["@next"] = new MIM.Selector ('@+');
1551 selectors["@["] = selectors["@previous-candidate-change"]
1552 = new MIM.Selector ('@[');
1553 selectors["@]"] = selectors["@next-candidate-change"]
1554 = new MIM.Selector ('@]');
1556 MIM.Selector.prototype.Parser = function (domain, node)
1558 var name = node.firstChild.nodeValue;
1559 var s = selectors[name];
1561 throw new Xex.ErrTerm (MIM.Error.ParseError,
1562 "Invalid selector: " + name);
1567 MIM.Rule = function (keyseq, actions)
1569 this.keyseq = keyseq;
1570 this.actions = actions;
1572 MIM.Rule.prototype = new Xex.Term ('rule');
1573 MIM.Rule.prototype.Parser = function (domain, node)
1576 for (n = node.firstChild; n && n.nodeType != 1; n = n.nextSibling);
1578 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1579 var keyseq = Xex.Term.Parse (domain, n);
1580 if (keyseq.type != 'keyseq')
1581 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1582 var actions = Xex.Term.Parse (domain, n.nextElement (), null);
1583 return new MIM.Rule (keyseq, actions);
1585 MIM.Rule.prototype.toString = function ()
1590 MIM.Map = function (name)
1593 this.rules = new Array ();
1597 var proto = new Xex.Term ('map');
1599 proto.Parser = function (domain, node)
1601 var name = node.attributes['mname'].nodeValue;
1603 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1604 var map = new MIM.Map (name);
1605 for (var n = node.firstChild; n; n = n.nextSibling)
1606 if (n.nodeType == 1)
1607 map.rules.push (Xex.Term.Parse (domain, n));
1611 proto.toString = function ()
1613 var str = '<map mname="' + this.name + '">';
1614 var len = this.rules.length;
1615 for (i = 0; i < len; i++)
1616 str += this.rules[i];
1617 return str + '</map>';
1620 MIM.Map.prototype = proto;
1623 Xex.CatchTag._mimtag = new Xex.SymTerm ('@mimtag');
1625 MIM.Action = function (domain, terms)
1627 var args = new Array ();
1628 args.push (Xex.CatchTag_.mimtag);
1629 for (var i = 0; i < terms.length; i++)
1630 args.push (terms[i]);
1631 this.action = Xex.Funcall.prototype.New (domain, 'catch', null, args);
1634 MIM.Action.prototype.Run = function (domain)
1636 var result = this.action.Eval (domain);
1637 if (result.type == 'error')
1639 domain.context.Error = result.toString ();
1642 return (result != Xex.CatchTag._mimtag);
1645 MIM.Keymap = function ()
1648 this.submaps = null;
1654 function add_rule (keymap, rule, branch_actions)
1656 var keyseq = rule.keyseq;
1657 var len = keyseq.val.length;
1660 for (var i = 0; i < len; i++)
1662 var key = keyseq.val[i];
1666 if (! keymap.submaps)
1667 keymap.submaps = {};
1669 sub = keymap.submaps[key.key];
1671 keymap.submaps[key.key] = sub = new MIM.Keymap ();
1675 keymap.map_actions = rule.actions;
1676 keymap.branch_actions = branch_actions;
1679 proto.Add = function (map, branch_actions)
1681 var rules = map.rules;
1682 var len = rules.length;
1684 for (var i = 0; i < len; i++)
1685 add_rule (this, rules[i], branch_actions);
1687 proto.Lookup = function (keys, index)
1691 if (index < keys.val.length && this.submaps
1692 && (sub = this.submaps[keys.val[index].key]))
1695 return sub.Lookup (keys, index);
1697 return { map: this, index: index };
1700 MIM.Keymap.prototype = proto;
1703 MIM.State = function (name)
1706 this.keymap = new MIM.Keymap ();
1710 var proto = new Xex.Term ('state');
1712 proto.Parser = function (domain, node)
1714 var map_list = domain.map_list;
1715 var name = node.attributes['sname'].nodeValue;
1717 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1718 var state = new MIM.State (name);
1719 for (node = node.firstElement (); node; node = node.nextElement ())
1721 if (node.nodeName == 'title')
1722 state.title = node.firstChild.nodeValue;
1725 var n = node.firstElement ();
1726 if (node.nodeName == 'branch')
1727 state.keymap.Add (map_list[node.attributes['mname'].nodeValue],
1728 Xex.Term.Parse (domain, n, null));
1729 else if (node.nodeName == 'state-hook')
1730 state.enter_actions = Xex.Term.Parse (domain, n, null);
1731 else if (node.nodeName == 'catch-all-branch')
1732 state.fallback_actions = Xex.Term.Parse (domain, n, null);
1738 proto.toString = function ()
1740 return '<state sname="' + this.name + '">' + this.keymap + '</state>';
1743 MIM.State.prototype = proto;
1747 function Block (index, term)
1751 this.Data = term.val;
1752 else if (term.IsList)
1754 this.Data = new Array ();
1755 for (var i = 0; i < term.val.length; i++)
1756 this.Data.push (term.val[i].val);
1760 Block.prototype.Count = function () { return this.Data.length; }
1761 Block.prototype.get = function (i)
1763 return (this.Data instanceof Array ? this.Data[i] : this.Data.charAt (i));
1766 MIM.Candidates = function (candidates, column)
1768 this.column = column;
1772 this.blocks = new Array ();
1774 for (var i = 0; i < candidates.length; i++)
1776 var block = new Block (this.total, candidates[i]);
1777 this.blocks.push (block);
1778 this.total += block.Count ();
1784 return (this.column > 0 ? this.index % this.column
1785 : this.index - this.blocks[this.row].Index);
1788 function prev_group ()
1790 var col = get_col.call (this);
1792 if (this.column > 0)
1794 this.index -= this.column;
1795 if (this.index >= 0)
1796 nitems = this.column;
1799 var lastcol = (this.total - 1) % this.column;
1800 this.index = (col < lastcol ? this.total - lastcol + col
1802 this.row = this.blocks.length - 1;
1803 nitems = lastcol + 1;
1805 while (this.blocks[this.row].Index > this.index)
1810 this.row = this.row > 0 ? this.row - 1 : this.blocks.length - 1;
1811 nitems = this.blocks[this.row].Count ();
1812 this.index = (this.blocks[this.row].Index
1813 + (col < nitems ? col : nitems - 1));
1818 function next_group ()
1820 var col = get_col.call (this);
1822 if (this.column > 0)
1824 this.index += this.column - col;
1825 if (this.index < this.total)
1827 if (this.index + col >= this.total)
1829 nitems = this.total - this.index;
1830 this.index = this.total - 1;
1834 nitems = this.column;
1843 while (this.blocks[this.row].Index > this.index)
1848 this.row = this.row < this.blocks.length - 1 ? this.row + 1 : 0;
1849 nitems = this.blocks[this.row].Count ();
1850 this.index = (this.blocks[this.row].Index
1851 + (col < nitems ? col : nitems - 1));
1858 if (this.index == 0)
1860 this.index = this.total - 1;
1861 this.row = this.blocks.length - 1;
1866 if (this.blocks[this.row].Index > this.index)
1874 if (this.index == this.total)
1881 var b = this.blocks[this.row];
1882 if (this.index == b.Index + b.Count ())
1889 this.index -= get_col.call (this);
1890 while (this.blocks[this.row].Index > this.index)
1896 var b = this.blocks[this.row];
1897 if (this.column > 0)
1899 if (this.index + 1 < this.total)
1901 this.index += this.column - get_col.call (this) + 1;
1902 while (b.Index + b.Count () <= this.index)
1903 b = this.blocks[++this.row];
1907 this.index = b.Index + b.Count () - 1;
1910 MIM.Candidates.prototype.Current = function ()
1912 var b = this.blocks[this.row];
1913 return b.get (this.index - b.Index);
1916 MIM.Candidates.prototype.Select = function (selector)
1918 if (selector.type == 'selector')
1920 switch (selector.val)
1922 case '@<': first.call (this); break;
1923 case '@>': last.call (this); break;
1924 case '@-': prev.call (this); break;
1925 case '@+': next.call (this); break;
1926 case '@[': prev_group.call (this); break;
1927 case '@]': next_group.cal (this); break;
1930 return this.Current ();
1933 if (this.column > 0)
1935 col = this.index % this.column;
1936 start = this.index - col;
1937 end = start + this.column;
1941 start = this.blocks[this.row].Index;
1942 col = this.index - start;
1943 end = start + this.blocks[this.row].Count;
1945 if (end > this.total)
1947 this.index += selector.val - col;
1948 if (this.index >= end)
1949 this.index = end - 1;
1950 if (this.column > 0)
1952 if (selector.val > col)
1953 while (this.blocks[this.row].Index + this.blocks[this.row].Count
1957 while (this.blocks[this.row].Index > this.index)
1960 return this.Current ();
1964 MIM.im_domain = new Xex.Domain ('input-method', null, null);
1965 MIM.im_domain.DefType (MIM.KeySeq.prototype);
1966 MIM.im_domain.DefType (MIM.Marker.prototype);
1967 MIM.im_domain.DefType (MIM.Selector.prototype);
1968 MIM.im_domain.DefType (MIM.Rule.prototype);
1969 MIM.im_domain.DefType (MIM.Map.prototype);
1970 MIM.im_domain.DefType (MIM.State.prototype);
1973 var im_domain = MIM.im_domain;
1975 function Finsert (domain, vari, args)
1978 if (args[0].type == 'integer')
1979 text = String.fromCharCode (args[0].val);
1982 domain.context.ins (text, null);
1986 function Finsert_candidates (domain, vari, args)
1988 var ic = domain.context;
1989 var gsize = domain.variables['candidates_group_size'];
1990 var candidates = new MIM.Candidates (args, gsize ? gsize.Intval : 0);
1991 ic.ins (candidates.Current (), candidates);
1995 function Fdelete (domain, vari, args)
1997 var ic = domain.context;
1998 var pos = args[0].IsInt ? args[0].Intval : args[0].Position (ic);
1999 return new Xex.IntTerm (ic.del (pos));
2002 function Fselect (domain, vari, args)
2004 var ic = domain.context;
2005 var can = ic.candidates;
2009 var old_text = can.Current ();
2010 var new_text = can.Select (args[0]);
2011 ic.rep (old_text, new_text, can);
2014 Xex.Log ('no candidates at ' + ic.cursor_pos + ' of ' + ic.candidate_table.table.length);
2018 function Fchar_at (domain, vari, args)
2020 return new Xex.IntTerm (args[0].CharAt (domain.context));
2023 function Fmove (domain, vari, args)
2025 var ic = domain.context;
2026 var pos = args[0].IsInt ? args[0].val : args[0].Position (ic);
2028 return new Xex.IntTerm (pos);
2031 function Fmark (domain, vari, args)
2033 args[0].Mark (domain.context);
2037 function Fpushback (domain, vari, args)
2039 var a = (args[0].IsInt ? args[0].Intval ()
2040 : args[0].IsStr ? new KeySeq (args[0])
2042 domain.context.pushback (a);
2046 function Fundo (domain, vari, args)
2048 var ic = domain.context;
2049 var n = args.length == 0 ? -2 : args[0].val;
2051 ic.keys.val.splice (ic.keys.length + n, -n);
2053 ic.keys.val.splice (n, ic.keys.length);
2058 function Fcommit (domain, vari, args)
2060 domain.context.commit ();
2064 function Funhandle (domain, vari, args)
2066 domain.context.commit ();
2067 return Xex.Fthrow (domain, vari, Xex.CatchTag._mimtag);
2070 function Fshift (domain, vari, args)
2072 var ic = domain.context;
2073 var state_name = args[0].val;
2074 var state = ic.im.state_list[state_name];
2076 throw ("Unknown state: " + state_name);
2081 function Fsurrounding_flag (domain, vari, args)
2083 return new Xex.IntTerm (-1);
2086 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
2087 im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, 1);
2088 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
2089 im_domain.DefSubr (Fselect, "select", false, 1, 1);
2090 //im_domain.DefSubr (Fshow, "show-candidates", false, 0, 0);
2091 //im_domain.DefSubr (Fhide, "hide-candidates", false, 0, 0);
2092 im_domain.DefSubr (Fmove, "move", false, 1, 1);
2093 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
2094 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
2095 //im_domain.DefSubr (Fpop, "pop", false, 0, 0);
2096 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
2097 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
2098 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
2099 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
2100 //im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
2101 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
2102 //im_domain.DefSubr (Fkey_count, "key-count", false, 0, 0);
2103 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag", false, 0, 0);
2108 function get_global_var (vname)
2110 if (MIM.im_global.load_status == MIM.LoadStatus.NotLoaded)
2111 MIM.im_global.Load ()
2112 return MIM.im_global.domain.variables[vname];
2115 function include (node)
2117 node = node.firstElement ();
2118 if (node.nodeName != 'tags')
2121 var lang = null, name = null, extra = null;
2122 for (node = node.firstElement (); node; node = node.nextElement ())
2124 if (node.nodeName == 'language')
2125 lang = node.firstChild.nodeValue;
2126 else if (node.nodeName == 'name')
2127 name = node.firstChild.nodeValue;
2128 else if (node.nodeName == 'extra-id')
2129 extra = node.firstChild.nodeValue;
2131 if (! lang || ! MIM.imlist[lang])
2135 if (! name || ! (im = MIM.imlist[lang][name]))
2140 if (! (im = MIM.imextra[lang][extra]))
2143 if (im.load_status != MIM.LoadStatus.Loaded
2144 && (im.load_status != MIM.LoadStatus.NotLoaded || ! im.Load ()))
2151 parsers['description'] = function (node)
2153 this.description = node.firstChild.nodeValue;
2155 parsers['variable-list'] = function (node)
2157 for (node = node.firstElement (); node; node = node.nextElement ())
2159 var vname = node.attributes['vname'].nodeValue;
2160 if (this != MIM.im_global)
2162 var vari = get_global_var (vname);
2164 this.domain.Defvar (vname);
2166 vname = Xex.Term.Parse (this.domain, node)
2169 parsers['command-list'] = function (node)
2172 parsers['macro-list'] = function (node)
2174 for (var n = node.firstElement (); n; n = n.nextElement ())
2175 if (n.nodeName == 'xi:include')
2177 var im = include (n);
2179 alert ('inclusion fail');
2181 for (var macro in im.domain.functions)
2183 var func = im.domain.functions[macro];
2184 if (func instanceof Xex.Macro)
2185 im.domain.CopyFunc (this.domain, macro);
2187 n = n.previousSibling;
2188 node.removeChild (n.nextSibling);
2190 Xex.Term.Parse (this.domain, node.firstElement (), null);
2192 parsers['title'] = function (node)
2194 this.title = node.firstChild.nodeValue;
2196 parsers['map-list'] = function (node)
2198 for (node = node.firstElement (); node; node = node.nextElement ())
2200 if (node.nodeName == 'xi:include')
2202 var im = include (node);
2205 alert ('inclusion fail');
2208 for (var mapname in im.map_list)
2209 this.map_list[mapname] = im.map_list[mapname];
2213 var map = Xex.Term.Parse (this.domain, node);
2214 this.map_list[map.name] = map;
2218 parsers['state-list'] = function (node)
2220 this.domain.map_list = this.map_list;
2221 for (node = node.firstElement (); node; node = node.nextElement ())
2223 if (node.nodeName == 'state')
2225 var state = Xex.Term.Parse (this.domain, node);
2227 state.title = this.title;
2228 if (! this.initial_state)
2229 this.initial_state = state;
2230 this.state_list[state.name] = state;
2233 delete this.domain.map_list;
2236 MIM.IM = function (lang, name, extra_id, file)
2240 this.extra_id = extra_id;
2242 this.load_status = MIM.LoadStatus.NotLoaded;
2243 this.domain = new Xex.Domain (this.lang + '-'
2244 + (this.name != 'nil'
2245 ? this.name : this.extra_id),
2246 MIM.im_domain, null);
2252 var node = Xex.Load (null, this.file);
2255 this.load_status = MIM.LoadStatus.Error;
2259 this.initial_state = null;
2260 this.state_list = {};
2261 for (node = node.firstElement (); node; node = node.nextElement ())
2263 var name = node.nodeName;
2264 var parser = parsers[name];
2266 parser.call (this, node);
2268 this.load_status = MIM.LoadStatus.Loaded;
2273 MIM.IM.prototype = proto;
2275 MIM.IC = function (im, target)
2277 if (im.load_status == MIM.LoadStatus.NotLoaded)
2279 if (im.load_status != MIM.LoadStatus.Loaded)
2280 alert ('im:' + im.name + ' error:' + im.load_status);
2282 this.target = target;
2283 this.domain = new Xex.Domain ('context', im.domain, this);
2285 this.range = new Array ();
2286 this.range[0] = this.range[1] = 0;
2288 this.initial_state = this.im.initial_state;
2289 this.keys = new MIM.KeySeq ();
2290 this.marker_positions = new Array ();
2291 this.candidate_table = new MIM.CandidateTable ();
2295 MIM.CandidateTable = function ()
2297 this.table = new Array ();
2300 MIM.CandidateTable.prototype.get = function (pos)
2302 for (var i = 0; i < this.table.length; i++)
2304 var elt = this.table[i];
2305 if (elt.from < pos && pos <= elt.to)
2310 MIM.CandidateTable.prototype.put = function (from, to, candidates)
2312 for (var i = 0; i < this.table.length; i++)
2314 var elt = this.table[i];
2315 if (elt.from < to && elt.to > from)
2319 elt.val = candidates;
2323 this.table.push ({ from: from, to: to, val: candidates });
2326 MIM.CandidateTable.prototype.adjust = function (from, to, inserted)
2328 var diff = inserted - (to - from);
2331 for (var i = 0; i < this.table.length; i++)
2333 var elt = this.table[i];
2342 MIM.CandidateTable.prototype.clear = function ()
2344 this.table.length = 0;
2347 function detach_candidates (ic)
2349 ic.candidate_table.clear ();
2350 ic.candidates = null;
2351 ic.changed |= (MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos
2352 | ChangedStatus.CandidateList
2353 | ChangedStatus.CandidateIndex
2354 | ChangedStatus.CandidateShow);
2357 function set_cursor (prefix, pos)
2359 this.cursor_pos = pos;
2360 this.candidates = this.candidate_table.get (pos);
2363 function save_state ()
2365 this.state_var_values = this.domain.SaveValues ();
2366 this.state_preedit = this.preedit;
2367 this.state_key_head = this.key_head;
2368 this.state_pos = this.cursor_pos;
2371 function restore_state ()
2373 this.domain.RestoreValues (this.state_var_values);
2374 this.preedit = this.state_preedit;
2375 set_cursor.call (this, "restore", this.state_pos);
2378 function handle_key ()
2380 var out = this.keymap.Lookup (this.keys, this.key_head);
2383 Xex.Log ('handling ' + this.keys.val[this.key_head]
2384 + ' in ' + this.state.name + ':' + this.keymap.name);
2385 this.key_head = out.index;
2386 if (sub != this.keymap)
2389 restore_state.call (this);
2391 Xex.Log ('submap found');
2392 if (this.keymap.map_actions)
2394 Xex.Log ('taking map actions:');
2395 if (! this.take_actions (this.keymap.map_actions))
2398 else if (this.keymap.submaps)
2400 Xex.Log ('no map actions');
2401 for (var i = this.state_key_head; i < this.key_head; i++)
2403 Xex.Log ('inserting key:' + this.keys.val[i].key);
2404 this.ins (this.keys.val[i].key, null);
2407 if (! this.keymap.submaps)
2409 Xex.Log ('terminal:');
2410 if (this.keymap.branch_actions != null)
2412 Xex.Log ('branch actions:');
2413 if (! this.take_actions (this.keymap.branch_actions))
2416 if (this.keymap != this.state.keymap)
2417 this.shift (this.state);
2422 Xex.Log ('no submap');
2423 var current_state = this.state;
2424 var map = this.keymap;
2426 if (map.branch_actions)
2428 Xex.Log ('branch actions');
2429 if (! this.take_actions (map.branch_actions))
2433 if (map == this.keymap)
2435 Xex.Log ('no state change');
2436 if (map == this.initial_state.keymap
2437 && this.key_head < this.keys.val.length)
2439 Xex.Log ('unhandled');
2442 if (this.keymap != current_state.keymap)
2443 this.shift (current_state);
2444 else if (this.keymap.actions == null)
2445 this.shift (this.initial_state);
2454 this.cursor_pos = 0;
2455 this.candidate_show = false;
2456 this.prev_state = null;
2457 this.title = this.initial_state.title;
2458 this.state_preedit = '';
2459 this.state_key_head = 0;
2460 this.state_var_values = {};
2463 this.keys.val.length = 0;
2464 this.key_unhandled = false;
2465 this.unhandled_key = null;
2466 this.changed = MIM.ChangedStatus.None;
2467 this.error_message = '';
2468 this.title = this.initial_state.title;
2471 this.preedit_saved = '';
2472 this.candidate_table.clear ();
2473 this.candidates = null;
2474 this.candidate_show = false;
2475 for (var elt in this.marker_positions)
2476 this.marker_positions[elt] = 0;
2477 this.shift (this.initial_state);
2480 catch_args: new Array (Xex.CatchTag._mimtag, null),
2482 take_actions: function (actions)
2484 var func_progn = this.domain.GetFunc ('progn');
2485 var func_catch = this.domain.GetFunc ('catch');
2486 this.catch_args[1] = new Xex.Funcall (func_progn, null, actions);
2487 var term = new Xex.Funcall (func_catch, null, this.catch_args);
2488 term = term.Eval (this.domain);
2489 return (! term.IsSymbol || term.val != '@mimtag');
2492 GetSurroundingChar: function (pos)
2496 pos += this.range[0];
2502 pos += this.range[1];
2503 if (pos >= this.target.value.length)
2506 return this.target.value.charCodeAt (pos);
2509 DelSurroundText: function (pos)
2514 pos += this.range[0];
2520 text = this.target.value.substring (0, pos);
2521 if (this.range[0] < this.target.value.length)
2522 text += this.target.value.substring (this.range[0]);
2523 this.target.value = text;
2524 this.range[1] -= this.range[0] - pos;
2525 this.range[0] = pos;
2529 pos += this.range[1];
2530 text = this.target.value.substring (0, this.range[1]);
2531 if (pos >= this.target.value.length)
2532 pos = this.target.value.length;
2534 text += this.target.value.substring (pos);
2535 this.target.value = text;
2539 adjust_markers: function (from, to, inserted)
2541 var diff = inserted - (to - from);
2543 for (var name in this.marker_positions)
2545 var pos = this.marker_positions[name];
2549 this.marker_positions[name] += diff;
2550 else if (pos > from)
2551 this.marker_positions[name] = from;
2554 if (this.cursor_pos >= to)
2555 set_cursor.call (this, 'adjust', this.cursor_pos + diff);
2556 else if (this.cursor_pos > from)
2557 set_cursor.call (this, 'adjust', from)
2560 preedit_replace: function (from, to, text, candidates)
2562 this.preedit = (this.preedit.substring (0, from)
2563 + text + this.preedit.substring (to));
2564 this.adjust_markers (from, to, text.length);
2565 this.candidate_table.adjust (from, to, text.length);
2567 this.candidate_table.put (from, from + text.length, candidates)
2570 ins: function (text, candidates)
2572 this.preedit_replace (this.cursor_pos, this.cursor_pos, text, candidates);
2573 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2576 rep: function (old_text, new_text, candidates)
2578 this.preedit_replace (this.cursor_pos - old_text.length,
2579 this.cursor_pos, new_text, candidates);
2580 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2585 var deleted = pos - this.cursor_pos;
2586 if (pos < this.cursor_pos)
2590 this.DelSurroundText (pos);
2591 deleted = - this.cursor_pos;
2594 if (pos < this.cursor_pos)
2595 this.preedit_replace (pos, this.cursor_pos, '', null);
2599 if (pos > this.preedit.length)
2601 this.DelSurroundText (pos - this.preedit.length);
2602 deleted = this.preedit.length - this.cursor_pos;
2603 pos = this.preedit.length;
2605 if (pos > this.cursor_pos)
2606 this.preedit_replace (this.cursor_pos, pos, '', null);
2609 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2615 this.candidate_show = true;
2616 this.changed |= MIM.ChangedStatus.CandidateShow;
2621 this.candidate_show = false;
2622 this.changed |= MIM.ChangedStatus.CandidateShow;
2625 move: function (pos)
2629 else if (pos > this.preedit.length)
2630 pos = this.preedit.length;
2631 if (pos != this.cursor_pos)
2633 set_cursor.call (this, 'move', pos);
2634 this.changed |= MIM.ChangedStatus.Preedit;
2638 pushback: function (n)
2640 if (n instanceof MIM.KeySeq)
2642 if (this.key_head > 0)
2644 if (this.key_head < this.keys.val.length)
2645 this.keys.val.splice (this.key_head,
2646 this.keys.val.length - this.key_head);
2647 for (var i = 0; i < n.val.length; i++)
2648 this.keys.val.push (n.val[i]);
2654 if (this.key_head < 0)
2661 this.key_head = - n;
2662 if (this.key_head > this.keys.val.length)
2663 this.key_head = this.keys.val.length;
2669 if (this.key_head < this.keys.val.length)
2670 this.keys.val.splice (this.key_head, 1);
2675 if (this.preedit.length > 0)
2677 this.candidate_table.clear ();
2678 this.produced += this.preedit;
2679 this.preedit_replace.call (this, 0, this.preedit.length, '', null);
2683 shift: function (state)
2687 if (this.prev_state == null)
2689 state = this.prev_state;
2692 if (state == this.initial_state)
2697 this.keys.val.splice (0, this.key_head);
2699 this.prev_state = null;
2704 if (state != this.state)
2705 this.prev_state = this.state;
2707 if (state != this.state && state.enter_actions)
2708 this.take_actions (state.enter_actions);
2709 if (! this.state || this.state.title != state.title)
2710 this.changed |= MIM.ChangedStatus.StateTitle;
2712 this.keymap = state.keymap;
2713 this.state_key_head = this.key_head;
2714 save_state.call (this);
2717 Filter: function (key)
2721 this.key_unhandled = true;
2722 this.unhandled_key = key;
2725 if (key.key == '_reload')
2727 this.changed = MIM.ChangedStatus.None;
2729 this.key_unhandled = false;
2730 this.keys.val.push (key);
2732 while (this.key_head < this.keys.val.length)
2734 if (! handle_key.call (this))
2736 if (this.key_head < this.keys.val.length)
2738 this.unhandled_key = this.keys.val[this.key_head];
2739 this.keys.val.splice (this.key_head, this.key_head + 1);
2741 this.key_unhandled = true;
2747 this.key_unhandled = true;
2751 if (this.key_unhandled)
2753 this.keys.val.length = 0;
2754 this.key_head = this.state_key_head = this.commit_key_head = 0;
2756 return (! this.key_unhandled
2757 && this.produced.length == 0
2758 && this.preedit.length == 0);
2762 MIM.IC.prototype = proto;
2764 var node = Xex.Load (null, "imlist.xml");
2765 for (node = node.firstChild; node; node = node.nextSibling)
2766 if (node.nodeName == 'input-method')
2768 var lang = null, name = null, extra_id = null, file = null;
2770 for (var n = node.firstChild; n; n = n.nextSibling)
2772 if (n.nodeName == 'language')
2773 lang = n.firstChild.nodeValue;
2774 else if (n.nodeName == 'name')
2775 name = n.firstChild.nodeValue;
2776 else if (n.nodeName == 'extra-id')
2777 extra_id = n.firstChild.nodeValue;
2778 else if (n.nodeName == 'filename')
2779 file = n.firstChild.nodeValue;
2781 if (name && name != 'nil')
2783 if (! MIM.imlist[lang])
2784 MIM.imlist[lang] = {};
2785 MIM.imlist[lang][name] = new MIM.IM (lang, name, extra_id, file);
2787 else if (extra_id && extra_id != 'nil')
2789 if (! MIM.imextra[lang])
2790 MIM.imextra[lang] = {};
2791 MIM.imextra[lang][extra_id] = new MIM.IM (lang, name, extra_id, file);
2794 if (MIM.imextra.t && MIM.imextra.t.global)
2795 MIM.im_global = MIM.imextra.t.global;
2798 MIM.im_global = new MIM.IM ('t', 'nil', 'global', null);
2799 MIM.im_global.load_status = MIM.LoadStatus.Error;
2805 var keys = new Array ();
2807 keys[0x08] = 'backspace';
2808 keys[0x0D] = 'return';
2809 keys[0x1B] = 'escape';
2810 keys[0x20] = 'space';
2811 keys[0x21] = 'pageup';
2812 keys[0x22] = 'pagedown';
2814 keys[0x24] = 'home';
2815 keys[0x25] = 'left';
2817 keys[0x27] = 'right';
2818 keys[0x28] = 'down';
2819 keys[0x2D] = 'insert';
2820 keys[0x2E] = 'delete';
2821 for (var i = 1; i <= 12; i++)
2822 keys[111 + i] = "f" + i;
2823 keys[0x90] = "numlock";
2824 keys[0xF0] = "capslock";
2826 MIM.decode_key_event = function (event)
2828 var key = ((event.type == 'keydown' || event.keyCode) ? event.keyCode
2829 : event.charCode ? event.charCode
2833 if (event.type == 'keydown')
2838 if (event.shiftKey) key = "S-" + key ;
2841 key = String.fromCharCode (key);
2842 if (event.altKey) key = "A-" + key ;
2843 if (event.ctrlKey) key = "C-" + key ;
2844 return new MIM.Key (key);
2848 MIM.add_event_listener
2849 = (window.addEventListener
2850 ? function (target, type, listener) {
2851 target.addEventListener (type, listener, false);
2853 : window.attachEvent
2854 ? function (target, type, listener) {
2855 target.attachEvent ('on' + type,
2857 listener.call (target, window.event);
2860 : function (target, type, listener) {
2862 = function (e) { listener.call (target, e || window.event); };
2865 MIM.debug_print = function (event, ic)
2869 if (! MIM.debug_nodes)
2871 MIM.debug_nodes = new Array ();
2872 MIM.debug_nodes['keydown'] = document.getElementById ('keydown');
2873 MIM.debug_nodes['keypress'] = document.getElementById ('keypress');
2874 MIM.debug_nodes['status0'] = document.getElementById ('status0');
2875 MIM.debug_nodes['status1'] = document.getElementById ('status1');
2876 MIM.debug_nodes['keymap0'] = document.getElementById ('keymap0');
2877 MIM.debug_nodes['keymap1'] = document.getElementById ('keymap1');
2878 MIM.debug_nodes['preedit0'] = document.getElementById ('preedit0');
2879 MIM.debug_nodes['preedit1'] = document.getElementById ('preedit1');
2881 var target = event.target;
2882 var code = event.keyCode;
2883 var ch = event.type == 'keydown' ? 0 : event.charCode;
2884 var key = MIM.decode_key_event (event);
2887 MIM.debug_nodes[event.type].innerHTML = "" + code + "/" + ch + " : " + key;
2888 index = (event.type == 'keydown' ? '0' : '1');
2890 MIM.debug_nodes['status' + index].innerHTML = ic.im.load_status;
2892 MIM.debug_nodes['status' + index].innerHTML = 'no IM';
2893 MIM.debug_nodes['keymap' + index].innerHTML = ic.state.name;
2894 MIM.debug_nodes['preedit' + index].innerHTML = ic.preedit;
2897 MIM.debug_nodes.keypress.innerHTML = '';
2898 MIM.debug_nodes.status1.innerHTML = '';
2899 MIM.debug_nodes.keymap1.innerHTML = '';
2900 MIM.debug_nodes.preedit1.innerHTML = ''
2904 MIM.get_range = function (target, ic)
2907 if (target.selectionStart != null) // for Mozilla
2909 from = target.selectionStart;
2910 to = target.selectionEnd;
2914 var r = document.selection.createRange ();
2915 var rr = r.duplicate ();
2917 rr.moveToElementText (target);
2918 rr.setEndPoint ('EndToEnd', range);
2919 from = rr.text.length - r.text.length;
2920 to = rr.text.length;
2922 if (ic.range[0] == from && ic.range[1] == to
2923 && (to == from || target.value.substring (from, to) == ic.preedit))
2930 MIM.set_caret = function (target, ic)
2932 if (target.setSelectionRange) // Mozilla
2934 var scrollTop = target.scrollTop;
2935 target.setSelectionRange (ic.range[0], ic.range[1]);
2936 target.scrollTop = scrollTop;
2940 var range = target.createTextRange ();
2941 range.moveStart ('character', ic.range[0]);
2942 range.moveEnd ('character', ic.range[1]);
2947 MIM.update = function (target, ic)
2949 var text = target.value;
2950 target.value = (text.substring (0, ic.range[0])
2953 + text.substring (ic.range[1]));
2954 ic.range[0] += ic.produced.length;
2955 ic.range[1] = ic.range[0] + ic.preedit.length;
2956 MIM.set_caret (target, ic);
2959 MIM.reset_ic = function (event)
2961 if (event.target.mim_ic)
2963 var target = event.target;
2964 var ic = target.mim_ic;
2965 if (ic.preedit.length > 0)
2966 event.target.setSelectionRange (ic.range[1], ic.range[1]);
2971 MIM.keydown = function (event)
2973 var target = event.target;
2974 if (target.id == 'log')
2976 if (! (target.type == "text" || target.type == "textarea"))
2979 var ic = target.mim_ic;
2980 if (! ic || ic.im != MIM.current)
2982 target.mim_ic = null;
2983 Xex.Log ('creating IC');
2984 ic = new MIM.IC (MIM.current, target);
2985 if (ic.im.load_status != MIM.LoadStatus.Loaded)
2988 MIM.add_event_listener (target, 'blur', MIM.reset_ic);
2989 MIM.get_range (target, ic)
2993 if (! MIM.get_range (target, ic))
2996 MIM.debug_print (event, ic);
2997 ic.key = MIM.decode_key_event (event);
3000 MIM.keypress = function (event)
3002 var target = event.target;
3003 if (target.id == 'log')
3005 if (! (target.type == "text" || target.type == "textarea"))
3008 var ic = target.mim_ic;
3012 if (ic.im.load_status != MIM.LoadStatus.Loaded)
3015 ic.key = MIM.decode_key_event (event);
3022 Xex.Log ("filtering " + ic.key);
3023 var result = ic.Filter (ic.key);
3024 MIM.update (target, ic);
3025 if (! ic.key_unhandled)
3026 event.preventDefault ();
3028 MIM.debug_print (event, ic);
3034 var lang_category = {
3036 cs: { name: 'Czech' },
3037 da: { name: 'Danish' },
3038 el: { name: 'Greek' },
3039 eo: { name: 'Esperanto' },
3040 fr: { name: 'French' },
3041 hr: { name: 'Croatian' },
3042 hy: { name: 'Armenian' },
3043 kk: { name: 'Kazakh' },
3044 ru: { name: 'Russian' },
3045 sk: { name: 'Slovak' },
3046 sr: { name: 'Serbian' },
3047 sv: { name: 'Swedish' },
3048 vi: { name: 'Vietnamese' },
3049 yi: { name: 'Yiddish' } },
3051 ar: { name: 'Arabic' },
3052 dv: { name: 'Divehi' },
3053 fa: { name: 'Persian' },
3054 he: { name: 'Hebrew' },
3055 kk: { name: 'Kazakh' },
3056 ps: { name: 'Pushto' },
3057 ug: { name: 'Uighur' },
3058 yi: { name: 'Yiddish' } },
3060 as: { name: 'Assamese' },
3061 bn: { name: 'Bengali' },
3062 bo: { name: 'Tibetan' },
3063 gu: { name: 'Gujarati' },
3064 hi: { name: 'Hindi' },
3065 kn: { name: 'Kannada' },
3066 ks: { name: 'Kashmiri' },
3067 ml: { name: 'Malayalam' },
3068 mr: { name: 'Marathi' },
3069 ne: { name: 'Nepali' },
3070 or: { name: 'Oriya' },
3071 pa: { name: 'Panjabi' },
3072 sa: { name: 'Sanskirit' },
3073 sd: { name: 'Sindhi' },
3074 si: { name: 'Sinhalese' },
3075 ta: { name: 'Tamil' },
3076 te: { name: 'Telugu' },
3077 ur: { name: 'Urdu' } },
3079 km: { name: 'Khmer'},
3080 lo: { name: 'Lao' },
3081 my: { name: 'Burmese' },
3082 tai: { name: 'Tai Viet' },
3083 th: { name: 'Thai' },
3084 vi: { name: 'Vietanamese' } },
3086 ii: { name: 'Yii' },
3087 ja: { name: 'Japanese' },
3088 ko: { name: 'Korean' },
3089 zh: { name: 'Chinese' } },
3091 am: { name: 'Amharic' },
3092 ath: { name: 'Carrier' },
3093 bla: { name: 'Blackfoot' },
3094 cr: { name: 'Cree' },
3095 eo: { name: 'Esperanto' },
3096 iu: { name: 'Inuktitut' },
3097 nsk: { name: 'Naskapi' },
3098 oj: { name: 'Ojibwe' } }
3101 function categorize_im ()
3103 var cat, lang, list, name;
3104 for (lang in MIM.imlist)
3107 for (cat in lang_category)
3108 if (lang_category[cat][lang])
3110 list = lang_category[cat][lang].list;
3112 list = lang_category[cat][lang].list = {};
3116 for (name in MIM.imlist[lang])
3117 list[name] = MIM.imlist[lang][name];
3125 clearTimeout (destroy_timer);
3126 var target = document.getElementById ('mim-menu');
3128 document.getElementsByTagName ('body')[0].removeChild (target);
3131 function destroy_menu () { destroy_timer = setTimeout (destroy, 1000); }
3135 function show_submenu (event)
3138 clearTimeout (destroy_timer);
3139 var target = event.target;
3140 if (target.menu_level)
3142 Xex.Log ("menu show level " + target.menu_level + ': '
3144 if (! last_target || last_target.parentLi == target)
3146 Xex.Log ('Sub opened');
3150 Xex.Log ('Sibling opened');
3151 last_target.style.backgroundColor = 'white';
3152 var uls = last_target.getElementsByTagName ('ul');
3153 for (var i = 0; i < uls.length; i++)
3154 uls[i].style.visibility = 'hidden';
3156 last_target = target;
3157 target.style.backgroundColor = 'yellow';
3158 target.lastChild.style.visibility = 'visible';
3159 target.lastChild.style.left = target.clientWidth + 'px';
3160 event.preventDefault ();
3164 function hide_submenu (event)
3166 var target = event.target;
3167 target.style.backgroundColor = 'white';
3168 for (var ul = target.firstChild; ul; ul = ul.nextSibling)
3169 if (ul.tagName == 'UL')
3170 ul.style.visibility = 'hidden';
3173 function select_im (event)
3175 var target = event.target.parentNode;
3176 while (target.tagName != "mim-menu")
3177 target = target.parentNode;
3180 for (var lang in MIM.imlist)
3181 for (var name in MIM.imlist[lang])
3182 if (idx++ == target.selectedIndex)
3184 im = MIM.imlist[lang][name];
3187 document.getElementsByTagName ('body')[0].removeChild (target);
3188 target.target.focus ();
3189 if (im && im != MIM.current)
3192 Xex.Log ('select IM: ' + im.name);
3198 function create_menu (event)
3200 var target = event.target;
3202 if (! ((target.type == "text" || target.type == "textarea")
3203 && event.which == 1 && event.ctrlKey))
3208 menu = document.createElement ('ul');
3209 menu.style.fontFamily = 'sans-serif';
3210 menu.style.fontWeight = 'bold';
3211 menu.style.margin = '0px';
3212 menu.style.padding = '0px';
3213 menu.style.border = '1px solid gray';
3214 menu.style.borderBottom = 'none';
3215 menu.style.backgroundColor = 'white';
3216 menu.style.position='absolute';
3217 menu.style.left = (event.clientX - 10) + "px";
3218 menu.style.top = (event.clientY - 10) + "px";
3219 //menu.style.width = '100px';
3220 menu.id = 'mim-menu';
3221 menu.onclick = select_im;
3222 menu.onmouseout = destroy_menu;
3223 menu.target = target;
3225 for (var catname in lang_category)
3227 var cat = lang_category[catname];
3228 var li = document.createElement ('li');
3231 li.style.position = 'relative';
3232 li.style.listStyle= 'none';
3233 li.style.margin = '0';
3234 li.style.padding = '1px';
3235 li.style.borderBottom = '1px solid gray';
3236 li.onmouseover = show_submenu;
3237 //li.onmouseout = hide_submenu;
3238 li.appendChild (document.createTextNode (catname));
3239 var sub = document.createElement ('ul');
3240 sub.style.position = 'absolute';
3241 sub.style.margin = '0px';
3242 sub.style.padding = '0px';
3243 sub.style.border = '1px solid gray';
3244 sub.style.borderBottom = 'none';
3245 sub.style.top = '-1px';
3246 //sub.style.width = '100px';
3247 sub.style.listStyle = 'disc inside';
3248 sub.style.visibility = 'hidden';
3249 sub.style.backgroundColor = 'white';
3250 li.appendChild (sub);
3251 for (var langname in cat)
3253 var lang = cat[langname];
3256 var sub_li = document.createElement ('li');
3257 sub_li.menu_level = 2;
3258 sub_li.parentLi = li;
3259 sub_li.style.position = 'relative';
3260 sub_li.style.padding = '1px';
3261 sub_li.style.borderBottom = '1px solid gray';
3262 sub_li.style.listStyle= 'none';
3263 sub_li.style.backgroundColor = 'white';
3264 //sub_li.onmouseover = show_submenu;
3265 //sub_li.onmouseout = hide_submenu;
3266 sub_li.appendChild (document.createTextNode (lang.name));
3267 sub.appendChild (sub_li);
3268 var subsub = document.createElement ('ul');
3269 subsub.style.position = 'absolute';
3270 subsub.style.margin = '0px';
3271 subsub.style.padding = '0px';
3272 subsub.style.border = '1px solid gray';
3273 subsub.style.borderBottom = 'none';
3274 subsub.style.top = '-1px';
3275 //subsub.style.width = '100px';
3276 //subsub.style.listStyle = 'disc inside';
3277 subsub.style.visibility = 'hidden';
3278 subsub.style.backgroundColor = 'white';
3279 for (var name in lang.list)
3281 var im = lang.list[name];
3282 var subsub_li = document.createElement ('li');
3283 subsub_li.menu_level = 3;
3284 subsub_li.parentLi = sub_li;
3285 subsub_li.style.position = 'relative';
3286 subsub_li.style.padding = '1px';
3287 subsub_li.style.borderBottom = '1px solid gray';
3288 subsub_li.style.listStyle= 'none';
3289 subsub_li.style.backgroundColor = 'white';
3290 //subsub_li.onmouseover = show_submenu;
3291 //subsub_li.onmouseout = hide_submenu;
3292 subsub_li.appendChild (document.createTextNode (im.name));
3294 subsub.appendChild (subsub_li);
3296 sub_li.appendChild (subsub);
3299 menu.appendChild (li);
3301 document.mimmenu = menu;
3303 document.getElementsByTagName ('body')[0].appendChild (menu);
3306 MIM.init = function ()
3308 MIM.add_event_listener (window, 'keydown', MIM.keydown);
3309 MIM.add_event_listener (window, 'keypress', MIM.keypress);
3310 MIM.add_event_listener (window, 'mousedown', create_menu);
3311 if (window.location == 'http://localhost/mim/index.html')
3312 MIM.server = 'http://localhost/mim';
3313 MIM.current = MIM.imlist['vi']['telex'];
3317 MIM.test = function ()
3319 var im = MIM.imlist['t']['latn-post'];
3320 var ic = new MIM.IC (im, null);
3322 ic.Filter (new MIM.Key ('a'));
3323 ic.Filter (new MIM.Key ("'"));
3326 document.getElementById ('text').value = ic.produced + ic.preedit;
3329 document.getElementById ('text').value
3330 = Xex.Term.Parse (domain, body).Eval (domain).toString ();
3332 if (e instanceof Xex.ErrTerm)
3340 MIM.init_debug = function ()
3343 Xex.LogNode = document.getElementById ('log');