1 // -* coding: utf-8; -*
5 Xex.Alist = function ()
10 Xex.Alist.prototype.put = function (key, val)
13 return (this[key] = val);
15 Xex.Alist.prototype.clone = function ()
17 var alist = new Xex.Alist ();
19 alist[key] = this[key];
22 Xex.Alist.prototype.toString = function ()
26 str += '"' + key + '"';
30 // Xex.alist = new Xex.Alist ();
31 // Xex.alist.put ('abc', "ABC");
32 // alert (Xex.alist['abc']);
35 UnknownError: "unknown-error",
36 WrongArgument: "wrong-argument",
38 InvalidInteger: "invalid-integer",
39 TermTypeInvalid: "term-type-invalid",
40 FunctionConflict: "function-conflict",
41 VariableTypeConflict: "variable-type-conflict",
42 VariableRangeConflict: "variable-range-conflict",
43 VariableWrongRange: "variable-wrong-range",
44 VariableWrongValue: "variable-wrong-value",
46 UnknownFunction: "unknown-function",
47 MacroExpansionError: "macro-expansion-error",
48 NoVariableName: "no-variable-anme",
51 ArithmeticError: "arithmetic-error",
52 WrongType: "wrong-type",
53 IndexOutOfRange: "index-out-of-range",
54 ValueOutOfRange: "value-out-of-range",
55 NoLoopToBreak: "no-loop-to-break",
56 UncaughtThrow: "uncaught-throw"
59 Xex.Variable = function (domain, name, val)
66 Xex.Variable.prototype.clone = function () {
67 return new Xex.Variable (this.domain, this.name, this.value);
70 Xex.Variable.prototype.Equals = function (obj) {
71 return ((obj instanceof Xex.Variable)
72 && obj.name == this.name);
75 Xex.Variable.prototype.SetValue = function (term) {
80 Xex.Function = function (name, with_var, min_args, max_args) {
82 this.with_var = with_var;
83 this.min_args = min_args;
84 this.max_args = max_args;
87 Xex.Subrountine = function (builtin, name, with_var, min_args, max_args) {
89 this.with_var = with_var;
90 this.min_args = min_args;
91 this.max_args = max_args;
92 this.builtin = builtin;
95 Xex.Subrountine.prototype.Call = function (domain, vari, args)
97 newargs = new Array ();
98 for (var i = 0; i < args.length; i++)
100 newargs[i] = args[i].Eval (domain);
101 if (domain.Thrown ())
104 return this.builtin (domain, vari, newargs)
107 Xex.SpecialForm = function (builtin, name, with_var, min_args, max_args)
110 this.with_var = with_var;
111 this.min_args = min_args;
112 this.max_args = max_args;
113 this.builtin = builtin;
116 Xex.SpecialForm.prototype.Call = function (domain, vari, args)
118 return this.builtin (domain, vari, args)
121 Xex.Lambda = function (name, min_args, max_args, args, body)
124 this.with_var = with_var;
125 this.min_args = min_args;
126 this.max_args = max_args;
131 Xex.Lambda.prototype.Call = function (domain, vari, args)
133 var current = domain.bindings;
134 var result = Xex.Zero;
135 var limit = max_args >= 0 ? args.length : args.length - 1;
139 for (i = 0; i < limit; i++)
141 result = args[i].Eval (domain);
142 if (domain.Thrown ())
144 domain.Bind (this.args[i], result);
148 var list = new Array ();
149 for (i = 0; i < args[limit].length; i++)
151 result = args[limit].Eval (domain);
152 if (domain.Thrown ())
156 domain.Bind (this.args[limit], list);
159 domain.Catch (Xex.CatchTag.Return);
160 for (var term in this.body)
162 result = term.Eval (domain);
163 if (domain.Thrown ())
170 domain.UnboundTo (current);
175 Xex.Macro = function (name, min_args, max_args, args, body)
178 this.with_var = with_var;
179 this.min_args = min_args;
180 this.max_args = max_args;
185 Xex.Macro.prototype.Call = function (domain, vari, args)
187 var current = domain.bindings;
188 var result = Xex.Zero;
192 for (i = 0; i < args.length; i++)
193 domain.Bind (this.args[i], args[i]);
195 domain.Catch (Xex.CatchTag.Return);
196 for (var term in body)
198 result = term.Eval (domain);
199 if (domain.Thrown ())
206 domain.UnboundTo (current);
211 Xex.Bindings = function (vari)
214 this.old_value = vari.val;
217 Xex.Bindings.prototype.UnboundTo = function (boundary)
219 for (var b = this; b != boundary; b = b.next)
220 b.vari.val = b.old_value;
224 Xex.Bind = function (bindings, vari, val)
226 var b = new Xex.Bindings (vari);
237 Xex.Domain = function (name, parent, context)
240 this.context = context;
243 if (name != 'basic' && ! parent)
244 parent = Xex.BasicDomain
245 this.parent = parent;
252 for (elt in parent.termtypes)
253 this.termtypes[elt] = parent.termtypes[elt];
254 for (elt in parent.functions)
255 this.functions[elt] = parent.functions[elt];
256 for (elt in parent.variables)
257 this.variables[elt] = parent.variables[elt];
260 this.call_stack = new Array ();
261 this.bindings = null;
262 this.catch_stack = new Array ();
263 this.catch_count = 0;
267 Xex.Domain.prototype = {
268 CallStackCount: function () { return this.call_stack.length; },
269 CallStackPush: function (term) { this.call_stack.push (term); },
270 CallStackPop: function () { this.call_stack.pop (); },
271 Bind: function (vari, val)
273 this.bindings = Xex.Bind (this.bindings, vari, val);
275 UnboundTo: function (boundary)
278 this.bindings = this.bindings.UnboundTo (boundary);
280 Catch: function (tag) { this.catch_stack.push (tag); this.catch_count++; },
283 this.catch_stack.pop ();
284 if (this.catch_count > this.catch_stack.length)
289 if (this.catch_count < this.catch_stack.length)
291 this.caught = (this.catch_count == this.catch_stack.length - 1);
297 ThrowReturn: function ()
299 for (var i = this.catch_stack.length - 1; i >= 0; i--)
302 if (this.catch_stack[i] == Xex.CatchTag.Return)
306 ThrowBreak: function ()
308 if (this.catch_stack[this.catch_stack.length - 1] != Xex.CatchTag.Break)
309 throw new Xex.ErrTerm (Xex.Error.NoLoopToBreak,
310 "No surrounding loop to break");
313 ThrowSymbol: function (tag)
315 var i = this.catch_count;
316 for (var j = this.catch_stack.length - 1; j >= 0; j--)
319 if (Xex.CatchTag.Matches (this.catch_stack[i], tag))
321 this.catch_count = i;
325 throw new Xex.ErrTerm (Xex.Error.UncaughtThrow,
326 "No corresponding catch: " + tag);
328 DefType: function (obj)
331 if (this.termtypes[type])
332 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
333 "Already defined: " + type);
334 if (this.functions[type])
335 throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
336 "Already defined as a funciton or a macro: "
338 this.termtypes[type] = obj.Parser;
340 DefSubr: function (builtin, name, with_var, min_args, max_args)
342 this.functions[name] = new Xex.Subrountine (builtin, name, with_var,
345 DefSpecial: function (builtin, name, with_var, min_args, max_args)
347 this.functions[name] = new Xex.SpecialForm (builtin, name, with_var,
350 Defun: function (name, min_args, max_args, args, body)
352 this.functions[name] = new Xex.Lambda (name, min_args, max_args,
355 DefunByFunc: function (func) { this.functions[func.Name] = func; },
356 Defmacro: function (name, min_args, max_args, args, body)
358 this.functions[name] = new Xex.Macro (name, min_args, max_args,
361 DefAlias: function (alias, fname)
363 var func = this.functions[fname];
365 if (this.termtypes[alias])
366 throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
367 "Already defined as a term type: " + alias);
368 if (this.functions[alias])
369 throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
370 "Already defined as a function: " + alias);
372 throw new Xex.ErrTerm (Xex.Error.UnknownFunction, fname);
373 this.functions[alias] = func;
375 Defvar: function (name)
377 var vari = this.variables[name];
381 throw new Xex.ErrTerm (Xex.Error.VariableTypeConflict,
382 "Not a non-typed variable: " + name);
386 vari = new Xex.Variable (this, name, Xex.Zero);
387 this.variables[name] = vari;
391 GetFunc: function (name)
393 var func = this.functions[name];
395 throw new Xex.ErrTerm (Xex.Error.UnknownFunction,
396 "Unknown function: " + this + ':' + name);
399 CopyFunc: function (domain, name)
401 var func = this.functions[name];
402 domain.DefunByFunc (func);
405 CopyFuncAll: function (domain)
407 for (var elt in this.functions)
408 domain.DefunByFunc (this.functions[elt]);
410 GetVarCreate: function (name)
412 var vari = this.variables[name];
414 vari = this.variables[name] = new Xex.Variable (this, name, Xex.Zero);
417 GetVar: function (name) { return this.variables[name]; },
418 SaveValues: function ()
421 for (var elt in this.variables)
422 values[elt] = this.variables[elt].val.Clone ();
425 RestoreValues: function (values)
430 var vari = this.variables[name];
431 vari.val = values[name];
436 Xex.Term = function (type) { this.type = type; }
437 Xex.Term.prototype = {
438 IsTrue: function () { return true; },
439 Eval: function (domain) { return this.Clone (); },
440 Clone: function (domain) { return this; },
441 Equals: function (obj)
443 return (this.type == obj.type
445 && obj.val == this.val);
447 Matches: function (obj) { return this.Equals (obj); },
448 toString: function ()
450 if (this.val != undefined)
451 return '<' + this.type + '>' + this.val + '</' + this.type + '>';
452 return '<' + this.type + '/>';
456 Xex.ParseTerm = function (domain, node)
458 var name = node.nodeName;
459 var parser = domain.termtypes[name];
462 return parser (domain, node);
463 if (name == 'defun' || name == 'defmacro')
465 name = parse_defun_head (domain, node);
466 parse_defun_body (domain, node);
467 return new Xex.StrTerm (name);
469 if (name == 'defvar')
471 name = parse_defvar (doamin, node);
472 return new Xex.StrTerm (nanme);
475 return new Xex.Funcall.prototype.Parser (domain, node);
478 Xex.ParseTermList = function (domain, node)
480 for (var n = node; n; n = n.nextSibling)
483 if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
484 Xex.parse_defun_head (domain, n);
486 var terms = new Array ();
487 for (var n = node; n; n = n.nextSibling)
490 if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
491 Xex.parse_defun_body (domain, n);
492 else if (n.nodeName == 'defvar')
493 Xex.parse_defvar (domain, n);
495 terms.push (Xex.ParseTerm (domain, n));
500 Xex.Varref = function (vname)
506 var proto = new Xex.Term ('varref');
508 proto.Clone = function () { return new Xex.Varref (this.val); }
509 proto.Eval = function (domain)
511 if (! this.vari || this.vari.domain != domain)
512 this.vari = domain.GetVarCreate (this.val);
513 return this.vari.val;
516 proto.Parser = function (domain, node)
518 return new Xex.Varref (node.attributes['vname'].nodeValue);
521 Xex.Varref.prototype = proto;
524 var null_args = new Array ();
526 Xex.Funcall = function (func, vari, args)
530 this.args = args || null_args;
534 var proto = new Xex.Term ('funcall');
536 proto.Parser = function (domain, node)
538 var fname = node.nodeName;
541 if (fname == 'funcall')
542 fname = node.attributes['fname']
543 var func = domain.GetFunc (fname);
545 attr = node.attributes['vname'];
546 vari = attr != undefined ? domain.GetVarCreate (attr.nodeValue) : false;
547 var args = Xex.ParseTermList (domain, node.firstChild);
548 return new Xex.Funcall (func, vari, args);
551 proto.New = function (domain, fname, vname, args)
553 var func = domain.GetFunc (fname);
554 var vari = vname ? domain.GetVarCreate (vname) : null;
555 var funcall = new Xex.Funcall (func, vari, args);
556 if (func instanceof Xex.Macro)
557 funcall = funcall.Eval (domain);
561 proto.Eval = function (domain)
563 return this.func.Call (domain, this.vari, this.args);
566 proto.Clone = function ()
568 return new Xex.Funcall (this.func, this.vari, this.args);
571 proto.Equals = function (obj)
573 return (obj.type == 'funcall'
574 && obj.func == this.func
575 && obj.vari.Equals (this.vari)
576 && obj.args.length == this.func.length);
579 proto.toString = function ()
582 var len = this.args.length;
584 return '<' + this.func.name + '/>';
585 for (var i = 0; i < len; i++)
586 arglist += this.args[i].toString ();
587 return '<' + this.func.name + '>' + arglist + '</' + this.func.name + '>';
590 Xex.Funcall.prototype = proto;
593 Xex.ErrTerm = function (ename, message, stack)
596 this.message = message;
601 var proto = new Xex.Term ('error');
603 proto.IsError = true;
605 proto.Parser = function (domain, node)
607 return new Xex.ErrTerm (node.attributes['ename'].nodeValue,
608 node.innerText, false);
611 proto.CallStack = function () { return stack; }
613 proto.SetCallStack = function (value) { statck = value; }
615 proto.Clone = function ()
617 return new Xex.ErrTerm (ename, message, false);
620 proto.Equals = function (obj)
623 && obj.ename == ename && obj.message == message
624 && (obj.stack ? (stack && stack.length == obj.stack.length)
628 proto.Matches = function (obj)
630 return (obj.IsError && obj.ename == ename);
633 proto.toString = function ()
635 return '<error ename="' + this.ename + '">' + this.message + '</error>';
638 Xex.ErrTerm.prototype = proto;
641 Xex.IntTerm = function (num) { this.val = num; };
643 var proto = new Xex.Term ('integer');
645 proto.IsTrue = function () { return this.val != 0; }
646 proto.Clone = function () { return new Xex.IntTerm (this.val); }
647 proto.Parser = function (domain, node)
649 var str = node.firstChild.nodeValue;
651 if (str.charAt (0) == '?' && str.length == 2)
652 return new Xex.IntTerm (str.charCodeAt (1));
653 return new Xex.IntTerm (parseInt (node.firstChild.nodeValue));
655 Xex.IntTerm.prototype = proto;
658 Xex.StrTerm = function (str) { this.val = str; };
660 var proto = new Xex.Term ('string');
662 proto.IsTrue = function () { return this.val.length > 0; }
663 proto.Clone = function () { return new Xex.StrTerm (this.val); }
664 proto.Parser = function (domain, node)
666 return new Xex.StrTerm (node.firstChild.nodeValue);
668 Xex.StrTerm.prototype = proto;
671 Xex.SymTerm = function (str) { this.val = str; };
673 var proto = new Xex.Term ('symbol');
674 proto.IsSymbol = true;
675 proto.IsTrue = function () { return this.val != 'nil'; }
676 proto.Clone = function () { return new Xex.SymTerm (this.val); }
677 proto.Parser = function (domain, node)
679 return new Xex.SymTerm (node.firstChild.nodeValue);
681 Xex.SymTerm.prototype = proto;
684 Xex.LstTerm = function (list) { this.val = list; };
686 var proto = new Xex.Term ('list');
688 proto.IsTrue = function () { return this.val.length > 0; }
689 proto.Clone = function () { return new Xex.LstTerm (this.val.slice (0)); }
691 proto.Equals = function (obj)
693 if (obj.type != 'list' || obj.val.length != this.val.length)
695 var i, len = this.val.length;
696 for (i = 0; i < len; i++)
697 if (! this.val[i].Equals (obj.val[i]))
702 proto.Parser = function (domain, node)
704 var list = Xex.ParseTermList (domain, node.firstChild);
705 return new Xex.LstTerm (list);
708 proto.toString = function ()
710 var len = this.val.length;
715 for (var i = 0; i < len; i++)
716 str += this.val[i].toString ();
717 return str + '</list>';
719 Xex.LstTerm.prototype = proto;
723 var basic = new Xex.Domain ('basic', null, null);
725 function Fset (domain, vari, args)
727 return vari.SetValue (args[0]);
730 function maybe_set_intvar (vari, n)
732 var term = new Xex.IntTerm (n);
734 vari.SetValue (term);
738 function Fadd (domain, vari, args)
740 var n = vari ? vari.val.val : 0;
741 var len = args.length;
743 for (var i = 0; i < len; i++)
745 return maybe_set_intvar (vari, n);
748 function Fand (domain, vari, args)
750 var len = args.length;
751 for (var i = 0; i < len; i++)
753 var result = args[i].Eval (domain);
754 if (domain.Thrown ())
762 function For (domain, vari, args)
764 var len = args.length;
765 for (var i = 0; i < len; i++)
767 var result = args[i].Eval (domain);
768 if (domain.Thrown ())
776 function Fprogn (domain, vari, args)
778 var result = Xex.One;
779 var len = args.length;
781 for (var i = 0; i < len; i++)
783 result = args[i].Eval (domain);
784 if (domain.Thrown ())
790 function Fif (domain, vari, args)
792 var result = args[0].Eval (domain);
794 if (domain.Thrown ())
797 return args[1].Eval (domain);
798 if (args.Length == 2)
800 return args[2].Eval (domain);
803 function eval_terms (domain, terms, idx)
805 var result = Xex.Zero;
806 domain.caught = false;
807 for (var i = idx; i < terms.length; i++)
809 result = terms[i].Eval (domain);
810 if (domain.Thrown ())
816 function Fcatch (domain, vari, args)
824 result = eval_terms (domain, args, 1);
826 if (e instanceof Xex.ErrTerm)
828 if (! args[0].Matches (e))
836 else if (args[0].IsSymbol)
839 domain.Catch (args[0].val);
840 result = eval_terms (domain, args, 1);
844 vari.SetValue (result);
852 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
853 "Not a symbol nor an error: " + args[0]);
856 function Fthrow (domain, vari, args)
860 domain.ThrowSymbol (args[0]);
861 return (args[args.length - 1]);
867 throw new Xex.ErrTerm (Xex.Error.WrongArgument,
868 "Not a symbol nor an error:" + args[0]);
871 Xex.BasicDomain = basic;
873 basic.DefSubr (Fset, "set", true, 1, 1);
874 basic.DefSubr (Fadd, "add", true, 1, -1);
875 basic.DefSubr (Fthrow, "throw", false, 1, 2);
877 basic.DefSpecial (Fand, "and", false, 1, -1);
878 basic.DefSpecial (For, "or", false, 1, -1);
879 basic.DefAlias ("=", "set");
880 basic.DefSpecial (Fprogn, "progn", false, 1, -1);
881 basic.DefSpecial (Fif, "if", false, 2, 3);
882 basic.DefSpecial (Fcatch, "catch", true, 2, -1);
884 basic.DefType (Xex.Funcall.prototype);
885 basic.DefType (Xex.Varref.prototype);
886 basic.DefType (Xex.ErrTerm.prototype);
887 basic.DefType (Xex.IntTerm.prototype);
888 basic.DefType (Xex.StrTerm.prototype);
889 basic.DefType (Xex.SymTerm.prototype);
890 basic.DefType (Xex.LstTerm.prototype);
894 Xex.Zero = new Xex.IntTerm (0);
895 Xex.One = new Xex.IntTerm (1);
897 Xex.Load = function (server, file)
899 var obj = new XMLHttpRequest ();
900 var url = server ? server + '/' + file : file;
901 obj.open ('GET', url, false);
902 obj.overrideMimeType ('text/xml');
904 return obj.responseXML.firstChild;
908 // URL of the input method server.
909 server: "http://www.m17n.org/common/mim-js",
910 // Boolean flag to tell if MIM is active or not.
912 // Boolean flag to tell if MIM is running in debug mode or not.
914 // List of registered input methods.
916 // Global input method data
918 // Currently selected input method.
922 LoadStatus: { NotLoaded:0, Loading:1, Loaded:2, Error:-1 },
931 Preedit: 0x06, // PreeditText | CursorPos
932 Candidate: 0x38 // CandidateList | CandidateIndex | CandidateShow
954 ParseError: "parse-error"
959 var keysyms = new Array ();
960 keysyms["bs"] = "backspace";
961 keysyms["lf"] = "linefeed";
962 keysyms["cr"] = keysyms["enter"] = "return";
963 keysyms["esc"] = "escape";
964 keysyms["spc"] = "space";
965 keysyms["del"] = "delete";
967 function decode_keysym (str) {
968 var parts = str.split ("-");
969 var len = parts.length, i;
970 var has_modifier = len > 1;
972 for (i = 0; i < len - 1; i++)
973 if (! MIM.KeyModifier.hasOwnProperty (parts[i]))
975 var key = parts[len - 1];
978 key = keysyms[key.toLowerCase ()];
984 for (i = 1; i < len - 1; i++)
985 str += '-' + parts[i];
994 parts = new Array ();
1001 MIM.Key = function (val)
1004 this.has_modifier = false;
1005 if (typeof val == 'string' || val instanceof String)
1007 this.key = decode_keysym (val);
1009 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1010 if (this.key instanceof Array)
1012 this.key = this.key[0];
1013 this.has_modifier = true;
1016 else if (typeof val == 'number' || val instanceof Number)
1017 this.key = String.fromCharCode (val);
1019 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1022 MIM.Key.prototype.toString = function () { return this.key; };
1026 MIM.KeySeq = function (seq)
1028 this.val = new Array ();
1029 this.has_modifier = false;
1035 var len = seq.val.length;
1036 for (var i = 0; i < len; i++)
1039 if (v.type != 'string' && v.type != 'integer'
1040 && v.type != 'symbol')
1041 throw new Xex.ErrTerm (MIM.Error.ParseError,
1042 "Invalid key: " + v);
1043 var key = new MIM.Key (v.val);
1044 this.val.push (key);
1045 if (key.has_modifier)
1046 this.has_modifier = true;
1051 var len = seq.val.length;
1052 for (var i = 0; i < len; i++)
1053 this.val.push (new MIM.Key (seq.val.charCodeAt (i)));
1056 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + seq);
1060 var proto = new Xex.Term ('keyseq');
1061 proto.Clone = function () { return this; }
1062 proto.Parser = function (domain, node)
1064 var seq = new Array ();
1065 for (node = node.firstChild; node; node = node.nextSibling)
1066 if (node.nodeType == 1)
1068 var term = Xex.ParseTerm (domain, node);
1069 return new MIM.KeySeq (term);
1071 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid keyseq");
1073 proto.toString = function ()
1075 var len = this.val.length;
1079 var str = '<keyseq>';
1080 for (var i = 0; i < len; i++)
1084 else if (this.has_modifier)
1086 str += this.val[i].toString ();
1088 return str + '</keyseq>';
1091 MIM.KeySeq.prototype = proto;
1095 MIM.Marker = function () { }
1096 MIM.Marker.prototype = new Xex.Term ('marker');
1097 MIM.Marker.prototype.CharAt = function (ic)
1099 var p = this.Position (ic);
1101 return ic.GetSurroundingChar (p);
1102 else if (pos >= ic.preedit.length)
1103 return ic.GetSurroundingChar (p - ic.preedit.length);
1104 return ic.preedit.charCodeAt (p);
1107 MIM.NamedMarker = function (name) { this.val = name; }
1108 MIM.NamedMarker.prototype = new MIM.Marker ();
1109 MIM.NamedMarker.prototype.Position = function (ic)
1111 var p = ic.marker_positions[this.val];
1112 return (p == undefined ? 0 : p);
1114 MIM.NamedMarker.prototype.Mark = function (ic)
1116 ic.marker_positions[this.val] = ic.cursor_pos;
1119 MIM.PredefinedMarker = function (name) { this.val = name; }
1120 MIM.PredefinedMarker.prototype = new MIM.Marker ();
1121 MIM.PredefinedMarker.prototype.Position = function (ic)
1123 if (typeof this.pos == 'number')
1125 return this.pos (ic);
1128 var predefined = { }
1130 function def_predefined (name, position)
1132 predefined[name] = new MIM.PredefinedMarker (name);
1133 predefined[name].pos = position;
1136 def_predefined ('@<', 0);
1137 def_predefined ('@>', function (ic) { return ic.preedit.length; });
1138 def_predefined ('@-', function (ic) { return ic.cursor_pos - 1; });
1139 def_predefined ('@+', function (ic) { return ic.cursor_pos + 1; });
1140 def_predefined ('@[', function (ic) {
1141 if (ic.cursor_pos > 0)
1143 var pos = ic.cursor_pos;
1144 return ic.preedit.FindProp ('candidates', pos - 1).from;
1148 def_predefined ('@]', function (ic) {
1149 if (ic.cursor_pos < ic.preedit.length - 1)
1151 var pos = ic.cursor_pos;
1152 return ic.preedit.FindProp ('candidates', pos).to;
1154 return ic.preedit.length;
1156 for (var i = 0; i < 10; i++)
1157 def_predefined ("@" + i, i);
1158 predefined['@first'] = predefined['@<'];
1159 predefined['@last'] = predefined['@>'];
1160 predefined['@previous'] = predefined['@-'];
1161 predefined['@next'] = predefined['@+'];
1162 predefined['@previous-candidate-change'] = predefined['@['];
1163 predefined['@next-candidate-change'] = predefined['@]'];
1165 MIM.SurroundMarker = function (name)
1168 this.distance = parseInt (name.slice (2));
1169 if (isNaN (this.distance))
1170 throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid marker: " + name);
1172 MIM.SurroundMarker.prototype = new MIM.Marker ();
1173 MIM.SurroundMarker.prototype.Position = function (ic)
1175 return ic.cursor_pos + this.distance;
1178 MIM.Marker.prototype.Parser = function (domain, node)
1180 var name = node.firstChild.nodeValue;
1181 if (name.charAt (0) == '@')
1183 var n = predefined[name];
1186 if (name.charAt (1) == '-')
1187 return new MIM.SurroundMarker (name);
1188 throw new Xex.ErrTerm (MIM.Error.ParseError,
1189 "Invalid marker: " + name);
1191 return new MIM.NamedMarker (name);
1195 MIM.Selector = function (name)
1199 MIM.Selector.prototype = new Xex.Term ('selector');
1202 selectors["@<"] = selectors["@first"] = new MIM.Selector ('@<');
1203 selectors["@="] = selectors["@current"] = new MIM.Selector ('@=');
1204 selectors["@>"] = selectors["@last"] = new MIM.Selector ('@>');
1205 selectors["@-"] = selectors["@previous"] = new MIM.Selector ('@-');
1206 selectors["@+"] = selectors["@next"] = new MIM.Selector ('@+');
1207 selectors["@["] = selectors["@previous-candidate-change"]
1208 = new MIM.Selector ('@[');
1209 selectors["@]"] = selectors["@next-candidate-change"]
1210 = new MIM.Selector ('@]');
1212 MIM.Selector.prototype.Parser = function (domain, node)
1214 var name = node.firstChild.nodeValue;
1215 var s = selectors[name];
1217 throw new Xex.ErrTerm (MIM.Error.ParseError,
1218 "Invalid selector: " + name);
1223 MIM.Rule = function (keyseq, actions)
1225 this.keyseq = keyseq;
1226 this.actions = actions;
1228 MIM.Rule.prototype = new Xex.Term ('rule');
1229 MIM.Rule.prototype.Parser = function (domain, node)
1232 for (n = node.firstChild; n && n.nodeType != 1; n = n.nextSibling);
1234 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1235 var keyseq = Xex.ParseTerm (domain, n);
1236 if (keyseq.type != 'keyseq')
1237 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1238 var actions = Xex.ParseTermList (domain, n.nextSibling);
1239 return new MIM.Rule (keyseq, actions);
1241 MIM.Rule.prototype.toString = function ()
1246 MIM.Map = function (name)
1249 this.rules = new Array ();
1252 var proto = new Xex.Term ('map');
1254 proto.Parser = function (domain, node)
1256 var name = node.attributes['mname'].nodeValue;
1258 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1259 var map = new MIM.Map (name);
1260 for (var n = node.firstChild; n; n = n.nextSibling)
1261 if (n.nodeType == 1)
1262 map.rules.push (Xex.ParseTerm (domain, n));
1266 proto.toString = function ()
1268 var str = '<map mname="' + this.name + '">';
1269 var len = this.rules.length;
1270 for (i = 0; i < len; i++)
1271 str += this.rules[i];
1272 return str + '</map>';
1275 MIM.Map.prototype = proto;
1278 Xex.CatchTag._mimtag = new Xex.SymTerm ('@mimtag');
1280 MIM.Action = function (domain, terms)
1282 var args = new Array ();
1283 args.push (Xex.CatchTag_.mimtag);
1284 for (var i = 0; i < terms.length; i++)
1285 args.push (terms[i]);
1286 this.action = Xex.Funcall.prototype.New (domain, 'catch', null, args);
1289 MIM.Action.prototype.Run = function (domain)
1291 var result = this.action.Eval (domain);
1292 if (result.type == 'error')
1294 domain.context.Error = result.toString ();
1297 return (result != Xex.CatchTag._mimtag);
1300 MIM.Keymap = function ()
1302 this.submaps = null;
1303 this.actions = null;
1308 function add_rule (keymap, rule)
1310 var keyseq = rule.keyseq;
1311 var len = keyseq.val.length;
1313 for (var i = 0; i < len; i++)
1315 var key = keyseq.val[i];
1318 if (! keymap.submaps)
1319 keymap.submaps = {};
1321 sub = keymap.submaps[key.key];
1323 keymap.submaps[key.key] = sub = new MIM.Keymap ();
1326 keymap.actions = rule.actions;
1329 proto.Add = function (map)
1331 var rules = map.rules;
1332 var len = rules.length;
1334 for (var i = 0; i < len; i++)
1335 add_rule (this, rules[i]);
1337 proto.Lookup = function (keys, index)
1341 if (index < keys.val.length && this.submaps
1342 && (sub = this.submaps[keys.val[index].key]))
1345 return sub.Lookup (keys, index);
1347 return { map: this, index: index };
1350 MIM.Keymap.prototype = proto;
1353 MIM.State = function (name)
1356 this.keymap = new MIM.Keymap ();
1359 var proto = new Xex.Term ('state');
1361 proto.Parser = function (domain, node)
1363 var map_list = domain.map_list;
1364 var name = node.attributes['sname'].nodeValue;
1366 throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1367 var state = new MIM.State (name);
1368 for (node = node.firstChild; node; node = node.nextSibling)
1370 if (node.nodeType != 1)
1372 if (node.nodeName == 'branch')
1374 state.keymap.Add (map_list[node.attributes['mname'].nodeValue]);
1375 state.keymap.actions = Xex.ParseTermList (domain, node.firstChild);
1377 else if (node.nodeName == 'state-hook')
1378 state.enter_actions = Xex.ParseTermList (domain, node.firstChild);
1379 else if (node.nodeName == 'catch-all-branch')
1380 state.fallback_actions = Xex.ParseTermList (domain, node.firstChild);
1381 else if (node.nodeName == 'title')
1382 state.title = node.firstChild.nodeValue;
1387 proto.toString = function ()
1389 return '<state sname="' + this.name + '">' + this.keymap + '</state>';
1392 MIM.State.prototype = proto;
1395 MIM.im_domain = new Xex.Domain ('input-method', null, null);
1396 MIM.im_domain.DefType (MIM.KeySeq.prototype);
1397 MIM.im_domain.DefType (MIM.Marker.prototype);
1398 MIM.im_domain.DefType (MIM.Selector.prototype);
1399 MIM.im_domain.DefType (MIM.Rule.prototype);
1400 MIM.im_domain.DefType (MIM.Map.prototype);
1401 MIM.im_domain.DefType (MIM.State.prototype);
1404 var im_domain = MIM.im_domain;
1406 function Finsert (domain, vari, args)
1408 domain.context.insert (args[0].val, null);
1411 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
1416 parsers['description'] = function (node)
1418 this.description = node.firstChild.nodeValue;
1420 parsers['title'] = function (node)
1422 this.title = node.firstChild.nodeValue;
1424 parsers['map-list'] = function (node)
1426 for (node = node.firstChild; node; node = node.nextSibling)
1428 if (node.nodeType != 1 || node.nodeName != 'map')
1430 var map = Xex.ParseTerm (this.domain, node);
1431 this.map_list[map.name] = map;
1434 parsers['state-list'] = function (node)
1436 this.domain.map_list = this.map_list;
1437 for (node = node.firstChild; node; node = node.nextSibling)
1439 if (node.nodeType != 1 || node.nodeName != 'state')
1441 var state = Xex.ParseTerm (this.domain, node);
1443 state.title = this.title;
1444 if (! this.initial_state)
1445 this.initial_state = state;
1446 this.state_list[state.name] = state;
1448 delete this.domain.map_list;
1451 MIM.IM = function (lang, name, extra_id, file)
1455 this.extra_id = extra_id;
1457 this.load_status = MIM.LoadStatus.NotLoaded;
1458 this.domain = new Xex.Domain (this.lang + '-' + this.name,
1459 MIM.im_domain, null);
1465 var node = Xex.Load (null, this.file);
1468 this.load_status = MIM.LoadStatus.Error;
1472 this.initial_state = null;
1473 this.state_list = {};
1474 for (node = node.firstChild; node; node = node.nextSibling)
1476 if (node.nodeType != 1)
1478 var name = node.nodeName;
1479 var parser = parsers[name];
1481 parser.call (this, node);
1483 this.load_status = MIM.LoadStatus.Loaded;
1488 MIM.IM.prototype = proto;
1490 MIM.IC = function (im)
1492 if (im.load_status == MIM.LoadStatus.NotLoaded)
1494 if (im.load_status != MIM.LoadStatus.Loaded)
1495 alert ('im:' + im.name + ' error:' + im.load_status);
1497 this.domain = new Xex.Domain ('context', im.domain, this);
1502 MIM.CandidateTable = function ()
1504 this.table = new Array ();
1507 MIM.CandidateTable.prototype.get = function (from)
1509 for (var i = 0; i < this.table.length; i++)
1511 var elt = this.table[i];
1512 if (elt.from <= from && elt.to > from)
1517 MIM.CandidateTable.prototype.put = function (from, to, candidates)
1519 for (var i = 0; i < this.table.length; i++)
1521 var elt = this.table[i];
1522 if (elt.from >= from && elt.from < to
1523 || elt.to >= from && elt.to < to)
1527 elt.val = candidates;
1531 this.table.push ({ from: from, to: to, val: candidates });
1534 MIM.CandidateTable.prototype.adjust = function (from, to, inserted)
1536 var diff = inserted - (to - from);
1537 for (var i = 0; i < this.table.length; i++)
1539 var elt = this.table[i];
1548 MIM.CandidateTable.prototype.clear = function ()
1550 this.table.length = 0;
1553 function set_cursor (prefix, pos)
1555 this.cursor_pos = pos;
1557 this.candidates = this.candidate_table.get (pos - 1);
1559 this.candidates = null;
1562 function save_state ()
1564 this.state_var_values = this.domain.SaveValues ();
1565 this.state_preedit = this.preedit;
1566 this.state_key_head = this.key_head;
1567 this.state_pos = this.cursor_pos;
1570 function restore_state ()
1572 this.domain.RestoreValues (this.state_var_values);
1573 this.preedit = this.state_preedit;
1574 set_cursor.call (this, "restore", this.state_pos);
1577 function handle_key ()
1579 var out = this.keymap.Lookup (this.keys, this.key_head);
1582 alert ('handling ' + this.keys.val[this.key_head]);
1583 this.key_head = out.index;
1584 if (sub != this.keymap)
1586 restore_state.call (this);
1588 alert ('submap found, taking map actions:' + sub.actions);
1589 if (this.keymap.actions != null)
1591 if (! this.take_actions (this.keymap.actions))
1594 else if (this.keymap.submaps != null)
1596 for (var i = this.state_key_head; i < this.key_head; i++)
1597 this.preedit_replace (this.cursor_pos, this.cursor_pos,
1598 this.keys.val[i].key, null);
1600 if (this.keymap.submaps == null)
1602 if (this.keymap.branch_actions != null)
1604 if (! this.take_actions (this.keymap.branch_actions))
1607 if (this.keymap != this.state.keymap)
1608 this.shift (this.state);
1613 var current_state = this.state;
1615 if (this.keymap.branch_actions != null)
1617 if (! this.take_actions (this.keymap.branch_actions))
1620 if (this.state == current_state)
1622 if (this.state == this.initial_state
1623 && this.key_head < this.keys.val.length)
1625 if (this.keymap != this.state.keymap)
1626 this.shift (this.state);
1627 else if (this.keymap.branch_actions == null)
1628 this.shift (this.initial_state);
1637 this.produced = null;
1639 this.cursor_pos = 0;
1640 this.marker_positions = {};
1641 this.candidates = null;
1642 this.candidate_show = false;
1644 this.prev_state = null;
1645 this.initial_state = this.im.initial_state;
1646 this.title = this.initial_state.title;
1647 this.state_preedit = '';
1648 this.state_key_head = 0;
1649 this.state_var_values = {};
1652 this.keys = new MIM.KeySeq ();
1654 this.key_unhandled = false;
1655 this.unhandled_key = null;
1656 this.changed = MIM.ChangedStatus.None;
1657 this.error_message = '';
1658 this.title = this.initial_state.title;
1659 this.produced = null;
1661 this.marker_positions = {};
1662 this.candidate_table = new MIM.CandidateTable ();
1663 this.candidates = null;
1664 this.candidate_show = false;
1670 this.state_var_values = {};
1671 this.shift (this.initial_state);
1674 catch_args: new Array (Xex.CatchTag._mimtag, null),
1676 take_actions: function (actions)
1678 var func_progn = this.domain.GetFunc ('progn');
1679 var func_catch = this.domain.GetFunc ('catch');
1680 this.catch_args[1] = new Xex.Funcall (func_progn, null, actions);
1681 var term = new Xex.Funcall (func_catch, null, this.catch_args);
1682 term = term.Eval (this.domain);
1683 return (! term.IsSymbol || term.val != '@mimtag');
1686 GetSurroundingChar: function (pos)
1688 if (pos < 0 ? this.caret_pos < - pos : this.target.value.length < pos)
1690 return this.target.value.charCodeAt (this.caret_pos + pos);
1693 adjust_markers: function (from, to, inserted)
1695 var diff = inserted - (to - from);
1697 for (var m in this.marker_positions)
1698 if (this.marker_positions[m] > from)
1699 this.marker_positions[m] = (this.marker_positions[m] >= to
1700 ? pos + diff : from);
1701 if (this.cursor_pos >= to)
1702 set_cursor.call (this, 'adjust', this.cursor_pos + diff);
1703 else if (this.cursor_pos > from)
1704 set_cursor.call (this, 'adjust', from)
1707 preedit_replace: function (from, to, text, candidates)
1709 this.preedit = (this.preedit.substring (0, from)
1710 + text + this.preedit.substring (to));
1711 this.adjust_markers (from, to, text.length);
1712 this.candidate_table.adjust (from, to, text.length);
1714 this.candidate_table.put (from, from + text.length, candidates)
1717 insert: function (text, candidates)
1719 this.preedit_replace (this.cursor_pos, this.cursor_pos, text, candidates);
1720 this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
1727 this.DelSurroundText (pos);
1730 else if (pos > this.preedit.length)
1732 this.DelSurroundText (pos - this.preedit.length);
1733 pos = this.preedit.length;
1735 if (pos < this.cursor_pos)
1736 this.preedit = (this.predit.substring (0, pos)
1737 + this.preedit.substring (this.cursor_pos));
1739 this.preedit = (this.preedit.substring (0, this.cursor_pos)
1740 + this.predit.substring (pos));
1745 this.candidate_show = true;
1746 this.changed |= MIM.ChangedStatus.CandidateShow;
1751 this.candidate_show = false;
1752 this.changed |= MIM.ChangedStatus.CandidateShow;
1755 move: function (pos)
1759 else if (pos > this.preedit.length)
1760 pos = this.preedit.length;
1761 if (pos != this.cursor_pos)
1763 set_cursor.call (this, 'move', pos);
1764 this.changed |= MIM.ChangedStatus.Preedit;
1768 pushback: function (n)
1770 if (n instanceof MIM.KeySeq)
1772 if (this.key_head > 0)
1774 if (this.key_head < this.keys.val.length)
1775 this.keys.val.splice (this.key_head,
1776 this.keys.val.length - this.key_head);
1777 for (var i = 0; i < n.val.length; i++)
1778 this.keys.val.push (n.val[i]);
1784 if (this.key_head < 0)
1791 this.key_head = - n;
1792 if (this.key_head > this.keys.val.length)
1793 this.key_head = this.keys.val.length;
1799 if (this.key_head < this.keys.val.length)
1800 this.keys.val.splice (this.key_head, 1);
1805 if (this.preedit.length > 0)
1807 this.candidate_table.clear ();
1808 this.produced += this.preedit;
1809 this.preedit_replace.call (this, 0, this.preedit.Length, '', null);
1813 shift: function (state)
1817 if (this.prev_state == null)
1819 state = this.prev_state;
1822 if (state == this.initial_state)
1825 this.keys.val.splice (0, this.key_head);
1827 if (state != this.state)
1829 this.domain.RestoreValues (this.state_initial_var_values);
1830 if (state.enter_actions != null)
1831 take_actions.call (state.enter_actions);
1833 this.prev_state = null;
1837 if (state != this.state && state.enter_actions != null)
1838 take_actions.call (state.enter_actions);
1839 this.prev_state = this.state;
1841 save_state.call (this);
1842 if (! this.state || this.state.title != state.title)
1843 this.changed |= MIM.ChangedStatus.StateTitle;
1845 this.keymap = state.keymap;
1848 Filter: function (key)
1852 this.key_unhandled = true;
1853 this.unhandled_key = key;
1856 if (key.key == '_reload')
1858 this.changed = MIM.ChangedStatus.None;
1860 this.key_unhandled = false;
1861 this.keys.val.push (key);
1863 while (this.key_head < this.keys.val.length)
1865 if (! handle_key.call (this))
1867 this.unhandled_key = this.keys.val[this.key_head++];
1868 this.key_unhandled = true;
1874 this.keys.val.splice (0, this.key_head);
1876 return (! this.key_unhandled && this.produced.length == 0);
1880 MIM.IC.prototype = proto;
1882 var node = Xex.Load (null, "imlist.xml");
1883 for (node = node.firstChild; node; node = node.nextSibling)
1884 if (node.nodeName == 'input-method')
1886 var lang, name, extra_id, file;
1888 for (var n = node.firstChild; n; n = n.nextSibling)
1890 if (n.nodeName == 'language')
1891 lang = n.firstChild.nodeValue;
1892 else if (n.nodeName == 'name')
1893 name = n.firstChild.nodeValue;
1894 else if (n.nodeName == 'extra-id')
1895 extra_id = n.firstChild.nodeValue;
1896 else if (n.nodeName == 'filename')
1897 file = n.firstChild.nodeValue;
1899 if (! MIM.im_list[lang])
1900 MIM.im_list[lang] = {};
1901 MIM.im_list[lang][name] = new MIM.IM (lang, name, extra_id, file);
1908 MIMTEST = function (name) { this.nam = name; };
1910 function testshow () { alert (this.nam); };
1912 MIMTEST.prototype.show = function () { testshow.call (this); }
1913 MIMTEST.prototype.cut = function (from, to) {
1914 this.val.splice (from, to -from); return this.val; }
1916 MIMTEST2 = function (name) { this.nam = name;
1917 this.val = new Array (1,2,3,4,5);}
1919 MIMTEST2.prototype = MIMTEST.prototype;
1921 var x = new MIMTEST2 ('test2');
1924 MIM.test = function ()
1926 var im = MIM.im_list['t']['latn-post'];
1927 var ic = new MIM.IC (im);
1931 ic.Filter (new MIM.Key ('a'));
1932 ic.Filter (new MIM.Key ("'"));
1935 document.getElementById ('text').value = ic.preedit;
1938 document.getElementById ('text').value
1939 = Xex.ParseTerm (domain, body).Eval (domain).toString ();
1941 if (e instanceof Xex.ErrTerm)