]> Pileus Git - ~andy/gtk/blob - gtk/gtktextbuffer.c
Document.
[~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  * Since: 2.4
2031  **/
2032 void
2033 gtk_text_buffer_select_range (GtkTextBuffer     *buffer,
2034                               const GtkTextIter *ins,
2035                               const GtkTextIter *bound)
2036 {
2037   GtkTextIter real_ins;
2038   GtkTextIter real_bound;
2039
2040   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2041
2042   real_ins = *ins;
2043   real_bound = *bound;
2044
2045   _gtk_text_btree_select_range (get_btree (buffer), &real_ins, &real_bound);
2046   gtk_text_buffer_mark_set (buffer, &real_ins,
2047                             gtk_text_buffer_get_mark (buffer,
2048                                                       "insert"));
2049   gtk_text_buffer_mark_set (buffer, &real_bound,
2050                             gtk_text_buffer_get_mark (buffer,
2051                                                       "selection_bound"));
2052 }
2053
2054 /*
2055  * Tags
2056  */
2057
2058 /**
2059  * gtk_text_buffer_create_tag:
2060  * @buffer: a #GtkTextBuffer
2061  * @tag_name: name of the new tag, or %NULL
2062  * @first_property_name: name of first property to set, or %NULL
2063  * @Varargs: %NULL-terminated list of property names and values
2064  *
2065  *
2066  * Creates a tag and adds it to the tag table for @buffer.
2067  * Equivalent to calling gtk_text_tag_new () and then adding the
2068  * tag to the buffer's tag table. The returned tag is owned by
2069  * the buffer's tag table, so the ref count will be equal to one.
2070  *
2071  * If @tag_name is %NULL, the tag is anonymous.
2072  *
2073  * If @tag_name is non-%NULL, a tag called @tag_name must not already
2074  * exist in the tag table for this buffer.
2075  *
2076  * The @first_property_name argument and subsequent arguments are a list
2077  * of properties to set on the tag, as with g_object_set().
2078  *
2079  * Return value: a new tag
2080  **/
2081 GtkTextTag*
2082 gtk_text_buffer_create_tag (GtkTextBuffer *buffer,
2083                             const gchar   *tag_name,
2084                             const gchar   *first_property_name,
2085                             ...)
2086 {
2087   GtkTextTag *tag;
2088   va_list list;
2089   
2090   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
2091
2092   tag = gtk_text_tag_new (tag_name);
2093
2094   gtk_text_tag_table_add (get_table (buffer), tag);
2095
2096   if (first_property_name)
2097     {
2098       va_start (list, first_property_name);
2099       g_object_set_valist (G_OBJECT (tag), first_property_name, list);
2100       va_end (list);
2101     }
2102   
2103   g_object_unref (tag);
2104
2105   return tag;
2106 }
2107
2108 static void
2109 gtk_text_buffer_real_apply_tag (GtkTextBuffer *buffer,
2110                                 GtkTextTag *tag,
2111                                 const GtkTextIter *start,
2112                                 const GtkTextIter *end)
2113 {
2114   if (tag->table != buffer->tag_table)
2115     {
2116       g_warning ("Can only apply tags that are in the tag table for the buffer");
2117       return;
2118     }
2119   
2120   _gtk_text_btree_tag (start, end, tag, TRUE);
2121 }
2122
2123 static void
2124 gtk_text_buffer_real_remove_tag (GtkTextBuffer *buffer,
2125                                  GtkTextTag *tag,
2126                                  const GtkTextIter *start,
2127                                  const GtkTextIter *end)
2128 {
2129   if (tag->table != buffer->tag_table)
2130     {
2131       g_warning ("Can only remove tags that are in the tag table for the buffer");
2132       return;
2133     }
2134   
2135   _gtk_text_btree_tag (start, end, tag, FALSE);
2136 }
2137
2138 static void
2139 gtk_text_buffer_real_changed (GtkTextBuffer *buffer)
2140 {
2141   gtk_text_buffer_set_modified (buffer, TRUE);
2142 }
2143
2144 static void
2145 gtk_text_buffer_emit_tag (GtkTextBuffer *buffer,
2146                           GtkTextTag *tag,
2147                           gboolean apply,
2148                           const GtkTextIter *start,
2149                           const GtkTextIter *end)
2150 {
2151   GtkTextIter start_tmp = *start;
2152   GtkTextIter end_tmp = *end;
2153
2154   g_return_if_fail (tag != NULL);
2155
2156   gtk_text_iter_order (&start_tmp, &end_tmp);
2157
2158   if (apply)
2159     g_signal_emit (buffer, signals[APPLY_TAG],
2160                    0,
2161                    tag, &start_tmp, &end_tmp);
2162   else
2163     g_signal_emit (buffer, signals[REMOVE_TAG],
2164                    0,
2165                    tag, &start_tmp, &end_tmp);
2166 }
2167
2168
2169 /**
2170  * gtk_text_buffer_apply_tag:
2171  * @buffer: a #GtkTextBuffer
2172  * @tag: a #GtkTextTag
2173  * @start: one bound of range to be tagged
2174  * @end: other bound of range to be tagged
2175  *
2176  * Emits the "apply_tag" signal on @buffer. The default
2177  * handler for the signal applies @tag to the given range.
2178  * @start and @end do not have to be in order.
2179  * 
2180  **/
2181 void
2182 gtk_text_buffer_apply_tag (GtkTextBuffer *buffer,
2183                            GtkTextTag    *tag,
2184                            const GtkTextIter *start,
2185                            const GtkTextIter *end)
2186 {
2187   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2188   g_return_if_fail (GTK_IS_TEXT_TAG (tag));
2189   g_return_if_fail (start != NULL);
2190   g_return_if_fail (end != NULL);
2191   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2192   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2193   g_return_if_fail (tag->table == buffer->tag_table);
2194   
2195   gtk_text_buffer_emit_tag (buffer, tag, TRUE, start, end);
2196 }
2197
2198 /**
2199  * gtk_text_buffer_remove_tag:
2200  * @buffer: a #GtkTextBuffer
2201  * @tag: a #GtkTextTag
2202  * @start: one bound of range to be untagged
2203  * @end: other bound of range to be untagged
2204  *
2205  * Emits the "remove_tag" signal. The default handler for the signal
2206  * removes all occurrences of @tag from the given range. @start and
2207  * @end don't have to be in order.
2208  * 
2209  **/
2210 void
2211 gtk_text_buffer_remove_tag (GtkTextBuffer *buffer,
2212                             GtkTextTag    *tag,
2213                             const GtkTextIter *start,
2214                             const GtkTextIter *end)
2215
2216 {
2217   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2218   g_return_if_fail (GTK_IS_TEXT_TAG (tag));
2219   g_return_if_fail (start != NULL);
2220   g_return_if_fail (end != NULL);
2221   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2222   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2223   g_return_if_fail (tag->table == buffer->tag_table);
2224   
2225   gtk_text_buffer_emit_tag (buffer, tag, FALSE, start, end);
2226 }
2227
2228
2229 /**
2230  * gtk_text_buffer_apply_tag_by_name:
2231  * @buffer: a #GtkTextBuffer
2232  * @name: name of a named #GtkTextTag
2233  * @start: one bound of range to be tagged
2234  * @end: other bound of range to be tagged
2235  *
2236  * Calls gtk_text_tag_table_lookup() on the buffer's tag table to
2237  * get a #GtkTextTag, then calls gtk_text_buffer_apply_tag().
2238  * 
2239  **/
2240 void
2241 gtk_text_buffer_apply_tag_by_name (GtkTextBuffer *buffer,
2242                                    const gchar   *name,
2243                                    const GtkTextIter *start,
2244                                    const GtkTextIter *end)
2245 {
2246   GtkTextTag *tag;
2247
2248   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2249   g_return_if_fail (name != NULL);
2250   g_return_if_fail (start != NULL);
2251   g_return_if_fail (end != NULL);
2252   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2253   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2254
2255   tag = gtk_text_tag_table_lookup (get_table (buffer),
2256                                    name);
2257
2258   if (tag == NULL)
2259     {
2260       g_warning ("Unknown tag `%s'", name);
2261       return;
2262     }
2263
2264   gtk_text_buffer_emit_tag (buffer, tag, TRUE, start, end);
2265 }
2266
2267 /**
2268  * gtk_text_buffer_remove_tag_by_name:
2269  * @buffer: a #GtkTextBuffer
2270  * @name: name of a #GtkTextTag
2271  * @start: one bound of range to be untagged
2272  * @end: other bound of range to be untagged
2273  *
2274  * Calls gtk_text_tag_table_lookup() on the buffer's tag table to
2275  * get a #GtkTextTag, then calls gtk_text_buffer_remove_tag().
2276  * 
2277  * 
2278  **/
2279 void
2280 gtk_text_buffer_remove_tag_by_name (GtkTextBuffer *buffer,
2281                                     const gchar *name,
2282                                     const GtkTextIter *start,
2283                                     const GtkTextIter *end)
2284 {
2285   GtkTextTag *tag;
2286
2287   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2288   g_return_if_fail (name != NULL);
2289   g_return_if_fail (start != NULL);
2290   g_return_if_fail (end != NULL);
2291   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2292   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2293   
2294   tag = gtk_text_tag_table_lookup (get_table (buffer),
2295                                    name);
2296
2297   if (tag == NULL)
2298     {
2299       g_warning ("Unknown tag `%s'", name);
2300       return;
2301     }
2302
2303   gtk_text_buffer_emit_tag (buffer, tag, FALSE, start, end);
2304 }
2305
2306 static gint
2307 pointer_cmp (gconstpointer a,
2308              gconstpointer b)
2309 {
2310   if (a < b)
2311     return -1;
2312   else if (a > b)
2313     return 1;
2314   else
2315     return 0;
2316 }
2317
2318 /**
2319  * gtk_text_buffer_remove_all_tags:
2320  * @buffer: a #GtkTextBuffer
2321  * @start: one bound of range to be untagged
2322  * @end: other bound of range to be untagged
2323  * 
2324  * Removes all tags in the range between @start and @end.  Be careful
2325  * with this function; it could remove tags added in code unrelated to
2326  * the code you're currently writing. That is, using this function is
2327  * probably a bad idea if you have two or more unrelated code sections
2328  * that add tags.
2329  **/
2330 void
2331 gtk_text_buffer_remove_all_tags (GtkTextBuffer     *buffer,
2332                                  const GtkTextIter *start,
2333                                  const GtkTextIter *end)
2334 {
2335   GtkTextIter first, second, tmp;
2336   GSList *tags;
2337   GSList *tmp_list;
2338   GSList *prev;
2339   GtkTextTag *tag;
2340   
2341   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2342   g_return_if_fail (start != NULL);
2343   g_return_if_fail (end != NULL);
2344   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2345   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2346   
2347   first = *start;
2348   second = *end;
2349
2350   gtk_text_iter_order (&first, &second);
2351
2352   /* Get all tags turned on at the start */
2353   tags = gtk_text_iter_get_tags (&first);
2354   
2355   /* Find any that are toggled on within the range */
2356   tmp = first;
2357   while (gtk_text_iter_forward_to_tag_toggle (&tmp, NULL))
2358     {
2359       GSList *toggled;
2360       GSList *tmp_list2;
2361
2362       if (gtk_text_iter_compare (&tmp, &second) >= 0)
2363         break; /* past the end of the range */
2364       
2365       toggled = gtk_text_iter_get_toggled_tags (&tmp, TRUE);
2366
2367       /* We could end up with a really big-ass list here.
2368        * Fix it someday.
2369        */
2370       tmp_list2 = toggled;
2371       while (tmp_list2 != NULL)
2372         {
2373           tags = g_slist_prepend (tags, tmp_list2->data);
2374
2375           tmp_list2 = g_slist_next (tmp_list2);
2376         }
2377
2378       g_slist_free (toggled);
2379     }
2380   
2381   /* Sort the list */
2382   tags = g_slist_sort (tags, pointer_cmp);
2383
2384   /* Strip duplicates */
2385   tag = NULL;
2386   prev = NULL;
2387   tmp_list = tags;
2388   while (tmp_list != NULL)
2389     {
2390       if (tag == tmp_list->data)
2391         {
2392           /* duplicate */
2393           if (prev)
2394             prev->next = tmp_list->next;
2395
2396           tmp_list->next = NULL;
2397
2398           g_slist_free (tmp_list);
2399
2400           tmp_list = prev->next;
2401           /* prev is unchanged */
2402         }
2403       else
2404         {
2405           /* not a duplicate */
2406           tag = GTK_TEXT_TAG (tmp_list->data);
2407           prev = tmp_list;
2408           tmp_list = tmp_list->next;
2409         }
2410     }
2411
2412   g_slist_foreach (tags, (GFunc) g_object_ref, NULL);
2413   
2414   tmp_list = tags;
2415   while (tmp_list != NULL)
2416     {
2417       tag = GTK_TEXT_TAG (tmp_list->data);
2418
2419       gtk_text_buffer_remove_tag (buffer, tag, &first, &second);
2420       
2421       tmp_list = tmp_list->next;
2422     }
2423
2424   g_slist_foreach (tags, (GFunc) g_object_unref, NULL);
2425   
2426   g_slist_free (tags);
2427 }
2428
2429
2430 /*
2431  * Obtain various iterators
2432  */
2433
2434 /**
2435  * gtk_text_buffer_get_iter_at_line_offset:
2436  * @buffer: a #GtkTextBuffer
2437  * @iter: iterator to initialize
2438  * @line_number: line number counting from 0
2439  * @char_offset: char offset from start of line
2440  *
2441  * Obtains an iterator pointing to @char_offset within the given
2442  * line. The @char_offset must exist, offsets off the end of the line
2443  * are not allowed. Note <emphasis>characters</emphasis>, not bytes;
2444  * UTF-8 may encode one character as multiple bytes.
2445  * 
2446  **/
2447 void
2448 gtk_text_buffer_get_iter_at_line_offset (GtkTextBuffer      *buffer,
2449                                          GtkTextIter        *iter,
2450                                          gint                line_number,
2451                                          gint                char_offset)
2452 {
2453   g_return_if_fail (iter != NULL);
2454   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2455
2456   _gtk_text_btree_get_iter_at_line_char (get_btree (buffer),
2457                                          iter, line_number, char_offset);
2458 }
2459
2460 /**
2461  * gtk_text_buffer_get_iter_at_line_index:
2462  * @buffer: a #GtkTextBuffer 
2463  * @iter: iterator to initialize 
2464  * @line_number: line number counting from 0
2465  * @byte_index: byte index from start of line
2466  *
2467  * Obtains an iterator pointing to @byte_index within the given line.
2468  * @byte_index must be the start of a UTF-8 character, and must not be
2469  * beyond the end of the line.  Note <emphasis>bytes</emphasis>, not
2470  * characters; UTF-8 may encode one character as multiple bytes.
2471  * 
2472  **/
2473 void
2474 gtk_text_buffer_get_iter_at_line_index  (GtkTextBuffer *buffer,
2475                                          GtkTextIter   *iter,
2476                                          gint           line_number,
2477                                          gint           byte_index)
2478 {
2479   g_return_if_fail (iter != NULL);
2480   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2481
2482   _gtk_text_btree_get_iter_at_line_byte (get_btree (buffer),
2483                                          iter, line_number, byte_index);
2484 }
2485
2486 /**
2487  * gtk_text_buffer_get_iter_at_line:
2488  * @buffer: a #GtkTextBuffer 
2489  * @iter: iterator to initialize
2490  * @line_number: line number counting from 0
2491  * 
2492  * Initializes @iter to the start of the given line.
2493  **/
2494 void
2495 gtk_text_buffer_get_iter_at_line    (GtkTextBuffer      *buffer,
2496                                      GtkTextIter        *iter,
2497                                      gint                line_number)
2498 {
2499   g_return_if_fail (iter != NULL);
2500   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2501
2502   gtk_text_buffer_get_iter_at_line_offset (buffer, iter, line_number, 0);
2503 }
2504
2505 /**
2506  * gtk_text_buffer_get_iter_at_offset:
2507  * @buffer: a #GtkTextBuffer 
2508  * @iter: iterator to initialize
2509  * @char_offset: char offset from start of buffer, counting from 0, or -1
2510  *
2511  * Initializes @iter to a position @char_offset chars from the start
2512  * of the entire buffer. If @char_offset is -1 or greater than the number
2513  * of characters in the buffer, @iter is initialized to the end iterator,
2514  * the iterator one past the last valid character in the buffer.
2515  **/
2516 void
2517 gtk_text_buffer_get_iter_at_offset         (GtkTextBuffer      *buffer,
2518                                             GtkTextIter        *iter,
2519                                             gint                char_offset)
2520 {
2521   g_return_if_fail (iter != NULL);
2522   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2523
2524   _gtk_text_btree_get_iter_at_char (get_btree (buffer), iter, char_offset);
2525 }
2526
2527 /**
2528  * gtk_text_buffer_get_start_iter:
2529  * @buffer: a #GtkTextBuffer
2530  * @iter: iterator to initialize
2531  *
2532  * Initialized @iter with the first position in the text buffer. This
2533  * is the same as using gtk_text_buffer_get_iter_at_offset() to get
2534  * the iter at character offset 0.
2535  **/
2536 void
2537 gtk_text_buffer_get_start_iter (GtkTextBuffer *buffer,
2538                                 GtkTextIter   *iter)
2539 {
2540   g_return_if_fail (iter != NULL);
2541   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2542
2543   _gtk_text_btree_get_iter_at_char (get_btree (buffer), iter, 0);
2544 }
2545
2546 /**
2547  * gtk_text_buffer_get_end_iter:
2548  * @buffer: a #GtkTextBuffer 
2549  * @iter: iterator to initialize
2550  *
2551  * Initializes @iter with the "end iterator," one past the last valid
2552  * character in the text buffer. If dereferenced with
2553  * gtk_text_iter_get_char(), the end iterator has a character value of
2554  * 0. The entire buffer lies in the range from the first position in
2555  * the buffer (call gtk_text_buffer_get_start_iter() to get
2556  * character position 0) to the end iterator.
2557  * 
2558  **/
2559 void
2560 gtk_text_buffer_get_end_iter         (GtkTextBuffer      *buffer,
2561                                        GtkTextIter        *iter)
2562 {
2563   g_return_if_fail (iter != NULL);
2564   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2565
2566   _gtk_text_btree_get_end_iter (get_btree (buffer), iter);
2567 }
2568
2569 /**
2570  * gtk_text_buffer_get_bounds:
2571  * @buffer: a #GtkTextBuffer 
2572  * @start: iterator to initialize with first position in the buffer
2573  * @end: iterator to initialize with the end iterator
2574  *
2575  * Retrieves the first and last iterators in the buffer, i.e. the
2576  * entire buffer lies within the range [@start,@end).
2577  * 
2578  **/
2579 void
2580 gtk_text_buffer_get_bounds (GtkTextBuffer *buffer,
2581                             GtkTextIter   *start,
2582                             GtkTextIter   *end)
2583 {
2584   g_return_if_fail (start != NULL);
2585   g_return_if_fail (end != NULL);
2586   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2587
2588   _gtk_text_btree_get_iter_at_char (get_btree (buffer), start, 0);
2589   _gtk_text_btree_get_end_iter (get_btree (buffer), end);
2590 }
2591
2592 /*
2593  * Modified flag
2594  */
2595
2596 /**
2597  * gtk_text_buffer_get_modified:
2598  * @buffer: a #GtkTextBuffer 
2599  * 
2600  * Indicates whether the buffer has been modified since the last call
2601  * to gtk_text_buffer_set_modified() set the modification flag to
2602  * %FALSE. Used for example to enable a "save" function in a text
2603  * editor.
2604  * 
2605  * Return value: %TRUE if the buffer has been modified
2606  **/
2607 gboolean
2608 gtk_text_buffer_get_modified (GtkTextBuffer *buffer)
2609 {
2610   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
2611
2612   return buffer->modified;
2613 }
2614
2615 /**
2616  * gtk_text_buffer_set_modified:
2617  * @buffer: a #GtkTextBuffer 
2618  * @setting: modification flag setting
2619  *
2620  * Used to keep track of whether the buffer has been modified since the
2621  * last time it was saved. Whenever the buffer is saved to disk, call
2622  * gtk_text_buffer_set_modified (@buffer, FALSE). When the buffer is modified,
2623  * it will automatically toggled on the modified bit again. When the modified
2624  * bit flips, the buffer emits a "modified_changed" signal.
2625  * 
2626  **/
2627 void
2628 gtk_text_buffer_set_modified (GtkTextBuffer      *buffer,
2629                               gboolean             setting)
2630 {
2631   gboolean fixed_setting;
2632
2633   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2634
2635   fixed_setting = setting != FALSE;
2636
2637   if (buffer->modified == fixed_setting)
2638     return;
2639   else
2640     {
2641       buffer->modified = fixed_setting;
2642       g_signal_emit (buffer, signals[MODIFIED_CHANGED], 0);
2643     }
2644 }
2645
2646
2647 /*
2648  * Assorted other stuff
2649  */
2650
2651 /**
2652  * gtk_text_buffer_get_line_count:
2653  * @buffer: a #GtkTextBuffer 
2654  * 
2655  * Obtains the number of lines in the buffer. This value is cached, so
2656  * the function is very fast.
2657  * 
2658  * Return value: number of lines in the buffer
2659  **/
2660 gint
2661 gtk_text_buffer_get_line_count (GtkTextBuffer *buffer)
2662 {
2663   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), 0);
2664
2665   return _gtk_text_btree_line_count (get_btree (buffer));
2666 }
2667
2668 /**
2669  * gtk_text_buffer_get_char_count:
2670  * @buffer: a #GtkTextBuffer 
2671  * 
2672  * Gets the number of characters in the buffer; note that characters
2673  * and bytes are not the same, you can't e.g. expect the contents of
2674  * the buffer in string form to be this many bytes long. The character
2675  * count is cached, so this function is very fast.
2676  * 
2677  * Return value: number of characters in the buffer
2678  **/
2679 gint
2680 gtk_text_buffer_get_char_count (GtkTextBuffer *buffer)
2681 {
2682   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), 0);
2683
2684   return _gtk_text_btree_char_count (get_btree (buffer));
2685 }
2686
2687 /* Called when we lose the primary selection.
2688  */
2689 static void
2690 clipboard_clear_selection_cb (GtkClipboard *clipboard,
2691                               gpointer      data)
2692 {
2693   /* Move selection_bound to the insertion point */
2694   GtkTextIter insert;
2695   GtkTextIter selection_bound;
2696   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
2697
2698   gtk_text_buffer_get_iter_at_mark (buffer, &insert,
2699                                     gtk_text_buffer_get_mark (buffer, "insert"));
2700   gtk_text_buffer_get_iter_at_mark (buffer, &selection_bound,
2701                                     gtk_text_buffer_get_mark (buffer, "selection_bound"));
2702
2703   if (!gtk_text_iter_equal (&insert, &selection_bound))
2704     gtk_text_buffer_move_mark (buffer,
2705                                gtk_text_buffer_get_mark (buffer, "selection_bound"),
2706                                &insert);
2707 }
2708
2709 /* Called when we have the primary selection and someone else wants our
2710  * data in order to paste it.
2711  */
2712 static void
2713 clipboard_get_selection_cb (GtkClipboard     *clipboard,
2714                             GtkSelectionData *selection_data,
2715                             guint             info,
2716                             gpointer          data)
2717 {
2718   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
2719   GtkTextIter start, end;
2720
2721   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
2722     {
2723       if (selection_data->target ==
2724           gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE))
2725         {
2726           /* Provide the address of the buffer; this will only be
2727            * used within-process
2728            */
2729           gtk_selection_data_set (selection_data,
2730                                   gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE),
2731                                   8, /* bytes */
2732                                   (void*)&buffer,
2733                                   sizeof (buffer));
2734         }
2735       else
2736         {
2737           gchar *str;
2738           
2739           str = gtk_text_iter_get_visible_text (&start, &end);
2740           gtk_selection_data_set_text (selection_data, str, -1);
2741           g_free (str);
2742         }
2743     }
2744 }
2745
2746 typedef struct
2747 {
2748   GtkClipboard *clipboard;
2749   GtkTextBuffer *buffer;
2750 } ContentsBuffer;
2751
2752 static void
2753 remove_all_clipboard_contents_buffers (GtkTextBuffer *buffer)
2754 {
2755   GSList *tmp_list = buffer->clipboard_contents_buffers;
2756   while (tmp_list)
2757     {
2758       ContentsBuffer *contents_buffer = tmp_list->data;
2759
2760       g_object_unref (contents_buffer->buffer);
2761       g_free (contents_buffer);
2762           
2763       tmp_list = tmp_list->next;
2764     }
2765
2766   g_slist_free (buffer->clipboard_contents_buffers);
2767   buffer->clipboard_contents_buffers = NULL;
2768 }
2769
2770 static void
2771 remove_clipboard_contents_buffer (GtkTextBuffer *buffer,
2772                                   GtkClipboard  *clipboard)
2773 {
2774   GSList *tmp_list = buffer->clipboard_contents_buffers;
2775   while (tmp_list)
2776     {
2777       ContentsBuffer *contents_buffer = tmp_list->data;
2778       
2779       if (contents_buffer->clipboard == clipboard)
2780         {
2781           buffer->clipboard_contents_buffers = g_slist_remove (buffer->clipboard_contents_buffers, contents_buffer);
2782           
2783           g_object_unref (contents_buffer->buffer);
2784           g_free (contents_buffer);
2785           
2786           return;
2787         }
2788
2789       tmp_list = tmp_list->next;
2790     }
2791 }
2792
2793 static GtkTextBuffer *
2794 get_clipboard_contents_buffer (GtkTextBuffer *buffer,
2795                                GtkClipboard  *clipboard,
2796                                gboolean       create)
2797 {
2798   ContentsBuffer *contents_buffer;
2799   GSList *tmp_list;
2800
2801   tmp_list = buffer->clipboard_contents_buffers;
2802   while (tmp_list)
2803     {
2804       contents_buffer = tmp_list->data;
2805       if (contents_buffer->clipboard == clipboard)
2806         return contents_buffer->buffer;
2807     }
2808   
2809   if (create)
2810     {
2811       contents_buffer = g_new (ContentsBuffer, 1);
2812       contents_buffer->clipboard = clipboard;
2813       contents_buffer->buffer = gtk_text_buffer_new (gtk_text_buffer_get_tag_table (buffer));
2814
2815       g_object_set_data (G_OBJECT (contents_buffer->buffer), "gtk-text-buffer-clipboard",
2816                          GUINT_TO_POINTER (1));
2817
2818       buffer->clipboard_contents_buffers = g_slist_prepend (buffer->clipboard_contents_buffers, contents_buffer);
2819
2820       
2821       return contents_buffer->buffer;
2822     }
2823   else
2824     return NULL;
2825 }
2826
2827 /* Provide cut/copied data */
2828 static void
2829 clipboard_get_contents_cb (GtkClipboard     *clipboard,
2830                            GtkSelectionData *selection_data,
2831                            guint             info,
2832                            gpointer          data)
2833 {
2834   GtkTextBuffer *buffer;
2835   GtkTextBuffer *contents;
2836
2837   buffer = GTK_TEXT_BUFFER (data);
2838   contents = get_clipboard_contents_buffer (buffer, clipboard, FALSE);
2839   
2840   g_assert (contents); /* This should never be called unless we own the clipboard */
2841
2842   if (selection_data->target ==
2843       gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE))
2844     {
2845       /* Provide the address of the clipboard buffer; this will only
2846        * be used within-process. OK to supply a NULL value for contents.
2847        */
2848       gtk_selection_data_set (selection_data,
2849                               gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE),
2850                               8, /* bytes */
2851                               (void*)&contents,
2852                               sizeof (contents));
2853     }
2854   else
2855     {
2856       gchar *str;
2857       GtkTextIter start, end;
2858       
2859       gtk_text_buffer_get_bounds (contents, &start, &end);
2860       
2861       str = gtk_text_iter_get_visible_text (&start, &end);
2862       gtk_selection_data_set_text (selection_data, str, -1);
2863       g_free (str);
2864     }
2865 }
2866
2867 static void
2868 clipboard_clear_contents_cb (GtkClipboard *clipboard,
2869                              gpointer      data)
2870 {
2871   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
2872
2873   remove_clipboard_contents_buffer (buffer, clipboard);
2874 }
2875
2876 static void
2877 get_paste_point (GtkTextBuffer *buffer,
2878                  GtkTextIter   *iter,
2879                  gboolean       clear_afterward)
2880 {
2881   GtkTextIter insert_point;
2882   GtkTextMark *paste_point_override;
2883
2884   paste_point_override = gtk_text_buffer_get_mark (buffer,
2885                                                    "gtk_paste_point_override");
2886
2887   if (paste_point_override != NULL)
2888     {
2889       gtk_text_buffer_get_iter_at_mark (buffer, &insert_point,
2890                                         paste_point_override);
2891       if (clear_afterward)
2892         gtk_text_buffer_delete_mark (buffer,
2893                                      gtk_text_buffer_get_mark (buffer,
2894                                                                "gtk_paste_point_override"));
2895     }
2896   else
2897     {
2898       gtk_text_buffer_get_iter_at_mark (buffer, &insert_point,
2899                                         gtk_text_buffer_get_mark (buffer,
2900                                                                   "insert"));
2901     }
2902
2903   *iter = insert_point;
2904 }
2905
2906 static void
2907 pre_paste_prep (ClipboardRequest *request_data,
2908                 GtkTextIter      *insert_point)
2909 {
2910   GtkTextBuffer *buffer = request_data->buffer;
2911   
2912   get_paste_point (buffer, insert_point, TRUE);
2913
2914   /* If we're going to replace the selection, we insert before it to
2915    * avoid messing it up, then we delete the selection after inserting.
2916    */
2917   if (request_data->replace_selection)
2918     {
2919       GtkTextIter start, end;
2920       
2921       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
2922         *insert_point = start;
2923     }
2924 }
2925
2926 static void
2927 post_paste_cleanup (ClipboardRequest *request_data)
2928 {
2929   if (request_data->replace_selection)
2930     {
2931       GtkTextIter start, end;
2932       
2933       if (gtk_text_buffer_get_selection_bounds (request_data->buffer,
2934                                                 &start, &end))
2935         {
2936           if (request_data->interactive)
2937             gtk_text_buffer_delete_interactive (request_data->buffer,
2938                                                 &start,
2939                                                 &end,
2940                                                 request_data->default_editable);
2941           else
2942             gtk_text_buffer_delete (request_data->buffer, &start, &end);
2943         }
2944     }
2945 }
2946
2947 /* Called when we request a paste and receive the text data
2948  */
2949 static void
2950 clipboard_text_received (GtkClipboard *clipboard,
2951                          const gchar  *str,
2952                          gpointer      data)
2953 {
2954   ClipboardRequest *request_data = data;
2955   GtkTextBuffer *buffer = request_data->buffer;
2956
2957   if (str)
2958     {
2959       GtkTextIter insert_point;
2960       
2961       if (request_data->interactive) 
2962         gtk_text_buffer_begin_user_action (buffer);
2963
2964       pre_paste_prep (request_data, &insert_point);
2965       
2966       if (request_data->interactive) 
2967         gtk_text_buffer_insert_interactive (buffer, &insert_point,
2968                                             str, -1, request_data->default_editable);
2969       else
2970         gtk_text_buffer_insert (buffer, &insert_point,
2971                                 str, -1);
2972
2973       post_paste_cleanup (request_data);
2974       
2975       if (request_data->interactive) 
2976         gtk_text_buffer_end_user_action (buffer);
2977     }
2978
2979   g_object_unref (buffer);
2980   g_free (request_data);
2981 }
2982
2983 static GtkTextBuffer*
2984 selection_data_get_buffer (GtkSelectionData *selection_data,
2985                            ClipboardRequest *request_data)
2986 {
2987   GdkWindow *owner;
2988   GtkTextBuffer *src_buffer = NULL;
2989
2990   /* If we can get the owner, the selection is in-process */
2991   owner = gdk_selection_owner_get_for_display (selection_data->display,
2992                                                selection_data->selection);
2993
2994   if (owner == NULL)
2995     return NULL;
2996   
2997   if (gdk_window_get_window_type (owner) == GDK_WINDOW_FOREIGN)
2998     return NULL;
2999  
3000   if (selection_data->type != gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE))
3001     return NULL;
3002
3003   if (selection_data->length != sizeof (src_buffer))
3004     return NULL;
3005           
3006   memcpy (&src_buffer, selection_data->data, sizeof (src_buffer));
3007
3008   if (src_buffer == NULL)
3009     return NULL;
3010   
3011   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (src_buffer), NULL);
3012
3013   if (gtk_text_buffer_get_tag_table (src_buffer) !=
3014       gtk_text_buffer_get_tag_table (request_data->buffer))
3015     return NULL;
3016   
3017   return src_buffer;
3018 }
3019
3020 #if 0
3021 /* These are pretty handy functions; maybe something like them
3022  * should be in the public API. Also, there are other places in this
3023  * file where they could be used.
3024  */
3025 static gpointer
3026 save_iter (const GtkTextIter *iter,
3027            gboolean           left_gravity)
3028 {
3029   return gtk_text_buffer_create_mark (gtk_text_iter_get_buffer (iter),
3030                                       NULL,
3031                                       iter,
3032                                       TRUE);
3033 }
3034
3035 static void
3036 restore_iter (const GtkTextIter *iter,
3037               gpointer           save_id)
3038 {
3039   gtk_text_buffer_get_iter_at_mark (gtk_text_mark_get_buffer (save_id),
3040                                     (GtkTextIter*) iter,
3041                                     save_id);
3042   gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (save_id),
3043                                save_id);
3044 }
3045 #endif
3046
3047 static void
3048 paste_from_buffer (ClipboardRequest    *request_data,
3049                    GtkTextBuffer       *src_buffer,
3050                    const GtkTextIter   *start,
3051                    const GtkTextIter   *end)
3052 {
3053   GtkTextIter insert_point;
3054   GtkTextBuffer *buffer = request_data->buffer;
3055   
3056   /* We're about to emit a bunch of signals, so be safe */
3057   g_object_ref (src_buffer);
3058   
3059   pre_paste_prep (request_data, &insert_point);
3060   
3061   if (request_data->interactive) 
3062     gtk_text_buffer_begin_user_action (buffer);
3063
3064   if (!gtk_text_iter_equal (start, end))
3065     {
3066       if (!request_data->interactive ||
3067           (gtk_text_iter_can_insert (&insert_point,
3068                                      request_data->default_editable)))
3069         gtk_text_buffer_real_insert_range (buffer,
3070                                            &insert_point,
3071                                            start,
3072                                            end,
3073                                            request_data->interactive);
3074     }
3075
3076   post_paste_cleanup (request_data);
3077       
3078   if (request_data->interactive) 
3079     gtk_text_buffer_end_user_action (buffer);
3080
3081   g_object_unref (src_buffer);
3082   g_free (request_data);
3083 }
3084
3085 static void
3086 clipboard_clipboard_buffer_received (GtkClipboard     *clipboard,
3087                                      GtkSelectionData *selection_data,
3088                                      gpointer          data)
3089 {
3090   ClipboardRequest *request_data = data;
3091   GtkTextBuffer *src_buffer;
3092   
3093   src_buffer = selection_data_get_buffer (selection_data, request_data); 
3094
3095   if (src_buffer)
3096     {
3097       GtkTextIter start, end;
3098
3099       if (g_object_get_data (G_OBJECT (src_buffer), "gtk-text-buffer-clipboard"))
3100         {
3101           gtk_text_buffer_get_bounds (src_buffer, &start, &end);
3102       
3103           paste_from_buffer (request_data, src_buffer,
3104                              &start, &end);
3105         }
3106       else
3107         {
3108           if (gtk_text_buffer_get_selection_bounds (src_buffer, &start, &end))
3109             paste_from_buffer (request_data, src_buffer,
3110                                &start, &end);
3111         }
3112     }
3113   else
3114     {
3115       /* Request the text selection instead */
3116       gtk_clipboard_request_text (clipboard,
3117                                   clipboard_text_received,
3118                                   data);
3119     }
3120 }
3121
3122 static const GtkTargetEntry targets[] = {
3123   { "STRING", 0, TARGET_STRING },
3124   { "TEXT",   0, TARGET_TEXT },
3125   { "COMPOUND_TEXT", 0, TARGET_COMPOUND_TEXT },
3126   { "UTF8_STRING", 0, TARGET_UTF8_STRING },
3127   { "GTK_TEXT_BUFFER_CONTENTS", 0, TARGET_TEXT_BUFFER_CONTENTS }
3128 };
3129
3130 typedef struct
3131 {
3132   GtkClipboard *clipboard;
3133   guint ref_count;
3134 } SelectionClipboard;
3135
3136 static void
3137 update_selection_clipboards (GtkTextBuffer *buffer)
3138 {
3139   GSList *tmp_list = buffer->selection_clipboards;
3140   while (tmp_list)
3141     {
3142       GtkTextIter start;
3143       GtkTextIter end;
3144       
3145       SelectionClipboard *selection_clipboard = tmp_list->data;
3146       GtkClipboard *clipboard = selection_clipboard->clipboard;
3147
3148       /* Determine whether we have a selection and adjust X selection
3149        * accordingly.
3150        */
3151       if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3152         {
3153           if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (buffer))
3154             gtk_clipboard_clear (clipboard);
3155         }
3156       else
3157         {
3158           /* Even if we already have the selection, we need to update our
3159            * timestamp.
3160            */
3161           if (!gtk_clipboard_set_with_owner (clipboard, targets, G_N_ELEMENTS (targets),
3162                                              clipboard_get_selection_cb,
3163                                              clipboard_clear_selection_cb,
3164                                              G_OBJECT (buffer)))
3165             clipboard_clear_selection_cb (clipboard, buffer);
3166         }
3167
3168       tmp_list = tmp_list->next;
3169     }
3170 }
3171
3172 static SelectionClipboard *
3173 find_selection_clipboard (GtkTextBuffer *buffer,
3174                           GtkClipboard  *clipboard)
3175 {
3176   GSList *tmp_list = buffer->selection_clipboards;
3177   while (tmp_list)
3178     {
3179       SelectionClipboard *selection_clipboard = tmp_list->data;
3180       if (selection_clipboard->clipboard == clipboard)
3181         return selection_clipboard;
3182       
3183       tmp_list = tmp_list->next;
3184     }
3185
3186   return NULL;
3187 }
3188
3189 /**
3190  * gtk_text_buffer_add_selection_clipboard:
3191  * @buffer: a #GtkTextBuffer
3192  * @clipboard: a #GtkClipboard
3193  * 
3194  * Adds @clipboard to the list of clipboards in which the selection contents
3195  * of @buffer are available. In most cases, @clipboard will be the #GtkClipboard
3196  * of type %GDK_SELECTION_PRIMARY for a view of @buffer.
3197  **/
3198 void
3199 gtk_text_buffer_add_selection_clipboard (GtkTextBuffer *buffer,
3200                                          GtkClipboard  *clipboard)
3201 {
3202   SelectionClipboard *selection_clipboard;
3203
3204   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3205   g_return_if_fail (clipboard != NULL);
3206
3207   selection_clipboard = find_selection_clipboard (buffer, clipboard);
3208   if (selection_clipboard)
3209     {
3210       selection_clipboard->ref_count++;
3211     }
3212   else
3213     {
3214       selection_clipboard = g_new (SelectionClipboard, 1);
3215
3216       selection_clipboard->clipboard = clipboard;
3217       selection_clipboard->ref_count = 1;
3218
3219       buffer->selection_clipboards = g_slist_prepend (buffer->selection_clipboards, selection_clipboard);
3220     }
3221 }
3222
3223 /**
3224  * gtk_text_buffer_remove_selection_clipboard:
3225  * @buffer: a #GtkTextBuffer
3226  * @clipboard: a #GtkClipboard added to @buffer by gtk_text_buffer_add_selection_clipboard().
3227  * 
3228  * Removes a #GtkClipboard added with gtk_text_buffer_add_selection_clipboard()
3229  **/
3230 void 
3231 gtk_text_buffer_remove_selection_clipboard (GtkTextBuffer *buffer,
3232                                             GtkClipboard  *clipboard)
3233 {
3234   SelectionClipboard *selection_clipboard;
3235
3236   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3237   g_return_if_fail (clipboard != NULL);
3238
3239   selection_clipboard = find_selection_clipboard (buffer, clipboard);
3240   g_return_if_fail (selection_clipboard != NULL);
3241
3242   selection_clipboard->ref_count--;
3243   if (selection_clipboard->ref_count == 0)
3244     {
3245       if (gtk_clipboard_get_owner (selection_clipboard->clipboard) == G_OBJECT (buffer))
3246         gtk_clipboard_clear (selection_clipboard->clipboard);
3247
3248       buffer->selection_clipboards = g_slist_remove (buffer->selection_clipboards,
3249                                                      selection_clipboard);
3250       
3251       g_free (selection_clipboard);
3252     }
3253 }
3254
3255 static void
3256 remove_all_selection_clipboards (GtkTextBuffer *buffer)
3257 {
3258   GSList *tmp_list = buffer->selection_clipboards;
3259   while (tmp_list)
3260     {
3261       SelectionClipboard *selection_clipboard = tmp_list->data;
3262       
3263       if (gtk_clipboard_get_owner (selection_clipboard->clipboard) == G_OBJECT (buffer))
3264         gtk_clipboard_clear (selection_clipboard->clipboard);
3265       
3266       g_free (selection_clipboard);
3267
3268       tmp_list = tmp_list->next;
3269     }
3270
3271   g_slist_free (buffer->selection_clipboards);
3272   buffer->selection_clipboards = NULL;
3273 }
3274
3275 /**
3276  * gtk_text_buffer_paste_clipboard:
3277  * @buffer: a #GtkTextBuffer
3278  * @clipboard: the #GtkClipboard to paste from
3279  * @override_location: location to insert pasted text, or %NULL for at the cursor
3280  * @default_editable: whether the buffer is editable by default
3281  *
3282  * Pastes the contents of a clipboard at the insertion point, or at @override_location.
3283  * (Note: pasting is asynchronous, that is, we'll ask for the paste data and
3284  * return, and at some point later after the main loop runs, the paste
3285  * data will be inserted.)
3286  * 
3287  **/
3288 void
3289 gtk_text_buffer_paste_clipboard (GtkTextBuffer *buffer,
3290                                  GtkClipboard  *clipboard,
3291                                  GtkTextIter   *override_location,
3292                                  gboolean       default_editable)
3293 {
3294   ClipboardRequest *data = g_new (ClipboardRequest, 1);
3295   GtkTextIter paste_point;
3296   GtkTextIter start, end;
3297
3298   if (override_location != NULL)
3299     gtk_text_buffer_create_mark (buffer,
3300                                  "gtk_paste_point_override",
3301                                  override_location, FALSE);
3302
3303   data->buffer = buffer;
3304   g_object_ref (buffer);
3305   data->interactive = TRUE;
3306   data->default_editable = default_editable;
3307
3308   /* When pasting with the cursor inside the selection area, you
3309    * replace the selection with the new text, otherwise, you
3310    * simply insert the new text at the point where the click
3311    * occured, unselecting any selected text. The replace_selection
3312    * flag toggles this behavior.
3313    */
3314   data->replace_selection = FALSE;
3315   
3316   get_paste_point (buffer, &paste_point, FALSE);
3317   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end) &&
3318       (gtk_text_iter_in_range (&paste_point, &start, &end) ||
3319        gtk_text_iter_equal (&paste_point, &end)))
3320     data->replace_selection = TRUE;
3321
3322   gtk_clipboard_request_contents (clipboard,
3323                                   gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE),
3324                                   clipboard_clipboard_buffer_received, data);
3325 }
3326
3327 /**
3328  * gtk_text_buffer_delete_selection:
3329  * @buffer: a #GtkTextBuffer 
3330  * @interactive: whether the deletion is caused by user interaction
3331  * @default_editable: whether the buffer is editable by default
3332  *
3333  * Deletes the range between the "insert" and "selection_bound" marks,
3334  * that is, the currently-selected text. If @interactive is %TRUE,
3335  * the editability of the selection will be considered (users can't delete
3336  * uneditable text).
3337  * 
3338  * Return value: whether there was a non-empty selection to delete
3339  **/
3340 gboolean
3341 gtk_text_buffer_delete_selection (GtkTextBuffer *buffer,
3342                                   gboolean interactive,
3343                                   gboolean default_editable)
3344 {
3345   GtkTextIter start;
3346   GtkTextIter end;
3347
3348   if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3349     {
3350       return FALSE; /* No selection */
3351     }
3352   else
3353     {
3354       if (interactive)
3355         {
3356           gtk_text_buffer_begin_user_action (buffer);
3357           gtk_text_buffer_delete_interactive (buffer, &start, &end, default_editable);
3358           gtk_text_buffer_end_user_action (buffer);
3359         }
3360       else
3361         gtk_text_buffer_delete (buffer, &start, &end);
3362
3363       return TRUE; /* We deleted stuff */
3364     }
3365 }
3366
3367 static void
3368 cut_or_copy (GtkTextBuffer *buffer,
3369              GtkClipboard  *clipboard,
3370              gboolean       delete_region_after,
3371              gboolean       interactive,
3372              gboolean       default_editable)
3373 {
3374   /* We prefer to cut the selected region between selection_bound and
3375    * insertion point. If that region is empty, then we cut the region
3376    * between the "anchor" and the insertion point (this is for
3377    * C-space and M-w and other Emacs-style copy/yank keys). Note that
3378    * insert and selection_bound are guaranteed to exist, but the
3379    * anchor only exists sometimes.
3380    */
3381   GtkTextIter start;
3382   GtkTextIter end;
3383   
3384   if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3385     {
3386       /* Let's try the anchor thing */
3387       GtkTextMark * anchor = gtk_text_buffer_get_mark (buffer, "anchor");
3388
3389       if (anchor == NULL)
3390         return;
3391       else
3392         {
3393           gtk_text_buffer_get_iter_at_mark (buffer, &end, anchor);
3394           gtk_text_iter_order (&start, &end);
3395         }
3396     }
3397
3398   if (!gtk_text_iter_equal (&start, &end))
3399     {
3400       GtkTextIter ins;
3401       GtkTextBuffer *contents;
3402
3403       remove_clipboard_contents_buffer (buffer, clipboard);
3404       contents = get_clipboard_contents_buffer (buffer, clipboard, TRUE);
3405
3406       gtk_text_buffer_get_iter_at_offset (contents, &ins, 0);
3407       
3408       gtk_text_buffer_insert_range (contents, &ins, &start, &end);
3409                                     
3410       if (!gtk_clipboard_set_with_owner (clipboard, targets, G_N_ELEMENTS (targets),
3411                                          clipboard_get_contents_cb,
3412                                          clipboard_clear_contents_cb,
3413                                          G_OBJECT (buffer)))
3414         clipboard_clear_contents_cb (clipboard, buffer);      
3415
3416       if (delete_region_after)
3417         {
3418           if (interactive)
3419             gtk_text_buffer_delete_interactive (buffer, &start, &end,
3420                                                 default_editable);
3421           else
3422             gtk_text_buffer_delete (buffer, &start, &end);
3423         }
3424     }
3425 }
3426
3427 /**
3428  * gtk_text_buffer_cut_clipboard:
3429  * @buffer: a #GtkTextBuffer
3430  * @clipboard: the #GtkClipboard object to cut to.
3431  * @default_editable: default editability of the buffer
3432  *
3433  * Copies the currently-selected text to a clipboard, then deletes
3434  * said text if it's editable.
3435  * 
3436  **/
3437 void
3438 gtk_text_buffer_cut_clipboard (GtkTextBuffer *buffer,
3439                                GtkClipboard  *clipboard,
3440                                gboolean       default_editable)
3441 {
3442   gtk_text_buffer_begin_user_action (buffer);
3443   cut_or_copy (buffer, clipboard, TRUE, TRUE, default_editable);
3444   gtk_text_buffer_end_user_action (buffer);
3445 }
3446
3447 /**
3448  * gtk_text_buffer_copy_clipboard:
3449  * @buffer: a #GtkTextBuffer 
3450  * @clipboard: the #GtkClipboard object to copy to.
3451  *
3452  * Copies the currently-selected text to a clipboard.
3453  * 
3454  **/
3455 void
3456 gtk_text_buffer_copy_clipboard (GtkTextBuffer *buffer,
3457                                 GtkClipboard  *clipboard)
3458 {
3459   gtk_text_buffer_begin_user_action (buffer);
3460   cut_or_copy (buffer, clipboard, FALSE, TRUE, TRUE);
3461   gtk_text_buffer_end_user_action (buffer);
3462 }
3463
3464
3465 /**
3466  * gtk_text_buffer_get_selection_bounds:
3467  * @buffer: a #GtkTextBuffer a #GtkTextBuffer
3468  * @start: iterator to initialize with selection start
3469  * @end: iterator to initialize with selection end
3470  *
3471  * Returns %TRUE if some text is selected; places the bounds
3472  * of the selection in @start and @end (if the selection has length 0,
3473  * then @start and @end are filled in with the same value).
3474  * @start and @end will be in ascending order. If @start and @end are
3475  * NULL, then they are not filled in, but the return value still indicates
3476  * whether text is selected.
3477  *
3478  * Return value: whether the selection has nonzero length
3479  **/
3480 gboolean
3481 gtk_text_buffer_get_selection_bounds   (GtkTextBuffer      *buffer,
3482                                         GtkTextIter        *start,
3483                                         GtkTextIter        *end)
3484 {
3485   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
3486
3487   return _gtk_text_btree_get_selection_bounds (get_btree (buffer), start, end);
3488 }
3489
3490 /**
3491  * gtk_text_buffer_begin_user_action:
3492  * @buffer: a #GtkTextBuffer
3493  * 
3494  * Called to indicate that the buffer operations between here and a
3495  * call to gtk_text_buffer_end_user_action() are part of a single
3496  * user-visible operation. The operations between
3497  * gtk_text_buffer_begin_user_action() and
3498  * gtk_text_buffer_end_user_action() can then be grouped when creating
3499  * an undo stack. #GtkTextBuffer maintains a count of calls to
3500  * gtk_text_buffer_begin_user_action() that have not been closed with
3501  * a call to gtk_text_buffer_end_user_action(), and emits the "begin_user_action"
3502  * and "end_user_action" signals only for the outermost pair of calls.
3503  * This allows you to build user actions from other user actions.
3504  *
3505  * The "interactive" buffer mutation functions, such as
3506  * gtk_text_buffer_insert_interactive(), automatically call begin/end
3507  * user action around the buffer operations they perform, so there's
3508  * no need to add extra calls if you user action consists solely of a
3509  * single call to one of those functions.
3510  **/
3511 void
3512 gtk_text_buffer_begin_user_action (GtkTextBuffer *buffer)
3513 {
3514   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3515
3516   buffer->user_action_count += 1;
3517   
3518   if (buffer->user_action_count == 1)
3519     {
3520       /* Outermost nested user action begin emits the signal */
3521       g_signal_emit (buffer, signals[BEGIN_USER_ACTION], 0);
3522     }
3523 }
3524
3525 /**
3526  * gtk_text_buffer_end_user_action:
3527  * @buffer: a #GtkTextBuffer
3528  * 
3529  * Should be paired with a call to gtk_text_buffer_begin_user_action().
3530  * See that function for a full explanation.
3531  **/
3532 void
3533 gtk_text_buffer_end_user_action (GtkTextBuffer *buffer)
3534 {
3535   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3536   g_return_if_fail (buffer->user_action_count > 0);
3537   
3538   buffer->user_action_count -= 1;
3539   
3540   if (buffer->user_action_count == 0)
3541     {
3542       /* Ended the outermost-nested user action end, so emit the signal */
3543       g_signal_emit (buffer, signals[END_USER_ACTION], 0);
3544     }
3545 }
3546
3547 /*
3548  * Logical attribute cache
3549  */
3550
3551 #define ATTR_CACHE_SIZE 2
3552
3553 typedef struct _CacheEntry CacheEntry;
3554 struct _CacheEntry
3555 {
3556   gint line;
3557   gint char_len;
3558   PangoLogAttr *attrs;
3559 };
3560
3561
3562 struct _GtkTextLogAttrCache
3563 {
3564   gint chars_changed_stamp;
3565   CacheEntry entries[ATTR_CACHE_SIZE];
3566 };
3567
3568 static void
3569 free_log_attr_cache (GtkTextLogAttrCache *cache)
3570 {
3571   gint i = 0;
3572   while (i < ATTR_CACHE_SIZE)
3573     {
3574       g_free (cache->entries[i].attrs);
3575       ++i;
3576     }
3577   g_free (cache);
3578 }
3579
3580 static void
3581 clear_log_attr_cache (GtkTextLogAttrCache *cache)
3582 {
3583   gint i = 0;
3584   while (i < ATTR_CACHE_SIZE)
3585     {
3586       g_free (cache->entries[i].attrs);
3587       cache->entries[i].attrs = NULL;
3588       ++i;
3589     }
3590 }
3591
3592 static PangoLogAttr*
3593 compute_log_attrs (const GtkTextIter *iter,
3594                    gint              *char_lenp)
3595 {
3596   GtkTextIter start;
3597   GtkTextIter end;
3598   gchar *paragraph;
3599   gint char_len, byte_len;
3600   PangoLogAttr *attrs = NULL;
3601   
3602   start = *iter;
3603   end = *iter;
3604
3605   gtk_text_iter_set_line_offset (&start, 0);
3606   gtk_text_iter_forward_line (&end);
3607
3608   paragraph = gtk_text_iter_get_slice (&start, &end);
3609   char_len = g_utf8_strlen (paragraph, -1);
3610   byte_len = strlen (paragraph);
3611
3612   g_assert (char_len > 0);
3613
3614   if (char_lenp)
3615     *char_lenp = char_len;
3616   
3617   attrs = g_new (PangoLogAttr, char_len + 1);
3618
3619   /* FIXME we need to follow PangoLayout and allow different language
3620    * tags within the paragraph
3621    */
3622   pango_get_log_attrs (paragraph, byte_len, -1,
3623                        gtk_text_iter_get_language (&start),
3624                        attrs,
3625                        char_len + 1);
3626   
3627   g_free (paragraph);
3628
3629   return attrs;
3630 }
3631
3632 /* The return value from this is valid until you call this a second time.
3633  */
3634 const PangoLogAttr*
3635 _gtk_text_buffer_get_line_log_attrs (GtkTextBuffer     *buffer,
3636                                      const GtkTextIter *anywhere_in_line,
3637                                      gint              *char_len)
3638 {
3639   gint line;
3640   GtkTextLogAttrCache *cache;
3641   gint i;
3642   
3643   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
3644   g_return_val_if_fail (anywhere_in_line != NULL, NULL);
3645
3646   /* special-case for empty last line in buffer */
3647   if (gtk_text_iter_is_end (anywhere_in_line) &&
3648       gtk_text_iter_get_line_offset (anywhere_in_line) == 0)
3649     {
3650       if (char_len)
3651         *char_len = 0;
3652       return NULL;
3653     }
3654   
3655   /* FIXME we also need to recompute log attrs if the language tag at
3656    * the start of a paragraph changes
3657    */
3658   
3659   if (buffer->log_attr_cache == NULL)
3660     {
3661       buffer->log_attr_cache = g_new0 (GtkTextLogAttrCache, 1);
3662       buffer->log_attr_cache->chars_changed_stamp =
3663         _gtk_text_btree_get_chars_changed_stamp (get_btree (buffer));
3664     }
3665   else if (buffer->log_attr_cache->chars_changed_stamp !=
3666            _gtk_text_btree_get_chars_changed_stamp (get_btree (buffer)))
3667     {
3668       clear_log_attr_cache (buffer->log_attr_cache);
3669     }
3670   
3671   cache = buffer->log_attr_cache;
3672   line = gtk_text_iter_get_line (anywhere_in_line);
3673
3674   i = 0;
3675   while (i < ATTR_CACHE_SIZE)
3676     {
3677       if (cache->entries[i].attrs &&
3678           cache->entries[i].line == line)
3679         {
3680           if (char_len)
3681             *char_len = cache->entries[i].char_len;
3682           return cache->entries[i].attrs;
3683         }
3684       ++i;
3685     }
3686   
3687   /* Not in cache; open up the first cache entry */
3688   if (cache->entries[ATTR_CACHE_SIZE-1].attrs)
3689     g_free (cache->entries[ATTR_CACHE_SIZE-1].attrs);
3690   
3691   g_memmove (cache->entries + 1, cache->entries,
3692              sizeof (CacheEntry) * (ATTR_CACHE_SIZE - 1));
3693
3694   cache->entries[0].line = line;
3695   cache->entries[0].attrs = compute_log_attrs (anywhere_in_line,
3696                                                &cache->entries[0].char_len);
3697
3698   if (char_len)
3699     *char_len = cache->entries[0].char_len;
3700   
3701   return cache->entries[0].attrs;
3702 }
3703
3704 void
3705 _gtk_text_buffer_notify_will_remove_tag (GtkTextBuffer *buffer,
3706                                          GtkTextTag    *tag)
3707 {
3708   /* This removes tag from the buffer, but DOESN'T emit the
3709    * remove_tag signal, because we can't afford to have user
3710    * code messing things up at this point; the tag MUST be removed
3711    * entirely.
3712    */
3713   if (buffer->btree)
3714     _gtk_text_btree_notify_will_remove_tag (buffer->btree, tag);
3715 }
3716
3717 /*
3718  * Debug spew
3719  */
3720
3721 void
3722 _gtk_text_buffer_spew (GtkTextBuffer *buffer)
3723 {
3724   _gtk_text_btree_spew (get_btree (buffer));
3725 }