1 // -* coding: utf-8; -*
5 Log: function (arg, indent)
10 if (indent != undefined)
11 for (var i = 0; i < indent; i++)
13 Xex.LogNode.value = str + arg + "\n" + Xex.LogNode.value;
18 UnknownError: "unknown-error",
19 WrongArgument: "wrong-argument",
21 InvalidInteger: "invalid-integer",
22 TermTypeInvalid: "term-type-invalid",
23 FunctionConflict: "function-conflict",
24 VariableTypeConflict: "variable-type-conflict",
25 VariableRangeConflict: "variable-range-conflict",
26 VariableWrongRange: "variable-wrong-range",
27 VariableWrongValue: "variable-wrong-value",
29 UnknownFunction: "unknown-function",
30 MacroExpansionError: "macro-expansion-error",
31 NoVariableName: "no-variable-name",
32 NoFunctionName: "no-funcion-name",
35 ArithmeticError: "arithmetic-error",
36 WrongType: "wrong-type",
37 IndexOutOfRange: "index-out-of-range",
38 ValueOutOfRange: "value-out-of-range",
39 NoLoopToBreak: "no-loop-to-break",
40 UncaughtThrow: "uncaught-throw"
43 Xex.Variable = function (domain, name, desc, val, range)
52 Xex.Variable.prototype.clone = function ()
54 return new Xex.Variable (this.domain, this.name, this.desc,
55 this.val, this.range);
58 Xex.Variable.prototype.Equals = function (obj)
60 return ((obj instanceof Xex.Variable)
61 && obj.name == this.name);
64 Xex.Variable.prototype.SetValue = function (term)
70 Xex.Function = function (name, with_var, min_args, max_args)
73 this.with_var = with_var;
74 this.min_args = min_args;
75 this.max_args = max_args;
78 Xex.Subrountine = function (builtin, name, with_var, min_args, max_args)
81 this.with_var = with_var;
82 this.min_args = min_args;
83 this.max_args = max_args;
84 this.builtin = builtin;
87 Xex.Subrountine.prototype.Call = function (domain, vari, args)
89 var newargs = new Array ();
90 for (var i = 0; i < args.length; i++)
92 newargs[i] = args[i].Eval (domain);
96 return this.builtin (domain, vari, newargs)
99 Xex.SpecialForm = function (builtin, name, with_var, min_args, max_args)
102 this.with_var = with_var;
103 this.min_args = min_args;
104 this.max_args = max_args;
105 this.builtin = builtin;
108 Xex.SpecialForm.prototype.Call = function (domain, vari, args)
110 return this.builtin (domain, vari, args)
113 Xex.Lambda = function (name, min_args, max_args, args, body)
116 this.min_args = min_args;
117 this.max_args = max_args;
122 Xex.Lambda.prototype.Call = function (domain, vari, args)
124 var current = domain.bindings;
125 var result = Xex.Zero;
126 var limit = max_args >= 0 ? args.length : args.length - 1;
130 for (i = 0; i < limit; i++)
132 result = args[i].Eval (domain);
133 if (domain.Thrown ())
135 domain.Bind (this.args[i], result);
139 var list = new Array ();
140 for (i = 0; i < args[limit].length; i++)
142 result = args[limit].Eval (domain);
143 if (domain.Thrown ())
147 domain.Bind (this.args[limit], list);
150 domain.Catch (Xex.CatchTag.Return);
151 for (var term in this.body)
153 result = term.Eval (domain);
154 if (domain.Thrown ())
161 domain.UnboundTo (current);
166 Xex.Macro = function (name, min_args, max_args, args, body)
169 this.min_args = min_args;
170 this.max_args = max_args;
175 Xex.Macro.prototype.Call = function (domain, vari, args)
177 var current = domain.bindings;
178 var result = Xex.Zero;
182 for (i = 0; i < args.length; i++)
183 domain.Bind (this.args[i], args[i]);
185 domain.Catch (Xex.CatchTag.Return);
186 for (var term in body)
188 result = term.Eval (domain);
189 if (domain.Thrown ())
196 domain.UnboundTo (current);
201 Xex.Bindings = function (vari)
204 this.old_value = vari.val;
207 Xex.Bindings.prototype.UnboundTo = function (boundary)
209 for (var b = this; b != boundary; b = b.next)
210 b.vari.val = b.old_value;
214 Xex.Bind = function (bindings, vari, val)
216 var b = new Xex.Bindings (vari);
227 Xex.Domain = function (name, parent, context)
230 this.context = context;
233 if (name != 'basic' && ! parent)
234 parent = Xex.BasicDomain
235 this.parent = parent;
242 for (elt in parent.termtypes)
243 this.termtypes[elt] = parent.termtypes[elt];
244 for (elt in parent.functions)
245 this.functions[elt] = parent.functions[elt];
246 for (elt in parent.variables)
247 this.variables[elt] = parent.variables[elt];
250 this.call_stack = new Array ();
251 this.bindings = null;
252 this.catch_stack = new Array ();
253 this.catch_count = 0;
257 Xex.Domain.prototype = {
258 CallStackCount: function () { return this.call_stack.length; },
259 CallStackPush: function (term) { this.call_stack.push (term); },
260 CallStackPop: function () { this.call_stack.pop (); },
261 Bind: function (vari, val)
263 this.bindings = Xex.Bind (this.bindings, vari, val);
265 UnboundTo: function (boundary)
268 this.bindings = this.bindings.UnboundTo (boundary);
270 Catch: function (tag) { this.catch_stack.push (tag); this.catch_count++; },
273 this.catch_stack.pop ();
274 if (this.catch_count > this.catch_stack.length)
279 if (this.catch_count < this.catch_stack.length)
281 this.caught = (this.catch_count == this.catch_stack.length - 1);
287 ThrowReturn: function ()
289 for (var i = this.catch_stack.length - 1; i >= 0; i--)
292 if (this.catch_stack[i] == Xex.CatchTag.Return)
296 ThrowBreak: function ()
298 if (this.catch_stack[this.catch_stack.length - 1] != Xex.CatchTag.Break)
299 throw new Xex.ErrTerm (Xex.Error.NoLoopToBreak,
300 "No surrounding loop to break");
303 ThrowSymbol: function (tag)
305 var i = this.catch_count;
306 for (var j = this.catch_stack.length - 1; j >= 0; j--)
309 if (Xex.CatchTag.Matches (this.catch_stack[i], tag))
311 this.catch_count = i;
315 throw new Xex.ErrTerm (Xex.Error.UncaughtThrow,
316 "No corresponding catch: " + tag);
318 DefType: function (obj)
321 if (this.termtypes[type])
322 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
323 "Already defined: " + type);
324 if (this.functions[type])
325 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
326 "Already defined as a funciton or a macro: "
328 this.termtypes[type] = obj.Parser;
330 DefSubr: function (builtin, name, with_var, min_args, max_args)
332 this.functions[name] = new Xex.Subrountine (builtin, name, with_var,
335 DefSpecial: function (builtin, name, with_var, min_args, max_args)
337 this.functions[name] = new Xex.SpecialForm (builtin, name, with_var,
340 Defun: function (name, min_args, max_args, args, body)
342 this.functions[name] = new Xex.Lambda (name, min_args, max_args,
345 DefunByFunc: function (func) { this.functions[func.name] = func; },
346 Defmacro: function (name, min_args, max_args, args, body)
348 this.functions[name] = new Xex.Macro (name, min_args, max_args,
351 DefAlias: function (alias, fname)
353 var func = this.functions[fname];
356 throw new Xex.ErrTerm (Xex.Error.UnknownFunction, fname);
357 if (this.termtypes[alias])
358 throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
359 "Already defined as a term type: " + alias);
360 if (this.functions[alias])
361 throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
362 "Already defined as a function: " + alias);
363 this.functions[alias] = func;
365 Defvar: function (name, desc, val, range)
367 var vari = new Xex.Variable (this, name, desc, val, range);
368 this.variables[name] = vari;
371 GetFunc: function (name)
373 var func = this.functions[name];
375 throw new Xex.ErrTerm (Xex.Error.UnknownFunction,
376 "Unknown function: " + name);
379 CopyFunc: function (domain, name)
381 var func = this.functions[name];
382 domain.DefunByFunc (func);
385 CopyFuncAll: function (domain)
387 for (var elt in this.functions)
388 domain.DefunByFunc (this.functions[elt]);
390 GetVarCreate: function (name)
392 var vari = this.variables[name];
394 vari = this.variables[name] = new Xex.Variable (this, name, null,
398 GetVar: function (name) { return this.variables[name]; },
399 SaveValues: function ()
402 for (var elt in this.variables)
403 values[elt] = this.variables[elt].val.Clone ();
406 RestoreValues: function (values)
411 var vari = this.variables[name];
412 vari.val = values[name];
417 Xex.Term = function (type) { this.type = type; }
418 Xex.Term.prototype = {
419 IsTrue: function () { return true; },
420 Eval: function (domain) { return this.Clone (); },
421 Clone: function (domain) { return this; },
422 Equals: function (obj)
424 return (this.type == obj.type
426 && obj.val == this.val);
428 Matches: function (obj) { return this.Equals (obj); },
429 toString: function ()
431 if (this.val != undefined)
432 return '<' + this.type + '>' + this.val + '</' + this.type + '>';
433 return '<' + this.type + '/>';
435 Intval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
436 "Not an integer"); },
437 Strval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
441 Node.prototype.firstElement = function ()
443 for (var n = this.firstChild; n; n = n.nextSibling)
449 Node.prototype.nextElement = function ()
451 for (var n = this.nextSibling; n; n = n.nextSibling)
458 function parse_defvar (domain, node)
460 var name = node.attributes['vname'].nodeValue;
462 throw new Xex.ErrTerm (Xex.Error.NoVariableName, node, '');
463 var vari = domain.variables[name];
464 var desc, val, range;
467 desc = vari.description;
471 node = node.firstElement ();
472 if (node && node.nodeName == 'description')
474 desc = node.firstChild.nodeValue;
475 node = node.nextElement ();
479 val = Xex.Term.Parse (domain, node);
480 node = node.nextElement ();
481 if (node && node.nodeName == 'possible-values')
482 for (node = node.firstElement (); node; node = node.nextElement ())
485 if (node.nodeName == 'range')
488 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
489 'Range not allowed for ' + name);
491 for (var n = node.firstElement (); n; n = n.nextElement ())
493 var v = Xex.Term.Parse (domain, n);
495 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
496 'Invalid range value: ' + val);
502 pval = Xex.Term.Parse (domain, node);
503 if (val.type != pval.type)
504 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
505 'Invalid possible value: ' + pval);
508 range = new Array ();
514 domain.Defvar (name, desc, val, range);
518 function parse_defun_head (domain, node)
520 var name = node.attributes['fname'].nodeValue;
522 throw new Xex.ErrTerm (Xex.Error.NoFunctionName, node, '');
523 var args = new Array ();
524 var nfixed = 0, noptional = 0, nrest = 0;
526 node = node.firstElement ();
527 if (node && node.nodeName == 'args')
530 for (n = n.firstElement (); n; n = n.nextElement ())
532 if (n.nodeName == 'fixed')
534 else if (n.nodeName == 'optional')
536 else if (n.nodeName == 'rest')
539 throw new Xex.ErrTerm (Xex.Error.WrongType, n, n.nodeName);
542 throw new Xex.ErrTerm (Xex.Error.WrongType, n, 'Too many <rest>');
543 for (n = node.firstElement (); n; n = n.nextElement ())
544 args.push (domain.DefVar (n.attributes['vname'].nodeValue));
546 args.min_args = nfixed;
547 args.max_args = nrest == 0 ? nfixed + noptional : -1;
549 if (node.nodeName == 'defun')
550 domain.Defun (name, args, null);
552 domain.Defmacro (name, args, null);
556 function parse_defun_body (domain, node)
558 var name = node.attributes['fname'].nodeValue;
559 var func = domain.GetFunc (name);
561 for (node = node.firstElement (); node; node = node.nextElement ())
562 if (node.nodeName != 'description' && node.nodeName != 'args')
564 body = Xex.Term.Parse (domain, node, null);
568 Xex.Term.Parse = function (domain, node, stop)
570 if (arguments.length == 2)
572 var name = node.nodeName;
573 var parser = domain.termtypes[name];
576 return parser (domain, node);
577 if (name == 'defun' || name == 'defmacro')
579 name = parse_defun_head (domain, node);
580 parse_defun_body (domain, node);
581 return new Xex.StrTerm (name);
583 if (name == 'defvar')
585 name = parse_defvar (domain, node);
586 return new Xex.StrTerm (name);
588 return new Xex.Funcall.prototype.Parser (domain, node);
590 for (var n = node; n && n != stop; n = n.nextElement ())
591 if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
592 parse_defun_head (domain, n);
594 for (var n = node; n && n != stop; n = n.nextElement ())
596 if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
597 parse_defun_body (domain, n);
598 else if (n.nodeName == 'defvar')
599 parse_defvar (domain, n);
603 terms = new Array ();
604 terms.push (Xex.Term.Parse (domain, n));
611 Xex.Varref = function (vname)
617 var proto = new Xex.Term ('varref');
619 proto.Clone = function () { return new Xex.Varref (this.val); }
620 proto.Eval = function (domain)
622 if (! this.vari || this.vari.domain != domain)
623 this.vari = domain.GetVarCreate (this.val);
624 Xex.Log (this.ToString () + '=>' + this.vari.val, domain.depth);
625 return this.vari.val;
628 proto.Parser = function (domain, node)
630 return new Xex.Varref (node.attributes['vname'].nodeValue);
633 proto.ToString = function ()
635 return '<varref vname="' + this.val + '"/>';
638 Xex.Varref.prototype = proto;
641 var null_args = new Array ();
643 Xex.Funcall = function (func, vari, args)
647 this.args = args || null_args;
651 var proto = new Xex.Term ('funcall');
653 proto.Parser = function (domain, node)
655 var fname = node.nodeName;
658 if (fname == 'funcall')
659 fname = node.attributes['fname'].nodeValue;
660 var func = domain.GetFunc (fname);
662 attr = node.attributes['vname'];
663 vari = attr != undefined ? domain.GetVarCreate (attr.nodeValue) : false;
664 var args = Xex.Term.Parse (domain, node.firstElement (), null);
665 return new Xex.Funcall (func, vari, args);
668 proto.New = function (domain, fname, vname, args)
670 var func = domain.GetFunc (fname);
671 var vari = vname ? domain.GetVarCreate (vname) : null;
672 var funcall = new Xex.Funcall (func, vari, args);
673 if (func instanceof Xex.Macro)
674 funcall = funcall.Eval (domain);
678 proto.Eval = function (domain)
680 Xex.Log (this, domain.depth++);
683 result = this.func.Call (domain, this.vari, this.args);
685 Xex.Log (this + ' => ' + result, --domain.depth);
690 proto.Clone = function ()
692 return new Xex.Funcall (this.func, this.vari, this.args);
695 proto.Equals = function (obj)
697 return (obj.type == 'funcall'
698 && obj.func == this.func
699 && obj.vari.Equals (this.vari)
700 && obj.args.length == this.func.length);
703 proto.toString = function ()
706 var len = this.args.length;
707 var str = '<' + this.func.name;
709 str += ' vname="' + this.vari.name + '"';
712 for (var i = 0; i < len; i++)
713 arglist += '.'; //this.args[i].toString ();
714 return str + '>' + arglist + '</' + this.func.name + '>';
717 Xex.Funcall.prototype = proto;
720 Xex.ErrTerm = function (ename, message, stack)
723 this.message = message;
728 var proto = new Xex.Term ('error');
730 proto.IsError = true;
732 proto.Parser = function (domain, node)
734 return new Xex.ErrTerm (node.attributes['ename'].nodeValue,
735 node.innerText, false);
738 proto.CallStack = function () { return stack; }
740 proto.SetCallStack = function (value) { statck = value; }
742 proto.Clone = function ()
744 return new Xex.ErrTerm (ename, message, false);
747 proto.Equals = function (obj)
750 && obj.ename == ename && obj.message == message
751 && (obj.stack ? (stack && stack.length == obj.stack.length)
755 proto.Matches = function (obj)
757 return (obj.IsError && obj.ename == ename);
760 proto.toString = function ()
762 return '<error ename="' + this.ename + '">' + this.message + '</error>';
765 Xex.ErrTerm.prototype = proto;
768 Xex.IntTerm = function (num) { this.val = num; };
770 var proto = new Xex.Term ('integer');
772 proto.Intval = function () { return this.val; };
773 proto.IsTrue = function () { return this.val != 0; }
774 proto.Clone = function () { return new Xex.IntTerm (this.val); }
775 proto.Parser = function (domain, node)
777 var str = node.firstChild.nodeValue;
779 if (str.charAt (0) == '?' && str.length == 2)
780 return new Xex.IntTerm (str.charCodeAt (1));
781 return new Xex.IntTerm (parseInt (node.firstChild.nodeValue));
783 Xex.IntTerm.prototype = proto;
786 Xex.StrTerm = function (str) { this.val = str; };
788 var proto = new Xex.Term ('string');
790 proto.Strval = function () { return this.val; };
791 proto.IsTrue = function () { return this.val.length > 0; }
792 proto.Clone = function () { return new Xex.StrTerm (this.val); }
793 proto.Parser = function (domain, node)
795 return new Xex.StrTerm (node.firstChild.nodeValue);
797 Xex.StrTerm.prototype = proto;
800 Xex.SymTerm = function (str) { this.val = str; };
802 var proto = new Xex.Term ('symbol');
803 proto.IsSymbol = true;
804 proto.IsTrue = function () { return this.val != 'nil'; }
805 proto.Clone = function () { return new Xex.SymTerm (this.val); }
806 proto.Parser = function (domain, node)
808 return new Xex.SymTerm (node.firstChild.nodeValue);
810 Xex.SymTerm.prototype = proto;
813 Xex.LstTerm = function (list) { this.val = list; };
815 var proto = new Xex.Term ('list');
817 proto.IsTrue = function () { return this.val.length > 0; }
818 proto.Clone = function () { return new Xex.LstTerm (this.val.slice (0)); }
820 proto.Equals = function (obj)
822 if (obj.type != 'list' || obj.val.length != this.val.length)
824 var i, len = this.val.length;
825 for (i = 0; i < len; i++)
826 if (! this.val[i].Equals (obj.val[i]))
831 proto.Parser = function (domain, node)
833 var list = Xex.Term.Parse (domain, node.firstElement (), null);
834 return new Xex.LstTerm (list);
837 proto.toString = function ()
839 var len = this.val.length;
844 for (var i = 0; i < len; i++)
845 str += this.val[i].toString ();
846 return str + '</list>';
848 Xex.LstTerm.prototype = proto;
852 var basic = new Xex.Domain ('basic', null, null);
854 function Fset (domain, vari, args)
857 throw new Xex.ErrTerm (Xex.Error.NoVariableName,
858 'No variable name to set');
859 vari.SetValue (args[0]);
863 function maybe_set_intvar (vari, n)
865 var term = new IntTerm (n);
867 vari.SetValue (term);
871 function Fadd (domain, vari, args)
873 var n = vari ? vari.val.Intval () : 0;
874 var len = args.length;
876 for (var i = 0; i < len; i++)
877 n += args[i].Intval ();
878 return maybe_set_intvar (vari, n);
881 function Fmul (domain, vari, args)
883 var n = vari ? vari.val.Intval () : 1;
884 for (var i = 0; i < args.length; i++)
886 return maybe_set_intvar (vari, n);
889 function Fsub (domain, vari, args)
895 n = args[0].Intval ();
900 n = vari.val.Intval ();
903 while (i < args.length)
904 n -= args[i++].Intval ();
905 return maybe_set_intvar (vari, n);
908 function Fdiv (domain, vari, args)
914 n = args[0].Intval ();
919 n = vari.val.Intval ();
922 while (i < args.length)
923 n /= args[i++].Intval ();
924 return maybe_set_intvar (vari, n);
927 function Fmod (domain, vari, args)
929 return maybe_set_intvar (vari, args[0].Intval () % args[1].Intval ());
932 function Flogior (domain, vari, args)
934 var n = vari == null ? 0 : vari.val;
935 for (var i = 0; i < args.length; i++)
937 return maybe_set_intvar (vari, n);
940 function Fand (domain, vari, args)
942 var len = args.length;
943 for (var i = 0; i < len; i++)
945 var result = args[i].Eval (domain);
946 if (domain.Thrown ())
948 if (! result.IsTrue ())
954 function For (domain, vari, args)
956 var len = args.length;
957 for (var i = 0; i < len; i++)
959 var result = args[i].Eval (domain);
960 if (domain.Thrown ())
962 if (result.IsTrue ())
968 function Feq (domain, vari, args)
970 for (var i = 1; i < args.length; i++)
971 if (! args[i - 1].Equals (args[i]))
976 function Flt (domain, vari, args)
978 var n = args[0].Intval;
980 for (var i = 1; i < args.length; i++)
982 var n1 = args[i].Intval;
990 function Fle (domain, vari, args)
992 var n = args[0].Intval;
993 for (var i = 1; i < args.length; i++)
995 var n1 = args[i].Intval;
1003 function Fgt (domain, vari, args)
1005 var n = args[0].Intval;
1006 for (var i = 1; i < args.length; i++)
1008 var n1 = args[i].Intval;
1016 function Fge (domain, vari, args)
1018 var n = args[0].Intval;
1019 for (var i = 1; i < args.Length; i++)
1021 var n1 = args[i].Intval;
1029 function Fprogn (domain, vari, args)
1031 var result = Xex.One;
1032 var len = args.length;
1034 for (var i = 0; i < len; i++)
1036 result = args[i].Eval (domain);
1037 if (domain.Thrown ())
1043 function Fif (domain, vari, args)
1045 var result = args[0].Eval (domain);
1047 if (domain.Thrown ())
1049 if (result.IsTrue ())
1050 return args[1].Eval (domain);
1051 if (args.length == 2)
1053 return args[2].Eval (domain);
1056 function Fcond (domain, vari, args)
1058 for (var i = 0; i < args.length; i++)
1060 var list = args[i].val;
1061 var result = list.val[0].Eval (doamin);
1062 if (result.isTrue ())
1064 for (var j = 1; j < list.val.length; j++)
1067 result = list.val[j].Eval (domain);
1069 if (domain.Thrown ())
1078 function eval_terms (domain, terms, idx)
1080 var result = Xex.Zero;
1081 domain.caught = false;
1082 for (var i = idx; i < terms.length; i++)
1084 result = terms[i].Eval (domain);
1085 if (domain.Thrown ())
1091 function Fcatch (domain, vari, args)
1096 if (args[0].IsError)
1099 result = eval_terms (domain, args, 1);
1101 if (e instanceof Xex.ErrTerm)
1103 if (! args[0].Matches (e))
1111 else if (args[0].IsSymbol)
1114 domain.Catch (args[0].val);
1115 result = eval_terms (domain, args, 1);
1119 vari.SetValue (result);
1127 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1128 "Not a symbol nor an error: " + args[0]);
1131 function Fthrow (domain, vari, args)
1133 if (args[0].IsSymbl)
1135 domain.ThrowSymbol (args[0]);
1136 return (args[args.length - 1]);
1138 if (args[0].IsError)
1142 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1143 "Not a symbol nor an error:" + args[0]);
1146 Xex.BasicDomain = basic;
1148 basic.DefSubr (Fset, "set", true, 1, 1);
1149 basic.DefAlias ("=", "set");
1150 //basic.DefSubr (Fnot, "not", false, 1, 1);
1151 //basic.DefAlias ("!", "not");
1152 basic.DefSubr (Fadd, "add", true, 1, -1);
1153 basic.DefSubr (Fmul, "mul", true, 1, -1);
1154 basic.DefAlias ("*", "mul");
1155 basic.DefSubr (Fsub, "sub", true, 1, -1);
1156 basic.DefAlias ("-", "sub");
1157 basic.DefSubr (Fdiv, "div", true, 1, -1);
1158 basic.DefAlias ("/", "div");
1159 basic.DefSubr (Fmod, "mod", true, 1, 2);
1160 basic.DefAlias ("%", "mod");
1161 basic.DefSubr (Flogior, "logior", true, 1, -1);
1162 basic.DefAlias ('|', "logior");
1163 //basic.DefSubr (Flogand, "logand", true, 1, -1);
1164 //basic.DefAlias ("&", "logand");
1165 //basic.DefSubr (Flsh, "lsh", true, 1, 2);
1166 //basic.DefAlias ("<<", "lsh");
1167 //basic.DefSubr (Frsh, "rsh", true, 1, 2);
1168 //basic.DefAlias (">>", "rsh");
1169 basic.DefSubr (Feq, "eq", false, 2, -1);
1170 basic.DefAlias ("==", "eq");
1171 //basic.DefSubr (Fnoteq, "noteq", false, 2, 2);
1172 //basic.DefAlias ("!=", "noteq");
1173 basic.DefSubr (Flt, "lt", false, 2, -1);
1174 basic.DefAlias ("<", "lt");
1175 basic.DefSubr (Fle, "le", false, 2, -1);
1176 basic.DefAlias ("<=", "le");
1177 basic.DefSubr (Fgt, "gt", false, 2, -1);
1178 basic.DefAlias (">", "gt");
1179 basic.DefSubr (Fge, "ge", false, 2, -1);
1180 basic.DefAlias (">=", "ge");
1181 basic.DefSubr (Fthrow, "throw", false, 1, 2);
1183 //basic.DefSubr (Fappend, "append", true, 0, -1);
1184 //basic.DefSubr (Fconcat, "concat", true, 0, -1);
1185 //basic.DefSubr (Fnth, "nth", false, 2, 2);
1186 //basic.DefSubr (Fcopy, "copy", false, 1, 1);
1187 //basic.DefSubr (Fins, "ins", true, 2, 2);
1188 //basic.DefSubr (Fdel, "del", true, 2, 2);
1189 //basic.DefSubr (Feval, "eval", false, 1, 1);
1190 //basic.DefSubr (Fbreak, "break", false, 0, 1);
1191 //basic.DefSubr (Freturn, "return", false, 0, 1);
1192 //basic.DefSubr (Fthrow, "throw", false, 1, 2);
1194 basic.DefSpecial (Fand, "and", false, 1, -1);
1195 basic.DefAlias ("&&", "and");
1196 basic.DefSpecial (For, "or", false, 1, -1);
1197 basic.DefAlias ("||", "or");
1198 basic.DefSpecial (Fprogn, "progn", false, 1, -1);
1199 basic.DefAlias ("expr", "progn");
1200 basic.DefSpecial (Fif, "if", false, 2, 3);
1201 //basic.DefSpecial (Fwhen, "when", false, 1, -1);
1202 //basic.DefSpecial (Floop, "loop", false, 1, -1);
1203 //basic.DefSpecial (Fwhile, "while", false, 1, -1);
1204 basic.DefSpecial (Fcond, "cond", false, 1, -1);
1205 //basic.DefSpecial (Fforeach, "foreach", true, 2, -1);
1206 //basic.DefSpecial (Fquote, "quote", false, 1, 1);
1207 //basic.DefSpecial (Ftype, "type", false, 1, 1);
1208 basic.DefSpecial (Fcatch, "catch", true, 2, -1);
1210 basic.DefType (Xex.Funcall.prototype);
1211 basic.DefType (Xex.Varref.prototype);
1212 basic.DefType (Xex.ErrTerm.prototype);
1213 basic.DefType (Xex.IntTerm.prototype);
1214 basic.DefType (Xex.StrTerm.prototype);
1215 basic.DefType (Xex.SymTerm.prototype);
1216 basic.DefType (Xex.LstTerm.prototype);
1220 Xex.Zero = new Xex.IntTerm (0);
1221 Xex.One = new Xex.IntTerm (1);
1222 Xex.nil = new Xex.SymTerm ('nil');
1224 Xex.Load = function (server, file)
1226 var obj = new XMLHttpRequest ();
1227 var url = server ? server + '/' + file : file;
1228 obj.open ('GET', url, false);
1229 obj.overrideMimeType ('text/xml');
1231 return obj.responseXML.firstChild;
1235 // URL of the input method server.
1236 server: "http://www.m17n.org/common/mim-js",
1237 // Boolean flag to tell if MIM is active or not.
1239 // Boolean flag to tell if MIM is running in debug mode or not.
1241 // List of main input methods.
1243 // List of extra input methods;
1245 // Global input method data
1247 // Currently selected input method.
1251 LoadStatus: { NotLoaded:0, Loading:1, Loaded:2, Error:-1 },
1258 CandidateIndex:0x10,
1260 Preedit: 0x06, // PreeditText | CursorPos
1261 Candidate: 0x38 // CandidateList | CandidateIndex | CandidateShow
1283 ParseError: "parse-error"
1288 var keysyms = new Array ();
1289 keysyms["bs"] = "backspace";
1290 keysyms["lf"] = "linefeed";
1291 keysyms["cr"] = keysyms["enter"] = "return";
1292 keysyms["esc"] = "escape";
1293 keysyms["spc"] = "space";
1294 keysyms["del"] = "delete";
1296 function decode_keysym (str) {
1297 var parts = str.split ("-");
1298 var len = parts.length, i;
1299 var has_modifier = len > 1;
1301 for (i = 0; i < len - 1; i++)
1302 if (! MIM.KeyModifier.hasOwnProperty (parts[i]))
1304 var key = parts[len - 1];
1307 key = keysyms[key.toLowerCase ()];
1313 for (i = 1; i < len - 1; i++)
1314 str += '-' + parts[i];
1323 parts = new Array ();
1330 MIM.Key = function (val)
1333 this.has_modifier = false;
1334 if (typeof val == 'string' || val instanceof String)
1336 this.key = decode_keysym (val);
1338 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1339 if (this.key instanceof Array)
1341 this.key = this.key[0];
1342 this.has_modifier = true;
1345 else if (typeof val == 'number' || val instanceof Number)
1346 this.key = String.fromCharCode (val);
1348 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1351 MIM.Key.prototype.toString = function () { return this.key; };
1355 MIM.KeySeq = function (seq)
1357 this.val = new Array ();
1358 this.has_modifier = false;
1364 var len = seq.val.length;
1365 for (var i = 0; i < len; i++)
1368 if (v.type != 'string' && v.type != 'integer'
1369 && v.type != 'symbol')
1370 throw new Xex.ErrTerm (MIM.Error.ParseError,
1371 "Invalid key: " + v);
1372 var key = new MIM.Key (v.val);
1373 this.val.push (key);
1374 if (key.has_modifier)
1375 this.has_modifier = true;
1380 var len = seq.val.length;
1381 for (var i = 0; i < len; i++)
1382 this.val.push (new MIM.Key (seq.val.charCodeAt (i)));
1385 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + seq);
1389 var proto = new Xex.Term ('keyseq');
1390 proto.Clone = function () { return this; }
1391 proto.Parser = function (domain, node)
1393 var seq = new Array ();
1394 for (node = node.firstChild; node; node = node.nextSibling)
1395 if (node.nodeType == 1)
1397 var term = Xex.Term.Parse (domain, node);
1398 return new MIM.KeySeq (term);
1400 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid keyseq");
1402 proto.toString = function ()
1404 var len = this.val.length;
1408 var str = '<keyseq>';
1409 for (var i = 0; i < len; i++)
1413 else if (this.has_modifier)
1415 str += this.val[i].toString ();
1417 return str + '</keyseq>';
1420 MIM.KeySeq.prototype = proto;
1424 MIM.Marker = function () { }
1425 MIM.Marker.prototype = new Xex.Term ('marker');
1426 MIM.Marker.prototype.CharAt = function (ic)
1428 var p = this.Position (ic);
1429 if (p < 0 || p >= ic.preedit.length)
1431 return ic.preedit.charCodeAt (p);
1434 MIM.NamedMarker = function (name) { this.val = name; }
1435 MIM.NamedMarker.prototype = new MIM.Marker ();
1436 MIM.NamedMarker.prototype.Position = function (ic)
1438 var p = ic.marker_positions[this.val];
1439 return (p == undefined ? 0 : p);
1441 MIM.NamedMarker.prototype.Mark = function (ic)
1443 ic.marker_positions[this.val] = ic.cursor_pos;
1446 MIM.PredefinedMarker = function (name) { this.val = name; }
1447 MIM.PredefinedMarker.prototype = new MIM.Marker ();
1448 MIM.PredefinedMarker.prototype.Position = function (ic)
1450 if (typeof this.pos == 'number')
1452 return this.pos (ic);
1455 var predefined = { }
1457 function def_predefined (name, position)
1459 predefined[name] = new MIM.PredefinedMarker (name);
1460 predefined[name].pos = position;
1463 def_predefined ('@<', 0);
1464 def_predefined ('@>', function (ic) { return ic.preedit.length; });
1465 def_predefined ('@-', function (ic) { return ic.cursor_pos - 1; });
1466 def_predefined ('@+', function (ic) { return ic.cursor_pos + 1; });
1467 def_predefined ('@[', function (ic) {
1468 if (ic.cursor_pos > 0)
1470 var pos = ic.cursor_pos;
1471 return ic.preedit.FindProp ('candidates', pos - 1).from;
1475 def_predefined ('@]', function (ic) {
1476 if (ic.cursor_pos < ic.preedit.length - 1)
1478 var pos = ic.cursor_pos;
1479 return ic.preedit.FindProp ('candidates', pos).to;
1481 return ic.preedit.length;
1483 for (var i = 0; i < 10; i++)
1484 def_predefined ("@" + i, i);
1485 predefined['@first'] = predefined['@<'];
1486 predefined['@last'] = predefined['@>'];
1487 predefined['@previous'] = predefined['@-'];
1488 predefined['@next'] = predefined['@+'];
1489 predefined['@previous-candidate-change'] = predefined['@['];
1490 predefined['@next-candidate-change'] = predefined['@]'];
1492 MIM.SurroundMarker = function (name)
1495 this.distance = parseInt (name.slice (1));
1496 if (isNaN (this.distance))
1497 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid marker: " + name);
1499 MIM.SurroundMarker.prototype = new MIM.Marker ();
1500 MIM.SurroundMarker.prototype.Position = function (ic)
1502 return ic.cursor_pos + this.distance;
1504 MIM.SurroundMarker.prototype.CharAt = function (ic)
1506 if (this.val == '@-0')
1508 var p = this.Position (ic);
1510 return ic.GetSurroundingChar (p);
1511 else if (p >= ic.preedit.length)
1512 return ic.GetSurroundingChar (p - ic.preedit.length);
1513 return ic.preedit.charCodeAt (p);
1516 MIM.Marker.prototype.Parser = function (domain, node)
1518 var name = node.firstChild.nodeValue;
1519 if (name.charAt (0) == '@')
1521 var n = predefined[name];
1524 if (name.charAt (1) == '-')
1525 return new MIM.SurroundMarker (name);
1526 throw new Xex.ErrTerm (MIM.Error.ParseError,
1527 "Invalid marker: " + name);
1529 return new MIM.NamedMarker (name);
1533 MIM.Selector = function (name)
1537 MIM.Selector.prototype = new Xex.Term ('selector');
1541 selectors["@<"] = selectors["@first"] = new MIM.Selector ('@<');
1542 selectors["@="] = selectors["@current"] = new MIM.Selector ('@=');
1543 selectors["@>"] = selectors["@last"] = new MIM.Selector ('@>');
1544 selectors["@-"] = selectors["@previous"] = new MIM.Selector ('@-');
1545 selectors["@+"] = selectors["@next"] = new MIM.Selector ('@+');
1546 selectors["@["] = selectors["@previous-candidate-change"]
1547 = new MIM.Selector ('@[');
1548 selectors["@]"] = selectors["@next-candidate-change"]
1549 = new MIM.Selector ('@]');
1551 MIM.Selector.prototype.Parser = function (domain, node)
1553 var name = node.firstChild.nodeValue;
1554 var s = selectors[name];
1556 throw new Xex.ErrTerm (MIM.Error.ParseError,
1557 "Invalid selector: " + name);
1562 MIM.Rule = function (keyseq, actions)
1564 this.keyseq = keyseq;
1565 this.actions = actions;
1567 MIM.Rule.prototype = new Xex.Term ('rule');
1568 MIM.Rule.prototype.Parser = function (domain, node)
1571 for (n = node.firstChild; n && n.nodeType != 1; n = n.nextSibling);
1573 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1574 var keyseq = Xex.Term.Parse (domain, n);
1575 if (keyseq.type != 'keyseq')
1576 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1577 var actions = Xex.Term.Parse (domain, n.nextElement (), null);
1578 return new MIM.Rule (keyseq, actions);
1580 MIM.Rule.prototype.toString = function ()
1585 MIM.Map = function (name)
1588 this.rules = new Array ();
1592 var proto = new Xex.Term ('map');
1594 proto.Parser = function (domain, node)
1596 var name = node.attributes['mname'].nodeValue;
1598 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1599 var map = new MIM.Map (name);
1600 for (var n = node.firstChild; n; n = n.nextSibling)
1601 if (n.nodeType == 1)
1602 map.rules.push (Xex.Term.Parse (domain, n));
1606 proto.toString = function ()
1608 var str = '<map mname="' + this.name + '">';
1609 var len = this.rules.length;
1610 for (i = 0; i < len; i++)
1611 str += this.rules[i];
1612 return str + '</map>';
1615 MIM.Map.prototype = proto;
1618 Xex.CatchTag._mimtag = new Xex.SymTerm ('@mimtag');
1620 MIM.Action = function (domain, terms)
1622 var args = new Array ();
1623 args.push (Xex.CatchTag_.mimtag);
1624 for (var i = 0; i < terms.length; i++)
1625 args.push (terms[i]);
1626 this.action = Xex.Funcall.prototype.New (domain, 'catch', null, args);
1629 MIM.Action.prototype.Run = function (domain)
1631 var result = this.action.Eval (domain);
1632 if (result.type == 'error')
1634 domain.context.Error = result.toString ();
1637 return (result != Xex.CatchTag._mimtag);
1640 MIM.Keymap = function ()
1643 this.submaps = null;
1649 function add_rule (keymap, rule, branch_actions)
1651 var keyseq = rule.keyseq;
1652 var len = keyseq.val.length;
1655 for (var i = 0; i < len; i++)
1657 var key = keyseq.val[i];
1661 if (! keymap.submaps)
1662 keymap.submaps = {};
1664 sub = keymap.submaps[key.key];
1666 keymap.submaps[key.key] = sub = new MIM.Keymap ();
1670 keymap.map_actions = rule.actions;
1671 keymap.branch_actions = branch_actions;
1674 proto.Add = function (map, branch_actions)
1676 var rules = map.rules;
1677 var len = rules.length;
1679 for (var i = 0; i < len; i++)
1680 add_rule (this, rules[i], branch_actions);
1682 proto.Lookup = function (keys, index)
1686 if (index < keys.val.length && this.submaps
1687 && (sub = this.submaps[keys.val[index].key]))
1690 return sub.Lookup (keys, index);
1692 return { map: this, index: index };
1695 MIM.Keymap.prototype = proto;
1698 MIM.State = function (name)
1701 this.keymap = new MIM.Keymap ();
1705 var proto = new Xex.Term ('state');
1707 proto.Parser = function (domain, node)
1709 var map_list = domain.map_list;
1710 var name = node.attributes['sname'].nodeValue;
1712 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1713 var state = new MIM.State (name);
1714 for (node = node.firstElement (); node; node = node.nextElement ())
1716 if (node.nodeName == 'title')
1717 state.title = node.firstChild.nodeValue;
1720 var n = node.firstElement ();
1721 if (node.nodeName == 'branch')
1722 state.keymap.Add (map_list[node.attributes['mname'].nodeValue],
1723 Xex.Term.Parse (domain, n, null));
1724 else if (node.nodeName == 'state-hook')
1725 state.enter_actions = Xex.Term.Parse (domain, n, null);
1726 else if (node.nodeName == 'catch-all-branch')
1727 state.fallback_actions = Xex.Term.Parse (domain, n, null);
1733 proto.toString = function ()
1735 return '<state sname="' + this.name + '">' + this.keymap + '</state>';
1738 MIM.State.prototype = proto;
1742 function Block (index, term)
1746 this.Data = term.val;
1747 else if (term.IsList)
1749 this.Data = new Array ();
1750 for (var i = 0; i < term.val.length; i++)
1751 this.Data.push (term.val[i].val);
1755 Block.prototype.Count = function () { return this.Data.length; }
1756 Block.prototype.get = function (i)
1758 return (this.Data instanceof Array ? this.Data[i] : this.Data.charAt (i));
1761 MIM.Candidates = function (candidates, column)
1763 this.column = column;
1767 this.blocks = new Array ();
1769 for (var i = 0; i < candidates.length; i++)
1771 var block = new Block (this.total, candidates[i]);
1772 this.blocks.push (block);
1773 this.total += block.Count ();
1779 return (this.column > 0 ? this.index % this.column
1780 : this.index - this.blocks[this.row].Index);
1783 function prev_group ()
1785 var col = get_col.call (this);
1787 if (this.column > 0)
1789 this.index -= this.column;
1790 if (this.index >= 0)
1791 nitems = this.column;
1794 var lastcol = (this.total - 1) % this.column;
1795 this.index = (col < lastcol ? this.total - lastcol + col
1797 this.row = this.blocks.length - 1;
1798 nitems = lastcol + 1;
1800 while (this.blocks[this.row].Index > this.index)
1805 this.row = this.row > 0 ? this.row - 1 : this.blocks.length - 1;
1806 nitems = this.blocks[this.row].Count ();
1807 this.index = (this.blocks[this.row].Index
1808 + (col < nitems ? col : nitems - 1));
1813 function next_group ()
1815 var col = get_col.call (this);
1817 if (this.column > 0)
1819 this.index += this.column - col;
1820 if (this.index < this.total)
1822 if (this.index + col >= this.total)
1824 nitems = this.total - this.index;
1825 this.index = this.total - 1;
1829 nitems = this.column;
1838 while (this.blocks[this.row].Index > this.index)
1843 this.row = this.row < this.blocks.length - 1 ? this.row + 1 : 0;
1844 nitems = this.blocks[this.row].Count ();
1845 this.index = (this.blocks[this.row].Index
1846 + (col < nitems ? col : nitems - 1));
1853 if (this.index == 0)
1855 this.index = this.total - 1;
1856 this.row = this.blocks.length - 1;
1861 if (this.blocks[this.row].Index > this.index)
1869 if (this.index == this.total)
1876 var b = this.blocks[this.row];
1877 if (this.index == b.Index + b.Count ())
1884 this.index -= get_col.call (this);
1885 while (this.blocks[this.row].Index > this.index)
1891 var b = this.blocks[this.row];
1892 if (this.column > 0)
1894 if (this.index + 1 < this.total)
1896 this.index += this.column - get_col.call (this) + 1;
1897 while (b.Index + b.Count () <= this.index)
1898 b = this.blocks[++this.row];
1902 this.index = b.Index + b.Count () - 1;
1905 MIM.Candidates.prototype.Current = function ()
1907 var b = this.blocks[this.row];
1908 return b.get (this.index - b.Index);
1911 MIM.Candidates.prototype.Select = function (selector)
1913 if (selector.type == 'selector')
1915 switch (selector.val)
1917 case '@<': first.call (this); break;
1918 case '@>': last.call (this); break;
1919 case '@-': prev.call (this); break;
1920 case '@+': next.call (this); break;
1921 case '@[': prev_group.call (this); break;
1922 case '@]': next_group.cal (this); break;
1925 return this.Current ();
1928 if (this.column > 0)
1930 col = this.index % this.column;
1931 start = this.index - col;
1932 end = start + this.column;
1936 start = this.blocks[this.row].Index;
1937 col = this.index - start;
1938 end = start + this.blocks[this.row].Count;
1940 if (end > this.total)
1942 this.index += selector.val - col;
1943 if (this.index >= end)
1944 this.index = end - 1;
1945 if (this.column > 0)
1947 if (selector.val > col)
1948 while (this.blocks[this.row].Index + this.blocks[this.row].Count
1952 while (this.blocks[this.row].Index > this.index)
1955 return this.Current ();
1959 MIM.im_domain = new Xex.Domain ('input-method', null, null);
1960 MIM.im_domain.DefType (MIM.KeySeq.prototype);
1961 MIM.im_domain.DefType (MIM.Marker.prototype);
1962 MIM.im_domain.DefType (MIM.Selector.prototype);
1963 MIM.im_domain.DefType (MIM.Rule.prototype);
1964 MIM.im_domain.DefType (MIM.Map.prototype);
1965 MIM.im_domain.DefType (MIM.State.prototype);
1968 var im_domain = MIM.im_domain;
1970 function Finsert (domain, vari, args)
1973 if (args[0].type == 'integer')
1974 text = String.fromCharCode (args[0].val);
1977 domain.context.insert (text, null);
1981 function Finsert_candidates (domain, vari, args)
1983 var ic = domain.context;
1984 var gsize = domain.variables['candidates_group_size'];
1985 var candidates = new MIM.Candidates (args, gsize ? gsize.Intval : 0);
1986 ic.insert (candidates.Current (), candidates);
1990 function Fdelete (domain, vari, args)
1992 var ic = domain.context;
1993 var pos = args[0].IsInt ? args[0].Intval : args[0].Position (ic);
1995 return new Xex.Term (ic.del (pos));
1998 function Fselect (domain, vari, args)
2000 var ic = domain.context;
2001 var can = ic.candidates;
2005 var candidate = can.Current ();
2007 ic.del (ic.cursor_pos - candidate.length);
2008 candidate = can.Select (args[0]);
2009 ic.insert (candidate, can);
2014 function Fchar_at (domain, vari, args)
2016 return new Xex.IntTerm (args[0].CharAt (domain.context));
2019 function Fmove (domain, vari, args)
2021 var ic = domain.context;
2022 var pos = args[0].IsInt ? args[0].val : args[0].Position (ic);
2027 function Fmark (domain, vari, args)
2029 args[0].Mark (domain.context);
2033 function Fpushback (domain, vari, args)
2035 var arg = (args[0].IsInt ? args[0].Intval
2036 : args[0].IsStr ? new KeySeq (args[0])
2038 domain.context.pushback (arg)
2042 function Fundo (domain, vari, args)
2044 var ic = domain.context;
2045 var n = args.length == 0 ? -2 : args[0].val;
2047 ic.keys.val.splice (ic.keys.length + n, -n);
2049 ic.keys.val.splice (n, ic.keys.length);
2054 function Fcommit (domain, vari, args)
2056 domain.context.commit ();
2060 function Funhandle (domain, vari, args)
2062 domain.context.commit ();
2063 return Xex.Fthrow (domain, vari, Xex.CatchTag._mimtag);
2066 function Fshift (domain, vari, args)
2068 var ic = domain.context;
2069 var state_name = args[0].val;
2070 var state = ic.im.state_list[state_name];
2072 throw ("Unknown state: " + state_name);
2077 function Fsurrounding_flag (domain, vari, args)
2079 return new Xex.IntTerm (-1);
2082 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
2083 im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, 1);
2084 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
2085 im_domain.DefSubr (Fselect, "select", false, 1, 1);
2086 //im_domain.DefSubr (Fshow, "show-candidates", false, 0, 0);
2087 //im_domain.DefSubr (Fhide, "hide-candidates", false, 0, 0);
2088 im_domain.DefSubr (Fmove, "move", false, 1, 1);
2089 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
2090 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
2091 //im_domain.DefSubr (Fpop, "pop", false, 0, 0);
2092 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
2093 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
2094 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
2095 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
2096 //im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
2097 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
2098 //im_domain.DefSubr (Fkey_count, "key-count", false, 0, 0);
2099 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag", false, 0, 0);
2104 function get_global_var (vname)
2106 if (MIM.im_global.load_status == MIM.LoadStatus.NotLoaded)
2107 MIM.im_global.Load ()
2108 return MIM.im_global.domain.variables[vname];
2111 function include (node)
2113 node = node.firstElement ();
2114 if (node.nodeName != 'tags')
2117 var lang = null, name = null, extra = null;
2118 for (node = node.firstElement (); node; node = node.nextElement ())
2120 if (node.nodeName == 'language')
2121 lang = node.firstChild.nodeValue;
2122 else if (node.nodeName == 'name')
2123 name = node.firstChild.nodeValue;
2124 else if (node.nodeName == 'extra-id')
2125 extra = node.firstChild.nodeValue;
2127 if (! lang || ! MIM.imlist[lang])
2131 if (! name || ! (im = MIM.imlist[lang][name]))
2136 if (! (im = MIM.imextra[lang][extra]))
2139 if (im.load_status != MIM.LoadStatus.Loaded
2140 && (im.load_status != MIM.LoadStatus.NotLoaded || ! im.Load ()))
2147 parsers['description'] = function (node)
2149 this.description = node.firstChild.nodeValue;
2151 parsers['variable-list'] = function (node)
2153 for (node = node.firstElement (); node; node = node.nextElement ())
2155 var vname = node.attributes['vname'].nodeValue;
2156 if (this != MIM.im_global)
2158 var vari = get_global_var (vname);
2160 this.domain.Defvar (vname);
2162 vname = Xex.Term.Parse (this.domain, node)
2165 parsers['command-list'] = function (node)
2168 parsers['macro-list'] = function (node)
2170 for (var n = node.firstElement (); n; n = n.nextElement ())
2171 if (n.nodeName == 'xi:include')
2173 var im = include (n);
2175 alert ('inclusion fail');
2177 for (var macro in im.domain.functions)
2179 var func = im.domain.functions[macro];
2180 if (func instanceof Xex.Macro)
2181 im.domain.CopyFunc (this.domain, macro);
2183 n = n.previousSibling;
2184 node.removeChild (n.nextSibling);
2186 Xex.Term.Parse (this.domain, node.firstElement (), null);
2188 parsers['title'] = function (node)
2190 this.title = node.firstChild.nodeValue;
2192 parsers['map-list'] = function (node)
2194 for (node = node.firstElement (); node; node = node.nextElement ())
2196 if (node.nodeName == 'xi:include')
2198 var im = include (node);
2201 alert ('inclusion fail');
2204 for (var mapname in im.map_list)
2205 this.map_list[mapname] = im.map_list[mapname];
2209 var map = Xex.Term.Parse (this.domain, node);
2210 this.map_list[map.name] = map;
2214 parsers['state-list'] = function (node)
2216 this.domain.map_list = this.map_list;
2217 for (node = node.firstElement (); node; node = node.nextElement ())
2219 if (node.nodeName == 'state')
2221 var state = Xex.Term.Parse (this.domain, node);
2223 state.title = this.title;
2224 if (! this.initial_state)
2225 this.initial_state = state;
2226 this.state_list[state.name] = state;
2229 delete this.domain.map_list;
2232 MIM.IM = function (lang, name, extra_id, file)
2236 this.extra_id = extra_id;
2238 this.load_status = MIM.LoadStatus.NotLoaded;
2239 this.domain = new Xex.Domain (this.lang + '-'
2240 + (this.name != 'nil'
2241 ? this.name : this.extra_id),
2242 MIM.im_domain, null);
2248 var node = Xex.Load (null, this.file);
2251 this.load_status = MIM.LoadStatus.Error;
2255 this.initial_state = null;
2256 this.state_list = {};
2257 for (node = node.firstElement (); node; node = node.nextElement ())
2259 var name = node.nodeName;
2260 var parser = parsers[name];
2262 parser.call (this, node);
2264 this.load_status = MIM.LoadStatus.Loaded;
2269 MIM.IM.prototype = proto;
2271 MIM.IC = function (im, target)
2273 if (im.load_status == MIM.LoadStatus.NotLoaded)
2275 if (im.load_status != MIM.LoadStatus.Loaded)
2276 alert ('im:' + im.name + ' error:' + im.load_status);
2278 this.target = target;
2279 this.domain = new Xex.Domain ('context', im.domain, this);
2285 MIM.CandidateTable = function ()
2287 this.table = new Array ();
2290 MIM.CandidateTable.prototype.get = function (from)
2292 for (var i = 0; i < this.table.length; i++)
2294 var elt = this.table[i];
2295 if (elt.from <= from && elt.to > from)
2300 MIM.CandidateTable.prototype.put = function (from, to, candidates)
2302 for (var i = 0; i < this.table.length; i++)
2304 var elt = this.table[i];
2305 if (elt.from >= from && elt.from < to
2306 || elt.to >= from && elt.to < to)
2310 elt.val = candidates;
2314 this.table.push ({ from: from, to: to, val: candidates });
2317 MIM.CandidateTable.prototype.adjust = function (from, to, inserted)
2319 var diff = inserted - (to - from);
2320 for (var i = 0; i < this.table.length; i++)
2322 var elt = this.table[i];
2331 MIM.CandidateTable.prototype.clear = function ()
2333 this.table.length = 0;
2336 function detach_candidates (ic)
2338 ic.candidate_table.clear ();
2339 ic.candidates = null;
2340 ic.changed |= (MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos
2341 | ChangedStatus.CandidateList
2342 | ChangedStatus.CandidateIndex
2343 | ChangedStatus.CandidateShow);
2346 function set_cursor (prefix, pos)
2348 this.cursor_pos = pos;
2350 this.candidates = this.candidate_table.get (pos - 1);
2352 this.candidates = null;
2355 function save_state ()
2357 this.state_var_values = this.domain.SaveValues ();
2358 this.state_preedit = this.preedit;
2359 this.state_key_head = this.key_head;
2360 this.state_pos = this.cursor_pos;
2363 function restore_state ()
2365 this.domain.RestoreValues (this.state_var_values);
2366 this.preedit = this.state_preedit;
2367 set_cursor.call (this, "restore", this.state_pos);
2370 function handle_key ()
2372 var out = this.keymap.Lookup (this.keys, this.key_head);
2375 Xex.Log ('handling ' + this.keys.val[this.key_head]
2376 + ' in ' + this.state.name + ':' + this.keymap.name);
2377 this.key_head = out.index;
2378 if (sub != this.keymap)
2381 restore_state.call (this);
2383 Xex.Log ('submap found');
2384 if (this.keymap.map_actions)
2386 Xex.Log ('taking map actions:');
2387 if (! this.take_actions (this.keymap.map_actions))
2390 else if (this.keymap.submaps)
2392 Xex.Log ('no map actions');
2393 for (var i = this.state_key_head; i < this.key_head; i++)
2395 Xex.Log ('inserting key:' + this.keys.val[i].key);
2396 this.insert (this.keys.val[i].key, null);
2399 if (! this.keymap.submaps)
2401 Xex.Log ('terminal:');
2402 if (this.keymap.branch_actions != null)
2404 Xex.Log ('branch actions:');
2405 if (! this.take_actions (this.keymap.branch_actions))
2408 if (this.keymap != this.state.keymap)
2409 this.shift (this.state);
2414 Xex.Log ('no submap');
2415 var current_state = this.state;
2416 var map = this.keymap;
2418 if (map.branch_actions)
2420 Xex.Log ('branch actions');
2421 if (! this.take_actions (map.branch_actions))
2425 if (map == this.keymap)
2427 Xex.Log ('no state change');
2428 if (map == this.initial_state.keymap
2429 && this.key_head < this.keys.val.length)
2431 Xex.Log ('unhandled');
2434 if (this.keymap != current_state.keymap)
2435 this.shift (current_state);
2436 else if (this.keymap.actions == null)
2437 this.shift (this.initial_state);
2446 this.produced = null;
2448 this.preedit_saved = '';
2449 this.cursor_pos = 0;
2450 this.marker_positions = {};
2451 this.candidates = null;
2452 this.candidate_show = false;
2454 this.prev_state = null;
2455 this.initial_state = this.im.initial_state;
2456 this.title = this.initial_state.title;
2457 this.state_preedit = '';
2458 this.state_key_head = 0;
2459 this.state_var_values = {};
2462 this.keys = new MIM.KeySeq ();
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.marker_positions = {};
2473 this.candidate_table = new MIM.CandidateTable ();
2474 this.candidates = null;
2475 this.candidate_show = false;
2476 this.shift (this.initial_state);
2479 catch_args: new Array (Xex.CatchTag._mimtag, null),
2481 take_actions: function (actions)
2483 var func_progn = this.domain.GetFunc ('progn');
2484 var func_catch = this.domain.GetFunc ('catch');
2485 this.catch_args[1] = new Xex.Funcall (func_progn, null, actions);
2486 var term = new Xex.Funcall (func_catch, null, this.catch_args);
2487 term = term.Eval (this.domain);
2488 return (! term.IsSymbol || term.val != '@mimtag');
2491 GetSurroundingChar: function (pos)
2494 if (pos < 0 || pos >= this.target.value.length)
2496 return this.target.value.charCodeAt (pos);
2499 adjust_markers: function (from, to, inserted)
2501 var diff = inserted - (to - from);
2503 for (var m in this.marker_positions)
2504 if (this.marker_positions[m] > from)
2505 this.marker_positions[m] = (this.marker_positions[m] >= to
2506 ? pos + diff : from);
2507 if (this.cursor_pos >= to)
2508 set_cursor.call (this, 'adjust', this.cursor_pos + diff);
2509 else if (this.cursor_pos > from)
2510 set_cursor.call (this, 'adjust', from)
2513 preedit_replace: function (from, to, text, candidates)
2515 this.preedit = (this.preedit.substring (0, from)
2516 + text + this.preedit.substring (to));
2517 this.adjust_markers (from, to, text.length);
2518 this.candidate_table.adjust (from, to, text.length);
2520 this.candidate_table.put (from, from + text.length, candidates)
2523 insert: function (text, candidates)
2525 this.preedit_replace (this.cursor_pos, this.cursor_pos, text, candidates);
2526 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2531 var deleted = pos - this.cursor_pos;
2534 this.DelSurroundText (pos);
2537 else if (pos > this.preedit.length)
2539 this.DelSurroundText (pos - this.preedit.length);
2540 pos = this.preedit.length;
2542 if (pos < this.cursor_pos)
2543 this.preedit = (this.preedit.substring (0, pos)
2544 + this.preedit.substring (this.cursor_pos));
2546 this.preedit = (this.preedit.substring (0, this.cursor_pos)
2547 + this.predit.substring (pos));
2553 this.candidate_show = true;
2554 this.changed |= MIM.ChangedStatus.CandidateShow;
2559 this.candidate_show = false;
2560 this.changed |= MIM.ChangedStatus.CandidateShow;
2563 move: function (pos)
2567 else if (pos > this.preedit.length)
2568 pos = this.preedit.length;
2569 if (pos != this.cursor_pos)
2571 set_cursor.call (this, 'move', pos);
2572 this.changed |= MIM.ChangedStatus.Preedit;
2576 pushback: function (n)
2578 if (n instanceof MIM.KeySeq)
2580 if (this.key_head > 0)
2582 if (this.key_head < this.keys.val.length)
2583 this.keys.val.splice (this.key_head,
2584 this.keys.val.length - this.key_head);
2585 for (var i = 0; i < n.val.length; i++)
2586 this.keys.val.push (n.val[i]);
2592 if (this.key_head < 0)
2599 this.key_head = - n;
2600 if (this.key_head > this.keys.val.length)
2601 this.key_head = this.keys.val.length;
2607 if (this.key_head < this.keys.val.length)
2608 this.keys.val.splice (this.key_head, 1);
2613 if (this.preedit.length > 0)
2615 this.candidate_table.clear ();
2616 this.produced += this.preedit;
2617 this.preedit_replace.call (this, 0, this.preedit.length, '', null);
2621 shift: function (state)
2625 if (this.prev_state == null)
2627 state = this.prev_state;
2630 if (state == this.initial_state)
2635 this.keys.val.splice (0, this.key_head);
2637 this.prev_state = null;
2642 if (state != this.state)
2643 this.prev_state = this.state;
2645 if (state != this.state && state.enter_actions)
2646 this.take_actions (state.enter_actions);
2647 if (! this.state || this.state.title != state.title)
2648 this.changed |= MIM.ChangedStatus.StateTitle;
2650 this.keymap = state.keymap;
2651 this.state_key_head = this.key_head;
2652 save_state.call (this);
2655 Filter: function (key)
2659 this.key_unhandled = true;
2660 this.unhandled_key = key;
2663 if (key.key == '_reload')
2665 this.changed = MIM.ChangedStatus.None;
2667 this.key_unhandled = false;
2668 this.keys.val.push (key);
2670 while (this.key_head < this.keys.val.length)
2672 if (! handle_key.call (this))
2674 if (this.key_head < this.keys.val.length)
2676 this.unhandled_key = this.keys.val[this.key_head];
2677 this.keys.val.splice (this.key_head, this.key_head + 1);
2679 this.key_unhandled = true;
2685 this.key_unhandled = true;
2689 if (this.key_unhandled)
2691 this.keys.val.length = 0;
2692 this.key_head = this.state_key_head = this.commit_key_head = 0;
2694 return (! this.key_unhandled
2695 && this.produced.length == 0
2696 && this.preedit.length == 0);
2700 MIM.IC.prototype = proto;
2702 var node = Xex.Load (null, "imlist.xml");
2703 for (node = node.firstChild; node; node = node.nextSibling)
2704 if (node.nodeName == 'input-method')
2706 var lang = null, name = null, extra_id = null, file = null;
2708 for (var n = node.firstChild; n; n = n.nextSibling)
2710 if (n.nodeName == 'language')
2711 lang = n.firstChild.nodeValue;
2712 else if (n.nodeName == 'name')
2713 name = n.firstChild.nodeValue;
2714 else if (n.nodeName == 'extra-id')
2715 extra_id = n.firstChild.nodeValue;
2716 else if (n.nodeName == 'filename')
2717 file = n.firstChild.nodeValue;
2719 if (name && name != 'nil')
2721 if (! MIM.imlist[lang])
2722 MIM.imlist[lang] = {};
2723 MIM.imlist[lang][name] = new MIM.IM (lang, name, extra_id, file);
2725 else if (extra_id && extra_id != 'nil')
2727 if (! MIM.imextra[lang])
2728 MIM.imextra[lang] = {};
2729 MIM.imextra[lang][extra_id] = new MIM.IM (lang, name, extra_id, file);
2732 if (MIM.imextra.t && MIM.imextra.t.global)
2733 MIM.im_global = MIM.imextra.t.global;
2736 MIM.im_global = new MIM.IM ('t', 'nil', 'global', null);
2737 MIM.im_global.load_status = MIM.LoadStatus.Error;
2743 var keys = new Array ();
2745 keys[0x08] = 'backspace';
2746 keys[0x0D] = 'return';
2747 keys[0x1B] = 'escape';
2748 keys[0x20] = 'space';
2749 keys[0x21] = 'pageup';
2750 keys[0x22] = 'pagedown';
2752 keys[0x24] = 'home';
2753 keys[0x25] = 'left';
2755 keys[0x27] = 'right';
2756 keys[0x28] = 'down';
2757 keys[0x2D] = 'insert';
2758 keys[0x2E] = 'delete';
2759 for (var i = 1; i <= 12; i++)
2760 keys[111 + i] = "f" + i;
2761 keys[0x90] = "numlock";
2762 keys[0xF0] = "capslock";
2764 MIM.decode_key_event = function (event)
2766 var key = ((event.type == 'keydown' || event.keyCode) ? event.keyCode
2767 : event.charCode ? event.charCode
2771 if (event.type == 'keydown')
2776 if (event.shiftKey) key = "S-" + key ;
2779 key = String.fromCharCode (key);
2780 if (event.altKey) key = "A-" + key ;
2781 if (event.ctrlKey) key = "C-" + key ;
2782 return new MIM.Key (key);
2786 MIM.add_event_listener
2787 = (window.addEventListener
2788 ? function (target, type, listener) {
2789 target.addEventListener (type, listener, false);
2791 : window.attachEvent
2792 ? function (target, type, listener) {
2793 target.attachEvent ('on' + type,
2795 listener.call (target, window.event);
2798 : function (target, type, listener) {
2800 = function (e) { listener.call (target, e || window.event); };
2803 MIM.debug_print = function (event, ic)
2807 if (! MIM.debug_nodes)
2809 MIM.debug_nodes = new Array ();
2810 MIM.debug_nodes['keydown'] = document.getElementById ('keydown');
2811 MIM.debug_nodes['keypress'] = document.getElementById ('keypress');
2812 MIM.debug_nodes['status0'] = document.getElementById ('status0');
2813 MIM.debug_nodes['status1'] = document.getElementById ('status1');
2814 MIM.debug_nodes['keymap0'] = document.getElementById ('keymap0');
2815 MIM.debug_nodes['keymap1'] = document.getElementById ('keymap1');
2816 MIM.debug_nodes['preedit0'] = document.getElementById ('preedit0');
2817 MIM.debug_nodes['preedit1'] = document.getElementById ('preedit1');
2819 var target = event.target;
2820 var code = event.keyCode;
2821 var ch = event.type == 'keydown' ? 0 : event.charCode;
2822 var key = MIM.decode_key_event (event);
2825 MIM.debug_nodes[event.type].innerHTML = "" + code + "/" + ch + " : " + key;
2826 index = (event.type == 'keydown' ? '0' : '1');
2828 MIM.debug_nodes['status' + index].innerHTML = ic.im.load_status;
2830 MIM.debug_nodes['status' + index].innerHTML = 'no IM';
2831 MIM.debug_nodes['keymap' + index].innerHTML = ic.state.name;
2832 MIM.debug_nodes['preedit' + index].innerHTML = ic.preedit;
2835 MIM.get_range = function (target, range)
2837 if (target.selectionStart != null) // for Mozilla
2839 range[0] = target.selectionStart;
2840 range[1] = target.selectionEnd;
2844 var r = document.selection.createRange ();
2845 var rr = r.duplicate ();
2847 rr.moveToElementText (target);
2848 rr.setEndPoint ('EndToEnd', range);
2849 range[0] = rr.text.length - r.text.length;
2850 range[1] = rr.text.length;
2854 MIM.set_caret = function (target, ic)
2856 if (target.setSelectionRange) // Mozilla
2858 var scrollTop = target.scrollTop;
2859 target.setSelectionRange (ic.spot, ic.spot + ic.preedit.length);
2860 target.scrollTop = scrollTop;
2864 var range = target.createTextRange ();
2865 range.moveStart ('character', ic.spot);
2866 range.moveEnd ('character', ic.spot + ic.preedit.length);
2872 var range = new Array ();
2874 MIM.check_range = function (target, ic)
2876 MIM.get_range (target, range);
2877 if (range[0] != ic.spot || range[1] - range[0] != ic.preedit.length
2878 || target.value.substring (range[0], range[1]) != ic.preedit)
2880 Xex.Log ('reset:' + ic.spot + '-' + (ic.spot + ic.preedit.length)
2881 + '/' + range[0] + '-' + range[1]);
2884 target.value = (target.value.substring (0, range[0])
2885 + target.value.substring (range[1]));
2890 MIM.update = function (target, ic)
2892 var text = target.value;
2893 target.value = (text.substring (0, ic.spot)
2896 + text.substring (ic.spot));
2897 ic.spot += ic.produced.length;
2898 MIM.set_caret (target, ic);
2901 MIM.reset_ic = function (event)
2903 if (event.target.mim_ic)
2905 var ic = event.target.mim_ic;
2906 var pos = ic.spot + ic.preedit.length;
2909 event.target.setSelectionRange (pos, pos);
2913 MIM.keydown = function (event)
2915 var target = event.target;
2916 if (target.id == 'log')
2918 if (! (target.type == "text" || target.type == "textarea"))
2921 var ic = target.mim_ic;
2922 if (! ic || ic.im != MIM.current)
2924 Xex.Log ('creating IC');
2925 ic = new MIM.IC (MIM.current, target);
2927 MIM.add_event_listener (target, 'blur', MIM.reset_ic);
2929 if (ic.im.load_status != MIM.LoadStatus.Loaded)
2931 MIM.check_range (target, ic);
2932 MIM.debug_print (event, ic);
2933 ic.key = MIM.decode_key_event (event);
2936 MIM.keypress = function (event)
2938 var target = event.target;
2939 if (target.id == 'log')
2941 if (! (target.type == "text" || target.type == "textarea"))
2944 var ic = target.mim_ic;
2948 if (ic.im.load_status != MIM.LoadStatus.Loaded)
2951 ic.key = MIM.decode_key_event (event);
2958 Xex.Log ("filtering " + ic.key);
2959 var result = ic.Filter (ic.key);
2960 MIM.update (target, ic);
2961 if (! ic.key_unhandled)
2962 event.preventDefault ();
2964 MIM.debug_print (event, ic);
2969 MIM.select_im = function (event)
2971 var target = event.target.parentNode;
2972 while (target.tagName != "SELECT")
2973 target = target.parentNode;
2976 for (var lang in MIM.imlist)
2977 for (var name in MIM.imlist[lang])
2978 if (idx++ == target.selectedIndex)
2980 im = MIM.imlist[lang][name];
2983 document.getElementsByTagName ('body')[0].removeChild (target);
2984 target.target.focus ();
2985 if (im && im != MIM.current)
2988 Xex.Log ('select IM: ' + im.name);
2992 MIM.destroy_menu = function (event)
2994 if (event.target.tagName == "SELECT")
2995 document.getElementsByTagName ('body')[0].removeChild (event.target);
2998 MIM.select_menu = function (event)
3000 var target = event.target;
3002 if (! ((target.type == "text" || target.type == "textarea")
3003 && event.which == 1 && event.ctrlKey))
3006 var sel = document.createElement ('select');
3007 sel.onclick = MIM.select_im;
3008 sel.onmouseout = MIM.destroy_menu;
3009 sel.style.position='absolute';
3010 sel.style.left = (event.clientX - 10) + "px";
3011 sel.style.top = (event.clientY - 10) + "px";
3012 sel.target = target;
3014 for (var lang in MIM.imlist)
3015 for (var name in MIM.imlist[lang])
3017 var option = document.createElement ('option');
3018 var imname = lang + "-" + name;
3019 option.appendChild (document.createTextNode (imname));
3020 option.value = imname;
3021 sel.appendChild (option);
3022 if (MIM.imlist[lang][name] == MIM.current)
3023 sel.selectedIndex = idx;
3027 document.getElementsByTagName ('body')[0].appendChild (sel);
3030 MIM.test = function ()
3032 var im = MIM.imlist['t']['latn-post'];
3033 var ic = new MIM.IC (im, null);
3035 ic.Filter (new MIM.Key ('a'));
3036 ic.Filter (new MIM.Key ("'"));
3039 document.getElementById ('text').value = ic.produced + ic.preedit;
3042 document.getElementById ('text').value
3043 = Xex.Term.Parse (domain, body).Eval (domain).toString ();
3045 if (e instanceof Xex.ErrTerm)
3053 MIM.init = function ()
3055 MIM.add_event_listener (window, 'keydown', MIM.keydown);
3056 MIM.add_event_listener (window, 'keypress', MIM.keypress);
3057 MIM.add_event_listener (window, 'mousedown', MIM.select_menu);
3058 if (window.location == 'http://localhost/mim/index.html')
3059 MIM.server = 'http://localhost/mim';
3060 MIM.current = MIM.imlist['vi']['telex'];
3063 MIM.init_debug = function ()
3066 Xex.LogNode = document.getElementById ('log');