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