]> Pileus Git - ~andy/gtk/blob - gtk/gtktextbuffer.c
Add infrastructure for copy/paste and DND of rich text for GtkTextBuffer.
[~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_set_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;
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           if (prev)
2573             prev->next = tmp_list->next;
2574
2575           tmp_list->next = NULL;
2576
2577           g_slist_free (tmp_list);
2578
2579           tmp_list = prev->next;
2580           /* prev is unchanged */
2581         }
2582       else
2583         {
2584           /* not a duplicate */
2585           tag = GTK_TEXT_TAG (tmp_list->data);
2586           prev = tmp_list;
2587           tmp_list = tmp_list->next;
2588         }
2589     }
2590
2591   g_slist_foreach (tags, (GFunc) g_object_ref, NULL);
2592   
2593   tmp_list = tags;
2594   while (tmp_list != NULL)
2595     {
2596       tag = GTK_TEXT_TAG (tmp_list->data);
2597
2598       gtk_text_buffer_remove_tag (buffer, tag, &first, &second);
2599       
2600       tmp_list = tmp_list->next;
2601     }
2602
2603   g_slist_foreach (tags, (GFunc) g_object_unref, NULL);
2604   
2605   g_slist_free (tags);
2606 }
2607
2608
2609 /*
2610  * Obtain various iterators
2611  */
2612
2613 /**
2614  * gtk_text_buffer_get_iter_at_line_offset:
2615  * @buffer: a #GtkTextBuffer
2616  * @iter: iterator to initialize
2617  * @line_number: line number counting from 0
2618  * @char_offset: char offset from start of line
2619  *
2620  * Obtains an iterator pointing to @char_offset within the given
2621  * line. The @char_offset must exist, offsets off the end of the line
2622  * are not allowed. Note <emphasis>characters</emphasis>, not bytes;
2623  * UTF-8 may encode one character as multiple bytes.
2624  * 
2625  **/
2626 void
2627 gtk_text_buffer_get_iter_at_line_offset (GtkTextBuffer      *buffer,
2628                                          GtkTextIter        *iter,
2629                                          gint                line_number,
2630                                          gint                char_offset)
2631 {
2632   g_return_if_fail (iter != NULL);
2633   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2634
2635   _gtk_text_btree_get_iter_at_line_char (get_btree (buffer),
2636                                          iter, line_number, char_offset);
2637 }
2638
2639 /**
2640  * gtk_text_buffer_get_iter_at_line_index:
2641  * @buffer: a #GtkTextBuffer 
2642  * @iter: iterator to initialize 
2643  * @line_number: line number counting from 0
2644  * @byte_index: byte index from start of line
2645  *
2646  * Obtains an iterator pointing to @byte_index within the given line.
2647  * @byte_index must be the start of a UTF-8 character, and must not be
2648  * beyond the end of the line.  Note <emphasis>bytes</emphasis>, not
2649  * characters; UTF-8 may encode one character as multiple bytes.
2650  * 
2651  **/
2652 void
2653 gtk_text_buffer_get_iter_at_line_index  (GtkTextBuffer *buffer,
2654                                          GtkTextIter   *iter,
2655                                          gint           line_number,
2656                                          gint           byte_index)
2657 {
2658   g_return_if_fail (iter != NULL);
2659   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2660
2661   _gtk_text_btree_get_iter_at_line_byte (get_btree (buffer),
2662                                          iter, line_number, byte_index);
2663 }
2664
2665 /**
2666  * gtk_text_buffer_get_iter_at_line:
2667  * @buffer: a #GtkTextBuffer 
2668  * @iter: iterator to initialize
2669  * @line_number: line number counting from 0
2670  * 
2671  * Initializes @iter to the start of the given line.
2672  **/
2673 void
2674 gtk_text_buffer_get_iter_at_line    (GtkTextBuffer      *buffer,
2675                                      GtkTextIter        *iter,
2676                                      gint                line_number)
2677 {
2678   g_return_if_fail (iter != NULL);
2679   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2680
2681   gtk_text_buffer_get_iter_at_line_offset (buffer, iter, line_number, 0);
2682 }
2683
2684 /**
2685  * gtk_text_buffer_get_iter_at_offset:
2686  * @buffer: a #GtkTextBuffer 
2687  * @iter: iterator to initialize
2688  * @char_offset: char offset from start of buffer, counting from 0, or -1
2689  *
2690  * Initializes @iter to a position @char_offset chars from the start
2691  * of the entire buffer. If @char_offset is -1 or greater than the number
2692  * of characters in the buffer, @iter is initialized to the end iterator,
2693  * the iterator one past the last valid character in the buffer.
2694  **/
2695 void
2696 gtk_text_buffer_get_iter_at_offset         (GtkTextBuffer      *buffer,
2697                                             GtkTextIter        *iter,
2698                                             gint                char_offset)
2699 {
2700   g_return_if_fail (iter != NULL);
2701   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2702
2703   _gtk_text_btree_get_iter_at_char (get_btree (buffer), iter, char_offset);
2704 }
2705
2706 /**
2707  * gtk_text_buffer_get_start_iter:
2708  * @buffer: a #GtkTextBuffer
2709  * @iter: iterator to initialize
2710  *
2711  * Initialized @iter with the first position in the text buffer. This
2712  * is the same as using gtk_text_buffer_get_iter_at_offset() to get
2713  * the iter at character offset 0.
2714  **/
2715 void
2716 gtk_text_buffer_get_start_iter (GtkTextBuffer *buffer,
2717                                 GtkTextIter   *iter)
2718 {
2719   g_return_if_fail (iter != NULL);
2720   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2721
2722   _gtk_text_btree_get_iter_at_char (get_btree (buffer), iter, 0);
2723 }
2724
2725 /**
2726  * gtk_text_buffer_get_end_iter:
2727  * @buffer: a #GtkTextBuffer 
2728  * @iter: iterator to initialize
2729  *
2730  * Initializes @iter with the "end iterator," one past the last valid
2731  * character in the text buffer. If dereferenced with
2732  * gtk_text_iter_get_char(), the end iterator has a character value of
2733  * 0. The entire buffer lies in the range from the first position in
2734  * the buffer (call gtk_text_buffer_get_start_iter() to get
2735  * character position 0) to the end iterator.
2736  * 
2737  **/
2738 void
2739 gtk_text_buffer_get_end_iter         (GtkTextBuffer      *buffer,
2740                                        GtkTextIter        *iter)
2741 {
2742   g_return_if_fail (iter != NULL);
2743   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2744
2745   _gtk_text_btree_get_end_iter (get_btree (buffer), iter);
2746 }
2747
2748 /**
2749  * gtk_text_buffer_get_bounds:
2750  * @buffer: a #GtkTextBuffer 
2751  * @start: iterator to initialize with first position in the buffer
2752  * @end: iterator to initialize with the end iterator
2753  *
2754  * Retrieves the first and last iterators in the buffer, i.e. the
2755  * entire buffer lies within the range [@start,@end).
2756  * 
2757  **/
2758 void
2759 gtk_text_buffer_get_bounds (GtkTextBuffer *buffer,
2760                             GtkTextIter   *start,
2761                             GtkTextIter   *end)
2762 {
2763   g_return_if_fail (start != NULL);
2764   g_return_if_fail (end != NULL);
2765   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2766
2767   _gtk_text_btree_get_iter_at_char (get_btree (buffer), start, 0);
2768   _gtk_text_btree_get_end_iter (get_btree (buffer), end);
2769 }
2770
2771 /*
2772  * Modified flag
2773  */
2774
2775 /**
2776  * gtk_text_buffer_get_modified:
2777  * @buffer: a #GtkTextBuffer 
2778  * 
2779  * Indicates whether the buffer has been modified since the last call
2780  * to gtk_text_buffer_set_modified() set the modification flag to
2781  * %FALSE. Used for example to enable a "save" function in a text
2782  * editor.
2783  * 
2784  * Return value: %TRUE if the buffer has been modified
2785  **/
2786 gboolean
2787 gtk_text_buffer_get_modified (GtkTextBuffer *buffer)
2788 {
2789   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
2790
2791   return buffer->modified;
2792 }
2793
2794 /**
2795  * gtk_text_buffer_set_modified:
2796  * @buffer: a #GtkTextBuffer 
2797  * @setting: modification flag setting
2798  *
2799  * Used to keep track of whether the buffer has been modified since the
2800  * last time it was saved. Whenever the buffer is saved to disk, call
2801  * gtk_text_buffer_set_modified (@buffer, FALSE). When the buffer is modified,
2802  * it will automatically toggled on the modified bit again. When the modified
2803  * bit flips, the buffer emits a "modified_changed" signal.
2804  * 
2805  **/
2806 void
2807 gtk_text_buffer_set_modified (GtkTextBuffer      *buffer,
2808                               gboolean             setting)
2809 {
2810   gboolean fixed_setting;
2811
2812   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
2813
2814   fixed_setting = setting != FALSE;
2815
2816   if (buffer->modified == fixed_setting)
2817     return;
2818   else
2819     {
2820       buffer->modified = fixed_setting;
2821       g_signal_emit (buffer, signals[MODIFIED_CHANGED], 0);
2822     }
2823 }
2824
2825 /**
2826  * gtk_text_buffer_get_has_selection:
2827  * @buffer: a #GtkTextBuffer 
2828  * 
2829  * Indicates whether the buffer has some text currently selected.
2830  * 
2831  * Return value: %TRUE if the there is text selected
2832  *
2833  * Since: 2.10
2834  **/
2835 gboolean
2836 gtk_text_buffer_get_has_selection (GtkTextBuffer *buffer)
2837 {
2838   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
2839
2840   return buffer->has_selection;
2841 }
2842
2843
2844 /*
2845  * Assorted other stuff
2846  */
2847
2848 /**
2849  * gtk_text_buffer_get_line_count:
2850  * @buffer: a #GtkTextBuffer 
2851  * 
2852  * Obtains the number of lines in the buffer. This value is cached, so
2853  * the function is very fast.
2854  * 
2855  * Return value: number of lines in the buffer
2856  **/
2857 gint
2858 gtk_text_buffer_get_line_count (GtkTextBuffer *buffer)
2859 {
2860   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), 0);
2861
2862   return _gtk_text_btree_line_count (get_btree (buffer));
2863 }
2864
2865 /**
2866  * gtk_text_buffer_get_char_count:
2867  * @buffer: a #GtkTextBuffer 
2868  * 
2869  * Gets the number of characters in the buffer; note that characters
2870  * and bytes are not the same, you can't e.g. expect the contents of
2871  * the buffer in string form to be this many bytes long. The character
2872  * count is cached, so this function is very fast.
2873  * 
2874  * Return value: number of characters in the buffer
2875  **/
2876 gint
2877 gtk_text_buffer_get_char_count (GtkTextBuffer *buffer)
2878 {
2879   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), 0);
2880
2881   return _gtk_text_btree_char_count (get_btree (buffer));
2882 }
2883
2884 /* Called when we lose the primary selection.
2885  */
2886 static void
2887 clipboard_clear_selection_cb (GtkClipboard *clipboard,
2888                               gpointer      data)
2889 {
2890   /* Move selection_bound to the insertion point */
2891   GtkTextIter insert;
2892   GtkTextIter selection_bound;
2893   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
2894
2895   gtk_text_buffer_get_iter_at_mark (buffer, &insert,
2896                                     gtk_text_buffer_get_mark (buffer, "insert"));
2897   gtk_text_buffer_get_iter_at_mark (buffer, &selection_bound,
2898                                     gtk_text_buffer_get_mark (buffer, "selection_bound"));
2899
2900   if (!gtk_text_iter_equal (&insert, &selection_bound))
2901     gtk_text_buffer_move_mark (buffer,
2902                                gtk_text_buffer_get_mark (buffer, "selection_bound"),
2903                                &insert);
2904 }
2905
2906 /* Called when we have the primary selection and someone else wants our
2907  * data in order to paste it.
2908  */
2909 static void
2910 clipboard_get_selection_cb (GtkClipboard     *clipboard,
2911                             GtkSelectionData *selection_data,
2912                             guint             info,
2913                             gpointer          data)
2914 {
2915   GtkTextBuffer *buffer = GTK_TEXT_BUFFER (data);
2916   GtkTextIter start, end;
2917
2918   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
2919     {
2920       if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
2921         {
2922           /* Provide the address of the buffer; this will only be
2923            * used within-process
2924            */
2925           gtk_selection_data_set (selection_data,
2926                                   selection_data->target,
2927                                   8, /* bytes */
2928                                   (void*)&buffer,
2929                                   sizeof (buffer));
2930         }
2931       else if (info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
2932         {
2933           guint8 *str;
2934           gsize   len;
2935
2936           str = gtk_text_buffer_serialize (buffer, buffer,
2937                                            selection_data->target,
2938                                            &start, &end, &len);
2939
2940           gtk_selection_data_set (selection_data,
2941                                   selection_data->target,
2942                                   8, /* bytes */
2943                                   str, len);
2944           g_free (str);
2945         }
2946       else
2947         {
2948           gchar *str;
2949
2950           str = gtk_text_iter_get_visible_text (&start, &end);
2951           gtk_selection_data_set_text (selection_data, str, -1);
2952           g_free (str);
2953         }
2954     }
2955 }
2956
2957 static GtkTextBuffer *
2958 create_clipboard_contents_buffer (GtkTextBuffer *buffer)
2959 {
2960   GtkTextBuffer *contents;
2961
2962   contents = gtk_text_buffer_new (gtk_text_buffer_get_tag_table (buffer));
2963
2964   g_object_set_data (G_OBJECT (contents), I_("gtk-text-buffer-clipboard-source"),
2965                      buffer);
2966   g_object_set_data (G_OBJECT (contents), I_("gtk-text-buffer-clipboard"),
2967                      GINT_TO_POINTER (1));
2968
2969   return contents;
2970 }
2971
2972 /* Provide cut/copied data */
2973 static void
2974 clipboard_get_contents_cb (GtkClipboard     *clipboard,
2975                            GtkSelectionData *selection_data,
2976                            guint             info,
2977                            gpointer          data)
2978 {
2979   GtkTextBuffer *contents = GTK_TEXT_BUFFER (data);
2980
2981   g_assert (contents); /* This should never be called unless we own the clipboard */
2982
2983   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
2984     {
2985       /* Provide the address of the clipboard buffer; this will only
2986        * be used within-process. OK to supply a NULL value for contents.
2987        */
2988       gtk_selection_data_set (selection_data,
2989                               selection_data->target,
2990                               8, /* bytes */
2991                               (void*)&contents,
2992                               sizeof (contents));
2993     }
2994   else if (info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
2995     {
2996       GtkTextBuffer *clipboard_source_buffer;
2997       GtkTextIter start, end;
2998       guint8 *str;
2999       gsize   len;
3000
3001       clipboard_source_buffer = g_object_get_data (G_OBJECT (contents),
3002                                                    "gtk-text-buffer-clipboard-source");
3003
3004       gtk_text_buffer_get_bounds (contents, &start, &end);
3005
3006       str = gtk_text_buffer_serialize (clipboard_source_buffer, contents,
3007                                        selection_data->target,
3008                                        &start, &end, &len);
3009
3010       gtk_selection_data_set (selection_data,
3011                               selection_data->target,
3012                               8, /* bytes */
3013                               str, len);
3014       g_free (str);
3015     }
3016   else
3017     {
3018       gchar *str;
3019       GtkTextIter start, end;
3020
3021       gtk_text_buffer_get_bounds (contents, &start, &end);
3022
3023       str = gtk_text_iter_get_visible_text (&start, &end);
3024       gtk_selection_data_set_text (selection_data, str, -1);
3025       g_free (str);
3026     }
3027 }
3028
3029 static void
3030 clipboard_clear_contents_cb (GtkClipboard *clipboard,
3031                              gpointer      data)
3032 {
3033   GtkTextBuffer *contents = GTK_TEXT_BUFFER (data);
3034
3035   g_object_unref (contents);
3036 }
3037
3038 static void
3039 get_paste_point (GtkTextBuffer *buffer,
3040                  GtkTextIter   *iter,
3041                  gboolean       clear_afterward)
3042 {
3043   GtkTextIter insert_point;
3044   GtkTextMark *paste_point_override;
3045
3046   paste_point_override = gtk_text_buffer_get_mark (buffer,
3047                                                    "gtk_paste_point_override");
3048
3049   if (paste_point_override != NULL)
3050     {
3051       gtk_text_buffer_get_iter_at_mark (buffer, &insert_point,
3052                                         paste_point_override);
3053       if (clear_afterward)
3054         gtk_text_buffer_delete_mark (buffer,
3055                                      gtk_text_buffer_get_mark (buffer,
3056                                                                "gtk_paste_point_override"));
3057     }
3058   else
3059     {
3060       gtk_text_buffer_get_iter_at_mark (buffer, &insert_point,
3061                                         gtk_text_buffer_get_mark (buffer,
3062                                                                   "insert"));
3063     }
3064
3065   *iter = insert_point;
3066 }
3067
3068 static void
3069 pre_paste_prep (ClipboardRequest *request_data,
3070                 GtkTextIter      *insert_point)
3071 {
3072   GtkTextBuffer *buffer = request_data->buffer;
3073   
3074   get_paste_point (buffer, insert_point, TRUE);
3075
3076   /* If we're going to replace the selection, we insert before it to
3077    * avoid messing it up, then we delete the selection after inserting.
3078    */
3079   if (request_data->replace_selection)
3080     {
3081       GtkTextIter start, end;
3082       
3083       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3084         *insert_point = start;
3085     }
3086 }
3087
3088 static void
3089 post_paste_cleanup (ClipboardRequest *request_data)
3090 {
3091   if (request_data->replace_selection)
3092     {
3093       GtkTextIter start, end;
3094       
3095       if (gtk_text_buffer_get_selection_bounds (request_data->buffer,
3096                                                 &start, &end))
3097         {
3098           if (request_data->interactive)
3099             gtk_text_buffer_delete_interactive (request_data->buffer,
3100                                                 &start,
3101                                                 &end,
3102                                                 request_data->default_editable);
3103           else
3104             gtk_text_buffer_delete (request_data->buffer, &start, &end);
3105         }
3106     }
3107 }
3108
3109 static void
3110 free_clipboard_request (ClipboardRequest *request_data)
3111 {
3112   g_object_unref (request_data->buffer);
3113   g_free (request_data);
3114 }
3115
3116 /* Called when we request a paste and receive the text data
3117  */
3118 static void
3119 clipboard_text_received (GtkClipboard *clipboard,
3120                          const gchar  *str,
3121                          gpointer      data)
3122 {
3123   ClipboardRequest *request_data = data;
3124   GtkTextBuffer *buffer = request_data->buffer;
3125
3126   if (str)
3127     {
3128       GtkTextIter insert_point;
3129       
3130       if (request_data->interactive) 
3131         gtk_text_buffer_begin_user_action (buffer);
3132
3133       pre_paste_prep (request_data, &insert_point);
3134       
3135       if (request_data->interactive) 
3136         gtk_text_buffer_insert_interactive (buffer, &insert_point,
3137                                             str, -1, request_data->default_editable);
3138       else
3139         gtk_text_buffer_insert (buffer, &insert_point,
3140                                 str, -1);
3141
3142       post_paste_cleanup (request_data);
3143       
3144       if (request_data->interactive) 
3145         gtk_text_buffer_end_user_action (buffer);
3146     }
3147
3148   free_clipboard_request (request_data);
3149 }
3150
3151 static GtkTextBuffer*
3152 selection_data_get_buffer (GtkSelectionData *selection_data,
3153                            ClipboardRequest *request_data)
3154 {
3155   GdkWindow *owner;
3156   GtkTextBuffer *src_buffer = NULL;
3157
3158   /* If we can get the owner, the selection is in-process */
3159   owner = gdk_selection_owner_get_for_display (selection_data->display,
3160                                                selection_data->selection);
3161
3162   if (owner == NULL)
3163     return NULL;
3164   
3165   if (gdk_window_get_window_type (owner) == GDK_WINDOW_FOREIGN)
3166     return NULL;
3167  
3168   if (selection_data->type !=
3169       gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"))
3170     return NULL;
3171
3172   if (selection_data->length != sizeof (src_buffer))
3173     return NULL;
3174           
3175   memcpy (&src_buffer, selection_data->data, sizeof (src_buffer));
3176
3177   if (src_buffer == NULL)
3178     return NULL;
3179   
3180   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (src_buffer), NULL);
3181
3182   if (gtk_text_buffer_get_tag_table (src_buffer) !=
3183       gtk_text_buffer_get_tag_table (request_data->buffer))
3184     return NULL;
3185   
3186   return src_buffer;
3187 }
3188
3189 #if 0
3190 /* These are pretty handy functions; maybe something like them
3191  * should be in the public API. Also, there are other places in this
3192  * file where they could be used.
3193  */
3194 static gpointer
3195 save_iter (const GtkTextIter *iter,
3196            gboolean           left_gravity)
3197 {
3198   return gtk_text_buffer_create_mark (gtk_text_iter_get_buffer (iter),
3199                                       NULL,
3200                                       iter,
3201                                       TRUE);
3202 }
3203
3204 static void
3205 restore_iter (const GtkTextIter *iter,
3206               gpointer           save_id)
3207 {
3208   gtk_text_buffer_get_iter_at_mark (gtk_text_mark_get_buffer (save_id),
3209                                     (GtkTextIter*) iter,
3210                                     save_id);
3211   gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (save_id),
3212                                save_id);
3213 }
3214 #endif
3215
3216 static void
3217 clipboard_rich_text_received (GtkClipboard *clipboard,
3218                               GdkAtom       format,
3219                               const guint8 *text,
3220                               gsize         length,
3221                               gpointer      data)
3222 {
3223   ClipboardRequest *request_data = data;
3224   GtkTextIter insert_point;
3225   gboolean retval = TRUE;
3226   GError *error = NULL;
3227   GtkTextBufferPrivate *priv;
3228
3229   priv = GTK_TEXT_BUFFER_GET_PRIVATE (request_data->buffer);
3230
3231   if (text != NULL && length > 0)
3232     {
3233       pre_paste_prep (request_data, &insert_point);
3234
3235       if (request_data->interactive)
3236         gtk_text_buffer_begin_user_action (request_data->buffer);
3237
3238       if (!request_data->interactive ||
3239           gtk_text_iter_can_insert (&insert_point,
3240                                     request_data->default_editable))
3241         {
3242           retval = gtk_text_buffer_deserialize (request_data->buffer,
3243                                                 request_data->buffer,
3244                                                 format,
3245                                                 &insert_point,
3246                                                 text, length,
3247                                                 &error);
3248         }
3249
3250       if (!retval)
3251         {
3252           g_warning ("error pasting: %s\n", error->message);
3253           g_clear_error (&error);
3254         }
3255
3256       if (request_data->interactive)
3257         gtk_text_buffer_end_user_action (request_data->buffer);
3258
3259       if (retval)
3260         {
3261           post_paste_cleanup (request_data);
3262           return;
3263         }
3264     }
3265
3266   /* Request the text selection instead */
3267   gtk_clipboard_request_text (clipboard,
3268                               clipboard_text_received,
3269                               data);
3270 }
3271
3272 static void
3273 paste_from_buffer (ClipboardRequest    *request_data,
3274                    GtkTextBuffer       *src_buffer,
3275                    const GtkTextIter   *start,
3276                    const GtkTextIter   *end)
3277 {
3278   GtkTextIter insert_point;
3279   GtkTextBuffer *buffer = request_data->buffer;
3280   
3281   /* We're about to emit a bunch of signals, so be safe */
3282   g_object_ref (src_buffer);
3283   
3284   pre_paste_prep (request_data, &insert_point);
3285   
3286   if (request_data->interactive) 
3287     gtk_text_buffer_begin_user_action (buffer);
3288
3289   if (!gtk_text_iter_equal (start, end))
3290     {
3291       if (!request_data->interactive ||
3292           (gtk_text_iter_can_insert (&insert_point,
3293                                      request_data->default_editable)))
3294         gtk_text_buffer_real_insert_range (buffer,
3295                                            &insert_point,
3296                                            start,
3297                                            end,
3298                                            request_data->interactive);
3299     }
3300
3301   post_paste_cleanup (request_data);
3302       
3303   if (request_data->interactive) 
3304     gtk_text_buffer_end_user_action (buffer);
3305
3306   g_object_unref (src_buffer);
3307
3308   free_clipboard_request (request_data);
3309 }
3310
3311 static void
3312 clipboard_clipboard_buffer_received (GtkClipboard     *clipboard,
3313                                      GtkSelectionData *selection_data,
3314                                      gpointer          data)
3315 {
3316   ClipboardRequest *request_data = data;
3317   GtkTextBuffer *src_buffer;
3318   GtkTextBufferPrivate *priv;
3319
3320   src_buffer = selection_data_get_buffer (selection_data, request_data); 
3321
3322   if (src_buffer)
3323     {
3324       GtkTextIter start, end;
3325
3326       if (g_object_get_data (G_OBJECT (src_buffer), "gtk-text-buffer-clipboard"))
3327         {
3328           gtk_text_buffer_get_bounds (src_buffer, &start, &end);
3329
3330           paste_from_buffer (request_data, src_buffer,
3331                              &start, &end);
3332         }
3333       else
3334         {
3335           if (gtk_text_buffer_get_selection_bounds (src_buffer, &start, &end))
3336             paste_from_buffer (request_data, src_buffer,
3337                                &start, &end);
3338         }
3339     }
3340   else
3341     {
3342       priv = GTK_TEXT_BUFFER_GET_PRIVATE (request_data->buffer);
3343
3344       if (gtk_clipboard_wait_is_rich_text_available (clipboard,
3345                                                      request_data->buffer))
3346         {
3347           /* Request rich text */
3348           gtk_clipboard_request_rich_text (clipboard,
3349                                            request_data->buffer,
3350                                            clipboard_rich_text_received,
3351                                            data);
3352         }
3353       else
3354         {
3355           /* Request the text selection instead */
3356           gtk_clipboard_request_text (clipboard,
3357                                       clipboard_text_received,
3358                                       data);
3359         }
3360     }
3361 }
3362
3363 typedef struct
3364 {
3365   GtkClipboard *clipboard;
3366   guint ref_count;
3367 } SelectionClipboard;
3368
3369 static void
3370 update_selection_clipboards (GtkTextBuffer *buffer)
3371 {
3372   GtkTextBufferPrivate *priv;
3373   GSList               *tmp_list = buffer->selection_clipboards;
3374
3375   priv = GTK_TEXT_BUFFER_GET_PRIVATE (buffer);
3376
3377   gtk_text_buffer_get_copy_target_list (buffer);
3378
3379   while (tmp_list)
3380     {
3381       GtkTextIter start;
3382       GtkTextIter end;
3383       
3384       SelectionClipboard *selection_clipboard = tmp_list->data;
3385       GtkClipboard *clipboard = selection_clipboard->clipboard;
3386
3387       /* Determine whether we have a selection and adjust X selection
3388        * accordingly.
3389        */
3390       if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3391         {
3392           if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (buffer))
3393             gtk_clipboard_clear (clipboard);
3394         }
3395       else
3396         {
3397           /* Even if we already have the selection, we need to update our
3398            * timestamp.
3399            */
3400           if (!gtk_clipboard_set_with_owner (clipboard,
3401                                              priv->copy_target_entries,
3402                                              priv->n_copy_target_entries,
3403                                              clipboard_get_selection_cb,
3404                                              clipboard_clear_selection_cb,
3405                                              G_OBJECT (buffer)))
3406             clipboard_clear_selection_cb (clipboard, buffer);
3407         }
3408
3409       tmp_list = tmp_list->next;
3410     }
3411 }
3412
3413 static SelectionClipboard *
3414 find_selection_clipboard (GtkTextBuffer *buffer,
3415                           GtkClipboard  *clipboard)
3416 {
3417   GSList *tmp_list = buffer->selection_clipboards;
3418   while (tmp_list)
3419     {
3420       SelectionClipboard *selection_clipboard = tmp_list->data;
3421       if (selection_clipboard->clipboard == clipboard)
3422         return selection_clipboard;
3423       
3424       tmp_list = tmp_list->next;
3425     }
3426
3427   return NULL;
3428 }
3429
3430 /**
3431  * gtk_text_buffer_add_selection_clipboard:
3432  * @buffer: a #GtkTextBuffer
3433  * @clipboard: a #GtkClipboard
3434  * 
3435  * Adds @clipboard to the list of clipboards in which the selection contents
3436  * of @buffer are available. In most cases, @clipboard will be the #GtkClipboard
3437  * of type %GDK_SELECTION_PRIMARY for a view of @buffer.
3438  **/
3439 void
3440 gtk_text_buffer_add_selection_clipboard (GtkTextBuffer *buffer,
3441                                          GtkClipboard  *clipboard)
3442 {
3443   SelectionClipboard *selection_clipboard;
3444
3445   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3446   g_return_if_fail (clipboard != NULL);
3447
3448   selection_clipboard = find_selection_clipboard (buffer, clipboard);
3449   if (selection_clipboard)
3450     {
3451       selection_clipboard->ref_count++;
3452     }
3453   else
3454     {
3455       selection_clipboard = g_new (SelectionClipboard, 1);
3456
3457       selection_clipboard->clipboard = clipboard;
3458       selection_clipboard->ref_count = 1;
3459
3460       buffer->selection_clipboards = g_slist_prepend (buffer->selection_clipboards, selection_clipboard);
3461     }
3462 }
3463
3464 /**
3465  * gtk_text_buffer_remove_selection_clipboard:
3466  * @buffer: a #GtkTextBuffer
3467  * @clipboard: a #GtkClipboard added to @buffer by gtk_text_buffer_add_selection_clipboard().
3468  * 
3469  * Removes a #GtkClipboard added with gtk_text_buffer_add_selection_clipboard()
3470  **/
3471 void 
3472 gtk_text_buffer_remove_selection_clipboard (GtkTextBuffer *buffer,
3473                                             GtkClipboard  *clipboard)
3474 {
3475   SelectionClipboard *selection_clipboard;
3476
3477   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3478   g_return_if_fail (clipboard != NULL);
3479
3480   selection_clipboard = find_selection_clipboard (buffer, clipboard);
3481   g_return_if_fail (selection_clipboard != NULL);
3482
3483   selection_clipboard->ref_count--;
3484   if (selection_clipboard->ref_count == 0)
3485     {
3486       if (gtk_clipboard_get_owner (selection_clipboard->clipboard) == G_OBJECT (buffer))
3487         gtk_clipboard_clear (selection_clipboard->clipboard);
3488
3489       buffer->selection_clipboards = g_slist_remove (buffer->selection_clipboards,
3490                                                      selection_clipboard);
3491       
3492       g_free (selection_clipboard);
3493     }
3494 }
3495
3496 static void
3497 remove_all_selection_clipboards (GtkTextBuffer *buffer)
3498 {
3499   GSList *tmp_list = buffer->selection_clipboards;
3500   while (tmp_list)
3501     {
3502       SelectionClipboard *selection_clipboard = tmp_list->data;
3503       
3504       if (gtk_clipboard_get_owner (selection_clipboard->clipboard) == G_OBJECT (buffer))
3505         gtk_clipboard_clear (selection_clipboard->clipboard);
3506       
3507       g_free (selection_clipboard);
3508
3509       tmp_list = tmp_list->next;
3510     }
3511
3512   g_slist_free (buffer->selection_clipboards);
3513   buffer->selection_clipboards = NULL;
3514 }
3515
3516 /**
3517  * gtk_text_buffer_paste_clipboard:
3518  * @buffer: a #GtkTextBuffer
3519  * @clipboard: the #GtkClipboard to paste from
3520  * @override_location: location to insert pasted text, or %NULL for at the cursor
3521  * @default_editable: whether the buffer is editable by default
3522  *
3523  * Pastes the contents of a clipboard at the insertion point, or at @override_location.
3524  * (Note: pasting is asynchronous, that is, we'll ask for the paste data and
3525  * return, and at some point later after the main loop runs, the paste
3526  * data will be inserted.)
3527  * 
3528  **/
3529 void
3530 gtk_text_buffer_paste_clipboard (GtkTextBuffer *buffer,
3531                                  GtkClipboard  *clipboard,
3532                                  GtkTextIter   *override_location,
3533                                  gboolean       default_editable)
3534 {
3535   ClipboardRequest *data = g_new (ClipboardRequest, 1);
3536   GtkTextIter paste_point;
3537   GtkTextIter start, end;
3538
3539   if (override_location != NULL)
3540     gtk_text_buffer_create_mark (buffer,
3541                                  "gtk_paste_point_override",
3542                                  override_location, FALSE);
3543
3544   data->buffer = g_object_ref (buffer);
3545   data->interactive = TRUE;
3546   data->default_editable = default_editable;
3547
3548   /* When pasting with the cursor inside the selection area, you
3549    * replace the selection with the new text, otherwise, you
3550    * simply insert the new text at the point where the click
3551    * occured, unselecting any selected text. The replace_selection
3552    * flag toggles this behavior.
3553    */
3554   data->replace_selection = FALSE;
3555   
3556   get_paste_point (buffer, &paste_point, FALSE);
3557   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end) &&
3558       (gtk_text_iter_in_range (&paste_point, &start, &end) ||
3559        gtk_text_iter_equal (&paste_point, &end)))
3560     data->replace_selection = TRUE;
3561
3562   gtk_clipboard_request_contents (clipboard,
3563                                   gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"),
3564                                   clipboard_clipboard_buffer_received, data);
3565 }
3566
3567 /**
3568  * gtk_text_buffer_delete_selection:
3569  * @buffer: a #GtkTextBuffer 
3570  * @interactive: whether the deletion is caused by user interaction
3571  * @default_editable: whether the buffer is editable by default
3572  *
3573  * Deletes the range between the "insert" and "selection_bound" marks,
3574  * that is, the currently-selected text. If @interactive is %TRUE,
3575  * the editability of the selection will be considered (users can't delete
3576  * uneditable text).
3577  * 
3578  * Return value: whether there was a non-empty selection to delete
3579  **/
3580 gboolean
3581 gtk_text_buffer_delete_selection (GtkTextBuffer *buffer,
3582                                   gboolean interactive,
3583                                   gboolean default_editable)
3584 {
3585   GtkTextIter start;
3586   GtkTextIter end;
3587
3588   if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3589     {
3590       return FALSE; /* No selection */
3591     }
3592   else
3593     {
3594       if (interactive)
3595         {
3596           gtk_text_buffer_begin_user_action (buffer);
3597           gtk_text_buffer_delete_interactive (buffer, &start, &end, default_editable);
3598           gtk_text_buffer_end_user_action (buffer);
3599         }
3600       else
3601         gtk_text_buffer_delete (buffer, &start, &end);
3602
3603       return TRUE; /* We deleted stuff */
3604     }
3605 }
3606
3607 /**
3608  * gtk_text_buffer_backspace:
3609  * @buffer: a #GtkTextBuffer
3610  * @iter: a position in @buffer
3611  * @interactive: whether the deletion is caused by user interaction
3612  * @default_editable: whether the buffer is editable by default
3613  * 
3614  * Performs the appropriate action as if the user hit the delete
3615  * key with the cursor at the position specified by @iter. In the
3616  * normal case a single character will be deleted, but when
3617  * combining accents are involved, more than one character can
3618  * be deleted, and when precomposed character and accent combinations
3619  * are involved, less than one character will be deleted.
3620  * 
3621  * Because the buffer is modified, all outstanding iterators become 
3622  * invalid after calling this function; however, the @iter will be
3623  * re-initialized to point to the location where text was deleted. 
3624  *
3625  * Return value: %TRUE if the buffer was modified
3626
3627  * Since: 2.6
3628  **/
3629 gboolean
3630 gtk_text_buffer_backspace (GtkTextBuffer *buffer,
3631                            GtkTextIter   *iter,
3632                            gboolean       interactive,
3633                            gboolean       default_editable)
3634 {
3635   gchar *cluster_text;
3636   GtkTextIter start;
3637   GtkTextIter end;
3638   gboolean retval = FALSE;
3639   const PangoLogAttr *attrs;
3640   int offset;
3641   gboolean backspace_deletes_character;
3642
3643   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
3644   g_return_val_if_fail (iter != NULL, FALSE);
3645
3646   start = *iter;
3647   end = *iter;
3648
3649   attrs = _gtk_text_buffer_get_line_log_attrs (buffer, &start, NULL);
3650
3651   /* For no good reason, attrs is NULL for the empty last line in
3652    * a buffer. Special case that here. (#156164)
3653    */
3654   if (attrs)
3655     {
3656       offset = gtk_text_iter_get_line_offset (&start);
3657       backspace_deletes_character = attrs[offset].backspace_deletes_character;
3658     }
3659   else
3660     backspace_deletes_character = FALSE;
3661
3662   gtk_text_iter_backward_cursor_position (&start);
3663
3664   if (gtk_text_iter_equal (&start, &end))
3665     return FALSE;
3666     
3667   cluster_text = gtk_text_iter_get_text (&start, &end);
3668
3669   if (interactive)
3670     gtk_text_buffer_begin_user_action (buffer);
3671   
3672   if (gtk_text_buffer_delete_interactive (buffer, &start, &end,
3673                                           default_editable))
3674     {
3675       if (backspace_deletes_character)
3676         {
3677           gchar *normalized_text = g_utf8_normalize (cluster_text,
3678                                                      strlen (cluster_text),
3679                                                      G_NORMALIZE_NFD);
3680           glong len = g_utf8_strlen (normalized_text, -1);
3681           
3682           if (len > 1)
3683             gtk_text_buffer_insert_interactive (buffer,
3684                                                 &start,
3685                                                 normalized_text,
3686                                                 g_utf8_offset_to_pointer (normalized_text, len - 1) - normalized_text,
3687                                                 default_editable);
3688           
3689           g_free (normalized_text);
3690         }
3691
3692       retval = TRUE;
3693     }
3694   
3695   if (interactive)
3696     gtk_text_buffer_end_user_action (buffer);
3697   
3698   g_free (cluster_text);
3699
3700   /* Revalidate the users iter */
3701   *iter = start;
3702
3703   return retval;
3704 }
3705
3706 static void
3707 cut_or_copy (GtkTextBuffer *buffer,
3708              GtkClipboard  *clipboard,
3709              gboolean       delete_region_after,
3710              gboolean       interactive,
3711              gboolean       default_editable)
3712 {
3713   GtkTextBufferPrivate *priv;
3714
3715   /* We prefer to cut the selected region between selection_bound and
3716    * insertion point. If that region is empty, then we cut the region
3717    * between the "anchor" and the insertion point (this is for
3718    * C-space and M-w and other Emacs-style copy/yank keys). Note that
3719    * insert and selection_bound are guaranteed to exist, but the
3720    * anchor only exists sometimes.
3721    */
3722   GtkTextIter start;
3723   GtkTextIter end;
3724
3725   priv = GTK_TEXT_BUFFER_GET_PRIVATE (buffer);
3726
3727   gtk_text_buffer_get_copy_target_list (buffer);
3728
3729   if (!gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
3730     {
3731       /* Let's try the anchor thing */
3732       GtkTextMark * anchor = gtk_text_buffer_get_mark (buffer, "anchor");
3733
3734       if (anchor == NULL)
3735         return;
3736       else
3737         {
3738           gtk_text_buffer_get_iter_at_mark (buffer, &end, anchor);
3739           gtk_text_iter_order (&start, &end);
3740         }
3741     }
3742
3743   if (!gtk_text_iter_equal (&start, &end))
3744     {
3745       GtkTextIter ins;
3746       GtkTextBuffer *contents;
3747
3748       contents = create_clipboard_contents_buffer (buffer);
3749
3750       gtk_text_buffer_get_iter_at_offset (contents, &ins, 0);
3751       
3752       gtk_text_buffer_insert_range (contents, &ins, &start, &end);
3753                                     
3754       if (!gtk_clipboard_set_with_data (clipboard,
3755                                         priv->copy_target_entries,
3756                                         priv->n_copy_target_entries,
3757                                         clipboard_get_contents_cb,
3758                                         clipboard_clear_contents_cb,
3759                                         contents))
3760         g_object_unref (contents);
3761       else
3762         gtk_clipboard_set_can_store (clipboard,
3763                                      priv->copy_target_entries + 1,
3764                                      priv->n_copy_target_entries - 1);
3765
3766       if (delete_region_after)
3767         {
3768           if (interactive)
3769             gtk_text_buffer_delete_interactive (buffer, &start, &end,
3770                                                 default_editable);
3771           else
3772             gtk_text_buffer_delete (buffer, &start, &end);
3773         }
3774     }
3775 }
3776
3777 /**
3778  * gtk_text_buffer_cut_clipboard:
3779  * @buffer: a #GtkTextBuffer
3780  * @clipboard: the #GtkClipboard object to cut to.
3781  * @default_editable: default editability of the buffer
3782  *
3783  * Copies the currently-selected text to a clipboard, then deletes
3784  * said text if it's editable.
3785  * 
3786  **/
3787 void
3788 gtk_text_buffer_cut_clipboard (GtkTextBuffer *buffer,
3789                                GtkClipboard  *clipboard,
3790                                gboolean       default_editable)
3791 {
3792   gtk_text_buffer_begin_user_action (buffer);
3793   cut_or_copy (buffer, clipboard, TRUE, TRUE, default_editable);
3794   gtk_text_buffer_end_user_action (buffer);
3795 }
3796
3797 /**
3798  * gtk_text_buffer_copy_clipboard:
3799  * @buffer: a #GtkTextBuffer 
3800  * @clipboard: the #GtkClipboard object to copy to.
3801  *
3802  * Copies the currently-selected text to a clipboard.
3803  * 
3804  **/
3805 void
3806 gtk_text_buffer_copy_clipboard (GtkTextBuffer *buffer,
3807                                 GtkClipboard  *clipboard)
3808 {
3809   gtk_text_buffer_begin_user_action (buffer);
3810   cut_or_copy (buffer, clipboard, FALSE, TRUE, TRUE);
3811   gtk_text_buffer_end_user_action (buffer);
3812 }
3813
3814
3815 /**
3816  * gtk_text_buffer_get_selection_bounds:
3817  * @buffer: a #GtkTextBuffer a #GtkTextBuffer
3818  * @start: iterator to initialize with selection start
3819  * @end: iterator to initialize with selection end
3820  *
3821  * Returns %TRUE if some text is selected; places the bounds
3822  * of the selection in @start and @end (if the selection has length 0,
3823  * then @start and @end are filled in with the same value).
3824  * @start and @end will be in ascending order. If @start and @end are
3825  * NULL, then they are not filled in, but the return value still indicates
3826  * whether text is selected.
3827  *
3828  * Return value: whether the selection has nonzero length
3829  **/
3830 gboolean
3831 gtk_text_buffer_get_selection_bounds   (GtkTextBuffer      *buffer,
3832                                         GtkTextIter        *start,
3833                                         GtkTextIter        *end)
3834 {
3835   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), FALSE);
3836
3837   return _gtk_text_btree_get_selection_bounds (get_btree (buffer), start, end);
3838 }
3839
3840 /**
3841  * gtk_text_buffer_begin_user_action:
3842  * @buffer: a #GtkTextBuffer
3843  * 
3844  * Called to indicate that the buffer operations between here and a
3845  * call to gtk_text_buffer_end_user_action() are part of a single
3846  * user-visible operation. The operations between
3847  * gtk_text_buffer_begin_user_action() and
3848  * gtk_text_buffer_end_user_action() can then be grouped when creating
3849  * an undo stack. #GtkTextBuffer maintains a count of calls to
3850  * gtk_text_buffer_begin_user_action() that have not been closed with
3851  * a call to gtk_text_buffer_end_user_action(), and emits the "begin_user_action"
3852  * and "end_user_action" signals only for the outermost pair of calls.
3853  * This allows you to build user actions from other user actions.
3854  *
3855  * The "interactive" buffer mutation functions, such as
3856  * gtk_text_buffer_insert_interactive(), automatically call begin/end
3857  * user action around the buffer operations they perform, so there's
3858  * no need to add extra calls if you user action consists solely of a
3859  * single call to one of those functions.
3860  **/
3861 void
3862 gtk_text_buffer_begin_user_action (GtkTextBuffer *buffer)
3863 {
3864   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3865
3866   buffer->user_action_count += 1;
3867   
3868   if (buffer->user_action_count == 1)
3869     {
3870       /* Outermost nested user action begin emits the signal */
3871       g_signal_emit (buffer, signals[BEGIN_USER_ACTION], 0);
3872     }
3873 }
3874
3875 /**
3876  * gtk_text_buffer_end_user_action:
3877  * @buffer: a #GtkTextBuffer
3878  * 
3879  * Should be paired with a call to gtk_text_buffer_begin_user_action().
3880  * See that function for a full explanation.
3881  **/
3882 void
3883 gtk_text_buffer_end_user_action (GtkTextBuffer *buffer)
3884 {
3885   g_return_if_fail (GTK_IS_TEXT_BUFFER (buffer));
3886   g_return_if_fail (buffer->user_action_count > 0);
3887   
3888   buffer->user_action_count -= 1;
3889   
3890   if (buffer->user_action_count == 0)
3891     {
3892       /* Ended the outermost-nested user action end, so emit the signal */
3893       g_signal_emit (buffer, signals[END_USER_ACTION], 0);
3894     }
3895 }
3896
3897 static void
3898 gtk_text_buffer_free_target_lists (GtkTextBuffer *buffer)
3899 {
3900   GtkTextBufferPrivate *priv = GTK_TEXT_BUFFER_GET_PRIVATE (buffer);
3901
3902   if (priv->copy_target_list)
3903     {
3904       gtk_target_list_unref (priv->copy_target_list);
3905       priv->copy_target_list = NULL;
3906
3907       gtk_target_table_free (priv->copy_target_entries,
3908                              priv->n_copy_target_entries);
3909       priv->copy_target_entries = NULL;
3910       priv->n_copy_target_entries = 0;
3911     }
3912
3913   if (priv->paste_target_list)
3914     {
3915       gtk_target_list_unref (priv->paste_target_list);
3916       priv->paste_target_list = NULL;
3917
3918       gtk_target_table_free (priv->paste_target_entries,
3919                              priv->n_paste_target_entries);
3920       priv->paste_target_entries = NULL;
3921       priv->n_paste_target_entries = 0;
3922     }
3923 }
3924
3925 static GtkTargetList *
3926 gtk_text_buffer_get_target_list (GtkTextBuffer   *buffer,
3927                                  gboolean         deserializable,
3928                                  GtkTargetEntry **entries,
3929                                  gint            *n_entries)
3930 {
3931   GtkTargetList *target_list;
3932
3933   target_list = gtk_target_list_new (NULL, 0);
3934
3935   gtk_target_list_add (target_list,
3936                        gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"),
3937                        GTK_TARGET_SAME_APP,
3938                        GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS);
3939
3940   gtk_target_list_add_rich_text_targets (target_list,
3941                                          GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT,
3942                                          deserializable,
3943                                          buffer);
3944
3945   gtk_target_list_add_text_targets (target_list,
3946                                     GTK_TEXT_BUFFER_TARGET_INFO_TEXT);
3947
3948   *entries = gtk_target_table_new_from_list (target_list, n_entries);
3949
3950   return target_list;
3951 }
3952
3953 /**
3954  * gtk_text_buffer_get_copy_target_list:
3955  * @buffer: a #GtkTextBuffer
3956  *
3957  * This function returns the list of targets this text buffer can
3958  * provide for copying and as DND source. The targets in the list are
3959  * added with %info values from the #GtkTextBufferTargetInfo enum,
3960  * using gtk_target_list_add_rich_text_targets() and
3961  * gtk_target_list_add_text_targets()
3962  *
3963  * Return value: the #GtkTargetList
3964  *
3965  * Since: 2.10
3966  **/
3967 GtkTargetList *
3968 gtk_text_buffer_get_copy_target_list (GtkTextBuffer *buffer)
3969 {
3970   GtkTextBufferPrivate *priv;
3971
3972   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
3973
3974   priv = GTK_TEXT_BUFFER_GET_PRIVATE (buffer);
3975
3976   if (! priv->copy_target_list)
3977     priv->copy_target_list =
3978       gtk_text_buffer_get_target_list (buffer, FALSE,
3979                                        &priv->copy_target_entries,
3980                                        &priv->n_copy_target_entries);
3981
3982   return priv->copy_target_list;
3983 }
3984
3985 /**
3986  * gtk_text_buffer_get_paste_target_list:
3987  * @buffer: a #GtkTextBuffer
3988  *
3989  * This function returns the list of targets this text buffer supports
3990  * for pasting and as DND destination. The targets in the list are
3991  * added with %info values from the #GtkTextBufferTargetInfo enum,
3992  * using gtk_target_list_add_rich_text_targets() and
3993  * gtk_target_list_add_text_targets()
3994  *
3995  * Return value: the #GtkTargetList
3996  *
3997  * Since: 2.10
3998  **/
3999 GtkTargetList *
4000 gtk_text_buffer_get_paste_target_list (GtkTextBuffer *buffer)
4001 {
4002   GtkTextBufferPrivate *priv;
4003
4004   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
4005
4006   priv = GTK_TEXT_BUFFER_GET_PRIVATE (buffer);
4007
4008   if (! priv->paste_target_list)
4009     priv->paste_target_list =
4010       gtk_text_buffer_get_target_list (buffer, TRUE,
4011                                        &priv->paste_target_entries,
4012                                        &priv->n_paste_target_entries);
4013
4014   return priv->paste_target_list;
4015 }
4016
4017 /*
4018  * Logical attribute cache
4019  */
4020
4021 #define ATTR_CACHE_SIZE 2
4022
4023 typedef struct _CacheEntry CacheEntry;
4024 struct _CacheEntry
4025 {
4026   gint line;
4027   gint char_len;
4028   PangoLogAttr *attrs;
4029 };
4030
4031
4032 struct _GtkTextLogAttrCache
4033 {
4034   gint chars_changed_stamp;
4035   CacheEntry entries[ATTR_CACHE_SIZE];
4036 };
4037
4038 static void
4039 free_log_attr_cache (GtkTextLogAttrCache *cache)
4040 {
4041   gint i = 0;
4042   while (i < ATTR_CACHE_SIZE)
4043     {
4044       g_free (cache->entries[i].attrs);
4045       ++i;
4046     }
4047   g_free (cache);
4048 }
4049
4050 static void
4051 clear_log_attr_cache (GtkTextLogAttrCache *cache)
4052 {
4053   gint i = 0;
4054   while (i < ATTR_CACHE_SIZE)
4055     {
4056       g_free (cache->entries[i].attrs);
4057       cache->entries[i].attrs = NULL;
4058       ++i;
4059     }
4060 }
4061
4062 static PangoLogAttr*
4063 compute_log_attrs (const GtkTextIter *iter,
4064                    gint              *char_lenp)
4065 {
4066   GtkTextIter start;
4067   GtkTextIter end;
4068   gchar *paragraph;
4069   gint char_len, byte_len;
4070   PangoLogAttr *attrs = NULL;
4071   
4072   start = *iter;
4073   end = *iter;
4074
4075   gtk_text_iter_set_line_offset (&start, 0);
4076   gtk_text_iter_forward_line (&end);
4077
4078   paragraph = gtk_text_iter_get_slice (&start, &end);
4079   char_len = g_utf8_strlen (paragraph, -1);
4080   byte_len = strlen (paragraph);
4081
4082   g_assert (char_len > 0);
4083
4084   if (char_lenp)
4085     *char_lenp = char_len;
4086   
4087   attrs = g_new (PangoLogAttr, char_len + 1);
4088
4089   /* FIXME we need to follow PangoLayout and allow different language
4090    * tags within the paragraph
4091    */
4092   pango_get_log_attrs (paragraph, byte_len, -1,
4093                        gtk_text_iter_get_language (&start),
4094                        attrs,
4095                        char_len + 1);
4096   
4097   g_free (paragraph);
4098
4099   return attrs;
4100 }
4101
4102 /* The return value from this is valid until you call this a second time.
4103  */
4104 const PangoLogAttr*
4105 _gtk_text_buffer_get_line_log_attrs (GtkTextBuffer     *buffer,
4106                                      const GtkTextIter *anywhere_in_line,
4107                                      gint              *char_len)
4108 {
4109   gint line;
4110   GtkTextLogAttrCache *cache;
4111   gint i;
4112   
4113   g_return_val_if_fail (GTK_IS_TEXT_BUFFER (buffer), NULL);
4114   g_return_val_if_fail (anywhere_in_line != NULL, NULL);
4115
4116   /* special-case for empty last line in buffer */
4117   if (gtk_text_iter_is_end (anywhere_in_line) &&
4118       gtk_text_iter_get_line_offset (anywhere_in_line) == 0)
4119     {
4120       if (char_len)
4121         *char_len = 0;
4122       return NULL;
4123     }
4124   
4125   /* FIXME we also need to recompute log attrs if the language tag at
4126    * the start of a paragraph changes
4127    */
4128   
4129   if (buffer->log_attr_cache == NULL)
4130     {
4131       buffer->log_attr_cache = g_new0 (GtkTextLogAttrCache, 1);
4132       buffer->log_attr_cache->chars_changed_stamp =
4133         _gtk_text_btree_get_chars_changed_stamp (get_btree (buffer));
4134     }
4135   else if (buffer->log_attr_cache->chars_changed_stamp !=
4136            _gtk_text_btree_get_chars_changed_stamp (get_btree (buffer)))
4137     {
4138       clear_log_attr_cache (buffer->log_attr_cache);
4139     }
4140   
4141   cache = buffer->log_attr_cache;
4142   line = gtk_text_iter_get_line (anywhere_in_line);
4143
4144   i = 0;
4145   while (i < ATTR_CACHE_SIZE)
4146     {
4147       if (cache->entries[i].attrs &&
4148           cache->entries[i].line == line)
4149         {
4150           if (char_len)
4151             *char_len = cache->entries[i].char_len;
4152           return cache->entries[i].attrs;
4153         }
4154       ++i;
4155     }
4156   
4157   /* Not in cache; open up the first cache entry */
4158   if (cache->entries[ATTR_CACHE_SIZE-1].attrs)
4159     g_free (cache->entries[ATTR_CACHE_SIZE-1].attrs);
4160   
4161   g_memmove (cache->entries + 1, cache->entries,
4162              sizeof (CacheEntry) * (ATTR_CACHE_SIZE - 1));
4163
4164   cache->entries[0].line = line;
4165   cache->entries[0].attrs = compute_log_attrs (anywhere_in_line,
4166                                                &cache->entries[0].char_len);
4167
4168   if (char_len)
4169     *char_len = cache->entries[0].char_len;
4170   
4171   return cache->entries[0].attrs;
4172 }
4173
4174 void
4175 _gtk_text_buffer_notify_will_remove_tag (GtkTextBuffer *buffer,
4176                                          GtkTextTag    *tag)
4177 {
4178   /* This removes tag from the buffer, but DOESN'T emit the
4179    * remove_tag signal, because we can't afford to have user
4180    * code messing things up at this point; the tag MUST be removed
4181    * entirely.
4182    */
4183   if (buffer->btree)
4184     _gtk_text_btree_notify_will_remove_tag (buffer->btree, tag);
4185 }
4186
4187 /*
4188  * Debug spew
4189  */
4190
4191 void
4192 _gtk_text_buffer_spew (GtkTextBuffer *buffer)
4193 {
4194   _gtk_text_btree_spew (get_btree (buffer));
4195 }
4196
4197 #define __GTK_TEXT_BUFFER_C__
4198 #include "gtkaliasdef.c"