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