]> Pileus Git - ~andy/gtk/blob - gtk/gtktextbuffer.c
#155952
[~andy/gtk] / gtk / gtktextbuffer.c
1 /* GTK - The GIMP Toolkit
2  * gtktextbuffer.c Copyright (C) 2000 Red Hat, Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GTK+ Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27
28 #include <config.h>
29 #include <string.h>
30 #include <stdarg.h>
31
32
33 #include "gtkalias.h"
34 #define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
35 #include "gtkclipboard.h"
36 #include "gtkinvisible.h"
37 #include "gtkmarshalers.h"
38 #include "gtktextbuffer.h"
39 #include "gtktextbtree.h"
40 #include "gtktextiterprivate.h"
41 #include "gtkintl.h"
42
43 typedef struct _ClipboardRequest ClipboardRequest;
44
45 struct _ClipboardRequest
46 {
47   GtkTextBuffer *buffer;
48   gboolean interactive;
49   gboolean default_editable;
50   gboolean is_clipboard;
51   gboolean replace_selection;
52 };
53
54 enum {
55   INSERT_TEXT,
56   INSERT_PIXBUF,
57   INSERT_CHILD_ANCHOR,
58   DELETE_RANGE,
59   CHANGED,
60   MODIFIED_CHANGED,
61   MARK_SET,
62   MARK_DELETED,
63   APPLY_TAG,
64   REMOVE_TAG,
65   BEGIN_USER_ACTION,
66   END_USER_ACTION,
67   LAST_SIGNAL
68 };
69
70 enum {
71   PROP_0,
72
73   /* Construct */
74   PROP_TAG_TABLE
75 };
76
77 enum {
78   TARGET_STRING,
79   TARGET_TEXT,
80   TARGET_COMPOUND_TEXT,
81   TARGET_UTF8_STRING,
82   TARGET_TEXT_BUFFER_CONTENTS
83 };
84
85 static void gtk_text_buffer_init       (GtkTextBuffer      *tkxt_buffer);
86 static void gtk_text_buffer_class_init (GtkTextBufferClass *klass);
87 static void gtk_text_buffer_finalize   (GObject            *object);
88
89
90 static void gtk_text_buffer_real_insert_text           (GtkTextBuffer     *buffer,
91                                                         GtkTextIter       *iter,
92                                                         const gchar       *text,
93                                                         gint               len);
94 static void gtk_text_buffer_real_insert_pixbuf         (GtkTextBuffer     *buffer,
95                                                         GtkTextIter       *iter,
96                                                         GdkPixbuf         *pixbuf);
97 static void gtk_text_buffer_real_insert_anchor         (GtkTextBuffer     *buffer,
98                                                         GtkTextIter       *iter,
99                                                         GtkTextChildAnchor *anchor);
100 static void gtk_text_buffer_real_delete_range          (GtkTextBuffer     *buffer,
101                                                         GtkTextIter       *start,
102                                                         GtkTextIter       *end);
103 static void gtk_text_buffer_real_apply_tag             (GtkTextBuffer     *buffer,
104                                                         GtkTextTag        *tag,
105                                                         const GtkTextIter *start_char,
106                                                         const GtkTextIter *end_char);
107 static void gtk_text_buffer_real_remove_tag            (GtkTextBuffer     *buffer,
108                                                         GtkTextTag        *tag,
109                                                         const GtkTextIter *start_char,
110                                                         const GtkTextIter *end_char);
111 static void gtk_text_buffer_real_changed               (GtkTextBuffer     *buffer);
112
113 static GtkTextBTree* get_btree (GtkTextBuffer *buffer);
114 static void          free_log_attr_cache (GtkTextLogAttrCache *cache);
115
116 static void remove_all_clipboard_contents_buffers (GtkTextBuffer *buffer);
117 static void remove_all_selection_clipboards       (GtkTextBuffer *buffer);
118 static void update_selection_clipboards           (GtkTextBuffer *buffer);
119
120 static GObjectClass *parent_class = NULL;
121 static guint signals[LAST_SIGNAL] = { 0 };
122
123 static void gtk_text_buffer_set_property (GObject         *object,
124                                           guint            prop_id,
125                                           const GValue    *value,
126                                           GParamSpec      *pspec);
127 static void gtk_text_buffer_get_property (GObject         *object,
128                                           guint            prop_id,
129                                           GValue          *value,
130                                           GParamSpec      *pspec);
131
132
133 GType
134 gtk_text_buffer_get_type (void)
135 {
136   static GType our_type = 0;
137
138   if (our_type == 0)
139     {
140       static const GTypeInfo our_info =
141       {
142         sizeof (GtkTextBufferClass),
143         (GBaseInitFunc) NULL,
144         (GBaseFinalizeFunc) NULL,
145         (GClassInitFunc) gtk_text_buffer_class_init,
146         NULL,           /* class_finalize */
147         NULL,           /* class_data */
148         sizeof (GtkTextBuffer),
149         0,              /* n_preallocs */
150         (GInstanceInitFunc) gtk_text_buffer_init
151       };
152
153       our_type = g_type_register_static (G_TYPE_OBJECT, "GtkTextBuffer",
154                                          &our_info, 0);
155     }
156
157   return our_type;
158 }
159
160 static void
161 gtk_text_buffer_class_init (GtkTextBufferClass *klass)
162 {
163   GObjectClass *object_class = G_OBJECT_CLASS (klass);
164
165   parent_class = g_type_class_peek_parent (klass);
166
167   object_class->finalize = gtk_text_buffer_finalize;
168   object_class->set_property = gtk_text_buffer_set_property;
169   object_class->get_property = gtk_text_buffer_get_property;
170  
171   klass->insert_text = gtk_text_buffer_real_insert_text;
172   klass->insert_pixbuf = gtk_text_buffer_real_insert_pixbuf;
173   klass->insert_child_anchor = gtk_text_buffer_real_insert_anchor;
174   klass->delete_range = gtk_text_buffer_real_delete_range;
175   klass->apply_tag = gtk_text_buffer_real_apply_tag;
176   klass->remove_tag = gtk_text_buffer_real_remove_tag;
177   klass->changed = gtk_text_buffer_real_changed;
178
179   /* Construct */
180   g_object_class_install_property (object_class,
181                                    PROP_TAG_TABLE,
182                                    g_param_spec_object ("tag_table",
183                                                         P_("Tag Table"),
184                                                         P_("Text Tag Table"),
185                                                         GTK_TYPE_TEXT_TAG_TABLE,
186                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
187
188   signals[INSERT_TEXT] =
189     g_signal_new ("insert_text",
190                   G_OBJECT_CLASS_TYPE (object_class),
191                   G_SIGNAL_RUN_LAST,
192                   G_STRUCT_OFFSET (GtkTextBufferClass, insert_text),
193                   NULL, NULL,
194                   _gtk_marshal_VOID__BOXED_STRING_INT,
195                   G_TYPE_NONE,
196                   3,
197                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
198                   G_TYPE_STRING | G_SIGNAL_TYPE_STATIC_SCOPE,
199                   G_TYPE_INT);
200
201   signals[INSERT_PIXBUF] =
202     g_signal_new ("insert_pixbuf",
203                   G_OBJECT_CLASS_TYPE (object_class),
204                   G_SIGNAL_RUN_LAST,
205                   G_STRUCT_OFFSET (GtkTextBufferClass, insert_pixbuf),
206                   NULL, NULL,
207                   _gtk_marshal_VOID__BOXED_OBJECT,
208                   G_TYPE_NONE,
209                   2,
210                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
211                   GDK_TYPE_PIXBUF);
212
213   signals[INSERT_CHILD_ANCHOR] =
214     g_signal_new ("insert_child_anchor",
215                   G_OBJECT_CLASS_TYPE (object_class),
216                   G_SIGNAL_RUN_LAST,
217                   G_STRUCT_OFFSET (GtkTextBufferClass, insert_child_anchor),
218                   NULL, NULL,
219                   _gtk_marshal_VOID__BOXED_OBJECT,
220                   G_TYPE_NONE,
221                   2,
222                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
223                   GTK_TYPE_TEXT_CHILD_ANCHOR);
224   
225   /**
226    * GtkTextBuffer::delete_range:
227    * @buffer: the object which received the signal.
228    * @start: the start of the range to be deleted
229    * @end: the end of the range to be deleted
230    *
231    * The ::delete_range signal is emitted to delete a range from 
232    * a #GtkTextBuffer. Note that your handler must not invalidate the
233    * @start and @end iters (or has to revalidate them), if it runs before the 
234    * default handler. There is no need to keep the iters valid in handlers
235    * which run after the default handler (see g_signal_connect_after()), but
236    * those don't have access to the deleted text.
237    */
238   signals[DELETE_RANGE] =
239     g_signal_new ("delete_range",
240                   G_OBJECT_CLASS_TYPE (object_class),
241                   G_SIGNAL_RUN_LAST,
242                   G_STRUCT_OFFSET (GtkTextBufferClass, delete_range),
243                   NULL, NULL,
244                   _gtk_marshal_VOID__BOXED_BOXED,
245                   G_TYPE_NONE,
246                   2,
247                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
248                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE);
249
250   signals[CHANGED] =
251     g_signal_new ("changed",
252                   G_OBJECT_CLASS_TYPE (object_class),
253                   G_SIGNAL_RUN_LAST,                   
254                   G_STRUCT_OFFSET (GtkTextBufferClass, changed),
255                   NULL, NULL,
256                   _gtk_marshal_VOID__VOID,
257                   G_TYPE_NONE,
258                   0);
259
260   signals[MODIFIED_CHANGED] =
261     g_signal_new ("modified_changed",
262                   G_OBJECT_CLASS_TYPE (object_class),
263                   G_SIGNAL_RUN_LAST,
264                   G_STRUCT_OFFSET (GtkTextBufferClass, modified_changed),
265                   NULL, NULL,
266                   _gtk_marshal_VOID__VOID,
267                   G_TYPE_NONE,
268                   0);
269
270   signals[MARK_SET] =
271     g_signal_new ("mark_set",
272                   G_OBJECT_CLASS_TYPE (object_class),
273                   G_SIGNAL_RUN_LAST,                   
274                   G_STRUCT_OFFSET (GtkTextBufferClass, mark_set),
275                   NULL, NULL,
276                   _gtk_marshal_VOID__BOXED_OBJECT,
277                   G_TYPE_NONE,
278                   2,
279                   GTK_TYPE_TEXT_ITER,
280                   GTK_TYPE_TEXT_MARK);
281
282   signals[MARK_DELETED] =
283     g_signal_new ("mark_deleted",
284                   G_OBJECT_CLASS_TYPE (object_class),
285                   G_SIGNAL_RUN_LAST,                   
286                   G_STRUCT_OFFSET (GtkTextBufferClass, mark_deleted),
287                   NULL, NULL,
288                   _gtk_marshal_VOID__OBJECT,
289                   G_TYPE_NONE,
290                   1,
291                   GTK_TYPE_TEXT_MARK);
292   
293   signals[APPLY_TAG] =
294     g_signal_new ("apply_tag",
295                   G_OBJECT_CLASS_TYPE (object_class),
296                   G_SIGNAL_RUN_LAST,
297                   G_STRUCT_OFFSET (GtkTextBufferClass, apply_tag),
298                   NULL, NULL,
299                   _gtk_marshal_VOID__OBJECT_BOXED_BOXED,
300                   G_TYPE_NONE,
301                   3,
302                   GTK_TYPE_TEXT_TAG,
303                   GTK_TYPE_TEXT_ITER,
304                   GTK_TYPE_TEXT_ITER);
305
306   signals[REMOVE_TAG] =
307     g_signal_new ("remove_tag",
308                   G_OBJECT_CLASS_TYPE (object_class),
309                   G_SIGNAL_RUN_LAST,
310                   G_STRUCT_OFFSET (GtkTextBufferClass, remove_tag),
311                   NULL, NULL,
312                   _gtk_marshal_VOID__OBJECT_BOXED_BOXED,
313                   G_TYPE_NONE,
314                   3,
315                   GTK_TYPE_TEXT_TAG,
316                   GTK_TYPE_TEXT_ITER,
317                   GTK_TYPE_TEXT_ITER);
318
319   signals[BEGIN_USER_ACTION] =
320     g_signal_new ("begin_user_action",
321                   G_OBJECT_CLASS_TYPE (object_class),
322                   G_SIGNAL_RUN_LAST,                   
323                   G_STRUCT_OFFSET (GtkTextBufferClass, begin_user_action),
324                   NULL, NULL,
325                   _gtk_marshal_VOID__VOID,
326                   G_TYPE_NONE,
327                   0);
328
329   signals[END_USER_ACTION] =
330     g_signal_new ("end_user_action",
331                   G_OBJECT_CLASS_TYPE (object_class),
332                   G_SIGNAL_RUN_LAST,                   
333                   G_STRUCT_OFFSET (GtkTextBufferClass, end_user_action),
334                   NULL, NULL,
335                   _gtk_marshal_VOID__VOID,
336                   G_TYPE_NONE,
337                   0);  
338 }
339
340 static void
341 gtk_text_buffer_init (GtkTextBuffer *buffer)
342 {
343   buffer->clipboard_contents_buffers = NULL;
344   buffer->tag_table = NULL;
345 }
346
347 static void
348 set_table (GtkTextBuffer *buffer, GtkTextTagTable *table)
349 {
350   g_return_if_fail (buffer->tag_table == NULL);
351
352   if (table)
353     {
354       buffer->tag_table = table;
355       g_object_ref (buffer->tag_table);
356       _gtk_text_tag_table_add_buffer (table, buffer);
357     }
358 }
359
360 static GtkTextTagTable*
361 get_table (GtkTextBuffer *buffer)
362 {
363   if (buffer->tag_table == NULL)
364     {
365       buffer->tag_table = gtk_text_tag_table_new ();
366       _gtk_text_tag_table_add_buffer (buffer->tag_table, buffer);
367     }
368
369   return buffer->tag_table;
370 }
371
372 static void
373 gtk_text_buffer_set_property (GObject         *object,
374                               guint            prop_id,
375                               const GValue    *value,
376                               GParamSpec      *pspec)
377 {
378   GtkTextBuffer *text_buffer;
379
380   text_buffer = GTK_TEXT_BUFFER (object);
381
382   switch (prop_id)
383     {
384     case PROP_TAG_TABLE:
385       set_table (text_buffer, g_value_get_object (value));
386       break;
387
388     default:
389       break;
390     }
391 }
392
393 static void
394 gtk_text_buffer_get_property (GObject         *object,
395                               guint            prop_id,
396                               GValue          *value,
397                               GParamSpec      *pspec)
398 {
399   GtkTextBuffer *text_buffer;
400
401   text_buffer = GTK_TEXT_BUFFER (object);
402
403   switch (prop_id)
404     {
405     case PROP_TAG_TABLE:
406       g_value_set_object (value, get_table (text_buffer));
407       break;
408
409     default:
410       break;
411     }
412 }
413
414 /**
415  * gtk_text_buffer_new:
416  * @table: a tag table, or NULL to create a new one
417  *
418  * Creates a new text buffer.
419  *
420  * Return value: a new text buffer
421  **/
422 GtkTextBuffer*
423 gtk_text_buffer_new (GtkTextTagTable *table)
424 {
425   GtkTextBuffer *text_buffer;
426
427   text_buffer = g_object_new (GTK_TYPE_TEXT_BUFFER, "tag_table", table, NULL);
428
429   return text_buffer;
430 }
431
432 static void
433 gtk_text_buffer_finalize (GObject *object)
434 {
435   GtkTextBuffer *buffer;
436
437   buffer = GTK_TEXT_BUFFER (object);
438
439   remove_all_clipboard_contents_buffers (buffer);
440   remove_all_selection_clipboards (buffer);
441
442   if (buffer->tag_table)
443     {
444       _gtk_text_tag_table_remove_buffer (buffer->tag_table, buffer);
445       g_object_unref (buffer->tag_table);
446       buffer->tag_table = NULL;
447     }
448
449   if (buffer->btree)
450     {
451       _gtk_text_btree_unref (buffer->btree);
452       buffer->btree = NULL;
453     }
454
455   if (buffer->log_attr_cache)
456     free_log_attr_cache (buffer->log_attr_cache);
457
458   buffer->log_attr_cache = NULL;
459   
460   G_OBJECT_CLASS (parent_class)->finalize (object);
461 }
462
463 static GtkTextBTree*
464 get_btree (GtkTextBuffer *buffer)
465 {
466   if (buffer->btree == NULL)
467     buffer->btree = _gtk_text_btree_new (gtk_text_buffer_get_tag_table (buffer),
468                                          buffer);
469
470   return buffer->btree;
471 }
472
473 GtkTextBTree*
474 _gtk_text_buffer_get_btree (GtkTextBuffer *buffer)
475 {
476   return get_btree (buffer);
477 }
478
479 /**
480  * gtk_text_buffer_get_tag_table:
481  * @buffer: a #GtkTextBuffer
482  *
483  * Get the #GtkTextTagTable associated with this buffer.
484  *
485  * Return value: the buffer's tag table
486  **/
487 GtkTextTagTable*
488 gtk_text_buffer_get_tag_table (GtkTextBuffer  *buffer)
489 {
490   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
491
492   return get_table (buffer);
493 }
494
495 /**
496  * gtk_text_buffer_set_text:
497  * @buffer: a #GtkTextBuffer
498  * @text: UTF-8 text to insert
499  * @len: length of @text in bytes
500  *
501  * Deletes current contents of @buffer, and inserts @text instead. If
502  * @len is -1, @text must be nul-terminated. @text must be valid UTF-8.
503  **/
504 void
505 gtk_text_buffer_set_text (GtkTextBuffer *buffer,
506                           const gchar   *text,
507                           gint           len)
508 {
509   GtkTextIter start, end;
510
511   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
512   g_return_if_fail (text != NULL);
513
514   if (len < 0)
515     len = strlen (text);
516
517   gtk_text_buffer_get_bounds (buffer, &start, &end);
518
519   gtk_text_buffer_delete (buffer, &start, &end);
520
521   if (len > 0)
522     {
523       gtk_text_buffer_get_iter_at_offset (buffer, &start, 0);
524       gtk_text_buffer_insert (buffer, &start, text, len);
525     }
526 }
527
528 /*
529  * Insertion
530  */
531
532 static void
533 gtk_text_buffer_real_insert_text (GtkTextBuffer *buffer,
534                                   GtkTextIter *iter,
535                                   const gchar *text,
536                                   gint len)
537 {
538   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
539   g_return_if_fail (iter != NULL);
540   
541   _gtk_text_btree_insert (iter, text, len);
542
543   g_signal_emit (buffer, signals[CHANGED], 0);
544 }
545
546 static void
547 gtk_text_buffer_emit_insert (GtkTextBuffer *buffer,
548                              GtkTextIter   *iter,
549                              const gchar   *text,
550                              gint           len)
551 {
552   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
553   g_return_if_fail (iter != NULL);
554   g_return_if_fail (text != NULL);
555
556   if (len < 0)
557     len = strlen (text);
558
559   g_return_if_fail (g_utf8_validate (text, len, NULL));
560   
561   if (len > 0)
562     {
563       g_signal_emit (buffer, signals[INSERT_TEXT], 0,
564                      iter, text, len);
565     }
566 }
567
568 /**
569  * gtk_text_buffer_insert:
570  * @buffer: a #GtkTextBuffer
571  * @iter: a position in the buffer
572  * @text: UTF-8 format text to insert
573  * @len: length of text in bytes, or -1
574  *
575  * Inserts @len bytes of @text at position @iter.  If @len is -1,
576  * @text must be nul-terminated and will be inserted in its
577  * entirety. Emits the "insert_text" signal; insertion actually occurs
578  * in the default handler for the signal. @iter is invalidated when
579  * insertion occurs (because the buffer contents change), but the
580  * default signal handler revalidates it to point to the end of the
581  * inserted text.
582  *
583  **/
584 void
585 gtk_text_buffer_insert (GtkTextBuffer *buffer,
586                         GtkTextIter *iter,
587                         const gchar *text,
588                         gint len)
589 {
590   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
591   g_return_if_fail (iter != NULL);
592   g_return_if_fail (text != NULL);
593   g_return_if_fail (gtk_text_iter_get_buffer (iter) == buffer);
594   
595   gtk_text_buffer_emit_insert (buffer, iter, text, len);
596 }
597
598 /**
599  * gtk_text_buffer_insert_at_cursor:
600  * @buffer: a #GtkTextBuffer
601  * @text: some text in UTF-8 format
602  * @len: length of text, in bytes
603  *
604  * Simply calls gtk_text_buffer_insert (), using the current
605  * cursor position as the insertion point.
606  **/
607 void
608 gtk_text_buffer_insert_at_cursor (GtkTextBuffer *buffer,
609                                   const gchar *text,
610                                   gint len)
611 {
612   GtkTextIter iter;
613
614   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
615   g_return_if_fail (text != NULL);
616
617   gtk_text_buffer_get_iter_at_mark (buffer, &iter,
618                                     gtk_text_buffer_get_mark (buffer,
619                                                               "insert"));
620
621   gtk_text_buffer_insert (buffer, &iter, text, len);
622 }
623
624 /**
625  * gtk_text_buffer_insert_interactive:
626  * @buffer: a #GtkTextBuffer
627  * @iter: a position in @buffer
628  * @text: some UTF-8 text
629  * @len: length of text in bytes, or -1
630  * @default_editable: default editability of buffer
631  *
632  * Like gtk_text_buffer_insert (), but the insertion will not occur if
633  * @iter is at a non-editable location in the buffer.  Usually you
634  * want to prevent insertions at ineditable locations if the insertion
635  * results from a user action (is interactive).
636  *
637  * @default_editable indicates the editability of text that doesn't
638  * have a tag affecting editability applied to it. Typically the
639  * result of gtk_text_view_get_editable() is appropriate here.
640  *
641  * Return value: whether text was actually inserted
642  **/
643 gboolean
644 gtk_text_buffer_insert_interactive (GtkTextBuffer *buffer,
645                                     GtkTextIter   *iter,
646                                     const gchar   *text,
647                                     gint           len,
648                                     gboolean       default_editable)
649 {
650   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
651   g_return_val_if_fail (text != NULL, FALSE);
652   g_return_val_if_fail (gtk_text_iter_get_buffer (iter) == buffer, FALSE);
653
654   if (gtk_text_iter_can_insert (iter, default_editable))
655     {
656       gtk_text_buffer_begin_user_action (buffer);
657       gtk_text_buffer_emit_insert (buffer, iter, text, len);
658       gtk_text_buffer_end_user_action (buffer);
659       return TRUE;
660     }
661   else
662     return FALSE;
663 }
664
665 /**
666  * gtk_text_buffer_insert_interactive_at_cursor:
667  * @buffer: a #GtkTextBuffer
668  * @text: text in UTF-8 format
669  * @len: length of text in bytes, or -1
670  * @default_editable: default editability of buffer
671  *
672  * Calls gtk_text_buffer_insert_interactive () at the cursor
673  * position.
674  *
675  * @default_editable indicates the editability of text that doesn't
676  * have a tag affecting editability applied to it. Typically the
677  * result of gtk_text_view_get_editable() is appropriate here.
678  * 
679  * Return value: whether text was actually inserted
680  **/
681 gboolean
682 gtk_text_buffer_insert_interactive_at_cursor (GtkTextBuffer *buffer,
683                                               const gchar   *text,
684                                               gint           len,
685                                               gboolean       default_editable)
686 {
687   GtkTextIter iter;
688
689   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
690   g_return_val_if_fail (text != NULL, FALSE);
691
692   gtk_text_buffer_get_iter_at_mark (buffer, &iter,
693                                     gtk_text_buffer_get_mark (buffer,
694                                                               "insert"));
695
696   return gtk_text_buffer_insert_interactive (buffer, &iter, text, len,
697                                              default_editable);
698 }
699
700 static gboolean
701 possibly_not_text (gunichar ch,
702                    gpointer user_data)
703 {
704   return ch == GTK_TEXT_UNKNOWN_CHAR;
705 }
706
707 static void
708 insert_text_range (GtkTextBuffer     *buffer,
709                    GtkTextIter       *iter,
710                    const GtkTextIter *orig_start,
711                    const GtkTextIter *orig_end,
712                    gboolean           interactive)
713 {
714   gchar *text;
715
716   text = gtk_text_iter_get_text (orig_start, orig_end);
717
718   gtk_text_buffer_emit_insert (buffer, iter, text, -1);
719
720   g_free (text);
721 }
722
723 typedef struct _Range Range;
724 struct _Range
725 {
726   GtkTextBuffer *buffer;
727   GtkTextMark *start_mark;
728   GtkTextMark *end_mark;
729   GtkTextMark *whole_end_mark;
730   GtkTextIter *range_start;
731   GtkTextIter *range_end;
732   GtkTextIter *whole_end;
733 };
734
735 static Range*
736 save_range (GtkTextIter *range_start,
737             GtkTextIter *range_end,
738             GtkTextIter *whole_end)
739 {
740   Range *r;
741
742   r = g_new (Range, 1);
743
744   r->buffer = gtk_text_iter_get_buffer (range_start);
745   g_object_ref (r->buffer);
746   
747   r->start_mark = 
748     gtk_text_buffer_create_mark (gtk_text_iter_get_buffer (range_start),
749                                  NULL,
750                                  range_start,
751                                  FALSE);
752   r->end_mark = 
753     gtk_text_buffer_create_mark (gtk_text_iter_get_buffer (range_start),
754                                  NULL,
755                                  range_end,
756                                  TRUE);
757
758   r->whole_end_mark = 
759     gtk_text_buffer_create_mark (gtk_text_iter_get_buffer (range_start),
760                                  NULL,
761                                  whole_end,
762                                  TRUE);
763
764   r->range_start = range_start;
765   r->range_end = range_end;
766   r->whole_end = whole_end;
767
768   return r;
769 }
770
771 static void
772 restore_range (Range *r)
773 {
774   gtk_text_buffer_get_iter_at_mark (r->buffer,
775                                     r->range_start,
776                                     r->start_mark);
777       
778   gtk_text_buffer_get_iter_at_mark (r->buffer,
779                                     r->range_end,
780                                     r->end_mark);
781       
782   gtk_text_buffer_get_iter_at_mark (r->buffer,
783                                     r->whole_end,
784                                     r->whole_end_mark);  
785   
786   gtk_text_buffer_delete_mark (r->buffer, r->start_mark);
787   gtk_text_buffer_delete_mark (r->buffer, r->end_mark);
788   gtk_text_buffer_delete_mark (r->buffer, r->whole_end_mark);
789
790   /* Due to the gravities on the marks, the ordering could have
791    * gotten mangled; we switch to an empty range in that
792    * case
793    */
794   
795   if (gtk_text_iter_compare (r->range_start, r->range_end) > 0)
796     *r->range_start = *r->range_end;
797
798   if (gtk_text_iter_compare (r->range_end, r->whole_end) > 0)
799     *r->range_end = *r->whole_end;
800   
801   g_object_unref (r->buffer);
802   g_free (r); 
803 }
804
805 static void
806 insert_range_untagged (GtkTextBuffer     *buffer,
807                        GtkTextIter       *iter,
808                        const GtkTextIter *orig_start,
809                        const GtkTextIter *orig_end,
810                        gboolean           interactive)
811 {
812   GtkTextIter range_start;
813   GtkTextIter range_end;
814   GtkTextIter start, end;
815   GtkTextBuffer *src_buffer;
816   Range *r;
817   
818   if (gtk_text_iter_equal (orig_start, orig_end))
819     return;
820
821   start = *orig_start;
822   end = *orig_end;
823   
824   src_buffer = gtk_text_iter_get_buffer (&start);
825   
826   range_start = start;
827   range_end = start;
828   
829   while (TRUE)
830     {
831       if (gtk_text_iter_equal (&range_start, &range_end))
832         {
833           /* Figure out how to move forward */
834
835           g_assert (gtk_text_iter_compare (&range_end, &end) <= 0);
836           
837           if (gtk_text_iter_equal (&range_end, &end))
838             {
839               /* nothing left to do */
840               break;
841             }
842           else if (gtk_text_iter_get_char (&range_end) == GTK_TEXT_UNKNOWN_CHAR)
843             {
844               GdkPixbuf *pixbuf = NULL;
845               GtkTextChildAnchor *anchor = NULL;
846               pixbuf = gtk_text_iter_get_pixbuf (&range_end);
847               anchor = gtk_text_iter_get_child_anchor (&range_end);
848
849               if (pixbuf)
850                 {
851                   r = save_range (&range_start,
852                                   &range_end,
853                                   &end);
854
855                   gtk_text_buffer_insert_pixbuf (buffer,
856                                                  iter,
857                                                  pixbuf);
858
859                   restore_range (r);
860                   r = NULL;
861                   
862                   gtk_text_iter_forward_char (&range_end);
863                   
864                   range_start = range_end;
865                 }
866               else if (anchor)
867                 {
868                   /* Just skip anchors */
869
870                   gtk_text_iter_forward_char (&range_end);
871                   range_start = range_end;
872                 }
873               else
874                 {
875                   /* The GTK_TEXT_UNKNOWN_CHAR was in a text segment, so
876                    * keep going. 
877                    */
878                   gtk_text_iter_forward_find_char (&range_end,
879                                                    possibly_not_text, NULL,
880                                                    &end);
881                   
882                   g_assert (gtk_text_iter_compare (&range_end, &end) <= 0);
883                 }
884             }
885           else
886             {
887               /* Text segment starts here, so forward search to
888                * find its possible endpoint
889                */
890               gtk_text_iter_forward_find_char (&range_end,
891                                                possibly_not_text, NULL,
892                                                &end);
893               
894               g_assert (gtk_text_iter_compare (&range_end, &end) <= 0);
895             }
896         }
897       else
898         {
899           r = save_range (&range_start,
900                           &range_end,
901                           &end);
902           
903           insert_text_range (buffer,
904                              iter,
905                              &range_start,
906                              &range_end,
907                              interactive);
908
909           restore_range (r);
910           r = NULL;
911           
912           range_start = range_end;
913         }
914     }
915 }
916
917 static void
918 insert_range_not_inside_self (GtkTextBuffer     *buffer,
919                               GtkTextIter       *iter,
920                               const GtkTextIter *orig_start,
921                               const GtkTextIter *orig_end,
922                               gboolean           interactive)
923 {
924   /* Find each range of uniformly-tagged text, insert it,
925    * then apply the tags.
926    */
927   GtkTextIter start = *orig_start;
928   GtkTextIter end = *orig_end;
929   GtkTextIter range_start;
930   GtkTextIter range_end;
931   GtkTextBuffer *src_buffer;
932   
933   if (gtk_text_iter_equal (orig_start, orig_end))
934     return;
935   
936   src_buffer = gtk_text_iter_get_buffer (orig_start);
937   
938   gtk_text_iter_order (&start, &end);
939
940   range_start = start;
941   range_end = start;  
942   
943   while (TRUE)
944     {
945       gint start_offset;
946       GtkTextIter start_iter;
947       GSList *tags;
948       GSList *tmp_list;
949       Range *r;
950       
951       if (gtk_text_iter_equal (&range_start, &end))
952         break; /* All done */
953
954       g_assert (gtk_text_iter_compare (&range_start, &end) < 0);
955       
956       gtk_text_iter_forward_to_tag_toggle (&range_end, NULL);
957
958       g_assert (!gtk_text_iter_equal (&range_start, &range_end));
959
960       /* Clamp to the end iterator */
961       if (gtk_text_iter_compare (&range_end, &end) > 0)
962         range_end = end;
963       
964       /* We have a range with unique tags; insert it, and
965        * apply all tags.
966        */
967       start_offset = gtk_text_iter_get_offset (iter);
968
969       r = save_range (&range_start, &range_end, &end);
970       
971       insert_range_untagged (buffer, iter, &range_start, &range_end, interactive);
972
973       restore_range (r);
974       r = NULL;
975       
976       gtk_text_buffer_get_iter_at_offset (buffer, &start_iter, start_offset);
977       
978       tags = gtk_text_iter_get_tags (&range_start);
979       tmp_list = tags;
980       while (tmp_list != NULL)
981         {
982           gtk_text_buffer_apply_tag (buffer,
983                                      tmp_list->data,
984                                      &start_iter,
985                                      iter);
986           
987           tmp_list = g_slist_next (tmp_list);
988         }
989       g_slist_free (tags);
990
991       range_start = range_end;
992     }
993 }
994
995 static void
996 gtk_text_buffer_real_insert_range (GtkTextBuffer     *buffer,
997                                    GtkTextIter       *iter,
998                                    const GtkTextIter *orig_start,
999                                    const GtkTextIter *orig_end,
1000                                    gboolean           interactive)
1001 {
1002   GtkTextBuffer *src_buffer;
1003   
1004   /* Find each range of uniformly-tagged text, insert it,
1005    * then apply the tags.
1006    */  
1007   if (gtk_text_iter_equal (orig_start, orig_end))
1008     return;
1009
1010   if (interactive)
1011     gtk_text_buffer_begin_user_action (buffer);
1012   
1013   src_buffer = gtk_text_iter_get_buffer (orig_start);
1014   
1015   if (gtk_text_iter_get_buffer (iter) != src_buffer ||
1016       !gtk_text_iter_in_range (iter, orig_start, orig_end))
1017     {
1018       insert_range_not_inside_self (buffer, iter, orig_start, orig_end, interactive);
1019     }
1020   else
1021     {
1022       /* If you insert a range into itself, it could loop infinitely
1023        * because the region being copied keeps growing as we insert. So
1024        * we have to separately copy the range before and after
1025        * the insertion point.
1026        */
1027       GtkTextIter start = *orig_start;
1028       GtkTextIter end = *orig_end;
1029       GtkTextIter range_start;
1030       GtkTextIter range_end;
1031       Range *first_half;
1032       Range *second_half;
1033
1034       gtk_text_iter_order (&start, &end);
1035       
1036       range_start = start;
1037       range_end = *iter;
1038       first_half = save_range (&range_start, &range_end, &end);
1039
1040       range_start = *iter;
1041       range_end = end;
1042       second_half = save_range (&range_start, &range_end, &end);
1043
1044       restore_range (first_half);
1045       insert_range_not_inside_self (buffer, iter, &range_start, &range_end, interactive);
1046
1047       restore_range (second_half);
1048       insert_range_not_inside_self (buffer, iter, &range_start, &range_end, interactive);
1049     }
1050   
1051   if (interactive)
1052     gtk_text_buffer_end_user_action (buffer);
1053 }
1054
1055 /**
1056  * gtk_text_buffer_insert_range:
1057  * @buffer: a #GtkTextBuffer
1058  * @iter: a position in @buffer
1059  * @start: a position in a #GtkTextBuffer
1060  * @end: another position in the same buffer as @start
1061  *
1062  * Copies text, tags, and pixbufs between @start and @end (the order
1063  * of @start and @end doesn't matter) and inserts the copy at @iter.
1064  * Used instead of simply getting/inserting text because it preserves
1065  * images and tags. If @start and @end are in a different buffer from
1066  * @buffer, the two buffers must share the same tag table.
1067  *
1068  * Implemented via emissions of the insert_text and apply_tag signals,
1069  * so expect those.
1070  **/
1071 void
1072 gtk_text_buffer_insert_range (GtkTextBuffer     *buffer,
1073                               GtkTextIter       *iter,
1074                               const GtkTextIter *start,
1075                               const GtkTextIter *end)
1076 {
1077   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1078   g_return_if_fail (iter != NULL);
1079   g_return_if_fail (start != NULL);
1080   g_return_if_fail (end != NULL);
1081   g_return_if_fail (gtk_text_iter_get_buffer (start) ==
1082                     gtk_text_iter_get_buffer (end));
1083   g_return_if_fail (gtk_text_iter_get_buffer (start)->tag_table ==
1084                     buffer->tag_table);  
1085   g_return_if_fail (gtk_text_iter_get_buffer (iter) == buffer);
1086   
1087   gtk_text_buffer_real_insert_range (buffer, iter, start, end, FALSE);
1088 }
1089
1090 /**
1091  * gtk_text_buffer_insert_range_interactive:
1092  * @buffer: a #GtkTextBuffer
1093  * @iter: a position in @buffer
1094  * @start: a position in a #GtkTextBuffer
1095  * @end: another position in the same buffer as @start
1096  * @default_editable: default editability of the buffer
1097  *
1098  * Same as gtk_text_buffer_insert_range(), but does nothing if the
1099  * insertion point isn't editable. The @default_editable parameter
1100  * indicates whether the text is editable at @iter if no tags
1101  * enclosing @iter affect editability. Typically the result of
1102  * gtk_text_view_get_editable() is appropriate here.
1103  *
1104  * Returns: whether an insertion was possible at @iter
1105  **/
1106 gboolean
1107 gtk_text_buffer_insert_range_interactive (GtkTextBuffer     *buffer,
1108                                           GtkTextIter       *iter,
1109                                           const GtkTextIter *start,
1110                                           const GtkTextIter *end,
1111                                           gboolean           default_editable)
1112 {
1113   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
1114   g_return_val_if_fail (iter != NULL, FALSE);
1115   g_return_val_if_fail (start != NULL, FALSE);
1116   g_return_val_if_fail (end != NULL, FALSE);
1117   g_return_val_if_fail (gtk_text_iter_get_buffer (start) ==
1118                         gtk_text_iter_get_buffer (end), FALSE);
1119   g_return_val_if_fail (gtk_text_iter_get_buffer (start)->tag_table ==
1120                         buffer->tag_table, FALSE);
1121
1122
1123   if (gtk_text_iter_can_insert (iter, default_editable))
1124     {
1125       gtk_text_buffer_real_insert_range (buffer, iter, start, end, TRUE);
1126       return TRUE;
1127     }
1128   else
1129     return FALSE;
1130 }
1131
1132 /**
1133  * gtk_text_buffer_insert_with_tags:
1134  * @buffer: a #GtkTextBuffer
1135  * @iter: an iterator in @buffer
1136  * @text: UTF-8 text
1137  * @len: length of @text, or -1
1138  * @first_tag: first tag to apply to @text
1139  * @Varargs: NULL-terminated list of tags to apply
1140  *
1141  * Inserts @text into @buffer at @iter, applying the list of tags to
1142  * the newly-inserted text. The last tag specified must be NULL to
1143  * terminate the list. Equivalent to calling gtk_text_buffer_insert (),
1144  * then gtk_text_buffer_apply_tag () on the inserted text;
1145  * gtk_text_buffer_insert_with_tags () is just a convenience function.
1146  **/
1147 void
1148 gtk_text_buffer_insert_with_tags (GtkTextBuffer *buffer,
1149                                   GtkTextIter   *iter,
1150                                   const gchar   *text,
1151                                   gint           len,
1152                                   GtkTextTag    *first_tag,
1153                                   ...)
1154 {
1155   gint start_offset;
1156   GtkTextIter start;
1157   va_list args;
1158   GtkTextTag *tag;
1159
1160   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1161   g_return_if_fail (iter != NULL);
1162   g_return_if_fail (text != NULL);
1163   g_return_if_fail (gtk_text_iter_get_buffer (iter) == buffer);
1164   
1165   start_offset = gtk_text_iter_get_offset (iter);
1166
1167   gtk_text_buffer_insert (buffer, iter, text, len);
1168
1169   if (first_tag == NULL)
1170     return;
1171
1172   gtk_text_buffer_get_iter_at_offset (buffer, &start, start_offset);
1173
1174   va_start (args, first_tag);
1175   tag = first_tag;
1176   while (tag)
1177     {
1178       gtk_text_buffer_apply_tag (buffer, tag, &start, iter);
1179
1180       tag = va_arg (args, GtkTextTag*);
1181     }
1182
1183   va_end (args);
1184 }
1185
1186 /**
1187  * gtk_text_buffer_insert_with_tags_by_name:
1188  * @buffer: a #GtkTextBuffer
1189  * @iter: position in @buffer
1190  * @text: UTF-8 text
1191  * @len: length of @text, or -1
1192  * @first_tag_name: name of a tag to apply to @text
1193  * @Varargs: more tag names
1194  *
1195  * Same as gtk_text_buffer_insert_with_tags (), but allows you
1196  * to pass in tag names instead of tag objects.
1197  **/
1198 void
1199 gtk_text_buffer_insert_with_tags_by_name  (GtkTextBuffer *buffer,
1200                                            GtkTextIter   *iter,
1201                                            const gchar   *text,
1202                                            gint           len,
1203                                            const gchar   *first_tag_name,
1204                                            ...)
1205 {
1206   gint start_offset;
1207   GtkTextIter start;
1208   va_list args;
1209   const gchar *tag_name;
1210
1211   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1212   g_return_if_fail (iter != NULL);
1213   g_return_if_fail (text != NULL);
1214   g_return_if_fail (gtk_text_iter_get_buffer (iter) == buffer);
1215   
1216   start_offset = gtk_text_iter_get_offset (iter);
1217
1218   gtk_text_buffer_insert (buffer, iter, text, len);
1219
1220   if (first_tag_name == NULL)
1221     return;
1222
1223   gtk_text_buffer_get_iter_at_offset (buffer, &start, start_offset);
1224
1225   va_start (args, first_tag_name);
1226   tag_name = first_tag_name;
1227   while (tag_name)
1228     {
1229       GtkTextTag *tag;
1230
1231       tag = gtk_text_tag_table_lookup (buffer->tag_table,
1232                                        tag_name);
1233
1234       if (tag == NULL)
1235         {
1236           g_warning ("%s: no tag with name '%s'!", G_STRLOC, tag_name);
1237           return;
1238         }
1239
1240       gtk_text_buffer_apply_tag (buffer, tag, &start, iter);
1241
1242       tag_name = va_arg (args, const gchar*);
1243     }
1244
1245   va_end (args);
1246 }
1247
1248
1249 /*
1250  * Deletion
1251  */
1252
1253 static void
1254 gtk_text_buffer_real_delete_range (GtkTextBuffer *buffer,
1255                                    GtkTextIter   *start,
1256                                    GtkTextIter   *end)
1257 {
1258   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1259   g_return_if_fail (start != NULL);
1260   g_return_if_fail (end != NULL);
1261
1262   _gtk_text_btree_delete (start, end);
1263
1264   /* may have deleted the selection... */
1265   update_selection_clipboards (buffer);
1266
1267   g_signal_emit (buffer, signals[CHANGED], 0);
1268 }
1269
1270 static void
1271 gtk_text_buffer_emit_delete (GtkTextBuffer *buffer,
1272                              GtkTextIter *start,
1273                              GtkTextIter *end)
1274 {
1275   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1276   g_return_if_fail (start != NULL);
1277   g_return_if_fail (end != NULL);
1278
1279   if (gtk_text_iter_equal (start, end))
1280     return;
1281
1282   gtk_text_iter_order (start, end);
1283
1284   g_signal_emit (buffer,
1285                  signals[DELETE_RANGE],
1286                  0,
1287                  start, end);
1288 }
1289
1290 /**
1291  * gtk_text_buffer_delete:
1292  * @buffer: a #GtkTextBuffer
1293  * @start: a position in @buffer
1294  * @end: another position in @buffer
1295  *
1296  * Deletes text between @start and @end. The order of @start and @end
1297  * is not actually relevant; gtk_text_buffer_delete () will reorder
1298  * them. This function actually emits the "delete_range" signal, and
1299  * the default handler of that signal deletes the text. Because the
1300  * buffer is modified, all outstanding iterators become invalid after
1301  * calling this function; however, the @start and @end will be
1302  * re-initialized to point to the location where text was deleted.
1303  *
1304  **/
1305 void
1306 gtk_text_buffer_delete (GtkTextBuffer *buffer,
1307                         GtkTextIter   *start,
1308                         GtkTextIter   *end)
1309 {
1310   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1311   g_return_if_fail (start != NULL);
1312   g_return_if_fail (end != NULL);
1313   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
1314   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
1315   
1316   gtk_text_buffer_emit_delete (buffer, start, end);
1317 }
1318
1319 /**
1320  * gtk_text_buffer_delete_interactive:
1321  * @buffer: a #GtkTextBuffer
1322  * @start_iter: start of range to delete
1323  * @end_iter: end of range
1324  * @default_editable: whether the buffer is editable by default
1325  *
1326  * Deletes all <emphasis>editable</emphasis> text in the given range.
1327  * Calls gtk_text_buffer_delete () for each editable sub-range of
1328  * [@start,@end). @start and @end are revalidated to point to
1329  * the location of the last deleted range, or left untouched if
1330  * no text was deleted.
1331  *
1332  * Return value: whether some text was actually deleted
1333  **/
1334 gboolean
1335 gtk_text_buffer_delete_interactive (GtkTextBuffer *buffer,
1336                                     GtkTextIter   *start_iter,
1337                                     GtkTextIter   *end_iter,
1338                                     gboolean       default_editable)
1339 {
1340   GtkTextMark *end_mark;
1341   GtkTextMark *start_mark;
1342   GtkTextIter iter;
1343   gboolean current_state;
1344   gboolean deleted_stuff = FALSE;
1345
1346   /* Delete all editable text in the range start_iter, end_iter */
1347
1348   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
1349   g_return_val_if_fail (start_iter != NULL, FALSE);
1350   g_return_val_if_fail (end_iter != NULL, FALSE);
1351   g_return_val_if_fail (gtk_text_iter_get_buffer (start_iter) == buffer, FALSE);
1352   g_return_val_if_fail (gtk_text_iter_get_buffer (end_iter) == buffer, FALSE);
1353
1354   
1355   gtk_text_buffer_begin_user_action (buffer);
1356   
1357   gtk_text_iter_order (start_iter, end_iter);
1358
1359   start_mark = gtk_text_buffer_create_mark (buffer, NULL,
1360                                             start_iter, TRUE);
1361   end_mark = gtk_text_buffer_create_mark (buffer, NULL,
1362                                           end_iter, FALSE);
1363
1364   gtk_text_buffer_get_iter_at_mark (buffer, &iter, start_mark);
1365
1366   current_state = gtk_text_iter_editable (&iter, default_editable);
1367
1368   while (TRUE)
1369     {
1370       gboolean new_state;
1371       gboolean done = FALSE;
1372       GtkTextIter end;
1373
1374       gtk_text_iter_forward_to_tag_toggle (&iter, NULL);
1375
1376       gtk_text_buffer_get_iter_at_mark (buffer, &end, end_mark);
1377
1378       if (gtk_text_iter_compare (&iter, &end) >= 0)
1379         {
1380           done = TRUE;
1381           iter = end; /* clamp to the last boundary */
1382         }
1383
1384       new_state = gtk_text_iter_editable (&iter, default_editable);
1385
1386       if (current_state == new_state)
1387         {
1388           if (done)
1389             {
1390               if (current_state)
1391                 {
1392                   /* We're ending an editable region. Delete said region. */
1393                   GtkTextIter start;
1394
1395                   gtk_text_buffer_get_iter_at_mark (buffer, &start, start_mark);
1396
1397                   gtk_text_buffer_emit_delete (buffer, &start, &iter);
1398
1399                   deleted_stuff = TRUE;
1400
1401                   /* revalidate user's iterators. */
1402                   *start_iter = start;
1403                   *end_iter = iter;
1404                 }
1405
1406               break;
1407             }
1408           else
1409             continue;
1410         }
1411
1412       if (current_state && !new_state)
1413         {
1414           /* End of an editable region. Delete it. */
1415           GtkTextIter start;
1416
1417           gtk_text_buffer_get_iter_at_mark (buffer, &start, start_mark);
1418
1419           gtk_text_buffer_emit_delete (buffer, &start, &iter);
1420
1421           current_state = FALSE;
1422           deleted_stuff = TRUE;
1423
1424           /* revalidate user's iterators. */
1425           *start_iter = start;
1426           *end_iter = iter;
1427         }
1428       else
1429         {
1430           /* We are at the start of an editable region. We won't be deleting
1431            * the previous region. Move start mark to start of this region.
1432            */
1433
1434           g_assert (!current_state && new_state);
1435
1436           gtk_text_buffer_move_mark (buffer, start_mark,
1437                                      &iter);
1438
1439
1440           current_state = TRUE;
1441         }
1442
1443       if (done)
1444         break;
1445     }
1446
1447
1448   gtk_text_buffer_delete_mark (buffer, start_mark);
1449   gtk_text_buffer_delete_mark (buffer, end_mark);
1450
1451   gtk_text_buffer_end_user_action (buffer);
1452   
1453   return deleted_stuff;
1454 }
1455
1456 /*
1457  * Extracting textual buffer contents
1458  */
1459
1460 /**
1461  * gtk_text_buffer_get_text:
1462  * @buffer: a #GtkTextBuffer
1463  * @start: start of a range
1464  * @end: end of a range
1465  * @include_hidden_chars: whether to include invisible text
1466  *
1467  * Returns the text in the range [@start,@end). Excludes undisplayed
1468  * text (text marked with tags that set the invisibility attribute) if
1469  * @include_hidden_chars is FALSE. Does not include characters
1470  * representing embedded images, so byte and character indexes into
1471  * the returned string do <emphasis>not</emphasis> correspond to byte
1472  * and character indexes into the buffer. Contrast with
1473  * gtk_text_buffer_get_slice ().
1474  *
1475  * Return value: an allocated UTF-8 string
1476  **/
1477 gchar*
1478 gtk_text_buffer_get_text (GtkTextBuffer      *buffer,
1479                           const GtkTextIter *start,
1480                           const GtkTextIter *end,
1481                           gboolean             include_hidden_chars)
1482 {
1483   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1484   g_return_val_if_fail (start != NULL, NULL);
1485   g_return_val_if_fail (end != NULL, NULL);
1486   g_return_val_if_fail (gtk_text_iter_get_buffer (start) == buffer, NULL);
1487   g_return_val_if_fail (gtk_text_iter_get_buffer (end) == buffer, NULL);
1488   
1489   if (include_hidden_chars)
1490     return gtk_text_iter_get_text (start, end);
1491   else
1492     return gtk_text_iter_get_visible_text (start, end);
1493 }
1494
1495 /**
1496  * gtk_text_buffer_get_slice:
1497  * @buffer: a #GtkTextBuffer
1498  * @start: start of a range
1499  * @end: end of a range
1500  * @include_hidden_chars: whether to include invisible text
1501  *
1502  * Returns the text in the range [@start,@end). Excludes undisplayed
1503  * text (text marked with tags that set the invisibility attribute) if
1504  * @include_hidden_chars is FALSE. The returned string includes a
1505  * 0xFFFC character whenever the buffer contains
1506  * embedded images, so byte and character indexes into
1507  * the returned string <emphasis>do</emphasis> correspond to byte
1508  * and character indexes into the buffer. Contrast with
1509  * gtk_text_buffer_get_text (). Note that 0xFFFC can occur in normal
1510  * text as well, so it is not a reliable indicator that a pixbuf or
1511  * widget is in the buffer.
1512  *
1513  * Return value: an allocated UTF-8 string
1514  **/
1515 gchar*
1516 gtk_text_buffer_get_slice (GtkTextBuffer      *buffer,
1517                            const GtkTextIter *start,
1518                            const GtkTextIter *end,
1519                            gboolean             include_hidden_chars)
1520 {
1521   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1522   g_return_val_if_fail (start != NULL, NULL);
1523   g_return_val_if_fail (end != NULL, NULL);
1524   g_return_val_if_fail (gtk_text_iter_get_buffer (start) == buffer, NULL);
1525   g_return_val_if_fail (gtk_text_iter_get_buffer (end) == buffer, NULL);
1526   
1527   if (include_hidden_chars)
1528     return gtk_text_iter_get_slice (start, end);
1529   else
1530     return gtk_text_iter_get_visible_slice (start, end);
1531 }
1532
1533 /*
1534  * Pixbufs
1535  */
1536
1537 static void
1538 gtk_text_buffer_real_insert_pixbuf (GtkTextBuffer     *buffer,
1539                                     GtkTextIter       *iter,
1540                                     GdkPixbuf         *pixbuf)
1541
1542   _gtk_text_btree_insert_pixbuf (iter, pixbuf);
1543
1544   g_signal_emit (buffer, signals[CHANGED], 0);
1545 }
1546
1547 /**
1548  * gtk_text_buffer_insert_pixbuf:
1549  * @buffer: a #GtkTextBuffer
1550  * @iter: location to insert the pixbuf
1551  * @pixbuf: a #GdkPixbuf
1552  *
1553  * Inserts an image into the text buffer at @iter. The image will be
1554  * counted as one character in character counts, and when obtaining
1555  * the buffer contents as a string, will be represented by the Unicode
1556  * "object replacement character" 0xFFFC. Note that the "slice"
1557  * variants for obtaining portions of the buffer as a string include
1558  * this character for pixbufs, but the "text" variants do
1559  * not. e.g. see gtk_text_buffer_get_slice() and
1560  * gtk_text_buffer_get_text().
1561  * 
1562  **/
1563 void
1564 gtk_text_buffer_insert_pixbuf         (GtkTextBuffer      *buffer,
1565                                        GtkTextIter        *iter,
1566                                        GdkPixbuf          *pixbuf)
1567 {
1568   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1569   g_return_if_fail (iter != NULL);
1570   g_return_if_fail (GDK_IS_PIXBUF (pixbuf));
1571   g_return_if_fail (gtk_text_iter_get_buffer (iter) == buffer);
1572   
1573   g_signal_emit (buffer, signals[INSERT_PIXBUF], 0,
1574                  iter, pixbuf);
1575 }
1576
1577 /*
1578  * Child anchor
1579  */
1580
1581
1582 static void
1583 gtk_text_buffer_real_insert_anchor (GtkTextBuffer      *buffer,
1584                                     GtkTextIter        *iter,
1585                                     GtkTextChildAnchor *anchor)
1586 {
1587   _gtk_text_btree_insert_child_anchor (iter, anchor);
1588
1589   g_signal_emit (buffer, signals[CHANGED], 0);
1590 }
1591
1592 /**
1593  * gtk_text_buffer_insert_child_anchor:
1594  * @buffer: a #GtkTextBuffer
1595  * @iter: location to insert the anchor
1596  * @anchor: a #GtkTextChildAnchor
1597  *
1598  * Inserts a child widget anchor into the text buffer at @iter. The
1599  * anchor will be counted as one character in character counts, and
1600  * when obtaining the buffer contents as a string, will be represented
1601  * by the Unicode "object replacement character" 0xFFFC. Note that the
1602  * "slice" variants for obtaining portions of the buffer as a string
1603  * include this character for child anchors, but the "text" variants do
1604  * not. e.g. see gtk_text_buffer_get_slice() and
1605  * gtk_text_buffer_get_text(). Consider
1606  * gtk_text_buffer_create_child_anchor() as a more convenient
1607  * alternative to this function. The buffer will add a reference to
1608  * the anchor, so you can unref it after insertion.
1609  * 
1610  **/
1611 void
1612 gtk_text_buffer_insert_child_anchor (GtkTextBuffer      *buffer,
1613                                      GtkTextIter        *iter,
1614                                      GtkTextChildAnchor *anchor)
1615 {
1616   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1617   g_return_if_fail (iter != NULL);
1618   g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
1619   g_return_if_fail (gtk_text_iter_get_buffer (iter) == buffer);
1620   
1621   g_signal_emit (buffer, signals[INSERT_CHILD_ANCHOR], 0,
1622                  iter, anchor);
1623 }
1624
1625
1626 /**
1627  * gtk_text_buffer_create_child_anchor:
1628  * @buffer: a #GtkTextBuffer
1629  * @iter: location in the buffer
1630  * 
1631  * This is a convenience function which simply creates a child anchor
1632  * with gtk_text_child_anchor_new() and inserts it into the buffer
1633  * with gtk_text_buffer_insert_child_anchor(). The new anchor is
1634  * owned by the buffer; no reference count is returned to
1635  * the caller of gtk_text_buffer_create_child_anchor().
1636  * 
1637  * Return value: the created child anchor
1638  **/
1639 GtkTextChildAnchor*
1640 gtk_text_buffer_create_child_anchor (GtkTextBuffer *buffer,
1641                                      GtkTextIter   *iter)
1642 {
1643   GtkTextChildAnchor *anchor;
1644   
1645   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1646   g_return_val_if_fail (iter != NULL, NULL);
1647   g_return_val_if_fail (gtk_text_iter_get_buffer (iter) == buffer, NULL);
1648   
1649   anchor = gtk_text_child_anchor_new ();
1650
1651   gtk_text_buffer_insert_child_anchor (buffer, iter, anchor);
1652
1653   g_object_unref (anchor);
1654
1655   return anchor;
1656 }
1657
1658 /*
1659  * Mark manipulation
1660  */
1661
1662 static void
1663 gtk_text_buffer_mark_set (GtkTextBuffer     *buffer,
1664                           const GtkTextIter *location,
1665                           GtkTextMark       *mark)
1666 {
1667   /* IMO this should NOT work like insert_text and delete_range,
1668    * where the real action happens in the default handler.
1669    * 
1670    * The reason is that the default handler would be _required_,
1671    * i.e. the whole widget would start breaking and segfaulting if the
1672    * default handler didn't get run. So you can't really override the
1673    * default handler or stop the emission; that is, this signal is
1674    * purely for notification, and not to allow users to modify the
1675    * default behavior.
1676    */
1677
1678   g_object_ref (mark);
1679
1680   g_signal_emit (buffer,
1681                  signals[MARK_SET],
1682                  0,
1683                  location,
1684                  mark);
1685
1686   g_object_unref (mark);
1687 }
1688
1689 /**
1690  * gtk_text_buffer_set_mark:
1691  * @buffer:       a #GtkTextBuffer
1692  * @mark_name:    name of the mark
1693  * @iter:         location for the mark.
1694  * @left_gravity: if the mark is created by this function, gravity for the new
1695  *                mark.
1696  * @should_exist: if %TRUE, warn if the mark does not exist, and return
1697  *                immediately.
1698  *
1699  * Move the mark to the given position, if not @should_exist, create the mark.
1700  *
1701  * Return value: mark
1702  **/
1703 static GtkTextMark*
1704 gtk_text_buffer_set_mark (GtkTextBuffer *buffer,
1705                           GtkTextMark *existing_mark,
1706                           const gchar *mark_name,
1707                           const GtkTextIter *iter,
1708                           gboolean left_gravity,
1709                           gboolean should_exist)
1710 {
1711   GtkTextIter location;
1712   GtkTextMark *mark;
1713
1714   g_return_val_if_fail (gtk_text_iter_get_buffer (iter) == buffer, NULL);
1715   
1716   mark = _gtk_text_btree_set_mark (get_btree (buffer),
1717                                    existing_mark,
1718                                    mark_name,
1719                                    left_gravity,
1720                                    iter,
1721                                    should_exist);
1722   
1723   if (_gtk_text_btree_mark_is_insert (get_btree (buffer), mark) ||
1724       _gtk_text_btree_mark_is_selection_bound (get_btree (buffer), mark))
1725     {
1726       update_selection_clipboards (buffer);
1727     }
1728
1729   _gtk_text_btree_get_iter_at_mark (get_btree (buffer),
1730                                    &location,
1731                                    mark);
1732
1733   gtk_text_buffer_mark_set (buffer, &location, mark);
1734
1735   return mark;
1736 }
1737
1738 /**
1739  * gtk_text_buffer_create_mark:
1740  * @buffer: a #GtkTextBuffer
1741  * @mark_name: name for mark, or %NULL
1742  * @where: location to place mark
1743  * @left_gravity: whether the mark has left gravity
1744  *
1745  * Creates a mark at position @where. If @mark_name is %NULL, the mark
1746  * is anonymous; otherwise, the mark can be retrieved by name using
1747  * gtk_text_buffer_get_mark (). If a mark has left gravity, and text is
1748  * inserted at the mark's current location, the mark will be moved to
1749  * the left of the newly-inserted text. If the mark has right gravity
1750  * (@left_gravity = %FALSE), the mark will end up on the right of
1751  * newly-inserted text. The standard left-to-right cursor is a mark
1752  * with right gravity (when you type, the cursor stays on the right
1753  * side of the text you're typing).
1754  *
1755  * The caller of this function does <emphasis>not</emphasis> own a reference
1756  * to the returned #GtkTextMark, so you can ignore the return value
1757  * if you like. Marks are owned by the buffer and go away when the
1758  * buffer does.
1759  *
1760  * Emits the "mark_set" signal as notification of the mark's initial
1761  * placement.
1762  *
1763  * Return value: the new #GtkTextMark object
1764  **/
1765 GtkTextMark*
1766 gtk_text_buffer_create_mark (GtkTextBuffer *buffer,
1767                              const gchar *mark_name,
1768                              const GtkTextIter *where,
1769                              gboolean left_gravity)
1770 {
1771   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1772
1773   return gtk_text_buffer_set_mark (buffer, NULL, mark_name, where,
1774                                    left_gravity, FALSE);
1775 }
1776
1777 /**
1778  * gtk_text_buffer_move_mark:
1779  * @buffer: a #GtkTextBuffer
1780  * @mark: a #GtkTextMark
1781  * @where: new location for @mark in @buffer
1782  *
1783  * Moves @mark to the new location @where. Emits the "mark_set" signal
1784  * as notification of the move.
1785  **/
1786 void
1787 gtk_text_buffer_move_mark (GtkTextBuffer *buffer,
1788                            GtkTextMark *mark,
1789                            const GtkTextIter *where)
1790 {
1791   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
1792   g_return_if_fail (!gtk_text_mark_get_deleted (mark));
1793   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1794
1795   gtk_text_buffer_set_mark (buffer, mark, NULL, where, FALSE, TRUE);
1796 }
1797
1798 /**
1799  * gtk_text_buffer_get_iter_at_mark:
1800  * @buffer: a #GtkTextBuffer
1801  * @iter: iterator to initialize
1802  * @mark: a #GtkTextMark in @buffer
1803  *
1804  * Initializes @iter with the current position of @mark.
1805  **/
1806 void
1807 gtk_text_buffer_get_iter_at_mark (GtkTextBuffer *buffer,
1808                                   GtkTextIter *iter,
1809                                   GtkTextMark *mark)
1810 {
1811   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
1812   g_return_if_fail (!gtk_text_mark_get_deleted (mark));
1813   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1814
1815   _gtk_text_btree_get_iter_at_mark (get_btree (buffer),
1816                                     iter,
1817                                     mark);
1818 }
1819
1820 /**
1821  * gtk_text_buffer_delete_mark:
1822  * @buffer: a #GtkTextBuffer
1823  * @mark: a #GtkTextMark in @buffer
1824  *
1825  * Deletes @mark, so that it's no longer located anywhere in the
1826  * buffer. Removes the reference the buffer holds to the mark, so if
1827  * you haven't called g_object_ref () on the mark, it will be freed. Even
1828  * if the mark isn't freed, most operations on @mark become
1829  * invalid. There is no way to undelete a
1830  * mark. gtk_text_mark_get_deleted () will return TRUE after this
1831  * function has been called on a mark; gtk_text_mark_get_deleted ()
1832  * indicates that a mark no longer belongs to a buffer. The "mark_deleted"
1833  * signal will be emitted as notification after the mark is deleted.
1834  **/
1835 void
1836 gtk_text_buffer_delete_mark (GtkTextBuffer *buffer,
1837                              GtkTextMark   *mark)
1838 {
1839   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
1840   g_return_if_fail (!gtk_text_mark_get_deleted (mark));
1841   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1842
1843   g_object_ref (mark);
1844
1845   _gtk_text_btree_remove_mark (get_btree (buffer), mark);
1846
1847   /* See rationale above for MARK_SET on why we emit this after
1848    * removing the mark, rather than removing the mark in a default
1849    * handler.
1850    */
1851   g_signal_emit (buffer, signals[MARK_DELETED],
1852                  0,
1853                  mark);
1854
1855   g_object_unref (mark);
1856 }
1857
1858 /**
1859  * gtk_text_buffer_get_mark:
1860  * @buffer: a #GtkTextBuffer
1861  * @name: a mark name
1862  *
1863  * Returns the mark named @name in buffer @buffer, or NULL if no such
1864  * mark exists in the buffer.
1865  *
1866  * Return value: a #GtkTextMark, or NULL
1867  **/
1868 GtkTextMark*
1869 gtk_text_buffer_get_mark (GtkTextBuffer      *buffer,
1870                           const gchar         *name)
1871 {
1872   GtkTextMark *mark;
1873
1874   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1875   g_return_val_if_fail (name != NULL, NULL);
1876
1877   mark = _gtk_text_btree_get_mark_by_name (get_btree (buffer), name);
1878
1879   return mark;
1880 }
1881
1882
1883 /**
1884  * gtk_text_buffer_move_mark_by_name:
1885  * @buffer: a #GtkTextBuffer
1886  * @name: name of a mark
1887  * @where: new location for mark
1888  *
1889  * Moves the mark named @name (which must exist) to location @where.
1890  * See gtk_text_buffer_move_mark () for details.
1891  **/
1892 void
1893 gtk_text_buffer_move_mark_by_name (GtkTextBuffer     *buffer,
1894                                    const gchar       *name,
1895                                    const GtkTextIter *where)
1896 {
1897   GtkTextMark *mark;
1898
1899   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1900   g_return_if_fail (name != NULL);
1901
1902   mark = _gtk_text_btree_get_mark_by_name (get_btree (buffer), name);
1903
1904   if (mark == NULL)
1905     {
1906       g_warning ("%s: no mark named '%s'", G_STRLOC, name);
1907       return;
1908     }
1909
1910   gtk_text_buffer_move_mark (buffer, mark, where);
1911 }
1912
1913 /**
1914  * gtk_text_buffer_delete_mark_by_name:
1915  * @buffer: a #GtkTextBuffer
1916  * @name: name of a mark in @buffer
1917  *
1918  * Deletes the mark named @name; the mark must exist. See
1919  * gtk_text_buffer_delete_mark () for details.
1920  **/
1921 void
1922 gtk_text_buffer_delete_mark_by_name (GtkTextBuffer     *buffer,
1923                                      const gchar       *name)
1924 {
1925   GtkTextMark *mark;
1926
1927   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
1928   g_return_if_fail (name != NULL);
1929
1930   mark = _gtk_text_btree_get_mark_by_name (get_btree (buffer), name);
1931
1932   if (mark == NULL)
1933     {
1934       g_warning ("%s: no mark named '%s'", G_STRLOC, name);
1935       return;
1936     }
1937
1938   gtk_text_buffer_delete_mark (buffer, mark);
1939 }
1940
1941 /**
1942  * gtk_text_buffer_get_insert:
1943  * @buffer: a #GtkTextBuffer
1944  *
1945  * Returns the mark that represents the cursor (insertion point).
1946  * Equivalent to calling gtk_text_buffer_get_mark () to get the mark
1947  * named "insert", but very slightly more efficient, and involves less
1948  * typing.
1949  *
1950  * Return value: insertion point mark
1951  **/
1952 GtkTextMark*
1953 gtk_text_buffer_get_insert (GtkTextBuffer *buffer)
1954 {
1955   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1956
1957   /* FIXME use struct member in btree */
1958   return gtk_text_buffer_get_mark (buffer, "insert");
1959 }
1960
1961 /**
1962  * gtk_text_buffer_get_selection_bound:
1963  * @buffer: a #GtkTextBuffer
1964  *
1965  * Returns the mark that represents the selection bound.  Equivalent
1966  * to calling gtk_text_buffer_get_mark () to get the mark named
1967  * "selection_bound", but very slightly more efficient, and involves
1968  * less typing.
1969  *
1970  * The currently-selected text in @buffer is the region between the
1971  * "selection_bound" and "insert" marks. If "selection_bound" and
1972  * "insert" are in the same place, then there is no current selection.
1973  * gtk_text_buffer_get_selection_bounds() is another convenient function
1974  * for handling the selection, if you just want to know whether there's a
1975  * selection and what its bounds are.
1976  *
1977  * Return value: selection bound mark
1978  **/
1979 GtkTextMark*
1980 gtk_text_buffer_get_selection_bound (GtkTextBuffer *buffer)
1981 {
1982   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
1983
1984   /* FIXME use struct member in btree */
1985   return gtk_text_buffer_get_mark (buffer, "selection_bound");
1986 }
1987
1988 /**
1989  * gtk_text_buffer_get_iter_at_child_anchor:
1990  * @buffer: a #GtkTextBuffer
1991  * @iter: an iterator to be initialized
1992  * @anchor: a child anchor that appears in @buffer
1993  *
1994  * Obtains the location of @anchor within @buffer.
1995  * 
1996  **/
1997 void
1998 gtk_text_buffer_get_iter_at_child_anchor (GtkTextBuffer      *buffer,
1999                                           GtkTextIter        *iter,
2000                                           GtkTextChildAnchor *anchor)
2001 {
2002   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2003   g_return_if_fail (iter != NULL);
2004   g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
2005   g_return_if_fail (!gtk_text_child_anchor_get_deleted (anchor));
2006   
2007   _gtk_text_btree_get_iter_at_child_anchor (get_btree (buffer),
2008                                            iter,
2009                                            anchor);
2010 }
2011
2012 /**
2013  * gtk_text_buffer_place_cursor:
2014  * @buffer: a #GtkTextBuffer
2015  * @where: where to put the cursor
2016  *
2017  * This function moves the "insert" and "selection_bound" marks
2018  * simultaneously.  If you move them to the same place in two steps
2019  * with gtk_text_buffer_move_mark(), you will temporarily select a
2020  * region in between their old and new locations, which can be pretty
2021  * inefficient since the temporarily-selected region will force stuff
2022  * to be recalculated. This function moves them as a unit, which can
2023  * be optimized.
2024  **/
2025 void
2026 gtk_text_buffer_place_cursor (GtkTextBuffer     *buffer,
2027                               const GtkTextIter *where)
2028 {
2029   gtk_text_buffer_select_range (buffer, where, where);
2030 }
2031
2032
2033 /**
2034  * gtk_text_buffer_select_range:
2035  * @buffer: a #GtkTextBuffer
2036  * @ins: where to put the "insert" mark
2037  * @bound: where to put the "selection_bound" mark
2038  *
2039  * This function moves the "insert" and "selection_bound" marks
2040  * simultaneously.  If you move them in two steps
2041  * with gtk_text_buffer_move_mark(), you will temporarily select a
2042  * region in between their old and new locations, which can be pretty
2043  * inefficient since the temporarily-selected region will force stuff
2044  * to be recalculated. This function moves them as a unit, which can
2045  * be optimized.
2046  *
2047  * Since: 2.4
2048  **/
2049 void
2050 gtk_text_buffer_select_range (GtkTextBuffer     *buffer,
2051                               const GtkTextIter *ins,
2052                               const GtkTextIter *bound)
2053 {
2054   GtkTextIter real_ins;
2055   GtkTextIter real_bound;
2056
2057   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2058
2059   real_ins = *ins;
2060   real_bound = *bound;
2061
2062   _gtk_text_btree_select_range (get_btree (buffer), &real_ins, &real_bound);
2063   gtk_text_buffer_mark_set (buffer, &real_ins,
2064                             gtk_text_buffer_get_mark (buffer,
2065                                                       "insert"));
2066   gtk_text_buffer_mark_set (buffer, &real_bound,
2067                             gtk_text_buffer_get_mark (buffer,
2068                                                       "selection_bound"));
2069   update_selection_clipboards (buffer);
2070 }
2071
2072 /*
2073  * Tags
2074  */
2075
2076 /**
2077  * gtk_text_buffer_create_tag:
2078  * @buffer: a #GtkTextBuffer
2079  * @tag_name: name of the new tag, or %NULL
2080  * @first_property_name: name of first property to set, or %NULL
2081  * @Varargs: %NULL-terminated list of property names and values
2082  *
2083  *
2084  * Creates a tag and adds it to the tag table for @buffer.
2085  * Equivalent to calling gtk_text_tag_new () and then adding the
2086  * tag to the buffer's tag table. The returned tag is owned by
2087  * the buffer's tag table, so the ref count will be equal to one.
2088  *
2089  * If @tag_name is %NULL, the tag is anonymous.
2090  *
2091  * If @tag_name is non-%NULL, a tag called @tag_name must not already
2092  * exist in the tag table for this buffer.
2093  *
2094  * The @first_property_name argument and subsequent arguments are a list
2095  * of properties to set on the tag, as with g_object_set().
2096  *
2097  * Return value: a new tag
2098  **/
2099 GtkTextTag*
2100 gtk_text_buffer_create_tag (GtkTextBuffer *buffer,
2101                             const gchar   *tag_name,
2102                             const gchar   *first_property_name,
2103                             ...)
2104 {
2105   GtkTextTag *tag;
2106   va_list list;
2107   
2108   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
2109
2110   tag = gtk_text_tag_new (tag_name);
2111
2112   gtk_text_tag_table_add (get_table (buffer), tag);
2113
2114   if (first_property_name)
2115     {
2116       va_start (list, first_property_name);
2117       g_object_set_valist (G_OBJECT (tag), first_property_name, list);
2118       va_end (list);
2119     }
2120   
2121   g_object_unref (tag);
2122
2123   return tag;
2124 }
2125
2126 static void
2127 gtk_text_buffer_real_apply_tag (GtkTextBuffer *buffer,
2128                                 GtkTextTag *tag,
2129                                 const GtkTextIter *start,
2130                                 const GtkTextIter *end)
2131 {
2132   if (tag->table != buffer->tag_table)
2133     {
2134       g_warning ("Can only apply tags that are in the tag table for the buffer");
2135       return;
2136     }
2137   
2138   _gtk_text_btree_tag (start, end, tag, TRUE);
2139 }
2140
2141 static void
2142 gtk_text_buffer_real_remove_tag (GtkTextBuffer *buffer,
2143                                  GtkTextTag *tag,
2144                                  const GtkTextIter *start,
2145                                  const GtkTextIter *end)
2146 {
2147   if (tag->table != buffer->tag_table)
2148     {
2149       g_warning ("Can only remove tags that are in the tag table for the buffer");
2150       return;
2151     }
2152   
2153   _gtk_text_btree_tag (start, end, tag, FALSE);
2154 }
2155
2156 static void
2157 gtk_text_buffer_real_changed (GtkTextBuffer *buffer)
2158 {
2159   gtk_text_buffer_set_modified (buffer, TRUE);
2160 }
2161
2162 static void
2163 gtk_text_buffer_emit_tag (GtkTextBuffer *buffer,
2164                           GtkTextTag *tag,
2165                           gboolean apply,
2166                           const GtkTextIter *start,
2167                           const GtkTextIter *end)
2168 {
2169   GtkTextIter start_tmp = *start;
2170   GtkTextIter end_tmp = *end;
2171
2172   g_return_if_fail (tag != NULL);
2173
2174   gtk_text_iter_order (&start_tmp, &end_tmp);
2175
2176   if (apply)
2177     g_signal_emit (buffer, signals[APPLY_TAG],
2178                    0,
2179                    tag, &start_tmp, &end_tmp);
2180   else
2181     g_signal_emit (buffer, signals[REMOVE_TAG],
2182                    0,
2183                    tag, &start_tmp, &end_tmp);
2184 }
2185
2186
2187 /**
2188  * gtk_text_buffer_apply_tag:
2189  * @buffer: a #GtkTextBuffer
2190  * @tag: a #GtkTextTag
2191  * @start: one bound of range to be tagged
2192  * @end: other bound of range to be tagged
2193  *
2194  * Emits the "apply_tag" signal on @buffer. The default
2195  * handler for the signal applies @tag to the given range.
2196  * @start and @end do not have to be in order.
2197  * 
2198  **/
2199 void
2200 gtk_text_buffer_apply_tag (GtkTextBuffer *buffer,
2201                            GtkTextTag    *tag,
2202                            const GtkTextIter *start,
2203                            const GtkTextIter *end)
2204 {
2205   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2206   g_return_if_fail (GTK_IS_TEXT_TAG (tag));
2207   g_return_if_fail (start != NULL);
2208   g_return_if_fail (end != NULL);
2209   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2210   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2211   g_return_if_fail (tag->table == buffer->tag_table);
2212   
2213   gtk_text_buffer_emit_tag (buffer, tag, TRUE, start, end);
2214 }
2215
2216 /**
2217  * gtk_text_buffer_remove_tag:
2218  * @buffer: a #GtkTextBuffer
2219  * @tag: a #GtkTextTag
2220  * @start: one bound of range to be untagged
2221  * @end: other bound of range to be untagged
2222  *
2223  * Emits the "remove_tag" signal. The default handler for the signal
2224  * removes all occurrences of @tag from the given range. @start and
2225  * @end don't have to be in order.
2226  * 
2227  **/
2228 void
2229 gtk_text_buffer_remove_tag (GtkTextBuffer *buffer,
2230                             GtkTextTag    *tag,
2231                             const GtkTextIter *start,
2232                             const GtkTextIter *end)
2233
2234 {
2235   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2236   g_return_if_fail (GTK_IS_TEXT_TAG (tag));
2237   g_return_if_fail (start != NULL);
2238   g_return_if_fail (end != NULL);
2239   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2240   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2241   g_return_if_fail (tag->table == buffer->tag_table);
2242   
2243   gtk_text_buffer_emit_tag (buffer, tag, FALSE, start, end);
2244 }
2245
2246
2247 /**
2248  * gtk_text_buffer_apply_tag_by_name:
2249  * @buffer: a #GtkTextBuffer
2250  * @name: name of a named #GtkTextTag
2251  * @start: one bound of range to be tagged
2252  * @end: other bound of range to be tagged
2253  *
2254  * Calls gtk_text_tag_table_lookup() on the buffer's tag table to
2255  * get a #GtkTextTag, then calls gtk_text_buffer_apply_tag().
2256  * 
2257  **/
2258 void
2259 gtk_text_buffer_apply_tag_by_name (GtkTextBuffer *buffer,
2260                                    const gchar   *name,
2261                                    const GtkTextIter *start,
2262                                    const GtkTextIter *end)
2263 {
2264   GtkTextTag *tag;
2265
2266   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2267   g_return_if_fail (name != NULL);
2268   g_return_if_fail (start != NULL);
2269   g_return_if_fail (end != NULL);
2270   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2271   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2272
2273   tag = gtk_text_tag_table_lookup (get_table (buffer),
2274                                    name);
2275
2276   if (tag == NULL)
2277     {
2278       g_warning ("Unknown tag `%s'", name);
2279       return;
2280     }
2281
2282   gtk_text_buffer_emit_tag (buffer, tag, TRUE, start, end);
2283 }
2284
2285 /**
2286  * gtk_text_buffer_remove_tag_by_name:
2287  * @buffer: a #GtkTextBuffer
2288  * @name: name of a #GtkTextTag
2289  * @start: one bound of range to be untagged
2290  * @end: other bound of range to be untagged
2291  *
2292  * Calls gtk_text_tag_table_lookup() on the buffer's tag table to
2293  * get a #GtkTextTag, then calls gtk_text_buffer_remove_tag().
2294  * 
2295  * 
2296  **/
2297 void
2298 gtk_text_buffer_remove_tag_by_name (GtkTextBuffer *buffer,
2299                                     const gchar *name,
2300                                     const GtkTextIter *start,
2301                                     const GtkTextIter *end)
2302 {
2303   GtkTextTag *tag;
2304
2305   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2306   g_return_if_fail (name != NULL);
2307   g_return_if_fail (start != NULL);
2308   g_return_if_fail (end != NULL);
2309   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2310   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2311   
2312   tag = gtk_text_tag_table_lookup (get_table (buffer),
2313                                    name);
2314
2315   if (tag == NULL)
2316     {
2317       g_warning ("Unknown tag `%s'", name);
2318       return;
2319     }
2320
2321   gtk_text_buffer_emit_tag (buffer, tag, FALSE, start, end);
2322 }
2323
2324 static gint
2325 pointer_cmp (gconstpointer a,
2326              gconstpointer b)
2327 {
2328   if (a < b)
2329     return -1;
2330   else if (a > b)
2331     return 1;
2332   else
2333     return 0;
2334 }
2335
2336 /**
2337  * gtk_text_buffer_remove_all_tags:
2338  * @buffer: a #GtkTextBuffer
2339  * @start: one bound of range to be untagged
2340  * @end: other bound of range to be untagged
2341  * 
2342  * Removes all tags in the range between @start and @end.  Be careful
2343  * with this function; it could remove tags added in code unrelated to
2344  * the code you're currently writing. That is, using this function is
2345  * probably a bad idea if you have two or more unrelated code sections
2346  * that add tags.
2347  **/
2348 void
2349 gtk_text_buffer_remove_all_tags (GtkTextBuffer     *buffer,
2350                                  const GtkTextIter *start,
2351                                  const GtkTextIter *end)
2352 {
2353   GtkTextIter first, second, tmp;
2354   GSList *tags;
2355   GSList *tmp_list;
2356   GSList *prev;
2357   GtkTextTag *tag;
2358   
2359   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2360   g_return_if_fail (start != NULL);
2361   g_return_if_fail (end != NULL);
2362   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2363   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2364   
2365   first = *start;
2366   second = *end;
2367
2368   gtk_text_iter_order (&first, &second);
2369
2370   /* Get all tags turned on at the start */
2371   tags = gtk_text_iter_get_tags (&first);
2372   
2373   /* Find any that are toggled on within the range */
2374   tmp = first;
2375   while (gtk_text_iter_forward_to_tag_toggle (&tmp, NULL))
2376     {
2377       GSList *toggled;
2378       GSList *tmp_list2;
2379
2380       if (gtk_text_iter_compare (&tmp, &second) >= 0)
2381         break; /* past the end of the range */
2382       
2383       toggled = gtk_text_iter_get_toggled_tags (&tmp, TRUE);
2384
2385       /* We could end up with a really big-ass list here.
2386        * Fix it someday.
2387        */
2388       tmp_list2 = toggled;
2389       while (tmp_list2 != NULL)
2390         {
2391           tags = g_slist_prepend (tags, tmp_list2->data);
2392
2393           tmp_list2 = g_slist_next (tmp_list2);
2394         }
2395
2396       g_slist_free (toggled);
2397     }
2398   
2399   /* Sort the list */
2400   tags = g_slist_sort (tags, pointer_cmp);
2401
2402   /* Strip duplicates */
2403   tag = NULL;
2404   prev = NULL;
2405   tmp_list = tags;
2406   while (tmp_list != NULL)
2407     {
2408       if (tag == tmp_list->data)
2409         {
2410           /* duplicate */
2411           if (prev)
2412             prev->next = tmp_list->next;
2413
2414           tmp_list->next = NULL;
2415
2416           g_slist_free (tmp_list);
2417
2418           tmp_list = prev->next;
2419           /* prev is unchanged */
2420         }
2421       else
2422         {
2423           /* not a duplicate */
2424           tag = GTK_TEXT_TAG (tmp_list->data);
2425           prev = tmp_list;
2426           tmp_list = tmp_list->next;
2427         }
2428     }
2429
2430   g_slist_foreach (tags, (GFunc) g_object_ref, NULL);
2431   
2432   tmp_list = tags;
2433   while (tmp_list != NULL)
2434     {
2435       tag = GTK_TEXT_TAG (tmp_list->data);
2436
2437       gtk_text_buffer_remove_tag (buffer, tag, &first, &second);
2438       
2439       tmp_list = tmp_list->next;
2440     }
2441
2442   g_slist_foreach (tags, (GFunc) g_object_unref, NULL);
2443   
2444   g_slist_free (tags);
2445 }
2446
2447
2448 /*
2449  * Obtain various iterators
2450  */
2451
2452 /**
2453  * gtk_text_buffer_get_iter_at_line_offset:
2454  * @buffer: a #GtkTextBuffer
2455  * @iter: iterator to initialize
2456  * @line_number: line number counting from 0
2457  * @char_offset: char offset from start of line
2458  *
2459  * Obtains an iterator pointing to @char_offset within the given
2460  * line. The @char_offset must exist, offsets off the end of the line
2461  * are not allowed. Note <emphasis>characters</emphasis>, not bytes;
2462  * UTF-8 may encode one character as multiple bytes.
2463  * 
2464  **/
2465 void
2466 gtk_text_buffer_get_iter_at_line_offset (GtkTextBuffer      *buffer,
2467                                          GtkTextIter        *iter,
2468                                          gint                line_number,
2469                                          gint                char_offset)
2470 {
2471   g_return_if_fail (iter != NULL);
2472   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2473
2474   _gtk_text_btree_get_iter_at_line_char (get_btree (buffer),
2475                                          iter, line_number, char_offset);
2476 }
2477
2478 /**
2479  * gtk_text_buffer_get_iter_at_line_index:
2480  * @buffer: a #GtkTextBuffer 
2481  * @iter: iterator to initialize 
2482  * @line_number: line number counting from 0
2483  * @byte_index: byte index from start of line
2484  *
2485  * Obtains an iterator pointing to @byte_index within the given line.
2486  * @byte_index must be the start of a UTF-8 character, and must not be
2487  * beyond the end of the line.  Note <emphasis>bytes</emphasis>, not
2488  * characters; UTF-8 may encode one character as multiple bytes.
2489  * 
2490  **/
2491 void
2492 gtk_text_buffer_get_iter_at_line_index  (GtkTextBuffer *buffer,
2493                                          GtkTextIter   *iter,
2494                                          gint           line_number,
2495                                          gint           byte_index)
2496 {
2497   g_return_if_fail (iter != NULL);
2498   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2499
2500   _gtk_text_btree_get_iter_at_line_byte (get_btree (buffer),
2501                                          iter, line_number, byte_index);
2502 }
2503
2504 /**
2505  * gtk_text_buffer_get_iter_at_line:
2506  * @buffer: a #GtkTextBuffer 
2507  * @iter: iterator to initialize
2508  * @line_number: line number counting from 0
2509  * 
2510  * Initializes @iter to the start of the given line.
2511  **/
2512 void
2513 gtk_text_buffer_get_iter_at_line    (GtkTextBuffer      *buffer,
2514                                      GtkTextIter        *iter,
2515                                      gint                line_number)
2516 {
2517   g_return_if_fail (iter != NULL);
2518   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2519
2520   gtk_text_buffer_get_iter_at_line_offset (buffer, iter, line_number, 0);
2521 }
2522
2523 /**
2524  * gtk_text_buffer_get_iter_at_offset:
2525  * @buffer: a #GtkTextBuffer 
2526  * @iter: iterator to initialize
2527  * @char_offset: char offset from start of buffer, counting from 0, or -1
2528  *
2529  * Initializes @iter to a position @char_offset chars from the start
2530  * of the entire buffer. If @char_offset is -1 or greater than the number
2531  * of characters in the buffer, @iter is initialized to the end iterator,
2532  * the iterator one past the last valid character in the buffer.
2533  **/
2534 void
2535 gtk_text_buffer_get_iter_at_offset         (GtkTextBuffer      *buffer,
2536                                             GtkTextIter        *iter,
2537                                             gint                char_offset)
2538 {
2539   g_return_if_fail (iter != NULL);
2540   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2541
2542   _gtk_text_btree_get_iter_at_char (get_btree (buffer), iter, char_offset);
2543 }
2544
2545 /**
2546  * gtk_text_buffer_get_start_iter:
2547  * @buffer: a #GtkTextBuffer
2548  * @iter: iterator to initialize
2549  *
2550  * Initialized @iter with the first position in the text buffer. This
2551  * is the same as using gtk_text_buffer_get_iter_at_offset() to get
2552  * the iter at character offset 0.
2553  **/
2554 void
2555 gtk_text_buffer_get_start_iter (GtkTextBuffer *buffer,
2556                                 GtkTextIter   *iter)
2557 {
2558   g_return_if_fail (iter != NULL);
2559   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2560
2561   _gtk_text_btree_get_iter_at_char (get_btree (buffer), iter, 0);
2562 }
2563
2564 /**
2565  * gtk_text_buffer_get_end_iter:
2566  * @buffer: a #GtkTextBuffer 
2567  * @iter: iterator to initialize
2568  *
2569  * Initializes @iter with the "end iterator," one past the last valid
2570  * character in the text buffer. If dereferenced with
2571  * gtk_text_iter_get_char(), the end iterator has a character value of
2572  * 0. The entire buffer lies in the range from the first position in
2573  * the buffer (call gtk_text_buffer_get_start_iter() to get
2574  * character position 0) to the end iterator.
2575  * 
2576  **/
2577 void
2578 gtk_text_buffer_get_end_iter         (GtkTextBuffer      *buffer,
2579                                        GtkTextIter        *iter)
2580 {
2581   g_return_if_fail (iter != NULL);
2582   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2583
2584   _gtk_text_btree_get_end_iter (get_btree (buffer), iter);
2585 }
2586
2587 /**
2588  * gtk_text_buffer_get_bounds:
2589  * @buffer: a #GtkTextBuffer 
2590  * @start: iterator to initialize with first position in the buffer
2591  * @end: iterator to initialize with the end iterator
2592  *
2593  * Retrieves the first and last iterators in the buffer, i.e. the
2594  * entire buffer lies within the range [@start,@end).
2595  * 
2596  **/
2597 void
2598 gtk_text_buffer_get_bounds (GtkTextBuffer *buffer,
2599                             GtkTextIter   *start,
2600                             GtkTextIter   *end)
2601 {
2602   g_return_if_fail (start != NULL);
2603   g_return_if_fail (end != NULL);
2604   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2605
2606   _gtk_text_btree_get_iter_at_char (get_btree (buffer), start, 0);
2607   _gtk_text_btree_get_end_iter (get_btree (buffer), end);
2608 }
2609
2610 /*
2611  * Modified flag
2612  */
2613
2614 /**
2615  * gtk_text_buffer_get_modified:
2616  * @buffer: a #GtkTextBuffer 
2617  * 
2618  * Indicates whether the buffer has been modified since the last call
2619  * to gtk_text_buffer_set_modified() set the modification flag to
2620  * %FALSE. Used for example to enable a "save" function in a text
2621  * editor.
2622  * 
2623  * Return value: %TRUE if the buffer has been modified
2624  **/
2625 gboolean
2626 gtk_text_buffer_get_modified (GtkTextBuffer *buffer)
2627 {
2628   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
2629
2630   return buffer->modified;
2631 }
2632
2633 /**
2634  * gtk_text_buffer_set_modified:
2635  * @buffer: a #GtkTextBuffer 
2636  * @setting: modification flag setting
2637  *
2638  * Used to keep track of whether the buffer has been modified since the
2639  * last time it was saved. Whenever the buffer is saved to disk, call
2640  * gtk_text_buffer_set_modified (@buffer, FALSE). When the buffer is modified,
2641  * it will automatically toggled on the modified bit again. When the modified
2642  * bit flips, the buffer emits a "modified_changed" signal.
2643  * 
2644  **/
2645 void
2646 gtk_text_buffer_set_modified (GtkTextBuffer      *buffer,
2647                               gboolean             setting)
2648 {
2649   gboolean fixed_setting;
2650
2651   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2652
2653   fixed_setting = setting != FALSE;
2654
2655   if (buffer->modified == fixed_setting)
2656     return;
2657   else
2658     {
2659       buffer->modified = fixed_setting;
2660       g_signal_emit (buffer, signals[MODIFIED_CHANGED], 0);
2661     }
2662 }
2663
2664
2665 /*
2666  * Assorted other stuff
2667  */
2668
2669 /**
2670  * gtk_text_buffer_get_line_count:
2671  * @buffer: a #GtkTextBuffer 
2672  * 
2673  * Obtains the number of lines in the buffer. This value is cached, so
2674  * the function is very fast.
2675  * 
2676  * Return value: number of lines in the buffer
2677  **/
2678 gint
2679 gtk_text_buffer_get_line_count (GtkTextBuffer *buffer)
2680 {
2681   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), 0);
2682
2683   return _gtk_text_btree_line_count (get_btree (buffer));
2684 }
2685
2686 /**
2687  * gtk_text_buffer_get_char_count:
2688  * @buffer: a #GtkTextBuffer 
2689  * 
2690  * Gets the number of characters in the buffer; note that characters
2691  * and bytes are not the same, you can't e.g. expect the contents of
2692  * the buffer in string form to be this many bytes long. The character
2693  * count is cached, so this function is very fast.
2694  * 
2695  * Return value: number of characters in the buffer
2696  **/
2697 gint
2698 gtk_text_buffer_get_char_count (GtkTextBuffer *buffer)
2699 {
2700   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), 0);
2701
2702   return _gtk_text_btree_char_count (get_btree (buffer));
2703 }
2704
2705 /* Called when we lose the primary selection.
2706  */
2707 static void
2708 clipboard_clear_selection_cb (GtkClipboard *clipboard,
2709                               gpointer      data)
2710 {
2711   /* Move selection_bound to the insertion point */
2712   GtkTextIter insert;
2713   GtkTextIter selection_bound;
2714   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
2715
2716   gtk_text_buffer_get_iter_at_mark (buffer, &insert,
2717                                     gtk_text_buffer_get_mark (buffer, "insert"));
2718   gtk_text_buffer_get_iter_at_mark (buffer, &selection_bound,
2719                                     gtk_text_buffer_get_mark (buffer, "selection_bound"));
2720
2721   if (!gtk_text_iter_equal (&insert, &selection_bound))
2722     gtk_text_buffer_move_mark (buffer,
2723                                gtk_text_buffer_get_mark (buffer, "selection_bound"),
2724                                &insert);
2725 }
2726
2727 /* Called when we have the primary selection and someone else wants our
2728  * data in order to paste it.
2729  */
2730 static void
2731 clipboard_get_selection_cb (GtkClipboard     *clipboard,
2732                             GtkSelectionData *selection_data,
2733                             guint             info,
2734                             gpointer          data)
2735 {
2736   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
2737   GtkTextIter start, end;
2738
2739   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
2740     {
2741       if (selection_data->target ==
2742           gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE))
2743         {
2744           /* Provide the address of the buffer; this will only be
2745            * used within-process
2746            */
2747           gtk_selection_data_set (selection_data,
2748                                   gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE),
2749                                   8, /* bytes */
2750                                   (void*)&buffer,
2751                                   sizeof (buffer));
2752         }
2753       else
2754         {
2755           gchar *str;
2756           
2757           str = gtk_text_iter_get_visible_text (&start, &end);
2758           gtk_selection_data_set_text (selection_data, str, -1);
2759           g_free (str);
2760         }
2761     }
2762 }
2763
2764 typedef struct
2765 {
2766   GtkClipboard *clipboard;
2767   GtkTextBuffer *buffer;
2768 } ContentsBuffer;
2769
2770 static void
2771 remove_all_clipboard_contents_buffers (GtkTextBuffer *buffer)
2772 {
2773   GSList *tmp_list = buffer->clipboard_contents_buffers;
2774   while (tmp_list)
2775     {
2776       ContentsBuffer *contents_buffer = tmp_list->data;
2777
2778       g_object_unref (contents_buffer->buffer);
2779       g_free (contents_buffer);
2780           
2781       tmp_list = tmp_list->next;
2782     }
2783
2784   g_slist_free (buffer->clipboard_contents_buffers);
2785   buffer->clipboard_contents_buffers = NULL;
2786 }
2787
2788 static void
2789 remove_clipboard_contents_buffer (GtkTextBuffer *buffer,
2790                                   GtkClipboard  *clipboard)
2791 {
2792   GSList *tmp_list = buffer->clipboard_contents_buffers;
2793   while (tmp_list)
2794     {
2795       ContentsBuffer *contents_buffer = tmp_list->data;
2796       
2797       if (contents_buffer->clipboard == clipboard)
2798         {
2799           buffer->clipboard_contents_buffers = g_slist_remove (buffer->clipboard_contents_buffers, contents_buffer);
2800           
2801           g_object_unref (contents_buffer->buffer);
2802           g_free (contents_buffer);
2803           
2804           return;
2805         }
2806
2807       tmp_list = tmp_list->next;
2808     }
2809 }
2810
2811 static GtkTextBuffer *
2812 get_clipboard_contents_buffer (GtkTextBuffer *buffer,
2813                                GtkClipboard  *clipboard,
2814                                gboolean       create)
2815 {
2816   ContentsBuffer *contents_buffer;
2817   GSList *tmp_list;
2818
2819   tmp_list = buffer->clipboard_contents_buffers;
2820   while (tmp_list)
2821     {
2822       contents_buffer = tmp_list->data;
2823       if (contents_buffer->clipboard == clipboard)
2824         return contents_buffer->buffer;
2825     }
2826   
2827   if (create)
2828     {
2829       contents_buffer = g_new (ContentsBuffer, 1);
2830       contents_buffer->clipboard = clipboard;
2831       contents_buffer->buffer = gtk_text_buffer_new (gtk_text_buffer_get_tag_table (buffer));
2832
2833       g_object_set_data (G_OBJECT (contents_buffer->buffer), "gtk-text-buffer-clipboard",
2834                          GUINT_TO_POINTER (1));
2835
2836       buffer->clipboard_contents_buffers = g_slist_prepend (buffer->clipboard_contents_buffers, contents_buffer);
2837
2838       
2839       return contents_buffer->buffer;
2840     }
2841   else
2842     return NULL;
2843 }
2844
2845 /* Provide cut/copied data */
2846 static void
2847 clipboard_get_contents_cb (GtkClipboard     *clipboard,
2848                            GtkSelectionData *selection_data,
2849                            guint             info,
2850                            gpointer          data)
2851 {
2852   GtkTextBuffer *buffer;
2853   GtkTextBuffer *contents;
2854
2855   buffer = GTK_TEXT_BUFFER (data);
2856   contents = get_clipboard_contents_buffer (buffer, clipboard, FALSE);
2857   
2858   g_assert (contents); /* This should never be called unless we own the clipboard */
2859
2860   if (selection_data->target ==
2861       gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE))
2862     {
2863       /* Provide the address of the clipboard buffer; this will only
2864        * be used within-process. OK to supply a NULL value for contents.
2865        */
2866       gtk_selection_data_set (selection_data,
2867                               gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE),
2868                               8, /* bytes */
2869                               (void*)&contents,
2870                               sizeof (contents));
2871     }
2872   else
2873     {
2874       gchar *str;
2875       GtkTextIter start, end;
2876       
2877       gtk_text_buffer_get_bounds (contents, &start, &end);
2878       
2879       str = gtk_text_iter_get_visible_text (&start, &end);
2880       gtk_selection_data_set_text (selection_data, str, -1);
2881       g_free (str);
2882     }
2883 }
2884
2885 static void
2886 clipboard_clear_contents_cb (GtkClipboard *clipboard,
2887                              gpointer      data)
2888 {
2889   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
2890
2891   remove_clipboard_contents_buffer (buffer, clipboard);
2892 }
2893
2894 static void
2895 get_paste_point (GtkTextBuffer *buffer,
2896                  GtkTextIter   *iter,
2897                  gboolean       clear_afterward)
2898 {
2899   GtkTextIter insert_point;
2900   GtkTextMark *paste_point_override;
2901
2902   paste_point_override = gtk_text_buffer_get_mark (buffer,
2903                                                    "gtk_paste_point_override");
2904
2905   if (paste_point_override != NULL)
2906     {
2907       gtk_text_buffer_get_iter_at_mark (buffer, &insert_point,
2908                                         paste_point_override);
2909       if (clear_afterward)
2910         gtk_text_buffer_delete_mark (buffer,
2911                                      gtk_text_buffer_get_mark (buffer,
2912                                                                "gtk_paste_point_override"));
2913     }
2914   else
2915     {
2916       gtk_text_buffer_get_iter_at_mark (buffer, &insert_point,
2917                                         gtk_text_buffer_get_mark (buffer,
2918                                                                   "insert"));
2919     }
2920
2921   *iter = insert_point;
2922 }
2923
2924 static void
2925 pre_paste_prep (ClipboardRequest *request_data,
2926                 GtkTextIter      *insert_point)
2927 {
2928   GtkTextBuffer *buffer = request_data->buffer;
2929   
2930   get_paste_point (buffer, insert_point, TRUE);
2931
2932   /* If we're going to replace the selection, we insert before it to
2933    * avoid messing it up, then we delete the selection after inserting.
2934    */
2935   if (request_data->replace_selection)
2936     {
2937       GtkTextIter start, end;
2938       
2939       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
2940         *insert_point = start;
2941     }
2942 }
2943
2944 static void
2945 post_paste_cleanup (ClipboardRequest *request_data)
2946 {
2947   if (request_data->replace_selection)
2948     {
2949       GtkTextIter start, end;
2950       
2951       if (gtk_text_buffer_get_selection_bounds (request_data->buffer,
2952                                                 &start, &end))
2953         {
2954           if (request_data->interactive)
2955             gtk_text_buffer_delete_interactive (request_data->buffer,
2956                                                 &start,
2957                                                 &end,
2958                                                 request_data->default_editable);
2959           else
2960             gtk_text_buffer_delete (request_data->buffer, &start, &end);
2961         }
2962     }
2963 }
2964
2965 /* Called when we request a paste and receive the text data
2966  */
2967 static void
2968 clipboard_text_received (GtkClipboard *clipboard,
2969                          const gchar  *str,
2970                          gpointer      data)
2971 {
2972   ClipboardRequest *request_data = data;
2973   GtkTextBuffer *buffer = request_data->buffer;
2974
2975   if (str)
2976     {
2977       GtkTextIter insert_point;
2978       
2979       if (request_data->interactive) 
2980         gtk_text_buffer_begin_user_action (buffer);
2981
2982       pre_paste_prep (request_data, &insert_point);
2983       
2984       if (request_data->interactive) 
2985         gtk_text_buffer_insert_interactive (buffer, &insert_point,
2986                                             str, -1, request_data->default_editable);
2987       else
2988         gtk_text_buffer_insert (buffer, &insert_point,
2989                                 str, -1);
2990
2991       post_paste_cleanup (request_data);
2992       
2993       if (request_data->interactive) 
2994         gtk_text_buffer_end_user_action (buffer);
2995     }
2996
2997   g_object_unref (buffer);
2998   g_free (request_data);
2999 }
3000
3001 static GtkTextBuffer*
3002 selection_data_get_buffer (GtkSelectionData *selection_data,
3003                            ClipboardRequest *request_data)
3004 {
3005   GdkWindow *owner;
3006   GtkTextBuffer *src_buffer = NULL;
3007
3008   /* If we can get the owner, the selection is in-process */
3009   owner = gdk_selection_owner_get_for_display (selection_data->display,
3010                                                selection_data->selection);
3011
3012   if (owner == NULL)
3013     return NULL;
3014   
3015   if (gdk_window_get_window_type (owner) == GDK_WINDOW_FOREIGN)
3016     return NULL;
3017  
3018   if (selection_data->type != gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE))
3019     return NULL;
3020
3021   if (selection_data->length != sizeof (src_buffer))
3022     return NULL;
3023           
3024   memcpy (&src_buffer, selection_data->data, sizeof (src_buffer));
3025
3026   if (src_buffer == NULL)
3027     return NULL;
3028   
3029   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (src_buffer), NULL);
3030
3031   if (gtk_text_buffer_get_tag_table (src_buffer) !=
3032       gtk_text_buffer_get_tag_table (request_data->buffer))
3033     return NULL;
3034   
3035   return src_buffer;
3036 }
3037
3038 #if 0
3039 /* These are pretty handy functions; maybe something like them
3040  * should be in the public API. Also, there are other places in this
3041  * file where they could be used.
3042  */
3043 static gpointer
3044 save_iter (const GtkTextIter *iter,
3045            gboolean           left_gravity)
3046 {
3047   return gtk_text_buffer_create_mark (gtk_text_iter_get_buffer (iter),
3048                                       NULL,
3049                                       iter,
3050                                       TRUE);
3051 }
3052
3053 static void
3054 restore_iter (const GtkTextIter *iter,
3055               gpointer           save_id)
3056 {
3057   gtk_text_buffer_get_iter_at_mark (gtk_text_mark_get_buffer (save_id),
3058                                     (GtkTextIter*) iter,
3059                                     save_id);
3060   gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (save_id),
3061                                save_id);
3062 }
3063 #endif
3064
3065 static void
3066 paste_from_buffer (ClipboardRequest    *request_data,
3067                    GtkTextBuffer       *src_buffer,
3068                    const GtkTextIter   *start,
3069                    const GtkTextIter   *end)
3070 {
3071   GtkTextIter insert_point;
3072   GtkTextBuffer *buffer = request_data->buffer;
3073   
3074   /* We're about to emit a bunch of signals, so be safe */
3075   g_object_ref (src_buffer);
3076   
3077   pre_paste_prep (request_data, &insert_point);
3078   
3079   if (request_data->interactive) 
3080     gtk_text_buffer_begin_user_action (buffer);
3081
3082   if (!gtk_text_iter_equal (start, end))
3083     {
3084       if (!request_data->interactive ||
3085           (gtk_text_iter_can_insert (&insert_point,
3086                                      request_data->default_editable)))
3087         gtk_text_buffer_real_insert_range (buffer,
3088                                            &insert_point,
3089                                            start,
3090                                            end,
3091                                            request_data->interactive);
3092     }
3093
3094   post_paste_cleanup (request_data);
3095       
3096   if (request_data->interactive) 
3097     gtk_text_buffer_end_user_action (buffer);
3098
3099   g_object_unref (src_buffer);
3100   g_free (request_data);
3101 }
3102
3103 static void
3104 clipboard_clipboard_buffer_received (GtkClipboard     *clipboard,
3105                                      GtkSelectionData *selection_data,
3106                                      gpointer          data)
3107 {
3108   ClipboardRequest *request_data = data;
3109   GtkTextBuffer *src_buffer;
3110   
3111   src_buffer = selection_data_get_buffer (selection_data, request_data); 
3112
3113   if (src_buffer)
3114     {
3115       GtkTextIter start, end;
3116
3117       if (g_object_get_data (G_OBJECT (src_buffer), "gtk-text-buffer-clipboard"))
3118         {
3119           gtk_text_buffer_get_bounds (src_buffer, &start, &end);
3120       
3121           paste_from_buffer (request_data, src_buffer,
3122                              &start, &end);
3123         }
3124       else
3125         {
3126           if (gtk_text_buffer_get_selection_bounds (src_buffer, &start, &end))
3127             paste_from_buffer (request_data, src_buffer,
3128                                &start, &end);
3129         }
3130     }
3131   else
3132     {
3133       /* Request the text selection instead */
3134       gtk_clipboard_request_text (clipboard,
3135                                   clipboard_text_received,
3136                                   data);
3137     }
3138 }
3139
3140 static const GtkTargetEntry targets[] = {
3141   { "STRING", 0, TARGET_STRING },
3142   { "TEXT",   0, TARGET_TEXT },
3143   { "COMPOUND_TEXT", 0, TARGET_COMPOUND_TEXT },
3144   { "UTF8_STRING", 0, TARGET_UTF8_STRING },
3145   { "GTK_TEXT_BUFFER_CONTENTS", 0, TARGET_TEXT_BUFFER_CONTENTS }
3146 };
3147
3148 typedef struct
3149 {
3150   GtkClipboard *clipboard;
3151   guint ref_count;
3152 } SelectionClipboard;
3153
3154 static void
3155 update_selection_clipboards (GtkTextBuffer *buffer)
3156 {
3157   GSList *tmp_list = buffer->selection_clipboards;
3158   while (tmp_list)
3159     {
3160       GtkTextIter start;
3161       GtkTextIter end;
3162       
3163       SelectionClipboard *selection_clipboard = tmp_list->data;
3164       GtkClipboard *clipboard = selection_clipboard->clipboard;
3165
3166       /* Determine whether we have a selection and adjust X selection
3167        * accordingly.
3168        */
3169       if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3170         {
3171           if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (buffer))
3172             gtk_clipboard_clear (clipboard);
3173         }
3174       else
3175         {
3176           /* Even if we already have the selection, we need to update our
3177            * timestamp.
3178            */
3179           if (!gtk_clipboard_set_with_owner (clipboard, targets, G_N_ELEMENTS (targets),
3180                                              clipboard_get_selection_cb,
3181                                              clipboard_clear_selection_cb,
3182                                              G_OBJECT (buffer)))
3183             clipboard_clear_selection_cb (clipboard, buffer);
3184         }
3185
3186       tmp_list = tmp_list->next;
3187     }
3188 }
3189
3190 static SelectionClipboard *
3191 find_selection_clipboard (GtkTextBuffer *buffer,
3192                           GtkClipboard  *clipboard)
3193 {
3194   GSList *tmp_list = buffer->selection_clipboards;
3195   while (tmp_list)
3196     {
3197       SelectionClipboard *selection_clipboard = tmp_list->data;
3198       if (selection_clipboard->clipboard == clipboard)
3199         return selection_clipboard;
3200       
3201       tmp_list = tmp_list->next;
3202     }
3203
3204   return NULL;
3205 }
3206
3207 /**
3208  * gtk_text_buffer_add_selection_clipboard:
3209  * @buffer: a #GtkTextBuffer
3210  * @clipboard: a #GtkClipboard
3211  * 
3212  * Adds @clipboard to the list of clipboards in which the selection contents
3213  * of @buffer are available. In most cases, @clipboard will be the #GtkClipboard
3214  * of type %GDK_SELECTION_PRIMARY for a view of @buffer.
3215  **/
3216 void
3217 gtk_text_buffer_add_selection_clipboard (GtkTextBuffer *buffer,
3218                                          GtkClipboard  *clipboard)
3219 {
3220   SelectionClipboard *selection_clipboard;
3221
3222   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3223   g_return_if_fail (clipboard != NULL);
3224
3225   selection_clipboard = find_selection_clipboard (buffer, clipboard);
3226   if (selection_clipboard)
3227     {
3228       selection_clipboard->ref_count++;
3229     }
3230   else
3231     {
3232       selection_clipboard = g_new (SelectionClipboard, 1);
3233
3234       selection_clipboard->clipboard = clipboard;
3235       selection_clipboard->ref_count = 1;
3236
3237       buffer->selection_clipboards = g_slist_prepend (buffer->selection_clipboards, selection_clipboard);
3238     }
3239 }
3240
3241 /**
3242  * gtk_text_buffer_remove_selection_clipboard:
3243  * @buffer: a #GtkTextBuffer
3244  * @clipboard: a #GtkClipboard added to @buffer by gtk_text_buffer_add_selection_clipboard().
3245  * 
3246  * Removes a #GtkClipboard added with gtk_text_buffer_add_selection_clipboard()
3247  **/
3248 void 
3249 gtk_text_buffer_remove_selection_clipboard (GtkTextBuffer *buffer,
3250                                             GtkClipboard  *clipboard)
3251 {
3252   SelectionClipboard *selection_clipboard;
3253
3254   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3255   g_return_if_fail (clipboard != NULL);
3256
3257   selection_clipboard = find_selection_clipboard (buffer, clipboard);
3258   g_return_if_fail (selection_clipboard != NULL);
3259
3260   selection_clipboard->ref_count--;
3261   if (selection_clipboard->ref_count == 0)
3262     {
3263       if (gtk_clipboard_get_owner (selection_clipboard->clipboard) == G_OBJECT (buffer))
3264         gtk_clipboard_clear (selection_clipboard->clipboard);
3265
3266       buffer->selection_clipboards = g_slist_remove (buffer->selection_clipboards,
3267                                                      selection_clipboard);
3268       
3269       g_free (selection_clipboard);
3270     }
3271 }
3272
3273 static void
3274 remove_all_selection_clipboards (GtkTextBuffer *buffer)
3275 {
3276   GSList *tmp_list = buffer->selection_clipboards;
3277   while (tmp_list)
3278     {
3279       SelectionClipboard *selection_clipboard = tmp_list->data;
3280       
3281       if (gtk_clipboard_get_owner (selection_clipboard->clipboard) == G_OBJECT (buffer))
3282         gtk_clipboard_clear (selection_clipboard->clipboard);
3283       
3284       g_free (selection_clipboard);
3285
3286       tmp_list = tmp_list->next;
3287     }
3288
3289   g_slist_free (buffer->selection_clipboards);
3290   buffer->selection_clipboards = NULL;
3291 }
3292
3293 /**
3294  * gtk_text_buffer_paste_clipboard:
3295  * @buffer: a #GtkTextBuffer
3296  * @clipboard: the #GtkClipboard to paste from
3297  * @override_location: location to insert pasted text, or %NULL for at the cursor
3298  * @default_editable: whether the buffer is editable by default
3299  *
3300  * Pastes the contents of a clipboard at the insertion point, or at @override_location.
3301  * (Note: pasting is asynchronous, that is, we'll ask for the paste data and
3302  * return, and at some point later after the main loop runs, the paste
3303  * data will be inserted.)
3304  * 
3305  **/
3306 void
3307 gtk_text_buffer_paste_clipboard (GtkTextBuffer *buffer,
3308                                  GtkClipboard  *clipboard,
3309                                  GtkTextIter   *override_location,
3310                                  gboolean       default_editable)
3311 {
3312   ClipboardRequest *data = g_new (ClipboardRequest, 1);
3313   GtkTextIter paste_point;
3314   GtkTextIter start, end;
3315
3316   if (override_location != NULL)
3317     gtk_text_buffer_create_mark (buffer,
3318                                  "gtk_paste_point_override",
3319                                  override_location, FALSE);
3320
3321   data->buffer = buffer;
3322   g_object_ref (buffer);
3323   data->interactive = TRUE;
3324   data->default_editable = default_editable;
3325
3326   /* When pasting with the cursor inside the selection area, you
3327    * replace the selection with the new text, otherwise, you
3328    * simply insert the new text at the point where the click
3329    * occured, unselecting any selected text. The replace_selection
3330    * flag toggles this behavior.
3331    */
3332   data->replace_selection = FALSE;
3333   
3334   get_paste_point (buffer, &paste_point, FALSE);
3335   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end) &&
3336       (gtk_text_iter_in_range (&paste_point, &start, &end) ||
3337        gtk_text_iter_equal (&paste_point, &end)))
3338     data->replace_selection = TRUE;
3339
3340   gtk_clipboard_request_contents (clipboard,
3341                                   gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE),
3342                                   clipboard_clipboard_buffer_received, data);
3343 }
3344
3345 /**
3346  * gtk_text_buffer_delete_selection:
3347  * @buffer: a #GtkTextBuffer 
3348  * @interactive: whether the deletion is caused by user interaction
3349  * @default_editable: whether the buffer is editable by default
3350  *
3351  * Deletes the range between the "insert" and "selection_bound" marks,
3352  * that is, the currently-selected text. If @interactive is %TRUE,
3353  * the editability of the selection will be considered (users can't delete
3354  * uneditable text).
3355  * 
3356  * Return value: whether there was a non-empty selection to delete
3357  **/
3358 gboolean
3359 gtk_text_buffer_delete_selection (GtkTextBuffer *buffer,
3360                                   gboolean interactive,
3361                                   gboolean default_editable)
3362 {
3363   GtkTextIter start;
3364   GtkTextIter end;
3365
3366   if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3367     {
3368       return FALSE; /* No selection */
3369     }
3370   else
3371     {
3372       if (interactive)
3373         {
3374           gtk_text_buffer_begin_user_action (buffer);
3375           gtk_text_buffer_delete_interactive (buffer, &start, &end, default_editable);
3376           gtk_text_buffer_end_user_action (buffer);
3377         }
3378       else
3379         gtk_text_buffer_delete (buffer, &start, &end);
3380
3381       return TRUE; /* We deleted stuff */
3382     }
3383 }
3384
3385 /**
3386  * gtk_text_buffer_backspace:
3387  * @buffer: a #GtkTextBuffer
3388  * @iter: a position in @buffer
3389  * @interactive: whether the deletion is caused by user interaction
3390  * @default_editable: whether the buffer is editable by default
3391  * 
3392  * Performs the appropriate action as if the user hit the delete
3393  * key with the cursor at the position specified by @iter. In the
3394  * normal case a single character will be deleted, but when
3395  * combining accents are involved, more than one character can
3396  * be deleted, and when precomposed character and accent combinations,
3397  * less than one character will be deleted.
3398  *
3399  * @iter must be at a cursor position.
3400  *
3401  * Return value: %TRUE if tbe buffer was modified
3402
3403  * Since: 2.6
3404  **/
3405 gboolean
3406 gtk_text_buffer_backspace (GtkTextBuffer *buffer,
3407                            GtkTextIter   *iter,
3408                            gboolean       interactive,
3409                            gboolean       default_editable)
3410 {
3411   gchar *cluster_text;
3412   GtkTextIter start;
3413   GtkTextIter end;
3414   gboolean retval = FALSE;
3415   const PangoLogAttr *attrs;
3416   int offset;
3417   gboolean backspace_deletes_character;
3418
3419   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
3420   g_return_val_if_fail (iter != NULL, FALSE);
3421
3422   start = *iter;
3423   end = *iter;
3424
3425   attrs = _gtk_text_buffer_get_line_log_attrs (buffer, &start, NULL);
3426   offset = gtk_text_iter_get_line_offset (&start);
3427   backspace_deletes_character = attrs[offset].backspace_deletes_character;
3428
3429   gtk_text_iter_backward_cursor_position (&start);
3430
3431   if (gtk_text_iter_equal (&start, &end))
3432     return FALSE;
3433     
3434   cluster_text = gtk_text_iter_get_text (&start, &end);
3435
3436   if (interactive)
3437     gtk_text_buffer_begin_user_action (buffer);
3438   
3439   if (gtk_text_buffer_delete_interactive (buffer, &start, &end,
3440                                           default_editable))
3441     {
3442       if (backspace_deletes_character)
3443         {
3444           gchar *normalized_text = g_utf8_normalize (cluster_text,
3445                                                      strlen (cluster_text),
3446                                                      G_NORMALIZE_NFD);
3447           glong len = g_utf8_strlen (normalized_text, -1);
3448           
3449           if (len > 1)
3450             gtk_text_buffer_insert_interactive (buffer,
3451                                                 &start,
3452                                                 normalized_text,
3453                                                 g_utf8_offset_to_pointer (normalized_text, len - 1) - normalized_text,
3454                                                 default_editable);
3455           
3456           g_free (normalized_text);
3457         }
3458
3459       retval = TRUE;
3460     }
3461   
3462   if (interactive)
3463     gtk_text_buffer_end_user_action (buffer);
3464   
3465   g_free (cluster_text);
3466
3467   return retval;
3468 }
3469
3470 static void
3471 cut_or_copy (GtkTextBuffer *buffer,
3472              GtkClipboard  *clipboard,
3473              gboolean       delete_region_after,
3474              gboolean       interactive,
3475              gboolean       default_editable)
3476 {
3477   /* We prefer to cut the selected region between selection_bound and
3478    * insertion point. If that region is empty, then we cut the region
3479    * between the "anchor" and the insertion point (this is for
3480    * C-space and M-w and other Emacs-style copy/yank keys). Note that
3481    * insert and selection_bound are guaranteed to exist, but the
3482    * anchor only exists sometimes.
3483    */
3484   GtkTextIter start;
3485   GtkTextIter end;
3486   
3487   if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3488     {
3489       /* Let's try the anchor thing */
3490       GtkTextMark * anchor = gtk_text_buffer_get_mark (buffer, "anchor");
3491
3492       if (anchor == NULL)
3493         return;
3494       else
3495         {
3496           gtk_text_buffer_get_iter_at_mark (buffer, &end, anchor);
3497           gtk_text_iter_order (&start, &end);
3498         }
3499     }
3500
3501   if (!gtk_text_iter_equal (&start, &end))
3502     {
3503       GtkTextIter ins;
3504       GtkTextBuffer *contents;
3505
3506       remove_clipboard_contents_buffer (buffer, clipboard);
3507       contents = get_clipboard_contents_buffer (buffer, clipboard, TRUE);
3508
3509       gtk_text_buffer_get_iter_at_offset (contents, &ins, 0);
3510       
3511       gtk_text_buffer_insert_range (contents, &ins, &start, &end);
3512                                     
3513       if (!gtk_clipboard_set_with_owner (clipboard, targets, G_N_ELEMENTS (targets),
3514                                          clipboard_get_contents_cb,
3515                                          clipboard_clear_contents_cb,
3516                                          G_OBJECT (buffer)))
3517         clipboard_clear_contents_cb (clipboard, buffer);      
3518
3519       if (delete_region_after)
3520         {
3521           if (interactive)
3522             gtk_text_buffer_delete_interactive (buffer, &start, &end,
3523                                                 default_editable);
3524           else
3525             gtk_text_buffer_delete (buffer, &start, &end);
3526         }
3527     }
3528 }
3529
3530 /**
3531  * gtk_text_buffer_cut_clipboard:
3532  * @buffer: a #GtkTextBuffer
3533  * @clipboard: the #GtkClipboard object to cut to.
3534  * @default_editable: default editability of the buffer
3535  *
3536  * Copies the currently-selected text to a clipboard, then deletes
3537  * said text if it's editable.
3538  * 
3539  **/
3540 void
3541 gtk_text_buffer_cut_clipboard (GtkTextBuffer *buffer,
3542                                GtkClipboard  *clipboard,
3543                                gboolean       default_editable)
3544 {
3545   gtk_text_buffer_begin_user_action (buffer);
3546   cut_or_copy (buffer, clipboard, TRUE, TRUE, default_editable);
3547   gtk_text_buffer_end_user_action (buffer);
3548 }
3549
3550 /**
3551  * gtk_text_buffer_copy_clipboard:
3552  * @buffer: a #GtkTextBuffer 
3553  * @clipboard: the #GtkClipboard object to copy to.
3554  *
3555  * Copies the currently-selected text to a clipboard.
3556  * 
3557  **/
3558 void
3559 gtk_text_buffer_copy_clipboard (GtkTextBuffer *buffer,
3560                                 GtkClipboard  *clipboard)
3561 {
3562   gtk_text_buffer_begin_user_action (buffer);
3563   cut_or_copy (buffer, clipboard, FALSE, TRUE, TRUE);
3564   gtk_text_buffer_end_user_action (buffer);
3565 }
3566
3567
3568 /**
3569  * gtk_text_buffer_get_selection_bounds:
3570  * @buffer: a #GtkTextBuffer a #GtkTextBuffer
3571  * @start: iterator to initialize with selection start
3572  * @end: iterator to initialize with selection end
3573  *
3574  * Returns %TRUE if some text is selected; places the bounds
3575  * of the selection in @start and @end (if the selection has length 0,
3576  * then @start and @end are filled in with the same value).
3577  * @start and @end will be in ascending order. If @start and @end are
3578  * NULL, then they are not filled in, but the return value still indicates
3579  * whether text is selected.
3580  *
3581  * Return value: whether the selection has nonzero length
3582  **/
3583 gboolean
3584 gtk_text_buffer_get_selection_bounds   (GtkTextBuffer      *buffer,
3585                                         GtkTextIter        *start,
3586                                         GtkTextIter        *end)
3587 {
3588   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
3589
3590   return _gtk_text_btree_get_selection_bounds (get_btree (buffer), start, end);
3591 }
3592
3593 /**
3594  * gtk_text_buffer_begin_user_action:
3595  * @buffer: a #GtkTextBuffer
3596  * 
3597  * Called to indicate that the buffer operations between here and a
3598  * call to gtk_text_buffer_end_user_action() are part of a single
3599  * user-visible operation. The operations between
3600  * gtk_text_buffer_begin_user_action() and
3601  * gtk_text_buffer_end_user_action() can then be grouped when creating
3602  * an undo stack. #GtkTextBuffer maintains a count of calls to
3603  * gtk_text_buffer_begin_user_action() that have not been closed with
3604  * a call to gtk_text_buffer_end_user_action(), and emits the "begin_user_action"
3605  * and "end_user_action" signals only for the outermost pair of calls.
3606  * This allows you to build user actions from other user actions.
3607  *
3608  * The "interactive" buffer mutation functions, such as
3609  * gtk_text_buffer_insert_interactive(), automatically call begin/end
3610  * user action around the buffer operations they perform, so there's
3611  * no need to add extra calls if you user action consists solely of a
3612  * single call to one of those functions.
3613  **/
3614 void
3615 gtk_text_buffer_begin_user_action (GtkTextBuffer *buffer)
3616 {
3617   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3618
3619   buffer->user_action_count += 1;
3620   
3621   if (buffer->user_action_count == 1)
3622     {
3623       /* Outermost nested user action begin emits the signal */
3624       g_signal_emit (buffer, signals[BEGIN_USER_ACTION], 0);
3625     }
3626 }
3627
3628 /**
3629  * gtk_text_buffer_end_user_action:
3630  * @buffer: a #GtkTextBuffer
3631  * 
3632  * Should be paired with a call to gtk_text_buffer_begin_user_action().
3633  * See that function for a full explanation.
3634  **/
3635 void
3636 gtk_text_buffer_end_user_action (GtkTextBuffer *buffer)
3637 {
3638   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3639   g_return_if_fail (buffer->user_action_count > 0);
3640   
3641   buffer->user_action_count -= 1;
3642   
3643   if (buffer->user_action_count == 0)
3644     {
3645       /* Ended the outermost-nested user action end, so emit the signal */
3646       g_signal_emit (buffer, signals[END_USER_ACTION], 0);
3647     }
3648 }
3649
3650 /*
3651  * Logical attribute cache
3652  */
3653
3654 #define ATTR_CACHE_SIZE 2
3655
3656 typedef struct _CacheEntry CacheEntry;
3657 struct _CacheEntry
3658 {
3659   gint line;
3660   gint char_len;
3661   PangoLogAttr *attrs;
3662 };
3663
3664
3665 struct _GtkTextLogAttrCache
3666 {
3667   gint chars_changed_stamp;
3668   CacheEntry entries[ATTR_CACHE_SIZE];
3669 };
3670
3671 static void
3672 free_log_attr_cache (GtkTextLogAttrCache *cache)
3673 {
3674   gint i = 0;
3675   while (i < ATTR_CACHE_SIZE)
3676     {
3677       g_free (cache->entries[i].attrs);
3678       ++i;
3679     }
3680   g_free (cache);
3681 }
3682
3683 static void
3684 clear_log_attr_cache (GtkTextLogAttrCache *cache)
3685 {
3686   gint i = 0;
3687   while (i < ATTR_CACHE_SIZE)
3688     {
3689       g_free (cache->entries[i].attrs);
3690       cache->entries[i].attrs = NULL;
3691       ++i;
3692     }
3693 }
3694
3695 static PangoLogAttr*
3696 compute_log_attrs (const GtkTextIter *iter,
3697                    gint              *char_lenp)
3698 {
3699   GtkTextIter start;
3700   GtkTextIter end;
3701   gchar *paragraph;
3702   gint char_len, byte_len;
3703   PangoLogAttr *attrs = NULL;
3704   
3705   start = *iter;
3706   end = *iter;
3707
3708   gtk_text_iter_set_line_offset (&start, 0);
3709   gtk_text_iter_forward_line (&end);
3710
3711   paragraph = gtk_text_iter_get_slice (&start, &end);
3712   char_len = g_utf8_strlen (paragraph, -1);
3713   byte_len = strlen (paragraph);
3714
3715   g_assert (char_len > 0);
3716
3717   if (char_lenp)
3718     *char_lenp = char_len;
3719   
3720   attrs = g_new (PangoLogAttr, char_len + 1);
3721
3722   /* FIXME we need to follow PangoLayout and allow different language
3723    * tags within the paragraph
3724    */
3725   pango_get_log_attrs (paragraph, byte_len, -1,
3726                        gtk_text_iter_get_language (&start),
3727                        attrs,
3728                        char_len + 1);
3729   
3730   g_free (paragraph);
3731
3732   return attrs;
3733 }
3734
3735 /* The return value from this is valid until you call this a second time.
3736  */
3737 const PangoLogAttr*
3738 _gtk_text_buffer_get_line_log_attrs (GtkTextBuffer     *buffer,
3739                                      const GtkTextIter *anywhere_in_line,
3740                                      gint              *char_len)
3741 {
3742   gint line;
3743   GtkTextLogAttrCache *cache;
3744   gint i;
3745   
3746   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
3747   g_return_val_if_fail (anywhere_in_line != NULL, NULL);
3748
3749   /* special-case for empty last line in buffer */
3750   if (gtk_text_iter_is_end (anywhere_in_line) &&
3751       gtk_text_iter_get_line_offset (anywhere_in_line) == 0)
3752     {
3753       if (char_len)
3754         *char_len = 0;
3755       return NULL;
3756     }
3757   
3758   /* FIXME we also need to recompute log attrs if the language tag at
3759    * the start of a paragraph changes
3760    */
3761   
3762   if (buffer->log_attr_cache == NULL)
3763     {
3764       buffer->log_attr_cache = g_new0 (GtkTextLogAttrCache, 1);
3765       buffer->log_attr_cache->chars_changed_stamp =
3766         _gtk_text_btree_get_chars_changed_stamp (get_btree (buffer));
3767     }
3768   else if (buffer->log_attr_cache->chars_changed_stamp !=
3769            _gtk_text_btree_get_chars_changed_stamp (get_btree (buffer)))
3770     {
3771       clear_log_attr_cache (buffer->log_attr_cache);
3772     }
3773   
3774   cache = buffer->log_attr_cache;
3775   line = gtk_text_iter_get_line (anywhere_in_line);
3776
3777   i = 0;
3778   while (i < ATTR_CACHE_SIZE)
3779     {
3780       if (cache->entries[i].attrs &&
3781           cache->entries[i].line == line)
3782         {
3783           if (char_len)
3784             *char_len = cache->entries[i].char_len;
3785           return cache->entries[i].attrs;
3786         }
3787       ++i;
3788     }
3789   
3790   /* Not in cache; open up the first cache entry */
3791   if (cache->entries[ATTR_CACHE_SIZE-1].attrs)
3792     g_free (cache->entries[ATTR_CACHE_SIZE-1].attrs);
3793   
3794   g_memmove (cache->entries + 1, cache->entries,
3795              sizeof (CacheEntry) * (ATTR_CACHE_SIZE - 1));
3796
3797   cache->entries[0].line = line;
3798   cache->entries[0].attrs = compute_log_attrs (anywhere_in_line,
3799                                                &cache->entries[0].char_len);
3800
3801   if (char_len)
3802     *char_len = cache->entries[0].char_len;
3803   
3804   return cache->entries[0].attrs;
3805 }
3806
3807 void
3808 _gtk_text_buffer_notify_will_remove_tag (GtkTextBuffer *buffer,
3809                                          GtkTextTag    *tag)
3810 {
3811   /* This removes tag from the buffer, but DOESN'T emit the
3812    * remove_tag signal, because we can't afford to have user
3813    * code messing things up at this point; the tag MUST be removed
3814    * entirely.
3815    */
3816   if (buffer->btree)
3817     _gtk_text_btree_notify_will_remove_tag (buffer->btree, tag);
3818 }
3819
3820 /*
3821  * Debug spew
3822  */
3823
3824 void
3825 _gtk_text_buffer_spew (GtkTextBuffer *buffer)
3826 {
3827   _gtk_text_btree_spew (get_btree (buffer));
3828 }