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 = "==";
79 private static Xex.Term Tnil = new Xex.Term ((Xex.Symbol) "nil");
80 private static Xex.Term Tcatch_tag = new Xex.Term ((Xex.Symbol) "@mimtag");
82 private static Dictionary<MDatabase.Tag, MInputMethod> im_table
83 = new Dictionary<MDatabase.Tag, MInputMethod> ();
85 internal static MInputMethod im_global = null;
88 private enum LoadStatus
98 public enum ChangedStatus
104 CandidateList = 0x08,
105 CandidateIndex = 0x10,
106 CandidateShow = 0x20,
109 private static ChangedStatus CandidateAll = (ChangedStatus.CandidateList
110 | ChangedStatus.CandidateIndex
111 | ChangedStatus.CandidateShow);
113 public enum KeyModifier
116 Shift_L = 0x00400000,
117 Shift_R = 0x00800000,
119 Control_L = 0x01000000,
120 Control_R = 0x02000000,
121 Control = 0x03000000,
136 private static Dictionary<string, uint> keysyms
137 = new Dictionary<string, uint> ();
138 private static Dictionary<string, KeyModifier> keymodifiers
139 = new Dictionary<string, KeyModifier> ();
140 private static uint keysym_base = 0x200000;
141 private static uint char_mask = ~((uint) KeyModifier.All);
142 public static Key Reload;
146 keysyms["bs"] = keysyms["backspace"] = 0x08;
147 keysyms["tab"] = 0x09;
148 keysyms["lf"] = keysyms["linefeed"] = 0x10;
149 keysyms["cr"] = keysyms["return"] = keysyms["enter"] = 0x13;
150 keysyms["esc"] = keysyms["escape"] = 0x1B;
151 keysyms["spc"] = keysyms["space"] = 0x20;
152 keysyms["del"] = keysyms["delete"] = 0x7F;
153 keymodifiers["shift-l"] = KeyModifier.Shift_L;
154 keymodifiers["shift-r"] = KeyModifier.Shift_R;
155 keymodifiers["shift"] = KeyModifier.Shift;
156 keymodifiers["control-l"] = KeyModifier.Control_L;
157 keymodifiers["control-r"] = KeyModifier.Control_R;
158 keymodifiers["control"] = KeyModifier.Control;
159 keymodifiers["alt-l"] = KeyModifier.Alt_L;
160 keymodifiers["alt-r"] = KeyModifier.Alt_R;
161 keymodifiers["alt"] = KeyModifier.Alt;
162 keymodifiers["altgr"] = KeyModifier.AltGr;
163 keymodifiers["super"] = KeyModifier.Super;
164 keymodifiers["hyper"] = KeyModifier.Hyper;
165 Reload = new Key (keysym_base);
166 keysyms["-reload"] = keysym_base++;
169 private static uint decode_keysym (MSymbol keysym)
172 string name = keysym.Name;
174 if (name.Length == 1)
176 name = name.ToLower ();
177 if (! keysyms.TryGetValue (name, out key))
178 keysyms[name] = key = keysym_base++;
182 private static uint combine_modifiers (uint c, KeyModifier modifiers)
184 if (c < 0x7F && c != 0x20)
186 if ((modifiers & KeyModifier.Shift) != KeyModifier.None
187 && Char.IsLower ((char) c))
189 modifiers &= ~KeyModifier.Shift;
190 c = Char.ToUpper ((char) c);
192 if ((modifiers & KeyModifier.Control) != KeyModifier.None)
194 modifiers &= ~KeyModifier.Control;
198 return c | (uint) modifiers;
201 public Key (uint c) { key = c; }
202 public Key (int c) { key = (uint) c; }
204 public Key (uint c, KeyModifier modifiers)
206 key = combine_modifiers (c, modifiers);
209 public Key (MSymbol keysym, KeyModifier modifiers)
211 key = combine_modifiers (decode_keysym (keysym), modifiers);
214 public Key (MSymbol keysym)
216 string str = keysym.Name;
217 int len = str.Length;
219 KeyModifier modifiers = KeyModifier.None;
221 for (i = 0; i + 2 < len && str[i + 1] == '-'; i += 2)
224 modifiers |= KeyModifier.Shift;
225 else if (str[i] == 'C')
226 modifiers |= KeyModifier.Control;
227 else if (str[i] == 'A')
228 modifiers |= KeyModifier.Alt;
229 else if (str[i] == 'G')
230 modifiers |= KeyModifier.AltGr;
231 else if (str[i] == 's')
232 modifiers |= KeyModifier.Super;
233 else if (str[i] == 'H')
234 modifiers |= KeyModifier.Hyper;
237 key = combine_modifiers (str[i], modifiers);
239 key = combine_modifiers (decode_keysym (keysym), modifiers);
242 public Key (MPlist plist)
244 KeyModifier modifiers = KeyModifier.None;
247 for (p = plist; ! p.IsEmpty; p = p.next)
251 if (! p.next.IsEmpty)
252 throw new Exception ("Invalid Key: " + plist);
255 else if (! p.IsSymbol)
256 throw new Exception ("Invalid Key: " + plist);
259 string name = p.Symbol.Name.ToLower ();
262 if (! keymodifiers.TryGetValue (name, out m))
267 if (p.IsEmpty || ! p.next.IsEmpty)
268 throw new Exception ("Invalid Key: " + plist);
270 key = combine_modifiers ((uint) p.Integer, modifiers);
272 key = combine_modifiers (decode_keysym (p.Symbol), modifiers);
275 public bool HasModifier
277 get { return ((key & (uint) KeyModifier.All) != 0); }
280 public static bool operator== (Key k1, Key k2)
282 return k1.key == k2.key;
285 public static bool operator!= (Key k1, Key k2)
287 return k1.key != k2.key;
290 public override bool Equals (object o) { return key == ((Key) o).key; }
292 public override int GetHashCode () { return (int) key; }
294 public bool Match (Key k)
298 if ((k.key & char_mask) != (key & char_mask))
300 KeyModifier m1 = ((KeyModifier) key) & KeyModifier.All;
301 KeyModifier m2 = ((KeyModifier) k.key) & KeyModifier.All;
302 return (((m1 & KeyModifier.Shift) == (m2 & KeyModifier.Shift)
303 || ((m1 & KeyModifier.Shift) == KeyModifier.Shift
304 && (m2 & KeyModifier.Shift) != KeyModifier.None))
305 && ((m1 & KeyModifier.Control) == (m2 & KeyModifier.Control)
306 || ((m1 & KeyModifier.Control) == KeyModifier.Control
307 && (m2 & KeyModifier.Control) != KeyModifier.None))
308 && ((m1 & KeyModifier.Alt) == (m2 & KeyModifier.Alt)
309 || ((m1 & KeyModifier.Alt) == KeyModifier.Alt
310 && (m2 & KeyModifier.Alt) != KeyModifier.None))
311 && ((m1 & KeyModifier.High) == (m2 & KeyModifier.High)));
316 return (int) (key & 0x1FFFFF);
319 public override string ToString ()
324 foreach (KeyValuePair<string, uint> kv in keysyms)
325 if ((uint) c == kv.Value)
333 KeyModifier m = ((KeyModifier) key) & KeyModifier.All;
335 if (m != KeyModifier.None)
337 if ((m & KeyModifier.Shift) != KeyModifier.None)
339 if ((m & KeyModifier.Control) != KeyModifier.None)
341 if ((m & KeyModifier.Alt) != KeyModifier.None)
343 if ((m & KeyModifier.AltGr) != KeyModifier.None)
345 if ((m & KeyModifier.Super) != KeyModifier.None)
347 if ((m & KeyModifier.Hyper) != KeyModifier.None)
354 internal class KeySeq : Xex.TermValue
356 public List<Key> keyseq = new List<Key> ();
358 public override Xex.TermValue Clone ()
360 KeySeq ks = new KeySeq ();
361 ks.keyseq.InsertRange (0, keyseq);
367 public KeySeq (MPlist plist)
369 foreach (MPlist p in plist)
372 keyseq.Add (new Key (p.Symbol));
373 else if (p.IsInteger)
374 keyseq.Add (new Key ((char) p.Integer));
376 keyseq.Add (new Key (p.Plist));
378 throw new Exception ("Invalid Key Sequence: " + plist);
382 public KeySeq (MText mt) : base ()
384 for (int i = 0; i < mt.Length; i++)
385 keyseq.Add (new Key ((uint) mt[i]));
388 public KeySeq (List<Xex.Term> list)
390 int len = list.Count;
392 for (int i = 0; i < len; i++)
395 keyseq.Add (new Key (list[i].Intval));
396 else if (list[i].IsStr)
397 keyseq.Add (new Key (list[i].Strval));
398 else if (list[i].IsSymbol)
399 keyseq.Add (new Key ((string) list[i].Symval));
401 throw new Exception ("Invalid key: " + list[i]);
405 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
407 Xex.Term term = new Xex.Term (domain, node.FirstChild).Eval (domain);
408 return (term.IsStr ? new KeySeq ((MText) term.Strval)
409 : new KeySeq (term.Listval));
412 public override string ToString ()
415 foreach (Key key in keyseq)
416 if (key.HasModifier || key.ToChar () < 0x20)
419 foreach (Key k in keyseq)
423 mt.Cat (k.ToString ());
425 return (string) mt.Cat (")");
428 foreach (Key k in keyseq)
432 if (c == '\\' || c == '"')
436 return (string) mt.Cat ("\"");
443 public MText description;
444 internal List<KeySeq> keys;
446 public Command (MPlist p)
450 description = parse_description (p);
451 if (description == null)
452 description = "No description";
453 keys = new List<KeySeq> ();
454 for (p = p.next; ! p.IsEmpty; p = p.next)
457 keys.Add (new KeySeq (p.Text));
459 keys.Add (new KeySeq (p.Plist));
463 public Command (XmlNode node)
465 name = node.Attributes[0].Value;
466 keys = new List<KeySeq> ();
467 for (node = node.FirstChild; node != null; node = node.NextSibling)
469 if (node.Name == "description")
470 description = parse_description (node);
471 else if (node.Name == "keyseq")
472 keys.Add ((KeySeq) KeySeq.parser (null, node));
476 public override string ToString ()
478 string str = "(" + name + " \"" + (string) description;
479 foreach (KeySeq keyseq in keys)
485 internal class Plugin
488 private Assembly assembly;
489 private Type plugin_type;
491 public Plugin (string name)
496 public MethodInfo GetMethod (Xex.Symbol name)
498 if (assembly == null)
500 assembly = Assembly.LoadFrom (name + ".dll");
501 plugin_type = assembly.GetType ("M17n.MInputMethod.Plugin");
504 MethodInfo info = plugin_type.GetMethod ((string) name);
506 throw new Exception ("Invalid plugin method: " + name);
510 public override string ToString ()
512 return String.Format ("(module {0}", name);
516 internal class PluginMethod : Xex.Function
518 private Plugin plugin;
519 private MethodInfo method_info;
520 object[] parameters = new object[2];
522 public PluginMethod (Plugin plugin, string name)
523 : base ((Xex.Symbol) name, 0, -1)
525 this.plugin = plugin;
528 public override Xex.Term Call (Xex.Domain domain, Xex.Variable vari,
531 args = (Xex.Term[]) args.Clone ();
532 for (int i = 0; i < args.Length; i++)
534 args[i] = args[i].Eval (domain);
538 if (method_info == null)
539 method_info = plugin.GetMethod (name);
540 parameters[0] = domain.context;
541 parameters[1] = args;
542 return (Xex.Term) method_info.Invoke (null, parameters);
546 internal abstract class Marker : Xex.TermValue
548 private Xex.Symbol name;
550 private Marker (Xex.Symbol name)
555 public abstract int Position (Context ic);
556 public virtual void Mark (Context ic)
558 throw new Exception ("Can't set predefined marker: " + name);
560 public virtual int CharAt (Context ic)
562 return ic.preedit[Position (ic)];
564 public override Xex.TermValue Clone () { return this; }
566 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
568 return Get ((Xex.Symbol) node.InnerText);
571 public class Named : Marker
573 public Named (Xex.Symbol name) : base (name) { }
575 public override int Position (Context ic)
579 if (ic.marker_positions.TryGetValue (this, out pos))
584 public override void Mark (Context ic)
586 ic.marker_positions[this] = ic.cursor_pos;
590 public class Predefined : Marker
593 public Predefined (Xex.Symbol 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 (Xex.Symbol 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 (Xex.Symbol 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<Xex.Symbol,Predefined> predefined_markers;
677 predefined_markers = new Dictionary<Xex.Symbol, Predefined> ();
679 = new Xex.Symbol[] {"@<", "@>", "@-", "@+", "@[", "@]" };
680 foreach (Xex.Symbol s in symlist)
681 predefined_markers[s] = new Predefined (s);
684 public static Marker Get (Xex.Symbol name)
690 if (predefined_markers.TryGetValue (name, out pred))
693 throw new Exception ("Invalid marker name: " + name);
694 if (Char.IsDigit (str[1]))
695 return new PredefinedAbsolute (name);
696 if (str.Length == 2 || name == Qat_minus_zero
697 || ! (str[1] == '-' || str[1] == '+'))
698 throw new Exception ("Invalid marker name: " + name);
699 return new PredefinedSurround (name);
701 return new Named (name);
705 internal class Candidates
712 public Block (int index, Xex.Term term)
716 Data = (MText) term.Strval;
719 MPlist plist = new MPlist ();
721 foreach (Xex.Term t in term.Listval)
722 p = p.Add (MSymbol.mtext, (MText) t.Strval);
727 public Block (int index, MPlist plist)
732 else if (plist.IsPlist)
735 throw new Exception ("Invalid candidate: " + plist);
740 get { return (Data is MText
741 ? ((MText) Data).Length
742 : ((MPlist) Data).Count); }
745 public object this[int i]
748 if (Data is MText) return ((MText) Data)[i];
749 return ((MPlist) Data)[i];
754 private Block[] blocks;
756 private int index = 0;
757 public object[] group;
759 private bool IsFixed { get { return group != null; } }
762 Block last = blocks[blocks.Length - 1];
763 return last.Index + last.Count; }
767 get { return (IsFixed ? index % group.Length
768 : index - blocks[row].Index); }
771 public object Group {
772 get { return (IsFixed ? group : blocks[row].Data); }
775 public int GroupLength
780 int nitems = group.Length;
781 int start = index - (index % nitems);
783 return (start + nitems <= total ? nitems : total - start);
785 return blocks[row].Count;
789 public object Current {
791 return (IsFixed ? group[index % group.Length]
792 : blocks[row][index - blocks[row].Index]);
796 public Candidates (MPlist list, int column)
798 int nblocks = list.Count;
800 blocks = new Block[nblocks];
801 for (int i = 0, start = 0; i < nblocks; i++, list = list.next)
802 start += (blocks[i] = new Block (index, list)).Count;
804 group = new object[column];
807 public Candidates (List<Xex.Term> list, int column)
809 int nblocks = list.Count;
811 blocks = new Block[nblocks];
812 for (int i = 0, start = 0; i < nblocks; i++)
813 start += (blocks[i] = new Block (index, list[i])).Count;
815 group = new object[column];
818 public static void Detach (Context ic)
820 ic.preedit.PopProp (0, ic.preedit.Length, Mcandidates);
821 ic.candidates = null;
822 ic.changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
826 // Fill the array "group" by candidates stating from INDEX.
827 // INDEX must be a multiple of "column". Set NTIMES to the
828 // number of valid candidates in "group". Update "block" if
829 // necessary. Return "group".
831 private int fill_group (int start)
833 int nitems = group.Length;
838 while (start < b.Index)
841 while (start >= b.Index + b.Count)
847 for (int i = 0; i < nitems; i++, start++)
852 if (r == blocks.Length)
863 // Update "row" to what contains the first candidate of
864 // the previous candidate-group, update "current_index", and
865 // update "group" if necessary. Return the previous
866 // candidate-group. Set NITEMS to the number of valid
867 // candidates contained in that group.
869 public int PrevGroup ()
876 nitems = group.Length;
877 if ((index -= col + nitems) < 0)
878 index = (Total / nitems) * nitems;
879 nitems = fill_group (index);
883 row = row > 0 ? row-- : blocks.Length - 1;
884 nitems = blocks[row].Count;
885 index = blocks[row].Index;
887 index += col < nitems ? col : nitems - 1;
891 public int NextGroup ()
898 nitems = group.Length;
899 if ((index += nitems - col) >= Total)
901 nitems = fill_group (index);
905 row = row < blocks.Length - 1 ? row + 1 : 0;
906 nitems = blocks[row].Count;
907 index = blocks[row].Count;
909 index += col < nitems ? col : nitems - 1;
919 int nitems = PrevGroup ();
920 index += col < nitems - 1 ? col : nitems - 1;
929 int nitems = GroupLength;
931 if (col == nitems - 1)
933 nitems = NextGroup ();
947 index += GroupLength - (Column + 1);
950 public void Select (int col)
952 int maxcol = GroupLength - 1;
955 index = index - Column + col;
959 internal class Selector : Xex.TermValue
961 static new Dictionary<MSymbol, Selector> selectors;
965 selectors = new Dictionary<MSymbol, Selector> ();
966 MSymbol[] symlist = new MSymbol[] { "@<", "@=", "@>", "@-", "@+",
968 foreach (MSymbol s in symlist)
969 selectors[s] = new Selector (s);
970 selectors["@first"] = new Selector ('<');
971 selectors["@current"] = new Selector ('=');
972 selectors["@last"] = new Selector ('>');
973 selectors["@previous"] = new Selector ('-');
974 selectors["@next"] = new Selector ('+');
975 selectors["@previous-candidate-change"] = new Selector ('[');
976 selectors["@next-candidate-change"] = new Selector (']');
981 private Selector (MSymbol sym) { tag = sym.Name[1]; }
983 private Selector (char tag) { this.tag = tag; }
985 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
987 return Get ((MSymbol) node.InnerText);
990 public static Xex.TermValue Get (MSymbol name)
993 if (! selectors.TryGetValue (name, out selector))
994 throw new Exception ("Invalid selector name: " + name);
998 public override Xex.TermValue Clone () { return this; }
1000 public void Select (Candidates candidates)
1004 case '<': candidates.First (); break;
1005 case '>': candidates.Last (); break;
1006 case '-': candidates.Prev (); break;
1007 case '+': candidates.Next (); break;
1008 case '[': candidates.PrevGroup (); break;
1009 case ']': candidates.NextGroup (); break;
1017 public MSymbol name;
1018 public List<Entry> entries = new List<Entry> ();
1020 public Map (MSymbol name) { this.name = name; }
1024 public KeySeq keyseq;
1025 public Xex.Term[] actions;
1027 public Entry (Xex.Domain domain, KeySeq keyseq, Xex.Term[] actions)
1029 this.keyseq = keyseq;
1030 this.actions = actions;
1034 public override string ToString ()
1036 string str = "(" + name;
1037 foreach (Entry e in entries)
1038 str += " " + e.keyseq.ToString ();
1043 internal class Keymap
1045 public Dictionary<Key, Keymap> submaps;
1046 public Xex.Term[] map_actions, branch_actions;
1048 public Keymap () { }
1050 public void Add (KeySeq keys, int index,
1051 Xex.Term[] map_actions, Xex.Term[] branch_actions)
1053 if (index == keys.keyseq.Count)
1055 this.map_actions = map_actions;
1056 this.branch_actions = branch_actions;
1060 Key key = keys.keyseq[index];
1063 if (submaps == null)
1064 submaps = new Dictionary<Key, Keymap> ();
1066 submaps.TryGetValue (key, out sub);
1068 submaps[key] = sub = new Keymap ();
1069 sub.Add (keys, index + 1, map_actions, branch_actions);
1073 public void AddMap (Map map, Xex.Term[] branch_actions)
1075 foreach (Map.Entry entry in map.entries)
1076 Add (entry.keyseq, 0, entry.actions, branch_actions);
1079 public Keymap Lookup (KeySeq keys, ref int index)
1083 if (index < keys.keyseq.Count
1085 && submaps.TryGetValue (keys.keyseq[index], out sub))
1088 return sub.Lookup (keys, ref index);
1093 private void describe (MText mt, KeySeq keyseq)
1095 if (map_actions != null || branch_actions != null)
1099 mt.Cat ('(').Cat (keyseq.ToString ());
1100 if (map_actions != null)
1101 foreach (Xex.Term term in map_actions)
1102 mt.Cat (' ').Cat (term.ToString ());
1103 if (branch_actions != null)
1104 foreach (Xex.Term term in branch_actions)
1105 mt.Cat (' ').Cat (term.ToString ());
1108 if (submaps != null)
1109 foreach (KeyValuePair<Key, Keymap> kv in submaps)
1111 keyseq.keyseq.Add (kv.Key);
1112 kv.Value.describe (mt, keyseq);
1113 keyseq.keyseq.RemoveAt (keyseq.keyseq.Count - 1);
1117 public override string ToString ()
1120 KeySeq keyseq = new KeySeq ();
1122 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;
1147 keymap = new Keymap ();
1148 for (node = node.FirstChild; node != null; node = node.NextSibling)
1150 if (node.Name == Qstate_hook)
1151 enter_actions = Xex.ParseTerms (im.domain, node.FirstChild);
1152 else if (node.Name == Qcatch_all_branch)
1153 fallback_actions = Xex.ParseTerms (im.domain, node.FirstChild);
1154 else if (node.Name == Qbranch)
1156 MSymbol mapname = node.Attributes[Qmname].Value;
1158 if (im.maps.TryGetValue (mapname, out map))
1159 keymap.AddMap (map, Xex.ParseTerms (im.domain,
1162 throw new Exception ("Unknown map: " + mapname);
1167 public State (MInputMethod im, MPlist plist)
1169 if (! plist.IsSymbol)
1170 throw new Exception ("Invalid state: " + plist);
1171 this.name = plist.Symbol.Name;
1175 this.title = plist.Text;
1178 keymap = new Keymap ();
1179 for (; ! plist.IsEmpty; plist = plist.next)
1181 if (! plist.IsPlist)
1182 throw new Exception ("Invalid branch: " + plist);
1183 MPlist p = plist.Plist;
1185 throw new Exception ("Invalid branch: " + p);
1186 MSymbol mapname = p.Symbol;
1187 if (mapname == MSymbol.t)
1188 enter_actions = im.parse_actions (p.next, false);
1189 else if (mapname == MSymbol.nil)
1190 fallback_actions = im.parse_actions (p.next, false);
1194 if (im.maps.TryGetValue (mapname, out map))
1195 keymap.AddMap (map, im.parse_actions (p.next, false));
1197 throw new Exception ("Unknown map: " + mapname);
1202 public override string ToString ()
1204 MText mt = "(" + name;
1207 mt.Cat (" \"" + title + "\"");
1208 mt.Cat (keymap.ToString ());
1209 return (string) mt + ")";
1214 internal Xex.Domain domain = new Xex.Domain (im_domain, null);
1216 private LoadStatus load_status = LoadStatus.None;
1217 private MDatabase.Tag tag;
1218 private MDatabase mdb;
1220 private MText description;
1221 internal MText title;
1222 internal Command[] commands;
1223 internal Xex.Symbol[] var_names;
1224 internal Dictionary<MSymbol, Plugin> plugins;
1225 internal Dictionary<MSymbol, Map> maps;
1226 internal Dictionary<Xex.Symbol, State> states;
1227 internal State initial_state;
1229 static MInputMethod ()
1231 im_domain.DefTerm ("keyseq", KeySeq.parser);
1232 im_domain.DefTerm ("marker", Marker.parser);
1233 im_domain.DefTerm ("selector", Selector.parser);
1235 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
1236 im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, -1);
1237 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
1238 im_domain.DefSubr (Fselect, "select", false, 1, 1);
1239 im_domain.DefSubr (Fshow, "show", false, 0, 0);
1240 im_domain.DefSubr (Fhide, "hide", false, 0, 0);
1241 im_domain.DefSubr (Fmove, "move", false, 1, 1);
1242 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
1243 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
1244 im_domain.DefSubr (Fpop, "pop", false, 0, 0);
1245 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
1246 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
1247 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
1248 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
1249 im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
1250 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
1251 im_domain.DefSubr (Fkey_count, "key-count", false, 1, 1);
1252 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag",
1255 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, "*", "*", "*");
1256 List<MDatabase> list = MDatabase.List (tag);
1257 M17n.DebugPrint ("Found {0} input methods\n", list.Count);
1258 foreach (MDatabase mdb in list)
1259 im_table[mdb.tag] = new MInputMethod (mdb.tag);
1263 private MInputMethod (MDatabase.Tag tag)
1268 // Instance Properties
1269 public MSymbol Language { get { return tag[1]; } }
1270 public MSymbol Name { get { return tag[2]; } }
1271 public MSymbol SubName { get { return tag[3]; } }
1273 public bool Info (out MText description,
1275 out Xex.Variable[] variables,
1276 out Command[] commands)
1278 if ((load_status & LoadStatus.Header) != LoadStatus.Header
1279 && ! load_header ())
1287 description = this.description;
1289 if (var_names == null)
1293 variables = new Xex.Variable[var_names.Length];
1295 foreach (Xex.Symbol name in var_names)
1296 variables[i++] = domain.GetVar (name, false);
1298 commands = this.commands;
1302 public static MInputMethod Find (MSymbol language, MSymbol name)
1304 return Find (language, name, MSymbol.nil);
1307 public static MInputMethod Find (MSymbol language, MSymbol name,
1310 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, language,
1314 return (im_table.TryGetValue (tag, out im) ? im : null);
1319 return ((load_status == LoadStatus.Full) || load_body ());
1322 public static MInputMethod[] List ()
1324 MInputMethod[] array = new MInputMethod[im_table.Count];
1327 foreach (KeyValuePair<MDatabase.Tag, MInputMethod> kv in im_table)
1328 array[i++] = kv.Value;
1332 private bool load_header ()
1334 mdb = MDatabase.Find (tag);
1337 mdb.name_table = Xex.Symbol.Table;
1339 MSymbol format = mdb.Format;
1341 if (format == MSymbol.plist)
1342 load ((MPlist) mdb.Load (Mmap), false);
1345 XmlDocument doc = (XmlDocument) mdb.Load (Mmap_list);
1346 load (doc.DocumentElement, false);
1348 } catch (Exception e) {
1349 Console.WriteLine ("{0}\n", e);
1350 load_status = LoadStatus.Error;
1353 load_status |= LoadStatus.Header;
1357 private bool load_body ()
1359 mdb = MDatabase.Find (tag);
1362 mdb.name_table = Xex.Symbol.Table;
1364 object obj = mdb.Load ();
1366 load ((MPlist) obj, true);
1368 load ((XmlDocument) obj, true);
1369 } catch (Exception e) {
1370 Console.WriteLine (e);
1371 load_status = LoadStatus.Error;
1374 load_status = LoadStatus.Full;
1378 private void add_default_state ()
1380 Xex.Symbol Qinit = "init";
1381 State state = new State (Qinit, null);
1382 foreach (KeyValuePair<MSymbol, Map>kv in maps)
1383 state.keymap.AddMap (kv.Value, null);
1384 states[Qinit] = initial_state = state;
1387 private void load (MPlist plist, bool full)
1389 maps = new Dictionary<MSymbol, Map> ();
1390 states = new Dictionary<Xex.Symbol, State> ();
1392 for (; ! plist.IsEmpty; plist = plist.next)
1395 MPlist pl = plist.Plist;
1398 MSymbol sym = pl.Symbol;
1401 if (sym == Mdescription)
1402 description = parse_description (pl);
1403 else if (sym == Mtitle)
1408 else if (sym == Mvariable)
1409 parse_variables (pl);
1410 else if (sym == Mcommand)
1411 parse_commands (pl);
1416 else if (sym == Minclude)
1418 else if (sym == Mmacro)
1420 else if (sym == Mmap)
1422 else if (sym == Mstate)
1427 if (description == null)
1428 description = (MText) "No description";
1430 title = new MText (tag[2].Name);
1431 if (commands == null)
1432 commands = new Command[0];
1435 if (states.Count == 0)
1436 add_default_state ();
1439 private void load (XmlNode node, bool full)
1441 bool skip_header = load_status == LoadStatus.Header;
1443 maps = new Dictionary<MSymbol, Map> ();
1444 states = new Dictionary<Xex.Symbol, State> ();
1446 if (node.NodeType == XmlNodeType.Document)
1447 node = node.FirstChild;
1448 while (node.NodeType != XmlNodeType.Element)
1449 node = node.NextSibling;
1450 for (node = node.FirstChild; node != null; node = node.NextSibling)
1452 if (node.NodeType != XmlNodeType.Element)
1456 if (node.Name == "description")
1457 description = parse_description (node);
1458 else if (node.Name == "title")
1459 title = parse_title (node);
1460 else if (node.Name == "variable-list")
1461 parse_variables (node);
1462 else if (node.Name == "command-list")
1463 parse_commands (node);
1467 if (node.Name == "module-list")
1468 parse_plugins (node);
1469 else if (node.Name == "macro-list")
1470 parse_macros (node);
1471 else if (node.Name == "map-list")
1473 else if (node.Name == "state-list")
1474 parse_states (node);
1477 if (description == null)
1478 description = (MText) "No description";
1480 title = new MText (tag[2].Name);
1481 if (commands == null)
1482 commands = new Command[0];
1485 if (states.Count == 0)
1486 add_default_state ();
1489 private static MText parse_description (MPlist plist)
1495 plist = plist.Plist;
1496 if (plist.IsSymbol && plist.Symbol == (MSymbol) "_"
1497 && plist.next.IsMText)
1498 return plist.next.Text;
1503 private static MText parse_description (XmlNode node)
1505 if (node.HasChildNodes)
1506 node = node.FirstChild;
1507 return node.InnerText;
1510 private static MText parse_title (XmlNode node)
1512 return node.InnerText;
1515 private void new_variable (Xex.Symbol name, string desc, int val,
1516 MPlist pl, Xex.Variable vari)
1524 int nrange = pl.Count;
1525 range = new int[nrange * 2];
1526 for (int i = 0; i < nrange; i++)
1530 MPlist p = pl.Plist;
1532 if (! p.IsInteger || ! p.next.IsInteger)
1533 throw new Exception ("Invalid range: " + p);
1534 range[i * 2] = p.Integer;
1535 range[i * 2 + 1] = p.next.Integer;
1537 else if (pl.IsInteger)
1538 range[i * 2] = range[i * 2 + 1] = pl.Integer;
1540 throw new Exception ("Invalid range: " + pl);
1544 domain.Defvar (new Xex.Variable.Int (name, desc, val, range));
1547 Xex.Term term = new Xex.Term (val);
1549 vari.DefaultValue = term;
1554 private void new_variable (Xex.Symbol name, string desc, MText val,
1555 MPlist pl, Xex.Variable vari)
1563 range = new string[pl.Count * 2];
1564 for (int i = 0; i < range.Length; i++)
1567 range[i] = (string) pl.Text;
1569 throw new Exception ("Invalid range: " + pl);
1573 domain.Defvar (new Xex.Variable.Str (name, desc, (string) val, range));
1576 Xex.Term term = new Xex.Term ((string) val);
1578 vari.DefaultValue = term;
1583 private void new_variable (Xex.Symbol name, string desc, MSymbol val,
1584 MPlist pl, Xex.Variable vari)
1587 Xex.Symbol sym = val.Name;
1593 range = new Xex.Symbol[pl.Count * 2];
1594 for (int i = 0; i < range.Length; i++)
1597 range[i] = pl.Symbol.Name;
1599 throw new Exception ("Invalid range: " + pl);
1603 domain.Defvar (new Xex.Variable.Sym (name, desc, sym, range));
1606 Xex.Term term = new Xex.Term (sym);
1608 vari.DefaultValue = term;
1613 private Xex.Variable get_global_var (Xex.Symbol name)
1615 if (im_global == null || this != im_global)
1617 tag = new MDatabase.Tag (Minput_method, MSymbol.t, MSymbol.nil,
1619 im_global = im_table[tag];
1620 if (! im_global.Open ())
1621 throw new Exception ("Failed to load global");
1623 return im_global.domain.GetVar (name, false);
1626 private void parse_variables (MPlist plist)
1628 var_names = new Xex.Symbol[plist.Count];
1630 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1632 if (! plist.IsPlist || ! plist.Plist.IsSymbol)
1633 throw new Exception ("Invalid variable: " + plist);
1635 MPlist p = plist.Plist;
1636 Xex.Symbol name = (Xex.Symbol) p.Symbol.Name;
1637 var_names[i] = name;
1639 string desc = (string) parse_description (p);
1640 Xex.Variable vari = get_global_var (name);
1642 domain.Defvar (vari);
1648 new_variable (name, desc, p.Integer, p.next, vari);
1650 new_variable (name, desc, p.Text, p.next, vari);
1651 else if (p.IsSymbol)
1652 new_variable (name, desc, p.Symbol, p.next, vari);
1654 throw new Exception ("Invalid variable type: " + p.val);
1659 private void parse_variables (XmlNode node)
1661 XmlNodeList node_list = node.ChildNodes;
1663 var_names = new Xex.Symbol[node_list.Count];
1664 for (int i = 0; i < node_list.Count; i++)
1666 Xex.Symbol name = node_list[i].Attributes[0].Value;
1667 Xex.Variable vari = get_global_var (name);
1669 domain.Defvar (vari);
1670 domain.Defvar (node_list[i]);
1671 var_names[i] = name;
1675 private void parse_commands (MPlist plist)
1677 commands = new Command[plist.Count];
1679 for (int i = 0; ! plist.IsEmpty; plist = plist.next)
1680 if (plist.IsPlist && plist.Plist.IsSymbol)
1681 commands[i++] = new Command (plist.Plist);
1684 private void parse_commands (XmlNode node)
1686 XmlNodeList node_list = node.ChildNodes;
1688 commands = new Command[node_list.Count];
1689 for (int i = 0; i < node_list.Count; i++)
1691 if (node_list[i].NodeType == XmlNodeType.Element)
1692 commands[i] = new Command (node_list[i]);
1696 private void parse_plugins (MPlist plist)
1698 plugins = new Dictionary<MSymbol, Plugin> ();
1700 for (; ! plist.IsEmpty; plist = plist.Next)
1702 MPlist p = plist.Plist;
1703 MSymbol sym = p.Symbol;
1704 Plugin plugin = new Plugin (sym.Name);
1706 for (p = p.next; ! p.IsEmpty; p = p.next)
1708 Xex.Function func = new PluginMethod (plugin, p.Symbol.Name);
1709 domain.Defun (func);
1714 private void parse_plugins (XmlNode node)
1716 plugins = new Dictionary<MSymbol, Plugin> ();
1718 foreach (XmlNode n in node.ChildNodes)
1720 Plugin plugin = new Plugin (n.Attributes[0].Value);
1721 foreach (XmlNode nn in n.ChildNodes)
1723 Xex.Function func = new PluginMethod (plugin,
1724 nn.Attributes[0].Value);
1725 domain.Defun (func);
1730 private void parse_macros (XmlNode node)
1732 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1733 if (nn.NodeType == XmlNodeType.Element)
1734 domain.Defun (nn, true);
1735 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1736 if (nn.NodeType == XmlNodeType.Element)
1737 domain.Defun (nn, false);
1740 private void parse_maps (XmlNode node)
1742 for (node = node.FirstChild; node != null; node = node.NextSibling)
1743 if (node.Name == Qmap)
1745 MSymbol name = node.Attributes[0].Value;
1746 Map map = new Map (name);
1748 for (XmlNode nd = node.FirstChild; nd != null; nd = nd.NextSibling)
1749 if (nd.Name == Qrule)
1751 XmlNode n = nd.FirstChild;
1752 if (n.Name != Qkeyseq)
1754 KeySeq keyseq = (KeySeq) KeySeq.parser (domain, n);
1755 Xex.Term[] actions = Xex.ParseTerms (domain, n.NextSibling);
1756 map.entries.Add (new Map.Entry (domain, keyseq, actions));
1761 private void parse_states (MPlist plist)
1763 for (; ! plist.IsEmpty; plist = plist.next)
1766 State state = new State (this, plist.Plist);
1767 states[state.name] = state;
1771 private void parse_states (XmlNode node)
1773 for (node = node.FirstChild; node != null; node = node.NextSibling)
1774 if (node.Name == Qstate)
1776 State state = new State (this, node);
1777 states[state.name] = state;
1781 private void parse_include (MPlist plist)
1783 if (! plist.IsPlist)
1785 MPlist p = plist.Plist;
1786 MSymbol language, name, subname;
1787 language = p.Symbol;
1790 name = subname = MSymbol.nil;
1796 subname = MSymbol.nil;
1801 MInputMethod im = MInputMethod.Find (language, name, subname);
1807 if (! plist.IsSymbol)
1809 MSymbol target_type = plist.Symbol;
1811 MSymbol target_name = MSymbol.nil;
1813 target_name = plist.Symbol;
1814 if (target_type == Mmacro)
1816 if (target_name == MSymbol.nil)
1817 im.domain.CopyFunc (domain);
1819 im.domain.CopyFunc (domain, (Xex.Symbol) target_name.Name);
1821 else if (target_type == Mmap)
1823 if (target_name == MSymbol.nil)
1825 foreach (KeyValuePair<MSymbol, Map> kv in im.maps)
1826 maps[kv.Key] = kv.Value;
1831 if (im.maps.TryGetValue (target_name, out map))
1832 maps[target_name] = map;
1835 else if (target_type == Mstate)
1837 if (target_name == MSymbol.nil)
1839 foreach (KeyValuePair<Xex.Symbol, State> kv in im.states)
1840 states[kv.Key] = kv.Value;
1844 Xex.Symbol state_name = target_name.Name;
1846 if (im.states.TryGetValue (state_name, out state))
1847 states[state_name] = state;
1852 private Xex.Term parse_cond (MPlist plist)
1854 Xex.Term[] args = new Xex.Term[plist.Count];
1856 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1858 if (! plist.IsPlist)
1859 throw new Exception ("Invalid cond args: " + plist);
1860 MPlist p = plist.Plist;
1861 List<Xex.Term> arg = new List<Xex.Term> (parse_actions (p, false));
1862 args[i] = new Xex.Term (arg);
1864 return new Xex.Term (domain, Qcond, args);
1867 private Xex.Term parse_insert (MPlist plist)
1872 arg = new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1873 else if (plist.IsMText)
1874 arg = new Xex.Term ((string) plist.Text);
1875 else if (plist.IsInteger)
1876 arg = new Xex.Term (plist.Integer);
1877 else if (plist.IsPlist)
1879 MPlist pl = plist.Plist;
1881 args = new Xex.Term[pl.Count];
1883 for (i = 0; ! pl.IsEmpty; i++, pl = pl.next)
1886 args[i] = new Xex.Term ((string) pl.Text);
1887 else if (pl.IsPlist)
1889 List<Xex.Term> list = new List<Xex.Term> ();
1890 for (MPlist p = pl.Plist; ! p.IsEmpty; p = p.next)
1893 list.Add (new Xex.Term ((string) p.Text));
1895 throw new Exception ("Invalid candidates: " + p);
1899 throw new Exception ("Invalid candidates: " + pl);
1901 return new Xex.Term (domain, Qinsert_candidates, args);
1904 throw new Exception ("Invalid arg to insert: " + plist);
1905 args = new Xex.Term[1];
1907 return new Xex.Term (domain, Qinsert, args);
1910 private Xex.Term parse_select (MPlist plist)
1912 Xex.Term[] args = new Xex.Term[1];
1913 if (plist.IsInteger)
1914 args[0] = new Xex.Term (plist.Integer);
1915 else if (! plist.IsSymbol)
1916 throw new Exception ("Invalid arg to select: " + plist);
1917 else if (plist.Symbol.Name[0] == '@')
1918 args[0] = new Xex.Term (Selector.Get (plist.Symbol));
1920 args[0] = new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1921 return new Xex.Term (domain, Qselect, args);
1924 private Xex.Term parse_funcall_with_marker (MPlist plist, Xex.Symbol func)
1926 Xex.Term[] args = new Xex.Term[1];
1927 if (plist.IsInteger && func != Qmark)
1928 args[0] = new Xex.Term (plist.Integer);
1929 else if (plist.IsSymbol)
1930 args[0] = new Xex.Term (Marker.Get ((Xex.Symbol) plist.Symbol.Name));
1932 throw new Exception ("Invalid arg to " + func + ": " + plist);
1933 return new Xex.Term (domain, func, args);
1936 private Xex.Term parse_char_at (Xex.Symbol name)
1938 Xex.Term[] args = new Xex.Term[1];
1939 args[0] = new Xex.Term (Marker.Get (name));
1940 return new Xex.Term (domain, Qchar_at, args);
1943 private Xex.Term parse_shift (MPlist plist)
1945 Xex.Term[] args = new Xex.Term[1];
1946 if (! plist.IsSymbol)
1947 throw new Exception ("Invalid arg to shift: " + plist);
1948 args[0] = new Xex.Term ((Xex.Symbol) plist.Symbol.Name);
1949 return new Xex.Term (domain, Qshift, args);
1952 private Xex.Term parse_action (MPlist plist, bool as_funarg)
1956 MPlist p = plist.Plist;
1958 if (p.IsMText || p.IsPlist)
1959 return parse_insert (plist);
1961 throw new Exception ("Invalid action: " + p);
1962 Xex.Symbol name = p.Symbol.Name;
1965 return parse_cond (p);
1966 if (name == Qinsert)
1967 return parse_insert (p);
1968 if (name == Qselect)
1969 return parse_select (p);
1970 if (name == Qdelete || name == Qmove || name == Qmark)
1971 return parse_funcall_with_marker (p, name);
1973 return parse_shift (p);
1974 if (((string) name)[0] == '@')
1975 return parse_char_at (name);
1976 if (name == Qset || name == Qadd || name == Qsub
1977 || name == Qmul || name == Qdiv)
1980 throw new Exception ("Invalid action: " + p);
1981 Xex.Symbol varname = p.Symbol.Name;
1982 Xex.Term[] args = new Xex.Term[1];
1983 args[0] = parse_action (p.next, true);
1984 return new Xex.Term (domain, name, varname, args);
1991 return new Xex.Term (domain, name, null);
1993 return new Xex.Term (domain, name, parse_actions (p, true));
1996 else if (plist.IsSymbol)
1997 return new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1998 else if (plist.IsMText)
1999 return (as_funarg ? new Xex.Term ((string) plist.Text)
2000 : parse_insert (plist));
2001 else if (plist.IsInteger)
2002 return (as_funarg ? new Xex.Term (plist.Integer)
2003 : parse_insert (plist));
2005 throw new Exception ("Invalid action: " + plist);
2008 private Xex.Term[] parse_actions (MPlist plist, bool as_funarg)
2010 Xex.Term[] terms = new Xex.Term[plist.Count];
2012 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
2013 terms[i] = parse_action (plist, as_funarg);
2017 private void parse_macros (MPlist plist)
2019 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
2022 MPlist p = pl.Plist;
2026 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null, null, true);
2028 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
2031 MPlist p = pl.Plist;
2035 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null,
2036 parse_actions (p.next, false), false);
2040 private void parse_maps (MPlist plist)
2042 for (; ! plist.IsEmpty; plist = plist.next)
2045 MPlist pl = plist.Plist;
2049 Map map = new Map (pl.Symbol);
2050 maps[pl.Symbol] = map;
2051 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
2055 MPlist p = pl.Plist;
2058 keys = new KeySeq (p.Text);
2060 keys = new KeySeq (p.Plist);
2065 = p.IsEmpty ? null : parse_actions (p, false);
2066 map.entries.Add (new Map.Entry (domain, keys, actions));
2071 private static Xex.Term Finsert (Xex.Domain domain, Xex.Variable vari,
2074 ((Context) domain.context).insert (args[0]);
2078 private static Xex.Term Finsert_candidates (Xex.Domain domain,
2082 ((Context) domain.context).insert_candidates (args[0]);
2086 private static Xex.Term Fchar_at (Xex.Domain domain, Xex.Variable vari,
2089 Context ic = (Context) domain.context;
2090 Marker m = (Marker) args[0].Objval;
2092 return new Xex.Term (ic.char_at (m.Position (ic)));
2095 private static Xex.Term Fdelete (Xex.Domain domain, Xex.Variable vari,
2098 ((Context) domain.context).delete ((int) args[0].Intval);
2102 private static Xex.Term Fselect (Xex.Domain domain, Xex.Variable vari,
2105 Candidates can = ((Context) domain.context).candidates;
2108 ((Selector) args[0].Objval).Select (can);
2112 private static Xex.Term Fshow (Xex.Domain domain, Xex.Variable vari,
2115 ((Context) domain.context).show ();
2119 private static Xex.Term Fhide (Xex.Domain domain, Xex.Variable vari,
2122 ((Context) domain.context).hide ();
2126 private static Xex.Term Fmove (Xex.Domain domain, Xex.Variable vari,
2130 ((Context) domain.context).move (args[0].Intval);
2133 Marker m = (Marker) args[0].Objval;
2134 Context ic = (Context) domain.context;
2135 ((Context) domain.context).move (m.Position (ic));
2140 private static Xex.Term Fmark (Xex.Domain domain, Xex.Variable vari,
2143 Marker m = (Marker) args[0].Objval;
2144 m.Mark ((Context) domain.context);
2148 private static Xex.Term Fpushback (Xex.Domain domain, Xex.Variable vari,
2151 Context ic = (Context) domain.context;
2154 ic.pushback (args[0].Intval);
2155 else if (args[0].IsStr)
2156 ic.pushback (new KeySeq (args[0].Strval));
2158 ic.pushback ((KeySeq) args[0].Objval);
2162 private static Xex.Term Fpop (Xex.Domain domain, Xex.Variable vari,
2165 ((Context) domain.context).pop ();
2169 private static Xex.Term Fundo (Xex.Domain domain, Xex.Variable vari,
2172 int n = args.Length == 0 ? -2 : args[0].Intval;
2173 ((Context) domain.context).undo (n);
2177 private static Xex.Term Fcommit (Xex.Domain domain, Xex.Variable vari,
2180 ((Context) domain.context).commit ();
2184 private static Xex.Term Funhandle (Xex.Domain domain, Xex.Variable vari,
2187 ((Context) domain.context).commit ();
2188 args = new Xex.Term[2];
2189 args[0] = args[1] = Tcatch_tag;
2190 return Xex.Fthrow (domain, vari, args);
2193 private static Xex.Term Fshift (Xex.Domain domain, Xex.Variable vari,
2196 Context ic = (Context) domain.context;
2198 if (ic.im.states.TryGetValue (args[0].Symval, out state))
2199 ((Context) domain.context).shift (state);
2201 throw new Exception ("Unknown state: " + args[0].Symval);
2205 private static Xex.Term Fshiftback (Xex.Domain domain, Xex.Variable vari,
2208 ((Context) domain.context).shift (null);
2212 private static Xex.Term Fkey_count (Xex.Domain domain, Xex.Variable vari,
2215 return new Xex.Term (((Context) domain.context).key_head);
2218 private static Xex.Term Fsurrounding_flag (Xex.Domain domain,
2222 return new Xex.Term (((Context) domain.context).SurroundingFlag);
2225 public override string ToString ()
2227 string str = (String.Format ("({0} (title \"{1}\")", tag, title));
2228 if (commands != null)
2230 str += " (commands";
2231 foreach (Command cmd in commands)
2235 if (var_names != null)
2237 str += " (variables";
2238 foreach (Xex.Symbol var in var_names)
2242 if (plugins != null)
2245 foreach (KeyValuePair<MSymbol, Plugin> kv in plugins)
2246 str += " " + kv.Value;
2250 foreach (KeyValuePair<MSymbol, Map> kv in maps)
2251 str += " " + kv.Value;
2253 foreach (KeyValuePair<Xex.Symbol, State> kv in states)
2255 str += " (" + kv.Key + " " + kv.Value.keymap + ")";
2260 public class Context
2262 internal static Xex.Symbol Qcandidates_group_size
2263 = "candidates-group-size";
2264 internal MInputMethod im;
2265 private Dictionary<MSymbol, Callback> callbacks
2266 = new Dictionary<MSymbol, Callback> ();
2268 private MText produced;
2269 private bool active;
2270 private MText status;
2271 internal MText preedit;
2272 internal int cursor_pos;
2273 internal Dictionary<Marker, int> marker_positions
2274 = new Dictionary<Marker, int> ();
2275 internal Candidates candidates;
2276 private int candidate_from, candidate_to;
2277 private bool candidate_show;
2278 public bool CandidateShow { get { return candidate_show; } }
2280 private List<State> state_list = new List<State> ();
2281 private Keymap keymap;
2283 // Sequence of input keys.
2284 internal KeySeq keys = new KeySeq ();
2286 // Index into KEYS specifying the next key to handle.
2287 internal int key_head;
2290 private int state_key_head;
2291 private object state_var_values;
2292 private int commit_key_head;
2293 private MText state_preedit;
2294 private int state_pos;
2295 internal MText preceding_text = new MText ();
2296 internal MText following_text = new MText ();
2298 // Set to false before calling the method 'handle_key', and set
2299 // to true when some key is unhandled.
2300 private bool key_unhandled;
2302 // The unhandled key. It has the meaning only when
2303 // 'key_unhandled' is true.
2304 private Key unhandled_key;
2306 internal Xex.Domain domain;
2308 internal ChangedStatus changed;
2310 static MPlist callback_arg = new MPlist ();
2312 static Xex.Term[] catch_args = new Xex.Term[2];
2314 private bool take_action (Xex.Term[] actions)
2316 catch_args[0] = Tcatch_tag;
2317 catch_args[1]= new Xex.Term (domain, Qprogn, actions);
2318 Xex.Term term = new Xex.Term (domain, Qcatch, catch_args);
2319 term = term.Eval (domain);
2320 return (! term.IsSymbol || term.Symval != Tcatch_tag.Symval);
2324 private bool call_callback (MSymbol name, MPlist arg)
2327 if (! callbacks.TryGetValue (name, out callback))
2329 return callback (this, arg);
2332 private bool get_surrounding_text (int len)
2334 if (len < 0 ? -len <= preceding_text.Length
2335 : len <= following_text.Length)
2337 callback_arg.Set (MSymbol.integer, len);
2338 if (! call_callback (Mget_surrounding_text, callback_arg)
2339 || ! callback_arg.IsMText)
2343 preceding_text = callback_arg.Text;
2344 return (-len <= preceding_text.Length);
2346 following_text = callback_arg.Text;
2347 return (len <= following_text.Length);
2350 internal int SurroundingFlag
2352 get { return (callbacks.ContainsKey (Mget_surrounding_text) ? 1 : 0); }
2355 internal int GetSurroundingChar (int pos)
2357 if (! get_surrounding_text (pos < 0 ? pos : pos + 1))
2360 return preceding_text[preceding_text.Length + pos];
2361 return following_text[pos];
2364 private void adjust_markers (int from, int to, object inserted)
2366 int ins = (inserted == null ? 0
2367 : inserted is int ? 1
2368 : ((MText) inserted).Length);
2369 int diff = ins - (to - from);
2371 foreach (Marker m in marker_positions.Keys)
2373 int pos = marker_positions[m];
2377 marker_positions[m] = pos + diff;
2379 marker_positions[m] = from;
2382 if (cursor_pos >= to)
2384 else if (cursor_pos > from)
2388 private void preedit_replace (int from, int to, int c)
2390 preedit.Del (from, to);
2391 preedit.Ins (from, c);
2392 adjust_markers (from, to, c);
2395 private void preedit_replace (int from, int to, MText mt)
2397 preedit[from, to] = mt;
2398 adjust_markers (from, to, mt);
2401 internal void insert (Xex.Term arg)
2404 preedit_replace (cursor_pos, cursor_pos, arg.Intval);
2406 preedit_replace (cursor_pos, cursor_pos, new MText (arg.Strval));
2407 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2410 private void update_candidate ()
2412 object candidate = candidates.Current;
2414 if (candidate is MText)
2416 preedit_replace (candidate_from, candidate_to, (MText) candidate);
2417 candidate_to = candidate_from + ((MText) candidate).Length;
2421 preedit_replace (candidate_from, candidate_to, (int) candidate);
2422 candidate_to = candidate_from + 1;
2424 preedit.PushProp (candidate_from, candidate_to,
2426 cursor_pos = candidate_from;
2427 changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
2431 internal void insert_candidates (Xex.Term arg)
2434 Xex.Variable v = domain.GetVar (Qcandidates_group_size, false);
2437 column = v.Value.Intval;
2438 candidates = new Candidates (arg.Listval, column);
2439 candidate_from = candidate_to = cursor_pos;
2440 update_candidate ();
2443 internal void select (int n)
2445 if (candidates != null)
2447 candidates.Select (n);
2448 update_candidate ();
2452 internal int char_at (int pos)
2459 if (preceding_text.Length < -pos)
2461 MPlist plist = new MPlist ();
2462 plist.Push (MSymbol.integer, pos);
2463 if (GetSurroundingText != null
2464 && GetSurroundingText (this, plist)
2466 && preceding_text.Length < plist.Text.Length)
2467 preceding_text = plist.Text;
2469 c = (-pos < preceding_text.Length
2470 ? preceding_text[preceding_text.Length + pos] : -1);
2472 else if (pos >= 0 && pos < preedit.Length)
2476 pos -= preedit.Length;
2477 if (pos >= following_text.Length)
2479 MPlist plist = new MPlist ();
2480 plist.Push (MSymbol.integer, pos + 1);
2481 if (GetSurroundingText != null
2482 && GetSurroundingText (this, plist)
2484 && following_text.Length < plist.Text.Length)
2485 following_text = plist.Text;
2487 c = (pos < following_text.Length ? following_text[pos] : -1);
2492 internal void delete (int pos)
2494 if (pos < cursor_pos)
2495 preedit_replace (pos, cursor_pos, null);
2497 preedit_replace (cursor_pos, pos, null);
2498 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2501 internal void show ()
2503 candidate_show = true;
2504 changed |= ChangedStatus.CandidateShow;
2507 internal void hide ()
2509 candidate_show = false;
2510 changed |= ChangedStatus.CandidateShow;
2513 internal void move (int pos)
2517 else if (pos > preedit.Length)
2518 pos = preedit.Length;
2519 if (pos != cursor_pos)
2522 changed |= ChangedStatus.Preedit;
2526 internal void pushback (int n)
2539 if (key_head > keys.keyseq.Count)
2540 key_head = keys.keyseq.Count;
2544 internal void pushback (KeySeq keyseq)
2548 if (key_head < keys.keyseq.Count)
2549 keys.keyseq.RemoveRange (key_head, keys.keyseq.Count - key_head);
2550 for (int i = 0; i < keyseq.keyseq.Count; i++)
2551 keys.keyseq.Add (keyseq.keyseq[i]);
2554 internal void pop ()
2556 if (key_head < keys.keyseq.Count)
2557 keys.keyseq.RemoveRange (key_head, 1);
2560 internal void undo (int n)
2563 keys.keyseq.RemoveRange (keys.keyseq.Count + n, - n);
2565 keys.keyseq.RemoveRange (n, keys.keyseq.Count - n);
2569 internal void commit ()
2571 produced.Cat (preedit);
2573 changed |= ChangedStatus.Preedit;
2576 internal void shift (State state)
2582 if (state_list.Count > 1)
2583 state_list.RemoveAt (state_list.Count - 1);
2584 state = state_list[state_list.Count - 1];
2589 changed = state != state_list[state_list.Count - 1];
2591 state_list.Add (state);
2593 if (state_list.Count == 1)
2600 state_key_head = key_head;
2601 state_pos = cursor_pos;
2602 state_preedit = preedit.Dup ();
2603 state_var_values = domain.SaveValues ();
2606 status = state.title;
2609 this.changed |= ChangedStatus.StateTitle;
2610 if (state.enter_actions != null)
2611 take_action (state.enter_actions);
2616 internal void reset ()
2619 state_preedit.Del ();
2621 marker_positions.Clear ();
2623 keys.keyseq.Clear ();
2624 key_head = commit_key_head = 0;
2625 state_list.Clear ();
2626 state_list.Add (im.initial_state);
2627 keymap = im.initial_state.keymap;
2628 key_head = state_key_head = 0;
2632 public Context (MInputMethod im)
2635 domain = new Xex.Domain (im.domain, this);
2639 public ChangedStatus Changed { get { return changed; } }
2641 public void AddCallback (MSymbol name, Callback callback)
2643 callbacks[name] = callback;
2646 internal object GetCandidates (out int column)
2649 if (cursor_pos == 0)
2651 Candidates candidates
2652 = (Candidates) preedit.GetProp (cursor_pos - 1, Mcandidates);
2653 if (candidates == null)
2655 column = candidates.Column;
2656 return candidates.Current;
2659 private void restore_state ()
2663 private bool handle_key ()
2665 State state = state_list[state_list.Count - 1];
2666 Keymap sub = keymap.Lookup (keys, ref key_head);
2671 if (keymap.map_actions != null)
2674 if (! take_action (keymap.map_actions))
2677 else if (keymap.submaps != null)
2679 for (int i = state_key_head; i < key_head; i++)
2680 preedit_replace (cursor_pos, cursor_pos,
2681 keys.keyseq[i].ToChar ());
2683 if (keymap.submaps == null)
2685 if (keymap.branch_actions != null)
2687 if (! take_action (keymap.branch_actions))
2690 if (keymap != state.keymap)
2696 if (keymap.branch_actions != null)
2698 if (! take_action (keymap.branch_actions))
2701 if (state == state_list[state_list.Count - 1])
2703 if (state == im.initial_state
2704 && key_head < keys.keyseq.Count)
2706 if (keymap != state.keymap)
2708 else if (keymap.branch_actions == null)
2709 shift (im.initial_state);
2715 public bool Toggle ()
2721 public bool UnhandledKey (out Key key)
2723 key = unhandled_key;
2724 return key_unhandled;
2727 public bool Produced (out MText mt)
2730 return (produced.Length > 0);
2734 // true: All keys are handled and there's no text to commit.
2735 // false: Some key is unhandled or there's a text to commit.
2736 // The caller should use methods UnhandledKey and Produced.
2738 public bool Filter (Key key)
2740 if (key == Key.Reload)
2742 changed = ChangedStatus.None;
2744 preceding_text.Del ();
2745 following_text.Del ();
2747 key_unhandled = false;
2748 keys.keyseq.Add (key);
2750 while (key_head < keys.keyseq.Count)
2752 if (! handle_key ())
2754 unhandled_key = keys.keyseq[key_head++];
2755 key_unhandled = true;
2761 keys.keyseq.RemoveRange (0, key_head);
2762 return (! key_unhandled && produced.Length == 0);