*** empty log message ***
[m17n/m17n-lib-cs.git] / MText.cs
index ff29503..98cb0c5 100644 (file)
--- a/MText.cs
+++ b/MText.cs
@@ -2,6 +2,7 @@ using System;
 using System.Text;
 using System.Collections;
 using System.Collections.Generic;
+using M17N;
 using M17N.Core;
 
 namespace M17N.Core
@@ -22,13 +23,31 @@ namespace M17N.Core
   {
     internal MSymbol key;
     internal object val;
-    private bool front_sticky;
-    private bool rear_sticky;
+
+    [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 front_sticky; } }
-    public bool RearSticky { get { return rear_sticky; } }
+    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)
     {
@@ -37,12 +56,21 @@ namespace M17N.Core
     }
 
     public MTextProperty (MSymbol key, object val,
-                         bool front_sticky, bool rear_sticky)
+                         bool front_sticky, bool rear_sticky, bool sensitive)
     {
       this.key = key;
       this.val = val;
-      this.front_sticky = front_sticky;
-      this.rear_sticky = rear_sticky;
+      if (front_sticky)
+       flags |= Flag.FrontSticky;
+      if (rear_sticky)
+       flags |= Flag.RearSticky;
+      if (sensitive)
+       flags |= Flag.Sensitive;
+    }
+
+    public override string ToString ()
+    {
+      return key.ToString () + ":" + val;
     }
   }
 
@@ -136,7 +164,7 @@ namespace M17N.Core
       return this.sb.ToString ().CompareTo (other.sb.ToString ());
     }
 
-    public override String ToString () { return sb.ToString (); }
+    public override String ToString () { return "\"" + sb.ToString () + "\""; }
 
     private static bool surrogate_high_p (char c)
     {
@@ -205,8 +233,26 @@ namespace M17N.Core
       return i;
     }
 
+    private void check_pos (int pos, bool tail_ok)
+    {
+      if (pos < 0 || (tail_ok ? pos > nchars : pos >= nchars))
+       throw new Exception ("Invalid MText position:" + pos);
+    }
+
+    private bool check_range (int from, int to, bool zero_ok)
+    {
+      if (from < 0 || (zero_ok ? from > to : from >= to)
+         || to > nchars)
+       throw new Exception ("Invalid MText range");
+      return (from == to);
+    }
+
     private void insert (int pos, MText mt2, int from, int to)
     {
+      check_pos (pos, true);
+
+      if (from == to)
+       return;
       int pos_idx = pos_to_idx (this, pos);
       int from_idx = pos_to_idx (mt2, from);
       int to_idx = pos_to_idx (mt2, to);
@@ -215,21 +261,45 @@ namespace M17N.Core
       nchars += to - from;
 
       foreach (MPlist plist in mt2.intervals)
-       if (intervals.find (plist.Key) == null)
-         intervals.push (plist.Key, new MInterval (plist.Key, this));
+       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);
+         MPlist p = mt2.intervals.Find (plist.Key);
          MInterval interval;
 
-         if (p.IsEmpty)
-           interval = new MInterval (plist.Key, to - from);
+         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);
+           interval = ((MInterval) p.Val).Copy (from, to);
+         ((MInterval) plist.Val).Insert (pos, interval);
        }
     }
 
+    private void insert (int pos, int c)
+    {
+      check_pos (pos, true);
+
+      int pos_idx = pos_to_idx (this, pos);
+
+      if (c < 0x10000)
+       {
+         char ch = (char) c;
+         sb.Insert (pos_idx, ch);
+       }
+      else
+       {
+         char high = (char) (0xD800 + ((c - 0x10000) >> 10));
+         char low = (char) (0xDC00 + ((c - 0x10000) & 0x3FF));
+         sb.Insert (pos_idx, low);
+         sb.Insert (pos_idx, high);
+       }
+      nchars++;
+      foreach (MPlist plist in intervals)
+       ((MInterval) plist.Val).Insert (pos,
+                                       new MInterval (plist.Key, this, 1));
+    }
+
     public int this[int i]
     {
       set {
@@ -259,90 +329,164 @@ namespace M17N.Core
       }
     }
 
-    public MText dup ()
+    public MText Dup ()
     {
-      return (new MText (sb.ToString ()));
+      MText mt = new MText (sb.ToString ());
+
+      foreach (MPlist p in intervals)
+       mt.intervals.Add (p.Key, ((MInterval) p.Val).Copy (0, Length));
+      return mt;
+    }
+
+    public MText Ins (int pos, int c)
+    {
+      insert (pos, c);
+      return this;
     }
 
-    public MText ins (int pos, MText mt)
+    public MText Ins (int pos, MText mt)
     {
       insert (pos, mt, 0, mt.nchars);
       return this;
     }
 
-    public MText ins (int pos, MText mt, int from, int to)
+    public MText Ins (int pos, MText mt, int from, int to)
     {
       insert (pos, mt, from, to);
       return this;
     }
 
-    public MText del (int from, int to)
+    public MText Cat (int c)
     {
+      insert (nchars, c);
+      return this;
+    }
+
+    public MText Del (int from, int to)
+    {
+      if (check_range (from, to, true))
+       return this;
+
       sb.Remove (from, pos_to_idx (this, to) - pos_to_idx (this, from));
       nchars -= to - from;
 
-      foreach (MPlist plist in intervals)
-       ((MInterval) plist.Val).delete (from, to);
+      if (nchars > 0)
+       foreach (MPlist plist in intervals)
+         ((MInterval) plist.Val).Delete (from, to);
+      else
+       intervals = new MPlist ();
       return this;
     }
 
-    public object get_prop (int pos, MSymbol key)
+    public object GetProp (int pos, MSymbol key)
     {
-      MInterval i = (MInterval) intervals.find (key).Val;
+      check_pos (pos, false);
 
+      MInterval i = (MInterval) intervals.Get (key);
       if (i == null)
        return null;
 
-      MTextProperty prop = i.get (pos);
+      MTextProperty prop = i.Get (pos);
       return (prop != null ? prop.Val : null);
     }
 
-    public object get_prop (int pos, MSymbol key, out MTextProperty prop)
+    public object GetProp (int pos, MSymbol key, out MTextProperty prop)
     {
-      MInterval i = (MInterval) intervals.find (key).Val;
+      check_pos (pos, false);
 
+      MInterval i = (MInterval) intervals.Get (key);
       if (i == null)
        return (prop = null);
-      prop = i.get (pos);
+      prop = i.Get (pos);
       return (prop != null ? prop.Val : null);
     }
 
-    public object get_prop (int pos, MSymbol key, out MTextProperty[] array)
+    public object GetProp (int pos, MSymbol key, out MTextProperty[] array)
     {
-      MInterval i = (MInterval) intervals.find (key).Val;
+      check_pos (pos, false);
 
+      MInterval i = (MInterval) intervals.Get (key);
       if (i == null)
        return (array = null);
-      MTextProperty prop = i.get (pos, out array);
+      MTextProperty prop = i.Get (pos, out array);
       return (prop != null ? prop.Val : null);
     }
 
-    public void push_prop (int from, int to, MSymbol key, object val)
+    public void PushProp (int from, int to, MSymbol key, object val)
     {
-      push_prop (from, to, new MTextProperty (key, val));
+      if (! check_range (from, to, true))
+       PushProp (from, to, new MTextProperty (key, val));
     }
 
-    public void push_prop (int from, int to, MTextProperty prop)
+    public void PushProp (int from, int to, MTextProperty prop)
     {
       if (from < 0)
        {
          if (default_property == null)
            default_property = new MPlist ();
-         default_property.push (prop.key, prop.val);
+         default_property.Push (prop.key, prop.val);
        }
       else
        {
-         MInterval root = (MInterval) intervals.find (prop.key).Val;
+         if (check_range (from, to, true))
+           return;
+
+         MPlist p = intervals.Find (prop.key);
+         MInterval root;
 
-         if (root == null)
+         if (p == null)
            {
              root = new MInterval (prop.key, this);
-             intervals.push (prop.key, root);
+             intervals.Push (prop.key, root);
            }
+         else
+           root = (MInterval) p.Val;
+
          root.Push (from, to, prop);
        }
     }
 
+    public void PopProp (int from, int to, MSymbol key)
+    {
+      if (from < 0)
+       {
+         if (default_property == null)
+           return;
+         MPlist p = default_property.Find (key);
+
+         if (p != null)
+           p.Pop ();
+       }
+      else
+       {
+         if (check_range (from, to, true))
+           return;
+
+         MPlist p = intervals.Find (key);
+
+         if (p != null)
+           {
+             MInterval root = (MInterval) p.Val;
+             root.Pop (from, to);
+             root.MergeAfterChange (from, to);
+           }
+       }
+    }
+
+    public void DumpProp ()
+    {
+      Console.Write ("(");
+      foreach (MPlist p in intervals)
+       ((MInterval) p.Val).Dump (true);
+      Console.WriteLine (")");
+    }
+
+    public void DumpPropNested ()
+    {
+      foreach (MPlist p in intervals)
+       ((MInterval) p.Val).DumpNested (true);
+    }
+
     private class MInterval
     {
       // position: 0   1   2   3   4   5   6   7
@@ -354,111 +498,155 @@ namespace M17N.Core
       //                      [7 (3 4)]
       //              [3 (1 2)]       [3 (4 6)]
       //         [1 (0 1)] [2 (2 3)]      [1 (6 7)]
-      private int total_length;
-      private int from, to;
-      private MSymbol key;
-      private Stack<MTextProperty> stack;
-      private MInterval left, right, parent;
+      //
+      private static int count = 0;
+      private int ID;
+      private int Length;
+      private int From, To;
+      private MSymbol Key;
+      private MPlist Stack;
+      private MInterval Left, Right, Parent;
       private MText mtext;
 
-      public MInterval (MSymbol key, int length)
+      public MInterval (MSymbol key, MText mt, int length)
       {
        if (length <= 0)
          throw new Exception ("Invalid interval length");
-       this.key = key;
-       total_length = length;
-       stack = new Stack<MTextProperty> ();
+       Key = key;
+       mtext = mt;
+       Length = length;
+       Stack = new MPlist ();
+       ID = count++;
       }
 
       public MInterval (MSymbol key, MText mt)
       {
-       this.key = key;
+       Key = key;
        mtext = mt;
-       total_length = mt.sb.Length;
-       from = 0;
-       to = total_length;
-       stack = new Stack<MTextProperty> ();
+       Length = mt.sb.Length;
+       From = 0;
+       To = Length;
+       Stack = new MPlist ();
+       ID = count++;
       }
 
-      public MTextProperty get (int pos)
+      public MTextProperty Get (int pos)
       {
        MInterval i = find (pos);
 
-       return (i.stack.Count > 0 ? i.stack.Peek () : null);
+       return (i.Stack.IsEmpty ? null : (MTextProperty) i.Stack.Val);
       }
 
-      public MTextProperty get (int pos, out MTextProperty[] array)
+      public MTextProperty Get (int pos, out MTextProperty[] array)
       {
        MInterval i = find (pos);
 
-       if (i.stack.Count == 0)
+       if (i.Stack.IsEmpty)
          {
            array = null;
            return null;
          }
-       array = i.stack.ToArray ();
-       return i.stack.Peek ();
+       array = new MTextProperty[i.Stack.Count];
+
+       int idx;
+       MPlist p;
+       for (idx = 0, p = i.Stack; ! p.IsEmpty; idx++, p = p.Next)
+         array[idx] = (MTextProperty) p.Val;
+       return array[0];
       }
 
-      private MInterval (MSymbol key, int length, Stack<MTextProperty> stack)
+      private MInterval (MSymbol key, MText mt, int length, MPlist stack)
       {
-       this.key = key;
-       total_length = length;
-       from = 0;
-       to = total_length;
-       stack = new Stack<MTextProperty> (stack);
+       Key = key;
+       mtext = mt;
+       Length = length;
+       From = 0;
+       To = Length;
+       Stack = stack.Clone ();
+       ID = count++;
       }
 
-
       private void update_from_to ()
       {
-       if (parent != null)
+       if (Parent == null)
+         {
+           From = LeftLength;
+           To = Length - RightLength;
+         }
+       else if (Parent.Left == this)
+         {
+           From = Parent.From - Length + LeftLength;
+           To = Parent.From - RightLength;
+         }
+       else
          {
-           from = parent.from - total_length + LeftLength;
-           to = parent.from - RightLength;
+           From = Parent.To + LeftLength;
+           To = Parent.To + Length - RightLength;
          }
       }
 
       private int LeftLength
       {
-       get { return (left == null ? 0 : left.total_length); }
+       get { return (Left == null ? 0 : Left.Length); }
       }
 
       private int RightLength
       {
-       get { return (right == null ? 0 : right.total_length); }
+       get { return (Right == null ? 0 : Right.Length); }
       }
 
-      private MInterval LeftMostNode
+      private MInterval LeftMost
       {
-       get { return (left == null ? this : left.LeftMostNode); }
+       get {
+         if (Left == null)
+           return this;
+         Left.update_from_to ();
+         return Left.LeftMost;
+       }
       }
 
-      private MInterval RightMostNode
+      private MInterval RightMost
       {
-       get { return (right == null ? this : right.RightMostNode); }
+       get {
+         if (Right == null)
+           return this;
+         Right.update_from_to ();
+         return Right.RightMost;
+       }
       }
 
-      private MInterval LeftNode {
+      private MInterval Prev {
        get {
          MInterval i;
 
-         if (left != null)
-           for (i = left; i.right != null; i = i.right);
+         if (Left != null)
+           for (i = Left; i.Right != null; i = i.Right)
+             i.update_from_to ();
          else
-           for (i = parent; i != null && i.left == null; i = i.parent);
+           {
+             MInterval child = this;
+             for (i = Parent; i != null && i.Left == child;
+                  child = i, i = i.Parent)
+               i.update_from_to ();
+           }
          return i;
        }
       }
 
-      private MInterval RightNode {
+      private MInterval Next {
        get {
          MInterval i;
 
-         if (right != null)
-           for (i = right; i.left != null; i = i.left);
+         if (Right != null)
+           for (i = Right; i.Left != null; i = i.Left)
+             i.update_from_to ();
          else
-           for (i = parent; i != null && i.right == null; i = i.parent);
+           {
+             MInterval child = this;
+             for (i = Parent; i != null && i.Right == child;
+                  child = i, i = i.Parent)
+               i.update_from_to ();
+           }
          return i;
        }
       }
@@ -466,43 +654,54 @@ namespace M17N.Core
       private MInterval find (int pos)
       {
        update_from_to ();
-       if (pos < from)
-         return left.find (pos);
-       if (pos >= to)
-         return right.find (pos);
+       if (pos < From)
+         return Left.find (pos);
+       if (pos >= To)
+         return Right.find (pos);
        return this;
       }
 
+      private bool mergeable (MInterval i)
+      {
+       MPlist p1, p2;
+
+       for (p1 = Stack, p2 = i.Stack; ! p1.IsEmpty && ! p2.IsEmpty;
+            p1 = p1.Next, p2 = p2.Next)
+         if (p1.Val != p2.Val)
+           return false;
+       return (p1.IsEmpty && p2.IsEmpty);
+      }
+
       //      p-. or .-p              p-. or .-p
       //       .-this-.                .-right-.
       //    left   .-right-.  ->   .-this-.    c2
       //          c1       c2    left     c1
       private MInterval promote_right ()
       {
-       int right_length = right.total_length;
+       int right_length = Right.Length;
        MInterval c1;
 
-       if (parent == null)
-         mtext.intervals.put (key, right);
-       else if (parent.left == this)
-         parent.left = right;
+       if (Parent == null)
+         mtext.intervals.Put (Key, Right);
+       else if (Parent.Left == this)
+         Parent.Left = Right;
        else
-         parent.right = right;
-       right.parent = parent;
-       c1 = right.left;
-       right.left = this;
-
-       parent = right;
-       right = c1;
-       parent.total_length += total_length;
-       total_length -= right_length;
+         Parent.Right = Right;
+       Right.Parent = Parent;
+       c1 = Right.Left;
+       Right.Left = this;
+
+       Parent = Right;
+       Right = c1;
+       Parent.Length += Length;
+       Length -= right_length;
        if (c1 != null)
          {
-           c1.parent = this;
-           parent.total_length -= c1.total_length;
-           total_length += c1.total_length;
+           c1.Parent = this;
+           Parent.Length -= c1.Length;
+           Length += c1.Length;
          }
-       return parent;
+       return Parent;
       }
 
       //      p-. or .-p              p-. or .-p
@@ -511,30 +710,30 @@ namespace M17N.Core
       // c1      c2                        c2     right
       private MInterval promote_left ()
       {
-       int left_length = left.total_length;
+       int left_length = Left.Length;
        MInterval c1;
 
-       if (parent == null)
-         mtext.intervals.put (key, left);
-       else if (parent.left == this)
-         parent.left = left;
+       if (Parent == null)
+         mtext.intervals.Put (Key, Left);
+       else if (Parent.Left == this)
+         Parent.Left = Left;
        else
-         parent.right = left;
-       left.parent = parent;
-       c1 = left.left;
-       left.right = this;
-
-       parent = left;
-       left = c1;
-       parent.total_length += total_length;
-       total_length -= left_length;
+         Parent.Right = Left;
+       Left.Parent = Parent;
+       c1 = Left.Left;
+       Left.Right = this;
+
+       Parent = Left;
+       Left = c1;
+       Parent.Length += Length;
+       Length -= left_length;
        if (c1 != null)
          {
-           c1.parent = this;
-           parent.total_length -= c1.total_length;
-           total_length += c1.total_length;
+           c1.Parent = this;
+           Parent.Length -= c1.Length;
+           Length += c1.Length;
          }
-       return parent;
+       return Parent;
       }
 
       private MInterval balance ()
@@ -551,48 +750,58 @@ namespace M17N.Core
 
            if (diff > 0)
              {
-               new_diff = (i.total_length - i.LeftLength
-                           + i.left.RightLength - i.left.LeftLength);
+               new_diff = (i.Length - i.LeftLength
+                           + i.Left.RightLength - i.Left.LeftLength);
                if (Math.Abs (new_diff) >= diff)
                  break;
                i = i.promote_left ();
-               i.right.balance ();
+               i.Right.balance ();
              }
            else if (diff < 0)
              {
-               new_diff = (i.total_length - i.RightLength
-                           + i.right.LeftLength - i.right.RightLength);
+               new_diff = (i.Length - i.RightLength
+                           + i.Right.LeftLength - i.Right.RightLength);
                if (Math.Abs (new_diff) >= diff)
                  break;
                i = i.promote_right ();
-               i.left.balance ();
+               i.Left.balance ();
              }
          }
        return i;
       }
 
-      public MInterval copy (int start, int end)
+      public MInterval Copy (int start, int end)
       {
-       MInterval this_copy, left_copy = null, right_copy = null;
+       MInterval copy, left_copy = null, right_copy = null;
 
        update_from_to ();
-       if (start < from)
+
+       if (start < From)
          {
-           if (end <= from)
-             return left.copy (start, end);
-           left_copy = left.copy (start, from);
+           if (end <= From)
+             return Left.Copy (start, end);
+           left_copy = Left.Copy (start, From);
          }
-       else if (end > to)
+       if (end > To)
          {
-           if (start >= to)
-             return right.copy (start, end);
-           right_copy = right.copy (to, end);
+           if (start >= To)
+             return Right.Copy (start, end);
+           right_copy = Right.Copy (To, end);
          }
-       this_copy = new MInterval (key, end - start, stack);
-       this_copy.left = left_copy;
-       this_copy.right = right_copy;
 
-       return this_copy;
+       copy = new MInterval (Key, null, end - start, Stack);
+       remove_properties (MTextProperty.Flag.Sensitive);
+       if (left_copy != null)
+         {
+           copy.Left = left_copy;
+           left_copy.Parent = copy;
+         }
+       if (right_copy != null)
+         {
+           copy.Right = right_copy;
+           right_copy.Parent = copy;
+         }
+       return copy;
       }
 
       //  this-.   ==>   this-.
@@ -600,18 +809,18 @@ namespace M17N.Core
       //                            right
       private MInterval divide_right (int pos)
       {
-       update_from_to ();
-
-       MInterval interval = new MInterval (key, to - pos, stack);
+       MInterval interval = new MInterval (Key, mtext, To - pos, Stack);
 
-       total_length -= to - pos;
-       if (right != null)
+       M17N.DebugPrint ("divide-right({0}) at ", pos); DumpOne (false, true);
+       To = pos;
+       if (Right != null)
          {
-           right.parent = interval;
-           interval.total_length += right.total_length;
+           interval.Right = Right;
+           Right.Parent = interval;
+           interval.Length += Right.Length;
          }
-       interval.parent = this;
-       right = interval;
+       interval.Parent = this;
+       Right = interval;
        return interval;
       }
 
@@ -620,195 +829,611 @@ namespace M17N.Core
       //                 left
       private MInterval divide_left (int pos)
       {
-       update_from_to ();
-
-       MInterval interval = new MInterval (key, to - pos, stack);
+       MInterval interval = new MInterval (Key, mtext, pos - From, Stack);
 
-       total_length -= to - pos;
-       if (left != null)
+       M17N.DebugPrint ("divide-left({0}) at ", pos); DumpOne (false, true);
+       From = pos;
+       if (Left != null)
          {
-           left.parent = interval;
-           interval.total_length += left.total_length;
+           interval.Left = Left;
+           Left.Parent = interval;
+           interval.Length += Left.Length;
          }
-       interval.parent = this;
-       left = interval;
+       interval.Parent = this;
+       Left = interval;
        return interval;
       }
 
-      public void insert (int pos, MInterval interval)
+      private void remove_properties (MTextProperty.Flag flags)
       {
-       update_from_to ();
-       if (pos < from)
+       for (MPlist p = Stack; ! p.IsEmpty;)
          {
-           LeftNode.insert (pos, interval);
-           return;
+           MTextProperty prop = (MTextProperty) p.Val;
+
+           if ((prop.flags & flags) == flags)
+             p.Pop ();
+           else
+             p = p.Next;
          }
-       if (pos >= to)
+      }
+
+      private void inherit_front_properties (MPlist plist)
+      {
+       for (MInterval i = LeftMost; i != null; i = i.Next)
          {
-           RightNode.insert (pos, interval);
-           return;
+           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);
+             }
          }
-       if (pos > from)
-         {
-           divide_right (pos).insert (pos, interval);
-           return;
-         }         
+      }
 
-       // POS == FROM
-       if (left != null && LeftNode.stack.Count > 0)
+      private void inherit_rear_properties (MPlist plist)
+      {
+       for (MInterval i = RightMost; i != null; i = i.Prev)
          {
-           Stack<MTextProperty> s = new Stack<MTextProperty> ();
-
-           foreach (MTextProperty p in LeftNode.stack)
-             if (p.RearSticky)
-               s.Push (p);
-           if (s.Count > 0)
+           if (! Stack.IsEmpty)
+             break;
+           for (MPlist p = plist; ! p.IsEmpty; p = p.Next)
              {
-               for (MInterval i = interval.LeftMostNode;
-                    i != null && i.stack.Count == 0;
-                    i = i.LeftNode)
-                 foreach (MTextProperty p in s)
-                   i.stack.Push (p);
+               MTextProperty prop = (MTextProperty) p.Val;
+
+               if ((prop.flags & MTextProperty.Flag.FrontSticky)
+                   == MTextProperty.Flag.FrontSticky)
+                 i.Stack.Add (prop.key, prop);
              }
          }
-       if (stack.Count > 0)
+      }
+
+      private MInterval delete_node_forward ()
+      {
+       if (Parent != null)
          {
-           Stack<MTextProperty> s = new Stack<MTextProperty> ();
+           int len = Length - RightLength;
 
-           foreach (MTextProperty p in stack)
-             if (p.FrontSticky)
-               s.Push (p);
-           if (s.Count > 0)
-             {
-               for (MInterval i = interval.RightMostNode;
-                    i != null && i.stack.Count == 0;
-                    i = i.RightNode)
-                 foreach (MTextProperty p in s)
-                   i.stack.Push (p);
-             }
+           for (MInterval i = Parent; i != null; i = i.Parent)
+             i.Length -= len;
+           if (Parent.Left == this)
+             Parent.Left = Right;
+           else
+             Parent.Right = Right;
          }
 
-       // INTERVAL is ready to insert.
-       //
-       //    .-this-.   ==>          .-this-.
-       // left-.                  left-.
-       //     child                  interval
-       //                         child
+       if (Right != null)
+         {
+           Right.Parent = Parent;
+           return Right.LeftMost;
+         }
+       return Parent;
+      }
 
-       if (left != null)
+      private MInterval delete_node_backward ()
+      {
+       if (Parent != null)
          {
-           MInterval i = left.RightMostNode;
-       
-           i.left = interval;
-           interval.parent = i;
-           for (; i != null; i = i.parent)
-             i.total_length += interval.total_length;
+           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;
+         }
+
+       if (Left != null)
+         {
+           Left.Parent = Parent;
+           return Left.RightMost;
+         }
+       return Parent;
+      }
+
+      private void set_mtext (MText mt)
+      {
+       mtext = mt;
+       if (Left != null)
+         Left.set_mtext (mt);
+       if (Right != null)
+         Right.set_mtext (mt);
+      }
+
+      private MInterval graft (MInterval interval, bool forward, out int len)
+      {
+       MInterval i;
+
+       len = 0;
+       if (forward)
+         {
+           i = interval.LeftMost;
+           while (i != null)
+             {
+               if (! mergeable (i))
+                 break;
+               len += i.Length - i.RightLength;
+               i = i.delete_node_forward ();
+             }
          }
        else
          {
-           left = interval;
+           i = interval.RightMost;
+           while (i != null)
+             {
+               if (! mergeable (i))
+                 break;
+               len += i.Length - i.LeftLength;
+               i = i.delete_node_backward ();
+             }
+         }
 
-           for (MInterval i = this; i != null; i = i.parent)
-             i.total_length += interval.total_length;
+       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)
+             {
+               ii.From += len;
+               ii.To += len;;
+             }
          }
+       if (i != null)
+         while (i.Parent != null) i = i.Parent;
+       return i;
       }
 
-      private void update_parent (MInterval i)
+      public void Insert (int pos, MInterval interval)
       {
-       if (parent == null)
-         mtext.intervals.put (key, i);
-       else
+       update_from_to ();
+       M17N.DebugPrint ("insert({0}) at {1} in ", interval.Length, pos);
+       DumpOne (false, false);
+
+       interval.set_mtext (mtext);
+
+       if (pos < From)
+         Prev.Insert (pos, interval);
+       else if (pos == From)
          {
-           int diff;
+           MInterval prev = Prev;
 
-           if (parent.right == i)
+           if (prev != null)
              {
-               diff = parent.right.total_length - i.total_length;
-               parent.right = i;
+               if (Left == null)
+                 {
+                   prev.Insert (pos, interval);
+                   return;
+                 }
+               prev.remove_properties
+                 (MTextProperty.Flag.Sensitive|MTextProperty.Flag.RearSticky);
+               interval.inherit_front_properties (prev.Stack);
              }
-           else
+           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)
+             {
+               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;
+             }
+         }
+       else if (pos < To)
+         {
+           remove_properties (MTextProperty.Flag.Sensitive);
+
+           int len;
+           interval = graft (interval, true, out len);
+           pos += len;
+           if (interval != null)
+             interval = graft (interval, false, out len);
+           if (interval != 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)
              {
-               diff = parent.left.total_length - i.total_length;
-               parent.left = i;
+               if (Right == null)
+                 {
+                   next.Insert (pos, interval);
+                   return;
+                 }
+               next.remove_properties
+                 (MTextProperty.Flag.Sensitive|MTextProperty.Flag.FrontSticky);
+               interval.inherit_rear_properties (next.Stack);
+             }
+           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)
+             {
+               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;
              }
-           for (i = parent; i != null; i = i.parent)
-             i.total_length += diff;
          }
+       else                    // (pos > To)
+         Next.Insert (pos, interval);
+       M17N.DebugPrint (" done\n");
       }
 
-      public void delete (int start, int end)
+      private void vacate_node (MInterval interval)
+      {
+       vacate_node (interval, null);
+      }
+
+      private void vacate_node (MInterval interval, MInterval stop)
+      {
+       if (interval != null)
+         M17N.DebugPrint ("vacate #{0} to #{1}\n", ID, interval.ID);
+       else
+         M17N.DebugPrint ("vacate #{0} to null\n", ID);
+       if (interval != null)
+         interval.Parent = Parent;
+       if (Parent == null)
+         {
+           if (mtext != null)
+             mtext.intervals.Put (Key, interval);
+         }
+       else
+         {
+           if (this == Parent.Right)
+             Parent.Right = interval;
+           else
+             Parent.Left = interval;
+
+           int diff = Length;
+           if (interval != null)
+             diff -= interval.Length;
+           for (MInterval i = Parent; i != stop; i = i.Parent)
+             i.Length -= diff;
+         }
+      }
+
+      public void Delete (int start, int end)
       {
        update_from_to ();
-       if (start < from)
+       M17N.DebugPrint ("delete({0} {1}) from ", start, end); DumpOne (false, true);
+       if (start < From)
          {
-           if (end <= from)
+           if (end <= From)
              {
-               left.delete (start, end);
+               Left.Delete (start, end);
                return;
              }
-           left.delete (start, from);
-           start = from;
+           Left.Delete (start, From);
+           To -= From - start;
+           end -= From - start;
+           From = start;
          }
-       else if (end > to)
+       if (end > To)
          {
-           if (start >= to)
+           if (start >= To)
              {
-               right.delete (start, end);
+               Right.Delete (start, end);
                return;
              }
-           right.delete (to, end);
-           end = to;
+           Right.Delete (To, end);
+           end = To;
          }
-       if (start == from && end == to)
+       if (start == From && end == To)
          {
-           if (left == null)
-             update_parent (right);
-           else if (right == null)
-             update_parent (left);
+           if (Right == null)
+             {
+               vacate_node (Left);
+             }
            else
              {
-               MInterval i;
+               if (Left != null)
+                 {
+                   MInterval i;
                
-               for (i = right; i.left != null; i = i.left)
-                 i.total_length += left.total_length;
-               i.total_length += left.total_length;
-               i.left = left;
-               update_parent (right);
+                   for (i = Right; i.Left != null; i = i.Left)
+                     i.Length += Left.Length;
+                   i.Length += Left.Length;
+                   i.Left = Left;
+                   Left.Parent = i;
+                 }
+               vacate_node (Right);
              }
          }
        else
          {
            int len = end - start;
 
-           for (MInterval i = this; i != null; i = i.parent)
-             i.total_length -= len;
+           for (MInterval i = this; i != null; i = i.Parent)
+             i.Length -= len;
          }
       }
 
-      public MTextProperty Push (int start, int end, MTextProperty prop)
+      public void Push (int start, int end, MTextProperty prop)
       {
        update_from_to ();
-       if (start < from)
+       M17N.DebugPrint ("push({0} {1}) at ", start, end); DumpOne (false, true);
+       if (start < From)
          {
-           left.Push (start, end, prop);
-           if (end <= from)
-             return prop;
-           start = from;
+           if (end <= From)
+             {
+               Left.Push (start, end, prop);
+               return;
+             }
+           Left.Push (start, From, prop);
+           start = From;
          }
-       else if (end > to)
+       if (end > To)
          {
-           right.Push (start, end, prop);
-           if (start >= to)
-             return prop;
-           end = to;
+           if (start >= To)
+             {
+               Right.Push (start, end, prop);
+               return;
+             }
+           Right.Push (To, end, prop);
+           end = To;
          }
 
-       if (start > from)
-         divide_left (from);
-       if (end < to)
+       if (start > From)
+         divide_left (start);
+       if (end < To)
          divide_right (end);
-       stack.Push (prop);
-       return prop;
+       Stack.Push (prop.key, prop);
+      }
+
+      private static void merge_nodes (MInterval head, MInterval tail)
+      {
+       M17N.DebugPrint ("merging "); head.DumpOne (true, false);
+       M17N.DebugPrint (" through "); tail.DumpOne (true, false);
+
+       int from = head.From;
+       int to = tail.To;
+       MInterval root;
+
+       for (root = head; root.To + root.RightLength < to;
+            root = root.Parent);
+       
+       M17N.DebugPrint (" common root is "); root.DumpOne (false, true);
+
+       if (from < root.From)
+         {
+           MInterval prev = root.Prev;
+
+           while (true)
+             {
+               M17N.DebugPrint ("merging "); prev.DumpOne (false, true);
+               prev.vacate_node (prev.Left, root);
+               if (prev == head)
+                 break;
+               if (prev.Left != null)
+                 prev = prev.Left.RightMost;
+               else
+                 prev = prev.Parent;
+             }
+         }
+       if (root.To < to)
+         {
+           MInterval next = root.Next;
+
+           while (true)
+             {
+               M17N.DebugPrint ("merging "); next.DumpOne (false, true);
+               next.vacate_node (next.Right, root);
+               if (next == tail)
+                 break;
+               if (next.Right != null)
+                 next = next.Right.LeftMost;
+               else
+                 next = next.Parent;
+             }
+         }
+      }
+
+      public void MergeAfterChange (int start, int end)
+      {
+       update_from_to ();
+       if (start < From)
+         {
+           Prev.MergeAfterChange (start, end);
+           return;
+         }
+
+       MInterval head = this, tail = this, i;
+
+       if (start == From && start > 0)
+         {
+           i = Prev;
+           if (mergeable (i))
+             head = i;
+         }
+       while (tail.To < end)
+         {
+           i = tail.Next;
+           if (! tail.mergeable (i))
+             {
+               if (head != tail)
+                 merge_nodes (head, tail);
+               head = i;
+             }
+           tail = i;
+         }
+       while (true)
+         {
+           i = tail.Next;
+           if (i == null || ! tail.mergeable (i))
+             break;
+           tail = i;
+         }
+       if (head != tail)
+         merge_nodes (head, tail);
+      }
+
+      public void Pop (int start, int end)
+      {
+       update_from_to ();
+       M17N.DebugPrint ("pop({0} {1}) at ", start, end); DumpOne (false, true);
+       if (start < From)
+         {
+           if (end <= From)
+             {
+               Left.Pop (start, end);
+               return;
+             }
+           Left.Pop (start, From);
+           start = From;
+         }
+       if (end > To)
+         {
+           if (start >= To)
+             {
+               Right.Pop (start, end);
+               return;
+             }
+           Right.Pop (To, end);
+           end = To;
+         }
+
+       if (! Stack.IsEmpty)
+         {
+           if (start > From)
+             divide_left (start);
+           if (end < To)
+             divide_right (end);
+           Stack.Pop ();
+         }
+      }
+
+      private void DumpOne (bool with_prop, bool newline)
+      {
+       DumpOne (with_prop, newline, false);
+      }
+
+      private void DumpOne (bool with_prop, bool newline, bool force)
+      {
+       if (force || M17N.debug)
+         {
+           Console.Write ("#{0}({1} {2} {3}", ID, Length, From, To);
+           if (with_prop)
+             foreach (MPlist p in Stack)
+               Console.Write (" " + p.Val);
+           Console.Write (")");
+           if (newline)
+             Console.WriteLine ();
+           if (Length <= 0)
+             throw new Exception ("Invalid interval length");
+         }
+      }
+
+      public void Dump () { Dump (false); }
+
+      public void Dump (bool force)
+      {
+       if (force || M17N.debug)
+         {
+           update_from_to ();
+
+           if (Left != null)
+             Left.Dump (force);
+           if (From > 0)
+             Console.Write (" ");
+           DumpOne (true, false, force);
+           if (Right != null)
+             Right.Dump (force);
+         }
+      }
+
+      private int Depth {
+       get { return (Parent == null ? 0 : Parent.Depth + 1); }
+      }
+
+      public void DumpNested (bool force)
+      {
+       DumpNested ("", force);
+      }
+
+      public void DumpNested (string indent, bool force)
+      {
+       if (force || M17N.debug)
+         {
+           int indent_type = (Parent == null ? 1
+                              : Parent.Left == this ? 0 : 2);
+
+           update_from_to ();
+           if (Left != null)
+             {
+               if (indent_type <= 1)
+                 Left.DumpNested (indent + "  ", force);
+               else
+                 Left.DumpNested (indent + "| ", force);
+             }
+           if (indent_type == 0)
+             Console.Write (indent + ".-");
+           else if (indent_type == 2)
+             Console.Write (indent + "`-");
+           DumpOne (true, true, true);
+           if (Right != null)
+             {
+               if (indent_type >= 1)
+                 Right.DumpNested (indent + "  ", force);
+               else
+                 Right.DumpNested (indent + "| ", force);
+             }
+         }
       }
     }