*** empty log message ***
[m17n/m17n-lib-js.git] / xex.js
1 // -* coding: utf-8; -*
2
3 var Xex = {
4   LogNode: null,
5   Log: function (arg, indent)
6   {
7     if (! Xex.LogNode)
8       return;
9     var str = '';
10     if (indent != undefined)
11       for (var i = 0; i < indent; i++)
12         str += '  ';
13     Xex.LogNode.value = str + arg + "\n" + Xex.LogNode.value;
14   }
15 };
16
17 Xex.Error = {
18   UnknownError: "unknown-error",
19   WrongArgument: "wrong-argument",
20   // Load time errors.
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",
28
29   UnknownFunction: "unknown-function",
30   MacroExpansionError: "macro-expansion-error",
31   NoVariableName: "no-variable-name",
32   NoFunctionName: "no-funcion-name",
33
34   // Run time errors.
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"
41 };
42
43 Xex.Variable = function (domain, name, desc, val, range)
44 {
45   this.domain = domain;
46   this.name = name;
47   this.desc = desc;
48   this.val = val;
49   this.range = range;
50 }
51
52 Xex.Variable.prototype.clone = function ()
53 {
54   return new Xex.Variable (this.domain, this.name, this.desc,
55                            this.val, this.range);
56 }
57     
58 Xex.Variable.prototype.Equals = function (obj)
59 {
60   return ((obj instanceof Xex.Variable)
61           && obj.name == this.name);
62 }
63
64 Xex.Variable.prototype.SetValue = function (term)
65 {
66   this.val = term;
67   return term;
68 }
69
70 Xex.Function = function (name, with_var, min_args, max_args)
71 {
72   this.name = name;
73   this.with_var = with_var;
74   this.min_args = min_args;
75   this.max_args = max_args;
76 };  
77
78 Xex.Subrountine = function (builtin, name, with_var, min_args, max_args)
79 {
80   this.name = name;
81   this.with_var = with_var;
82   this.min_args = min_args;
83   this.max_args = max_args;
84   this.builtin = builtin;
85 }
86
87 Xex.Subrountine.prototype.Call = function (domain, vari, args)
88 {
89   var newargs = new Array ();
90   for (var i = 0; i < args.length; i++)
91     {
92       newargs[i] = args[i].Eval (domain);
93       if (domain.Thrown ())
94         return newargs[i];
95     }
96   return this.builtin (domain, vari, newargs)
97 }
98
99 Xex.SpecialForm = function (builtin, name, with_var, min_args, max_args)
100 {
101   this.name = name;
102   this.with_var = with_var;
103   this.min_args = min_args;
104   this.max_args = max_args;
105   this.builtin = builtin;
106 }
107
108 Xex.SpecialForm.prototype.Call = function (domain, vari, args)
109 {
110   return this.builtin (domain, vari, args)
111 }
112
113 Xex.Lambda = function (name, min_args, max_args, args, body)
114 {
115   this.name = name;
116   this.min_args = min_args;
117   this.max_args = max_args;
118   this.args = args;
119   this.body = body;
120 }
121
122 Xex.Lambda.prototype.Call = function (domain, vari, args)
123 {
124   var current = domain.bindings;
125   var result = Xex.Zero;
126   var limit = max_args >= 0 ? args.length : args.length - 1;
127   var i;
128   
129   try {
130     for (i = 0; i < limit; i++)
131       {
132         result = args[i].Eval (domain);
133         if (domain.Thrown ())
134           return result;
135         domain.Bind (this.args[i], result);
136       }
137     if (max_args < 0)
138       {
139         var list = new Array ();
140         for (i = 0; i < args[limit].length; i++)
141           {
142             result = args[limit].Eval (domain);
143             if (domain.Thrown ())
144               return result;
145             list[i] = result;
146           }
147         domain.Bind (this.args[limit], list);
148       }
149     try {
150       domain.Catch (Xex.CatchTag.Return);
151       for (var term in this.body)
152         {
153           result = term.Eval (domain);
154           if (domain.Thrown ())
155             return result;
156         }
157     } finally {
158       domain.Uncatch ();
159     }
160   } finally {
161     domain.UnboundTo (current);
162   }
163   return result;
164 }
165
166 Xex.Macro = function (name, min_args, max_args, args, body)
167 {
168   this.name = name;
169   this.min_args = min_args;
170   this.max_args = max_args;
171   this.args = args;
172   this.body = body;
173 }
174
175 Xex.Macro.prototype.Call = function (domain, vari, args)
176 {
177   var current = domain.bindings;
178   var result = Xex.Zero;
179   var i;
180
181   try {
182     for (i = 0; i < args.length; i++)
183       domain.Bind (this.args[i], args[i]);
184     try {
185       domain.Catch (Xex.CatchTag.Return);
186       for (var term in body)
187         {
188           result = term.Eval (domain);
189           if (domain.Thrown ())
190             break;
191         }
192     } finally {
193       domain.Uncatch ();
194     }
195   } finally {
196     domain.UnboundTo (current);
197   }
198   return result;
199 }
200
201 Xex.Bindings = function (vari)
202 {
203   this.vari = vari;
204   this.old_value = vari.val;
205 }
206
207 Xex.Bindings.prototype.UnboundTo = function (boundary)
208 {
209   for (var b = this; b != boundary; b = b.next)
210     b.vari.val = b.old_value;
211   return boundary;
212 }
213
214 Xex.Bind = function (bindings, vari, val)
215 {
216   var b = new Xex.Bindings (vari);
217   b.vari.val = val;
218   b.next = bindings;
219   return b;
220 }
221
222 Xex.CatchTag = {
223   Return: 0,
224   Break: 1
225 }
226
227 Xex.Domain = function (name, parent, context)
228 {
229   this.name = name;
230   this.context = context;
231   this.depth = 0;
232
233   if (name != 'basic' && ! parent)
234     parent = Xex.BasicDomain
235   this.parent = parent;
236   this.termtypes = {};
237   this.functions = {};
238   this.variables = {};
239   if (parent)
240     {
241       var elt;
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];
248     }
249
250   this.call_stack = new Array ();
251   this.bindings = null;
252   this.catch_stack = new Array ();
253   this.catch_count = 0;
254   this.caught = false;
255 };
256
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)
262   {
263     this.bindings = Xex.Bind (this.bindings, vari, val);
264   },
265   UnboundTo: function (boundary)
266   {
267     if (this.bindings)
268       this.bindings = this.bindings.UnboundTo (boundary);
269   },
270   Catch: function (tag) { this.catch_stack.push (tag); this.catch_count++; },
271   Uncatch: function ()
272   {
273     this.catch_stack.pop ();
274     if (this.catch_count > this.catch_stack.length)
275       this.catch_count--;
276   },
277   Thrown: function ()
278   {
279     if (this.catch_count < this.catch_stack.length)
280       {
281         this.caught = (this.catch_count == this.catch_stack.length - 1);
282         return true;
283       }
284     this.caught = false;
285     return false;
286   },
287   ThrowReturn: function ()
288   {
289     for (var i = this.catch_stack.length - 1; i >= 0; i--)
290       {
291         this.catch_count--;
292         if (this.catch_stack[i] == Xex.CatchTag.Return)
293           break;
294       }
295   },
296   ThrowBreak: function ()
297   {
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");
301     this.catch_count--;
302   },
303   ThrowSymbol: function (tag)
304   {
305     var i = this.catch_count;
306     for (var j = this.catch_stack.length - 1; j >= 0; j--)
307       {
308         i--;
309         if (Xex.CatchTag.Matches (this.catch_stack[i], tag))
310           {
311             this.catch_count = i;
312             return;
313           }
314       }
315     throw new Xex.ErrTerm (Xex.Error.UncaughtThrow,
316                          "No corresponding catch: " + tag);
317   },
318   DefType: function (obj)
319   {
320     var type = obj.type;
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: "
327                            + type);
328     this.termtypes[type] = obj.Parser;
329   },
330   DefSubr: function (builtin, name, with_var, min_args, max_args)
331   {
332     this.functions[name] = new Xex.Subrountine (builtin, name, with_var,
333                                                 min_args, max_args);
334   },
335   DefSpecial: function (builtin, name, with_var, min_args, max_args)
336   {
337     this.functions[name] = new Xex.SpecialForm (builtin, name, with_var,
338                                                 min_args, max_args);
339   },
340   Defun: function (name, min_args, max_args, args, body)
341   {
342     this.functions[name] =  new Xex.Lambda (name, min_args, max_args,
343                                             args, body);
344   },
345   DefunByFunc: function (func) { this.functions[func.name] = func; },
346   Defmacro: function (name, min_args, max_args, args, body)
347   {
348     this.functions[name] = new Xex.Macro (name, min_args, max_args,
349                                           args, body);
350   },
351   DefAlias: function (alias, fname)
352   {
353     var func = this.functions[fname];
354
355     if (! func)
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;
364   },
365   Defvar: function (name, desc, val, range)
366   {
367     var vari = new Xex.Variable (this, name, desc, val, range);
368     this.variables[name] = vari;
369     return vari;
370   },
371   GetFunc: function (name)
372   {
373     var func = this.functions[name];
374     if (! func)
375       throw new Xex.ErrTerm (Xex.Error.UnknownFunction,
376                              "Unknown function: " + name);
377     return func;
378   },
379   CopyFunc: function (domain, name)
380   {
381     var func = this.functions[name];
382     domain.DefunByFunc (func);
383     return true;
384   },
385   CopyFuncAll: function (domain)
386   {
387     for (var elt in this.functions)
388       domain.DefunByFunc (this.functions[elt]);
389   },
390   GetVarCreate: function (name)
391   {
392     var vari = this.variables[name];
393     if (! vari)
394       vari = this.variables[name] = new Xex.Variable (this, name, null,
395                                                       Xex.Zero, null);
396     return vari;
397   },
398   GetVar: function (name) { return this.variables[name]; },
399   SaveValues: function ()
400   {
401     values = {};
402     for (var elt in this.variables)
403       values[elt] = this.variables[elt].val.Clone ();
404     return values;
405   },
406   RestoreValues: function (values)
407   {
408     var name;
409     for (name in values)
410       {
411         var vari = this.variables[name];
412         vari.val = values[name];
413       }
414   }
415 };
416
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)
423   {
424     return (this.type == obj.type
425             && this.val
426             && obj.val == this.val);
427   },
428   Matches: function (obj) { return this.Equals (obj); },
429   toString: function ()
430   {
431     if (this.val != undefined)
432       return '<' + this.type + '>' + this.val + '</' + this.type + '>';
433     return '<' + this.type + '/>';
434   },
435   Intval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
436                                                "Not an integer"); },
437   Strval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
438                                                "Not a string"); }
439 };
440
441 Node.prototype.firstElement = function ()
442 {
443   for (var n = this.firstChild; n; n = n.nextSibling)
444     if (n.nodeType == 1)
445       return n;
446   return null;
447 }
448
449 Node.prototype.nextElement = function ()
450 {
451   for (var n = this.nextSibling; n; n = n.nextSibling)
452     if (n.nodeType == 1)
453       return n;
454   return null;
455 };
456
457 (function () {
458   function parse_defvar (domain, node)
459   {
460     var name = node.attributes['vname'].nodeValue;
461     if (! name)
462       throw new Xex.ErrTerm (Xex.Error.NoVariableName, node, '');
463     var vari = domain.variables[name];
464     var desc, val, range;
465     if (vari)
466       {
467         desc = vari.description;
468         val = vari.val;
469         range = vari.range;
470       }
471     node = node.firstElement ();
472     if (node && node.nodeName == 'description')
473       {
474         desc = node.firstChild.nodeValue;
475         node = node.nextElement ();
476       }
477     if (node)
478       {
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 ())
483             {
484               var pval;
485               if (node.nodeName == 'range')
486                 {
487                   if (! val.IsInt)
488                     throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
489                                            'Range not allowed for ' + name);
490                   pval = new Array ();
491                   for (var n = node.firstElement (); n; n = n.nextElement ())
492                     {
493                       var v = Xex.Term.Parse (domain, n);
494                       if (! v.IsInt)
495                         throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
496                                                'Invalid range value: ' + val);
497                       pval.push (v);
498                     }
499                   }
500               else
501                 {
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);
506                 }
507               if (! range)
508                 range = new Array ();
509               range.push (pval);
510           }
511       }
512     if (! val)
513       val = Xex.Zero;
514     domain.Defvar (name, desc, val, range);
515     return name;
516   }
517
518   function parse_defun_head (domain, node)
519   {
520     var name = node.attributes['fname'].nodeValue;
521     if (! name)
522       throw new Xex.ErrTerm (Xex.Error.NoFunctionName, node, '');
523     var args = new Array ();
524     var nfixed = 0, noptional = 0, nrest = 0;
525
526     node = node.firstElement ();
527     if (node && node.nodeName == 'args')
528       {
529         var n;
530         for (n = n.firstElement (); n; n = n.nextElement ())
531           {
532             if (n.nodeName == 'fixed')
533               nfixed++;
534             else if (n.nodeName == 'optional')
535               noptional++;
536             else if (n.nodeName == 'rest')
537               nrest++;
538             else
539               throw new Xex.ErrTerm (Xex.Error.WrongType, n, n.nodeName);
540           }
541         if (nrest > 1)
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));
545       }
546     args.min_args = nfixed;
547     args.max_args = nrest == 0 ? nfixed + noptional : -1;
548
549     if (node.nodeName == 'defun')
550       domain.Defun (name, args, null);
551     else
552       domain.Defmacro (name, args, null);
553     return name;
554   }
555
556   function parse_defun_body (domain, node)
557   {
558     var name = node.attributes['fname'].nodeValue;
559     var func = domain.GetFunc (name);
560     var body;
561     for (node = node.firstElement (); node; node = node.nextElement ())
562       if (node.nodeName != 'description' && node.nodeName != 'args')
563         break;
564     body = Xex.Term.Parse (domain, node, null);
565     func.body = body;
566   }
567
568   Xex.Term.Parse = function (domain, node, stop)
569   {
570     if (arguments.length == 2)
571       {
572         var name = node.nodeName;
573         var parser = domain.termtypes[name];
574
575         if (parser)
576           return parser (domain, node);
577         if (name == 'defun' || name == 'defmacro')
578           {
579             name = parse_defun_head (domain, node);
580             parse_defun_body (domain, node);
581             return new Xex.StrTerm (name);
582           }
583         if (name == 'defvar')
584           {
585             name = parse_defvar (domain, node);
586             return new Xex.StrTerm (name);
587           }
588         return new Xex.Funcall.prototype.Parser (domain, node);
589       }
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);
593     var terms = null;
594     for (var n = node; n && n != stop; n = n.nextElement ())
595       {
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);
600         else
601           {
602             if (! terms)
603               terms = new Array ();
604             terms.push (Xex.Term.Parse (domain, n));
605           }
606       }
607     return terms;
608   }
609 }) ();
610
611 Xex.Varref = function (vname)
612 {
613   this.val = vname;
614 };
615
616 (function () {
617   var proto = new Xex.Term ('varref');
618
619   proto.Clone = function () { return new Xex.Varref (this.val); }
620   proto.Eval = function (domain)
621   {
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;
626   }
627
628   proto.Parser = function (domain, node)
629   {
630     return new Xex.Varref (node.attributes['vname'].nodeValue);
631   }
632
633   proto.ToString = function ()
634   {
635     return '<varref vname="' + this.val + '"/>';
636   }
637
638   Xex.Varref.prototype = proto;
639 }) ();
640
641 var null_args = new Array ();
642   
643 Xex.Funcall = function (func, vari, args)
644 {
645   this.func = func;
646   this.vari = vari;
647   this.args = args || null_args;
648 };
649
650 (function () {
651   var proto = new Xex.Term ('funcall');
652
653   proto.Parser = function (domain, node)
654   {
655     var fname = node.nodeName;
656     var attr;
657
658     if (fname == 'funcall')
659       fname = node.attributes['fname'].nodeValue;
660     var func = domain.GetFunc (fname);
661     var vari;
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);
666   }
667
668   proto.New = function (domain, fname, vname, args)
669   {
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);
675     return funcall;
676   }
677
678   proto.Eval = function (domain)
679   {
680     Xex.Log (this, domain.depth++);
681     var result;
682     try {
683       result = this.func.Call (domain, this.vari, this.args);
684     } finally {
685       Xex.Log (this + ' => ' + result, --domain.depth);
686     }
687     return result;
688   }
689
690   proto.Clone = function ()
691   {
692     return new Xex.Funcall (this.func, this.vari, this.args);
693   }
694
695   proto.Equals = function (obj)
696   {
697     return (obj.type == 'funcall'
698             && obj.func == this.func
699             && obj.vari.Equals (this.vari)
700             && obj.args.length == this.func.length);
701   }
702
703   proto.toString = function ()
704   {
705     var arglist = ''
706     var len = this.args.length;
707     var str = '<' + this.func.name;
708     if (this.vari)
709       str += ' vname="' + this.vari.name + '"';
710     if (len == 0)
711       return str + '/>';
712     for (var i = 0; i < len; i++)
713       arglist += '.'; //this.args[i].toString ();
714     return str + '>' + arglist + '</' + this.func.name + '>';
715   }
716
717   Xex.Funcall.prototype = proto;
718 }) ();
719
720 Xex.ErrTerm = function (ename, message, stack)
721 {
722   this.ename = ename;
723   this.message = message;
724   this.stack = stack;
725 };
726
727 (function () {
728   var proto = new Xex.Term ('error');
729
730   proto.IsError = true;
731
732   proto.Parser = function (domain, node)
733   {
734     return new Xex.ErrTerm (node.attributes['ename'].nodeValue,
735                             node.innerText, false);
736   }
737
738   proto.CallStack = function () { return stack; }
739
740   proto.SetCallStack = function (value) { statck = value; }
741
742   proto.Clone = function ()
743   {
744     return new Xex.ErrTerm (ename, message, false);
745   }
746
747   proto.Equals = function (obj)
748   {
749     return (obj.IsError
750             && obj.ename == ename && obj.message == message
751             && (obj.stack ? (stack && stack.length == obj.stack.length)
752                 : ! stack));
753   }
754
755   proto.Matches = function (obj)
756   {
757     return (obj.IsError && obj.ename == ename);
758   }
759
760   proto.toString = function ()
761   {
762     return '<error ename="' + this.ename + '">' + this.message + '</error>';
763   }
764
765   Xex.ErrTerm.prototype = proto;
766 }) ();
767
768 Xex.IntTerm = function (num) { this.val = num; };
769 (function () {
770   var proto = new Xex.Term ('integer');
771   proto.IsInt = true;
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)
776   {
777     var str = node.firstChild.nodeValue;
778
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));
782   }
783   Xex.IntTerm.prototype = proto;
784 }) ();
785
786 Xex.StrTerm = function (str) { this.val = str; };
787 (function () {
788   var proto = new Xex.Term ('string');
789   proto.IsStr = true;
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)
794   {
795     return new Xex.StrTerm (node.firstChild.nodeValue);
796   }
797   Xex.StrTerm.prototype = proto;
798 }) ();
799
800 Xex.SymTerm = function (str) { this.val = str; };
801 (function () {
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)
807   {
808     return new Xex.SymTerm (node.firstChild.nodeValue);
809   }
810   Xex.SymTerm.prototype = proto;
811 }) ();
812
813 Xex.LstTerm = function (list) { this.val = list; };
814 (function () {
815   var proto = new Xex.Term ('list');
816   proto.IsList = true;
817   proto.IsTrue = function () { return this.val.length > 0; }
818   proto.Clone = function () { return new Xex.LstTerm (this.val.slice (0)); }
819
820   proto.Equals = function (obj)
821   {
822     if (obj.type != 'list' || obj.val.length != this.val.length)
823       return false;
824     var i, len = this.val.length;
825     for (i = 0; i < len; i++)
826       if (! this.val[i].Equals (obj.val[i]))
827         return false;
828     return true;
829   }
830
831   proto.Parser = function (domain, node)
832   {
833     var list = Xex.Term.Parse (domain, node.firstElement (), null);
834     return new Xex.LstTerm (list);
835   }
836
837   proto.toString = function ()
838   {
839     var len = this.val.length;
840
841     if (len == 0)
842       return '<list/>';
843     var str = '<list>';
844     for (var i = 0; i < len; i++)
845       str += this.val[i].toString ();
846     return str + '</list>';
847   }
848   Xex.LstTerm.prototype = proto;
849 }) ();
850
851 (function () {
852   var basic = new Xex.Domain ('basic', null, null);
853
854   function Fset (domain, vari, args)
855   {
856     if (! vari)
857       throw new Xex.ErrTerm (Xex.Error.NoVariableName,
858                              'No variable name to set');
859     vari.SetValue (args[0]);
860     return args[0];
861   }
862
863   function maybe_set_intvar (vari, n)
864   {
865     var term = new IntTerm (n);
866     if (vari)
867       vari.SetValue (term);
868     return term;
869   }
870
871   function Fadd (domain, vari, args)
872   {
873     var n = vari ? vari.val.Intval () : 0;
874     var len = args.length;
875
876     for (var i = 0; i < len; i++)
877       n += args[i].Intval ();
878     return maybe_set_intvar (vari, n);
879   }
880
881   function Fmul (domain, vari, args)
882   {
883     var n = vari ? vari.val.Intval () : 1;
884     for (var i = 0; i < args.length; i++)
885       n *= arg.Intval ();
886     return maybe_set_intvar (vari, n);
887   }
888
889   function Fsub (domain, vari, args)
890   {
891     var n, i;
892
893     if (! vari)
894       {
895         n = args[0].Intval ();
896         i = 1;
897       }
898     else
899       {
900         n = vari.val.Intval ();
901         i = 0;
902       }
903     while (i < args.length)
904       n -= args[i++].Intval ();
905     return maybe_set_intvar (vari, n);
906   }
907
908   function Fdiv (domain, vari, args)
909   {
910     var n, i;
911
912     if (! vari == null)
913       {
914         n = args[0].Intval ();
915         i = 1;
916       }
917     else
918       {
919         n = vari.val.Intval ();
920         i = 0;
921       }
922     while (i < args.length)
923       n /= args[i++].Intval ();
924     return maybe_set_intvar (vari, n);
925   }
926
927   function Fmod (domain, vari, args)
928   {
929     return maybe_set_intvar (vari, args[0].Intval () % args[1].Intval ());
930   }
931
932   function Flogior (domain, vari, args)
933   {
934     var n = vari == null ? 0 : vari.val;
935     for (var i = 0; i < args.length; i++)
936       n |= args[i].val;
937     return maybe_set_intvar (vari, n);
938   }
939
940   function Fand (domain, vari, args)
941   {
942     var len = args.length;
943     for (var i = 0; i < len; i++)
944     {
945       var result = args[i].Eval (domain);
946       if (domain.Thrown ())
947         return result;
948       if (! result.IsTrue ())
949         return Xex.Zero;
950     }
951     return Xex.One;
952   }
953
954   function For (domain, vari, args)
955   {
956     var len = args.length;
957     for (var i = 0; i < len; i++)
958     {
959       var result = args[i].Eval (domain);
960       if (domain.Thrown ())
961         return result;
962       if (result.IsTrue ())
963         return Xex.One;
964     }
965     return Xex.Zero;
966   }
967
968   function Feq (domain, vari, args)
969   {
970     for (var i = 1; i < args.length; i++)
971       if (! args[i - 1].Equals (args[i]))
972         return Xex.Zero;
973     return Xex.One;
974   }
975
976   function Flt (domain, vari, args)
977   {
978     var n = args[0].Intval;
979
980     for (var i = 1; i < args.length; i++)
981       {
982         var n1 = args[i].Intval;
983         if (n >= n1)
984           return Xex.Zero;
985         n = n1;
986       }
987     return Xex.One;
988   }
989
990   function Fle (domain, vari, args)
991   {
992     var n = args[0].Intval;
993     for (var i = 1; i < args.length; i++)
994       {
995         var n1 = args[i].Intval;
996         if (n > n1)
997           return Xex.Zero;
998         n = n1;
999       }
1000     return Xex.One;
1001   }
1002
1003   function Fgt (domain, vari, args)
1004   {
1005     var n = args[0].Intval;
1006     for (var i = 1; i < args.length; i++)
1007       {
1008         var n1 = args[i].Intval;
1009         if (n <= n1)
1010           return Xex.Zero;
1011         n = n1;
1012       }
1013     return Xex.One;
1014   }
1015
1016   function Fge (domain, vari, args)
1017   {
1018     var n = args[0].Intval;
1019     for (var i = 1; i < args.Length; i++)
1020       {
1021         var n1 = args[i].Intval;
1022         if (n < n1)
1023           return Xex.Zero;
1024         n = n1;
1025       }
1026     return Xex.One;
1027   }
1028
1029   function Fprogn (domain, vari, args)
1030   {
1031     var result = Xex.One;
1032     var len = args.length;
1033
1034     for (var i = 0; i < len; i++)
1035       {
1036         result = args[i].Eval (domain);
1037         if (domain.Thrown ())
1038           return result;
1039       }
1040     return result;
1041   }
1042
1043   function Fif (domain, vari, args)
1044   {
1045     var result = args[0].Eval (domain);
1046
1047     if (domain.Thrown ())
1048       return result;
1049     if (result.IsTrue ())
1050       return args[1].Eval (domain);
1051     if (args.length == 2)
1052       return Zero;
1053     return args[2].Eval (domain);
1054   }
1055
1056   function Fcond (domain, vari, args)
1057   {
1058     for (var i = 0; i < args.length; i++)
1059       {
1060         var list = args[i].val;
1061         var result = list.val[0].Eval (doamin);
1062         if (result.isTrue ())
1063           {
1064             for (var j = 1; j < list.val.length; j++)
1065               {
1066                 domain.depth++;
1067                 result = list.val[j].Eval (domain);
1068                 domain.depth--;
1069                 if (domain.Thrown ())
1070                   return result;
1071                 }
1072             return result;
1073           }
1074       }
1075     return Xex.Zero;
1076   }
1077
1078   function eval_terms (domain, terms, idx)
1079   {
1080     var result = Xex.Zero;
1081     domain.caught = false;
1082     for (var i = idx; i < terms.length; i++)
1083       {
1084         result = terms[i].Eval (domain);
1085         if (domain.Thrown ())
1086           return result;
1087       }
1088     return result;
1089   }
1090
1091   function Fcatch (domain, vari, args)
1092   {
1093     var caught = false;
1094     var result;
1095
1096     if (args[0].IsError)
1097       {
1098         try {
1099           result = eval_terms (domain, args, 1);
1100         } catch (e) {
1101           if (e instanceof Xex.ErrTerm)
1102             {
1103               if (! args[0].Matches (e))
1104                 throw e;
1105               if (vari)
1106                 vari.SetValue (e);
1107               return Xex.One;
1108             }
1109         }
1110       }
1111     else if (args[0].IsSymbol)
1112       {
1113         try {
1114           domain.Catch (args[0].val);
1115           result = eval_terms (domain, args, 1);
1116           if (domain.caught)
1117             {
1118               if (vari != null)
1119                 vari.SetValue (result);
1120               return Xex.One;
1121             }
1122           return Xex.Zero;
1123         } finally {
1124           domain.Uncatch ();
1125         }
1126       }
1127     throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1128                            "Not a symbol nor an error: " + args[0]);
1129   }
1130
1131   function Fthrow (domain, vari, args)
1132   {
1133     if (args[0].IsSymbl)
1134       {
1135         domain.ThrowSymbol (args[0]);
1136         return (args[args.length - 1]);
1137       }
1138     if (args[0].IsError)
1139       {
1140         throw args[0];
1141       }
1142     throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1143                            "Not a symbol nor an error:" + args[0]);
1144   }
1145
1146   Xex.BasicDomain = basic;
1147
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);
1182
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);
1193
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);
1209
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);
1217
1218 }) ();
1219
1220 Xex.Zero = new Xex.IntTerm (0);
1221 Xex.One = new Xex.IntTerm (1);
1222 Xex.nil = new Xex.SymTerm ('nil');
1223
1224 Xex.Load = function (server, file)
1225 {
1226   var obj = new XMLHttpRequest ();
1227   var url = server ? server + '/' + file : file;
1228   obj.open ('GET', url, false);
1229   obj.overrideMimeType ('text/xml');
1230   obj.send ('');
1231   return obj.responseXML.firstChild;
1232 }
1233
1234 var MIM = {
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.
1238   enabled: true,
1239   // Boolean flag to tell if MIM is running in debug mode or not.
1240   debug: false,
1241   // List of main input methods.
1242   imlist: {},
1243   // List of extra input methods;
1244   imextra: {},
1245   // Global input method data
1246   im_global: null,
1247   // Currently selected input method.
1248   current: false,
1249
1250   // enum
1251   LoadStatus: { NotLoaded:0, Loading:1, Loaded:2, Error:-1 },
1252   ChangedStatus: {
1253     None:       0x00,
1254     StateTitle: 0x01,
1255     PreeditText:0x02,
1256     CursorPos:  0x04,
1257     CandidateList:0x08,
1258     CandidateIndex:0x10,
1259     CandidateShow:0x20,
1260     Preedit:    0x06,           // PreeditText | CursorPos
1261     Candidate:  0x38 // CandidateList | CandidateIndex | CandidateShow
1262   },
1263   KeyModifier: {
1264     SL: 0x00400000,
1265     SR: 0x00800000,
1266     S:  0x00C00000,
1267     CL: 0x01000000,
1268     CR: 0x02000000,
1269     C:  0x03000000,
1270     AL: 0x04000000,
1271     AR: 0x08000000,
1272     A:  0x0C000000,
1273     ML: 0x04000000,
1274     MR: 0x08000000,
1275     M:  0x0C000000,
1276     G:  0x10000000,
1277     s:  0x20000000,
1278     H:  0x40000000,
1279     High:       0x70000000,
1280     All:        0x7FC00000
1281   },
1282   Error: {
1283     ParseError: "parse-error"
1284   }
1285 };
1286   
1287 (function () {
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";
1295
1296   function decode_keysym (str) {
1297     var parts = str.split ("-");
1298     var len = parts.length, i;
1299     var has_modifier = len > 1;
1300
1301     for (i = 0; i < len - 1; i++)
1302       if (! MIM.KeyModifier.hasOwnProperty (parts[i]))
1303         return false;
1304     var key = parts[len - 1];
1305     if (key.length > 1)
1306       {
1307         key = keysyms[key.toLowerCase ()];
1308         if (key)
1309           {
1310             if (len > 1)
1311               {
1312                 str = parts[0];
1313                 for (i = 1; i < len - 1; i++)
1314                   str += '-' + parts[i];
1315                 str += '-' + key;
1316               }
1317             else
1318               str = key;
1319           }
1320       }
1321     if (has_modifier)
1322       {
1323         parts = new Array ();
1324         parts.push (str);
1325         return parts;
1326       }
1327     return str;
1328   }
1329
1330   MIM.Key = function (val)
1331   {
1332     this.key;
1333     this.has_modifier = false;
1334     if (typeof val == 'string' || val instanceof String)
1335       {
1336         this.key = decode_keysym (val);
1337         if (! this.key)
1338           throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1339         if (this.key instanceof Array)
1340           {
1341             this.key = this.key[0];
1342             this.has_modifier = true;
1343           }
1344       }
1345     else if (typeof val == 'number' || val instanceof Number)
1346       this.key = String.fromCharCode (val);
1347     else
1348       throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1349   }
1350
1351   MIM.Key.prototype.toString = function () { return this.key; };
1352 }) ();
1353
1354 (function () {
1355   MIM.KeySeq = function (seq)
1356   {
1357     this.val = new Array ();
1358     this.has_modifier = false;
1359
1360     if (seq)
1361       {
1362         if (seq.IsList)
1363           {
1364             var len = seq.val.length;
1365             for (var i = 0; i < len; i++)
1366               {
1367                 var v = seq.val[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;
1376               }
1377           }
1378         else if (seq.IsStr)
1379           {
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)));
1383           }
1384         else
1385           throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + seq);
1386       }
1387   }
1388
1389   var proto = new Xex.Term ('keyseq');
1390   proto.Clone = function () { return this; }
1391   proto.Parser = function (domain, node)
1392   {
1393     var seq = new Array ();
1394     for (node = node.firstChild; node; node = node.nextSibling)
1395       if (node.nodeType == 1)
1396         {
1397           var term = Xex.Term.Parse (domain, node);
1398           return new MIM.KeySeq (term);
1399         }
1400     throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid keyseq");
1401   }
1402   proto.toString = function ()
1403   {
1404     var len = this.val.length;
1405     if (len == 0)
1406       return '<keyseq/>';
1407     var first = true;
1408     var str = '<keyseq>';
1409     for (var i = 0; i < len; i++)
1410       {
1411         if (first)
1412           first = false;
1413         else if (this.has_modifier)
1414           str += ' ';
1415         str += this.val[i].toString ();
1416       }
1417     return str + '</keyseq>';
1418   }
1419
1420   MIM.KeySeq.prototype = proto;
1421 }) ();
1422
1423 (function () {
1424   MIM.Marker = function () { }
1425   MIM.Marker.prototype = new Xex.Term ('marker');
1426   MIM.Marker.prototype.CharAt = function (ic)
1427   {
1428     var p = this.Position (ic);
1429     if (p < 0 || p >= ic.preedit.length)
1430       return 0;
1431     return ic.preedit.charCodeAt (p);
1432   }
1433
1434   MIM.NamedMarker = function (name) { this.val = name; }
1435   MIM.NamedMarker.prototype = new MIM.Marker ();
1436   MIM.NamedMarker.prototype.Position = function (ic)
1437   {
1438     var p = ic.marker_positions[this.val];
1439     return (p == undefined ? 0 : p);
1440   }
1441   MIM.NamedMarker.prototype.Mark = function (ic)
1442   {
1443     ic.marker_positions[this.val] = ic.cursor_pos;
1444   }
1445
1446   MIM.PredefinedMarker = function (name) { this.val = name; }
1447   MIM.PredefinedMarker.prototype = new MIM.Marker ();
1448   MIM.PredefinedMarker.prototype.Position = function (ic)
1449   {
1450     if (typeof this.pos == 'number')
1451       return this.pos;
1452     return this.pos (ic);
1453   }
1454
1455   var predefined = { }
1456
1457   function def_predefined (name, position)
1458   {
1459     predefined[name] = new MIM.PredefinedMarker (name);
1460     predefined[name].pos = position;
1461   }
1462
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)
1469       {
1470         var pos = ic.cursor_pos;
1471         return ic.preedit.FindProp ('candidates', pos - 1).from;
1472       }
1473     return 0;
1474   });
1475   def_predefined ('@]', function (ic) {
1476     if (ic.cursor_pos < ic.preedit.length - 1)
1477       {
1478         var pos = ic.cursor_pos;
1479         return ic.preedit.FindProp ('candidates', pos).to;
1480       }
1481     return ic.preedit.length;
1482   });
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['@]'];
1491
1492   MIM.SurroundMarker = function (name)
1493   {
1494     this.val = name;
1495     this.distance = parseInt (name.slice (1));
1496     if (isNaN (this.distance))
1497       throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid marker: " + name);
1498   }
1499   MIM.SurroundMarker.prototype = new MIM.Marker ();
1500   MIM.SurroundMarker.prototype.Position = function (ic)
1501   {
1502     return ic.cursor_pos + this.distance;
1503   }
1504   MIM.SurroundMarker.prototype.CharAt = function (ic)
1505   {
1506     if (this.val == '@-0')
1507       return -1;
1508     var p = this.Position (ic);
1509     if (p < 0)
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);
1514   }
1515
1516   MIM.Marker.prototype.Parser = function (domain, node)
1517   {
1518     var name = node.firstChild.nodeValue;
1519     if (name.charAt (0) == '@')
1520       {
1521         var n = predefined[name];
1522         if (n)
1523           return n;
1524         if (name.charAt (1) == '-')
1525           return new MIM.SurroundMarker (name);
1526         throw new Xex.ErrTerm (MIM.Error.ParseError,
1527                                "Invalid marker: " + name);
1528       }
1529     return new MIM.NamedMarker (name);
1530   }
1531 }) ();
1532
1533 MIM.Selector = function (name)
1534 {
1535   this.val = name;
1536 }
1537 MIM.Selector.prototype = new Xex.Term ('selector');
1538
1539 (function () {
1540   var selectors = {};
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 ('@]');
1550
1551   MIM.Selector.prototype.Parser = function (domain, node)
1552   {
1553     var name = node.firstChild.nodeValue;
1554     var s = selectors[name];
1555     if (! s)
1556       throw new Xex.ErrTerm (MIM.Error.ParseError,
1557                              "Invalid selector: " + name);
1558     return s;
1559   }
1560 }) ();
1561
1562 MIM.Rule = function (keyseq, actions)
1563 {
1564   this.keyseq = keyseq;
1565   this.actions = actions;
1566 }
1567 MIM.Rule.prototype = new Xex.Term ('rule');
1568 MIM.Rule.prototype.Parser = function (domain, node)
1569 {
1570   var n;
1571   for (n = node.firstChild; n && n.nodeType != 1; n = n.nextSibling);
1572   if (! n)
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);
1579 }
1580 MIM.Rule.prototype.toString = function ()
1581 {
1582   return '<rule/>';
1583 }
1584
1585 MIM.Map = function (name)
1586 {
1587   this.name = name;
1588   this.rules = new Array ();
1589 };
1590
1591 (function () {
1592   var proto = new Xex.Term ('map');
1593
1594   proto.Parser = function (domain, node)
1595   {
1596     var name = node.attributes['mname'].nodeValue;
1597     if (! name)
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));
1603     return map;
1604   }
1605
1606   proto.toString = function ()
1607   {
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>';
1613   }
1614
1615   MIM.Map.prototype = proto;
1616 }) ();
1617
1618 Xex.CatchTag._mimtag = new Xex.SymTerm ('@mimtag');
1619
1620 MIM.Action = function (domain, terms)
1621 {
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);
1627 }
1628
1629 MIM.Action.prototype.Run = function (domain)
1630 {
1631   var result = this.action.Eval (domain);
1632   if (result.type == 'error')
1633     {
1634       domain.context.Error = result.toString ();
1635       return false;
1636     }
1637   return (result != Xex.CatchTag._mimtag);
1638 }
1639
1640 MIM.Keymap = function ()
1641 {
1642   this.name = 'TOP';
1643   this.submaps = null;
1644 };
1645
1646 (function () {
1647   var proto = {};
1648
1649   function add_rule (keymap, rule, branch_actions)
1650   {
1651     var keyseq = rule.keyseq;
1652     var len = keyseq.val.length;
1653     var name = '';
1654
1655     for (var i = 0; i < len; i++)
1656       {
1657         var key = keyseq.val[i];
1658         var sub = false;
1659
1660         name += key.key;
1661         if (! keymap.submaps)
1662           keymap.submaps = {};
1663         else
1664           sub = keymap.submaps[key.key];
1665         if (! sub)
1666           keymap.submaps[key.key] = sub = new MIM.Keymap ();
1667         keymap = sub;
1668         keymap.name = name;
1669       }
1670     keymap.map_actions = rule.actions;
1671     keymap.branch_actions = branch_actions;
1672   }
1673
1674   proto.Add = function (map, branch_actions)
1675   {
1676     var rules = map.rules;
1677     var len = rules.length;
1678
1679     for (var i = 0; i < len; i++)
1680       add_rule (this, rules[i], branch_actions);
1681   }
1682   proto.Lookup = function (keys, index)
1683   {
1684     var sub;
1685
1686     if (index < keys.val.length && this.submaps
1687         && (sub = this.submaps[keys.val[index].key]))
1688       {
1689         index++;
1690         return sub.Lookup (keys, index);
1691       }
1692     return { map: this, index: index };
1693   }
1694
1695   MIM.Keymap.prototype = proto;
1696 }) ();
1697
1698 MIM.State = function (name)
1699 {
1700   this.name = name;
1701   this.keymap = new MIM.Keymap ();
1702 };
1703
1704 (function () {
1705   var proto = new Xex.Term ('state');
1706
1707   proto.Parser = function (domain, node)
1708   {
1709     var map_list = domain.map_list;
1710     var name = node.attributes['sname'].nodeValue;
1711     if (! name)
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 ())
1715       {
1716         if (node.nodeName == 'title')
1717           state.title = node.firstChild.nodeValue;
1718         else
1719           {
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);
1728           }
1729       }
1730     return state;
1731   }
1732
1733   proto.toString = function ()
1734   {
1735     return '<state sname="' + this.name + '">' + this.keymap + '</state>';
1736   }
1737
1738   MIM.State.prototype = proto;
1739 }) ();
1740
1741 (function () {
1742   function Block (index, term)
1743   {
1744     this.Index = index;
1745     if (term.IsStr)
1746       this.Data = term.val;
1747     else if (term.IsList)
1748       {
1749         this.Data = new Array ();
1750         for (var i = 0; i < term.val.length; i++)
1751           this.Data.push (term.val[i].val);
1752       }
1753   }
1754
1755   Block.prototype.Count = function () { return this.Data.length; }
1756   Block.prototype.get = function (i)
1757   {
1758     return (this.Data instanceof Array ? this.Data[i] : this.Data.charAt (i));
1759   }
1760
1761   MIM.Candidates = function (candidates, column)
1762   {
1763     this.column = column;
1764     this.row = 0;
1765     this.index = 0;
1766     this.total = 0;
1767     this.blocks = new Array ();
1768
1769     for (var i = 0; i < candidates.length; i++)
1770       {
1771         var block = new Block (this.total, candidates[i]);
1772         this.blocks.push (block);
1773         this.total += block.Count ();
1774       }
1775   }
1776
1777   function get_col ()
1778   {
1779     return (this.column > 0 ? this.index % this.column
1780             : this.index - this.blocks[this.row].Index);
1781   }
1782
1783   function prev_group ()
1784   {
1785     var col = get_col.call (this);
1786     var nitems;
1787     if (this.column > 0)
1788       {
1789         this.index -= this.column;
1790         if (this.index >= 0)
1791           nitems = this.column;
1792         else
1793           {
1794             var lastcol = (this.total - 1) % this.column;
1795             this.index = (col < lastcol ? this.total - lastcol + col
1796                           : this.total - 1);
1797             this.row = this.blocks.length - 1;
1798             nitems = lastcol + 1;
1799           }
1800         while (this.blocks[this.row].Index > this.index)
1801           this.row--;
1802       }
1803     else
1804       {
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));
1809       }
1810     return nitems;
1811   }
1812
1813   function next_group ()
1814   {
1815     var col = get_col.call (this);
1816     var nitems;
1817     if (this.column > 0)
1818       {
1819         this.index += this.column - col;
1820         if (this.index < this.total)
1821           {
1822             if (this.index + col >= this.total)
1823               {
1824                 nitems = this.total - this.index;
1825                 this.index = this.total - 1;
1826               }
1827             else
1828               {
1829                 nitems = this.column;
1830                 this.index += col;
1831               }
1832           }
1833         else
1834           {
1835             this.index = col;
1836             this.row = 0;
1837           }
1838         while (this.blocks[this.row].Index > this.index)
1839           this.row++;
1840       }
1841     else
1842       {
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));
1847       }
1848     return nitems;
1849   }
1850
1851   function prev ()
1852   {
1853     if (this.index == 0)
1854       {
1855         this.index = this.total - 1;
1856         this.row = this.blocks.length - 1;
1857       }
1858     else
1859       {
1860         this.index--;
1861         if (this.blocks[this.row].Index > this.index)
1862           this.row--;
1863       }
1864     }
1865
1866   function next ()
1867   {
1868     this.index++;
1869     if (this.index == this.total)
1870       {
1871         this.index = 0;
1872         this.row = 0;
1873       }
1874     else
1875       {
1876         var b = this.blocks[this.row];
1877         if (this.index == b.Index + b.Count ())
1878           this.row++;
1879       }
1880   }
1881
1882   function first ()
1883   {
1884     this.index -= get_col.call (this);
1885     while (this.blocks[this.row].Index > this.index)
1886       this.row--;
1887   }
1888
1889   function last ()
1890   {
1891     var b = this.blocks[this.row];
1892     if (this.column > 0)
1893       {
1894         if (this.index + 1 < this.total)
1895           {
1896             this.index += this.column - get_col.call (this) + 1;
1897             while (b.Index + b.Count () <= this.index)
1898               b = this.blocks[++this.row];
1899           }
1900       }
1901     else
1902       this.index = b.Index + b.Count () - 1;
1903   }
1904
1905   MIM.Candidates.prototype.Current = function ()
1906   {
1907     var b = this.blocks[this.row];
1908     return b.get (this.index - b.Index);
1909   }
1910
1911   MIM.Candidates.prototype.Select = function (selector)
1912   {
1913     if (selector.type == 'selector')
1914       {
1915         switch (selector.val)
1916           {
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;
1923           default: break;
1924           }
1925         return this.Current ();
1926       }
1927     var col, start, end
1928     if (this.column > 0)
1929       {
1930         col = this.index % this.column;
1931         start = this.index - col;
1932         end = start + this.column;
1933       }
1934     else
1935       {
1936         start = this.blocks[this.row].Index;
1937         col = this.index - start;
1938         end = start + this.blocks[this.row].Count;
1939       }
1940     if (end > this.total)
1941       end = this.total;
1942     this.index += selector.val - col;
1943     if (this.index >= end)
1944       this.index = end - 1;
1945     if (this.column > 0)
1946       {
1947         if (selector.val > col)
1948           while (this.blocks[this.row].Index + this.blocks[this.row].Count
1949                  < this.index)
1950             this.row++;
1951         else
1952           while (this.blocks[this.row].Index > this.index)
1953             this.row--;
1954       }
1955     return this.Current ();
1956   }
1957 }) ();
1958
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);
1966
1967 (function () {
1968   var im_domain = MIM.im_domain;
1969
1970   function Finsert (domain, vari, args)
1971   {
1972     var text;
1973     if (args[0].type == 'integer')
1974       text = String.fromCharCode (args[0].val);
1975     else
1976       text = args[0].val;
1977     domain.context.insert (text, null);
1978     return args[0];
1979   }
1980
1981   function Finsert_candidates (domain, vari, args)
1982   {
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);
1987     return args[0];
1988   }
1989
1990   function Fdelete (domain, vari, args)
1991   {
1992     var ic = domain.context;
1993     var pos = args[0].IsInt ? args[0].Intval : args[0].Position (ic);
1994     ic.del (pos);
1995     return new Xex.Term (ic.del (pos));
1996   }
1997
1998   function Fselect (domain, vari, args)
1999   {
2000     var ic = domain.context;
2001     var can = ic.candidates;
2002
2003     if (can)
2004       {
2005         var candidate = can.Current ();
2006
2007         ic.del (ic.cursor_pos - candidate.length);
2008         candidate = can.Select (args[0]);
2009         ic.insert (candidate, can);
2010       }
2011     return args[0];
2012   }
2013
2014   function Fchar_at (domain, vari, args)
2015   {
2016     return new Xex.IntTerm (args[0].CharAt (domain.context));
2017   }
2018
2019   function Fmove (domain, vari, args)
2020   {
2021     var ic = domain.context;
2022     var pos = args[0].IsInt ? args[0].val : args[0].Position (ic);
2023     ic.move (pos);
2024     return args[0];
2025   }
2026
2027   function Fmark (domain, vari, args)
2028   {
2029     args[0].Mark (domain.context);
2030     return args[0];
2031   }
2032
2033   function Fpushback (domain, vari, args)
2034   {
2035     var arg = (args[0].IsInt ? args[0].Intval
2036                : args[0].IsStr ? new KeySeq (args[0])
2037                : args[0]);
2038     domain.context.pushback (arg)
2039     return args[0];
2040   }
2041
2042   function Fundo  (domain, vari, args)
2043   {
2044     var ic = domain.context;
2045     var n = args.length == 0 ? -2 : args[0].val;
2046     if (n < 0)
2047       ic.keys.val.splice (ic.keys.length + n, -n);
2048     else
2049       ic.keys.val.splice (n, ic.keys.length);
2050     ic.reset ();
2051     return Xex.nil;
2052   }
2053
2054   function Fcommit (domain, vari, args)
2055   {
2056     domain.context.commit ();
2057     return Xex.nil;
2058   }
2059
2060   function Funhandle (domain, vari, args)
2061     {
2062       domain.context.commit ();
2063       return Xex.Fthrow (domain, vari, Xex.CatchTag._mimtag);
2064     }
2065
2066   function Fshift (domain, vari, args)
2067   {
2068     var ic = domain.context;
2069     var state_name = args[0].val;
2070     var state = ic.im.state_list[state_name];
2071     if (! state)
2072       throw ("Unknown state: " + state_name);
2073       ic.shift (state);
2074     return args[0];
2075   }
2076
2077   function Fsurrounding_flag (domain, vari, args)
2078   {
2079     return new Xex.IntTerm (-1);
2080   }
2081
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);
2100 }) ();
2101
2102
2103 (function () {
2104   function get_global_var (vname)
2105   {
2106     if (MIM.im_global.load_status == MIM.LoadStatus.NotLoaded)
2107       MIM.im_global.Load ()
2108     return MIM.im_global.domain.variables[vname];
2109   }
2110
2111   function include (node)
2112   {
2113     node = node.firstElement ();
2114     if (node.nodeName != 'tags')
2115       return null;
2116     
2117     var lang = null, name = null, extra = null;
2118     for (node = node.firstElement (); node; node = node.nextElement ())
2119       {
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;
2126       }
2127     if (! lang || ! MIM.imlist[lang])
2128       return null;
2129     if (! extra)
2130       {
2131         if (! name || ! (im = MIM.imlist[lang][name]))
2132           return null;
2133       }
2134     else
2135       {
2136         if (! (im = MIM.imextra[lang][extra]))
2137           return null;
2138       }
2139     if (im.load_status != MIM.LoadStatus.Loaded
2140         && (im.load_status != MIM.LoadStatus.NotLoaded || ! im.Load ()))
2141       return null;
2142     return im;
2143   }
2144
2145   var parsers = { };
2146
2147   parsers['description'] = function (node)
2148   {
2149     this.description = node.firstChild.nodeValue;
2150   }
2151   parsers['variable-list'] = function (node)
2152   {
2153     for (node = node.firstElement (); node; node = node.nextElement ())
2154       {
2155         var vname = node.attributes['vname'].nodeValue;
2156         if (this != MIM.im_global)
2157           {
2158             var vari = get_global_var (vname);
2159             if (vari != null)
2160               this.domain.Defvar (vname);
2161           }
2162         vname = Xex.Term.Parse (this.domain, node)
2163       }
2164   }
2165   parsers['command-list'] = function (node)
2166   {
2167   }
2168   parsers['macro-list'] = function (node)
2169   {
2170     for (var n = node.firstElement (); n; n = n.nextElement ())
2171       if (n.nodeName == 'xi:include')
2172         {
2173           var im = include (n);
2174           if (! im)
2175             alert ('inclusion fail');
2176           else
2177             for (var macro in im.domain.functions)
2178               {
2179                 var func = im.domain.functions[macro];
2180                 if (func instanceof Xex.Macro)
2181                   im.domain.CopyFunc (this.domain, macro);
2182               }
2183           n = n.previousSibling;
2184           node.removeChild (n.nextSibling);
2185         }
2186     Xex.Term.Parse (this.domain, node.firstElement (), null);
2187   }
2188   parsers['title'] = function (node)
2189   {
2190     this.title = node.firstChild.nodeValue;
2191   }
2192   parsers['map-list'] = function (node)
2193   {
2194     for (node = node.firstElement (); node; node = node.nextElement ())
2195       {
2196         if (node.nodeName == 'xi:include')
2197           {
2198             var im = include (node);
2199             if (! im)
2200               {
2201                 alert ('inclusion fail');
2202                 continue;
2203               }
2204             for (var mapname in im.map_list)
2205               this.map_list[mapname] = im.map_list[mapname];
2206           }
2207         else
2208           {
2209             var map = Xex.Term.Parse (this.domain, node);
2210             this.map_list[map.name] = map;
2211           }
2212       }
2213   }
2214   parsers['state-list'] = function (node)
2215   {
2216     this.domain.map_list = this.map_list;
2217     for (node = node.firstElement (); node; node = node.nextElement ())
2218       {
2219         if (node.nodeName == 'state')
2220           {
2221             var state = Xex.Term.Parse (this.domain, node);
2222             if (! state.title)
2223               state.title = this.title;
2224             if (! this.initial_state)
2225               this.initial_state = state;
2226             this.state_list[state.name] = state;
2227           }
2228       }
2229     delete this.domain.map_list;
2230   }
2231
2232   MIM.IM = function (lang, name, extra_id, file)
2233   {
2234     this.lang = lang;
2235     this.name = name;
2236     this.extra_id = extra_id;
2237     this.file = file;
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);
2243   }
2244
2245   var proto = {
2246     Load: function ()
2247     {
2248       var node = Xex.Load (null, this.file);
2249       if (! node)
2250         {
2251           this.load_status = MIM.LoadStatus.Error;
2252           return false;
2253         }
2254       this.map_list = {};
2255       this.initial_state = null;
2256       this.state_list = {};
2257       for (node = node.firstElement (); node; node = node.nextElement ())
2258         {
2259           var name = node.nodeName;
2260           var parser = parsers[name];
2261           if (parser)
2262             parser.call (this, node);
2263         }
2264       this.load_status = MIM.LoadStatus.Loaded;
2265       return true;
2266     }
2267   }
2268
2269   MIM.IM.prototype = proto;
2270
2271   MIM.IC = function (im, target)
2272   {
2273     if (im.load_status == MIM.LoadStatus.NotLoaded)
2274       im.Load ();
2275     if (im.load_status != MIM.LoadStatus.Loaded)
2276       alert ('im:' + im.name + ' error:' + im.load_status);
2277     this.im = im;
2278     this.target = target;
2279     this.domain = new Xex.Domain ('context', im.domain, this);
2280     this.active = true;
2281     this.spot = 0;
2282     this.reset ();
2283   }
2284
2285   MIM.CandidateTable = function ()
2286   {
2287     this.table = new Array ();
2288   }
2289
2290   MIM.CandidateTable.prototype.get = function (from)
2291   {
2292     for (var i = 0; i < this.table.length; i++)
2293       {
2294         var elt = this.table[i];
2295         if (elt.from <= from && elt.to > from)
2296           return elt.val;
2297       }
2298   }
2299
2300   MIM.CandidateTable.prototype.put = function (from, to, candidates)
2301   {
2302     for (var i = 0; i < this.table.length; i++)
2303       {
2304         var elt = this.table[i];
2305         if (elt.from >= from && elt.from < to
2306             || elt.to >= from && elt.to < to)
2307           {
2308             elt.from = from;
2309             elt.to = to;
2310             elt.val = candidates;
2311             return;
2312           }
2313       }
2314     this.table.push ({ from: from, to: to, val: candidates });
2315   }
2316
2317   MIM.CandidateTable.prototype.adjust = function (from, to, inserted)
2318   {
2319     var diff = inserted - (to - from);
2320     for (var i = 0; i < this.table.length; i++)
2321       {
2322         var elt = this.table[i];
2323         if (elt.from >= to)
2324           {
2325             elt.from += diff;
2326             elt.to += diff;
2327           }
2328       }
2329   }
2330
2331   MIM.CandidateTable.prototype.clear = function ()
2332   {
2333     this.table.length = 0;
2334   }
2335
2336   function detach_candidates (ic)
2337   {
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);
2344   }
2345
2346   function set_cursor (prefix, pos)
2347   {
2348     this.cursor_pos = pos;
2349     if (pos > 0)
2350       this.candidates = this.candidate_table.get (pos - 1);
2351     else
2352       this.candidates = null;
2353   }
2354
2355   function save_state ()
2356   {
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;
2361   }
2362
2363   function restore_state ()
2364   {
2365     this.domain.RestoreValues (this.state_var_values);
2366     this.preedit = this.state_preedit;
2367     set_cursor.call (this, "restore", this.state_pos);
2368   }
2369
2370   function handle_key ()
2371   {
2372     var out = this.keymap.Lookup (this.keys, this.key_head);
2373     var sub = out.map;
2374
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)
2379       {
2380
2381         restore_state.call (this);
2382         this.keymap = sub;
2383         Xex.Log ('submap found');
2384         if (this.keymap.map_actions)
2385           {
2386             Xex.Log ('taking map actions:');
2387             if (! this.take_actions (this.keymap.map_actions))
2388               return false;
2389           }
2390         else if (this.keymap.submaps)
2391           {
2392             Xex.Log ('no map actions');
2393             for (var i = this.state_key_head; i < this.key_head; i++)
2394               {
2395                 Xex.Log ('inserting key:' + this.keys.val[i].key);
2396                 this.insert (this.keys.val[i].key, null);
2397               }
2398           }
2399         if (! this.keymap.submaps)
2400           {
2401             Xex.Log ('terminal:');
2402             if (this.keymap.branch_actions != null)
2403               {
2404                 Xex.Log ('branch actions:');
2405                 if (! this.take_actions (this.keymap.branch_actions))
2406                   return false;
2407               }
2408             if (this.keymap != this.state.keymap)
2409               this.shift (this.state);
2410           }
2411       }
2412     else
2413       {
2414         Xex.Log ('no submap');
2415         var current_state = this.state;
2416         var map = this.keymap;
2417
2418         if (map.branch_actions)
2419           {
2420             Xex.Log ('branch actions');
2421             if (! this.take_actions (map.branch_actions))
2422               return false;
2423           }
2424
2425         if (map == this.keymap)
2426           {
2427             Xex.Log ('no state change');
2428             if (map == this.initial_state.keymap
2429                 && this.key_head < this.keys.val.length)
2430               {
2431                 Xex.Log ('unhandled');
2432                 return false;
2433               }
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);
2438           }
2439       }
2440     return true;
2441   }
2442
2443   proto = {
2444     reset: function ()
2445     {
2446       this.produced = null;
2447       this.preedit = '';
2448       this.preedit_saved = '';
2449       this.cursor_pos = 0;
2450       this.marker_positions = {};
2451       this.candidates = null;
2452       this.candidate_show = false;
2453       this.state = null;
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 = {};
2460       this.state_pos = 0;
2461       this.keymap = null;
2462       this.keys = new MIM.KeySeq ();
2463       this.key_head = 0;
2464       this.key_unhandled = false;
2465       this.unhandled_key = null;
2466       this.changed = MIM.ChangedStatus.None;
2467       this.error_message = '';
2468       this.title = this.initial_state.title;
2469       this.produced = '';
2470       this.preedit = '';
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);
2477     },
2478
2479     catch_args: new Array (Xex.CatchTag._mimtag, null),
2480
2481     take_actions: function (actions)
2482     {
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');
2489     },
2490
2491     GetSurroundingChar: function (pos)
2492     {
2493       pos += this.spot;
2494       if (pos < 0 || pos >= this.target.value.length)
2495         return 0;
2496       return this.target.value.charCodeAt (pos);
2497     },
2498     
2499     adjust_markers: function (from, to, inserted)
2500     {
2501       var diff = inserted - (to - from);
2502
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)
2511     },
2512
2513     preedit_replace: function (from, to, text, candidates)
2514     {
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);
2519       if (candidates)
2520         this.candidate_table.put (from, from + text.length, candidates)
2521     },
2522
2523     insert: function (text, candidates)
2524     {
2525       this.preedit_replace (this.cursor_pos, this.cursor_pos, text, candidates);
2526       this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2527     },
2528
2529     del: function (pos)
2530     {
2531       var deleted = pos - this.cursor_pos;
2532       if (pos < 0)
2533         {
2534           this.DelSurroundText (pos);
2535           pos = 0;
2536         }
2537       else if (pos > this.preedit.length)
2538         {
2539           this.DelSurroundText (pos - this.preedit.length);
2540           pos = this.preedit.length;
2541         }
2542       if  (pos < this.cursor_pos)
2543         this.preedit = (this.preedit.substring (0, pos)
2544                         + this.preedit.substring (this.cursor_pos));
2545       else
2546         this.preedit = (this.preedit.substring (0, this.cursor_pos)
2547                         + this.predit.substring (pos));
2548       return deleted;
2549     },
2550
2551     show: function ()
2552     {
2553       this.candidate_show = true;
2554       this.changed |= MIM.ChangedStatus.CandidateShow;
2555     },
2556
2557     hide: function ()
2558     {
2559       this.candidate_show = false;
2560       this.changed |= MIM.ChangedStatus.CandidateShow;
2561     },
2562
2563     move: function (pos)
2564     {
2565       if (pos < 0)
2566         pos = 0;
2567       else if (pos > this.preedit.length)
2568         pos = this.preedit.length;
2569       if (pos != this.cursor_pos)
2570         {
2571           set_cursor.call (this, 'move', pos);
2572           this.changed |= MIM.ChangedStatus.Preedit;
2573         }
2574     },
2575
2576     pushback: function (n)
2577     {
2578       if (n instanceof MIM.KeySeq)
2579         {
2580           if (this.key_head > 0)
2581             this.key_head--;
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]);
2587           return;
2588         }
2589       if (n > 0)
2590         {
2591           this.key_head -= n;
2592           if (this.key_head < 0)
2593             this.key_head = 0;
2594         }
2595       else if (n == 0)
2596         this.key_head = 0;
2597       else
2598       {
2599         this.key_head = - n;
2600         if (this.key_head > this.keys.val.length)
2601           this.key_head = this.keys.val.length;
2602       }
2603     },
2604
2605     pop: function ()
2606     {
2607       if (this.key_head < this.keys.val.length)
2608         this.keys.val.splice (this.key_head, 1);
2609     },
2610
2611     commit: function ()
2612     {
2613       if (this.preedit.length > 0)
2614       {
2615         this.candidate_table.clear ();
2616         this.produced += this.preedit;
2617         this.preedit_replace.call (this, 0, this.preedit.length, '', null);
2618       }
2619     },
2620
2621     shift: function (state)
2622     {
2623       if (state == null)
2624         {
2625           if (this.prev_state == null)
2626             return;
2627           state = this.prev_state;
2628         }
2629
2630       if (state == this.initial_state)
2631         {
2632           if (this.state)
2633             {
2634               this.commit ();
2635               this.keys.val.splice (0, this.key_head);
2636               this.key_head = 0;
2637               this.prev_state = null;
2638             }
2639         }
2640       else
2641         {
2642           if (state != this.state)
2643             this.prev_state = this.state;
2644         }
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;
2649       this.state = state;
2650       this.keymap = state.keymap;
2651       this.state_key_head = this.key_head;
2652       save_state.call (this);
2653     },
2654
2655     Filter: function (key)
2656     {
2657       if (! this.active)
2658         {
2659           this.key_unhandled = true;
2660           this.unhandled_key = key;
2661           return false;
2662         }
2663       if (key.key == '_reload')
2664         return true;
2665       this.changed = MIM.ChangedStatus.None;
2666       this.produced = '';
2667       this.key_unhandled = false;
2668       this.keys.val.push (key);
2669       var count = 0;
2670       while (this.key_head < this.keys.val.length)
2671         {
2672           if (! handle_key.call (this))
2673             {
2674               if (this.key_head < this.keys.val.length)
2675                 {
2676                   this.unhandled_key = this.keys.val[this.key_head];
2677                   this.keys.val.splice (this.key_head, this.key_head + 1);
2678                 }
2679               this.key_unhandled = true;
2680               break;
2681             }
2682           if (++count == 10)
2683             {
2684               this.reset ();
2685               this.key_unhandled = true;
2686               break;
2687             }
2688         }
2689       if (this.key_unhandled)
2690         {
2691           this.keys.val.length = 0;
2692           this.key_head = this.state_key_head = this.commit_key_head = 0;
2693         }
2694       return (! this.key_unhandled
2695               && this.produced.length == 0
2696               && this.preedit.length == 0);
2697     }
2698   }
2699
2700   MIM.IC.prototype = proto;
2701
2702   var node = Xex.Load (null, "imlist.xml");
2703   for (node = node.firstChild; node; node = node.nextSibling)
2704     if (node.nodeName == 'input-method')
2705       {
2706         var lang = null, name = null, extra_id = null, file = null;
2707
2708         for (var n = node.firstChild; n; n = n.nextSibling)
2709           {
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;
2718           }
2719         if (name && name != 'nil')
2720           {
2721             if (! MIM.imlist[lang])
2722               MIM.imlist[lang] = {};
2723             MIM.imlist[lang][name] = new MIM.IM (lang, name, extra_id, file);
2724           }
2725         else if (extra_id && extra_id != 'nil')
2726           {
2727             if (! MIM.imextra[lang])
2728               MIM.imextra[lang] = {};
2729             MIM.imextra[lang][extra_id] = new MIM.IM (lang, name, extra_id, file);
2730           }
2731       }
2732   if (MIM.imextra.t && MIM.imextra.t.global)
2733     MIM.im_global = MIM.imextra.t.global;
2734   else
2735     {
2736       MIM.im_global = new MIM.IM ('t', 'nil', 'global', null);
2737       MIM.im_global.load_status = MIM.LoadStatus.Error;
2738     }
2739   node = undefined;
2740 }) ();
2741
2742 (function () {
2743   var keys = new Array ();
2744   keys[0x09] = 'tab';
2745   keys[0x08] = 'backspace';
2746   keys[0x0D] = 'return';
2747   keys[0x1B] = 'escape';
2748   keys[0x20] = 'space';
2749   keys[0x21] = 'pageup';
2750   keys[0x22] = 'pagedown';
2751   keys[0x23] = 'end';
2752   keys[0x24] = 'home';
2753   keys[0x25] = 'left';
2754   keys[0x26] = 'up';
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";
2763
2764   MIM.decode_key_event = function (event)
2765   {
2766     var key = ((event.type == 'keydown' || event.keyCode) ? event.keyCode
2767                : event.charCode ? event.charCode
2768                : false);
2769     if (! key)
2770       return false;
2771     if (event.type == 'keydown')
2772       {
2773         key = keys[key];
2774         if (! key)
2775           return false;
2776         if (event.shiftKey) key = "S-" + key ;
2777       }
2778     else
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);
2783   }
2784 }) ();
2785
2786 MIM.add_event_listener
2787   = (window.addEventListener
2788      ? function (target, type, listener) {
2789        target.addEventListener (type, listener, false);
2790      }
2791      : window.attachEvent
2792      ? function (target, type, listener) {
2793        target.attachEvent ('on' + type,
2794                            function() {
2795                              listener.call (target, window.event);
2796                            });
2797      }
2798      : function (target, type, listener) {
2799        target['on' + type]
2800          = function (e) { listener.call (target, e || window.event); };
2801      });
2802
2803 MIM.debug_print = function (event, ic)
2804 {
2805   if (! MIM.debug)
2806     return;
2807   if (! MIM.debug_nodes)
2808     {
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');
2818     }
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);
2823   var index;
2824
2825   MIM.debug_nodes[event.type].innerHTML = "" + code + "/" + ch + " : " + key;
2826   index = (event.type == 'keydown' ? '0' : '1');
2827   if (ic)
2828     MIM.debug_nodes['status' + index].innerHTML = ic.im.load_status;
2829   else
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;
2833 };
2834
2835 MIM.get_range = function (target, range)
2836 {
2837   if (target.selectionStart != null) // for Mozilla
2838     {
2839       range[0] = target.selectionStart;
2840       range[1] = target.selectionEnd;
2841     }
2842   else                          // for IE
2843     {
2844       var r = document.selection.createRange ();
2845       var rr = r.duplicate ();
2846
2847       rr.moveToElementText (target);
2848       rr.setEndPoint ('EndToEnd', range);
2849       range[0] = rr.text.length - r.text.length;
2850       range[1] = rr.text.length;
2851     }
2852 }
2853
2854 MIM.set_caret = function (target, ic)
2855 {
2856   if (target.setSelectionRange) // Mozilla
2857     {
2858       var scrollTop = target.scrollTop;
2859       target.setSelectionRange (ic.spot, ic.spot + ic.preedit.length);
2860       target.scrollTop = scrollTop;
2861     }
2862   else                          // IE
2863     {
2864       var range = target.createTextRange ();
2865       range.moveStart ('character', ic.spot);
2866       range.moveEnd ('character', ic.spot + ic.preedit.length);
2867       range.select ();
2868     }
2869 };
2870
2871 (function () {
2872   var range = new Array ();
2873
2874   MIM.check_range = function (target, ic)
2875   {
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)
2879       {
2880         Xex.Log ('reset:' + ic.spot + '-' + (ic.spot + ic.preedit.length)
2881                  + '/' + range[0] + '-' + range[1]);
2882         ic.reset ();
2883       }
2884     target.value = (target.value.substring (0, range[0])
2885                     + target.value.substring (range[1]));
2886     ic.spot = range[0];
2887   }
2888 }) ();
2889
2890 MIM.update = function (target, ic)
2891 {
2892   var text = target.value;
2893   target.value = (text.substring (0, ic.spot)
2894                   + ic.produced
2895                   + ic.preedit
2896                   + text.substring (ic.spot));
2897   ic.spot += ic.produced.length;
2898   MIM.set_caret (target, ic);
2899 };
2900
2901 MIM.reset_ic = function (event)
2902 {
2903   if (event.target.mim_ic)
2904     {
2905       var ic = event.target.mim_ic;
2906       var pos = ic.spot + ic.preedit.length;
2907       ic.reset ();
2908       if (pos > ic.spot)
2909         event.target.setSelectionRange (pos, pos);
2910     }
2911 };
2912
2913 MIM.keydown = function (event)
2914 {
2915   var target = event.target;
2916   if (target.id == 'log')
2917     return;
2918   if (! (target.type == "text" || target.type == "textarea"))
2919     return;
2920
2921   var ic = target.mim_ic;
2922   if (! ic || ic.im != MIM.current)
2923     {
2924       Xex.Log ('creating IC');
2925       ic = new MIM.IC (MIM.current, target);
2926       target.mim_ic = ic;
2927       MIM.add_event_listener (target, 'blur', MIM.reset_ic);
2928     }
2929   if (ic.im.load_status != MIM.LoadStatus.Loaded)
2930     return;
2931   MIM.check_range (target, ic);
2932   MIM.debug_print (event, ic);
2933   ic.key = MIM.decode_key_event (event);
2934 };
2935
2936 MIM.keypress = function (event)
2937 {
2938   var target = event.target;
2939   if (target.id == 'log')
2940     return;
2941   if (! (target.type == "text" || target.type == "textarea"))
2942     return;
2943
2944   var ic = target.mim_ic;
2945   var i;
2946
2947   try {
2948     if (ic.im.load_status != MIM.LoadStatus.Loaded)
2949       return;
2950     if (! ic.key)
2951       ic.key = MIM.decode_key_event (event);
2952     if (! ic.key)
2953       {
2954         ic.reset ();
2955         return;
2956       }
2957     
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 ();
2963   } finally {
2964     MIM.debug_print (event, ic);
2965   }
2966   return;
2967 };
2968
2969 MIM.select_im = function (event)
2970 {
2971   var target = event.target.parentNode;
2972   while (target.tagName != "SELECT")
2973     target = target.parentNode;
2974   var idx = 0;
2975   var im = false;
2976   for (var lang in MIM.imlist)
2977     for (var name in MIM.imlist[lang])
2978       if (idx++ == target.selectedIndex)
2979         {
2980           im = MIM.imlist[lang][name];
2981           break;
2982         }
2983   document.getElementsByTagName ('body')[0].removeChild (target);
2984   target.target.focus ();
2985   if (im && im != MIM.current)
2986     {
2987       MIM.current = im;
2988       Xex.Log ('select IM: ' + im.name);
2989     }
2990 };
2991
2992 MIM.destroy_menu = function (event)
2993 {
2994   if (event.target.tagName == "SELECT")
2995     document.getElementsByTagName ('body')[0].removeChild (event.target);
2996 };
2997
2998 MIM.select_menu = function (event)
2999 {
3000   var target = event.target;
3001
3002   if (! ((target.type == "text" || target.type == "textarea")
3003          && event.which == 1 && event.ctrlKey))
3004     return;
3005
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;
3013   var idx = 0;
3014   for (var lang in MIM.imlist)
3015     for (var name in MIM.imlist[lang])
3016       {
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;
3024         idx++;
3025       }
3026   sel.size = idx;
3027   document.getElementsByTagName ('body')[0].appendChild (sel);
3028 };
3029
3030 MIM.test = function ()
3031 {
3032   var im = MIM.imlist['t']['latn-post'];
3033   var ic = new MIM.IC (im, null);
3034
3035   ic.Filter (new MIM.Key ('a'));
3036   ic.Filter (new MIM.Key ("'"));
3037
3038   if (true)
3039     document.getElementById ('text').value = ic.produced + ic.preedit;
3040   else {
3041     try {
3042       document.getElementById ('text').value
3043         = Xex.Term.Parse (domain, body).Eval (domain).toString ();
3044     } catch (e) {
3045       if (e instanceof Xex.ErrTerm)
3046         alert (e);
3047       throw e;
3048     }
3049   }
3050 }
3051
3052
3053 MIM.init = function ()
3054 {
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'];
3061 };
3062
3063 MIM.init_debug = function ()
3064 {
3065   MIM.debug = true;
3066   Xex.LogNode = document.getElementById ('log');
3067   MIM.init ();
3068 };