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