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