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