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