2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Reflection;
14 using Xex = System.Xml.Expression.Xexpression;
15 using Mim = MInputMethod;
17 public class MInputMethod
20 public delegate bool Callback (MInputContext ic, MPlist args);
23 public static Callback PreeditStart, PreeditDone, PreeditDraw;
24 public static Callback StatusStart, StatusDone, StatusDraw;
25 public static Callback CandidateStart, CandidateDone, CandidateDraw;
26 public static Callback SetSpot;
27 public static Callback Toggle;
28 public static Callback Reset;
29 public static Callback GetSurroundingText;
30 public static Callback DeleteSurroundingText;
32 internal static Xex.Domain im_domain = new Xex.Domain (null);
33 private static MSymbol Minput_method = "input-method";
34 private static MSymbol Mdescription = "description";
35 private static MSymbol Mvariable = "variable";
36 private static MSymbol Mcommand = "command";
37 private static MSymbol Mmodule = "module";
38 private static MSymbol Mtitle = "title";
39 private static MSymbol Minclude = "include";
40 private static MSymbol Mmacro = "macro";
41 private static MSymbol Mmap = "map";
42 private static MSymbol Mmap_list = "map-list";
43 private static MSymbol Mstate = "state";
44 internal static MSymbol Mcandidates = "candidates";
45 private static MSymbol Minsert = "insert";
46 private static MSymbol Mdelete = "delete";
47 private static MSymbol Mmove = "move";
48 private static MSymbol Mmark = "mark";
49 private static MSymbol Mmarker = "marker";
50 private static MSymbol Mset = "set";
51 private static MSymbol Madd = "add";
52 private static MSymbol Msub = "sub";
53 private static MSymbol Mmul = "mul";
54 private static MSymbol Mdiv = "div";
55 private static MSymbol Mif = "if";
56 private static MSymbol Mcond = "cond";
57 private static MSymbol Mchar_at = "char-at";
58 private static MSymbol Msurrounding_text_p = "surrounding-text-p";
59 private static MSymbol Mpushback = "pushback";
60 private static MSymbol Mkeyseq = "keyseq";
62 private static Xex.Symbol Nprogn = "progn";
63 private static Xex.Term Tnil = new Xex.Term ((Xex.Symbol) "nil");
64 private static Xex.Term Tcatch_tag = new Xex.Term ((Xex.Symbol) "@mimtag");
66 private static Dictionary<MDatabase.Tag, MInputMethod> im_table
67 = new Dictionary<MDatabase.Tag, MInputMethod> ();
69 internal static MInputMethod im_global = null;
72 private enum LoadStatus
82 public enum ChangedStatus
89 CandidateIndex = 0x10,
93 private static ChangedStatus CandidateAll = (ChangedStatus.CandidateList
94 | ChangedStatus.CandidateIndex
95 | ChangedStatus.CandidateShow);
97 public enum KeyModifier
100 Shift_L = 0x00400000,
101 Shift_R = 0x00800000,
103 Control_L = 0x01000000,
104 Control_R = 0x02000000,
105 Control = 0x03000000,
120 private static Dictionary<string, uint> keysyms
121 = new Dictionary<string, uint> ();
122 private static Dictionary<string, KeyModifier> keymodifiers
123 = new Dictionary<string, KeyModifier> ();
124 private static uint keysym_base = 0x200000;
125 private static uint char_mask = ~((uint) KeyModifier.All);
129 keysyms["bs"] = keysyms["backspace"] = 0x08;
130 keysyms["tab"] = 0x09;
131 keysyms["lf"] = keysyms["linefeed"] = 0x10;
132 keysyms["cr"] = keysyms["return"] = keysyms["enter"] = 0x13;
133 keysyms["esc"] = keysyms["escape"] = 0x1B;
134 keysyms["spc"] = keysyms["space"] = 0x20;
135 keysyms["del"] = keysyms["delete"] = 0x7F;
136 keymodifiers["shift-l"] = KeyModifier.Shift_L;
137 keymodifiers["shift-r"] = KeyModifier.Shift_R;
138 keymodifiers["shift"] = KeyModifier.Shift;
139 keymodifiers["control-l"] = KeyModifier.Control_L;
140 keymodifiers["control-r"] = KeyModifier.Control_R;
141 keymodifiers["control"] = KeyModifier.Control;
142 keymodifiers["alt-l"] = KeyModifier.Alt_L;
143 keymodifiers["alt-r"] = KeyModifier.Alt_R;
144 keymodifiers["alt"] = KeyModifier.Alt;
145 keymodifiers["altgr"] = KeyModifier.AltGr;
146 keymodifiers["super"] = KeyModifier.Super;
147 keymodifiers["hyper"] = KeyModifier.Hyper;
150 private static uint decode_keysym (MSymbol keysym)
153 string name = keysym.Name;
155 if (name.Length == 1)
157 name = name.ToLower ();
158 if (! keysyms.TryGetValue (name, out key))
159 keysyms[name] = key = keysym_base++;
163 private static uint combine_modifiers (uint c, KeyModifier modifiers)
165 if (c < 0x7F && c != 0x20)
167 if ((modifiers & KeyModifier.Shift) != KeyModifier.None
168 && Char.IsLower ((char) c))
170 modifiers &= ~KeyModifier.Shift;
171 c = Char.ToUpper ((char) c);
173 if ((modifiers & KeyModifier.Control) != KeyModifier.None)
175 modifiers &= ~KeyModifier.Control;
179 return c | (uint) modifiers;
182 public Key (uint c) { key = c; }
183 public Key (int c) { key = (uint) c; }
185 public Key (uint c, KeyModifier modifiers)
187 key = combine_modifiers (c, modifiers);
190 public Key (MSymbol keysym, KeyModifier modifiers)
192 key = combine_modifiers (decode_keysym (keysym), modifiers);
195 public Key (MSymbol keysym)
197 string str = keysym.Name;
198 int len = str.Length;
200 KeyModifier modifiers = KeyModifier.None;
202 for (i = 0; i + 2 < len && str[i + 1] == '-'; i += 2)
205 modifiers |= KeyModifier.Shift;
206 else if (str[i] == 'C')
207 modifiers |= KeyModifier.Control;
208 else if (str[i] == 'A')
209 modifiers |= KeyModifier.Alt;
210 else if (str[i] == 'G')
211 modifiers |= KeyModifier.AltGr;
212 else if (str[i] == 's')
213 modifiers |= KeyModifier.Super;
214 else if (str[i] == 'H')
215 modifiers |= KeyModifier.Hyper;
218 key = combine_modifiers (str[i], modifiers);
220 key = combine_modifiers (decode_keysym (keysym), modifiers);
223 public Key (MPlist plist)
225 KeyModifier modifiers = KeyModifier.None;
228 for (p = plist; ! p.IsEmpty; p = p.next)
232 if (! p.next.IsEmpty)
233 throw new Exception ("Invalid Key: " + plist);
236 else if (! p.IsSymbol)
237 throw new Exception ("Invalid Key: " + plist);
240 string name = p.Symbol.Name.ToLower ();
243 if (! keymodifiers.TryGetValue (name, out m))
248 if (p.IsEmpty || ! p.next.IsEmpty)
249 throw new Exception ("Invalid Key: " + plist);
251 key = combine_modifiers ((uint) p.Integer, modifiers);
253 key = combine_modifiers (decode_keysym (p.Symbol), modifiers);
256 public bool HasModifier
258 get { return ((key & (uint) KeyModifier.All) != 0); }
261 public bool Match (Key k)
265 if ((k.key & char_mask) != (key & char_mask))
267 KeyModifier m1 = ((KeyModifier) key) & KeyModifier.All;
268 KeyModifier m2 = ((KeyModifier) k.key) & KeyModifier.All;
269 return (((m1 & KeyModifier.Shift) == (m2 & KeyModifier.Shift)
270 || ((m1 & KeyModifier.Shift) == KeyModifier.Shift
271 && (m2 & KeyModifier.Shift) != KeyModifier.None))
272 && ((m1 & KeyModifier.Control) == (m2 & KeyModifier.Control)
273 || ((m1 & KeyModifier.Control) == KeyModifier.Control
274 && (m2 & KeyModifier.Control) != KeyModifier.None))
275 && ((m1 & KeyModifier.Alt) == (m2 & KeyModifier.Alt)
276 || ((m1 & KeyModifier.Alt) == KeyModifier.Alt
277 && (m2 & KeyModifier.Alt) != KeyModifier.None))
278 && ((m1 & KeyModifier.High) == (m2 & KeyModifier.High)));
281 public override string ToString ()
283 string str = Char.ToString ((char) key);
284 KeyModifier m = ((KeyModifier) key) & KeyModifier.All;
286 if (m != KeyModifier.None)
288 if ((m & KeyModifier.Shift) != KeyModifier.None)
290 if ((m & KeyModifier.Control) != KeyModifier.None)
292 if ((m & KeyModifier.Alt) != KeyModifier.None)
294 if ((m & KeyModifier.AltGr) != KeyModifier.None)
296 if ((m & KeyModifier.Super) != KeyModifier.None)
298 if ((m & KeyModifier.Hyper) != KeyModifier.None)
305 public class KeySeq : Xex.TermValue
307 public List<Key> keyseq = new List<Key> ();
309 public override Xex.TermValue Clone ()
311 KeySeq ks = new KeySeq ();
312 ks.keyseq.InsertRange (0, keyseq);
318 public KeySeq (MPlist plist)
320 foreach (MPlist p in plist)
323 keyseq.Add (new Key (p.Symbol));
324 else if (p.IsInteger)
325 keyseq.Add (new Key ((char) p.Integer));
327 keyseq.Add (new Key (p.Plist));
329 throw new Exception ("Invalid Key Sequence: " + plist);
333 public KeySeq (MText mt) : base ()
335 for (int i = 0; i < mt.Length; i++)
336 keyseq.Add (new Key ((uint) mt[i]));
339 private static uint parse_integer (string str)
341 if (Char.IsDigit (str[0]))
343 if (str[0] == '0' && str.Length > 2 && str[1] == 'x')
346 for (int idx = 2; idx < str.Length; idx++)
349 if (c >= '0' && c <= '9')
350 i = i * 16 + (c - '0');
351 else if (c >= 'A' && c <= 'F')
352 i = i * 16 + 10 + (c - 'A');
353 else if (c >= 'a' && c <= 'f')
354 i = i * 16 + 10 + (c - 'a');
360 return UInt32.Parse (str);
362 else if (str[0] == '?')
367 public KeySeq (List<Xex.Term> list)
369 int len = list.Count;
371 for (int i = 0; i < len; i++)
374 keyseq.Add (new Key (list[i].Intval));
375 else if (list[i].IsStr)
376 keyseq.Add (new Key (list[i].Strval));
377 else if (list[i].IsSymbol)
378 keyseq.Add (new Key ((string) list[i].Symval));
380 throw new Exception ("Invalid key: " + list[i]);
384 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
386 Xex.Term term = new Xex.Term (domain, node.FirstChild).Eval (domain);
387 return (term.IsStr ? new KeySeq ((MText) term.Strval)
388 : new KeySeq (term.Listval));
391 public override string ToString ()
395 foreach (Key key in keyseq)
399 foreach (Key k in keyseq)
400 str += " " + k.ToString ();
404 foreach (Key key in keyseq)
405 str += key.ToString ();
410 public class Variable
413 public MText description;
416 public object[] candidates;
418 public Variable (MPlist p)
422 description = parse_description (p);
423 if (description == null)
424 description = new MText ("No description");
427 type = (p.IsMText ? typeof (MText)
428 : p.IsInteger ? typeof (int)
429 : p.IsSymbol ? typeof (MSymbol)
433 candidates = new object[p.Count];
434 for (int i = 0; ! p.IsEmpty; i++, p = p.next)
435 candidates[i] = p.val;
438 private static Type parse_value (XmlNode node, out object value)
440 string typename = node.Attributes["type"].Value;
443 if (typename == "integer")
446 if (! Int32.TryParse (node.InnerText, out i))
451 else if (typename == "string")
453 MText mt = node.InnerText;
455 type = typeof (MText);
457 else if (typename == "symbol")
459 MSymbol sym = node.InnerText;
461 type = typeof (MSymbol);
466 type = typeof (object);
471 public Variable (XmlNode node)
473 name = node.Attributes["id"].Value;
474 for (node = node.FirstChild; node != null; node = node.NextSibling)
475 if (node.NodeType == XmlNodeType.Element)
477 if (node.Name == "description")
478 description = parse_description (node);
479 else if (node.Name == "value")
480 type = parse_value (node, out value);
481 else if (node.Name == "valiable-value-candidate")
483 XmlNodeList n_list = node.ChildNodes;
484 candidates = new object[n_list.Count];
485 for (int i = 0; i < n_list.Count; i++)
488 parse_value (n_list[i], out val);
495 public override string ToString ()
497 return ("(" + name + " \"" + (string) description
498 + "\" " + type + " " + value + " " + candidates + ")");
505 public MText description;
506 public List<KeySeq> keys;
508 public Command (MPlist p)
512 description = parse_description (p);
513 if (description == null)
514 description = "No description";
515 keys = new List<KeySeq> ();
516 Console.WriteLine ("cmd:" + p);
517 for (p = p.next; ! p.IsEmpty; p = p.next)
520 keys.Add (new KeySeq (p.Text));
522 keys.Add (new KeySeq (p.Plist));
526 public Command (XmlNode node)
528 name = node.Attributes[0].Value;
529 keys = new List<KeySeq> ();
530 for (node = node.FirstChild; node != null; node = node.NextSibling)
532 if (node.Name == "description")
533 description = parse_description (node);
534 else if (node.Name == "keyseq")
535 keys.Add ((KeySeq) KeySeq.parser (null, node));
539 public override string ToString ()
541 string str = "(" + name + " \"" + (string) description;
542 foreach (KeySeq keyseq in keys)
548 internal class Plugin
551 private Assembly assembly;
552 private Type plugin_type;
554 public Plugin (string name)
559 public MethodInfo GetMethod (Xex.Symbol name)
561 if (assembly == null)
563 assembly = Assembly.LoadFrom (name + ".dll");
564 plugin_type = assembly.GetType ("M17n.MInputMethod.Plugin");
567 MethodInfo info = plugin_type.GetMethod ((string) name);
569 throw new Exception ("Invalid plugin method: " + name);
573 public override string ToString ()
575 return String.Format ("(module {0}", name);
579 internal class PluginMethod : Xex.Function
581 private Plugin plugin;
582 private MethodInfo method_info;
583 object[] parameters = new object[2];
585 public PluginMethod (Plugin plugin, string name)
586 : base ((Xex.Symbol) name, 0, -1)
588 this.plugin = plugin;
591 public override Xex.Term Call (Xex.Domain domain, Xex.Variable vari,
594 args = (Xex.Term[]) args.Clone ();
595 for (int i = 0; i < args.Length; i++)
597 args[i] = args[i].Eval (domain);
601 if (method_info == null)
602 method_info = plugin.GetMethod (name);
603 parameters[0] = domain.context;
604 parameters[1] = args;
605 return (Xex.Term) method_info.Invoke (null, parameters);
609 internal abstract class Marker : Xex.TermValue
611 private MSymbol name;
613 public Marker (MSymbol name)
618 public abstract int Position (MInputContext ic);
619 public abstract void Mark (MInputContext ic);
621 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
623 MSymbol name = node.InnerText;
625 return Get ((MInputContext) domain.context, name);
628 public class Named : Marker
632 public Named (MSymbol name) : this (name, 0) { }
634 private Named (MSymbol name, int p) : base (name) { pos = p; }
636 public override int Position (MInputContext ic) { return pos; }
638 public override void Mark (MInputContext ic) { pos = ic.cursor_pos; }
640 public override Xex.TermValue Clone ()
642 return new Named (name, pos);
646 public class Predefined : Marker
648 public Predefined (MSymbol name) : base (name) { }
650 public override int Position (MInputContext ic)
652 switch (name.Name[1]) {
654 case '>': return ic.preedit.Length;
655 case '-': return ic.cursor_pos - 1;
656 case '+': return ic.cursor_pos + 1;
658 if (ic.cursor_pos > 0)
660 int pos = ic.cursor_pos;
662 ic.preedit.FindProp (Mcandidates, pos - 1, out pos, out to);
667 if (ic.cursor_pos < ic.preedit.Length - 1)
669 int pos = ic.cursor_pos;
671 ic.preedit.FindProp (Mcandidates, pos, out from, out pos);
674 return ic.preedit.Length;
676 return name.Name[1] - '0';
680 public override void Mark (MInputContext ic)
682 throw new Exception ("Can't set predefined marker: " + name);
685 public override Xex.TermValue Clone ()
687 return new Predefined (name);
691 static internal Dictionary<MSymbol,Predefined> predefined_markers;
695 predefined_markers = new Dictionary<MSymbol,Predefined> ();
696 MSymbol[] symlist = new MSymbol[] {"@<", "@>", "@-", "@+", "@[", "@]",
697 "@0", "@1", "@2", "@3", "@4",
698 "@5", "@6", "@7", "@8", "@9" };
699 foreach (MSymbol s in symlist)
700 predefined_markers[s] = new Predefined (s);
703 public static Marker Get (MInputContext ic, MSymbol name)
708 if (predefined_markers.TryGetValue (name, out pred))
710 if (name.Name[0] == '@')
711 throw new Exception ("Invalid marker name: " + name);
712 m = (Marker) ic.markers.Get (name);
715 m = new Named (name);
716 ic.markers.Put (name, m);
722 internal class Candidates
729 public Block (int index, Xex.Term term)
733 Data = (MText) term.Strval;
736 MPlist plist = new MPlist ();
738 foreach (Xex.Term t in term.Listval)
739 p = p.Add (MSymbol.mtext, (MText) t.Strval);
744 public Block (int index, MPlist plist)
749 else if (plist.IsPlist)
752 throw new Exception ("Invalid candidate: " + plist);
757 get { return (Data is MText
758 ? ((MText) Data).Length
759 : ((MPlist) Data).Count); }
762 public object this[int i]
765 if (Data is MText) return ((MText) Data)[i];
766 return ((MPlist) Data)[i];
771 private Block[] blocks;
773 private int index = 0;
774 public object[] group;
776 private bool IsFixed { get { return group != null; } }
779 Block last = blocks[blocks.Length - 1];
780 return last.Index + last.Count; }
784 get { return (IsFixed ? index % group.Length
785 : index - blocks[row].Index); }
788 public object Group {
789 get { return (IsFixed ? group : blocks[row].Data); }
792 public int GroupLength
797 int nitems = group.Length;
798 int start = index - (index % nitems);
800 return (start + nitems <= total ? nitems : total - start);
802 return blocks[row].Count;
806 public object Current {
808 return (IsFixed ? group[index % group.Length]
809 : blocks[row][index - blocks[row].Index]);
813 public Candidates (MPlist list, int column)
815 int nblocks = list.Count;
817 blocks = new Block[nblocks];
818 for (int i = 0, start = 0; i < nblocks; i++, list = list.next)
819 start += (blocks[i] = new Block (index, list)).Count;
821 group = new object[column];
824 public Candidates (List<Xex.Term> list, int column)
826 int nblocks = list.Count;
828 blocks = new Block[nblocks];
829 for (int i = 0, start = 0; i < nblocks; i++)
830 start += (blocks[i] = new Block (index, list[i])).Count;
832 group = new object[column];
835 public static void Detach (MInputContext ic)
837 ic.preedit.PopProp (0, ic.preedit.Length, Mcandidates);
838 ic.candidates = null;
839 ic.changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
843 // Fill the array "group" by candidates stating from INDEX.
844 // INDEX must be a multiple of "column". Set NTIMES to the
845 // number of valid candidates in "group". Update "block" if
846 // necessary. Return "group".
848 private int fill_group (int start)
850 int nitems = group.Length;
855 while (start < b.Index)
858 while (start >= b.Index + b.Count)
864 for (int i = 0; i < nitems; i++, start++)
869 if (r == blocks.Length)
880 // Update "row" to what contains the first candidate of
881 // the previous candidate-group, update "current_index", and
882 // update "group" if necessary. Return the previous
883 // candidate-group. Set NITEMS to the number of valid
884 // candidates contained in that group.
886 public int PrevGroup ()
893 nitems = group.Length;
894 if ((index -= col + nitems) < 0)
895 index = (Total / nitems) * nitems;
896 nitems = fill_group (index);
900 row = row > 0 ? row-- : blocks.Length - 1;
901 nitems = blocks[row].Count;
902 index = blocks[row].Index;
904 index += col < nitems ? col : nitems - 1;
908 public int NextGroup ()
915 nitems = group.Length;
916 if ((index += nitems - col) >= Total)
918 nitems = fill_group (index);
922 row = row < blocks.Length - 1 ? row + 1 : 0;
923 nitems = blocks[row].Count;
924 index = blocks[row].Count;
926 index += col < nitems ? col : nitems - 1;
936 int nitems = PrevGroup ();
937 index += col < nitems - 1 ? col : nitems - 1;
946 int nitems = GroupLength;
948 if (col == nitems - 1)
950 nitems = NextGroup ();
964 index += GroupLength - (Column + 1);
967 public void Select (int col)
969 int maxcol = GroupLength - 1;
972 index = index - Column + col;
976 internal abstract class Selector : Xex.TermValue
978 private Selector () { }
980 public abstract void Select (Candidates candidates);
982 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
984 MSymbol name = node.InnerText;
987 if (predefined_selectors.TryGetValue (name, out pred))
989 if (name.Name[0] == '@')
990 throw new Exception ("Invalid selector name: " + name);
992 if (! Int32.TryParse (node.InnerText, out index))
993 throw new Exception ("Invalid selector name: " + name);
994 return new Numbered (index);
997 public override Xex.TermValue Clone () { return this; }
999 public class Numbered : Selector
1003 public Numbered (int index) { this.index = index; }
1005 public override void Select (Candidates can) { can.Select (index); }
1008 public class Predefined : Selector
1012 internal Predefined (MSymbol sym) { this.tag = sym.Name[1]; }
1014 public override void Select (Candidates can)
1018 case '<': candidates.First (); break;
1019 case '>': candidates.Last (); break;
1020 case '-': candidates.Prev (); break;
1021 case '+': candidates.Next (); break;
1022 case '[': candidates.PrevGroup (); break;
1023 case ']': candidates.NextGroup (); break;
1029 static new Dictionary<MSymbol, Predefined> predefined_selectors;
1033 predefined_selectors = new Dictionary<MSymbol, Predefined> ();
1034 MSymbol[] symlist = new MSymbol[] { "@<", "@=", "@>", "@-", "@+",
1036 foreach (MSymbol s in symlist)
1037 predefined_selectors[s] = new Predefined (s);
1043 public MSymbol name;
1044 public Dictionary<Key, Map> submaps;
1045 public Xex.Term actions;
1047 public void Add (KeySeq keys, int index, Xex.Term actions)
1051 if (submaps == null)
1052 submaps = new Dictionary<Key, Map> ();
1054 submaps.TryGetValue (keys.keyseq[index], out sub);
1057 Key key = keys.keyseq[index];
1058 submaps[key] = sub = new Map ();
1060 if (index + 1 < keys.keyseq.Count)
1061 sub.Add (keys, index + 1, actions);
1063 this.actions = actions;
1066 public Xex.Term Lookup (KeySeq keys, int index)
1070 if (index + 1 == keys.keyseq.Count)
1072 if (submaps.TryGetValue (keys.keyseq[index], out sub))
1073 return sub.Lookup (keys, index + 1);
1077 private void describe (MText mt, KeySeq keyseq)
1079 if (keyseq.keyseq.Count > 0)
1081 mt.Cat (" (").Cat (keyseq.ToString ());
1082 mt.Cat (' ').Cat (actions.ToString ());
1085 if (submaps != null)
1086 foreach (KeyValuePair<Key, Map> kv in submaps)
1088 keyseq.keyseq.Add (kv.Key);
1089 kv.Value.describe (mt, keyseq);
1090 keyseq.keyseq.RemoveAt (keyseq.keyseq.Count - 1);
1094 public override string ToString ()
1096 MText mt = "(" + name.Name;
1097 KeySeq keyseq = new KeySeq ();
1099 describe (mt, keyseq);
1105 internal class State
1107 public MSymbol name;
1109 public MPlist branches = new MPlist ();
1111 public State (MSymbol name)
1116 public override string ToString ()
1118 MText mt = "(" + name.Name;
1121 mt.Cat (" \"" + title + "\"");
1122 for (MPlist p = branches; ! p.IsEmpty; p = p.next)
1123 mt.Cat (" (" + p.Key + " " + (Xex) p.Val + ")");
1124 return (string) mt + ")";
1129 internal Xex.Domain domain = new Xex.Domain (im_domain, null);
1131 private LoadStatus load_status = LoadStatus.None;
1132 private MDatabase.Tag tag;
1133 private MDatabase mdb;
1135 private MText description;
1136 internal MText title;
1137 internal Command[] commands;
1138 internal Xex.Symbol[] var_names;
1139 internal Dictionary<MSymbol, Plugin> plugins;
1140 internal Dictionary<MSymbol, Map> maps;
1141 internal MPlist states;
1143 static MInputMethod ()
1145 im_domain.DefTerm ("keyseq", KeySeq.parser);
1146 im_domain.DefTerm ("marker", Marker.parser);
1147 im_domain.DefTerm ("selector", Selector.parser);
1149 im_domain.DefSubr (Finsert, "insert", true, 1, 1);
1150 im_domain.DefSubr (Finsert_candidates, "candidates", true, 1, -1);
1151 im_domain.DefSubr (Fdelete, "delete", true, 1, 1);
1152 im_domain.DefSubr (Fselect, "select", true, 1, 1);
1153 im_domain.DefSubr (Fshow, "show", true, 0, 0);
1154 im_domain.DefSubr (Fhide, "hide", true, 0, 0);
1155 im_domain.DefSubr (Fmove, "move", true, 1, 1);
1156 im_domain.DefSubr (Fmark, "mark", true, 1, 1);
1157 im_domain.DefSubr (Fpushback, "pushback", true, 1, 1);
1158 im_domain.DefSubr (Fpop, "pop", true, 0, 0);
1159 im_domain.DefSubr (Fundo, "undo", true, 0, 1);
1160 im_domain.DefSubr (Fcommit, "commit", true, 0, 0);
1161 im_domain.DefSubr (Funhandle, "unhandle", true, 0, 0);
1162 im_domain.DefSubr (Fshift, "shift", true, 1, 1);
1163 im_domain.DefSubr (Fmarker, "marker", true, 1, 1);
1164 im_domain.DefSubr (Fchar_at, "char-at", true, 1, 1);
1166 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, "*", "*", "*");
1167 List<MDatabase> list = MDatabase.List (tag);
1168 M17n.DebugPrint ("Found {0} input methods\n", list.Count);
1169 foreach (MDatabase mdb in list)
1170 im_table[mdb.tag] = new MInputMethod (mdb.tag);
1174 private MInputMethod (MDatabase.Tag tag)
1179 // Instance Properties
1180 public MSymbol Language { get { return tag[1]; } }
1181 public MSymbol Name { get { return tag[2]; } }
1182 public MSymbol SubName { get { return tag[3]; } }
1184 public bool Info (out MText description,
1186 out Xex.Variable[] variables,
1187 out Command[] commands)
1189 if ((load_status & LoadStatus.Header) != LoadStatus.Header
1190 && ! load_header ())
1198 description = this.description;
1200 if (var_names == null)
1204 variables = new Xex.Variable[var_names.Length];
1206 foreach (Xex.Symbol name in var_names)
1207 variables[i++] = domain.GetVar (name, false);
1209 commands = this.commands;
1213 public static MInputMethod Find (MSymbol language, MSymbol name)
1215 return Find (language, name, MSymbol.nil);
1218 public static MInputMethod Find (MSymbol language, MSymbol name,
1221 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, language,
1225 return (im_table.TryGetValue (tag, out im) ? im : null);
1230 return ((load_status == LoadStatus.Full) || load_body ());
1233 public static MInputMethod[] List ()
1235 MInputMethod[] array = new MInputMethod[im_table.Count];
1238 foreach (KeyValuePair<MDatabase.Tag, MInputMethod> kv in im_table)
1239 array[i++] = kv.Value;
1243 private bool load_header ()
1245 mdb = MDatabase.Find (tag);
1248 mdb.name_table = Xex.Symbol.Table;
1250 MSymbol format = mdb.Format;
1252 if (format == MSymbol.plist)
1253 load ((MPlist) mdb.Load (Mmap), false);
1256 XmlDocument doc = (XmlDocument) mdb.Load (Mmap_list);
1257 load (doc.DocumentElement, false);
1259 } catch (Exception e) {
1260 Console.WriteLine ("{0}\n", e);
1261 load_status = LoadStatus.Error;
1264 load_status |= LoadStatus.Header;
1268 private bool load_body ()
1270 mdb = MDatabase.Find (tag);
1273 mdb.name_table = Xex.Symbol.Table;
1275 object obj = mdb.Load ();
1277 load ((MPlist) obj, true);
1279 load ((XmlDocument) obj, true);
1280 } catch (Exception e) {
1281 Console.WriteLine (e);
1282 load_status = LoadStatus.Error;
1285 load_status = LoadStatus.Full;
1289 private void load (MPlist plist, bool full)
1291 maps = new Dictionary<MSymbol, Map> ();
1292 states = new MPlist ();
1294 for (; ! plist.IsEmpty; plist = plist.next)
1297 MPlist pl = plist.Plist;
1300 MSymbol sym = pl.Symbol;
1303 if (sym == Mdescription)
1304 description = parse_description (pl);
1305 else if (sym == Mtitle)
1310 else if (sym == Mvariable)
1311 parse_variables (pl);
1312 else if (sym == Mcommand)
1313 parse_commands (pl);
1318 else if (sym == Minclude)
1320 else if (sym == Mmacro)
1322 else if (sym == Mmap)
1324 else if (sym == Mstate)
1329 if (description == null)
1330 description = (MText) "No description";
1332 title = new MText (tag[2].Name);
1333 if (commands == null)
1334 commands = new Command[0];
1339 State state = new State ((MSymbol) "init");
1340 plist = new MPlist ();
1341 foreach (KeyValuePair<MSymbol, Map>kv in maps)
1342 state.branches.Add (kv.Key, null);
1343 states.Add (state.name, state);
1347 private void load (XmlNode node, bool full)
1349 bool skip_header = load_status == LoadStatus.Header;
1351 maps = new Dictionary<MSymbol, Map> ();
1352 states = new MPlist ();
1354 if (node.NodeType == XmlNodeType.Document)
1355 node = node.FirstChild;
1356 while (node.NodeType != XmlNodeType.Element)
1357 node = node.NextSibling;
1358 for (node = node.FirstChild; node != null; node = node.NextSibling)
1360 if (node.NodeType != XmlNodeType.Element)
1364 if (node.Name == "description")
1365 description = parse_description (node);
1366 else if (node.Name == "title")
1367 title = parse_title (node);
1368 else if (node.Name == "variable-list")
1369 parse_variables (node);
1370 else if (node.Name == "command-list")
1371 parse_commands (node);
1375 if (node.Name == "module-list")
1376 parse_plugins (node);
1377 else if (node.Name == "macro-list")
1378 parse_macros (node);
1379 else if (node.Name == "map-list")
1381 else if (node.Name == "state-list")
1382 parse_states (node);
1385 if (description == null)
1386 description = (MText) "No description";
1388 title = new MText (tag[2].Name);
1389 if (commands == null)
1390 commands = new Command[0];
1395 State state = new State ((MSymbol) "init");
1396 foreach (KeyValuePair<MSymbol, Map>kv in maps)
1397 state.branches.Add (kv.Key, null);
1398 states.Add (state.name, state);
1402 private static void transform (MPlist plist)
1404 for (; ! plist.IsEmpty; plist = plist.next)
1408 MPlist p = new MPlist ();
1409 p.Add (MSymbol.symbol, Minsert);
1410 p.Add (MSymbol.mtext, plist.Text);
1411 plist.Set (MSymbol.plist, p);
1413 else if (plist.IsInteger)
1415 MPlist p = new MPlist ();
1416 p.Add (MSymbol.symbol, Minsert);
1417 p.Add (MSymbol.integer, plist.Integer);
1418 plist.Set (MSymbol.plist, p);
1420 else if (plist.IsPlist)
1422 MPlist pl = plist.Plist;
1426 if (pl.Symbol == Madd)
1427 pl.Set (MSymbol.symbol, (MSymbol) "+=");
1428 else if (pl.Symbol == Msub)
1429 pl.Set (MSymbol.symbol, (MSymbol) "-=");
1430 else if (pl.Symbol == Mmul)
1431 pl.Set (MSymbol.symbol, (MSymbol) "*=");
1432 else if (pl.Symbol == Mdiv)
1433 pl.Set (MSymbol.symbol, (MSymbol) "/=");
1434 else if (pl.Symbol == Minsert)
1436 // (insert (CANDIDATES ...))
1437 // => (candidates CANDIDATES ...)
1438 if (pl.next.IsPlist)
1440 pl.Set (MSymbol.symbol, Mcandidates);
1442 MPlist p = pl.Plist;
1443 pl.Set (p.key, p.val);
1444 for (p = p.next; ! p.IsEmpty; p = p.next);
1445 pl.Add (p.key, p.val);
1448 else if (pl.Symbol == Mif)
1452 transform (pl.next);
1454 else if (pl.Symbol == Mcond)
1456 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1459 MPlist p = pl.Plist;
1467 else if (pl.Symbol == Mdelete
1468 || pl.Symbol == Mmove
1469 || pl.Symbol == Mmark)
1474 MSymbol sym = pl.Symbol;
1475 MPlist p = new MPlist ();
1476 p.Add (MSymbol.symbol, Mmarker);
1477 p.Add (MSymbol.symbol, sym);
1478 pl.Set (MSymbol.plist, p);
1481 else if (pl.Symbol == Mpushback)
1485 pl.Plist.Push (MSymbol.symbol, Mkeyseq);
1488 else if (pl.IsMText)
1490 // (CANDIDATES ...) => (candidates CANDIDATES ...)
1491 pl.Push (MSymbol.symbol, Mcandidates);
1494 else if (plist.IsSymbol)
1496 MSymbol sym = plist.Symbol;
1498 if (sym.Name.Length >= 3
1499 && sym.Name[0] == '@'
1500 && (sym.Name[1] == '-' || sym.Name[1] == '+'))
1502 int pos = int.Parse (sym.Name.Substring (1));
1503 MPlist p = new MPlist ();
1507 p.Add (MSymbol.symbol, Msurrounding_text_p);
1511 if (sym.Name[1] == '+')
1513 p.Add (MSymbol.symbol, Mchar_at);
1514 p.Add (MSymbol.integer, pos);
1516 plist.Set (MSymbol.plist, p);
1522 private static MText parse_description (MPlist plist)
1528 plist = plist.Plist;
1529 if (plist.IsSymbol && plist.Symbol == (MSymbol) "_"
1530 && plist.next.IsMText)
1531 return plist.next.Text;
1536 private static MText parse_description (XmlNode node)
1538 if (node.HasChildNodes)
1539 node = node.FirstChild;
1540 return node.InnerText;
1543 private static MText parse_title (XmlNode node)
1545 return node.InnerText;
1548 private void new_variable (Xex.Symbol name, string desc, int val,
1549 MPlist pl, Xex.Variable vari)
1557 range = new int[pl.Count * 2];
1558 for (int i = 0; i < range.Length; i++)
1562 MPlist p = pl.Plist;
1564 if (! p.IsInteger || ! p.next.IsInteger)
1565 throw new Exception ("Invalid range: " + p);
1566 range[i * 2] = p.Integer;
1567 range[i * 2 + 1] = p.next.Integer;
1569 else if (pl.IsInteger)
1570 range[i * 2] = range[i * 2 + 1] = pl.Integer;
1572 throw new Exception ("Invalid range: " + pl);
1576 domain.Defvar (new Xex.Variable.Int (name, desc, val, range));
1579 Xex.Term term = new Xex.Term (val);
1581 vari.DefaultValue = term;
1586 private void new_variable (Xex.Symbol name, string desc, MText val,
1587 MPlist pl, Xex.Variable vari)
1595 range = new string[pl.Count * 2];
1596 for (int i = 0; i < range.Length; i++)
1599 range[i] = (string) pl.Text;
1601 throw new Exception ("Invalid range: " + pl);
1605 domain.Defvar (new Xex.Variable.Str (name, desc, (string) val, range));
1608 Xex.Term term = new Xex.Term ((string) val);
1610 vari.DefaultValue = term;
1615 private void new_variable (Xex.Symbol name, string desc, MSymbol val,
1616 MPlist pl, Xex.Variable vari)
1619 Xex.Symbol sym = val.Name;
1625 range = new Xex.Symbol[pl.Count * 2];
1626 for (int i = 0; i < range.Length; i++)
1629 range[i] = pl.Symbol.Name;
1631 throw new Exception ("Invalid range: " + pl);
1635 domain.Defvar (new Xex.Variable.Sym (name, desc, sym, range));
1638 Xex.Term term = new Xex.Term (sym);
1640 vari.DefaultValue = term;
1645 private Xex.Variable get_global_var (Xex.Symbol name)
1647 if (im_global == null || this != im_global)
1649 tag = new MDatabase.Tag (Minput_method, MSymbol.t, MSymbol.nil,
1651 im_global = im_table[tag];
1652 if (! im_global.Open ())
1653 throw new Exception ("Failed to load global");
1655 return im_global.domain.GetVar (name, false);
1658 private void parse_variables (MPlist plist)
1660 var_names = new Xex.Symbol[plist.Count];
1662 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1664 if (! plist.IsPlist || ! plist.Plist.IsSymbol)
1665 throw new Exception ("Invalid variable: " + plist);
1667 MPlist p = plist.Plist;
1668 Xex.Symbol name = (Xex.Symbol) p.Symbol.Name;
1669 var_names[i] = name;
1671 string desc = (string) parse_description (p);
1672 Xex.Variable vari = get_global_var (name);
1674 domain.Defvar (vari);
1680 new_variable (name, desc, p.Integer, p.next, vari);
1682 new_variable (name, desc, p.Text, p.next, vari);
1683 else if (p.IsSymbol)
1684 new_variable (name, desc, p.Symbol, p.next, vari);
1686 throw new Exception ("Invalid variable type: " + p.val);
1691 private void parse_variables (XmlNode node)
1693 XmlNodeList node_list = node.ChildNodes;
1695 var_names = new Xex.Symbol[node_list.Count];
1696 for (int i = 0; i < node_list.Count; i++)
1698 Xex.Symbol name = node_list[i].Attributes[0].Value;
1699 Xex.Variable vari = get_global_var (name);
1701 domain.Defvar (vari);
1702 domain.Defvar (node_list[i]);
1703 var_names[i] = name;
1707 private void parse_commands (MPlist plist)
1709 commands = new Command[plist.Count];
1711 for (int i = 0; ! plist.IsEmpty; plist = plist.next)
1712 if (plist.IsPlist && plist.Plist.IsSymbol)
1713 commands[i++] = new Command (plist.Plist);
1716 private void parse_commands (XmlNode node)
1718 XmlNodeList node_list = node.ChildNodes;
1720 commands = new Command[node_list.Count];
1721 for (int i = 0; i < node_list.Count; i++)
1723 if (node_list[i].NodeType == XmlNodeType.Element)
1724 commands[i] = new Command (node_list[i]);
1728 private void parse_plugins (MPlist plist)
1730 plugins = new Dictionary<MSymbol, Plugin> ();
1732 for (; ! plist.IsEmpty; plist = plist.Next)
1734 MPlist p = plist.Plist;
1735 MSymbol sym = p.Symbol;
1736 Plugin plugin = new Plugin (sym.Name);
1738 for (p = p.next; ! p.IsEmpty; p = p.next)
1740 Xex.Function func = new PluginMethod (plugin, p.Symbol.Name);
1741 domain.Defun (func);
1746 private void parse_plugins (XmlNode node)
1748 plugins = new Dictionary<MSymbol, Plugin> ();
1750 foreach (XmlNode n in node.ChildNodes)
1752 Plugin plugin = new Plugin (n.Attributes[0].Value);
1753 foreach (XmlNode nn in n.ChildNodes)
1755 Xex.Function func = new PluginMethod (plugin,
1756 nn.Attributes[0].Value);
1757 domain.Defun (func);
1762 private void parse_macros (XmlNode node)
1764 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1765 if (nn.NodeType == XmlNodeType.Element)
1766 domain.Defun (nn, true);
1767 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1768 if (nn.NodeType == XmlNodeType.Element)
1769 domain.Defun (nn, false);
1772 private void parse_maps (XmlNode node)
1776 private void parse_states (XmlNode node)
1780 private void parse_include (MPlist plist)
1782 if (! plist.IsPlist)
1784 MPlist p = plist.Plist;
1785 MSymbol language, name, subname;
1786 language = p.Symbol;
1789 name = subname = MSymbol.nil;
1795 subname = MSymbol.nil;
1800 MInputMethod im = MInputMethod.Find (language, name, subname);
1806 if (! plist.IsSymbol)
1808 MSymbol target_type = plist.Symbol;
1810 MSymbol target_name = MSymbol.nil;
1812 target_name = plist.Symbol;
1813 if (target_type == Mmacro)
1815 if (target_name == MSymbol.nil)
1816 im.domain.CopyFunc (domain);
1818 im.domain.CopyFunc (domain, (Xex.Symbol) target_name.Name);
1820 else if (target_type == Mmap)
1822 if (target_name == MSymbol.nil)
1824 foreach (KeyValuePair<MSymbol, Map> kv in im.maps)
1825 maps[kv.Key] = kv.Value;
1830 if (im.maps.TryGetValue (target_name, out map))
1831 maps[target_name] = map;
1834 else if (target_type == Mstate)
1836 if (target_name == MSymbol.nil)
1838 for (p = im.states; ! p.IsEmpty; p = p.next)
1839 states.Add (p.key, p.val);
1843 object state = im.states.Get (target_name);
1845 states.Add (target_name, state);
1850 private Xex.Term parse_cond (MPlist plist)
1852 Xex.Term[] args = new Xex.Term[plist.Count];
1854 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1856 if (! plist.IsPlist)
1857 throw new Exception ("Invalid cond args: " + plist);
1858 MPlist p = plist.Plist;
1859 List<Xex.Term> arg = new List<Xex.Term> (parse_action (p));
1860 args[i] = new Xex.Term (arg);
1862 return new Xex.Term (domain, (Xex.Symbol) Mcond.Name, args);
1865 private Xex.Term[] parse_action (MPlist plist)
1867 Xex.Term[] terms = new Xex.Term[plist.Count];
1869 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1872 terms[i] = new Xex.Term ((Xex.Symbol) plist.Symbol.Name);
1873 else if (plist.IsMText)
1874 terms[i] = new Xex.Term ((string) plist.Text);
1875 else if (plist.IsInteger)
1876 terms[i] = new Xex.Term (plist.Integer);
1877 else if (plist.IsPlist)
1879 MPlist p = plist.Plist;
1881 throw new Exception ("Invalid action: " + p);
1882 MSymbol name = p.Symbol;
1885 terms[i] = parse_cond (p);
1886 else if (name == Mset || name == Madd || name == Msub
1887 || name == Mmul || name == Mdiv)
1890 throw new Exception ("Invalid action: " + p);
1891 Xex.Symbol varname = p.Symbol.Name;
1892 terms[i] = new Xex.Term (domain, (Xex.Symbol) name.Name,
1893 varname, parse_action (p.next));
1896 terms[i] = new Xex.Term (domain, (Xex.Symbol) name.Name,
1900 throw new Exception ("Invalid action: " + plist);
1906 private void parse_macros (MPlist plist)
1908 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
1911 MPlist p = pl.Plist;
1915 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null, null, true);
1917 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
1920 MPlist p = pl.Plist;
1925 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null,
1926 parse_action (p.next), false);
1930 private void parse_maps (MPlist plist)
1932 for (; ! plist.IsEmpty; plist = plist.next)
1935 MPlist pl = plist.Plist;
1939 Map map = new Map ();
1940 map.name = pl.Symbol;
1941 maps[map.name] = map;
1942 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1946 MPlist p = pl.Plist;
1949 keys = new KeySeq (p.Text);
1951 keys = new KeySeq (p.Plist);
1958 new Xex.Term (domain, Nprogn, parse_action (p)));
1963 private void parse_states (MPlist plist)
1965 for (; ! plist.IsEmpty; plist = plist.next)
1968 MPlist pl = plist.Plist;
1979 State state = new State (pl.Symbol);
1980 state.title = title;
1982 states = new MPlist ();
1983 states.Add (state.name, state);
1984 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1988 MPlist p = pl.Plist;
1991 MSymbol map_name = p.Symbol;
1993 Xex.Term term = new Xex.Term (domain, Nprogn, parse_action (p));
1994 state.branches.Add (map_name, term);
1999 private static Xex.Term Finsert (Xex.Domain domain, Xex.Variable vari,
2002 ((MInputContext) domain.context).insert (args[0]);
2006 private static Xex.Term Finsert_candidates (Xex.Domain domain,
2010 ((MInputContext) domain.context).insert_candidates (args[0]);
2014 private static Xex.Term Fmarker (Xex.Domain domain, Xex.Variable vari,
2017 MSymbol name = (string) args[0].Symval;
2018 return new Xex.Term (Marker.Get ((MInputContext) domain.context, name));
2021 private static Xex.Term Fchar_at (Xex.Domain domain, Xex.Variable vari,
2024 int c = ((MInputContext) domain.context).char_at (args[0].Intval);
2025 return new Xex.Term (c);
2028 private static Xex.Term Fdelete (Xex.Domain domain, Xex.Variable vari,
2031 ((MInputContext) domain.context).delete ((int) args[0].Intval);
2035 private static Xex.Term Fselect (Xex.Domain domain, Xex.Variable vari,
2038 Candidates can = ((MInputContext) domain.context).candidates;
2041 ((Selector) args[0].Objval).Select (can);
2045 private static Xex.Term Fshow (Xex.Domain domain, Xex.Variable vari,
2048 ((MInputContext) domain.context).show ();
2052 private static Xex.Term Fhide (Xex.Domain domain, Xex.Variable vari,
2055 ((MInputContext) domain.context).hide ();
2059 private static Xex.Term Fmove (Xex.Domain domain, Xex.Variable vari,
2063 ((MInputContext) domain.context).move (args[0].Intval);
2066 Marker m = (Marker) args[0].Objval;
2067 MInputContext ic = (MInputContext) domain.context;
2068 ((MInputContext) domain.context).move (m.Position (ic));
2073 private static Xex.Term Fmark (Xex.Domain domain, Xex.Variable vari,
2076 Marker m = (Marker) args[0].Objval;
2077 m.Mark ((MInputContext) domain.context);
2081 private static Xex.Term Fpushback (Xex.Domain domain, Xex.Variable vari,
2084 MInputContext ic = (MInputContext) domain.context;
2087 ic.pushback (args[0].Intval);
2088 else if (args[0].IsStr)
2089 ic.pushback (new KeySeq (args[0].Strval));
2091 ic.pushback ((KeySeq) args[0].Objval);
2095 private static Xex.Term Fpop (Xex.Domain domain, Xex.Variable vari,
2098 ((MInputContext) domain.context).pop ();
2102 private static Xex.Term Fundo (Xex.Domain domain, Xex.Variable vari,
2105 int n = args.Length == 0 ? -2 : args[0].Intval;
2106 ((MInputContext) domain.context).undo (n);
2110 private static Xex.Term Fcommit (Xex.Domain domain, Xex.Variable vari,
2113 ((MInputContext) domain.context).commit ();
2117 private static Xex.Term Funhandle (Xex.Domain domain, Xex.Variable vari,
2120 ((MInputContext) domain.context).commit ();
2121 args = new Xex.Term[2];
2122 args[0] = args[1] = Tcatch_tag;
2123 return Xex.Fthrow (domain, vari, args);
2126 private static Xex.Term Fshift (Xex.Domain domain, Xex.Variable vari,
2129 ((MInputContext) domain.context).shift (args[0].Symval);
2133 public override string ToString ()
2135 string str = (String.Format ("({0} (title \"{1}\")", tag, title));
2136 if (commands != null)
2138 str += " (commands";
2139 foreach (Command cmd in commands)
2143 if (var_names != null)
2145 str += " (variables";
2146 foreach (Xex.Symbol var in var_names)
2150 if (plugins != null)
2153 foreach (KeyValuePair<MSymbol, Plugin> kv in plugins)
2154 str += " " + kv.Value;
2158 foreach (KeyValuePair<MSymbol, Map> kv in maps)
2159 str += " " + kv.Value;
2161 foreach (MPlist p in states)
2167 public class MInputContext
2169 internal static Xex.Symbol Ncandidates_group_size = "candidates-group-size";
2170 private static MSymbol Mat_less_than = "@<";
2171 private static MSymbol Mat_greater_than = "@>";
2172 private static MSymbol Mat_minus = "@-";
2173 private static MSymbol Mat_plus = "@+";
2174 private static MSymbol Mat_open_square_bracket = "@[";
2175 private static MSymbol Mat_close_square_bracket = "@]";
2177 public MInputMethod im;
2178 private MText produced;
2179 private bool active;
2180 private MText status;
2181 internal MText preedit;
2182 internal int cursor_pos;
2183 internal Mim.Candidates candidates;
2184 private MPlist candidate_group;
2185 private int candidate_index;
2186 private int candidate_from, candidate_to;
2187 private bool candidate_show;
2189 private Stack<Mim.State> states;
2190 internal Mim.KeySeq keys;
2191 private int key_head;
2192 private int state_key_head;
2193 private object state_var_values;
2194 private int commit_key_head;
2195 private MText state_preedit;
2196 private int state_pos;
2197 internal MPlist markers = new MPlist ();
2198 internal MText preceding_text = new MText ();
2199 internal MText following_text = new MText ();
2200 private bool key_unhandled;
2202 internal Xex.Domain domain;
2204 internal Mim.ChangedStatus changed;
2206 public Mim.ChangedStatus Changed { get { return changed; } }
2208 public MInputContext (MInputMethod im)
2211 domain = new Xex.Domain (im.domain, this);
2212 states = new Stack<Mim.State> ();
2213 states.Push ((Mim.State) im.states.val);
2214 keys = new Mim.KeySeq ();
2217 private void adjust_markers (int from, int to, object inserted)
2219 int ins = (inserted == null ? 0
2220 : inserted is int ? 1
2221 : ((MText) inserted).Length);
2222 int diff = ins - (to - from);
2224 for (MPlist plist = markers; ! plist.IsEmpty; plist = plist.next)
2226 int pos = plist.Integer;
2230 plist.val = pos + diff;
2235 if (cursor_pos >= to)
2237 else if (cursor_pos > from)
2241 private void preedit_replace (int from, int to, int c)
2243 preedit.Del (from, to);
2244 preedit.Ins (from, c);
2245 adjust_markers (from, to, c);
2248 private void preedit_replace (int from, int to, MText mt)
2250 preedit[from, to] = mt;
2251 adjust_markers (from, to, mt);
2254 internal void insert (Xex.Term arg)
2257 preedit_replace (cursor_pos, cursor_pos, arg.Intval);
2259 preedit_replace (cursor_pos, cursor_pos, new MText (arg.Strval));
2260 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2263 private void update_candidate ()
2265 object candidate = candidates.Current;
2267 if (candidate is MText)
2269 preedit_replace (candidate_from, candidate_to, (MText) candidate);
2270 candidate_to = candidate_from + ((MText) candidate).Length;
2274 preedit_replace (candidate_from, candidate_to, (int) candidate);
2275 candidate_to = candidate_from + 1;
2277 preedit.PushProp (candidate_from, candidate_to,
2278 Mim.Mcandidates, this);
2279 cursor_pos = candidate_from;
2280 changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
2284 internal void insert_candidates (Xex.Term arg)
2287 Xex.Variable v = domain.GetVar (Ncandidates_group_size, false);
2290 column = v.Value.Intval;
2291 candidates = new Mim.Candidates (arg.Listval, column);
2292 candidate_from = candidate_to = cursor_pos;
2293 update_candidate ();
2296 internal void select (int n)
2298 if (candidates != null)
2300 candidates.Select (n);
2301 update_candidate ();
2305 internal int marker (MSymbol sym)
2307 int pos = cursor_pos;
2309 if (sym.Name.Length == 2 && sym.Name[0] == '@')
2311 switch (sym.Name[0])
2313 case '<': pos = 0; break;
2314 case '>': pos = preedit.Length; break;
2315 case '-': pos = cursor_pos - 1; break;
2316 case '+': pos = cursor_pos + 1; break;
2321 preedit.FindProp (Mim.Mcandidates, pos - 1,
2328 if (cursor_pos < preedit.Length - 1)
2331 preedit.FindProp (Mim.Mcandidates, pos,
2335 pos = preedit.Length;
2338 if (sym.Name[0] >= '0' && sym.Name[0] <= '9')
2343 else if (sym.Name.Length >= 3 && sym.Name[0] == '@')
2345 pos = int.Parse (sym.Name.Substring (2));
2349 object val = markers.Get (sym);
2357 internal int char_at (int pos)
2364 if (preceding_text.Length < -pos)
2366 MPlist plist = new MPlist ();
2367 plist.Push (MSymbol.integer, pos);
2368 if (Mim.GetSurroundingText != null
2369 && Mim.GetSurroundingText (this, plist)
2371 && preceding_text.Length < plist.Text.Length)
2372 preceding_text = plist.Text;
2374 c = (-pos < preceding_text.Length
2375 ? preceding_text[preceding_text.Length + pos] : -1);
2377 else if (pos >= 0 && pos < preedit.Length)
2381 pos -= preedit.Length;
2382 if (pos >= following_text.Length)
2384 MPlist plist = new MPlist ();
2385 plist.Push (MSymbol.integer, pos + 1);
2386 if (Mim.GetSurroundingText != null
2387 && Mim.GetSurroundingText (this, plist)
2389 && following_text.Length < plist.Text.Length)
2390 following_text = plist.Text;
2392 c = (pos < following_text.Length ? following_text[pos] : -1);
2397 internal void delete (int pos)
2399 if (pos < cursor_pos)
2400 preedit_replace (pos, cursor_pos, null);
2402 preedit_replace (cursor_pos, pos, null);
2403 changed |= ChangedStatus.Preedit | ChangedStatus.CursorPos;
2406 internal void show ()
2408 candidate_show = true;
2409 changed |= ChangedStatus.CandidateShow;
2412 internal void hide ()
2414 candidate_show = false;
2415 changed |= ChangedStatus.CandidateShow;
2418 internal void move (int pos)
2422 else if (pos > preedit.Length)
2423 pos = preedit.Length;
2424 if (pos != cursor_pos)
2427 changed |= ChangedStatus.Preedit;
2431 internal void mark (MSymbol sym)
2433 MPlist slot = markers.Find (sym);
2436 markers.Push (sym, cursor_pos);
2438 slot.val = cursor_pos;
2441 internal void pushback (int n)
2454 if (key_head > keys.keyseq.Count)
2455 key_head = keys.keyseq.Count;
2459 internal void pushback (Mim.KeySeq keyseq)
2463 if (key_head < keys.keyseq.Count)
2464 keys.keyseq.RemoveRange (key_head, keys.keyseq.Count - key_head);
2465 for (int i = 0; i < keyseq.keyseq.Count; i++)
2466 keys.keyseq.Add (keyseq.keyseq[i]);
2469 internal void pop ()
2471 if (key_head < keys.keyseq.Count)
2472 keys.keyseq.RemoveRange (key_head, 1);
2475 internal void undo (int n)
2478 keys.keyseq.RemoveRange (keys.keyseq.Count + n, - n);
2480 keys.keyseq.RemoveRange (n, keys.keyseq.Count - n);
2484 internal void commit ()
2486 produced.Cat (preedit);
2488 changed |= ChangedStatus.Preedit;
2491 internal void shift (MSymbol sym)
2495 if (sym == MSymbol.t)
2497 if (states.Count > 1)
2498 state = states.Pop ();
2500 state = states.Peek ();
2504 state = (Mim.State) im.states.Get (sym);
2506 throw new Exception ("Unknown state: " + state.name);
2509 state = states.Pop ();
2510 if (state == (Mim.State) im.states.val)
2517 state_key_head = key_head;
2518 state_pos = cursor_pos;
2519 state_preedit = preedit.Dup ();
2520 if (state != states.Peek ())
2522 states.Push (state);
2523 state_var_values = domain.SaveValues ();
2524 status = state.title;
2527 changed |= ChangedStatus.StateTitle;
2529 = (Xex) state.branches.Get (MSymbol.t);
2530 if (on_entry != null)
2531 on_entry.Eval (domain);
2536 internal void reset ()
2539 state_preedit.Del ();
2543 key_head = commit_key_head = 0;
2545 states.Push ((Mim.State) im.states.Val);
2550 internal object GetCandidates (out int column)
2553 if (cursor_pos == 0)
2555 Mim.Candidates candidates
2556 = (Mim.Candidates) preedit.GetProp (cursor_pos - 1, Mim.Mcandidates);
2557 if (candidates == null)
2559 column = candidates.Column;
2560 return candidates.Current;
2563 internal void HandleKey ()
2567 public bool Toggle ()