2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Reflection;
12 using Xex = System.Xml.Expression.Xexpression;
16 public class MInputMethod
19 public delegate bool Callback (Context ic, MPlist args);
22 public static event Callback PreeditChanged;
23 public static event Callback StatusChanged;
24 public static event Callback CandidateChanged;
25 public static Callback GetSurroundingText;
26 public static Callback DeleteSurroundingText;
28 internal static Xex.Domain im_domain = new Xex.Domain (null);
29 private static MSymbol Minput_method = "input-method";
30 private static MSymbol Mdescription = "description";
31 private static MSymbol Mvariable = "variable";
32 private static MSymbol Mcommand = "command";
33 private static MSymbol Mmodule = "module";
34 private static MSymbol Mtitle = "title";
35 private static MSymbol Minclude = "include";
36 private static MSymbol Mmacro = "macro";
37 private static MSymbol Mmap = "map";
38 private static MSymbol Mmap_list = "map-list";
39 private static MSymbol Mstate = "state";
40 internal static MSymbol Mcandidates = "candidates";
41 private static MSymbol Mat_minus_zero = "@-0";
43 private static Xex.Symbol Qmap = "map";
44 private static Xex.Symbol Qrule = "rule";
45 private static Xex.Symbol Qkeyseq = "keyseq";
46 private static Xex.Symbol Qprogn = "progn";
47 private static Xex.Symbol Qcatch = "catch";
48 private static Xex.Symbol Qinsert = "insert";
49 private static Xex.Symbol Qinsert_candidates = "insert-candidates";
50 private static Xex.Symbol Qchar_at = "char-at";
51 private static Xex.Symbol Qselect = "select";
52 private static Xex.Symbol Qdelete = "delete";
53 private static Xex.Symbol Qshift = "shift";
54 private static Xex.Symbol Qmove = "move";
55 private static Xex.Symbol Qmark = "mark";
56 private static Xex.Symbol Qset = "set";
57 private static Xex.Symbol Qadd = "add";
58 private static Xex.Symbol Qsub = "sub";
59 private static Xex.Symbol Qmul = "mul";
60 private static Xex.Symbol Qdiv = "div";
61 private static Xex.Symbol Qcond = "cond";
62 private static Xex.Symbol Qsname = "sname";
63 private static Xex.Symbol Qmname = "mname";
64 private static Xex.Symbol Qstate_hook = "state-hook";
65 private static Xex.Symbol Qcatch_all_branch = "catch-all-branch";
66 private static Xex.Symbol Qbranch = "branch";
67 private static Xex.Symbol Qstate = "state";
68 private static Xex.Symbol Qtitle = "title";
69 private static Xex.Symbol Qeq = "=";
70 private static Xex.Symbol Qeqeq = "==";
71 private static Xex.Symbol Qcandidates_group_size = "candidates-group-size";
73 private static Xex.Term Tnil = new Xex.Term ((Xex.Symbol) "nil");
74 private static Xex.Term Tcatch_tag = new Xex.Term ((Xex.Symbol) "@mimtag");
76 private static Dictionary<MDatabase.Tag, MInputMethod> im_table
77 = new Dictionary<MDatabase.Tag, MInputMethod> ();
79 internal static MInputMethod im_global = null;
82 protected enum LoadStatus
92 public enum ChangedStatus
99 CandidateIndex = 0x10,
100 CandidateShow = 0x20,
101 Preedit = PreeditText | CursorPos,
102 Candidate = CandidateList | CandidateIndex | CandidateShow,
105 private static ChangedStatus CandidateAll = (ChangedStatus.CandidateList
106 | ChangedStatus.CandidateIndex
107 | ChangedStatus.CandidateShow);
109 public enum KeyModifier
112 Shift_L = 0x00400000,
113 Shift_R = 0x00800000,
115 Control_L = 0x01000000,
116 Control_R = 0x02000000,
117 Control = 0x03000000,
132 private static Dictionary<string, uint> keysyms
133 = new Dictionary<string, uint> ();
134 private static Dictionary<string, KeyModifier> keymodifiers
135 = new Dictionary<string, KeyModifier> ();
136 private static uint keysym_base = 0x200000;
137 private static uint char_mask = ~((uint) KeyModifier.All);
138 public static Key Reload;
142 keysyms["bs"] = keysyms["backspace"] = 0x08;
143 keysyms["tab"] = 0x09;
144 keysyms["lf"] = keysyms["linefeed"] = 0x10;
145 keysyms["cr"] = keysyms["return"] = keysyms["enter"] = 0x13;
146 keysyms["esc"] = keysyms["escape"] = 0x1B;
147 keysyms["spc"] = keysyms["space"] = 0x20;
148 keysyms["del"] = keysyms["delete"] = 0x7F;
149 keymodifiers["shift-l"] = KeyModifier.Shift_L;
150 keymodifiers["shift-r"] = KeyModifier.Shift_R;
151 keymodifiers["shift"] = KeyModifier.Shift;
152 keymodifiers["control-l"] = KeyModifier.Control_L;
153 keymodifiers["control-r"] = KeyModifier.Control_R;
154 keymodifiers["control"] = KeyModifier.Control;
155 keymodifiers["alt-l"] = KeyModifier.Alt_L;
156 keymodifiers["alt-r"] = KeyModifier.Alt_R;
157 keymodifiers["alt"] = KeyModifier.Alt;
158 keymodifiers["altgr"] = KeyModifier.AltGr;
159 keymodifiers["super"] = KeyModifier.Super;
160 keymodifiers["hyper"] = KeyModifier.Hyper;
161 Reload = new Key (keysym_base);
162 keysyms["-reload"] = keysym_base++;
165 private static uint decode_keysym (MSymbol keysym)
168 string name = keysym.Name;
170 if (name.Length == 1)
172 name = name.ToLower ();
173 if (! keysyms.TryGetValue (name, out key))
174 keysyms[name] = key = keysym_base++;
178 private static uint combine_modifiers (uint c, KeyModifier modifiers)
180 if (c < 0x7F && c != 0x20)
182 if ((modifiers & KeyModifier.Shift) != KeyModifier.None
183 && Char.IsLower ((char) c))
185 modifiers &= ~KeyModifier.Shift;
186 c = Char.ToUpper ((char) c);
188 if ((modifiers & KeyModifier.Control) != KeyModifier.None)
190 modifiers &= ~KeyModifier.Control;
194 return c | (uint) modifiers;
197 public Key (uint c) { key = c; }
198 public Key (int c) { key = (uint) c; }
200 public Key (uint c, KeyModifier modifiers)
202 key = combine_modifiers (c, modifiers);
205 public Key (MSymbol keysym, KeyModifier modifiers)
207 key = combine_modifiers (decode_keysym (keysym), modifiers);
210 public Key (MSymbol keysym)
212 string str = keysym.Name;
213 int len = str.Length;
215 KeyModifier modifiers = KeyModifier.None;
217 for (i = 0; i + 2 < len && str[i + 1] == '-'; i += 2)
220 modifiers |= KeyModifier.Shift;
221 else if (str[i] == 'C')
222 modifiers |= KeyModifier.Control;
223 else if (str[i] == 'A')
224 modifiers |= KeyModifier.Alt;
225 else if (str[i] == 'G')
226 modifiers |= KeyModifier.AltGr;
227 else if (str[i] == 's')
228 modifiers |= KeyModifier.Super;
229 else if (str[i] == 'H')
230 modifiers |= KeyModifier.Hyper;
233 key = combine_modifiers (str[i], modifiers);
235 key = combine_modifiers (decode_keysym (keysym), modifiers);
238 public Key (MPlist plist)
240 KeyModifier modifiers = KeyModifier.None;
243 for (p = plist; ! p.IsEmpty; p = p.next)
247 if (! p.next.IsEmpty)
248 throw new Exception ("Invalid Key: " + plist);
251 else if (! p.IsSymbol)
252 throw new Exception ("Invalid Key: " + plist);
255 string name = p.Symbol.Name.ToLower ();
258 if (! keymodifiers.TryGetValue (name, out m))
263 if (p.IsEmpty || ! p.next.IsEmpty)
264 throw new Exception ("Invalid Key: " + plist);
266 key = combine_modifiers ((uint) p.Integer, modifiers);
268 key = combine_modifiers (decode_keysym (p.Symbol), modifiers);
271 public bool HasModifier
273 get { return ((key & (uint) KeyModifier.All) != 0); }
276 public static bool operator== (Key k1, Key k2)
278 return k1.key == k2.key;
281 public static bool operator!= (Key k1, Key k2)
283 return k1.key != k2.key;
286 public override bool Equals (object o) { return key == ((Key) o).key; }
288 public override int GetHashCode () { return (int) key; }
290 public bool Match (Key k)
294 if ((k.key & char_mask) != (key & char_mask))
296 KeyModifier m1 = ((KeyModifier) key) & KeyModifier.All;
297 KeyModifier m2 = ((KeyModifier) k.key) & KeyModifier.All;
298 return (((m1 & KeyModifier.Shift) == (m2 & KeyModifier.Shift)
299 || ((m1 & KeyModifier.Shift) == KeyModifier.Shift
300 && (m2 & KeyModifier.Shift) != KeyModifier.None))
301 && ((m1 & KeyModifier.Control) == (m2 & KeyModifier.Control)
302 || ((m1 & KeyModifier.Control) == KeyModifier.Control
303 && (m2 & KeyModifier.Control) != KeyModifier.None))
304 && ((m1 & KeyModifier.Alt) == (m2 & KeyModifier.Alt)
305 || ((m1 & KeyModifier.Alt) == KeyModifier.Alt
306 && (m2 & KeyModifier.Alt) != KeyModifier.None))
307 && ((m1 & KeyModifier.High) == (m2 & KeyModifier.High)));
312 return (int) (key & 0x1FFFFF);
315 public override string ToString ()
320 foreach (KeyValuePair<string, uint> kv in keysyms)
321 if ((uint) c == kv.Value)
329 KeyModifier m = ((KeyModifier) key) & KeyModifier.All;
331 if (m != KeyModifier.None)
333 if ((m & KeyModifier.Shift) != KeyModifier.None)
335 if ((m & KeyModifier.Control) != KeyModifier.None)
337 if ((m & KeyModifier.Alt) != KeyModifier.None)
339 if ((m & KeyModifier.AltGr) != KeyModifier.None)
341 if ((m & KeyModifier.Super) != KeyModifier.None)
343 if ((m & KeyModifier.Hyper) != KeyModifier.None)
350 internal class KeySeq : Xex.TermValue
352 public List<Key> keyseq = new List<Key> ();
354 public override Xex.TermValue Clone ()
356 KeySeq ks = new KeySeq ();
357 ks.keyseq.InsertRange (0, keyseq);
363 public KeySeq (MPlist plist)
365 foreach (MPlist p in plist)
368 keyseq.Add (new Key (p.Symbol));
369 else if (p.IsInteger)
370 keyseq.Add (new Key ((char) p.Integer));
372 keyseq.Add (new Key (p.Plist));
374 throw new Exception ("Invalid Key Sequence: " + plist);
378 public KeySeq (MText mt) : base ()
380 for (int i = 0; i < mt.Length; i++)
381 keyseq.Add (new Key ((uint) mt[i]));
384 public KeySeq (List<Xex.Term> list)
386 int len = list.Count;
388 for (int i = 0; i < len; i++)
391 keyseq.Add (new Key (list[i].Intval));
392 else if (list[i].IsStr)
393 keyseq.Add (new Key (list[i].Strval));
394 else if (list[i].IsSymbol)
395 keyseq.Add (new Key ((string) list[i].Symval));
397 throw new Exception ("Invalid key: " + list[i]);
401 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
403 Xex.Term term = new Xex.Term (domain, node.FirstChild).Eval (domain);
404 return (term.IsStr ? new KeySeq ((MText) term.Strval)
405 : new KeySeq (term.Listval));
408 public override string ToString ()
411 foreach (Key key in keyseq)
412 if (key.HasModifier || key.ToChar () < 0x20)
415 foreach (Key k in keyseq)
419 mt.Cat (k.ToString ());
421 return (string) mt.Cat (")");
424 foreach (Key k in keyseq)
428 if (c == '\\' || c == '"')
432 return (string) mt.Cat ("\"");
439 public MText description;
440 internal List<KeySeq> keys;
442 public Command (MPlist p)
446 description = parse_description (p);
447 if (description == null)
448 description = "No description";
449 keys = new List<KeySeq> ();
450 for (p = p.next; ! p.IsEmpty; p = p.next)
453 keys.Add (new KeySeq (p.Text));
455 keys.Add (new KeySeq (p.Plist));
459 public Command (XmlNode node)
461 name = node.Attributes[0].Value;
462 keys = new List<KeySeq> ();
463 for (node = node.FirstChild; node != null; node = node.NextSibling)
465 if (node.Name == "description")
466 description = parse_description (node);
467 else if (node.Name == "keyseq")
468 keys.Add ((KeySeq) KeySeq.parser (null, node));
472 public override string ToString ()
474 string str = "(" + name + " \"" + (string) description;
475 foreach (KeySeq keyseq in keys)
481 internal class Plugin
484 private Assembly assembly;
485 private Type plugin_type;
487 public Plugin (string name)
492 public MethodInfo GetMethod (Xex.Symbol name)
494 if (assembly == null)
496 assembly = Assembly.LoadFrom (name + ".dll");
497 plugin_type = assembly.GetType ("M17n.MInputMethod.Plugin");
500 MethodInfo info = plugin_type.GetMethod ((string) name);
502 throw new Exception ("Invalid plugin method: " + name);
506 public override string ToString ()
508 return String.Format ("(module {0}", name);
512 internal class PluginMethod : Xex.Function
514 private Plugin plugin;
515 private MethodInfo method_info;
516 object[] parameters = new object[2];
518 public PluginMethod (Plugin plugin, string name)
519 : base ((Xex.Symbol) name, 0, -1)
521 this.plugin = plugin;
524 public override Xex.Term Call (Xex.Domain domain, Xex.Variable vari,
527 args = (Xex.Term[]) args.Clone ();
528 for (int i = 0; i < args.Length; i++)
530 args[i] = args[i].Eval (domain);
534 if (method_info == null)
535 method_info = plugin.GetMethod (name);
536 parameters[0] = domain.context;
537 parameters[1] = args;
538 return (Xex.Term) method_info.Invoke (null, parameters);
542 internal abstract class Marker : Xex.TermValue
544 private MSymbol name;
546 private Marker (MSymbol name)
551 public abstract int Position (Context ic);
553 public virtual void Mark (Context ic)
555 throw new Exception ("Can't set predefined marker: " + name);
557 public virtual int CharAt (Context ic)
559 return ic.preedit[Position (ic)];
562 public override string ToString () { return name.Name; }
564 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
566 return Get ((MSymbol) node.InnerText);
569 public class Named : Marker
571 public Named (MSymbol name) : base (name) { }
573 public override int Position (Context ic)
575 MPlist p = ic.marker_positions.Find (name);
576 return (p == null ? 0 : p.Integer);
579 public override void Mark (Context ic)
581 ic.marker_positions.Put (name, ic.cursor_pos);
585 public class Predefined : Marker
589 public Predefined (MSymbol name) : base (name)
591 tag = ((string) name)[1];
594 public override int Position (Context ic)
598 case '>': return ic.preedit.Length;
599 case '-': return ic.cursor_pos - 1;
600 case '+': return ic.cursor_pos + 1;
602 if (ic.cursor_pos > 0)
604 int pos = ic.cursor_pos;
606 ic.preedit.FindProp (Mcandidates, pos - 1, out pos, out to);
611 if (ic.cursor_pos < ic.preedit.Length - 1)
613 int pos = ic.cursor_pos;
615 ic.preedit.FindProp (Mcandidates, pos, out from, out pos);
618 return ic.preedit.Length;
625 public class PredefinedAbsolute : Marker
629 public PredefinedAbsolute (MSymbol name) : base (name)
631 if (! int.TryParse (((string) name).Substring (1), out pos))
632 throw new Exception ("Invalid marker name: " + name);
635 public override int Position (Context ic)
637 return (pos < ic.preedit.Length ? pos : ic.preedit.Length);
641 public class PredefinedSurround : Marker
643 private int distance;
645 public PredefinedSurround (MSymbol name) : base (name)
647 if (! int.TryParse (((string) name).Substring (2), out distance))
648 throw new Exception ("Invalid marker name: " + name);
653 public override int Position (Context ic)
655 return ic.cursor_pos + distance;
658 public override int CharAt (Context ic)
660 int pos = ic.cursor_pos + distance;
662 return ic.GetSurroundingChar (pos);
663 else if (pos >= ic.preedit.Length)
664 return ic.GetSurroundingChar (pos - ic.preedit.Length);
665 return ic.preedit[pos];
669 static internal Dictionary<MSymbol,Predefined> predefined_markers;
673 predefined_markers = new Dictionary<MSymbol, Predefined> ();
674 MSymbol[] symlist = new MSymbol[] {"@<", "@>", "@-", "@+", "@[", "@]" };
675 foreach (MSymbol s in symlist)
676 predefined_markers[s] = new Predefined (s);
679 public static Marker Get (MSymbol name)
681 string str = name.Name;
685 if (predefined_markers.TryGetValue (name, out pred))
688 throw new Exception ("Invalid marker name: " + name);
689 if (Char.IsDigit (str[1]))
690 return new PredefinedAbsolute (name);
691 if (str.Length == 2 || name == Mat_minus_zero
692 || ! (str[1] == '-' || str[1] == '+'))
693 throw new Exception ("Invalid marker name: " + name);
694 return new PredefinedSurround (name);
696 return new Named (name);
700 internal class Candidates
707 public Block (int index, Xex.Term term)
711 Data = (MText) term.Strval;
714 MPlist plist = new MPlist ();
716 foreach (Xex.Term t in term.Listval)
717 p = p.Add (MSymbol.mtext, (MText) t.Strval);
722 public Block (int index, MPlist plist)
727 else if (plist.IsPlist)
730 throw new Exception ("Invalid candidate: " + plist);
735 get { return (Data is MText
736 ? ((MText) Data).Length
737 : ((MPlist) Data).Count); }
740 public object this[int i]
743 if (Data is MText) return ((MText) Data)[i];
744 return ((MPlist) Data)[i];
749 private Block[] blocks;
751 private int index = 0;
752 public object[] group;
754 private bool IsFixed { get { return group != null; } }
757 Block last = blocks[blocks.Length - 1];
758 return last.Index + last.Count; }
762 get { return (IsFixed ? index % group.Length
763 : index - blocks[row].Index); }
766 public object Group {
767 get { return (IsFixed ? group : blocks[row].Data); }
770 public int GroupLength
775 int nitems = group.Length;
776 int start = index - (index % nitems);
778 return (start + nitems <= total ? nitems : total - start);
780 return blocks[row].Count;
784 public object Current {
786 return (IsFixed ? group[index % group.Length]
787 : blocks[row][index - blocks[row].Index]);
791 public Candidates (MPlist list, int column)
793 int nblocks = list.Count;
795 blocks = new Block[nblocks];
796 for (int i = 0, start = 0; i < nblocks; i++, list = list.next)
797 start += (blocks[i] = new Block (index, list)).Count;
799 group = new object[column];
802 public Candidates (Xex.Term[] candidates, int column)
804 int nblocks = candidates.Length;
806 blocks = new Block[nblocks];
807 for (int i = 0, start = 0; i < nblocks; i++)
808 start += (blocks[i] = new Block (index, candidates[i])).Count;
810 group = new object[column];
813 public static void Detach (Context ic)
815 ic.preedit.PopProp (0, ic.preedit.Length, Mcandidates);
816 ic.candidates = null;
817 ic.changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
821 // Fill the array "group" by candidates stating from INDEX.
822 // INDEX must be a multiple of "column". Set NTIMES to the
823 // number of valid candidates in "group". Update "block" if
824 // necessary. Return "group".
826 private int fill_group (int start)
828 int nitems = group.Length;
833 while (start < b.Index)
836 while (start >= b.Index + b.Count)
842 for (int i = 0; i < nitems; i++, start++)
847 if (r == blocks.Length)
858 // Update "row" to what contains the first candidate of
859 // the previous candidate-group, update "current_index", and
860 // update "group" if necessary. Return the previous
861 // candidate-group. Set NITEMS to the number of valid
862 // candidates contained in that group.
864 public int PrevGroup ()
871 nitems = group.Length;
872 if ((index -= col + nitems) < 0)
873 index = (Total / nitems) * nitems;
874 nitems = fill_group (index);
878 row = row > 0 ? row-- : blocks.Length - 1;
879 nitems = blocks[row].Count;
880 index = blocks[row].Index;
882 index += col < nitems ? col : nitems - 1;
886 public int NextGroup ()
893 nitems = group.Length;
894 if ((index += nitems - col) >= Total)
896 nitems = fill_group (index);
900 row = row < blocks.Length - 1 ? row + 1 : 0;
901 nitems = blocks[row].Count;
902 index = blocks[row].Count;
904 index += col < nitems ? col : nitems - 1;
914 int nitems = PrevGroup ();
915 index += col < nitems - 1 ? col : nitems - 1;
924 int nitems = GroupLength;
926 if (col == nitems - 1)
928 nitems = NextGroup ();
942 index += GroupLength - (Column + 1);
945 public void Select (int col)
947 int maxcol = GroupLength - 1;
950 index = index - Column + col;
954 internal class Selector : Xex.TermValue
956 static new Dictionary<MSymbol, Selector> selectors;
960 selectors = new Dictionary<MSymbol, Selector> ();
961 MSymbol[] symlist = new MSymbol[] { "@<", "@=", "@>", "@-", "@+",
963 foreach (MSymbol s in symlist)
964 selectors[s] = new Selector (s);
965 selectors["@first"] = new Selector ('<');
966 selectors["@current"] = new Selector ('=');
967 selectors["@last"] = new Selector ('>');
968 selectors["@previous"] = new Selector ('-');
969 selectors["@next"] = new Selector ('+');
970 selectors["@previous-candidate-change"] = new Selector ('[');
971 selectors["@next-candidate-change"] = new Selector (']');
976 private Selector (MSymbol sym) { tag = sym.Name[1]; }
978 private Selector (char tag) { this.tag = tag; }
980 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
982 return Get ((MSymbol) node.InnerText);
985 public static Xex.TermValue Get (MSymbol name)
988 if (! selectors.TryGetValue (name, out selector))
989 throw new Exception ("Invalid selector name: " + name);
993 public void Select (Candidates candidates)
997 case '<': candidates.First (); break;
998 case '>': candidates.Last (); break;
999 case '-': candidates.Prev (); break;
1000 case '+': candidates.Next (); break;
1001 case '[': candidates.PrevGroup (); break;
1002 case ']': candidates.NextGroup (); break;
1010 public MSymbol name;
1011 public List<Entry> entries = new List<Entry> ();
1013 public Map (MSymbol name) { this.name = name; }
1017 public KeySeq keyseq;
1018 public Xex.Term[] actions;
1020 public Entry (Xex.Domain domain, KeySeq keyseq, Xex.Term[] actions)
1022 this.keyseq = keyseq;
1023 this.actions = actions;
1027 public override string ToString ()
1029 string str = "(" + name;
1030 foreach (Entry e in entries)
1031 str += " " + e.keyseq.ToString ();
1036 internal class Keymap
1038 public Dictionary<Key, Keymap> submaps;
1039 public Xex.Term[] map_actions, branch_actions;
1041 public Keymap () { }
1043 public void Add (KeySeq keys, int index,
1044 Xex.Term[] map_actions, Xex.Term[] branch_actions)
1046 if (index == keys.keyseq.Count)
1048 this.map_actions = map_actions;
1049 this.branch_actions = branch_actions;
1053 Key key = keys.keyseq[index];
1056 if (submaps == null)
1057 submaps = new Dictionary<Key, Keymap> ();
1059 submaps.TryGetValue (key, out sub);
1061 submaps[key] = sub = new Keymap ();
1062 sub.Add (keys, index + 1, map_actions, branch_actions);
1066 public void AddMap (Map map, Xex.Term[] branch_actions)
1068 foreach (Map.Entry entry in map.entries)
1069 Add (entry.keyseq, 0, entry.actions, branch_actions);
1072 public Keymap Lookup (KeySeq keys, ref int index)
1076 if (index < keys.keyseq.Count
1078 && submaps.TryGetValue (keys.keyseq[index], out sub))
1081 return sub.Lookup (keys, ref index);
1086 private void describe (MText mt, KeySeq keyseq)
1088 if (map_actions != null || branch_actions != null)
1092 mt.Cat ('(').Cat (keyseq.ToString ());
1093 if (map_actions != null)
1094 foreach (Xex.Term term in map_actions)
1095 mt.Cat (' ').Cat (term.ToString ());
1096 if (branch_actions != null)
1097 foreach (Xex.Term term in branch_actions)
1098 mt.Cat (' ').Cat (term.ToString ());
1101 if (submaps != null)
1102 foreach (KeyValuePair<Key, Keymap> kv in submaps)
1104 keyseq.keyseq.Add (kv.Key);
1105 kv.Value.describe (mt, keyseq);
1106 keyseq.keyseq.RemoveAt (keyseq.keyseq.Count - 1);
1110 public override string ToString ()
1113 KeySeq keyseq = new KeySeq ();
1115 describe (mt, keyseq);
1120 internal class State
1122 public Xex.Symbol name;
1124 public Xex.Term[] enter_actions, fallback_actions;
1125 public Keymap keymap = new Keymap ();
1127 public State (Xex.Symbol name, MText title)
1133 public State (MInputMethod im, XmlNode node)
1135 this.name = node.Attributes[Qsname].Value;
1136 XmlAttribute attr = node.Attributes[Qtitle];
1138 title = (MText) attr.Value;
1141 keymap = new Keymap ();
1142 for (node = node.FirstChild; node != null; node = node.NextSibling)
1144 if (node.Name == Qstate_hook)
1145 enter_actions = Xex.ParseTerms (im.domain, node.FirstChild);
1146 else if (node.Name == Qcatch_all_branch)
1147 fallback_actions = Xex.ParseTerms (im.domain, node.FirstChild);
1148 else if (node.Name == Qbranch)
1150 MSymbol mapname = node.Attributes[Qmname].Value;
1152 if (im.maps.TryGetValue (mapname, out map))
1153 keymap.AddMap (map, Xex.ParseTerms (im.domain,
1156 throw new Exception ("Unknown map: " + mapname);
1161 public State (MInputMethod im, MPlist plist)
1163 if (! plist.IsSymbol)
1164 throw new Exception ("Invalid state: " + plist);
1165 this.name = plist.Symbol.Name;
1174 keymap = new Keymap ();
1175 for (; ! plist.IsEmpty; plist = plist.next)
1177 if (! plist.IsPlist)
1178 throw new Exception ("Invalid branch: " + plist);
1179 MPlist p = plist.Plist;
1181 throw new Exception ("Invalid branch: " + p);
1182 MSymbol mapname = p.Symbol;
1183 if (mapname == MSymbol.t)
1184 enter_actions = im.parse_actions (p.next, false);
1185 else if (mapname == MSymbol.nil)
1186 fallback_actions = im.parse_actions (p.next, false);
1190 if (im.maps.TryGetValue (mapname, out map))
1191 keymap.AddMap (map, im.parse_actions (p.next, false));
1193 throw new Exception ("Unknown map: " + mapname);
1198 public override string ToString ()
1200 MText mt = "(" + name;
1203 mt.Cat (" \"" + title + "\"");
1204 mt.Cat (keymap.ToString ());
1205 return (string) mt + ")";
1210 internal Xex.Domain domain = new Xex.Domain (im_domain, null);
1212 protected LoadStatus load_status = LoadStatus.None;
1213 protected MDatabase.Tag tag;
1214 private MDatabase mdb;
1216 private MText description;
1217 internal MText title;
1218 internal Command[] commands;
1219 internal Xex.Symbol[] var_names;
1220 internal Dictionary<MSymbol, Plugin> plugins;
1221 internal Dictionary<MSymbol, Map> maps;
1222 internal Dictionary<Xex.Symbol, State> states;
1223 internal State initial_state;
1225 static MInputMethod ()
1227 im_domain.DefTerm ("keyseq", KeySeq.parser);
1228 im_domain.DefTerm ("marker", Marker.parser);
1229 im_domain.DefTerm ("selector", Selector.parser);
1231 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
1232 im_domain.DefSubr (Finsert_candidates, "insert-candidates", false, 1, -1);
1233 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
1234 im_domain.DefSubr (Fselect, "select", false, 1, 1);
1235 im_domain.DefSubr (Fshow, "show", false, 0, 0);
1236 im_domain.DefSubr (Fhide, "hide", false, 0, 0);
1237 im_domain.DefSubr (Fmove, "move", false, 1, 1);
1238 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
1239 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
1240 im_domain.DefSubr (Fpop, "pop", false, 0, 0);
1241 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
1242 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
1243 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
1244 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
1245 im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
1246 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
1247 im_domain.DefSubr (Fkey_count, "key-count", false, 1, 1);
1248 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag",
1251 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, "*", "*", "*");
1252 List<MDatabase> list = MDatabase.List (tag);
1253 M17n.DebugPrint ("Found {0} input methods\n", list.Count);
1254 foreach (MDatabase mdb in list)
1255 im_table[mdb.tag] = new MInputMethod (mdb.tag);
1259 private MInputMethod (MDatabase.Tag tag)
1264 // Instance Properties
1265 public MSymbol Language { get { return tag[1]; } }
1266 public MSymbol Name { get { return tag[2]; } }
1267 public MSymbol SubName { get { return tag[3]; } }
1269 public bool Info (out MText description,
1271 out Xex.Variable[] variables,
1272 out Command[] commands)
1274 if ((load_status & LoadStatus.Header) != LoadStatus.Header
1275 && ! load_header ())
1283 description = this.description;
1285 if (var_names == null)
1289 variables = new Xex.Variable[var_names.Length];
1291 foreach (Xex.Symbol name in var_names)
1292 variables[i++] = domain.GetVar (name, false);
1294 commands = this.commands;
1298 public static MInputMethod Find (MSymbol language, MSymbol name)
1300 return Find (language, name, MSymbol.nil);
1303 public static MInputMethod Find (MSymbol language, MSymbol name,
1306 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, language,
1310 return (im_table.TryGetValue (tag, out im) ? im : null);
1313 private bool Open ()
1315 return ((load_status == LoadStatus.Full) || load_body ());
1318 public static MInputMethod[] List ()
1320 MInputMethod[] array = new MInputMethod[im_table.Count];
1323 foreach (KeyValuePair<MDatabase.Tag, MInputMethod> kv in im_table)
1324 array[i++] = kv.Value;
1328 private bool load_header ()
1330 mdb = MDatabase.Find (tag);
1333 mdb.name_table = Xex.Symbol.Table;
1335 MSymbol format = mdb.Format;
1337 if (format == MSymbol.plist)
1338 load ((MPlist) mdb.Load (Mmap), false);
1341 XmlDocument doc = (XmlDocument) mdb.Load (Mmap_list);
1342 load (doc.DocumentElement, false);
1344 } catch (Exception e) {
1345 Console.WriteLine ("{0}\n", e);
1346 load_status = LoadStatus.Error;
1349 load_status |= LoadStatus.Header;
1353 private bool load_body ()
1355 mdb = MDatabase.Find (tag);
1358 mdb.name_table = Xex.Symbol.Table;
1360 object obj = mdb.Load ();
1362 load ((MPlist) obj, true);
1364 load ((XmlDocument) obj, true);
1365 } catch (Exception e) {
1366 Console.WriteLine (e);
1367 load_status = LoadStatus.Error;
1370 load_status = LoadStatus.Full;
1374 private void add_default_state ()
1376 Xex.Symbol Qinit = "init";
1377 State state = new State (Qinit, title);
1378 foreach (KeyValuePair<MSymbol, Map>kv in maps)
1379 state.keymap.AddMap (kv.Value, null);
1380 states[Qinit] = initial_state = state;
1383 private void load (MPlist plist, bool full)
1385 maps = new Dictionary<MSymbol, Map> ();
1386 states = new Dictionary<Xex.Symbol, State> ();
1388 for (; ! plist.IsEmpty; plist = plist.next)
1391 MPlist pl = plist.Plist;
1394 MSymbol sym = pl.Symbol;
1397 if (sym == Mdescription)
1398 description = parse_description (pl);
1399 else if (sym == Mtitle)
1404 else if (sym == Mvariable)
1405 parse_variables (pl);
1406 else if (sym == Mcommand)
1407 parse_commands (pl);
1412 else if (sym == Minclude)
1414 else if (sym == Mmacro)
1416 else if (sym == Mmap)
1418 else if (sym == Mstate)
1423 if (description == null)
1424 description = (MText) "No description";
1426 title = new MText (tag[2].Name);
1427 if (commands == null)
1428 commands = new Command[0];
1431 if (states.Count == 0)
1432 add_default_state ();
1435 private void load (XmlNode node, bool full)
1437 bool skip_header = load_status == LoadStatus.Header;
1439 maps = new Dictionary<MSymbol, Map> ();
1440 states = new Dictionary<Xex.Symbol, State> ();
1442 if (node.NodeType == XmlNodeType.Document)
1443 node = node.FirstChild;
1444 while (node.NodeType != XmlNodeType.Element)
1445 node = node.NextSibling;
1446 for (node = node.FirstChild; node != null; node = node.NextSibling)
1448 if (node.NodeType != XmlNodeType.Element)
1452 if (node.Name == "description")
1453 description = parse_description (node);
1454 else if (node.Name == "title")
1455 title = parse_title (node);
1456 else if (node.Name == "variable-list")
1457 parse_variables (node);
1458 else if (node.Name == "command-list")
1459 parse_commands (node);
1463 if (node.Name == "module-list")
1464 parse_plugins (node);
1465 else if (node.Name == "macro-list")
1466 parse_macros (node);
1467 else if (node.Name == "map-list")
1469 else if (node.Name == "state-list")
1470 parse_states (node);
1473 if (description == null)
1474 description = (MText) "No description";
1476 title = new MText (tag[2].Name);
1477 if (commands == null)
1478 commands = new Command[0];
1481 if (states.Count == 0)
1482 add_default_state ();
1485 private static MText parse_description (MPlist plist)
1491 plist = plist.Plist;
1492 if (plist.IsSymbol && plist.Symbol == (MSymbol) "_"
1493 && plist.next.IsMText)
1494 return plist.next.Text;
1499 private static MText parse_description (XmlNode node)
1501 if (node.HasChildNodes)
1502 node = node.FirstChild;
1503 return node.InnerText;
1506 private static MText parse_title (XmlNode node)
1508 return node.InnerText;
1511 private void new_variable (Xex.Symbol name, string desc, int val,
1512 MPlist pl, Xex.Variable vari)
1520 int nrange = pl.Count;
1521 range = new int[nrange * 2];
1522 for (int i = 0; i < nrange; i++)
1526 MPlist p = pl.Plist;
1528 if (! p.IsInteger || ! p.next.IsInteger)
1529 throw new Exception ("Invalid range: " + p);
1530 range[i * 2] = p.Integer;
1531 range[i * 2 + 1] = p.next.Integer;
1533 else if (pl.IsInteger)
1534 range[i * 2] = range[i * 2 + 1] = pl.Integer;
1536 throw new Exception ("Invalid range: " + pl);
1540 domain.Defvar (new Xex.Variable.Int (name, desc, val, range));
1543 Xex.Term term = new Xex.Term (val);
1545 vari.DefaultValue = term;
1550 private void new_variable (Xex.Symbol name, string desc, MText val,
1551 MPlist pl, Xex.Variable vari)
1559 range = new string[pl.Count * 2];
1560 for (int i = 0; i < range.Length; i++)
1563 range[i] = (string) pl.Text;
1565 throw new Exception ("Invalid range: " + pl);
1569 domain.Defvar (new Xex.Variable.Str (name, desc, (string) val, range));
1572 Xex.Term term = new Xex.Term ((string) val);
1574 vari.DefaultValue = term;
1579 private void new_variable (Xex.Symbol name, string desc, MSymbol val,
1580 MPlist pl, Xex.Variable vari)
1583 Xex.Symbol sym = val.Name;
1589 range = new Xex.Symbol[pl.Count * 2];
1590 for (int i = 0; i < range.Length; i++)
1593 range[i] = pl.Symbol.Name;
1595 throw new Exception ("Invalid range: " + pl);
1599 domain.Defvar (new Xex.Variable.Sym (name, desc, sym, range));
1602 Xex.Term term = new Xex.Term (sym);
1604 vari.DefaultValue = term;
1609 private Xex.Variable get_global_var (Xex.Symbol name)
1611 if (im_global == null || this != im_global)
1613 tag = new MDatabase.Tag (Minput_method, MSymbol.t, MSymbol.nil,
1615 im_global = im_table[tag];
1616 if (! im_global.Open ())
1617 throw new Exception ("Failed to load global");
1619 return im_global.domain.GetVar (name, false);
1622 private void parse_variables (MPlist plist)
1624 var_names = new Xex.Symbol[plist.Count];
1626 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1628 if (! plist.IsPlist || ! plist.Plist.IsSymbol)
1629 throw new Exception ("Invalid variable: " + plist);
1631 MPlist p = plist.Plist;
1632 Xex.Symbol name = (Xex.Symbol) p.Symbol.Name;
1633 var_names[i] = name;
1635 string desc = (string) parse_description (p);
1636 Xex.Variable vari = get_global_var (name);
1638 domain.Defvar (vari);
1644 new_variable (name, desc, p.Integer, p.next, vari);
1646 new_variable (name, desc, p.Text, p.next, vari);
1647 else if (p.IsSymbol)
1648 new_variable (name, desc, p.Symbol, p.next, vari);
1650 throw new Exception ("Invalid variable type: " + p.val);
1655 private void parse_variables (XmlNode node)
1657 XmlNodeList node_list = node.ChildNodes;
1659 var_names = new Xex.Symbol[node_list.Count];
1660 for (int i = 0; i < node_list.Count; i++)
1662 Xex.Symbol name = node_list[i].Attributes[0].Value;
1663 Xex.Variable vari = get_global_var (name);
1665 domain.Defvar (vari);
1666 domain.Defvar (node_list[i]);
1667 var_names[i] = name;
1671 private void parse_commands (MPlist plist)
1673 commands = new Command[plist.Count];
1675 for (int i = 0; ! plist.IsEmpty; plist = plist.next)
1676 if (plist.IsPlist && plist.Plist.IsSymbol)
1677 commands[i++] = new Command (plist.Plist);
1680 private void parse_commands (XmlNode node)
1682 XmlNodeList node_list = node.ChildNodes;
1684 commands = new Command[node_list.Count];
1685 for (int i = 0; i < node_list.Count; i++)
1687 if (node_list[i].NodeType == XmlNodeType.Element)
1688 commands[i] = new Command (node_list[i]);
1692 private void parse_plugins (MPlist plist)
1694 plugins = new Dictionary<MSymbol, Plugin> ();
1696 for (; ! plist.IsEmpty; plist = plist.Next)
1698 MPlist p = plist.Plist;
1699 MSymbol sym = p.Symbol;
1700 Plugin plugin = new Plugin (sym.Name);
1702 for (p = p.next; ! p.IsEmpty; p = p.next)
1704 Xex.Function func = new PluginMethod (plugin, p.Symbol.Name);
1705 domain.Defun (func);
1710 private void parse_plugins (XmlNode node)
1712 plugins = new Dictionary<MSymbol, Plugin> ();
1714 foreach (XmlNode n in node.ChildNodes)
1716 Plugin plugin = new Plugin (n.Attributes[0].Value);
1717 foreach (XmlNode nn in n.ChildNodes)
1719 Xex.Function func = new PluginMethod (plugin,
1720 nn.Attributes[0].Value);
1721 domain.Defun (func);
1726 private void parse_macros (XmlNode node)
1728 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1729 if (nn.NodeType == XmlNodeType.Element)
1730 domain.Defun (nn, true);
1731 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1732 if (nn.NodeType == XmlNodeType.Element)
1733 domain.Defun (nn, false);
1736 private void parse_maps (XmlNode node)
1738 for (node = node.FirstChild; node != null; node = node.NextSibling)
1739 if (node.Name == Qmap)
1741 MSymbol name = node.Attributes[0].Value;
1742 Map map = new Map (name);
1744 for (XmlNode nd = node.FirstChild; nd != null; nd = nd.NextSibling)
1745 if (nd.Name == Qrule)
1747 XmlNode n = nd.FirstChild;
1748 if (n.Name != Qkeyseq)
1750 KeySeq keyseq = (KeySeq) KeySeq.parser (domain, n);
1751 Xex.Term[] actions = Xex.ParseTerms (domain, n.NextSibling);
1752 map.entries.Add (new Map.Entry (domain, keyseq, actions));
1757 private void parse_states (MPlist plist)
1759 for (; ! plist.IsEmpty; plist = plist.next)
1762 State state = new State (this, plist.Plist);
1763 states[state.name] = state;
1764 if (initial_state == null)
1765 initial_state = state;
1769 private void parse_states (XmlNode node)
1771 for (node = node.FirstChild; node != null; node = node.NextSibling)
1772 if (node.Name == Qstate)
1774 State state = new State (this, node);
1775 states[state.name] = state;
1776 if (initial_state == null)
1777 initial_state = 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 (plist.Symbol));
1932 throw new Exception ("Invalid arg to " + func + ": " + plist);
1933 return new Xex.Term (domain, func, args);
1936 private Xex.Term parse_char_at (MSymbol 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 MSymbol sym = p.Symbol;
1963 Xex.Symbol name = sym.Name;
1966 return parse_cond (p);
1967 if (name == Qinsert)
1968 return parse_insert (p);
1969 if (name == Qselect)
1970 return parse_select (p);
1971 if (name == Qdelete || name == Qmove || name == Qmark)
1972 return parse_funcall_with_marker (p, name);
1974 return parse_shift (p);
1975 if (((string) name)[0] == '@')
1976 return parse_char_at (sym);
1977 if (name == Qset || name == Qadd || name == Qsub
1978 || name == Qmul || name == Qdiv)
1981 throw new Exception ("Invalid action: " + p);
1982 Xex.Symbol varname = p.Symbol.Name;
1983 Xex.Term[] args = new Xex.Term[1];
1984 args[0] = parse_action (p.next, true);
1985 return new Xex.Term (domain, name, varname, args);
1992 return new Xex.Term (domain, name, null);
1994 return new Xex.Term (domain, name, parse_actions (p, true));
1997 else if (plist.IsSymbol)
1998 return new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1999 else if (plist.IsMText)
2000 return (as_funarg ? new Xex.Term ((string) plist.Text)
2001 : parse_insert (plist));
2002 else if (plist.IsInteger)
2003 return (as_funarg ? new Xex.Term (plist.Integer)
2004 : parse_insert (plist));
2006 throw new Exception ("Invalid action: " + plist);
2009 private Xex.Term[] parse_actions (MPlist plist, bool as_funarg)
2011 Xex.Term[] terms = new Xex.Term[plist.Count];
2013 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
2014 terms[i] = parse_action (plist, as_funarg);
2018 private void parse_macros (MPlist plist)
2020 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
2023 MPlist p = pl.Plist;
2027 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null, null, true);
2029 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
2032 MPlist p = pl.Plist;
2036 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null,
2037 parse_actions (p.next, false), false);
2041 private void parse_maps (MPlist plist)
2043 for (; ! plist.IsEmpty; plist = plist.next)
2046 MPlist pl = plist.Plist;
2050 Map map = new Map (pl.Symbol);
2051 maps[pl.Symbol] = map;
2052 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
2056 MPlist p = pl.Plist;
2059 keys = new KeySeq (p.Text);
2061 keys = new KeySeq (p.Plist);
2066 = p.IsEmpty ? null : parse_actions (p, false);
2067 map.entries.Add (new Map.Entry (domain, keys, actions));
2072 private static Xex.Term Finsert (Xex.Domain domain, Xex.Variable vari,
2076 ((Context) domain.context).insert (args[0].Intval);
2078 ((Context) domain.context).insert (args[0].Strval);
2082 private static Xex.Term Finsert_candidates (Xex.Domain domain,
2086 Context ic = (Context) domain.context;
2087 Xex.Variable v = ic.domain.GetVar (Qcandidates_group_size, false);
2088 int column = (v == null ? 0 : v.Value.Intval);
2090 ic.insert_candidates (new Candidates (args, column));
2094 private static Xex.Term Fchar_at (Xex.Domain domain, Xex.Variable vari,
2097 Context ic = (Context) domain.context;
2098 Marker m = (Marker) args[0].Objval;
2100 return new Xex.Term (m.CharAt (ic));
2103 private static Xex.Term Fdelete (Xex.Domain domain, Xex.Variable vari,
2106 Context ic = (Context) domain.context;
2110 pos = args[0].Intval;
2113 Marker m = (Marker) args[0].Objval;
2114 pos = m.Position (ic);
2116 return new Xex.Term (ic.delete (pos));
2119 private static Xex.Term Fselect (Xex.Domain domain, Xex.Variable vari,
2122 Candidates can = ((Context) domain.context).candidates;
2127 can.Select (args[0].Intval);
2129 ((Selector) args[0].Objval).Select (can);
2134 private static Xex.Term Fshow (Xex.Domain domain, Xex.Variable vari,
2137 ((Context) domain.context).show ();
2141 private static Xex.Term Fhide (Xex.Domain domain, Xex.Variable vari,
2144 ((Context) domain.context).hide ();
2148 private static Xex.Term Fmove (Xex.Domain domain, Xex.Variable vari,
2151 Context ic = (Context) domain.context;
2152 int pos = (args[0].IsInt ? args[0].Intval
2153 : ((Marker) args[0].Objval).Position (ic));
2158 private static Xex.Term Fmark (Xex.Domain domain, Xex.Variable vari,
2161 Marker m = (Marker) args[0].Objval;
2162 m.Mark ((Context) domain.context);
2166 private static Xex.Term Fpushback (Xex.Domain domain, Xex.Variable vari,
2169 Context ic = (Context) domain.context;
2172 ic.pushback (args[0].Intval);
2173 else if (args[0].IsStr)
2174 ic.pushback (new KeySeq (args[0].Strval));
2176 ic.pushback ((KeySeq) args[0].Objval);
2180 private static Xex.Term Fpop (Xex.Domain domain, Xex.Variable vari,
2183 ((Context) domain.context).pop ();
2187 private static Xex.Term Fundo (Xex.Domain domain, Xex.Variable vari,
2190 int n = args.Length == 0 ? -2 : args[0].Intval;
2191 ((Context) domain.context).undo (n);
2195 private static Xex.Term Fcommit (Xex.Domain domain, Xex.Variable vari,
2198 ((Context) domain.context).commit ();
2202 private static Xex.Term Funhandle (Xex.Domain domain, Xex.Variable vari,
2205 ((Context) domain.context).commit ();
2206 args = new Xex.Term[2];
2207 args[0] = args[1] = Tcatch_tag;
2208 return Xex.Fthrow (domain, vari, args);
2211 private static Xex.Term Fshift (Xex.Domain domain, Xex.Variable vari,
2214 Context ic = (Context) domain.context;
2216 if (ic.im.states.TryGetValue (args[0].Symval, out state))
2217 ((Context) domain.context).shift (state);
2219 throw new Exception ("Unknown state: " + args[0].Symval);
2223 private static Xex.Term Fshiftback (Xex.Domain domain, Xex.Variable vari,
2226 ((Context) domain.context).shift (null);
2230 private static Xex.Term Fkey_count (Xex.Domain domain, Xex.Variable vari,
2233 return new Xex.Term (((Context) domain.context).key_head);
2236 private static Xex.Term Fsurrounding_flag (Xex.Domain domain,
2240 return new Xex.Term (GetSurroundingText == null ? 0 : 1);
2243 public override string ToString ()
2246 string str = (String.Format ("({0} (title \"{1}\")", tag, title));
2247 if (commands != null)
2249 str += " (commands";
2250 foreach (Command cmd in commands)
2254 if (var_names != null)
2256 str += " (variables";
2257 foreach (Xex.Symbol var in var_names)
2261 if (plugins != null)
2264 foreach (KeyValuePair<MSymbol, Plugin> kv in plugins)
2265 str += " " + kv.Value;
2269 foreach (KeyValuePair<MSymbol, Map> kv in maps)
2270 str += " " + kv.Value;
2272 foreach (KeyValuePair<Xex.Symbol, State> kv in states)
2274 str += " (" + kv.Key + " " + kv.Value.keymap + ")";
2279 public class Context
2281 internal MInputMethod im;
2282 internal Xex.Domain domain;
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 MPlist marker_positions = new MPlist ();
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 State state, prev_state;
2297 private MText state_preedit = new MText ();
2298 private int state_key_head;
2299 private object state_var_values, state_initial_var_values;
2300 private int state_pos;
2302 private Keymap keymap;
2303 // Sequence of input keys.
2304 internal KeySeq keys = new KeySeq ();
2305 // Index into KEYS specifying the next key to handle.
2306 internal int key_head;
2308 internal MText preceding_text = new MText ();
2309 internal MText following_text = new MText ();
2311 // Set to false before calling the method 'handle_key', and set
2312 // to true when some key is unhandled.
2313 private bool key_unhandled;
2315 // The unhandled key. It has the meaning only when
2316 // 'key_unhandled' is true.
2317 private Key unhandled_key;
2319 internal ChangedStatus changed;
2321 private void set_cursor (string prefix, int pos)
2326 internal void reset ()
2328 status = im.initial_state.title;
2332 set_cursor ("reset", 0);
2333 marker_positions.Clear ();
2335 candidate_show = false;
2337 state = im.initial_state;
2339 state_preedit.Del ();
2341 state_var_values = state_initial_var_values;
2344 keymap = im.initial_state.keymap;
2345 keys.keyseq.Clear ();
2347 preceding_text.Del ();
2348 following_text.Del ();
2350 changed = ChangedStatus.None;
2353 static Xex.Term[] catch_args = new Xex.Term[2];
2355 private bool take_actions (Xex.Term[] actions)
2357 catch_args[0] = Tcatch_tag;
2358 catch_args[1]= new Xex.Term (domain, Qprogn, actions);
2359 Xex.Term term = new Xex.Term (domain, Qcatch, catch_args);
2360 term = term.Eval (domain);
2361 return (! term.IsSymbol || term.Symval != Tcatch_tag.Symval);
2364 static MPlist callback_arg = new MPlist ();
2366 private bool get_surrounding_text (int len)
2368 if (len < 0 ? -len <= preceding_text.Length
2369 : len <= following_text.Length)
2371 if (GetSurroundingText == null)
2373 callback_arg.Set (MSymbol.integer, len);
2374 if (! GetSurroundingText (this, callback_arg)
2375 || ! callback_arg.IsMText)
2379 preceding_text = callback_arg.Text;
2380 return (-len <= preceding_text.Length);
2382 following_text = callback_arg.Text;
2383 return (len <= following_text.Length);
2386 internal int GetSurroundingChar (int pos)
2388 if (! get_surrounding_text (pos < 0 ? pos : pos + 1))
2391 return preceding_text[preceding_text.Length + pos];
2392 return following_text[pos];
2395 private void adjust_markers (int from, int to, object inserted)
2397 int ins = (inserted == null ? 0
2398 : inserted is int ? 1
2399 : ((MText) inserted).Length);
2400 int diff = ins - (to - from);
2402 for (MPlist p = marker_positions; ! p.IsEmpty; p = p.next)
2404 int pos = p.Integer;
2406 p.Set (p.Key, pos >= to ? pos + diff : from);
2408 if (cursor_pos >= to)
2409 set_cursor ("adjust", cursor_pos + diff);
2410 else if (cursor_pos > from)
2411 set_cursor ("adjust", from);
2414 private void preedit_replace (int from, int to, int c)
2416 preedit.Del (from, to);
2417 preedit.Ins (from, c);
2418 adjust_markers (from, to, c);
2421 private void preedit_replace (int from, int to, MText mt)
2423 preedit[from, to] = mt;
2424 adjust_markers (from, to, mt);
2427 internal void insert (int c)
2429 preedit_replace (cursor_pos, cursor_pos, c);
2430 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2433 internal void insert (string str)
2435 preedit_replace (cursor_pos, cursor_pos, (MText) str);
2436 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2439 private void update_candidate ()
2441 object candidate = candidates.Current;
2443 if (candidate is MText)
2445 preedit_replace (candidate_from, candidate_to, (MText) candidate);
2446 candidate_to = candidate_from + ((MText) candidate).Length;
2450 preedit_replace (candidate_from, candidate_to, (int) candidate);
2451 candidate_to = candidate_from + 1;
2453 preedit.PushProp (candidate_from, candidate_to,
2455 set_cursor ("update-candidate", candidate_to);
2456 changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
2460 internal void insert_candidates (Candidates candidates)
2462 this.candidates = candidates;
2463 candidate_from = candidate_to = cursor_pos;
2464 update_candidate ();
2467 internal void select (int n)
2469 if (candidates != null)
2471 candidates.Select (n);
2472 update_candidate ();
2476 internal int delete (int pos)
2478 int deleted = pos - cursor_pos;
2480 if (pos < cursor_pos)
2484 if (DeleteSurroundingText != null)
2486 callback_arg.Set (MSymbol.integer, pos);
2487 if (DeleteSurroundingText (this, callback_arg))
2489 if (callback_arg.IsInteger)
2490 deleted = callback_arg.Integer - cursor_pos;
2491 preceding_text.Del ();
2494 deleted = - cursor_pos;
2498 if (pos < cursor_pos)
2499 preedit_replace (pos, cursor_pos, null);
2503 if (pos > preedit.Length)
2505 if (DeleteSurroundingText != null)
2507 callback_arg.Set (MSymbol.integer, pos - preedit.Length);
2508 if (DeleteSurroundingText (this, callback_arg))
2510 if (callback_arg.IsInteger)
2511 deleted = callback_arg.Integer - cursor_pos;
2512 preceding_text.Del ();
2515 deleted = preedit.Length - cursor_pos;
2517 pos = preedit.Length;
2519 if (pos > cursor_pos)
2520 preedit_replace (cursor_pos, pos, null);
2523 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2527 internal void show ()
2529 candidate_show = true;
2530 changed |= ChangedStatus.CandidateShow;
2533 internal void hide ()
2535 candidate_show = false;
2536 changed |= ChangedStatus.CandidateShow;
2539 internal void move (int pos)
2543 else if (pos > preedit.Length)
2544 pos = preedit.Length;
2545 if (pos != cursor_pos)
2547 set_cursor ("move", pos);
2548 changed |= ChangedStatus.Preedit;
2552 internal void pushback (int n)
2565 if (key_head > keys.keyseq.Count)
2566 key_head = keys.keyseq.Count;
2570 internal void pushback (KeySeq keyseq)
2574 if (key_head < keys.keyseq.Count)
2575 keys.keyseq.RemoveRange (key_head, keys.keyseq.Count - key_head);
2576 for (int i = 0; i < keyseq.keyseq.Count; i++)
2577 keys.keyseq.Add (keyseq.keyseq[i]);
2580 internal void pop ()
2582 if (key_head < keys.keyseq.Count)
2583 keys.keyseq.RemoveRange (key_head, 1);
2586 internal void undo (int n)
2589 keys.keyseq.RemoveRange (keys.keyseq.Count + n, - n);
2591 keys.keyseq.RemoveRange (n, keys.keyseq.Count - n);
2595 internal void commit ()
2597 produced.Cat (preedit);
2598 preedit_replace (0, preedit.Length, null);
2599 changed |= ChangedStatus.Preedit;
2602 internal void shift (State state)
2606 if (prev_state == null)
2611 if (state == im.initial_state)
2614 keys.keyseq.RemoveRange (0, key_head);
2616 if (state != this.state)
2618 domain.RestoreValues (state_initial_var_values);
2619 if (state.enter_actions != null)
2620 take_actions (state.enter_actions);
2626 if (state != this.state && state.enter_actions != null)
2627 take_actions (state.enter_actions);
2628 prev_state = this.state;
2631 if (this.state.title != state.title)
2632 this.changed |= ChangedStatus.StateTitle;
2634 keymap = state.keymap;
2637 public Context (MInputMethod im)
2639 if (im.load_status != LoadStatus.Full
2641 throw new Exception ("Openging " + im.tag + " failed");
2643 domain = new Xex.Domain (im.domain, this);
2644 state_initial_var_values = domain.SaveValues ();
2647 if (PreeditChanged != null)
2649 callback_arg.Set (MSymbol.mtext, preedit);
2650 PreeditChanged (this, callback_arg);
2652 if (StatusChanged != null)
2654 callback_arg.Set (MSymbol.mtext, status);
2655 StatusChanged (this, callback_arg);
2659 public ChangedStatus Changed { get { return changed; } }
2661 internal object GetCandidates (out int column)
2664 if (cursor_pos == 0)
2666 Candidates candidates
2667 = (Candidates) preedit.GetProp (cursor_pos - 1, Mcandidates);
2668 if (candidates == null)
2670 column = candidates.Column;
2671 return candidates.Current;
2674 private void save_state ()
2676 state_var_values = domain.SaveValues ();
2677 state_preedit.Del ();
2678 state_preedit.Ins (0, preedit);
2679 state_key_head = key_head;
2680 state_pos = cursor_pos;
2683 private void restore_state ()
2685 domain.RestoreValues (state_var_values);
2687 preedit.Ins (0, state_preedit);
2688 set_cursor ("restore", state_pos);
2691 private bool handle_key ()
2693 Console.Write ("\nHandle ({0}[{1}]) in {2}",
2694 keys, key_head, state.name);
2696 Keymap sub = keymap.Lookup (keys, ref key_head);
2702 if (keymap.map_actions != null)
2704 if (! take_actions (keymap.map_actions))
2707 else if (keymap.submaps != null)
2709 for (int i = state_key_head; i < key_head; i++)
2710 preedit_replace (cursor_pos, cursor_pos,
2711 keys.keyseq[i].ToChar ());
2713 if (keymap.submaps == null)
2715 if (keymap.branch_actions != null)
2717 if (! take_actions (keymap.branch_actions))
2720 if (keymap != state.keymap)
2726 State current_state = state;
2728 if (keymap.branch_actions != null)
2730 if (! take_actions (keymap.branch_actions))
2733 if (state == current_state)
2735 if (state == im.initial_state
2736 && key_head < keys.keyseq.Count)
2738 if (keymap != state.keymap)
2740 else if (keymap.branch_actions == null)
2741 shift (im.initial_state);
2747 public bool Toggle ()
2753 public bool UnhandledKey (out Key key)
2755 key = unhandled_key;
2756 return key_unhandled;
2759 public MText Preedit { get { return preedit; } }
2760 public MText Produced { get { return produced; } }
2763 // true: All keys are handled and there's no text to commit.
2764 // false: Some key is left unhandled or there's a text to
2765 // commit. The caller should refer to UnhandledKey and
2768 public bool Filter (Key key)
2772 key_unhandled = true;
2773 unhandled_key = key;
2776 if (key == Key.Reload)
2778 changed = ChangedStatus.None;
2780 preceding_text.Del ();
2781 following_text.Del ();
2783 key_unhandled = false;
2784 keys.keyseq.Add (key);
2786 while (key_head < keys.keyseq.Count)
2788 if (! handle_key ())
2790 unhandled_key = keys.keyseq[key_head++];
2791 key_unhandled = true;
2797 keys.keyseq.RemoveRange (0, key_head);
2800 if ((changed & ChangedStatus.Preedit) != ChangedStatus.None
2801 && PreeditChanged != null)
2803 callback_arg.Set (MSymbol.mtext, preedit);
2804 PreeditChanged (this, callback_arg);
2806 if ((changed & ChangedStatus.StateTitle) != ChangedStatus.None
2807 && StatusChanged != null)
2809 callback_arg.Set (MSymbol.mtext, status);
2810 StatusChanged (this, callback_arg);
2812 if ((changed & ChangedStatus.Candidate) != ChangedStatus.None
2813 && CandidateChanged != null)
2815 CandidateChanged (this, callback_arg);
2818 Console.Write ("\nPreedit(\"{0}\"/{1}), Produced({2})",
2819 preedit, cursor_pos, produced);
2821 return (! key_unhandled && produced.Length == 0);