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