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