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