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 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;
31 internal static Xex.Domain im_domain = new Xex.Domain (null);
32 private static MSymbol Minput_method = "input-method";
33 private static MSymbol Mdescription = "description";
34 private static MSymbol Mvariable = "variable";
35 private static MSymbol Mcommand = "command";
36 private static MSymbol Mmodule = "module";
37 private static MSymbol Mtitle = "title";
38 private static MSymbol Minclude = "include";
39 private static MSymbol Mmacro = "macro";
40 private static MSymbol Mmap = "map";
41 private static MSymbol Mmap_list = "map-list";
42 private static MSymbol Mstate = "state";
43 internal static MSymbol Mcandidates = "candidates";
46 private static MSymbol Mget_surrounding_text = "get-surrounding-text";
47 private static MSymbol Mdel_surrounding_text = "del-surrounding-text";
49 private static Xex.Symbol Qmap = "map";
50 private static Xex.Symbol Qrule = "rule";
51 private static Xex.Symbol Qkeyseq = "keyseq";
52 private static Xex.Symbol Qprogn = "progn";
53 private static Xex.Symbol Qcatch = "catch";
54 private static Xex.Symbol Qinsert = "insert";
55 private static Xex.Symbol Qinsert_candidates = "insert-candidates";
56 private static Xex.Symbol Qchar_at = "char-at";
57 private static Xex.Symbol Qat_minus_zero = "@-0";
58 private static Xex.Symbol Qselect = "select";
59 private static Xex.Symbol Qdelete = "delete";
60 private static Xex.Symbol Qshift = "shift";
61 private static Xex.Symbol Qmove = "move";
62 private static Xex.Symbol Qmark = "mark";
63 private static Xex.Symbol Qset = "set";
64 private static Xex.Symbol Qadd = "add";
65 private static Xex.Symbol Qsub = "sub";
66 private static Xex.Symbol Qmul = "mul";
67 private static Xex.Symbol Qdiv = "div";
68 private static Xex.Symbol Qcond = "cond";
69 private static Xex.Symbol Qsname = "sname";
70 private static Xex.Symbol Qmname = "mname";
71 private static Xex.Symbol Qstate_hook = "state-hook";
72 private static Xex.Symbol Qcatch_all_branch = "catch-all-branch";
73 private static Xex.Symbol Qbranch = "branch";
74 private static Xex.Symbol Qstate = "state";
75 private static Xex.Symbol Qtitle = "title";
76 private static Xex.Symbol Qeq = "=";
77 private static Xex.Symbol Qeqeq = "==";
78 private static Xex.Symbol Qcandidates_group_size = "candidates-group-size";
80 private static Xex.Term Tnil = new Xex.Term ((Xex.Symbol) "nil");
81 private static Xex.Term Tcatch_tag = new Xex.Term ((Xex.Symbol) "@mimtag");
83 private static Dictionary<MDatabase.Tag, MInputMethod> im_table
84 = new Dictionary<MDatabase.Tag, MInputMethod> ();
86 internal static MInputMethod im_global = null;
89 private enum LoadStatus
99 public enum ChangedStatus
105 CandidateList = 0x08,
106 CandidateIndex = 0x10,
107 CandidateShow = 0x20,
110 private static ChangedStatus CandidateAll = (ChangedStatus.CandidateList
111 | ChangedStatus.CandidateIndex
112 | ChangedStatus.CandidateShow);
114 public enum KeyModifier
117 Shift_L = 0x00400000,
118 Shift_R = 0x00800000,
120 Control_L = 0x01000000,
121 Control_R = 0x02000000,
122 Control = 0x03000000,
137 private static Dictionary<string, uint> keysyms
138 = new Dictionary<string, uint> ();
139 private static Dictionary<string, KeyModifier> keymodifiers
140 = new Dictionary<string, KeyModifier> ();
141 private static uint keysym_base = 0x200000;
142 private static uint char_mask = ~((uint) KeyModifier.All);
143 public static Key Reload;
147 keysyms["bs"] = keysyms["backspace"] = 0x08;
148 keysyms["tab"] = 0x09;
149 keysyms["lf"] = keysyms["linefeed"] = 0x10;
150 keysyms["cr"] = keysyms["return"] = keysyms["enter"] = 0x13;
151 keysyms["esc"] = keysyms["escape"] = 0x1B;
152 keysyms["spc"] = keysyms["space"] = 0x20;
153 keysyms["del"] = keysyms["delete"] = 0x7F;
154 keymodifiers["shift-l"] = KeyModifier.Shift_L;
155 keymodifiers["shift-r"] = KeyModifier.Shift_R;
156 keymodifiers["shift"] = KeyModifier.Shift;
157 keymodifiers["control-l"] = KeyModifier.Control_L;
158 keymodifiers["control-r"] = KeyModifier.Control_R;
159 keymodifiers["control"] = KeyModifier.Control;
160 keymodifiers["alt-l"] = KeyModifier.Alt_L;
161 keymodifiers["alt-r"] = KeyModifier.Alt_R;
162 keymodifiers["alt"] = KeyModifier.Alt;
163 keymodifiers["altgr"] = KeyModifier.AltGr;
164 keymodifiers["super"] = KeyModifier.Super;
165 keymodifiers["hyper"] = KeyModifier.Hyper;
166 Reload = new Key (keysym_base);
167 keysyms["-reload"] = keysym_base++;
170 private static uint decode_keysym (MSymbol keysym)
173 string name = keysym.Name;
175 if (name.Length == 1)
177 name = name.ToLower ();
178 if (! keysyms.TryGetValue (name, out key))
179 keysyms[name] = key = keysym_base++;
183 private static uint combine_modifiers (uint c, KeyModifier modifiers)
185 if (c < 0x7F && c != 0x20)
187 if ((modifiers & KeyModifier.Shift) != KeyModifier.None
188 && Char.IsLower ((char) c))
190 modifiers &= ~KeyModifier.Shift;
191 c = Char.ToUpper ((char) c);
193 if ((modifiers & KeyModifier.Control) != KeyModifier.None)
195 modifiers &= ~KeyModifier.Control;
199 return c | (uint) modifiers;
202 public Key (uint c) { key = c; }
203 public Key (int c) { key = (uint) c; }
205 public Key (uint c, KeyModifier modifiers)
207 key = combine_modifiers (c, modifiers);
210 public Key (MSymbol keysym, KeyModifier modifiers)
212 key = combine_modifiers (decode_keysym (keysym), modifiers);
215 public Key (MSymbol keysym)
217 string str = keysym.Name;
218 int len = str.Length;
220 KeyModifier modifiers = KeyModifier.None;
222 for (i = 0; i + 2 < len && str[i + 1] == '-'; i += 2)
225 modifiers |= KeyModifier.Shift;
226 else if (str[i] == 'C')
227 modifiers |= KeyModifier.Control;
228 else if (str[i] == 'A')
229 modifiers |= KeyModifier.Alt;
230 else if (str[i] == 'G')
231 modifiers |= KeyModifier.AltGr;
232 else if (str[i] == 's')
233 modifiers |= KeyModifier.Super;
234 else if (str[i] == 'H')
235 modifiers |= KeyModifier.Hyper;
238 key = combine_modifiers (str[i], modifiers);
240 key = combine_modifiers (decode_keysym (keysym), modifiers);
243 public Key (MPlist plist)
245 KeyModifier modifiers = KeyModifier.None;
248 for (p = plist; ! p.IsEmpty; p = p.next)
252 if (! p.next.IsEmpty)
253 throw new Exception ("Invalid Key: " + plist);
256 else if (! p.IsSymbol)
257 throw new Exception ("Invalid Key: " + plist);
260 string name = p.Symbol.Name.ToLower ();
263 if (! keymodifiers.TryGetValue (name, out m))
268 if (p.IsEmpty || ! p.next.IsEmpty)
269 throw new Exception ("Invalid Key: " + plist);
271 key = combine_modifiers ((uint) p.Integer, modifiers);
273 key = combine_modifiers (decode_keysym (p.Symbol), modifiers);
276 public bool HasModifier
278 get { return ((key & (uint) KeyModifier.All) != 0); }
281 public static bool operator== (Key k1, Key k2)
283 return k1.key == k2.key;
286 public static bool operator!= (Key k1, Key k2)
288 return k1.key != k2.key;
291 public override bool Equals (object o) { return key == ((Key) o).key; }
293 public override int GetHashCode () { return (int) key; }
295 public bool Match (Key k)
299 if ((k.key & char_mask) != (key & char_mask))
301 KeyModifier m1 = ((KeyModifier) key) & KeyModifier.All;
302 KeyModifier m2 = ((KeyModifier) k.key) & KeyModifier.All;
303 return (((m1 & KeyModifier.Shift) == (m2 & KeyModifier.Shift)
304 || ((m1 & KeyModifier.Shift) == KeyModifier.Shift
305 && (m2 & KeyModifier.Shift) != KeyModifier.None))
306 && ((m1 & KeyModifier.Control) == (m2 & KeyModifier.Control)
307 || ((m1 & KeyModifier.Control) == KeyModifier.Control
308 && (m2 & KeyModifier.Control) != KeyModifier.None))
309 && ((m1 & KeyModifier.Alt) == (m2 & KeyModifier.Alt)
310 || ((m1 & KeyModifier.Alt) == KeyModifier.Alt
311 && (m2 & KeyModifier.Alt) != KeyModifier.None))
312 && ((m1 & KeyModifier.High) == (m2 & KeyModifier.High)));
317 return (int) (key & 0x1FFFFF);
320 public override string ToString ()
325 foreach (KeyValuePair<string, uint> kv in keysyms)
326 if ((uint) c == kv.Value)
334 KeyModifier m = ((KeyModifier) key) & KeyModifier.All;
336 if (m != KeyModifier.None)
338 if ((m & KeyModifier.Shift) != KeyModifier.None)
340 if ((m & KeyModifier.Control) != KeyModifier.None)
342 if ((m & KeyModifier.Alt) != KeyModifier.None)
344 if ((m & KeyModifier.AltGr) != KeyModifier.None)
346 if ((m & KeyModifier.Super) != KeyModifier.None)
348 if ((m & KeyModifier.Hyper) != KeyModifier.None)
355 internal class KeySeq : Xex.TermValue
357 public List<Key> keyseq = new List<Key> ();
359 public override Xex.TermValue Clone ()
361 KeySeq ks = new KeySeq ();
362 ks.keyseq.InsertRange (0, keyseq);
368 public KeySeq (MPlist plist)
370 foreach (MPlist p in plist)
373 keyseq.Add (new Key (p.Symbol));
374 else if (p.IsInteger)
375 keyseq.Add (new Key ((char) p.Integer));
377 keyseq.Add (new Key (p.Plist));
379 throw new Exception ("Invalid Key Sequence: " + plist);
383 public KeySeq (MText mt) : base ()
385 for (int i = 0; i < mt.Length; i++)
386 keyseq.Add (new Key ((uint) mt[i]));
389 public KeySeq (List<Xex.Term> list)
391 int len = list.Count;
393 for (int i = 0; i < len; i++)
396 keyseq.Add (new Key (list[i].Intval));
397 else if (list[i].IsStr)
398 keyseq.Add (new Key (list[i].Strval));
399 else if (list[i].IsSymbol)
400 keyseq.Add (new Key ((string) list[i].Symval));
402 throw new Exception ("Invalid key: " + list[i]);
406 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
408 Xex.Term term = new Xex.Term (domain, node.FirstChild).Eval (domain);
409 return (term.IsStr ? new KeySeq ((MText) term.Strval)
410 : new KeySeq (term.Listval));
413 public override string ToString ()
416 foreach (Key key in keyseq)
417 if (key.HasModifier || key.ToChar () < 0x20)
420 foreach (Key k in keyseq)
424 mt.Cat (k.ToString ());
426 return (string) mt.Cat (")");
429 foreach (Key k in keyseq)
433 if (c == '\\' || c == '"')
437 return (string) mt.Cat ("\"");
444 public MText description;
445 internal List<KeySeq> keys;
447 public Command (MPlist p)
451 description = parse_description (p);
452 if (description == null)
453 description = "No description";
454 keys = new List<KeySeq> ();
455 for (p = p.next; ! p.IsEmpty; p = p.next)
458 keys.Add (new KeySeq (p.Text));
460 keys.Add (new KeySeq (p.Plist));
464 public Command (XmlNode node)
466 name = node.Attributes[0].Value;
467 keys = new List<KeySeq> ();
468 for (node = node.FirstChild; node != null; node = node.NextSibling)
470 if (node.Name == "description")
471 description = parse_description (node);
472 else if (node.Name == "keyseq")
473 keys.Add ((KeySeq) KeySeq.parser (null, node));
477 public override string ToString ()
479 string str = "(" + name + " \"" + (string) description;
480 foreach (KeySeq keyseq in keys)
486 internal class Plugin
489 private Assembly assembly;
490 private Type plugin_type;
492 public Plugin (string name)
497 public MethodInfo GetMethod (Xex.Symbol name)
499 if (assembly == null)
501 assembly = Assembly.LoadFrom (name + ".dll");
502 plugin_type = assembly.GetType ("M17n.MInputMethod.Plugin");
505 MethodInfo info = plugin_type.GetMethod ((string) name);
507 throw new Exception ("Invalid plugin method: " + name);
511 public override string ToString ()
513 return String.Format ("(module {0}", name);
517 internal class PluginMethod : Xex.Function
519 private Plugin plugin;
520 private MethodInfo method_info;
521 object[] parameters = new object[2];
523 public PluginMethod (Plugin plugin, string name)
524 : base ((Xex.Symbol) name, 0, -1)
526 this.plugin = plugin;
529 public override Xex.Term Call (Xex.Domain domain, Xex.Variable vari,
532 args = (Xex.Term[]) args.Clone ();
533 for (int i = 0; i < args.Length; i++)
535 args[i] = args[i].Eval (domain);
539 if (method_info == null)
540 method_info = plugin.GetMethod (name);
541 parameters[0] = domain.context;
542 parameters[1] = args;
543 return (Xex.Term) method_info.Invoke (null, parameters);
547 internal abstract class Marker : Xex.TermValue
549 private Xex.Symbol name;
551 private Marker (Xex.Symbol name)
556 public abstract int Position (Context ic);
557 public virtual void Mark (Context ic)
559 throw new Exception ("Can't set predefined marker: " + name);
561 public virtual int CharAt (Context ic)
563 return ic.preedit[Position (ic)];
565 public override Xex.TermValue Clone () { return this; }
567 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
569 return Get ((Xex.Symbol) node.InnerText);
572 public class Named : Marker
574 public Named (Xex.Symbol name) : base (name) { }
576 public override int Position (Context ic)
580 if (ic.marker_positions.TryGetValue (this, out pos))
585 public override void Mark (Context ic)
587 ic.marker_positions[this] = ic.cursor_pos;
591 public class Predefined : Marker
594 public Predefined (Xex.Symbol name) : base (name)
596 tag = ((string) name)[1];
599 public override int Position (Context ic)
603 case '>': return ic.preedit.Length;
604 case '-': return ic.cursor_pos - 1;
605 case '+': return ic.cursor_pos + 1;
607 if (ic.cursor_pos > 0)
609 int pos = ic.cursor_pos;
611 ic.preedit.FindProp (Mcandidates, pos - 1, out pos, out to);
616 if (ic.cursor_pos < ic.preedit.Length - 1)
618 int pos = ic.cursor_pos;
620 ic.preedit.FindProp (Mcandidates, pos, out from, out pos);
623 return ic.preedit.Length;
630 public class PredefinedAbsolute : Marker
634 public PredefinedAbsolute (Xex.Symbol name) : base (name)
636 if (! int.TryParse (((string) name).Substring (1), out pos))
637 throw new Exception ("Invalid marker name: " + name);
640 public override int Position (Context ic)
642 return (pos < ic.preedit.Length ? pos : ic.preedit.Length);
646 public class PredefinedSurround : Marker
648 private int distance;
650 public PredefinedSurround (Xex.Symbol name) : base (name)
652 if (! int.TryParse (((string) name).Substring (2), out distance))
653 throw new Exception ("Invalid marker name: " + name);
658 public override int Position (Context ic)
660 return ic.cursor_pos + distance;
663 public override int CharAt (Context ic)
665 int pos = ic.cursor_pos + distance;
667 return ic.GetSurroundingChar (pos);
668 else if (pos >= ic.preedit.Length)
669 return ic.GetSurroundingChar (pos - ic.preedit.Length);
670 return ic.preedit[pos];
674 static internal Dictionary<Xex.Symbol,Predefined> predefined_markers;
678 predefined_markers = new Dictionary<Xex.Symbol, Predefined> ();
680 = new Xex.Symbol[] {"@<", "@>", "@-", "@+", "@[", "@]" };
681 foreach (Xex.Symbol s in symlist)
682 predefined_markers[s] = new Predefined (s);
685 public static Marker Get (Xex.Symbol name)
691 if (predefined_markers.TryGetValue (name, out pred))
694 throw new Exception ("Invalid marker name: " + name);
695 if (Char.IsDigit (str[1]))
696 return new PredefinedAbsolute (name);
697 if (str.Length == 2 || name == Qat_minus_zero
698 || ! (str[1] == '-' || str[1] == '+'))
699 throw new Exception ("Invalid marker name: " + name);
700 return new PredefinedSurround (name);
702 return new Named (name);
706 internal class Candidates
713 public Block (int index, Xex.Term term)
717 Data = (MText) term.Strval;
720 MPlist plist = new MPlist ();
722 foreach (Xex.Term t in term.Listval)
723 p = p.Add (MSymbol.mtext, (MText) t.Strval);
728 public Block (int index, MPlist plist)
733 else if (plist.IsPlist)
736 throw new Exception ("Invalid candidate: " + plist);
741 get { return (Data is MText
742 ? ((MText) Data).Length
743 : ((MPlist) Data).Count); }
746 public object this[int i]
749 if (Data is MText) return ((MText) Data)[i];
750 return ((MPlist) Data)[i];
755 private Block[] blocks;
757 private int index = 0;
758 public object[] group;
760 private bool IsFixed { get { return group != null; } }
763 Block last = blocks[blocks.Length - 1];
764 return last.Index + last.Count; }
768 get { return (IsFixed ? index % group.Length
769 : index - blocks[row].Index); }
772 public object Group {
773 get { return (IsFixed ? group : blocks[row].Data); }
776 public int GroupLength
781 int nitems = group.Length;
782 int start = index - (index % nitems);
784 return (start + nitems <= total ? nitems : total - start);
786 return blocks[row].Count;
790 public object Current {
792 return (IsFixed ? group[index % group.Length]
793 : blocks[row][index - blocks[row].Index]);
797 public Candidates (MPlist list, int column)
799 int nblocks = list.Count;
801 blocks = new Block[nblocks];
802 for (int i = 0, start = 0; i < nblocks; i++, list = list.next)
803 start += (blocks[i] = new Block (index, list)).Count;
805 group = new object[column];
808 public Candidates (Xex.Term[] candidates, int column)
810 int nblocks = candidates.Length;
812 blocks = new Block[nblocks];
813 for (int i = 0, start = 0; i < nblocks; i++)
814 start += (blocks[i] = new Block (index, candidates[i])).Count;
816 group = new object[column];
819 public static void Detach (Context ic)
821 ic.preedit.PopProp (0, ic.preedit.Length, Mcandidates);
822 ic.candidates = null;
823 ic.changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
827 // Fill the array "group" by candidates stating from INDEX.
828 // INDEX must be a multiple of "column". Set NTIMES to the
829 // number of valid candidates in "group". Update "block" if
830 // necessary. Return "group".
832 private int fill_group (int start)
834 int nitems = group.Length;
839 while (start < b.Index)
842 while (start >= b.Index + b.Count)
848 for (int i = 0; i < nitems; i++, start++)
853 if (r == blocks.Length)
864 // Update "row" to what contains the first candidate of
865 // the previous candidate-group, update "current_index", and
866 // update "group" if necessary. Return the previous
867 // candidate-group. Set NITEMS to the number of valid
868 // candidates contained in that group.
870 public int PrevGroup ()
877 nitems = group.Length;
878 if ((index -= col + nitems) < 0)
879 index = (Total / nitems) * nitems;
880 nitems = fill_group (index);
884 row = row > 0 ? row-- : blocks.Length - 1;
885 nitems = blocks[row].Count;
886 index = blocks[row].Index;
888 index += col < nitems ? col : nitems - 1;
892 public int NextGroup ()
899 nitems = group.Length;
900 if ((index += nitems - col) >= Total)
902 nitems = fill_group (index);
906 row = row < blocks.Length - 1 ? row + 1 : 0;
907 nitems = blocks[row].Count;
908 index = blocks[row].Count;
910 index += col < nitems ? col : nitems - 1;
920 int nitems = PrevGroup ();
921 index += col < nitems - 1 ? col : nitems - 1;
930 int nitems = GroupLength;
932 if (col == nitems - 1)
934 nitems = NextGroup ();
948 index += GroupLength - (Column + 1);
951 public void Select (int col)
953 int maxcol = GroupLength - 1;
956 index = index - Column + col;
960 internal class Selector : Xex.TermValue
962 static new Dictionary<MSymbol, Selector> selectors;
966 selectors = new Dictionary<MSymbol, Selector> ();
967 MSymbol[] symlist = new MSymbol[] { "@<", "@=", "@>", "@-", "@+",
969 foreach (MSymbol s in symlist)
970 selectors[s] = new Selector (s);
971 selectors["@first"] = new Selector ('<');
972 selectors["@current"] = new Selector ('=');
973 selectors["@last"] = new Selector ('>');
974 selectors["@previous"] = new Selector ('-');
975 selectors["@next"] = new Selector ('+');
976 selectors["@previous-candidate-change"] = new Selector ('[');
977 selectors["@next-candidate-change"] = new Selector (']');
982 private Selector (MSymbol sym) { tag = sym.Name[1]; }
984 private Selector (char tag) { this.tag = tag; }
986 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
988 return Get ((MSymbol) node.InnerText);
991 public static Xex.TermValue Get (MSymbol name)
994 if (! selectors.TryGetValue (name, out selector))
995 throw new Exception ("Invalid selector name: " + name);
999 public override Xex.TermValue Clone () { return this; }
1001 public void Select (Candidates candidates)
1005 case '<': candidates.First (); break;
1006 case '>': candidates.Last (); break;
1007 case '-': candidates.Prev (); break;
1008 case '+': candidates.Next (); break;
1009 case '[': candidates.PrevGroup (); break;
1010 case ']': candidates.NextGroup (); break;
1018 public MSymbol name;
1019 public List<Entry> entries = new List<Entry> ();
1021 public Map (MSymbol name) { this.name = name; }
1025 public KeySeq keyseq;
1026 public Xex.Term[] actions;
1028 public Entry (Xex.Domain domain, KeySeq keyseq, Xex.Term[] actions)
1030 this.keyseq = keyseq;
1031 this.actions = actions;
1035 public override string ToString ()
1037 string str = "(" + name;
1038 foreach (Entry e in entries)
1039 str += " " + e.keyseq.ToString ();
1044 internal class Keymap
1046 public Dictionary<Key, Keymap> submaps;
1047 public Xex.Term[] map_actions, branch_actions;
1049 public Keymap () { }
1051 public void Add (KeySeq keys, int index,
1052 Xex.Term[] map_actions, Xex.Term[] branch_actions)
1054 if (index == keys.keyseq.Count)
1056 this.map_actions = map_actions;
1057 this.branch_actions = branch_actions;
1061 Key key = keys.keyseq[index];
1064 if (submaps == null)
1065 submaps = new Dictionary<Key, Keymap> ();
1067 submaps.TryGetValue (key, out sub);
1069 submaps[key] = sub = new Keymap ();
1070 sub.Add (keys, index + 1, map_actions, branch_actions);
1074 public void AddMap (Map map, Xex.Term[] branch_actions)
1076 foreach (Map.Entry entry in map.entries)
1077 Add (entry.keyseq, 0, entry.actions, branch_actions);
1080 public Keymap Lookup (KeySeq keys, ref int index)
1084 if (index < keys.keyseq.Count
1086 && submaps.TryGetValue (keys.keyseq[index], out sub))
1089 return sub.Lookup (keys, ref index);
1094 private void describe (MText mt, KeySeq keyseq)
1096 if (map_actions != null || branch_actions != null)
1100 mt.Cat ('(').Cat (keyseq.ToString ());
1101 if (map_actions != null)
1102 foreach (Xex.Term term in map_actions)
1103 mt.Cat (' ').Cat (term.ToString ());
1104 if (branch_actions != null)
1105 foreach (Xex.Term term in branch_actions)
1106 mt.Cat (' ').Cat (term.ToString ());
1109 if (submaps != null)
1110 foreach (KeyValuePair<Key, Keymap> kv in submaps)
1112 keyseq.keyseq.Add (kv.Key);
1113 kv.Value.describe (mt, keyseq);
1114 keyseq.keyseq.RemoveAt (keyseq.keyseq.Count - 1);
1118 public override string ToString ()
1121 KeySeq keyseq = new KeySeq ();
1123 describe (mt, keyseq);
1128 internal class State
1130 public Xex.Symbol name;
1132 public Xex.Term[] enter_actions, fallback_actions;
1133 public Keymap keymap = new Keymap ();
1135 public State (Xex.Symbol name, MText title)
1141 public State (MInputMethod im, XmlNode node)
1143 this.name = node.Attributes[Qsname].Value;
1144 XmlAttribute attr = node.Attributes[Qtitle];
1146 title = (MText) attr.Value;
1149 keymap = new Keymap ();
1150 for (node = node.FirstChild; node != null; node = node.NextSibling)
1152 if (node.Name == Qstate_hook)
1153 enter_actions = Xex.ParseTerms (im.domain, node.FirstChild);
1154 else if (node.Name == Qcatch_all_branch)
1155 fallback_actions = Xex.ParseTerms (im.domain, node.FirstChild);
1156 else if (node.Name == Qbranch)
1158 MSymbol mapname = node.Attributes[Qmname].Value;
1160 if (im.maps.TryGetValue (mapname, out map))
1161 keymap.AddMap (map, Xex.ParseTerms (im.domain,
1164 throw new Exception ("Unknown map: " + mapname);
1169 public State (MInputMethod im, MPlist plist)
1171 if (! plist.IsSymbol)
1172 throw new Exception ("Invalid state: " + plist);
1173 this.name = plist.Symbol.Name;
1182 keymap = new Keymap ();
1183 for (; ! plist.IsEmpty; plist = plist.next)
1185 if (! plist.IsPlist)
1186 throw new Exception ("Invalid branch: " + plist);
1187 MPlist p = plist.Plist;
1189 throw new Exception ("Invalid branch: " + p);
1190 MSymbol mapname = p.Symbol;
1191 if (mapname == MSymbol.t)
1192 enter_actions = im.parse_actions (p.next, false);
1193 else if (mapname == MSymbol.nil)
1194 fallback_actions = im.parse_actions (p.next, false);
1198 if (im.maps.TryGetValue (mapname, out map))
1199 keymap.AddMap (map, im.parse_actions (p.next, false));
1201 throw new Exception ("Unknown map: " + mapname);
1206 public override string ToString ()
1208 MText mt = "(" + name;
1211 mt.Cat (" \"" + title + "\"");
1212 mt.Cat (keymap.ToString ());
1213 return (string) mt + ")";
1218 internal Xex.Domain domain = new Xex.Domain (im_domain, null);
1220 private LoadStatus load_status = LoadStatus.None;
1221 private MDatabase.Tag tag;
1222 private MDatabase mdb;
1224 private MText description;
1225 internal MText title;
1226 internal Command[] commands;
1227 internal Xex.Symbol[] var_names;
1228 internal Dictionary<MSymbol, Plugin> plugins;
1229 internal Dictionary<MSymbol, Map> maps;
1230 internal Dictionary<Xex.Symbol, State> states;
1231 internal State initial_state;
1233 static MInputMethod ()
1235 im_domain.DefTerm ("keyseq", KeySeq.parser);
1236 im_domain.DefTerm ("marker", Marker.parser);
1237 im_domain.DefTerm ("selector", Selector.parser);
1239 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
1240 im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, -1);
1241 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
1242 im_domain.DefSubr (Fselect, "select", false, 1, 1);
1243 im_domain.DefSubr (Fshow, "show", false, 0, 0);
1244 im_domain.DefSubr (Fhide, "hide", false, 0, 0);
1245 im_domain.DefSubr (Fmove, "move", false, 1, 1);
1246 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
1247 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
1248 im_domain.DefSubr (Fpop, "pop", false, 0, 0);
1249 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
1250 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
1251 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
1252 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
1253 im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
1254 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
1255 im_domain.DefSubr (Fkey_count, "key-count", false, 1, 1);
1256 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag",
1259 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, "*", "*", "*");
1260 List<MDatabase> list = MDatabase.List (tag);
1261 M17n.DebugPrint ("Found {0} input methods\n", list.Count);
1262 foreach (MDatabase mdb in list)
1263 im_table[mdb.tag] = new MInputMethod (mdb.tag);
1267 private MInputMethod (MDatabase.Tag tag)
1272 // Instance Properties
1273 public MSymbol Language { get { return tag[1]; } }
1274 public MSymbol Name { get { return tag[2]; } }
1275 public MSymbol SubName { get { return tag[3]; } }
1277 public bool Info (out MText description,
1279 out Xex.Variable[] variables,
1280 out Command[] commands)
1282 if ((load_status & LoadStatus.Header) != LoadStatus.Header
1283 && ! load_header ())
1291 description = this.description;
1293 if (var_names == null)
1297 variables = new Xex.Variable[var_names.Length];
1299 foreach (Xex.Symbol name in var_names)
1300 variables[i++] = domain.GetVar (name, false);
1302 commands = this.commands;
1306 public static MInputMethod Find (MSymbol language, MSymbol name)
1308 return Find (language, name, MSymbol.nil);
1311 public static MInputMethod Find (MSymbol language, MSymbol name,
1314 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, language,
1318 return (im_table.TryGetValue (tag, out im) ? im : null);
1323 return ((load_status == LoadStatus.Full) || load_body ());
1326 public static MInputMethod[] List ()
1328 MInputMethod[] array = new MInputMethod[im_table.Count];
1331 foreach (KeyValuePair<MDatabase.Tag, MInputMethod> kv in im_table)
1332 array[i++] = kv.Value;
1336 private bool load_header ()
1338 mdb = MDatabase.Find (tag);
1341 mdb.name_table = Xex.Symbol.Table;
1343 MSymbol format = mdb.Format;
1345 if (format == MSymbol.plist)
1346 load ((MPlist) mdb.Load (Mmap), false);
1349 XmlDocument doc = (XmlDocument) mdb.Load (Mmap_list);
1350 load (doc.DocumentElement, false);
1352 } catch (Exception e) {
1353 Console.WriteLine ("{0}\n", e);
1354 load_status = LoadStatus.Error;
1357 load_status |= LoadStatus.Header;
1361 private bool load_body ()
1363 mdb = MDatabase.Find (tag);
1366 mdb.name_table = Xex.Symbol.Table;
1368 object obj = mdb.Load ();
1370 load ((MPlist) obj, true);
1372 load ((XmlDocument) obj, true);
1373 } catch (Exception e) {
1374 Console.WriteLine (e);
1375 load_status = LoadStatus.Error;
1378 load_status = LoadStatus.Full;
1382 private void add_default_state ()
1384 Xex.Symbol Qinit = "init";
1385 State state = new State (Qinit, im.title);
1386 foreach (KeyValuePair<MSymbol, Map>kv in maps)
1387 state.keymap.AddMap (kv.Value, null);
1388 states[Qinit] = initial_state = state;
1391 private void load (MPlist plist, bool full)
1393 maps = new Dictionary<MSymbol, Map> ();
1394 states = new Dictionary<Xex.Symbol, State> ();
1396 for (; ! plist.IsEmpty; plist = plist.next)
1399 MPlist pl = plist.Plist;
1402 MSymbol sym = pl.Symbol;
1405 if (sym == Mdescription)
1406 description = parse_description (pl);
1407 else if (sym == Mtitle)
1412 else if (sym == Mvariable)
1413 parse_variables (pl);
1414 else if (sym == Mcommand)
1415 parse_commands (pl);
1420 else if (sym == Minclude)
1422 else if (sym == Mmacro)
1424 else if (sym == Mmap)
1426 else if (sym == Mstate)
1431 if (description == null)
1432 description = (MText) "No description";
1434 title = new MText (tag[2].Name);
1435 if (commands == null)
1436 commands = new Command[0];
1439 if (states.Count == 0)
1440 add_default_state ();
1443 private void load (XmlNode node, bool full)
1445 bool skip_header = load_status == LoadStatus.Header;
1447 maps = new Dictionary<MSymbol, Map> ();
1448 states = new Dictionary<Xex.Symbol, State> ();
1450 if (node.NodeType == XmlNodeType.Document)
1451 node = node.FirstChild;
1452 while (node.NodeType != XmlNodeType.Element)
1453 node = node.NextSibling;
1454 for (node = node.FirstChild; node != null; node = node.NextSibling)
1456 if (node.NodeType != XmlNodeType.Element)
1460 if (node.Name == "description")
1461 description = parse_description (node);
1462 else if (node.Name == "title")
1463 title = parse_title (node);
1464 else if (node.Name == "variable-list")
1465 parse_variables (node);
1466 else if (node.Name == "command-list")
1467 parse_commands (node);
1471 if (node.Name == "module-list")
1472 parse_plugins (node);
1473 else if (node.Name == "macro-list")
1474 parse_macros (node);
1475 else if (node.Name == "map-list")
1477 else if (node.Name == "state-list")
1478 parse_states (node);
1481 if (description == null)
1482 description = (MText) "No description";
1484 title = new MText (tag[2].Name);
1485 if (commands == null)
1486 commands = new Command[0];
1489 if (states.Count == 0)
1490 add_default_state ();
1493 private static MText parse_description (MPlist plist)
1499 plist = plist.Plist;
1500 if (plist.IsSymbol && plist.Symbol == (MSymbol) "_"
1501 && plist.next.IsMText)
1502 return plist.next.Text;
1507 private static MText parse_description (XmlNode node)
1509 if (node.HasChildNodes)
1510 node = node.FirstChild;
1511 return node.InnerText;
1514 private static MText parse_title (XmlNode node)
1516 return node.InnerText;
1519 private void new_variable (Xex.Symbol name, string desc, int val,
1520 MPlist pl, Xex.Variable vari)
1528 int nrange = pl.Count;
1529 range = new int[nrange * 2];
1530 for (int i = 0; i < nrange; i++)
1534 MPlist p = pl.Plist;
1536 if (! p.IsInteger || ! p.next.IsInteger)
1537 throw new Exception ("Invalid range: " + p);
1538 range[i * 2] = p.Integer;
1539 range[i * 2 + 1] = p.next.Integer;
1541 else if (pl.IsInteger)
1542 range[i * 2] = range[i * 2 + 1] = pl.Integer;
1544 throw new Exception ("Invalid range: " + pl);
1548 domain.Defvar (new Xex.Variable.Int (name, desc, val, range));
1551 Xex.Term term = new Xex.Term (val);
1553 vari.DefaultValue = term;
1558 private void new_variable (Xex.Symbol name, string desc, MText val,
1559 MPlist pl, Xex.Variable vari)
1567 range = new string[pl.Count * 2];
1568 for (int i = 0; i < range.Length; i++)
1571 range[i] = (string) pl.Text;
1573 throw new Exception ("Invalid range: " + pl);
1577 domain.Defvar (new Xex.Variable.Str (name, desc, (string) val, range));
1580 Xex.Term term = new Xex.Term ((string) val);
1582 vari.DefaultValue = term;
1587 private void new_variable (Xex.Symbol name, string desc, MSymbol val,
1588 MPlist pl, Xex.Variable vari)
1591 Xex.Symbol sym = val.Name;
1597 range = new Xex.Symbol[pl.Count * 2];
1598 for (int i = 0; i < range.Length; i++)
1601 range[i] = pl.Symbol.Name;
1603 throw new Exception ("Invalid range: " + pl);
1607 domain.Defvar (new Xex.Variable.Sym (name, desc, sym, range));
1610 Xex.Term term = new Xex.Term (sym);
1612 vari.DefaultValue = term;
1617 private Xex.Variable get_global_var (Xex.Symbol name)
1619 if (im_global == null || this != im_global)
1621 tag = new MDatabase.Tag (Minput_method, MSymbol.t, MSymbol.nil,
1623 im_global = im_table[tag];
1624 if (! im_global.Open ())
1625 throw new Exception ("Failed to load global");
1627 return im_global.domain.GetVar (name, false);
1630 private void parse_variables (MPlist plist)
1632 var_names = new Xex.Symbol[plist.Count];
1634 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1636 if (! plist.IsPlist || ! plist.Plist.IsSymbol)
1637 throw new Exception ("Invalid variable: " + plist);
1639 MPlist p = plist.Plist;
1640 Xex.Symbol name = (Xex.Symbol) p.Symbol.Name;
1641 var_names[i] = name;
1643 string desc = (string) parse_description (p);
1644 Xex.Variable vari = get_global_var (name);
1646 domain.Defvar (vari);
1652 new_variable (name, desc, p.Integer, p.next, vari);
1654 new_variable (name, desc, p.Text, p.next, vari);
1655 else if (p.IsSymbol)
1656 new_variable (name, desc, p.Symbol, p.next, vari);
1658 throw new Exception ("Invalid variable type: " + p.val);
1663 private void parse_variables (XmlNode node)
1665 XmlNodeList node_list = node.ChildNodes;
1667 var_names = new Xex.Symbol[node_list.Count];
1668 for (int i = 0; i < node_list.Count; i++)
1670 Xex.Symbol name = node_list[i].Attributes[0].Value;
1671 Xex.Variable vari = get_global_var (name);
1673 domain.Defvar (vari);
1674 domain.Defvar (node_list[i]);
1675 var_names[i] = name;
1679 private void parse_commands (MPlist plist)
1681 commands = new Command[plist.Count];
1683 for (int i = 0; ! plist.IsEmpty; plist = plist.next)
1684 if (plist.IsPlist && plist.Plist.IsSymbol)
1685 commands[i++] = new Command (plist.Plist);
1688 private void parse_commands (XmlNode node)
1690 XmlNodeList node_list = node.ChildNodes;
1692 commands = new Command[node_list.Count];
1693 for (int i = 0; i < node_list.Count; i++)
1695 if (node_list[i].NodeType == XmlNodeType.Element)
1696 commands[i] = new Command (node_list[i]);
1700 private void parse_plugins (MPlist plist)
1702 plugins = new Dictionary<MSymbol, Plugin> ();
1704 for (; ! plist.IsEmpty; plist = plist.Next)
1706 MPlist p = plist.Plist;
1707 MSymbol sym = p.Symbol;
1708 Plugin plugin = new Plugin (sym.Name);
1710 for (p = p.next; ! p.IsEmpty; p = p.next)
1712 Xex.Function func = new PluginMethod (plugin, p.Symbol.Name);
1713 domain.Defun (func);
1718 private void parse_plugins (XmlNode node)
1720 plugins = new Dictionary<MSymbol, Plugin> ();
1722 foreach (XmlNode n in node.ChildNodes)
1724 Plugin plugin = new Plugin (n.Attributes[0].Value);
1725 foreach (XmlNode nn in n.ChildNodes)
1727 Xex.Function func = new PluginMethod (plugin,
1728 nn.Attributes[0].Value);
1729 domain.Defun (func);
1734 private void parse_macros (XmlNode node)
1736 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1737 if (nn.NodeType == XmlNodeType.Element)
1738 domain.Defun (nn, true);
1739 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1740 if (nn.NodeType == XmlNodeType.Element)
1741 domain.Defun (nn, false);
1744 private void parse_maps (XmlNode node)
1746 for (node = node.FirstChild; node != null; node = node.NextSibling)
1747 if (node.Name == Qmap)
1749 MSymbol name = node.Attributes[0].Value;
1750 Map map = new Map (name);
1752 for (XmlNode nd = node.FirstChild; nd != null; nd = nd.NextSibling)
1753 if (nd.Name == Qrule)
1755 XmlNode n = nd.FirstChild;
1756 if (n.Name != Qkeyseq)
1758 KeySeq keyseq = (KeySeq) KeySeq.parser (domain, n);
1759 Xex.Term[] actions = Xex.ParseTerms (domain, n.NextSibling);
1760 map.entries.Add (new Map.Entry (domain, keyseq, actions));
1765 private void parse_states (MPlist plist)
1767 for (; ! plist.IsEmpty; plist = plist.next)
1770 State state = new State (this, plist.Plist);
1771 states[state.name] = state;
1775 private void parse_states (XmlNode node)
1777 for (node = node.FirstChild; node != null; node = node.NextSibling)
1778 if (node.Name == Qstate)
1780 State state = new State (this, node);
1781 states[state.name] = state;
1785 private void parse_include (MPlist plist)
1787 if (! plist.IsPlist)
1789 MPlist p = plist.Plist;
1790 MSymbol language, name, subname;
1791 language = p.Symbol;
1794 name = subname = MSymbol.nil;
1800 subname = MSymbol.nil;
1805 MInputMethod im = MInputMethod.Find (language, name, subname);
1811 if (! plist.IsSymbol)
1813 MSymbol target_type = plist.Symbol;
1815 MSymbol target_name = MSymbol.nil;
1817 target_name = plist.Symbol;
1818 if (target_type == Mmacro)
1820 if (target_name == MSymbol.nil)
1821 im.domain.CopyFunc (domain);
1823 im.domain.CopyFunc (domain, (Xex.Symbol) target_name.Name);
1825 else if (target_type == Mmap)
1827 if (target_name == MSymbol.nil)
1829 foreach (KeyValuePair<MSymbol, Map> kv in im.maps)
1830 maps[kv.Key] = kv.Value;
1835 if (im.maps.TryGetValue (target_name, out map))
1836 maps[target_name] = map;
1839 else if (target_type == Mstate)
1841 if (target_name == MSymbol.nil)
1843 foreach (KeyValuePair<Xex.Symbol, State> kv in im.states)
1844 states[kv.Key] = kv.Value;
1848 Xex.Symbol state_name = target_name.Name;
1850 if (im.states.TryGetValue (state_name, out state))
1851 states[state_name] = state;
1856 private Xex.Term parse_cond (MPlist plist)
1858 Xex.Term[] args = new Xex.Term[plist.Count];
1860 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1862 if (! plist.IsPlist)
1863 throw new Exception ("Invalid cond args: " + plist);
1864 MPlist p = plist.Plist;
1865 List<Xex.Term> arg = new List<Xex.Term> (parse_actions (p, false));
1866 args[i] = new Xex.Term (arg);
1868 return new Xex.Term (domain, Qcond, args);
1871 private Xex.Term parse_insert (MPlist plist)
1876 arg = new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1877 else if (plist.IsMText)
1878 arg = new Xex.Term ((string) plist.Text);
1879 else if (plist.IsInteger)
1880 arg = new Xex.Term (plist.Integer);
1881 else if (plist.IsPlist)
1883 MPlist pl = plist.Plist;
1885 args = new Xex.Term[pl.Count];
1887 for (i = 0; ! pl.IsEmpty; i++, pl = pl.next)
1890 args[i] = new Xex.Term ((string) pl.Text);
1891 else if (pl.IsPlist)
1893 List<Xex.Term> list = new List<Xex.Term> ();
1894 for (MPlist p = pl.Plist; ! p.IsEmpty; p = p.next)
1897 list.Add (new Xex.Term ((string) p.Text));
1899 throw new Exception ("Invalid candidates: " + p);
1903 throw new Exception ("Invalid candidates: " + pl);
1905 return new Xex.Term (domain, Qinsert_candidates, args);
1908 throw new Exception ("Invalid arg to insert: " + plist);
1909 args = new Xex.Term[1];
1911 return new Xex.Term (domain, Qinsert, args);
1914 private Xex.Term parse_select (MPlist plist)
1916 Xex.Term[] args = new Xex.Term[1];
1917 if (plist.IsInteger)
1918 args[0] = new Xex.Term (plist.Integer);
1919 else if (! plist.IsSymbol)
1920 throw new Exception ("Invalid arg to select: " + plist);
1921 else if (plist.Symbol.Name[0] == '@')
1922 args[0] = new Xex.Term (Selector.Get (plist.Symbol));
1924 args[0] = new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1925 return new Xex.Term (domain, Qselect, args);
1928 private Xex.Term parse_funcall_with_marker (MPlist plist, Xex.Symbol func)
1930 Xex.Term[] args = new Xex.Term[1];
1931 if (plist.IsInteger && func != Qmark)
1932 args[0] = new Xex.Term (plist.Integer);
1933 else if (plist.IsSymbol)
1934 args[0] = new Xex.Term (Marker.Get ((Xex.Symbol) plist.Symbol.Name));
1936 throw new Exception ("Invalid arg to " + func + ": " + plist);
1937 return new Xex.Term (domain, func, args);
1940 private Xex.Term parse_char_at (Xex.Symbol name)
1942 Xex.Term[] args = new Xex.Term[1];
1943 args[0] = new Xex.Term (Marker.Get (name));
1944 return new Xex.Term (domain, Qchar_at, args);
1947 private Xex.Term parse_shift (MPlist plist)
1949 Xex.Term[] args = new Xex.Term[1];
1950 if (! plist.IsSymbol)
1951 throw new Exception ("Invalid arg to shift: " + plist);
1952 args[0] = new Xex.Term ((Xex.Symbol) plist.Symbol.Name);
1953 return new Xex.Term (domain, Qshift, args);
1956 private Xex.Term parse_action (MPlist plist, bool as_funarg)
1960 MPlist p = plist.Plist;
1962 if (p.IsMText || p.IsPlist)
1963 return parse_insert (plist);
1965 throw new Exception ("Invalid action: " + p);
1966 Xex.Symbol name = p.Symbol.Name;
1969 return parse_cond (p);
1970 if (name == Qinsert)
1971 return parse_insert (p);
1972 if (name == Qselect)
1973 return parse_select (p);
1974 if (name == Qdelete || name == Qmove || name == Qmark)
1975 return parse_funcall_with_marker (p, name);
1977 return parse_shift (p);
1978 if (((string) name)[0] == '@')
1979 return parse_char_at (name);
1980 if (name == Qset || name == Qadd || name == Qsub
1981 || name == Qmul || name == Qdiv)
1984 throw new Exception ("Invalid action: " + p);
1985 Xex.Symbol varname = p.Symbol.Name;
1986 Xex.Term[] args = new Xex.Term[1];
1987 args[0] = parse_action (p.next, true);
1988 return new Xex.Term (domain, name, varname, args);
1995 return new Xex.Term (domain, name, null);
1997 return new Xex.Term (domain, name, parse_actions (p, true));
2000 else if (plist.IsSymbol)
2001 return new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
2002 else if (plist.IsMText)
2003 return (as_funarg ? new Xex.Term ((string) plist.Text)
2004 : parse_insert (plist));
2005 else if (plist.IsInteger)
2006 return (as_funarg ? new Xex.Term (plist.Integer)
2007 : parse_insert (plist));
2009 throw new Exception ("Invalid action: " + plist);
2012 private Xex.Term[] parse_actions (MPlist plist, bool as_funarg)
2014 Xex.Term[] terms = new Xex.Term[plist.Count];
2016 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
2017 terms[i] = parse_action (plist, as_funarg);
2021 private void parse_macros (MPlist plist)
2023 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
2026 MPlist p = pl.Plist;
2030 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null, null, true);
2032 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
2035 MPlist p = pl.Plist;
2039 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null,
2040 parse_actions (p.next, false), false);
2044 private void parse_maps (MPlist plist)
2046 for (; ! plist.IsEmpty; plist = plist.next)
2049 MPlist pl = plist.Plist;
2053 Map map = new Map (pl.Symbol);
2054 maps[pl.Symbol] = map;
2055 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
2059 MPlist p = pl.Plist;
2062 keys = new KeySeq (p.Text);
2064 keys = new KeySeq (p.Plist);
2069 = p.IsEmpty ? null : parse_actions (p, false);
2070 map.entries.Add (new Map.Entry (domain, keys, actions));
2075 private static Xex.Term Finsert (Xex.Domain domain, Xex.Variable vari,
2079 ((Context) domain.context).insert (args[0].Intval);
2081 ((Context) domain.context).insert (args[0].Strval);
2085 private static Xex.Term Finsert_candidates (Xex.Domain domain,
2089 Context ic = (Context) domain.context;
2090 Xex.Variable v = ic.domain.GetVar (Qcandidates_group_size, false);
2091 int column = (v == null ? 0 : v.Value.Intval);
2093 ic.insert_candidates (new Candidates (args, column));
2097 private static Xex.Term Fchar_at (Xex.Domain domain, Xex.Variable vari,
2100 Context ic = (Context) domain.context;
2101 Marker m = (Marker) args[0].Objval;
2103 return new Xex.Term (ic.char_at (m.Position (ic)));
2106 private static Xex.Term Fdelete (Xex.Domain domain, Xex.Variable vari,
2109 Context ic = (Context) domain.context;
2113 pos = args[0].Intval;
2116 Marker m = (Marker) args[0].Objval;
2117 pos = m.Position (ic);
2123 private static Xex.Term Fselect (Xex.Domain domain, Xex.Variable vari,
2126 Candidates can = ((Context) domain.context).candidates;
2129 ((Selector) args[0].Objval).Select (can);
2133 private static Xex.Term Fshow (Xex.Domain domain, Xex.Variable vari,
2136 ((Context) domain.context).show ();
2140 private static Xex.Term Fhide (Xex.Domain domain, Xex.Variable vari,
2143 ((Context) domain.context).hide ();
2147 private static Xex.Term Fmove (Xex.Domain domain, Xex.Variable vari,
2150 Context ic = (Context) domain.context;
2151 int pos = (args[0].IsInt ? args[0].Intval
2152 : ((Marker) args[0].Objval).Position (ic));
2157 private static Xex.Term Fmark (Xex.Domain domain, Xex.Variable vari,
2160 Marker m = (Marker) args[0].Objval;
2161 m.Mark ((Context) domain.context);
2165 private static Xex.Term Fpushback (Xex.Domain domain, Xex.Variable vari,
2168 Context ic = (Context) domain.context;
2171 ic.pushback (args[0].Intval);
2172 else if (args[0].IsStr)
2173 ic.pushback (new KeySeq (args[0].Strval));
2175 ic.pushback ((KeySeq) args[0].Objval);
2179 private static Xex.Term Fpop (Xex.Domain domain, Xex.Variable vari,
2182 ((Context) domain.context).pop ();
2186 private static Xex.Term Fundo (Xex.Domain domain, Xex.Variable vari,
2189 int n = args.Length == 0 ? -2 : args[0].Intval;
2190 ((Context) domain.context).undo (n);
2194 private static Xex.Term Fcommit (Xex.Domain domain, Xex.Variable vari,
2197 ((Context) domain.context).commit ();
2201 private static Xex.Term Funhandle (Xex.Domain domain, Xex.Variable vari,
2204 ((Context) domain.context).commit ();
2205 args = new Xex.Term[2];
2206 args[0] = args[1] = Tcatch_tag;
2207 return Xex.Fthrow (domain, vari, args);
2210 private static Xex.Term Fshift (Xex.Domain domain, Xex.Variable vari,
2213 Context ic = (Context) domain.context;
2215 if (ic.im.states.TryGetValue (args[0].Symval, out state))
2216 ((Context) domain.context).shift (state);
2218 throw new Exception ("Unknown state: " + args[0].Symval);
2222 private static Xex.Term Fshiftback (Xex.Domain domain, Xex.Variable vari,
2225 ((Context) domain.context).shift (null);
2229 private static Xex.Term Fkey_count (Xex.Domain domain, Xex.Variable vari,
2232 return new Xex.Term (((Context) domain.context).key_head);
2235 private static Xex.Term Fsurrounding_flag (Xex.Domain domain,
2239 return new Xex.Term (((Context) domain.context).SurroundingFlag);
2242 public override string ToString ()
2244 string str = (String.Format ("({0} (title \"{1}\")", tag, title));
2245 if (commands != null)
2247 str += " (commands";
2248 foreach (Command cmd in commands)
2252 if (var_names != null)
2254 str += " (variables";
2255 foreach (Xex.Symbol var in var_names)
2259 if (plugins != null)
2262 foreach (KeyValuePair<MSymbol, Plugin> kv in plugins)
2263 str += " " + kv.Value;
2267 foreach (KeyValuePair<MSymbol, Map> kv in maps)
2268 str += " " + kv.Value;
2270 foreach (KeyValuePair<Xex.Symbol, State> kv in states)
2272 str += " (" + kv.Key + " " + kv.Value.keymap + ")";
2277 public class Context
2279 internal MInputMethod im;
2280 internal Xex.Domain domain;
2281 private Dictionary<MSymbol, Callback> callbacks
2282 = new Dictionary<MSymbol, Callback> ();
2283 private bool active;
2285 private MText status;
2286 private MText produced = new MText ();
2287 internal MText preedit = new MText ();
2288 internal int cursor_pos;
2289 internal Dictionary<Marker, int> marker_positions
2290 = new Dictionary<Marker, int> ();
2291 internal Candidates candidates;
2292 private int candidate_from, candidate_to;
2293 private bool candidate_show;
2294 public bool CandidateShow { get { return candidate_show; } }
2296 private List<State> state_list = new List<State> ();
2297 private Keymap keymap;
2299 // Sequence of input keys.
2300 internal KeySeq keys = new KeySeq ();
2302 // Index into KEYS specifying the next key to handle.
2303 internal int key_head;
2305 private int state_key_head;
2306 private object state_var_values;
2307 private int commit_key_head;
2308 private MText state_preedit;
2309 private int state_pos;
2310 internal MText preceding_text = new MText ();
2311 internal MText following_text = new MText ();
2313 // Set to false before calling the method 'handle_key', and set
2314 // to true when some key is unhandled.
2315 private bool key_unhandled;
2317 // The unhandled key. It has the meaning only when
2318 // 'key_unhandled' is true.
2319 private Key unhandled_key;
2321 internal ChangedStatus changed;
2323 internal void reset ()
2325 status = im.initial_state.title;
2329 marker_positions.Clear ();
2331 candidate_show = false;
2332 keys.keyseq.Clear ();
2333 state_preedit.Del ();
2334 key_head = commit_key_head = 0;
2335 state_list.Clear ();
2336 state_list.Add (im.initial_state);
2337 keymap = im.initial_state.keymap;
2338 key_head = state_key_head = 0;
2342 static MPlist callback_arg = new MPlist ();
2344 static Xex.Term[] catch_args = new Xex.Term[2];
2346 private bool take_action (Xex.Term[] actions)
2348 catch_args[0] = Tcatch_tag;
2349 catch_args[1]= new Xex.Term (domain, Qprogn, actions);
2350 Xex.Term term = new Xex.Term (domain, Qcatch, catch_args);
2351 term = term.Eval (domain);
2352 return (! term.IsSymbol || term.Symval != Tcatch_tag.Symval);
2356 private bool call_callback (MSymbol name, MPlist arg)
2359 if (! callbacks.TryGetValue (name, out callback))
2361 return callback (this, arg);
2364 private bool get_surrounding_text (int len)
2366 if (len < 0 ? -len <= preceding_text.Length
2367 : len <= following_text.Length)
2369 callback_arg.Set (MSymbol.integer, len);
2370 if (! call_callback (Mget_surrounding_text, callback_arg)
2371 || ! callback_arg.IsMText)
2375 preceding_text = callback_arg.Text;
2376 return (-len <= preceding_text.Length);
2378 following_text = callback_arg.Text;
2379 return (len <= following_text.Length);
2382 internal int SurroundingFlag
2384 get { return (callbacks.ContainsKey (Mget_surrounding_text) ? 1 : 0); }
2387 internal int GetSurroundingChar (int pos)
2389 if (! get_surrounding_text (pos < 0 ? pos : pos + 1))
2392 return preceding_text[preceding_text.Length + pos];
2393 return following_text[pos];
2396 private void adjust_markers (int from, int to, object inserted)
2398 int ins = (inserted == null ? 0
2399 : inserted is int ? 1
2400 : ((MText) inserted).Length);
2401 int diff = ins - (to - from);
2403 foreach (Marker m in marker_positions.Keys)
2405 int pos = marker_positions[m];
2409 marker_positions[m] = pos + diff;
2411 marker_positions[m] = from;
2414 if (cursor_pos >= to)
2416 else if (cursor_pos > from)
2420 private void preedit_replace (int from, int to, int c)
2422 preedit.Del (from, to);
2423 preedit.Ins (from, c);
2424 adjust_markers (from, to, c);
2427 private void preedit_replace (int from, int to, MText mt)
2429 preedit[from, to] = mt;
2430 adjust_markers (from, to, mt);
2433 internal void insert (int c)
2435 preedit_replace (cursor_pos, cursor_pos, c);
2436 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2439 internal void insert (string str)
2441 preedit_replace (cursor_pos, cursor_pos, (MText) str);
2442 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2445 private void update_candidate ()
2447 object candidate = candidates.Current;
2449 if (candidate is MText)
2451 preedit_replace (candidate_from, candidate_to, (MText) candidate);
2452 candidate_to = candidate_from + ((MText) candidate).Length;
2456 preedit_replace (candidate_from, candidate_to, (int) candidate);
2457 candidate_to = candidate_from + 1;
2459 preedit.PushProp (candidate_from, candidate_to,
2461 cursor_pos = candidate_from;
2462 changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
2466 internal void insert_candidates (Candidates candidates)
2468 this.candidates = candidates;
2469 candidate_from = candidate_to = cursor_pos;
2470 update_candidate ();
2473 internal void select (int n)
2475 if (candidates != null)
2477 candidates.Select (n);
2478 update_candidate ();
2482 internal int char_at (int pos)
2489 if (preceding_text.Length < -pos)
2491 MPlist plist = new MPlist ();
2492 plist.Push (MSymbol.integer, pos);
2493 if (GetSurroundingText != null
2494 && GetSurroundingText (this, plist)
2496 && preceding_text.Length < plist.Text.Length)
2497 preceding_text = plist.Text;
2499 c = (-pos < preceding_text.Length
2500 ? preceding_text[preceding_text.Length + pos] : -1);
2502 else if (pos >= 0 && pos < preedit.Length)
2506 pos -= preedit.Length;
2507 if (pos >= following_text.Length)
2509 MPlist plist = new MPlist ();
2510 plist.Push (MSymbol.integer, pos + 1);
2511 if (GetSurroundingText != null
2512 && GetSurroundingText (this, plist)
2514 && following_text.Length < plist.Text.Length)
2515 following_text = plist.Text;
2517 c = (pos < following_text.Length ? following_text[pos] : -1);
2522 internal void delete (int pos)
2524 if (pos < cursor_pos)
2525 preedit_replace (pos, cursor_pos, null);
2527 preedit_replace (cursor_pos, pos, null);
2528 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2531 internal void show ()
2533 candidate_show = true;
2534 changed |= ChangedStatus.CandidateShow;
2537 internal void hide ()
2539 candidate_show = false;
2540 changed |= ChangedStatus.CandidateShow;
2543 internal void move (int pos)
2547 else if (pos > preedit.Length)
2548 pos = preedit.Length;
2549 if (pos != cursor_pos)
2552 changed |= ChangedStatus.Preedit;
2556 internal void pushback (int n)
2569 if (key_head > keys.keyseq.Count)
2570 key_head = keys.keyseq.Count;
2574 internal void pushback (KeySeq keyseq)
2578 if (key_head < keys.keyseq.Count)
2579 keys.keyseq.RemoveRange (key_head, keys.keyseq.Count - key_head);
2580 for (int i = 0; i < keyseq.keyseq.Count; i++)
2581 keys.keyseq.Add (keyseq.keyseq[i]);
2584 internal void pop ()
2586 if (key_head < keys.keyseq.Count)
2587 keys.keyseq.RemoveRange (key_head, 1);
2590 internal void undo (int n)
2593 keys.keyseq.RemoveRange (keys.keyseq.Count + n, - n);
2595 keys.keyseq.RemoveRange (n, keys.keyseq.Count - n);
2599 internal void commit ()
2601 produced.Cat (preedit);
2603 changed |= ChangedStatus.Preedit;
2606 internal void shift (State state)
2612 if (state_list.Count > 1)
2613 state_list.RemoveAt (state_list.Count - 1);
2614 state = state_list[state_list.Count - 1];
2619 changed = state != state_list[state_list.Count - 1];
2621 state_list.Add (state);
2623 if (state_list.Count == 1)
2630 state_key_head = key_head;
2631 state_pos = cursor_pos;
2632 state_preedit = preedit.Dup ();
2633 state_var_values = domain.SaveValues ();
2636 status = state.title;
2637 this.changed |= ChangedStatus.StateTitle;
2638 if (state.enter_actions != null)
2639 take_action (state.enter_actions);
2644 public Context (MInputMethod im)
2647 domain = new Xex.Domain (im.domain, this);
2652 public ChangedStatus Changed { get { return changed; } }
2654 public void AddCallback (MSymbol name, Callback callback)
2656 callbacks[name] = callback;
2659 internal object GetCandidates (out int column)
2662 if (cursor_pos == 0)
2664 Candidates candidates
2665 = (Candidates) preedit.GetProp (cursor_pos - 1, Mcandidates);
2666 if (candidates == null)
2668 column = candidates.Column;
2669 return candidates.Current;
2672 private void restore_state ()
2676 private bool handle_key ()
2678 State state = state_list[state_list.Count - 1];
2679 Keymap sub = keymap.Lookup (keys, ref key_head);
2684 if (keymap.map_actions != null)
2687 if (! take_action (keymap.map_actions))
2690 else if (keymap.submaps != null)
2692 for (int i = state_key_head; i < key_head; i++)
2693 preedit_replace (cursor_pos, cursor_pos,
2694 keys.keyseq[i].ToChar ());
2696 if (keymap.submaps == null)
2698 if (keymap.branch_actions != null)
2700 if (! take_action (keymap.branch_actions))
2703 if (keymap != state.keymap)
2709 if (keymap.branch_actions != null)
2711 if (! take_action (keymap.branch_actions))
2714 if (state == state_list[state_list.Count - 1])
2716 if (state == im.initial_state
2717 && key_head < keys.keyseq.Count)
2719 if (keymap != state.keymap)
2721 else if (keymap.branch_actions == null)
2722 shift (im.initial_state);
2728 public bool Toggle ()
2734 public bool UnhandledKey (out Key key)
2736 key = unhandled_key;
2737 return key_unhandled;
2740 public bool Produced (out MText mt)
2743 return (produced.Length > 0);
2747 // true: All keys are handled and there's no text to commit.
2748 // false: Some key is unhandled or there's a text to commit.
2749 // The caller should use methods UnhandledKey and Produced.
2751 public bool Filter (Key key)
2755 key_unhandled = true;
2756 unhandled_key = key;
2759 if (key == Key.Reload)
2761 changed = ChangedStatus.None;
2763 preceding_text.Del ();
2764 following_text.Del ();
2766 key_unhandled = false;
2767 keys.keyseq.Add (key);
2769 while (key_head < keys.keyseq.Count)
2771 if (! handle_key ())
2773 unhandled_key = keys.keyseq[key_head++];
2774 key_unhandled = true;
2780 keys.keyseq.RemoveRange (0, key_head);
2781 return (! key_unhandled && produced.Length == 0);