*** empty log message ***
[m17n/m17n-lib-cs.git] / MText.cs
1 using System;
2 using System.Text;
3 using System.Collections;
4 using System.Collections.Generic;
5 using M17N;
6 using M17N.Core;
7
8 namespace M17N.Core
9 {
10 #if false
11   public enum MTextFormat
12     {
13       MTEXT_FORMAT_US_ASCII,
14       MTEXT_FORMAT_UTF_8,
15       MTEXT_FORMAT_UTF_16BE,
16       MTEXT_FORMAT_UTF_16LE,
17       MTEXT_FORMAT_UTF_32BE,
18       MTEXT_FORMAT_UTF_32LE,
19     }
20 #endif
21
22   public class MProperty
23   {
24     [FlagsAttribute]
25     public enum Flags
26     {
27       None =            0x00,
28
29       /// On inserting a text in between two characters, if the
30       /// preceding and following characters have Sticky properties of
31       /// the same key with same values, the inserted text inherits
32       /// those properties.  In that case, properties of the inserted
33       /// text are overriden.
34       Sticky =          0x01,   // 00000001
35
36       /// On inserting a text before a character, if the character has
37       /// FrontSticky properties, the inserted text inherits those
38       /// properties.
39       FrontSticky =     0x03,   // 00000011
40
41       /// On inserting a text after a character, if the character has
42       /// RearSticky properties, the inserted text inherits those
43       /// properties.
44       RearSticky =      0x05,   // 00000101
45
46       /// Like RearSticky, but if the inserted text inherits no
47       /// properties from the preceding character, it inherits
48       /// BothSticky properties from the following character if any.
49       BothSticky =      0x07,   // 00000111
50
51       /// This property is deleted from a span of text if the span is
52       /// modified (i.e. one of a character is changed, a text is
53       /// inserted, some part is deleted).  Here, "span" means a
54       /// sequence of characters that has this property with the same
55       /// value.  This property is also deleted if a property of the
56       /// same key is added, which means that this property is not
57       /// stackable.  In addition this property is never merged with
58       /// the same value of preceding or following property.  At last,
59       /// this property can't be sticky in any way.
60       Sensitive =       0x10,   // 00010000
61
62       /// Like Sensitive but also this property is deleted from a span
63       /// of text if a characeter just before the span is modified,
64       /// inserted, or deleted.
65       FrontSensitive =  0x30,   // 00110000
66
67       /// Like Sensitive but also this property is deleted from a span
68       /// of text if a character just after the span is modified,
69       /// inserted, or deleted.
70       RearSensitive =   0x50,   // 01010000
71
72       /// Same as (FrontSensitive | RearSensitive).
73       BothSensitive =   0x70,   // 01110000
74     };
75
76     internal MSymbol key;
77     internal object val;
78
79     public MSymbol Key { get { return key; } }
80     public object Val { get { return val; } }
81
82     public MProperty (MSymbol key, object val)
83     {
84       if (key.flags == null)
85         key.flags = Flags.None;
86       this.key = key;
87       this.val = val;
88     }
89
90     public MProperty (string name, object val)
91     {
92       key = MSymbol.PropertyKey (name);
93       this.val = val;
94     }
95
96     public static bool HasFlags (MSymbol key, Flags flags)
97     {
98       return ((key.flags & flags) == flags);
99     }
100
101     public override string ToString ()
102     {
103       return key.ToString () + ":" + val;
104     }
105   }
106
107   public class MText : IEnumerable, IEquatable<MText>, IComparable<MText>
108   {
109 #if false
110     public enum MTextFormat format;
111 #endif
112     private StringBuilder sb;
113     private int nchars;
114     private int cache_pos;
115     private int cache_idx;
116     private MPlist intervals;
117     private MPlist default_property;
118     private bool read_only;
119
120     private static UTF8Encoding utf8 = new UTF8Encoding ();
121
122     private static int count_chars (String str)
123     {
124       int len = str.Length, n = 0;
125
126       for (int i = 0; i < len; i++, n++) 
127         if (surrogate_high_p (str[i]))
128           i++;
129       return n;
130     }
131
132     private static int count_chars (StringBuilder str)
133     {
134       int len = str.Length, n = 0;
135
136       for (int i = 0; i < len; i++, n++) 
137         if (surrogate_high_p (str[i]))
138           i++;
139       return n;
140     }
141
142     public MText ()
143       {
144         sb = new StringBuilder ();
145         intervals = new MPlist ();
146       }
147
148     public MText (byte[] str)
149       {
150         sb = new StringBuilder (utf8.GetString (str));
151         nchars = count_chars (sb);
152         intervals = new MPlist ();
153       }
154
155     public MText (String str)
156       {
157         sb = new StringBuilder (str);
158         nchars = count_chars (str);
159         intervals = new MPlist ();
160       }
161
162     public MText (StringBuilder str)
163       {
164         sb = str;
165         nchars = count_chars (str);
166         intervals = new MPlist ();
167       }
168
169     public static MText operator+ (object obj, MText mt)
170     {
171       if (obj is string)
172         {
173           MText mtnew = new MText ((string) obj);
174           return mtnew.Ins (mtnew.Length, mt);
175         }
176       throw new Exception ("Unknown object type: " + obj.GetType());
177     }
178
179     public static MText operator+ (MText mt, object obj)
180     {
181       if (obj is string)
182         return mt + new MText ((string) obj);
183       if (obj is int)
184         return mt.Dup ().Ins (mt.Length, (int) obj);
185       if (obj is char)
186         return mt.Dup ().Ins (mt.Length, (int) ((char) obj));
187       throw new Exception ("Unknown object type: " + obj.GetType());
188     }
189
190     public static MText operator+ (MText mt1, MText mt2)
191     {
192       return mt1.Dup ().Ins (mt1.Length, mt2);
193     }
194
195     // Public properties
196     public bool ReadOnly { get { return read_only; } }
197     public int Length { get { return nchars; } }
198
199     // Public methods
200
201     // for IEnumerable interface
202     public IEnumerator GetEnumerator() { return new MTextEnum (this); }
203
204     // for IEquatable interface
205     public bool Equals (MText other) { return this.sb.Equals (other.sb); }
206
207     // for IComparable interface
208     public int CompareTo (MText other)
209     {
210       return this.sb.ToString ().CompareTo (other.sb.ToString ());
211     }
212
213     public override string ToString () { return sb.ToString (); }
214
215     private static bool surrogate_high_p (char c)
216     {
217       return (c >= 0xD800 && c < 0xDC00);
218     }
219
220     private static bool surrogate_low_p (char c)
221     {
222       return (c >= 0xDC00 && c < 0xE000);
223     }
224
225     private static int inc_idx (StringBuilder sb, int i)
226     {
227       return (i + (surrogate_high_p (sb[i]) ? 2 : 1));
228     }
229
230     private static int dec_idx (StringBuilder sb, int i)
231     {
232       return (i - (surrogate_low_p (sb[i - 1]) ? 2 : 1));
233     }
234
235     private static int pos_to_idx (MText mt, int pos)
236     {
237       if (pos == mt.cache_pos)
238         return mt.cache_idx;
239
240       int p, i;
241       bool forward;
242
243       if (pos < mt.cache_pos)
244         {
245           if (mt.cache_pos == mt.cache_idx)
246             return mt.cache_idx;
247           if (pos < mt.cache_pos - pos)
248             {
249               p = i = 0;
250               forward = true;
251             }
252           else
253             {
254               p = mt.cache_pos; i = mt.cache_idx;
255               forward = false;
256             }
257         }
258       else
259         {
260           if (mt.nchars - mt.cache_pos == mt.sb.Length - mt.cache_idx)
261             return (mt.cache_idx + pos - mt.cache_pos);
262           if (pos - mt.cache_pos < mt.nchars - pos)
263             {
264               p = mt.cache_pos; i = mt.cache_idx;
265               forward = true;
266             }
267           else
268             {
269               p = mt.nchars; i = mt.sb.Length;
270               forward = false;
271             }
272         }
273       if (forward)
274         for (; p < pos; i = inc_idx (mt.sb, i), p++);
275       else
276         for (; p > pos; i = dec_idx (mt.sb, i), p--);
277       mt.cache_pos = p;
278       mt.cache_idx = i;
279       return i;
280     }
281
282     private void check_pos (int pos, bool tail_ok)
283     {
284       if (pos < 0 || (tail_ok ? pos > nchars : pos >= nchars))
285         throw new Exception ("Invalid MText position:" + pos);
286     }
287
288     private bool check_range (int from, int to, bool zero_ok)
289     {
290       if (from < 0 || (zero_ok ? from > to : from >= to)
291           || to > nchars)
292         throw new Exception ("Invalid MText range");
293       return (from == to);
294     }
295
296     private void insert (int pos, MText mt2, int from, int to)
297     {
298       check_pos (pos, true);
299
300       if (M17n.debug)
301         {
302           Console.Write ("inserting {0} to {1} of ", from, to);
303           mt2.DumpPropNested ();
304         }
305       if (from == to)
306         return;
307       foreach (MPlist plist in intervals)
308         {
309           MInterval root = (MInterval) plist.Val;
310           MPlist p = mt2.intervals.Find (plist.Key);
311           MInterval i = p == null ? null : (MInterval) p.Val;
312
313           root.Insert (pos, i, from, to);
314         }
315       foreach (MPlist plist in mt2.intervals)
316         if (intervals.Find (plist.Key) == null)
317           {
318             MInterval root;
319
320             if (nchars == 0)
321               root = ((MInterval) plist.Val).Copy (this, from, to);
322             else
323               {
324                 root = new MInterval (plist.Key, this);
325                 root.Insert (pos, (MInterval) plist.Val, from, to);
326               }
327             intervals.Push (plist.Key, root);
328           }
329
330       int pos_idx = pos_to_idx (this, pos);
331       int from_idx = pos_to_idx (mt2, from);
332       int to_idx = pos_to_idx (mt2, to);
333
334       sb.Insert (pos_idx, mt2.sb.ToString (from_idx, to_idx - from_idx));
335       nchars += to - from;
336     }
337
338     private void insert (int pos, int c)
339     {
340       check_pos (pos, true);
341
342       int pos_idx = pos_to_idx (this, pos);
343
344       if (c < 0x10000)
345         {
346           char ch = (char) c;
347           sb.Insert (pos_idx, ch);
348         }
349       else
350         {
351           char high = (char) (0xD800 + ((c - 0x10000) >> 10));
352           char low = (char) (0xDC00 + ((c - 0x10000) & 0x3FF));
353           sb.Insert (pos_idx, low);
354           sb.Insert (pos_idx, high);
355         }
356       nchars++;
357       foreach (MPlist plist in intervals)
358         ((MInterval) plist.Val).Insert (pos, null, 0, 1);
359     }
360
361     public int this[int i]
362     {
363       set {
364         i = pos_to_idx (this, i);
365         if (value < 0x10000)
366           {
367             if (surrogate_high_p (sb[i]))
368               sb.Remove (i, 1);
369             sb[i] = (char) value;
370           }
371         else
372           {
373             char high = (char) (0xD800 + ((value - 0x10000) >> 10));
374             char low = (char) (0xDC00 + ((value - 0x10000) & 0x3FF));
375
376             if (! surrogate_high_p (sb[i]))
377               sb.Insert (i, 0);
378             sb[i] = high;
379             sb[i + 1] = low;
380           }
381       }
382       get {
383         i = pos_to_idx (this, i);
384         return (surrogate_high_p (sb[i])
385                 ? ((sb[i] - 0xD800) << 10) + (sb[i + 1] - 0xDC00) + 0x10000
386                 : sb[i]);
387       }
388     }
389
390     public MText Dup ()
391     {
392       MText mt = new MText (sb.ToString ());
393
394       foreach (MPlist p in intervals)
395         mt.intervals.Add (p.Key, ((MInterval) p.Val).Copy (mt, 0, Length));
396       return mt;
397     }
398
399     public MText Dup (int from, int to)
400     {
401       if (check_range (from, to, true))
402         return new MText ();
403       int from_idx = pos_to_idx (this, from);
404       int len = pos_to_idx (this, to) - from_idx;
405       MText mt = new MText (sb.ToString ().Substring (from_idx, len));
406
407       foreach (MPlist p in intervals)
408         mt.intervals.Add (p.Key, ((MInterval) p.Val).Copy (mt, from, to));
409       return mt;
410     }
411
412     public MText Ins (int pos, int c)
413     {
414       insert (pos, c);
415       return this;
416     }
417
418     public MText Ins (int pos, MText mt)
419     {
420       insert (pos, mt, 0, mt.nchars);
421       return this;
422     }
423
424     public MText Ins (int pos, MText mt, int from, int to)
425     {
426       insert (pos, mt, from, to);
427       return this;
428     }
429
430     public MText Cat (int c)
431     {
432       insert (nchars, c);
433       return this;
434     }
435
436     public MText Del (int from, int to)
437     {
438       if (check_range (from, to, true))
439         return this;
440
441       sb.Remove (from, pos_to_idx (this, to) - pos_to_idx (this, from));
442       nchars -= to - from;
443
444       if (nchars > 0)
445         foreach (MPlist plist in intervals)
446           {
447             MInterval root = (MInterval) plist.Val;
448             root.Delete (from, to);
449             if (from > 0 && from < nchars)
450               ((MInterval) plist.Val).MergeAfterChange (from, from);
451           }
452       else
453         intervals.Clear ();
454       if (M17n.debug)
455         DumpPropNested ();
456       return this;
457     }
458
459     public object GetProp (int pos, MSymbol key)
460     {
461       check_pos (pos, false);
462
463       MInterval i = (MInterval) intervals.Get (key);
464       if (i == null)
465         return null;
466
467       MProperty prop = i.Get (pos);
468       return (prop != null ? prop.Val : null);
469     }
470
471     public object GetProp (int pos, MSymbol key, out MProperty prop)
472     {
473       check_pos (pos, false);
474
475       MInterval i = (MInterval) intervals.Get (key);
476       if (i == null)
477         return (prop = null);
478       prop = i.Get (pos);
479       return (prop != null ? prop.Val : null);
480     }
481
482     public object GetProp (int pos, MSymbol key, out MProperty[] array)
483     {
484       check_pos (pos, false);
485
486       MInterval i = (MInterval) intervals.Get (key);
487       if (i == null)
488         return (array = null);
489       MProperty prop = i.Get (pos, out array);
490       return (prop != null ? prop.Val : null);
491     }
492
493     public void PushProp (int from, int to, MSymbol key, object val)
494     {
495       if (! check_range (from, to, true))
496         PushProp (from, to, new MProperty (key, val));
497     }
498
499     public void PushProp (int from, int to, MProperty prop)
500     {
501       if (from < 0)
502         {
503           if (default_property == null)
504             default_property = new MPlist ();
505           default_property.Push (prop.key, prop.val);
506         }
507       else
508         {
509           if (check_range (from, to, true))
510             return;
511
512           MPlist p = intervals.Find (prop.key);
513           MInterval root;
514
515           if (p == null)
516             {
517               root = new MInterval (prop.key, this);
518               intervals.Push (prop.key, root);
519             }
520           else
521             {
522               root = (MInterval) p.Val;
523               if (root.isSensitive)
524                 {
525                   root.PopSensitive (from, to);
526                   root.MergeAfterChange (from, to);
527                   root = (MInterval) p.Val;
528                   if (M17n.debug)
529                     DumpPropNested ();
530                 }
531             }
532           root.Push (from, to, prop);
533           root.MergeAfterChange (from, to);
534           root.Balance ();
535         }
536     }
537
538     public void PopProp (int from, int to, MSymbol key)
539     {
540       if (from < 0)
541         {
542           if (default_property == null)
543             return;
544           MPlist p = default_property.Find (key);
545
546           if (p != null)
547             p.Pop ();
548         }
549       else
550         {
551           if (check_range (from, to, true))
552             return;
553
554           MPlist p = intervals.Find (key);
555
556           if (p != null)
557             {
558               MInterval root = (MInterval) p.Val;
559               if (root.isSensitive)
560                 root.PopSensitive (from, to);
561               else
562                 root.Pop (from, to);
563               root = (MInterval) p.Val;
564               if (M17n.debug)
565                 DumpPropNested ();
566               root.MergeAfterChange (from, to);
567               root.Balance ();
568             }
569         }
570     }
571
572     public void DumpProp ()
573     {
574       Console.Write ("(");
575       foreach (MPlist p in intervals)
576         ((MInterval) p.Val).Dump (true);
577       Console.WriteLine (")");
578     }
579
580     public void DumpPropNested ()
581     {
582       Console.WriteLine ("total length = {0}", Length);
583       foreach (MPlist p in intervals)
584         ((MInterval) p.Val).DumpNested (true);
585     }
586
587     private class MInterval
588     {
589       // position: 0   1   2   3   4   5   6   7
590       //           | A | B | C | D | E   F | G |
591       // interval  |---|---|---|<->|-------|---|
592       //           |---|<->|---|   |<----->|---|
593       //           |<->|   |<->|           |<->|
594       // 
595       //                      [7 (3 4)]
596       //              [3 (1 2)]       [3 (4 6)]
597       //         [1 (0 1)] [2 (2 3)]      [1 (6 7)]
598       //
599       private static int count = 0;
600       private int ID;
601       private int Length;
602       private int From, To;
603       private MSymbol Key;
604       private MPlist Stack;
605       private MInterval Left, Right, Parent;
606       private MText mtext;
607
608       public MInterval (MSymbol key, MText mt, int length)
609       {
610         if (length <= 0)
611           throw new Exception ("Invalid interval length");
612         Key = key;
613         mtext = mt;
614         Length = length;
615         Stack = new MPlist ();
616         ID = count++;
617       }
618
619       public MInterval (MSymbol key, MText mt)
620       {
621         Key = key;
622         mtext = mt;
623         Length = mt.sb.Length;
624         From = 0;
625         To = Length;
626         Stack = new MPlist ();
627         ID = count++;
628       }
629
630       /// POS must be smaller than Length;
631       public MProperty Get (int pos)
632       {
633         MInterval i = find_head (pos);
634
635         return (i.Stack.IsEmpty ? null : (MProperty) i.Stack.Val);
636       }
637
638       /// POS must be smaller than Length;
639       public MProperty Get (int pos, out MProperty[] array)
640       {
641         MInterval i = find_head (pos);
642
643         if (i.To == pos)
644           i = i.Next;
645         if (i.Stack.IsEmpty)
646           {
647             array = null;
648             return null;
649           }
650         array = new MProperty[i.Stack.Count];
651
652         int idx;
653         MPlist p;
654         for (idx = 0, p = i.Stack; ! p.IsEmpty; idx++, p = p.Next)
655           array[idx] = (MProperty) p.Val;
656         return array[0];
657       }
658
659       private MInterval (MSymbol key, MText mt, int length, MPlist stack)
660       {
661         Key = key;
662         mtext = mt;
663         Length = length;
664         From = 0;
665         To = Length;
666         Stack = stack == null ? new MPlist () : stack.Clone ();
667         ID = count++;
668       }
669
670       private bool isRearSticky
671       {
672         get { return MProperty.HasFlags (Key, MProperty.Flags.RearSticky) ; }
673       }
674
675       private bool isFrontSticky
676       {
677         get { return MProperty.HasFlags (Key, MProperty.Flags.FrontSticky) ; }
678       }
679
680       public bool isSensitive
681       {
682         get { return MProperty.HasFlags (Key, MProperty.Flags.Sensitive) ; }
683       }
684
685       public bool isFrontSensitive
686       {
687         get { return MProperty.HasFlags (Key,
688                                          MProperty.Flags.FrontSensitive) ; }
689       }
690
691       public bool isRearSensitive
692       {
693         get { return MProperty.HasFlags (Key,
694                                          MProperty.Flags.RearSensitive) ; }
695       }
696
697       private void update_from_to ()
698       {
699         if (Parent == null)
700           {
701             From = LeftLength;
702             To = Length - RightLength;
703           }
704         else if (Parent.Left == this)
705           {
706             From = Parent.From - Length + LeftLength;
707             To = Parent.From - RightLength;
708           }
709         else
710           {
711             From = Parent.To + LeftLength;
712             To = Parent.To + Length - RightLength;
713           }
714       }
715
716       private int LeftLength
717       {
718         get { return (Left == null ? 0 : Left.Length); }
719       }
720
721       private int RightLength
722       {
723         get { return (Right == null ? 0 : Right.Length); }
724       }
725
726       private MInterval LeftMost
727       {
728         get {
729           update_from_to ();
730           if (Left == null)
731             return this;
732           return Left.LeftMost;
733         }
734       }
735
736       private MInterval RightMost
737       {
738         get {
739           update_from_to ();
740           if (Right == null)
741             return this;
742           return Right.RightMost;
743         }
744       }
745
746       private MInterval Prev {
747         get {
748           MInterval i;
749
750           if (Left != null)
751             {
752               for (i = Left; i.Right != null; i = i.Right)
753                 i.update_from_to ();
754               i.update_from_to ();
755             }
756           else
757             {
758               MInterval child = this;
759               for (i = Parent; i != null && i.Left == child;
760                    child = i, i = i.Parent);
761             }
762           return i;
763         }
764       }
765
766       private MInterval Next {
767         get {
768           MInterval i;
769
770           if (Right != null)
771             {
772               for (i = Right; i.Left != null; i = i.Left)
773                 i.update_from_to ();
774               i.update_from_to ();
775             }
776           else
777             {
778               MInterval child = this;
779               for (i = Parent; i != null && i.Right == child;
780                    child = i, i = i.Parent);
781             }
782           return i;
783         }
784       }
785
786       private MInterval find_head (int pos)
787       {
788         update_from_to ();
789         if (pos < From)
790           return Left.find_head (pos);
791         if (pos >= To)
792           return Right.find_head (pos);
793         return this;
794       }
795
796       private MInterval find_tail (int pos)
797       {
798         update_from_to ();
799         if (pos <= From)
800           return Left.find_tail (pos);
801         if (pos > To)
802           return Right.find_tail (pos);
803         return this;
804       }
805
806       private bool mergeable (MInterval i)
807       {
808         MPlist p1, p2;
809
810         if (Stack.IsEmpty && i.Stack.IsEmpty)
811           return true;
812         if (isSensitive)
813           return false;
814         for (p1 = Stack, p2 = i.Stack; ! p1.IsEmpty && ! p2.IsEmpty;
815              p1 = p1.Next, p2 = p2.Next)
816           if (p1.Val != p2.Val)
817             return false;
818         return (p1.IsEmpty && p2.IsEmpty);
819       }
820
821       //      p-. or .-p              p-. or .-p
822       //       .-this-.                .-right-.
823       //    left   .-right-.  ->   .-this-.    c2
824       //          c1       c2    left     c1
825       private MInterval promote_right ()
826       {
827         MInterval c1 = Right.Left;
828
829         // Update Parent.
830         if (Parent == null)
831           mtext.intervals.Put (Key, Right);
832         else if (Parent.Left == this)
833           Parent.Left = Right;
834         else
835           Parent.Right = Right;
836
837         // Update Right.
838         Right.Parent = Parent;
839         Right.Left = this;
840         Right.Length += LeftLength + (To - From);
841
842         // Update this.
843         Parent = Right;
844         Right = c1;
845         Length = LeftLength + (To - From) + RightLength;
846
847         // Update C1 if necessary.
848         if (c1 != null)
849           c1.Parent = this;
850
851         Parent.update_from_to ();
852         return Parent;
853       }
854
855       //      p-. or .-p              p-. or .-p
856       //       .-this-.                .-left-.
857       //  .-left-.  .-right-.  ->     c1    .-this-.
858       // c1      c2                        c2     right
859       private MInterval promote_left ()
860       {
861         MInterval c2 = Left.Right;
862
863         // Update Parent.
864         if (Parent == null)
865           mtext.intervals.Put (Key, Left);
866         else if (Parent.Left == this)
867           Parent.Left = Left;
868         else
869           Parent.Right = Left;
870
871         // Update Left.
872         Left.Parent = Parent;
873         Left.Right = this;
874         Left.Length += (To - From) + RightLength;
875
876         // Update this.
877         Parent = Left;
878         Left = c2;
879         Length = LeftLength + (To - From) + RightLength;
880
881         // Update C2 if necessary.
882         if (c2 != null)
883           c2.Parent = this;
884
885         Parent.update_from_to ();
886         return Parent;
887       }
888
889       public MInterval Balance ()
890       {
891         MInterval i = this;
892
893         update_from_to ();
894         while (true)
895           {
896             //       .-this-.
897             //  .-left-.  .-right-.
898             // c1     c2  c3      c4
899             int diff = i.LeftLength - i.RightLength;
900             int new_diff;
901
902             if (diff > 0)
903               {
904                 new_diff = (i.Length - i.LeftLength
905                             + i.Left.RightLength - i.Left.LeftLength);
906                 if (Math.Abs (new_diff) >= diff)
907                   break;
908                 M17n.DebugPrint ("balancing #{0} by promoting left...", i.ID);
909                 i = i.promote_left ();
910                 M17n.DebugPrint ("done\n");
911                 i.Right.Balance ();
912               }
913             else if (diff < 0)
914               {
915                 new_diff = (i.Length - i.RightLength
916                             + i.Right.LeftLength - i.Right.RightLength);
917                 if (Math.Abs (new_diff) >= diff)
918                   break;
919                 M17n.DebugPrint ("balancing #{0} by promoting right\n", i.ID);
920                 i = i.promote_right ();
921                 i.Left.Balance ();
922               }
923             else
924               break;
925           }
926         return i;
927       }
928
929       public MInterval Copy (MText mt, int start, int end)
930       {
931         MInterval copy, left_copy = null, right_copy = null;
932
933         update_from_to ();
934
935         if (start < From)
936           {
937             if (end <= From)
938               return Left.Copy (mt, start, end);
939             left_copy = Left.Copy (mt, start, From);
940           }
941         if (end > To)
942           {
943             if (start >= To)
944               return Right.Copy (mt, start, end);
945             right_copy = Right.Copy (mt, To, end);
946           }
947
948         copy = new MInterval (Key, null, end - start, Stack);
949         copy.mtext = mt;
950         if (isSensitive && (From < start || end < To))
951           copy.Stack.Clear ();
952         if (left_copy != null)
953           {
954             copy.Left = left_copy;
955             left_copy.Parent = copy;
956           }
957         if (right_copy != null)
958           {
959             copy.Right = right_copy;
960             right_copy.Parent = copy;
961           }
962         return copy;
963       }
964
965       public MInterval Copy (MText mt, int start, int end,
966                              bool first, bool last)
967       {
968         MInterval copy = Copy (mt, start, end);
969         MInterval head = find_head (start);
970         MInterval tail = find_tail (end);
971
972         if (! head.Stack.IsEmpty
973             && (isSensitive && head.From < start
974                 || isFrontSensitive && ! first))
975           {
976             head = copy.find_head (0);
977             head.Stack.Clear ();
978           }
979         if (! tail.Stack.IsEmpty
980             && (isSensitive && end < head.To
981                 || isRearSensitive && ! last))
982           {
983             tail = copy.find_tail (copy.Length);
984             tail.Stack.Clear ();
985           }
986         M17n.DebugPrint ("Copied: {0}\n", copy);
987         return copy;
988       }
989
990       //  this-.   ==>   this-.
991       //     right          newright-.
992       //                            right
993       private MInterval divide_right (int pos)
994       {
995         MInterval interval = new MInterval (Key, mtext, To - pos, Stack);
996
997         M17n.DebugPrint ("divide-right({0}) at {1}\n", pos, this);
998         To = pos;
999         if (Right != null)
1000           {
1001             interval.Right = Right;
1002             Right.Parent = interval;
1003             interval.Length += Right.Length;
1004           }
1005         interval.Parent = this;
1006         Right = interval;
1007         return interval;
1008       }
1009
1010       //    .-this   ==>       .-this
1011       //  left             .-newleft
1012       //                 left
1013       private MInterval divide_left (int pos)
1014       {
1015         MInterval interval = new MInterval (Key, mtext, pos - From, Stack);
1016
1017         M17n.DebugPrint ("divide-left({0}) at {1}\n", pos, this);
1018         From = pos;
1019         if (Left != null)
1020           {
1021             interval.Left = Left;
1022             Left.Parent = interval;
1023             interval.Length += Left.Length;
1024           }
1025         interval.Parent = this;
1026         Left = interval;
1027         return interval;
1028       }
1029
1030       private void set_mtext (MText mt)
1031       {
1032         mtext = mt;
1033         if (Left != null)
1034           Left.set_mtext (mt);
1035         if (Right != null)
1036           Right.set_mtext (mt);
1037       }
1038
1039       private void enlarge (int len)
1040       {
1041         Length += len;
1042         To += len;
1043         for (MInterval prev = this, i = this.Parent; i != null;
1044              prev = i, i = i.Parent)
1045           {
1046             i.Length += len;
1047             if (prev == i.Left)
1048               {
1049                 i.From += len;
1050                 i.To += len;;
1051               }
1052           }
1053       }
1054
1055       private int graft_forward (MInterval interval, int start, int end)
1056       {
1057         int len;
1058
1059         if (! Stack.IsEmpty && isRearSticky)
1060           len = end - start;
1061         else if (interval == null)
1062           len = Stack.IsEmpty ? end - start : 0;
1063         else
1064           {
1065             MInterval i = interval.find_head (start);
1066
1067             len = 0;
1068             if (Stack.IsEmpty
1069                 && (isFrontSensitive || (isSensitive && i.From < start)))
1070               {
1071                 M17n.DebugPrint (" forward grafting {0}", i);
1072                 if (i.To < end)
1073                   len = i.To - start;
1074                 else
1075                   len = end - start;
1076                 i = i.Next;
1077               }
1078             while (i != null && i.From < end && mergeable (i))
1079               {
1080                 M17n.DebugPrint (" forward grafting {0}", i);
1081                 len += i.To - i.From;
1082                 if (i.From < start)
1083                   len -= start - i.From;
1084                 if (i.To >= end)
1085                   {
1086                     len -= i.To - end;
1087                     break;
1088                   }
1089                 i = i.Next;
1090               }
1091           }
1092
1093         M17n.DebugPrint (" grafted {0} in {1}\n", len, this);
1094         if (len > 0)
1095           enlarge (len);
1096         return len;
1097       }
1098
1099       private int graft_backward (MInterval interval, int start, int end)
1100       {
1101         int len;
1102
1103         if (! Stack.IsEmpty && isFrontSticky)
1104           len = end - start;
1105         else if (interval == null)
1106           len = Stack.IsEmpty ? end - start : 0;
1107         else
1108           {
1109             MInterval i = interval.find_tail (end);
1110
1111             len = 0;
1112             if (Stack.IsEmpty
1113                 && (isRearSensitive || (isSensitive && end < i.To)))
1114               {
1115                 M17n.DebugPrint (" backward grafting {0}", i);
1116                 if (i.From <= start)
1117                   len = end - start;
1118                 else
1119                   len = end - i.From;
1120                 i = i.Prev;
1121               }
1122             while (i != null && i.To <= start && mergeable (i))
1123               {
1124                 M17n.DebugPrint (" backward grafting {0}", i);
1125                 len += i.To - i.From;
1126                 if (end < i.To)
1127                   len -= i.To - end;
1128                 if (i.From <= start)
1129                   {
1130                     len -= start - i.From;
1131                     break;
1132                   }
1133                 i = i.Prev;
1134               }
1135           }
1136
1137         M17n.DebugPrint (" grafted {0} in {1}\n", len, this);
1138         if (len > 0)
1139           enlarge (len);
1140         return len;
1141       }
1142
1143       public void Insert (int pos, MInterval interval, int start, int end)
1144       {
1145         update_from_to ();
1146
1147         M17n.DebugPrint ("insert({0} to {1}) at {2} in {3}",
1148                          start, end, pos, this);
1149
1150         if (pos < From)
1151           Left.Insert (pos, interval, start, end);
1152         else if (pos == From)
1153           {
1154             MInterval prev = Left != null ? Prev : null;
1155
1156             if (isFrontSensitive)
1157               Stack.Clear ();
1158             if (prev != null && isRearSensitive)
1159               prev.Stack.Clear ();
1160             if (prev != null && isRearSticky && ! prev.Stack.IsEmpty)
1161               {
1162                 prev.enlarge (end - start);
1163                 M17n.DebugPrint (" done\n");
1164                 return;
1165               }
1166             if (isFrontSticky && ! Stack.IsEmpty)
1167               {
1168                 enlarge (end - start);
1169                 M17n.DebugPrint (" done\n");
1170                 return;
1171               }
1172             bool front_grafted = false, rear_grafted = false;
1173             int grafted;
1174             if (prev != null
1175                 && (grafted = prev.graft_forward (interval, start, end)) > 0)
1176               {
1177                 start += grafted;
1178                 if (start == end)
1179                   {
1180                     M17n.DebugPrint (" done\n");
1181                     return;
1182                   }
1183                 front_grafted = true;
1184               }
1185             if ((grafted = graft_backward (interval, start, end)) > 0)
1186               {
1187                 end -= grafted;
1188                 if (start == end)
1189                   {
1190                     M17n.DebugPrint (" done\n");
1191                     return;
1192                   }
1193                 rear_grafted = true;
1194               }
1195
1196             if (interval != null)
1197               interval = interval.Copy (mtext, start, end,
1198                                         (front_grafted
1199                                          || (prev == null && start == 0)),
1200                                         rear_grafted);
1201             else
1202               interval = new MInterval (Key, mtext, end - start, null);
1203
1204             MInterval i;
1205             if (Left != null)
1206               {
1207                 //    .-this-.   ==>          .-this-.
1208                 // left-.                 .-left-.
1209                 //    child                     child-.
1210                 //                                 interval
1211                 i = Left.RightMost;
1212                 i.Right = interval;
1213               }
1214             else
1215               {
1216                 Left = interval;
1217                 i = this;
1218               }
1219             interval.Parent = i;
1220             for (; i != null; i = i.Parent)
1221               i.Length += interval.Length;
1222           }
1223         else if (pos < To)
1224           {
1225             if (! Stack.IsEmpty)
1226               {
1227                 if (isSensitive)
1228                   Stack.Clear ();
1229                 else if (isFrontSticky || isRearSticky)
1230                   {
1231                     enlarge (end - start);
1232                     return;
1233                   }
1234               }
1235             bool front_grafted = false, rear_grafted = false;
1236             int grafted;
1237             if ((grafted = graft_forward (interval, start, end)) > 0)
1238               {
1239                 start += grafted;
1240                 if (start == end)
1241                   {
1242                     M17n.DebugPrint (" done\n");
1243                     return;
1244                   }
1245                 front_grafted = true;
1246                 pos += grafted;
1247               }
1248             if ((grafted = graft_backward (interval, start, end)) > 0)
1249               {
1250                 end -= grafted;
1251                 if (start == end)
1252                   {
1253                     M17n.DebugPrint (" done\n");
1254                     return;
1255                   }
1256                 rear_grafted = true;
1257               }
1258             if (interval != null)
1259               interval = interval.Copy (mtext, start, end,
1260                                         front_grafted, rear_grafted);
1261             else
1262               interval = new MInterval (Key, mtext, end - start, null);
1263
1264             divide_right (pos);
1265             Right.Left = interval;
1266             interval.Parent = Right;
1267             for (MInterval i = Right; i != null; i = i.Parent)
1268               i.Length += interval.Length;
1269           }
1270         else if (pos == To)
1271           {
1272             MInterval next = Right != null ? Next : null;
1273
1274             if (isRearSensitive)
1275               Stack.Clear ();
1276             if (next != null && isFrontSensitive)
1277               next.Stack.Clear ();
1278             if (isRearSticky && ! Stack.IsEmpty)
1279               {
1280                 enlarge (end - start);
1281                 M17n.DebugPrint (" done by enlarging this\n");
1282                 return;
1283               }
1284             if (next != null && isFrontSticky && ! next.Stack.IsEmpty)
1285               {
1286                 M17n.DebugPrint (" next is {0}\n", next);
1287                 next.enlarge (end - start);
1288                 M17n.DebugPrint (" done by enlarging next\n");
1289                 return;
1290               }
1291             bool front_grafted = false, rear_grafted = false;
1292             int grafted;
1293             if (next != null
1294                 && (grafted = next.graft_backward (interval, start, end)) > 0)
1295               {
1296                 end -= grafted;
1297                 if (start == end)
1298                   {
1299                     M17n.DebugPrint (" done\n");
1300                     return;
1301                   }
1302                 rear_grafted = true;
1303               }
1304             if ((grafted = graft_forward (interval, start, end)) > 0)
1305               {
1306                 start += grafted;
1307                 if (start == end)
1308                   {
1309                     M17n.DebugPrint (" done\n");
1310                     return;
1311                   }
1312                 front_grafted = true;
1313               }
1314             if (interval != null)
1315               interval = interval.Copy (mtext, start, end,
1316                                         front_grafted,
1317                                         (rear_grafted
1318                                          || (next == null && end < interval.mtext.Length)));
1319             else
1320               interval = new MInterval (Key, mtext, end - start, null);
1321
1322             MInterval i;
1323             if (Right != null)
1324               {
1325                 //    .-this-.   ==>          .-this-.
1326                 //         .-right                 .-right
1327                 //     child                  .-child
1328                 //                        interval
1329
1330                 i = Right.LeftMost;
1331                 i.Left = interval;
1332               }
1333             else
1334               {
1335                 Right = interval;
1336                 i = this;
1337               }
1338             interval.Parent = i;
1339             for (; i != null; i = i.Parent)
1340               i.Length += interval.Length;
1341           }
1342         else                    // (pos > To)
1343           Right.Insert (pos, interval, start, end);
1344         M17n.DebugPrint (" done\n");
1345       }
1346
1347       private void vacate_node (MInterval interval)
1348       {
1349         vacate_node (interval, null);
1350       }
1351
1352       private void vacate_node (MInterval interval, MInterval stop)
1353       {
1354         if (interval != null)
1355           M17n.DebugPrint ("vacate #{0} to #{1}\n", ID, interval.ID);
1356         else
1357           M17n.DebugPrint ("vacate #{0} to null\n", ID);
1358         if (interval != null)
1359           interval.Parent = Parent;
1360         if (Parent == null)
1361           {
1362             if (mtext != null)
1363               mtext.intervals.Put (Key, interval);
1364           }
1365         else
1366           {
1367             if (this == Parent.Right)
1368               Parent.Right = interval;
1369             else
1370               Parent.Left = interval;
1371
1372             int diff = Length;
1373             if (interval != null)
1374               diff -= interval.Length;
1375             for (MInterval i = Parent; i != stop; i = i.Parent)
1376               i.Length -= diff;
1377           }
1378       }
1379
1380       public void Delete (int start, int end)
1381       {
1382         update_from_to ();
1383         M17n.DebugPrint ("delete({0} {1}) from {2}\n", start, end, this);
1384
1385         bool front_checked = false;
1386         bool rear_checked = false;
1387
1388         if (start < From)
1389           {
1390             if (end <= From)
1391               {
1392                 if (end == From && isFrontSensitive)
1393                   Stack.Clear ();
1394                 Left.Delete (start, end);
1395                 return;
1396               }
1397             if (isSensitive)
1398               Stack.Clear ();
1399             Left.Delete (start, From);
1400             To -= From - start;
1401             end -= From - start;
1402             From = start;
1403             front_checked = true;
1404           }
1405         if (end > To)
1406           {
1407             if (start >= To)
1408               {
1409                 if (start == To && isRearSensitive)
1410                   Stack.Clear ();
1411                 Right.Delete (start, end);
1412                 return;
1413               }
1414             if (isSensitive)
1415               Stack.Clear ();
1416             Right.Delete (To, end);
1417             end = To;
1418             rear_checked = true;
1419           }
1420         if (start == From
1421             && ! front_checked
1422             && start > 0
1423             && isRearSensitive)
1424           Prev.Stack.Clear ();
1425         if (end == To
1426             && ! rear_checked
1427             && Next != null
1428             && isFrontSensitive)
1429           Next.Stack.Clear ();
1430         if (start == From && end == To)
1431           {
1432             if (Right == null)
1433               {
1434                 vacate_node (Left);
1435               }
1436             else
1437               {
1438                 if (Left != null)
1439                   {
1440                     MInterval i;
1441                 
1442                     for (i = Right; i.Left != null; i = i.Left)
1443                       i.Length += Left.Length;
1444                     i.Length += Left.Length;
1445                     i.Left = Left;
1446                     Left.Parent = i;
1447                   }
1448                 vacate_node (Right);
1449               }
1450           }
1451         else
1452           {
1453             int len = end - start;
1454
1455             if (isSensitive)
1456               Stack.Clear ();
1457             for (MInterval i = this; i != null; i = i.Parent)
1458               i.Length -= len;
1459           }
1460       }
1461
1462       public void Push (int start, int end, MProperty prop)
1463       {
1464         update_from_to ();
1465         M17n.DebugPrint ("push({0} {1}) at {2}\n", start, end, this);
1466         if (start < From)
1467           {
1468             if (end <= From)
1469               {
1470                 Left.Push (start, end, prop);
1471                 return;
1472               }
1473             Left.Push (start, From, prop);
1474             start = From;
1475           }
1476         if (end > To)
1477           {
1478             if (start >= To)
1479               {
1480                 Right.Push (start, end, prop);
1481                 return;
1482               }
1483             Right.Push (To, end, prop);
1484             end = To;
1485           }
1486
1487         if (! Stack.IsEmpty && isSensitive)
1488           Stack.Clear ();
1489         if (start > From)
1490           divide_left (start);
1491         if (end < To)
1492           divide_right (end);
1493         Stack.Push (prop.key, prop);
1494       }
1495
1496       /// Combine intervals between HEAD and TAIL (both inclusive) to
1497       /// the common parent of HEAD and TAIL.  Callers should assure
1498       /// that the intervals are mergeable in advance.
1499       private static void combine (MInterval head, MInterval tail)
1500       {
1501         M17n.DebugPrint ("combining {0} through {1}", head, tail);
1502
1503         head.update_from_to ();
1504         tail.update_from_to ();
1505         int from = head.From;
1506         int to = tail.To;
1507
1508         // The nearest common parent of HEAD and TAIL.
1509         MInterval root;
1510         for (root = head; root.To + root.RightLength < to;
1511              root = root.Parent);
1512         
1513         M17n.DebugPrint (" with common root {0}\n", root);
1514
1515         if (from < root.From)
1516           {
1517             MInterval prev = root.Prev;
1518
1519             while (true)
1520               {
1521                 M17n.DebugPrint ("merging {0}\n", prev);
1522                 prev.vacate_node (prev.Left, root);
1523                 if (prev == head)
1524                   break;
1525                 if (prev.Left != null)
1526                   prev = prev.Left.RightMost;
1527                 else
1528                   prev = prev.Parent;
1529               }
1530             root.update_from_to ();
1531           }
1532         if (root.To < to)
1533           {
1534             MInterval next = root.Next;
1535
1536             while (true)
1537               {
1538                 M17n.DebugPrint ("merging {0}\n", next);
1539                 next.vacate_node (next.Right, root);
1540                 if (next == tail)
1541                   break;
1542                 if (next.Right != null)
1543                   next = next.Right.LeftMost;
1544                 else
1545                   next = next.Parent;
1546               }
1547             root.update_from_to ();
1548           }
1549       }
1550
1551       public void MergeAfterChange (int start, int end)
1552       {
1553         update_from_to ();
1554
1555         MInterval head = find_head (start), i = head;
1556         MInterval tail = start < end ? find_tail (end) : head;
1557
1558         if (tail.To < Length)
1559           tail = tail.Next;
1560
1561         if (start == head.From && start > 0)
1562           {
1563             MInterval prev = head.Prev;
1564             if (head.mergeable (prev))
1565               head = prev;
1566           }
1567         M17n.DebugPrint ("merge between {0} and {1}\n", head, tail);
1568         while (i != tail)
1569           {
1570             MInterval next = i.Next;
1571
1572             if (! i.mergeable (next))
1573               {
1574                 if (head != i)
1575                   combine (head, i);
1576                 head = next;
1577               }
1578             i = next;
1579           }
1580         if (head != i)
1581           combine (head, i);
1582       }
1583
1584       public void Pop (int start, int end)
1585       {
1586         update_from_to ();
1587         M17n.DebugPrint ("pop({0} {1}) at {2}\n", start, end, this);
1588         if (start < From)
1589           {
1590             if (end <= From)
1591               {
1592                 Left.Pop (start, end);
1593                 return;
1594               }
1595             Left.Pop (start, From);
1596             start = From;
1597           }
1598         if (end > To)
1599           {
1600             if (start >= To)
1601               {
1602                 Right.Pop (start, end);
1603                 return;
1604               }
1605             Right.Pop (To, end);
1606             end = To;
1607           }
1608
1609         if (! Stack.IsEmpty)
1610           {
1611             if (isSensitive)
1612               Stack.Clear ();
1613             else
1614               {
1615                 if (start > From)
1616                   divide_left (start);
1617                 if (end < To)
1618                   divide_right (end);
1619                 Stack.Pop ();
1620               }
1621           }
1622       }
1623
1624       public void PopSensitive (int start, int end)
1625       {
1626         update_from_to ();
1627         MInterval head = find_head (start);
1628         MInterval tail = find_tail (end);
1629         Pop (head.From, tail.To);
1630       }
1631
1632       public override string ToString ()
1633       {
1634         string str = String.Format ("#{0}({1} {2} {3} [", ID, Length, From, To);
1635         bool first = true;
1636         foreach (MPlist p in Stack)
1637           {
1638             if (first)
1639               {
1640                 str += ((MProperty) p.Val).Val;
1641                 first = false;
1642               }
1643             else
1644               str += " " + ((MProperty) p.Val).Val;
1645           }
1646         return (str + "])");
1647       }
1648
1649       private void DumpOne (bool with_prop, bool newline, bool force)
1650       {
1651         if (force || M17n.debug)
1652           {
1653             Console.Write ("#{0}({1} {2} {3}", ID, Length, From, To);
1654             if (with_prop && ! Stack.IsEmpty)
1655               {
1656                 string prepend = " [";
1657                 foreach (MPlist p in Stack)
1658                   {
1659                     Console.Write (prepend + ((MProperty) p.Val).Val);
1660                     prepend = " ";
1661                   }
1662                 Console.Write ("]");
1663               }
1664             Console.Write (")");
1665             if (newline)
1666               Console.WriteLine ();
1667             if (Length <= 0)
1668               throw new Exception ("Invalid interval length");
1669           }
1670       }
1671
1672       public void Dump () { Dump (false); }
1673
1674       public void Dump (bool force)
1675       {
1676         if (force || M17n.debug)
1677           {
1678             update_from_to ();
1679
1680             if (Left != null)
1681               Left.Dump (force);
1682             if (From > 0)
1683               Console.Write (" ");
1684             DumpOne (true, false, force);
1685             if (Right != null)
1686               Right.Dump (force);
1687           }
1688       }
1689
1690       private int Depth {
1691         get { return (Parent == null ? 0 : Parent.Depth + 1); }
1692       }
1693
1694       public void DumpNested (bool force)
1695       {
1696         DumpNested ("  " + Key.ToString () + ":", force);
1697       }
1698
1699       public void DumpNested (string indent, bool force)
1700       {
1701         if (force || M17n.debug)
1702           {
1703             int indent_type = (Parent == null ? 1
1704                                : Parent.Left == this ? 0 : 2);
1705
1706             update_from_to ();
1707             if (Left != null)
1708               {
1709                 if (indent_type <= 1)
1710                   Left.DumpNested (indent + "  ", force);
1711                 else
1712                   Left.DumpNested (indent + "| ", force);
1713               }
1714             Console.Write (indent);
1715             if (indent_type == 0)
1716               Console.Write (".-");
1717             else if (indent_type == 2)
1718               Console.Write ("`-");
1719             DumpOne (true, true, true);
1720             if (Right != null)
1721               {
1722                 if (indent_type >= 1)
1723                   Right.DumpNested (indent + "  ", force);
1724                 else
1725                   Right.DumpNested (indent + "| ", force);
1726               }
1727           }
1728       }
1729     }
1730
1731     private class MTextEnum : IEnumerator
1732     {
1733       private MText mt;
1734       private int pos = -1;
1735
1736       public MTextEnum (MText mt)
1737         {
1738           this.mt = mt;
1739         }
1740
1741       public bool MoveNext ()
1742       {
1743         pos++;
1744         return (pos < mt.nchars);
1745       }
1746
1747       public void Reset ()
1748       {
1749         pos = -1;
1750       }
1751
1752       public object Current
1753       {
1754         get {
1755           //if (pos < 0 || pos >= mt.nchars)
1756           //throw new InvalidOperationException ();
1757           return mt[pos];
1758         }
1759       }
1760     }
1761   }
1762 }