*** empty log message ***
[m17n/m17n-lib-cs.git] / MInputMethod.cs
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Reflection;
5 using System.IO;
6 using System.Xml;
7
8 using M17N;
9 using M17N.Core;
10 using M17N.Input;
11
12 namespace M17N.Input
13 {
14   using Xex = System.Xml.Expression.Xexpression;
15
16   public class MInputMethod
17   {
18     // Delegaes
19     public delegate bool Callback (MInputContext ic, MPlist args);
20
21     // Class members
22     public static Callback PreeditStart, PreeditDone, PreeditDraw;
23     public static Callback StatusStart, StatusDone, StatusDraw;
24     public static Callback CandidateStart, CandidateDone, CandidateDraw;
25     public static Callback SetSpot;
26     public static Callback Toggle;
27     public static Callback Reset;
28     public static Callback GetSurroundingText;
29     public static Callback DeleteSurroundingText;
30
31     internal static Xex.Domain im_domain = new Xex.Domain (null);
32     private static MSymbol Minput_method = "input-method";
33     private static MSymbol Mdescription = "description";
34     private static MSymbol Mvariable = "variable";
35     private static MSymbol Mcommand = "command";
36     private static MSymbol Mmodule = "module";
37     private static MSymbol Mmodule_list = "module-list";
38     private static MSymbol Mtitle = "title";
39     private static MSymbol Minclude = "include";
40     private static MSymbol Mmacro = "macro";
41     private static MSymbol Mmacro_list = "macro-list";
42     private static MSymbol Mmap = "map";
43     private static MSymbol Mmap_list = "map-list";
44     private static MSymbol Mstate = "state";
45     private static MSymbol Mstate_list = "state-list";
46     internal static MSymbol Mcandidates = "candidates";
47     private static MSymbol Minsert = "insert";
48     private static MSymbol Mdelete = "delete";
49     private static MSymbol Mmove = "move";
50     private static MSymbol Mmark = "mark";
51     private static MSymbol Mmarker = "marker";
52     private static MSymbol Madd = "add";
53     private static MSymbol Msub = "sub";
54     private static MSymbol Mmul = "mul";
55     private static MSymbol Mdiv = "div";
56     private static MSymbol Mif = "if";
57     private static MSymbol Mcond = "cond";
58     private static MSymbol Mchar_at = "char-at";
59     private static MSymbol Msurrounding_text_p = "surrounding-text-p";
60     private static MSymbol Mpushback = "pushback"; 
61     private static MSymbol Mkeyseq = "keyseq"; 
62
63     private static Dictionary<MDatabase.Tag, MInputMethod> im_table
64       = new Dictionary<MDatabase.Tag, MInputMethod> ();
65
66     internal static MInputMethod im_global;
67
68     // Sub classes
69     private class Exception : System.Exception
70     {
71       bool error;
72
73       public Exception (string msg) : base (msg)
74         {
75           error = true;
76         }
77
78       public Exception (string fmt, params object[] args)
79         : base (String.Format (fmt, args))
80         {
81           error = true;
82         }
83
84       public Exception (string msg, bool error) : base (msg)
85         {
86           this.error = error;
87         }
88     }
89
90     [FlagsAttribute]
91     private enum LoadStatus
92     {
93       None =   0x00,
94       Header = 0x01,
95       Body =   0x02,
96       Full =   0x03,
97       Error =  0x04,
98     };
99
100     [FlagsAttribute]
101     public enum KeyModifier
102       {
103         None =      0x00000000,
104         Shift_L =   0x00400000,
105         Shift_R =   0x00800000,
106         Shift =     0x00C00000,
107         Control_L = 0x01000000,
108         Control_R = 0x02000000,
109         Control   = 0x03000000,
110         Alt_L =     0x04000000,
111         Alt_R =     0x08000000,
112         Alt =       0x0C000000,
113         AltGr =     0x10000000,
114         Super =     0x20000000,
115         Hyper =     0x40000000,
116         High =      0x70000000,
117         All =       0x7FC00000,
118       };
119
120     public struct Key
121     {
122       internal uint key;
123
124       private static Dictionary<string, uint> keysyms
125         = new Dictionary<string, uint> ();
126       private static Dictionary<string, KeyModifier> keymodifiers
127         = new Dictionary<string, KeyModifier> ();
128       private static uint keysym_base = 0x200000;
129       private static uint char_mask = ~((uint) KeyModifier.All);
130
131       static Key ()
132       {
133         keysyms["bs"] = keysyms["backspace"] = 0x08;
134         keysyms["tab"] = 0x09;
135         keysyms["lf"] = keysyms["linefeed"] = 0x10;
136         keysyms["cr"] = keysyms["return"] = keysyms["enter"] = 0x13;
137         keysyms["esc"] = keysyms["escape"] = 0x1B;
138         keysyms["spc"] = keysyms["space"] = 0x20;
139         keysyms["del"] = keysyms["delete"] = 0x7F;
140         keymodifiers["shift-l"] = KeyModifier.Shift_L;
141         keymodifiers["shift-r"] = KeyModifier.Shift_R;
142         keymodifiers["shift"] = KeyModifier.Shift;
143         keymodifiers["control-l"] = KeyModifier.Control_L;
144         keymodifiers["control-r"] = KeyModifier.Control_R;
145         keymodifiers["control"] = KeyModifier.Control;
146         keymodifiers["alt-l"] = KeyModifier.Alt_L;
147         keymodifiers["alt-r"] = KeyModifier.Alt_R;
148         keymodifiers["alt"] = KeyModifier.Alt;
149         keymodifiers["altgr"] = KeyModifier.AltGr;
150         keymodifiers["super"] = KeyModifier.Super;
151         keymodifiers["hyper"] = KeyModifier.Hyper;
152       }
153
154       private static uint decode_keysym (MSymbol keysym)
155       {
156         uint key;
157         string name = keysym.Name;
158
159         if (name.Length == 1)
160           return name[0];
161         name = name.ToLower ();
162         if (! keysyms.TryGetValue (name, out key))
163           keysyms[name] = key = keysym_base++;
164         return key;
165       }
166
167       private static uint combine_modifiers (uint c, KeyModifier modifiers)
168       {
169         if (c < 0x7F && c != 0x20)
170           {
171             if ((modifiers & KeyModifier.Shift) != KeyModifier.None
172                 && Char.IsLower ((char) c))
173               {
174                 modifiers &= ~KeyModifier.Shift;
175                 c = Char.ToUpper ((char) c);
176               }
177             if ((modifiers & KeyModifier.Control) != KeyModifier.None)
178               {
179                 modifiers &= ~KeyModifier.Control;
180                 c &= 0x1F;
181               }
182           }     
183         return c | (uint) modifiers;
184       }
185
186       public Key (uint c)
187       {
188         key = c;
189       }
190
191       public Key (uint c, KeyModifier modifiers)
192       {
193         key = combine_modifiers (c, modifiers);
194       }
195
196       public Key (MSymbol keysym, KeyModifier modifiers)
197       {
198         key = combine_modifiers (decode_keysym (keysym), modifiers);
199       }
200
201       public Key (MSymbol keysym)
202       {
203         string str = keysym.Name;
204         int len = str.Length;
205         int i;
206         KeyModifier modifiers = KeyModifier.None;
207
208         for (i = 0; i + 2 < len && str[i + 1] == '-'; i += 2)
209           {
210             if (str[i] == 'S')
211               modifiers |= KeyModifier.Shift;
212             else if (str[i] == 'C')
213               modifiers |= KeyModifier.Control;
214             else if (str[i] == 'A')
215               modifiers |= KeyModifier.Alt;
216             else if (str[i] == 'G')
217               modifiers |= KeyModifier.AltGr;
218             else if (str[i] == 's')
219               modifiers |= KeyModifier.Super;
220             else if (str[i] == 'H')
221               modifiers |= KeyModifier.Hyper;
222           }
223         if (i + 1 == len)
224           key = combine_modifiers (str[i], modifiers);
225         else
226           key = combine_modifiers (decode_keysym (keysym), modifiers);
227       }
228
229       public Key (MPlist plist)
230       {
231         KeyModifier modifiers = KeyModifier.None;
232         MPlist p;
233
234         for (p = plist; ! p.IsEmpty; p = p.next)
235           {
236             if (p.IsInteger)
237               {
238                 if (! p.next.IsEmpty)
239                   throw new Exception ("Invalid Key: " + plist);
240                 break;
241               }
242             else if (! p.IsSymbol)
243               throw new Exception ("Invalid Key: " + plist);
244             else
245               {
246                 string name = p.Symbol.Name.ToLower ();
247                 KeyModifier m;
248                 
249                 if (! keymodifiers.TryGetValue (name, out m))
250                   break;
251                 modifiers |= m;
252               }
253           }
254         if (p.IsEmpty || ! p.next.IsEmpty)
255           throw new Exception ("Invalid Key: " + plist);
256         if (p.IsInteger)
257           key = combine_modifiers ((uint) p.Integer, modifiers);
258         else
259           key = combine_modifiers (decode_keysym (p.Symbol), modifiers);
260       }
261
262       public bool HasModifier
263       {
264         get { return ((key & (uint) KeyModifier.All) != 0); }
265       }
266
267       public bool Match (Key k)
268       {
269         if (k.key == key)
270           return true;
271         if ((k.key & char_mask) != (key & char_mask))
272           return false;
273         KeyModifier m1 = ((KeyModifier) key) & KeyModifier.All;
274         KeyModifier m2 = ((KeyModifier) k.key) & KeyModifier.All;
275         return (((m1 & KeyModifier.Shift) == (m2 & KeyModifier.Shift)
276                  || ((m1 & KeyModifier.Shift) == KeyModifier.Shift
277                      && (m2 & KeyModifier.Shift) != KeyModifier.None))
278                 && ((m1 & KeyModifier.Control) == (m2 & KeyModifier.Control)
279                     || ((m1 & KeyModifier.Control) == KeyModifier.Control
280                         && (m2 & KeyModifier.Control) != KeyModifier.None))
281                 && ((m1 & KeyModifier.Alt) == (m2 & KeyModifier.Alt)
282                     || ((m1 & KeyModifier.Alt) == KeyModifier.Alt
283                         && (m2 & KeyModifier.Alt) != KeyModifier.None))
284                 && ((m1 & KeyModifier.High) == (m2 & KeyModifier.High)));
285       }
286
287       public override string ToString ()
288       {
289         string str = Char.ToString ((char) key);
290         KeyModifier m = ((KeyModifier) key) & KeyModifier.All;
291
292         if (m != KeyModifier.None)
293           {
294             if ((m & KeyModifier.Shift) != KeyModifier.None)
295               str = "S-" + str;
296             if ((m & KeyModifier.Control) != KeyModifier.None)
297               str = "C-" + str;
298             if ((m & KeyModifier.Alt) != KeyModifier.None)
299               str = "A-" + str;
300             if ((m & KeyModifier.AltGr) != KeyModifier.None)
301               str = "G-" + str;
302             if ((m & KeyModifier.Super) != KeyModifier.None)
303               str = "s-" + str;
304             if ((m & KeyModifier.Hyper) != KeyModifier.None)
305               str = "H-" + str;
306           }
307         return str;
308       }
309     }
310
311     public class KeySeq : Xex.TermValue
312     {
313       List<Key> keyseq = new List<Key> ();
314
315       public KeySeq () { }
316
317       public KeySeq (MPlist plist)
318       {
319         foreach (MPlist p in plist)
320           {
321             if (p.IsSymbol)
322               keyseq.Add (new Key (p.Symbol));
323             else if (p.IsInteger)
324               keyseq.Add (new Key ((char) p.Integer));
325             else if (p.IsPlist)
326               keyseq.Add (new Key (p.Plist));
327             else
328               throw new Exception ("Invalid Key Sequence: " + plist);
329           }
330       }
331
332       public KeySeq (MText mt) : base ()
333       {
334         for (int i = 0; i < mt.Length; i++)
335           keyseq.Add (new Key ((uint) mt[i]));
336       }
337
338       private static uint parse_integer (string str)
339       {
340         if (Char.IsDigit (str[0]))
341           {
342             if (str[0] == '0' && str.Length > 2 && str[1] == 'x')
343               {
344                 uint i = 0;
345                 for (int idx = 2; idx < str.Length; idx++)
346                   {
347                     uint c = str[idx];
348                     if (c >= '0' && c <= '9')
349                       i = i * 16 + (c - '0');
350                     else if (c >= 'A' && c <= 'F')
351                       i = i * 16 + 10 + (c - 'A');
352                     else if (c >= 'a' && c <= 'f')
353                       i = i * 16 + 10 + (c - 'a');
354                     else
355                       break;
356                   }
357                 return i;
358               }
359             return UInt32.Parse (str);
360           }
361         else if (str[0] == '?')
362           return str[1];
363         return 0;
364       }
365
366       public KeySeq (XmlNode node)
367         {
368           XmlAttributeCollection acol = node.Attributes;
369           XmlNode n;
370
371           if (acol != null && (n = acol["keys"]) != null)
372             {
373               foreach (char c in  n.Value)
374                 keyseq.Add (new Key ((uint) c));
375             }
376
377           for (node = node.FirstChild; node != null; node = node.NextSibling)
378             {
379               if (node.Name == "key-event")
380                 keyseq.Add (new Key ((MSymbol) node.InnerText));
381               else
382                 keyseq.Add (new Key (parse_integer (node.InnerText)));
383             }
384         }
385
386       public KeySeq (Xex.Term[] args)
387         {
388           foreach (Xex.Term term in args)
389             {
390               if (term.IsName)
391                 keyseq.Add (new Key ((MSymbol) term.Nameval.name));
392               else
393                 keyseq.Add (new Key (term.Strval));
394             }
395         }
396
397       public override string ToString ()
398       {
399         string str;
400
401         foreach (Key key in this)
402           if (key.HasModifier)
403             {
404               str = "(keyseq";
405               foreach (Key k in this)
406                 str += " " + k.ToString ();
407               return str + ")";
408             }
409         str = "\"";
410         foreach (Key key in this)               
411           str += key.ToString ();
412         return str + "\"";
413       }
414     }
415
416     public class Variable
417     {
418       public MSymbol name;
419       public MText description;
420       public Type type;
421       public object value;
422       public object[] candidates;
423
424       public Variable (MPlist p)
425       {
426         name = p.Symbol;
427         p = p.Next;
428         description = parse_description (p);
429         if (description == null)
430           description = new MText ("No description");
431         else
432           p = p.next;
433         type = (p.IsMText ? typeof (MText)
434                 : p.IsInteger ? typeof (int)
435                 : p.IsSymbol ? typeof (MSymbol)
436                 : typeof (object));
437         value = p.val;
438         p = p.next;
439         candidates = new object[p.Count];
440         for (int i = 0; ! p.IsEmpty; i++, p = p.next)
441           candidates[i] = p.val;
442       }
443
444       private static Type parse_value (XmlNode node, out object value)
445       {
446         string typename = node.Attributes["type"].Value;
447         Type type;
448
449         if (typename == "integer")
450           {
451             int i;
452             if (! Int32.TryParse (node.InnerText, out i))
453               i = 0;
454             value = i;
455             type = typeof (int);
456           }
457         else if (typename == "string")
458           {
459             MText mt = node.InnerText;
460             value = mt;
461             type = typeof (MText);
462           }
463         else if (typename == "symbol")
464           {
465             MSymbol sym = node.InnerText;
466             value = sym;
467             type = typeof (MSymbol);
468           }
469         else
470           {
471             value = null;
472             type = typeof (object);
473           }
474         return type;
475       }
476
477       public Variable (XmlNode node)
478       {
479         name = node.Attributes["id"].Value;
480         for (node = node.FirstChild; node != null; node = node.NextSibling)
481           if (node.NodeType == XmlNodeType.Element)
482             {
483               if (node.Name == "description")
484                 description = parse_description (node);
485               else if (node.Name == "value")
486                 type = parse_value (node, out value);
487               else if (node.Name == "valiable-value-candidate")
488                 {
489                   XmlNodeList n_list = node.ChildNodes;
490                   candidates = new object[n_list.Count];
491                   for (int i = 0; i < n_list.Count; i++)
492                     {
493                       object val;
494                       parse_value (n_list[i], out val);
495                       candidates[i] = val;
496                     }
497                 }
498             }
499       }
500
501       public override string ToString ()
502       {
503         return ("(" + name + " \"" + (string) description
504                 + "\" " + type + " " + value + " " + candidates + ")");
505       }
506     }
507
508     public class Command
509     {
510       public MSymbol name;
511       public MText description;
512       public List<KeySeq> keys;
513
514       public Command (MPlist p)
515       {
516         name = p.Symbol;
517         p = p.Next;
518         description = parse_description (p);
519         if (description == null)
520           description = "No description";
521         keys = new List<KeySeq> ();
522         for (p = p.next; ! p.IsEmpty; p = p.next)
523           {
524             if (p.IsMText)
525               keys.Add (new KeySeq (p.Text));
526             else if (p.IsPlist)
527               keys.Add (new KeySeq (p.Plist));
528           }
529       }
530
531       public Command (XmlNode node)
532       {
533         name = node.Attributes["id"].Value;
534         keys = new List<KeySeq> ();
535         for (node = node.FirstChild; node != null; node = node.NextSibling)
536           {
537             if (node.Name == "description")
538               description = parse_description (node);
539             else if (node.Name == "keyseq")
540               keys.Add (new KeySeq (node));
541           }
542       }
543
544       public override string ToString ()
545       {
546         string str = "(" + name + " \"" + (string) description;
547         foreach (KeySeq keyseq in keys)
548           str += " " + keyseq;
549         return str + ")";
550       }
551     }
552
553     internal class Plugin
554     {
555       public string name;
556       public Assembly assembly;
557       public MPlist methods;
558
559       public override string ToString ()
560       {
561         string str = "(" + name;
562         for (MPlist p = methods; ! p.IsEmpty; p = p.next)
563           str += " " + p.key;
564         return str + ")";
565       }
566
567       public Xex.Term Call (MSymbol method, MInputContext ic, Xex.Term[] args)
568       {
569         if (assembly == null)
570           {
571             try {
572               assembly = Assembly.LoadFrom (name + ".dll");
573             } catch {
574               return Xex.Zero;
575             }
576             Type t = assembly.GetType ("Plugin");
577             for (MPlist p = plugin.methods; ! p.IsEmpty; p = p.next)
578               p.Set (p.key, t.GetMethod (p.key.Name));
579           }
580
581         MethodInfo method_info = (MethodInfo) methods.Get (method);
582         if (method_info == null)
583           return Xex.Zero;
584         Xex.Term result = (Xex.Term) method_info.Invoke (null, args);
585         return result.Eval ();
586       }
587     }
588
589     internal class PluginMethod : Xex.Function
590     {
591       public Plugin plugin;
592       public MSymbol method;
593
594       public PluginMethod (Plugin plugin, MSymbol name)
595         : base ((Name) name.name, 0, -1)
596         {
597           this.plugin = plugin;
598           method = name.name.Substring (plugin.name.Length + 1);
599         }
600
601       public override Xex.Term Call (Xex.Domain domain, Xex.Variable vari,
602                                      Xex.Term[] args)
603       {
604         args = (Xex.Term[]) args.Clone ();
605         for (int i = 0; i < args.Length; i++)
606           {
607             args[i] = args[i].Eval (domain);
608             if (domain.Thrown)
609               return args[i];
610           }
611         return plugin.Call (method, (MIntutContext) domain.context, args);
612       }
613     }
614
615     internal class PluginCall : Xex.TermValue
616     {
617       PluginMethod method;
618       Xex.Term[] args;
619
620       public PluginCall (Plugin plugin, MSymbol entry, Xex.Term[] args)
621         {
622           this.plugin = plugin;
623           this.entry = entry;
624           this.args = args;
625         }
626
627       public override Xex.Term Eval (Xex.Domain domain)
628         {
629           Xex.Term[] args = new Xex.Term[this.args.Length];
630           for (int i = 0; i < args.Length; i++)
631             args[i] = this.args[i].Eval (domain);
632           return plugin.Call (entry, args);
633         }
634     }
635
636     internal abstract class Marker : Xex.TermValue
637     {
638       MSymbol name;
639
640       public Marker (MSymbol name)
641         {
642           this.name = name;
643         }
644
645       public abstract int Position (MInputContext ic);
646       public abstract void Mark (MInputContext ic);
647
648       public class Named : Marker
649       {
650         int pos;
651
652         public Named (MSymbol name) : base (name) { }
653
654         public override int Position (MInputContext ic) { return pos; }
655
656         public override void Mark (MInputContext ic) { pos = ic.cursor_pos; } 
657       }
658      
659       public class Predefined : Marker
660       {
661         public Predefined (MSymbol name) : base (name) { }
662         
663         public override int Position (MInputContext ic)
664         {
665           switch (name.Name[1]) {
666           case '<': return 0;
667           case '>': return ic.preedit.Length;
668           case '-': return ic.cursor_pos - 1;
669           case '+': return ic.cursor_pos + 1;
670           case '[':
671             if (ic.cursor_pos > 0)
672               {
673                 int pos = ic.cursor_os;
674                 int to;
675                 ic.preedit.FindProp (MInputMethod.Mcandidates, pos - 1,
676                                      out pos, out to);
677                 return pos;
678               }
679             return 0;
680           case ']':
681             if (ic.cursor_pos < ic.preedit.Length - 1)
682               {
683                 int pos = ic.cursor_pos;
684                 int from;
685                 ic.preedit.FindProp (MInputMethod.Mcandidates, pos,
686                                      out from, out pos);
687                 return pos;
688               }
689             return ic.preedit.Length;
690           default:
691             return name.Name[1] - '0';
692           }
693         }
694       
695         public override void Mark (MInputContext ic)
696         {
697           throw new Exception ("Can't set predefined marker: " + name);
698         }
699       }
700
701       static internal Dictionary<MSymbol,Predefined> predefined_markers;
702
703       static Marker ()
704       {
705         predefined_markers = new Dictionary<MSymbol,Predefined> ();
706         MSymbol[] symlist = new MSYmbol[] {"@<", "@>", "@-", "@+", "@[", "@]",
707                                            "@0", "@1", "@2", "@3", "@4",
708                                            "@5", "@6", "@7", "@8", "@9" };
709         foreach (MSymbol s in strline)
710           predefined_markers[s] = new Predefined (s);
711       }
712
713       public static Marker Get (MInputContext ic, MSymbol name)
714       {
715         Marker m;
716
717         if (predefined_markers.TryGetValue (name, out m))
718           return m;
719         if (name.Name[0] == '@')
720           throw new Exception ("Invalid marker name: " + name);
721         m = (Marker) ic->markers.Get (name);
722         if (m == null)
723           {
724             m = new Named (name);
725             ic->markers.Put (name, m);
726           }
727         return m;
728       }
729     }
730       
731     internal class Map
732     {
733       public MSymbol name;
734       public Dictionary<Key, Map> submaps;
735       public Xex actions;
736
737       public void Add (KeySeq keys, int index, Xex actions)
738       {
739         Map sub = null;
740
741         if (submaps == null)
742           submaps = new Dictionary<Key, Map> ();
743         else
744           submaps.TryGetValue (keys[index], out sub);
745         if (sub == null)
746           {
747             Key key = keys[index];
748             submaps[key] = sub = new Map ();
749           }
750         if (index + 1 < keys.Count)
751           sub.Add (keys, index + 1, actions);
752         else
753           this.actions = actions;
754       }
755
756       public Xex Lookup (KeySeq keys, int index)
757       {
758         Map sub;
759
760         if (index + 1 == keys.Count)
761           return actions;
762         if (submaps.TryGetValue (keys[index], out sub))
763           return sub.Lookup (keys, index + 1);
764         return null;
765       }
766
767       private void describe (MText mt, KeySeq keyseq)
768       {
769         if (keyseq.Count > 0)
770           {
771             mt.Cat (" (").Cat (keyseq.ToString ());
772             if (actions != null)
773               mt.Cat (' ').Cat (actions.ToString ());
774             mt.Cat (')');           
775           }
776         if (submaps != null)
777           foreach (KeyValuePair<Key, Map> kv in submaps)
778             {
779               keyseq.Add (kv.Key);
780               kv.Value.describe (mt, keyseq);
781               keyseq.RemoveAt (keyseq.Count - 1);
782             }
783       }
784
785       public override string ToString ()
786       {
787         MText mt = "(" + name.Name;
788         KeySeq keyseq = new KeySeq ();
789
790         describe (mt, keyseq);
791         mt.Cat (')');
792         return (string) mt;
793       }
794     }
795
796     internal class State
797     {
798       public MSymbol name;
799       public MText title;
800       public MPlist branches = new MPlist ();
801
802       public State (MSymbol name)
803       {
804         this.name = name;
805       }
806
807       public override string ToString ()
808       {
809         MText mt = "(" + name.Name;
810
811         if (title != null)
812           mt.Cat (" \"" + title + "\"");
813         for (MPlist p = branches; ! p.IsEmpty; p = p.next)
814           mt.Cat (" (" + p.Key + " " + (Xex) p.Val + ")");
815         return (string) mt + ")";
816       }
817     }
818
819     // Instance members
820     internal Xex.Domain domain;
821
822     private LoadStatus load_status = LoadStatus.None;
823     private MDatabase.Tag tag;
824     private MDatabase mdb;
825
826     private MText description;
827     internal MText title;
828     internal Command[] commands;
829     internal Xex.Name[] var_names;
830     internal Dictionary<MSymbol, Plugin> plugins;
831     internal Dictionary<MSymbol, Map> maps;
832     internal MPlist states;
833
834     static MInputMethod ()
835     {
836       im_domain.DefSubr (Finsert, "insert", true, 1, 1);
837       im_domain.DefSubr (Finsert_candidates, "candidates", true, 1, -1);
838       im_domain.DefSubr (Fdelete, "delete", true, 1, 1);
839       im_domain.DefSubr (Fselect, "select", true, 1, 1);
840       im_domain.DefSubr (Fshow, "show", true, 0, 0);
841       im_domain.DefSubr (Fhide, "hide", true, 0, 0);
842       im_domain.DefSubr (Fmove, "move", true, 1, 1);
843       im_domain.DefSubr (Fmark, "mark", true, 1, 1);
844       im_domain.DefSubr (Fpushback, "pushback", true, 1, 1);
845       im_domain.DefSubr (Fpop, "pop", true, 0, 0);
846       im_domain.DefSubr (Fundo, "undo", true, 0, 1);
847       im_domain.DefSubr (Fcommit, "commit", true, 0, 0);
848       im_domain.DefSubr (Funhandle, "unhandle", true, 0, 0);
849       im_domain.DefSubr (Fshift, "shift", true, 1, 1);
850       im_domain.DefSubr (Fmarker, "marker", true, 1, 1);
851       im_domain.DefSubr (Fchar_at, "char-at", true, 1, 1);
852       im_domain.DefSubr (Fkeyseq, "keyseq", true, 1, -1);
853
854       MDatabase.Tag tag = new MDatabase.Tag (Minput_method, "*", "*", "*");
855       List<MDatabase> list = MDatabase.List (tag);
856       M17n.DebugPrint ("Found {0} input methods\n", list.Count);
857       foreach (MDatabase mdb in list)
858         im_table[mdb.tag] = new MInputMethod (mdb.tag);
859       tag = new MDatabase.Tag (Minput_method, MSymbol.t, MSymbol.nil, "global");
860       im_global = im_table[tag];
861     }
862
863     // Constructor
864     private MInputMethod (MDatabase.Tag tag)
865     {
866       this.tag = tag;
867     }
868
869     // Instance Properties
870     public MSymbol Language { get { return tag[1]; } }
871     public MSymbol Name { get { return tag[2]; } }
872     public MSymbol SubName { get { return tag[3]; } }
873
874     public bool Info (out MText description,
875                       out MText title,
876                       out Xex.Variable[] variables,
877                       out Command[] commands)
878     {
879       if ((load_status & LoadStatus.Header) != LoadStatus.Header
880           && ! load_header ())
881         {
882           description = null;
883           title = null;
884           variables = null;
885           commands = null;
886           return false;
887         }
888       description = this.description;
889       title = this.title;
890       variables = new Xex.Variable[var_names.Length];
891       int i = 0;
892       foreach (Xex.Name name in var_names)
893         variables[i++] = domain.GetVar (name, false);
894       commands = this.commands;
895       return true;
896     }
897
898     public static MInputMethod Find (MSymbol language, MSymbol name)
899     {
900       return Find (language, name, MSymbol.nil);
901     }
902
903     public static MInputMethod Find (MSymbol language, MSymbol name,
904                                      MSymbol subname)
905     {
906       MDatabase.Tag tag = new MDatabase.Tag (Minput_method, language,
907                                              name, subname);
908       MInputMethod im;
909
910       return (im_table.TryGetValue (tag, out im) ? im : null);
911     }
912
913     public bool Open ()
914     {
915       return ((load_status == LoadStatus.Full) || load_body ());
916     }
917
918     public static MInputMethod[] List ()
919     {
920       MInputMethod[] array = new MInputMethod[im_table.Count];
921       int i = 0;
922
923       foreach (KeyValuePair<MDatabase.Tag, MInputMethod> kv in im_table)
924         array[i++] = kv.Value;
925       return array;
926     }
927
928     private bool load_header ()
929     {
930       mdb = MDatabase.Find (tag);
931       if (mdb == null)
932         return false;
933       try {
934         MSymbol format = mdb.Format;
935
936         if (format == MSymbol.plist)
937           load ((MPlist) mdb.Load (Mmap), false);
938         else
939           {
940             XmlDocument doc = (XmlDocument) mdb.Load (Mmap_list);
941             load (doc.DocumentElement, false);
942           }
943       } catch (Exception e) {
944         Console.WriteLine ("{0}\n", e);
945         load_status = LoadStatus.Error;
946         return false;
947       }
948       load_status |= LoadStatus.Header;
949       return true;
950     }
951
952     private bool load_body ()
953     {
954       domain = new Xex.Domain (domain, null);
955       mdb = MDatabase.Find (tag);
956       if (mdb == null)
957         return false;
958       try {
959         object obj = mdb.Load ();
960         if (obj is MPlist)
961           load ((MPlist) obj, true);
962         else
963           load ((XmlDocument) obj, true);
964       } catch (Exception e) {
965         Console.WriteLine (e);
966         load_status = LoadStatus.Error;
967         return false;
968       }
969       load_status = LoadStatus.Full;
970       return true;
971     }
972
973     private void load (MPlist plist, bool full)
974     {
975       maps = new Dictionary<MSymbol, Map> ();
976       states = new MPlist ();
977
978       for (; ! plist.IsEmpty; plist = plist.next)
979         if (plist.IsPlist)
980           {
981             MPlist pl = plist.Plist;
982             if (pl.IsSymbol)
983               {
984                 MSymbol sym = pl.Symbol;
985
986                 pl = pl.next;
987                 if (sym == Mdescription)
988                   {
989                     description = parse_description (pl);
990                     if (description == null)
991                       description = new MText ("No description");
992                   }
993                 else if (sym == Mtitle)
994                   {
995                     if (pl.IsMText)
996                       title = pl.Text;
997                   }
998                 else if (sym == Mvariable)
999                   parse_variables (pl);
1000                 else if (sym == Mcommand)
1001                   parse_commands (pl);
1002                 else if (full)
1003                   {
1004                     if (sym == Mmodule)
1005                       parse_plugins (pl);
1006                     else if (sym == Minclude)
1007                       parse_include (pl);
1008                     else if (sym == Mmacro)
1009                       parse_macros (pl);
1010                     else if (sym == Mmap)
1011                       parse_maps (pl);
1012                     else if (sym == Mstate)
1013                       parse_states (pl);
1014                   }
1015               }
1016           }
1017       if (description == null)
1018         description = (MText) "No description";
1019       if (title == null)
1020         title = new MText (tag[2].Name);
1021       if (commands == null)
1022         commands = new Command[0];
1023       if (! full)
1024         return;
1025       if (states.IsEmpty)
1026         {
1027           State state = new State ((MSymbol) "init");
1028           plist = new MPlist ();
1029           foreach (KeyValuePair<MSymbol, Map>kv in maps)
1030             state.branches.Add (kv.Key, null);
1031           states.Add (state.name, state);
1032         }
1033     }
1034
1035     private void load (XmlNode node, bool full)
1036     {
1037       bool skip_header = load_status == LoadStatus.Header;
1038
1039       maps = new Dictionary<MSymbol, Map> ();
1040       states = new MPlist ();
1041
1042       if (node.NodeType == XmlNodeType.Document)
1043         node = node.FirstChild;
1044       while (node.NodeType != XmlNodeType.Element)
1045         node = node.NextSibling;
1046       for (node = node.FirstChild; node != null; node = node.NextSibling)
1047         {
1048           if (node.NodeType != XmlNodeType.Element)
1049             continue;
1050           if (! skip_header)
1051             {
1052               if (node.Name == "description")
1053                 description = parse_description (node);
1054               else if (node.Name == "title")
1055                 title = parse_title (node);
1056               else if (node.Name == "variable-list")
1057                 parse_variables (node);
1058               else if (node.Name == "command-list")
1059                 parse_commands (node);
1060             }
1061           else if (full)
1062             {
1063               if (node.Name == "module-list")
1064                 parse_plugins (node);
1065               else if (node.Name == "macro-list")
1066                 parse_macros (node);
1067               else if (node.Name == "map-list")
1068                 parse_maps (node);
1069               else if (node.Name == "state-list")
1070                 parse_states (node);
1071             }
1072         }
1073       if (description == null)
1074         description = (MText) "No description";
1075       if (title == null)
1076         title = new MText (tag[2].Name);
1077       if (commands == null)
1078         commands = new Command[0];
1079       if (! full)
1080         return;
1081       if (states.IsEmpty)
1082         {
1083           State state = new State ((MSymbol) "init");
1084           foreach (KeyValuePair<MSymbol, Map>kv in maps)
1085             state.branches.Add (kv.Key, null);
1086           states.Add (state.name, state);
1087         }
1088     }
1089
1090     private static void transform (MPlist plist)
1091     {
1092       for (; ! plist.IsEmpty; plist = plist.next)
1093         {
1094           if (plist.IsMText)
1095             {
1096               MPlist p = new MPlist ();
1097               p.Add (MSymbol.symbol, Minsert);
1098               p.Add (MSymbol.mtext, plist.Text);
1099               plist.Set (MSymbol.plist, p);
1100             }
1101           else if (plist.IsInteger)
1102             {
1103               MPlist p = new MPlist ();
1104               p.Add (MSymbol.symbol, Minsert);
1105               p.Add (MSymbol.integer, plist.Integer);
1106               plist.Set (MSymbol.plist, p);
1107             }
1108           else if (plist.IsPlist)
1109             {
1110               MPlist pl = plist.Plist;
1111
1112               if (pl.IsSymbol)
1113                 {
1114                   if (pl.Symbol == Madd)
1115                     pl.Set (MSymbol.symbol, (MSymbol) "+=");
1116                   else if (pl.Symbol == Msub)
1117                     pl.Set (MSymbol.symbol, (MSymbol) "-=");
1118                   else if (pl.Symbol == Mmul)
1119                     pl.Set (MSymbol.symbol, (MSymbol) "*=");
1120                   else if (pl.Symbol == Mdiv)
1121                     pl.Set (MSymbol.symbol, (MSymbol) "/=");
1122                   else if (pl.Symbol == Minsert)
1123                     {
1124                       // (insert (CANDIDATES ...))
1125                       //   => (candidates CANDIDATES ...)
1126                       if (pl.next.IsPlist)
1127                         {
1128                           pl.Set (MSymbol.symbol, Mcandidates);
1129                           pl = pl.next;
1130                           MPlist p = pl.Plist;
1131                           pl.Set (p.key, p.val);
1132                           for (p = p.next; ! p.IsEmpty; p = p.next);
1133                           pl.Add (p.key, p.val);
1134                         }
1135                     }
1136                   else if (pl.Symbol == Mif)
1137                     {
1138                       pl = pl.next;
1139                       if (! pl.IsEmpty)
1140                         transform (pl.next);
1141                     }
1142                   else if (pl.Symbol == Mcond)
1143                     {
1144                       for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1145                         if (pl.IsPlist)
1146                           {
1147                             MPlist p = pl.Plist;
1148
1149                             if (p.IsPlist)
1150                               transform (p);
1151                             else
1152                               transform (p.next);
1153                           }
1154                     }
1155                   else if (pl.Symbol == Mdelete
1156                            || pl.Symbol == Mmove
1157                            || pl.Symbol == Mmark)
1158                     {
1159                       pl = pl.next;
1160                       if (pl.IsSymbol)
1161                         {
1162                           MSymbol sym = pl.Symbol;
1163                           MPlist p = new MPlist ();
1164                           p.Add (MSymbol.symbol, Mmarker);
1165                           p.Add (MSymbol.symbol, sym);
1166                           pl.Set (MSymbol.plist, p);
1167                         }
1168                     }
1169                   else if (pl.Symbol == Mpushback)
1170                     {
1171                       pl = pl.next;
1172                       if (pl.IsPlist)
1173                         pl.Plist.Push (MSymbol.symbol, Mkeyseq);
1174                     }
1175                 }
1176               else if (pl.IsMText)
1177                 {
1178                   // (CANDIDATES ...) => (candidates CANDIDATES ...)
1179                   pl.Push (MSymbol.symbol, Mcandidates);
1180                 }
1181             }
1182           else if (plist.IsSymbol)
1183             {
1184               MSymbol sym = plist.Symbol;
1185
1186               if (sym.Name.Length >= 3
1187                   && sym.Name[0] == '@'
1188                   && (sym.Name[1] == '-' || sym.Name[1] == '+'))
1189                 {
1190                   int pos = int.Parse (sym.Name.Substring (1));
1191                   MPlist p = new MPlist ();
1192
1193                   if (pos == 0)
1194                     {
1195                       p.Add (MSymbol.symbol, Msurrounding_text_p);
1196                     }
1197                   else
1198                     {
1199                       if (sym.Name[1] == '+')
1200                         pos--;
1201                       p.Add (MSymbol.symbol, Mchar_at);
1202                       p.Add (MSymbol.integer, pos);
1203                     }
1204                   plist.Set (MSymbol.plist, p);
1205                 }
1206             }
1207         }
1208     }
1209
1210     private static MText parse_description (MPlist plist)
1211     {
1212       if (plist.IsMText)
1213         return plist.Text;
1214       if (plist.IsPlist)
1215         {
1216           plist = plist.Plist;
1217           if (plist.IsSymbol && plist.Symbol == (MSymbol) "_"
1218               && plist.next.IsMText)
1219             return plist.next.Text;
1220         }
1221       return null;
1222     }
1223
1224     private static MText parse_description (XmlNode node)
1225     {
1226       if (node.HasChildNodes)
1227         node = node.FirstChild;
1228       return node.InnerText;
1229     }
1230
1231     private static MText parse_title (XmlNode node)
1232     {
1233       return node.InnerText;
1234     }
1235
1236     private void new_variable (Xex.Name name, string desc, int val,
1237                                MPlist pl, Xex.Variable vari)
1238     {
1239       int[] range;
1240
1241       if (pl.IsEmpty)
1242         range = null;
1243       else
1244         {
1245           range = new int[pl.Count * 2];
1246           for (int i = 0; i < range.Length; i++)
1247             {
1248               if (pl.IsPlist)
1249                 {
1250                   MPlist p = pl.Plist;
1251
1252                   if (! p.IsInteger || ! p.next.IsInteger)
1253                     throw new Exception ("Invalid range: " + p);
1254                   range[i * 2] = p.Integer;
1255                   range[i * 2 + 1] = p.next.Integer;
1256                 }
1257               else if (pl.IsInteger)
1258                 range[i * 2] = range[i * 2 + 1] = pl.Integer;
1259               else
1260                 throw new Exception ("Invalid range: " + pl);
1261             }
1262         }
1263       if (vari == null)
1264         domain.Defvar (new Xex.Variable.Int (name, desc, val, range));
1265       else
1266         {
1267           Xex.Term term = new Xex.Term (val);
1268           vari.Value = term;
1269           vari.DefaultValue = term;
1270           vari.Range = range;
1271         }
1272     }
1273
1274     private void new_variable (Xex.Name name, string desc, MText val,
1275                                MPlist pl, Xex.Variable vari)
1276     {
1277       string[] range;
1278
1279       if (pl.IsEmpty)
1280         range = null;
1281       else
1282         {
1283           range = new string[pl.Count * 2];
1284           for (int i = 0; i < range.Length; i++)
1285             {
1286               if (pl.IsMText)
1287                 range[i] = (string) pl.Text;
1288               else
1289                 throw new Exception ("Invalid range: " + pl);
1290             }
1291         }
1292       if (vari == null)
1293         domain.Defvar (new Xex.Variable.Str (name, desc, (string) val, range));
1294       else
1295         {
1296           Xex.Term term = new Xex.Term ((string) val);
1297           vari.Value = term;
1298           vari.DefaultValue = term;
1299           vari.Range = range;
1300         }
1301     }
1302
1303     private void new_variable (Xex.Name name, string desc, MSymbol val,
1304                                MPlist pl, Xex.Variable vari)
1305     {
1306       Xex.Name[] range;
1307       Xex.Name sym = val.Name;
1308
1309       if (pl.IsEmpty)
1310         range = null;
1311       else
1312         {
1313           range = new Xex.Name[pl.Count * 2];
1314           for (int i = 0; i < range.Length; i++)
1315             {
1316               if (pl.IsSymbol)
1317                 range[i] = pl.Symbol.Name;
1318               else
1319                 throw new Exception ("Invalid range: " + pl);
1320             }
1321         }
1322       if (vari == null)
1323         domain.Defvar (new Xex.Variable.Sym (name, desc, sym, range));
1324       else
1325         {
1326           Xex.Term term = new Xex.Term (sym);
1327           vari.Value = term;
1328           vari.DefaultValue = term;
1329           vari.Range = range;
1330         }
1331     }
1332
1333     private void parse_variables (MPlist plist)
1334     {
1335       var_names = new Xex.Name[plist.Count];
1336
1337       for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1338         {
1339           if (! plist.IsPlist || ! plist.Plist.IsSymbol)
1340             throw new Exception ("Invalid variable: " + plist);
1341
1342           MPlist p = plist.Plist;
1343           Xex.Name name = (Xex.Name) p.Symbol.Name;
1344           var_names[i] = name;
1345           p = p.next;
1346           string desc = (string) parse_description (p);
1347           Xex.Variable vari = im_global.domain.GetVar (name, false);
1348
1349           if (vari != null)
1350             domain.Defvar (vari);
1351           if (desc != null)
1352             p = p.next;
1353           if (! p.IsEmpty)
1354             {
1355               if (p.IsInteger)
1356                 new_variable (name, desc, p.Integer, p.next, vari);
1357               else if (p.IsMText)
1358                 new_variable (name, desc, p.Text, p.next, vari);
1359               else if (p.IsSymbol)
1360                 new_variable (name, desc, p.Symbol, p.next, vari);
1361               else
1362                 throw new Exception ("Invalid variable type: " + p.val);
1363             }
1364         }
1365     }
1366
1367     private void parse_variables (XmlNode node)
1368     {
1369       XmlNodeList node_list = node.ChildNodes;
1370
1371       var_names = new Xex.Name[node_list.Count];
1372       for (int i = 0; i < node_list.Count; i++)
1373         {
1374           Xex.Name name = node_list[i].Attributes[0].Value;
1375           Xex.Variable vari = im_global.domain.GetVar (name, false);
1376
1377           if (vari != null)
1378             domain.Defvar (vari);
1379           else
1380             domain.Defvar (node_list[i]);
1381
1382           var_names[i] = name;
1383         }
1384     }
1385
1386     private void parse_commands (MPlist plist)
1387     {
1388       commands = new Command[plist.Count];
1389
1390       for (int i = 0; ! plist.IsEmpty; plist = plist.next)
1391         if (plist.IsPlist && plist.Plist.IsSymbol)
1392           commands[i++] = new Command (plist.Plist);
1393     }
1394
1395     private void parse_commands (XmlNode node)
1396     {
1397       XmlNodeList node_list = node.ChildNodes;
1398
1399       commands = new Command[node_list.Count];
1400       for (int i = 0; i < node_list.Count; i++)
1401         {
1402           if (node_list[i].NodeType == XmlNodeType.Element)
1403             commands[i] = new Command (node_list[i]);
1404         }
1405     }
1406
1407     private void parse_plugins (MPlist plist)
1408     {
1409       plugins = new Dictionary<MSymbol, Plugin> ();
1410
1411       for (; ! plist.IsEmpty; plist = plist.Next)
1412         {
1413           MPlist p = plist.Plist;
1414           MSymbol sym = p.Symbol;
1415           Plugin plugin = new Plugin ();
1416
1417           plugin.name = sym.Name;
1418           plugin.methods = new MPlist ();
1419           for (p = p.next; ! p.IsEmpty; p = p.next)
1420             plugin.methods.Add (p.Symbol, null);
1421           plugins.Add (sym, plugin);
1422         }
1423     }
1424
1425     private void parse_plugins (XmlNode node)
1426     {
1427       plugins = new Dictionary<MSymbol, Plugin> ();
1428
1429       foreach (XmlNode n in node.ChildNodes)
1430         {
1431           Plugin plugin = new Plugin ();
1432           plugin.name = n.Attributes["id"].Value;
1433           plugin.methods = new MPlist ();
1434           foreach (XmlNode nn in n.ChildNodes)
1435             plugin.methods.Add ((MSymbol) nn.Attributes["id"].Value,
1436                                 null);
1437           plugins.Add (plugin.name, plugin);
1438         }
1439     }
1440
1441     private void parse_macros (XmlNode node)
1442     {
1443       for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1444         if (nn.NodeType == XmlNodeType.Element)
1445           domain.Defun ((MSymbol) node.GetAttribute ("id"));
1446       for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1447         if (nn.NodeType == XmlNodeType.Element)
1448           domain.Defun ((MSymbol) node.GetAttribute ("id"), null,
1449                         nn.FirstChild);
1450     }
1451
1452     private void parse_maps (XmlNode node)
1453     {
1454     }
1455
1456     private void parse_states (XmlNode node)
1457     {
1458     }
1459
1460     private void parse_include (MPlist plist)
1461     {
1462       if (! plist.IsPlist)
1463         return;
1464       MPlist p = plist.Plist;
1465       MSymbol language, name, subname;
1466       language = p.Symbol;
1467       p = p.next;
1468       if (! p.IsSymbol)
1469         name = subname = MSymbol.nil;
1470       else
1471         {
1472           name = p.Symbol;
1473           p = p.next;
1474           if (! p.IsSymbol)
1475             subname = MSymbol.nil;
1476           else
1477             subname = p.Symbol;
1478         }
1479
1480       MInputMethod im = MInputMethod.Find (language, name, subname);
1481       if (im == null)
1482         return;
1483       if (! im.Open ())
1484         return;
1485       plist = plist.next;
1486       if (! plist.IsSymbol)
1487         return;
1488       MSymbol target_type = plist.Symbol;
1489       plist = plist.next;
1490       MSymbol target_name = MSymbol.nil;
1491       if (plist.IsSymbol)
1492         target_name = plist.Symbol;
1493       if (target_type == Mmacro)
1494         {
1495           if (target_name == MSymbol.nil)
1496             im.domain.CopyFunc (domain);
1497           else
1498             im.domain.CopyFunc (domain, target_name);
1499         }
1500       else if (target_type == Mmap)
1501         {
1502           if (target_name == MSymbol.nil)
1503             {
1504               foreach (KeyValuePair<MSymbol, Map> kv in im.maps)
1505                 maps[kv.Key] = kv.Value;
1506             }
1507           else
1508             {
1509               Map map;
1510               if (im.maps.TryGetValue (target_name, out map))
1511                 maps[target_name] = map;
1512             }
1513         }
1514       else if (target_type == Mstate)
1515         {
1516           if (target_name == MSymbol.nil)
1517             {
1518               for (p = im.states; ! p.IsEmpty; p = p.next)
1519                 states.Add (p.key, p.val);
1520             }
1521           else
1522             {
1523               object state = im.states.Get (target_name);
1524               if (state != null)
1525                 states.Add (target_name, state);
1526             }
1527         }
1528     }
1529
1530     private void parse_macros (MPlist plist)
1531     {
1532       for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
1533         if (pl.IsPlist)
1534           {
1535             MPlist p = pl.Plist;
1536
1537             if (! p.IsSymbol)
1538               continue;
1539             domain.Defun (p.Symbol, null, null);
1540           }
1541       for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
1542         if (pl.IsPlist)
1543           {
1544             MPlist p = pl.Plist;
1545
1546             if (! p.IsSymbol)
1547               continue;
1548             transform (p.next);
1549             domain.Defun (p.Symbol, null, p.next);
1550           }
1551     }
1552
1553     private void parse_maps (MPlist plist)
1554     {
1555       for (; ! plist.IsEmpty; plist = plist.next)
1556         if (plist.IsPlist)
1557           {
1558             MPlist pl = plist.Plist;
1559           
1560             if (! pl.IsSymbol)
1561               continue;
1562             Map map = new Map ();
1563             map.name = pl.Symbol;
1564             maps[map.name] = map;
1565             for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1566               {
1567                 if (! pl.IsPlist)
1568                   continue;
1569                 MPlist p = pl.Plist;
1570                 KeySeq keys;
1571                 if (p.IsMText)
1572                   keys = new KeySeq (p.Text);
1573                 else if (p.IsPlist)
1574                   keys = new KeySeq (p.Plist);
1575                 else
1576                   continue;
1577                 p = p.next;
1578                 if (p.IsEmpty)
1579                   continue;
1580                 transform (p);
1581                 MXex expr = new MXex (p, domain);
1582                 map.Add (keys, 0, expr);
1583               }
1584           }
1585     }
1586
1587     private void parse_states (MPlist plist)
1588     {
1589       for (; ! plist.IsEmpty; plist = plist.next)
1590         if (plist.IsPlist)
1591           {
1592             MPlist pl = plist.Plist;
1593             MText title = null;
1594           
1595             if (pl.IsMText)
1596               {
1597                 title = pl.Text;
1598                 pl = pl.next;
1599               }
1600             if (! pl.IsSymbol)
1601               continue;
1602
1603             State state = new State (pl.Symbol);
1604             state.title = title;
1605             if (states == null)
1606               states = new MPlist ();
1607             states.Add (state.name, state);
1608             for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1609               {
1610                 if (! pl.IsPlist)
1611                   continue;
1612                 MPlist p = pl.Plist;
1613                 if (! p.IsSymbol)
1614                   continue;
1615                 MSymbol map_name = p.Symbol;
1616                 p = p.next;
1617                 transform (p);
1618                 state.branches.Add (map_name,
1619                                     new MXex (p, domain));
1620               }
1621           }
1622     }
1623
1624     private static Xex.Term Finsert (Xex.Domain domain, Xex.Variable vari,
1625                                      Xex.Term[] args)
1626     {
1627       ((MInputContext) domain.context).insert (args[0]);
1628       return args[0];
1629     }
1630
1631     private static Xex.Term Finsert_candidates (Xex.Domain domain,
1632                                                 Xex.Variable vari,
1633                                                 Xex.Term[] args)
1634     {
1635       ((MInputContext) domain.context).insert_candidates (args[0]);
1636       return args[0];
1637     }
1638
1639     private static Xex.Term Fmarker (Xex.Domain domain, Xex.Variable vari,
1640                                      Xex.Term[] args)
1641     {
1642       MSymbol name = (string) args[0].Nameval;
1643       return Marker.Get (name);
1644     }
1645
1646     private static Xex.Term Fchar_at (Xex.Domain domain, Xex.Variable vari,
1647                                       Xex.Term[] args)
1648     {
1649       return ((MInputContext) domain.context).char_at (args[0].Intval);
1650     }
1651
1652     private static Xex.Term Fdelete (Xex.Domain domain, Xex.Variable vari,
1653                                    Xex.Term[] args)
1654     {
1655       ((MInputContext) domain.context).delete ((int) args[0].Intval);
1656       return true;
1657     }
1658
1659     private static Xex.Term Fselect (Xex.Domain domain, Xex.Variable vari,
1660                                    Xex.Term[] args)
1661     {
1662       MInputContext ic = (MInputContext) domain.context;
1663
1664       if (args[0].IsInt)
1665         ic.select (args[0].Intval);
1666       else
1667         ic.select ((MSYmbol) ((string) args[0].Nameval));
1668       return args[0];
1669     }
1670
1671     private static Xex.Term Fshow (Xex.Domain domain, Xex.Variable vari,
1672                                  Xex.Term[] args)
1673     {
1674       ((MInputContext) domain.context).show ();
1675       return Xex.Zero;
1676     }
1677
1678     private static Xex.Term Fhide (Xex.Domain domain, Xex.Variable vari,
1679                                  Xex.Term[] args)
1680     {
1681       ((MInputContext) domain.context).hide ();
1682       return Xex.Zero;
1683     }
1684
1685     private static Xex.Term Fmove (Xex.Domain domain, Xex.Variable vari,
1686                                  Xex.Term[] args)
1687     {
1688       if (args[0].IsInt)
1689         ((MInputContext) domain.context).move (args[0].Intval);
1690       else
1691         {
1692           Marker m = (Marker) args[0].Objval;
1693           MInputContext ic = (MInputContext) domain.context;
1694           ((MInputContext) domain.context).move (m.Position (ic));
1695         }
1696       return args[0];
1697     }
1698
1699     private static Xex.Term Fmark (Xex.Domain domain, Xex.Variable vari,
1700                                    Xex.Term[] args)
1701     {
1702       Marker m = (Marker) args[0].Objval;
1703       m.Mark ((MInputContext) domain.context);
1704       return args[0];
1705     }
1706
1707     private static Xex.Term Fkeyseq (Xex.Domain domain, Xex.Variable vari,
1708                                      Xex.Term[] args)
1709     {
1710       return new KeySeq (args);
1711     }
1712
1713     private static Xex.Term Fpushback (Xex.Domain domain, Xex.Variable vari,
1714                                        Xex.Term[] args)
1715     {
1716       MInputContext ic = (MInputContext) domain.context;
1717
1718       if (args[0].IsInt)
1719         ic.pushback (args[0].Intval);
1720       else if (args[0].IsStr)
1721         ic.pushback (new KeySeq (args[0].Strval));
1722       else
1723         ic.pushback ((KeySeq) args[0].Objval);
1724       return args[0];
1725     }
1726
1727     private static Xex.Term Fpop (Xex.Domain domain, Xex.Variable vari,
1728                                   Xex.Term[] args)
1729     {
1730       ((MInputContext) domain.context).pop ();
1731       return Xex.Zero;
1732     }
1733
1734     private static Xex.Term Fundo (Xex.Domain domain, Xex.Variable vari,
1735                                    Xex.Term[] args)
1736     {
1737       int n = args.Length == 0 ? -2 : args[0].Intval;
1738       ((MInputContext) domain.context).undo (n);
1739       return Xex.Zero;
1740     }
1741
1742     private static Xex.Term Fcommit (Xex.Domain domain, Xex.Variable vari,
1743                                      Xex.Term[] args)
1744     {
1745       ((MInputContext) domain.context).commit ();
1746       return Xex.Zero;
1747     }
1748
1749     private static Xex.Term Funhandle (Xex.Domain domain, Xex.Variable vari,
1750                                        Xex.Term[] args)
1751     {
1752       ((MInputContext) domain.context).commit ();
1753       args = new Xex.Term[2];
1754       args[0] = args[1] = catch_tag;
1755       return Xex.Fthrow (domain, vari, args);
1756     }
1757
1758     private static Xex.Term Fshift (Xex.Domain domain, Xex.Variable vari,
1759                                     Xex.Term[] args)
1760     {
1761       ((MInputContext) domain.context).shift (args[0].Symval);
1762       return args[0];
1763     }
1764
1765     public override string ToString ()
1766     {
1767       string str = (String.Format ("({0} (title \"{1}\")", tag, title));
1768       if (commands != null)
1769         {
1770           str += " (commands";
1771           foreach (Command cmd in commands)
1772             str += " " + cmd;
1773           str += ")";
1774         }
1775       if (variables != null)
1776         {
1777           str += " (variables";
1778           foreach (Variable var in variables)
1779             str += " " + var;
1780           str += ")";
1781         }
1782       if (plugins != null)
1783         {
1784           str += " (modules";
1785           foreach (KeyValuePair<MSymbol, Plugin> kv in plugins)
1786             str += " " + kv.Value;
1787           str += ")";
1788         }
1789       str += " (maps";
1790       foreach (KeyValuePair<MSymbol, Map> kv in maps)
1791         str += " " + kv.Value;
1792       str += ") (states";
1793       foreach (MPlist p in states)
1794         str += " " + p.val;
1795       return str + "))";
1796     }
1797   }
1798
1799   public class MInputContext
1800   {
1801     internal static MSymbol Mcandidates_group_size = "candidates-group-size";
1802     private static MSymbol Mat_less_than = "@<";
1803     private static MSymbol Mat_greater_than = "@>";
1804     private static MSymbol Mat_minus = "@-";
1805     private static MSymbol Mat_plus = "@+";
1806     private static MSymbol Mat_open_square_bracket = "@[";
1807     private static MSymbol Mat_close_square_bracket = "@]";
1808
1809     public MInputMethod im;
1810     private MText produced;
1811     private bool active;
1812     private MText status;
1813     private bool status_changed;
1814     private MText preedit;
1815     private bool preedit_changed;
1816     private int cursor_pos;
1817     private bool cursor_pos_changed;
1818     private Candidates candidates;
1819     private MPlist candidate_group;
1820     private int candidate_index;
1821     private int candidate_from, candidate_to;
1822     private bool candidate_show;
1823     private bool candidate_changed;
1824
1825     private Stack<MInputMethod.State> states;
1826     internal MInputMethod.KeySeq keys;
1827     private int key_head;
1828     private int state_key_head;
1829     private MPlist state_boundary;
1830     private int commit_key_head;
1831     private MText state_preedit;
1832     private int state_pos;
1833     internal MPlist markers = new MPlist ();
1834     private MPlist vars;
1835     private MPlist vars_saved;
1836     internal MText preceding_text = new MText ();
1837     internal MText following_text = new MText ();
1838     private bool key_unhandled;
1839
1840     internal Xex.Domain domain;
1841
1842     public MInputContext (MInputMethod im)
1843     {
1844       this.im = im;
1845       domain = new Xex.Domain (im.domain, this);
1846       states = new Stack<MInputMethod.State> ();
1847       states.Push ((MInputMethod.State) im.states.val);
1848       keys = new MInputMethod.KeySeq ();
1849     }
1850
1851     private void adjust_markers (int from, int to, object inserted)
1852     {
1853       int ins = (inserted == null ? 0
1854                  : inserted is int ? 1
1855                  : ((MText) inserted).Length);
1856       int diff = ins - (to - from);
1857
1858       for (MPlist plist = markers; ! plist.IsEmpty; plist = plist.next)
1859         {
1860           int pos = plist.Integer;
1861           if (pos > from)
1862             {
1863               if (pos >= to)
1864                 plist.val = pos + diff;
1865               else
1866                 plist.val = from;
1867             }
1868         }
1869       if (cursor_pos >= to)
1870         cursor_pos += diff;
1871       else if (cursor_pos > from)
1872         cursor_pos = from;
1873     }
1874
1875     private void preedit_replace (int from, int to, int c)
1876     {
1877       preedit.Del (from, to);
1878       preedit.Ins (from, c);
1879       adjust_markers (from, to, c);
1880     }
1881
1882     private void preedit_replace (int from, int to, MText mt)
1883     {
1884       preedit[from, to] = mt;
1885       adjust_markers (from, to, mt);
1886     }
1887
1888     internal void insert (Xex.Term arg)
1889     {
1890       if (arg.IsInt)
1891         preedit_replace (cursor_pos, cursor_pos, arg.Intval);
1892       else
1893         preedit_replace (cursor_pos, cursor_pos, new MText (arg.Strval));
1894       preedit_changed = true;
1895       cursor_pos_changed = true;
1896     }
1897
1898     private class Candidates
1899     {
1900       private class Block
1901       {
1902         public int Index;
1903         public object Data;
1904
1905         public Block (int index, MPlist plist)
1906         {
1907           Index = index;
1908           if (plist.IsMText)
1909             Data = plist.Text;
1910           else
1911             Data = plist.Plist;
1912         }
1913
1914         public int Count
1915         {
1916           get { return (Data is MText
1917                         ? ((MText) Data).Length
1918                         : ((MPlist) Data).Count); }
1919         }
1920
1921         public object this[int i]
1922         {
1923           get {
1924             if (Data is MText) return ((MText) Data)[i];
1925             return  ((MPlist) Data)[i];
1926           }
1927         }
1928       }
1929
1930       private Block[] blocks;
1931       private int row = 0;
1932       private int index = 0;
1933       public object[] group;
1934
1935       private bool IsFixed { get { return group != null; } }
1936       private int Total {
1937         get {
1938           Block last = blocks[blocks.Length - 1];
1939           return last.Index + last.Count; }
1940       }
1941
1942       public int Column {
1943         get { return (IsFixed ? index % group.Length
1944                       : index - blocks[row].Index); }
1945       }
1946
1947       public object Group {
1948         get { return (IsFixed ? group : blocks[row].Data); }
1949       }
1950
1951       public int GroupLength
1952       {
1953         get {
1954           if (IsFixed)
1955             {
1956               int nitems = group.Length;
1957               int start = index - (index % nitems);
1958               int total = Total;
1959               return (start + nitems <= total ? nitems : total - start);
1960             }
1961           return blocks[row].Count;
1962         }
1963       }
1964
1965       public object Current {
1966         get {
1967           return (IsFixed ? group[index % group.Length]
1968                   : blocks[row][index - blocks[row].Index]);
1969         }
1970       }
1971
1972       public Candidates (MPlist list, int column)
1973       {
1974         int nblocks = list.Count;
1975
1976         blocks = new Block[nblocks];
1977         for (int i = 0, start = 0; i < nblocks; i++, list = list.next)
1978           start += (blocks[i] = new Block (index, list)).Count;
1979         if (column > 0)
1980           group = new object[column];
1981       }
1982
1983       public Candidates (List<Xex.Term> list, int column)
1984       {
1985         int nblocks = list.Count;
1986
1987         blocks = new Block[nblocks];
1988         for (int i = 0, start = 0; i < nblocks; i++)
1989           start += (blocks[i] = new Block (index, list[i])).Count;
1990         if (column > 0)
1991           group = new object[column];
1992       }
1993
1994       public static void Detach (MInputContext ic)
1995       {
1996         ic.preedit.PopProp (0, ic.preedit.Length, MInputMethod.Mcandidates);
1997         ic.candidates = null;
1998         ic.preedit_changed = true;
1999         ic.cursor_pos_changed = true;
2000         ic.candidate_changed = true;
2001       }
2002
2003       // Fill the array "group" by candidates stating from INDEX.
2004       // INDEX must be a multiple of "column".  Set NTIMES to the
2005       // number of valid candidates in "group".  Update "block" if
2006       // necessary.  Return "group".
2007
2008       private int fill_group (int start)
2009       {
2010         int nitems = group.Length;
2011         int r = row;
2012         Block b = blocks[r];
2013
2014         if (start < b.Index)
2015           while (start < b.Index)
2016             b = blocks[--r];
2017         else
2018           while (start >= b.Index + b.Count)
2019             b = blocks[++r];
2020         row = r;
2021
2022         int count = b.Count;
2023         start -= b.Index;
2024         for (int i = 0; i < nitems; i++, start++)
2025           {
2026             if (start >= count)
2027               {
2028                 r++;
2029                 if (r == blocks.Length)
2030                   return i;
2031                 b = blocks[r];
2032                 count = b.Count;
2033                 start = 0;
2034               }
2035             group[i] = b[start];
2036           }
2037         return nitems;
2038       }
2039
2040       // Update "row" to what contains the first candidate of
2041       // the previous candidate-group, update "current_index", and
2042       // update "group" if necessary.  Return the previous
2043       // candidate-group.  Set NITEMS to the number of valid
2044       // candidates contained in that group.
2045
2046       public int PrevGroup ()
2047       {
2048         int nitems;
2049         int col = Column;
2050
2051         if (IsFixed)
2052           {
2053             nitems = group.Length;
2054             if ((index -= col + nitems) < 0)
2055               index = (Total / nitems) * nitems;
2056             nitems = fill_group (index);
2057           }
2058         else
2059           {
2060             row = row > 0 ? row-- : blocks.Length - 1;
2061             nitems = blocks[row].Count;
2062             index = blocks[row].Index;
2063           }
2064         index += col < nitems ? col : nitems - 1;
2065         return nitems;
2066       }
2067
2068       public int NextGroup ()
2069       {
2070         int nitems;
2071         int col = Column;
2072
2073         if (IsFixed)
2074           {
2075             nitems = group.Length;
2076             if ((index += nitems - col) >= Total)
2077               index = 0;
2078             nitems = fill_group (index);
2079           }
2080         else
2081           {
2082             row = row < blocks.Length - 1 ? row + 1 : 0;
2083             nitems = blocks[row].Count;
2084             index = blocks[row].Count;
2085           }
2086         index += col < nitems ? col : nitems - 1;
2087         return nitems;
2088       }
2089
2090       public void Prev ()
2091       {
2092         int col = Column;
2093
2094         if (col == 0)
2095           {
2096             int nitems = PrevGroup ();
2097             index += col < nitems - 1 ? col : nitems - 1;
2098           }
2099         else
2100           index--;
2101       }
2102
2103       public void Next ()
2104       {
2105         int col = Column;
2106         int nitems = GroupLength;
2107
2108         if (col == nitems - 1)
2109           {
2110             nitems = NextGroup ();
2111             index -= Column;
2112           }
2113         else
2114           index++;
2115       }
2116
2117       public void First ()
2118       {
2119         index -= Column;
2120       }
2121
2122       public void Last ()
2123       {
2124         index += GroupLength - (Column + 1);
2125       }
2126
2127       public void Select (int col)
2128       {
2129         int maxcol = GroupLength - 1;
2130         if (col > maxcol)
2131           col = maxcol;
2132         index = index - Column + col;
2133       }
2134     }
2135
2136     private void update_candidate ()
2137     {
2138       object candidate = candidates.Current;
2139
2140       if (candidate is MText)
2141         {
2142           preedit_replace (candidate_from, candidate_to, (MText) candidate);
2143           candidate_to = candidate_from + ((MText) candidate).Length;
2144         }
2145       else
2146         {
2147           preedit_replace (candidate_from, candidate_to, (int) candidate);
2148           candidate_to = candidate_from + 1;
2149         }
2150       preedit.PushProp (candidate_from, candidate_to,
2151                         MInputMethod.Mcandidates, this);
2152       cursor_pos = candidate_from;
2153       preedit_changed = true;
2154       cursor_pos_changed = true;
2155       candidate_changed = true;
2156     }
2157
2158     internal void insert_candidates (Xex.Term arg)
2159     {
2160       int column = 0;
2161
2162       if (domain.IsBound (Mcandidates_group_size))
2163         {
2164           object val = domain.GetValue (Mcandidates_group_size);
2165           if (val is int)
2166             column = (int) val;
2167         }
2168       candidates = new Candidates (arg.Listval, column);
2169       candidate_from = candidate_to = cursor_pos;
2170       update_candidate ();
2171     }
2172
2173     internal void select (int n)
2174     {
2175       if (candidates != null)
2176         {
2177           candidates.Select (n);
2178           update_candidate ();
2179         }
2180     }
2181
2182     internal void select (MSymbol sym)
2183     {
2184       if (candidates != null)
2185         {
2186           if (sym == Mat_less_than)
2187             candidates.First ();
2188           else if (sym == Mat_greater_than)
2189             candidates.Last ();
2190           else if (sym == Mat_minus)
2191             candidates.Prev ();
2192           else if (sym == Mat_plus)
2193             candidates.Next ();
2194           else if (sym == Mat_open_square_bracket)
2195             candidates.PrevGroup ();
2196           else if (sym == Mat_close_square_bracket)
2197             candidates.NextGroup ();
2198         }
2199     }
2200
2201     internal int marker (MSymbol sym)
2202     {
2203       int pos = cursor_pos;
2204
2205       if (sym.Name.Length == 2 && sym.Name[0] == '@')
2206         {
2207           switch (sym.Name[0])
2208             {
2209             case '<': pos = 0; break;
2210             case '>': pos = preedit.Length; break;
2211             case '-': pos = cursor_pos - 1; break;
2212             case '+': pos = cursor_pos + 1; break;
2213             case '[':
2214               if (pos > 0)
2215                 {
2216                   int to;
2217                   preedit.FindProp (MInputMethod.Mcandidates, pos - 1,
2218                                     out pos, out to);
2219                 }
2220               else
2221                 pos = 0;
2222               break;
2223             case ']':
2224               if (cursor_pos < preedit.Length - 1)
2225                 {
2226                   int from;
2227                   preedit.FindProp (MInputMethod.Mcandidates, pos,
2228                                     out from, out pos);
2229                 }
2230               else
2231                 pos = preedit.Length;
2232               break;
2233             default:
2234               if (sym.Name[0] >= '0' && sym.Name[0] <= '9')
2235                 pos = sym.Name[0];
2236               break;
2237             }
2238         }
2239       else if (sym.Name.Length >= 3 && sym.Name[0] == '@')
2240         {
2241           pos = int.Parse (sym.Name.Substring (2));
2242         }
2243       else
2244         {
2245           object val = markers.Get (sym);
2246
2247           if (val is int)
2248             pos = (int) val;
2249         }
2250       return pos;
2251     }
2252
2253     internal int char_at (int pos)
2254     {
2255       int c;
2256
2257       pos += cursor_pos;
2258       if (pos < 0)
2259         {
2260           if (preceding_text.Length < -pos)
2261             {
2262               MPlist plist = new MPlist ();
2263               plist.Push (MSymbol.integer, pos);
2264               if (MInputMethod.GetSurroundingText != null
2265                   && MInputMethod.GetSurroundingText (this, plist)
2266                   && plist.IsMText
2267                   && preceding_text.Length < plist.Text.Length)
2268                 preceding_text = plist.Text;
2269             }
2270           c = (-pos < preceding_text.Length
2271                ? preceding_text[preceding_text.Length + pos] : -1);
2272         }
2273       else if (pos >= 0 && pos < preedit.Length)
2274         c = preedit[pos];
2275       else
2276         {
2277           pos -= preedit.Length;
2278           if (pos >= following_text.Length)
2279             {
2280               MPlist plist = new MPlist ();
2281               plist.Push (MSymbol.integer, pos + 1);
2282               if (MInputMethod.GetSurroundingText != null
2283                   && MInputMethod.GetSurroundingText (this, plist)
2284                   && plist.IsMText
2285                   && following_text.Length < plist.Text.Length)
2286                 following_text = plist.Text;
2287             }
2288           c = (pos < following_text.Length ? following_text[pos] : -1);
2289         }
2290       return c;
2291     }
2292
2293     internal void delete (int pos)
2294     {
2295       if (pos < cursor_pos)
2296         preedit_replace (pos, cursor_pos, null);
2297       else
2298         preedit_replace (cursor_pos, pos, null);
2299       preedit_changed = true;
2300       cursor_pos_changed = true;
2301     }
2302
2303     internal void show ()
2304     {
2305       candidate_show = true;
2306       candidate_changed = true;
2307     }
2308
2309     internal void hide ()
2310     {
2311       candidate_show = false;
2312       candidate_changed = true;
2313     }
2314
2315     internal void move (int pos)
2316     {
2317       if (pos < 0)
2318         pos = 0;
2319       else if (pos > preedit.Length)
2320         pos = preedit.Length;
2321       if (pos != cursor_pos)
2322         {
2323           cursor_pos = pos;
2324           preedit_changed = true;
2325         }
2326     }
2327
2328     internal void mark (MSymbol sym)
2329     {
2330       MPlist slot = markers.Find (sym);
2331
2332       if (slot == null)
2333         markers.Push (sym, cursor_pos);
2334       else
2335         slot.val = cursor_pos;
2336     }
2337
2338     internal void pushback (int n)
2339     {
2340       if (n > 0)
2341         {
2342           key_head -= n;
2343           if (key_head < 0)
2344             key_head = 0;
2345         }
2346       else if (n == 0)
2347         key_head = 0;
2348       else
2349         {
2350           key_head = - n;
2351           if (key_head > keys.Count)
2352             key_head = keys.Count;
2353         }
2354     }
2355
2356     internal void pushback (MInputMethod.KeySeq keyseq)
2357     {
2358       if (key_head > 0)
2359         key_head--;
2360       if (key_head < keys.Count)
2361         keys.RemoveRange (key_head, keys.Count - key_head);
2362       for (int i = 0; i < keyseq.Count; i++)
2363         keys.Add (keyseq[i]);
2364     }
2365
2366     internal void pop ()
2367     {
2368       if (key_head < keys.Count)
2369         keys.RemoveRange (key_head, 1);
2370     }
2371
2372     internal void undo (int n)
2373     {
2374       if (n < 0)
2375         keys.RemoveRange (keys.Count + n, - n);
2376       else
2377         keys.RemoveRange (n, keys.Count  - n);
2378       reset ();
2379     }
2380
2381     internal void commit ()
2382     {
2383       produced.Cat (preedit);
2384       preedit.Del ();
2385       preedit_changed = true;
2386     }
2387
2388     internal void shift (MSymbol sym)
2389     {
2390       MInputMethod.State state;
2391
2392       if (sym == MSymbol.t)
2393         {
2394           if (states.Count > 1)
2395             state = states.Pop ();
2396           else
2397             state = states.Peek ();
2398         }
2399       else
2400         {
2401           state = (MInputMethod.State) im.states.Get (sym);
2402           if (state == null)
2403             throw new Exception ("Unknown state: " + state.name);
2404         }
2405       if (state == null)
2406         state = states.Pop ();
2407       if (state == (MInputMethod.State) im.states.val)
2408         {
2409           commit ();
2410           reset ();
2411         }
2412       else
2413         {
2414           state_key_head = key_head;
2415           state_pos = cursor_pos;
2416           state_preedit = preedit.Dup ();
2417           if (state != states.Peek ())
2418             {
2419               states.Push (state);
2420               state_boundary = domain.SetBoundary ();
2421               status = state.title;
2422               if (status == null)
2423                 status = im.title;
2424               status_changed = true;
2425               Xex on_entry
2426                 = (Xex) state.branches.Get (MSymbol.t);
2427               if (on_entry != null)
2428                 on_entry.Eval (domain);
2429             }
2430         }
2431     }
2432
2433     internal bool call (MSymbol module, MSymbol method, MPlist arglist)
2434     {
2435       MInputMethod.Plugin plugin;
2436
2437       if (! im.plugins.TryGetValue (module, out plugin))
2438         return false;
2439       if (plugin.assembly == null)
2440         {
2441           Assembly assembly;
2442
2443           try {
2444             assembly = Assembly.LoadFrom (module.Name + ".dll");
2445           } catch {
2446             return false;
2447           }
2448           Type t = assembly.GetType ("Plugin");
2449           for (MPlist p = plugin.methods; ! p.IsEmpty; p = p.next)
2450             p.Set (p.key, t.GetMethod (p.key.Name));
2451         }
2452
2453       MethodInfo method_info = (MethodInfo) plugin.methods.Get (method);
2454       if (method_info == null)
2455         return false;
2456       object[] method_arg = new object[1];
2457       method_arg[0] = arglist;
2458       bool result = (bool) method_info.Invoke (null, method_arg);
2459       if (! result)
2460         return false;
2461       if (! arglist.IsEmpty)
2462         (new Xex (arglist, domain)).Eval (domain);
2463       return true;
2464     }
2465
2466     internal void reset ()
2467     {
2468       preedit.Del ();
2469       state_preedit.Del ();
2470       produced.Del ();
2471       markers.Clear ();
2472       cursor_pos = 0;
2473       key_head = commit_key_head = 0;
2474       states.Clear ();
2475       states.Push ((MInputMethod.State) im.states.Val);
2476       state_key_head = 0;
2477       state_pos = 0;
2478     }
2479
2480     internal object GetCandidates (out int column)
2481     {
2482       column = 0;
2483       if (cursor_pos == 0)
2484         return null;
2485       Candidates candidates
2486         = (Candidates) preedit.GetProp (cursor_pos - 1,
2487                                         MInputMethod.Mcandidates);
2488       if (candidates == null)
2489         return null;
2490       column = candidates.Column;
2491       return candidates.Current;
2492     }
2493
2494     internal void HandleKey ()
2495     {
2496       MInputMethod.State state = states.Peek ();
2497
2498       
2499     }
2500   }
2501 }