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) : null;
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 ? 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 Fnot (domain, vari, args)
876 return (args[0].IsTrue () ? Xex.Zero : Xex.One);
879 function maybe_set_intvar (vari, n)
881 var term = new Xex.IntTerm (n);
883 vari.SetValue (term);
887 function Fadd (domain, vari, args)
889 var n = vari ? vari.val.Intval () : 0;
890 var len = args.length;
892 for (var i = 0; i < len; i++)
893 n += args[i].Intval ();
894 return maybe_set_intvar (vari, n);
897 function Fmul (domain, vari, args)
899 var n = vari ? vari.val.Intval () : 1;
900 for (var i = 0; i < args.length; i++)
902 return maybe_set_intvar (vari, n);
905 function Fsub (domain, vari, args)
911 n = args[0].Intval ();
916 n = vari.val.Intval ();
919 while (i < args.length)
920 n -= args[i++].Intval ();
921 return maybe_set_intvar (vari, n);
924 function Fdiv (domain, vari, args)
930 n = args[0].Intval ();
935 n = vari.val.Intval ();
938 while (i < args.length)
939 n /= args[i++].Intval ();
940 return maybe_set_intvar (vari, n);
943 function Fmod (domain, vari, args)
945 return maybe_set_intvar (vari, args[0].Intval () % args[1].Intval ());
948 function Flogior (domain, vari, args)
950 var n = vari == null ? 0 : vari.val;
951 for (var i = 0; i < args.length; i++)
953 return maybe_set_intvar (vari, n);
956 function Flogand (domain, vari, args)
961 Xex.Log ("logand arg args[0]" + args[0]);
962 n = args[0].Intval ()
967 Xex.Log ("logand arg var " + vari);
968 n = vari.val.Intval ();
971 while (n > 0 && i < args.length)
973 Xex.Log ("logand arg " + args[i]);
976 return maybe_set_intvar (vari, n);
979 function Flsh (domain, vari, args)
981 return maybe_set_intvar (vari, args[0].Intval () << args[1].Intval ());
984 function Frsh (domain, vari, args)
986 return maybe_set_intvar (vari, args[0].Intval () >> args[1].Intval ());
989 function Fand (domain, vari, args)
991 var len = args.length;
992 for (var i = 0; i < len; i++)
994 var result = args[i].Eval (domain);
995 if (domain.Thrown ())
997 if (! result.IsTrue ())
1003 function For (domain, vari, args)
1005 var len = args.length;
1006 for (var i = 0; i < len; i++)
1008 var result = args[i].Eval (domain);
1009 if (domain.Thrown ())
1011 if (result.IsTrue ())
1017 function Feq (domain, vari, args)
1019 for (var i = 1; i < args.length; i++)
1020 if (! args[i - 1].Equals (args[i]))
1025 function Fnoteq (domain, vari, args)
1027 return (Feq (domain, vari, args) == Xex.One ? Xex.Zero : Xex.One);
1030 function Flt (domain, vari, args)
1032 var n = args[0].Intval ();
1034 for (var i = 1; i < args.length; i++)
1036 var n1 = args[i].Intval ();
1044 function Fle (domain, vari, args)
1046 var n = args[0].Intval ();
1047 for (var i = 1; i < args.length; i++)
1049 var n1 = args[i].Intval ();
1057 function Fgt (domain, vari, args)
1059 var n = args[0].Intval ();
1060 for (var i = 1; i < args.length; i++)
1062 var n1 = args[i].Intval ();
1070 function Fge (domain, vari, args)
1072 var n = args[0].Intval ();
1073 for (var i = 1; i < args.Length; i++)
1075 var n1 = args[i].Intval ();
1083 function Fprogn (domain, vari, args)
1085 var result = Xex.One;
1086 var len = args.length;
1088 for (var i = 0; i < len; i++)
1090 result = args[i].Eval (domain);
1091 if (domain.Thrown ())
1097 function Fif (domain, vari, args)
1099 var result = args[0].Eval (domain);
1101 if (domain.Thrown ())
1103 if (result.IsTrue ())
1104 return args[1].Eval (domain);
1105 if (args.length == 2)
1107 return args[2].Eval (domain);
1110 function Fcond (domain, vari, args)
1112 for (var i = 0; i < args.length; i++)
1115 var result = list.val[0].Eval (domain);
1116 if (result.IsTrue ())
1118 for (var j = 1; j < list.val.length; j++)
1121 result = list.val[j].Eval (domain);
1123 if (domain.Thrown ())
1132 function eval_terms (domain, terms, idx)
1134 var result = Xex.Zero;
1135 domain.caught = false;
1136 for (var i = idx; i < terms.length; i++)
1138 result = terms[i].Eval (domain);
1139 if (domain.Thrown ())
1145 function Fcatch (domain, vari, args)
1150 if (args[0].IsError)
1153 result = eval_terms (domain, args, 1);
1155 if (e instanceof Xex.ErrTerm)
1157 if (! args[0].Matches (e))
1165 else if (args[0].IsSymbol)
1168 domain.Catch (args[0].val);
1169 result = eval_terms (domain, args, 1);
1173 vari.SetValue (result);
1181 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1182 "Not a symbol nor an error: " + args[0]);
1185 function Fthrow (domain, vari, args)
1187 if (args[0].IsSymbl)
1189 domain.ThrowSymbol (args[0]);
1190 return (args[args.length - 1]);
1192 if (args[0].IsError)
1196 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1197 "Not a symbol nor an error:" + args[0]);
1200 Xex.BasicDomain = basic;
1202 basic.DefSubr (Fset, "set", true, 1, 1);
1203 basic.DefAlias ("=", "set");
1204 basic.DefSubr (Fnot, "not", false, 1, 1);
1205 basic.DefAlias ("!", "not");
1206 basic.DefSubr (Fadd, "add", true, 1, -1);
1207 basic.DefSubr (Fmul, "mul", true, 1, -1);
1208 basic.DefAlias ("*", "mul");
1209 basic.DefSubr (Fsub, "sub", true, 1, -1);
1210 basic.DefAlias ("-", "sub");
1211 basic.DefSubr (Fdiv, "div", true, 1, -1);
1212 basic.DefAlias ("/", "div");
1213 basic.DefSubr (Fmod, "mod", true, 1, 2);
1214 basic.DefAlias ("%", "mod");
1215 basic.DefSubr (Flogior, "logior", true, 1, -1);
1216 basic.DefAlias ('|', "logior");
1217 basic.DefSubr (Flogand, "logand", true, 1, -1);
1218 basic.DefAlias ("&", "logand");
1219 basic.DefSubr (Flsh, "lsh", true, 1, 2);
1220 basic.DefAlias ("<<", "lsh");
1221 basic.DefSubr (Frsh, "rsh", true, 1, 2);
1222 basic.DefAlias (">>", "rsh");
1223 basic.DefSubr (Feq, "eq", false, 2, -1);
1224 basic.DefAlias ("==", "eq");
1225 basic.DefSubr (Fnoteq, "noteq", false, 2, 2);
1226 basic.DefAlias ("!=", "noteq");
1227 basic.DefSubr (Flt, "lt", false, 2, -1);
1228 basic.DefAlias ("<", "lt");
1229 basic.DefSubr (Fle, "le", false, 2, -1);
1230 basic.DefAlias ("<=", "le");
1231 basic.DefSubr (Fgt, "gt", false, 2, -1);
1232 basic.DefAlias (">", "gt");
1233 basic.DefSubr (Fge, "ge", false, 2, -1);
1234 basic.DefAlias (">=", "ge");
1235 basic.DefSubr (Fthrow, "throw", false, 1, 2);
1237 //basic.DefSubr (Fappend, "append", true, 0, -1);
1238 //basic.DefSubr (Fconcat, "concat", true, 0, -1);
1239 //basic.DefSubr (Fnth, "nth", false, 2, 2);
1240 //basic.DefSubr (Fcopy, "copy", false, 1, 1);
1241 //basic.DefSubr (Fins, "ins", true, 2, 2);
1242 //basic.DefSubr (Fdel, "del", true, 2, 2);
1243 //basic.DefSubr (Feval, "eval", false, 1, 1);
1244 //basic.DefSubr (Fbreak, "break", false, 0, 1);
1245 //basic.DefSubr (Freturn, "return", false, 0, 1);
1246 //basic.DefSubr (Fthrow, "throw", false, 1, 2);
1248 basic.DefSpecial (Fand, "and", false, 1, -1);
1249 basic.DefAlias ("&&", "and");
1250 basic.DefSpecial (For, "or", false, 1, -1);
1251 basic.DefAlias ("||", "or");
1252 basic.DefSpecial (Fprogn, "progn", false, 1, -1);
1253 basic.DefAlias ("expr", "progn");
1254 basic.DefSpecial (Fif, "if", false, 2, 3);
1255 //basic.DefSpecial (Fwhen, "when", false, 1, -1);
1256 //basic.DefSpecial (Floop, "loop", false, 1, -1);
1257 //basic.DefSpecial (Fwhile, "while", false, 1, -1);
1258 basic.DefSpecial (Fcond, "cond", false, 1, -1);
1259 //basic.DefSpecial (Fforeach, "foreach", true, 2, -1);
1260 //basic.DefSpecial (Fquote, "quote", false, 1, 1);
1261 //basic.DefSpecial (Ftype, "type", false, 1, 1);
1262 basic.DefSpecial (Fcatch, "catch", true, 2, -1);
1264 basic.DefType (Xex.Funcall.prototype);
1265 basic.DefType (Xex.Varref.prototype);
1266 basic.DefType (Xex.ErrTerm.prototype);
1267 basic.DefType (Xex.IntTerm.prototype);
1268 basic.DefType (Xex.StrTerm.prototype);
1269 basic.DefType (Xex.SymTerm.prototype);
1270 basic.DefType (Xex.LstTerm.prototype);
1274 Xex.Zero = new Xex.IntTerm (0);
1275 Xex.One = new Xex.IntTerm (1);
1276 Xex.nil = new Xex.SymTerm ('nil');
1278 Xex.Load = function (server, file)
1280 var obj = new XMLHttpRequest ();
1281 var url = server ? server + '/' + file : file;
1282 obj.open ('GET', url, false);
1283 obj.overrideMimeType ('text/xml');
1285 return obj.responseXML.firstChild;
1289 // URL of the input method server.
1290 server: "http://www.m17n.org/common/mim-js",
1291 // Boolean flag to tell if MIM is active or not.
1293 // Boolean flag to tell if MIM is running in debug mode or not.
1295 // List of main input methods.
1297 // List of extra input methods;
1299 // Global input method data
1301 // Currently selected input method.
1305 LoadStatus: { NotLoaded:0, Loading:1, Loaded:2, Error:-1 },
1312 CandidateIndex:0x10,
1314 Preedit: 0x06, // PreeditText | CursorPos
1315 Candidate: 0x38 // CandidateList | CandidateIndex | CandidateShow
1337 ParseError: "parse-error"
1342 var keysyms = new Array ();
1343 keysyms["bs"] = "backspace";
1344 keysyms["lf"] = "linefeed";
1345 keysyms["cr"] = keysyms["enter"] = "return";
1346 keysyms["esc"] = "escape";
1347 keysyms["spc"] = "space";
1348 keysyms["del"] = "delete";
1350 function decode_keysym (str) {
1351 if (str.length == 1)
1353 var parts = str.split ("-");
1354 var len = parts.length, i;
1355 var has_modifier = len > 1;
1357 for (i = 0; i < len - 1; i++)
1358 if (! MIM.KeyModifier.hasOwnProperty (parts[i]))
1360 var key = parts[len - 1];
1363 key = keysyms[key.toLowerCase ()];
1369 for (i = 1; i < len - 1; i++)
1370 str += '-' + parts[i];
1379 parts = new Array ();
1386 MIM.Key = function (val)
1389 this.has_modifier = false;
1390 if (val instanceof Xex.Term)
1392 else if (typeof val == 'string' || val instanceof String)
1394 this.key = decode_keysym (val);
1396 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1397 if (this.key instanceof Array)
1399 this.key = this.key[0];
1400 this.has_modifier = true;
1403 else if (typeof val == 'number' || val instanceof Number)
1404 this.key = String.fromCharCode (val);
1406 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1409 MIM.Key.prototype.toString = function () { return this.key; };
1413 MIM.KeySeq = function (seq)
1415 this.val = new Array ();
1416 this.has_modifier = false;
1422 var len = seq.val.length;
1423 for (var i = 0; i < len; i++)
1425 var v = seq.val[i], key;
1426 if (v.type == 'symbol' || v.type == 'string')
1427 key = new MIM.Key (v);
1428 else if (v.type == 'integer')
1429 key = new MIM.Key (v.val);
1431 throw new Xex.ErrTerm (MIM.Error.ParseError,
1432 "Invalid key: " + v);
1433 this.val.push (key);
1434 if (key.has_modifier)
1435 this.has_modifier = true;
1440 var len = seq.val.length;
1441 for (var i = 0; i < len; i++)
1442 this.val.push (new MIM.Key (seq.val.charCodeAt (i)));
1445 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + seq);
1449 var proto = new Xex.Term ('keyseq');
1450 proto.Clone = function () { return this; }
1451 proto.Parser = function (domain, node)
1453 var seq = new Array ();
1454 for (node = node.firstChild; node; node = node.nextSibling)
1455 if (node.nodeType == 1)
1457 var term = Xex.Term.Parse (domain, node);
1458 return new MIM.KeySeq (term);
1460 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid keyseq");
1462 proto.toString = function ()
1464 var len = this.val.length;
1468 var str = '<keyseq>';
1469 for (var i = 0; i < len; i++)
1473 else if (this.has_modifier)
1475 str += this.val[i].toString ();
1477 return str + '</keyseq>';
1480 MIM.KeySeq.prototype = proto;
1484 MIM.Marker = function () { }
1485 MIM.Marker.prototype = new Xex.Term ('marker');
1486 MIM.Marker.prototype.CharAt = function (ic)
1488 var p = this.Position (ic);
1489 if (p < 0 || p >= ic.preedit.length)
1491 return ic.preedit.charCodeAt (p);
1494 MIM.FloatingMarker = function (name) { this.val = name; };
1495 var proto = new MIM.Marker ();
1496 MIM.FloatingMarker.prototype = proto;
1497 proto.Position = function (ic) { return ic.marker_positions[this.val]; };
1498 proto.Mark = function (ic) { ic.marker_positions[this.val] = ic.cursor_pos; };
1500 MIM.PredefinedMarker = function (name) { this.val = name; }
1501 MIM.PredefinedMarker.prototype = new MIM.Marker ();
1502 MIM.PredefinedMarker.prototype.Position = function (ic)
1504 if (typeof this.pos == 'number')
1506 return this.pos (ic);
1509 var predefined = { }
1511 function def_predefined (name, position)
1513 predefined[name] = new MIM.PredefinedMarker (name);
1514 predefined[name].pos = position;
1517 def_predefined ('@<', 0);
1518 def_predefined ('@>', function (ic) { return ic.preedit.length; });
1519 def_predefined ('@-', function (ic) { return ic.cursor_pos - 1; });
1520 def_predefined ('@+', function (ic) { return ic.cursor_pos + 1; });
1521 def_predefined ('@[', function (ic) {
1522 if (ic.cursor_pos > 0)
1524 var pos = ic.cursor_pos;
1525 return ic.preedit.FindProp ('candidates', pos - 1).from;
1529 def_predefined ('@]', function (ic) {
1530 if (ic.cursor_pos < ic.preedit.length - 1)
1532 var pos = ic.cursor_pos;
1533 return ic.preedit.FindProp ('candidates', pos).to;
1535 return ic.preedit.length;
1537 for (var i = 0; i < 10; i++)
1538 def_predefined ("@" + i, i);
1539 predefined['@first'] = predefined['@<'];
1540 predefined['@last'] = predefined['@>'];
1541 predefined['@previous'] = predefined['@-'];
1542 predefined['@next'] = predefined['@+'];
1543 predefined['@previous-candidate-change'] = predefined['@['];
1544 predefined['@next-candidate-change'] = predefined['@]'];
1546 MIM.SurroundMarker = function (name)
1549 this.distance = parseInt (name.slice (1));
1550 if (isNaN (this.distance))
1551 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid marker: " + name);
1553 MIM.SurroundMarker.prototype = new MIM.Marker ();
1554 MIM.SurroundMarker.prototype.Position = function (ic)
1556 return ic.cursor_pos + this.distance;
1558 MIM.SurroundMarker.prototype.CharAt = function (ic)
1560 if (this.val == '@-0')
1562 var p = this.Position (ic);
1564 return ic.GetSurroundingChar (p);
1565 else if (p >= ic.preedit.length)
1566 return ic.GetSurroundingChar (p - ic.preedit.length);
1567 return ic.preedit.charCodeAt (p);
1570 MIM.Marker.prototype.Parser = function (domain, node)
1572 var name = node.firstChild.nodeValue;
1573 if (name.charAt (0) == '@')
1575 var n = predefined[name];
1578 if (name.charAt (1) == '-' || name.charAt (1) == '+')
1579 return new MIM.SurroundMarker (name);
1580 throw new Xex.ErrTerm (MIM.Error.ParseError,
1581 "Invalid marker: " + name);
1583 return new MIM.FloatingMarker (name);;
1587 MIM.Selector = function (name)
1591 MIM.Selector.prototype = new Xex.Term ('selector');
1595 selectors["@<"] = selectors["@first"] = new MIM.Selector ('@<');
1596 selectors["@="] = selectors["@current"] = new MIM.Selector ('@=');
1597 selectors["@>"] = selectors["@last"] = new MIM.Selector ('@>');
1598 selectors["@-"] = selectors["@previous"] = new MIM.Selector ('@-');
1599 selectors["@+"] = selectors["@next"] = new MIM.Selector ('@+');
1600 selectors["@["] = selectors["@previous-candidate-change"]
1601 = new MIM.Selector ('@[');
1602 selectors["@]"] = selectors["@next-candidate-change"]
1603 = new MIM.Selector ('@]');
1605 MIM.Selector.prototype.Parser = function (domain, node)
1607 var name = node.firstChild.nodeValue;
1608 var s = selectors[name];
1610 throw new Xex.ErrTerm (MIM.Error.ParseError,
1611 "Invalid selector: " + name);
1616 MIM.Rule = function (keyseq, actions)
1618 this.keyseq = keyseq;
1619 this.actions = actions;
1621 MIM.Rule.prototype = new Xex.Term ('rule');
1622 MIM.Rule.prototype.Parser = function (domain, node)
1625 for (n = node.firstChild; n && n.nodeType != 1; n = n.nextSibling);
1627 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1628 var keyseq = Xex.Term.Parse (domain, n);
1629 if (keyseq.type != 'keyseq')
1630 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1631 var actions = Xex.Term.Parse (domain, n.nextElement (), null);
1632 return new MIM.Rule (keyseq, actions);
1634 MIM.Rule.prototype.toString = function ()
1639 MIM.Map = function (name)
1642 this.rules = new Array ();
1646 var proto = new Xex.Term ('map');
1648 proto.Parser = function (domain, node)
1650 var name = node.attributes['mname'].nodeValue;
1652 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1653 var map = new MIM.Map (name);
1654 for (var n = node.firstChild; n; n = n.nextSibling)
1655 if (n.nodeType == 1)
1656 map.rules.push (Xex.Term.Parse (domain, n));
1660 proto.toString = function ()
1662 var str = '<map mname="' + this.name + '">';
1663 var len = this.rules.length;
1664 for (i = 0; i < len; i++)
1665 str += this.rules[i];
1666 return str + '</map>';
1669 MIM.Map.prototype = proto;
1672 Xex.CatchTag._mimtag = new Xex.SymTerm ('@mimtag');
1674 MIM.Action = function (domain, terms)
1676 var args = new Array ();
1677 args.push (Xex.CatchTag_.mimtag);
1678 for (var i = 0; i < terms.length; i++)
1679 args.push (terms[i]);
1680 this.action = Xex.Funcall.prototype.New (domain, 'catch', null, args);
1683 MIM.Action.prototype.Run = function (domain)
1685 var result = this.action.Eval (domain);
1686 if (result.type == 'error')
1688 domain.context.Error = result.toString ();
1691 return (result != Xex.CatchTag._mimtag);
1694 MIM.Keymap = function ()
1697 this.submaps = null;
1703 function add_rule (keymap, rule, branch_actions)
1705 var keyseq = rule.keyseq;
1706 var len = keyseq.val.length;
1709 for (var i = 0; i < len; i++)
1711 var key = keyseq.val[i];
1715 if (! keymap.submaps)
1716 keymap.submaps = {};
1718 sub = keymap.submaps[key.key];
1720 keymap.submaps[key.key] = sub = new MIM.Keymap ();
1724 keymap.map_actions = rule.actions;
1725 keymap.branch_actions = branch_actions;
1728 proto.Add = function (map, branch_actions)
1730 var rules = map.rules;
1731 var len = rules.length;
1733 for (var i = 0; i < len; i++)
1734 add_rule (this, rules[i], branch_actions);
1736 proto.Lookup = function (keys, index)
1740 if (index < keys.val.length && this.submaps
1741 && (sub = this.submaps[keys.val[index].key]))
1744 return sub.Lookup (keys, index);
1746 return { map: this, index: index };
1749 MIM.Keymap.prototype = proto;
1752 MIM.State = function (name)
1755 this.keymap = new MIM.Keymap ();
1759 var proto = new Xex.Term ('state');
1761 proto.Parser = function (domain, node)
1763 var map_list = domain.map_list;
1764 var name = node.attributes['sname'].nodeValue;
1766 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1767 var state = new MIM.State (name);
1768 for (node = node.firstElement (); node; node = node.nextElement ())
1770 if (node.nodeName == 'title')
1771 state.title = node.firstChild.nodeValue;
1774 var n = node.firstElement ();
1775 if (node.nodeName == 'branch')
1776 state.keymap.Add (map_list[node.attributes['mname'].nodeValue],
1777 Xex.Term.Parse (domain, n, null));
1778 else if (node.nodeName == 'state-hook')
1779 state.enter_actions = Xex.Term.Parse (domain, n, null);
1780 else if (node.nodeName == 'catch-all-branch')
1781 state.fallback_actions = Xex.Term.Parse (domain, n, null);
1787 proto.toString = function ()
1789 return '<state sname="' + this.name + '">' + this.keymap + '</state>';
1792 MIM.State.prototype = proto;
1796 function Block (index, term)
1800 this.Data = term.val;
1801 else if (term.IsList)
1803 this.Data = new Array ();
1804 for (var i = 0; i < term.val.length; i++)
1805 this.Data.push (term.val[i].val);
1809 Block.prototype.Count = function () { return this.Data.length; }
1810 Block.prototype.get = function (i)
1812 return (this.Data instanceof Array ? this.Data[i] : this.Data.charAt (i));
1815 MIM.Candidates = function (candidates, column)
1817 this.column = column;
1821 this.blocks = new Array ();
1823 for (var i = 0; i < candidates.length; i++)
1825 var block = new Block (this.total, candidates[i]);
1826 this.blocks.push (block);
1827 this.total += block.Count ();
1833 return (this.column > 0 ? this.index % this.column
1834 : this.index - this.blocks[this.row].Index);
1837 function prev_group ()
1839 var col = get_col.call (this);
1841 if (this.column > 0)
1843 this.index -= this.column;
1844 if (this.index >= 0)
1845 nitems = this.column;
1848 var lastcol = (this.total - 1) % this.column;
1849 this.index = (col < lastcol ? this.total - lastcol + col
1851 this.row = this.blocks.length - 1;
1852 nitems = lastcol + 1;
1854 while (this.blocks[this.row].Index > this.index)
1859 this.row = this.row > 0 ? this.row - 1 : this.blocks.length - 1;
1860 nitems = this.blocks[this.row].Count ();
1861 this.index = (this.blocks[this.row].Index
1862 + (col < nitems ? col : nitems - 1));
1867 function next_group ()
1869 var col = get_col.call (this);
1871 if (this.column > 0)
1873 this.index += this.column - col;
1874 if (this.index < this.total)
1876 if (this.index + col >= this.total)
1878 nitems = this.total - this.index;
1879 this.index = this.total - 1;
1883 nitems = this.column;
1892 while (this.blocks[this.row].Index > this.index)
1897 this.row = this.row < this.blocks.length - 1 ? this.row + 1 : 0;
1898 nitems = this.blocks[this.row].Count ();
1899 this.index = (this.blocks[this.row].Index
1900 + (col < nitems ? col : nitems - 1));
1907 if (this.index == 0)
1909 this.index = this.total - 1;
1910 this.row = this.blocks.length - 1;
1915 if (this.blocks[this.row].Index > this.index)
1923 if (this.index == this.total)
1930 var b = this.blocks[this.row];
1931 if (this.index == b.Index + b.Count ())
1938 this.index -= get_col.call (this);
1939 while (this.blocks[this.row].Index > this.index)
1945 var b = this.blocks[this.row];
1946 if (this.column > 0)
1948 if (this.index + 1 < this.total)
1950 this.index += this.column - get_col.call (this) + 1;
1951 while (b.Index + b.Count () <= this.index)
1952 b = this.blocks[++this.row];
1956 this.index = b.Index + b.Count () - 1;
1959 MIM.Candidates.prototype.Current = function ()
1961 var b = this.blocks[this.row];
1962 return b.get (this.index - b.Index);
1965 MIM.Candidates.prototype.Select = function (selector)
1967 if (selector.type == 'selector')
1969 switch (selector.val)
1971 case '@<': first.call (this); break;
1972 case '@>': last.call (this); break;
1973 case '@-': prev.call (this); break;
1974 case '@+': next.call (this); break;
1975 case '@[': prev_group.call (this); break;
1976 case '@]': next_group.cal (this); break;
1979 return this.Current ();
1982 if (this.column > 0)
1984 col = this.index % this.column;
1985 start = this.index - col;
1986 end = start + this.column;
1990 start = this.blocks[this.row].Index;
1991 col = this.index - start;
1992 end = start + this.blocks[this.row].Count;
1994 if (end > this.total)
1996 this.index += selector.val - col;
1997 if (this.index >= end)
1998 this.index = end - 1;
1999 if (this.column > 0)
2001 if (selector.val > col)
2002 while (this.blocks[this.row].Index + this.blocks[this.row].Count
2006 while (this.blocks[this.row].Index > this.index)
2009 return this.Current ();
2013 MIM.im_domain = new Xex.Domain ('input-method', null, null);
2014 MIM.im_domain.DefType (MIM.KeySeq.prototype);
2015 MIM.im_domain.DefType (MIM.Marker.prototype);
2016 MIM.im_domain.DefType (MIM.Selector.prototype);
2017 MIM.im_domain.DefType (MIM.Rule.prototype);
2018 MIM.im_domain.DefType (MIM.Map.prototype);
2019 MIM.im_domain.DefType (MIM.State.prototype);
2022 var im_domain = MIM.im_domain;
2024 function Finsert (domain, vari, args)
2027 if (args[0].type == 'integer')
2028 text = String.fromCharCode (args[0].val);
2031 domain.context.ins (text, null);
2035 function Finsert_candidates (domain, vari, args)
2037 var ic = domain.context;
2038 var gsize = domain.variables['candidates_group_size'];
2039 var candidates = new MIM.Candidates (args, gsize ? gsize.Intval () : 0);
2040 ic.ins (candidates.Current (), candidates);
2044 function Fdelete (domain, vari, args)
2046 var ic = domain.context;
2047 var pos = args[0].IsInt ? args[0].Intval () : args[0].Position (ic);
2048 return new Xex.IntTerm (ic.del (pos));
2051 function Fselect (domain, vari, args)
2053 var ic = domain.context;
2054 var can = ic.candidates;
2058 var old_text = can.Current ();
2059 var new_text = can.Select (args[0]);
2060 ic.rep (old_text, new_text, can);
2063 Xex.Log ('no candidates at ' + ic.cursor_pos + ' of ' + ic.candidate_table.table.length);
2067 function Fshow (domain, vari, args)
2069 domain.context.candidate_show = true;
2070 domain.context.changed |= MIM.ChangedStatus.CandidateShow;
2074 function Fhide (domain, vari, args)
2076 domain.context.candidate_show = false;
2077 domain.context.changed |= MIM.ChangedStatus.CandidateShow;
2081 function Fchar_at (domain, vari, args)
2083 return new Xex.IntTerm (args[0].CharAt (domain.context));
2086 function Fmove (domain, vari, args)
2088 var ic = domain.context;
2089 var pos = args[0].IsInt ? args[0].val : args[0].Position (ic);
2091 return new Xex.IntTerm (pos);
2094 function Fmark (domain, vari, args)
2096 args[0].Mark (domain.context);
2100 function Fpushback (domain, vari, args)
2102 var a = (args[0].IsInt ? args[0].Intval ()
2103 : args[0].IsStr ? new KeySeq (args[0])
2105 domain.context.pushback (a);
2109 function Fpop (domain, vari, args)
2111 var ic = domain.context;
2112 if (ic.key_head < ic.keys.val.length)
2113 ic.keys.val.splice (ic.keys_head, 1);
2117 function Fundo (domain, vari, args)
2119 var ic = domain.context;
2120 var n = args.length == 0 ? -2 : args[0].val;
2122 ic.keys.val.splice (ic.keys.length + n, -n);
2124 ic.keys.val.splice (n, ic.keys.length);
2129 function Fcommit (domain, vari, args)
2131 domain.context.commit ();
2135 function Funhandle (domain, vari, args)
2137 domain.context.commit ();
2138 return Xex.Fthrow (domain, vari, Xex.CatchTag._mimtag);
2141 function Fshift (domain, vari, args)
2143 var ic = domain.context;
2144 var state_name = args[0].val;
2145 var state = ic.im.state_list[state_name];
2147 throw ("Unknown state: " + state_name);
2152 function Fshiftback (domain, vari, args)
2154 domain.context.shift (null);
2158 function Fkey_count (domain, vari, args)
2160 return new Xex.IntTerm (domain.context.key_head);
2163 function Fsurrounding_flag (domain, vari, args)
2165 return new Xex.IntTerm (-1);
2168 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
2169 im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, 1);
2170 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
2171 im_domain.DefSubr (Fselect, "select", false, 1, 1);
2172 im_domain.DefSubr (Fshow, "show-candidates", false, 0, 0);
2173 im_domain.DefSubr (Fhide, "hide-candidates", false, 0, 0);
2174 im_domain.DefSubr (Fmove, "move", false, 1, 1);
2175 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
2176 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
2177 im_domain.DefSubr (Fpop, "pop", false, 0, 0);
2178 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
2179 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
2180 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
2181 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
2182 im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
2183 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
2184 im_domain.DefSubr (Fkey_count, "key-count", false, 0, 0);
2185 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag", false, 0, 0);
2190 function get_global_var (vname)
2192 if (MIM.im_global.load_status == MIM.LoadStatus.NotLoaded)
2193 MIM.im_global.Load ()
2194 return MIM.im_global.domain.variables[vname];
2197 function include (node)
2199 node = node.firstElement ();
2200 if (node.nodeName != 'tags')
2203 var lang = null, name = null, extra = null;
2204 for (node = node.firstElement (); node; node = node.nextElement ())
2206 if (node.nodeName == 'language')
2207 lang = node.firstChild.nodeValue;
2208 else if (node.nodeName == 'name')
2209 name = node.firstChild.nodeValue;
2210 else if (node.nodeName == 'extra-id')
2211 extra = node.firstChild.nodeValue;
2213 if (! lang || ! MIM.imlist[lang])
2217 if (! name || ! (im = MIM.imlist[lang][name]))
2222 if (! (im = MIM.imextra[lang][extra]))
2225 if (im.load_status != MIM.LoadStatus.Loaded
2226 && (im.load_status != MIM.LoadStatus.NotLoaded || ! im.Load ()))
2233 parsers['description'] = function (node)
2235 this.description = node.firstChild.nodeValue;
2237 parsers['variable-list'] = function (node)
2239 for (node = node.firstElement (); node; node = node.nextElement ())
2241 var vname = node.attributes['vname'].nodeValue;
2242 if (this != MIM.im_global)
2244 var vari = get_global_var (vname);
2246 this.domain.Defvar (vname);
2248 vname = Xex.Term.Parse (this.domain, node)
2251 parsers['command-list'] = function (node)
2254 parsers['macro-list'] = function (node)
2256 for (var n = node.firstElement (); n; n = n.nextElement ())
2257 if (n.nodeName == 'xi:include')
2259 var im = include (n);
2261 alert ('inclusion fail');
2263 for (var macro in im.domain.functions)
2265 var func = im.domain.functions[macro];
2266 if (func instanceof Xex.Macro)
2267 im.domain.CopyFunc (this.domain, macro);
2269 n = n.previousSibling;
2270 node.removeChild (n.nextSibling);
2272 Xex.Term.Parse (this.domain, node.firstElement (), null);
2274 parsers['title'] = function (node)
2276 this.title = node.firstChild.nodeValue;
2278 parsers['map-list'] = function (node)
2280 for (node = node.firstElement (); node; node = node.nextElement ())
2282 if (node.nodeName == 'xi:include')
2284 var im = include (node);
2287 alert ('inclusion fail');
2290 for (var mapname in im.map_list)
2291 this.map_list[mapname] = im.map_list[mapname];
2295 var map = Xex.Term.Parse (this.domain, node);
2296 this.map_list[map.name] = map;
2300 parsers['state-list'] = function (node)
2302 this.domain.map_list = this.map_list;
2303 for (node = node.firstElement (); node; node = node.nextElement ())
2305 if (node.nodeName == 'state')
2307 var state = Xex.Term.Parse (this.domain, node);
2309 state.title = this.title;
2310 if (! this.initial_state)
2311 this.initial_state = state;
2312 this.state_list[state.name] = state;
2315 delete this.domain.map_list;
2318 MIM.IM = function (lang, name, extra_id, file)
2322 this.extra_id = extra_id;
2324 this.load_status = MIM.LoadStatus.NotLoaded;
2325 this.domain = new Xex.Domain (this.lang + '-'
2326 + (this.name != 'nil'
2327 ? this.name : this.extra_id),
2328 MIM.im_domain, null);
2334 var node = Xex.Load (null, this.file);
2337 this.load_status = MIM.LoadStatus.Error;
2341 this.initial_state = null;
2342 this.state_list = {};
2343 for (node = node.firstElement (); node; node = node.nextElement ())
2345 var name = node.nodeName;
2346 var parser = parsers[name];
2348 parser.call (this, node);
2350 this.load_status = MIM.LoadStatus.Loaded;
2355 MIM.IM.prototype = proto;
2357 MIM.IC = function (im, target)
2359 if (im.load_status == MIM.LoadStatus.NotLoaded)
2361 if (im.load_status != MIM.LoadStatus.Loaded)
2362 alert ('im:' + im.name + ' error:' + im.load_status);
2364 this.target = target;
2365 this.domain = new Xex.Domain ('context', im.domain, this);
2367 this.range = new Array ();
2368 this.range[0] = this.range[1] = 0;
2370 this.initial_state = this.im.initial_state;
2371 this.keys = new MIM.KeySeq ();
2372 this.marker_positions = new Array ();
2373 this.candidate_table = new MIM.CandidateTable ();
2377 MIM.CandidateTable = function ()
2379 this.table = new Array ();
2382 MIM.CandidateTable.prototype.get = function (pos)
2384 for (var i = 0; i < this.table.length; i++)
2386 var elt = this.table[i];
2387 if (elt.from < pos && pos <= elt.to)
2392 MIM.CandidateTable.prototype.put = function (from, to, candidates)
2394 for (var i = 0; i < this.table.length; i++)
2396 var elt = this.table[i];
2397 if (elt.from < to && elt.to > from)
2401 elt.val = candidates;
2405 this.table.push ({ from: from, to: to, val: candidates });
2408 MIM.CandidateTable.prototype.adjust = function (from, to, inserted)
2410 var diff = inserted - (to - from);
2413 for (var i = 0; i < this.table.length; i++)
2415 var elt = this.table[i];
2424 MIM.CandidateTable.prototype.clear = function ()
2426 this.table.length = 0;
2429 function detach_candidates (ic)
2431 ic.candidate_table.clear ();
2432 ic.candidates = null;
2433 ic.changed |= (MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos
2434 | MIM.ChangedStatus.CandidateList
2435 | MIM.ChangedStatus.CandidateIndex
2436 | MIM.ChangedStatus.CandidateShow);
2439 function set_cursor (prefix, pos)
2441 this.cursor_pos = pos;
2442 this.candidates = this.candidate_table.get (pos);
2445 function save_state ()
2447 this.state_var_values = this.domain.SaveValues ();
2448 this.state_preedit = this.preedit;
2449 this.state_key_head = this.key_head;
2450 this.state_pos = this.cursor_pos;
2453 function restore_state ()
2455 this.domain.RestoreValues (this.state_var_values);
2456 this.preedit = this.state_preedit;
2457 set_cursor.call (this, "restore", this.state_pos);
2460 function handle_key ()
2462 var out = this.keymap.Lookup (this.keys, this.key_head);
2465 Xex.Log ('handling ' + this.keys.val[this.key_head]
2466 + ' in ' + this.state.name + ':' + this.keymap.name);
2467 this.key_head = out.index;
2468 if (sub != this.keymap)
2471 restore_state.call (this);
2473 Xex.Log ('submap found');
2474 if (this.keymap.map_actions)
2476 Xex.Log ('taking map actions:');
2477 if (! this.take_actions (this.keymap.map_actions))
2480 else if (this.keymap.submaps)
2482 Xex.Log ('no map actions');
2483 for (var i = this.state_key_head; i < this.key_head; i++)
2485 Xex.Log ('inserting key:' + this.keys.val[i].key);
2486 this.ins (this.keys.val[i].key, null);
2489 if (! this.keymap.submaps)
2491 Xex.Log ('terminal:');
2492 if (this.keymap.branch_actions != null)
2494 Xex.Log ('branch actions:');
2495 if (! this.take_actions (this.keymap.branch_actions))
2498 if (this.keymap != this.state.keymap)
2499 this.shift (this.state);
2504 Xex.Log ('no submap');
2505 var current_state = this.state;
2506 var map = this.keymap;
2508 if (map.branch_actions)
2510 Xex.Log ('branch actions');
2511 if (! this.take_actions (map.branch_actions))
2515 if (map == this.keymap)
2517 Xex.Log ('no state change');
2518 if (map == this.initial_state.keymap
2519 && this.key_head < this.keys.val.length)
2521 Xex.Log ('unhandled');
2524 if (this.keymap != current_state.keymap)
2525 this.shift (current_state);
2526 else if (this.keymap.actions == null)
2527 this.shift (this.initial_state);
2536 Xex.Log ('reseting ' + this.im.lang);
2537 this.cursor_pos = 0;
2538 this.candidate_show = false;
2539 this.prev_state = null;
2540 this.title = this.initial_state.title;
2541 this.state_preedit = '';
2542 this.state_key_head = 0;
2543 this.state_var_values = {};
2546 this.keys.val.length = 0;
2547 this.key_unhandled = false;
2548 this.unhandled_key = null;
2549 this.changed = MIM.ChangedStatus.None;
2550 this.error_message = '';
2551 this.title = this.initial_state.title;
2554 this.preedit_saved = '';
2555 this.candidate_table.clear ();
2556 this.candidates = null;
2557 this.candidate_show = false;
2558 for (var elt in this.marker_positions)
2559 this.marker_positions[elt] = 0;
2560 this.shift (this.initial_state);
2563 catch_args: new Array (Xex.CatchTag._mimtag, null),
2565 take_actions: function (actions)
2567 var func_progn = this.domain.GetFunc ('progn');
2568 var func_catch = this.domain.GetFunc ('catch');
2569 this.catch_args[1] = new Xex.Funcall (func_progn, null, actions);
2570 var term = new Xex.Funcall (func_catch, null, this.catch_args);
2571 term = term.Eval (this.domain);
2572 return (! term.IsSymbol || term.val != '@mimtag');
2575 GetSurroundingChar: function (pos)
2579 pos += this.range[0];
2585 pos += this.range[1];
2586 if (pos >= this.target.value.length)
2589 return this.target.value.charCodeAt (pos);
2592 DelSurroundText: function (pos)
2597 pos += this.range[0];
2603 text = this.target.value.substring (0, pos);
2604 if (this.range[0] < this.target.value.length)
2605 text += this.target.value.substring (this.range[0]);
2606 this.target.value = text;
2607 this.range[1] -= this.range[0] - pos;
2608 this.range[0] = pos;
2612 pos += this.range[1];
2613 text = this.target.value.substring (0, this.range[1]);
2614 if (pos >= this.target.value.length)
2615 pos = this.target.value.length;
2617 text += this.target.value.substring (pos);
2618 this.target.value = text;
2622 adjust_markers: function (from, to, inserted)
2624 var diff = inserted - (to - from);
2626 for (var name in this.marker_positions)
2628 var pos = this.marker_positions[name];
2632 this.marker_positions[name] += diff;
2633 else if (pos > from)
2634 this.marker_positions[name] = from;
2637 if (this.cursor_pos >= to)
2638 set_cursor.call (this, 'adjust', this.cursor_pos + diff);
2639 else if (this.cursor_pos > from)
2640 set_cursor.call (this, 'adjust', from)
2643 preedit_replace: function (from, to, text, candidates)
2645 this.preedit = (this.preedit.substring (0, from)
2646 + text + this.preedit.substring (to));
2647 this.adjust_markers (from, to, text.length);
2648 this.candidate_table.adjust (from, to, text.length);
2650 this.candidate_table.put (from, from + text.length, candidates)
2653 ins: function (text, candidates)
2655 this.preedit_replace (this.cursor_pos, this.cursor_pos, text, candidates);
2656 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2659 rep: function (old_text, new_text, candidates)
2661 this.preedit_replace (this.cursor_pos - old_text.length,
2662 this.cursor_pos, new_text, candidates);
2663 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2668 var deleted = pos - this.cursor_pos;
2669 if (pos < this.cursor_pos)
2673 this.DelSurroundText (pos);
2674 deleted = - this.cursor_pos;
2677 if (pos < this.cursor_pos)
2678 this.preedit_replace (pos, this.cursor_pos, '', null);
2682 if (pos > this.preedit.length)
2684 this.DelSurroundText (pos - this.preedit.length);
2685 deleted = this.preedit.length - this.cursor_pos;
2686 pos = this.preedit.length;
2688 if (pos > this.cursor_pos)
2689 this.preedit_replace (this.cursor_pos, pos, '', null);
2692 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2698 this.candidate_show = true;
2699 this.changed |= MIM.ChangedStatus.CandidateShow;
2704 this.candidate_show = false;
2705 this.changed |= MIM.ChangedStatus.CandidateShow;
2708 move: function (pos)
2712 else if (pos > this.preedit.length)
2713 pos = this.preedit.length;
2714 if (pos != this.cursor_pos)
2716 set_cursor.call (this, 'move', pos);
2717 this.changed |= MIM.ChangedStatus.Preedit;
2721 pushback: function (n)
2723 if (n instanceof MIM.KeySeq)
2725 if (this.key_head > 0)
2727 if (this.key_head < this.keys.val.length)
2728 this.keys.val.splice (this.key_head,
2729 this.keys.val.length - this.key_head);
2730 for (var i = 0; i < n.val.length; i++)
2731 this.keys.val.push (n.val[i]);
2737 if (this.key_head < 0)
2744 this.key_head = - n;
2745 if (this.key_head > this.keys.val.length)
2746 this.key_head = this.keys.val.length;
2752 if (this.key_head < this.keys.val.length)
2753 this.keys.val.splice (this.key_head, 1);
2758 if (this.preedit.length > 0)
2760 this.candidate_table.clear ();
2761 this.produced += this.preedit;
2762 this.preedit_replace.call (this, 0, this.preedit.length, '', null);
2766 shift: function (state)
2770 if (this.prev_state == null)
2772 state = this.prev_state;
2775 if (state == this.initial_state)
2780 this.keys.val.splice (0, this.key_head);
2782 this.prev_state = null;
2787 if (state != this.state)
2788 this.prev_state = this.state;
2790 if (state != this.state && state.enter_actions)
2791 this.take_actions (state.enter_actions);
2792 if (! this.state || this.state.title != state.title)
2793 this.changed |= MIM.ChangedStatus.StateTitle;
2795 this.keymap = state.keymap;
2796 this.state_key_head = this.key_head;
2797 save_state.call (this);
2800 Filter: function (key)
2804 this.key_unhandled = true;
2805 this.unhandled_key = key;
2808 if (key.key == '_reload')
2810 this.changed = MIM.ChangedStatus.None;
2812 this.key_unhandled = false;
2813 this.keys.val.push (key);
2815 while (this.key_head < this.keys.val.length)
2817 if (! handle_key.call (this))
2819 if (this.key_head < this.keys.val.length)
2821 this.unhandled_key = this.keys.val[this.key_head];
2822 this.keys.val.splice (this.key_head, this.key_head + 1);
2824 this.key_unhandled = true;
2830 this.key_unhandled = true;
2834 if (this.key_unhandled)
2836 this.keys.val.length = 0;
2837 this.key_head = this.state_key_head = this.commit_key_head = 0;
2839 return (! this.key_unhandled
2840 && this.produced.length == 0
2841 && this.preedit.length == 0);
2845 MIM.IC.prototype = proto;
2847 var node = Xex.Load (null, "imlist.xml");
2848 for (node = node.firstChild; node; node = node.nextSibling)
2849 if (node.nodeName == 'input-method')
2851 var lang = null, name = null, extra_id = null, file = null;
2853 for (var n = node.firstChild; n; n = n.nextSibling)
2855 if (n.nodeName == 'language')
2856 lang = n.firstChild.nodeValue;
2857 else if (n.nodeName == 'name')
2858 name = n.firstChild.nodeValue;
2859 else if (n.nodeName == 'extra-id')
2860 extra_id = n.firstChild.nodeValue;
2861 else if (n.nodeName == 'filename')
2862 file = n.firstChild.nodeValue;
2864 if (name && name != 'nil')
2866 if (! MIM.imlist[lang])
2867 MIM.imlist[lang] = {};
2868 MIM.imlist[lang][name] = new MIM.IM (lang, name, extra_id, file);
2870 else if (extra_id && extra_id != 'nil')
2872 if (! MIM.imextra[lang])
2873 MIM.imextra[lang] = {};
2874 MIM.imextra[lang][extra_id] = new MIM.IM (lang, name, extra_id, file);
2877 if (MIM.imextra.t && MIM.imextra.t.global)
2878 MIM.im_global = MIM.imextra.t.global;
2881 MIM.im_global = new MIM.IM ('t', 'nil', 'global', null);
2882 MIM.im_global.load_status = MIM.LoadStatus.Error;
2888 var keys = new Array ();
2890 keys[0x08] = 'backspace';
2891 keys[0x0D] = 'return';
2892 keys[0x1B] = 'escape';
2893 keys[0x20] = 'space';
2894 keys[0x21] = 'pageup';
2895 keys[0x22] = 'pagedown';
2897 keys[0x24] = 'home';
2898 keys[0x25] = 'left';
2900 keys[0x27] = 'right';
2901 keys[0x28] = 'down';
2902 keys[0x2D] = 'insert';
2903 keys[0x2E] = 'delete';
2904 for (var i = 1; i <= 12; i++)
2905 keys[111 + i] = "f" + i;
2906 keys[0x90] = "numlock";
2907 keys[0xF0] = "capslock";
2910 keyids['U+0008'] = 'backspace';
2911 keyids['U+0009'] = 'tab';
2912 keyids['U+0018'] = 'cancel';
2913 keyids['U+001B'] = 'escape';
2914 keyids['U+0020'] = 'space';
2915 keyids['U+007F'] = 'delete';
2918 modifiers.Shift = 1;
2919 modifiers.Control = 1;
2921 modifiers.AltGraph = 1;
2924 MIM.decode_key_event = function (event)
2926 var key = event.keyIdentifier;
2928 if (key) // keydown event of Chrome
2933 if (event.ctrlKey) mod += 'C-';
2934 if (event.metaKey) mod += 'M-';
2935 if (event.altKey) mod += 'A-';
2936 var keysym = keyids[key];
2939 else if (key.match(/^U\+([0-9A-Z]+)$/))
2941 if (mod.length == 0)
2943 key = String.fromCharCode (parseInt (RegExp.$1, 16));
2946 key = key.toLowerCase ();
2947 if (event.shiftKey) mod += 'S-';
2948 return new MIM.Key (mod + key);
2952 key = ((event.type == 'keydown' || event.keyCode) ? event.keyCode
2953 : event.charCode ? event.charCode
2957 if (event.type == 'keydown')
2962 if (event.shiftKey) key = "S-" + key ;
2965 key = String.fromCharCode (key);
2967 if (event.altKey) key = "A-" + key ;
2968 if (event.ctrlKey) key = "C-" + key ;
2969 return new MIM.Key (key);
2973 MIM.add_event_listener
2974 = (window.addEventListener
2975 ? function (target, type, listener) {
2976 target.addEventListener (type, listener, false);
2978 : window.attachEvent
2979 ? function (target, type, listener) {
2980 target.attachEvent ('on' + type,
2982 listener.call (target, window.event);
2985 : function (target, type, listener) {
2987 = function (e) { listener.call (target, e || window.event); };
2990 MIM.debug_print = function (event, ic)
2994 if (! MIM.debug_nodes)
2996 MIM.debug_nodes = new Array ();
2997 MIM.debug_nodes['status0'] = document.getElementById ('status0');
2998 MIM.debug_nodes['status1'] = document.getElementById ('status1');
2999 MIM.debug_nodes['keydown'] = document.getElementById ('keydown');
3000 MIM.debug_nodes['keypress'] = document.getElementById ('keypress');
3001 MIM.debug_nodes['keymap0'] = document.getElementById ('keymap0');
3002 MIM.debug_nodes['keymap1'] = document.getElementById ('keymap1');
3003 MIM.debug_nodes['preedit0'] = document.getElementById ('preedit0');
3004 MIM.debug_nodes['preedit1'] = document.getElementById ('preedit1');
3006 var target = event.target;
3007 var code = event.keyCode;
3008 var ch = event.type == 'keypress' ? event.charCode : 0;
3009 var key = MIM.decode_key_event (event);
3012 MIM.debug_nodes[event.type].innerHTML = "" + code + "/" + ch + ":" + key + '/' + event.keyIdentifier;
3013 index = (event.type == 'keydown' ? '0' : '1');
3015 MIM.debug_nodes['status' + index].innerHTML = ic.im.load_status;
3017 MIM.debug_nodes['status' + index].innerHTML = 'no IM';
3018 MIM.debug_nodes['keymap' + index].innerHTML = ic.state.name;
3019 MIM.debug_nodes['preedit' + index].innerHTML = ic.preedit;
3022 MIM.debug_nodes.keypress.innerHTML = '';
3023 MIM.debug_nodes.status1.innerHTML = '';
3024 MIM.debug_nodes.keymap1.innerHTML = '';
3025 MIM.debug_nodes.preedit1.innerHTML = ''
3029 MIM.get_range = function (target, ic)
3032 if (target.selectionStart != null) // for Mozilla
3034 from = target.selectionStart;
3035 to = target.selectionEnd;
3039 var r = document.selection.createRange ();
3040 var rr = r.duplicate ();
3042 rr.moveToElementText (target);
3043 rr.setEndPoint ('EndToEnd', range);
3044 from = rr.text.length - r.text.length;
3045 to = rr.text.length;
3047 if (ic.range[0] == from && ic.range[1] == to
3048 && (to == from || target.value.substring (from, to) == ic.preedit))
3055 MIM.set_caret = function (target, ic)
3057 if (target.setSelectionRange) // Mozilla
3059 var scrollTop = target.scrollTop;
3060 target.setSelectionRange (ic.range[0], ic.range[1]);
3061 target.scrollTop = scrollTop;
3065 var range = target.createTextRange ();
3066 range.moveStart ('character', ic.range[0]);
3067 range.moveEnd ('character', ic.range[1]);
3072 MIM.update = function (target, ic)
3074 var text = target.value;
3075 target.value = (text.substring (0, ic.range[0])
3078 + text.substring (ic.range[1]));
3079 ic.range[0] += ic.produced.length;
3080 ic.range[1] = ic.range[0] + ic.preedit.length;
3081 MIM.set_caret (target, ic);
3084 MIM.reset_ic = function (event)
3086 if (event.target.mim_ic)
3088 var target = event.target;
3089 var ic = target.mim_ic;
3090 if (ic.preedit.length > 0)
3091 event.target.setSelectionRange (ic.range[1], ic.range[1]);
3096 MIM.keydown = function (event)
3098 var target = event.target;
3099 if (target.id == 'log')
3101 if (! (target.type == "text" || target.type == "textarea"))
3104 var ic = target.mim_ic;
3105 if (! ic || ic.im != MIM.current)
3107 target.mim_ic = null;
3108 Xex.Log ('creating IC');
3109 ic = new MIM.IC (MIM.current, target);
3110 if (ic.im.load_status != MIM.LoadStatus.Loaded)
3113 MIM.add_event_listener (target, 'blur', MIM.reset_ic);
3114 MIM.get_range (target, ic)
3118 if (! MIM.get_range (target, ic))
3121 MIM.debug_print (event, ic);
3122 ic.key = MIM.decode_key_event (event);
3125 Xex.Log ("filtering " + ic.key);
3127 var result = ic.Filter (ic.key);
3129 Xex.Log ('Error;' + e);
3132 MIM.update (target, ic);
3133 if (! ic.key_unhandled)
3134 event.preventDefault ();
3138 MIM.keypress = function (event)
3140 var target = event.target;
3141 if (target.id == 'log')
3143 if (! (target.type == "text" || target.type == "textarea"))
3146 var ic = target.mim_ic;
3150 if (ic.im.load_status != MIM.LoadStatus.Loaded)
3153 ic.key = MIM.decode_key_event (event);
3160 Xex.Log ("filtering " + ic.key);
3162 var result = ic.Filter (ic.key);
3164 Xex.Log ('Error;' + e);
3167 MIM.update (target, ic);
3168 if (! ic.key_unhandled)
3169 event.preventDefault ();
3171 Xex.Log ("error:" + e);
3172 event.preventDefault ();
3174 MIM.debug_print (event, ic);
3180 var lang_category = {
3182 cs: { name: 'Czech' },
3183 da: { name: 'Danish' },
3184 el: { name: 'Greek' },
3185 en: { name: 'English' },
3186 eo: { name: 'Esperanto' },
3187 fr: { name: 'French' },
3188 grc: { name: 'ClassicGreek' },
3189 hr: { name: 'Croatian' },
3190 hy: { name: 'Armenian' },
3191 ka: { name: 'Georgian' },
3192 kk: { name: 'Kazakh' },
3193 ru: { name: 'Russian' },
3194 sk: { name: 'Slovak' },
3195 sr: { name: 'Serbian' },
3196 sv: { name: 'Swedish' },
3197 vi: { name: 'Vietnamese' },
3198 yi: { name: 'Yiddish' } },
3200 ar: { name: 'Arabic' },
3201 dv: { name: 'Divehi' },
3202 fa: { name: 'Persian' },
3203 he: { name: 'Hebrew' },
3204 kk: { name: 'Kazakh' },
3205 ps: { name: 'Pushto' },
3206 ug: { name: 'Uighur' },
3207 yi: { name: 'Yiddish' } },
3209 as: { name: 'Assamese' },
3210 bn: { name: 'Bengali' },
3211 bo: { name: 'Tibetan' },
3212 gu: { name: 'Gujarati' },
3213 hi: { name: 'Hindi' },
3214 kn: { name: 'Kannada' },
3215 ks: { name: 'Kashmiri' },
3216 ml: { name: 'Malayalam' },
3217 mr: { name: 'Marathi' },
3218 ne: { name: 'Nepali' },
3219 or: { name: 'Oriya' },
3220 pa: { name: 'Panjabi' },
3221 sa: { name: 'Sanskirit' },
3222 sd: { name: 'Sindhi' },
3223 si: { name: 'Sinhalese' },
3224 ta: { name: 'Tamil' },
3225 te: { name: 'Telugu' },
3226 ur: { name: 'Urdu' } },
3228 cmc: { name: 'Cham' },
3229 km: { name: 'Khmer'},
3230 lo: { name: 'Lao' },
3231 my: { name: 'Burmese' },
3232 tai: { name: 'Tai Viet' },
3233 th: { name: 'Thai' },
3234 vi: { name: 'Vietanamese' } },
3236 ii: { name: 'Yii' },
3237 ja: { name: 'Japanese' },
3238 ko: { name: 'Korean' },
3239 zh: { name: 'Chinese' } },
3241 am: { name: 'Amharic' },
3242 ath: { name: 'Carrier' },
3243 bla: { name: 'Blackfoot' },
3244 cr: { name: 'Cree' },
3245 eo: { name: 'Esperanto' },
3246 iu: { name: 'Inuktitut' },
3247 nsk: { name: 'Naskapi' },
3248 oj: { name: 'Ojibwe' },
3249 t: { name: 'Generic' } }
3252 function categorize_im ()
3254 var cat, lang, list, name;
3255 for (lang in MIM.imlist)
3258 for (cat in lang_category)
3259 if (lang_category[cat][lang])
3261 list = lang_category[cat][lang].list;
3263 list = lang_category[cat][lang].list = {};
3267 for (name in MIM.imlist[lang])
3268 list[name] = MIM.imlist[lang][name];
3270 for (name in MIM.imlist[lang])
3271 Xex.Log ('no category ' + lang + '-' + name);
3280 clearTimeout (destroy_timer);
3281 destroy_timer = null;
3282 var target = document.getElementById ('mim-menu');
3285 for (; last_target && last_target.menu_level;
3286 last_target = last_target.parentLi)
3287 last_target.style.backgroundColor = 'white';
3288 var nodes = target.getElementsByTagName ('ul');
3289 for (var i = 0; i < nodes.length; i++)
3290 nodes[i].style.visibility = 'hidden';
3291 document.getElementsByTagName ('body')[0].removeChild (target);
3295 function destroy_menu () {
3296 if (! destroy_timer)
3297 destroy_timer = setTimeout (destroy, 1000);
3300 function show_submenu (event)
3304 clearTimeout (destroy_timer);
3305 destroy_timer = null;
3307 var target = event.target;
3308 if (! target.menu_level)
3310 if (last_target && target.parentLi != last_target)
3312 last_target.style.backgroundColor = 'white';
3313 if (target.menu_level < last_target.menu_level)
3315 last_target = last_target.parentLi;
3316 last_target.style.backgroundColor = 'white';
3318 var uls = last_target.getElementsByTagName ('ul');
3319 for (var i = 0; i < uls.length; i++)
3320 uls[i].style.visibility = 'hidden';
3322 last_target = target;
3323 target.style.backgroundColor = 'yellow';
3324 if (target.menu_level < 3)
3326 target.lastChild.style.visibility = 'visible';
3327 target.lastChild.style.left = target.clientWidth + 'px';
3329 event.preventDefault ();
3332 function select_im (event)
3334 var target = event.target;
3337 MIM.current = target.im;
3340 event.preventDefault ();
3343 function create_ul (visibility)
3345 var ul = document.createElement ('ul');
3346 ul.style.position = 'absolute';
3347 ul.style.margin = '0px';
3348 ul.style.padding = '0px';
3349 ul.style.border = '1px solid gray';
3350 ul.style.borderBottom = 'none';
3351 ul.style.top = '-1px';
3352 ul.style.backgroundColor = 'white';
3353 ul.style.visibility = visibility;
3357 function create_li (level, text)
3359 var li = document.createElement ('li');
3360 li.style.position = 'relative';
3361 li.style.margin = '0px';
3362 li.style.padding = '1px';
3363 li.style.borderBottom = '1px solid gray';
3364 li.style.top = '0px';
3365 li.style.listStyle = 'none';
3366 li.menu_level = level;
3367 li.appendChild (document.createTextNode (text));
3373 function create_menu (event)
3375 var target = event.target;
3377 if (! ((target.type == "text" || target.type == "textarea")
3378 && event.which == 1 && event.ctrlKey))
3383 menu = create_ul ('visible');
3384 menu.style.fontFamily = 'sans-serif';
3385 menu.style.fontWeight = 'bold';
3386 menu.id = 'mim-menu';
3387 menu.onclick = select_im;
3388 menu.onmouseover = show_submenu;
3389 menu.onmouseout = destroy_menu;
3390 for (var catname in lang_category)
3392 var cat = lang_category[catname];
3393 var li = create_li (1, catname);
3394 var sub = create_ul ('hidden');
3395 for (var langname in cat)
3397 var lang = cat[langname];
3400 var sub_li = create_li (2, lang.name);
3401 sub_li.parentLi = li;
3402 var subsub = create_ul ('hidden');
3403 for (var name in lang.list)
3405 var im = lang.list[name];
3406 var subsub_li = create_li (3, im.name);
3407 subsub_li.parentLi = sub_li;
3409 subsub.appendChild (subsub_li);
3411 sub_li.appendChild (subsub);
3412 sub.appendChild (sub_li);
3414 li.appendChild (sub);
3415 menu.appendChild (li);
3417 document.mimmenu = menu;
3418 lang_category = null;
3420 menu.style.left = (event.clientX - 10) + "px";
3421 menu.style.top = (event.clientY - 10) + "px";
3422 document.getElementsByTagName ('body')[0].appendChild (menu);
3425 MIM.init = function ()
3427 MIM.add_event_listener (window, 'keydown', MIM.keydown);
3428 MIM.add_event_listener (window, 'keypress', MIM.keypress);
3429 MIM.add_event_listener (window, 'mousedown', create_menu);
3430 if (window.location == 'http://localhost/mim/index.html')
3431 MIM.server = 'http://localhost/mim';
3432 MIM.current = MIM.imlist['vi']['telex'];
3436 MIM.test = function ()
3438 var im = MIM.imlist['t']['latn-post'];
3439 var ic = new MIM.IC (im, null);
3441 ic.Filter (new MIM.Key ('a'));
3442 ic.Filter (new MIM.Key ("'"));
3445 document.getElementById ('text').value = ic.produced + ic.preedit;
3448 document.getElementById ('text').value
3449 = Xex.Term.Parse (domain, body).Eval (domain).toString ();
3451 if (e instanceof Xex.ErrTerm)
3459 MIM.init_debug = function ()
3462 Xex.LogNode = document.getElementById ('log');