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