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