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