*** 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     if (! arg)
10       Xex.LogNode.value = '';
11     else
12       {
13         var str = '';
14         if (indent != undefined)
15           for (var i = 0; i <= indent; i++)
16             str += '  ';
17         Xex.LogNode.value = str + arg + "\n" + Xex.LogNode.value;
18       }
19   }
20 };
21
22 Xex.Error = {
23   UnknownError: "unknown-error",
24   WrongArgument: "wrong-argument",
25   // Load time errors.
26   InvalidInteger: "invalid-integer",
27   TermTypeInvalid: "term-type-invalid",
28   FunctionConflict: "function-conflict",
29   VariableTypeConflict: "variable-type-conflict",
30   VariableRangeConflict: "variable-range-conflict",
31   VariableWrongRange: "variable-wrong-range",
32   VariableWrongValue: "variable-wrong-value",
33
34   UnknownFunction: "unknown-function",
35   MacroExpansionError: "macro-expansion-error",
36   NoVariableName: "no-variable-name",
37   NoFunctionName: "no-funcion-name",
38
39   // Run time errors.
40   ArithmeticError: "arithmetic-error",
41   WrongType: "wrong-type",
42   IndexOutOfRange: "index-out-of-range",
43   ValueOutOfRange: "value-out-of-range",
44   NoLoopToBreak: "no-loop-to-break",
45   UncaughtThrow: "uncaught-throw"
46 };
47
48 Xex.Variable = function (domain, name, desc, val, range)
49 {
50   this.domain = domain;
51   this.name = name;
52   this.desc = desc;
53   this.val = val;
54   this.range = range;
55 }
56
57 Xex.Variable.prototype.clone = function ()
58 {
59   return new Xex.Variable (this.domain, this.name, this.desc,
60                            this.val, this.range);
61 }
62     
63 Xex.Variable.prototype.Equals = function (obj)
64 {
65   return ((obj instanceof Xex.Variable)
66           && obj.name == this.name);
67 }
68
69 Xex.Variable.prototype.SetValue = function (term)
70 {
71   this.val = term;
72   return term;
73 }
74
75 Xex.Function = function (name, with_var, min_args, max_args)
76 {
77   this.name = name;
78   this.with_var = with_var;
79   this.min_args = min_args;
80   this.max_args = max_args;
81 };  
82
83 Xex.Subrountine = function (builtin, name, with_var, min_args, max_args)
84 {
85   this.name = name;
86   this.with_var = with_var;
87   this.min_args = min_args;
88   this.max_args = max_args;
89   this.builtin = builtin;
90 }
91
92 Xex.Subrountine.prototype.Call = function (domain, vari, args)
93 {
94   var newargs = new Array ();
95   for (var i = 0; i < args.length; i++)
96     {
97       newargs[i] = args[i].Eval (domain);
98       if (domain.Thrown ())
99         return newargs[i];
100     }
101   return this.builtin (domain, vari, newargs)
102 }
103
104 Xex.SpecialForm = function (builtin, name, with_var, min_args, max_args)
105 {
106   this.name = name;
107   this.with_var = with_var;
108   this.min_args = min_args;
109   this.max_args = max_args;
110   this.builtin = builtin;
111 }
112
113 Xex.SpecialForm.prototype.Call = function (domain, vari, args)
114 {
115   return this.builtin (domain, vari, args)
116 }
117
118 Xex.Lambda = function (name, min_args, max_args, args, body)
119 {
120   this.name = name;
121   this.min_args = min_args;
122   this.max_args = max_args;
123   this.args = args;
124   this.body = body;
125 }
126
127 Xex.Lambda.prototype.Call = function (domain, vari, args)
128 {
129   var current = domain.bindings;
130   var result = Xex.Zero;
131   var limit = max_args >= 0 ? args.length : args.length - 1;
132   var i;
133   
134   try {
135     for (i = 0; i < limit; i++)
136       {
137         result = args[i].Eval (domain);
138         if (domain.Thrown ())
139           return result;
140         domain.Bind (this.args[i], result);
141       }
142     if (max_args < 0)
143       {
144         var list = new Array ();
145         for (i = 0; i < args[limit].length; i++)
146           {
147             result = args[limit].Eval (domain);
148             if (domain.Thrown ())
149               return result;
150             list[i] = result;
151           }
152         domain.Bind (this.args[limit], list);
153       }
154     try {
155       domain.Catch (Xex.CatchTag.Return);
156       for (var term in this.body)
157         {
158           result = term.Eval (domain);
159           if (domain.Thrown ())
160             return result;
161         }
162     } finally {
163       domain.Uncatch ();
164     }
165   } finally {
166     domain.UnboundTo (current);
167   }
168   return result;
169 }
170
171 Xex.Macro = function (name, min_args, max_args, args, body)
172 {
173   this.name = name;
174   this.min_args = min_args;
175   this.max_args = max_args;
176   this.args = args;
177   this.body = body;
178 }
179
180 Xex.Macro.prototype.Call = function (domain, vari, args)
181 {
182   var current = domain.bindings;
183   var result = Xex.Zero;
184   var i;
185
186   try {
187     for (i = 0; i < args.length; i++)
188       domain.Bind (this.args[i], args[i]);
189     try {
190       domain.Catch (Xex.CatchTag.Return);
191       for (var i in this.body)
192         {
193           result = this.body[i].Eval (domain);
194           if (domain.Thrown ())
195             break;
196         }
197     } finally {
198       domain.Uncatch ();
199     }
200   } finally {
201     domain.UnboundTo (current);
202   }
203   return result;
204 }
205
206 Xex.Bindings = function (vari)
207 {
208   this.vari = vari;
209   this.old_value = vari.val;
210 }
211
212 Xex.Bindings.prototype.UnboundTo = function (boundary)
213 {
214   for (var b = this; b != boundary; b = b.next)
215     b.vari.val = b.old_value;
216   return boundary;
217 }
218
219 Xex.Bind = function (bindings, vari, val)
220 {
221   var b = new Xex.Bindings (vari);
222   b.vari.val = val;
223   b.next = bindings;
224   return b;
225 }
226
227 Xex.CatchTag = {
228   Return: 0,
229   Break: 1
230 }
231
232 Xex.Domain = function (name, parent, context)
233 {
234   this.name = name;
235   this.context = context;
236   this.depth = 0;
237
238   if (name != 'basic' && ! parent)
239     parent = Xex.BasicDomain
240   this.parent = parent;
241   this.termtypes = {};
242   this.functions = {};
243   this.variables = {};
244   if (parent)
245     {
246       var elt;
247       for (elt in parent.termtypes)
248         this.termtypes[elt] = parent.termtypes[elt];
249       for (elt in parent.functions)
250         this.functions[elt] = parent.functions[elt];
251       for (elt in parent.variables)
252         this.variables[elt] = parent.variables[elt];
253     }
254
255   this.call_stack = new Array ();
256   this.bindings = null;
257   this.catch_stack = new Array ();
258   this.catch_count = 0;
259   this.caught = false;
260 };
261
262 Xex.Domain.prototype = {
263   CallStackCount: function () { return this.call_stack.length; },
264   CallStackPush: function (term) { this.call_stack.push (term); },
265   CallStackPop: function () { this.call_stack.pop (); },
266   Bind: function (vari, val)
267   {
268     this.bindings = Xex.Bind (this.bindings, vari, val);
269   },
270   UnboundTo: function (boundary)
271   {
272     if (this.bindings)
273       this.bindings = this.bindings.UnboundTo (boundary);
274   },
275   Catch: function (tag) { this.catch_stack.push (tag); this.catch_count++; },
276   Uncatch: function ()
277   {
278     this.catch_stack.pop ();
279     if (this.catch_count > this.catch_stack.length)
280       this.catch_count--;
281   },
282   Thrown: function ()
283   {
284     if (this.catch_count < this.catch_stack.length)
285       {
286         this.caught = (this.catch_count == this.catch_stack.length - 1);
287         return true;
288       }
289     this.caught = false;
290     return false;
291   },
292   ThrowReturn: function ()
293   {
294     for (var i = this.catch_stack.length - 1; i >= 0; i--)
295       {
296         this.catch_count--;
297         if (this.catch_stack[i] == Xex.CatchTag.Return)
298           break;
299       }
300   },
301   ThrowBreak: function ()
302   {
303     if (this.catch_stack[this.catch_stack.length - 1] != Xex.CatchTag.Break)
304       throw new Xex.ErrTerm (Xex.Error.NoLoopToBreak,
305                            "No surrounding loop to break");
306     this.catch_count--;
307   },
308   ThrowSymbol: function (tag)
309   {
310     var i = this.catch_count;
311     for (var j = this.catch_stack.length - 1; j >= 0; j--)
312       {
313         i--;
314         if (Xex.CatchTag.Matches (this.catch_stack[i], tag))
315           {
316             this.catch_count = i;
317             return;
318           }
319       }
320     throw new Xex.ErrTerm (Xex.Error.UncaughtThrow,
321                          "No corresponding catch: " + tag);
322   },
323   DefType: function (obj)
324   {
325     var type = obj.type;
326     if (this.termtypes[type])
327       throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
328                            "Already defined: " + type);
329     if (this.functions[type])
330       throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
331                            "Already defined as a funciton or a macro: "
332                            + type);
333     this.termtypes[type] = obj.Parser;
334   },
335   DefSubr: function (builtin, name, with_var, min_args, max_args)
336   {
337     this.functions[name] = new Xex.Subrountine (builtin, name, with_var,
338                                                 min_args, max_args);
339   },
340   DefSpecial: function (builtin, name, with_var, min_args, max_args)
341   {
342     this.functions[name] = new Xex.SpecialForm (builtin, name, with_var,
343                                                 min_args, max_args);
344   },
345   Defun: function (name, min_args, max_args, args, body)
346   {
347     this.functions[name] =  new Xex.Lambda (name, min_args, max_args,
348                                             args, body);
349   },
350   DefunByFunc: function (func) { this.functions[func.name] = func; },
351   Defmacro: function (name, min_args, max_args, args, body)
352   {
353     this.functions[name] = new Xex.Macro (name, min_args, max_args,
354                                           args, body);
355   },
356   DefAlias: function (alias, fname)
357   {
358     var func = this.functions[fname];
359
360     if (! func)
361       throw new Xex.ErrTerm (Xex.Error.UnknownFunction, fname);
362     if (this.termtypes[alias])
363       throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
364                            "Already defined as a term type: " + alias);
365     if (this.functions[alias])
366       throw new Xex.ErrTerm (Xex.Error.FunctionConflict,
367                            "Already defined as a function: " + alias);
368     this.functions[alias] = func;
369   },
370   Defvar: function (name, desc, val, range)
371   {
372     var vari = new Xex.Variable (this, name, desc, val, range);
373     this.variables[name] = vari;
374     return vari;
375   },
376   GetFunc: function (name)
377   {
378     var func = this.functions[name];
379     if (! func)
380       throw new Xex.ErrTerm (Xex.Error.UnknownFunction,
381                              "Unknown function: " + name);
382     return func;
383   },
384   CopyFunc: function (domain, name)
385   {
386     var func = this.functions[name];
387     domain.DefunByFunc (func);
388     return true;
389   },
390   CopyFuncAll: function (domain)
391   {
392     for (var elt in this.functions)
393       domain.DefunByFunc (this.functions[elt]);
394   },
395   GetVarCreate: function (name)
396   {
397     var vari = this.variables[name];
398     if (! vari)
399       vari = this.variables[name] = new Xex.Variable (this, name, null,
400                                                       Xex.Zero, null);
401     return vari;
402   },
403   GetVar: function (name) { return this.variables[name]; },
404   SaveValues: function ()
405   {
406     values = {};
407     for (var elt in this.variables)
408       values[elt] = this.variables[elt].val.Clone ();
409     return values;
410   },
411   RestoreValues: function (values)
412   {
413     var name;
414     for (name in values)
415       {
416         var vari = this.variables[name];
417         vari.val = values[name];
418       }
419   }
420 };
421
422 Xex.Term = function (type) { this.type = type; }
423 Xex.Term.prototype = {
424   IsTrue: function () { return true; },
425   Eval: function (domain) { return this.Clone (); },
426   Clone: function (domain) { return this; },
427   Equals: function (obj)
428   {
429     return (this.type == obj.type
430             && this.val
431             && obj.val == this.val);
432   },
433   Matches: function (obj) { return this.Equals (obj); },
434   toString: function ()
435   {
436     if (this.val != undefined)
437       return '<' + this.type + '>' + this.val + '</' + this.type + '>';
438     return '<' + this.type + '/>';
439   },
440   Intval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
441                                                "Not an integer"); },
442   Strval: function () { throw new Xex.ErrTerm (Xex.Error.WrongType,
443                                                "Not a string"); }
444 };
445
446 Node.prototype.firstElement = function ()
447 {
448   for (var n = this.firstChild; n; n = n.nextSibling)
449     if (n.nodeType == 1)
450       return n;
451   return null;
452 }
453
454 Node.prototype.nextElement = function ()
455 {
456   for (var n = this.nextSibling; n; n = n.nextSibling)
457     if (n.nodeType == 1)
458       return n;
459   return null;
460 };
461
462 (function () {
463   function parse_defvar (domain, node)
464   {
465     var name = node.attributes['vname'].nodeValue;
466     if (! name)
467       throw new Xex.ErrTerm (Xex.Error.NoVariableName, node, '');
468     var vari = domain.variables[name];
469     var desc, val, range;
470     if (vari)
471       {
472         desc = vari.description;
473         val = vari.val;
474         range = vari.range;
475       }
476     node = node.firstElement ();
477     if (node && node.nodeName == 'description')
478       {
479         desc = node.firstChild.nodeValue;
480         node = node.nextElement ();
481       }
482     if (node)
483       {
484         val = Xex.Term.Parse (domain, node);
485         node = node.nextElement ();
486         if (node && node.nodeName == 'possible-values')
487           for (node = node.firstElement (); node; node = node.nextElement ())
488             {
489               var pval;
490               if (node.nodeName == 'range')
491                 {
492                   if (! val.IsInt)
493                     throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
494                                            'Range not allowed for ' + name);
495                   pval = new Array ();
496                   for (var n = node.firstElement (); n; n = n.nextElement ())
497                     {
498                       var v = Xex.Term.Parse (domain, n);
499                       if (! v.IsInt)
500                         throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
501                                                'Invalid range value: ' + val);
502                       pval.push (v);
503                     }
504                   }
505               else
506                 {
507                   pval = Xex.Term.Parse (domain, node);
508                   if (val.type != pval.type)
509                     throw new Xex.ErrTerm (Xex.Error.TermTypeInvalid,
510                                            'Invalid possible value: ' + pval);
511                 }
512               if (! range)
513                 range = new Array ();
514               range.push (pval);
515           }
516       }
517     if (! val)
518       val = Xex.Zero;
519     domain.Defvar (name, desc, val, range);
520     return name;
521   }
522
523   function parse_defun_head (domain, node)
524   {
525     var name = node.attributes['fname'].nodeValue;
526     if (! name)
527       throw new Xex.ErrTerm (Xex.Error.NoFunctionName, node, '');
528     var args = new Array ();
529     var nfixed = 0, noptional = 0, nrest = 0;
530
531     node = node.firstElement ();
532     if (node && node.nodeName == 'args')
533       {
534         var n;
535         for (n = n.firstElement (); n; n = n.nextElement ())
536           {
537             if (n.nodeName == 'fixed')
538               nfixed++;
539             else if (n.nodeName == 'optional')
540               noptional++;
541             else if (n.nodeName == 'rest')
542               nrest++;
543             else
544               throw new Xex.ErrTerm (Xex.Error.WrongType, n, n.nodeName);
545           }
546         if (nrest > 1)
547           throw new Xex.ErrTerm (Xex.Error.WrongType, n, 'Too many <rest>');
548         for (n = node.firstElement (); n; n = n.nextElement ())
549           args.push (domain.DefVar (n.attributes['vname'].nodeValue));
550       }
551     args.min_args = nfixed;
552     args.max_args = nrest == 0 ? nfixed + noptional : -1;
553
554     if (node.nodeName == 'defun')
555       domain.Defun (name, args, null);
556     else
557       domain.Defmacro (name, args, null);
558     return name;
559   }
560
561   function parse_defun_body (domain, node)
562   {
563     var name = node.attributes['fname'].nodeValue;
564     var func = domain.GetFunc (name);
565     var body;
566     for (node = node.firstElement (); node; node = node.nextElement ())
567       if (node.nodeName != 'description' && node.nodeName != 'args')
568         break;
569     body = Xex.Term.Parse (domain, node, null);
570     func.body = body;
571   }
572
573   Xex.Term.Parse = function (domain, node, stop)
574   {
575     if (arguments.length == 2)
576       {
577         var name = node.nodeName;
578         var parser = domain.termtypes[name];
579
580         if (parser)
581           return parser (domain, node);
582         if (name == 'defun' || name == 'defmacro')
583           {
584             name = parse_defun_head (domain, node);
585             parse_defun_body (domain, node);
586             return new Xex.StrTerm (name);
587           }
588         if (name == 'defvar')
589           {
590             name = parse_defvar (domain, node);
591             return new Xex.StrTerm (name);
592           }
593         return new Xex.Funcall.prototype.Parser (domain, node);
594       }
595     for (var n = node; n && n != stop; n = n.nextElement ())
596       if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
597         parse_defun_head (domain, n);
598     var terms = null;
599     for (var n = node; n && n != stop; n = n.nextElement ())
600       {
601         if (n.nodeName == 'defun' || n.nodeName == 'defmacro')
602           parse_defun_body (domain, n);
603         else if (n.nodeName == 'defvar')
604           parse_defvar (domain, n);
605         else
606           {
607             if (! terms)
608               terms = new Array ();
609             terms.push (Xex.Term.Parse (domain, n));
610           }
611       }
612     return terms;
613   }
614 }) ();
615
616 Xex.Varref = function (vname)
617 {
618   this.val = vname;
619 };
620
621 (function () {
622   var proto = new Xex.Term ('varref');
623
624   proto.Clone = function () { return new Xex.Varref (this.val); }
625   proto.Eval = function (domain)
626   {
627     if (! this.vari || this.vari.domain != domain)
628       this.vari = domain.GetVarCreate (this.val);
629     Xex.Log (this.ToString () + '=>' + this.vari.val, domain.depth);
630     return this.vari.val;
631   }
632
633   proto.Parser = function (domain, node)
634   {
635     return new Xex.Varref (node.attributes['vname'].nodeValue);
636   }
637
638   proto.ToString = function ()
639   {
640     return '<varref vname="' + this.val + '"/>';
641   }
642
643   Xex.Varref.prototype = proto;
644 }) ();
645
646 var null_args = new Array ();
647   
648 Xex.Funcall = function (func, vari, args)
649 {
650   this.func = func;
651   this.vari = vari;
652   this.args = args || null_args;
653 };
654
655 (function () {
656   var proto = new Xex.Term ('funcall');
657
658   proto.Parser = function (domain, node)
659   {
660     var fname = node.nodeName;
661     var attr;
662
663     if (fname == 'funcall')
664       fname = node.attributes['fname'].nodeValue;
665     var func = domain.GetFunc (fname);
666     var vari;
667     attr = node.attributes['vname'];
668     vari = attr != undefined ? domain.GetVarCreate (attr.nodeValue) : false;
669     var args = Xex.Term.Parse (domain, node.firstElement (), null);
670     return new Xex.Funcall (func, vari, args);
671   }
672
673   proto.New = function (domain, fname, vname, args)
674   {
675     var func = domain.GetFunc (fname);
676     var vari = vname ? domain.GetVarCreate (vname) : null;
677     var funcall = new Xex.Funcall (func, vari, args);
678     if (func instanceof Xex.Macro)
679       funcall = funcall.Eval (domain);
680     return funcall;
681   }
682
683   proto.Eval = function (domain)
684   {
685     if (! (this.func instanceof Xex.Subrountine))
686       Xex.Log (this, domain.depth);
687     domain.depth++;
688     var result;
689     try {
690       result = this.func.Call (domain, this.vari, this.args);
691     } finally {
692       Xex.Log (this + ' => ' + result, --domain.depth);
693     }
694     return result;
695   }
696
697   proto.Clone = function ()
698   {
699     return new Xex.Funcall (this.func, this.vari, this.args);
700   }
701
702   proto.Equals = function (obj)
703   {
704     return (obj.type == 'funcall'
705             && obj.func == this.func
706             && obj.vari.Equals (this.vari)
707             && obj.args.length == this.func.length);
708   }
709
710   proto.toString = function ()
711   {
712     var arglist = ''
713     var len = this.args.length;
714     var str = '<' + this.func.name;
715     if (this.vari)
716       str += ' vname="' + this.vari.name + '"';
717     if (len == 0)
718       return str + '/>';
719     if (this.func instanceof Xex.Subrountine)
720       for (var i = 0; i < len; i++)
721         arglist += this.args[i].toString ();
722     else
723       for (var i = 0; i < len; i++)
724         arglist += '.';
725     return str + '>' + arglist + '</' + this.func.name + '>';
726   }
727
728   Xex.Funcall.prototype = proto;
729 }) ();
730
731 Xex.ErrTerm = function (ename, message, stack)
732 {
733   this.ename = ename;
734   this.message = message;
735   this.stack = stack;
736 };
737
738 (function () {
739   var proto = new Xex.Term ('error');
740
741   proto.IsError = true;
742
743   proto.Parser = function (domain, node)
744   {
745     return new Xex.ErrTerm (node.attributes['ename'].nodeValue,
746                             node.innerText, false);
747   }
748
749   proto.CallStack = function () { return stack; }
750
751   proto.SetCallStack = function (value) { statck = value; }
752
753   proto.Clone = function ()
754   {
755     return new Xex.ErrTerm (ename, message, false);
756   }
757
758   proto.Equals = function (obj)
759   {
760     return (obj.IsError
761             && obj.ename == ename && obj.message == message
762             && (obj.stack ? (stack && stack.length == obj.stack.length)
763                 : ! stack));
764   }
765
766   proto.Matches = function (obj)
767   {
768     return (obj.IsError && obj.ename == ename);
769   }
770
771   proto.toString = function ()
772   {
773     return '<error ename="' + this.ename + '">' + this.message + '</error>';
774   }
775
776   Xex.ErrTerm.prototype = proto;
777 }) ();
778
779 Xex.IntTerm = function (num) { this.val = num; };
780 (function () {
781   var proto = new Xex.Term ('integer');
782   proto.IsInt = true;
783   proto.Intval = function () { return this.val; };
784   proto.IsTrue = function () { return this.val != 0; }
785   proto.Clone = function () { return new Xex.IntTerm (this.val); }
786   proto.Parser = function (domain, node)
787   {
788     var str = node.firstChild.nodeValue;
789
790     if (str.charAt (0) == '?' && str.length == 2)
791       return new Xex.IntTerm (str.charCodeAt (1));
792     return new Xex.IntTerm (parseInt (node.firstChild.nodeValue));
793   }
794   Xex.IntTerm.prototype = proto;
795 }) ();
796
797 Xex.StrTerm = function (str) { this.val = str; };
798 (function () {
799   var proto = new Xex.Term ('string');
800   proto.IsStr = true;
801   proto.Strval = function () { return this.val; };
802   proto.IsTrue = function () { return this.val.length > 0; }
803   proto.Clone = function () { return new Xex.StrTerm (this.val); }
804   proto.Parser = function (domain, node)
805   {
806     return new Xex.StrTerm (node.firstChild.nodeValue);
807   }
808   Xex.StrTerm.prototype = proto;
809 }) ();
810
811 Xex.SymTerm = function (str) { this.val = str; };
812 (function () {
813   var proto = new Xex.Term ('symbol');
814   proto.IsSymbol = true;
815   proto.IsTrue = function () { return this.val != 'nil'; }
816   proto.Clone = function () { return new Xex.SymTerm (this.val); }
817   proto.Parser = function (domain, node)
818   {
819     return new Xex.SymTerm (node.firstChild.nodeValue);
820   }
821   Xex.SymTerm.prototype = proto;
822 }) ();
823
824 Xex.LstTerm = function (list) { this.val = list; };
825 (function () {
826   var proto = new Xex.Term ('list');
827   proto.IsList = true;
828   proto.IsTrue = function () { return this.val.length > 0; }
829   proto.Clone = function () { return new Xex.LstTerm (this.val.slice (0)); }
830
831   proto.Equals = function (obj)
832   {
833     if (obj.type != 'list' || obj.val.length != this.val.length)
834       return false;
835     var i, len = this.val.length;
836     for (i = 0; i < len; i++)
837       if (! this.val[i].Equals (obj.val[i]))
838         return false;
839     return true;
840   }
841
842   proto.Parser = function (domain, node)
843   {
844     var list = Xex.Term.Parse (domain, node.firstElement (), null);
845     return new Xex.LstTerm (list);
846   }
847
848   proto.toString = function ()
849   {
850     var len = this.val.length;
851
852     if (len == 0)
853       return '<list/>';
854     var str = '<list>';
855     for (var i = 0; i < len; i++)
856       str += this.val[i].toString ();
857     return str + '</list>';
858   }
859   Xex.LstTerm.prototype = proto;
860 }) ();
861
862 (function () {
863   var basic = new Xex.Domain ('basic', null, null);
864
865   function Fset (domain, vari, args)
866   {
867     if (! vari)
868       throw new Xex.ErrTerm (Xex.Error.NoVariableName,
869                              'No variable name to set');
870     vari.SetValue (args[0]);
871     return args[0];
872   }
873
874   function maybe_set_intvar (vari, n)
875   {
876     var term = new Xex.IntTerm (n);
877     if (vari)
878       vari.SetValue (term);
879     return term;
880   }
881
882   function Fadd (domain, vari, args)
883   {
884     var n = vari ? vari.val.Intval () : 0;
885     var len = args.length;
886
887     for (var i = 0; i < len; i++)
888       n += args[i].Intval ();
889     return maybe_set_intvar (vari, n);
890   }
891
892   function Fmul (domain, vari, args)
893   {
894     var n = vari ? vari.val.Intval () : 1;
895     for (var i = 0; i < args.length; i++)
896       n *= arg.Intval ();
897     return maybe_set_intvar (vari, n);
898   }
899
900   function Fsub (domain, vari, args)
901   {
902     var n, i;
903
904     if (! vari)
905       {
906         n = args[0].Intval ();
907         i = 1;
908       }
909     else
910       {
911         n = vari.val.Intval ();
912         i = 0;
913       }
914     while (i < args.length)
915       n -= args[i++].Intval ();
916     return maybe_set_intvar (vari, n);
917   }
918
919   function Fdiv (domain, vari, args)
920   {
921     var n, i;
922
923     if (! vari == null)
924       {
925         n = args[0].Intval ();
926         i = 1;
927       }
928     else
929       {
930         n = vari.val.Intval ();
931         i = 0;
932       }
933     while (i < args.length)
934       n /= args[i++].Intval ();
935     return maybe_set_intvar (vari, n);
936   }
937
938   function Fmod (domain, vari, args)
939   {
940     return maybe_set_intvar (vari, args[0].Intval () % args[1].Intval ());
941   }
942
943   function Flogior (domain, vari, args)
944   {
945     var n = vari == null ? 0 : vari.val;
946     for (var i = 0; i < args.length; i++)
947       n |= args[i].val;
948     return maybe_set_intvar (vari, n);
949   }
950
951   function Fand (domain, vari, args)
952   {
953     var len = args.length;
954     for (var i = 0; i < len; i++)
955     {
956       var result = args[i].Eval (domain);
957       if (domain.Thrown ())
958         return result;
959       if (! result.IsTrue ())
960         return Xex.Zero;
961     }
962     return Xex.One;
963   }
964
965   function For (domain, vari, args)
966   {
967     var len = args.length;
968     for (var i = 0; i < len; i++)
969     {
970       var result = args[i].Eval (domain);
971       if (domain.Thrown ())
972         return result;
973       if (result.IsTrue ())
974         return Xex.One;
975     }
976     return Xex.Zero;
977   }
978
979   function Feq (domain, vari, args)
980   {
981     for (var i = 1; i < args.length; i++)
982       if (! args[i - 1].Equals (args[i]))
983         return Xex.Zero;
984     return Xex.One;
985   }
986
987   function Flt (domain, vari, args)
988   {
989     var n = args[0].Intval;
990
991     for (var i = 1; i < args.length; i++)
992       {
993         var n1 = args[i].Intval;
994         if (n >= n1)
995           return Xex.Zero;
996         n = n1;
997       }
998     return Xex.One;
999   }
1000
1001   function Fle (domain, vari, args)
1002   {
1003     var n = args[0].Intval;
1004     for (var i = 1; i < args.length; i++)
1005       {
1006         var n1 = args[i].Intval;
1007         if (n > n1)
1008           return Xex.Zero;
1009         n = n1;
1010       }
1011     return Xex.One;
1012   }
1013
1014   function Fgt (domain, vari, args)
1015   {
1016     var n = args[0].Intval;
1017     for (var i = 1; i < args.length; i++)
1018       {
1019         var n1 = args[i].Intval;
1020         if (n <= n1)
1021           return Xex.Zero;
1022         n = n1;
1023       }
1024     return Xex.One;
1025   }
1026
1027   function Fge (domain, vari, args)
1028   {
1029     var n = args[0].Intval;
1030     for (var i = 1; i < args.Length; i++)
1031       {
1032         var n1 = args[i].Intval;
1033         if (n < n1)
1034           return Xex.Zero;
1035         n = n1;
1036       }
1037     return Xex.One;
1038   }
1039
1040   function Fprogn (domain, vari, args)
1041   {
1042     var result = Xex.One;
1043     var len = args.length;
1044
1045     for (var i = 0; i < len; i++)
1046       {
1047         result = args[i].Eval (domain);
1048         if (domain.Thrown ())
1049           return result;
1050       }
1051     return result;
1052   }
1053
1054   function Fif (domain, vari, args)
1055   {
1056     var result = args[0].Eval (domain);
1057
1058     if (domain.Thrown ())
1059       return result;
1060     if (result.IsTrue ())
1061       return args[1].Eval (domain);
1062     if (args.length == 2)
1063       return Zero;
1064     return args[2].Eval (domain);
1065   }
1066
1067   function Fcond (domain, vari, args)
1068   {
1069     for (var i = 0; i < args.length; i++)
1070       {
1071         var list = args[i];
1072         var result = list.val[0].Eval (domain);
1073         if (result.IsTrue ())
1074           {
1075             for (var j = 1; j < list.val.length; j++)
1076               {
1077                 domain.depth++;
1078                 result = list.val[j].Eval (domain);
1079                 domain.depth--;
1080                 if (domain.Thrown ())
1081                   return result;
1082                 }
1083             return result;
1084           }
1085       }
1086     return Xex.Zero;
1087   }
1088
1089   function eval_terms (domain, terms, idx)
1090   {
1091     var result = Xex.Zero;
1092     domain.caught = false;
1093     for (var i = idx; i < terms.length; i++)
1094       {
1095         result = terms[i].Eval (domain);
1096         if (domain.Thrown ())
1097           return result;
1098       }
1099     return result;
1100   }
1101
1102   function Fcatch (domain, vari, args)
1103   {
1104     var caught = false;
1105     var result;
1106
1107     if (args[0].IsError)
1108       {
1109         try {
1110           result = eval_terms (domain, args, 1);
1111         } catch (e) {
1112           if (e instanceof Xex.ErrTerm)
1113             {
1114               if (! args[0].Matches (e))
1115                 throw e;
1116               if (vari)
1117                 vari.SetValue (e);
1118               return Xex.One;
1119             }
1120         }
1121       }
1122     else if (args[0].IsSymbol)
1123       {
1124         try {
1125           domain.Catch (args[0].val);
1126           result = eval_terms (domain, args, 1);
1127           if (domain.caught)
1128             {
1129               if (vari != null)
1130                 vari.SetValue (result);
1131               return Xex.One;
1132             }
1133           return Xex.Zero;
1134         } finally {
1135           domain.Uncatch ();
1136         }
1137       }
1138     throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1139                            "Not a symbol nor an error: " + args[0]);
1140   }
1141
1142   function Fthrow (domain, vari, args)
1143   {
1144     if (args[0].IsSymbl)
1145       {
1146         domain.ThrowSymbol (args[0]);
1147         return (args[args.length - 1]);
1148       }
1149     if (args[0].IsError)
1150       {
1151         throw args[0];
1152       }
1153     throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1154                            "Not a symbol nor an error:" + args[0]);
1155   }
1156
1157   Xex.BasicDomain = basic;
1158
1159   basic.DefSubr (Fset, "set", true, 1, 1);
1160   basic.DefAlias ("=", "set");
1161   //basic.DefSubr (Fnot, "not", false, 1, 1);
1162   //basic.DefAlias ("!", "not");
1163   basic.DefSubr (Fadd, "add", true, 1, -1);
1164   basic.DefSubr (Fmul, "mul", true, 1, -1);
1165   basic.DefAlias ("*", "mul");
1166   basic.DefSubr (Fsub, "sub", true, 1, -1);
1167   basic.DefAlias ("-", "sub");
1168   basic.DefSubr (Fdiv, "div", true, 1, -1);
1169   basic.DefAlias ("/", "div");
1170   basic.DefSubr (Fmod, "mod", true, 1, 2);
1171   basic.DefAlias ("%", "mod");
1172   basic.DefSubr (Flogior, "logior", true, 1, -1);
1173   basic.DefAlias ('|', "logior");
1174   //basic.DefSubr (Flogand, "logand", true, 1, -1);
1175   //basic.DefAlias ("&", "logand");
1176   //basic.DefSubr (Flsh, "lsh", true, 1, 2);
1177   //basic.DefAlias ("<<", "lsh");
1178   //basic.DefSubr (Frsh, "rsh", true, 1, 2);
1179   //basic.DefAlias (">>", "rsh");
1180   basic.DefSubr (Feq, "eq", false, 2, -1);
1181   basic.DefAlias ("==", "eq");
1182   //basic.DefSubr (Fnoteq, "noteq", false, 2, 2);
1183   //basic.DefAlias ("!=", "noteq");
1184   basic.DefSubr (Flt, "lt", false, 2, -1);
1185   basic.DefAlias ("<", "lt");
1186   basic.DefSubr (Fle, "le", false, 2, -1);
1187   basic.DefAlias ("<=", "le");
1188   basic.DefSubr (Fgt, "gt", false, 2, -1);
1189   basic.DefAlias (">", "gt");
1190   basic.DefSubr (Fge, "ge", false, 2, -1);
1191   basic.DefAlias (">=", "ge");
1192   basic.DefSubr (Fthrow, "throw", false, 1, 2);
1193
1194   //basic.DefSubr (Fappend, "append", true, 0, -1);
1195   //basic.DefSubr (Fconcat, "concat", true, 0, -1);
1196   //basic.DefSubr (Fnth, "nth", false, 2, 2);
1197   //basic.DefSubr (Fcopy, "copy", false, 1, 1);
1198   //basic.DefSubr (Fins, "ins", true, 2, 2);
1199   //basic.DefSubr (Fdel, "del", true, 2, 2);
1200   //basic.DefSubr (Feval, "eval", false, 1, 1);
1201   //basic.DefSubr (Fbreak, "break", false, 0, 1);
1202   //basic.DefSubr (Freturn, "return", false, 0, 1);
1203   //basic.DefSubr (Fthrow, "throw", false, 1, 2);
1204
1205   basic.DefSpecial (Fand, "and", false, 1, -1);
1206   basic.DefAlias ("&&", "and");
1207   basic.DefSpecial (For, "or", false, 1, -1);
1208   basic.DefAlias ("||", "or");
1209   basic.DefSpecial (Fprogn, "progn", false, 1, -1);
1210   basic.DefAlias ("expr", "progn");
1211   basic.DefSpecial (Fif, "if", false, 2, 3);
1212   //basic.DefSpecial (Fwhen, "when", false, 1, -1);
1213   //basic.DefSpecial (Floop, "loop", false, 1, -1);
1214   //basic.DefSpecial (Fwhile, "while", false, 1, -1);
1215   basic.DefSpecial (Fcond, "cond", false, 1, -1);
1216   //basic.DefSpecial (Fforeach, "foreach", true, 2, -1);
1217   //basic.DefSpecial (Fquote, "quote", false, 1, 1);
1218   //basic.DefSpecial (Ftype, "type", false, 1, 1);
1219   basic.DefSpecial (Fcatch, "catch", true, 2, -1);
1220
1221   basic.DefType (Xex.Funcall.prototype);
1222   basic.DefType (Xex.Varref.prototype);
1223   basic.DefType (Xex.ErrTerm.prototype);
1224   basic.DefType (Xex.IntTerm.prototype);
1225   basic.DefType (Xex.StrTerm.prototype);
1226   basic.DefType (Xex.SymTerm.prototype);
1227   basic.DefType (Xex.LstTerm.prototype);
1228
1229 }) ();
1230
1231 Xex.Zero = new Xex.IntTerm (0);
1232 Xex.One = new Xex.IntTerm (1);
1233 Xex.nil = new Xex.SymTerm ('nil');
1234
1235 Xex.Load = function (server, file)
1236 {
1237   var obj = new XMLHttpRequest ();
1238   var url = server ? server + '/' + file : file;
1239   obj.open ('GET', url, false);
1240   obj.overrideMimeType ('text/xml');
1241   obj.send ('');
1242   return obj.responseXML.firstChild;
1243 }
1244
1245 var MIM = {
1246   // URL of the input method server.
1247   server: "http://www.m17n.org/common/mim-js",
1248   // Boolean flag to tell if MIM is active or not.
1249   enabled: true,
1250   // Boolean flag to tell if MIM is running in debug mode or not.
1251   debug: false,
1252   // List of main input methods.
1253   imlist: {},
1254   // List of extra input methods;
1255   imextra: {},
1256   // Global input method data
1257   im_global: null,
1258   // Currently selected input method.
1259   current: false,
1260
1261   // enum
1262   LoadStatus: { NotLoaded:0, Loading:1, Loaded:2, Error:-1 },
1263   ChangedStatus: {
1264     None:       0x00,
1265     StateTitle: 0x01,
1266     PreeditText:0x02,
1267     CursorPos:  0x04,
1268     CandidateList:0x08,
1269     CandidateIndex:0x10,
1270     CandidateShow:0x20,
1271     Preedit:    0x06,           // PreeditText | CursorPos
1272     Candidate:  0x38 // CandidateList | CandidateIndex | CandidateShow
1273   },
1274   KeyModifier: {
1275     SL: 0x00400000,
1276     SR: 0x00800000,
1277     S:  0x00C00000,
1278     CL: 0x01000000,
1279     CR: 0x02000000,
1280     C:  0x03000000,
1281     AL: 0x04000000,
1282     AR: 0x08000000,
1283     A:  0x0C000000,
1284     ML: 0x04000000,
1285     MR: 0x08000000,
1286     M:  0x0C000000,
1287     G:  0x10000000,
1288     s:  0x20000000,
1289     H:  0x40000000,
1290     High:       0x70000000,
1291     All:        0x7FC00000
1292   },
1293   Error: {
1294     ParseError: "parse-error"
1295   }
1296 };
1297   
1298 (function () {
1299   var keysyms = new Array ();
1300   keysyms["bs"] = "backspace";
1301   keysyms["lf"] = "linefeed";
1302   keysyms["cr"] = keysyms["enter"] = "return";
1303   keysyms["esc"] = "escape";
1304   keysyms["spc"] = "space";
1305   keysyms["del"] = "delete";
1306
1307   function decode_keysym (str) {
1308     var parts = str.split ("-");
1309     var len = parts.length, i;
1310     var has_modifier = len > 1;
1311
1312     for (i = 0; i < len - 1; i++)
1313       if (! MIM.KeyModifier.hasOwnProperty (parts[i]))
1314         return false;
1315     var key = parts[len - 1];
1316     if (key.length > 1)
1317       {
1318         key = keysyms[key.toLowerCase ()];
1319         if (key)
1320           {
1321             if (len > 1)
1322               {
1323                 str = parts[0];
1324                 for (i = 1; i < len - 1; i++)
1325                   str += '-' + parts[i];
1326                 str += '-' + key;
1327               }
1328             else
1329               str = key;
1330           }
1331       }
1332     if (has_modifier)
1333       {
1334         parts = new Array ();
1335         parts.push (str);
1336         return parts;
1337       }
1338     return str;
1339   }
1340
1341   MIM.Key = function (val)
1342   {
1343     this.key;
1344     this.has_modifier = false;
1345     if (typeof val == 'string' || val instanceof String)
1346       {
1347         this.key = decode_keysym (val);
1348         if (! this.key)
1349           throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1350         if (this.key instanceof Array)
1351           {
1352             this.key = this.key[0];
1353             this.has_modifier = true;
1354           }
1355       }
1356     else if (typeof val == 'number' || val instanceof Number)
1357       this.key = String.fromCharCode (val);
1358     else
1359       throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1360   }
1361
1362   MIM.Key.prototype.toString = function () { return this.key; };
1363 }) ();
1364
1365 (function () {
1366   MIM.KeySeq = function (seq)
1367   {
1368     this.val = new Array ();
1369     this.has_modifier = false;
1370
1371     if (seq)
1372       {
1373         if (seq.IsList)
1374           {
1375             var len = seq.val.length;
1376             for (var i = 0; i < len; i++)
1377               {
1378                 var v = seq.val[i];
1379                 if (v.type != 'string' && v.type != 'integer'
1380                     && v.type != 'symbol')
1381                   throw new Xex.ErrTerm (MIM.Error.ParseError,
1382                                          "Invalid key: " + v);
1383                 var key = new MIM.Key (v.val);
1384                 this.val.push (key);
1385                 if (key.has_modifier)
1386                   this.has_modifier = true;
1387               }
1388           }
1389         else if (seq.IsStr)
1390           {
1391             var len = seq.val.length;
1392             for (var i = 0; i < len; i++)
1393               this.val.push (new MIM.Key (seq.val.charCodeAt (i)));
1394           }
1395         else
1396           throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + seq);
1397       }
1398   }
1399
1400   var proto = new Xex.Term ('keyseq');
1401   proto.Clone = function () { return this; }
1402   proto.Parser = function (domain, node)
1403   {
1404     var seq = new Array ();
1405     for (node = node.firstChild; node; node = node.nextSibling)
1406       if (node.nodeType == 1)
1407         {
1408           var term = Xex.Term.Parse (domain, node);
1409           return new MIM.KeySeq (term);
1410         }
1411     throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid keyseq");
1412   }
1413   proto.toString = function ()
1414   {
1415     var len = this.val.length;
1416     if (len == 0)
1417       return '<keyseq/>';
1418     var first = true;
1419     var str = '<keyseq>';
1420     for (var i = 0; i < len; i++)
1421       {
1422         if (first)
1423           first = false;
1424         else if (this.has_modifier)
1425           str += ' ';
1426         str += this.val[i].toString ();
1427       }
1428     return str + '</keyseq>';
1429   }
1430
1431   MIM.KeySeq.prototype = proto;
1432 }) ();
1433
1434 (function () {
1435   MIM.Marker = function () { }
1436   MIM.Marker.prototype = new Xex.Term ('marker');
1437   MIM.Marker.prototype.CharAt = function (ic)
1438   {
1439     var p = this.Position (ic);
1440     if (p < 0 || p >= ic.preedit.length)
1441       return 0;
1442     return ic.preedit.charCodeAt (p);
1443   }
1444
1445   MIM.FloatingMarker = function (name) { this.val = name; };
1446   var proto = new MIM.Marker ();
1447   MIM.FloatingMarker.prototype = proto;
1448   proto.Position = function (ic) { return ic.marker_positions[this.val]; };
1449   proto.Mark = function (ic) { ic.marker_positions[this.val] = ic.cursor_pos; };
1450
1451   MIM.PredefinedMarker = function (name) { this.val = name; }
1452   MIM.PredefinedMarker.prototype = new MIM.Marker ();
1453   MIM.PredefinedMarker.prototype.Position = function (ic)
1454   {
1455     if (typeof this.pos == 'number')
1456       return this.pos;
1457     return this.pos (ic);
1458   }
1459
1460   var predefined = { }
1461
1462   function def_predefined (name, position)
1463   {
1464     predefined[name] = new MIM.PredefinedMarker (name);
1465     predefined[name].pos = position;
1466   }
1467
1468   def_predefined ('@<', 0);
1469   def_predefined ('@>', function (ic) { return ic.preedit.length; });
1470   def_predefined ('@-', function (ic) { return ic.cursor_pos - 1; });
1471   def_predefined ('@+', function (ic) { return ic.cursor_pos + 1; });
1472   def_predefined ('@[', function (ic) {
1473     if (ic.cursor_pos > 0)
1474       {
1475         var pos = ic.cursor_pos;
1476         return ic.preedit.FindProp ('candidates', pos - 1).from;
1477       }
1478     return 0;
1479   });
1480   def_predefined ('@]', function (ic) {
1481     if (ic.cursor_pos < ic.preedit.length - 1)
1482       {
1483         var pos = ic.cursor_pos;
1484         return ic.preedit.FindProp ('candidates', pos).to;
1485       }
1486     return ic.preedit.length;
1487   });
1488   for (var i = 0; i < 10; i++)
1489     def_predefined ("@" + i, i);
1490   predefined['@first'] = predefined['@<'];
1491   predefined['@last'] = predefined['@>'];
1492   predefined['@previous'] = predefined['@-'];
1493   predefined['@next'] = predefined['@+'];
1494   predefined['@previous-candidate-change'] = predefined['@['];
1495   predefined['@next-candidate-change'] = predefined['@]'];
1496
1497   MIM.SurroundMarker = function (name)
1498   {
1499     this.val = name;
1500     this.distance = parseInt (name.slice (1));
1501     if (isNaN (this.distance))
1502       throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid marker: " + name);
1503   }
1504   MIM.SurroundMarker.prototype = new MIM.Marker ();
1505   MIM.SurroundMarker.prototype.Position = function (ic)
1506   {
1507     return ic.cursor_pos + this.distance;
1508   }
1509   MIM.SurroundMarker.prototype.CharAt = function (ic)
1510   {
1511     if (this.val == '@-0')
1512       return -1;
1513     var p = this.Position (ic);
1514     if (p < 0)
1515       return ic.GetSurroundingChar (p);
1516     else if (p >= ic.preedit.length)
1517       return ic.GetSurroundingChar (p - ic.preedit.length);
1518     return ic.preedit.charCodeAt (p);
1519   }
1520
1521   MIM.Marker.prototype.Parser = function (domain, node)
1522   {
1523     var name = node.firstChild.nodeValue;
1524     if (name.charAt (0) == '@')
1525       {
1526         var n = predefined[name];
1527         if (n)
1528           return n;
1529         if (name.charAt (1) == '-')
1530           return new MIM.SurroundMarker (name);
1531         throw new Xex.ErrTerm (MIM.Error.ParseError,
1532                                "Invalid marker: " + name);
1533       }
1534     return new MIM.FloatingMarker (name);;
1535   }
1536 }) ();
1537
1538 MIM.Selector = function (name)
1539 {
1540   this.val = name;
1541 }
1542 MIM.Selector.prototype = new Xex.Term ('selector');
1543
1544 (function () {
1545   var selectors = {};
1546   selectors["@<"] = selectors["@first"] = new MIM.Selector ('@<');
1547   selectors["@="] = selectors["@current"] = new MIM.Selector ('@=');
1548   selectors["@>"] = selectors["@last"] = new MIM.Selector ('@>');
1549   selectors["@-"] = selectors["@previous"] = new MIM.Selector ('@-');
1550   selectors["@+"] = selectors["@next"] = new MIM.Selector ('@+');
1551   selectors["@["] = selectors["@previous-candidate-change"]
1552     = new MIM.Selector ('@[');
1553   selectors["@]"] = selectors["@next-candidate-change"]
1554     = new MIM.Selector ('@]');
1555
1556   MIM.Selector.prototype.Parser = function (domain, node)
1557   {
1558     var name = node.firstChild.nodeValue;
1559     var s = selectors[name];
1560     if (! s)
1561       throw new Xex.ErrTerm (MIM.Error.ParseError,
1562                              "Invalid selector: " + name);
1563     return s;
1564   }
1565 }) ();
1566
1567 MIM.Rule = function (keyseq, actions)
1568 {
1569   this.keyseq = keyseq;
1570   this.actions = actions;
1571 }
1572 MIM.Rule.prototype = new Xex.Term ('rule');
1573 MIM.Rule.prototype.Parser = function (domain, node)
1574 {
1575   var n;
1576   for (n = node.firstChild; n && n.nodeType != 1; n = n.nextSibling);
1577   if (! n)
1578     throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1579   var keyseq = Xex.Term.Parse (domain, n);
1580   if (keyseq.type != 'keyseq')
1581     throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1582   var actions = Xex.Term.Parse (domain, n.nextElement (), null);
1583   return new MIM.Rule (keyseq, actions);
1584 }
1585 MIM.Rule.prototype.toString = function ()
1586 {
1587   return '<rule/>';
1588 }
1589
1590 MIM.Map = function (name)
1591 {
1592   this.name = name;
1593   this.rules = new Array ();
1594 };
1595
1596 (function () {
1597   var proto = new Xex.Term ('map');
1598
1599   proto.Parser = function (domain, node)
1600   {
1601     var name = node.attributes['mname'].nodeValue;
1602     if (! name)
1603       throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1604     var map = new MIM.Map (name);
1605     for (var n = node.firstChild; n; n = n.nextSibling)
1606       if (n.nodeType == 1)
1607         map.rules.push (Xex.Term.Parse (domain, n));
1608     return map;
1609   }
1610
1611   proto.toString = function ()
1612   {
1613     var str = '<map mname="' + this.name + '">';
1614     var len = this.rules.length;
1615     for (i = 0; i < len; i++)
1616       str += this.rules[i];
1617     return str + '</map>';
1618   }
1619
1620   MIM.Map.prototype = proto;
1621 }) ();
1622
1623 Xex.CatchTag._mimtag = new Xex.SymTerm ('@mimtag');
1624
1625 MIM.Action = function (domain, terms)
1626 {
1627   var args = new Array ();
1628   args.push (Xex.CatchTag_.mimtag);
1629   for (var i = 0; i < terms.length; i++)
1630     args.push (terms[i]);
1631   this.action = Xex.Funcall.prototype.New (domain, 'catch', null, args);
1632 }
1633
1634 MIM.Action.prototype.Run = function (domain)
1635 {
1636   var result = this.action.Eval (domain);
1637   if (result.type == 'error')
1638     {
1639       domain.context.Error = result.toString ();
1640       return false;
1641     }
1642   return (result != Xex.CatchTag._mimtag);
1643 }
1644
1645 MIM.Keymap = function ()
1646 {
1647   this.name = 'TOP';
1648   this.submaps = null;
1649 };
1650
1651 (function () {
1652   var proto = {};
1653
1654   function add_rule (keymap, rule, branch_actions)
1655   {
1656     var keyseq = rule.keyseq;
1657     var len = keyseq.val.length;
1658     var name = '';
1659
1660     for (var i = 0; i < len; i++)
1661       {
1662         var key = keyseq.val[i];
1663         var sub = false;
1664
1665         name += key.key;
1666         if (! keymap.submaps)
1667           keymap.submaps = {};
1668         else
1669           sub = keymap.submaps[key.key];
1670         if (! sub)
1671           keymap.submaps[key.key] = sub = new MIM.Keymap ();
1672         keymap = sub;
1673         keymap.name = name;
1674       }
1675     keymap.map_actions = rule.actions;
1676     keymap.branch_actions = branch_actions;
1677   }
1678
1679   proto.Add = function (map, branch_actions)
1680   {
1681     var rules = map.rules;
1682     var len = rules.length;
1683
1684     for (var i = 0; i < len; i++)
1685       add_rule (this, rules[i], branch_actions);
1686   }
1687   proto.Lookup = function (keys, index)
1688   {
1689     var sub;
1690
1691     if (index < keys.val.length && this.submaps
1692         && (sub = this.submaps[keys.val[index].key]))
1693       {
1694         index++;
1695         return sub.Lookup (keys, index);
1696       }
1697     return { map: this, index: index };
1698   }
1699
1700   MIM.Keymap.prototype = proto;
1701 }) ();
1702
1703 MIM.State = function (name)
1704 {
1705   this.name = name;
1706   this.keymap = new MIM.Keymap ();
1707 };
1708
1709 (function () {
1710   var proto = new Xex.Term ('state');
1711
1712   proto.Parser = function (domain, node)
1713   {
1714     var map_list = domain.map_list;
1715     var name = node.attributes['sname'].nodeValue;
1716     if (! name)
1717       throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1718     var state = new MIM.State (name);
1719     for (node = node.firstElement (); node; node = node.nextElement ())
1720       {
1721         if (node.nodeName == 'title')
1722           state.title = node.firstChild.nodeValue;
1723         else
1724           {
1725             var n = node.firstElement ();
1726             if (node.nodeName == 'branch')
1727               state.keymap.Add (map_list[node.attributes['mname'].nodeValue],
1728                                 Xex.Term.Parse (domain, n, null));
1729             else if (node.nodeName == 'state-hook')
1730               state.enter_actions = Xex.Term.Parse (domain, n, null);
1731             else if (node.nodeName == 'catch-all-branch')
1732               state.fallback_actions = Xex.Term.Parse (domain, n, null);
1733           }
1734       }
1735     return state;
1736   }
1737
1738   proto.toString = function ()
1739   {
1740     return '<state sname="' + this.name + '">' + this.keymap + '</state>';
1741   }
1742
1743   MIM.State.prototype = proto;
1744 }) ();
1745
1746 (function () {
1747   function Block (index, term)
1748   {
1749     this.Index = index;
1750     if (term.IsStr)
1751       this.Data = term.val;
1752     else if (term.IsList)
1753       {
1754         this.Data = new Array ();
1755         for (var i = 0; i < term.val.length; i++)
1756           this.Data.push (term.val[i].val);
1757       }
1758   }
1759
1760   Block.prototype.Count = function () { return this.Data.length; }
1761   Block.prototype.get = function (i)
1762   {
1763     return (this.Data instanceof Array ? this.Data[i] : this.Data.charAt (i));
1764   }
1765
1766   MIM.Candidates = function (candidates, column)
1767   {
1768     this.column = column;
1769     this.row = 0;
1770     this.index = 0;
1771     this.total = 0;
1772     this.blocks = new Array ();
1773
1774     for (var i = 0; i < candidates.length; i++)
1775       {
1776         var block = new Block (this.total, candidates[i]);
1777         this.blocks.push (block);
1778         this.total += block.Count ();
1779       }
1780   }
1781
1782   function get_col ()
1783   {
1784     return (this.column > 0 ? this.index % this.column
1785             : this.index - this.blocks[this.row].Index);
1786   }
1787
1788   function prev_group ()
1789   {
1790     var col = get_col.call (this);
1791     var nitems;
1792     if (this.column > 0)
1793       {
1794         this.index -= this.column;
1795         if (this.index >= 0)
1796           nitems = this.column;
1797         else
1798           {
1799             var lastcol = (this.total - 1) % this.column;
1800             this.index = (col < lastcol ? this.total - lastcol + col
1801                           : this.total - 1);
1802             this.row = this.blocks.length - 1;
1803             nitems = lastcol + 1;
1804           }
1805         while (this.blocks[this.row].Index > this.index)
1806           this.row--;
1807       }
1808     else
1809       {
1810         this.row = this.row > 0 ? this.row - 1 : this.blocks.length - 1;
1811         nitems = this.blocks[this.row].Count ();
1812         this.index = (this.blocks[this.row].Index
1813                       + (col < nitems ? col : nitems - 1));
1814       }
1815     return nitems;
1816   }
1817
1818   function next_group ()
1819   {
1820     var col = get_col.call (this);
1821     var nitems;
1822     if (this.column > 0)
1823       {
1824         this.index += this.column - col;
1825         if (this.index < this.total)
1826           {
1827             if (this.index + col >= this.total)
1828               {
1829                 nitems = this.total - this.index;
1830                 this.index = this.total - 1;
1831               }
1832             else
1833               {
1834                 nitems = this.column;
1835                 this.index += col;
1836               }
1837           }
1838         else
1839           {
1840             this.index = col;
1841             this.row = 0;
1842           }
1843         while (this.blocks[this.row].Index > this.index)
1844           this.row++;
1845       }
1846     else
1847       {
1848         this.row = this.row < this.blocks.length - 1 ? this.row + 1 : 0;
1849         nitems = this.blocks[this.row].Count ();
1850         this.index = (this.blocks[this.row].Index
1851                       + (col < nitems ? col : nitems - 1));
1852       }
1853     return nitems;
1854   }
1855
1856   function prev ()
1857   {
1858     if (this.index == 0)
1859       {
1860         this.index = this.total - 1;
1861         this.row = this.blocks.length - 1;
1862       }
1863     else
1864       {
1865         this.index--;
1866         if (this.blocks[this.row].Index > this.index)
1867           this.row--;
1868       }
1869     }
1870
1871   function next ()
1872   {
1873     this.index++;
1874     if (this.index == this.total)
1875       {
1876         this.index = 0;
1877         this.row = 0;
1878       }
1879     else
1880       {
1881         var b = this.blocks[this.row];
1882         if (this.index == b.Index + b.Count ())
1883           this.row++;
1884       }
1885   }
1886
1887   function first ()
1888   {
1889     this.index -= get_col.call (this);
1890     while (this.blocks[this.row].Index > this.index)
1891       this.row--;
1892   }
1893
1894   function last ()
1895   {
1896     var b = this.blocks[this.row];
1897     if (this.column > 0)
1898       {
1899         if (this.index + 1 < this.total)
1900           {
1901             this.index += this.column - get_col.call (this) + 1;
1902             while (b.Index + b.Count () <= this.index)
1903               b = this.blocks[++this.row];
1904           }
1905       }
1906     else
1907       this.index = b.Index + b.Count () - 1;
1908   }
1909
1910   MIM.Candidates.prototype.Current = function ()
1911   {
1912     var b = this.blocks[this.row];
1913     return b.get (this.index - b.Index);
1914   }
1915
1916   MIM.Candidates.prototype.Select = function (selector)
1917   {
1918     if (selector.type == 'selector')
1919       {
1920         switch (selector.val)
1921           {
1922           case '@<': first.call (this); break;
1923           case '@>': last.call (this); break;
1924           case '@-': prev.call (this); break;
1925           case '@+': next.call (this); break;
1926           case '@[': prev_group.call (this); break;
1927           case '@]': next_group.cal (this); break;
1928           default: break;
1929           }
1930         return this.Current ();
1931       }
1932     var col, start, end
1933     if (this.column > 0)
1934       {
1935         col = this.index % this.column;
1936         start = this.index - col;
1937         end = start + this.column;
1938       }
1939     else
1940       {
1941         start = this.blocks[this.row].Index;
1942         col = this.index - start;
1943         end = start + this.blocks[this.row].Count;
1944       }
1945     if (end > this.total)
1946       end = this.total;
1947     this.index += selector.val - col;
1948     if (this.index >= end)
1949       this.index = end - 1;
1950     if (this.column > 0)
1951       {
1952         if (selector.val > col)
1953           while (this.blocks[this.row].Index + this.blocks[this.row].Count
1954                  < this.index)
1955             this.row++;
1956         else
1957           while (this.blocks[this.row].Index > this.index)
1958             this.row--;
1959       }
1960     return this.Current ();
1961   }
1962 }) ();
1963
1964 MIM.im_domain = new Xex.Domain ('input-method', null, null);
1965 MIM.im_domain.DefType (MIM.KeySeq.prototype);
1966 MIM.im_domain.DefType (MIM.Marker.prototype);
1967 MIM.im_domain.DefType (MIM.Selector.prototype);
1968 MIM.im_domain.DefType (MIM.Rule.prototype);
1969 MIM.im_domain.DefType (MIM.Map.prototype);
1970 MIM.im_domain.DefType (MIM.State.prototype);
1971
1972 (function () {
1973   var im_domain = MIM.im_domain;
1974
1975   function Finsert (domain, vari, args)
1976   {
1977     var text;
1978     if (args[0].type == 'integer')
1979       text = String.fromCharCode (args[0].val);
1980     else
1981       text = args[0].val;
1982     domain.context.ins (text, null);
1983     return args[0];
1984   }
1985
1986   function Finsert_candidates (domain, vari, args)
1987   {
1988     var ic = domain.context;
1989     var gsize = domain.variables['candidates_group_size'];
1990     var candidates = new MIM.Candidates (args, gsize ? gsize.Intval : 0);
1991     ic.ins (candidates.Current (), candidates);
1992     return args[0];
1993   }
1994
1995   function Fdelete (domain, vari, args)
1996   {
1997     var ic = domain.context;
1998     var pos = args[0].IsInt ? args[0].Intval : args[0].Position (ic);
1999     return new Xex.IntTerm (ic.del (pos));
2000   }
2001
2002   function Fselect (domain, vari, args)
2003   {
2004     var ic = domain.context;
2005     var can = ic.candidates;
2006
2007     if (can)
2008       {
2009         var old_text = can.Current ();
2010         var new_text = can.Select (args[0]);
2011         ic.rep (old_text, new_text, can);
2012       }
2013     else
2014       Xex.Log ('no candidates at ' + ic.cursor_pos + ' of ' + ic.candidate_table.table.length);
2015     return args[0];
2016   }
2017
2018   function Fchar_at (domain, vari, args)
2019   {
2020     return new Xex.IntTerm (args[0].CharAt (domain.context));
2021   }
2022
2023   function Fmove (domain, vari, args)
2024   {
2025     var ic = domain.context;
2026     var pos = args[0].IsInt ? args[0].val : args[0].Position (ic);
2027     ic.move (pos);
2028     return new Xex.IntTerm (pos);
2029   }
2030
2031   function Fmark (domain, vari, args)
2032   {
2033     args[0].Mark (domain.context);
2034     return args[0];
2035   }
2036
2037   function Fpushback (domain, vari, args)
2038   {
2039     var a = (args[0].IsInt ? args[0].Intval ()
2040              : args[0].IsStr ? new KeySeq (args[0])
2041              : args[0]);
2042     domain.context.pushback (a);
2043     return args[0];
2044   }
2045
2046   function Fundo  (domain, vari, args)
2047   {
2048     var ic = domain.context;
2049     var n = args.length == 0 ? -2 : args[0].val;
2050     if (n < 0)
2051       ic.keys.val.splice (ic.keys.length + n, -n);
2052     else
2053       ic.keys.val.splice (n, ic.keys.length);
2054     ic.reset ();
2055     return Xex.nil;
2056   }
2057
2058   function Fcommit (domain, vari, args)
2059   {
2060     domain.context.commit ();
2061     return Xex.nil;
2062   }
2063
2064   function Funhandle (domain, vari, args)
2065     {
2066       domain.context.commit ();
2067       return Xex.Fthrow (domain, vari, Xex.CatchTag._mimtag);
2068     }
2069
2070   function Fshift (domain, vari, args)
2071   {
2072     var ic = domain.context;
2073     var state_name = args[0].val;
2074     var state = ic.im.state_list[state_name];
2075     if (! state)
2076       throw ("Unknown state: " + state_name);
2077       ic.shift (state);
2078     return args[0];
2079   }
2080
2081   function Fsurrounding_flag (domain, vari, args)
2082   {
2083     return new Xex.IntTerm (-1);
2084   }
2085
2086   im_domain.DefSubr (Finsert, "insert", false, 1, 1);
2087   im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, 1);
2088   im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
2089   im_domain.DefSubr (Fselect, "select", false, 1, 1);
2090   //im_domain.DefSubr (Fshow, "show-candidates", false, 0, 0);
2091   //im_domain.DefSubr (Fhide, "hide-candidates", false, 0, 0);
2092   im_domain.DefSubr (Fmove, "move", false, 1, 1);
2093   im_domain.DefSubr (Fmark, "mark", false, 1, 1);
2094   im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
2095   //im_domain.DefSubr (Fpop, "pop", false, 0, 0);
2096   im_domain.DefSubr (Fundo, "undo", false, 0, 1);
2097   im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
2098   im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
2099   im_domain.DefSubr (Fshift, "shift", false, 1, 1);
2100   //im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
2101   im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
2102   //im_domain.DefSubr (Fkey_count, "key-count", false, 0, 0);
2103   im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag", false, 0, 0);
2104 }) ();
2105
2106
2107 (function () {
2108   function get_global_var (vname)
2109   {
2110     if (MIM.im_global.load_status == MIM.LoadStatus.NotLoaded)
2111       MIM.im_global.Load ()
2112     return MIM.im_global.domain.variables[vname];
2113   }
2114
2115   function include (node)
2116   {
2117     node = node.firstElement ();
2118     if (node.nodeName != 'tags')
2119       return null;
2120     
2121     var lang = null, name = null, extra = null;
2122     for (node = node.firstElement (); node; node = node.nextElement ())
2123       {
2124         if (node.nodeName == 'language')
2125           lang = node.firstChild.nodeValue;
2126         else if (node.nodeName == 'name')
2127           name = node.firstChild.nodeValue;
2128         else if (node.nodeName == 'extra-id')
2129           extra = node.firstChild.nodeValue;
2130       }
2131     if (! lang || ! MIM.imlist[lang])
2132       return null;
2133     if (! extra)
2134       {
2135         if (! name || ! (im = MIM.imlist[lang][name]))
2136           return null;
2137       }
2138     else
2139       {
2140         if (! (im = MIM.imextra[lang][extra]))
2141           return null;
2142       }
2143     if (im.load_status != MIM.LoadStatus.Loaded
2144         && (im.load_status != MIM.LoadStatus.NotLoaded || ! im.Load ()))
2145       return null;
2146     return im;
2147   }
2148
2149   var parsers = { };
2150
2151   parsers['description'] = function (node)
2152   {
2153     this.description = node.firstChild.nodeValue;
2154   }
2155   parsers['variable-list'] = function (node)
2156   {
2157     for (node = node.firstElement (); node; node = node.nextElement ())
2158       {
2159         var vname = node.attributes['vname'].nodeValue;
2160         if (this != MIM.im_global)
2161           {
2162             var vari = get_global_var (vname);
2163             if (vari != null)
2164               this.domain.Defvar (vname);
2165           }
2166         vname = Xex.Term.Parse (this.domain, node)
2167       }
2168   }
2169   parsers['command-list'] = function (node)
2170   {
2171   }
2172   parsers['macro-list'] = function (node)
2173   {
2174     for (var n = node.firstElement (); n; n = n.nextElement ())
2175       if (n.nodeName == 'xi:include')
2176         {
2177           var im = include (n);
2178           if (! im)
2179             alert ('inclusion fail');
2180           else
2181             for (var macro in im.domain.functions)
2182               {
2183                 var func = im.domain.functions[macro];
2184                 if (func instanceof Xex.Macro)
2185                   im.domain.CopyFunc (this.domain, macro);
2186               }
2187           n = n.previousSibling;
2188           node.removeChild (n.nextSibling);
2189         }
2190     Xex.Term.Parse (this.domain, node.firstElement (), null);
2191   }
2192   parsers['title'] = function (node)
2193   {
2194     this.title = node.firstChild.nodeValue;
2195   }
2196   parsers['map-list'] = function (node)
2197   {
2198     for (node = node.firstElement (); node; node = node.nextElement ())
2199       {
2200         if (node.nodeName == 'xi:include')
2201           {
2202             var im = include (node);
2203             if (! im)
2204               {
2205                 alert ('inclusion fail');
2206                 continue;
2207               }
2208             for (var mapname in im.map_list)
2209               this.map_list[mapname] = im.map_list[mapname];
2210           }
2211         else
2212           {
2213             var map = Xex.Term.Parse (this.domain, node);
2214             this.map_list[map.name] = map;
2215           }
2216       }
2217   }
2218   parsers['state-list'] = function (node)
2219   {
2220     this.domain.map_list = this.map_list;
2221     for (node = node.firstElement (); node; node = node.nextElement ())
2222       {
2223         if (node.nodeName == 'state')
2224           {
2225             var state = Xex.Term.Parse (this.domain, node);
2226             if (! state.title)
2227               state.title = this.title;
2228             if (! this.initial_state)
2229               this.initial_state = state;
2230             this.state_list[state.name] = state;
2231           }
2232       }
2233     delete this.domain.map_list;
2234   }
2235
2236   MIM.IM = function (lang, name, extra_id, file)
2237   {
2238     this.lang = lang;
2239     this.name = name;
2240     this.extra_id = extra_id;
2241     this.file = file;
2242     this.load_status = MIM.LoadStatus.NotLoaded;
2243     this.domain = new Xex.Domain (this.lang + '-'
2244                                   + (this.name != 'nil'
2245                                      ? this.name : this.extra_id),
2246                                   MIM.im_domain, null);
2247   }
2248
2249   var proto = {
2250     Load: function ()
2251     {
2252       var node = Xex.Load (null, this.file);
2253       if (! node)
2254         {
2255           this.load_status = MIM.LoadStatus.Error;
2256           return false;
2257         }
2258       this.map_list = {};
2259       this.initial_state = null;
2260       this.state_list = {};
2261       for (node = node.firstElement (); node; node = node.nextElement ())
2262         {
2263           var name = node.nodeName;
2264           var parser = parsers[name];
2265           if (parser)
2266             parser.call (this, node);
2267         }
2268       this.load_status = MIM.LoadStatus.Loaded;
2269       return true;
2270     }
2271   }
2272
2273   MIM.IM.prototype = proto;
2274
2275   MIM.IC = function (im, target)
2276   {
2277     if (im.load_status == MIM.LoadStatus.NotLoaded)
2278       im.Load ();
2279     if (im.load_status != MIM.LoadStatus.Loaded)
2280       alert ('im:' + im.name + ' error:' + im.load_status);
2281     this.im = im;
2282     this.target = target;
2283     this.domain = new Xex.Domain ('context', im.domain, this);
2284     this.active = true;
2285     this.range = new Array ();
2286     this.range[0] = this.range[1] = 0;
2287     this.state = null;
2288     this.initial_state = this.im.initial_state;
2289     this.keys = new MIM.KeySeq ();
2290     this.marker_positions = new Array ();
2291     this.candidate_table = new MIM.CandidateTable ();
2292     this.reset ();
2293   }
2294
2295   MIM.CandidateTable = function ()
2296   {
2297     this.table = new Array ();
2298   }
2299
2300   MIM.CandidateTable.prototype.get = function (pos)
2301   {
2302     for (var i = 0; i < this.table.length; i++)
2303       {
2304         var elt = this.table[i];
2305         if (elt.from < pos && pos <= elt.to)
2306           return elt.val;
2307       }
2308   }
2309
2310   MIM.CandidateTable.prototype.put = function (from, to, candidates)
2311   {
2312     for (var i = 0; i < this.table.length; i++)
2313       {
2314         var elt = this.table[i];
2315         if (elt.from < to && elt.to > from)
2316           {
2317             elt.from = from;
2318             elt.to = to;
2319             elt.val = candidates;
2320             return;
2321           }
2322       }
2323     this.table.push ({ from: from, to: to, val: candidates });
2324   }
2325
2326   MIM.CandidateTable.prototype.adjust = function (from, to, inserted)
2327   {
2328     var diff = inserted - (to - from);
2329     if (diff == 0)
2330       return;
2331     for (var i = 0; i < this.table.length; i++)
2332       {
2333         var elt = this.table[i];
2334         if (elt.from >= to)
2335           {
2336             elt.from += diff;
2337             elt.to += diff;
2338           }
2339       }
2340   }
2341
2342   MIM.CandidateTable.prototype.clear = function ()
2343   {
2344     this.table.length = 0;
2345   }
2346
2347   function detach_candidates (ic)
2348   {
2349     ic.candidate_table.clear ();
2350     ic.candidates = null;
2351     ic.changed |= (MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos
2352                    | ChangedStatus.CandidateList
2353                    | ChangedStatus.CandidateIndex
2354                    | ChangedStatus.CandidateShow);
2355   }
2356
2357   function set_cursor (prefix, pos)
2358   {
2359     this.cursor_pos = pos;
2360     this.candidates = this.candidate_table.get (pos);
2361   }
2362
2363   function save_state ()
2364   {
2365     this.state_var_values = this.domain.SaveValues ();
2366     this.state_preedit = this.preedit;
2367     this.state_key_head = this.key_head;
2368     this.state_pos = this.cursor_pos;
2369   }
2370
2371   function restore_state ()
2372   {
2373     this.domain.RestoreValues (this.state_var_values);
2374     this.preedit = this.state_preedit;
2375     set_cursor.call (this, "restore", this.state_pos);
2376   }
2377
2378   function handle_key ()
2379   {
2380     var out = this.keymap.Lookup (this.keys, this.key_head);
2381     var sub = out.map;
2382
2383     Xex.Log ('handling ' + this.keys.val[this.key_head]
2384              + ' in ' + this.state.name + ':' + this.keymap.name);
2385     this.key_head = out.index;
2386     if (sub != this.keymap)
2387       {
2388
2389         restore_state.call (this);
2390         this.keymap = sub;
2391         Xex.Log ('submap found');
2392         if (this.keymap.map_actions)
2393           {
2394             Xex.Log ('taking map actions:');
2395             if (! this.take_actions (this.keymap.map_actions))
2396               return false;
2397           }
2398         else if (this.keymap.submaps)
2399           {
2400             Xex.Log ('no map actions');
2401             for (var i = this.state_key_head; i < this.key_head; i++)
2402               {
2403                 Xex.Log ('inserting key:' + this.keys.val[i].key);
2404                 this.ins (this.keys.val[i].key, null);
2405               }
2406           }
2407         if (! this.keymap.submaps)
2408           {
2409             Xex.Log ('terminal:');
2410             if (this.keymap.branch_actions != null)
2411               {
2412                 Xex.Log ('branch actions:');
2413                 if (! this.take_actions (this.keymap.branch_actions))
2414                   return false;
2415               }
2416             if (this.keymap != this.state.keymap)
2417               this.shift (this.state);
2418           }
2419       }
2420     else
2421       {
2422         Xex.Log ('no submap');
2423         var current_state = this.state;
2424         var map = this.keymap;
2425
2426         if (map.branch_actions)
2427           {
2428             Xex.Log ('branch actions');
2429             if (! this.take_actions (map.branch_actions))
2430               return false;
2431           }
2432
2433         if (map == this.keymap)
2434           {
2435             Xex.Log ('no state change');
2436             if (map == this.initial_state.keymap
2437                 && this.key_head < this.keys.val.length)
2438               {
2439                 Xex.Log ('unhandled');
2440                 return false;
2441               }
2442             if (this.keymap != current_state.keymap)
2443               this.shift (current_state);
2444             else if (this.keymap.actions == null)
2445               this.shift (this.initial_state);
2446           }
2447       }
2448     return true;
2449   }
2450
2451   proto = {
2452     reset: function ()
2453     {
2454       this.cursor_pos = 0;
2455       this.candidate_show = false;
2456       this.prev_state = null;
2457       this.title = this.initial_state.title;
2458       this.state_preedit = '';
2459       this.state_key_head = 0;
2460       this.state_var_values = {};
2461       this.state_pos = 0;
2462       this.key_head = 0;
2463       this.keys.val.length = 0;
2464       this.key_unhandled = false;
2465       this.unhandled_key = null;
2466       this.changed = MIM.ChangedStatus.None;
2467       this.error_message = '';
2468       this.title = this.initial_state.title;
2469       this.produced = '';
2470       this.preedit = '';
2471       this.preedit_saved = '';
2472       this.candidate_table.clear ();
2473       this.candidates = null;
2474       this.candidate_show = false;
2475       for (var elt in this.marker_positions)
2476         this.marker_positions[elt] = 0;
2477       this.shift (this.initial_state);
2478     },
2479
2480     catch_args: new Array (Xex.CatchTag._mimtag, null),
2481
2482     take_actions: function (actions)
2483     {
2484       var func_progn = this.domain.GetFunc ('progn');
2485       var func_catch = this.domain.GetFunc ('catch');
2486       this.catch_args[1] = new Xex.Funcall (func_progn, null, actions);
2487       var term = new Xex.Funcall (func_catch, null, this.catch_args);
2488       term = term.Eval (this.domain);
2489       return (! term.IsSymbol || term.val != '@mimtag');
2490     },
2491
2492     GetSurroundingChar: function (pos)
2493     {
2494       if (pos < 0)
2495         {
2496           pos += this.range[0];
2497           if (pos < 0)
2498             return 0;
2499         }
2500       else
2501         {
2502           pos += this.range[1];
2503           if (pos >= this.target.value.length)
2504             return 0;
2505         }
2506       return this.target.value.charCodeAt (pos);
2507     },
2508     
2509     DelSurroundText: function (pos)
2510     {
2511       var text;
2512       if (pos < 0)
2513         {
2514           pos += this.range[0];
2515           if (pos <= 0)
2516             {
2517               pos = 0; text = '';
2518             }
2519           else
2520             text = this.target.value.substring (0, pos);
2521           if (this.range[0] < this.target.value.length)
2522             text += this.target.value.substring (this.range[0]);
2523           this.target.value = text;
2524           this.range[1] -= this.range[0] - pos;
2525           this.range[0] = pos;
2526         }
2527       else
2528         {
2529           pos += this.range[1];
2530           text = this.target.value.substring (0, this.range[1]);
2531           if (pos >= this.target.value.length)
2532             pos = this.target.value.length;
2533           else
2534             text += this.target.value.substring (pos);
2535           this.target.value = text;
2536         }
2537     },
2538
2539     adjust_markers: function (from, to, inserted)
2540     {
2541       var diff = inserted - (to - from);
2542
2543       for (var name in this.marker_positions)
2544         {
2545           var pos = this.marker_positions[name];
2546           if (pos > from)
2547             {
2548               if (pos >= to)
2549                 this.marker_positions[name] += diff;
2550               else if (pos > from)
2551                 this.marker_positions[name] = from;
2552             }
2553         }
2554       if (this.cursor_pos >= to)
2555         set_cursor.call (this, 'adjust', this.cursor_pos + diff);
2556       else if (this.cursor_pos > from)
2557         set_cursor.call (this, 'adjust', from)
2558     },
2559
2560     preedit_replace: function (from, to, text, candidates)
2561     {
2562       this.preedit = (this.preedit.substring (0, from)
2563                       + text + this.preedit.substring (to));
2564       this.adjust_markers (from, to, text.length);
2565       this.candidate_table.adjust (from, to, text.length);
2566       if (candidates)
2567         this.candidate_table.put (from, from + text.length, candidates)
2568     },
2569
2570     ins: function (text, candidates)
2571     {
2572       this.preedit_replace (this.cursor_pos, this.cursor_pos, text, candidates);
2573       this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2574     },
2575
2576     rep: function (old_text, new_text, candidates)
2577     {
2578       this.preedit_replace (this.cursor_pos - old_text.length,
2579                             this.cursor_pos, new_text, candidates);
2580       this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2581     },
2582
2583     del: function (pos)
2584     {
2585       var deleted = pos - this.cursor_pos;
2586       if (pos < this.cursor_pos)
2587         {
2588           if (pos < 0)
2589             {
2590               this.DelSurroundText (pos);
2591               deleted = - this.cursor_pos;
2592               pos = 0;
2593             }
2594           if (pos < this.cursor_pos)
2595             this.preedit_replace (pos, this.cursor_pos, '', null);
2596         }
2597       else
2598         {
2599           if (pos > this.preedit.length)
2600             {
2601               this.DelSurroundText (pos - this.preedit.length);
2602               deleted = this.preedit.length - this.cursor_pos;
2603               pos = this.preedit.length;
2604             }
2605           if (pos > this.cursor_pos)
2606             this.preedit_replace (this.cursor_pos, pos, '', null);
2607         }
2608       if (deleted != 0)
2609         this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2610       return deleted;
2611     },
2612
2613     show: function ()
2614     {
2615       this.candidate_show = true;
2616       this.changed |= MIM.ChangedStatus.CandidateShow;
2617     },
2618
2619     hide: function ()
2620     {
2621       this.candidate_show = false;
2622       this.changed |= MIM.ChangedStatus.CandidateShow;
2623     },
2624
2625     move: function (pos)
2626     {
2627       if (pos < 0)
2628         pos = 0;
2629       else if (pos > this.preedit.length)
2630         pos = this.preedit.length;
2631       if (pos != this.cursor_pos)
2632         {
2633           set_cursor.call (this, 'move', pos);
2634           this.changed |= MIM.ChangedStatus.Preedit;
2635         }
2636     },
2637
2638     pushback: function (n)
2639     {
2640       if (n instanceof MIM.KeySeq)
2641         {
2642           if (this.key_head > 0)
2643             this.key_head--;
2644           if (this.key_head < this.keys.val.length)
2645             this.keys.val.splice (this.key_head,
2646                                   this.keys.val.length - this.key_head);
2647           for (var i = 0; i < n.val.length; i++)
2648             this.keys.val.push (n.val[i]);
2649           return;
2650         }
2651       if (n > 0)
2652         {
2653           this.key_head -= n;
2654           if (this.key_head < 0)
2655             this.key_head = 0;
2656         }
2657       else if (n == 0)
2658         this.key_head = 0;
2659       else
2660       {
2661         this.key_head = - n;
2662         if (this.key_head > this.keys.val.length)
2663           this.key_head = this.keys.val.length;
2664       }
2665     },
2666
2667     pop: function ()
2668     {
2669       if (this.key_head < this.keys.val.length)
2670         this.keys.val.splice (this.key_head, 1);
2671     },
2672
2673     commit: function ()
2674     {
2675       if (this.preedit.length > 0)
2676       {
2677         this.candidate_table.clear ();
2678         this.produced += this.preedit;
2679         this.preedit_replace.call (this, 0, this.preedit.length, '', null);
2680       }
2681     },
2682
2683     shift: function (state)
2684     {
2685       if (state == null)
2686         {
2687           if (this.prev_state == null)
2688             return;
2689           state = this.prev_state;
2690         }
2691
2692       if (state == this.initial_state)
2693         {
2694           if (this.state)
2695             {
2696               this.commit ();
2697               this.keys.val.splice (0, this.key_head);
2698               this.key_head = 0;
2699               this.prev_state = null;
2700             }
2701         }
2702       else
2703         {
2704           if (state != this.state)
2705             this.prev_state = this.state;
2706         }
2707       if (state != this.state && state.enter_actions)
2708         this.take_actions (state.enter_actions);
2709       if (! this.state || this.state.title != state.title)
2710         this.changed |= MIM.ChangedStatus.StateTitle;
2711       this.state = state;
2712       this.keymap = state.keymap;
2713       this.state_key_head = this.key_head;
2714       save_state.call (this);
2715     },
2716
2717     Filter: function (key)
2718     {
2719       if (! this.active)
2720         {
2721           this.key_unhandled = true;
2722           this.unhandled_key = key;
2723           return false;
2724         }
2725       if (key.key == '_reload')
2726         return true;
2727       this.changed = MIM.ChangedStatus.None;
2728       this.produced = '';
2729       this.key_unhandled = false;
2730       this.keys.val.push (key);
2731       var count = 0;
2732       while (this.key_head < this.keys.val.length)
2733         {
2734           if (! handle_key.call (this))
2735             {
2736               if (this.key_head < this.keys.val.length)
2737                 {
2738                   this.unhandled_key = this.keys.val[this.key_head];
2739                   this.keys.val.splice (this.key_head, this.key_head + 1);
2740                 }
2741               this.key_unhandled = true;
2742               break;
2743             }
2744           if (++count == 10)
2745             {
2746               this.reset ();
2747               this.key_unhandled = true;
2748               break;
2749             }
2750         }
2751       if (this.key_unhandled)
2752         {
2753           this.keys.val.length = 0;
2754           this.key_head = this.state_key_head = this.commit_key_head = 0;
2755         }
2756       return (! this.key_unhandled
2757               && this.produced.length == 0
2758               && this.preedit.length == 0);
2759     }
2760   }
2761
2762   MIM.IC.prototype = proto;
2763
2764   var node = Xex.Load (null, "imlist.xml");
2765   for (node = node.firstChild; node; node = node.nextSibling)
2766     if (node.nodeName == 'input-method')
2767       {
2768         var lang = null, name = null, extra_id = null, file = null;
2769
2770         for (var n = node.firstChild; n; n = n.nextSibling)
2771           {
2772             if (n.nodeName == 'language')
2773               lang = n.firstChild.nodeValue;
2774             else if (n.nodeName == 'name')
2775               name = n.firstChild.nodeValue;
2776             else if (n.nodeName == 'extra-id')
2777               extra_id = n.firstChild.nodeValue;
2778             else if (n.nodeName == 'filename')
2779               file = n.firstChild.nodeValue;
2780           }
2781         if (name && name != 'nil')
2782           {
2783             if (! MIM.imlist[lang])
2784               MIM.imlist[lang] = {};
2785             MIM.imlist[lang][name] = new MIM.IM (lang, name, extra_id, file);
2786           }
2787         else if (extra_id && extra_id != 'nil')
2788           {
2789             if (! MIM.imextra[lang])
2790               MIM.imextra[lang] = {};
2791             MIM.imextra[lang][extra_id] = new MIM.IM (lang, name, extra_id, file);
2792           }
2793       }
2794   if (MIM.imextra.t && MIM.imextra.t.global)
2795     MIM.im_global = MIM.imextra.t.global;
2796   else
2797     {
2798       MIM.im_global = new MIM.IM ('t', 'nil', 'global', null);
2799       MIM.im_global.load_status = MIM.LoadStatus.Error;
2800     }
2801   node = undefined;
2802 }) ();
2803
2804 (function () {
2805   var keys = new Array ();
2806   keys[0x09] = 'tab';
2807   keys[0x08] = 'backspace';
2808   keys[0x0D] = 'return';
2809   keys[0x1B] = 'escape';
2810   keys[0x20] = 'space';
2811   keys[0x21] = 'pageup';
2812   keys[0x22] = 'pagedown';
2813   keys[0x23] = 'end';
2814   keys[0x24] = 'home';
2815   keys[0x25] = 'left';
2816   keys[0x26] = 'up';
2817   keys[0x27] = 'right';
2818   keys[0x28] = 'down';
2819   keys[0x2D] = 'insert';
2820   keys[0x2E] = 'delete';
2821   for (var i = 1; i <= 12; i++)
2822     keys[111 + i] = "f" + i;
2823   keys[0x90] = "numlock";
2824   keys[0xF0] = "capslock";
2825
2826   MIM.decode_key_event = function (event)
2827   {
2828     var key = ((event.type == 'keydown' || event.keyCode) ? event.keyCode
2829                : event.charCode ? event.charCode
2830                : false);
2831     if (! key)
2832       return false;
2833     if (event.type == 'keydown')
2834       {
2835         key = keys[key];
2836         if (! key)
2837           return false;
2838         if (event.shiftKey) key = "S-" + key ;
2839       }
2840     else
2841       key = String.fromCharCode (key);
2842     if (event.altKey) key = "A-" + key ;
2843     if (event.ctrlKey) key = "C-" + key ;
2844     return new MIM.Key (key);
2845   }
2846 }) ();
2847
2848 MIM.add_event_listener
2849   = (window.addEventListener
2850      ? function (target, type, listener) {
2851        target.addEventListener (type, listener, false);
2852      }
2853      : window.attachEvent
2854      ? function (target, type, listener) {
2855        target.attachEvent ('on' + type,
2856                            function() {
2857                              listener.call (target, window.event);
2858                            });
2859      }
2860      : function (target, type, listener) {
2861        target['on' + type]
2862          = function (e) { listener.call (target, e || window.event); };
2863      });
2864
2865 MIM.debug_print = function (event, ic)
2866 {
2867   if (! MIM.debug)
2868     return;
2869   if (! MIM.debug_nodes)
2870     {
2871       MIM.debug_nodes = new Array ();
2872       MIM.debug_nodes['keydown'] = document.getElementById ('keydown');
2873       MIM.debug_nodes['keypress'] = document.getElementById ('keypress');
2874       MIM.debug_nodes['status0'] = document.getElementById ('status0');
2875       MIM.debug_nodes['status1'] = document.getElementById ('status1');
2876       MIM.debug_nodes['keymap0'] = document.getElementById ('keymap0');
2877       MIM.debug_nodes['keymap1'] = document.getElementById ('keymap1');
2878       MIM.debug_nodes['preedit0'] = document.getElementById ('preedit0');
2879       MIM.debug_nodes['preedit1'] = document.getElementById ('preedit1');
2880     }
2881   var target = event.target;
2882   var code = event.keyCode;
2883   var ch = event.type == 'keydown' ? 0 : event.charCode;
2884   var key = MIM.decode_key_event (event);
2885   var index;
2886
2887   MIM.debug_nodes[event.type].innerHTML = "" + code + "/" + ch + " : " + key;
2888   index = (event.type == 'keydown' ? '0' : '1');
2889   if (ic)
2890     MIM.debug_nodes['status' + index].innerHTML = ic.im.load_status;
2891   else
2892     MIM.debug_nodes['status' + index].innerHTML = 'no IM';
2893   MIM.debug_nodes['keymap' + index].innerHTML = ic.state.name;
2894   MIM.debug_nodes['preedit' + index].innerHTML = ic.preedit;
2895   if (index == 0)
2896     {
2897       MIM.debug_nodes.keypress.innerHTML = '';
2898       MIM.debug_nodes.status1.innerHTML = '';
2899       MIM.debug_nodes.keymap1.innerHTML = '';
2900       MIM.debug_nodes.preedit1.innerHTML = ''
2901     }
2902 };
2903
2904 MIM.get_range = function (target, ic)
2905 {
2906   var from, to;
2907   if (target.selectionStart != null) // for Mozilla
2908     {
2909       from = target.selectionStart;
2910       to = target.selectionEnd;
2911     }
2912   else                          // for IE
2913     {
2914       var r = document.selection.createRange ();
2915       var rr = r.duplicate ();
2916
2917       rr.moveToElementText (target);
2918       rr.setEndPoint ('EndToEnd', range);
2919       from = rr.text.length - r.text.length;
2920       to = rr.text.length;
2921     }
2922   if (ic.range[0] == from && ic.range[1] == to
2923       && (to == from || target.value.substring (from, to) == ic.preedit))
2924     return true;
2925   ic.range[0] = from;
2926   ic.range[1] = to;
2927   return false;
2928 }
2929
2930 MIM.set_caret = function (target, ic)
2931 {
2932   if (target.setSelectionRange) // Mozilla
2933     {
2934       var scrollTop = target.scrollTop;
2935       target.setSelectionRange (ic.range[0], ic.range[1]);
2936       target.scrollTop = scrollTop;
2937     }
2938   else                          // IE
2939     {
2940       var range = target.createTextRange ();
2941       range.moveStart ('character', ic.range[0]);
2942       range.moveEnd ('character', ic.range[1]);
2943       range.select ();
2944     }
2945 };
2946
2947 MIM.update = function (target, ic)
2948 {
2949   var text = target.value;
2950   target.value = (text.substring (0, ic.range[0])
2951                   + ic.produced
2952                   + ic.preedit
2953                   + text.substring (ic.range[1]));
2954   ic.range[0] += ic.produced.length;
2955   ic.range[1] = ic.range[0] + ic.preedit.length;
2956   MIM.set_caret (target, ic);
2957 };
2958
2959 MIM.reset_ic = function (event)
2960 {
2961   if (event.target.mim_ic)
2962     {
2963       var target = event.target;
2964       var ic = target.mim_ic;
2965       if (ic.preedit.length > 0)
2966         event.target.setSelectionRange (ic.range[1], ic.range[1]);
2967       ic.reset ();
2968     }
2969 };
2970
2971 MIM.keydown = function (event)
2972 {
2973   var target = event.target;
2974   if (target.id == 'log')
2975     return;
2976   if (! (target.type == "text" || target.type == "textarea"))
2977     return;
2978
2979   var ic = target.mim_ic;
2980   if (! ic || ic.im != MIM.current)
2981     {
2982       target.mim_ic = null;
2983       Xex.Log ('creating IC');
2984       ic = new MIM.IC (MIM.current, target);
2985       if (ic.im.load_status != MIM.LoadStatus.Loaded)
2986         return;
2987       target.mim_ic = ic;
2988       MIM.add_event_listener (target, 'blur', MIM.reset_ic);
2989       MIM.get_range (target, ic)
2990     }
2991   else
2992     {
2993       if (! MIM.get_range (target, ic))
2994         ic.reset ();
2995     }
2996   MIM.debug_print (event, ic);
2997   ic.key = MIM.decode_key_event (event);
2998 };
2999
3000 MIM.keypress = function (event)
3001 {
3002   var target = event.target;
3003   if (target.id == 'log')
3004     return;
3005   if (! (target.type == "text" || target.type == "textarea"))
3006     return;
3007
3008   var ic = target.mim_ic;
3009   var i;
3010
3011   try {
3012     if (ic.im.load_status != MIM.LoadStatus.Loaded)
3013       return;
3014     if (! ic.key)
3015       ic.key = MIM.decode_key_event (event);
3016     if (! ic.key)
3017       {
3018         ic.reset ();
3019         return;
3020       }
3021     
3022     Xex.Log ("filtering " + ic.key);
3023     var result = ic.Filter (ic.key);
3024     MIM.update (target, ic);
3025     if (! ic.key_unhandled)
3026       event.preventDefault ();
3027   } finally {
3028     MIM.debug_print (event, ic);
3029   }
3030   return;
3031 };
3032
3033 (function () {
3034   var lang_category = {
3035     European: {
3036       cs: { name: 'Czech' },
3037       da: { name: 'Danish' },
3038       el: { name: 'Greek' },
3039       eo: { name: 'Esperanto' },
3040       fr: { name: 'French' },
3041       hr: { name: 'Croatian' },
3042       hy: { name: 'Armenian' },
3043       kk: { name: 'Kazakh' },
3044       ru: { name: 'Russian' },
3045       sk: { name: 'Slovak' },
3046       sr: { name: 'Serbian' },
3047       sv: { name: 'Swedish' },
3048       vi: { name: 'Vietnamese' },
3049       yi: { name: 'Yiddish' } },
3050     MiddleEast: {
3051       ar: { name: 'Arabic' },
3052       dv: { name: 'Divehi' },
3053       fa: { name: 'Persian' },
3054       he: { name: 'Hebrew' },
3055       kk: { name: 'Kazakh' },
3056       ps: { name: 'Pushto' },
3057       ug: { name: 'Uighur' },
3058       yi: { name: 'Yiddish' } },
3059     SouthAsia: {
3060       as: { name: 'Assamese' },
3061       bn: { name: 'Bengali' },
3062       bo: { name: 'Tibetan' },
3063       gu: { name: 'Gujarati' },
3064       hi: { name: 'Hindi' },
3065       kn: { name: 'Kannada' },
3066       ks: { name: 'Kashmiri' },
3067       ml: { name: 'Malayalam' },
3068       mr: { name: 'Marathi' },
3069       ne: { name: 'Nepali' },
3070       or: { name: 'Oriya' },
3071       pa: { name: 'Panjabi' },
3072       sa: { name: 'Sanskirit' },
3073       sd: { name: 'Sindhi' },
3074       si: { name: 'Sinhalese' },
3075       ta: { name: 'Tamil' },
3076       te: { name: 'Telugu' },
3077       ur: { name: 'Urdu' } },
3078     SouthEastAsia: {
3079       km: { name: 'Khmer'},
3080       lo: { name: 'Lao' },
3081       my: { name: 'Burmese' },
3082       tai: { name: 'Tai Viet' },
3083       th: { name: 'Thai' },
3084       vi: { name: 'Vietanamese' } },
3085     EastAsia: {
3086       ii: { name: 'Yii' },
3087       ja: { name: 'Japanese' },
3088       ko: { name: 'Korean' },
3089       zh: { name: 'Chinese' } },
3090     Other: {
3091       am: { name:  'Amharic' },
3092       ath: { name: 'Carrier' },
3093       bla: { name: 'Blackfoot' },
3094       cr: { name: 'Cree' },
3095       eo: { name: 'Esperanto' },
3096       iu: { name: 'Inuktitut' },
3097       nsk: { name: 'Naskapi' },
3098       oj: { name: 'Ojibwe' } }
3099   };
3100
3101   function categorize_im ()
3102   {
3103     var cat, lang, list, name;
3104     for (lang in MIM.imlist)
3105       {
3106         list = null;
3107         for (cat in lang_category)
3108           if (lang_category[cat][lang])
3109             {
3110               list = lang_category[cat][lang].list;
3111               if (! list)
3112                 list = lang_category[cat][lang].list = {};
3113               break;
3114             }
3115         if (list)
3116           for (name in MIM.imlist[lang])
3117             list[name] = MIM.imlist[lang][name];
3118       }
3119   }
3120
3121   var destroy_timer;
3122
3123   function destroy ()
3124   {
3125     clearTimeout (destroy_timer);
3126     var target = document.getElementById ('mim-menu');
3127     if (target)
3128       document.getElementsByTagName ('body')[0].removeChild (target);
3129   }    
3130
3131   function destroy_menu () { destroy_timer = setTimeout (destroy, 1000); }
3132
3133   var last_target;
3134
3135   function show_submenu (event)
3136   {
3137     if (destroy_timer)
3138       clearTimeout (destroy_timer);
3139     var target = event.target;
3140     if (target.menu_level)
3141       {
3142         Xex.Log ("menu show level " + target.menu_level
3143                  + ': ' + target.tagName);
3144         if (! last_target || last_target.parentLi == target)
3145           {
3146             Xex.Log ('Sub opened');
3147           }
3148         else
3149           {
3150             Xex.Log ('Sibling opened');
3151             last_target.style.backgroundColor = 'white';
3152             var uls = last_target.getElementsByTagName ('ul');
3153             for (var i = 0; i < uls.length; i++)
3154               uls[i].style.visibility = 'hidden';
3155           }
3156         last_target = target;
3157         target.style.backgroundColor = 'yellow';
3158         target.lastChild.style.visibility = 'visible';
3159         target.lastChild.style.left = target.clientWidth + 'px';
3160         event.preventDefault ();        
3161       }
3162   }
3163
3164   function hide_submenu (event)
3165   {
3166     var target = event.target;
3167     target.style.backgroundColor = 'white';
3168     for (var ul = target.firstChild; ul; ul = ul.nextSibling)
3169       if (ul.tagName == 'UL')
3170         ul.style.visibility = 'hidden';
3171   }
3172
3173   function select_im (event)
3174   {
3175     var target = event.target.parentNode;
3176     while (target.tagName != "mim-menu")
3177       target = target.parentNode;
3178     var idx = 0;
3179     var im = false;
3180     for (var lang in MIM.imlist)
3181       for (var name in MIM.imlist[lang])
3182         if (idx++ == target.selectedIndex)
3183           {
3184             im = MIM.imlist[lang][name];
3185             break;
3186           }
3187     document.getElementsByTagName ('body')[0].removeChild (target);
3188     target.target.focus ();
3189     if (im && im != MIM.current)
3190       {
3191         MIM.current = im;
3192         Xex.Log ('select IM: ' + im.name);
3193       }
3194   }
3195
3196   var menu;
3197
3198   function create_menu (event)
3199   {
3200     var target = event.target;
3201
3202     if (! ((target.type == "text" || target.type == "textarea")
3203            && event.which == 1 && event.ctrlKey))
3204       return;
3205     if (! menu)
3206       {
3207         categorize_im ();
3208         menu = document.createElement ('ul');
3209         menu.style.fontFamily = 'sans-serif';
3210         menu.style.fontWeight = 'bold';
3211         menu.style.margin = '0px';
3212         menu.style.padding = '0px';
3213         menu.style.border = '1px solid gray';
3214         menu.style.borderBottom = 'none';
3215         menu.style.backgroundColor = 'white';
3216         menu.style.position='absolute';
3217         menu.style.left = (event.clientX - 10) + "px";
3218         menu.style.top = (event.clientY - 10) + "px";
3219         //menu.style.width = '100px';
3220         menu.id = 'mim-menu';
3221         menu.onclick = select_im;
3222         menu.onmouseout = destroy_menu;
3223         menu.target = target;
3224         var idx = 0;
3225         for (var catname in lang_category)
3226           {
3227             var cat = lang_category[catname];
3228             var li = document.createElement ('li');
3229             li.menu_level = 1;
3230             li.parentLi = menu;
3231             li.style.position = 'relative';
3232             li.style.listStyle= 'none';
3233             li.style.margin = '0';
3234             li.style.padding = '1px';
3235             li.style.borderBottom = '1px solid gray';
3236             li.onmouseover = show_submenu;
3237             //li.onmouseout = hide_submenu;
3238             li.appendChild (document.createTextNode (catname));
3239             var sub = document.createElement ('ul');
3240             sub.style.position = 'absolute';
3241             sub.style.margin = '0px';
3242             sub.style.padding = '0px';
3243             sub.style.border = '1px solid gray';
3244             sub.style.borderBottom = 'none';
3245             sub.style.top = '-1px';
3246             //sub.style.width = '100px';
3247             sub.style.listStyle = 'disc inside';
3248             sub.style.visibility = 'hidden';
3249             sub.style.backgroundColor = 'white';
3250             li.appendChild (sub);
3251             for (var langname in cat)
3252               {
3253                 var lang = cat[langname];
3254                 if (! lang.list)
3255                   continue;
3256                 var sub_li = document.createElement ('li');
3257                 sub_li.menu_level = 2;
3258                 sub_li.parentLi = li;
3259                 sub_li.style.position = 'relative';
3260                 sub_li.style.padding = '1px';
3261                 sub_li.style.borderBottom = '1px solid gray';
3262                 sub_li.style.listStyle= 'none';
3263                 sub_li.style.backgroundColor = 'white';
3264                 //sub_li.onmouseover = show_submenu;
3265                 //sub_li.onmouseout = hide_submenu;
3266                 sub_li.appendChild (document.createTextNode (lang.name));
3267                 sub.appendChild (sub_li);
3268                 var subsub = document.createElement ('ul');
3269                 subsub.style.position = 'absolute';
3270                 subsub.style.margin = '0px';
3271                 subsub.style.padding = '0px';
3272                 subsub.style.border = '1px solid gray';
3273                 subsub.style.borderBottom = 'none';
3274                 subsub.style.top = '-1px';
3275                 //subsub.style.width = '100px';
3276                 //subsub.style.listStyle = 'disc inside';
3277                 subsub.style.visibility = 'hidden';
3278                 subsub.style.backgroundColor = 'white';
3279                 for (var name in lang.list)
3280                   {
3281                     var im = lang.list[name];
3282                     var subsub_li = document.createElement ('li');
3283                     subsub_li.menu_level = 3;
3284                     subsub_li.parentLi = sub_li;
3285                     subsub_li.style.position = 'relative';
3286                     subsub_li.style.padding = '1px';
3287                     subsub_li.style.borderBottom = '1px solid gray';
3288                     subsub_li.style.listStyle= 'none';
3289                     subsub_li.style.backgroundColor = 'white';
3290                     //subsub_li.onmouseover = show_submenu;
3291                     //subsub_li.onmouseout = hide_submenu;
3292                     subsub_li.appendChild (document.createTextNode (im.name));
3293                     subsub_li.im = im;
3294                     subsub.appendChild (subsub_li);
3295                   }
3296                 sub_li.appendChild (subsub);
3297                 idx++;
3298               }
3299             menu.appendChild (li);
3300           }
3301         document.mimmenu = menu;
3302       }
3303     document.getElementsByTagName ('body')[0].appendChild (menu);
3304   };
3305
3306   MIM.init = function ()
3307   {
3308     MIM.add_event_listener (window, 'keydown', MIM.keydown);
3309     MIM.add_event_listener (window, 'keypress', MIM.keypress);
3310     MIM.add_event_listener (window, 'mousedown', create_menu);
3311     if (window.location == 'http://localhost/mim/index.html')
3312       MIM.server = 'http://localhost/mim';
3313     MIM.current = MIM.imlist['vi']['telex'];
3314   };
3315 }) ();
3316
3317 MIM.test = function ()
3318 {
3319   var im = MIM.imlist['t']['latn-post'];
3320   var ic = new MIM.IC (im, null);
3321
3322   ic.Filter (new MIM.Key ('a'));
3323   ic.Filter (new MIM.Key ("'"));
3324
3325   if (true)
3326     document.getElementById ('text').value = ic.produced + ic.preedit;
3327   else {
3328     try {
3329       document.getElementById ('text').value
3330         = Xex.Term.Parse (domain, body).Eval (domain).toString ();
3331     } catch (e) {
3332       if (e instanceof Xex.ErrTerm)
3333         alert (e);
3334       throw e;
3335     }
3336   }
3337 }
3338
3339
3340 MIM.init_debug = function ()
3341 {
3342   MIM.debug = true;
3343   Xex.LogNode = document.getElementById ('log');
3344   Xex.Log (null);
3345   MIM.init ();
3346 };