]> Pileus Git - ~andy/gtk/blob - gtk/gtktextbuffer.c
gtktexttag: Move public members to private header
[~andy/gtk] / gtk / gtktextbuffer.c
1 /* GTK - The GIMP Toolkit
2  * gtktextbuffer.c Copyright (C) 2000 Red Hat, Inc.
3  *                 Copyright (C) 2004 Nokia Corporation
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /*
22  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
23  * file for a list of people on the GTK+ Team.  See the ChangeLog
24  * files for a list of changes.  These files are distributed with
25  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
26  */
27
28 #include "config.h"
29 #include <string.h>
30 #include <stdarg.h>
31
32 #define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
33 #include "gtkclipboard.h"
34 #include "gtkdnd.h"
35 #include "gtkinvisible.h"
36 #include "gtkmarshalers.h"
37 #include "gtktextbuffer.h"
38 #include "gtktextbufferrichtext.h"
39 #include "gtktextbtree.h"
40 #include "gtktextiterprivate.h"
41 #include "gtktexttagprivate.h"
42 #include "gtkprivate.h"
43 #include "gtkintl.h"
44
45
46 typedef struct _GtkTextLogAttrCache GtkTextLogAttrCache;
47
48 struct _GtkTextBufferPrivate
49 {
50   GtkTargetList  *copy_target_list;
51   GtkTargetEntry *copy_target_entries;
52   gint            n_copy_target_entries;
53
54   GtkTargetList  *paste_target_list;
55   GtkTargetEntry *paste_target_entries;
56   gint            n_paste_target_entries;
57
58   GtkTextTagTable *tag_table;
59   GtkTextBTree *btree;
60
61   GSList *clipboard_contents_buffers;
62   GSList *selection_clipboards;
63
64   GtkTextLogAttrCache *log_attr_cache;
65
66   guint user_action_count;
67
68   /* Whether the buffer has been modified since last save */
69   guint modified : 1;
70
71   guint has_selection : 1;
72 };
73
74
75 typedef struct _ClipboardRequest ClipboardRequest;
76
77 struct _ClipboardRequest
78 {
79   GtkTextBuffer *buffer;
80   guint interactive : 1;
81   guint default_editable : 1;
82   guint replace_selection : 1;
83 };
84
85 enum {
86   INSERT_TEXT,
87   INSERT_PIXBUF,
88   INSERT_CHILD_ANCHOR,
89   DELETE_RANGE,
90   CHANGED,
91   MODIFIED_CHANGED,
92   MARK_SET,
93   MARK_DELETED,
94   APPLY_TAG,
95   REMOVE_TAG,
96   BEGIN_USER_ACTION,
97   END_USER_ACTION,
98   PASTE_DONE,
99   LAST_SIGNAL
100 };
101
102 enum {
103   PROP_0,
104
105   /* Construct */
106   PROP_TAG_TABLE,
107
108   /* Normal */
109   PROP_TEXT,
110   PROP_HAS_SELECTION,
111   PROP_CURSOR_POSITION,
112   PROP_COPY_TARGET_LIST,
113   PROP_PASTE_TARGET_LIST
114 };
115
116 static void gtk_text_buffer_finalize   (GObject            *object);
117
118 static void gtk_text_buffer_real_insert_text           (GtkTextBuffer     *buffer,
119                                                         GtkTextIter       *iter,
120                                                         const gchar       *text,
121                                                         gint               len);
122 static void gtk_text_buffer_real_insert_pixbuf         (GtkTextBuffer     *buffer,
123                                                         GtkTextIter       *iter,
124                                                         GdkPixbuf         *pixbuf);
125 static void gtk_text_buffer_real_insert_anchor         (GtkTextBuffer     *buffer,
126                                                         GtkTextIter       *iter,
127                                                         GtkTextChildAnchor *anchor);
128 static void gtk_text_buffer_real_delete_range          (GtkTextBuffer     *buffer,
129                                                         GtkTextIter       *start,
130                                                         GtkTextIter       *end);
131 static void gtk_text_buffer_real_apply_tag             (GtkTextBuffer     *buffer,
132                                                         GtkTextTag        *tag,
133                                                         const GtkTextIter *start_char,
134                                                         const GtkTextIter *end_char);
135 static void gtk_text_buffer_real_remove_tag            (GtkTextBuffer     *buffer,
136                                                         GtkTextTag        *tag,
137                                                         const GtkTextIter *start_char,
138                                                         const GtkTextIter *end_char);
139 static void gtk_text_buffer_real_changed               (GtkTextBuffer     *buffer);
140 static void gtk_text_buffer_real_mark_set              (GtkTextBuffer     *buffer,
141                                                         const GtkTextIter *iter,
142                                                         GtkTextMark       *mark);
143
144 static GtkTextBTree* get_btree (GtkTextBuffer *buffer);
145 static void          free_log_attr_cache (GtkTextLogAttrCache *cache);
146
147 static void remove_all_selection_clipboards       (GtkTextBuffer *buffer);
148 static void update_selection_clipboards           (GtkTextBuffer *buffer);
149
150 static GtkTextBuffer *create_clipboard_contents_buffer (GtkTextBuffer *buffer);
151
152 static void gtk_text_buffer_free_target_lists     (GtkTextBuffer *buffer);
153
154 static guint signals[LAST_SIGNAL] = { 0 };
155
156 static void gtk_text_buffer_set_property (GObject         *object,
157                                           guint            prop_id,
158                                           const GValue    *value,
159                                           GParamSpec      *pspec);
160 static void gtk_text_buffer_get_property (GObject         *object,
161                                           guint            prop_id,
162                                           GValue          *value,
163                                           GParamSpec      *pspec);
164 static void gtk_text_buffer_notify       (GObject         *object,
165                                           GParamSpec      *pspec);
166
167 G_DEFINE_TYPE (GtkTextBuffer, gtk_text_buffer, G_TYPE_OBJECT)
168
169 static void
170 gtk_text_buffer_class_init (GtkTextBufferClass *klass)
171 {
172   GObjectClass *object_class = G_OBJECT_CLASS (klass);
173
174   object_class->finalize = gtk_text_buffer_finalize;
175   object_class->set_property = gtk_text_buffer_set_property;
176   object_class->get_property = gtk_text_buffer_get_property;
177   object_class->notify       = gtk_text_buffer_notify;
178  
179   klass->insert_text = gtk_text_buffer_real_insert_text;
180   klass->insert_pixbuf = gtk_text_buffer_real_insert_pixbuf;
181   klass->insert_child_anchor = gtk_text_buffer_real_insert_anchor;
182   klass->delete_range = gtk_text_buffer_real_delete_range;
183   klass->apply_tag = gtk_text_buffer_real_apply_tag;
184   klass->remove_tag = gtk_text_buffer_real_remove_tag;
185   klass->changed = gtk_text_buffer_real_changed;
186   klass->mark_set = gtk_text_buffer_real_mark_set;
187
188   /* Construct */
189   g_object_class_install_property (object_class,
190                                    PROP_TAG_TABLE,
191                                    g_param_spec_object ("tag-table",
192                                                         P_("Tag Table"),
193                                                         P_("Text Tag Table"),
194                                                         GTK_TYPE_TEXT_TAG_TABLE,
195                                                         GTK_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
196
197   /* Normal properties*/
198   
199   /**
200    * GtkTextBuffer:text:
201    *
202    * The text content of the buffer. Without child widgets and images,
203    * see gtk_text_buffer_get_text() for more information.
204    *
205    * Since: 2.8
206    */
207   g_object_class_install_property (object_class,
208                                    PROP_TEXT,
209                                    g_param_spec_string ("text",
210                                                         P_("Text"),
211                                                         P_("Current text of the buffer"),
212                                                         "",
213                                                         GTK_PARAM_READWRITE));
214
215   /**
216    * GtkTextBuffer:has-selection:
217    *
218    * Whether the buffer has some text currently selected.
219    *
220    * Since: 2.10
221    */
222   g_object_class_install_property (object_class,
223                                    PROP_HAS_SELECTION,
224                                    g_param_spec_boolean ("has-selection",
225                                                          P_("Has selection"),
226                                                          P_("Whether the buffer has some text currently selected"),
227                                                          FALSE,
228                                                          GTK_PARAM_READABLE));
229
230   /**
231    * GtkTextBuffer:cursor-position:
232    *
233    * The position of the insert mark (as offset from the beginning 
234    * of the buffer). It is useful for getting notified when the 
235    * cursor moves.
236    *
237    * Since: 2.10
238    */
239   g_object_class_install_property (object_class,
240                                    PROP_CURSOR_POSITION,
241                                    g_param_spec_int ("cursor-position",
242                                                      P_("Cursor position"),
243                                                      P_("The position of the insert mark (as offset from the beginning of the buffer)"),
244                                                      0, G_MAXINT, 0,
245                                                      GTK_PARAM_READABLE));
246
247   /**
248    * GtkTextBuffer:copy-target-list:
249    *
250    * The list of targets this buffer supports for clipboard copying
251    * and as DND source.
252    *
253    * Since: 2.10
254    */
255   g_object_class_install_property (object_class,
256                                    PROP_COPY_TARGET_LIST,
257                                    g_param_spec_boxed ("copy-target-list",
258                                                        P_("Copy target list"),
259                                                        P_("The list of targets this buffer supports for clipboard copying and DND source"),
260                                                        GTK_TYPE_TARGET_LIST,
261                                                        GTK_PARAM_READABLE));
262
263   /**
264    * GtkTextBuffer:paste-target-list:
265    *
266    * The list of targets this buffer supports for clipboard pasting
267    * and as DND destination.
268    *
269    * Since: 2.10
270    */
271   g_object_class_install_property (object_class,
272                                    PROP_PASTE_TARGET_LIST,
273                                    g_param_spec_boxed ("paste-target-list",
274                                                        P_("Paste target list"),
275                                                        P_("The list of targets this buffer supports for clipboard pasting and DND destination"),
276                                                        GTK_TYPE_TARGET_LIST,
277                                                        GTK_PARAM_READABLE));
278
279   /**
280    * GtkTextBuffer::insert-text:
281    * @textbuffer: the object which received the signal
282    * @location: position to insert @text in @textbuffer
283    * @text: the UTF-8 text to be inserted
284    * @len: length of the inserted text in bytes
285    * 
286    * The ::insert-text signal is emitted to insert text in a #GtkTextBuffer.
287    * Insertion actually occurs in the default handler.  
288    * 
289    * Note that if your handler runs before the default handler it must not 
290    * invalidate the @location iter (or has to revalidate it). 
291    * The default signal handler revalidates it to point to the end of the 
292    * inserted text.
293    * 
294    * See also: 
295    * gtk_text_buffer_insert(), 
296    * gtk_text_buffer_insert_range().
297    */
298   signals[INSERT_TEXT] =
299     g_signal_new (I_("insert-text"),
300                   G_OBJECT_CLASS_TYPE (object_class),
301                   G_SIGNAL_RUN_LAST,
302                   G_STRUCT_OFFSET (GtkTextBufferClass, insert_text),
303                   NULL, NULL,
304                   _gtk_marshal_VOID__BOXED_STRING_INT,
305                   G_TYPE_NONE,
306                   3,
307                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
308                   G_TYPE_STRING | G_SIGNAL_TYPE_STATIC_SCOPE,
309                   G_TYPE_INT);
310
311   /**
312    * GtkTextBuffer::insert-pixbuf:
313    * @textbuffer: the object which received the signal
314    * @location: position to insert @pixbuf in @textbuffer
315    * @pixbuf: the #GdkPixbuf to be inserted
316    * 
317    * The ::insert-pixbuf signal is emitted to insert a #GdkPixbuf 
318    * in a #GtkTextBuffer. Insertion actually occurs in the default handler.
319    * 
320    * Note that if your handler runs before the default handler it must not 
321    * invalidate the @location iter (or has to revalidate it). 
322    * The default signal handler revalidates it to be placed after the 
323    * inserted @pixbuf.
324    * 
325    * See also: gtk_text_buffer_insert_pixbuf().
326    */
327   signals[INSERT_PIXBUF] =
328     g_signal_new (I_("insert-pixbuf"),
329                   G_OBJECT_CLASS_TYPE (object_class),
330                   G_SIGNAL_RUN_LAST,
331                   G_STRUCT_OFFSET (GtkTextBufferClass, insert_pixbuf),
332                   NULL, NULL,
333                   _gtk_marshal_VOID__BOXED_OBJECT,
334                   G_TYPE_NONE,
335                   2,
336                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
337                   GDK_TYPE_PIXBUF);
338
339
340   /**
341    * GtkTextBuffer::insert-child-anchor:
342    * @textbuffer: the object which received the signal
343    * @location: position to insert @anchor in @textbuffer
344    * @anchor: the #GtkTextChildAnchor to be inserted
345    * 
346    * The ::insert-child-anchor signal is emitted to insert a
347    * #GtkTextChildAnchor in a #GtkTextBuffer.
348    * Insertion actually occurs in the default handler.
349    * 
350    * Note that if your handler runs before the default handler it must
351    * not invalidate the @location iter (or has to revalidate it). 
352    * The default signal handler revalidates it to be placed after the 
353    * inserted @anchor.
354    * 
355    * See also: gtk_text_buffer_insert_child_anchor().
356    */
357   signals[INSERT_CHILD_ANCHOR] =
358     g_signal_new (I_("insert-child-anchor"),
359                   G_OBJECT_CLASS_TYPE (object_class),
360                   G_SIGNAL_RUN_LAST,
361                   G_STRUCT_OFFSET (GtkTextBufferClass, insert_child_anchor),
362                   NULL, NULL,
363                   _gtk_marshal_VOID__BOXED_OBJECT,
364                   G_TYPE_NONE,
365                   2,
366                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
367                   GTK_TYPE_TEXT_CHILD_ANCHOR);
368   
369   /**
370    * GtkTextBuffer::delete-range:
371    * @textbuffer: the object which received the signal
372    * @start: the start of the range to be deleted
373    * @end: the end of the range to be deleted
374    * 
375    * The ::delete-range signal is emitted to delete a range 
376    * from a #GtkTextBuffer. 
377    * 
378    * Note that if your handler runs before the default handler it must not 
379    * invalidate the @start and @end iters (or has to revalidate them). 
380    * The default signal handler revalidates the @start and @end iters to 
381    * both point point to the location where text was deleted. Handlers
382    * which run after the default handler (see g_signal_connect_after())
383    * do not have access to the deleted text.
384    * 
385    * See also: gtk_text_buffer_delete().
386    */
387   signals[DELETE_RANGE] =
388     g_signal_new (I_("delete-range"),
389                   G_OBJECT_CLASS_TYPE (object_class),
390                   G_SIGNAL_RUN_LAST,
391                   G_STRUCT_OFFSET (GtkTextBufferClass, delete_range),
392                   NULL, NULL,
393                   _gtk_marshal_VOID__BOXED_BOXED,
394                   G_TYPE_NONE,
395                   2,
396                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
397                   GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE);
398
399   /**
400    * GtkTextBuffer::changed:
401    * @textbuffer: the object which received the signal
402    * 
403    * The ::changed signal is emitted when the content of a #GtkTextBuffer 
404    * has changed.
405    */
406   signals[CHANGED] =
407     g_signal_new (I_("changed"),
408                   G_OBJECT_CLASS_TYPE (object_class),
409                   G_SIGNAL_RUN_LAST,                   
410                   G_STRUCT_OFFSET (GtkTextBufferClass, changed),
411                   NULL, NULL,
412                   _gtk_marshal_VOID__VOID,
413                   G_TYPE_NONE,
414                   0);
415
416   /**
417    * GtkTextBuffer::modified-changed:
418    * @textbuffer: the object which received the signal
419    * 
420    * The ::modified-changed signal is emitted when the modified bit of a 
421    * #GtkTextBuffer flips.
422    * 
423    * See also:
424    * gtk_text_buffer_set_modified().
425    */
426   signals[MODIFIED_CHANGED] =
427     g_signal_new (I_("modified-changed"),
428                   G_OBJECT_CLASS_TYPE (object_class),
429                   G_SIGNAL_RUN_LAST,
430                   G_STRUCT_OFFSET (GtkTextBufferClass, modified_changed),
431                   NULL, NULL,
432                   _gtk_marshal_VOID__VOID,
433                   G_TYPE_NONE,
434                   0);
435
436   /**
437    * GtkTextBuffer::mark-set:
438    * @textbuffer: the object which received the signal
439    * @location: The location of @mark in @textbuffer
440    * @mark: The mark that is set
441    * 
442    * The ::mark-set signal is emitted as notification
443    * after a #GtkTextMark is set.
444    * 
445    * See also: 
446    * gtk_text_buffer_create_mark(),
447    * gtk_text_buffer_move_mark().
448    */
449   signals[MARK_SET] =
450     g_signal_new (I_("mark-set"),
451                   G_OBJECT_CLASS_TYPE (object_class),
452                   G_SIGNAL_RUN_LAST,                   
453                   G_STRUCT_OFFSET (GtkTextBufferClass, mark_set),
454                   NULL, NULL,
455                   _gtk_marshal_VOID__BOXED_OBJECT,
456                   G_TYPE_NONE,
457                   2,
458                   GTK_TYPE_TEXT_ITER,
459                   GTK_TYPE_TEXT_MARK);
460
461   /**
462    * GtkTextBuffer::mark-deleted:
463    * @textbuffer: the object which received the signal
464    * @mark: The mark that was deleted
465    * 
466    * The ::mark-deleted signal is emitted as notification
467    * after a #GtkTextMark is deleted. 
468    * 
469    * See also:
470    * gtk_text_buffer_delete_mark().
471    */
472   signals[MARK_DELETED] =
473     g_signal_new (I_("mark-deleted"),
474                   G_OBJECT_CLASS_TYPE (object_class),
475                   G_SIGNAL_RUN_LAST,                   
476                   G_STRUCT_OFFSET (GtkTextBufferClass, mark_deleted),
477                   NULL, NULL,
478                   _gtk_marshal_VOID__OBJECT,
479                   G_TYPE_NONE,
480                   1,
481                   GTK_TYPE_TEXT_MARK);
482
483    /**
484    * GtkTextBuffer::apply-tag:
485    * @textbuffer: the object which received the signal
486    * @tag: the applied tag
487    * @start: the start of the range the tag is applied to
488    * @end: the end of the range the tag is applied to
489    * 
490    * The ::apply-tag signal is emitted to apply a tag to a
491    * range of text in a #GtkTextBuffer. 
492    * Applying actually occurs in the default handler.
493    * 
494    * Note that if your handler runs before the default handler it must not 
495    * invalidate the @start and @end iters (or has to revalidate them). 
496    * 
497    * See also: 
498    * gtk_text_buffer_apply_tag(),
499    * gtk_text_buffer_insert_with_tags(),
500    * gtk_text_buffer_insert_range().
501    */ 
502   signals[APPLY_TAG] =
503     g_signal_new (I_("apply-tag"),
504                   G_OBJECT_CLASS_TYPE (object_class),
505                   G_SIGNAL_RUN_LAST,
506                   G_STRUCT_OFFSET (GtkTextBufferClass, apply_tag),
507                   NULL, NULL,
508                   _gtk_marshal_VOID__OBJECT_BOXED_BOXED,
509                   G_TYPE_NONE,
510                   3,
511                   GTK_TYPE_TEXT_TAG,
512                   GTK_TYPE_TEXT_ITER,
513                   GTK_TYPE_TEXT_ITER);
514
515
516    /**
517    * GtkTextBuffer::remove-tag:
518    * @textbuffer: the object which received the signal
519    * @tag: the tag to be removed
520    * @start: the start of the range the tag is removed from
521    * @end: the end of the range the tag is removed from
522    * 
523    * The ::remove-tag signal is emitted to remove all occurrences of @tag from
524    * a range of text in a #GtkTextBuffer. 
525    * Removal actually occurs in the default handler.
526    * 
527    * Note that if your handler runs before the default handler it must not 
528    * invalidate the @start and @end iters (or has to revalidate them). 
529    * 
530    * See also: 
531    * gtk_text_buffer_remove_tag(). 
532    */ 
533   signals[REMOVE_TAG] =
534     g_signal_new (I_("remove-tag"),
535                   G_OBJECT_CLASS_TYPE (object_class),
536                   G_SIGNAL_RUN_LAST,
537                   G_STRUCT_OFFSET (GtkTextBufferClass, remove_tag),
538                   NULL, NULL,
539                   _gtk_marshal_VOID__OBJECT_BOXED_BOXED,
540                   G_TYPE_NONE,
541                   3,
542                   GTK_TYPE_TEXT_TAG,
543                   GTK_TYPE_TEXT_ITER,
544                   GTK_TYPE_TEXT_ITER);
545
546    /**
547    * GtkTextBuffer::begin-user-action:
548    * @textbuffer: the object which received the signal
549    * 
550    * The ::begin-user-action signal is emitted at the beginning of a single
551    * user-visible operation on a #GtkTextBuffer.
552    * 
553    * See also: 
554    * gtk_text_buffer_begin_user_action(),
555    * gtk_text_buffer_insert_interactive(),
556    * gtk_text_buffer_insert_range_interactive(),
557    * gtk_text_buffer_delete_interactive(),
558    * gtk_text_buffer_backspace(),
559    * gtk_text_buffer_delete_selection().
560    */ 
561   signals[BEGIN_USER_ACTION] =
562     g_signal_new (I_("begin-user-action"),
563                   G_OBJECT_CLASS_TYPE (object_class),
564                   G_SIGNAL_RUN_LAST,                   
565                   G_STRUCT_OFFSET (GtkTextBufferClass, begin_user_action),
566                   NULL, NULL,
567                   _gtk_marshal_VOID__VOID,
568                   G_TYPE_NONE,
569                   0);
570
571    /**
572    * GtkTextBuffer::end-user-action:
573    * @textbuffer: the object which received the signal
574    * 
575    * The ::end-user-action signal is emitted at the end of a single
576    * user-visible operation on the #GtkTextBuffer.
577    * 
578    * See also: 
579    * gtk_text_buffer_end_user_action(),
580    * gtk_text_buffer_insert_interactive(),
581    * gtk_text_buffer_insert_range_interactive(),
582    * gtk_text_buffer_delete_interactive(),
583    * gtk_text_buffer_backspace(),
584    * gtk_text_buffer_delete_selection(),
585    * gtk_text_buffer_backspace().
586    */ 
587   signals[END_USER_ACTION] =
588     g_signal_new (I_("end-user-action"),
589                   G_OBJECT_CLASS_TYPE (object_class),
590                   G_SIGNAL_RUN_LAST,                   
591                   G_STRUCT_OFFSET (GtkTextBufferClass, end_user_action),
592                   NULL, NULL,
593                   _gtk_marshal_VOID__VOID,
594                   G_TYPE_NONE,
595                   0);
596
597    /**
598    * GtkTextBuffer::paste-done:
599    * @textbuffer: the object which received the signal
600    * 
601    * The paste-done signal is emitted after paste operation has been completed.
602    * This is useful to properly scroll the view to the end of the pasted text.
603    * See gtk_text_buffer_paste_clipboard() for more details.
604    * 
605    * Since: 2.16
606    */ 
607   signals[PASTE_DONE] =
608     g_signal_new (I_("paste-done"),
609                   G_OBJECT_CLASS_TYPE (object_class),
610                   G_SIGNAL_RUN_LAST,
611                   G_STRUCT_OFFSET (GtkTextBufferClass, paste_done),
612                   NULL, NULL,
613                   _gtk_marshal_VOID__OBJECT,
614                   G_TYPE_NONE,
615                   1,
616                   GTK_TYPE_CLIPBOARD);
617
618   g_type_class_add_private (object_class, sizeof (GtkTextBufferPrivate));
619 }
620
621 static void
622 gtk_text_buffer_init (GtkTextBuffer *buffer)
623 {
624   buffer->priv = G_TYPE_INSTANCE_GET_PRIVATE (buffer,
625                                               GTK_TYPE_TEXT_BUFFER,
626                                               GtkTextBufferPrivate);
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: text in UTF-8 format
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: 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: (transfer none): 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  * Creates a tag and adds it to the tag table for @buffer.
2461  * Equivalent to calling gtk_text_tag_new() and then adding the
2462  * tag to the buffer's tag table. The returned tag is owned by
2463  * the buffer's tag table, so the ref count will be equal to one.
2464  *
2465  * If @tag_name is %NULL, the tag is anonymous.
2466  *
2467  * If @tag_name is non-%NULL, a tag called @tag_name must not already
2468  * exist in the tag table for this buffer.
2469  *
2470  * The @first_property_name argument and subsequent arguments are a list
2471  * of properties to set on the tag, as with g_object_set().
2472  *
2473  * Return value: (transfer none): a new tag
2474  */
2475 GtkTextTag*
2476 gtk_text_buffer_create_tag (GtkTextBuffer *buffer,
2477                             const gchar   *tag_name,
2478                             const gchar   *first_property_name,
2479                             ...)
2480 {
2481   GtkTextTag *tag;
2482   va_list list;
2483   
2484   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
2485
2486   tag = gtk_text_tag_new (tag_name);
2487
2488   gtk_text_tag_table_add (get_table (buffer), tag);
2489
2490   if (first_property_name)
2491     {
2492       va_start (list, first_property_name);
2493       g_object_set_valist (G_OBJECT (tag), first_property_name, list);
2494       va_end (list);
2495     }
2496   
2497   g_object_unref (tag);
2498
2499   return tag;
2500 }
2501
2502 static void
2503 gtk_text_buffer_real_apply_tag (GtkTextBuffer     *buffer,
2504                                 GtkTextTag        *tag,
2505                                 const GtkTextIter *start,
2506                                 const GtkTextIter *end)
2507 {
2508   if (tag->priv->table != buffer->priv->tag_table)
2509     {
2510       g_warning ("Can only apply tags that are in the tag table for the buffer");
2511       return;
2512     }
2513   
2514   _gtk_text_btree_tag (start, end, tag, TRUE);
2515 }
2516
2517 static void
2518 gtk_text_buffer_real_remove_tag (GtkTextBuffer     *buffer,
2519                                  GtkTextTag        *tag,
2520                                  const GtkTextIter *start,
2521                                  const GtkTextIter *end)
2522 {
2523   if (tag->priv->table != buffer->priv->tag_table)
2524     {
2525       g_warning ("Can only remove tags that are in the tag table for the buffer");
2526       return;
2527     }
2528   
2529   _gtk_text_btree_tag (start, end, tag, FALSE);
2530 }
2531
2532 static void
2533 gtk_text_buffer_real_changed (GtkTextBuffer *buffer)
2534 {
2535   gtk_text_buffer_set_modified (buffer, TRUE);
2536 }
2537
2538 static void
2539 gtk_text_buffer_real_mark_set (GtkTextBuffer     *buffer,
2540                                const GtkTextIter *iter,
2541                                GtkTextMark       *mark)
2542 {
2543   GtkTextMark *insert;
2544   
2545   insert = gtk_text_buffer_get_insert (buffer);
2546
2547   if (mark == insert || mark == gtk_text_buffer_get_selection_bound (buffer))
2548     {
2549       gboolean has_selection;
2550
2551       update_selection_clipboards (buffer);
2552     
2553       has_selection = gtk_text_buffer_get_selection_bounds (buffer,
2554                                                             NULL,
2555                                                             NULL);
2556
2557       if (has_selection != buffer->priv->has_selection)
2558         {
2559           buffer->priv->has_selection = has_selection;
2560           g_object_notify (G_OBJECT (buffer), "has-selection");
2561         }
2562     }
2563     
2564     if (mark == insert)
2565       g_object_notify (G_OBJECT (buffer), "cursor-position");
2566 }
2567
2568 static void
2569 gtk_text_buffer_emit_tag (GtkTextBuffer     *buffer,
2570                           GtkTextTag        *tag,
2571                           gboolean           apply,
2572                           const GtkTextIter *start,
2573                           const GtkTextIter *end)
2574 {
2575   GtkTextIter start_tmp = *start;
2576   GtkTextIter end_tmp = *end;
2577
2578   g_return_if_fail (tag != NULL);
2579
2580   gtk_text_iter_order (&start_tmp, &end_tmp);
2581
2582   if (apply)
2583     g_signal_emit (buffer, signals[APPLY_TAG],
2584                    0,
2585                    tag, &start_tmp, &end_tmp);
2586   else
2587     g_signal_emit (buffer, signals[REMOVE_TAG],
2588                    0,
2589                    tag, &start_tmp, &end_tmp);
2590 }
2591
2592 /**
2593  * gtk_text_buffer_apply_tag:
2594  * @buffer: a #GtkTextBuffer
2595  * @tag: a #GtkTextTag
2596  * @start: one bound of range to be tagged
2597  * @end: other bound of range to be tagged
2598  *
2599  * Emits the "apply-tag" signal on @buffer. The default
2600  * handler for the signal applies @tag to the given range.
2601  * @start and @end do not have to be in order.
2602  **/
2603 void
2604 gtk_text_buffer_apply_tag (GtkTextBuffer     *buffer,
2605                            GtkTextTag        *tag,
2606                            const GtkTextIter *start,
2607                            const GtkTextIter *end)
2608 {
2609   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2610   g_return_if_fail (GTK_IS_TEXT_TAG (tag));
2611   g_return_if_fail (start != NULL);
2612   g_return_if_fail (end != NULL);
2613   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2614   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2615   g_return_if_fail (tag->priv->table == buffer->priv->tag_table);
2616   
2617   gtk_text_buffer_emit_tag (buffer, tag, TRUE, start, end);
2618 }
2619
2620 /**
2621  * gtk_text_buffer_remove_tag:
2622  * @buffer: a #GtkTextBuffer
2623  * @tag: a #GtkTextTag
2624  * @start: one bound of range to be untagged
2625  * @end: other bound of range to be untagged
2626  *
2627  * Emits the "remove-tag" signal. The default handler for the signal
2628  * removes all occurrences of @tag from the given range. @start and
2629  * @end don't have to be in order.
2630  **/
2631 void
2632 gtk_text_buffer_remove_tag (GtkTextBuffer     *buffer,
2633                             GtkTextTag        *tag,
2634                             const GtkTextIter *start,
2635                             const GtkTextIter *end)
2636
2637 {
2638   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2639   g_return_if_fail (GTK_IS_TEXT_TAG (tag));
2640   g_return_if_fail (start != NULL);
2641   g_return_if_fail (end != NULL);
2642   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2643   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2644   g_return_if_fail (tag->priv->table == buffer->priv->tag_table);
2645   
2646   gtk_text_buffer_emit_tag (buffer, tag, FALSE, start, end);
2647 }
2648
2649 /**
2650  * gtk_text_buffer_apply_tag_by_name:
2651  * @buffer: a #GtkTextBuffer
2652  * @name: name of a named #GtkTextTag
2653  * @start: one bound of range to be tagged
2654  * @end: other bound of range to be tagged
2655  *
2656  * Calls gtk_text_tag_table_lookup() on the buffer's tag table to
2657  * get a #GtkTextTag, then calls gtk_text_buffer_apply_tag().
2658  **/
2659 void
2660 gtk_text_buffer_apply_tag_by_name (GtkTextBuffer     *buffer,
2661                                    const gchar       *name,
2662                                    const GtkTextIter *start,
2663                                    const GtkTextIter *end)
2664 {
2665   GtkTextTag *tag;
2666
2667   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2668   g_return_if_fail (name != NULL);
2669   g_return_if_fail (start != NULL);
2670   g_return_if_fail (end != NULL);
2671   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2672   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2673
2674   tag = gtk_text_tag_table_lookup (get_table (buffer),
2675                                    name);
2676
2677   if (tag == NULL)
2678     {
2679       g_warning ("Unknown tag `%s'", name);
2680       return;
2681     }
2682
2683   gtk_text_buffer_emit_tag (buffer, tag, TRUE, start, end);
2684 }
2685
2686 /**
2687  * gtk_text_buffer_remove_tag_by_name:
2688  * @buffer: a #GtkTextBuffer
2689  * @name: name of a #GtkTextTag
2690  * @start: one bound of range to be untagged
2691  * @end: other bound of range to be untagged
2692  *
2693  * Calls gtk_text_tag_table_lookup() on the buffer's tag table to
2694  * get a #GtkTextTag, then calls gtk_text_buffer_remove_tag().
2695  **/
2696 void
2697 gtk_text_buffer_remove_tag_by_name (GtkTextBuffer     *buffer,
2698                                     const gchar       *name,
2699                                     const GtkTextIter *start,
2700                                     const GtkTextIter *end)
2701 {
2702   GtkTextTag *tag;
2703
2704   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2705   g_return_if_fail (name != NULL);
2706   g_return_if_fail (start != NULL);
2707   g_return_if_fail (end != NULL);
2708   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2709   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2710   
2711   tag = gtk_text_tag_table_lookup (get_table (buffer),
2712                                    name);
2713
2714   if (tag == NULL)
2715     {
2716       g_warning ("Unknown tag `%s'", name);
2717       return;
2718     }
2719
2720   gtk_text_buffer_emit_tag (buffer, tag, FALSE, start, end);
2721 }
2722
2723 static gint
2724 pointer_cmp (gconstpointer a,
2725              gconstpointer b)
2726 {
2727   if (a < b)
2728     return -1;
2729   else if (a > b)
2730     return 1;
2731   else
2732     return 0;
2733 }
2734
2735 /**
2736  * gtk_text_buffer_remove_all_tags:
2737  * @buffer: a #GtkTextBuffer
2738  * @start: one bound of range to be untagged
2739  * @end: other bound of range to be untagged
2740  * 
2741  * Removes all tags in the range between @start and @end.  Be careful
2742  * with this function; it could remove tags added in code unrelated to
2743  * the code you're currently writing. That is, using this function is
2744  * probably a bad idea if you have two or more unrelated code sections
2745  * that add tags.
2746  **/
2747 void
2748 gtk_text_buffer_remove_all_tags (GtkTextBuffer     *buffer,
2749                                  const GtkTextIter *start,
2750                                  const GtkTextIter *end)
2751 {
2752   GtkTextIter first, second, tmp;
2753   GSList *tags;
2754   GSList *tmp_list;
2755   GSList *prev, *next;
2756   GtkTextTag *tag;
2757   
2758   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2759   g_return_if_fail (start != NULL);
2760   g_return_if_fail (end != NULL);
2761   g_return_if_fail (gtk_text_iter_get_buffer (start) == buffer);
2762   g_return_if_fail (gtk_text_iter_get_buffer (end) == buffer);
2763   
2764   first = *start;
2765   second = *end;
2766
2767   gtk_text_iter_order (&first, &second);
2768
2769   /* Get all tags turned on at the start */
2770   tags = gtk_text_iter_get_tags (&first);
2771   
2772   /* Find any that are toggled on within the range */
2773   tmp = first;
2774   while (gtk_text_iter_forward_to_tag_toggle (&tmp, NULL))
2775     {
2776       GSList *toggled;
2777       GSList *tmp_list2;
2778
2779       if (gtk_text_iter_compare (&tmp, &second) >= 0)
2780         break; /* past the end of the range */
2781       
2782       toggled = gtk_text_iter_get_toggled_tags (&tmp, TRUE);
2783
2784       /* We could end up with a really big-ass list here.
2785        * Fix it someday.
2786        */
2787       tmp_list2 = toggled;
2788       while (tmp_list2 != NULL)
2789         {
2790           tags = g_slist_prepend (tags, tmp_list2->data);
2791
2792           tmp_list2 = g_slist_next (tmp_list2);
2793         }
2794
2795       g_slist_free (toggled);
2796     }
2797   
2798   /* Sort the list */
2799   tags = g_slist_sort (tags, pointer_cmp);
2800
2801   /* Strip duplicates */
2802   tag = NULL;
2803   prev = NULL;
2804   tmp_list = tags;
2805   while (tmp_list != NULL)
2806     {
2807       if (tag == tmp_list->data)
2808         {
2809           /* duplicate */
2810           next = tmp_list->next;
2811           if (prev)
2812             prev->next = next;
2813
2814           tmp_list->next = NULL;
2815
2816           g_slist_free (tmp_list);
2817
2818           tmp_list = next;
2819           /* prev is unchanged */
2820         }
2821       else
2822         {
2823           /* not a duplicate */
2824           tag = GTK_TEXT_TAG (tmp_list->data);
2825           prev = tmp_list;
2826           tmp_list = tmp_list->next;
2827         }
2828     }
2829
2830   g_slist_foreach (tags, (GFunc) g_object_ref, NULL);
2831   
2832   tmp_list = tags;
2833   while (tmp_list != NULL)
2834     {
2835       tag = GTK_TEXT_TAG (tmp_list->data);
2836
2837       gtk_text_buffer_remove_tag (buffer, tag, &first, &second);
2838       
2839       tmp_list = tmp_list->next;
2840     }
2841
2842   g_slist_foreach (tags, (GFunc) g_object_unref, NULL);
2843   
2844   g_slist_free (tags);
2845 }
2846
2847
2848 /*
2849  * Obtain various iterators
2850  */
2851
2852 /**
2853  * gtk_text_buffer_get_iter_at_line_offset:
2854  * @buffer: a #GtkTextBuffer
2855  * @iter: (out): iterator to initialize
2856  * @line_number: line number counting from 0
2857  * @char_offset: char offset from start of line
2858  *
2859  * Obtains an iterator pointing to @char_offset within the given
2860  * line. The @char_offset must exist, offsets off the end of the line
2861  * are not allowed. Note <emphasis>characters</emphasis>, not bytes;
2862  * UTF-8 may encode one character as multiple bytes.
2863  **/
2864 void
2865 gtk_text_buffer_get_iter_at_line_offset (GtkTextBuffer *buffer,
2866                                          GtkTextIter   *iter,
2867                                          gint           line_number,
2868                                          gint           char_offset)
2869 {
2870   g_return_if_fail (iter != NULL);
2871   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2872
2873   _gtk_text_btree_get_iter_at_line_char (get_btree (buffer),
2874                                          iter, line_number, char_offset);
2875 }
2876
2877 /**
2878  * gtk_text_buffer_get_iter_at_line_index:
2879  * @buffer: a #GtkTextBuffer 
2880  * @iter: (out): iterator to initialize 
2881  * @line_number: line number counting from 0
2882  * @byte_index: byte index from start of line
2883  *
2884  * Obtains an iterator pointing to @byte_index within the given line.
2885  * @byte_index must be the start of a UTF-8 character, and must not be
2886  * beyond the end of the line.  Note <emphasis>bytes</emphasis>, not
2887  * characters; UTF-8 may encode one character as multiple bytes.
2888  **/
2889 void
2890 gtk_text_buffer_get_iter_at_line_index  (GtkTextBuffer *buffer,
2891                                          GtkTextIter   *iter,
2892                                          gint           line_number,
2893                                          gint           byte_index)
2894 {
2895   g_return_if_fail (iter != NULL);
2896   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2897
2898   _gtk_text_btree_get_iter_at_line_byte (get_btree (buffer),
2899                                          iter, line_number, byte_index);
2900 }
2901
2902 /**
2903  * gtk_text_buffer_get_iter_at_line:
2904  * @buffer: a #GtkTextBuffer 
2905  * @iter: (out): iterator to initialize
2906  * @line_number: line number counting from 0
2907  * 
2908  * Initializes @iter to the start of the given line.
2909  **/
2910 void
2911 gtk_text_buffer_get_iter_at_line (GtkTextBuffer *buffer,
2912                                   GtkTextIter   *iter,
2913                                   gint           line_number)
2914 {
2915   g_return_if_fail (iter != NULL);
2916   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2917
2918   gtk_text_buffer_get_iter_at_line_offset (buffer, iter, line_number, 0);
2919 }
2920
2921 /**
2922  * gtk_text_buffer_get_iter_at_offset:
2923  * @buffer: a #GtkTextBuffer 
2924  * @iter: (out): iterator to initialize
2925  * @char_offset: char offset from start of buffer, counting from 0, or -1
2926  *
2927  * Initializes @iter to a position @char_offset chars from the start
2928  * of the entire buffer. If @char_offset is -1 or greater than the number
2929  * of characters in the buffer, @iter is initialized to the end iterator,
2930  * the iterator one past the last valid character in the buffer.
2931  **/
2932 void
2933 gtk_text_buffer_get_iter_at_offset (GtkTextBuffer *buffer,
2934                                     GtkTextIter   *iter,
2935                                     gint           char_offset)
2936 {
2937   g_return_if_fail (iter != NULL);
2938   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2939
2940   _gtk_text_btree_get_iter_at_char (get_btree (buffer), iter, char_offset);
2941 }
2942
2943 /**
2944  * gtk_text_buffer_get_start_iter:
2945  * @buffer: a #GtkTextBuffer
2946  * @iter: (out): iterator to initialize
2947  *
2948  * Initialized @iter with the first position in the text buffer. This
2949  * is the same as using gtk_text_buffer_get_iter_at_offset() to get
2950  * the iter at character offset 0.
2951  **/
2952 void
2953 gtk_text_buffer_get_start_iter (GtkTextBuffer *buffer,
2954                                 GtkTextIter   *iter)
2955 {
2956   g_return_if_fail (iter != NULL);
2957   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2958
2959   _gtk_text_btree_get_iter_at_char (get_btree (buffer), iter, 0);
2960 }
2961
2962 /**
2963  * gtk_text_buffer_get_end_iter:
2964  * @buffer: a #GtkTextBuffer 
2965  * @iter: (out): iterator to initialize
2966  *
2967  * Initializes @iter with the "end iterator," one past the last valid
2968  * character in the text buffer. If dereferenced with
2969  * gtk_text_iter_get_char(), the end iterator has a character value of
2970  * 0. The entire buffer lies in the range from the first position in
2971  * the buffer (call gtk_text_buffer_get_start_iter() to get
2972  * character position 0) to the end iterator.
2973  **/
2974 void
2975 gtk_text_buffer_get_end_iter (GtkTextBuffer *buffer,
2976                               GtkTextIter   *iter)
2977 {
2978   g_return_if_fail (iter != NULL);
2979   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2980
2981   _gtk_text_btree_get_end_iter (get_btree (buffer), iter);
2982 }
2983
2984 /**
2985  * gtk_text_buffer_get_bounds:
2986  * @buffer: a #GtkTextBuffer 
2987  * @start: (out): iterator to initialize with first position in the buffer
2988  * @end: (out): iterator to initialize with the end iterator
2989  *
2990  * Retrieves the first and last iterators in the buffer, i.e. the
2991  * entire buffer lies within the range [@start,@end).
2992  **/
2993 void
2994 gtk_text_buffer_get_bounds (GtkTextBuffer *buffer,
2995                             GtkTextIter   *start,
2996                             GtkTextIter   *end)
2997 {
2998   g_return_if_fail (start != NULL);
2999   g_return_if_fail (end != NULL);
3000   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3001
3002   _gtk_text_btree_get_iter_at_char (get_btree (buffer), start, 0);
3003   _gtk_text_btree_get_end_iter (get_btree (buffer), end);
3004 }
3005
3006 /*
3007  * Modified flag
3008  */
3009
3010 /**
3011  * gtk_text_buffer_get_modified:
3012  * @buffer: a #GtkTextBuffer 
3013  * 
3014  * Indicates whether the buffer has been modified since the last call
3015  * to gtk_text_buffer_set_modified() set the modification flag to
3016  * %FALSE. Used for example to enable a "save" function in a text
3017  * editor.
3018  * 
3019  * Return value: %TRUE if the buffer has been modified
3020  **/
3021 gboolean
3022 gtk_text_buffer_get_modified (GtkTextBuffer *buffer)
3023 {
3024   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
3025
3026   return buffer->priv->modified;
3027 }
3028
3029 /**
3030  * gtk_text_buffer_set_modified:
3031  * @buffer: a #GtkTextBuffer 
3032  * @setting: modification flag setting
3033  *
3034  * Used to keep track of whether the buffer has been modified since the
3035  * last time it was saved. Whenever the buffer is saved to disk, call
3036  * gtk_text_buffer_set_modified (@buffer, FALSE). When the buffer is modified,
3037  * it will automatically toggled on the modified bit again. When the modified
3038  * bit flips, the buffer emits a "modified-changed" signal.
3039  **/
3040 void
3041 gtk_text_buffer_set_modified (GtkTextBuffer *buffer,
3042                               gboolean       setting)
3043 {
3044   gboolean fixed_setting;
3045
3046   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3047
3048   fixed_setting = setting != FALSE;
3049
3050   if (buffer->priv->modified == fixed_setting)
3051     return;
3052   else
3053     {
3054       buffer->priv->modified = fixed_setting;
3055       g_signal_emit (buffer, signals[MODIFIED_CHANGED], 0);
3056     }
3057 }
3058
3059 /**
3060  * gtk_text_buffer_get_has_selection:
3061  * @buffer: a #GtkTextBuffer 
3062  * 
3063  * Indicates whether the buffer has some text currently selected.
3064  * 
3065  * Return value: %TRUE if the there is text selected
3066  *
3067  * Since: 2.10
3068  **/
3069 gboolean
3070 gtk_text_buffer_get_has_selection (GtkTextBuffer *buffer)
3071 {
3072   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
3073
3074   return buffer->priv->has_selection;
3075 }
3076
3077
3078 /*
3079  * Assorted other stuff
3080  */
3081
3082 /**
3083  * gtk_text_buffer_get_line_count:
3084  * @buffer: a #GtkTextBuffer 
3085  * 
3086  * Obtains the number of lines in the buffer. This value is cached, so
3087  * the function is very fast.
3088  * 
3089  * Return value: number of lines in the buffer
3090  **/
3091 gint
3092 gtk_text_buffer_get_line_count (GtkTextBuffer *buffer)
3093 {
3094   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), 0);
3095
3096   return _gtk_text_btree_line_count (get_btree (buffer));
3097 }
3098
3099 /**
3100  * gtk_text_buffer_get_char_count:
3101  * @buffer: a #GtkTextBuffer 
3102  * 
3103  * Gets the number of characters in the buffer; note that characters
3104  * and bytes are not the same, you can't e.g. expect the contents of
3105  * the buffer in string form to be this many bytes long. The character
3106  * count is cached, so this function is very fast.
3107  * 
3108  * Return value: number of characters in the buffer
3109  **/
3110 gint
3111 gtk_text_buffer_get_char_count (GtkTextBuffer *buffer)
3112 {
3113   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), 0);
3114
3115   return _gtk_text_btree_char_count (get_btree (buffer));
3116 }
3117
3118 /* Called when we lose the primary selection.
3119  */
3120 static void
3121 clipboard_clear_selection_cb (GtkClipboard *clipboard,
3122                               gpointer      data)
3123 {
3124   /* Move selection_bound to the insertion point */
3125   GtkTextIter insert;
3126   GtkTextIter selection_bound;
3127   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
3128
3129   gtk_text_buffer_get_iter_at_mark (buffer, &insert,
3130                                     gtk_text_buffer_get_insert (buffer));
3131   gtk_text_buffer_get_iter_at_mark (buffer, &selection_bound,
3132                                     gtk_text_buffer_get_selection_bound (buffer));
3133
3134   if (!gtk_text_iter_equal (&insert, &selection_bound))
3135     gtk_text_buffer_move_mark (buffer,
3136                                gtk_text_buffer_get_selection_bound (buffer),
3137                                &insert);
3138 }
3139
3140 /* Called when we have the primary selection and someone else wants our
3141  * data in order to paste it.
3142  */
3143 static void
3144 clipboard_get_selection_cb (GtkClipboard     *clipboard,
3145                             GtkSelectionData *selection_data,
3146                             guint             info,
3147                             gpointer          data)
3148 {
3149   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
3150   GtkTextIter start, end;
3151
3152   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3153     {
3154       if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
3155         {
3156           /* Provide the address of the buffer; this will only be
3157            * used within-process
3158            */
3159           gtk_selection_data_set (selection_data,
3160                                   gtk_selection_data_get_target (selection_data),
3161                                   8, /* bytes */
3162                                   (void*)&buffer,
3163                                   sizeof (buffer));
3164         }
3165       else if (info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
3166         {
3167           guint8 *str;
3168           gsize   len;
3169
3170           str = gtk_text_buffer_serialize (buffer, buffer,
3171                                            gtk_selection_data_get_target (selection_data),
3172                                            &start, &end, &len);
3173
3174           gtk_selection_data_set (selection_data,
3175                                   gtk_selection_data_get_target (selection_data),
3176                                   8, /* bytes */
3177                                   str, len);
3178           g_free (str);
3179         }
3180       else
3181         {
3182           gchar *str;
3183
3184           str = gtk_text_iter_get_visible_text (&start, &end);
3185           gtk_selection_data_set_text (selection_data, str, -1);
3186           g_free (str);
3187         }
3188     }
3189 }
3190
3191 static GtkTextBuffer *
3192 create_clipboard_contents_buffer (GtkTextBuffer *buffer)
3193 {
3194   GtkTextBuffer *contents;
3195
3196   contents = gtk_text_buffer_new (gtk_text_buffer_get_tag_table (buffer));
3197
3198   g_object_set_data (G_OBJECT (contents), I_("gtk-text-buffer-clipboard-source"),
3199                      buffer);
3200   g_object_set_data (G_OBJECT (contents), I_("gtk-text-buffer-clipboard"),
3201                      GINT_TO_POINTER (1));
3202
3203   /*  Ref the source buffer as long as the clipboard contents buffer
3204    *  exists, because it's needed for serializing the contents buffer.
3205    *  See http://bugzilla.gnome.org/show_bug.cgi?id=339195
3206    */
3207   g_object_ref (buffer);
3208   g_object_weak_ref (G_OBJECT (contents), (GWeakNotify) g_object_unref, buffer);
3209
3210   return contents;
3211 }
3212
3213 /* Provide cut/copied data */
3214 static void
3215 clipboard_get_contents_cb (GtkClipboard     *clipboard,
3216                            GtkSelectionData *selection_data,
3217                            guint             info,
3218                            gpointer          data)
3219 {
3220   GtkTextBuffer *contents = GTK_TEXT_BUFFER (data);
3221
3222   g_assert (contents); /* This should never be called unless we own the clipboard */
3223
3224   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
3225     {
3226       /* Provide the address of the clipboard buffer; this will only
3227        * be used within-process. OK to supply a NULL value for contents.
3228        */
3229       gtk_selection_data_set (selection_data,
3230                               gtk_selection_data_get_target (selection_data),
3231                               8, /* bytes */
3232                               (void*)&contents,
3233                               sizeof (contents));
3234     }
3235   else if (info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
3236     {
3237       GtkTextBuffer *clipboard_source_buffer;
3238       GtkTextIter start, end;
3239       guint8 *str;
3240       gsize   len;
3241
3242       clipboard_source_buffer = g_object_get_data (G_OBJECT (contents),
3243                                                    "gtk-text-buffer-clipboard-source");
3244
3245       gtk_text_buffer_get_bounds (contents, &start, &end);
3246
3247       str = gtk_text_buffer_serialize (clipboard_source_buffer, contents,
3248                                        gtk_selection_data_get_target (selection_data),
3249                                        &start, &end, &len);
3250
3251       gtk_selection_data_set (selection_data,
3252                               gtk_selection_data_get_target (selection_data),
3253                               8, /* bytes */
3254                               str, len);
3255       g_free (str);
3256     }
3257   else
3258     {
3259       gchar *str;
3260       GtkTextIter start, end;
3261
3262       gtk_text_buffer_get_bounds (contents, &start, &end);
3263
3264       str = gtk_text_iter_get_visible_text (&start, &end);
3265       gtk_selection_data_set_text (selection_data, str, -1);
3266       g_free (str);
3267     }
3268 }
3269
3270 static void
3271 clipboard_clear_contents_cb (GtkClipboard *clipboard,
3272                              gpointer      data)
3273 {
3274   GtkTextBuffer *contents = GTK_TEXT_BUFFER (data);
3275
3276   g_object_unref (contents);
3277 }
3278
3279 static void
3280 get_paste_point (GtkTextBuffer *buffer,
3281                  GtkTextIter   *iter,
3282                  gboolean       clear_afterward)
3283 {
3284   GtkTextIter insert_point;
3285   GtkTextMark *paste_point_override;
3286
3287   paste_point_override = gtk_text_buffer_get_mark (buffer,
3288                                                    "gtk_paste_point_override");
3289
3290   if (paste_point_override != NULL)
3291     {
3292       gtk_text_buffer_get_iter_at_mark (buffer, &insert_point,
3293                                         paste_point_override);
3294       if (clear_afterward)
3295         gtk_text_buffer_delete_mark (buffer,
3296                                      gtk_text_buffer_get_mark (buffer,
3297                                                                "gtk_paste_point_override"));
3298     }
3299   else
3300     {
3301       gtk_text_buffer_get_iter_at_mark (buffer, &insert_point,
3302                                         gtk_text_buffer_get_insert (buffer));
3303     }
3304
3305   *iter = insert_point;
3306 }
3307
3308 static void
3309 pre_paste_prep (ClipboardRequest *request_data,
3310                 GtkTextIter      *insert_point)
3311 {
3312   GtkTextBuffer *buffer = request_data->buffer;
3313   
3314   get_paste_point (buffer, insert_point, TRUE);
3315
3316   /* If we're going to replace the selection, we insert before it to
3317    * avoid messing it up, then we delete the selection after inserting.
3318    */
3319   if (request_data->replace_selection)
3320     {
3321       GtkTextIter start, end;
3322       
3323       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3324         *insert_point = start;
3325     }
3326 }
3327
3328 static void
3329 post_paste_cleanup (ClipboardRequest *request_data)
3330 {
3331   if (request_data->replace_selection)
3332     {
3333       GtkTextIter start, end;
3334       
3335       if (gtk_text_buffer_get_selection_bounds (request_data->buffer,
3336                                                 &start, &end))
3337         {
3338           if (request_data->interactive)
3339             gtk_text_buffer_delete_interactive (request_data->buffer,
3340                                                 &start,
3341                                                 &end,
3342                                                 request_data->default_editable);
3343           else
3344             gtk_text_buffer_delete (request_data->buffer, &start, &end);
3345         }
3346     }
3347 }
3348
3349 static void
3350 emit_paste_done (GtkTextBuffer *buffer,
3351                  GtkClipboard  *clipboard)
3352 {
3353   g_signal_emit (buffer, signals[PASTE_DONE], 0, clipboard);
3354 }
3355
3356 static void
3357 free_clipboard_request (ClipboardRequest *request_data)
3358 {
3359   g_object_unref (request_data->buffer);
3360   g_free (request_data);
3361 }
3362
3363 /* Called when we request a paste and receive the text data
3364  */
3365 static void
3366 clipboard_text_received (GtkClipboard *clipboard,
3367                          const gchar  *str,
3368                          gpointer      data)
3369 {
3370   ClipboardRequest *request_data = data;
3371   GtkTextBuffer *buffer = request_data->buffer;
3372
3373   if (str)
3374     {
3375       GtkTextIter insert_point;
3376       
3377       if (request_data->interactive) 
3378         gtk_text_buffer_begin_user_action (buffer);
3379
3380       pre_paste_prep (request_data, &insert_point);
3381       
3382       if (request_data->interactive) 
3383         gtk_text_buffer_insert_interactive (buffer, &insert_point,
3384                                             str, -1, request_data->default_editable);
3385       else
3386         gtk_text_buffer_insert (buffer, &insert_point,
3387                                 str, -1);
3388
3389       post_paste_cleanup (request_data);
3390       
3391       if (request_data->interactive) 
3392         gtk_text_buffer_end_user_action (buffer);
3393
3394       emit_paste_done (buffer, clipboard);
3395     }
3396
3397   free_clipboard_request (request_data);
3398 }
3399
3400 static GtkTextBuffer*
3401 selection_data_get_buffer (GtkSelectionData *selection_data,
3402                            ClipboardRequest *request_data)
3403 {
3404   GdkWindow *owner;
3405   GtkTextBuffer *src_buffer = NULL;
3406
3407   /* If we can get the owner, the selection is in-process */
3408   owner = gdk_selection_owner_get_for_display (gtk_selection_data_get_display (selection_data),
3409                                                gtk_selection_data_get_selection (selection_data));
3410
3411   if (owner == NULL)
3412     return NULL;
3413   
3414   if (gdk_window_get_window_type (owner) == GDK_WINDOW_FOREIGN)
3415     return NULL;
3416
3417   if (gtk_selection_data_get_data_type (selection_data) != gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"))
3418     return NULL;
3419
3420   if (gtk_selection_data_get_length (selection_data) != sizeof (src_buffer))
3421     return NULL;
3422
3423   memcpy (&src_buffer, gtk_selection_data_get_data (selection_data), sizeof (src_buffer));
3424
3425   if (src_buffer == NULL)
3426     return NULL;
3427   
3428   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (src_buffer), NULL);
3429
3430   if (gtk_text_buffer_get_tag_table (src_buffer) !=
3431       gtk_text_buffer_get_tag_table (request_data->buffer))
3432     return NULL;
3433   
3434   return src_buffer;
3435 }
3436
3437 #if 0
3438 /* These are pretty handy functions; maybe something like them
3439  * should be in the public API. Also, there are other places in this
3440  * file where they could be used.
3441  */
3442 static gpointer
3443 save_iter (const GtkTextIter *iter,
3444            gboolean           left_gravity)
3445 {
3446   return gtk_text_buffer_create_mark (gtk_text_iter_get_buffer (iter),
3447                                       NULL,
3448                                       iter,
3449                                       TRUE);
3450 }
3451
3452 static void
3453 restore_iter (const GtkTextIter *iter,
3454               gpointer           save_id)
3455 {
3456   gtk_text_buffer_get_iter_at_mark (gtk_text_mark_get_buffer (save_id),
3457                                     (GtkTextIter*) iter,
3458                                     save_id);
3459   gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (save_id),
3460                                save_id);
3461 }
3462 #endif
3463
3464 static void
3465 clipboard_rich_text_received (GtkClipboard *clipboard,
3466                               GdkAtom       format,
3467                               const guint8 *text,
3468                               gsize         length,
3469                               gpointer      data)
3470 {
3471   ClipboardRequest *request_data = data;
3472   GtkTextIter insert_point;
3473   gboolean retval = TRUE;
3474   GError *error = NULL;
3475
3476   if (text != NULL && length > 0)
3477     {
3478       pre_paste_prep (request_data, &insert_point);
3479
3480       if (request_data->interactive)
3481         gtk_text_buffer_begin_user_action (request_data->buffer);
3482
3483       if (!request_data->interactive ||
3484           gtk_text_iter_can_insert (&insert_point,
3485                                     request_data->default_editable))
3486         {
3487           retval = gtk_text_buffer_deserialize (request_data->buffer,
3488                                                 request_data->buffer,
3489                                                 format,
3490                                                 &insert_point,
3491                                                 text, length,
3492                                                 &error);
3493         }
3494
3495       if (!retval)
3496         {
3497           g_warning ("error pasting: %s\n", error->message);
3498           g_clear_error (&error);
3499         }
3500
3501       if (request_data->interactive)
3502         gtk_text_buffer_end_user_action (request_data->buffer);
3503
3504       emit_paste_done (request_data->buffer, clipboard);
3505
3506       if (retval)
3507         {
3508           post_paste_cleanup (request_data);
3509           return;
3510         }
3511     }
3512
3513   /* Request the text selection instead */
3514   gtk_clipboard_request_text (clipboard,
3515                               clipboard_text_received,
3516                               data);
3517 }
3518
3519 static void
3520 paste_from_buffer (GtkClipboard      *clipboard,
3521                    ClipboardRequest  *request_data,
3522                    GtkTextBuffer     *src_buffer,
3523                    const GtkTextIter *start,
3524                    const GtkTextIter *end)
3525 {
3526   GtkTextIter insert_point;
3527   GtkTextBuffer *buffer = request_data->buffer;
3528   
3529   /* We're about to emit a bunch of signals, so be safe */
3530   g_object_ref (src_buffer);
3531   
3532   pre_paste_prep (request_data, &insert_point);
3533   
3534   if (request_data->interactive) 
3535     gtk_text_buffer_begin_user_action (buffer);
3536
3537   if (!gtk_text_iter_equal (start, end))
3538     {
3539       if (!request_data->interactive ||
3540           (gtk_text_iter_can_insert (&insert_point,
3541                                      request_data->default_editable)))
3542         gtk_text_buffer_real_insert_range (buffer,
3543                                            &insert_point,
3544                                            start,
3545                                            end,
3546                                            request_data->interactive);
3547     }
3548
3549   post_paste_cleanup (request_data);
3550       
3551   if (request_data->interactive) 
3552     gtk_text_buffer_end_user_action (buffer);
3553
3554   emit_paste_done (buffer, clipboard);
3555
3556   g_object_unref (src_buffer);
3557
3558   free_clipboard_request (request_data);
3559 }
3560
3561 static void
3562 clipboard_clipboard_buffer_received (GtkClipboard     *clipboard,
3563                                      GtkSelectionData *selection_data,
3564                                      gpointer          data)
3565 {
3566   ClipboardRequest *request_data = data;
3567   GtkTextBuffer *src_buffer;
3568
3569   src_buffer = selection_data_get_buffer (selection_data, request_data); 
3570
3571   if (src_buffer)
3572     {
3573       GtkTextIter start, end;
3574
3575       if (g_object_get_data (G_OBJECT (src_buffer), "gtk-text-buffer-clipboard"))
3576         {
3577           gtk_text_buffer_get_bounds (src_buffer, &start, &end);
3578
3579           paste_from_buffer (clipboard, request_data, src_buffer,
3580                              &start, &end);
3581         }
3582       else
3583         {
3584           if (gtk_text_buffer_get_selection_bounds (src_buffer, &start, &end))
3585             paste_from_buffer (clipboard, request_data, src_buffer,
3586                                &start, &end);
3587         }
3588     }
3589   else
3590     {
3591       if (gtk_clipboard_wait_is_rich_text_available (clipboard,
3592                                                      request_data->buffer))
3593         {
3594           /* Request rich text */
3595           gtk_clipboard_request_rich_text (clipboard,
3596                                            request_data->buffer,
3597                                            clipboard_rich_text_received,
3598                                            data);
3599         }
3600       else
3601         {
3602           /* Request the text selection instead */
3603           gtk_clipboard_request_text (clipboard,
3604                                       clipboard_text_received,
3605                                       data);
3606         }
3607     }
3608 }
3609
3610 typedef struct
3611 {
3612   GtkClipboard *clipboard;
3613   guint ref_count;
3614 } SelectionClipboard;
3615
3616 static void
3617 update_selection_clipboards (GtkTextBuffer *buffer)
3618 {
3619   GtkTextBufferPrivate *priv;
3620   GSList               *tmp_list = buffer->priv->selection_clipboards;
3621
3622   priv = buffer->priv;
3623
3624   gtk_text_buffer_get_copy_target_list (buffer);
3625
3626   while (tmp_list)
3627     {
3628       GtkTextIter start;
3629       GtkTextIter end;
3630       
3631       SelectionClipboard *selection_clipboard = tmp_list->data;
3632       GtkClipboard *clipboard = selection_clipboard->clipboard;
3633
3634       /* Determine whether we have a selection and adjust X selection
3635        * accordingly.
3636        */
3637       if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3638         {
3639           if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (buffer))
3640             gtk_clipboard_clear (clipboard);
3641         }
3642       else
3643         {
3644           /* Even if we already have the selection, we need to update our
3645            * timestamp.
3646            */
3647           if (!gtk_clipboard_set_with_owner (clipboard,
3648                                              priv->copy_target_entries,
3649                                              priv->n_copy_target_entries,
3650                                              clipboard_get_selection_cb,
3651                                              clipboard_clear_selection_cb,
3652                                              G_OBJECT (buffer)))
3653             clipboard_clear_selection_cb (clipboard, buffer);
3654         }
3655
3656       tmp_list = tmp_list->next;
3657     }
3658 }
3659
3660 static SelectionClipboard *
3661 find_selection_clipboard (GtkTextBuffer *buffer,
3662                           GtkClipboard  *clipboard)
3663 {
3664   GSList *tmp_list = buffer->priv->selection_clipboards;
3665   while (tmp_list)
3666     {
3667       SelectionClipboard *selection_clipboard = tmp_list->data;
3668       if (selection_clipboard->clipboard == clipboard)
3669         return selection_clipboard;
3670       
3671       tmp_list = tmp_list->next;
3672     }
3673
3674   return NULL;
3675 }
3676
3677 /**
3678  * gtk_text_buffer_add_selection_clipboard:
3679  * @buffer: a #GtkTextBuffer
3680  * @clipboard: a #GtkClipboard
3681  * 
3682  * Adds @clipboard to the list of clipboards in which the selection 
3683  * contents of @buffer are available. In most cases, @clipboard will be 
3684  * the #GtkClipboard of type %GDK_SELECTION_PRIMARY for a view of @buffer.
3685  **/
3686 void
3687 gtk_text_buffer_add_selection_clipboard (GtkTextBuffer *buffer,
3688                                          GtkClipboard  *clipboard)
3689 {
3690   SelectionClipboard *selection_clipboard;
3691
3692   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3693   g_return_if_fail (clipboard != NULL);
3694
3695   selection_clipboard = find_selection_clipboard (buffer, clipboard);
3696   if (selection_clipboard)
3697     {
3698       selection_clipboard->ref_count++;
3699     }
3700   else
3701     {
3702       selection_clipboard = g_new (SelectionClipboard, 1);
3703
3704       selection_clipboard->clipboard = clipboard;
3705       selection_clipboard->ref_count = 1;
3706
3707       buffer->priv->selection_clipboards = g_slist_prepend (buffer->priv->selection_clipboards,
3708                                                             selection_clipboard);
3709     }
3710 }
3711
3712 /**
3713  * gtk_text_buffer_remove_selection_clipboard:
3714  * @buffer: a #GtkTextBuffer
3715  * @clipboard: a #GtkClipboard added to @buffer by 
3716  *             gtk_text_buffer_add_selection_clipboard()
3717  * 
3718  * Removes a #GtkClipboard added with 
3719  * gtk_text_buffer_add_selection_clipboard().
3720  **/
3721 void 
3722 gtk_text_buffer_remove_selection_clipboard (GtkTextBuffer *buffer,
3723                                             GtkClipboard  *clipboard)
3724 {
3725   SelectionClipboard *selection_clipboard;
3726
3727   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3728   g_return_if_fail (clipboard != NULL);
3729
3730   selection_clipboard = find_selection_clipboard (buffer, clipboard);
3731   g_return_if_fail (selection_clipboard != NULL);
3732
3733   selection_clipboard->ref_count--;
3734   if (selection_clipboard->ref_count == 0)
3735     {
3736       if (gtk_clipboard_get_owner (selection_clipboard->clipboard) == G_OBJECT (buffer))
3737         gtk_clipboard_clear (selection_clipboard->clipboard);
3738
3739       buffer->priv->selection_clipboards = g_slist_remove (buffer->priv->selection_clipboards,
3740                                                            selection_clipboard);
3741       
3742       g_free (selection_clipboard);
3743     }
3744 }
3745
3746 static void
3747 remove_all_selection_clipboards (GtkTextBuffer *buffer)
3748 {
3749   GtkTextBufferPrivate *priv = buffer->priv;
3750
3751   g_slist_foreach (priv->selection_clipboards, (GFunc)g_free, NULL);
3752   g_slist_free (priv->selection_clipboards);
3753   priv->selection_clipboards = NULL;
3754 }
3755
3756 /**
3757  * gtk_text_buffer_paste_clipboard:
3758  * @buffer: a #GtkTextBuffer
3759  * @clipboard: the #GtkClipboard to paste from
3760  * @override_location: (allow-none): location to insert pasted text, or %NULL for
3761  *                     at the cursor
3762  * @default_editable: whether the buffer is editable by default
3763  *
3764  * Pastes the contents of a clipboard at the insertion point, or
3765  * at @override_location. (Note: pasting is asynchronous, that is,
3766  * we'll ask for the paste data and return, and at some point later
3767  * after the main loop runs, the paste data will be inserted.)
3768  **/
3769 void
3770 gtk_text_buffer_paste_clipboard (GtkTextBuffer *buffer,
3771                                  GtkClipboard  *clipboard,
3772                                  GtkTextIter   *override_location,
3773                                  gboolean       default_editable)
3774 {
3775   ClipboardRequest *data = g_new (ClipboardRequest, 1);
3776   GtkTextIter paste_point;
3777   GtkTextIter start, end;
3778
3779   if (override_location != NULL)
3780     gtk_text_buffer_create_mark (buffer,
3781                                  "gtk_paste_point_override",
3782                                  override_location, FALSE);
3783
3784   data->buffer = g_object_ref (buffer);
3785   data->interactive = TRUE;
3786   data->default_editable = !!default_editable;
3787
3788   /* When pasting with the cursor inside the selection area, you
3789    * replace the selection with the new text, otherwise, you
3790    * simply insert the new text at the point where the click
3791    * occured, unselecting any selected text. The replace_selection
3792    * flag toggles this behavior.
3793    */
3794   data->replace_selection = FALSE;
3795   
3796   get_paste_point (buffer, &paste_point, FALSE);
3797   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end) &&
3798       (gtk_text_iter_in_range (&paste_point, &start, &end) ||
3799        gtk_text_iter_equal (&paste_point, &end)))
3800     data->replace_selection = TRUE;
3801
3802   gtk_clipboard_request_contents (clipboard,
3803                                   gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"),
3804                                   clipboard_clipboard_buffer_received, data);
3805 }
3806
3807 /**
3808  * gtk_text_buffer_delete_selection:
3809  * @buffer: a #GtkTextBuffer 
3810  * @interactive: whether the deletion is caused by user interaction
3811  * @default_editable: whether the buffer is editable by default
3812  *
3813  * Deletes the range between the "insert" and "selection_bound" marks,
3814  * that is, the currently-selected text. If @interactive is %TRUE,
3815  * the editability of the selection will be considered (users can't delete
3816  * uneditable text).
3817  * 
3818  * Return value: whether there was a non-empty selection to delete
3819  **/
3820 gboolean
3821 gtk_text_buffer_delete_selection (GtkTextBuffer *buffer,
3822                                   gboolean interactive,
3823                                   gboolean default_editable)
3824 {
3825   GtkTextIter start;
3826   GtkTextIter end;
3827
3828   if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3829     {
3830       return FALSE; /* No selection */
3831     }
3832   else
3833     {
3834       if (interactive)
3835         gtk_text_buffer_delete_interactive (buffer, &start, &end, default_editable);
3836       else
3837         gtk_text_buffer_delete (buffer, &start, &end);
3838
3839       return TRUE; /* We deleted stuff */
3840     }
3841 }
3842
3843 /**
3844  * gtk_text_buffer_backspace:
3845  * @buffer: a #GtkTextBuffer
3846  * @iter: a position in @buffer
3847  * @interactive: whether the deletion is caused by user interaction
3848  * @default_editable: whether the buffer is editable by default
3849  * 
3850  * Performs the appropriate action as if the user hit the delete
3851  * key with the cursor at the position specified by @iter. In the
3852  * normal case a single character will be deleted, but when
3853  * combining accents are involved, more than one character can
3854  * be deleted, and when precomposed character and accent combinations
3855  * are involved, less than one character will be deleted.
3856  * 
3857  * Because the buffer is modified, all outstanding iterators become 
3858  * invalid after calling this function; however, the @iter will be
3859  * re-initialized to point to the location where text was deleted. 
3860  *
3861  * Return value: %TRUE if the buffer was modified
3862  *
3863  * Since: 2.6
3864  **/
3865 gboolean
3866 gtk_text_buffer_backspace (GtkTextBuffer *buffer,
3867                            GtkTextIter   *iter,
3868                            gboolean       interactive,
3869                            gboolean       default_editable)
3870 {
3871   gchar *cluster_text;
3872   GtkTextIter start;
3873   GtkTextIter end;
3874   gboolean retval = FALSE;
3875   const PangoLogAttr *attrs;
3876   int offset;
3877   gboolean backspace_deletes_character;
3878
3879   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
3880   g_return_val_if_fail (iter != NULL, FALSE);
3881
3882   start = *iter;
3883   end = *iter;
3884
3885   attrs = _gtk_text_buffer_get_line_log_attrs (buffer, &start, NULL);
3886
3887   /* For no good reason, attrs is NULL for the empty last line in
3888    * a buffer. Special case that here. (#156164)
3889    */
3890   if (attrs)
3891     {
3892       offset = gtk_text_iter_get_line_offset (&start);
3893       backspace_deletes_character = attrs[offset].backspace_deletes_character;
3894     }
3895   else
3896     backspace_deletes_character = FALSE;
3897
3898   gtk_text_iter_backward_cursor_position (&start);
3899
3900   if (gtk_text_iter_equal (&start, &end))
3901     return FALSE;
3902     
3903   cluster_text = gtk_text_iter_get_text (&start, &end);
3904
3905   if (interactive)
3906     gtk_text_buffer_begin_user_action (buffer);
3907   
3908   if (gtk_text_buffer_delete_interactive (buffer, &start, &end,
3909                                           default_editable))
3910     {
3911       /* special case \r\n, since we never want to reinsert \r */
3912       if (backspace_deletes_character && strcmp ("\r\n", cluster_text))
3913         {
3914           gchar *normalized_text = g_utf8_normalize (cluster_text,
3915                                                      strlen (cluster_text),
3916                                                      G_NORMALIZE_NFD);
3917           glong len = g_utf8_strlen (normalized_text, -1);
3918
3919           if (len > 1)
3920             gtk_text_buffer_insert_interactive (buffer,
3921                                                 &start,
3922                                                 normalized_text,
3923                                                 g_utf8_offset_to_pointer (normalized_text, len - 1) - normalized_text,
3924                                                 default_editable);
3925           
3926           g_free (normalized_text);
3927         }
3928
3929       retval = TRUE;
3930     }
3931   
3932   if (interactive)
3933     gtk_text_buffer_end_user_action (buffer);
3934   
3935   g_free (cluster_text);
3936
3937   /* Revalidate the users iter */
3938   *iter = start;
3939
3940   return retval;
3941 }
3942
3943 static void
3944 cut_or_copy (GtkTextBuffer *buffer,
3945              GtkClipboard  *clipboard,
3946              gboolean       delete_region_after,
3947              gboolean       interactive,
3948              gboolean       default_editable)
3949 {
3950   GtkTextBufferPrivate *priv;
3951
3952   /* We prefer to cut the selected region between selection_bound and
3953    * insertion point. If that region is empty, then we cut the region
3954    * between the "anchor" and the insertion point (this is for
3955    * C-space and M-w and other Emacs-style copy/yank keys). Note that
3956    * insert and selection_bound are guaranteed to exist, but the
3957    * anchor only exists sometimes.
3958    */
3959   GtkTextIter start;
3960   GtkTextIter end;
3961
3962   priv = buffer->priv;
3963
3964   gtk_text_buffer_get_copy_target_list (buffer);
3965
3966   if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3967     {
3968       /* Let's try the anchor thing */
3969       GtkTextMark * anchor = gtk_text_buffer_get_mark (buffer, "anchor");
3970
3971       if (anchor == NULL)
3972         return;
3973       else
3974         {
3975           gtk_text_buffer_get_iter_at_mark (buffer, &end, anchor);
3976           gtk_text_iter_order (&start, &end);
3977         }
3978     }
3979
3980   if (!gtk_text_iter_equal (&start, &end))
3981     {
3982       GtkTextIter ins;
3983       GtkTextBuffer *contents;
3984
3985       contents = create_clipboard_contents_buffer (buffer);
3986
3987       gtk_text_buffer_get_iter_at_offset (contents, &ins, 0);
3988       
3989       gtk_text_buffer_insert_range (contents, &ins, &start, &end);
3990                                     
3991       if (!gtk_clipboard_set_with_data (clipboard,
3992                                         priv->copy_target_entries,
3993                                         priv->n_copy_target_entries,
3994                                         clipboard_get_contents_cb,
3995                                         clipboard_clear_contents_cb,
3996                                         contents))
3997         g_object_unref (contents);
3998       else
3999         gtk_clipboard_set_can_store (clipboard,
4000                                      priv->copy_target_entries + 1,
4001                                      priv->n_copy_target_entries - 1);
4002
4003       if (delete_region_after)
4004         {
4005           if (interactive)
4006             gtk_text_buffer_delete_interactive (buffer, &start, &end,
4007                                                 default_editable);
4008           else
4009             gtk_text_buffer_delete (buffer, &start, &end);
4010         }
4011     }
4012 }
4013
4014 /**
4015  * gtk_text_buffer_cut_clipboard:
4016  * @buffer: a #GtkTextBuffer
4017  * @clipboard: the #GtkClipboard object to cut to
4018  * @default_editable: default editability of the buffer
4019  *
4020  * Copies the currently-selected text to a clipboard, then deletes
4021  * said text if it's editable.
4022  **/
4023 void
4024 gtk_text_buffer_cut_clipboard (GtkTextBuffer *buffer,
4025                                GtkClipboard  *clipboard,
4026                                gboolean       default_editable)
4027 {
4028   gtk_text_buffer_begin_user_action (buffer);
4029   cut_or_copy (buffer, clipboard, TRUE, TRUE, default_editable);
4030   gtk_text_buffer_end_user_action (buffer);
4031 }
4032
4033 /**
4034  * gtk_text_buffer_copy_clipboard:
4035  * @buffer: a #GtkTextBuffer 
4036  * @clipboard: the #GtkClipboard object to copy to
4037  *
4038  * Copies the currently-selected text to a clipboard.
4039  **/
4040 void
4041 gtk_text_buffer_copy_clipboard (GtkTextBuffer *buffer,
4042                                 GtkClipboard  *clipboard)
4043 {
4044   cut_or_copy (buffer, clipboard, FALSE, TRUE, TRUE);
4045 }
4046
4047 /**
4048  * gtk_text_buffer_get_selection_bounds:
4049  * @buffer: a #GtkTextBuffer a #GtkTextBuffer
4050  * @start: (out): iterator to initialize with selection start
4051  * @end: (out): iterator to initialize with selection end
4052  *
4053  * Returns %TRUE if some text is selected; places the bounds
4054  * of the selection in @start and @end (if the selection has length 0,
4055  * then @start and @end are filled in with the same value).
4056  * @start and @end will be in ascending order. If @start and @end are
4057  * NULL, then they are not filled in, but the return value still indicates
4058  * whether text is selected.
4059  *
4060  * Return value: whether the selection has nonzero length
4061  **/
4062 gboolean
4063 gtk_text_buffer_get_selection_bounds (GtkTextBuffer *buffer,
4064                                       GtkTextIter   *start,
4065                                       GtkTextIter   *end)
4066 {
4067   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
4068
4069   return _gtk_text_btree_get_selection_bounds (get_btree (buffer), start, end);
4070 }
4071
4072 /**
4073  * gtk_text_buffer_begin_user_action:
4074  * @buffer: a #GtkTextBuffer
4075  * 
4076  * Called to indicate that the buffer operations between here and a
4077  * call to gtk_text_buffer_end_user_action() are part of a single
4078  * user-visible operation. The operations between
4079  * gtk_text_buffer_begin_user_action() and
4080  * gtk_text_buffer_end_user_action() can then be grouped when creating
4081  * an undo stack. #GtkTextBuffer maintains a count of calls to
4082  * gtk_text_buffer_begin_user_action() that have not been closed with
4083  * a call to gtk_text_buffer_end_user_action(), and emits the 
4084  * "begin-user-action" and "end-user-action" signals only for the 
4085  * outermost pair of calls. This allows you to build user actions 
4086  * from other user actions.
4087  *
4088  * The "interactive" buffer mutation functions, such as
4089  * gtk_text_buffer_insert_interactive(), automatically call begin/end
4090  * user action around the buffer operations they perform, so there's
4091  * no need to add extra calls if you user action consists solely of a
4092  * single call to one of those functions.
4093  **/
4094 void
4095 gtk_text_buffer_begin_user_action (GtkTextBuffer *buffer)
4096 {
4097   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
4098
4099   buffer->priv->user_action_count += 1;
4100   
4101   if (buffer->priv->user_action_count == 1)
4102     {
4103       /* Outermost nested user action begin emits the signal */
4104       g_signal_emit (buffer, signals[BEGIN_USER_ACTION], 0);
4105     }
4106 }
4107
4108 /**
4109  * gtk_text_buffer_end_user_action:
4110  * @buffer: a #GtkTextBuffer
4111  * 
4112  * Should be paired with a call to gtk_text_buffer_begin_user_action().
4113  * See that function for a full explanation.
4114  **/
4115 void
4116 gtk_text_buffer_end_user_action (GtkTextBuffer *buffer)
4117 {
4118   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
4119   g_return_if_fail (buffer->priv->user_action_count > 0);
4120   
4121   buffer->priv->user_action_count -= 1;
4122   
4123   if (buffer->priv->user_action_count == 0)
4124     {
4125       /* Ended the outermost-nested user action end, so emit the signal */
4126       g_signal_emit (buffer, signals[END_USER_ACTION], 0);
4127     }
4128 }
4129
4130 static void
4131 gtk_text_buffer_free_target_lists (GtkTextBuffer *buffer)
4132 {
4133   GtkTextBufferPrivate *priv = buffer->priv;
4134
4135   if (priv->copy_target_list)
4136     {
4137       gtk_target_list_unref (priv->copy_target_list);
4138       priv->copy_target_list = NULL;
4139
4140       gtk_target_table_free (priv->copy_target_entries,
4141                              priv->n_copy_target_entries);
4142       priv->copy_target_entries = NULL;
4143       priv->n_copy_target_entries = 0;
4144     }
4145
4146   if (priv->paste_target_list)
4147     {
4148       gtk_target_list_unref (priv->paste_target_list);
4149       priv->paste_target_list = NULL;
4150
4151       gtk_target_table_free (priv->paste_target_entries,
4152                              priv->n_paste_target_entries);
4153       priv->paste_target_entries = NULL;
4154       priv->n_paste_target_entries = 0;
4155     }
4156 }
4157
4158 static GtkTargetList *
4159 gtk_text_buffer_get_target_list (GtkTextBuffer   *buffer,
4160                                  gboolean         deserializable,
4161                                  GtkTargetEntry **entries,
4162                                  gint            *n_entries)
4163 {
4164   GtkTargetList *target_list;
4165
4166   target_list = gtk_target_list_new (NULL, 0);
4167
4168   gtk_target_list_add (target_list,
4169                        gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"),
4170                        GTK_TARGET_SAME_APP,
4171                        GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS);
4172
4173   gtk_target_list_add_rich_text_targets (target_list,
4174                                          GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT,
4175                                          deserializable,
4176                                          buffer);
4177
4178   gtk_target_list_add_text_targets (target_list,
4179                                     GTK_TEXT_BUFFER_TARGET_INFO_TEXT);
4180
4181   *entries = gtk_target_table_new_from_list (target_list, n_entries);
4182
4183   return target_list;
4184 }
4185
4186 /**
4187  * gtk_text_buffer_get_copy_target_list:
4188  * @buffer: a #GtkTextBuffer
4189  *
4190  * This function returns the list of targets this text buffer can
4191  * provide for copying and as DND source. The targets in the list are
4192  * added with %info values from the #GtkTextBufferTargetInfo enum,
4193  * using gtk_target_list_add_rich_text_targets() and
4194  * gtk_target_list_add_text_targets().
4195  *
4196  * Return value: the #GtkTargetList
4197  *
4198  * Since: 2.10
4199  **/
4200 GtkTargetList *
4201 gtk_text_buffer_get_copy_target_list (GtkTextBuffer *buffer)
4202 {
4203   GtkTextBufferPrivate *priv;
4204
4205   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
4206
4207   priv = buffer->priv;
4208
4209   if (! priv->copy_target_list)
4210     priv->copy_target_list =
4211       gtk_text_buffer_get_target_list (buffer, FALSE,
4212                                        &priv->copy_target_entries,
4213                                        &priv->n_copy_target_entries);
4214
4215   return priv->copy_target_list;
4216 }
4217
4218 /**
4219  * gtk_text_buffer_get_paste_target_list:
4220  * @buffer: a #GtkTextBuffer
4221  *
4222  * This function returns the list of targets this text buffer supports
4223  * for pasting and as DND destination. The targets in the list are
4224  * added with %info values from the #GtkTextBufferTargetInfo enum,
4225  * using gtk_target_list_add_rich_text_targets() and
4226  * gtk_target_list_add_text_targets().
4227  *
4228  * Return value: the #GtkTargetList
4229  *
4230  * Since: 2.10
4231  **/
4232 GtkTargetList *
4233 gtk_text_buffer_get_paste_target_list (GtkTextBuffer *buffer)
4234 {
4235   GtkTextBufferPrivate *priv;
4236
4237   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
4238
4239   priv = buffer->priv;
4240
4241   if (! priv->paste_target_list)
4242     priv->paste_target_list =
4243       gtk_text_buffer_get_target_list (buffer, TRUE,
4244                                        &priv->paste_target_entries,
4245                                        &priv->n_paste_target_entries);
4246
4247   return priv->paste_target_list;
4248 }
4249
4250 /*
4251  * Logical attribute cache
4252  */
4253
4254 #define ATTR_CACHE_SIZE 2
4255
4256 typedef struct _CacheEntry CacheEntry;
4257 struct _CacheEntry
4258 {
4259   gint line;
4260   gint char_len;
4261   PangoLogAttr *attrs;
4262 };
4263
4264 struct _GtkTextLogAttrCache
4265 {
4266   gint chars_changed_stamp;
4267   CacheEntry entries[ATTR_CACHE_SIZE];
4268 };
4269
4270 static void
4271 free_log_attr_cache (GtkTextLogAttrCache *cache)
4272 {
4273   gint i = 0;
4274   while (i < ATTR_CACHE_SIZE)
4275     {
4276       g_free (cache->entries[i].attrs);
4277       ++i;
4278     }
4279   g_free (cache);
4280 }
4281
4282 static void
4283 clear_log_attr_cache (GtkTextLogAttrCache *cache)
4284 {
4285   gint i = 0;
4286   while (i < ATTR_CACHE_SIZE)
4287     {
4288       g_free (cache->entries[i].attrs);
4289       cache->entries[i].attrs = NULL;
4290       ++i;
4291     }
4292 }
4293
4294 static PangoLogAttr*
4295 compute_log_attrs (const GtkTextIter *iter,
4296                    gint              *char_lenp)
4297 {
4298   GtkTextIter start;
4299   GtkTextIter end;
4300   gchar *paragraph;
4301   gint char_len, byte_len;
4302   PangoLogAttr *attrs = NULL;
4303   
4304   start = *iter;
4305   end = *iter;
4306
4307   gtk_text_iter_set_line_offset (&start, 0);
4308   gtk_text_iter_forward_line (&end);
4309
4310   paragraph = gtk_text_iter_get_slice (&start, &end);
4311   char_len = g_utf8_strlen (paragraph, -1);
4312   byte_len = strlen (paragraph);
4313
4314   g_assert (char_len > 0);
4315
4316   if (char_lenp)
4317     *char_lenp = char_len;
4318   
4319   attrs = g_new (PangoLogAttr, char_len + 1);
4320
4321   /* FIXME we need to follow PangoLayout and allow different language
4322    * tags within the paragraph
4323    */
4324   pango_get_log_attrs (paragraph, byte_len, -1,
4325                        gtk_text_iter_get_language (&start),
4326                        attrs,
4327                        char_len + 1);
4328   
4329   g_free (paragraph);
4330
4331   return attrs;
4332 }
4333
4334 /* The return value from this is valid until you call this a second time.
4335  */
4336 const PangoLogAttr*
4337 _gtk_text_buffer_get_line_log_attrs (GtkTextBuffer     *buffer,
4338                                      const GtkTextIter *anywhere_in_line,
4339                                      gint              *char_len)
4340 {
4341   GtkTextBufferPrivate *priv;
4342   gint line;
4343   GtkTextLogAttrCache *cache;
4344   gint i;
4345   
4346   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
4347   g_return_val_if_fail (anywhere_in_line != NULL, NULL);
4348
4349   priv = buffer->priv;
4350
4351   /* special-case for empty last line in buffer */
4352   if (gtk_text_iter_is_end (anywhere_in_line) &&
4353       gtk_text_iter_get_line_offset (anywhere_in_line) == 0)
4354     {
4355       if (char_len)
4356         *char_len = 0;
4357       return NULL;
4358     }
4359   
4360   /* FIXME we also need to recompute log attrs if the language tag at
4361    * the start of a paragraph changes
4362    */
4363   
4364   if (priv->log_attr_cache == NULL)
4365     {
4366       priv->log_attr_cache = g_new0 (GtkTextLogAttrCache, 1);
4367       priv->log_attr_cache->chars_changed_stamp =
4368         _gtk_text_btree_get_chars_changed_stamp (get_btree (buffer));
4369     }
4370   else if (priv->log_attr_cache->chars_changed_stamp !=
4371            _gtk_text_btree_get_chars_changed_stamp (get_btree (buffer)))
4372     {
4373       clear_log_attr_cache (priv->log_attr_cache);
4374     }
4375   
4376   cache = priv->log_attr_cache;
4377   line = gtk_text_iter_get_line (anywhere_in_line);
4378
4379   i = 0;
4380   while (i < ATTR_CACHE_SIZE)
4381     {
4382       if (cache->entries[i].attrs &&
4383           cache->entries[i].line == line)
4384         {
4385           if (char_len)
4386             *char_len = cache->entries[i].char_len;
4387           return cache->entries[i].attrs;
4388         }
4389       ++i;
4390     }
4391   
4392   /* Not in cache; open up the first cache entry */
4393   g_free (cache->entries[ATTR_CACHE_SIZE-1].attrs);
4394   
4395   g_memmove (cache->entries + 1, cache->entries,
4396              sizeof (CacheEntry) * (ATTR_CACHE_SIZE - 1));
4397
4398   cache->entries[0].line = line;
4399   cache->entries[0].attrs = compute_log_attrs (anywhere_in_line,
4400                                                &cache->entries[0].char_len);
4401
4402   if (char_len)
4403     *char_len = cache->entries[0].char_len;
4404   
4405   return cache->entries[0].attrs;
4406 }
4407
4408 void
4409 _gtk_text_buffer_notify_will_remove_tag (GtkTextBuffer *buffer,
4410                                          GtkTextTag    *tag)
4411 {
4412   /* This removes tag from the buffer, but DOESN'T emit the
4413    * remove-tag signal, because we can't afford to have user
4414    * code messing things up at this point; the tag MUST be removed
4415    * entirely.
4416    */
4417   if (buffer->priv->btree)
4418     _gtk_text_btree_notify_will_remove_tag (buffer->priv->btree, tag);
4419 }
4420
4421 /*
4422  * Debug spew
4423  */
4424
4425 void
4426 _gtk_text_buffer_spew (GtkTextBuffer *buffer)
4427 {
4428   _gtk_text_btree_spew (get_btree (buffer));
4429 }