2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Reflection;
12 using Xex = System.Xml.Expression.Xexpression;
16 public class MInputMethod
19 public delegate bool Callback (Context ic, MPlist args);
22 public static Callback PreeditStart, PreeditDone, PreeditDraw;
23 public static Callback StatusStart, StatusDone, StatusDraw;
24 public static Callback CandidateStart, CandidateDone, CandidateDraw;
25 public static Callback SetSpot;
26 public static Callback Toggle;
27 public static Callback Reset;
28 public static Callback GetSurroundingText;
29 public static Callback DeleteSurroundingText;
31 internal static Xex.Domain im_domain = new Xex.Domain (null);
32 private static MSymbol Minput_method = "input-method";
33 private static MSymbol Mdescription = "description";
34 private static MSymbol Mvariable = "variable";
35 private static MSymbol Mcommand = "command";
36 private static MSymbol Mmodule = "module";
37 private static MSymbol Mtitle = "title";
38 private static MSymbol Minclude = "include";
39 private static MSymbol Mmacro = "macro";
40 private static MSymbol Mmap = "map";
41 private static MSymbol Mmap_list = "map-list";
42 private static MSymbol Mstate = "state";
43 internal static MSymbol Mcandidates = "candidates";
44 private static MSymbol Minsert = "insert";
45 internal static MSymbol Mselect = "select";
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_flag = "surrounding-text-flag";
59 private static MSymbol Mpushback = "pushback";
60 private static MSymbol Mkeyseq = "keyseq";
62 private static Xex.Symbol Nprogn = "progn";
63 private static Xex.Symbol Ninsert = "insert";
64 private static Xex.Symbol Ninsert_candidates = "insert-candidates";
65 private static Xex.Symbol Nchar_at = "char-at";
67 private static Xex.Term Tnil = new Xex.Term ((Xex.Symbol) "nil");
68 private static Xex.Term Tcatch_tag = new Xex.Term ((Xex.Symbol) "@mimtag");
70 private static Dictionary<MDatabase.Tag, MInputMethod> im_table
71 = new Dictionary<MDatabase.Tag, MInputMethod> ();
73 internal static MInputMethod im_global = null;
76 private enum LoadStatus
86 public enum ChangedStatus
93 CandidateIndex = 0x10,
97 private static ChangedStatus CandidateAll = (ChangedStatus.CandidateList
98 | ChangedStatus.CandidateIndex
99 | ChangedStatus.CandidateShow);
101 public enum KeyModifier
104 Shift_L = 0x00400000,
105 Shift_R = 0x00800000,
107 Control_L = 0x01000000,
108 Control_R = 0x02000000,
109 Control = 0x03000000,
124 private static Dictionary<string, uint> keysyms
125 = new Dictionary<string, uint> ();
126 private static Dictionary<string, KeyModifier> keymodifiers
127 = new Dictionary<string, KeyModifier> ();
128 private static uint keysym_base = 0x200000;
129 private static uint char_mask = ~((uint) KeyModifier.All);
133 keysyms["bs"] = keysyms["backspace"] = 0x08;
134 keysyms["tab"] = 0x09;
135 keysyms["lf"] = keysyms["linefeed"] = 0x10;
136 keysyms["cr"] = keysyms["return"] = keysyms["enter"] = 0x13;
137 keysyms["esc"] = keysyms["escape"] = 0x1B;
138 keysyms["spc"] = keysyms["space"] = 0x20;
139 keysyms["del"] = keysyms["delete"] = 0x7F;
140 keymodifiers["shift-l"] = KeyModifier.Shift_L;
141 keymodifiers["shift-r"] = KeyModifier.Shift_R;
142 keymodifiers["shift"] = KeyModifier.Shift;
143 keymodifiers["control-l"] = KeyModifier.Control_L;
144 keymodifiers["control-r"] = KeyModifier.Control_R;
145 keymodifiers["control"] = KeyModifier.Control;
146 keymodifiers["alt-l"] = KeyModifier.Alt_L;
147 keymodifiers["alt-r"] = KeyModifier.Alt_R;
148 keymodifiers["alt"] = KeyModifier.Alt;
149 keymodifiers["altgr"] = KeyModifier.AltGr;
150 keymodifiers["super"] = KeyModifier.Super;
151 keymodifiers["hyper"] = KeyModifier.Hyper;
154 private static uint decode_keysym (MSymbol keysym)
157 string name = keysym.Name;
159 if (name.Length == 1)
161 name = name.ToLower ();
162 if (! keysyms.TryGetValue (name, out key))
163 keysyms[name] = key = keysym_base++;
167 private static uint combine_modifiers (uint c, KeyModifier modifiers)
169 if (c < 0x7F && c != 0x20)
171 if ((modifiers & KeyModifier.Shift) != KeyModifier.None
172 && Char.IsLower ((char) c))
174 modifiers &= ~KeyModifier.Shift;
175 c = Char.ToUpper ((char) c);
177 if ((modifiers & KeyModifier.Control) != KeyModifier.None)
179 modifiers &= ~KeyModifier.Control;
183 return c | (uint) modifiers;
186 public Key (uint c) { key = c; }
187 public Key (int c) { key = (uint) c; }
189 public Key (uint c, KeyModifier modifiers)
191 key = combine_modifiers (c, modifiers);
194 public Key (MSymbol keysym, KeyModifier modifiers)
196 key = combine_modifiers (decode_keysym (keysym), modifiers);
199 public Key (MSymbol keysym)
201 string str = keysym.Name;
202 int len = str.Length;
204 KeyModifier modifiers = KeyModifier.None;
206 for (i = 0; i + 2 < len && str[i + 1] == '-'; i += 2)
209 modifiers |= KeyModifier.Shift;
210 else if (str[i] == 'C')
211 modifiers |= KeyModifier.Control;
212 else if (str[i] == 'A')
213 modifiers |= KeyModifier.Alt;
214 else if (str[i] == 'G')
215 modifiers |= KeyModifier.AltGr;
216 else if (str[i] == 's')
217 modifiers |= KeyModifier.Super;
218 else if (str[i] == 'H')
219 modifiers |= KeyModifier.Hyper;
222 key = combine_modifiers (str[i], modifiers);
224 key = combine_modifiers (decode_keysym (keysym), modifiers);
227 public Key (MPlist plist)
229 KeyModifier modifiers = KeyModifier.None;
232 for (p = plist; ! p.IsEmpty; p = p.next)
236 if (! p.next.IsEmpty)
237 throw new Exception ("Invalid Key: " + plist);
240 else if (! p.IsSymbol)
241 throw new Exception ("Invalid Key: " + plist);
244 string name = p.Symbol.Name.ToLower ();
247 if (! keymodifiers.TryGetValue (name, out m))
252 if (p.IsEmpty || ! p.next.IsEmpty)
253 throw new Exception ("Invalid Key: " + plist);
255 key = combine_modifiers ((uint) p.Integer, modifiers);
257 key = combine_modifiers (decode_keysym (p.Symbol), modifiers);
260 public bool HasModifier
262 get { return ((key & (uint) KeyModifier.All) != 0); }
265 public bool Match (Key k)
269 if ((k.key & char_mask) != (key & char_mask))
271 KeyModifier m1 = ((KeyModifier) key) & KeyModifier.All;
272 KeyModifier m2 = ((KeyModifier) k.key) & KeyModifier.All;
273 return (((m1 & KeyModifier.Shift) == (m2 & KeyModifier.Shift)
274 || ((m1 & KeyModifier.Shift) == KeyModifier.Shift
275 && (m2 & KeyModifier.Shift) != KeyModifier.None))
276 && ((m1 & KeyModifier.Control) == (m2 & KeyModifier.Control)
277 || ((m1 & KeyModifier.Control) == KeyModifier.Control
278 && (m2 & KeyModifier.Control) != KeyModifier.None))
279 && ((m1 & KeyModifier.Alt) == (m2 & KeyModifier.Alt)
280 || ((m1 & KeyModifier.Alt) == KeyModifier.Alt
281 && (m2 & KeyModifier.Alt) != KeyModifier.None))
282 && ((m1 & KeyModifier.High) == (m2 & KeyModifier.High)));
285 public override string ToString ()
287 string str = Char.ToString ((char) key);
288 KeyModifier m = ((KeyModifier) key) & KeyModifier.All;
290 if (m != KeyModifier.None)
292 if ((m & KeyModifier.Shift) != KeyModifier.None)
294 if ((m & KeyModifier.Control) != KeyModifier.None)
296 if ((m & KeyModifier.Alt) != KeyModifier.None)
298 if ((m & KeyModifier.AltGr) != KeyModifier.None)
300 if ((m & KeyModifier.Super) != KeyModifier.None)
302 if ((m & KeyModifier.Hyper) != KeyModifier.None)
309 public class KeySeq : Xex.TermValue
311 public List<Key> keyseq = new List<Key> ();
313 public override Xex.TermValue Clone ()
315 KeySeq ks = new KeySeq ();
316 ks.keyseq.InsertRange (0, keyseq);
322 public KeySeq (MPlist plist)
324 foreach (MPlist p in plist)
327 keyseq.Add (new Key (p.Symbol));
328 else if (p.IsInteger)
329 keyseq.Add (new Key ((char) p.Integer));
331 keyseq.Add (new Key (p.Plist));
333 throw new Exception ("Invalid Key Sequence: " + plist);
337 public KeySeq (MText mt) : base ()
339 for (int i = 0; i < mt.Length; i++)
340 keyseq.Add (new Key ((uint) mt[i]));
343 public KeySeq (List<Xex.Term> list)
345 int len = list.Count;
347 for (int i = 0; i < len; i++)
350 keyseq.Add (new Key (list[i].Intval));
351 else if (list[i].IsStr)
352 keyseq.Add (new Key (list[i].Strval));
353 else if (list[i].IsSymbol)
354 keyseq.Add (new Key ((string) list[i].Symval));
356 throw new Exception ("Invalid key: " + list[i]);
360 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
362 Xex.Term term = new Xex.Term (domain, node.FirstChild).Eval (domain);
363 return (term.IsStr ? new KeySeq ((MText) term.Strval)
364 : new KeySeq (term.Listval));
367 public override string ToString ()
371 foreach (Key key in keyseq)
375 foreach (Key k in keyseq)
376 str += " " + k.ToString ();
380 foreach (Key key in keyseq)
381 str += key.ToString ();
389 public MText description;
390 public List<KeySeq> keys;
392 public Command (MPlist p)
396 description = parse_description (p);
397 if (description == null)
398 description = "No description";
399 keys = new List<KeySeq> ();
400 Console.WriteLine ("cmd:" + p);
401 for (p = p.next; ! p.IsEmpty; p = p.next)
404 keys.Add (new KeySeq (p.Text));
406 keys.Add (new KeySeq (p.Plist));
410 public Command (XmlNode node)
412 name = node.Attributes[0].Value;
413 keys = new List<KeySeq> ();
414 for (node = node.FirstChild; node != null; node = node.NextSibling)
416 if (node.Name == "description")
417 description = parse_description (node);
418 else if (node.Name == "keyseq")
419 keys.Add ((KeySeq) KeySeq.parser (null, node));
423 public override string ToString ()
425 string str = "(" + name + " \"" + (string) description;
426 foreach (KeySeq keyseq in keys)
432 internal class Plugin
435 private Assembly assembly;
436 private Type plugin_type;
438 public Plugin (string name)
443 public MethodInfo GetMethod (Xex.Symbol name)
445 if (assembly == null)
447 assembly = Assembly.LoadFrom (name + ".dll");
448 plugin_type = assembly.GetType ("M17n.MInputMethod.Plugin");
451 MethodInfo info = plugin_type.GetMethod ((string) name);
453 throw new Exception ("Invalid plugin method: " + name);
457 public override string ToString ()
459 return String.Format ("(module {0}", name);
463 internal class PluginMethod : Xex.Function
465 private Plugin plugin;
466 private MethodInfo method_info;
467 object[] parameters = new object[2];
469 public PluginMethod (Plugin plugin, string name)
470 : base ((Xex.Symbol) name, 0, -1)
472 this.plugin = plugin;
475 public override Xex.Term Call (Xex.Domain domain, Xex.Variable vari,
478 args = (Xex.Term[]) args.Clone ();
479 for (int i = 0; i < args.Length; i++)
481 args[i] = args[i].Eval (domain);
485 if (method_info == null)
486 method_info = plugin.GetMethod (name);
487 parameters[0] = domain.context;
488 parameters[1] = args;
489 return (Xex.Term) method_info.Invoke (null, parameters);
493 internal abstract class Marker : Xex.TermValue
495 private MSymbol name;
497 public Marker (MSymbol name)
502 public abstract int Position (Context ic);
503 public abstract void Mark (Context ic);
504 public abstract int CharAt (Context ic);
506 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
508 MSymbol name = node.InnerText;
510 return Get ((Context) domain.context, name);
513 public class Named : Marker
515 public Named (MSymbol name) : base (name) { }
517 public override int Position (Context ic)
520 if (ic.markers.TryGetValue (name, out pos))
525 public override void Mark (Context ic)
527 ic.markers[name] = ic.cursor_pos;
530 public override Xex.TermValue Clone ()
532 return new Named (name, pos);
536 public class Predefined : Marker
538 public Predefined (MSymbol name) : base (name) { }
540 public override int Position (Context ic)
542 switch (name.Name[1]) {
544 case '>': return ic.preedit.Length;
545 case '-': return ic.cursor_pos - 1;
546 case '+': return ic.cursor_pos + 1;
548 if (ic.cursor_pos > 0)
550 int pos = ic.cursor_pos;
552 ic.preedit.FindProp (Mcandidates, pos - 1, out pos, out to);
557 if (ic.cursor_pos < ic.preedit.Length - 1)
559 int pos = ic.cursor_pos;
561 ic.preedit.FindProp (Mcandidates, pos, out from, out pos);
564 return ic.preedit.Length;
566 return name.Name[1] - '0';
570 public override void Mark (Context ic)
572 throw new Exception ("Can't set predefined marker: " + name);
575 public override Xex.TermValue Clone ()
577 return new Predefined (name);
581 public class PredefinedPlusMinus : Marker
583 private int distance;
585 public PredefinedPlusMinus (MSymbol name): base (name)
587 if (! int.TryParse (name.Name.Substring (2), out distance))
588 throw new Exception ("Invalid marker name: " + name);
593 public override int Position (Context ic)
595 return ic.cursor_pos + distance;
599 static internal Dictionary<MSymbol,Predefined> predefined_markers;
603 predefined_markers = new Dictionary<MSymbol,Predefined> ();
604 MSymbol[] symlist = new MSymbol[] {"@<", "@>", "@-", "@+", "@[", "@]",
605 "@0", "@1", "@2", "@3", "@4",
606 "@5", "@6", "@7", "@8", "@9" };
607 foreach (MSymbol s in symlist)
608 predefined_markers[s] = new Predefined (s);
611 public static Marker Get (MSymbol name)
615 if (predefined_markers.TryGetValue (name, out pred))
617 if (name.Name[0] == '@')
620 if (name.Name.Length >= 3
621 && (name.Name[1] == '-' || name.Name[1] == '+')
622 && int.TryParse (name.Name.Substring (2), out pos)
624 return (predefined_markers[name] = new Predefined (name));
626 throw new Exception ("Invalid marker name: " + name);
628 return new Named (name);
632 internal class Candidates
639 public Block (int index, Xex.Term term)
643 Data = (MText) term.Strval;
646 MPlist plist = new MPlist ();
648 foreach (Xex.Term t in term.Listval)
649 p = p.Add (MSymbol.mtext, (MText) t.Strval);
654 public Block (int index, MPlist plist)
659 else if (plist.IsPlist)
662 throw new Exception ("Invalid candidate: " + plist);
667 get { return (Data is MText
668 ? ((MText) Data).Length
669 : ((MPlist) Data).Count); }
672 public object this[int i]
675 if (Data is MText) return ((MText) Data)[i];
676 return ((MPlist) Data)[i];
681 private Block[] blocks;
683 private int index = 0;
684 public object[] group;
686 private bool IsFixed { get { return group != null; } }
689 Block last = blocks[blocks.Length - 1];
690 return last.Index + last.Count; }
694 get { return (IsFixed ? index % group.Length
695 : index - blocks[row].Index); }
698 public object Group {
699 get { return (IsFixed ? group : blocks[row].Data); }
702 public int GroupLength
707 int nitems = group.Length;
708 int start = index - (index % nitems);
710 return (start + nitems <= total ? nitems : total - start);
712 return blocks[row].Count;
716 public object Current {
718 return (IsFixed ? group[index % group.Length]
719 : blocks[row][index - blocks[row].Index]);
723 public Candidates (MPlist list, int column)
725 int nblocks = list.Count;
727 blocks = new Block[nblocks];
728 for (int i = 0, start = 0; i < nblocks; i++, list = list.next)
729 start += (blocks[i] = new Block (index, list)).Count;
731 group = new object[column];
734 public Candidates (List<Xex.Term> list, int column)
736 int nblocks = list.Count;
738 blocks = new Block[nblocks];
739 for (int i = 0, start = 0; i < nblocks; i++)
740 start += (blocks[i] = new Block (index, list[i])).Count;
742 group = new object[column];
745 public static void Detach (Context ic)
747 ic.preedit.PopProp (0, ic.preedit.Length, Mcandidates);
748 ic.candidates = null;
749 ic.changed |= (ChangedStatus.Preedit | ChangedStatus.CursorPos
753 // Fill the array "group" by candidates stating from INDEX.
754 // INDEX must be a multiple of "column". Set NTIMES to the
755 // number of valid candidates in "group". Update "block" if
756 // necessary. Return "group".
758 private int fill_group (int start)
760 int nitems = group.Length;
765 while (start < b.Index)
768 while (start >= b.Index + b.Count)
774 for (int i = 0; i < nitems; i++, start++)
779 if (r == blocks.Length)
790 // Update "row" to what contains the first candidate of
791 // the previous candidate-group, update "current_index", and
792 // update "group" if necessary. Return the previous
793 // candidate-group. Set NITEMS to the number of valid
794 // candidates contained in that group.
796 public int PrevGroup ()
803 nitems = group.Length;
804 if ((index -= col + nitems) < 0)
805 index = (Total / nitems) * nitems;
806 nitems = fill_group (index);
810 row = row > 0 ? row-- : blocks.Length - 1;
811 nitems = blocks[row].Count;
812 index = blocks[row].Index;
814 index += col < nitems ? col : nitems - 1;
818 public int NextGroup ()
825 nitems = group.Length;
826 if ((index += nitems - col) >= Total)
828 nitems = fill_group (index);
832 row = row < blocks.Length - 1 ? row + 1 : 0;
833 nitems = blocks[row].Count;
834 index = blocks[row].Count;
836 index += col < nitems ? col : nitems - 1;
846 int nitems = PrevGroup ();
847 index += col < nitems - 1 ? col : nitems - 1;
856 int nitems = GroupLength;
858 if (col == nitems - 1)
860 nitems = NextGroup ();
874 index += GroupLength - (Column + 1);
877 public void Select (int col)
879 int maxcol = GroupLength - 1;
882 index = index - Column + col;
886 internal class Selector : Xex.TermValue
888 public static Xex.TermValue parser (Xex.Domain domain, XmlNode node)
890 return Get ((MSymbol) node.InnerText);
893 public static Xex.TermValue Get (MSymbol name)
897 if (! predefined_selectors.TryGetValue (name, out pred))
898 throw new Exception ("Invalid selector name: " + name);
902 public override Xex.TermValue Clone () { return this; }
904 public void Select (Candidates candidates)
908 case '<': candidates.First (); break;
909 case '>': candidates.Last (); break;
910 case '-': candidates.Prev (); break;
911 case '+': candidates.Next (); break;
912 case '[': candidates.PrevGroup (); break;
913 case ']': candidates.NextGroup (); break;
918 static new Dictionary<MSymbol, Selector> selectors;
922 selectors = new Dictionary<MSymbol, Selector> ();
923 MSymbol[] symlist = new MSymbol[] { "@<", "@=", "@>", "@-", "@+",
925 foreach (MSymbol s in symlist)
926 selectors[s] = new Selector (s);
933 public Dictionary<Key, Map> submaps;
934 public Xex.Term actions;
936 public void Add (KeySeq keys, int index, Xex.Term actions)
941 submaps = new Dictionary<Key, Map> ();
943 submaps.TryGetValue (keys.keyseq[index], out sub);
946 Key key = keys.keyseq[index];
947 submaps[key] = sub = new Map ();
949 if (index + 1 < keys.keyseq.Count)
950 sub.Add (keys, index + 1, actions);
952 this.actions = actions;
955 public Xex.Term Lookup (KeySeq keys, ref int index)
957 if (index < keys.keyseq.Count)
960 if (submaps.TryGetValue (keys.keyseq[index], out sub))
963 return sub.Lookup (keys, ref index);
970 private void describe (MText mt, KeySeq keyseq)
972 if (keyseq.keyseq.Count > 0)
974 mt.Cat (" (").Cat (keyseq.ToString ());
975 mt.Cat (' ').Cat (actions.ToString ());
979 foreach (KeyValuePair<Key, Map> kv in submaps)
981 keyseq.keyseq.Add (kv.Key);
982 kv.Value.describe (mt, keyseq);
983 keyseq.keyseq.RemoveAt (keyseq.keyseq.Count - 1);
987 public override string ToString ()
989 MText mt = "(" + name.Name;
990 KeySeq keyseq = new KeySeq ();
992 describe (mt, keyseq);
1000 public MSymbol name;
1002 public MPlist branches = new MPlist ();
1004 public State (MSymbol name)
1009 public override string ToString ()
1011 MText mt = "(" + name.Name;
1014 mt.Cat (" \"" + title + "\"");
1015 for (MPlist p = branches; ! p.IsEmpty; p = p.next)
1016 mt.Cat (" (" + p.Key + " " + (Xex) p.Val + ")");
1017 return (string) mt + ")";
1022 internal Xex.Domain domain = new Xex.Domain (im_domain, null);
1024 private LoadStatus load_status = LoadStatus.None;
1025 private MDatabase.Tag tag;
1026 private MDatabase mdb;
1028 private MText description;
1029 internal MText title;
1030 internal Command[] commands;
1031 internal Xex.Symbol[] var_names;
1032 internal Dictionary<MSymbol, Plugin> plugins;
1033 internal Dictionary<MSymbol, Map> maps;
1034 internal MPlist states;
1036 static MInputMethod ()
1038 im_domain.DefTerm ("keyseq", KeySeq.parser);
1039 im_domain.DefTerm ("marker", Marker.parser);
1040 im_domain.DefTerm ("selector", Selector.parser);
1042 im_domain.DefSubr (Finsert, "insert", false, 1, 1);
1043 im_domain.DefSubr (Finsert_candidates, "candidates", false, 1, -1);
1044 im_domain.DefSubr (Fdelete, "delete", false, 1, 1);
1045 im_domain.DefSubr (Fselect, "select", false, 1, 1);
1046 im_domain.DefSubr (Fshow, "show", false, 0, 0);
1047 im_domain.DefSubr (Fhide, "hide", false, 0, 0);
1048 im_domain.DefSubr (Fmove, "move", false, 1, 1);
1049 im_domain.DefSubr (Fmark, "mark", false, 1, 1);
1050 im_domain.DefSubr (Fpushback, "pushback", false, 1, 1);
1051 im_domain.DefSubr (Fpop, "pop", false, 0, 0);
1052 im_domain.DefSubr (Fundo, "undo", false, 0, 1);
1053 im_domain.DefSubr (Fcommit, "commit", false, 0, 0);
1054 im_domain.DefSubr (Funhandle, "unhandle", false, 0, 0);
1055 im_domain.DefSubr (Fshift, "shift", false, 1, 1);
1056 im_domain.DefSubr (Fshiftback, "shiftback", false, 0, 0);
1057 im_domain.DefSubr (Fchar_at, "char-at", false, 1, 1);
1058 im_domain.DefSubr (Fkey_count, "key-count", false, 1, 1);
1059 im_domain.DefSubr (Fsurrounding_flag, "surrounding-text-flag",
1062 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, "*", "*", "*");
1063 List<MDatabase> list = MDatabase.List (tag);
1064 M17n.DebugPrint ("Found {0} input methods\n", list.Count);
1065 foreach (MDatabase mdb in list)
1066 im_table[mdb.tag] = new MInputMethod (mdb.tag);
1070 private MInputMethod (MDatabase.Tag tag)
1075 // Instance Properties
1076 public MSymbol Language { get { return tag[1]; } }
1077 public MSymbol Name { get { return tag[2]; } }
1078 public MSymbol SubName { get { return tag[3]; } }
1080 public bool Info (out MText description,
1082 out Xex.Variable[] variables,
1083 out Command[] commands)
1085 if ((load_status & LoadStatus.Header) != LoadStatus.Header
1086 && ! load_header ())
1094 description = this.description;
1096 if (var_names == null)
1100 variables = new Xex.Variable[var_names.Length];
1102 foreach (Xex.Symbol name in var_names)
1103 variables[i++] = domain.GetVar (name, false);
1105 commands = this.commands;
1109 public static MInputMethod Find (MSymbol language, MSymbol name)
1111 return Find (language, name, MSymbol.nil);
1114 public static MInputMethod Find (MSymbol language, MSymbol name,
1117 MDatabase.Tag tag = new MDatabase.Tag (Minput_method, language,
1121 return (im_table.TryGetValue (tag, out im) ? im : null);
1126 return ((load_status == LoadStatus.Full) || load_body ());
1129 public static MInputMethod[] List ()
1131 MInputMethod[] array = new MInputMethod[im_table.Count];
1134 foreach (KeyValuePair<MDatabase.Tag, MInputMethod> kv in im_table)
1135 array[i++] = kv.Value;
1139 private bool load_header ()
1141 mdb = MDatabase.Find (tag);
1144 mdb.name_table = Xex.Symbol.Table;
1146 MSymbol format = mdb.Format;
1148 if (format == MSymbol.plist)
1149 load ((MPlist) mdb.Load (Mmap), false);
1152 XmlDocument doc = (XmlDocument) mdb.Load (Mmap_list);
1153 load (doc.DocumentElement, false);
1155 } catch (Exception e) {
1156 Console.WriteLine ("{0}\n", e);
1157 load_status = LoadStatus.Error;
1160 load_status |= LoadStatus.Header;
1164 private bool load_body ()
1166 mdb = MDatabase.Find (tag);
1169 mdb.name_table = Xex.Symbol.Table;
1171 object obj = mdb.Load ();
1173 load ((MPlist) obj, true);
1175 load ((XmlDocument) obj, true);
1176 } catch (Exception e) {
1177 Console.WriteLine (e);
1178 load_status = LoadStatus.Error;
1181 load_status = LoadStatus.Full;
1185 private void load (MPlist plist, bool full)
1187 maps = new Dictionary<MSymbol, Map> ();
1188 states = new MPlist ();
1190 for (; ! plist.IsEmpty; plist = plist.next)
1193 MPlist pl = plist.Plist;
1196 MSymbol sym = pl.Symbol;
1199 if (sym == Mdescription)
1200 description = parse_description (pl);
1201 else if (sym == Mtitle)
1206 else if (sym == Mvariable)
1207 parse_variables (pl);
1208 else if (sym == Mcommand)
1209 parse_commands (pl);
1214 else if (sym == Minclude)
1216 else if (sym == Mmacro)
1218 else if (sym == Mmap)
1220 else if (sym == Mstate)
1225 if (description == null)
1226 description = (MText) "No description";
1228 title = new MText (tag[2].Name);
1229 if (commands == null)
1230 commands = new Command[0];
1235 State state = new State ((MSymbol) "init");
1236 plist = new MPlist ();
1237 foreach (KeyValuePair<MSymbol, Map>kv in maps)
1238 state.branches.Add (kv.Key, null);
1239 states.Add (state.name, state);
1243 private void load (XmlNode node, bool full)
1245 bool skip_header = load_status == LoadStatus.Header;
1247 maps = new Dictionary<MSymbol, Map> ();
1248 states = new MPlist ();
1250 if (node.NodeType == XmlNodeType.Document)
1251 node = node.FirstChild;
1252 while (node.NodeType != XmlNodeType.Element)
1253 node = node.NextSibling;
1254 for (node = node.FirstChild; node != null; node = node.NextSibling)
1256 if (node.NodeType != XmlNodeType.Element)
1260 if (node.Name == "description")
1261 description = parse_description (node);
1262 else if (node.Name == "title")
1263 title = parse_title (node);
1264 else if (node.Name == "variable-list")
1265 parse_variables (node);
1266 else if (node.Name == "command-list")
1267 parse_commands (node);
1271 if (node.Name == "module-list")
1272 parse_plugins (node);
1273 else if (node.Name == "macro-list")
1274 parse_macros (node);
1275 else if (node.Name == "map-list")
1277 else if (node.Name == "state-list")
1278 parse_states (node);
1281 if (description == null)
1282 description = (MText) "No description";
1284 title = new MText (tag[2].Name);
1285 if (commands == null)
1286 commands = new Command[0];
1291 State state = new State ((MSymbol) "init");
1292 foreach (KeyValuePair<MSymbol, Map>kv in maps)
1293 state.branches.Add (kv.Key, null);
1294 states.Add (state.name, state);
1298 private static void transform (MPlist plist)
1300 for (; ! plist.IsEmpty; plist = plist.next)
1304 MPlist p = new MPlist ();
1305 p.Add (MSymbol.symbol, Minsert);
1306 p.Add (MSymbol.mtext, plist.Text);
1307 plist.Set (MSymbol.plist, p);
1309 else if (plist.IsInteger)
1311 MPlist p = new MPlist ();
1312 p.Add (MSymbol.symbol, Minsert);
1313 p.Add (MSymbol.integer, plist.Integer);
1314 plist.Set (MSymbol.plist, p);
1316 else if (plist.IsPlist)
1318 MPlist pl = plist.Plist;
1322 if (pl.Symbol == Madd)
1323 pl.Set (MSymbol.symbol, (MSymbol) "+=");
1324 else if (pl.Symbol == Msub)
1325 pl.Set (MSymbol.symbol, (MSymbol) "-=");
1326 else if (pl.Symbol == Mmul)
1327 pl.Set (MSymbol.symbol, (MSymbol) "*=");
1328 else if (pl.Symbol == Mdiv)
1329 pl.Set (MSymbol.symbol, (MSymbol) "/=");
1330 else if (pl.Symbol == Minsert)
1332 // (insert (CANDIDATES ...))
1333 // => (candidates CANDIDATES ...)
1334 if (pl.next.IsPlist)
1336 pl.Set (MSymbol.symbol, Mcandidates);
1338 MPlist p = pl.Plist;
1339 pl.Set (p.key, p.val);
1340 for (p = p.next; ! p.IsEmpty; p = p.next);
1341 pl.Add (p.key, p.val);
1344 else if (pl.Symbol == Mif)
1348 transform (pl.next);
1350 else if (pl.Symbol == Mcond)
1352 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1355 MPlist p = pl.Plist;
1363 else if (pl.Symbol == Mdelete
1364 || pl.Symbol == Mmove
1365 || pl.Symbol == Mmark)
1370 MSymbol sym = pl.Symbol;
1371 MPlist p = new MPlist ();
1372 p.Add (MSymbol.symbol, Mmarker);
1373 p.Add (MSymbol.symbol, sym);
1374 pl.Set (MSymbol.plist, p);
1377 else if (pl.Symbol == Mpushback)
1381 pl.Plist.Push (MSymbol.symbol, Mkeyseq);
1384 else if (pl.IsMText)
1386 // (CANDIDATES ...) => (candidates CANDIDATES ...)
1387 pl.Push (MSymbol.symbol, Mcandidates);
1390 else if (plist.IsSymbol)
1392 MSymbol sym = plist.Symbol;
1394 if (sym.Name.Length >= 3
1395 && sym.Name[0] == '@'
1396 && (sym.Name[1] == '-' || sym.Name[1] == '+'))
1398 int pos = int.Parse (sym.Name.Substring (1));
1399 MPlist p = new MPlist ();
1403 p.Add (MSymbol.symbol, Msurrounding_flag);
1407 if (sym.Name[1] == '+')
1409 p.Add (MSymbol.symbol, Mchar_at);
1410 p.Add (MSymbol.integer, pos);
1412 plist.Set (MSymbol.plist, p);
1418 private static MText parse_description (MPlist plist)
1424 plist = plist.Plist;
1425 if (plist.IsSymbol && plist.Symbol == (MSymbol) "_"
1426 && plist.next.IsMText)
1427 return plist.next.Text;
1432 private static MText parse_description (XmlNode node)
1434 if (node.HasChildNodes)
1435 node = node.FirstChild;
1436 return node.InnerText;
1439 private static MText parse_title (XmlNode node)
1441 return node.InnerText;
1444 private void new_variable (Xex.Symbol name, string desc, int val,
1445 MPlist pl, Xex.Variable vari)
1453 range = new int[pl.Count * 2];
1454 for (int i = 0; i < range.Length; i++)
1458 MPlist p = pl.Plist;
1460 if (! p.IsInteger || ! p.next.IsInteger)
1461 throw new Exception ("Invalid range: " + p);
1462 range[i * 2] = p.Integer;
1463 range[i * 2 + 1] = p.next.Integer;
1465 else if (pl.IsInteger)
1466 range[i * 2] = range[i * 2 + 1] = pl.Integer;
1468 throw new Exception ("Invalid range: " + pl);
1472 domain.Defvar (new Xex.Variable.Int (name, desc, val, range));
1475 Xex.Term term = new Xex.Term (val);
1477 vari.DefaultValue = term;
1482 private void new_variable (Xex.Symbol name, string desc, MText val,
1483 MPlist pl, Xex.Variable vari)
1491 range = new string[pl.Count * 2];
1492 for (int i = 0; i < range.Length; i++)
1495 range[i] = (string) pl.Text;
1497 throw new Exception ("Invalid range: " + pl);
1501 domain.Defvar (new Xex.Variable.Str (name, desc, (string) val, range));
1504 Xex.Term term = new Xex.Term ((string) val);
1506 vari.DefaultValue = term;
1511 private void new_variable (Xex.Symbol name, string desc, MSymbol val,
1512 MPlist pl, Xex.Variable vari)
1515 Xex.Symbol sym = val.Name;
1521 range = new Xex.Symbol[pl.Count * 2];
1522 for (int i = 0; i < range.Length; i++)
1525 range[i] = pl.Symbol.Name;
1527 throw new Exception ("Invalid range: " + pl);
1531 domain.Defvar (new Xex.Variable.Sym (name, desc, sym, range));
1534 Xex.Term term = new Xex.Term (sym);
1536 vari.DefaultValue = term;
1541 private Xex.Variable get_global_var (Xex.Symbol name)
1543 if (im_global == null || this != im_global)
1545 tag = new MDatabase.Tag (Minput_method, MSymbol.t, MSymbol.nil,
1547 im_global = im_table[tag];
1548 if (! im_global.Open ())
1549 throw new Exception ("Failed to load global");
1551 return im_global.domain.GetVar (name, false);
1554 private void parse_variables (MPlist plist)
1556 var_names = new Xex.Symbol[plist.Count];
1558 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1560 if (! plist.IsPlist || ! plist.Plist.IsSymbol)
1561 throw new Exception ("Invalid variable: " + plist);
1563 MPlist p = plist.Plist;
1564 Xex.Symbol name = (Xex.Symbol) p.Symbol.Name;
1565 var_names[i] = name;
1567 string desc = (string) parse_description (p);
1568 Xex.Variable vari = get_global_var (name);
1570 domain.Defvar (vari);
1576 new_variable (name, desc, p.Integer, p.next, vari);
1578 new_variable (name, desc, p.Text, p.next, vari);
1579 else if (p.IsSymbol)
1580 new_variable (name, desc, p.Symbol, p.next, vari);
1582 throw new Exception ("Invalid variable type: " + p.val);
1587 private void parse_variables (XmlNode node)
1589 XmlNodeList node_list = node.ChildNodes;
1591 var_names = new Xex.Symbol[node_list.Count];
1592 for (int i = 0; i < node_list.Count; i++)
1594 Xex.Symbol name = node_list[i].Attributes[0].Value;
1595 Xex.Variable vari = get_global_var (name);
1597 domain.Defvar (vari);
1598 domain.Defvar (node_list[i]);
1599 var_names[i] = name;
1603 private void parse_commands (MPlist plist)
1605 commands = new Command[plist.Count];
1607 for (int i = 0; ! plist.IsEmpty; plist = plist.next)
1608 if (plist.IsPlist && plist.Plist.IsSymbol)
1609 commands[i++] = new Command (plist.Plist);
1612 private void parse_commands (XmlNode node)
1614 XmlNodeList node_list = node.ChildNodes;
1616 commands = new Command[node_list.Count];
1617 for (int i = 0; i < node_list.Count; i++)
1619 if (node_list[i].NodeType == XmlNodeType.Element)
1620 commands[i] = new Command (node_list[i]);
1624 private void parse_plugins (MPlist plist)
1626 plugins = new Dictionary<MSymbol, Plugin> ();
1628 for (; ! plist.IsEmpty; plist = plist.Next)
1630 MPlist p = plist.Plist;
1631 MSymbol sym = p.Symbol;
1632 Plugin plugin = new Plugin (sym.Name);
1634 for (p = p.next; ! p.IsEmpty; p = p.next)
1636 Xex.Function func = new PluginMethod (plugin, p.Symbol.Name);
1637 domain.Defun (func);
1642 private void parse_plugins (XmlNode node)
1644 plugins = new Dictionary<MSymbol, Plugin> ();
1646 foreach (XmlNode n in node.ChildNodes)
1648 Plugin plugin = new Plugin (n.Attributes[0].Value);
1649 foreach (XmlNode nn in n.ChildNodes)
1651 Xex.Function func = new PluginMethod (plugin,
1652 nn.Attributes[0].Value);
1653 domain.Defun (func);
1658 private void parse_macros (XmlNode node)
1660 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1661 if (nn.NodeType == XmlNodeType.Element)
1662 domain.Defun (nn, true);
1663 for (XmlNode nn = node.FirstChild; nn != null; nn = nn.NextSibling)
1664 if (nn.NodeType == XmlNodeType.Element)
1665 domain.Defun (nn, false);
1668 private void parse_maps (XmlNode node)
1672 private void parse_states (XmlNode node)
1676 private void parse_include (MPlist plist)
1678 if (! plist.IsPlist)
1680 MPlist p = plist.Plist;
1681 MSymbol language, name, subname;
1682 language = p.Symbol;
1685 name = subname = MSymbol.nil;
1691 subname = MSymbol.nil;
1696 MInputMethod im = MInputMethod.Find (language, name, subname);
1702 if (! plist.IsSymbol)
1704 MSymbol target_type = plist.Symbol;
1706 MSymbol target_name = MSymbol.nil;
1708 target_name = plist.Symbol;
1709 if (target_type == Mmacro)
1711 if (target_name == MSymbol.nil)
1712 im.domain.CopyFunc (domain);
1714 im.domain.CopyFunc (domain, (Xex.Symbol) target_name.Name);
1716 else if (target_type == Mmap)
1718 if (target_name == MSymbol.nil)
1720 foreach (KeyValuePair<MSymbol, Map> kv in im.maps)
1721 maps[kv.Key] = kv.Value;
1726 if (im.maps.TryGetValue (target_name, out map))
1727 maps[target_name] = map;
1730 else if (target_type == Mstate)
1732 if (target_name == MSymbol.nil)
1734 for (p = im.states; ! p.IsEmpty; p = p.next)
1735 states.Add (p.key, p.val);
1739 object state = im.states.Get (target_name);
1741 states.Add (target_name, state);
1746 private Xex.Term parse_cond (MPlist plist)
1748 Xex.Term[] args = new Xex.Term[plist.Count];
1750 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1752 if (! plist.IsPlist)
1753 throw new Exception ("Invalid cond args: " + plist);
1754 MPlist p = plist.Plist;
1755 List<Xex.Term> arg = new List<Xex.Term> (parse_actions (p));
1756 args[i] = new Xex.Term (arg);
1758 return new Xex.Term (domain, (Xex.Symbol) Mcond.Name, args);
1761 private Xex.Term parse_insert (MPlist plist)
1766 arg = new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1767 else if (plist.IsMText)
1768 arg = new Xex.Term ((string) plist.Text);
1769 else if (plist.IsInteger)
1770 arg = new Xex.Term (plist.Integer);
1771 else if (plist.IsPlist)
1773 MPlist pl = plist.Plist;
1774 args = new Xex.Term[pl.Count];
1776 for (i = 0; ! pl.IsEmpty; i++, pl = pl.next)
1779 args[i] = new Xex.Term ((string) pl.Text);
1780 else if (pl.IsPlist)
1782 List<Xex.Term> list = new List<Xex.Term> ();
1783 for (MPlist p = pl.Plist; ! p.IsEmpty; p = p.next)
1786 list.Add (new Xex.Term ((string) p.Text));
1788 throw new Exception ("Invalid candidates: " + p);
1792 throw new Exception ("Invalid candidates: " + pl);
1794 return new Xex.Term (domain, Ninsert_candidates, args);
1797 throw new Exception ("Invalid arg to insert: " + plist);
1798 args = new Xex.Term[1];
1800 return new Xex.Term (domain, Ninsert, args);
1803 private Xex.Term parse_select (MPlist plist)
1805 Xex.Term[] args = new Xex.Term[1];
1806 if (plist.IsInteger)
1807 args[0] = new Xex.Term (plist.Integer);
1808 else if (! plist.IsSymbol)
1809 throw new Exception ("Invalid arg to select: " + plist);
1810 else if (plist.Symbol.Name[0] == '@')
1811 args[0] = new Xex.Term (Selector.Get (plist.Symbol));
1813 args[0] = new Xex.Term (domain, (Xex.Symbol) plist.Symbol.Name);
1814 return new Xex.Term (domain, (Xex.Symbol) Mselect.Name, args);
1817 private Xex.Term parse_funcall_with_marker (MPlist plist, MSymbol func)
1819 Xex.Term[] args = new Xex.Term[1];
1820 if (plist.IsInteger && func != Mmark)
1821 args[0] = new Xex.Term (plist.Integer);
1822 else if (plist.IsSymbol)
1823 args[0] = new Xex.Term (Marker.Get (plist.Symbol));
1825 throw new Exception ("Invalid arg to " + func + ": " + plist);
1826 return new Xex.Term (domain, (Xex.Symbol) func.Name, args);
1829 private Xex.Term parse_char_at (MSymbol name)
1831 Xex.Term[] args = new Xex.Term[1];
1832 args[0] = new Xex.Term (Marker.Get (name));
1833 return new Xex.Term (domain, Nchar_at, args);
1836 private Xex.Term parse_action (MPlist plist)
1840 MPlist p = plist.Plist;
1842 if (p.IsMText || p.IsPlist)
1843 return parse_insert (p);
1845 throw new Exception ("Invalid action: " + p);
1846 MSymbol name = p.Symbol;
1849 return parse_cond (p);
1850 if (name == Minsert)
1851 return parse_insert (p);
1852 if (name == Mselect)
1853 return parse_select (p);
1854 if (name == Mdelete || name == Mmove || name == Mmark)
1855 return parse_funcall_with_marker (p, name);
1856 if (name.Name[0] == '@')
1857 return parse_char_at (name);
1858 if (name == Mset || name == Madd || name == Msub
1859 || name == Mmul || name == Mdiv)
1862 throw new Exception ("Invalid action: " + p);
1863 Xex.Symbol varname = p.Symbol.Name;
1864 return new Xex.Term (domain, (Xex.Symbol) name.Name,
1865 varname, parse_actions (p.next));
1868 return new Xex.Term (domain, (Xex.Symbol) name.Name,
1871 else if (plist.IsMText || plist.IsInteger || plist.IsSymbol)
1872 return parse_insert (plist);
1874 throw new Exception ("Invalid action: " + plist);
1877 private Xex.Term[] parse_actions (MPlist plist)
1879 Xex.Term[] terms = new Xex.Term[plist.Count];
1881 for (int i = 0; ! plist.IsEmpty; i++, plist = plist.next)
1882 terms[i] = parse_action (plist);
1887 private void parse_macros (MPlist plist)
1889 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
1892 MPlist p = pl.Plist;
1896 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null, null, true);
1898 for (MPlist pl = plist; ! pl.IsEmpty; pl = pl.next)
1901 MPlist p = pl.Plist;
1906 domain.Defun ((Xex.Symbol) p.Symbol.Name, false, null,
1907 parse_actions (p.next), false);
1911 private void parse_maps (MPlist plist)
1913 for (; ! plist.IsEmpty; plist = plist.next)
1916 MPlist pl = plist.Plist;
1920 Map map = new Map ();
1921 map.name = pl.Symbol;
1922 maps[map.name] = map;
1923 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1927 MPlist p = pl.Plist;
1930 keys = new KeySeq (p.Text);
1932 keys = new KeySeq (p.Plist);
1939 new Xex.Term (domain, Nprogn, parse_actions (p)));
1944 private void parse_states (MPlist plist)
1946 for (; ! plist.IsEmpty; plist = plist.next)
1949 MPlist pl = plist.Plist;
1960 State state = new State (pl.Symbol);
1961 state.title = title;
1963 states = new MPlist ();
1964 states.Add (state.name, state);
1965 for (pl = pl.next; ! pl.IsEmpty; pl = pl.next)
1969 MPlist p = pl.Plist;
1972 MSymbol map_name = p.Symbol;
1974 Xex.Term term = new Xex.Term (domain, Nprogn, parse_actions (p));
1975 state.branches.Add (map_name, term);
1980 private static Xex.Term Finsert (Xex.Domain domain, Xex.Variable vari,
1983 ((Context) domain.context).insert (args[0]);
1987 private static Xex.Term Finsert_candidates (Xex.Domain domain,
1991 ((Context) domain.context).insert_candidates (args[0]);
1995 private static Xex.Term Fchar_at (Xex.Domain domain, Xex.Variable vari,
1998 Context ic = (Context) domain.context;
1999 Marker m = (Marker) args[0].Objval;
2001 return new Xex.Term (ic.char_at (m.Position (ic)));
2004 private static Xex.Term Fdelete (Xex.Domain domain, Xex.Variable vari,
2007 ((Context) domain.context).delete ((int) args[0].Intval);
2011 private static Xex.Term Fselect (Xex.Domain domain, Xex.Variable vari,
2014 Candidates can = ((Context) domain.context).candidates;
2017 ((Selector) args[0].Objval).Select (can);
2021 private static Xex.Term Fshow (Xex.Domain domain, Xex.Variable vari,
2024 ((Context) domain.context).show ();
2028 private static Xex.Term Fhide (Xex.Domain domain, Xex.Variable vari,
2031 ((Context) domain.context).hide ();
2035 private static Xex.Term Fmove (Xex.Domain domain, Xex.Variable vari,
2039 ((Context) domain.context).move (args[0].Intval);
2042 Marker m = (Marker) args[0].Objval;
2043 Context ic = (Context) domain.context;
2044 ((Context) domain.context).move (m.Position (ic));
2049 private static Xex.Term Fmark (Xex.Domain domain, Xex.Variable vari,
2052 Marker m = (Marker) args[0].Objval;
2053 m.Mark ((Context) domain.context);
2057 private static Xex.Term Fpushback (Xex.Domain domain, Xex.Variable vari,
2060 Context ic = (Context) domain.context;
2063 ic.pushback (args[0].Intval);
2064 else if (args[0].IsStr)
2065 ic.pushback (new KeySeq (args[0].Strval));
2067 ic.pushback ((KeySeq) args[0].Objval);
2071 private static Xex.Term Fpop (Xex.Domain domain, Xex.Variable vari,
2074 ((Context) domain.context).pop ();
2078 private static Xex.Term Fundo (Xex.Domain domain, Xex.Variable vari,
2081 int n = args.Length == 0 ? -2 : args[0].Intval;
2082 ((Context) domain.context).undo (n);
2086 private static Xex.Term Fcommit (Xex.Domain domain, Xex.Variable vari,
2089 ((Context) domain.context).commit ();
2093 private static Xex.Term Funhandle (Xex.Domain domain, Xex.Variable vari,
2096 ((Context) domain.context).commit ();
2097 args = new Xex.Term[2];
2098 args[0] = args[1] = Tcatch_tag;
2099 return Xex.Fthrow (domain, vari, args);
2102 private static Xex.Term Fshift (Xex.Domain domain, Xex.Variable vari,
2105 ((Context) domain.context).shift (args[0].Symval);
2109 private static Xex.Term Fshiftback (Xex.Domain domain, Xex.Variable vari,
2112 ((Context) domain.context).shift_back ();
2116 private static Xex.Term Fkey_count (Xex.Domain domain, Xex.Variable vari,
2119 return new Xex.Term (((Context) domain.context).key_head);
2122 private static Xex.Term Fsurrounding_flag (Xex.Domain domain,
2126 return new Xex.Term (((Context) domain.context).surrounding_flag);
2129 public override string ToString ()
2131 string str = (String.Format ("({0} (title \"{1}\")", tag, title));
2132 if (commands != null)
2134 str += " (commands";
2135 foreach (Command cmd in commands)
2139 if (var_names != null)
2141 str += " (variables";
2142 foreach (Xex.Symbol var in var_names)
2146 if (plugins != null)
2149 foreach (KeyValuePair<MSymbol, Plugin> kv in plugins)
2150 str += " " + kv.Value;
2154 foreach (KeyValuePair<MSymbol, Map> kv in maps)
2155 str += " " + kv.Value;
2157 foreach (MPlist p in states)
2162 public class Context
2164 internal static Xex.Symbol Ncandidates_group_size
2165 = "candidates-group-size";
2166 public MInputMethod im;
2167 private MText produced;
2168 private bool active;
2169 private MText status;
2170 internal MText preedit;
2171 internal int cursor_pos;
2172 internal Dictionary<Xex.Symbol, int> markers;
2173 internal Candidates candidates;
2174 private int candidate_from, candidate_to;
2175 private bool candidate_show;
2177 private List<State> state_list;
2179 // Sequence of input keys.
2180 internal KeySeq keys;
2182 // Index into KEYS specifying the next key to handle.
2183 internal int key_head;
2186 private int state_key_head;
2187 private object state_var_values;
2188 private int commit_key_head;
2189 private MText state_preedit;
2190 private int state_pos;
2191 internal MText preceding_text = new MText ();
2192 internal MText following_text = new MText ();
2194 // Set to false before calling the method 'handle_key', and set
2195 // to true when some key is unhandled.
2196 private bool key_unhandled;
2198 // The unhandled key. It has the meaning only when
2199 // 'key_unhandled' is true.
2200 private Key unhandled_key;
2202 internal Xex.Domain domain;
2204 internal ChangedStatus changed;
2206 public ChangedStatus Changed { get { return changed; } }
2208 public Context (MInputMethod im)
2211 domain = new Xex.Domain (im.domain, this);
2212 state_list = new List<State> ();
2213 state_list.Add ((State) im.states.val);
2214 keys = new 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,
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 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 (Mcandidates, pos - 1,
2328 if (cursor_pos < preedit.Length - 1)
2331 preedit.FindProp (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 (GetSurroundingText != null
2369 && 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 (GetSurroundingText != null
2387 && 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 (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 state = state_list.Last ();
2498 if (state_list.Count > 1)
2499 state_list.RemoveAt (state_list.Count - 1);
2503 state = (State) im.states.Get (sym);
2505 throw new Exception ("Unknown state: " + state.name);
2509 state = state_list.Last;
2510 state_list.RemoveAt (state_list.Count -1);
2512 if (state == (State) im.states.val)
2519 state_key_head = key_head;
2520 state_pos = cursor_pos;
2521 state_preedit = preedit.Dup ();
2522 if (state != state_list.Last ())
2524 state_list.Add (state);
2525 state_var_values = domain.SaveValues ();
2526 status = state.title;
2529 changed |= ChangedStatus.StateTitle;
2531 = (Xex) state.branches.Get (MSymbol.t);
2532 if (on_entry != null)
2533 on_entry.Eval (domain);
2538 internal void reset ()
2541 state_preedit.Del ();
2545 key_head = commit_key_head = 0;
2546 state_list.Clear ();
2547 state_list.Add ((State) im.states.Val);
2552 internal object GetCandidates (out int column)
2555 if (cursor_pos == 0)
2557 Candidates candidates
2558 = (Candidates) preedit.GetProp (cursor_pos - 1, Mcandidates);
2559 if (candidates == null)
2561 column = candidates.Column;
2562 return candidates.Current;
2565 internal void HandleKey ()
2569 public bool Toggle ()
2575 public bool UnhandledKey (out Key key)
2577 key = unhandled_key;
2578 return key_unhandled;
2581 public bool Produced (out MText mt)
2584 return (produced.Length > 0);
2589 // true: All keys are handled and there's no text to commit.
2590 // false: Some key is unhandled or there's a text to commit.
2591 // The caller should use methods UnhandledKey and Produced.
2593 public bool Filter (Key key)
2595 if (check_reload (key))
2597 changed = ChangedStatus.None;
2599 preceding_text.Del ();
2600 following_text.Del ();
2602 key_unhandled = false;
2605 while (key_head < keys.Length)
2607 if (! handle_key ())
2609 unhandled_key = keys[key_head++];
2610 key_unhandled = true;
2616 keys.RemoveRange (0, key_head);
2617 return (! key_unhandled && produced.Length == 0);