2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Reflection;
12 using Xex = System.Xml.Expression.Xexpression;
16 public class MInputMethod
19 public delegate bool Callback (Context ic, MPlist args);
22 public static event Callback PreeditChanged;
23 public static event Callback StatusChanged;
24 public static event Callback CandidateChanged;
25 public static Callback GetSurroundingText;
26 public static Callback DeleteSurroundingText;
28 internal static Xex.Domain im_domain
29 = new Xex.Domain ("input-method", null);
30 private static MSymbol Minput_method = "input-method";
31 private static MSymbol Mdescription = "description";
32 private static MSymbol Mvariable = "variable";
33 private static MSymbol Mcommand = "command";
34 private static MSymbol Mmodule = "module";
35 private static MSymbol Mtitle = "title";
36 private static MSymbol Minclude = "include";
37 private static MSymbol Mmacro = "macro";
38 private static MSymbol Mmap = "map";
39 private static MSymbol Mmap_list = "map-list";
40 private static MSymbol Mstate = "state";
41 internal static MSymbol Mcandidates = "candidates";
42 private static MSymbol Mat_minus_zero = "@-0";
44 private static Xex.Symbol Qmap = "map";
45 private static Xex.Symbol Qrule = "rule";
46 private static Xex.Symbol Qkeyseq = "keyseq";
47 private static Xex.Symbol Qprogn = "progn";
48 private static Xex.Symbol Qcatch = "catch";
49 private static Xex.Symbol Qinsert = "insert";
50 private static Xex.Symbol Qinsert_candidates = "insert-candidates";
51 private static Xex.Symbol Qchar_at = "char-at";
52 private static Xex.Symbol Qselect = "select";
53 private static Xex.Symbol Qdelete = "delete";
54 private static Xex.Symbol Qshift = "shift";
55 private static Xex.Symbol Qmove = "move";
56 private static Xex.Symbol Qmark = "mark";
57 private static Xex.Symbol Qset = "set";
58 private static Xex.Symbol Qadd = "add";
59 private static Xex.Symbol Qsub = "sub";
60 private static Xex.Symbol Qmul = "mul";
61 private static Xex.Symbol Qdiv = "div";
62 private static Xex.Symbol Qcond = "cond";
63 private static Xex.Symbol Qsname = "sname";
64 private static Xex.Symbol Qmname = "mname";
65 private static Xex.Symbol Qstate_hook = "state-hook";
66 private static Xex.Symbol Qcatch_all_branch = "catch-all-branch";
67 private static Xex.Symbol Qbranch = "branch";
68 private static Xex.Symbol Qstate = "state";
69 private static Xex.Symbol Qtitle = "title";
70 private static Xex.Symbol Qeq = "=";
71 private static Xex.Symbol Qeqeq = "==";
72 private static Xex.Symbol Qcandidates_group_size = "candidates-group-size";
74 private static Xex.Term Tnil = new Xex.Term ((Xex.Symbol) "nil");
75 private static Xex.Term Tcatch_tag = new Xex.Term ((Xex.Symbol) "@mimtag");
77 private static Dictionary<MDatabase.Tag, MInputMethod> im_table
78 = new Dictionary<MDatabase.Tag, MInputMethod> ();
80 internal static MInputMethod im_global = null;
83 protected enum LoadStatus
93 public enum ChangedStatus
100 CandidateIndex = 0x10,
101 CandidateShow = 0x20,
102 Preedit = PreeditText | CursorPos,
103 Candidate = CandidateList | CandidateIndex | CandidateShow,
106 private static ChangedStatus CandidateAll = (ChangedStatus.CandidateList
107 | ChangedStatus.CandidateIndex
108 | ChangedStatus.CandidateShow);
110 public enum KeyModifier
113 Shift_L = 0x00400000,
114 Shift_R = 0x00800000,
116 Control_L = 0x01000000,
117 Control_R = 0x02000000,
118 Control = 0x03000000,
133 private static Dictionary<string, uint> keysyms
134 = new Dictionary<string, uint> ();
135 private static Dictionary<string, KeyModifier> keymodifiers
136 = new Dictionary<string, KeyModifier> ();
137 private static uint keysym_base = 0x200000;
138 private static uint char_mask = ~((uint) KeyModifier.All);
139 public static Key Reload;
143 keysyms["bs"] = keysyms["backspace"] = 0x08;
144 keysyms["tab"] = 0x09;
145 keysyms["lf"] = keysyms["linefeed"] = 0x10;
146 keysyms["cr"] = keysyms["return"] = keysyms["enter"] = 0x13;
147 keysyms["esc"] = keysyms["escape"] = 0x1B;
148 keysyms["spc"] = keysyms["space"] = 0x20;
149 keysyms["del"] = keysyms["delete"] = 0x7F;
150 keymodifiers["shift-l"] = KeyModifier.Shift_L;
151 keymodifiers["shift-r"] = KeyModifier.Shift_R;
152 keymodifiers["shift"] = KeyModifier.Shift;
153 keymodifiers["control-l"] = KeyModifier.Control_L;
154 keymodifiers["control-r"] = KeyModifier.Control_R;
155 keymodifiers["control"] = KeyModifier.Control;
156 keymodifiers["alt-l"] = KeyModifier.Alt_L;
157 keymodifiers["alt-r"] = KeyModifier.Alt_R;
158 keymodifiers["alt"] = KeyModifier.Alt;
159 keymodifiers["altgr"] = KeyModifier.AltGr;
160 keymodifiers["super"] = KeyModifier.Super;
161 keymodifiers["hyper"] = KeyModifier.Hyper;
162 Reload = new Key (keysym_base);
163 keysyms["-reload"] = keysym_base++;
166 private static uint decode_keysym (MSymbol keysym)
169 string name = keysym.Name;
171 if (name.Length == 1)
173 name = name.ToLower ();
174 if (! keysyms.TryGetValue (name, out key))
175 keysyms[name] = key = keysym_base++;
179 private static uint combine_modifiers (uint c, KeyModifier modifiers)
181 if (c < 0x7F && c != 0x20)
183 if ((modifiers & KeyModifier.Shift) != KeyModifier.None
184 && Char.IsLower ((char) c))
186 modifiers &= ~KeyModifier.Shift;
187 c = Char.ToUpper ((char) c);
189 if ((modifiers & KeyModifier.Control) != KeyModifier.None)
191 modifiers &= ~KeyModifier.Control;
195 return c | (uint) modifiers;
198 public Key (uint c) { key = c; }
199 public Key (int c) { key = (uint) c; }
201 public Key (uint c, KeyModifier modifiers)
203 key = combine_modifiers (c, modifiers);
206 public Key (MSymbol keysym, KeyModifier modifiers)
208 key = combine_modifiers (decode_keysym (keysym), modifiers);
211 public Key (MSymbol keysym)
213 string str = keysym.Name;
214 int len = str.Length;
216 KeyModifier modifiers = KeyModifier.None;
218 for (i = 0; i + 2 < len && str[i + 1] == '-'; i += 2)
221 modifiers |= KeyModifier.Shift;
222 else if (str[i] == 'C')
223 modifiers |= KeyModifier.Control;
224 else if (str[i] == 'A')
225 modifiers |= KeyModifier.Alt;
226 else if (str[i] == 'G')
227 modifiers |= KeyModifier.AltGr;
228 else if (str[i] == 's')
229 modifiers |= KeyModifier.Super;
230 else if (str[i] == 'H')
231 modifiers |= KeyModifier.Hyper;
234 key = combine_modifiers (str[i], modifiers);
236 key = combine_modifiers (decode_keysym (keysym), modifiers);
239 public Key (MPlist plist)
241 KeyModifier modifiers = KeyModifier.None;
244 for (p = plist; ! p.IsEmpty; p = p.next)
248 if (! p.next.IsEmpty)
249 throw new Exception ("Invalid Key: " + plist);
252 else if (! p.IsSymbol)
253 throw new Exception ("Invalid Key: " + plist);
256 string name = p.Symbol.Name.ToLower ();
259 if (! keymodifiers.TryGetValue (name, out m))
264 if (p.IsEmpty || ! p.next.IsEmpty)
265 throw new Exception ("Invalid Key: " + plist);
267 key = combine_modifiers ((uint) p.Integer, modifiers);
269 key = combine_modifiers (decode_keysym (p.Symbol), modifiers);
272 public bool HasModifier
274 get { return ((key & (uint) KeyModifier.All) != 0); }
277 public static bool operator== (Key k1, Key k2)
279 return k1.key == k2.key;
282 public static bool operator!= (Key k1, Key k2)
284 return k1.key != k2.key;
287 public override bool Equals (object o) { return key == ((Key) o).key; }
289 public override int GetHashCode () { return (int) key; }
291 public bool Match (Key k)
295 if ((k.key & char_mask) != (key & char_mask))
297 KeyModifier m1 = ((KeyModifier) key) & KeyModifier.All;
298 KeyModifier m2 = ((KeyModifier) k.key) & KeyModifier.All;
299 return (((m1 & KeyModifier.Shift) == (m2 & KeyModifier.Shift)
300 || ((m1 & KeyModifier.Shift) == KeyModifier.Shift
301 && (m2 & KeyModifier.Shift) != KeyModifier.None))
302 && ((m1 & KeyModifier.Control) == (m2 & KeyModifier.Control)
303 || ((m1 & KeyModifier.Control) == KeyModifier.Control
304 && (m2 & KeyModifier.Control) != KeyModifier.None))
305 && ((m1 & KeyModifier.Alt) == (m2 & KeyModifier.Alt)
306 || ((m1 & KeyModifier.Alt) == KeyModifier.Alt
307 && (m2 & KeyModifier.Alt) != KeyModifier.None))
308 && ((m1 & KeyModifier.High) == (m2 & KeyModifier.High)));
313 return (int) (key & 0x1FFFFF);
316 public override string ToString ()
321 foreach (KeyValuePair<string, uint> kv in keysyms)
322 if ((uint) c == kv.Value)
330 KeyModifier m = ((KeyModifier) key) & KeyModifier.All;
332 if (m != KeyModifier.None)
334 if ((m & KeyModifier.Shift) != KeyModifier.None)
336 if ((m & KeyModifier.Control) != KeyModifier.None)
338 if ((m & KeyModifier.Alt) != KeyModifier.None)
340 if ((m & KeyModifier.AltGr) != KeyModifier.None)
342 if ((m & KeyModifier.Super) != KeyModifier.None)
344 if ((m & KeyModifier.Hyper) != KeyModifier.None)
351 internal class KeySeq : Xex.TermValue
353 public List<Key> keyseq = new List<Key> ();
355 public override Xex.TermValue Clone ()
357 KeySeq ks = new KeySeq ();
358 ks.keyseq.InsertRange (0, keyseq);
364 public KeySeq (MPlist plist)
366 foreach (MPlist p in plist)
369 keyseq.Add (new Key (p.Symbol));
370 else if (p.IsInteger)
371 keyseq.Add (new Key ((char) p.Integer));
373 keyseq.Add (new Key (p.Plist));
375 throw new Exception ("Invalid Key Sequence: " + plist);
379 public KeySeq (MText mt) : base ()
381 for (int i = 0; i < mt.Length; i++)
382 keyseq.Add (new Key ((uint) mt[i]));
385 public KeySeq (List<Xex.Term> list)
387 int len = list.Count;
389 for (int i = 0; i < len; i++)
392 keyseq.Add (new Key (list[i].Intval));
393 else if (list[i].IsStr)
394 keyseq.Add (new Key (list[i].Strval));
395 else if (list[i].IsSymbol)
396 keyseq.Add (new Key ((string) list[i].Symval));
398 throw new Exception ("Invalid key: " + list[i]);
402 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
404 Xex.Term term = new Xex.Term (domain, node.FirstChild).Eval (domain);
405 return (term.IsStr ? new KeySeq ((MText) term.Strval)
406 : new KeySeq (term.Listval));
409 public override string ToString ()
412 foreach (Key key in keyseq)
413 if (key.HasModifier || key.ToChar () < 0x20)
416 foreach (Key k in keyseq)
420 mt.Cat (k.ToString ());
422 return (string) mt.Cat (")");
425 foreach (Key k in keyseq)
429 if (c == '\\' || c == '"')
433 return (string) mt.Cat ("\"");
440 public MText description;
441 internal List<KeySeq> keys;
443 public Command (MPlist p)
447 description = parse_description (p);
448 if (description == null)
449 description = "No description";
450 keys = new List<KeySeq> ();
451 for (p = p.next; ! p.IsEmpty; p = p.next)
454 keys.Add (new KeySeq (p.Text));
456 keys.Add (new KeySeq (p.Plist));
460 public Command (XmlNode node)
462 name = node.Attributes[0].Value;
463 keys = new List<KeySeq> ();
464 for (node = node.FirstChild; node != null; node = node.NextSibling)
466 if (node.Name == "description")
467 description = parse_description (node);
468 else if (node.Name == "keyseq")
469 keys.Add ((KeySeq) KeySeq.parser (null, node));
473 public override string ToString ()
475 string str = "(" + name + " \"" + (string) description;
476 foreach (KeySeq keyseq in keys)
482 internal class Plugin
485 private Assembly assembly;
486 private Type plugin_type;
488 public Plugin (string name)
493 public MethodInfo GetMethod (Xex.Symbol name)
495 if (assembly == null)
497 assembly = Assembly.LoadFrom (name + ".dll");
498 plugin_type = assembly.GetType ("M17n.MInputMethod.Plugin");
501 MethodInfo info = plugin_type.GetMethod ((string) name);
503 throw new Exception ("Invalid plugin method: " + name);
507 public override string ToString ()
509 return String.Format ("(module {0}", name);
513 internal class PluginMethod : Xex.Function
515 private Plugin plugin;
516 private MethodInfo method_info;
517 object[] parameters = new object[2];
519 public PluginMethod (Plugin plugin, string name)
520 : base ((Xex.Symbol) name, 0, -1)
522 this.plugin = plugin;
525 public override Xex.Term Call (Xex.Domain domain, Xex.Variable vari,
528 args = (Xex.Term[]) args.Clone ();
529 for (int i = 0; i < args.Length; i++)
531 args[i] = args[i].Eval (domain);
535 if (method_info == null)
536 method_info = plugin.GetMethod (name);
537 parameters[0] = domain.context;
538 parameters[1] = args;
539 return (Xex.Term) method_info.Invoke (null, parameters);
543 internal abstract class Marker : Xex.TermValue
545 private MSymbol name;
547 private Marker (MSymbol name)
552 public abstract int Position (Context ic);
554 public virtual void Mark (Context ic)
556 throw new Exception ("Can't set predefined marker: " + name);
558 public virtual int CharAt (Context ic)
560 return ic.preedit[Position (ic)];
563 public override string ToString ()
565 return "<marker>" + name.Name + "</marker>";
568 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
570 return Get ((MSymbol) node.InnerText);
573 public class Named : Marker
575 public Named (MSymbol name) : base (name) { }
577 public override int Position (Context ic)
579 MPlist p = ic.marker_positions.Find (name);
580 return (p == null ? 0 : p.Integer);
583 public override void Mark (Context ic)
585 ic.marker_positions.Put (name, ic.cursor_pos);
589 public class Predefined : Marker
593 public Predefined (MSymbol name) : base (name)
595 tag = ((string) name)[1];
598 public override int Position (Context ic)
602 case '>': return ic.preedit.Length;
603 case '-': return ic.cursor_pos - 1;
604 case '+': return ic.cursor_pos + 1;
606 if (ic.cursor_pos > 0)
608 int pos = ic.cursor_pos;
610 ic.preedit.FindProp (Mcandidates, pos - 1, out pos, out to);
615 if (ic.cursor_pos < ic.preedit.Length - 1)
617 int pos = ic.cursor_pos;
619 ic.preedit.FindProp (Mcandidates, pos, out from, out pos);
622 return ic.preedit.Length;
629 public class PredefinedAbsolute : Marker
633 public PredefinedAbsolute (MSymbol name) : base (name)
635 if (! int.TryParse (((string) name).Substring (1), out pos))
636 throw new Exception ("Invalid marker name: " + name);
639 public override int Position (Context ic)
641 return (pos < ic.preedit.Length ? pos : ic.preedit.Length);
645 public class PredefinedSurround : Marker
647 private int distance;
649 public PredefinedSurround (MSymbol name) : base (name)
651 if (! int.TryParse (((string) name).Substring (2), out distance))
652 throw new Exception ("Invalid marker name: " + name);
657 public override int Position (Context ic)
659 return ic.cursor_pos + distance;
662 public override int CharAt (Context ic)
664 int pos = ic.cursor_pos + distance;
666 return ic.GetSurroundingChar (pos);
667 else if (pos >= ic.preedit.Length)
668 return ic.GetSurroundingChar (pos - ic.preedit.Length);
669 return ic.preedit[pos];
673 static internal Dictionary<MSymbol,Predefined> predefined_markers;
677 predefined_markers = new Dictionary<MSymbol, Predefined> ();
678 MSymbol[] symlist = new MSymbol[] {"@<", "@>", "@-", "@+", "@[", "@]" };
679 foreach (MSymbol s in symlist)
680 predefined_markers[s] = new Predefined (s);
683 public static Marker Get (MSymbol name)
685 string str = name.Name;
689 if (predefined_markers.TryGetValue (name, out pred))
692 throw new Exception ("Invalid marker name: " + name);
693 if (Char.IsDigit (str[1]))
694 return new PredefinedAbsolute (name);
695 if (str.Length == 2 || name == Mat_minus_zero
696 || ! (str[1] == '-' || str[1] == '+'))
697 throw new Exception ("Invalid marker name: " + name);
698 return new PredefinedSurround (name);
700 return new Named (name);
704 internal class Candidates
711 public Block (int index, Xex.Term term)
715 Data = (MText) term.Strval;
718 MPlist plist = new MPlist ();
720 foreach (Xex.Term t in term.Listval)
721 p = p.Add (MSymbol.mtext, (MText) t.Strval);
726 public Block (int index, MPlist plist)
731 else if (plist.IsPlist)
734 throw new Exception ("Invalid candidate: " + plist);
739 get { return (Data is MText
740 ? ((MText) Data).Length
741 : ((MPlist) Data).Count); }
744 public object this[int i]
747 if (Data is MText) return ((MText) Data)[i];
748 return ((MPlist) Data)[i];
753 private Block[] blocks;
755 private int index = 0;
756 public object[] group;
758 private bool IsFixed { get { return group != null; } }
761 Block last = blocks[blocks.Length - 1];
762 return last.Index + last.Count; }
766 get { return (IsFixed ? index % group.Length
767 : index - blocks[row].Index); }
770 public object Group {
771 get { return (IsFixed ? group : blocks[row].Data); }
774 public int GroupLength
779 int nitems = group.Length;
780 int start = index - (index % nitems);
782 return (start + nitems <= total ? nitems : total - start);
784 return blocks[row].Count;
788 public object Current {
790 return (IsFixed ? group[index % group.Length]
791 : blocks[row][index - blocks[row].Index]);
795 public Candidates (MPlist list, int column)
797 int nblocks = list.Count;
799 blocks = new Block[nblocks];
800 for (int i = 0, start = 0; i < nblocks; i++, list = list.next)
801 start += (blocks[i] = new Block (index, list)).Count;
803 group = new object[column];
806 public Candidates (Xex.Term[] candidates, int column)
808 int nblocks = candidates.Length;
810 blocks = new Block[nblocks];
811 for (int i = 0, start = 0; i < nblocks; i++)
812 start += (blocks[i] = new Block (index, candidates[i])).Count;
814 group = new object[column];
817 public static void Detach (Context ic)
819 ic.preedit.PopProp (0, ic.preedit.Length, Mcandidates);
820 ic.candidates = null;
821 ic.changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
825 // Fill the array "group" by candidates stating from START.
826 // START must be a multiple of "column". Return the number of
827 // valid candidates in "group".
829 private int fill_group (int start)
831 int nitems = group.Length;
836 while (start < b.Index)
839 while (start >= b.Index + b.Count)
845 for (int i = 0; i < nitems; i++, start++)
850 if (r == blocks.Length)
861 // Update "row" to what contains the first candidate of
862 // the previous candidate-group, update "current_index", and
863 // update "group" if necessary. Return the previous
864 // candidate-group. Set NITEMS to the number of valid
865 // candidates contained in that group.
867 public int PrevGroup ()
874 nitems = group.Length;
875 if ((index -= col + nitems) < 0)
876 index = (Total / nitems) * nitems;
877 nitems = fill_group (index);
881 row = row > 0 ? row-- : blocks.Length - 1;
882 nitems = blocks[row].Count;
883 index = blocks[row].Index;
885 index += col < nitems ? col : nitems - 1;
889 public int NextGroup ()
896 nitems = group.Length;
897 if ((index += nitems - col) >= Total)
899 nitems = fill_group (index);
903 row = row < blocks.Length - 1 ? row + 1 : 0;
904 nitems = blocks[row].Count;
905 index = blocks[row].Count;
907 index += col < nitems ? col : nitems - 1;
917 int nitems = PrevGroup ();
918 index += col < nitems - 1 ? col : nitems - 1;
927 int nitems = GroupLength;
929 if (col == nitems - 1)
931 nitems = NextGroup ();
945 index += GroupLength - (Column + 1);
948 public void Select (int col)
950 int maxcol = GroupLength - 1;
953 index = index - Column + col;
956 public override string ToString ()
958 return (String.Format ("<candidates row={0} col={1}>", row, index)
964 internal class Selector : Xex.TermValue
966 static new Dictionary<MSymbol, Selector> selectors;
970 selectors = new Dictionary<MSymbol, Selector> ();
971 MSymbol[] symlist = new MSymbol[] { "@<", "@=", "@>", "@-", "@+",
973 foreach (MSymbol s in symlist)
974 selectors[s] = new Selector (s);
975 selectors["@first"] = new Selector ('<');
976 selectors["@current"] = new Selector ('=');
977 selectors["@last"] = new Selector ('>');
978 selectors["@previous"] = new Selector ('-');
979 selectors["@next"] = new Selector ('+');
980 selectors["@previous-candidate-change"] = new Selector ('[');
981 selectors["@next-candidate-change"] = new Selector (']');
986 private Selector (MSymbol sym) { tag = sym.Name[1]; }
988 private Selector (char tag) { this.tag = tag; }
990 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
992 return Get ((MSymbol) node.InnerText);
995 public static Xex.TermValue Get (MSymbol name)
998 if (! selectors.TryGetValue (name, out selector))
999 throw new Exception ("Invalid selector name: " + name);
1003 public void Select (Candidates candidates)
1007 case '<': candidates.First (); break;
1008 case '>': candidates.Last (); break;
1009 case '-': candidates.Prev (); break;
1010 case '+': candidates.Next (); break;
1011 case '[': candidates.PrevGroup (); break;
1012 case ']': candidates.NextGroup (); break;
1020 public MSymbol name;
1021 public List<Entry> entries = new List<Entry> ();
1023 public Map (MSymbol name) { this.name = name; }
1027 public KeySeq keyseq;
1028 public Xex.Term[] actions;
1030 public Entry (Xex.Domain domain, KeySeq keyseq, Xex.Term[] actions)
1032 this.keyseq = keyseq;
1033 this.actions = actions;
1037 public override string ToString ()
1039 string str = "(" + name;
1040 foreach (Entry e in entries)
1041 str += " " + e.keyseq.ToString ();
1046 internal class Keymap
1048 public Dictionary<Key, Keymap> submaps;
1049 public Xex.Term[] map_actions, branch_actions;
1051 public Keymap () { }
1053 public void Add (KeySeq keys, int index,
1054 Xex.Term[] map_actions, Xex.Term[] branch_actions)
1056 if (index == keys.keyseq.Count)
1058 this.map_actions = map_actions;
1059 this.branch_actions = branch_actions;
1063 Key key = keys.keyseq[index];
1066 if (submaps == null)
1067 submaps = new Dictionary<Key, Keymap> ();
1069 submaps.TryGetValue (key, out sub);
1071 submaps[key] = sub = new Keymap ();
1072 sub.Add (keys, index + 1, map_actions, branch_actions);
1076 public void AddMap (Map map, Xex.Term[] branch_actions)
1078 foreach (Map.Entry entry in map.entries)
1079 Add (entry.keyseq, 0, entry.actions, branch_actions);
1082 public Keymap Lookup (KeySeq keys, ref int index)
1086 if (index < keys.keyseq.Count
1088 && submaps.TryGetValue (keys.keyseq[index], out sub))
1091 return sub.Lookup (keys, ref index);
1096 private void describe (MText mt, KeySeq keyseq)
1098 if (map_actions != null || branch_actions != null)
1102 mt.Cat ('(').Cat (keyseq.ToString ());
1103 if (map_actions != null)
1104 foreach (Xex.Term term in map_actions)
1105 mt.Cat (' ').Cat (term.ToString ());
1106 if (branch_actions != null)
1107 foreach (Xex.Term term in branch_actions)
1108 mt.Cat (' ').Cat (term.ToString ());
1111 if (submaps != null)
1112 foreach (KeyValuePair<Key, Keymap> kv in submaps)
1114 keyseq.keyseq.Add (kv.Key);
1115 kv.Value.describe (mt, keyseq);
1116 keyseq.keyseq.RemoveAt (keyseq.keyseq.Count - 1);
1120 public override string ToString ()
1123 KeySeq keyseq = new KeySeq ();
1125 describe (mt, keyseq);
1130 internal class State
1132 public Xex.Symbol name;
1134 public Xex.Term[] enter_actions, fallback_actions;
1135 public Keymap keymap = new Keymap ();
1137 public State (Xex.Symbol name, MText title)
1143 public State (MInputMethod im, XmlNode node)
1145 this.name = node.Attributes[Qsname].Value;
1146 XmlAttribute attr = node.Attributes[Qtitle];
1148 title = (MText) attr.Value;
1151 keymap = new Keymap ();
1152 for (node = node.FirstChild; node != null; node = node.NextSibling)
1154 if (node.Name == Qstate_hook)
1155 enter_actions = Xex.ParseTerms (im.domain, node.FirstChild);
1156 else if (node.Name == Qcatch_all_branch)
1157 fallback_actions = Xex.ParseTerms (im.domain, node.FirstChild);
1158 else if (node.Name == Qbranch)
1160 MSymbol mapname = node.Attributes[Qmname].Value;
1162 if (im.maps.TryGetValue (mapname, out map))
1163 keymap.AddMap (map, Xex.ParseTerms (im.domain,
1166 throw new Exception ("Unknown map: " + mapname);
1171 public State (MInputMethod im, MPlist plist)
1173 if (! plist.IsSymbol)
1174 throw new Exception ("Invalid state: " + plist);
1175 this.name = plist.Symbol.Name;
1184 keymap = new Keymap ();
1185 for (; ! plist.IsEmpty; plist = plist.next)
1187 if (! plist.IsPlist)
1188 throw new Exception ("Invalid branch: " + plist);
1189 MPlist p = plist.Plist;
1191 throw new Exception ("Invalid branch: " + p);
1192 MSymbol mapname = p.Symbol;
1193 if (mapname == MSymbol.t)
1194 enter_actions = im.parse_actions (p.next, false);
1195 else if (mapname == MSymbol.nil)
1196 fallback_actions = im.parse_actions (p.next, false);
1200 if (im.maps.TryGetValue (mapname, out map))
1201 keymap.AddMap (map, im.parse_actions (p.next, false));
1203 throw new Exception ("Unknown map: " + mapname);
1208 public override string ToString ()
1210 MText mt = "(" + name;
1213 mt.Cat (" \"" + title + "\"");
1214 mt.Cat (keymap.ToString ());
1215 return (string) mt + ")";
1220 internal Xex.Domain domain;
1222 protected LoadStatus load_status = LoadStatus.None;
1223 protected MDatabase.Tag tag;
1224 private MDatabase mdb;
1226 private MText description;
1227 internal MText title;
1228 internal Command[] commands;
1229 internal Xex.Symbol[] var_names;
1230 internal Dictionary<MSymbol, Plugin> plugins;
1231 internal Dictionary<MSymbol, Map> maps;
1232 internal Dictionary<Xex.Symbol, State> states;
1233 internal State initial_state;
1235 static MInputMethod ()
1237 im_domain.DefTerm ("keyseq", KeySeq.parser);
1238 im_domain.DefTerm ("marker", Marker.parser);
1239 im_domain.DefTerm ("selector", Selector.parser);
1241 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
1242 im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, -1);
1243 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
1244 im_domain.DefSubr (Fselect, "select", false, 1, 1);
1245 im_domain.DefSubr (Fshow, "show", false, 0, 0);
1246 im_domain.DefSubr (Fhide, "hide", false, 0, 0);
1247 im_domain.DefSubr (Fmove, "move", false, 1, 1);
1248 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
1249 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
1250 im_domain.DefSubr (Fpop, "pop", false, 0, 0);
1251 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
1252 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
1253 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
1254 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
1255 im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
1256 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
1257 im_domain.DefSubr (Fkey_count, "key-count", false, 1, 1);
1258 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag",
1261 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, "*", "*", "*");
1262 List<MDatabase> list = MDatabase.List (tag);
1263 M17n.DebugPrint ("Found {0} input methods\n", list.Count);
1264 foreach (MDatabase mdb in list)
1265 im_table[mdb.tag] = new MInputMethod (mdb.tag);
1269 private MInputMethod (MDatabase.Tag tag)
1272 domain = new Xex.Domain (tag[1].Name, im_domain, null);
1275 // Instance Properties
1276 public MSymbol Language { get { return tag[1]; } }
1277 public MSymbol Name { get { return tag[2]; } }
1278 public MSymbol SubName { get { return tag[3]; } }
1280 public bool Info (out MText description,
1282 out Xex.Variable[] variables,
1283 out Command[] commands)
1285 if ((load_status & LoadStatus.Header) != LoadStatus.Header
1286 && ! load_header ())
1294 description = this.description;
1296 if (var_names == null)
1300 variables = new Xex.Variable[var_names.Length];
1302 foreach (Xex.Symbol name in var_names)
1303 variables[i++] = domain.GetVar (name, false);
1305 commands = this.commands;
1309 public static MInputMethod Find (MSymbol language, MSymbol name)
1311 return Find (language, name, MSymbol.nil);
1314 public static MInputMethod Find (MSymbol language, MSymbol name,
1317 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, language,
1321 return (im_table.TryGetValue (tag, out im) ? im : null);
1324 private bool Open ()
1326 return ((load_status == LoadStatus.Full) || load_body ());
1329 public static MInputMethod[] List ()
1331 MInputMethod[] array = new MInputMethod[im_table.Count];
1334 foreach (KeyValuePair<MDatabase.Tag, MInputMethod> kv in im_table)
1335 array[i++] = kv.Value;
1339 private bool load_header ()
1341 mdb = MDatabase.Find (tag);
1344 mdb.name_table = Xex.Symbol.Table;
1346 MSymbol format = mdb.Format;
1348 if (format == MSymbol.plist)
1349 load ((MPlist) mdb.Load (Mmap), false);
1352 XmlDocument doc = (XmlDocument) mdb.Load (Mmap_list);
1353 load (doc.DocumentElement, false);
1355 } catch (Exception e) {
1356 Console.WriteLine ("{0}\n", e);
1357 load_status = LoadStatus.Error;
1360 load_status |= LoadStatus.Header;
1364 private bool load_body ()
1366 mdb = MDatabase.Find (tag);
1369 mdb.name_table = Xex.Symbol.Table;
1371 object obj = mdb.Load ();
1373 load ((MPlist) obj, true);
1375 load ((XmlDocument) obj, true);
1376 } catch (Exception e) {
1377 Console.WriteLine (e);
1378 load_status = LoadStatus.Error;
1381 load_status = LoadStatus.Full;
1385 private void add_default_state ()
1387 Xex.Symbol Qinit = "init";
1388 State state = new State (Qinit, title);
1389 foreach (KeyValuePair<MSymbol, Map>kv in maps)
1390 state.keymap.AddMap (kv.Value, null);
1391 states[Qinit] = initial_state = state;
1394 private void load (MPlist plist, bool full)
1396 maps = new Dictionary<MSymbol, Map> ();
1397 states = new Dictionary<Xex.Symbol, State> ();
1399 for (; ! plist.IsEmpty; plist = plist.next)
1402 MPlist pl = plist.Plist;
1405 MSymbol sym = pl.Symbol;
1408 if (sym == Mdescription)
1409 description = parse_description (pl);
1410 else if (sym == Mtitle)
1415 else if (sym == Mvariable)
1416 parse_variables (pl);
1417 else if (sym == Mcommand)
1418 parse_commands (pl);
1423 else if (sym == Minclude)
1425 else if (sym == Mmacro)
1427 else if (sym == Mmap)
1429 else if (sym == Mstate)
1434 if (description == null)
1435 description = (MText) "No description";
1437 title = new MText (tag[2].Name);
1438 if (commands == null)
1439 commands = new Command[0];
1442 if (states.Count == 0)
1443 add_default_state ();
1446 private void load (XmlNode node, bool full)
1448 bool skip_header = load_status == LoadStatus.Header;
1450 maps = new Dictionary<MSymbol, Map> ();
1451 states = new Dictionary<Xex.Symbol, State> ();
1453 if (node.NodeType == XmlNodeType.Document)
1454 node = node.FirstChild;
1455 while (node.NodeType != XmlNodeType.Element)
1456 node = node.NextSibling;
1457 for (node = node.FirstChild; node != null; node = node.NextSibling)
1459 if (node.NodeType != XmlNodeType.Element)
1463 if (node.Name == "description")
1464 description = parse_description (node);
1465 else if (node.Name == "title")
1466 title = parse_title (node);
1467 else if (node.Name == "variable-list")
1468 parse_variables (node);
1469 else if (node.Name == "command-list")
1470 parse_commands (node);
1474 if (node.Name == "module-list")
1475 parse_plugins (node);
1476 else if (node.Name == "macro-list")
1477 parse_macros (node);
1478 else if (node.Name == "map-list")
1480 else if (node.Name == "state-list")
1481 parse_states (node);
1484 if (description == null)
1485 description = (MText) "No description";
1487 title = new MText (tag[2].Name);
1488 if (commands == null)
1489 commands = new Command[0];
1492 if (states.Count == 0)
1493 add_default_state ();
1496 private static MText parse_description (MPlist plist)
1502 plist = plist.Plist;
1503 if (plist.IsSymbol && plist.Symbol == (MSymbol) "_"
1504 && plist.next.IsMText)
1505 return plist.next.Text;
1510 private static MText parse_description (XmlNode node)
1512 if (node.HasChildNodes)
1513 node = node.FirstChild;
1514 return node.InnerText;
1517 private static MText parse_title (XmlNode node)
1519 return node.InnerText;
1522 private void new_variable (Xex.Symbol name, string desc, int val,
1523 MPlist pl, Xex.Variable vari)
1531 int nrange = pl.Count;
1532 range = new int[nrange * 2];
1533 for (int i = 0; i < nrange; i++)
1537 MPlist p = pl.Plist;
1539 if (! p.IsInteger || ! p.next.IsInteger)
1540 throw new Exception ("Invalid range: " + p);
1541 range[i * 2] = p.Integer;
1542 range[i * 2 + 1] = p.next.Integer;
1544 else if (pl.IsInteger)
1545 range[i * 2] = range[i * 2 + 1] = pl.Integer;
1547 throw new Exception ("Invalid range: " + pl);
1551 domain.Defvar (new Xex.Variable.Int (domain, name, desc, val, range));
1554 Xex.Term term = new Xex.Term (val);
1556 vari.DefaultValue = term;
1561 private void new_variable (Xex.Symbol name, string desc, MText val,
1562 MPlist pl, Xex.Variable vari)
1570 range = new string[pl.Count * 2];
1571 for (int i = 0; i < range.Length; i++)
1574 range[i] = (string) pl.Text;
1576 throw new Exception ("Invalid range: " + pl);
1580 domain.Defvar (new Xex.Variable.Str (domain, name, desc, (string) val, range));
1583 Xex.Term term = new Xex.Term ((string) val);
1585 vari.DefaultValue = term;
1590 private void new_variable (Xex.Symbol name, string desc, MSymbol val,
1591 MPlist pl, Xex.Variable vari)
1594 Xex.Symbol sym = val.Name;
1600 range = new Xex.Symbol[pl.Count * 2];
1601 for (int i = 0; i < range.Length; i++)
1604 range[i] = pl.Symbol.Name;
1606 throw new Exception ("Invalid range: " + pl);
1610 domain.Defvar (new Xex.Variable.Sym (domain, name, desc, sym, range));
1613 Xex.Term term = new Xex.Term (sym);
1615 vari.DefaultValue = term;
1620 private Xex.Variable get_global_var (Xex.Symbol name)
1622 if (im_global == null || this != im_global)
1624 tag = new MDatabase.Tag (Minput_method, MSymbol.t, MSymbol.nil,
1626 im_global = im_table[tag];
1627 if (! im_global.Open ())
1628 throw new Exception ("Failed to load global");
1630 return im_global.domain.GetVar (name, false);
1633 private void parse_variables (MPlist plist)
1635 var_names = new Xex.Symbol[plist.Count];
1637 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1639 if (! plist.IsPlist || ! plist.Plist.IsSymbol)
1640 throw new Exception ("Invalid variable: " + plist);
1642 MPlist p = plist.Plist;
1643 Xex.Symbol name = (Xex.Symbol) p.Symbol.Name;
1644 var_names[i] = name;
1646 string desc = (string) parse_description (p);
1647 Xex.Variable vari = get_global_var (name);
1649 domain.Defvar (vari);
1655 new_variable (name, desc, p.Integer, p.next, vari);
1657 new_variable (name, desc, p.Text, p.next, vari);
1658 else if (p.IsSymbol)
1659 new_variable (name, desc, p.Symbol, p.next, vari);
1661 throw new Exception ("Invalid variable type: " + p.val);
1666 private void parse_variables (XmlNode node)
1668 XmlNodeList node_list = node.ChildNodes;
1670 var_names = new Xex.Symbol[node_list.Count];
1671 for (int i = 0; i < node_list.Count; i++)
1673 Xex.Symbol name = node_list[i].Attributes[0].Value;
1674 Xex.Variable vari = get_global_var (name);
1676 domain.Defvar (vari);
1677 domain.Defvar (node_list[i]);
1678 var_names[i] = name;
1682 private void parse_commands (MPlist plist)
1684 commands = new Command[plist.Count];
1686 for (int i = 0; ! plist.IsEmpty; plist = plist.next)
1687 if (plist.IsPlist && plist.Plist.IsSymbol)
1688 commands[i++] = new Command (plist.Plist);
1691 private void parse_commands (XmlNode node)
1693 XmlNodeList node_list = node.ChildNodes;
1695 commands = new Command[node_list.Count];
1696 for (int i = 0; i < node_list.Count; i++)
1698 if (node_list[i].NodeType == XmlNodeType.Element)
1699 commands[i] = new Command (node_list[i]);
1703 private void parse_plugins (MPlist plist)
1705 plugins = new Dictionary<MSymbol, Plugin> ();
1707 for (; ! plist.IsEmpty; plist = plist.Next)
1709 MPlist p = plist.Plist;
1710 MSymbol sym = p.Symbol;
1711 Plugin plugin = new Plugin (sym.Name);
1713 for (p = p.next; ! p.IsEmpty; p = p.next)
1715 Xex.Function func = new PluginMethod (plugin, p.Symbol.Name);
1716 domain.Defun (func);
1721 private void parse_plugins (XmlNode node)
1723 plugins = new Dictionary<MSymbol, Plugin> ();
1725 foreach (XmlNode n in node.ChildNodes)
1727 Plugin plugin = new Plugin (n.Attributes[0].Value);
1728 foreach (XmlNode nn in n.ChildNodes)
1730 Xex.Function func = new PluginMethod (plugin,
1731 nn.Attributes[0].Value);
1732 domain.Defun (func);
1737 private void parse_macros (XmlNode node)
1739 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1740 if (nn.NodeType == XmlNodeType.Element)
1741 domain.Defun (nn, true);
1742 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1743 if (nn.NodeType == XmlNodeType.Element)
1744 domain.Defun (nn, false);
1747 private void parse_maps (XmlNode node)
1749 for (node = node.FirstChild; node != null; node = node.NextSibling)
1750 if (node.Name == Qmap)
1752 MSymbol name = node.Attributes[0].Value;
1753 Map map = new Map (name);
1755 for (XmlNode nd = node.FirstChild; nd != null; nd = nd.NextSibling)
1756 if (nd.Name == Qrule)
1758 XmlNode n = nd.FirstChild;
1759 if (n.Name != Qkeyseq)
1761 KeySeq keyseq = (KeySeq) KeySeq.parser (domain, n);
1762 Xex.Term[] actions = Xex.ParseTerms (domain, n.NextSibling);
1763 map.entries.Add (new Map.Entry (domain, keyseq, actions));
1768 private void parse_states (MPlist plist)
1770 for (; ! plist.IsEmpty; plist = plist.next)
1773 State state = new State (this, plist.Plist);
1774 states[state.name] = state;
1775 if (initial_state == null)
1776 initial_state = state;
1780 private void parse_states (XmlNode node)
1782 for (node = node.FirstChild; node != null; node = node.NextSibling)
1783 if (node.Name == Qstate)
1785 State state = new State (this, node);
1786 states[state.name] = state;
1787 if (initial_state == null)
1788 initial_state = state;
1792 private void parse_include (MPlist plist)
1794 if (! plist.IsPlist)
1796 MPlist p = plist.Plist;
1797 MSymbol language, name, subname;
1798 language = p.Symbol;
1801 name = subname = MSymbol.nil;
1807 subname = MSymbol.nil;
1812 MInputMethod im = MInputMethod.Find (language, name, subname);
1818 if (! plist.IsSymbol)
1820 MSymbol target_type = plist.Symbol;
1822 MSymbol target_name = MSymbol.nil;
1824 target_name = plist.Symbol;
1825 if (target_type == Mmacro)
1827 if (target_name == MSymbol.nil)
1828 im.domain.CopyFunc (domain);
1830 im.domain.CopyFunc (domain, (Xex.Symbol) target_name.Name);
1832 else if (target_type == Mmap)
1834 if (target_name == MSymbol.nil)
1836 foreach (KeyValuePair<MSymbol, Map> kv in im.maps)
1837 maps[kv.Key] = kv.Value;
1842 if (im.maps.TryGetValue (target_name, out map))
1843 maps[target_name] = map;
1846 else if (target_type == Mstate)
1848 if (target_name == MSymbol.nil)
1850 foreach (KeyValuePair<Xex.Symbol, State> kv in im.states)
1851 states[kv.Key] = kv.Value;
1855 Xex.Symbol state_name = target_name.Name;
1857 if (im.states.TryGetValue (state_name, out state))
1858 states[state_name] = state;
1863 private Xex.Term parse_cond (MPlist plist)
1865 Xex.Term[] args = new Xex.Term[plist.Count];
1867 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1869 if (! plist.IsPlist)
1870 throw new Exception ("Invalid cond args: " + plist);
1871 MPlist p = plist.Plist;
1872 List<Xex.Term> arg = new List<Xex.Term> ();
1873 arg.Add (parse_action (p, true));
1874 for (p = p.next; ! p.IsEmpty; p = p.next)
1875 arg.Add (parse_action (p, false));
1876 args[i] = new Xex.Term (arg);
1878 return new Xex.Term (domain, Qcond, args);
1881 private Xex.Term parse_insert (MPlist plist)
1886 arg = new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1887 else if (plist.IsMText)
1888 arg = new Xex.Term ((string) plist.Text);
1889 else if (plist.IsInteger)
1890 arg = new Xex.Term (plist.Integer);
1891 else if (plist.IsPlist)
1893 MPlist pl = plist.Plist;
1895 args = new Xex.Term[pl.Count];
1897 for (i = 0; ! pl.IsEmpty; i++, pl = pl.next)
1900 args[i] = new Xex.Term ((string) pl.Text);
1901 else if (pl.IsPlist)
1903 List<Xex.Term> list = new List<Xex.Term> ();
1904 for (MPlist p = pl.Plist; ! p.IsEmpty; p = p.next)
1907 list.Add (new Xex.Term ((string) p.Text));
1909 throw new Exception ("Invalid candidates: " + p);
1913 throw new Exception ("Invalid candidates: " + pl);
1915 return new Xex.Term (domain, Qinsert_candidates, args);
1918 throw new Exception ("Invalid arg to insert: " + plist);
1919 args = new Xex.Term[1];
1921 return new Xex.Term (domain, Qinsert, args);
1924 private Xex.Term parse_select (MPlist plist)
1926 Xex.Term[] args = new Xex.Term[1];
1927 if (plist.IsInteger)
1928 args[0] = new Xex.Term (plist.Integer);
1929 else if (! plist.IsSymbol)
1930 throw new Exception ("Invalid arg to select: " + plist);
1931 else if (plist.Symbol.Name[0] == '@')
1932 args[0] = new Xex.Term (Selector.Get (plist.Symbol));
1934 args[0] = new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1935 return new Xex.Term (domain, Qselect, args);
1938 private Xex.Term parse_funcall_with_marker (MPlist plist, Xex.Symbol func)
1940 Xex.Term[] args = new Xex.Term[1];
1941 if (plist.IsInteger && func != Qmark)
1942 args[0] = new Xex.Term (plist.Integer);
1943 else if (plist.IsSymbol)
1944 args[0] = new Xex.Term (Marker.Get (plist.Symbol));
1946 throw new Exception ("Invalid arg to " + func + ": " + plist);
1947 return new Xex.Term (domain, func, args);
1950 private Xex.Term parse_char_at (MSymbol name)
1952 Xex.Term[] args = new Xex.Term[1];
1953 args[0] = new Xex.Term (Marker.Get (name));
1954 return new Xex.Term (domain, Qchar_at, args);
1957 private Xex.Term parse_shift (MPlist plist)
1959 Xex.Term[] args = new Xex.Term[1];
1960 if (! plist.IsSymbol)
1961 throw new Exception ("Invalid arg to shift: " + plist);
1962 args[0] = new Xex.Term ((Xex.Symbol) plist.Symbol.Name);
1963 return new Xex.Term (domain, Qshift, args);
1966 private Xex.Term parse_action (MPlist plist, bool as_funarg)
1970 MPlist p = plist.Plist;
1972 if (p.IsMText || p.IsPlist)
1973 return parse_insert (plist);
1975 throw new Exception ("Invalid action: " + p);
1976 MSymbol sym = p.Symbol;
1977 Xex.Symbol name = sym.Name;
1980 return parse_cond (p);
1981 if (name == Qinsert)
1982 return parse_insert (p);
1983 if (name == Qselect)
1984 return parse_select (p);
1985 if (name == Qdelete || name == Qmove || name == Qmark)
1986 return parse_funcall_with_marker (p, name);
1988 return parse_shift (p);
1989 if (((string) name)[0] == '@')
1990 return parse_char_at (sym);
1991 if (name == Qset || name == Qadd || name == Qsub
1992 || name == Qmul || name == Qdiv)
1995 throw new Exception ("Invalid action: " + p);
1996 Xex.Symbol varname = p.Symbol.Name;
1997 Xex.Term[] args = new Xex.Term[1];
1998 args[0] = parse_action (p.next, true);
1999 return new Xex.Term (domain, name, varname, args);
2006 return new Xex.Term (domain, name, null);
2008 return new Xex.Term (domain, name, parse_actions (p, true));
2011 else if (plist.IsSymbol)
2013 if (plist.Symbol.Name[0] == '@')
2014 return parse_char_at (plist.Symbol);
2015 return new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
2017 else if (plist.IsMText)
2018 return (as_funarg ? new Xex.Term ((string) plist.Text)
2019 : parse_insert (plist));
2020 else if (plist.IsInteger)
2021 return (as_funarg ? new Xex.Term (plist.Integer)
2022 : parse_insert (plist));
2024 throw new Exception ("Invalid action: " + plist);
2027 private Xex.Term[] parse_actions (MPlist plist, bool as_funarg)
2029 Xex.Term[] terms = new Xex.Term[plist.Count];
2031 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
2032 terms[i] = parse_action (plist, as_funarg);
2036 private void parse_macros (MPlist plist)
2038 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
2041 MPlist p = pl.Plist;
2045 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null, null, true);
2047 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
2050 MPlist p = pl.Plist;
2054 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null,
2055 parse_actions (p.next, false), false);
2059 private void parse_maps (MPlist plist)
2061 for (; ! plist.IsEmpty; plist = plist.next)
2064 MPlist pl = plist.Plist;
2068 Map map = new Map (pl.Symbol);
2069 maps[pl.Symbol] = map;
2070 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
2074 MPlist p = pl.Plist;
2077 keys = new KeySeq (p.Text);
2079 keys = new KeySeq (p.Plist);
2084 = p.IsEmpty ? null : parse_actions (p, false);
2085 map.entries.Add (new Map.Entry (domain, keys, actions));
2090 private static Xex.Term Finsert (Xex.Domain domain, Xex.Variable vari,
2094 ((Context) domain.context).insert (args[0].Intval);
2096 ((Context) domain.context).insert (args[0].Strval);
2100 private static Xex.Term Finsert_candidates (Xex.Domain domain,
2104 Context ic = (Context) domain.context;
2105 Xex.Variable v = ic.domain.GetVar (Qcandidates_group_size, false);
2106 int column = (v == null ? 0 : v.Value.Intval);
2108 ic.insert_candidates (new Candidates (args, column));
2112 private static Xex.Term Fchar_at (Xex.Domain domain, Xex.Variable vari,
2115 Context ic = (Context) domain.context;
2116 Marker m = (Marker) args[0].Objval;
2118 return new Xex.Term (m.CharAt (ic));
2121 private static Xex.Term Fdelete (Xex.Domain domain, Xex.Variable vari,
2124 Context ic = (Context) domain.context;
2128 pos = args[0].Intval;
2131 Marker m = (Marker) args[0].Objval;
2132 pos = m.Position (ic);
2134 return new Xex.Term (ic.delete (pos));
2137 private static Xex.Term Fselect (Xex.Domain domain, Xex.Variable vari,
2140 Candidates can = ((Context) domain.context).candidates;
2145 can.Select (args[0].Intval);
2147 ((Selector) args[0].Objval).Select (can);
2152 private static Xex.Term Fshow (Xex.Domain domain, Xex.Variable vari,
2155 ((Context) domain.context).show ();
2159 private static Xex.Term Fhide (Xex.Domain domain, Xex.Variable vari,
2162 ((Context) domain.context).hide ();
2166 private static Xex.Term Fmove (Xex.Domain domain, Xex.Variable vari,
2169 Context ic = (Context) domain.context;
2170 int pos = (args[0].IsInt ? args[0].Intval
2171 : ((Marker) args[0].Objval).Position (ic));
2176 private static Xex.Term Fmark (Xex.Domain domain, Xex.Variable vari,
2179 Marker m = (Marker) args[0].Objval;
2180 m.Mark ((Context) domain.context);
2184 private static Xex.Term Fpushback (Xex.Domain domain, Xex.Variable vari,
2187 Context ic = (Context) domain.context;
2190 ic.pushback (args[0].Intval);
2191 else if (args[0].IsStr)
2192 ic.pushback (new KeySeq (args[0].Strval));
2194 ic.pushback ((KeySeq) args[0].Objval);
2198 private static Xex.Term Fpop (Xex.Domain domain, Xex.Variable vari,
2201 ((Context) domain.context).pop ();
2205 private static Xex.Term Fundo (Xex.Domain domain, Xex.Variable vari,
2208 int n = args.Length == 0 ? -2 : args[0].Intval;
2209 ((Context) domain.context).undo (n);
2213 private static Xex.Term Fcommit (Xex.Domain domain, Xex.Variable vari,
2216 ((Context) domain.context).commit ();
2220 private static Xex.Term Funhandle (Xex.Domain domain, Xex.Variable vari,
2223 ((Context) domain.context).commit ();
2224 args = new Xex.Term[2];
2225 args[0] = args[1] = Tcatch_tag;
2226 return Xex.Fthrow (domain, vari, args);
2229 private static Xex.Term Fshift (Xex.Domain domain, Xex.Variable vari,
2232 Context ic = (Context) domain.context;
2234 if (ic.im.states.TryGetValue (args[0].Symval, out state))
2235 ((Context) domain.context).shift (state);
2237 throw new Exception ("Unknown state: " + args[0].Symval);
2241 private static Xex.Term Fshiftback (Xex.Domain domain, Xex.Variable vari,
2244 ((Context) domain.context).shift (null);
2248 private static Xex.Term Fkey_count (Xex.Domain domain, Xex.Variable vari,
2251 return new Xex.Term (((Context) domain.context).key_head);
2254 private static Xex.Term Fsurrounding_flag (Xex.Domain domain,
2258 return new Xex.Term (GetSurroundingText == null ? 0 : 1);
2261 public override string ToString ()
2264 string str = (String.Format ("({0} (title \"{1}\")", tag, title));
2265 if (commands != null)
2267 str += " (commands";
2268 foreach (Command cmd in commands)
2272 if (var_names != null)
2274 str += " (variables";
2275 foreach (Xex.Symbol var in var_names)
2279 if (plugins != null)
2282 foreach (KeyValuePair<MSymbol, Plugin> kv in plugins)
2283 str += " " + kv.Value;
2287 foreach (KeyValuePair<MSymbol, Map> kv in maps)
2288 str += " " + kv.Value;
2290 foreach (KeyValuePair<Xex.Symbol, State> kv in states)
2292 str += " (" + kv.Key + " " + kv.Value.keymap + ")";
2297 public class Context
2299 internal MInputMethod im;
2300 internal Xex.Domain domain;
2301 private bool active;
2303 private MText status;
2304 private MText produced = new MText ();
2305 internal MText preedit = new MText ();
2306 internal int cursor_pos;
2307 internal MPlist marker_positions = new MPlist ();
2309 internal Candidates candidates;
2310 private int candidate_from, candidate_to;
2311 private bool candidate_show;
2312 public bool CandidateShow { get { return candidate_show; } }
2314 private State state, prev_state;
2315 private MText state_preedit = new MText ();
2316 private int state_key_head;
2317 private object state_var_values, state_initial_var_values;
2318 private int state_pos;
2320 private Keymap keymap;
2321 // Sequence of input keys.
2322 internal KeySeq keys = new KeySeq ();
2323 // Index into KEYS specifying the next key to handle.
2324 internal int key_head;
2326 internal MText preceding_text = new MText ();
2327 internal MText following_text = new MText ();
2329 // Set to false before calling the method 'handle_key', and set
2330 // to true when some key is unhandled.
2331 private bool key_unhandled;
2333 // The unhandled key. It has the meaning only when
2334 // 'key_unhandled' is true.
2335 private Key unhandled_key;
2337 internal ChangedStatus changed;
2339 private void set_cursor (string prefix, int pos)
2343 candidates = (Candidates) preedit.GetProp (cursor_pos - 1,
2349 internal void reset ()
2351 status = im.initial_state.title;
2355 set_cursor ("reset", 0);
2356 marker_positions.Clear ();
2358 candidate_show = false;
2360 state = prev_state = null;
2361 state_preedit.Del ();
2362 state_var_values = state_initial_var_values;
2364 shift (im.initial_state);
2366 preceding_text.Del ();
2367 following_text.Del ();
2369 changed = ChangedStatus.None;
2372 static Xex.Term[] catch_args = new Xex.Term[2];
2374 private bool take_actions (Xex.Term[] actions)
2376 catch_args[0] = Tcatch_tag;
2377 catch_args[1]= new Xex.Term (domain, Qprogn, actions);
2378 Xex.Term term = new Xex.Term (domain, Qcatch, catch_args);
2379 term = term.Eval (domain);
2380 return (! term.IsSymbol || term.Symval != Tcatch_tag.Symval);
2383 static MPlist callback_arg = new MPlist ();
2385 private bool get_surrounding_text (int len)
2387 if (len < 0 ? -len <= preceding_text.Length
2388 : len <= following_text.Length)
2390 if (GetSurroundingText == null)
2392 callback_arg.Set (MSymbol.integer, len);
2393 if (! GetSurroundingText (this, callback_arg)
2394 || ! callback_arg.IsMText)
2398 preceding_text = callback_arg.Text;
2399 return (-len <= preceding_text.Length);
2401 following_text = callback_arg.Text;
2402 return (len <= following_text.Length);
2405 internal int GetSurroundingChar (int pos)
2407 if (! get_surrounding_text (pos < 0 ? pos : pos + 1))
2410 return preceding_text[preceding_text.Length + pos];
2411 return following_text[pos];
2414 private void adjust_markers (int from, int to, object inserted)
2416 int ins = (inserted == null ? 0
2417 : inserted is int ? 1
2418 : ((MText) inserted).Length);
2419 int diff = ins - (to - from);
2421 for (MPlist p = marker_positions; ! p.IsEmpty; p = p.next)
2423 int pos = p.Integer;
2425 p.Set (p.Key, pos >= to ? pos + diff : from);
2427 if (cursor_pos >= to)
2428 set_cursor ("adjust", cursor_pos + diff);
2429 else if (cursor_pos > from)
2430 set_cursor ("adjust", from);
2433 private void preedit_replace (int from, int to, int c)
2435 preedit.Del (from, to);
2436 preedit.Ins (from, c);
2437 adjust_markers (from, to, c);
2440 private void preedit_replace (int from, int to, MText mt)
2442 preedit[from, to] = mt;
2443 adjust_markers (from, to, mt);
2446 internal void insert (int c)
2448 preedit_replace (cursor_pos, cursor_pos, c);
2449 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2452 internal void insert (string str)
2454 preedit_replace (cursor_pos, cursor_pos, (MText) str);
2455 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2458 private void update_candidate (Candidates candidates)
2460 object candidate = candidates.Current;
2462 if (candidate is MText)
2464 preedit_replace (candidate_from, candidate_to, (MText) candidate);
2465 candidate_to = candidate_from + ((MText) candidate).Length;
2469 preedit_replace (candidate_from, candidate_to, (int) candidate);
2470 candidate_to = candidate_from + 1;
2472 set_cursor ("update-candidate", candidate_to);
2473 changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
2477 internal void insert_candidates (Candidates candidates)
2479 this.candidates = candidates;
2480 candidate_from = candidate_to = cursor_pos;
2481 update_candidate (candidates);
2484 internal void select (int n)
2486 if (candidates != null)
2488 candidates.Select (n);
2489 update_candidate (null);
2493 internal int delete (int pos)
2495 int deleted = pos - cursor_pos;
2497 if (pos < cursor_pos)
2501 if (DeleteSurroundingText != null)
2503 callback_arg.Set (MSymbol.integer, pos);
2504 if (DeleteSurroundingText (this, callback_arg))
2506 if (callback_arg.IsInteger)
2507 deleted = callback_arg.Integer - cursor_pos;
2508 preceding_text.Del ();
2511 deleted = - cursor_pos;
2515 if (pos < cursor_pos)
2516 preedit_replace (pos, cursor_pos, null);
2520 if (pos > preedit.Length)
2522 if (DeleteSurroundingText != null)
2524 callback_arg.Set (MSymbol.integer, pos - preedit.Length);
2525 if (DeleteSurroundingText (this, callback_arg))
2527 if (callback_arg.IsInteger)
2528 deleted = callback_arg.Integer - cursor_pos;
2529 preceding_text.Del ();
2532 deleted = preedit.Length - cursor_pos;
2534 pos = preedit.Length;
2536 if (pos > cursor_pos)
2537 preedit_replace (cursor_pos, pos, null);
2540 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2544 internal void show ()
2546 candidate_show = true;
2547 changed |= ChangedStatus.CandidateShow;
2550 internal void hide ()
2552 candidate_show = false;
2553 changed |= ChangedStatus.CandidateShow;
2556 internal void move (int pos)
2560 else if (pos > preedit.Length)
2561 pos = preedit.Length;
2562 if (pos != cursor_pos)
2564 set_cursor ("move", pos);
2565 changed |= ChangedStatus.Preedit;
2569 internal void pushback (int n)
2582 if (key_head > keys.keyseq.Count)
2583 key_head = keys.keyseq.Count;
2587 internal void pushback (KeySeq keyseq)
2591 if (key_head < keys.keyseq.Count)
2592 keys.keyseq.RemoveRange (key_head, keys.keyseq.Count - key_head);
2593 for (int i = 0; i < keyseq.keyseq.Count; i++)
2594 keys.keyseq.Add (keyseq.keyseq[i]);
2597 internal void pop ()
2599 if (key_head < keys.keyseq.Count)
2600 keys.keyseq.RemoveRange (key_head, 1);
2603 internal void undo (int n)
2606 keys.keyseq.RemoveRange (keys.keyseq.Count + n, - n);
2608 keys.keyseq.RemoveRange (n, keys.keyseq.Count - n);
2612 internal void commit ()
2614 produced.Cat (preedit);
2615 preedit_replace (0, preedit.Length, null);
2616 changed |= ChangedStatus.Preedit;
2619 internal void shift (State state)
2623 if (prev_state == null)
2628 if (state == im.initial_state)
2631 keys.keyseq.RemoveRange (0, key_head);
2633 if (state != this.state)
2635 domain.RestoreValues (state_initial_var_values);
2636 if (state.enter_actions != null)
2637 take_actions (state.enter_actions);
2643 if (state != this.state && state.enter_actions != null)
2644 take_actions (state.enter_actions);
2645 prev_state = this.state;
2648 if (this.state == null || this.state.title != state.title)
2649 this.changed |= ChangedStatus.StateTitle;
2651 keymap = state.keymap;
2654 public Context (MInputMethod im)
2656 if (im.load_status != LoadStatus.Full
2658 throw new Exception ("Openging " + im.tag + " failed");
2660 domain = new Xex.Domain ("context", im.domain, this);
2661 state_initial_var_values = domain.SaveValues ();
2664 if (PreeditChanged != null)
2666 callback_arg.Set (MSymbol.mtext, preedit);
2667 PreeditChanged (this, callback_arg);
2669 if (StatusChanged != null)
2671 callback_arg.Set (MSymbol.mtext, status);
2672 StatusChanged (this, callback_arg);
2676 public ChangedStatus Changed { get { return changed; } }
2678 internal object GetCandidates (out int column)
2681 if (cursor_pos == 0)
2683 Candidates candidates
2684 = (Candidates) preedit.GetProp (cursor_pos - 1, Mcandidates);
2685 if (candidates == null)
2687 column = candidates.Column;
2688 return candidates.Current;
2691 private void save_state ()
2693 state_var_values = domain.SaveValues ();
2694 state_preedit.Del ();
2695 state_preedit.Ins (0, preedit);
2696 state_key_head = key_head;
2697 state_pos = cursor_pos;
2700 private void restore_state ()
2702 domain.RestoreValues (state_var_values);
2704 preedit.Ins (0, state_preedit);
2705 set_cursor ("restore", state_pos);
2708 private bool handle_key ()
2710 Console.Write ("\nHandle ({0}[{1}]) in {2}",
2711 keys, key_head, state.name);
2713 Keymap sub = keymap.Lookup (keys, ref key_head);
2719 if (keymap.map_actions != null)
2721 if (! take_actions (keymap.map_actions))
2724 else if (keymap.submaps != null)
2726 for (int i = state_key_head; i < key_head; i++)
2727 preedit_replace (cursor_pos, cursor_pos,
2728 keys.keyseq[i].ToChar ());
2730 if (keymap.submaps == null)
2732 if (keymap.branch_actions != null)
2734 if (! take_actions (keymap.branch_actions))
2737 if (keymap != state.keymap)
2743 State current_state = state;
2745 if (keymap.branch_actions != null)
2747 if (! take_actions (keymap.branch_actions))
2750 if (state == current_state)
2752 if (state == im.initial_state
2753 && key_head < keys.keyseq.Count)
2755 if (keymap != state.keymap)
2757 else if (keymap.branch_actions == null)
2758 shift (im.initial_state);
2764 public bool Toggle ()
2770 public bool UnhandledKey (out Key key)
2772 key = unhandled_key;
2773 return key_unhandled;
2776 public MText Preedit { get { return preedit; } }
2777 public MText Produced { get { return produced; } }
2780 // true: All keys are handled and there's no text to commit.
2781 // false: Some key is left unhandled or there's a text to
2782 // commit. The caller should refer to UnhandledKey and
2785 public bool Filter (Key key)
2789 key_unhandled = true;
2790 unhandled_key = key;
2793 if (key == Key.Reload)
2795 changed = ChangedStatus.None;
2797 preceding_text.Del ();
2798 following_text.Del ();
2800 key_unhandled = false;
2801 keys.keyseq.Add (key);
2803 while (key_head < keys.keyseq.Count)
2805 if (! handle_key ())
2807 unhandled_key = keys.keyseq[key_head++];
2808 key_unhandled = true;
2814 keys.keyseq.RemoveRange (0, key_head);
2817 if ((changed & ChangedStatus.Preedit) != ChangedStatus.None
2818 && PreeditChanged != null)
2820 callback_arg.Set (MSymbol.mtext, preedit);
2821 PreeditChanged (this, callback_arg);
2823 if ((changed & ChangedStatus.StateTitle) != ChangedStatus.None
2824 && StatusChanged != null)
2826 callback_arg.Set (MSymbol.mtext, status);
2827 StatusChanged (this, callback_arg);
2829 if ((changed & ChangedStatus.Candidate) != ChangedStatus.None
2830 && CandidateChanged != null)
2832 CandidateChanged (this, callback_arg);
2835 Console.Write ("\nPreedit(\"{0}\"/{1}), Produced({2})",
2836 preedit, cursor_pos, produced);
2838 return (! key_unhandled && produced.Length == 0);