*** empty log message ***
[m17n/m17n-lib-cs.git] / MText.cs
index 6b69daf..6f529a8 100644 (file)
--- a/MText.cs
+++ b/MText.cs
@@ -19,54 +19,51 @@ namespace M17N.Core
     }
 #endif
 
-  public class MTextProperty
+  public class MProperty
   {
+    [FlagsAttribute]
+    public enum Flags
+    {
+      None =           0,
+      /// A text inserted before a character that has this property
+      /// inherits this property.  If the text already has properties
+      /// of the same key, they are deleted.  See the documentation of
+      /// Sensitive for exception.
+      FrontSticky =    1,
+      /// A text inserted after a character that has this property
+      /// inherits this property.  If the text already has properties
+      /// of the same key, they are deleted.  See the documentation of
+      /// Sensitive for exception.
+      RearSticky =     2,
+      /// This property is deleted from a span of text if the span is
+      /// modified (i.e. a character is changed, a text is inserted,
+      /// some part is deleted).  This propery is also deleted if a
+      /// property of the same key is added, which means that this
+      /// property is not stackable.  If this property is also
+      /// FrontSticky (or RearSticky), text insertion just before (or
+      /// after) the span also deletes this property from the span of
+      /// text.
+      Sensitive =      4,
+    };
+
     internal MSymbol key;
     internal object val;
 
-    [FlagsAttribute]
-    internal enum Flag : byte
-      {
-       None =          0,
-       FrontSticky =   1,
-       RearSticky =    2,
-       Sensitive =     4
-      };
-    internal Flag flags;
-
     public MSymbol Key { get { return key; } }
     public object Val { get { return val; } }
-    public bool FrontSticky
-    {
-      get { return (flags & Flag.FrontSticky) != Flag.None; }
-    }
-    public bool RearSticky
-    {
-      get { return (flags & Flag.RearSticky) != Flag.None; }
-    }
-    public bool Sensitive
-    {
-      get { return (flags & Flag.Sensitive) != Flag.None; }
-    }
 
-    public MTextProperty (MSymbol key, object val)
+    public MProperty (MSymbol key, object val)
     {
+      if (key.flags == null)
+       key.flags = MProperty.Flags.None;
       this.key = key;
       this.val = val;
-      flags |= Flag.RearSticky;
     }
 
-    public MTextProperty (MSymbol key, object val,
-                         bool front_sticky, bool rear_sticky, bool sensitive)
+    public MProperty (string name, object val)
     {
-      this.key = key;
+      key = MSymbol.PropertyKey (name);
       this.val = val;
-      if (front_sticky)
-       flags |= Flag.FrontSticky;
-      if (rear_sticky)
-       flags |= Flag.RearSticky;
-      if (sensitive)
-       flags |= Flag.Sensitive;
     }
 
     public override string ToString ()
@@ -137,6 +134,13 @@ namespace M17N.Core
        intervals = new MPlist ();
       }
 
+    public static MText operator+ (object obj, MText mt)
+    {
+      if (obj is string)
+       return new MText ((string) obj) + mt;
+      throw new Exception ("Unknown object type: " + obj.GetType());
+    }
+
     public static MText operator+ (MText mt1, MText mt2)
     {
       MText mt = new MText ();
@@ -147,6 +151,15 @@ namespace M17N.Core
       return mt;
     }
 
+    public static MText operator+ (string str, MText mt)
+    {
+      MText mtnew = new MText (str);
+
+      mtnew.sb.Append (mt.sb);
+      mtnew.nchars += mt.nchars;
+      return mtnew;
+    }
+
     // Public properties
     public bool ReadOnly { get { return read_only; } }
     public int Length { get { return nchars; } }
@@ -252,27 +265,42 @@ namespace M17N.Core
     {
       check_pos (pos, true);
 
+      if (M17n.debug)
+       {
+         Console.Write ("inserting {0} to {1} of ", from, to);
+         mt2.DumpPropNested ();
+       }
+      if (from == to)
+       return;
+      foreach (MPlist plist in intervals)
+       {
+         MInterval root = (MInterval) plist.Val;
+         MPlist p = mt2.intervals.Find (plist.Key);
+         MInterval i = p == null ? null : (MInterval) p.Val;
+
+         root.Insert (pos, i, from, to);
+       }
+      foreach (MPlist plist in mt2.intervals)
+       if (intervals.Find (plist.Key) == null)
+         {
+           MInterval root;
+
+           if (nchars == 0)
+             root = ((MInterval) plist.Val).Copy (this, from, to);
+           else
+             {
+               root = new MInterval (plist.Key, this);
+               root.Insert (pos, (MInterval) plist.Val, from, to);
+             }
+           intervals.Push (plist.Key, root);
+         }
+
       int pos_idx = pos_to_idx (this, pos);
       int from_idx = pos_to_idx (mt2, from);
       int to_idx = pos_to_idx (mt2, to);
 
       sb.Insert (pos_idx, mt2.sb.ToString (from_idx, to_idx - from_idx));
       nchars += to - from;
-
-      foreach (MPlist plist in mt2.intervals)
-       if (intervals.Find (plist.Key) == null)
-         intervals.Push (plist.Key, new MInterval (plist.Key, this));
-      foreach (MPlist plist in intervals)
-       {
-         MPlist p = mt2.intervals.Find (plist.Key);
-         MInterval interval;
-
-         if (p == null)
-           interval = new MInterval (plist.Key, this, to - from);
-         else
-           interval = ((MInterval) p.Val).Copy (from, to);
-         ((MInterval) plist.Val).Insert (pos, interval);
-       }
     }
 
     private void insert (int pos, int c)
@@ -295,8 +323,7 @@ namespace M17N.Core
        }
       nchars++;
       foreach (MPlist plist in intervals)
-       ((MInterval) plist.Val).Insert (pos,
-                                       new MInterval (plist.Key, this, 1));
+       ((MInterval) plist.Val).Insert (pos, null, 0, 1);
     }
 
     public int this[int i]
@@ -333,7 +360,20 @@ namespace M17N.Core
       MText mt = new MText (sb.ToString ());
 
       foreach (MPlist p in intervals)
-       mt.intervals.Add (p.Key, ((MInterval) p.Val).Copy (0, Length));
+       mt.intervals.Add (p.Key, ((MInterval) p.Val).Copy (mt, 0, Length));
+      return mt;
+    }
+
+    public MText Dup (int from, int to)
+    {
+      if (check_range (from, to, true))
+       return new MText ();
+      int from_idx = pos_to_idx (this, from);
+      int len = pos_to_idx (this, to) - from_idx;
+      MText mt = new MText (sb.ToString ().Substring (from_idx, len));
+
+      foreach (MPlist p in intervals)
+       mt.intervals.Add (p.Key, ((MInterval) p.Val).Copy (mt, from, to));
       return mt;
     }
 
@@ -371,9 +411,16 @@ namespace M17N.Core
 
       if (nchars > 0)
        foreach (MPlist plist in intervals)
-         ((MInterval) plist.Val).Delete (from, to);
+         {
+           MInterval root = (MInterval) plist.Val;
+           root.Delete (from, to);
+           if (from > 0 && from < nchars)
+             ((MInterval) plist.Val).MergeAfterChange (from, from);
+         }
       else
-       intervals = new MPlist ();
+       intervals.Clear ();
+      if (M17n.debug)
+       DumpPropNested ();
       return this;
     }
 
@@ -385,11 +432,11 @@ namespace M17N.Core
       if (i == null)
        return null;
 
-      MTextProperty prop = i.Get (pos);
+      MProperty prop = i.Get (pos);
       return (prop != null ? prop.Val : null);
     }
 
-    public object GetProp (int pos, MSymbol key, out MTextProperty prop)
+    public object GetProp (int pos, MSymbol key, out MProperty prop)
     {
       check_pos (pos, false);
 
@@ -400,24 +447,24 @@ namespace M17N.Core
       return (prop != null ? prop.Val : null);
     }
 
-    public object GetProp (int pos, MSymbol key, out MTextProperty[] array)
+    public object GetProp (int pos, MSymbol key, out MProperty[] array)
     {
       check_pos (pos, false);
 
       MInterval i = (MInterval) intervals.Get (key);
       if (i == null)
        return (array = null);
-      MTextProperty prop = i.Get (pos, out array);
+      MProperty prop = i.Get (pos, out array);
       return (prop != null ? prop.Val : null);
     }
 
     public void PushProp (int from, int to, MSymbol key, object val)
     {
       if (! check_range (from, to, true))
-       PushProp (from, to, new MTextProperty (key, val));
+       PushProp (from, to, new MProperty (key, val));
     }
 
-    public void PushProp (int from, int to, MTextProperty prop)
+    public void PushProp (int from, int to, MProperty prop)
     {
       if (from < 0)
        {
@@ -441,7 +488,11 @@ namespace M17N.Core
          else
            root = (MInterval) p.Val;
 
+         if (root.isSensitive)
+           root.PopSensitive (from, to);
          root.Push (from, to, prop);
+         root.MergeAfterChange (from, to);
+         root.Balance ();
        }
     }
 
@@ -466,9 +517,15 @@ namespace M17N.Core
          if (p != null)
            {
              MInterval root = (MInterval) p.Val;
-             root.Pop (from, to);
-             DumpPropNested ();
+             if (root.isSensitive)
+               root.PopSensitive (from, to);
+             else
+               root.Pop (from, to);
+             root = (MInterval) p.Val;
+             if (M17n.debug)
+               DumpPropNested ();
              root.MergeAfterChange (from, to);
+             root.Balance ();
            }
        }
     }
@@ -483,6 +540,7 @@ namespace M17N.Core
 
     public void DumpPropNested ()
     {
+      Console.WriteLine ("total length = {0}", Length);
       foreach (MPlist p in intervals)
        ((MInterval) p.Val).DumpNested (true);
     }
@@ -530,28 +588,32 @@ namespace M17N.Core
        ID = count++;
       }
 
-      public MTextProperty Get (int pos)
+      /// POS must be smaller than Length;
+      public MProperty Get (int pos)
       {
-       MInterval i = find (pos);
+       MInterval i = find_head (pos);
 
-       return (i.Stack.IsEmpty ? null : (MTextProperty) i.Stack.Val);
+       return (i.Stack.IsEmpty ? null : (MProperty) i.Stack.Val);
       }
 
-      public MTextProperty Get (int pos, out MTextProperty[] array)
+      /// POS must be smaller than Length;
+      public MProperty Get (int pos, out MProperty[] array)
       {
-       MInterval i = find (pos);
+       MInterval i = find_head (pos);
 
+       if (i.To == pos)
+         i = i.Next;
        if (i.Stack.IsEmpty)
          {
            array = null;
            return null;
          }
-       array = new MTextProperty[i.Stack.Count];
+       array = new MProperty[i.Stack.Count];
 
        int idx;
        MPlist p;
        for (idx = 0, p = i.Stack; ! p.IsEmpty; idx++, p = p.Next)
-         array[idx] = (MTextProperty) p.Val;
+         array[idx] = (MProperty) p.Val;
        return array[0];
       }
 
@@ -562,10 +624,28 @@ namespace M17N.Core
        Length = length;
        From = 0;
        To = Length;
-       Stack = stack.Clone ();
+       Stack = stack == null ? new MPlist () : stack.Clone ();
        ID = count++;
       }
 
+      private bool isRearSticky
+      {
+       get { return ((Key.flags & MProperty.Flags.RearSticky)
+                     != MProperty.Flags.None); }
+      }
+
+      private bool isFrontSticky
+      {
+       get { return ((Key.flags & MProperty.Flags.FrontSticky)
+                     != MProperty.Flags.None); }
+      }
+
+      public bool isSensitive
+      {
+       get { return ((Key.flags & MProperty.Flags.Sensitive)
+                     != MProperty.Flags.None); }
+      }
+
       private void update_from_to ()
       {
        if (Parent == null)
@@ -597,12 +677,22 @@ namespace M17N.Core
 
       private MInterval LeftMost
       {
-       get { return (Left == null ? this : Left.LeftMost); }
+       get {
+         update_from_to ();
+         if (Left == null)
+           return this;
+         return Left.LeftMost;
+       }
       }
 
       private MInterval RightMost
       {
-       get { return (Right == null ? this : Right.RightMost); }
+       get {
+         update_from_to ();
+         if (Right == null)
+           return this;
+         return Right.RightMost;
+       }
       }
 
       private MInterval Prev {
@@ -610,7 +700,11 @@ namespace M17N.Core
          MInterval i;
 
          if (Left != null)
-           for (i = Left; i.Right != null; i = i.Right);
+           {
+             for (i = Left; i.Right != null; i = i.Right)
+               i.update_from_to ();
+             i.update_from_to ();
+           }
          else
            {
              MInterval child = this;
@@ -626,7 +720,11 @@ namespace M17N.Core
          MInterval i;
 
          if (Right != null)
-           for (i = Right; i.Left != null; i = i.Left);
+           {
+             for (i = Right; i.Left != null; i = i.Left)
+               i.update_from_to ();
+             i.update_from_to ();
+           }
          else
            {
              MInterval child = this;
@@ -637,13 +735,23 @@ namespace M17N.Core
        }
       }
 
-      private MInterval find (int pos)
+      private MInterval find_head (int pos)
       {
        update_from_to ();
        if (pos < From)
-         return Left.find (pos);
+         return Left.find_head (pos);
        if (pos >= To)
-         return Right.find (pos);
+         return Right.find_head (pos);
+       return this;
+      }
+
+      private MInterval find_tail (int pos)
+      {
+       update_from_to ();
+       if (pos <= From)
+         return Left.find_tail (pos);
+       if (pos > To)
+         return Right.find_tail (pos);
        return this;
       }
 
@@ -664,29 +772,31 @@ namespace M17N.Core
       //          c1       c2    left     c1
       private MInterval promote_right ()
       {
-       int right_length = Right.Length;
-       MInterval c1;
+       MInterval c1 = Right.Left;
 
+       // Update Parent.
        if (Parent == null)
          mtext.intervals.Put (Key, Right);
        else if (Parent.Left == this)
          Parent.Left = Right;
        else
          Parent.Right = Right;
+
+       // Update Right.
        Right.Parent = Parent;
-       c1 = Right.Left;
        Right.Left = this;
+       Right.Length += LeftLength + (To - From);
 
+       // Update this.
        Parent = Right;
        Right = c1;
-       Parent.Length += Length;
-       Length -= right_length;
+       Length = LeftLength + (To - From) + RightLength;
+
+       // Update C1 if necessary.
        if (c1 != null)
-         {
-           c1.Parent = this;
-           Parent.Length -= c1.Length;
-           Length += c1.Length;
-         }
+         c1.Parent = this;
+
+       Parent.update_from_to ();
        return Parent;
       }
 
@@ -696,36 +806,39 @@ namespace M17N.Core
       // c1      c2                        c2     right
       private MInterval promote_left ()
       {
-       int left_length = Left.Length;
-       MInterval c1;
+       MInterval c2 = Left.Right;
 
+       // Update Parent.
        if (Parent == null)
          mtext.intervals.Put (Key, Left);
        else if (Parent.Left == this)
          Parent.Left = Left;
        else
          Parent.Right = Left;
+
+       // Update Left.
        Left.Parent = Parent;
-       c1 = Left.Left;
        Left.Right = this;
+       Left.Length += (To - From) + RightLength;
 
+       // Update this.
        Parent = Left;
-       Left = c1;
-       Parent.Length += Length;
-       Length -= left_length;
-       if (c1 != null)
-         {
-           c1.Parent = this;
-           Parent.Length -= c1.Length;
-           Length += c1.Length;
-         }
+       Left = c2;
+       Length = LeftLength + (To - From) + RightLength;
+
+       // Update C2 if necessary.
+       if (c2 != null)
+         c2.Parent = this;
+
+       Parent.update_from_to ();
        return Parent;
       }
 
-      private MInterval balance ()
+      public MInterval Balance ()
       {
        MInterval i = this;
 
+       update_from_to ();
        while (true)
          {
            //       .-this-.
@@ -740,8 +853,10 @@ namespace M17N.Core
                            + i.Left.RightLength - i.Left.LeftLength);
                if (Math.Abs (new_diff) >= diff)
                  break;
+               M17n.DebugPrint ("balancing #{0} by promoting left...", i.ID);
                i = i.promote_left ();
-               i.Right.balance ();
+               M17n.DebugPrint ("done\n");
+               i.Right.Balance ();
              }
            else if (diff < 0)
              {
@@ -749,14 +864,17 @@ namespace M17N.Core
                            + i.Right.LeftLength - i.Right.RightLength);
                if (Math.Abs (new_diff) >= diff)
                  break;
+               M17n.DebugPrint ("balancing #{0} by promoting right\n", i.ID);
                i = i.promote_right ();
-               i.Left.balance ();
+               i.Left.Balance ();
              }
+           else
+             break;
          }
        return i;
       }
 
-      public MInterval Copy (int start, int end)
+      public MInterval Copy (MText mt, int start, int end)
       {
        MInterval copy, left_copy = null, right_copy = null;
 
@@ -765,18 +883,20 @@ namespace M17N.Core
        if (start < From)
          {
            if (end <= From)
-             return Left.Copy (start, end);
-           left_copy = Left.Copy (start, From);
+             return Left.Copy (mt, start, end);
+           left_copy = Left.Copy (mt, start, From);
          }
        if (end > To)
          {
            if (start >= To)
-             return Right.Copy (start, end);
-           right_copy = Right.Copy (To, end);
+             return Right.Copy (mt, start, end);
+           right_copy = Right.Copy (mt, To, end);
          }
 
        copy = new MInterval (Key, null, end - start, Stack);
-       remove_properties (MTextProperty.Flag.Sensitive);
+       copy.mtext = mt;
+       if (isSensitive && (From < start || end < To))
+         copy.Stack.Clear ();
        if (left_copy != null)
          {
            copy.Left = left_copy;
@@ -797,7 +917,7 @@ namespace M17N.Core
       {
        MInterval interval = new MInterval (Key, mtext, To - pos, Stack);
 
-       M17N.DebugPrint ("divide-right({0}) at ", pos); DumpOne (false, true);
+       M17n.DebugPrint ("divide-right({0}) at ", pos); DumpOne (false, true);
        To = pos;
        if (Right != null)
          {
@@ -817,7 +937,7 @@ namespace M17N.Core
       {
        MInterval interval = new MInterval (Key, mtext, pos - From, Stack);
 
-       M17N.DebugPrint ("divide-left({0}) at ", pos); DumpOne (false, true);
+       M17n.DebugPrint ("divide-left({0}) at ", pos); DumpOne (false, true);
        From = pos;
        if (Left != null)
          {
@@ -830,274 +950,224 @@ namespace M17N.Core
        return interval;
       }
 
-      private void remove_properties (MTextProperty.Flag flags)
-      {
-       for (MPlist p = Stack; ! p.IsEmpty;)
-         {
-           MTextProperty prop = (MTextProperty) p.Val;
-
-           if ((prop.flags & flags) == flags)
-             p.Pop ();
-           else
-             p = p.Next;
-         }
-      }
-
-      private void inherit_front_properties (MPlist plist)
+      private void set_mtext (MText mt)
       {
-       for (MInterval i = LeftMost; i != null; i = i.Next)
-         {
-           if (! Stack.IsEmpty)
-             break;
-           for (MPlist p = plist; ! p.IsEmpty; p = p.Next)
-             {
-               MTextProperty prop = (MTextProperty) p.Val;
-
-               if ((prop.flags & MTextProperty.Flag.RearSticky)
-                   == MTextProperty.Flag.RearSticky)
-                 i.Stack.Add (prop.key, prop);
-             }
-         }
+       mtext = mt;
+       if (Left != null)
+         Left.set_mtext (mt);
+       if (Right != null)
+         Right.set_mtext (mt);
       }
 
-      private void inherit_rear_properties (MPlist plist)
+      private void enlarge (int len)
       {
-       for (MInterval i = RightMost; i != null; i = i.Prev)
+       Length += len;
+       To += len;
+       for (MInterval prev = this, i = this.Parent; i != null;
+            prev = i, i = i.Parent)
          {
-           if (! Stack.IsEmpty)
-             break;
-           for (MPlist p = plist; ! p.IsEmpty; p = p.Next)
+           i.Length += len;
+           if (prev == i.Left)
              {
-               MTextProperty prop = (MTextProperty) p.Val;
-
-               if ((prop.flags & MTextProperty.Flag.FrontSticky)
-                   == MTextProperty.Flag.FrontSticky)
-                 i.Stack.Add (prop.key, prop);
+               i.From += len;
+               i.To += len;;
              }
          }
       }
 
-      private MInterval delete_node_forward ()
+      private int graft_forward (MInterval interval, int start, int end)
       {
-       if (Parent != null)
-         {
-           int len = Length - RightLength;
-
-           for (MInterval i = Parent; i != null; i = i.Parent)
-             i.Length -= len;
-           if (Parent.Left == this)
-             Parent.Left = Right;
-           else
-             Parent.Right = Right;
-         }
+       int len;
 
-       if (Right != null)
-         {
-           Right.Parent = Parent;
-           return Right.LeftMost;
-         }
-       return Parent;
-      }
-
-      private MInterval delete_node_backward ()
-      {
-       if (Parent != null)
+       if (! Stack.IsEmpty && isRearSticky)
+         len = end - start;
+       else if (interval == null)
+         len = Stack.IsEmpty ? end - start : 0;
+       else
          {
-           int len = Length - RightLength;
-
-           for (MInterval i = Parent; i != null; i = i.Parent)
-             i.Length -= len;
-           if (Parent.Left == this)
-             Parent.Left = Left;
-           else
-             Parent.Right = Left;
-         }
+           MInterval i = interval.find_head (start);
 
-       if (Left != null)
-         {
-           Left.Parent = Parent;
-           return Left.RightMost;
+           len = 0;
+           while (i != null && mergeable (i))
+             {
+               M17n.DebugPrint (" grafting "); i.DumpOne (false, false);
+               len += i.To - i.From;
+               if (i.From < start)
+                 len -= start - i.From;
+               if (i.To >= end)
+                 {
+                   len -= i.To - end;
+                   break;
+                 }
+               i = i.Next;
+             }
          }
-       return Parent;
-      }
 
-      private void set_mtext (MText mt)
-      {
-       mtext = mt;
-       if (Left != null)
-         Left.set_mtext (mt);
-       if (Right != null)
-         Right.set_mtext (mt);
+       M17n.DebugPrint (" grafted {0} in ", len); DumpOne (false, true);
+       if (len > 0)
+         enlarge (len);
+       return len;
       }
 
-      private MInterval graft (MInterval interval, bool forward, out int len)
+      private int graft_backward (MInterval interval, int start, int end)
       {
-       MInterval i;
+       int len;
 
-       len = 0;
-       if (forward)
-         {
-           i = interval.LeftMost;
-           while (i != null)
-             {
-               if (! mergeable (i))
-                 break;
-               len += i.Length - i.RightLength;
-               i = i.delete_node_forward ();
-             }
-         }
+       if (! Stack.IsEmpty && isFrontSticky)
+         len = end - start;
+       else if (interval == null)
+         len = Stack.IsEmpty ? end - start : 0;
        else
          {
-           i = interval.RightMost;
-           while (i != null)
-             {
-               if (! mergeable (i))
-                 break;
-               len += i.Length - i.LeftLength;
-               i = i.delete_node_backward ();
-             }
-         }
+           MInterval i = interval.find_tail (end);
 
-       Length += len;
-       To += len;
-       for (MInterval prev = this, ii = this.Parent; ii != null;
-            prev = ii, ii = ii.Parent)
-         {
-           ii.Length += len;
-           if (prev == ii.Left)
+           len = 0;
+           while (i != null && mergeable (i))
              {
-               ii.From += len;
-               ii.To += len;;
+               M17n.DebugPrint (" grafting "); i.DumpOne (false, false);
+               len += i.To - i.From;
+               if (end < i.To)
+                 len -= i.To - end;
+               if (i.From <= start)
+                 {
+                   len -= start - i.From;
+                   break;
+                 }
+               i = i.Prev;
              }
          }
-       if (i != null)
-         while (i.Parent != null) i = i.Parent;
-       return i;
+
+       M17n.DebugPrint (" grafted {0} in ", len); DumpOne (false, true);
+       if (len > 0)
+         enlarge (len);
+       return len;
       }
 
-      public void Insert (int pos, MInterval interval)
+      public void Insert (int pos, MInterval interval, int start, int end)
       {
        update_from_to ();
-       M17N.DebugPrint ("insert({0}) at {1} in ", interval.Length, pos);
-       DumpOne (false, true);
 
-       interval.set_mtext (mtext);
+       M17n.DebugPrint ("insert({0} to {1}) at {2} in ", start, end, pos);
+       DumpOne (false, false);
 
        if (pos < From)
-         Prev.Insert (pos, interval);
+         Left.Insert (pos, interval, start, end);
        else if (pos == From)
          {
-           MInterval prev = Prev;
-
-           if (prev != null)
+           if (Left != null)
              {
-               if (Left == null)
-                 {
-                   prev.Insert (pos, interval);
-                   return;
-                 }
-               prev.remove_properties
-                 (MTextProperty.Flag.Sensitive|MTextProperty.Flag.RearSticky);
-               interval.inherit_front_properties (prev.Stack);
+               MInterval prev = Prev;
+
+               if (prev.isSensitive && prev.isRearSticky)
+                 prev.Stack.Clear ();
+               start += prev.graft_forward (interval, start, end);
              }
-           remove_properties
-             (MTextProperty.Flag.Sensitive|MTextProperty.Flag.FrontSticky);
-           interval.inherit_rear_properties (Stack);
-
-           int len;
-           interval = graft (interval, false, out len);
-           if (interval != null && prev != null)
-             interval = prev.graft (interval, true, out len);
-           if (interval != null)
+           if (isSensitive && isFrontSticky)
+             Stack.Clear ();
+           if (start < end)
              {
-               MInterval i;
-
-               if (Left != null)
+               end -= graft_backward (interval, start, end);
+               if (start < end)
                  {
-                   //    .-this-.   ==>          .-this-.
-                   // left-.                 .-left-.
-                   //    child                     child-.
-                   //                                 interval
-                   i = Left.RightMost;
-                   i.Right = interval;
-                 }
-               else
-                 {
-                   Left = interval;
-                   i = this;
+                   if (interval != null)
+                     interval = interval.Copy (mtext, start, end);
+                   else
+                     interval = new MInterval (Key, mtext, end - start, null);
+
+                   MInterval i;
+                   if (Left != null)
+                     {
+                       //    .-this-.   ==>          .-this-.
+                       // left-.                 .-left-.
+                       //    child                     child-.
+                       //                                 interval
+                       i = Left.RightMost;
+                       i.Right = interval;
+                     }
+                   else
+                     {
+                       Left = interval;
+                       i = this;
+                     }
+                   interval.Parent = i;
+                   for (; i != null; i = i.Parent)
+                     i.Length += interval.Length;
                  }
-               interval.Parent = i;
-               for (; i != null; i = i.Parent)
-                 i.Length += interval.Length;
              }
          }
        else if (pos < To)
          {
-           remove_properties (MTextProperty.Flag.Sensitive);
+           if (isSensitive)
+             Stack.Clear ();
 
-           int len;
-           interval = graft (interval, true, out len);
+           int len = graft_forward (interval, start, end);
+           start += len;
            pos += len;
-           if (interval != null)
-             interval = graft (interval, false, out len);
-           if (interval != null)
+           if (start < end)
              {
-               divide_right (pos);
-               Right.Left = interval;
-               interval.Parent = Right;
-               for (MInterval i = Right; i != null; i = i.Parent)
-                 i.Length += interval.Length;
+               end -= graft_backward (interval, start, end);
+               if (start < end)
+                 {
+                   if (interval != null)
+                     interval = interval.Copy (mtext, start, end);
+                   else
+                     interval = new MInterval (Key, mtext, end - start, null);
+
+                   divide_right (pos);
+                   Right.Left = interval;
+                   interval.Parent = Right;
+                   for (MInterval i = Right; i != null; i = i.Parent)
+                     i.Length += interval.Length;
+                 }
              }
          }
        else if (pos == To)
          {
-           MInterval next = Next;
-
-           if (next != null)
+           if (Right != null)
              {
-               if (Right == null)
-                 {
-                   next.Insert (pos, interval);
-                   return;
-                 }
-               next.remove_properties
-                 (MTextProperty.Flag.Sensitive|MTextProperty.Flag.FrontSticky);
-               interval.inherit_rear_properties (next.Stack);
+               MInterval next = Next;
+
+               if (next.isSensitive && next.isFrontSticky)
+                 next.Stack.Clear ();
+               end -= next.graft_backward (interval, start, end);
              }
-           remove_properties
-             (MTextProperty.Flag.Sensitive|MTextProperty.Flag.RearSticky);
-           interval.inherit_front_properties (Stack);
-
-           int len;
-           interval = graft (interval, true, out len);
-           if (interval != null && next != null)
-             interval = next.graft (interval, false, out len);
-           if (interval != null)
+           if (isSensitive && isRearSticky)
+             Stack.Clear ();
+           if (start < end)
              {
-               MInterval i;
-
-               if (Right != null)
+               start += graft_forward (interval, start, end);
+               if (start < end)
                  {
-                   //    .-this-.   ==>          .-this-.
-                   //         .-right                 .-right
-                   //     child                  .-child
-                   //                        interval
+                   if (interval != null)
+                     interval = interval.Copy (mtext, start, end);
+                   else
+                     interval = new MInterval (Key, mtext, end - start, null);
 
-                   i = Right.LeftMost;
-                   i.Left = interval;
-                 }
-               else
-                 {
-                   Right = interval;
-                   i = this;
+                   MInterval i;
+                   if (Right != null)
+                     {
+                       //    .-this-.   ==>          .-this-.
+                       //         .-right                 .-right
+                       //     child                  .-child
+                       //                        interval
+
+                       i = Right.LeftMost;
+                       i.Left = interval;
+                     }
+                   else
+                     {
+                       Right = interval;
+                       i = this;
+                     }
+                   interval.Parent = i;
+                   for (; i != null; i = i.Parent)
+                     i.Length += interval.Length;
                  }
-               interval.Parent = i;
-               for (; i != null; i = i.Parent)
-                 i.Length += interval.Length;
              }
          }
        else                    // (pos > To)
-         Next.Insert (pos, interval);
+         Next.Insert (pos, interval, start, end);
+       M17n.DebugPrint (" done\n");
       }
 
       private void vacate_node (MInterval interval)
@@ -1108,9 +1178,9 @@ namespace M17N.Core
       private void vacate_node (MInterval interval, MInterval stop)
       {
        if (interval != null)
-         M17N.DebugPrint ("vacate #{0} to #{1}\n", ID, interval.ID);
+         M17n.DebugPrint ("vacate #{0} to #{1}\n", ID, interval.ID);
        else
-         M17N.DebugPrint ("vacate #{0} to null\n", ID);
+         M17n.DebugPrint ("vacate #{0} to null\n", ID);
        if (interval != null)
          interval.Parent = Parent;
        if (Parent == null)
@@ -1136,7 +1206,7 @@ namespace M17N.Core
       public void Delete (int start, int end)
       {
        update_from_to ();
-       M17N.DebugPrint ("delete({0} {1}) from ", start, end); DumpOne (false, true);
+       M17n.DebugPrint ("delete({0} {1}) from ", start, end); DumpOne (false, true);
        if (start < From)
          {
            if (end <= From)
@@ -1189,10 +1259,10 @@ namespace M17N.Core
          }
       }
 
-      public void Push (int start, int end, MTextProperty prop)
+      public void Push (int start, int end, MProperty prop)
       {
        update_from_to ();
-       M17N.DebugPrint ("push({0} {1}) at ", start, end); DumpOne (false, true);
+       M17n.DebugPrint ("push({0} {1}) at ", start, end); DumpOne (false, true);
        if (start < From)
          {
            if (end <= From)
@@ -1221,19 +1291,23 @@ namespace M17N.Core
        Stack.Push (prop.key, prop);
       }
 
-      private static void merge_nodes (MInterval head, MInterval tail)
+      /// Combine intervals between HEAD and TAIL (both inclusive) to
+      /// the common parent of HEAD and TAIL while assuming that the
+      /// intervals are mergeable.
+      private static void combine (MInterval head, MInterval tail)
       {
-       M17N.DebugPrint ("merging "); head.DumpOne (true, false);
-       M17N.DebugPrint (" through "); tail.DumpOne (true, false);
+       M17n.DebugPrint ("combining "); head.DumpOne (true, false);
+       M17n.DebugPrint (" through "); tail.DumpOne (true, false);
 
        int from = head.From;
        int to = tail.To;
+       // The nearest common parent of HEAD and TAIL.
        MInterval root;
 
-       for (root = head; root.To + head.RightLength < to;
+       for (root = head; root.To + root.RightLength < to;
             root = root.Parent);
        
-       M17N.DebugPrint (" common root is "); root.DumpOne (false, true);
+       M17n.DebugPrint (" common root is "); root.DumpOne (false, true);
 
        if (from < root.From)
          {
@@ -1241,7 +1315,7 @@ namespace M17N.Core
 
            while (true)
              {
-               M17N.DebugPrint ("merging "); prev.DumpOne (false, true);
+               M17n.DebugPrint ("merging "); prev.DumpOne (false, true);
                prev.vacate_node (prev.Left, root);
                if (prev == head)
                  break;
@@ -1250,6 +1324,7 @@ namespace M17N.Core
                else
                  prev = prev.Parent;
              }
+           root.update_from_to ();
          }
        if (root.To < to)
          {
@@ -1257,7 +1332,7 @@ namespace M17N.Core
 
            while (true)
              {
-               M17N.DebugPrint ("merging "); next.DumpOne (false, true);
+               M17n.DebugPrint ("merging "); next.DumpOne (false, true);
                next.vacate_node (next.Right, root);
                if (next == tail)
                  break;
@@ -1266,24 +1341,20 @@ namespace M17N.Core
                else
                  next = next.Parent;
              }
+           root.update_from_to ();
          }
       }
 
       public void MergeAfterChange (int start, int end)
       {
        update_from_to ();
-       if (start < From)
-         {
-           Prev.MergeAfterChange (start, end);
-           return;
-         }
 
-       MInterval head = this, tail = this, i;
+       MInterval head = find_head (start), tail = head, i;
 
-       if (start == From && start > 0)
+       if (start == head.From && start > 0)
          {
-           i = Prev;
-           if (mergeable (i))
+           i = head.Prev;
+           if (head.mergeable (i))
              head = i;
          }
        while (tail.To < end)
@@ -1292,7 +1363,8 @@ namespace M17N.Core
            if (! tail.mergeable (i))
              {
                if (head != tail)
-                 merge_nodes (head, tail);
+                 combine (head, tail);
+               i.update_from_to ();
                head = i;
              }
            tail = i;
@@ -1305,13 +1377,13 @@ namespace M17N.Core
            tail = i;
          }
        if (head != tail)
-         merge_nodes (head, tail);
+         combine (head, tail);
       }
 
       public void Pop (int start, int end)
       {
        update_from_to ();
-       M17N.DebugPrint ("pop({0} {1}) at ", start, end); DumpOne (false, true);
+       M17n.DebugPrint ("pop({0} {1}) at ", start, end); DumpOne (false, true);
        if (start < From)
          {
            if (end <= From)
@@ -1343,6 +1415,30 @@ namespace M17N.Core
          }
       }
 
+      public void PopSensitive (int start, int end)
+      {
+       update_from_to ();
+       MInterval head = find_head (start);
+       MInterval tail = find_tail (end);
+       while (! head.Stack.IsEmpty && head.From > 0)
+         {
+           MInterval prev = head.Prev;
+
+           if (prev.Stack.IsEmpty || head.Stack.Val != prev.Stack.Val)
+             break;
+           head = head.Prev;
+         }
+       while (! tail.Stack.IsEmpty && tail.To < mtext.Length)
+         {
+           MInterval next = tail.Next;
+
+           if (next.Stack.IsEmpty || tail.Stack.Val != next.Stack.Val)
+             break;
+           tail = tail.Next;
+         }
+       Pop (head.From, tail.To);
+      }
+
       private void DumpOne (bool with_prop, bool newline)
       {
        DumpOne (with_prop, newline, false);
@@ -1350,7 +1446,7 @@ namespace M17N.Core
 
       private void DumpOne (bool with_prop, bool newline, bool force)
       {
-       if (force || M17N.debug)
+       if (force || M17n.debug)
          {
            Console.Write ("#{0}({1} {2} {3}", ID, Length, From, To);
            if (with_prop)
@@ -1368,7 +1464,7 @@ namespace M17N.Core
 
       public void Dump (bool force)
       {
-       if (force || M17N.debug)
+       if (force || M17n.debug)
          {
            update_from_to ();
 
@@ -1388,12 +1484,12 @@ namespace M17N.Core
 
       public void DumpNested (bool force)
       {
-       DumpNested ("", force);
+       DumpNested (Key.ToString () + ":", force);
       }
 
       public void DumpNested (string indent, bool force)
       {
-       if (force || M17N.debug)
+       if (force || M17n.debug)
          {
            int indent_type = (Parent == null ? 1
                               : Parent.Left == this ? 0 : 2);
@@ -1406,10 +1502,11 @@ namespace M17N.Core
                else
                  Left.DumpNested (indent + "| ", force);
              }
+           Console.Write (indent);
            if (indent_type == 0)
-             Console.Write (indent + ".-");
+             Console.Write (".-");
            else if (indent_type == 2)
-             Console.Write (indent + "`-");
+             Console.Write ("`-");
            DumpOne (true, true, true);
            if (Right != null)
              {