]> Pileus Git - ~andy/gtk/blobdiff - gtk/gtktextbtree.c
Make PLT-reduction work with gcc4, and don't include everything in
[~andy/gtk] / gtk / gtktextbtree.c
index 3e9d1648fb380f60043c2ee84cb7c290dae09ad8..ac5a9fc9043f4f4b7e0cd6ec3824b36b6ce73c40 100644 (file)
  *
  */
 
+#define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
+#include <config.h>
 #include "gtktextbtree.h"
 #include <string.h>
-#include <ctype.h>
 #include <stdlib.h>
 #include <stdio.h>
-#include "gtksignal.h"
 #include "gtktexttag.h"
 #include "gtktexttagtable.h"
 #include "gtktextlayout.h"
 #include "gtktextiterprivate.h"
 #include "gtkdebug.h"
 #include "gtktextmarkprivate.h"
+#include "gtkalias.h"
 
 /*
  * Types
@@ -100,10 +101,15 @@ struct _NodeData {
 
   /* Height and width of this node */
   gint height;
-  gint width : 24;
+  signed int width : 24;
 
-  /* boolean indicating whether the height/width need to be recomputed */
-  gint valid : 8;
+  /* boolean indicating whether the lines below this node are in need of validation.
+   * However, width/height should always represent the current total width and
+   * max height for lines below this node; the valid flag indicates whether the
+   * width/height on the lines needs recomputing, not whether the totals
+   * need recomputing.
+   */
+  guint valid : 8;             /* Actually a boolean */
 };
 
 
@@ -177,25 +183,35 @@ struct _GtkTextBTree {
   GtkTextBuffer *buffer;
   BTreeView *views;
   GSList *tag_infos;
-  guint tag_changed_handler;
-  guint tag_removed_handler;
+  gulong tag_changed_handler;
+
   /* Incremented when a segment with a byte size > 0
-     is added to or removed from the tree (i.e. the
-     length of a line may have changed, and lines may
-     have been added or removed). This invalidates
-     all outstanding iterators.
-  */
+   * is added to or removed from the tree (i.e. the
+   * length of a line may have changed, and lines may
+   * have been added or removed). This invalidates
+   * all outstanding iterators.
+   */
   guint chars_changed_stamp;
   /* Incremented when any segments are added or deleted;
-     this makes outstanding iterators recalculate their
-     pointed-to segment and segment offset.
-  */
+   * this makes outstanding iterators recalculate their
+   * pointed-to segment and segment offset.
+   */
   guint segments_changed_stamp;
 
-  GtkTextLine *end_iter_line;
+  /* Cache the last line in the buffer */
+  GtkTextLine *last_line;
+  guint last_line_stamp;
 
+  /* Cache the next-to-last line in the buffer,
+   * containing the end iterator
+   */
+  GtkTextLine *end_iter_line;
+  GtkTextLineSegment *end_iter_segment;
+  int end_iter_segment_byte_index;
+  int end_iter_segment_char_offset;
   guint end_iter_line_stamp;
-
+  guint end_iter_segment_stamp;
+  
   GHashTable *child_anchor_table;
 };
 
@@ -280,6 +296,8 @@ static void                  gtk_text_btree_node_remove_view         (BTreeView
                                                                       gpointer          view_id);
 static void                  gtk_text_btree_node_destroy             (GtkTextBTree     *tree,
                                                                       GtkTextBTreeNode *node);
+static void                  gtk_text_btree_node_free_empty          (GtkTextBTree *tree,
+                                                                      GtkTextBTreeNode *node);
 static NodeData         *    gtk_text_btree_node_ensure_data         (GtkTextBTreeNode *node,
                                                                       gpointer          view_id);
 static void                  gtk_text_btree_node_remove_data         (GtkTextBTreeNode *node,
@@ -297,9 +315,6 @@ static void tag_changed_cb        (GtkTextTagTable  *table,
                                    GtkTextTag       *tag,
                                    gboolean          size_changed,
                                    GtkTextBTree     *tree);
-static void tag_removed_cb        (GtkTextTagTable  *table,
-                                   GtkTextTag       *tag,
-                                   GtkTextBTree     *tree);
 static void cleanup_line          (GtkTextLine      *line);
 static void recompute_node_counts (GtkTextBTree     *tree,
                                    GtkTextBTreeNode *node);
@@ -347,7 +362,7 @@ chars_changed (GtkTextBTree *tree)
 
 GtkTextBTree*
 _gtk_text_btree_new (GtkTextTagTable *table,
-                    GtkTextBuffer *buffer)
+                     GtkTextBuffer *buffer)
 {
   GtkTextBTree *tree;
   GtkTextBTreeNode *root_node;
@@ -402,22 +417,21 @@ _gtk_text_btree_new (GtkTextTagTable *table,
   tree->chars_changed_stamp = g_random_int ();
   tree->segments_changed_stamp = g_random_int ();
 
+  tree->last_line_stamp = tree->chars_changed_stamp - 1;
+  tree->last_line = NULL;
+
   tree->end_iter_line_stamp = tree->chars_changed_stamp - 1;
+  tree->end_iter_segment_stamp = tree->segments_changed_stamp - 1;
   tree->end_iter_line = NULL;
+  tree->end_iter_segment_byte_index = 0;
+  tree->end_iter_segment_char_offset = 0;
+  
+  g_object_ref (tree->table);
 
-  g_object_ref (G_OBJECT (tree->table));
-
-  tree->tag_changed_handler = g_signal_connect_data (G_OBJECT (tree->table),
-                                                     "tag_changed",
-                                                     tag_changed_cb,
-                                                     tree,
-                                                     NULL, FALSE, FALSE);
-
-  tree->tag_removed_handler = g_signal_connect_data (G_OBJECT (tree->table),
-                                                     "tag_removed",
-                                                     tag_removed_cb,
-                                                     tree,
-                                                     NULL, FALSE, FALSE);
+  tree->tag_changed_handler = g_signal_connect (tree->table,
+                                               "tag_changed",
+                                               G_CALLBACK (tag_changed_cb),
+                                               tree);
 
   tree->mark_table = g_hash_table_new (g_str_hash, g_str_equal);
   tree->child_anchor_table = NULL;
@@ -458,8 +472,8 @@ _gtk_text_btree_new (GtkTextTagTable *table,
 
     seg->body.mark.not_deleteable = TRUE;
 
-    g_object_ref (G_OBJECT (tree->insert_mark));
-    g_object_ref (G_OBJECT (tree->selection_bound_mark));
+    g_object_ref (tree->insert_mark);
+    g_object_ref (tree->selection_bound_mark);
   }
 
   tree->refcount = 1;
@@ -476,16 +490,6 @@ _gtk_text_btree_ref (GtkTextBTree *tree)
   tree->refcount += 1;
 }
 
-static void
-mark_destroy_foreach (gpointer key, gpointer value, gpointer user_data)
-{
-  GtkTextLineSegment *seg = value;
-
-  g_return_if_fail (seg->body.mark.tree == NULL);
-
-  g_object_unref (G_OBJECT (seg->body.mark.obj));
-}
-
 void
 _gtk_text_btree_unref (GtkTextBTree *tree)
 {
@@ -495,24 +499,29 @@ _gtk_text_btree_unref (GtkTextBTree *tree)
   tree->refcount -= 1;
 
   if (tree->refcount == 0)
-    {
-      gtk_text_btree_node_destroy (tree, tree->root_node);
-
-      g_hash_table_foreach (tree->mark_table,
-                            mark_destroy_foreach,
-                            NULL);
-      g_hash_table_destroy (tree->mark_table);
-
-      g_object_unref (G_OBJECT (tree->insert_mark));
-      g_object_unref (G_OBJECT (tree->selection_bound_mark));
-
-      g_signal_handler_disconnect (G_OBJECT (tree->table),
+    {      
+      g_signal_handler_disconnect (tree->table,
                                    tree->tag_changed_handler);
 
-      g_signal_handler_disconnect (G_OBJECT (tree->table),
-                                   tree->tag_removed_handler);
-
-      g_object_unref (G_OBJECT (tree->table));
+      g_object_unref (tree->table);
+      tree->table = NULL;
+      
+      gtk_text_btree_node_destroy (tree, tree->root_node);
+      tree->root_node = NULL;
+      
+      g_assert (g_hash_table_size (tree->mark_table) == 0);
+      g_hash_table_destroy (tree->mark_table);
+      tree->mark_table = NULL;
+      if (tree->child_anchor_table != NULL) 
+       {
+         g_hash_table_destroy (tree->child_anchor_table);
+         tree->child_anchor_table = NULL;
+       }
+
+      g_object_unref (tree->insert_mark);
+      tree->insert_mark = NULL;
+      g_object_unref (tree->selection_bound_mark);
+      tree->selection_bound_mark = NULL;
 
       g_free (tree);
     }
@@ -547,9 +556,177 @@ _gtk_text_btree_segments_changed (GtkTextBTree *tree)
  * Indexable segment mutation
  */
 
+/*
+ *  The following function is responsible for resolving the bidi direction
+ *  for the lines between start and end. But it also calculates any
+ *  dependent bidi direction for surrounding lines that change as a result
+ *  of the bidi direction decisions within the range. The function is
+ *  trying to do as little propagation as is needed.
+ */
+static void
+gtk_text_btree_resolve_bidi (GtkTextIter *start,
+                            GtkTextIter *end)
+{
+  GtkTextBTree *tree = _gtk_text_iter_get_btree (start);
+  GtkTextLine *start_line, *end_line, *start_line_prev, *end_line_next, *line;
+  PangoDirection last_strong, dir_above_propagated, dir_below_propagated;
+
+  /* Resolve the strong bidi direction for all lines between
+   * start and end.
+  */
+  start_line = _gtk_text_iter_get_text_line (start);
+  start_line_prev = _gtk_text_line_previous (start_line);
+  end_line = _gtk_text_iter_get_text_line (end);
+  end_line_next = _gtk_text_line_next (end_line);
+  
+  line = start_line;
+  while (line && line != end_line_next)
+    {
+      /* Loop through the segments and search for a strong character
+       */
+      GtkTextLineSegment *seg = line->segments;
+      line->dir_strong = PANGO_DIRECTION_NEUTRAL;
+      
+      while (seg)
+        {
+          if (seg->byte_count > 0)
+            {
+             PangoDirection pango_dir;
+
+              pango_dir = pango_find_base_dir (seg->body.chars,
+                                              seg->byte_count);
+             
+              if (pango_dir != PANGO_DIRECTION_NEUTRAL)
+                {
+                  line->dir_strong = pango_dir;
+                  break;
+                }
+            }
+          seg = seg->next;
+        }
+
+      line = _gtk_text_line_next (line);
+    }
+
+  /* Sweep forward */
+
+  /* The variable dir_above_propagated contains the forward propagated
+   * direction before start. It is neutral if start is in the beginning
+   * of the buffer.
+   */
+  dir_above_propagated = PANGO_DIRECTION_NEUTRAL;
+  if (start_line_prev)
+    dir_above_propagated = start_line_prev->dir_propagated_forward;
+
+  /* Loop forward and propagate the direction of each paragraph 
+   * to all neutral lines.
+   */
+  line = start_line;
+  last_strong = dir_above_propagated;
+  while (line != end_line_next)
+    {
+      if (line->dir_strong != PANGO_DIRECTION_NEUTRAL)
+        last_strong = line->dir_strong;
+      
+      line->dir_propagated_forward = last_strong;
+      
+      line = _gtk_text_line_next (line);
+    }
+
+  /* Continue propagating as long as the previous resolved forward
+   * is different from last_strong.
+   */
+  {
+    GtkTextIter end_propagate;
+    
+    while (line &&
+          line->dir_strong == PANGO_DIRECTION_NEUTRAL &&
+          line->dir_propagated_forward != last_strong)
+      {
+        GtkTextLine *prev = line;
+        line->dir_propagated_forward = last_strong;
+        
+        line = _gtk_text_line_next(line);
+        if (!line)
+          {
+            line = prev;
+            break;
+          }
+      }
+
+    /* The last line to invalidate is the last line before the
+     * line with the strong character. Or in case of the end of the
+     * buffer, the last line of the buffer. (There seems to be an
+     * extra "virtual" last line in the buffer that must not be used
+     * calling _gtk_text_btree_get_iter_at_line (causes crash). Thus the
+     * _gtk_text_line_previous is ok in that case as well.)
+     */
+    line = _gtk_text_line_previous (line);
+    _gtk_text_btree_get_iter_at_line (tree, &end_propagate, line, 0);
+    _gtk_text_btree_invalidate_region (tree, end, &end_propagate);
+  }
+  
+  /* Sweep backward */
+
+  /* The variable dir_below_propagated contains the backward propagated
+   * direction after end. It is neutral if end is at the end of
+   * the buffer.
+  */
+  dir_below_propagated = PANGO_DIRECTION_NEUTRAL;
+  if (end_line_next)
+    dir_below_propagated = end_line_next->dir_propagated_back;
+
+  /* Loop backward and propagate the direction of each paragraph 
+   * to all neutral lines.
+   */
+  line = end_line;
+  last_strong = dir_below_propagated;
+  while (line != start_line_prev)
+    {
+      if (line->dir_strong != PANGO_DIRECTION_NEUTRAL)
+        last_strong = line->dir_strong;
+
+      line->dir_propagated_back = last_strong;
+
+      line = _gtk_text_line_previous (line);
+    }
+
+  /* Continue propagating as long as the resolved backward dir
+   * is different from last_strong.
+   */
+  {
+    GtkTextIter start_propagate;
+
+    while (line &&
+          line->dir_strong == PANGO_DIRECTION_NEUTRAL &&
+          line->dir_propagated_back != last_strong)
+      {
+        GtkTextLine *prev = line;
+        line->dir_propagated_back = last_strong;
+
+        line = _gtk_text_line_previous (line);
+        if (!line)
+          {
+            line = prev;
+            break;
+          }
+      }
+
+    /* We only need to invalidate for backwards propagation if the
+     * line we ended up on didn't get a direction from forwards
+     * propagation.
+     */
+    if (line && line->dir_propagated_forward == PANGO_DIRECTION_NEUTRAL)
+      {
+        _gtk_text_btree_get_iter_at_line (tree, &start_propagate, line, 0);
+        _gtk_text_btree_invalidate_region(tree, &start_propagate, start);
+      }
+  }
+}
+
 void
 _gtk_text_btree_delete (GtkTextIter *start,
-                       GtkTextIter *end)
+                        GtkTextIter *end)
 {
   GtkTextLineSegment *prev_seg;             /* The segment just before the start
                                              * of the deletion range. */
@@ -569,68 +746,15 @@ _gtk_text_btree_delete (GtkTextIter *start,
   g_return_if_fail (_gtk_text_iter_get_btree (start) ==
                     _gtk_text_iter_get_btree (end));
 
-  gtk_text_iter_reorder (start, end);
+  gtk_text_iter_order (start, end);
 
   tree = _gtk_text_iter_get_btree (start);
-
-  {
-    /*
-     * The code below is ugly, but it's needed to make sure there
-     * is always a dummy empty line at the end of the text.  If the
-     * final newline of the file (just before the dummy line) is being
-     * deleted, then back up index to just before the newline.  If
-     * there is a newline just before the first character being deleted,
-     * then back up the first index too, so that an even number of lines
-     * gets deleted.  Furthermore, remove any tags that are present on
-     * the newline that isn't going to be deleted after all (this simulates
-     * deleting the newline and then adding a "clean" one back again).
-     */
-
-    gint line1;
-    gint line2;
-
-    line1 = gtk_text_iter_get_line (start);
-    line2 = gtk_text_iter_get_line (end);
-
-    if (line2 == _gtk_text_btree_line_count (tree))
-      {
-        GtkTextTag** tags;
-        int array_size;
-        GtkTextIter orig_end;
-
-        orig_end = *end;
-        gtk_text_iter_backward_char (end);
-
-        --line2;
-
-        if (gtk_text_iter_get_line_offset (start) == 0 &&
-            line1 != 0)
-          {
-            gtk_text_iter_backward_char (start);
-            --line1;
-          }
-
-        tags = _gtk_text_btree_get_tags (end,
-                                        &array_size);
-
-        if (tags != NULL)
-          {
-            int i;
-
-            i = 0;
-            while (i < array_size)
-              {
-                _gtk_text_btree_tag (end, &orig_end, tags[i], FALSE);
-
-                ++i;
-              }
-
-            g_free (tags);
-          }
-      }
-  }
-
+  if (gtk_debug_flags & GTK_DEBUG_TEXT)
+    _gtk_text_btree_check (tree);
+  
   /* Broadcast the need for redisplay before we break the iterators */
+  DV (g_print ("invalidating due to deleting some text (%s)\n", G_STRLOC));
   _gtk_text_btree_invalidate_region (tree, start, end);
 
   /* Save the byte offset so we can reset the iterators */
@@ -701,6 +825,9 @@ _gtk_text_btree_delete (GtkTextIter *start,
               for (node = curnode; node != NULL;
                    node = node->parent)
                 {
+                  /* Don't update node->num_chars, because
+                   * that was done when we deleted the segments.
+                   */
                   node->num_lines -= 1;
                 }
 
@@ -736,7 +863,7 @@ _gtk_text_btree_delete (GtkTextIter *start,
                   prevnode->next = curnode->next;
                 }
               parent->num_children--;
-              g_free (curnode);
+              gtk_text_btree_node_free_empty (tree, curnode);
               curnode = parent;
             }
           curnode = curline->parent;
@@ -746,7 +873,7 @@ _gtk_text_btree_delete (GtkTextIter *start,
       next = seg->next;
       char_count = seg->char_count;
 
-      if ((*seg->type->deleteFunc)(seg, curline, 0) != 0)
+      if ((*seg->type->deleteFunc)(seg, curline, FALSE) != 0)
         {
           /*
            * This segment refuses to die.  Move it to prev_seg and
@@ -791,21 +918,32 @@ _gtk_text_btree_delete (GtkTextIter *start,
     {
       BTreeView *view;
       GtkTextBTreeNode *ancestor_node;
-
       GtkTextLine *prevline;
+      int chars_moved;      
 
+      /* last_seg was appended to start_line up at the top of this function */
+      chars_moved = 0;
       for (seg = last_seg; seg != NULL;
            seg = seg->next)
         {
+          chars_moved += seg->char_count;
           if (seg->type->lineChangeFunc != NULL)
             {
               (*seg->type->lineChangeFunc)(seg, end_line);
             }
         }
+
+      for (node = start_line->parent; node != NULL;
+           node = node->parent)
+        {
+          node->num_chars += chars_moved;
+        }
+      
       curnode = end_line->parent;
       for (node = curnode; node != NULL;
            node = node->parent)
         {
+          node->num_chars -= chars_moved;
           node->num_lines--;
         }
       curnode->num_children--;
@@ -860,15 +998,21 @@ _gtk_text_btree_delete (GtkTextIter *start,
           if (deleted_width > 0 || deleted_height > 0)
             {
               ld = _gtk_text_line_get_data (start_line, view->view_id);
-
-              /* FIXME: ld is _NOT_ necessarily non-null here, but there is currently
-               * no way to add ld without also validating the node, which would
-               * be improper at this point.
-               */
-              /* This assertion does actually fail sometimes, must
-                 fix before stable release -hp */
-              g_assert (ld);
-
+              
+              if (ld == NULL)
+                {
+                  /* This means that start_line has never been validated.
+                   * We don't really want to do the validation here but
+                   * we do need to store our temporary sizes. So we
+                   * create the line data and assume a line w/h of 0.
+                   */
+                  ld = _gtk_text_line_data_new (view->layout, start_line);
+                  _gtk_text_line_add_data (start_line, ld);
+                  ld->width = 0;
+                  ld->height = 0;
+                  ld->valid = FALSE;
+                }
+              
               ld->width = MAX (deleted_width, ld->width);
               ld->height += deleted_height;
               ld->valid = FALSE;
@@ -881,6 +1025,9 @@ _gtk_text_btree_delete (GtkTextIter *start,
           view = view->next;
         }
 
+      /* avoid dangling pointer */
+      deleted_lines = NULL;
+      
       gtk_text_btree_rebalance (tree, curnode);
     }
 
@@ -907,12 +1054,14 @@ _gtk_text_btree_delete (GtkTextIter *start,
   /* Re-initialize our iterators */
   _gtk_text_btree_get_iter_at_line (tree, start, start_line, start_byte_offset);
   *end = *start;
+
+  gtk_text_btree_resolve_bidi (start, end);
 }
 
 void
 _gtk_text_btree_insert (GtkTextIter *iter,
-                       const gchar *text,
-                       gint len)
+                        const gchar *text,
+                        gint         len)
 {
   GtkTextLineSegment *prev_seg;     /* The segment just before the first
                                      * new segment (NULL means new segment
@@ -949,18 +1098,21 @@ _gtk_text_btree_insert (GtkTextIter *iter,
   /* extract iterator info */
   tree = _gtk_text_iter_get_btree (iter);
   line = _gtk_text_iter_get_text_line (iter);
+  
   start_line = line;
   start_byte_index = gtk_text_iter_get_line_index (iter);
 
-  /* Get our insertion segment split */
+  /* Get our insertion segment split. Note this assumes line allows
+   * char insertions, which isn't true of the "last" line. But iter
+   * should not be on that line, as we assert here.
+   */
+  g_assert (!_gtk_text_line_is_last (line, tree));
   prev_seg = gtk_text_line_segment_split (iter);
   cur_seg = prev_seg;
 
   /* Invalidate all iterators */
   chars_changed (tree);
   segments_changed (tree);
-
-  g_assert (g_utf8_validate (text, len, NULL));
   
   /*
    * Chop the text up into lines and create a new segment for
@@ -1063,12 +1215,15 @@ _gtk_text_btree_insert (GtkTextIter *iter,
        above. FIXME */
     gtk_text_iter_forward_chars (&end, char_count_delta);
 
+    DV (g_print ("invalidating due to inserting some text (%s)\n", G_STRLOC));
     _gtk_text_btree_invalidate_region (tree,
                                       &start, &end);
 
 
     /* Convenience for the user */
     *iter = end;
+
+    gtk_text_btree_resolve_bidi (&start, &end);
   }
 }
 
@@ -1111,6 +1266,7 @@ insert_pixbuf_or_widget_segment (GtkTextIter        *iter,
   *iter = start;
   gtk_text_iter_forward_char (iter); /* skip forward past the segment */
 
+  DV (g_print ("invalidating due to inserting pixbuf/widget (%s)\n", G_STRLOC));
   _gtk_text_btree_invalidate_region (tree, &start, iter);
 }
      
@@ -1125,15 +1281,23 @@ _gtk_text_btree_insert_pixbuf (GtkTextIter *iter,
   insert_pixbuf_or_widget_segment (iter, seg);
 }
 
-GtkTextChildAnchor*
-_gtk_text_btree_create_child_anchor (GtkTextIter *iter)
+void
+_gtk_text_btree_insert_child_anchor (GtkTextIter        *iter,
+                                     GtkTextChildAnchor *anchor)
 {
   GtkTextLineSegment *seg;
   GtkTextBTree *tree;
+
+  if (anchor->segment != NULL)
+    {
+      g_warning (G_STRLOC": Same child anchor can't be inserted twice");
+      return;
+    }
   
-  seg = _gtk_widget_segment_new ();
+  seg = _gtk_widget_segment_new (anchor);
 
   tree = seg->body.child.tree = _gtk_text_iter_get_btree (iter);
+  seg->body.child.line = _gtk_text_iter_get_text_line (iter);
   
   insert_pixbuf_or_widget_segment (iter, seg);
 
@@ -1143,8 +1307,6 @@ _gtk_text_btree_create_child_anchor (GtkTextIter *iter)
   g_hash_table_insert (tree->child_anchor_table,
                        seg->body.child.obj,
                        seg->body.child.obj);
-  
-  return seg->body.child.obj;
 }
 
 void
@@ -1358,7 +1520,7 @@ _gtk_text_btree_add_view (GtkTextBTree *tree,
   GtkTextLineData *line_data;
 
   g_return_if_fail (tree != NULL);
-
+  
   view = g_new (BTreeView, 1);
 
   view->view_id = layout;
@@ -1367,6 +1529,12 @@ _gtk_text_btree_add_view (GtkTextBTree *tree,
   view->next = tree->views;
   view->prev = NULL;
 
+  if (tree->views)
+    {
+      g_assert (tree->views->prev == NULL);
+      tree->views->prev = view;
+    }
+  
   tree->views = view;
 
   /* The last line in the buffer has identity values for the per-view
@@ -1387,14 +1555,14 @@ _gtk_text_btree_add_view (GtkTextBTree *tree,
 
 void
 _gtk_text_btree_remove_view (GtkTextBTree *tree,
-                            gpointer view_id)
+                             gpointer      view_id)
 {
   BTreeView *view;
   GtkTextLine *last_line;
   GtkTextLineData *line_data;
 
   g_return_if_fail (tree != NULL);
-
+  
   view = tree->views;
 
   while (view != NULL)
@@ -1425,13 +1593,16 @@ _gtk_text_btree_remove_view (GtkTextBTree *tree,
 
   gtk_text_btree_node_remove_view (view, tree->root_node, view_id);
 
+  view->layout = (gpointer) 0xdeadbeef;
+  view->view_id = (gpointer) 0xdeadbeef;
+  
   g_free (view);
 }
 
 void
-_gtk_text_btree_invalidate_region (GtkTextBTree *tree,
-                                  const GtkTextIter *start,
-                                  const GtkTextIter *end)
+_gtk_text_btree_invalidate_region (GtkTextBTree      *tree,
+                                   const GtkTextIter *start,
+                                   const GtkTextIter *end)
 {
   BTreeView *view;
 
@@ -1541,6 +1712,7 @@ queue_tag_redisplay (GtkTextBTree      *tree,
 {
   if (_gtk_text_tag_affects_size (tag))
     {
+      DV (g_print ("invalidating due to size-affecting tag (%s)\n", G_STRLOC));
       _gtk_text_btree_invalidate_region (tree, start, end);
     }
   else if (_gtk_text_tag_affects_nonsize_appearance (tag))
@@ -1554,9 +1726,9 @@ queue_tag_redisplay (GtkTextBTree      *tree,
 
 void
 _gtk_text_btree_tag (const GtkTextIter *start_orig,
-                    const GtkTextIter *end_orig,
-                    GtkTextTag *tag,
-                    gboolean add)
+                     const GtkTextIter *end_orig,
+                     GtkTextTag        *tag,
+                     gboolean           add)
 {
   GtkTextLineSegment *seg, *prev;
   GtkTextLine *cleanupline;
@@ -1574,7 +1746,8 @@ _gtk_text_btree_tag (const GtkTextIter *start_orig,
   g_return_if_fail (GTK_IS_TEXT_TAG (tag));
   g_return_if_fail (_gtk_text_iter_get_btree (start_orig) ==
                     _gtk_text_iter_get_btree (end_orig));
-
+  g_return_if_fail (tag->table == _gtk_text_iter_get_btree (start_orig)->table);
+  
 #if 0
   printf ("%s tag %s from %d to %d\n",
           add ? "Adding" : "Removing",
@@ -1589,7 +1762,7 @@ _gtk_text_btree_tag (const GtkTextIter *start_orig,
   start = *start_orig;
   end = *end_orig;
 
-  gtk_text_iter_reorder (&start, &end);
+  gtk_text_iter_order (&start, &end);
 
   tree = _gtk_text_iter_get_btree (&start);
 
@@ -1606,8 +1779,11 @@ _gtk_text_btree_tag (const GtkTextIter *start_orig,
      with the tree. */
   stack = iter_stack_new ();
   iter = start;
-  /* We don't want to delete a toggle that's at the start iterator. */
-  gtk_text_iter_forward_char (&iter);
+
+  /* forward_to_tag_toggle() skips a toggle at the start iterator,
+   * which is deliberate - we don't want to delete a toggle at the
+   * start.
+   */
   while (gtk_text_iter_forward_to_tag_toggle (&iter, tag))
     {
       if (gtk_text_iter_compare (&iter, &end) >= 0)
@@ -1685,7 +1861,7 @@ _gtk_text_btree_tag (const GtkTextIter *start_orig,
           g_assert (seg != NULL);
           g_assert (indexable_seg != NULL);
           g_assert (seg != indexable_seg);
-
+          
           if ( (seg->type == &gtk_text_toggle_on_type ||
                 seg->type == &gtk_text_toggle_off_type) &&
                (seg->body.toggle.info == info) )
@@ -1808,10 +1984,11 @@ _gtk_text_btree_tag (const GtkTextIter *start_orig,
  * "Getters"
  */
 
-GtkTextLine*
-_gtk_text_btree_get_line (GtkTextBTree *tree,
-                         gint  line_number,
-                         gint *real_line_number)
+static GtkTextLine*
+get_line_internal (GtkTextBTree *tree,
+                   gint          line_number,
+                   gint         *real_line_number,
+                   gboolean      include_last)
 {
   GtkTextBTreeNode *node;
   GtkTextLine *line;
@@ -1819,7 +1996,9 @@ _gtk_text_btree_get_line (GtkTextBTree *tree,
   int line_count;
 
   line_count = _gtk_text_btree_line_count (tree);
-
+  if (!include_last)
+    line_count -= 1;
+  
   if (line_number < 0)
     {
       line_number = line_count;
@@ -1874,11 +2053,36 @@ _gtk_text_btree_get_line (GtkTextBTree *tree,
   return line;
 }
 
+GtkTextLine*
+_gtk_text_btree_get_end_iter_line (GtkTextBTree *tree)
+{
+  return
+    _gtk_text_btree_get_line (tree,
+                              _gtk_text_btree_line_count (tree) - 1,
+                              NULL);
+}
+
+GtkTextLine*
+_gtk_text_btree_get_line (GtkTextBTree *tree,
+                          gint          line_number,
+                          gint         *real_line_number)
+{
+  return get_line_internal (tree, line_number, real_line_number, TRUE);
+}
+
+GtkTextLine*
+_gtk_text_btree_get_line_no_last (GtkTextBTree      *tree,
+                                  gint               line_number,
+                                  gint              *real_line_number)
+{
+  return get_line_internal (tree, line_number, real_line_number, FALSE);
+}
+
 GtkTextLine*
 _gtk_text_btree_get_line_at_char (GtkTextBTree      *tree,
-                                 gint                char_index,
-                                 gint               *line_start_index,
-                                 gint               *real_char_index)
+                                  gint               char_index,
+                                  gint              *line_start_index,
+                                  gint              *real_char_index)
 {
   GtkTextBTreeNode *node;
   GtkTextLine *line;
@@ -1889,10 +2093,13 @@ _gtk_text_btree_get_line_at_char (GtkTextBTree      *tree,
 
   node = tree->root_node;
 
-  /* Clamp to valid indexes (-1 is magic for "highest index") */
-  if (char_index < 0 || char_index >= node->num_chars)
+  /* Clamp to valid indexes (-1 is magic for "highest index"),
+   * node->num_chars includes the two newlines that aren't really
+   * in the buffer.
+   */
+  if (char_index < 0 || char_index >= (node->num_chars - 1))
     {
-      char_index = node->num_chars - 1;
+      char_index = node->num_chars - 2;
     }
 
   *real_char_index = char_index;
@@ -2176,9 +2383,9 @@ _gtk_text_btree_get_text (const GtkTextIter *start_orig,
   start = *start_orig;
   end = *end_orig;
 
-  gtk_text_iter_reorder (&start, &end);
+  gtk_text_iter_order (&start, &end);
 
-  retval = g_string_new ("");
+  retval = g_string_new (NULL);
 
   tree = _gtk_text_iter_get_btree (&start);
 
@@ -2213,8 +2420,10 @@ _gtk_text_btree_line_count (GtkTextBTree *tree)
 gint
 _gtk_text_btree_char_count (GtkTextBTree *tree)
 {
-  /* Exclude newline in bogus last line */
-  return tree->root_node->num_chars - 1;
+  /* Exclude newline in bogus last line and the
+   * one in the last line that is after the end iterator
+   */
+  return tree->root_node->num_chars - 2;
 }
 
 #define LOTSA_TAGS 1000
@@ -2241,7 +2450,7 @@ _gtk_text_btree_char_is_invisible (const GtkTextIter *iter)
   tree = _gtk_text_iter_get_btree (iter);
   byte_index = gtk_text_iter_get_line_index (iter);
 
-  numTags = gtk_text_tag_table_size (tree->table);
+  numTags = gtk_text_tag_table_get_size (tree->table);
 
   /* almost always avoid malloc, so stay out of system calls */
   if (LOTSA_TAGS < numTags)
@@ -2426,6 +2635,7 @@ redisplay_mark (GtkTextLineSegment *mark)
   end = iter;
   gtk_text_iter_forward_char (&end);
 
+  DV (g_print ("invalidating due to moving visible mark (%s)\n", G_STRLOC));
   _gtk_text_btree_invalidate_region (mark->body.mark.tree,
                                     &iter, &end);
 }
@@ -2604,7 +2814,7 @@ _gtk_text_btree_get_selection_bounds (GtkTextBTree *tree,
     }
   else
     {
-      gtk_text_iter_reorder (&tmp_start, &tmp_end);
+      gtk_text_iter_order (&tmp_start, &tmp_end);
 
       if (start)
         *start = tmp_start;
@@ -2619,6 +2829,14 @@ _gtk_text_btree_get_selection_bounds (GtkTextBTree *tree,
 void
 _gtk_text_btree_place_cursor (GtkTextBTree      *tree,
                              const GtkTextIter *iter)
+{
+  _gtk_text_btree_select_range (tree, iter, iter);
+}
+
+void
+_gtk_text_btree_select_range (GtkTextBTree      *tree,
+                             const GtkTextIter *ins,
+                              const GtkTextIter *bound)
 {
   GtkTextIter start, end;
 
@@ -2627,11 +2845,14 @@ _gtk_text_btree_place_cursor (GtkTextBTree      *tree,
 
   /* Move insert AND selection_bound before we redisplay */
   real_set_mark (tree, tree->insert_mark,
-                 "insert", FALSE, iter, TRUE, FALSE);
+                 "insert", FALSE, ins, TRUE, FALSE);
   real_set_mark (tree, tree->selection_bound_mark,
-                 "selection_bound", FALSE, iter, TRUE, FALSE);
+                 "selection_bound", FALSE, bound, TRUE, FALSE);
+
+  redisplay_region (tree, ins, bound);
 }
 
+
 void
 _gtk_text_btree_remove_mark_by_name (GtkTextBTree *tree,
                                     const gchar *name)
@@ -2647,9 +2868,26 @@ _gtk_text_btree_remove_mark_by_name (GtkTextBTree *tree,
   _gtk_text_btree_remove_mark (tree, mark);
 }
 
+void
+_gtk_text_btree_release_mark_segment (GtkTextBTree       *tree,
+                                      GtkTextLineSegment *segment)
+{
+
+  if (segment->body.mark.name)
+    g_hash_table_remove (tree->mark_table, segment->body.mark.name);
+
+  segment->body.mark.tree = NULL;
+  segment->body.mark.line = NULL;
+  
+  /* Remove the ref on the mark, which frees segment as a side effect
+   * if this is the last reference.
+   */
+  g_object_unref (segment->body.mark.obj);
+}
+
 void
 _gtk_text_btree_remove_mark (GtkTextBTree *tree,
-                            GtkTextMark *mark)
+                             GtkTextMark *mark)
 {
   GtkTextLineSegment *segment;
 
@@ -2666,34 +2904,27 @@ _gtk_text_btree_remove_mark (GtkTextBTree *tree,
 
   /* This calls cleanup_line and segments_changed */
   gtk_text_btree_unlink_segment (tree, segment, segment->body.mark.line);
-
-  if (segment->body.mark.name)
-    g_hash_table_remove (tree->mark_table, segment->body.mark.name);
-
-  /* Remove the ref on the mark that belonged to the segment. */
-  g_object_unref (G_OBJECT (mark));
-
-  segment->body.mark.tree = NULL;
-  segment->body.mark.line = NULL;
+  
+  _gtk_text_btree_release_mark_segment (tree, segment);
 }
 
 gboolean
 _gtk_text_btree_mark_is_insert (GtkTextBTree *tree,
-                               GtkTextMark *segment)
+                                GtkTextMark *segment)
 {
   return segment == tree->insert_mark;
 }
 
 gboolean
 _gtk_text_btree_mark_is_selection_bound (GtkTextBTree *tree,
-                                        GtkTextMark *segment)
+                                         GtkTextMark *segment)
 {
   return segment == tree->selection_bound_mark;
 }
 
 GtkTextMark*
 _gtk_text_btree_get_mark_by_name (GtkTextBTree *tree,
-                                 const gchar *name)
+                                  const gchar *name)
 {
   GtkTextLineSegment *seg;
 
@@ -2705,6 +2936,18 @@ _gtk_text_btree_get_mark_by_name (GtkTextBTree *tree,
   return seg ? seg->body.mark.obj : NULL;
 }
 
+/**
+ * gtk_text_mark_set_visible:
+ * @mark: a #GtkTextMark
+ * @setting: visibility of mark
+ * 
+ * Sets the visibility of @mark; the insertion point is normally
+ * visible, i.e. you can see it as a vertical bar. Also, the text
+ * widget uses a visible mark to indicate where a drop will occur when
+ * dragging-and-dropping text. Most other marks are not visible.
+ * Marks are not visible by default.
+ * 
+ **/
 void
 gtk_text_mark_set_visible (GtkTextMark       *mark,
                            gboolean           setting)
@@ -2837,7 +3080,7 @@ _gtk_text_btree_last_could_contain_tag (GtkTextBTree *tree,
          at least not without complexity.
          So, we just return the last line.
       */
-      return _gtk_text_btree_get_line (tree, -1, NULL);
+      return _gtk_text_btree_get_end_iter_line (tree);
     }
 }
 
@@ -3033,9 +3276,9 @@ find_toggle_outside_current_line (GtkTextLine *line,
 /* FIXME this function is far too slow, for no good reason. */
 gboolean
 _gtk_text_line_char_has_tag (GtkTextLine *line,
-                            GtkTextBTree *tree,
-                            gint char_in_line,
-                            GtkTextTag *tag)
+                             GtkTextBTree *tree,
+                             gint char_in_line,
+                             GtkTextTag *tag)
 {
   GtkTextLineSegment *toggle_seg;
 
@@ -3057,9 +3300,9 @@ _gtk_text_line_char_has_tag (GtkTextLine *line,
 
 gboolean
 _gtk_text_line_byte_has_tag (GtkTextLine *line,
-                            GtkTextBTree *tree,
-                            gint byte_in_line,
-                            GtkTextTag *tag)
+                             GtkTextBTree *tree,
+                             gint byte_in_line,
+                             GtkTextTag *tag)
 {
   GtkTextLineSegment *toggle_seg;
 
@@ -3081,11 +3324,96 @@ _gtk_text_line_byte_has_tag (GtkTextLine *line,
 
 gboolean
 _gtk_text_line_is_last (GtkTextLine *line,
-                       GtkTextBTree *tree)
+                        GtkTextBTree *tree)
 {
   return line == get_last_line (tree);
 }
 
+static void
+ensure_end_iter_line (GtkTextBTree *tree)
+{
+  if (tree->end_iter_line_stamp != tree->chars_changed_stamp)
+    {
+      int n_lines;
+      int real_line;
+
+      /* n_lines is without the magic line at the end */
+      n_lines = _gtk_text_btree_line_count (tree);
+      g_assert (n_lines >= 1);
+
+      tree->end_iter_line = _gtk_text_btree_get_line_no_last (tree, -1, &real_line);
+      
+      tree->end_iter_line_stamp = tree->chars_changed_stamp;
+    }
+}
+
+static void
+ensure_end_iter_segment (GtkTextBTree *tree)
+{
+  if (tree->end_iter_segment_stamp != tree->segments_changed_stamp)
+    {
+      GtkTextLineSegment *seg;
+      GtkTextLineSegment *last_with_chars;
+
+      ensure_end_iter_line (tree);
+
+      last_with_chars = NULL;
+      
+      seg = tree->end_iter_line->segments;
+      while (seg != NULL)
+        {
+          if (seg->char_count > 0)
+            last_with_chars = seg;
+          seg = seg->next;
+        }
+
+      tree->end_iter_segment = last_with_chars;
+
+      /* We know the last char in the last line is '\n' */
+      tree->end_iter_segment_byte_index = last_with_chars->byte_count - 1;
+      tree->end_iter_segment_char_offset = last_with_chars->char_count - 1;
+      
+      tree->end_iter_segment_stamp = tree->segments_changed_stamp;
+
+      g_assert (tree->end_iter_segment->type == &gtk_text_char_type);
+      g_assert (tree->end_iter_segment->body.chars[tree->end_iter_segment_byte_index] == '\n');
+    }
+}
+
+gboolean
+_gtk_text_line_contains_end_iter (GtkTextLine  *line,
+                                  GtkTextBTree *tree)
+{
+  ensure_end_iter_line (tree);
+
+  return line == tree->end_iter_line;
+}
+
+gboolean
+_gtk_text_btree_is_end (GtkTextBTree       *tree,
+                        GtkTextLine        *line,
+                        GtkTextLineSegment *seg,
+                        int                 byte_index,
+                        int                 char_offset)
+{
+  g_return_val_if_fail (byte_index >= 0 || char_offset >= 0, FALSE);
+  
+  /* Do this first to avoid walking segments in most cases */
+  if (!_gtk_text_line_contains_end_iter (line, tree))
+    return FALSE;
+
+  ensure_end_iter_segment (tree);
+
+  if (seg != tree->end_iter_segment)
+    return FALSE;
+
+  if (byte_index >= 0)
+    return byte_index == tree->end_iter_segment_byte_index;
+  else
+    return char_offset == tree->end_iter_segment_char_offset;
+}
+
 GtkTextLine*
 _gtk_text_line_next (GtkTextLine *line)
 {
@@ -3121,6 +3449,23 @@ _gtk_text_line_next (GtkTextLine *line)
     }
 }
 
+GtkTextLine*
+_gtk_text_line_next_excluding_last (GtkTextLine *line)
+{
+  GtkTextLine *next;
+  
+  next = _gtk_text_line_next (line);
+
+  /* If we were on the end iter line, we can't go to
+   * the last line
+   */
+  if (next && next->next == NULL && /* these checks are optimization only */
+      _gtk_text_line_next (next) == NULL)
+    return NULL;
+
+  return next;
+}
+
 GtkTextLine*
 _gtk_text_line_previous (GtkTextLine *line)
 {
@@ -3178,9 +3523,27 @@ _gtk_text_line_previous (GtkTextLine *line)
   return NULL;
 }
 
+
+GtkTextLineData*
+_gtk_text_line_data_new (GtkTextLayout *layout,
+                         GtkTextLine   *line)
+{
+  GtkTextLineData *line_data;
+
+  line_data = g_new (GtkTextLineData, 1);
+
+  line_data->view_id = layout;
+  line_data->next = NULL;
+  line_data->width = 0;
+  line_data->height = 0;
+  line_data->valid = FALSE;
+
+  return line_data;
+}
+
 void
 _gtk_text_line_add_data (GtkTextLine     *line,
-                        GtkTextLineData *data)
+                         GtkTextLineData *data)
 {
   g_return_if_fail (line != NULL);
   g_return_if_fail (data != NULL);
@@ -3232,7 +3595,7 @@ _gtk_text_line_remove_data (GtkTextLine *line,
 
 gpointer
 _gtk_text_line_get_data (GtkTextLine *line,
-                        gpointer view_id)
+                         gpointer view_id)
 {
   GtkTextLineData *iter;
 
@@ -3899,9 +4262,9 @@ node_compare (GtkTextBTreeNode *lhs,
 
 /* remember that tag == NULL means "any tag" */
 GtkTextLine*
-_gtk_text_line_next_could_contain_tag (GtkTextLine *line,
-                                      GtkTextBTree *tree,
-                                      GtkTextTag  *tag)
+_gtk_text_line_next_could_contain_tag (GtkTextLine  *line,
+                                       GtkTextBTree *tree,
+                                       GtkTextTag   *tag)
 {
   GtkTextBTreeNode *node;
   GtkTextTagInfo *info;
@@ -3917,17 +4280,17 @@ _gtk_text_line_next_could_contain_tag (GtkTextLine *line,
       /* Right now we can only offer linear-search if the user wants
        * to know about any tag toggle at all.
        */
-      return _gtk_text_line_next (line);
+      return _gtk_text_line_next_excluding_last (line);
     }
 
   /* Our tag summaries only have node precision, not line
-     precision. This means that if any line under a node could contain a
-     tag, then any of the others could also contain a tag.
-
-     In the future we could have some mechanism to keep track of how
-     many toggles we've found under a node so far, since we have a
-     count of toggles under the node. But for now I'm going with KISS.
-  */
+   * precision. This means that if any line under a node could contain a
+   * tag, then any of the others could also contain a tag.
+   * 
+   * In the future we could have some mechanism to keep track of how
+   * many toggles we've found under a node so far, since we have a
+   * count of toggles under the node. But for now I'm going with KISS.
+   */
 
   /* return same-node line, if any. */
   if (line->next)
@@ -4127,9 +4490,7 @@ _gtk_text_line_previous_could_contain_tag (GtkTextLine  *line,
       line_ancestor = line->parent;
       line_ancestor_parent = line->parent->parent;
 
-      node = line_ancestor_parent->children.node;
-      while (node != line_ancestor &&
-             line_ancestor != info->tag_root)
+      while (line_ancestor != info->tag_root)
         {
           GSList *child_nodes = NULL;
           GSList *tmp;
@@ -4137,8 +4498,12 @@ _gtk_text_line_previous_could_contain_tag (GtkTextLine  *line,
           /* Create reverse-order list of nodes before
            * line_ancestor
            */
-          while (node != line_ancestor
-                 && node != NULL)
+          if (line_ancestor_parent != NULL)
+           node = line_ancestor_parent->children.node;
+         else
+           node = line_ancestor;
+
+          while (node != line_ancestor && node != NULL)
             {
               child_nodes = g_slist_prepend (child_nodes, node);
 
@@ -4168,8 +4533,6 @@ _gtk_text_line_previous_could_contain_tag (GtkTextLine  *line,
           /* Didn't find anything on this level; go up one level. */
           line_ancestor = line_ancestor_parent;
           line_ancestor_parent = line_ancestor->parent;
-
-          node = line_ancestor_parent->children.node;
         }
 
       /* No dice. */
@@ -4279,7 +4642,7 @@ summary_list_destroy (Summary *summary)
 static GtkTextLine*
 get_last_line (GtkTextBTree *tree)
 {
-  if (tree->end_iter_line_stamp != tree->chars_changed_stamp)
+  if (tree->last_line_stamp != tree->chars_changed_stamp)
     {
       gint n_lines;
       GtkTextLine *line;
@@ -4291,11 +4654,11 @@ get_last_line (GtkTextBTree *tree)
 
       line = _gtk_text_btree_get_line (tree, n_lines, &real_line);
 
-      tree->end_iter_line_stamp = tree->chars_changed_stamp;
-      tree->end_iter_line = line;
+      tree->last_line_stamp = tree->chars_changed_stamp;
+      tree->last_line = line;
     }
 
-  return tree->end_iter_line;
+  return tree->last_line;
 }
 
 /*
@@ -4308,6 +4671,9 @@ gtk_text_line_new (void)
   GtkTextLine *line;
 
   line = g_new0(GtkTextLine, 1);
+  line->dir_strong = PANGO_DIRECTION_NEUTRAL;
+  line->dir_propagated_forward = PANGO_DIRECTION_NEUTRAL;
+  line->dir_propagated_back = PANGO_DIRECTION_NEUTRAL;
 
   return line;
 }
@@ -4390,7 +4756,7 @@ static NodeData*
 node_data_new (gpointer view_id)
 {
   NodeData *nd;
-
+  
   nd = g_new (NodeData, 1);
 
   nd->view_id = view_id;
@@ -4405,7 +4771,6 @@ node_data_new (gpointer view_id)
 static void
 node_data_destroy (NodeData *nd)
 {
-
   g_free (nd);
 }
 
@@ -5071,14 +5436,7 @@ gtk_text_btree_node_destroy (GtkTextBTree *tree, GtkTextBTreeNode *node)
               seg = line->segments;
               line->segments = seg->next;
 
-              if (GTK_IS_TEXT_MARK_SEGMENT (seg))
-                {
-                  /* Set the mark as deleted */
-                  seg->body.mark.tree = NULL;
-                  seg->body.mark.line = NULL;
-                }
-
-              (*seg->type->deleteFunc) (seg, line, 1);
+              (*seg->type->deleteFunc) (seg, line, TRUE);
             }
           gtk_text_line_destroy (tree, line);
         }
@@ -5095,6 +5453,16 @@ gtk_text_btree_node_destroy (GtkTextBTree *tree, GtkTextBTreeNode *node)
         }
     }
 
+  gtk_text_btree_node_free_empty (tree, node);
+}
+
+static void
+gtk_text_btree_node_free_empty (GtkTextBTree *tree,
+                                GtkTextBTreeNode *node)
+{
+  g_return_if_fail ((node->level > 0 && node->children.node == NULL) ||
+                    (node->level == 0 && node->children.line == NULL));
+
   summary_list_destroy (node->summary);
   node_data_list_destroy (node->node_data);
   g_free (node);
@@ -5114,14 +5482,15 @@ gtk_text_btree_node_ensure_data (GtkTextBTreeNode *node, gpointer view_id)
       nd = nd->next;
     }
 
-  if (nd == NULL)    {
-    nd = node_data_new (view_id);
-
-    if (node->node_data)
-      nd->next = node->node_data;
-
-    node->node_data = nd;
-  }
+  if (nd == NULL)
+    {
+      nd = node_data_new (view_id);
+      
+      if (node->node_data)
+        nd->next = node->node_data;
+      
+      node->node_data = nd;
+    }
 
   return nd;
 }
@@ -5222,7 +5591,7 @@ get_tree_bounds (GtkTextBTree *tree,
                  GtkTextIter *end)
 {
   _gtk_text_btree_get_iter_at_line_char (tree, start, 0, 0);
-  _gtk_text_btree_get_last_iter (tree, end);
+  _gtk_text_btree_get_end_iter (tree, end);
 }
 
 static void
@@ -5244,6 +5613,7 @@ tag_changed_cb (GtkTextTagTable *table,
         {
           /* Must be a last toggle if there was a first one. */
           _gtk_text_btree_get_iter_at_last_toggle (tree, &end, tag);
+          DV (g_print ("invalidating due to tag change (%s)\n", G_STRLOC));
           _gtk_text_btree_invalidate_region (tree,
                                             &start, &end);
 
@@ -5268,10 +5638,9 @@ tag_changed_cb (GtkTextTagTable *table,
     }
 }
 
-static void
-tag_removed_cb (GtkTextTagTable *table,
-                GtkTextTag *tag,
-                GtkTextBTree *tree)
+void
+_gtk_text_btree_notify_will_remove_tag (GtkTextBTree    *tree,
+                                        GtkTextTag      *tag)
 {
   /* Remove the tag from the tree */
 
@@ -5391,8 +5760,9 @@ gtk_text_btree_rebalance (GtkTextBTree *tree,
                 {
                   tree->root_node = node->children.node;
                   tree->root_node->parent = NULL;
-                  summary_list_destroy (node->summary);
-                  g_free (node);
+
+                  node->children.node = NULL;
+                  gtk_text_btree_node_free_empty (tree, node);
                 }
               return;
             }
@@ -5496,8 +5866,10 @@ gtk_text_btree_rebalance (GtkTextBTree *tree,
               recompute_node_counts (tree, node);
               node->next = other->next;
               node->parent->num_children--;
-              summary_list_destroy (other->summary);
-              g_free (other);
+
+              other->children.node = NULL;
+              other->children.line = NULL;
+              gtk_text_btree_node_free_empty (tree, other);
               continue;
             }
 
@@ -5593,11 +5965,17 @@ gtk_text_btree_get_tag_info (GtkTextBTree *tree,
       info = g_new (GtkTextTagInfo, 1);
 
       info->tag = tag;
-      g_object_ref (G_OBJECT (tag));
+      g_object_ref (tag);
       info->tag_root = NULL;
       info->toggle_count = 0;
 
       tree->tag_infos = g_slist_prepend (tree->tag_infos, info);
+
+#if 0
+      g_print ("Created tag info %p for tag %s(%p)\n",
+               info, info->tag->name ? info->tag->name : "anon",
+               info->tag);
+#endif
     }
 
   return info;
@@ -5618,6 +5996,12 @@ gtk_text_btree_remove_tag_info (GtkTextBTree *tree,
       info = list->data;
       if (info->tag == tag)
         {
+#if 0
+          g_print ("Removing tag info %p for tag %s(%p)\n",
+                   info, info->tag->name ? info->tag->name : "anon",
+                   info->tag);
+#endif
+          
           if (prev != NULL)
             {
               prev->next = list->next;
@@ -5629,17 +6013,15 @@ gtk_text_btree_remove_tag_info (GtkTextBTree *tree,
           list->next = NULL;
           g_slist_free (list);
 
-          g_object_unref (G_OBJECT (info->tag));
+          g_object_unref (info->tag);
 
           g_free (info);
           return;
         }
 
+      prev = list;
       list = g_slist_next (list);
     }
-
-  g_assert_not_reached ();
-  return;
 }
 
 static void
@@ -5783,7 +6165,7 @@ recompute_node_counts (GtkTextBTree *tree, GtkTextBTreeNode *node)
       gtk_text_btree_node_check_valid (node, view->view_id);
       view = view->next;
     }
-
+  
   /*
    * Scan through the GtkTextBTreeNode's tag records again and delete any Summary
    * records that still have a zero count, or that have all the toggles.
@@ -6206,18 +6588,45 @@ _gtk_toggle_segment_check_func (GtkTextLineSegment *segPtr,
  */
 
 static void
-gtk_text_btree_node_view_check_consistency (GtkTextBTreeNode *node,
+gtk_text_btree_node_view_check_consistency (GtkTextBTree     *tree,
+                                            GtkTextBTreeNode *node,
                                             NodeData         *nd)
 {
   gint width;
   gint height;
   gboolean valid;
+  BTreeView *view;
+  
+  view = tree->views;
 
+  while (view != NULL)
+    {
+      if (view->view_id == nd->view_id)
+        break;
+
+      view = view->next;
+    }
+
+  if (view == NULL)
+    g_error ("Node has data for a view %p no longer attached to the tree",
+             nd->view_id);
+  
   gtk_text_btree_node_compute_view_aggregates (node, nd->view_id,
                                                &width, &height, &valid);
+
+  /* valid aggregate not checked the same as width/height, because on
+   * btree rebalance we can have invalid nodes where all lines below
+   * them are actually valid, due to moving lines around between
+   * nodes.
+   *
+   * The guarantee is that if there are invalid lines the node is
+   * invalid - we don't guarantee that if the node is invalid there
+   * are invalid lines.
+   */
+  
   if (nd->width != width ||
       nd->height != height ||
-      !nd->valid != !valid)
+      (nd->valid && !valid))
     {
       g_error ("Node aggregates for view %p are invalid:\n"
                "Are (%d,%d,%s), should be (%d,%d,%s)",
@@ -6228,7 +6637,8 @@ gtk_text_btree_node_view_check_consistency (GtkTextBTreeNode *node,
 }
 
 static void
-gtk_text_btree_node_check_consistency (GtkTextBTreeNode *node)
+gtk_text_btree_node_check_consistency (GtkTextBTree     *tree,
+                                       GtkTextBTreeNode *node)
 {
   GtkTextBTreeNode *childnode;
   Summary *summary, *summary2;
@@ -6259,7 +6669,7 @@ gtk_text_btree_node_check_consistency (GtkTextBTreeNode *node)
   nd = node->node_data;
   while (nd != NULL)
     {
-      gtk_text_btree_node_view_check_consistency (node, nd);
+      gtk_text_btree_node_view_check_consistency (tree, node, nd);
       nd = nd->next;
     }
 
@@ -6328,7 +6738,7 @@ gtk_text_btree_node_check_consistency (GtkTextBTreeNode *node)
               g_error ("gtk_text_btree_node_check_consistency: level mismatch (%d %d)",
                        node->level, childnode->level);
             }
-          gtk_text_btree_node_check_consistency (childnode);
+          gtk_text_btree_node_check_consistency (tree, childnode);
           for (summary = childnode->summary; summary != NULL;
                summary = summary->next)
             {
@@ -6464,15 +6874,15 @@ _gtk_text_btree_check (GtkTextBTree *tree)
   GtkTextLine *line;
   GtkTextLineSegment *seg;
   GtkTextTag *tag;
-  GSList *taglist = NULL;
+  GSList *all_tags, *taglist = NULL;
   int count;
   GtkTextTagInfo *info;
 
   /*
    * Make sure that the tag toggle counts and the tag root pointers are OK.
    */
-  for (taglist = list_of_tags (tree->table);
-       taglist != NULL ; taglist = taglist->next)
+  all_tags = list_of_tags (tree->table);
+  for (taglist = all_tags; taglist != NULL ; taglist = taglist->next)
     {
       tag = taglist->data;
       info = gtk_text_btree_get_existing_tag_info (tree, tag);
@@ -6556,15 +6966,14 @@ _gtk_text_btree_check (GtkTextBTree *tree)
         }
     }
 
-  g_slist_free (taglist);
-  taglist = NULL;
+  g_slist_free (all_tags);
 
   /*
    * Call a recursive procedure to do the main body of checks.
    */
 
   node = tree->root_node;
-  gtk_text_btree_node_check_consistency (tree->root_node);
+  gtk_text_btree_node_check_consistency (tree, tree->root_node);
 
   /*
    * Make sure that there are at least two lines in the text and
@@ -6834,4 +7243,5 @@ _gtk_text_btree_spew_segment (GtkTextBTree* tree, GtkTextLineSegment * seg)
     }
 }
 
-
+#define __GTK_TEXT_BTREE_C__
+#include "gtkaliasdef.c"