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