*** 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) : null;
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 ? 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 Fnot (domain, vari, args)
875   {
876     return (args[0].IsTrue () ? Xex.Zero : Xex.One);
877   }
878
879   function maybe_set_intvar (vari, n)
880   {
881     var term = new Xex.IntTerm (n);
882     if (vari)
883       vari.SetValue (term);
884     return term;
885   }
886
887   function Fadd (domain, vari, args)
888   {
889     var n = vari ? vari.val.Intval () : 0;
890     var len = args.length;
891
892     for (var i = 0; i < len; i++)
893       n += args[i].Intval ();
894     return maybe_set_intvar (vari, n);
895   }
896
897   function Fmul (domain, vari, args)
898   {
899     var n = vari ? vari.val.Intval () : 1;
900     for (var i = 0; i < args.length; i++)
901       n *= arg.Intval ();
902     return maybe_set_intvar (vari, n);
903   }
904
905   function Fsub (domain, vari, args)
906   {
907     var n, i;
908
909     if (! vari)
910       {
911         n = args[0].Intval ();
912         i = 1;
913       }
914     else
915       {
916         n = vari.val.Intval ();
917         i = 0;
918       }
919     while (i < args.length)
920       n -= args[i++].Intval ();
921     return maybe_set_intvar (vari, n);
922   }
923
924   function Fdiv (domain, vari, args)
925   {
926     var n, i;
927
928     if (! vari == null)
929       {
930         n = args[0].Intval ();
931         i = 1;
932       }
933     else
934       {
935         n = vari.val.Intval ();
936         i = 0;
937       }
938     while (i < args.length)
939       n /= args[i++].Intval ();
940     return maybe_set_intvar (vari, n);
941   }
942
943   function Fmod (domain, vari, args)
944   {
945     return maybe_set_intvar (vari, args[0].Intval () % args[1].Intval ());
946   }
947
948   function Flogior (domain, vari, args)
949   {
950     var n = vari == null ? 0 : vari.val;
951     for (var i = 0; i < args.length; i++)
952       n |= args[i].val;
953     return maybe_set_intvar (vari, n);
954   }
955
956   function Flogand (domain, vari, args)
957   {
958     var n, i;
959     if (vari == null)
960       {
961         Xex.Log ("logand arg args[0]" + args[0]);
962         n = args[0].Intval ()
963         i = 1;
964       }
965     else
966       {
967         Xex.Log ("logand arg var " + vari);
968         n = vari.val.Intval ();
969         i = 0;
970       }
971     while (n > 0 && i < args.length)
972       {
973         Xex.Log ("logand arg " + args[i]);
974         n &= args[i++].val;
975       }
976     return maybe_set_intvar (vari, n);
977   }
978
979   function Flsh (domain, vari, args)
980   {
981     return maybe_set_intvar (vari, args[0].Intval () << args[1].Intval ());
982   }
983
984   function Frsh (domain, vari, args)
985   {
986     return maybe_set_intvar (vari, args[0].Intval () >> args[1].Intval ());
987   }
988
989   function Fand (domain, vari, args)
990   {
991     var len = args.length;
992     for (var i = 0; i < len; i++)
993     {
994       var result = args[i].Eval (domain);
995       if (domain.Thrown ())
996         return result;
997       if (! result.IsTrue ())
998         return Xex.Zero;
999     }
1000     return Xex.One;
1001   }
1002
1003   function For (domain, vari, args)
1004   {
1005     var len = args.length;
1006     for (var i = 0; i < len; i++)
1007     {
1008       var result = args[i].Eval (domain);
1009       if (domain.Thrown ())
1010         return result;
1011       if (result.IsTrue ())
1012         return Xex.One;
1013     }
1014     return Xex.Zero;
1015   }
1016
1017   function Feq (domain, vari, args)
1018   {
1019     for (var i = 1; i < args.length; i++)
1020       if (! args[i - 1].Equals (args[i]))
1021         return Xex.Zero;
1022     return Xex.One;
1023   }
1024
1025   function Fnoteq (domain, vari, args)
1026   {
1027     return (Feq (domain, vari, args) == Xex.One ? Xex.Zero : Xex.One);
1028   }
1029
1030   function Flt (domain, vari, args)
1031   {
1032     var n = args[0].Intval ();
1033
1034     for (var i = 1; i < args.length; i++)
1035       {
1036         var n1 = args[i].Intval ();
1037         if (n >= n1)
1038           return Xex.Zero;
1039         n = n1;
1040       }
1041     return Xex.One;
1042   }
1043
1044   function Fle (domain, vari, args)
1045   {
1046     var n = args[0].Intval ();
1047     for (var i = 1; i < args.length; i++)
1048       {
1049         var n1 = args[i].Intval ();
1050         if (n > n1)
1051           return Xex.Zero;
1052         n = n1;
1053       }
1054     return Xex.One;
1055   }
1056
1057   function Fgt (domain, vari, args)
1058   {
1059     var n = args[0].Intval ();
1060     for (var i = 1; i < args.length; i++)
1061       {
1062         var n1 = args[i].Intval ();
1063         if (n <= n1)
1064           return Xex.Zero;
1065         n = n1;
1066       }
1067     return Xex.One;
1068   }
1069
1070   function Fge (domain, vari, args)
1071   {
1072     var n = args[0].Intval ();
1073     for (var i = 1; i < args.Length; i++)
1074       {
1075         var n1 = args[i].Intval ();
1076         if (n < n1)
1077           return Xex.Zero;
1078         n = n1;
1079       }
1080     return Xex.One;
1081   }
1082
1083   function Fprogn (domain, vari, args)
1084   {
1085     var result = Xex.One;
1086     var len = args.length;
1087
1088     for (var i = 0; i < len; i++)
1089       {
1090         result = args[i].Eval (domain);
1091         if (domain.Thrown ())
1092           return result;
1093       }
1094     return result;
1095   }
1096
1097   function Fif (domain, vari, args)
1098   {
1099     var result = args[0].Eval (domain);
1100
1101     if (domain.Thrown ())
1102       return result;
1103     if (result.IsTrue ())
1104       return args[1].Eval (domain);
1105     if (args.length == 2)
1106       return Zero;
1107     return args[2].Eval (domain);
1108   }
1109
1110   function Fcond (domain, vari, args)
1111   {
1112     for (var i = 0; i < args.length; i++)
1113       {
1114         var list = args[i];
1115         var result = list.val[0].Eval (domain);
1116         if (result.IsTrue ())
1117           {
1118             for (var j = 1; j < list.val.length; j++)
1119               {
1120                 domain.depth++;
1121                 result = list.val[j].Eval (domain);
1122                 domain.depth--;
1123                 if (domain.Thrown ())
1124                   return result;
1125                 }
1126             return result;
1127           }
1128       }
1129     return Xex.Zero;
1130   }
1131
1132   function eval_terms (domain, terms, idx)
1133   {
1134     var result = Xex.Zero;
1135     domain.caught = false;
1136     for (var i = idx; i < terms.length; i++)
1137       {
1138         result = terms[i].Eval (domain);
1139         if (domain.Thrown ())
1140           return result;
1141       }
1142     return result;
1143   }
1144
1145   function Fcatch (domain, vari, args)
1146   {
1147     var caught = false;
1148     var result;
1149
1150     if (args[0].IsError)
1151       {
1152         try {
1153           result = eval_terms (domain, args, 1);
1154         } catch (e) {
1155           if (e instanceof Xex.ErrTerm)
1156             {
1157               if (! args[0].Matches (e))
1158                 throw e;
1159               if (vari)
1160                 vari.SetValue (e);
1161               return Xex.One;
1162             }
1163         }
1164       }
1165     else if (args[0].IsSymbol)
1166       {
1167         try {
1168           domain.Catch (args[0].val);
1169           result = eval_terms (domain, args, 1);
1170           if (domain.caught)
1171             {
1172               if (vari != null)
1173                 vari.SetValue (result);
1174               return Xex.One;
1175             }
1176           return Xex.Zero;
1177         } finally {
1178           domain.Uncatch ();
1179         }
1180       }
1181     throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1182                            "Not a symbol nor an error: " + args[0]);
1183   }
1184
1185   function Fthrow (domain, vari, args)
1186   {
1187     if (args[0].IsSymbl)
1188       {
1189         domain.ThrowSymbol (args[0]);
1190         return (args[args.length - 1]);
1191       }
1192     if (args[0].IsError)
1193       {
1194         throw args[0];
1195       }
1196     throw new Xex.ErrTerm (Xex.Error.WrongArgument,
1197                            "Not a symbol nor an error:" + args[0]);
1198   }
1199
1200   Xex.BasicDomain = basic;
1201
1202   basic.DefSubr (Fset, "set", true, 1, 1);
1203   basic.DefAlias ("=", "set");
1204   basic.DefSubr (Fnot, "not", false, 1, 1);
1205   basic.DefAlias ("!", "not");
1206   basic.DefSubr (Fadd, "add", true, 1, -1);
1207   basic.DefSubr (Fmul, "mul", true, 1, -1);
1208   basic.DefAlias ("*", "mul");
1209   basic.DefSubr (Fsub, "sub", true, 1, -1);
1210   basic.DefAlias ("-", "sub");
1211   basic.DefSubr (Fdiv, "div", true, 1, -1);
1212   basic.DefAlias ("/", "div");
1213   basic.DefSubr (Fmod, "mod", true, 1, 2);
1214   basic.DefAlias ("%", "mod");
1215   basic.DefSubr (Flogior, "logior", true, 1, -1);
1216   basic.DefAlias ('|', "logior");
1217   basic.DefSubr (Flogand, "logand", true, 1, -1);
1218   basic.DefAlias ("&", "logand");
1219   basic.DefSubr (Flsh, "lsh", true, 1, 2);
1220   basic.DefAlias ("<<", "lsh");
1221   basic.DefSubr (Frsh, "rsh", true, 1, 2);
1222   basic.DefAlias (">>", "rsh");
1223   basic.DefSubr (Feq, "eq", false, 2, -1);
1224   basic.DefAlias ("==", "eq");
1225   basic.DefSubr (Fnoteq, "noteq", false, 2, 2);
1226   basic.DefAlias ("!=", "noteq");
1227   basic.DefSubr (Flt, "lt", false, 2, -1);
1228   basic.DefAlias ("<", "lt");
1229   basic.DefSubr (Fle, "le", false, 2, -1);
1230   basic.DefAlias ("<=", "le");
1231   basic.DefSubr (Fgt, "gt", false, 2, -1);
1232   basic.DefAlias (">", "gt");
1233   basic.DefSubr (Fge, "ge", false, 2, -1);
1234   basic.DefAlias (">=", "ge");
1235   basic.DefSubr (Fthrow, "throw", false, 1, 2);
1236
1237   //basic.DefSubr (Fappend, "append", true, 0, -1);
1238   //basic.DefSubr (Fconcat, "concat", true, 0, -1);
1239   //basic.DefSubr (Fnth, "nth", false, 2, 2);
1240   //basic.DefSubr (Fcopy, "copy", false, 1, 1);
1241   //basic.DefSubr (Fins, "ins", true, 2, 2);
1242   //basic.DefSubr (Fdel, "del", true, 2, 2);
1243   //basic.DefSubr (Feval, "eval", false, 1, 1);
1244   //basic.DefSubr (Fbreak, "break", false, 0, 1);
1245   //basic.DefSubr (Freturn, "return", false, 0, 1);
1246   //basic.DefSubr (Fthrow, "throw", false, 1, 2);
1247
1248   basic.DefSpecial (Fand, "and", false, 1, -1);
1249   basic.DefAlias ("&&", "and");
1250   basic.DefSpecial (For, "or", false, 1, -1);
1251   basic.DefAlias ("||", "or");
1252   basic.DefSpecial (Fprogn, "progn", false, 1, -1);
1253   basic.DefAlias ("expr", "progn");
1254   basic.DefSpecial (Fif, "if", false, 2, 3);
1255   //basic.DefSpecial (Fwhen, "when", false, 1, -1);
1256   //basic.DefSpecial (Floop, "loop", false, 1, -1);
1257   //basic.DefSpecial (Fwhile, "while", false, 1, -1);
1258   basic.DefSpecial (Fcond, "cond", false, 1, -1);
1259   //basic.DefSpecial (Fforeach, "foreach", true, 2, -1);
1260   //basic.DefSpecial (Fquote, "quote", false, 1, 1);
1261   //basic.DefSpecial (Ftype, "type", false, 1, 1);
1262   basic.DefSpecial (Fcatch, "catch", true, 2, -1);
1263
1264   basic.DefType (Xex.Funcall.prototype);
1265   basic.DefType (Xex.Varref.prototype);
1266   basic.DefType (Xex.ErrTerm.prototype);
1267   basic.DefType (Xex.IntTerm.prototype);
1268   basic.DefType (Xex.StrTerm.prototype);
1269   basic.DefType (Xex.SymTerm.prototype);
1270   basic.DefType (Xex.LstTerm.prototype);
1271
1272 }) ();
1273
1274 Xex.Zero = new Xex.IntTerm (0);
1275 Xex.One = new Xex.IntTerm (1);
1276 Xex.nil = new Xex.SymTerm ('nil');
1277
1278 Xex.Load = function (server, file)
1279 {
1280   var obj = new XMLHttpRequest ();
1281   var url = server ? server + '/' + file : file;
1282   obj.open ('GET', url, false);
1283   obj.overrideMimeType ('text/xml');
1284   obj.send ('');
1285   return obj.responseXML.firstChild;
1286 }
1287
1288 var MIM = {
1289   // URL of the input method server.
1290   server: "http://www.m17n.org/common/mim-js",
1291   // Boolean flag to tell if MIM is active or not.
1292   enabled: true,
1293   // Boolean flag to tell if MIM is running in debug mode or not.
1294   debug: false,
1295   // List of main input methods.
1296   imlist: {},
1297   // List of extra input methods;
1298   imextra: {},
1299   // Global input method data
1300   im_global: null,
1301   // Currently selected input method.
1302   current: false,
1303
1304   // enum
1305   LoadStatus: { NotLoaded:0, Loading:1, Loaded:2, Error:-1 },
1306   ChangedStatus: {
1307     None:       0x00,
1308     StateTitle: 0x01,
1309     PreeditText:0x02,
1310     CursorPos:  0x04,
1311     CandidateList:0x08,
1312     CandidateIndex:0x10,
1313     CandidateShow:0x20,
1314     Preedit:    0x06,           // PreeditText | CursorPos
1315     Candidate:  0x38 // CandidateList | CandidateIndex | CandidateShow
1316   },
1317   KeyModifier: {
1318     SL: 0x00400000,
1319     SR: 0x00800000,
1320     S:  0x00C00000,
1321     CL: 0x01000000,
1322     CR: 0x02000000,
1323     C:  0x03000000,
1324     AL: 0x04000000,
1325     AR: 0x08000000,
1326     A:  0x0C000000,
1327     ML: 0x04000000,
1328     MR: 0x08000000,
1329     M:  0x0C000000,
1330     G:  0x10000000,
1331     s:  0x20000000,
1332     H:  0x40000000,
1333     High:       0x70000000,
1334     All:        0x7FC00000
1335   },
1336   Error: {
1337     ParseError: "parse-error"
1338   }
1339 };
1340   
1341 (function () {
1342   var keysyms = new Array ();
1343   keysyms["bs"] = "backspace";
1344   keysyms["lf"] = "linefeed";
1345   keysyms["cr"] = keysyms["enter"] = "return";
1346   keysyms["esc"] = "escape";
1347   keysyms["spc"] = "space";
1348   keysyms["del"] = "delete";
1349
1350   function decode_keysym (str) {
1351     if (str.length == 1)
1352       return str;
1353     var parts = str.split ("-");
1354     var len = parts.length, i;
1355     var has_modifier = len > 1;
1356
1357     for (i = 0; i < len - 1; i++)
1358       if (! MIM.KeyModifier.hasOwnProperty (parts[i]))
1359         return false;
1360     var key = parts[len - 1];
1361     if (key.length > 1)
1362       {
1363         key = keysyms[key.toLowerCase ()];
1364         if (key)
1365           {
1366             if (len > 1)
1367               {
1368                 str = parts[0];
1369                 for (i = 1; i < len - 1; i++)
1370                   str += '-' + parts[i];
1371                 str += '-' + key;
1372               }
1373             else
1374               str = key;
1375           }
1376       }
1377     if (has_modifier)
1378       {
1379         parts = new Array ();
1380         parts.push (str);
1381         return parts;
1382       }
1383     return str;
1384   }
1385
1386   MIM.Key = function (val)
1387   {
1388     this.key;
1389     this.has_modifier = false;
1390     if (val instanceof Xex.Term)
1391       this.key = val.val;
1392     else if (typeof val == 'string' || val instanceof String)
1393       {
1394         this.key = decode_keysym (val);
1395         if (! this.key)
1396           throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1397         if (this.key instanceof Array)
1398           {
1399             this.key = this.key[0];
1400             this.has_modifier = true;
1401           }
1402       }
1403     else if (typeof val == 'number' || val instanceof Number)
1404       this.key = String.fromCharCode (val);
1405     else
1406       throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + val);
1407   }
1408
1409   MIM.Key.prototype.toString = function () { return this.key; };
1410 }) ();
1411
1412 (function () {
1413   MIM.KeySeq = function (seq)
1414   {
1415     this.val = new Array ();
1416     this.has_modifier = false;
1417
1418     if (seq)
1419       {
1420         if (seq.IsList)
1421           {
1422             var len = seq.val.length;
1423             for (var i = 0; i < len; i++)
1424               {
1425                 var v = seq.val[i], key;
1426                 if (v.type == 'symbol' || v.type == 'string')
1427                   key = new MIM.Key (v);
1428                 else if (v.type == 'integer')
1429                   key = new MIM.Key (v.val);
1430                 else
1431                   throw new Xex.ErrTerm (MIM.Error.ParseError,
1432                                          "Invalid key: " + v);
1433                 this.val.push (key);
1434                 if (key.has_modifier)
1435                   this.has_modifier = true;
1436               }
1437           }
1438         else if (seq.IsStr)
1439           {
1440             var len = seq.val.length;
1441             for (var i = 0; i < len; i++)
1442               this.val.push (new MIM.Key (seq.val.charCodeAt (i)));
1443           }
1444         else
1445           throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid key: " + seq);
1446       }
1447   }
1448
1449   var proto = new Xex.Term ('keyseq');
1450   proto.Clone = function () { return this; }
1451   proto.Parser = function (domain, node)
1452   {
1453     var seq = new Array ();
1454     for (node = node.firstChild; node; node = node.nextSibling)
1455       if (node.nodeType == 1)
1456         {
1457           var term = Xex.Term.Parse (domain, node);
1458           return new MIM.KeySeq (term);
1459         }
1460     throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid keyseq");
1461   }
1462   proto.toString = function ()
1463   {
1464     var len = this.val.length;
1465     if (len == 0)
1466       return '<keyseq/>';
1467     var first = true;
1468     var str = '<keyseq>';
1469     for (var i = 0; i < len; i++)
1470       {
1471         if (first)
1472           first = false;
1473         else if (this.has_modifier)
1474           str += ' ';
1475         str += this.val[i].toString ();
1476       }
1477     return str + '</keyseq>';
1478   }
1479
1480   MIM.KeySeq.prototype = proto;
1481 }) ();
1482
1483 (function () {
1484   MIM.Marker = function () { }
1485   MIM.Marker.prototype = new Xex.Term ('marker');
1486   MIM.Marker.prototype.CharAt = function (ic)
1487   {
1488     var p = this.Position (ic);
1489     if (p < 0 || p >= ic.preedit.length)
1490       return 0;
1491     return ic.preedit.charCodeAt (p);
1492   }
1493
1494   MIM.FloatingMarker = function (name) { this.val = name; };
1495   var proto = new MIM.Marker ();
1496   MIM.FloatingMarker.prototype = proto;
1497   proto.Position = function (ic) { return ic.marker_positions[this.val]; };
1498   proto.Mark = function (ic) { ic.marker_positions[this.val] = ic.cursor_pos; };
1499
1500   MIM.PredefinedMarker = function (name) { this.val = name; }
1501   MIM.PredefinedMarker.prototype = new MIM.Marker ();
1502   MIM.PredefinedMarker.prototype.Position = function (ic)
1503   {
1504     if (typeof this.pos == 'number')
1505       return this.pos;
1506     return this.pos (ic);
1507   }
1508
1509   var predefined = { }
1510
1511   function def_predefined (name, position)
1512   {
1513     predefined[name] = new MIM.PredefinedMarker (name);
1514     predefined[name].pos = position;
1515   }
1516
1517   def_predefined ('@<', 0);
1518   def_predefined ('@>', function (ic) { return ic.preedit.length; });
1519   def_predefined ('@-', function (ic) { return ic.cursor_pos - 1; });
1520   def_predefined ('@+', function (ic) { return ic.cursor_pos + 1; });
1521   def_predefined ('@[', function (ic) {
1522     if (ic.cursor_pos > 0)
1523       {
1524         var pos = ic.cursor_pos;
1525         return ic.preedit.FindProp ('candidates', pos - 1).from;
1526       }
1527     return 0;
1528   });
1529   def_predefined ('@]', function (ic) {
1530     if (ic.cursor_pos < ic.preedit.length - 1)
1531       {
1532         var pos = ic.cursor_pos;
1533         return ic.preedit.FindProp ('candidates', pos).to;
1534       }
1535     return ic.preedit.length;
1536   });
1537   for (var i = 0; i < 10; i++)
1538     def_predefined ("@" + i, i);
1539   predefined['@first'] = predefined['@<'];
1540   predefined['@last'] = predefined['@>'];
1541   predefined['@previous'] = predefined['@-'];
1542   predefined['@next'] = predefined['@+'];
1543   predefined['@previous-candidate-change'] = predefined['@['];
1544   predefined['@next-candidate-change'] = predefined['@]'];
1545
1546   MIM.SurroundMarker = function (name)
1547   {
1548     this.val = name;
1549     this.distance = parseInt (name.slice (1));
1550     if (isNaN (this.distance))
1551       throw new Xex.ErrTerm (MIM.Error.ParseError, "Invalid marker: " + name);
1552   }
1553   MIM.SurroundMarker.prototype = new MIM.Marker ();
1554   MIM.SurroundMarker.prototype.Position = function (ic)
1555   {
1556     return ic.cursor_pos + this.distance;
1557   }
1558   MIM.SurroundMarker.prototype.CharAt = function (ic)
1559   {
1560     if (this.val == '@-0')
1561       return -1;
1562     var p = this.Position (ic);
1563     if (p < 0)
1564       return ic.GetSurroundingChar (p);
1565     else if (p >= ic.preedit.length)
1566       return ic.GetSurroundingChar (p - ic.preedit.length);
1567     return ic.preedit.charCodeAt (p);
1568   }
1569
1570   MIM.Marker.prototype.Parser = function (domain, node)
1571   {
1572     var name = node.firstChild.nodeValue;
1573     if (name.charAt (0) == '@')
1574       {
1575         var n = predefined[name];
1576         if (n)
1577           return n;
1578         if (name.charAt (1) == '-' || name.charAt (1) == '+')
1579           return new MIM.SurroundMarker (name);
1580         throw new Xex.ErrTerm (MIM.Error.ParseError,
1581                                "Invalid marker: " + name);
1582       }
1583     return new MIM.FloatingMarker (name);;
1584   }
1585 }) ();
1586
1587 MIM.Selector = function (name)
1588 {
1589   this.val = name;
1590 }
1591 MIM.Selector.prototype = new Xex.Term ('selector');
1592
1593 (function () {
1594   var selectors = {};
1595   selectors["@<"] = selectors["@first"] = new MIM.Selector ('@<');
1596   selectors["@="] = selectors["@current"] = new MIM.Selector ('@=');
1597   selectors["@>"] = selectors["@last"] = new MIM.Selector ('@>');
1598   selectors["@-"] = selectors["@previous"] = new MIM.Selector ('@-');
1599   selectors["@+"] = selectors["@next"] = new MIM.Selector ('@+');
1600   selectors["@["] = selectors["@previous-candidate-change"]
1601     = new MIM.Selector ('@[');
1602   selectors["@]"] = selectors["@next-candidate-change"]
1603     = new MIM.Selector ('@]');
1604
1605   MIM.Selector.prototype.Parser = function (domain, node)
1606   {
1607     var name = node.firstChild.nodeValue;
1608     var s = selectors[name];
1609     if (! s)
1610       throw new Xex.ErrTerm (MIM.Error.ParseError,
1611                              "Invalid selector: " + name);
1612     return s;
1613   }
1614 }) ();
1615
1616 MIM.Rule = function (keyseq, actions)
1617 {
1618   this.keyseq = keyseq;
1619   this.actions = actions;
1620 }
1621 MIM.Rule.prototype = new Xex.Term ('rule');
1622 MIM.Rule.prototype.Parser = function (domain, node)
1623 {
1624   var n;
1625   for (n = node.firstChild; n && n.nodeType != 1; n = n.nextSibling);
1626   if (! n)
1627     throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1628   var keyseq = Xex.Term.Parse (domain, n);
1629   if (keyseq.type != 'keyseq')
1630     throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid rule:" + node);
1631   var actions = Xex.Term.Parse (domain, n.nextElement (), null);
1632   return new MIM.Rule (keyseq, actions);
1633 }
1634 MIM.Rule.prototype.toString = function ()
1635 {
1636   return '<rule/>';
1637 }
1638
1639 MIM.Map = function (name)
1640 {
1641   this.name = name;
1642   this.rules = new Array ();
1643 };
1644
1645 (function () {
1646   var proto = new Xex.Term ('map');
1647
1648   proto.Parser = function (domain, node)
1649   {
1650     var name = node.attributes['mname'].nodeValue;
1651     if (! name)
1652       throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1653     var map = new MIM.Map (name);
1654     for (var n = node.firstChild; n; n = n.nextSibling)
1655       if (n.nodeType == 1)
1656         map.rules.push (Xex.Term.Parse (domain, n));
1657     return map;
1658   }
1659
1660   proto.toString = function ()
1661   {
1662     var str = '<map mname="' + this.name + '">';
1663     var len = this.rules.length;
1664     for (i = 0; i < len; i++)
1665       str += this.rules[i];
1666     return str + '</map>';
1667   }
1668
1669   MIM.Map.prototype = proto;
1670 }) ();
1671
1672 Xex.CatchTag._mimtag = new Xex.SymTerm ('@mimtag');
1673
1674 MIM.Action = function (domain, terms)
1675 {
1676   var args = new Array ();
1677   args.push (Xex.CatchTag_.mimtag);
1678   for (var i = 0; i < terms.length; i++)
1679     args.push (terms[i]);
1680   this.action = Xex.Funcall.prototype.New (domain, 'catch', null, args);
1681 }
1682
1683 MIM.Action.prototype.Run = function (domain)
1684 {
1685   var result = this.action.Eval (domain);
1686   if (result.type == 'error')
1687     {
1688       domain.context.Error = result.toString ();
1689       return false;
1690     }
1691   return (result != Xex.CatchTag._mimtag);
1692 }
1693
1694 MIM.Keymap = function ()
1695 {
1696   this.name = 'TOP';
1697   this.submaps = null;
1698 };
1699
1700 (function () {
1701   var proto = {};
1702
1703   function add_rule (keymap, rule, branch_actions)
1704   {
1705     var keyseq = rule.keyseq;
1706     var len = keyseq.val.length;
1707     var name = '';
1708
1709     for (var i = 0; i < len; i++)
1710       {
1711         var key = keyseq.val[i];
1712         var sub = false;
1713
1714         name += key.key;
1715         if (! keymap.submaps)
1716           keymap.submaps = {};
1717         else
1718           sub = keymap.submaps[key.key];
1719         if (! sub)
1720           keymap.submaps[key.key] = sub = new MIM.Keymap ();
1721         keymap = sub;
1722         keymap.name = name;
1723       }
1724     keymap.map_actions = rule.actions;
1725     keymap.branch_actions = branch_actions;
1726   }
1727
1728   proto.Add = function (map, branch_actions)
1729   {
1730     var rules = map.rules;
1731     var len = rules.length;
1732
1733     for (var i = 0; i < len; i++)
1734       add_rule (this, rules[i], branch_actions);
1735   }
1736   proto.Lookup = function (keys, index)
1737   {
1738     var sub;
1739
1740     if (index < keys.val.length && this.submaps
1741         && (sub = this.submaps[keys.val[index].key]))
1742       {
1743         index++;
1744         return sub.Lookup (keys, index);
1745       }
1746     return { map: this, index: index };
1747   }
1748
1749   MIM.Keymap.prototype = proto;
1750 }) ();
1751
1752 MIM.State = function (name)
1753 {
1754   this.name = name;
1755   this.keymap = new MIM.Keymap ();
1756 };
1757
1758 (function () {
1759   var proto = new Xex.Term ('state');
1760
1761   proto.Parser = function (domain, node)
1762   {
1763     var map_list = domain.map_list;
1764     var name = node.attributes['sname'].nodeValue;
1765     if (! name)
1766       throw new Xex.ErrTerm (MIM.Error.ParseError, "invalid map");
1767     var state = new MIM.State (name);
1768     for (node = node.firstElement (); node; node = node.nextElement ())
1769       {
1770         if (node.nodeName == 'title')
1771           state.title = node.firstChild.nodeValue;
1772         else
1773           {
1774             var n = node.firstElement ();
1775             if (node.nodeName == 'branch')
1776               state.keymap.Add (map_list[node.attributes['mname'].nodeValue],
1777                                 Xex.Term.Parse (domain, n, null));
1778             else if (node.nodeName == 'state-hook')
1779               state.enter_actions = Xex.Term.Parse (domain, n, null);
1780             else if (node.nodeName == 'catch-all-branch')
1781               state.fallback_actions = Xex.Term.Parse (domain, n, null);
1782           }
1783       }
1784     return state;
1785   }
1786
1787   proto.toString = function ()
1788   {
1789     return '<state sname="' + this.name + '">' + this.keymap + '</state>';
1790   }
1791
1792   MIM.State.prototype = proto;
1793 }) ();
1794
1795 (function () {
1796   function Block (index, term)
1797   {
1798     this.Index = index;
1799     if (term.IsStr)
1800       this.Data = term.val;
1801     else if (term.IsList)
1802       {
1803         this.Data = new Array ();
1804         for (var i = 0; i < term.val.length; i++)
1805           this.Data.push (term.val[i].val);
1806       }
1807   }
1808
1809   Block.prototype.Count = function () { return this.Data.length; }
1810   Block.prototype.get = function (i)
1811   {
1812     return (this.Data instanceof Array ? this.Data[i] : this.Data.charAt (i));
1813   }
1814
1815   MIM.Candidates = function (candidates, column)
1816   {
1817     this.column = column;
1818     this.row = 0;
1819     this.index = 0;
1820     this.total = 0;
1821     this.blocks = new Array ();
1822
1823     for (var i = 0; i < candidates.length; i++)
1824       {
1825         var block = new Block (this.total, candidates[i]);
1826         this.blocks.push (block);
1827         this.total += block.Count ();
1828       }
1829   }
1830
1831   function get_col ()
1832   {
1833     return (this.column > 0 ? this.index % this.column
1834             : this.index - this.blocks[this.row].Index);
1835   }
1836
1837   function prev_group ()
1838   {
1839     var col = get_col.call (this);
1840     var nitems;
1841     if (this.column > 0)
1842       {
1843         this.index -= this.column;
1844         if (this.index >= 0)
1845           nitems = this.column;
1846         else
1847           {
1848             var lastcol = (this.total - 1) % this.column;
1849             this.index = (col < lastcol ? this.total - lastcol + col
1850                           : this.total - 1);
1851             this.row = this.blocks.length - 1;
1852             nitems = lastcol + 1;
1853           }
1854         while (this.blocks[this.row].Index > this.index)
1855           this.row--;
1856       }
1857     else
1858       {
1859         this.row = this.row > 0 ? this.row - 1 : this.blocks.length - 1;
1860         nitems = this.blocks[this.row].Count ();
1861         this.index = (this.blocks[this.row].Index
1862                       + (col < nitems ? col : nitems - 1));
1863       }
1864     return nitems;
1865   }
1866
1867   function next_group ()
1868   {
1869     var col = get_col.call (this);
1870     var nitems;
1871     if (this.column > 0)
1872       {
1873         this.index += this.column - col;
1874         if (this.index < this.total)
1875           {
1876             if (this.index + col >= this.total)
1877               {
1878                 nitems = this.total - this.index;
1879                 this.index = this.total - 1;
1880               }
1881             else
1882               {
1883                 nitems = this.column;
1884                 this.index += col;
1885               }
1886           }
1887         else
1888           {
1889             this.index = col;
1890             this.row = 0;
1891           }
1892         while (this.blocks[this.row].Index > this.index)
1893           this.row++;
1894       }
1895     else
1896       {
1897         this.row = this.row < this.blocks.length - 1 ? this.row + 1 : 0;
1898         nitems = this.blocks[this.row].Count ();
1899         this.index = (this.blocks[this.row].Index
1900                       + (col < nitems ? col : nitems - 1));
1901       }
1902     return nitems;
1903   }
1904
1905   function prev ()
1906   {
1907     if (this.index == 0)
1908       {
1909         this.index = this.total - 1;
1910         this.row = this.blocks.length - 1;
1911       }
1912     else
1913       {
1914         this.index--;
1915         if (this.blocks[this.row].Index > this.index)
1916           this.row--;
1917       }
1918     }
1919
1920   function next ()
1921   {
1922     this.index++;
1923     if (this.index == this.total)
1924       {
1925         this.index = 0;
1926         this.row = 0;
1927       }
1928     else
1929       {
1930         var b = this.blocks[this.row];
1931         if (this.index == b.Index + b.Count ())
1932           this.row++;
1933       }
1934   }
1935
1936   function first ()
1937   {
1938     this.index -= get_col.call (this);
1939     while (this.blocks[this.row].Index > this.index)
1940       this.row--;
1941   }
1942
1943   function last ()
1944   {
1945     var b = this.blocks[this.row];
1946     if (this.column > 0)
1947       {
1948         if (this.index + 1 < this.total)
1949           {
1950             this.index += this.column - get_col.call (this) + 1;
1951             while (b.Index + b.Count () <= this.index)
1952               b = this.blocks[++this.row];
1953           }
1954       }
1955     else
1956       this.index = b.Index + b.Count () - 1;
1957   }
1958
1959   MIM.Candidates.prototype.Current = function ()
1960   {
1961     var b = this.blocks[this.row];
1962     return b.get (this.index - b.Index);
1963   }
1964
1965   MIM.Candidates.prototype.Select = function (selector)
1966   {
1967     if (selector.type == 'selector')
1968       {
1969         switch (selector.val)
1970           {
1971           case '@<': first.call (this); break;
1972           case '@>': last.call (this); break;
1973           case '@-': prev.call (this); break;
1974           case '@+': next.call (this); break;
1975           case '@[': prev_group.call (this); break;
1976           case '@]': next_group.cal (this); break;
1977           default: break;
1978           }
1979         return this.Current ();
1980       }
1981     var col, start, end
1982     if (this.column > 0)
1983       {
1984         col = this.index % this.column;
1985         start = this.index - col;
1986         end = start + this.column;
1987       }
1988     else
1989       {
1990         start = this.blocks[this.row].Index;
1991         col = this.index - start;
1992         end = start + this.blocks[this.row].Count;
1993       }
1994     if (end > this.total)
1995       end = this.total;
1996     this.index += selector.val - col;
1997     if (this.index >= end)
1998       this.index = end - 1;
1999     if (this.column > 0)
2000       {
2001         if (selector.val > col)
2002           while (this.blocks[this.row].Index + this.blocks[this.row].Count
2003                  < this.index)
2004             this.row++;
2005         else
2006           while (this.blocks[this.row].Index > this.index)
2007             this.row--;
2008       }
2009     return this.Current ();
2010   }
2011 }) ();
2012
2013 MIM.im_domain = new Xex.Domain ('input-method', null, null);
2014 MIM.im_domain.DefType (MIM.KeySeq.prototype);
2015 MIM.im_domain.DefType (MIM.Marker.prototype);
2016 MIM.im_domain.DefType (MIM.Selector.prototype);
2017 MIM.im_domain.DefType (MIM.Rule.prototype);
2018 MIM.im_domain.DefType (MIM.Map.prototype);
2019 MIM.im_domain.DefType (MIM.State.prototype);
2020
2021 (function () {
2022   var im_domain = MIM.im_domain;
2023
2024   function Finsert (domain, vari, args)
2025   {
2026     var text;
2027     if (args[0].type == 'integer')
2028       text = String.fromCharCode (args[0].val);
2029     else
2030       text = args[0].val;
2031     domain.context.ins (text, null);
2032     return args[0];
2033   }
2034
2035   function Finsert_candidates (domain, vari, args)
2036   {
2037     var ic = domain.context;
2038     var gsize = domain.variables['candidates_group_size'];
2039     var candidates = new MIM.Candidates (args, gsize ? gsize.Intval () : 0);
2040     ic.ins (candidates.Current (), candidates);
2041     return args[0];
2042   }
2043
2044   function Fdelete (domain, vari, args)
2045   {
2046     var ic = domain.context;
2047     var pos = args[0].IsInt ? args[0].Intval () : args[0].Position (ic);
2048     return new Xex.IntTerm (ic.del (pos));
2049   }
2050
2051   function Fselect (domain, vari, args)
2052   {
2053     var ic = domain.context;
2054     var can = ic.candidates;
2055
2056     if (can)
2057       {
2058         var old_text = can.Current ();
2059         var new_text = can.Select (args[0]);
2060         ic.rep (old_text, new_text, can);
2061       }
2062     else
2063       Xex.Log ('no candidates at ' + ic.cursor_pos + ' of ' + ic.candidate_table.table.length);
2064     return args[0];
2065   }
2066
2067   function Fshow (domain, vari, args)
2068   {
2069     domain.context.candidate_show = true;
2070     domain.context.changed |= MIM.ChangedStatus.CandidateShow;
2071     return Xex.nil;
2072   }
2073
2074   function Fhide (domain, vari, args)
2075   {
2076     domain.context.candidate_show = false;
2077     domain.context.changed |= MIM.ChangedStatus.CandidateShow;
2078     return Xex.nil;
2079   }
2080
2081   function Fchar_at (domain, vari, args)
2082   {
2083     return new Xex.IntTerm (args[0].CharAt (domain.context));
2084   }
2085
2086   function Fmove (domain, vari, args)
2087   {
2088     var ic = domain.context;
2089     var pos = args[0].IsInt ? args[0].val : args[0].Position (ic);
2090     ic.move (pos);
2091     return new Xex.IntTerm (pos);
2092   }
2093
2094   function Fmark (domain, vari, args)
2095   {
2096     args[0].Mark (domain.context);
2097     return args[0];
2098   }
2099
2100   function Fpushback (domain, vari, args)
2101   {
2102     var a = (args[0].IsInt ? args[0].Intval ()
2103              : args[0].IsStr ? new KeySeq (args[0])
2104              : args[0]);
2105     domain.context.pushback (a);
2106     return args[0];
2107   }
2108
2109   function Fpop (domain, vari, args)
2110   {
2111     var ic = domain.context;
2112     if (ic.key_head < ic.keys.val.length)
2113       ic.keys.val.splice (ic.keys_head, 1);
2114     return Xex.nil;
2115   }
2116
2117   function Fundo  (domain, vari, args)
2118   {
2119     var ic = domain.context;
2120     var n = args.length == 0 ? -2 : args[0].val;
2121     if (n < 0)
2122       ic.keys.val.splice (ic.keys.length + n, -n);
2123     else
2124       ic.keys.val.splice (n, ic.keys.length);
2125     ic.reset ();
2126     return Xex.nil;
2127   }
2128
2129   function Fcommit (domain, vari, args)
2130   {
2131     domain.context.commit ();
2132     return Xex.nil;
2133   }
2134
2135   function Funhandle (domain, vari, args)
2136     {
2137       domain.context.commit ();
2138       return Xex.Fthrow (domain, vari, Xex.CatchTag._mimtag);
2139     }
2140
2141   function Fshift (domain, vari, args)
2142   {
2143     var ic = domain.context;
2144     var state_name = args[0].val;
2145     var state = ic.im.state_list[state_name];
2146     if (! state)
2147       throw ("Unknown state: " + state_name);
2148       ic.shift (state);
2149     return args[0];
2150   }
2151
2152   function Fshiftback (domain, vari, args)
2153   {
2154     domain.context.shift (null);
2155     return Xex.nil;
2156   }
2157
2158   function Fkey_count (domain, vari, args)
2159   {
2160     return new Xex.IntTerm (domain.context.key_head);
2161   }
2162
2163   function Fsurrounding_flag (domain, vari, args)
2164   {
2165     return new Xex.IntTerm (-1);
2166   }
2167
2168   im_domain.DefSubr (Finsert, "insert", false, 1, 1);
2169   im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, 1);
2170   im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
2171   im_domain.DefSubr (Fselect, "select", false, 1, 1);
2172   im_domain.DefSubr (Fshow, "show-candidates", false, 0, 0);
2173   im_domain.DefSubr (Fhide, "hide-candidates", false, 0, 0);
2174   im_domain.DefSubr (Fmove, "move", false, 1, 1);
2175   im_domain.DefSubr (Fmark, "mark", false, 1, 1);
2176   im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
2177   im_domain.DefSubr (Fpop, "pop", false, 0, 0);
2178   im_domain.DefSubr (Fundo, "undo", false, 0, 1);
2179   im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
2180   im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
2181   im_domain.DefSubr (Fshift, "shift", false, 1, 1);
2182   im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
2183   im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
2184   im_domain.DefSubr (Fkey_count, "key-count", false, 0, 0);
2185   im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag", false, 0, 0);
2186 }) ();
2187
2188
2189 (function () {
2190   function get_global_var (vname)
2191   {
2192     if (MIM.im_global.load_status == MIM.LoadStatus.NotLoaded)
2193       MIM.im_global.Load ()
2194     return MIM.im_global.domain.variables[vname];
2195   }
2196
2197   function include (node)
2198   {
2199     node = node.firstElement ();
2200     if (node.nodeName != 'tags')
2201       return null;
2202     
2203     var lang = null, name = null, extra = null;
2204     for (node = node.firstElement (); node; node = node.nextElement ())
2205       {
2206         if (node.nodeName == 'language')
2207           lang = node.firstChild.nodeValue;
2208         else if (node.nodeName == 'name')
2209           name = node.firstChild.nodeValue;
2210         else if (node.nodeName == 'extra-id')
2211           extra = node.firstChild.nodeValue;
2212       }
2213     if (! lang || ! MIM.imlist[lang])
2214       return null;
2215     if (! extra)
2216       {
2217         if (! name || ! (im = MIM.imlist[lang][name]))
2218           return null;
2219       }
2220     else
2221       {
2222         if (! (im = MIM.imextra[lang][extra]))
2223           return null;
2224       }
2225     if (im.load_status != MIM.LoadStatus.Loaded
2226         && (im.load_status != MIM.LoadStatus.NotLoaded || ! im.Load ()))
2227       return null;
2228     return im;
2229   }
2230
2231   var parsers = { };
2232
2233   parsers['description'] = function (node)
2234   {
2235     this.description = node.firstChild.nodeValue;
2236   }
2237   parsers['variable-list'] = function (node)
2238   {
2239     for (node = node.firstElement (); node; node = node.nextElement ())
2240       {
2241         var vname = node.attributes['vname'].nodeValue;
2242         if (this != MIM.im_global)
2243           {
2244             var vari = get_global_var (vname);
2245             if (vari != null)
2246               this.domain.Defvar (vname);
2247           }
2248         vname = Xex.Term.Parse (this.domain, node)
2249       }
2250   }
2251   parsers['command-list'] = function (node)
2252   {
2253   }
2254   parsers['macro-list'] = function (node)
2255   {
2256     for (var n = node.firstElement (); n; n = n.nextElement ())
2257       if (n.nodeName == 'xi:include')
2258         {
2259           var im = include (n);
2260           if (! im)
2261             alert ('inclusion fail');
2262           else
2263             for (var macro in im.domain.functions)
2264               {
2265                 var func = im.domain.functions[macro];
2266                 if (func instanceof Xex.Macro)
2267                   im.domain.CopyFunc (this.domain, macro);
2268               }
2269           n = n.previousSibling;
2270           node.removeChild (n.nextSibling);
2271         }
2272     Xex.Term.Parse (this.domain, node.firstElement (), null);
2273   }
2274   parsers['title'] = function (node)
2275   {
2276     this.title = node.firstChild.nodeValue;
2277   }
2278   parsers['map-list'] = function (node)
2279   {
2280     for (node = node.firstElement (); node; node = node.nextElement ())
2281       {
2282         if (node.nodeName == 'xi:include')
2283           {
2284             var im = include (node);
2285             if (! im)
2286               {
2287                 alert ('inclusion fail');
2288                 continue;
2289               }
2290             for (var mapname in im.map_list)
2291               this.map_list[mapname] = im.map_list[mapname];
2292           }
2293         else
2294           {
2295             var map = Xex.Term.Parse (this.domain, node);
2296             this.map_list[map.name] = map;
2297           }
2298       }
2299   }
2300   parsers['state-list'] = function (node)
2301   {
2302     this.domain.map_list = this.map_list;
2303     for (node = node.firstElement (); node; node = node.nextElement ())
2304       {
2305         if (node.nodeName == 'state')
2306           {
2307             var state = Xex.Term.Parse (this.domain, node);
2308             if (! state.title)
2309               state.title = this.title;
2310             if (! this.initial_state)
2311               this.initial_state = state;
2312             this.state_list[state.name] = state;
2313           }
2314       }
2315     delete this.domain.map_list;
2316   }
2317
2318   MIM.IM = function (lang, name, extra_id, file)
2319   {
2320     this.lang = lang;
2321     this.name = name;
2322     this.extra_id = extra_id;
2323     this.file = file;
2324     this.load_status = MIM.LoadStatus.NotLoaded;
2325     this.domain = new Xex.Domain (this.lang + '-'
2326                                   + (this.name != 'nil'
2327                                      ? this.name : this.extra_id),
2328                                   MIM.im_domain, null);
2329   }
2330
2331   var proto = {
2332     Load: function ()
2333     {
2334       var node = Xex.Load (null, this.file);
2335       if (! node)
2336         {
2337           this.load_status = MIM.LoadStatus.Error;
2338           return false;
2339         }
2340       this.map_list = {};
2341       this.initial_state = null;
2342       this.state_list = {};
2343       for (node = node.firstElement (); node; node = node.nextElement ())
2344         {
2345           var name = node.nodeName;
2346           var parser = parsers[name];
2347           if (parser)
2348             parser.call (this, node);
2349         }
2350       this.load_status = MIM.LoadStatus.Loaded;
2351       return true;
2352     }
2353   }
2354
2355   MIM.IM.prototype = proto;
2356
2357   MIM.IC = function (im, target)
2358   {
2359     if (im.load_status == MIM.LoadStatus.NotLoaded)
2360       im.Load ();
2361     if (im.load_status != MIM.LoadStatus.Loaded)
2362       alert ('im:' + im.name + ' error:' + im.load_status);
2363     this.im = im;
2364     this.target = target;
2365     this.domain = new Xex.Domain ('context', im.domain, this);
2366     this.active = true;
2367     this.range = new Array ();
2368     this.range[0] = this.range[1] = 0;
2369     this.state = null;
2370     this.initial_state = this.im.initial_state;
2371     this.keys = new MIM.KeySeq ();
2372     this.marker_positions = new Array ();
2373     this.candidate_table = new MIM.CandidateTable ();
2374     this.reset ();
2375   }
2376
2377   MIM.CandidateTable = function ()
2378   {
2379     this.table = new Array ();
2380   }
2381
2382   MIM.CandidateTable.prototype.get = function (pos)
2383   {
2384     for (var i = 0; i < this.table.length; i++)
2385       {
2386         var elt = this.table[i];
2387         if (elt.from < pos && pos <= elt.to)
2388           return elt.val;
2389       }
2390   }
2391
2392   MIM.CandidateTable.prototype.put = function (from, to, candidates)
2393   {
2394     for (var i = 0; i < this.table.length; i++)
2395       {
2396         var elt = this.table[i];
2397         if (elt.from < to && elt.to > from)
2398           {
2399             elt.from = from;
2400             elt.to = to;
2401             elt.val = candidates;
2402             return;
2403           }
2404       }
2405     this.table.push ({ from: from, to: to, val: candidates });
2406   }
2407
2408   MIM.CandidateTable.prototype.adjust = function (from, to, inserted)
2409   {
2410     var diff = inserted - (to - from);
2411     if (diff == 0)
2412       return;
2413     for (var i = 0; i < this.table.length; i++)
2414       {
2415         var elt = this.table[i];
2416         if (elt.from >= to)
2417           {
2418             elt.from += diff;
2419             elt.to += diff;
2420           }
2421       }
2422   }
2423
2424   MIM.CandidateTable.prototype.clear = function ()
2425   {
2426     this.table.length = 0;
2427   }
2428
2429   function detach_candidates (ic)
2430   {
2431     ic.candidate_table.clear ();
2432     ic.candidates = null;
2433     ic.changed |= (MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos
2434                    | MIM.ChangedStatus.CandidateList
2435                    | MIM.ChangedStatus.CandidateIndex
2436                    | MIM.ChangedStatus.CandidateShow);
2437   }
2438
2439   function set_cursor (prefix, pos)
2440   {
2441     this.cursor_pos = pos;
2442     this.candidates = this.candidate_table.get (pos);
2443   }
2444
2445   function save_state ()
2446   {
2447     this.state_var_values = this.domain.SaveValues ();
2448     this.state_preedit = this.preedit;
2449     this.state_key_head = this.key_head;
2450     this.state_pos = this.cursor_pos;
2451   }
2452
2453   function restore_state ()
2454   {
2455     this.domain.RestoreValues (this.state_var_values);
2456     this.preedit = this.state_preedit;
2457     set_cursor.call (this, "restore", this.state_pos);
2458   }
2459
2460   function handle_key ()
2461   {
2462     var out = this.keymap.Lookup (this.keys, this.key_head);
2463     var sub = out.map;
2464
2465     Xex.Log ('handling ' + this.keys.val[this.key_head]
2466              + ' in ' + this.state.name + ':' + this.keymap.name);
2467     this.key_head = out.index;
2468     if (sub != this.keymap)
2469       {
2470
2471         restore_state.call (this);
2472         this.keymap = sub;
2473         Xex.Log ('submap found');
2474         if (this.keymap.map_actions)
2475           {
2476             Xex.Log ('taking map actions:');
2477             if (! this.take_actions (this.keymap.map_actions))
2478               return false;
2479           }
2480         else if (this.keymap.submaps)
2481           {
2482             Xex.Log ('no map actions');
2483             for (var i = this.state_key_head; i < this.key_head; i++)
2484               {
2485                 Xex.Log ('inserting key:' + this.keys.val[i].key);
2486                 this.ins (this.keys.val[i].key, null);
2487               }
2488           }
2489         if (! this.keymap.submaps)
2490           {
2491             Xex.Log ('terminal:');
2492             if (this.keymap.branch_actions != null)
2493               {
2494                 Xex.Log ('branch actions:');
2495                 if (! this.take_actions (this.keymap.branch_actions))
2496                   return false;
2497               }
2498             if (this.keymap != this.state.keymap)
2499               this.shift (this.state);
2500           }
2501       }
2502     else
2503       {
2504         Xex.Log ('no submap');
2505         var current_state = this.state;
2506         var map = this.keymap;
2507
2508         if (map.branch_actions)
2509           {
2510             Xex.Log ('branch actions');
2511             if (! this.take_actions (map.branch_actions))
2512               return false;
2513           }
2514
2515         if (map == this.keymap)
2516           {
2517             Xex.Log ('no state change');
2518             if (map == this.initial_state.keymap
2519                 && this.key_head < this.keys.val.length)
2520               {
2521                 Xex.Log ('unhandled');
2522                 return false;
2523               }
2524             if (this.keymap != current_state.keymap)
2525               this.shift (current_state);
2526             else if (this.keymap.actions == null)
2527               this.shift (this.initial_state);
2528           }
2529       }
2530     return true;
2531   }
2532
2533   proto = {
2534     reset: function ()
2535     {
2536       Xex.Log ('reseting ' + this.im.lang);
2537       this.cursor_pos = 0;
2538       this.candidate_show = false;
2539       this.prev_state = null;
2540       this.title = this.initial_state.title;
2541       this.state_preedit = '';
2542       this.state_key_head = 0;
2543       this.state_var_values = {};
2544       this.state_pos = 0;
2545       this.key_head = 0;
2546       this.keys.val.length = 0;
2547       this.key_unhandled = false;
2548       this.unhandled_key = null;
2549       this.changed = MIM.ChangedStatus.None;
2550       this.error_message = '';
2551       this.title = this.initial_state.title;
2552       this.produced = '';
2553       this.preedit = '';
2554       this.preedit_saved = '';
2555       this.candidate_table.clear ();
2556       this.candidates = null;
2557       this.candidate_show = false;
2558       for (var elt in this.marker_positions)
2559         this.marker_positions[elt] = 0;
2560       this.shift (this.initial_state);
2561     },
2562
2563     catch_args: new Array (Xex.CatchTag._mimtag, null),
2564
2565     take_actions: function (actions)
2566     {
2567       var func_progn = this.domain.GetFunc ('progn');
2568       var func_catch = this.domain.GetFunc ('catch');
2569       this.catch_args[1] = new Xex.Funcall (func_progn, null, actions);
2570       var term = new Xex.Funcall (func_catch, null, this.catch_args);
2571       term = term.Eval (this.domain);
2572       return (! term.IsSymbol || term.val != '@mimtag');
2573     },
2574
2575     GetSurroundingChar: function (pos)
2576     {
2577       if (pos < 0)
2578         {
2579           pos += this.range[0];
2580           if (pos < 0)
2581             return 0;
2582         }
2583       else
2584         {
2585           pos += this.range[1];
2586           if (pos >= this.target.value.length)
2587             return 0;
2588         }
2589       return this.target.value.charCodeAt (pos);
2590     },
2591     
2592     DelSurroundText: function (pos)
2593     {
2594       var text;
2595       if (pos < 0)
2596         {
2597           pos += this.range[0];
2598           if (pos <= 0)
2599             {
2600               pos = 0; text = '';
2601             }
2602           else
2603             text = this.target.value.substring (0, pos);
2604           if (this.range[0] < this.target.value.length)
2605             text += this.target.value.substring (this.range[0]);
2606           this.target.value = text;
2607           this.range[1] -= this.range[0] - pos;
2608           this.range[0] = pos;
2609         }
2610       else
2611         {
2612           pos += this.range[1];
2613           text = this.target.value.substring (0, this.range[1]);
2614           if (pos >= this.target.value.length)
2615             pos = this.target.value.length;
2616           else
2617             text += this.target.value.substring (pos);
2618           this.target.value = text;
2619         }
2620     },
2621
2622     adjust_markers: function (from, to, inserted)
2623     {
2624       var diff = inserted - (to - from);
2625
2626       for (var name in this.marker_positions)
2627         {
2628           var pos = this.marker_positions[name];
2629           if (pos > from)
2630             {
2631               if (pos >= to)
2632                 this.marker_positions[name] += diff;
2633               else if (pos > from)
2634                 this.marker_positions[name] = from;
2635             }
2636         }
2637       if (this.cursor_pos >= to)
2638         set_cursor.call (this, 'adjust', this.cursor_pos + diff);
2639       else if (this.cursor_pos > from)
2640         set_cursor.call (this, 'adjust', from)
2641     },
2642
2643     preedit_replace: function (from, to, text, candidates)
2644     {
2645       this.preedit = (this.preedit.substring (0, from)
2646                       + text + this.preedit.substring (to));
2647       this.adjust_markers (from, to, text.length);
2648       this.candidate_table.adjust (from, to, text.length);
2649       if (candidates)
2650         this.candidate_table.put (from, from + text.length, candidates)
2651     },
2652
2653     ins: function (text, candidates)
2654     {
2655       this.preedit_replace (this.cursor_pos, this.cursor_pos, text, candidates);
2656       this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2657     },
2658
2659     rep: function (old_text, new_text, candidates)
2660     {
2661       this.preedit_replace (this.cursor_pos - old_text.length,
2662                             this.cursor_pos, new_text, candidates);
2663       this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2664     },
2665
2666     del: function (pos)
2667     {
2668       var deleted = pos - this.cursor_pos;
2669       if (pos < this.cursor_pos)
2670         {
2671           if (pos < 0)
2672             {
2673               this.DelSurroundText (pos);
2674               deleted = - this.cursor_pos;
2675               pos = 0;
2676             }
2677           if (pos < this.cursor_pos)
2678             this.preedit_replace (pos, this.cursor_pos, '', null);
2679         }
2680       else
2681         {
2682           if (pos > this.preedit.length)
2683             {
2684               this.DelSurroundText (pos - this.preedit.length);
2685               deleted = this.preedit.length - this.cursor_pos;
2686               pos = this.preedit.length;
2687             }
2688           if (pos > this.cursor_pos)
2689             this.preedit_replace (this.cursor_pos, pos, '', null);
2690         }
2691       if (deleted != 0)
2692         this.changed = MIM.ChangedStatus.Preedit | MIM.ChangedStatus.CursorPos;
2693       return deleted;
2694     },
2695
2696     show: function ()
2697     {
2698       this.candidate_show = true;
2699       this.changed |= MIM.ChangedStatus.CandidateShow;
2700     },
2701
2702     hide: function ()
2703     {
2704       this.candidate_show = false;
2705       this.changed |= MIM.ChangedStatus.CandidateShow;
2706     },
2707
2708     move: function (pos)
2709     {
2710       if (pos < 0)
2711         pos = 0;
2712       else if (pos > this.preedit.length)
2713         pos = this.preedit.length;
2714       if (pos != this.cursor_pos)
2715         {
2716           set_cursor.call (this, 'move', pos);
2717           this.changed |= MIM.ChangedStatus.Preedit;
2718         }
2719     },
2720
2721     pushback: function (n)
2722     {
2723       if (n instanceof MIM.KeySeq)
2724         {
2725           if (this.key_head > 0)
2726             this.key_head--;
2727           if (this.key_head < this.keys.val.length)
2728             this.keys.val.splice (this.key_head,
2729                                   this.keys.val.length - this.key_head);
2730           for (var i = 0; i < n.val.length; i++)
2731             this.keys.val.push (n.val[i]);
2732           return;
2733         }
2734       if (n > 0)
2735         {
2736           this.key_head -= n;
2737           if (this.key_head < 0)
2738             this.key_head = 0;
2739         }
2740       else if (n == 0)
2741         this.key_head = 0;
2742       else
2743       {
2744         this.key_head = - n;
2745         if (this.key_head > this.keys.val.length)
2746           this.key_head = this.keys.val.length;
2747       }
2748     },
2749
2750     pop: function ()
2751     {
2752       if (this.key_head < this.keys.val.length)
2753         this.keys.val.splice (this.key_head, 1);
2754     },
2755
2756     commit: function ()
2757     {
2758       if (this.preedit.length > 0)
2759       {
2760         this.candidate_table.clear ();
2761         this.produced += this.preedit;
2762         this.preedit_replace.call (this, 0, this.preedit.length, '', null);
2763       }
2764     },
2765
2766     shift: function (state)
2767     {
2768       if (state == null)
2769         {
2770           if (this.prev_state == null)
2771             return;
2772           state = this.prev_state;
2773         }
2774
2775       if (state == this.initial_state)
2776         {
2777           if (this.state)
2778             {
2779               this.commit ();
2780               this.keys.val.splice (0, this.key_head);
2781               this.key_head = 0;
2782               this.prev_state = null;
2783             }
2784         }
2785       else
2786         {
2787           if (state != this.state)
2788             this.prev_state = this.state;
2789         }
2790       if (state != this.state && state.enter_actions)
2791         this.take_actions (state.enter_actions);
2792       if (! this.state || this.state.title != state.title)
2793         this.changed |= MIM.ChangedStatus.StateTitle;
2794       this.state = state;
2795       this.keymap = state.keymap;
2796       this.state_key_head = this.key_head;
2797       save_state.call (this);
2798     },
2799
2800     Filter: function (key)
2801     {
2802       if (! this.active)
2803         {
2804           this.key_unhandled = true;
2805           this.unhandled_key = key;
2806           return false;
2807         }
2808       if (key.key == '_reload')
2809         return true;
2810       this.changed = MIM.ChangedStatus.None;
2811       this.produced = '';
2812       this.key_unhandled = false;
2813       this.keys.val.push (key);
2814       var count = 0;
2815       while (this.key_head < this.keys.val.length)
2816         {
2817           if (! handle_key.call (this))
2818             {
2819               if (this.key_head < this.keys.val.length)
2820                 {
2821                   this.unhandled_key = this.keys.val[this.key_head];
2822                   this.keys.val.splice (this.key_head, this.key_head + 1);
2823                 }
2824               this.key_unhandled = true;
2825               break;
2826             }
2827           if (++count == 10)
2828             {
2829               this.reset ();
2830               this.key_unhandled = true;
2831               break;
2832             }
2833         }
2834       if (this.key_unhandled)
2835         {
2836           this.keys.val.length = 0;
2837           this.key_head = this.state_key_head = this.commit_key_head = 0;
2838         }
2839       return (! this.key_unhandled
2840               && this.produced.length == 0
2841               && this.preedit.length == 0);
2842     }
2843   }
2844
2845   MIM.IC.prototype = proto;
2846
2847   var node = Xex.Load (null, "imlist.xml");
2848   for (node = node.firstChild; node; node = node.nextSibling)
2849     if (node.nodeName == 'input-method')
2850       {
2851         var lang = null, name = null, extra_id = null, file = null;
2852
2853         for (var n = node.firstChild; n; n = n.nextSibling)
2854           {
2855             if (n.nodeName == 'language')
2856               lang = n.firstChild.nodeValue;
2857             else if (n.nodeName == 'name')
2858               name = n.firstChild.nodeValue;
2859             else if (n.nodeName == 'extra-id')
2860               extra_id = n.firstChild.nodeValue;
2861             else if (n.nodeName == 'filename')
2862               file = n.firstChild.nodeValue;
2863           }
2864         if (name && name != 'nil')
2865           {
2866             if (! MIM.imlist[lang])
2867               MIM.imlist[lang] = {};
2868             MIM.imlist[lang][name] = new MIM.IM (lang, name, extra_id, file);
2869           }
2870         else if (extra_id && extra_id != 'nil')
2871           {
2872             if (! MIM.imextra[lang])
2873               MIM.imextra[lang] = {};
2874             MIM.imextra[lang][extra_id] = new MIM.IM (lang, name, extra_id, file);
2875           }
2876       }
2877   if (MIM.imextra.t && MIM.imextra.t.global)
2878     MIM.im_global = MIM.imextra.t.global;
2879   else
2880     {
2881       MIM.im_global = new MIM.IM ('t', 'nil', 'global', null);
2882       MIM.im_global.load_status = MIM.LoadStatus.Error;
2883     }
2884   node = undefined;
2885 }) ();
2886
2887 (function () {
2888   var keys = new Array ();
2889   keys[0x09] = 'tab';
2890   keys[0x08] = 'backspace';
2891   keys[0x0D] = 'return';
2892   keys[0x1B] = 'escape';
2893   keys[0x20] = 'space';
2894   keys[0x21] = 'pageup';
2895   keys[0x22] = 'pagedown';
2896   keys[0x23] = 'end';
2897   keys[0x24] = 'home';
2898   keys[0x25] = 'left';
2899   keys[0x26] = 'up';
2900   keys[0x27] = 'right';
2901   keys[0x28] = 'down';
2902   keys[0x2D] = 'insert';
2903   keys[0x2E] = 'delete';
2904   for (var i = 1; i <= 12; i++)
2905     keys[111 + i] = "f" + i;
2906   keys[0x90] = "numlock";
2907   keys[0xF0] = "capslock";
2908
2909   var keyids = {};
2910   keyids['U+0008'] = 'backspace';
2911   keyids['U+0009'] = 'tab';
2912   keyids['U+0018'] = 'cancel';
2913   keyids['U+001B'] = 'escape';
2914   keyids['U+0020'] = 'space';
2915   keyids['U+007F'] = 'delete';
2916
2917   var modifiers = {}
2918   modifiers.Shift = 1;
2919   modifiers.Control = 1;
2920   modifiers.Alt = 1;
2921   modifiers.AltGraph = 1;
2922   modifiers.Meta = 1
2923
2924   MIM.decode_key_event = function (event)
2925   {
2926     var key = event.keyIdentifier;
2927
2928     if (key)                    // keydown event of Chrome
2929       {
2930         if (modifiers[key])
2931           return false;
2932         var mod = '';
2933         if (event.ctrlKey) mod += 'C-';
2934         if (event.metaKey) mod += 'M-';
2935         if (event.altKey) mod += 'A-';
2936         var keysym = keyids[key];
2937         if (keysym)
2938           key = keysym;
2939         else if (key.match(/^U\+([0-9A-Z]+)$/))
2940           {
2941             if (mod.length == 0)
2942               return false;
2943             key = String.fromCharCode (parseInt (RegExp.$1, 16));
2944           }
2945         else
2946           key = key.toLowerCase ();
2947         if (event.shiftKey) mod += 'S-';
2948         return new MIM.Key (mod + key);
2949       }
2950     else
2951       {
2952         key = ((event.type == 'keydown' || event.keyCode) ? event.keyCode
2953                : event.charCode ? event.charCode
2954                : false);
2955         if (! key)
2956           return false;
2957         if (event.type == 'keydown')
2958           {
2959             key = keys[key];
2960             if (! key)
2961               return false;
2962             if (event.shiftKey) key = "S-" + key ;
2963           }
2964         else
2965           key = String.fromCharCode (key);
2966       }
2967     if (event.altKey) key = "A-" + key ;
2968     if (event.ctrlKey) key = "C-" + key ;
2969     return new MIM.Key (key);
2970   }
2971 }) ();
2972
2973 MIM.add_event_listener
2974   = (window.addEventListener
2975      ? function (target, type, listener) {
2976        target.addEventListener (type, listener, false);
2977      }
2978      : window.attachEvent
2979      ? function (target, type, listener) {
2980        target.attachEvent ('on' + type,
2981                            function() {
2982                              listener.call (target, window.event);
2983                            });
2984      }
2985      : function (target, type, listener) {
2986        target['on' + type]
2987          = function (e) { listener.call (target, e || window.event); };
2988      });
2989
2990 MIM.debug_print = function (event, ic)
2991 {
2992   if (! MIM.debug)
2993     return;
2994   if (! MIM.debug_nodes)
2995     {
2996       MIM.debug_nodes = new Array ();
2997       MIM.debug_nodes['status0'] = document.getElementById ('status0');
2998       MIM.debug_nodes['status1'] = document.getElementById ('status1');
2999       MIM.debug_nodes['keydown'] = document.getElementById ('keydown');
3000       MIM.debug_nodes['keypress'] = document.getElementById ('keypress');
3001       MIM.debug_nodes['keymap0'] = document.getElementById ('keymap0');
3002       MIM.debug_nodes['keymap1'] = document.getElementById ('keymap1');
3003       MIM.debug_nodes['preedit0'] = document.getElementById ('preedit0');
3004       MIM.debug_nodes['preedit1'] = document.getElementById ('preedit1');
3005     }
3006   var target = event.target;
3007   var code = event.keyCode;
3008   var ch = event.type == 'keypress' ? event.charCode : 0;
3009   var key = MIM.decode_key_event (event);
3010   var index;
3011
3012   MIM.debug_nodes[event.type].innerHTML = "" + code + "/" + ch + ":" + key + '/' + event.keyIdentifier;
3013   index = (event.type == 'keydown' ? '0' : '1');
3014   if (ic)
3015     MIM.debug_nodes['status' + index].innerHTML = ic.im.load_status;
3016   else
3017     MIM.debug_nodes['status' + index].innerHTML = 'no IM';
3018   MIM.debug_nodes['keymap' + index].innerHTML = ic.state.name;
3019   MIM.debug_nodes['preedit' + index].innerHTML = ic.preedit;
3020   if (index == 0)
3021     {
3022       MIM.debug_nodes.keypress.innerHTML = '';
3023       MIM.debug_nodes.status1.innerHTML = '';
3024       MIM.debug_nodes.keymap1.innerHTML = '';
3025       MIM.debug_nodes.preedit1.innerHTML = ''
3026     }
3027 };
3028
3029 MIM.get_range = function (target, ic)
3030 {
3031   var from, to;
3032   if (target.selectionStart != null) // for Mozilla
3033     {
3034       from = target.selectionStart;
3035       to = target.selectionEnd;
3036     }
3037   else                          // for IE
3038     {
3039       var r = document.selection.createRange ();
3040       var rr = r.duplicate ();
3041
3042       rr.moveToElementText (target);
3043       rr.setEndPoint ('EndToEnd', range);
3044       from = rr.text.length - r.text.length;
3045       to = rr.text.length;
3046     }
3047   if (ic.range[0] == from && ic.range[1] == to
3048       && (to == from || target.value.substring (from, to) == ic.preedit))
3049     return true;
3050   ic.range[0] = from;
3051   ic.range[1] = to;
3052   return false;
3053 }
3054
3055 MIM.set_caret = function (target, ic)
3056 {
3057   if (target.setSelectionRange) // Mozilla
3058     {
3059       var scrollTop = target.scrollTop;
3060       target.setSelectionRange (ic.range[0], ic.range[1]);
3061       target.scrollTop = scrollTop;
3062     }
3063   else                          // IE
3064     {
3065       var range = target.createTextRange ();
3066       range.moveStart ('character', ic.range[0]);
3067       range.moveEnd ('character', ic.range[1]);
3068       range.select ();
3069     }
3070 };
3071
3072 MIM.update = function (target, ic)
3073 {
3074   var text = target.value;
3075   target.value = (text.substring (0, ic.range[0])
3076                   + ic.produced
3077                   + ic.preedit
3078                   + text.substring (ic.range[1]));
3079   ic.range[0] += ic.produced.length;
3080   ic.range[1] = ic.range[0] + ic.preedit.length;
3081   MIM.set_caret (target, ic);
3082 };
3083
3084 MIM.reset_ic = function (event)
3085 {
3086   if (event.target.mim_ic)
3087     {
3088       var target = event.target;
3089       var ic = target.mim_ic;
3090       if (ic.preedit.length > 0)
3091         event.target.setSelectionRange (ic.range[1], ic.range[1]);
3092       ic.reset ();
3093     }
3094 };
3095
3096 MIM.keydown = function (event)
3097 {
3098   var target = event.target;
3099   if (target.id == 'log')
3100     return;
3101   if (! (target.type == "text" || target.type == "textarea"))
3102     return;
3103
3104   var ic = target.mim_ic;
3105   if (! ic || ic.im != MIM.current)
3106     {
3107       target.mim_ic = null;
3108       Xex.Log ('creating IC');
3109       ic = new MIM.IC (MIM.current, target);
3110       if (ic.im.load_status != MIM.LoadStatus.Loaded)
3111         return;
3112       target.mim_ic = ic;
3113       MIM.add_event_listener (target, 'blur', MIM.reset_ic);
3114       MIM.get_range (target, ic)
3115     }
3116   else
3117     {
3118       if (! MIM.get_range (target, ic))
3119         ic.reset ();
3120     }
3121   MIM.debug_print (event, ic);
3122   ic.key = MIM.decode_key_event (event);
3123   if (ic.key)
3124     {
3125       Xex.Log ("filtering " + ic.key);
3126       try {
3127         var result = ic.Filter (ic.key);
3128       } catch (e) {
3129         Xex.Log ('Error;' + e);
3130         throw (e);
3131       }
3132       MIM.update (target, ic);
3133       if (! ic.key_unhandled)
3134         event.preventDefault ();
3135     }
3136 };
3137
3138 MIM.keypress = function (event)
3139 {
3140   var target = event.target;
3141   if (target.id == 'log')
3142     return;
3143   if (! (target.type == "text" || target.type == "textarea"))
3144     return;
3145
3146   var ic = target.mim_ic;
3147   var i;
3148
3149   try {
3150     if (ic.im.load_status != MIM.LoadStatus.Loaded)
3151       return;
3152     if (! ic.key)
3153       ic.key = MIM.decode_key_event (event);
3154     if (! ic.key)
3155       {
3156         ic.reset ();
3157         return;
3158       }
3159     
3160     Xex.Log ("filtering " + ic.key);
3161     try {
3162       var result = ic.Filter (ic.key);
3163     } catch (e) {
3164       Xex.Log ('Error;' + e);
3165       throw (e);
3166     }
3167     MIM.update (target, ic);
3168     if (! ic.key_unhandled)
3169       event.preventDefault ();
3170   } catch (e) {
3171     Xex.Log ("error:" + e);
3172     event.preventDefault ();
3173   } finally {
3174     MIM.debug_print (event, ic);
3175   }
3176   return;
3177 };
3178
3179 (function () {
3180   var lang_category = {
3181     European: {
3182       cs: { name: 'Czech' },
3183       da: { name: 'Danish' },
3184       el: { name: 'Greek' },
3185       en: { name: 'English' },
3186       eo: { name: 'Esperanto' },
3187       fr: { name: 'French' },
3188       grc: { name: 'ClassicGreek' },
3189       hr: { name: 'Croatian' },
3190       hy: { name: 'Armenian' },
3191       ka: { name: 'Georgian' },
3192       kk: { name: 'Kazakh' },
3193       ru: { name: 'Russian' },
3194       sk: { name: 'Slovak' },
3195       sr: { name: 'Serbian' },
3196       sv: { name: 'Swedish' },
3197       vi: { name: 'Vietnamese' },
3198       yi: { name: 'Yiddish' } },
3199     MiddleEast: {
3200       ar: { name: 'Arabic' },
3201       dv: { name: 'Divehi' },
3202       fa: { name: 'Persian' },
3203       he: { name: 'Hebrew' },
3204       kk: { name: 'Kazakh' },
3205       ps: { name: 'Pushto' },
3206       ug: { name: 'Uighur' },
3207       yi: { name: 'Yiddish' } },
3208     SouthAsia: {
3209       as: { name: 'Assamese' },
3210       bn: { name: 'Bengali' },
3211       bo: { name: 'Tibetan' },
3212       gu: { name: 'Gujarati' },
3213       hi: { name: 'Hindi' },
3214       kn: { name: 'Kannada' },
3215       ks: { name: 'Kashmiri' },
3216       ml: { name: 'Malayalam' },
3217       mr: { name: 'Marathi' },
3218       ne: { name: 'Nepali' },
3219       or: { name: 'Oriya' },
3220       pa: { name: 'Panjabi' },
3221       sa: { name: 'Sanskirit' },
3222       sd: { name: 'Sindhi' },
3223       si: { name: 'Sinhalese' },
3224       ta: { name: 'Tamil' },
3225       te: { name: 'Telugu' },
3226       ur: { name: 'Urdu' } },
3227     SouthEastAsia: {
3228       cmc: { name: 'Cham' },
3229       km: { name: 'Khmer'},
3230       lo: { name: 'Lao' },
3231       my: { name: 'Burmese' },
3232       tai: { name: 'Tai Viet' },
3233       th: { name: 'Thai' },
3234       vi: { name: 'Vietanamese' } },
3235     EastAsia: {
3236       ii: { name: 'Yii' },
3237       ja: { name: 'Japanese' },
3238       ko: { name: 'Korean' },
3239       zh: { name: 'Chinese' } },
3240     Other: {
3241       am: { name:  'Amharic' },
3242       ath: { name: 'Carrier' },
3243       bla: { name: 'Blackfoot' },
3244       cr: { name: 'Cree' },
3245       eo: { name: 'Esperanto' },
3246       iu: { name: 'Inuktitut' },
3247       nsk: { name: 'Naskapi' },
3248       oj: { name: 'Ojibwe' },
3249       t: { name: 'Generic' } }
3250   };
3251
3252   function categorize_im ()
3253   {
3254     var cat, lang, list, name;
3255     for (lang in MIM.imlist)
3256       {
3257         list = null;
3258         for (cat in lang_category)
3259           if (lang_category[cat][lang])
3260             {
3261               list = lang_category[cat][lang].list;
3262               if (! list)
3263                 list = lang_category[cat][lang].list = {};
3264               break;
3265             }
3266         if (list)
3267           for (name in MIM.imlist[lang])
3268             list[name] = MIM.imlist[lang][name];
3269         else
3270           for (name in MIM.imlist[lang])
3271             Xex.Log ('no category ' + lang + '-' + name);
3272       }
3273   }
3274
3275   var destroy_timer;
3276   var last_target;
3277
3278   function destroy ()
3279   {
3280     clearTimeout (destroy_timer);
3281     destroy_timer = null;
3282     var target = document.getElementById ('mim-menu');
3283     if (target)
3284       {
3285         for (; last_target && last_target.menu_level;
3286              last_target = last_target.parentLi)
3287           last_target.style.backgroundColor = 'white';
3288         var nodes = target.getElementsByTagName ('ul');
3289         for (var i = 0; i < nodes.length; i++)
3290           nodes[i].style.visibility = 'hidden';
3291         document.getElementsByTagName ('body')[0].removeChild (target);
3292       }
3293   }    
3294
3295   function destroy_menu () {
3296     if (! destroy_timer)
3297       destroy_timer = setTimeout (destroy, 1000);
3298   }
3299
3300   function show_submenu (event)
3301   {
3302     if (destroy_timer)
3303       {
3304         clearTimeout (destroy_timer);
3305         destroy_timer = null;
3306       }
3307     var target = event.target;
3308     if (! target.menu_level)
3309       return;
3310     if (last_target && target.parentLi != last_target)
3311       {
3312         last_target.style.backgroundColor = 'white';
3313         if (target.menu_level < last_target.menu_level)
3314           {
3315             last_target = last_target.parentLi;
3316             last_target.style.backgroundColor = 'white';
3317           }
3318         var uls = last_target.getElementsByTagName ('ul');
3319         for (var i = 0; i < uls.length; i++)
3320           uls[i].style.visibility = 'hidden';
3321       }
3322     last_target = target;
3323     target.style.backgroundColor = 'yellow';
3324     if (target.menu_level < 3)
3325       {
3326         target.lastChild.style.visibility = 'visible';
3327         target.lastChild.style.left = target.clientWidth + 'px';
3328       }
3329     event.preventDefault ();    
3330   }
3331
3332   function select_im (event)
3333   {
3334     var target = event.target;
3335     if (target.im)
3336       {
3337         MIM.current = target.im;
3338         destroy ();
3339       }
3340     event.preventDefault ();
3341   }
3342
3343   function create_ul (visibility)
3344   {
3345     var ul = document.createElement ('ul');
3346     ul.style.position = 'absolute';
3347     ul.style.margin = '0px';
3348     ul.style.padding = '0px';
3349     ul.style.border = '1px solid gray';
3350     ul.style.borderBottom = 'none';
3351     ul.style.top = '-1px';
3352     ul.style.backgroundColor = 'white';
3353     ul.style.visibility = visibility;
3354     return ul;
3355   }
3356
3357   function create_li (level, text)
3358   {
3359     var li = document.createElement ('li');
3360     li.style.position = 'relative';
3361     li.style.margin = '0px';
3362     li.style.padding = '1px';
3363     li.style.borderBottom = '1px solid gray';
3364     li.style.top = '0px';
3365     li.style.listStyle = 'none';
3366     li.menu_level = level;
3367     li.appendChild (document.createTextNode (text));
3368     return li;
3369   }
3370
3371   var menu;
3372
3373   function create_menu (event)
3374   {
3375     var target = event.target;
3376
3377     if (! ((target.type == "text" || target.type == "textarea")
3378            && event.which == 1 && event.ctrlKey))
3379       return;
3380     if (! menu)
3381       {
3382         categorize_im ();
3383         menu = create_ul ('visible');
3384         menu.style.fontFamily = 'sans-serif';
3385         menu.style.fontWeight = 'bold';
3386         menu.id = 'mim-menu';
3387         menu.onclick = select_im;
3388         menu.onmouseover = show_submenu;
3389         menu.onmouseout = destroy_menu;
3390         for (var catname in lang_category)
3391           {
3392             var cat = lang_category[catname];
3393             var li = create_li (1, catname);
3394             var sub = create_ul ('hidden');
3395             for (var langname in cat)
3396               {
3397                 var lang = cat[langname];
3398                 if (! lang.list)
3399                   continue;
3400                 var sub_li = create_li (2, lang.name);
3401                 sub_li.parentLi = li;
3402                 var subsub = create_ul ('hidden');
3403                 for (var name in lang.list)
3404                   {
3405                     var im = lang.list[name];
3406                     var subsub_li = create_li (3, im.name);
3407                     subsub_li.parentLi = sub_li;
3408                     subsub_li.im = im;
3409                     subsub.appendChild (subsub_li);
3410                   }
3411                 sub_li.appendChild (subsub);
3412                 sub.appendChild (sub_li);
3413               }
3414             li.appendChild (sub);
3415             menu.appendChild (li);
3416           }
3417         document.mimmenu = menu;
3418         lang_category = null;
3419       }
3420     menu.style.left = (event.clientX - 10) + "px";
3421     menu.style.top = (event.clientY - 10) + "px";
3422     document.getElementsByTagName ('body')[0].appendChild (menu);
3423   };
3424
3425   MIM.init = function ()
3426   {
3427     MIM.add_event_listener (window, 'keydown', MIM.keydown);
3428     MIM.add_event_listener (window, 'keypress', MIM.keypress);
3429     MIM.add_event_listener (window, 'mousedown', create_menu);
3430     if (window.location == 'http://localhost/mim/index.html')
3431       MIM.server = 'http://localhost/mim';
3432     MIM.current = MIM.imlist['vi']['telex'];
3433   };
3434 }) ();
3435
3436 MIM.test = function ()
3437 {
3438   var im = MIM.imlist['t']['latn-post'];
3439   var ic = new MIM.IC (im, null);
3440
3441   ic.Filter (new MIM.Key ('a'));
3442   ic.Filter (new MIM.Key ("'"));
3443
3444   if (true)
3445     document.getElementById ('text').value = ic.produced + ic.preedit;
3446   else {
3447     try {
3448       document.getElementById ('text').value
3449         = Xex.Term.Parse (domain, body).Eval (domain).toString ();
3450     } catch (e) {
3451       if (e instanceof Xex.ErrTerm)
3452         alert (e);
3453       throw e;
3454     }
3455   }
3456 }
3457
3458
3459 MIM.init_debug = function ()
3460 {
3461   MIM.debug = true;
3462   Xex.LogNode = document.getElementById ('log');
3463   Xex.Log (null);
3464   MIM.init ();
3465 };