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