]> Pileus Git - ~andy/gtk/blob - gtk/gtktextview.c
testview: Convert _gtk_text_util_create_rich_drag_icon() to use surfaces
[~andy/gtk] / gtk / gtktextview.c
1 /* -*- Mode: C; c-file-style: "gnu"; tab-width: 8 -*- */
2 /* GTK - The GIMP Toolkit
3  * gtktextview.c Copyright (C) 2000 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /*
22  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
23  * file for a list of people on the GTK+ Team.  See the ChangeLog
24  * files for a list of changes.  These files are distributed with
25  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
26  */
27
28 #include "config.h"
29 #include <string.h>
30
31 #define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
32 #include "gtkbindings.h"
33 #include "gtkdnd.h"
34 #include "gtkimagemenuitem.h"
35 #include "gtkintl.h"
36 #include "gtkmain.h"
37 #include "gtkmarshalers.h"
38 #include "gtkmenu.h"
39 #include "gtkmenuitem.h"
40 #include "gtkseparatormenuitem.h"
41 #include "gtksettings.h"
42 #include "gtkstock.h"
43 #include "gtksizerequest.h"
44 #include "gtktextbufferrichtext.h"
45 #include "gtktextdisplay.h"
46 #include "gtktextview.h"
47 #include "gtkimmulticontext.h"
48 #include "gdk/gdkkeysyms.h"
49 #include "gtkprivate.h"
50 #include "gtktextutil.h"
51 #include "gtkwindow.h"
52
53
54 /* How scrolling, validation, exposes, etc. work.
55  *
56  * The expose_event handler has the invariant that the onscreen lines
57  * have been validated.
58  *
59  * There are two ways that onscreen lines can become invalid. The first
60  * is to change which lines are onscreen. This happens when the value
61  * of a scroll adjustment changes. So the code path begins in
62  * gtk_text_view_value_changed() and goes like this:
63  *   - gdk_window_scroll() to reflect the new adjustment value
64  *   - validate the lines that were moved onscreen
65  *   - gdk_window_process_updates() to handle the exposes immediately
66  *
67  * The second way is that you get the "invalidated" signal from the layout,
68  * indicating that lines have become invalid. This code path begins in
69  * invalidated_handler() and goes like this:
70  *   - install high-priority idle which does the rest of the steps
71  *   - if a scroll is pending from scroll_to_mark(), do the scroll,
72  *     jumping to the gtk_text_view_value_changed() code path
73  *   - otherwise, validate the onscreen lines
74  *   - DO NOT process updates
75  *
76  * In both cases, validating the onscreen lines can trigger a scroll
77  * due to maintaining the first_para on the top of the screen.
78  * If validation triggers a scroll, we jump to the top of the code path
79  * for value_changed, and bail out of the current code path.
80  *
81  * Also, in size_allocate, if we invalidate some lines from changing
82  * the layout width, we need to go ahead and run the high-priority idle,
83  * because GTK sends exposes right after doing the size allocates without
84  * returning to the main loop. This is also why the high-priority idle
85  * is at a higher priority than resizing.
86  *
87  */
88
89 #if 0
90 #define DEBUG_VALIDATION_AND_SCROLLING
91 #endif
92
93 #ifdef DEBUG_VALIDATION_AND_SCROLLING
94 #define DV(x) (x)
95 #else
96 #define DV(x)
97 #endif
98
99 #define SCREEN_WIDTH(widget) text_window_get_width (GTK_TEXT_VIEW (widget)->priv->text_window)
100 #define SCREEN_HEIGHT(widget) text_window_get_height (GTK_TEXT_VIEW (widget)->priv->text_window)
101
102 #define SPACE_FOR_CURSOR 1
103
104 #define GTK_TEXT_VIEW_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GTK_TYPE_TEXT_VIEW, GtkTextViewPrivate))
105
106 typedef struct _GtkTextWindow GtkTextWindow;
107 typedef struct _GtkTextPendingScroll GtkTextPendingScroll;
108
109 struct _GtkTextViewPrivate 
110 {
111   GtkTextLayout *layout;
112   GtkTextBuffer *buffer;
113
114   guint blink_time;  /* time in msec the cursor has blinked since last user event */
115   guint im_spot_idle;
116   gchar *im_module;
117   GdkDevice *grab_device;
118   GdkDevice *dnd_device;
119
120   guint selection_drag_handler;
121   guint scroll_timeout;
122
123   GtkTextWindow *text_window;
124   GtkTextWindow *left_window;
125   GtkTextWindow *right_window;
126   GtkTextWindow *top_window;
127   GtkTextWindow *bottom_window;
128
129   GtkAdjustment *hadjustment;
130   GtkAdjustment *vadjustment;
131
132   gint xoffset;         /* Offsets between widget coordinates and buffer coordinates */
133   gint yoffset;
134   gint width;           /* Width and height of the buffer */
135   gint height;
136
137   /* This is used to monitor the overall size request 
138    * and decide whether we need to queue resizes when
139    * the buffer content changes. 
140    *
141    * FIXME: This could be done in a simpler way by 
142    * consulting the above width/height of the buffer + some
143    * padding values, however all of this request code needs
144    * to be changed to use GtkSizeRequestIface and deserves
145    * more attention.
146    */
147   GtkRequisition cached_size_request;
148
149   /* The virtual cursor position is normally the same as the
150    * actual (strong) cursor position, except in two circumstances:
151    *
152    * a) When the cursor is moved vertically with the keyboard
153    * b) When the text view is scrolled with the keyboard
154    *
155    * In case a), virtual_cursor_x is preserved, but not virtual_cursor_y
156    * In case b), both virtual_cursor_x and virtual_cursor_y are preserved.
157    */
158   gint virtual_cursor_x;   /* -1 means use actual cursor position */
159   gint virtual_cursor_y;   /* -1 means use actual cursor position */
160
161   GtkTextMark *first_para_mark; /* Mark at the beginning of the first onscreen paragraph */
162   gint first_para_pixels;       /* Offset of top of screen in the first onscreen paragraph */
163
164   GtkTextMark *dnd_mark;
165   guint blink_timeout;
166
167   guint first_validate_idle;        /* Idle to revalidate onscreen portion, runs before resize */
168   guint incremental_validate_idle;  /* Idle to revalidate offscreen portions, runs after redraw */
169
170   GtkIMContext *im_context;
171   GtkWidget *popup_menu;
172
173   gint drag_start_x;
174   gint drag_start_y;
175
176   GSList *children;
177
178   GtkTextPendingScroll *pending_scroll;
179
180   gint pending_place_cursor_button;
181
182   /* Default style settings */
183   gint pixels_above_lines;
184   gint pixels_below_lines;
185   gint pixels_inside_wrap;
186   GtkWrapMode wrap_mode;
187   GtkJustification justify;
188   gint left_margin;
189   gint right_margin;
190   gint indent;
191   PangoTabArray *tabs;
192   guint editable : 1;
193
194   guint overwrite_mode : 1;
195   guint cursor_visible : 1;
196
197   /* if we have reset the IM since the last character entered */  
198   guint need_im_reset : 1;
199
200   guint accepts_tab : 1;
201
202   guint width_changed : 1;
203
204   /* debug flag - means that we've validated onscreen since the
205    * last "invalidate" signal from the layout
206    */
207   guint onscreen_validated : 1;
208
209   guint mouse_cursor_obscured : 1;
210
211   guint scroll_after_paste : 1;
212 };
213
214 struct _GtkTextPendingScroll
215 {
216   GtkTextMark   *mark;
217   gdouble        within_margin;
218   gboolean       use_align;
219   gdouble        xalign;
220   gdouble        yalign;
221 };
222
223 enum
224 {
225   SET_SCROLL_ADJUSTMENTS,
226   POPULATE_POPUP,
227   MOVE_CURSOR,
228   PAGE_HORIZONTALLY,
229   SET_ANCHOR,
230   INSERT_AT_CURSOR,
231   DELETE_FROM_CURSOR,
232   BACKSPACE,
233   CUT_CLIPBOARD,
234   COPY_CLIPBOARD,
235   PASTE_CLIPBOARD,
236   TOGGLE_OVERWRITE,
237   MOVE_VIEWPORT,
238   SELECT_ALL,
239   TOGGLE_CURSOR_VISIBLE,
240   PREEDIT_CHANGED,
241   LAST_SIGNAL
242 };
243
244 enum
245 {
246   PROP_0,
247   PROP_PIXELS_ABOVE_LINES,
248   PROP_PIXELS_BELOW_LINES,
249   PROP_PIXELS_INSIDE_WRAP,
250   PROP_EDITABLE,
251   PROP_WRAP_MODE,
252   PROP_JUSTIFICATION,
253   PROP_LEFT_MARGIN,
254   PROP_RIGHT_MARGIN,
255   PROP_INDENT,
256   PROP_TABS,
257   PROP_CURSOR_VISIBLE,
258   PROP_BUFFER,
259   PROP_OVERWRITE,
260   PROP_ACCEPTS_TAB,
261   PROP_IM_MODULE
262 };
263
264 static void gtk_text_view_destroy              (GtkObject        *object);
265 static void gtk_text_view_finalize             (GObject          *object);
266 static void gtk_text_view_set_property         (GObject         *object,
267                                                 guint            prop_id,
268                                                 const GValue    *value,
269                                                 GParamSpec      *pspec);
270 static void gtk_text_view_get_property         (GObject         *object,
271                                                 guint            prop_id,
272                                                 GValue          *value,
273                                                 GParamSpec      *pspec);
274 static void gtk_text_view_size_request         (GtkWidget        *widget,
275                                                 GtkRequisition   *requisition);
276 static void gtk_text_view_size_allocate        (GtkWidget        *widget,
277                                                 GtkAllocation    *allocation);
278 static void gtk_text_view_realize              (GtkWidget        *widget);
279 static void gtk_text_view_unrealize            (GtkWidget        *widget);
280 static void gtk_text_view_style_set            (GtkWidget        *widget,
281                                                 GtkStyle         *previous_style);
282 static void gtk_text_view_direction_changed    (GtkWidget        *widget,
283                                                 GtkTextDirection  previous_direction);
284 static void gtk_text_view_grab_notify          (GtkWidget        *widget,
285                                                 gboolean         was_grabbed);
286 static void gtk_text_view_state_changed        (GtkWidget        *widget,
287                                                 GtkStateType      previous_state);
288
289 static gint gtk_text_view_event                (GtkWidget        *widget,
290                                                 GdkEvent         *event);
291 static gint gtk_text_view_key_press_event      (GtkWidget        *widget,
292                                                 GdkEventKey      *event);
293 static gint gtk_text_view_key_release_event    (GtkWidget        *widget,
294                                                 GdkEventKey      *event);
295 static gint gtk_text_view_button_press_event   (GtkWidget        *widget,
296                                                 GdkEventButton   *event);
297 static gint gtk_text_view_button_release_event (GtkWidget        *widget,
298                                                 GdkEventButton   *event);
299 static gint gtk_text_view_focus_in_event       (GtkWidget        *widget,
300                                                 GdkEventFocus    *event);
301 static gint gtk_text_view_focus_out_event      (GtkWidget        *widget,
302                                                 GdkEventFocus    *event);
303 static gint gtk_text_view_motion_event         (GtkWidget        *widget,
304                                                 GdkEventMotion   *event);
305 static gint gtk_text_view_expose_event         (GtkWidget        *widget,
306                                                 GdkEventExpose   *expose);
307 static void gtk_text_view_draw_focus           (GtkWidget        *widget);
308 static gboolean gtk_text_view_focus            (GtkWidget        *widget,
309                                                 GtkDirectionType  direction);
310 static void gtk_text_view_move_focus           (GtkWidget        *widget,
311                                                 GtkDirectionType  direction_type);
312 static void gtk_text_view_select_all           (GtkWidget        *widget,
313                                                 gboolean          select);
314
315
316 /* Source side drag signals */
317 static void gtk_text_view_drag_begin       (GtkWidget        *widget,
318                                             GdkDragContext   *context);
319 static void gtk_text_view_drag_end         (GtkWidget        *widget,
320                                             GdkDragContext   *context);
321 static void gtk_text_view_drag_data_get    (GtkWidget        *widget,
322                                             GdkDragContext   *context,
323                                             GtkSelectionData *selection_data,
324                                             guint             info,
325                                             guint             time);
326 static void gtk_text_view_drag_data_delete (GtkWidget        *widget,
327                                             GdkDragContext   *context);
328
329 /* Target side drag signals */
330 static void     gtk_text_view_drag_leave         (GtkWidget        *widget,
331                                                   GdkDragContext   *context,
332                                                   guint             time);
333 static gboolean gtk_text_view_drag_motion        (GtkWidget        *widget,
334                                                   GdkDragContext   *context,
335                                                   gint              x,
336                                                   gint              y,
337                                                   guint             time);
338 static gboolean gtk_text_view_drag_drop          (GtkWidget        *widget,
339                                                   GdkDragContext   *context,
340                                                   gint              x,
341                                                   gint              y,
342                                                   guint             time);
343 static void     gtk_text_view_drag_data_received (GtkWidget        *widget,
344                                                   GdkDragContext   *context,
345                                                   gint              x,
346                                                   gint              y,
347                                                   GtkSelectionData *selection_data,
348                                                   guint             info,
349                                                   guint             time);
350
351 static void gtk_text_view_set_scroll_adjustments (GtkTextView   *text_view,
352                                                   GtkAdjustment *hadj,
353                                                   GtkAdjustment *vadj);
354 static gboolean gtk_text_view_popup_menu         (GtkWidget     *widget);
355
356 static void gtk_text_view_move_cursor       (GtkTextView           *text_view,
357                                              GtkMovementStep        step,
358                                              gint                   count,
359                                              gboolean               extend_selection);
360 static gboolean gtk_text_view_move_viewport (GtkTextView           *text_view,
361                                              GtkScrollStep          step,
362                                              gint                   count);
363 static void gtk_text_view_set_anchor       (GtkTextView           *text_view);
364 static gboolean gtk_text_view_scroll_pages (GtkTextView           *text_view,
365                                             gint                   count,
366                                             gboolean               extend_selection);
367 static gboolean gtk_text_view_scroll_hpages(GtkTextView           *text_view,
368                                             gint                   count,
369                                             gboolean               extend_selection);
370 static void gtk_text_view_insert_at_cursor (GtkTextView           *text_view,
371                                             const gchar           *str);
372 static void gtk_text_view_delete_from_cursor (GtkTextView           *text_view,
373                                               GtkDeleteType          type,
374                                               gint                   count);
375 static void gtk_text_view_backspace        (GtkTextView           *text_view);
376 static void gtk_text_view_cut_clipboard    (GtkTextView           *text_view);
377 static void gtk_text_view_copy_clipboard   (GtkTextView           *text_view);
378 static void gtk_text_view_paste_clipboard  (GtkTextView           *text_view);
379 static void gtk_text_view_toggle_overwrite (GtkTextView           *text_view);
380 static void gtk_text_view_toggle_cursor_visible (GtkTextView      *text_view);
381 static void gtk_text_view_compat_move_focus(GtkTextView           *text_view,
382                                             GtkDirectionType       direction_type);
383 static void gtk_text_view_unselect         (GtkTextView           *text_view);
384
385 static void     gtk_text_view_validate_onscreen     (GtkTextView        *text_view);
386 static void     gtk_text_view_get_first_para_iter   (GtkTextView        *text_view,
387                                                      GtkTextIter        *iter);
388 static void     gtk_text_view_update_layout_width       (GtkTextView        *text_view);
389 static void     gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
390                                                          GtkTextAttributes *values,
391                                                          GtkStyle           *style);
392 static void     gtk_text_view_ensure_layout          (GtkTextView        *text_view);
393 static void     gtk_text_view_destroy_layout         (GtkTextView        *text_view);
394 static void     gtk_text_view_check_keymap_direction (GtkTextView        *text_view);
395 static void     gtk_text_view_start_selection_drag   (GtkTextView        *text_view,
396                                                       const GtkTextIter  *iter,
397                                                       GdkEventButton     *event);
398 static gboolean gtk_text_view_end_selection_drag     (GtkTextView        *text_view);
399 static void     gtk_text_view_start_selection_dnd    (GtkTextView        *text_view,
400                                                       const GtkTextIter  *iter,
401                                                       GdkEventMotion     *event);
402 static void     gtk_text_view_check_cursor_blink     (GtkTextView        *text_view);
403 static void     gtk_text_view_pend_cursor_blink      (GtkTextView        *text_view);
404 static void     gtk_text_view_stop_cursor_blink      (GtkTextView        *text_view);
405 static void     gtk_text_view_reset_blink_time       (GtkTextView        *text_view);
406
407 static void     gtk_text_view_value_changed                (GtkAdjustment *adj,
408                                                             GtkTextView   *view);
409 static void     gtk_text_view_commit_handler               (GtkIMContext  *context,
410                                                             const gchar   *str,
411                                                             GtkTextView   *text_view);
412 static void     gtk_text_view_commit_text                  (GtkTextView   *text_view,
413                                                             const gchar   *text);
414 static void     gtk_text_view_preedit_changed_handler      (GtkIMContext  *context,
415                                                             GtkTextView   *text_view);
416 static gboolean gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
417                                                             GtkTextView   *text_view);
418 static gboolean gtk_text_view_delete_surrounding_handler   (GtkIMContext  *context,
419                                                             gint           offset,
420                                                             gint           n_chars,
421                                                             GtkTextView   *text_view);
422
423 static void gtk_text_view_mark_set_handler       (GtkTextBuffer     *buffer,
424                                                   const GtkTextIter *location,
425                                                   GtkTextMark       *mark,
426                                                   gpointer           data);
427 static void gtk_text_view_target_list_notify     (GtkTextBuffer     *buffer,
428                                                   const GParamSpec  *pspec,
429                                                   gpointer           data);
430 static void gtk_text_view_paste_done_handler     (GtkTextBuffer     *buffer,
431                                                   GtkClipboard      *clipboard,
432                                                   gpointer           data);
433 static void gtk_text_view_get_cursor_location    (GtkTextView       *text_view,
434                                                   GdkRectangle      *pos);
435 static void gtk_text_view_get_virtual_cursor_pos (GtkTextView       *text_view,
436                                                   GtkTextIter       *cursor,
437                                                   gint              *x,
438                                                   gint              *y);
439 static void gtk_text_view_set_virtual_cursor_pos (GtkTextView       *text_view,
440                                                   gint               x,
441                                                   gint               y);
442
443 static GtkAdjustment* get_hadjustment            (GtkTextView       *text_view);
444 static GtkAdjustment* get_vadjustment            (GtkTextView       *text_view);
445
446 static void gtk_text_view_do_popup               (GtkTextView       *text_view,
447                                                   GdkEventButton    *event);
448
449 static void cancel_pending_scroll                (GtkTextView   *text_view);
450 static void gtk_text_view_queue_scroll           (GtkTextView   *text_view,
451                                                   GtkTextMark   *mark,
452                                                   gdouble        within_margin,
453                                                   gboolean       use_align,
454                                                   gdouble        xalign,
455                                                   gdouble        yalign);
456
457 static gboolean gtk_text_view_flush_scroll         (GtkTextView *text_view);
458 static void     gtk_text_view_update_adjustments   (GtkTextView *text_view);
459 static void     gtk_text_view_invalidate           (GtkTextView *text_view);
460 static void     gtk_text_view_flush_first_validate (GtkTextView *text_view);
461
462 static void gtk_text_view_update_im_spot_location (GtkTextView *text_view);
463
464 /* Container methods */
465 static void gtk_text_view_add    (GtkContainer *container,
466                                   GtkWidget    *child);
467 static void gtk_text_view_remove (GtkContainer *container,
468                                   GtkWidget    *child);
469 static void gtk_text_view_forall (GtkContainer *container,
470                                   gboolean      include_internals,
471                                   GtkCallback   callback,
472                                   gpointer      callback_data);
473
474 /* FIXME probably need the focus methods. */
475
476 typedef struct _GtkTextViewChild GtkTextViewChild;
477
478 struct _GtkTextViewChild
479 {
480   GtkWidget *widget;
481
482   GtkTextChildAnchor *anchor;
483
484   gint from_top_of_line;
485   gint from_left_of_buffer;
486   
487   /* These are ignored if anchor != NULL */
488   GtkTextWindowType type;
489   gint x;
490   gint y;
491 };
492
493 static GtkTextViewChild* text_view_child_new_anchored      (GtkWidget          *child,
494                                                             GtkTextChildAnchor *anchor,
495                                                             GtkTextLayout      *layout);
496 static GtkTextViewChild* text_view_child_new_window        (GtkWidget          *child,
497                                                             GtkTextWindowType   type,
498                                                             gint                x,
499                                                             gint                y);
500 static void              text_view_child_free              (GtkTextViewChild   *child);
501 static void              text_view_child_set_parent_window (GtkTextView        *text_view,
502                                                             GtkTextViewChild   *child);
503
504 struct _GtkTextWindow
505 {
506   GtkTextWindowType type;
507   GtkWidget *widget;
508   GdkWindow *window;
509   GdkWindow *bin_window;
510   GtkRequisition requisition;
511   GdkRectangle allocation;
512 };
513
514 static GtkTextWindow *text_window_new             (GtkTextWindowType  type,
515                                                    GtkWidget         *widget,
516                                                    gint               width_request,
517                                                    gint               height_request);
518 static void           text_window_free            (GtkTextWindow     *win);
519 static void           text_window_realize         (GtkTextWindow     *win,
520                                                    GtkWidget         *widget);
521 static void           text_window_unrealize       (GtkTextWindow     *win);
522 static void           text_window_size_allocate   (GtkTextWindow     *win,
523                                                    GdkRectangle      *rect);
524 static void           text_window_scroll          (GtkTextWindow     *win,
525                                                    gint               dx,
526                                                    gint               dy);
527 static void           text_window_invalidate_rect (GtkTextWindow     *win,
528                                                    GdkRectangle      *rect);
529 static void           text_window_invalidate_cursors (GtkTextWindow  *win);
530
531 static gint           text_window_get_width       (GtkTextWindow     *win);
532 static gint           text_window_get_height      (GtkTextWindow     *win);
533
534
535 static guint signals[LAST_SIGNAL] = { 0 };
536
537 G_DEFINE_TYPE (GtkTextView, gtk_text_view, GTK_TYPE_CONTAINER)
538
539 static void
540 add_move_binding (GtkBindingSet  *binding_set,
541                   guint           keyval,
542                   guint           modmask,
543                   GtkMovementStep step,
544                   gint            count)
545 {
546   g_assert ((modmask & GDK_SHIFT_MASK) == 0);
547
548   gtk_binding_entry_add_signal (binding_set, keyval, modmask,
549                                 "move-cursor", 3,
550                                 G_TYPE_ENUM, step,
551                                 G_TYPE_INT, count,
552                                 G_TYPE_BOOLEAN, FALSE);
553
554   /* Selection-extending version */
555   gtk_binding_entry_add_signal (binding_set, keyval, modmask | GDK_SHIFT_MASK,
556                                 "move-cursor", 3,
557                                 G_TYPE_ENUM, step,
558                                 G_TYPE_INT, count,
559                                 G_TYPE_BOOLEAN, TRUE);
560 }
561
562 static void
563 gtk_text_view_class_init (GtkTextViewClass *klass)
564 {
565   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
566   GtkObjectClass *object_class = GTK_OBJECT_CLASS (klass);
567   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
568   GtkContainerClass *container_class = GTK_CONTAINER_CLASS (klass);
569   GtkBindingSet *binding_set;
570
571   /* Default handlers and virtual methods
572    */
573   gobject_class->set_property = gtk_text_view_set_property;
574   gobject_class->get_property = gtk_text_view_get_property;
575
576   object_class->destroy = gtk_text_view_destroy;
577   gobject_class->finalize = gtk_text_view_finalize;
578
579   widget_class->realize = gtk_text_view_realize;
580   widget_class->unrealize = gtk_text_view_unrealize;
581   widget_class->style_set = gtk_text_view_style_set;
582   widget_class->direction_changed = gtk_text_view_direction_changed;
583   widget_class->grab_notify = gtk_text_view_grab_notify;
584   widget_class->state_changed = gtk_text_view_state_changed;
585   widget_class->size_request = gtk_text_view_size_request;
586   widget_class->size_allocate = gtk_text_view_size_allocate;
587   widget_class->event = gtk_text_view_event;
588   widget_class->key_press_event = gtk_text_view_key_press_event;
589   widget_class->key_release_event = gtk_text_view_key_release_event;
590   widget_class->button_press_event = gtk_text_view_button_press_event;
591   widget_class->button_release_event = gtk_text_view_button_release_event;
592   widget_class->focus_in_event = gtk_text_view_focus_in_event;
593   widget_class->focus_out_event = gtk_text_view_focus_out_event;
594   widget_class->motion_notify_event = gtk_text_view_motion_event;
595   widget_class->expose_event = gtk_text_view_expose_event;
596   widget_class->focus = gtk_text_view_focus;
597
598   /* need to override the base class function via override_class_handler,
599    * because the signal slot is not available in GtkWidgetCLass
600    */
601   g_signal_override_class_handler ("move-focus",
602                                    GTK_TYPE_TEXT_VIEW,
603                                    G_CALLBACK (gtk_text_view_move_focus));
604
605   widget_class->drag_begin = gtk_text_view_drag_begin;
606   widget_class->drag_end = gtk_text_view_drag_end;
607   widget_class->drag_data_get = gtk_text_view_drag_data_get;
608   widget_class->drag_data_delete = gtk_text_view_drag_data_delete;
609
610   widget_class->drag_leave = gtk_text_view_drag_leave;
611   widget_class->drag_motion = gtk_text_view_drag_motion;
612   widget_class->drag_drop = gtk_text_view_drag_drop;
613   widget_class->drag_data_received = gtk_text_view_drag_data_received;
614
615   widget_class->popup_menu = gtk_text_view_popup_menu;
616   
617   container_class->add = gtk_text_view_add;
618   container_class->remove = gtk_text_view_remove;
619   container_class->forall = gtk_text_view_forall;
620
621   klass->move_cursor = gtk_text_view_move_cursor;
622   klass->set_anchor = gtk_text_view_set_anchor;
623   klass->insert_at_cursor = gtk_text_view_insert_at_cursor;
624   klass->delete_from_cursor = gtk_text_view_delete_from_cursor;
625   klass->backspace = gtk_text_view_backspace;
626   klass->cut_clipboard = gtk_text_view_cut_clipboard;
627   klass->copy_clipboard = gtk_text_view_copy_clipboard;
628   klass->paste_clipboard = gtk_text_view_paste_clipboard;
629   klass->toggle_overwrite = gtk_text_view_toggle_overwrite;
630   klass->move_focus = gtk_text_view_compat_move_focus;
631   klass->set_scroll_adjustments = gtk_text_view_set_scroll_adjustments;
632
633   /*
634    * Properties
635    */
636  
637   g_object_class_install_property (gobject_class,
638                                    PROP_PIXELS_ABOVE_LINES,
639                                    g_param_spec_int ("pixels-above-lines",
640                                                      P_("Pixels Above Lines"),
641                                                      P_("Pixels of blank space above paragraphs"),
642                                                      0,
643                                                      G_MAXINT,
644                                                      0,
645                                                      GTK_PARAM_READWRITE));
646  
647   g_object_class_install_property (gobject_class,
648                                    PROP_PIXELS_BELOW_LINES,
649                                    g_param_spec_int ("pixels-below-lines",
650                                                      P_("Pixels Below Lines"),
651                                                      P_("Pixels of blank space below paragraphs"),
652                                                      0,
653                                                      G_MAXINT,
654                                                      0,
655                                                      GTK_PARAM_READWRITE));
656  
657   g_object_class_install_property (gobject_class,
658                                    PROP_PIXELS_INSIDE_WRAP,
659                                    g_param_spec_int ("pixels-inside-wrap",
660                                                      P_("Pixels Inside Wrap"),
661                                                      P_("Pixels of blank space between wrapped lines in a paragraph"),
662                                                      0,
663                                                      G_MAXINT,
664                                                      0,
665                                                      GTK_PARAM_READWRITE));
666
667   g_object_class_install_property (gobject_class,
668                                    PROP_EDITABLE,
669                                    g_param_spec_boolean ("editable",
670                                                          P_("Editable"),
671                                                          P_("Whether the text can be modified by the user"),
672                                                          TRUE,
673                                                          GTK_PARAM_READWRITE));
674
675   g_object_class_install_property (gobject_class,
676                                    PROP_WRAP_MODE,
677                                    g_param_spec_enum ("wrap-mode",
678                                                       P_("Wrap Mode"),
679                                                       P_("Whether to wrap lines never, at word boundaries, or at character boundaries"),
680                                                       GTK_TYPE_WRAP_MODE,
681                                                       GTK_WRAP_NONE,
682                                                       GTK_PARAM_READWRITE));
683  
684   g_object_class_install_property (gobject_class,
685                                    PROP_JUSTIFICATION,
686                                    g_param_spec_enum ("justification",
687                                                       P_("Justification"),
688                                                       P_("Left, right, or center justification"),
689                                                       GTK_TYPE_JUSTIFICATION,
690                                                       GTK_JUSTIFY_LEFT,
691                                                       GTK_PARAM_READWRITE));
692  
693   g_object_class_install_property (gobject_class,
694                                    PROP_LEFT_MARGIN,
695                                    g_param_spec_int ("left-margin",
696                                                      P_("Left Margin"),
697                                                      P_("Width of the left margin in pixels"),
698                                                      0,
699                                                      G_MAXINT,
700                                                      0,
701                                                      GTK_PARAM_READWRITE));
702
703   g_object_class_install_property (gobject_class,
704                                    PROP_RIGHT_MARGIN,
705                                    g_param_spec_int ("right-margin",
706                                                      P_("Right Margin"),
707                                                      P_("Width of the right margin in pixels"),
708                                                      0,
709                                                      G_MAXINT,
710                                                      0,
711                                                      GTK_PARAM_READWRITE));
712
713   g_object_class_install_property (gobject_class,
714                                    PROP_INDENT,
715                                    g_param_spec_int ("indent",
716                                                      P_("Indent"),
717                                                      P_("Amount to indent the paragraph, in pixels"),
718                                                      G_MININT,
719                                                      G_MAXINT,
720                                                      0,
721                                                      GTK_PARAM_READWRITE));
722
723   g_object_class_install_property (gobject_class,
724                                    PROP_TABS,
725                                    g_param_spec_boxed ("tabs",
726                                                        P_("Tabs"),
727                                                        P_("Custom tabs for this text"),
728                                                        PANGO_TYPE_TAB_ARRAY,
729                                                        GTK_PARAM_READWRITE));
730
731   g_object_class_install_property (gobject_class,
732                                    PROP_CURSOR_VISIBLE,
733                                    g_param_spec_boolean ("cursor-visible",
734                                                          P_("Cursor Visible"),
735                                                          P_("If the insertion cursor is shown"),
736                                                          TRUE,
737                                                          GTK_PARAM_READWRITE));
738
739   g_object_class_install_property (gobject_class,
740                                    PROP_BUFFER,
741                                    g_param_spec_object ("buffer",
742                                                         P_("Buffer"),
743                                                         P_("The buffer which is displayed"),
744                                                         GTK_TYPE_TEXT_BUFFER,
745                                                         GTK_PARAM_READWRITE));
746
747   g_object_class_install_property (gobject_class,
748                                    PROP_OVERWRITE,
749                                    g_param_spec_boolean ("overwrite",
750                                                          P_("Overwrite mode"),
751                                                          P_("Whether entered text overwrites existing contents"),
752                                                          FALSE,
753                                                          GTK_PARAM_READWRITE));
754
755   g_object_class_install_property (gobject_class,
756                                    PROP_ACCEPTS_TAB,
757                                    g_param_spec_boolean ("accepts-tab",
758                                                          P_("Accepts tab"),
759                                                          P_("Whether Tab will result in a tab character being entered"),
760                                                          TRUE,
761                                                          GTK_PARAM_READWRITE));
762
763    /**
764     * GtkTextView:im-module:
765     *
766     * Which IM (input method) module should be used for this entry. 
767     * See #GtkIMContext.
768     *
769     * Setting this to a non-%NULL value overrides the
770     * system-wide IM module setting. See the GtkSettings 
771     * #GtkSettings:gtk-im-module property.
772     *
773     * Since: 2.16
774     */
775    g_object_class_install_property (gobject_class,
776                                     PROP_IM_MODULE,
777                                     g_param_spec_string ("im-module",
778                                                          P_("IM module"),
779                                                          P_("Which IM module should be used"),
780                                                          NULL,
781                                                          GTK_PARAM_READWRITE));
782
783   /*
784    * Style properties
785    */
786   gtk_widget_class_install_style_property (widget_class,
787                                            g_param_spec_boxed ("error-underline-color",
788                                                                P_("Error underline color"),
789                                                                P_("Color with which to draw error-indication underlines"),
790                                                                GDK_TYPE_COLOR,
791                                                                GTK_PARAM_READABLE));
792   
793   /*
794    * Signals
795    */
796
797   /**
798    * GtkTextView::move-cursor: 
799    * @text_view: the object which received the signal
800    * @step: the granularity of the move, as a #GtkMovementStep
801    * @count: the number of @step units to move
802    * @extend_selection: %TRUE if the move should extend the selection
803    *  
804    * The ::move-cursor signal is a 
805    * <link linkend="keybinding-signals">keybinding signal</link> 
806    * which gets emitted when the user initiates a cursor movement. 
807    * If the cursor is not visible in @text_view, this signal causes
808    * the viewport to be moved instead.
809    *
810    * Applications should not connect to it, but may emit it with 
811    * g_signal_emit_by_name() if they need to control the cursor
812    * programmatically.
813    *
814    * The default bindings for this signal come in two variants,
815    * the variant with the Shift modifier extends the selection,
816    * the variant without the Shift modifer does not.
817    * There are too many key combinations to list them all here.
818    * <itemizedlist>
819    * <listitem>Arrow keys move by individual characters/lines</listitem>
820    * <listitem>Ctrl-arrow key combinations move by words/paragraphs</listitem>
821    * <listitem>Home/End keys move to the ends of the buffer</listitem>
822    * <listitem>PageUp/PageDown keys move vertically by pages</listitem>
823    * <listitem>Ctrl-PageUp/PageDown keys move horizontally by pages</listitem>
824    * </itemizedlist>
825    */
826   signals[MOVE_CURSOR] = 
827     g_signal_new (I_("move-cursor"),
828                   G_OBJECT_CLASS_TYPE (gobject_class), 
829                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, 
830                   G_STRUCT_OFFSET (GtkTextViewClass, move_cursor),
831                   NULL, NULL, 
832                   _gtk_marshal_VOID__ENUM_INT_BOOLEAN, 
833                   G_TYPE_NONE, 3,
834                   GTK_TYPE_MOVEMENT_STEP, 
835                   G_TYPE_INT, 
836                   G_TYPE_BOOLEAN);
837
838   /**
839    * GtkTextView::move-viewport:
840    * @text_view: the object which received the signal
841    * @step: the granularity of the move, as a #GtkMovementStep
842    * @count: the number of @step units to move
843    *
844    * The ::move-viewport signal is a 
845    * <link linkend="keybinding-signals">keybinding signal</link> 
846    * which can be bound to key combinations to allow the user
847    * to move the viewport, i.e. change what part of the text view
848    * is visible in a containing scrolled window.
849    *
850    * There are no default bindings for this signal.
851    */
852   signals[MOVE_VIEWPORT] =
853     g_signal_new_class_handler (I_("move-viewport"),
854                                 G_OBJECT_CLASS_TYPE (gobject_class),
855                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
856                                 G_CALLBACK (gtk_text_view_move_viewport),
857                                 NULL, NULL,
858                                 _gtk_marshal_VOID__ENUM_INT,
859                                 G_TYPE_NONE, 2,
860                                 GTK_TYPE_SCROLL_STEP,
861                                 G_TYPE_INT);
862
863   /**
864    * GtkTextView::set-anchor:
865    * @text_view: the object which received the signal
866    *
867    * The ::set-anchor signal is a
868    * <link linkend="keybinding-signals">keybinding signal</link>
869    * which gets emitted when the user initiates setting the "anchor" 
870    * mark. The "anchor" mark gets placed at the same position as the
871    * "insert" mark.
872    *
873    * This signal has no default bindings.
874    */   
875   signals[SET_ANCHOR] =
876     g_signal_new (I_("set-anchor"),
877                   G_OBJECT_CLASS_TYPE (gobject_class),
878                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
879                   G_STRUCT_OFFSET (GtkTextViewClass, set_anchor),
880                   NULL, NULL,
881                   _gtk_marshal_VOID__VOID,
882                   G_TYPE_NONE, 0);
883
884   /**
885    * GtkTextView::insert-at-cursor:
886    * @text_view: the object which received the signal
887    * @string: the string to insert
888    *
889    * The ::insert-at-cursor signal is a
890    * <link linkend="keybinding-signals">keybinding signal</link>
891    * which gets emitted when the user initiates the insertion of a 
892    * fixed string at the cursor.
893    *
894    * This signal has no default bindings.
895    */
896   signals[INSERT_AT_CURSOR] =
897     g_signal_new (I_("insert-at-cursor"),
898                   G_OBJECT_CLASS_TYPE (gobject_class),
899                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
900                   G_STRUCT_OFFSET (GtkTextViewClass, insert_at_cursor),
901                   NULL, NULL,
902                   _gtk_marshal_VOID__STRING,
903                   G_TYPE_NONE, 1,
904                   G_TYPE_STRING);
905
906   /**
907    * GtkTextView::delete-from-cursor:
908    * @text_view: the object which received the signal
909    * @type: the granularity of the deletion, as a #GtkDeleteType
910    * @count: the number of @type units to delete
911    *
912    * The ::delete-from-cursor signal is a 
913    * <link linkend="keybinding-signals">keybinding signal</link> 
914    * which gets emitted when the user initiates a text deletion.
915    *
916    * If the @type is %GTK_DELETE_CHARS, GTK+ deletes the selection
917    * if there is one, otherwise it deletes the requested number
918    * of characters.
919    *
920    * The default bindings for this signal are
921    * Delete for deleting a character, Ctrl-Delete for 
922    * deleting a word and Ctrl-Backspace for deleting a word 
923    * backwords.
924    */
925   signals[DELETE_FROM_CURSOR] =
926     g_signal_new (I_("delete-from-cursor"),
927                   G_OBJECT_CLASS_TYPE (gobject_class),
928                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
929                   G_STRUCT_OFFSET (GtkTextViewClass, delete_from_cursor),
930                   NULL, NULL,
931                   _gtk_marshal_VOID__ENUM_INT,
932                   G_TYPE_NONE, 2,
933                   GTK_TYPE_DELETE_TYPE,
934                   G_TYPE_INT);
935
936   /**
937    * GtkTextView::backspace:
938    * @text_view: the object which received the signal
939    *
940    * The ::backspace signal is a 
941    * <link linkend="keybinding-signals">keybinding signal</link> 
942    * which gets emitted when the user asks for it.
943    * 
944    * The default bindings for this signal are
945    * Backspace and Shift-Backspace.
946    */
947   signals[BACKSPACE] =
948     g_signal_new (I_("backspace"),
949                   G_OBJECT_CLASS_TYPE (gobject_class),
950                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
951                   G_STRUCT_OFFSET (GtkTextViewClass, backspace),
952                   NULL, NULL,
953                   _gtk_marshal_VOID__VOID,
954                   G_TYPE_NONE, 0);
955
956   /**
957    * GtkTextView::cut-clipboard:
958    * @text_view: the object which received the signal
959    *
960    * The ::cut-clipboard signal is a 
961    * <link linkend="keybinding-signals">keybinding signal</link> 
962    * which gets emitted to cut the selection to the clipboard.
963    * 
964    * The default bindings for this signal are
965    * Ctrl-x and Shift-Delete.
966    */
967   signals[CUT_CLIPBOARD] =
968     g_signal_new (I_("cut-clipboard"),
969                   G_OBJECT_CLASS_TYPE (gobject_class),
970                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
971                   G_STRUCT_OFFSET (GtkTextViewClass, cut_clipboard),
972                   NULL, NULL,
973                   _gtk_marshal_VOID__VOID,
974                   G_TYPE_NONE, 0);
975
976   /**
977    * GtkTextView::copy-clipboard:
978    * @text_view: the object which received the signal
979    *
980    * The ::copy-clipboard signal is a 
981    * <link linkend="keybinding-signals">keybinding signal</link> 
982    * which gets emitted to copy the selection to the clipboard.
983    * 
984    * The default bindings for this signal are
985    * Ctrl-c and Ctrl-Insert.
986    */
987   signals[COPY_CLIPBOARD] =
988     g_signal_new (I_("copy-clipboard"),
989                   G_OBJECT_CLASS_TYPE (gobject_class),
990                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
991                   G_STRUCT_OFFSET (GtkTextViewClass, copy_clipboard),
992                   NULL, NULL,
993                   _gtk_marshal_VOID__VOID,
994                   G_TYPE_NONE, 0);
995
996   /**
997    * GtkTextView::paste-clipboard:
998    * @text_view: the object which received the signal
999    *
1000    * The ::paste-clipboard signal is a 
1001    * <link linkend="keybinding-signals">keybinding signal</link> 
1002    * which gets emitted to paste the contents of the clipboard 
1003    * into the text view.
1004    * 
1005    * The default bindings for this signal are
1006    * Ctrl-v and Shift-Insert.
1007    */
1008   signals[PASTE_CLIPBOARD] =
1009     g_signal_new (I_("paste-clipboard"),
1010                   G_OBJECT_CLASS_TYPE (gobject_class),
1011                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1012                   G_STRUCT_OFFSET (GtkTextViewClass, paste_clipboard),
1013                   NULL, NULL,
1014                   _gtk_marshal_VOID__VOID,
1015                   G_TYPE_NONE, 0);
1016
1017   /**
1018    * GtkTextView::toggle-overwrite:
1019    * @text_view: the object which received the signal
1020    *
1021    * The ::toggle-overwrite signal is a 
1022    * <link linkend="keybinding-signals">keybinding signal</link> 
1023    * which gets emitted to toggle the overwrite mode of the text view.
1024    * 
1025    * The default bindings for this signal is Insert.
1026    */ 
1027   signals[TOGGLE_OVERWRITE] =
1028     g_signal_new (I_("toggle-overwrite"),
1029                   G_OBJECT_CLASS_TYPE (gobject_class),
1030                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1031                   G_STRUCT_OFFSET (GtkTextViewClass, toggle_overwrite),
1032                   NULL, NULL,
1033                   _gtk_marshal_VOID__VOID,
1034                   G_TYPE_NONE, 0);
1035
1036   /**
1037    * GtkTextView::set-scroll-adjustments
1038    * @horizontal: the horizontal #GtkAdjustment
1039    * @vertical: the vertical #GtkAdjustment
1040    *
1041    * Set the scroll adjustments for the text view. Usually scrolled containers
1042    * like #GtkScrolledWindow will emit this signal to connect two instances
1043    * of #GtkScrollbar to the scroll directions of the #GtkTextView.
1044    */
1045   signals[SET_SCROLL_ADJUSTMENTS] =
1046     g_signal_new (I_("set-scroll-adjustments"),
1047                   G_OBJECT_CLASS_TYPE (gobject_class),
1048                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1049                   G_STRUCT_OFFSET (GtkTextViewClass, set_scroll_adjustments),
1050                   NULL, NULL,
1051                   _gtk_marshal_VOID__OBJECT_OBJECT,
1052                   G_TYPE_NONE, 2,
1053                   GTK_TYPE_ADJUSTMENT,
1054                   GTK_TYPE_ADJUSTMENT);
1055   widget_class->set_scroll_adjustments_signal = signals[SET_SCROLL_ADJUSTMENTS];
1056
1057   /**
1058    * GtkTextView::populate-popup:
1059    * @entry: The text view on which the signal is emitted
1060    * @menu: the menu that is being populated
1061    *
1062    * The ::populate-popup signal gets emitted before showing the 
1063    * context menu of the text view.
1064    *
1065    * If you need to add items to the context menu, connect
1066    * to this signal and append your menuitems to the @menu.
1067    */
1068   signals[POPULATE_POPUP] =
1069     g_signal_new (I_("populate-popup"),
1070                   G_OBJECT_CLASS_TYPE (gobject_class),
1071                   G_SIGNAL_RUN_LAST,
1072                   G_STRUCT_OFFSET (GtkTextViewClass, populate_popup),
1073                   NULL, NULL,
1074                   _gtk_marshal_VOID__OBJECT,
1075                   G_TYPE_NONE, 1,
1076                   GTK_TYPE_MENU);
1077   
1078   /**
1079    * GtkTextView::select-all:
1080    * @text_view: the object which received the signal
1081    * @select: %TRUE to select, %FALSE to unselect
1082    *
1083    * The ::select-all signal is a 
1084    * <link linkend="keybinding-signals">keybinding signal</link> 
1085    * which gets emitted to select or unselect the complete
1086    * contents of the text view.
1087    *
1088    * The default bindings for this signal are Ctrl-a and Ctrl-/ 
1089    * for selecting and Shift-Ctrl-a and Ctrl-\ for unselecting.
1090    */
1091   signals[SELECT_ALL] =
1092     g_signal_new_class_handler (I_("select-all"),
1093                                 G_OBJECT_CLASS_TYPE (object_class),
1094                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1095                                 G_CALLBACK (gtk_text_view_select_all),
1096                                 NULL, NULL,
1097                                 _gtk_marshal_VOID__BOOLEAN,
1098                                 G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
1099
1100   /**
1101    * GtkTextView::toggle-cursor-visible:
1102    * @text_view: the object which received the signal
1103    *
1104    * The ::toggle-cursor-visible signal is a 
1105    * <link linkend="keybinding-signals">keybinding signal</link> 
1106    * which gets emitted to toggle the visibility of the cursor.
1107    *
1108    * The default binding for this signal is F7.
1109    */ 
1110   signals[TOGGLE_CURSOR_VISIBLE] =
1111     g_signal_new_class_handler (I_("toggle-cursor-visible"),
1112                                 G_OBJECT_CLASS_TYPE (object_class),
1113                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1114                                 G_CALLBACK (gtk_text_view_toggle_cursor_visible),
1115                                 NULL, NULL,
1116                                 _gtk_marshal_VOID__VOID,
1117                                 G_TYPE_NONE, 0);
1118
1119   /**
1120    * GtkTextView::preedit-changed:
1121    * @text_view: the object which received the signal
1122    * @preedit: the current preedit string
1123    *
1124    * If an input method is used, the typed text will not immediately
1125    * be committed to the buffer. So if you are interested in the text,
1126    * connect to this signal.
1127    *
1128    * This signal is only emitted if the text at the given position
1129    * is actually editable.
1130    *
1131    * Since: 2.20
1132    */
1133   signals[PREEDIT_CHANGED] =
1134     g_signal_new_class_handler (I_("preedit-changed"),
1135                                 G_OBJECT_CLASS_TYPE (object_class),
1136                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1137                                 NULL,
1138                                 NULL, NULL,
1139                                 _gtk_marshal_VOID__STRING,
1140                                 G_TYPE_NONE, 1,
1141                                 G_TYPE_STRING);
1142
1143   /*
1144    * Key bindings
1145    */
1146
1147   binding_set = gtk_binding_set_by_class (klass);
1148   
1149   /* Moving the insertion point */
1150   add_move_binding (binding_set, GDK_KEY_Right, 0,
1151                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
1152
1153   add_move_binding (binding_set, GDK_KEY_KP_Right, 0,
1154                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
1155   
1156   add_move_binding (binding_set, GDK_KEY_Left, 0,
1157                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
1158
1159   add_move_binding (binding_set, GDK_KEY_KP_Left, 0,
1160                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
1161   
1162   add_move_binding (binding_set, GDK_KEY_Right, GDK_CONTROL_MASK,
1163                     GTK_MOVEMENT_WORDS, 1);
1164
1165   add_move_binding (binding_set, GDK_KEY_KP_Right, GDK_CONTROL_MASK,
1166                     GTK_MOVEMENT_WORDS, 1);
1167   
1168   add_move_binding (binding_set, GDK_KEY_Left, GDK_CONTROL_MASK,
1169                     GTK_MOVEMENT_WORDS, -1);
1170
1171   add_move_binding (binding_set, GDK_KEY_KP_Left, GDK_CONTROL_MASK,
1172                     GTK_MOVEMENT_WORDS, -1);
1173   
1174   add_move_binding (binding_set, GDK_KEY_Up, 0,
1175                     GTK_MOVEMENT_DISPLAY_LINES, -1);
1176
1177   add_move_binding (binding_set, GDK_KEY_KP_Up, 0,
1178                     GTK_MOVEMENT_DISPLAY_LINES, -1);
1179   
1180   add_move_binding (binding_set, GDK_KEY_Down, 0,
1181                     GTK_MOVEMENT_DISPLAY_LINES, 1);
1182
1183   add_move_binding (binding_set, GDK_KEY_KP_Down, 0,
1184                     GTK_MOVEMENT_DISPLAY_LINES, 1);
1185   
1186   add_move_binding (binding_set, GDK_KEY_Up, GDK_CONTROL_MASK,
1187                     GTK_MOVEMENT_PARAGRAPHS, -1);
1188
1189   add_move_binding (binding_set, GDK_KEY_KP_Up, GDK_CONTROL_MASK,
1190                     GTK_MOVEMENT_PARAGRAPHS, -1);
1191   
1192   add_move_binding (binding_set, GDK_KEY_Down, GDK_CONTROL_MASK,
1193                     GTK_MOVEMENT_PARAGRAPHS, 1);
1194
1195   add_move_binding (binding_set, GDK_KEY_KP_Down, GDK_CONTROL_MASK,
1196                     GTK_MOVEMENT_PARAGRAPHS, 1);
1197   
1198   add_move_binding (binding_set, GDK_KEY_Home, 0,
1199                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
1200
1201   add_move_binding (binding_set, GDK_KEY_KP_Home, 0,
1202                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
1203   
1204   add_move_binding (binding_set, GDK_KEY_End, 0,
1205                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
1206
1207   add_move_binding (binding_set, GDK_KEY_KP_End, 0,
1208                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
1209   
1210   add_move_binding (binding_set, GDK_KEY_Home, GDK_CONTROL_MASK,
1211                     GTK_MOVEMENT_BUFFER_ENDS, -1);
1212
1213   add_move_binding (binding_set, GDK_KEY_KP_Home, GDK_CONTROL_MASK,
1214                     GTK_MOVEMENT_BUFFER_ENDS, -1);
1215   
1216   add_move_binding (binding_set, GDK_KEY_End, GDK_CONTROL_MASK,
1217                     GTK_MOVEMENT_BUFFER_ENDS, 1);
1218
1219   add_move_binding (binding_set, GDK_KEY_KP_End, GDK_CONTROL_MASK,
1220                     GTK_MOVEMENT_BUFFER_ENDS, 1);
1221   
1222   add_move_binding (binding_set, GDK_KEY_Page_Up, 0,
1223                     GTK_MOVEMENT_PAGES, -1);
1224
1225   add_move_binding (binding_set, GDK_KEY_KP_Page_Up, 0,
1226                     GTK_MOVEMENT_PAGES, -1);
1227   
1228   add_move_binding (binding_set, GDK_KEY_Page_Down, 0,
1229                     GTK_MOVEMENT_PAGES, 1);
1230
1231   add_move_binding (binding_set, GDK_KEY_KP_Page_Down, 0,
1232                     GTK_MOVEMENT_PAGES, 1);
1233
1234   add_move_binding (binding_set, GDK_KEY_Page_Up, GDK_CONTROL_MASK,
1235                     GTK_MOVEMENT_HORIZONTAL_PAGES, -1);
1236
1237   add_move_binding (binding_set, GDK_KEY_KP_Page_Up, GDK_CONTROL_MASK,
1238                     GTK_MOVEMENT_HORIZONTAL_PAGES, -1);
1239   
1240   add_move_binding (binding_set, GDK_KEY_Page_Down, GDK_CONTROL_MASK,
1241                     GTK_MOVEMENT_HORIZONTAL_PAGES, 1);
1242
1243   add_move_binding (binding_set, GDK_KEY_KP_Page_Down, GDK_CONTROL_MASK,
1244                     GTK_MOVEMENT_HORIZONTAL_PAGES, 1);
1245
1246   /* Select all */
1247   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_CONTROL_MASK,
1248                                 "select-all", 1,
1249                                 G_TYPE_BOOLEAN, TRUE);
1250
1251   gtk_binding_entry_add_signal (binding_set, GDK_KEY_slash, GDK_CONTROL_MASK,
1252                                 "select-all", 1,
1253                                 G_TYPE_BOOLEAN, TRUE);
1254   
1255   /* Unselect all */
1256   gtk_binding_entry_add_signal (binding_set, GDK_KEY_backslash, GDK_CONTROL_MASK,
1257                                  "select-all", 1,
1258                                  G_TYPE_BOOLEAN, FALSE);
1259
1260   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1261                                  "select-all", 1,
1262                                  G_TYPE_BOOLEAN, FALSE);
1263
1264   /* Deleting text */
1265   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, 0,
1266                                 "delete-from-cursor", 2,
1267                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
1268                                 G_TYPE_INT, 1);
1269
1270   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, 0,
1271                                 "delete-from-cursor", 2,
1272                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
1273                                 G_TYPE_INT, 1);
1274   
1275   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, 0,
1276                                 "backspace", 0);
1277
1278   /* Make this do the same as Backspace, to help with mis-typing */
1279   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_SHIFT_MASK,
1280                                 "backspace", 0);
1281
1282   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_CONTROL_MASK,
1283                                 "delete-from-cursor", 2,
1284                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1285                                 G_TYPE_INT, 1);
1286
1287   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, GDK_CONTROL_MASK,
1288                                 "delete-from-cursor", 2,
1289                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1290                                 G_TYPE_INT, 1);
1291   
1292   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_CONTROL_MASK,
1293                                 "delete-from-cursor", 2,
1294                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1295                                 G_TYPE_INT, -1);
1296
1297   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1298                                 "delete-from-cursor", 2,
1299                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1300                                 G_TYPE_INT, 1);
1301
1302   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1303                                 "delete-from-cursor", 2,
1304                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1305                                 G_TYPE_INT, 1);
1306
1307   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1308                                 "delete-from-cursor", 2,
1309                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1310                                 G_TYPE_INT, -1);
1311
1312   /* Cut/copy/paste */
1313
1314   gtk_binding_entry_add_signal (binding_set, GDK_KEY_x, GDK_CONTROL_MASK,
1315                                 "cut-clipboard", 0);
1316   gtk_binding_entry_add_signal (binding_set, GDK_KEY_c, GDK_CONTROL_MASK,
1317                                 "copy-clipboard", 0);
1318   gtk_binding_entry_add_signal (binding_set, GDK_KEY_v, GDK_CONTROL_MASK,
1319                                 "paste-clipboard", 0);
1320
1321   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_SHIFT_MASK,
1322                                 "cut-clipboard", 0);
1323   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, GDK_CONTROL_MASK,
1324                                 "copy-clipboard", 0);
1325   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, GDK_SHIFT_MASK,
1326                                 "paste-clipboard", 0);
1327
1328   /* Overwrite */
1329   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, 0,
1330                                 "toggle-overwrite", 0);
1331   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Insert, 0,
1332                                 "toggle-overwrite", 0);
1333
1334   /* Caret mode */
1335   gtk_binding_entry_add_signal (binding_set, GDK_KEY_F7, 0,
1336                                 "toggle-cursor-visible", 0);
1337
1338   /* Control-tab focus motion */
1339   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Tab, GDK_CONTROL_MASK,
1340                                 "move-focus", 1,
1341                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_FORWARD);
1342   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Tab, GDK_CONTROL_MASK,
1343                                 "move-focus", 1,
1344                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_FORWARD);
1345   
1346   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Tab, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1347                                 "move-focus", 1,
1348                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_BACKWARD);
1349   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Tab, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1350                                 "move-focus", 1,
1351                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_BACKWARD);
1352
1353   g_type_class_add_private (gobject_class, sizeof (GtkTextViewPrivate));
1354 }
1355
1356 static void
1357 gtk_text_view_init (GtkTextView *text_view)
1358 {
1359   GtkWidget *widget = GTK_WIDGET (text_view);
1360   GtkTargetList *target_list;
1361   GtkTextViewPrivate *priv;
1362
1363   text_view->priv = GTK_TEXT_VIEW_GET_PRIVATE (text_view);
1364   priv = text_view->priv;
1365
1366   gtk_widget_set_can_focus (widget, TRUE);
1367
1368   /* Set up default style */
1369   priv->wrap_mode = GTK_WRAP_NONE;
1370   priv->pixels_above_lines = 0;
1371   priv->pixels_below_lines = 0;
1372   priv->pixels_inside_wrap = 0;
1373   priv->justify = GTK_JUSTIFY_LEFT;
1374   priv->left_margin = 0;
1375   priv->right_margin = 0;
1376   priv->indent = 0;
1377   priv->tabs = NULL;
1378   priv->editable = TRUE;
1379
1380   priv->scroll_after_paste = TRUE;
1381
1382   gtk_drag_dest_set (widget, 0, NULL, 0,
1383                      GDK_ACTION_COPY | GDK_ACTION_MOVE);
1384
1385   target_list = gtk_target_list_new (NULL, 0);
1386   gtk_drag_dest_set_target_list (widget, target_list);
1387   gtk_target_list_unref (target_list);
1388
1389   priv->virtual_cursor_x = -1;
1390   priv->virtual_cursor_y = -1;
1391
1392   /* This object is completely private. No external entity can gain a reference
1393    * to it; so we create it here and destroy it in finalize ().
1394    */
1395   priv->im_context = gtk_im_multicontext_new ();
1396
1397   g_signal_connect (priv->im_context, "commit",
1398                     G_CALLBACK (gtk_text_view_commit_handler), text_view);
1399   g_signal_connect (priv->im_context, "preedit-changed",
1400                     G_CALLBACK (gtk_text_view_preedit_changed_handler), text_view);
1401   g_signal_connect (priv->im_context, "retrieve-surrounding",
1402                     G_CALLBACK (gtk_text_view_retrieve_surrounding_handler), text_view);
1403   g_signal_connect (priv->im_context, "delete-surrounding",
1404                     G_CALLBACK (gtk_text_view_delete_surrounding_handler), text_view);
1405
1406   priv->cursor_visible = TRUE;
1407
1408   priv->accepts_tab = TRUE;
1409
1410   priv->text_window = text_window_new (GTK_TEXT_WINDOW_TEXT,
1411                                        widget, 200, 200);
1412
1413   priv->drag_start_x = -1;
1414   priv->drag_start_y = -1;
1415
1416   priv->pending_place_cursor_button = 0;
1417
1418   /* We handle all our own redrawing */
1419   gtk_widget_set_redraw_on_allocate (widget, FALSE);
1420 }
1421
1422 /**
1423  * gtk_text_view_new:
1424  *
1425  * Creates a new #GtkTextView. If you don't call gtk_text_view_set_buffer()
1426  * before using the text view, an empty default buffer will be created
1427  * for you. Get the buffer with gtk_text_view_get_buffer(). If you want
1428  * to specify your own buffer, consider gtk_text_view_new_with_buffer().
1429  *
1430  * Return value: a new #GtkTextView
1431  **/
1432 GtkWidget*
1433 gtk_text_view_new (void)
1434 {
1435   return g_object_new (GTK_TYPE_TEXT_VIEW, NULL);
1436 }
1437
1438 /**
1439  * gtk_text_view_new_with_buffer:
1440  * @buffer: a #GtkTextBuffer
1441  *
1442  * Creates a new #GtkTextView widget displaying the buffer
1443  * @buffer. One buffer can be shared among many widgets.
1444  * @buffer may be %NULL to create a default buffer, in which case
1445  * this function is equivalent to gtk_text_view_new(). The
1446  * text view adds its own reference count to the buffer; it does not
1447  * take over an existing reference.
1448  *
1449  * Return value: a new #GtkTextView.
1450  **/
1451 GtkWidget*
1452 gtk_text_view_new_with_buffer (GtkTextBuffer *buffer)
1453 {
1454   GtkTextView *text_view;
1455
1456   text_view = (GtkTextView*)gtk_text_view_new ();
1457
1458   gtk_text_view_set_buffer (text_view, buffer);
1459
1460   return GTK_WIDGET (text_view);
1461 }
1462
1463 /**
1464  * gtk_text_view_set_buffer:
1465  * @text_view: a #GtkTextView
1466  * @buffer: (allow-none): a #GtkTextBuffer
1467  *
1468  * Sets @buffer as the buffer being displayed by @text_view. The previous
1469  * buffer displayed by the text view is unreferenced, and a reference is
1470  * added to @buffer. If you owned a reference to @buffer before passing it
1471  * to this function, you must remove that reference yourself; #GtkTextView
1472  * will not "adopt" it.
1473  **/
1474 void
1475 gtk_text_view_set_buffer (GtkTextView   *text_view,
1476                           GtkTextBuffer *buffer)
1477 {
1478   GtkTextViewPrivate *priv;
1479
1480   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1481   g_return_if_fail (buffer == NULL || GTK_IS_TEXT_BUFFER (buffer));
1482
1483   priv = text_view->priv;
1484
1485   if (priv->buffer == buffer)
1486     return;
1487
1488   if (priv->buffer != NULL)
1489     {
1490       /* Destroy all anchored children */
1491       GSList *tmp_list;
1492       GSList *copy;
1493
1494       copy = g_slist_copy (priv->children);
1495       tmp_list = copy;
1496       while (tmp_list != NULL)
1497         {
1498           GtkTextViewChild *vc = tmp_list->data;
1499
1500           if (vc->anchor)
1501             {
1502               gtk_widget_destroy (vc->widget);
1503               /* vc may now be invalid! */
1504             }
1505
1506           tmp_list = g_slist_next (tmp_list);
1507         }
1508
1509       g_slist_free (copy);
1510
1511       g_signal_handlers_disconnect_by_func (priv->buffer,
1512                                             gtk_text_view_mark_set_handler,
1513                                             text_view);
1514       g_signal_handlers_disconnect_by_func (priv->buffer,
1515                                             gtk_text_view_target_list_notify,
1516                                             text_view);
1517       g_signal_handlers_disconnect_by_func (priv->buffer,
1518                                             gtk_text_view_paste_done_handler,
1519                                             text_view);
1520
1521       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
1522         {
1523           GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
1524                                                               GDK_SELECTION_PRIMARY);
1525           gtk_text_buffer_remove_selection_clipboard (priv->buffer, clipboard);
1526         }
1527
1528       if (priv->layout)
1529         gtk_text_layout_set_buffer (priv->layout, NULL);
1530
1531       g_object_unref (priv->buffer);
1532       priv->dnd_mark = NULL;
1533       priv->first_para_mark = NULL;
1534       cancel_pending_scroll (text_view);
1535     }
1536
1537   priv->buffer = buffer;
1538
1539   if (priv->layout)
1540     gtk_text_layout_set_buffer (priv->layout, buffer);
1541
1542   if (buffer != NULL)
1543     {
1544       GtkTextIter start;
1545
1546       g_object_ref (buffer);
1547
1548       gtk_text_buffer_get_iter_at_offset (priv->buffer, &start, 0);
1549
1550       priv->dnd_mark = gtk_text_buffer_create_mark (priv->buffer,
1551                                                     "gtk_drag_target",
1552                                                     &start, FALSE);
1553
1554       priv->first_para_mark = gtk_text_buffer_create_mark (priv->buffer,
1555                                                            NULL,
1556                                                            &start, TRUE);
1557
1558       priv->first_para_pixels = 0;
1559
1560
1561       g_signal_connect (priv->buffer, "mark-set",
1562                         G_CALLBACK (gtk_text_view_mark_set_handler),
1563                         text_view);
1564       g_signal_connect (priv->buffer, "notify::paste-target-list",
1565                         G_CALLBACK (gtk_text_view_target_list_notify),
1566                         text_view);
1567       g_signal_connect (priv->buffer, "paste-done",
1568                         G_CALLBACK (gtk_text_view_paste_done_handler),
1569                         text_view);
1570
1571       gtk_text_view_target_list_notify (priv->buffer, NULL, text_view);
1572
1573       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
1574         {
1575           GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
1576                                                               GDK_SELECTION_PRIMARY);
1577           gtk_text_buffer_add_selection_clipboard (priv->buffer, clipboard);
1578         }
1579     }
1580
1581   g_object_notify (G_OBJECT (text_view), "buffer");
1582   
1583   if (gtk_widget_get_visible (GTK_WIDGET (text_view)))
1584     gtk_widget_queue_draw (GTK_WIDGET (text_view));
1585
1586   DV(g_print ("Invalidating due to set_buffer\n"));
1587   gtk_text_view_invalidate (text_view);
1588 }
1589
1590 static GtkTextBuffer*
1591 get_buffer (GtkTextView *text_view)
1592 {
1593   if (text_view->priv->buffer == NULL)
1594     {
1595       GtkTextBuffer *b;
1596       b = gtk_text_buffer_new (NULL);
1597       gtk_text_view_set_buffer (text_view, b);
1598       g_object_unref (b);
1599     }
1600
1601   return text_view->priv->buffer;
1602 }
1603
1604 /**
1605  * gtk_text_view_get_buffer:
1606  * @text_view: a #GtkTextView
1607  *
1608  * Returns the #GtkTextBuffer being displayed by this text view.
1609  * The reference count on the buffer is not incremented; the caller
1610  * of this function won't own a new reference.
1611  *
1612  * Return value: (transfer none): a #GtkTextBuffer
1613  **/
1614 GtkTextBuffer*
1615 gtk_text_view_get_buffer (GtkTextView *text_view)
1616 {
1617   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
1618
1619   return get_buffer (text_view);
1620 }
1621
1622 /**
1623  * gtk_text_view_get_iter_at_location:
1624  * @text_view: a #GtkTextView
1625  * @iter: (out): a #GtkTextIter
1626  * @x: x position, in buffer coordinates
1627  * @y: y position, in buffer coordinates
1628  *
1629  * Retrieves the iterator at buffer coordinates @x and @y. Buffer
1630  * coordinates are coordinates for the entire buffer, not just the
1631  * currently-displayed portion.  If you have coordinates from an
1632  * event, you have to convert those to buffer coordinates with
1633  * gtk_text_view_window_to_buffer_coords().
1634  **/
1635 void
1636 gtk_text_view_get_iter_at_location (GtkTextView *text_view,
1637                                     GtkTextIter *iter,
1638                                     gint         x,
1639                                     gint         y)
1640 {
1641   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1642   g_return_if_fail (iter != NULL);
1643
1644   gtk_text_view_ensure_layout (text_view);
1645   
1646   gtk_text_layout_get_iter_at_pixel (text_view->priv->layout,
1647                                      iter, x, y);
1648 }
1649
1650 /**
1651  * gtk_text_view_get_iter_at_position:
1652  * @text_view: a #GtkTextView
1653  * @iter: (out): a #GtkTextIter
1654  * @trailing: (out) (allow-none): if non-%NULL, location to store an integer indicating where
1655  *    in the grapheme the user clicked. It will either be
1656  *    zero, or the number of characters in the grapheme. 
1657  *    0 represents the trailing edge of the grapheme.
1658  * @x: x position, in buffer coordinates
1659  * @y: y position, in buffer coordinates
1660  *
1661  * Retrieves the iterator pointing to the character at buffer 
1662  * coordinates @x and @y. Buffer coordinates are coordinates for 
1663  * the entire buffer, not just the currently-displayed portion.  
1664  * If you have coordinates from an event, you have to convert 
1665  * those to buffer coordinates with 
1666  * gtk_text_view_window_to_buffer_coords().
1667  *
1668  * Note that this is different from gtk_text_view_get_iter_at_location(),
1669  * which returns cursor locations, i.e. positions <emphasis>between</emphasis>
1670  * characters.
1671  *
1672  * Since: 2.6
1673  **/
1674 void
1675 gtk_text_view_get_iter_at_position (GtkTextView *text_view,
1676                                     GtkTextIter *iter,
1677                                     gint        *trailing,
1678                                     gint         x,
1679                                     gint         y)
1680 {
1681   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1682   g_return_if_fail (iter != NULL);
1683
1684   gtk_text_view_ensure_layout (text_view);
1685   
1686   gtk_text_layout_get_iter_at_position (text_view->priv->layout,
1687                                         iter, trailing, x, y);
1688 }
1689
1690 /**
1691  * gtk_text_view_get_iter_location:
1692  * @text_view: a #GtkTextView
1693  * @iter: a #GtkTextIter
1694  * @location: (out): bounds of the character at @iter
1695  *
1696  * Gets a rectangle which roughly contains the character at @iter.
1697  * The rectangle position is in buffer coordinates; use
1698  * gtk_text_view_buffer_to_window_coords() to convert these
1699  * coordinates to coordinates for one of the windows in the text view.
1700  **/
1701 void
1702 gtk_text_view_get_iter_location (GtkTextView       *text_view,
1703                                  const GtkTextIter *iter,
1704                                  GdkRectangle      *location)
1705 {
1706   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1707   g_return_if_fail (gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1708
1709   gtk_text_view_ensure_layout (text_view);
1710   
1711   gtk_text_layout_get_iter_location (text_view->priv->layout, iter, location);
1712 }
1713
1714 /**
1715  * gtk_text_view_get_line_yrange:
1716  * @text_view: a #GtkTextView
1717  * @iter: a #GtkTextIter
1718  * @y: (out): return location for a y coordinate
1719  * @height: (out): return location for a height
1720  *
1721  * Gets the y coordinate of the top of the line containing @iter,
1722  * and the height of the line. The coordinate is a buffer coordinate;
1723  * convert to window coordinates with gtk_text_view_buffer_to_window_coords().
1724  **/
1725 void
1726 gtk_text_view_get_line_yrange (GtkTextView       *text_view,
1727                                const GtkTextIter *iter,
1728                                gint              *y,
1729                                gint              *height)
1730 {
1731   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1732   g_return_if_fail (gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1733
1734   gtk_text_view_ensure_layout (text_view);
1735   
1736   gtk_text_layout_get_line_yrange (text_view->priv->layout,
1737                                    iter,
1738                                    y,
1739                                    height);
1740 }
1741
1742 /**
1743  * gtk_text_view_get_line_at_y:
1744  * @text_view: a #GtkTextView
1745  * @target_iter: (out): a #GtkTextIter
1746  * @y: a y coordinate
1747  * @line_top: (out): return location for top coordinate of the line
1748  *
1749  * Gets the #GtkTextIter at the start of the line containing
1750  * the coordinate @y. @y is in buffer coordinates, convert from
1751  * window coordinates with gtk_text_view_window_to_buffer_coords().
1752  * If non-%NULL, @line_top will be filled with the coordinate of the top
1753  * edge of the line.
1754  **/
1755 void
1756 gtk_text_view_get_line_at_y (GtkTextView *text_view,
1757                              GtkTextIter *target_iter,
1758                              gint         y,
1759                              gint        *line_top)
1760 {
1761   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1762
1763   gtk_text_view_ensure_layout (text_view);
1764   
1765   gtk_text_layout_get_line_at_y (text_view->priv->layout,
1766                                  target_iter,
1767                                  y,
1768                                  line_top);
1769 }
1770
1771 static gboolean
1772 set_adjustment_clamped (GtkAdjustment *adj, gdouble val)
1773 {
1774   DV (g_print ("  Setting adj to raw value %g\n", val));
1775   
1776   /* We don't really want to clamp to upper; we want to clamp to
1777      upper - page_size which is the highest value the scrollbar
1778      will let us reach. */
1779   if (val > (adj->upper - adj->page_size))
1780     val = adj->upper - adj->page_size;
1781
1782   if (val < adj->lower)
1783     val = adj->lower;
1784
1785   if (val != adj->value)
1786     {
1787       DV (g_print ("  Setting adj to clamped value %g\n", val));
1788       gtk_adjustment_set_value (adj, val);
1789       return TRUE;
1790     }
1791   else
1792     return FALSE;
1793 }
1794
1795 /**
1796  * gtk_text_view_scroll_to_iter:
1797  * @text_view: a #GtkTextView
1798  * @iter: a #GtkTextIter
1799  * @within_margin: margin as a [0.0,0.5) fraction of screen size
1800  * @use_align: whether to use alignment arguments (if %FALSE, 
1801  *    just get the mark onscreen)
1802  * @xalign: horizontal alignment of mark within visible area
1803  * @yalign: vertical alignment of mark within visible area
1804  *
1805  * Scrolls @text_view so that @iter is on the screen in the position
1806  * indicated by @xalign and @yalign. An alignment of 0.0 indicates
1807  * left or top, 1.0 indicates right or bottom, 0.5 means center. 
1808  * If @use_align is %FALSE, the text scrolls the minimal distance to 
1809  * get the mark onscreen, possibly not scrolling at all. The effective 
1810  * screen for purposes of this function is reduced by a margin of size 
1811  * @within_margin.
1812  *
1813  * Note that this function uses the currently-computed height of the
1814  * lines in the text buffer. Line heights are computed in an idle 
1815  * handler; so this function may not have the desired effect if it's 
1816  * called before the height computations. To avoid oddness, consider 
1817  * using gtk_text_view_scroll_to_mark() which saves a point to be 
1818  * scrolled to after line validation.
1819  *
1820  * Return value: %TRUE if scrolling occurred
1821  **/
1822 gboolean
1823 gtk_text_view_scroll_to_iter (GtkTextView   *text_view,
1824                               GtkTextIter   *iter,
1825                               gdouble        within_margin,
1826                               gboolean       use_align,
1827                               gdouble        xalign,
1828                               gdouble        yalign)
1829 {
1830   GdkRectangle rect;
1831   GdkRectangle screen;
1832   gint screen_bottom;
1833   gint screen_right;
1834   gint scroll_dest;
1835   GtkWidget *widget;
1836   gboolean retval = FALSE;
1837   gint scroll_inc;
1838   gint screen_xoffset, screen_yoffset;
1839   gint current_x_scroll, current_y_scroll;
1840
1841   /* FIXME why don't we do the validate-at-scroll-destination thing
1842    * from flush_scroll in this function? I think it wasn't done before
1843    * because changed_handler was screwed up, but I could be wrong.
1844    */
1845   
1846   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
1847   g_return_val_if_fail (iter != NULL, FALSE);
1848   g_return_val_if_fail (within_margin >= 0.0 && within_margin < 0.5, FALSE);
1849   g_return_val_if_fail (xalign >= 0.0 && xalign <= 1.0, FALSE);
1850   g_return_val_if_fail (yalign >= 0.0 && yalign <= 1.0, FALSE);
1851   
1852   widget = GTK_WIDGET (text_view);
1853
1854   DV(g_print(G_STRLOC"\n"));
1855   
1856   gtk_text_layout_get_iter_location (text_view->priv->layout,
1857                                      iter,
1858                                      &rect);
1859
1860   DV (g_print (" target rect %d,%d  %d x %d\n", rect.x, rect.y, rect.width, rect.height));
1861   
1862   current_x_scroll = text_view->priv->xoffset;
1863   current_y_scroll = text_view->priv->yoffset;
1864
1865   screen.x = current_x_scroll;
1866   screen.y = current_y_scroll;
1867   screen.width = SCREEN_WIDTH (widget);
1868   screen.height = SCREEN_HEIGHT (widget);
1869   
1870   screen_xoffset = screen.width * within_margin;
1871   screen_yoffset = screen.height * within_margin;
1872   
1873   screen.x += screen_xoffset;
1874   screen.y += screen_yoffset;
1875   screen.width -= screen_xoffset * 2;
1876   screen.height -= screen_yoffset * 2;
1877
1878   /* paranoia check */
1879   if (screen.width < 1)
1880     screen.width = 1;
1881   if (screen.height < 1)
1882     screen.height = 1;
1883   
1884   /* The -1 here ensures that we leave enough space to draw the cursor
1885    * when this function is used for horizontal scrolling. 
1886    */
1887   screen_right = screen.x + screen.width - 1;
1888   screen_bottom = screen.y + screen.height;
1889   
1890   /* The alignment affects the point in the target character that we
1891    * choose to align. If we're doing right/bottom alignment, we align
1892    * the right/bottom edge of the character the mark is at; if we're
1893    * doing left/top we align the left/top edge of the character; if
1894    * we're doing center alignment we align the center of the
1895    * character.
1896    */
1897   
1898   /* Vertical scroll */
1899
1900   scroll_inc = 0;
1901   scroll_dest = current_y_scroll;
1902   
1903   if (use_align)
1904     {      
1905       scroll_dest = rect.y + (rect.height * yalign) - (screen.height * yalign);
1906       
1907       /* if scroll_dest < screen.y, we move a negative increment (up),
1908        * else a positive increment (down)
1909        */
1910       scroll_inc = scroll_dest - screen.y + screen_yoffset;
1911     }
1912   else
1913     {
1914       /* move minimum to get onscreen */
1915       if (rect.y < screen.y)
1916         {
1917           scroll_dest = rect.y;
1918           scroll_inc = scroll_dest - screen.y - screen_yoffset;
1919         }
1920       else if ((rect.y + rect.height) > screen_bottom)
1921         {
1922           scroll_dest = rect.y + rect.height;
1923           scroll_inc = scroll_dest - screen_bottom + screen_yoffset;
1924         }
1925     }  
1926   
1927   if (scroll_inc != 0)
1928     {
1929       retval = set_adjustment_clamped (get_vadjustment (text_view),
1930                                        current_y_scroll + scroll_inc);
1931
1932       DV (g_print (" vert increment %d\n", scroll_inc));
1933     }
1934
1935   /* Horizontal scroll */
1936   
1937   scroll_inc = 0;
1938   scroll_dest = current_x_scroll;
1939   
1940   if (use_align)
1941     {      
1942       scroll_dest = rect.x + (rect.width * xalign) - (screen.width * xalign);
1943
1944       /* if scroll_dest < screen.y, we move a negative increment (left),
1945        * else a positive increment (right)
1946        */
1947       scroll_inc = scroll_dest - screen.x + screen_xoffset;
1948     }
1949   else
1950     {
1951       /* move minimum to get onscreen */
1952       if (rect.x < screen.x)
1953         {
1954           scroll_dest = rect.x;
1955           scroll_inc = scroll_dest - screen.x - screen_xoffset;
1956         }
1957       else if ((rect.x + rect.width) > screen_right)
1958         {
1959           scroll_dest = rect.x + rect.width;
1960           scroll_inc = scroll_dest - screen_right + screen_xoffset;
1961         }
1962     }
1963   
1964   if (scroll_inc != 0)
1965     {
1966       retval = set_adjustment_clamped (get_hadjustment (text_view),
1967                                        current_x_scroll + scroll_inc);
1968
1969       DV (g_print (" horiz increment %d\n", scroll_inc));
1970     }
1971   
1972   if (retval)
1973     {
1974       DV(g_print (">Actually scrolled ("G_STRLOC")\n"));
1975     }
1976   else
1977     {
1978       DV(g_print (">Didn't end up scrolling ("G_STRLOC")\n"));
1979     }
1980   
1981   return retval;
1982 }
1983
1984 static void
1985 free_pending_scroll (GtkTextPendingScroll *scroll)
1986 {
1987   if (!gtk_text_mark_get_deleted (scroll->mark))
1988     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (scroll->mark),
1989                                  scroll->mark);
1990   g_object_unref (scroll->mark);
1991   g_free (scroll);
1992 }
1993
1994 static void
1995 cancel_pending_scroll (GtkTextView *text_view)
1996 {
1997   if (text_view->priv->pending_scroll)
1998     {
1999       free_pending_scroll (text_view->priv->pending_scroll);
2000       text_view->priv->pending_scroll = NULL;
2001     }
2002 }
2003
2004 static void
2005 gtk_text_view_queue_scroll (GtkTextView   *text_view,
2006                             GtkTextMark   *mark,
2007                             gdouble        within_margin,
2008                             gboolean       use_align,
2009                             gdouble        xalign,
2010                             gdouble        yalign)
2011 {
2012   GtkTextIter iter;
2013   GtkTextPendingScroll *scroll;
2014
2015   DV(g_print(G_STRLOC"\n"));
2016   
2017   scroll = g_new (GtkTextPendingScroll, 1);
2018
2019   scroll->within_margin = within_margin;
2020   scroll->use_align = use_align;
2021   scroll->xalign = xalign;
2022   scroll->yalign = yalign;
2023   
2024   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, mark);
2025
2026   scroll->mark = gtk_text_buffer_create_mark (get_buffer (text_view),
2027                                               NULL,
2028                                               &iter,
2029                                               gtk_text_mark_get_left_gravity (mark));
2030
2031   g_object_ref (scroll->mark);
2032   
2033   cancel_pending_scroll (text_view);
2034
2035   text_view->priv->pending_scroll = scroll;
2036 }
2037
2038 static gboolean
2039 gtk_text_view_flush_scroll (GtkTextView *text_view)
2040 {
2041   GtkAllocation allocation;
2042   GtkTextIter iter;
2043   GtkTextPendingScroll *scroll;
2044   gboolean retval;
2045   GtkWidget *widget;
2046
2047   widget = GTK_WIDGET (text_view);
2048   
2049   DV(g_print(G_STRLOC"\n"));
2050   
2051   if (text_view->priv->pending_scroll == NULL)
2052     {
2053       DV (g_print ("in flush scroll, no pending scroll\n"));
2054       return FALSE;
2055     }
2056
2057   scroll = text_view->priv->pending_scroll;
2058
2059   /* avoid recursion */
2060   text_view->priv->pending_scroll = NULL;
2061   
2062   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, scroll->mark);
2063
2064   /* Validate area around the scroll destination, so the adjustment
2065    * can meaningfully point into that area. We must validate
2066    * enough area to be sure that after we scroll, everything onscreen
2067    * is valid; otherwise, validation will maintain the first para
2068    * in one place, but may push the target iter off the bottom of
2069    * the screen.
2070    */
2071   DV(g_print (">Validating scroll destination ("G_STRLOC")\n"));
2072   gtk_widget_get_allocation (widget, &allocation);
2073   gtk_text_layout_validate_yrange (text_view->priv->layout, &iter,
2074                                    -(allocation.height * 2),
2075                                    allocation.height * 2);
2076
2077   DV(g_print (">Done validating scroll destination ("G_STRLOC")\n"));
2078
2079   /* Ensure we have updated width/height */
2080   gtk_text_view_update_adjustments (text_view);
2081   
2082   retval = gtk_text_view_scroll_to_iter (text_view,
2083                                          &iter,
2084                                          scroll->within_margin,
2085                                          scroll->use_align,
2086                                          scroll->xalign,
2087                                          scroll->yalign);
2088
2089   free_pending_scroll (scroll);
2090
2091   return retval;
2092 }
2093
2094 static void
2095 gtk_text_view_set_adjustment_upper (GtkAdjustment *adj, gdouble upper)
2096 {  
2097   if (upper != adj->upper)
2098     {
2099       gdouble min = MAX (0.0, upper - adj->page_size);
2100       gboolean value_changed = FALSE;
2101
2102       adj->upper = upper;
2103
2104       if (adj->value > min)
2105         {
2106           adj->value = min;
2107           value_changed = TRUE;
2108         }
2109
2110       gtk_adjustment_changed (adj);
2111       DV(g_print(">Changed adj upper to %g ("G_STRLOC")\n", upper));
2112       
2113       if (value_changed)
2114         {
2115           DV(g_print(">Changed adj value because upper decreased ("G_STRLOC")\n"));
2116           gtk_adjustment_value_changed (adj);
2117         }
2118     }
2119 }
2120
2121 static void
2122 gtk_text_view_update_adjustments (GtkTextView *text_view)
2123 {
2124   GtkTextViewPrivate *priv;
2125   gint width = 0, height = 0;
2126
2127   DV(g_print(">Updating adjustments ("G_STRLOC")\n"));
2128
2129   priv = text_view->priv;
2130
2131   if (priv->layout)
2132     gtk_text_layout_get_size (priv->layout, &width, &height);
2133
2134   /* Make room for the cursor after the last character in the widest line */
2135   width += SPACE_FOR_CURSOR;
2136
2137   if (priv->width != width || priv->height != height)
2138     {
2139       if (priv->width != width)
2140         priv->width_changed = TRUE;
2141
2142       priv->width = width;
2143       priv->height = height;
2144
2145       gtk_text_view_set_adjustment_upper (get_hadjustment (text_view),
2146                                           MAX (SCREEN_WIDTH (text_view), width));
2147       gtk_text_view_set_adjustment_upper (get_vadjustment (text_view),
2148                                           MAX (SCREEN_HEIGHT (text_view), height));
2149       
2150       /* hadj/vadj exist since we called get_hadjustment/get_vadjustment above */
2151
2152       /* Set up the step sizes; we'll say that a page is
2153          our allocation minus one step, and a step is
2154          1/10 of our allocation. */
2155       priv->hadjustment->step_increment =
2156         SCREEN_WIDTH (text_view) / 10.0;
2157       priv->hadjustment->page_increment =
2158         SCREEN_WIDTH (text_view) * 0.9;
2159       
2160       priv->vadjustment->step_increment =
2161         SCREEN_HEIGHT (text_view) / 10.0;
2162       priv->vadjustment->page_increment =
2163         SCREEN_HEIGHT (text_view) * 0.9;
2164
2165       gtk_adjustment_changed (get_hadjustment (text_view));
2166       gtk_adjustment_changed (get_vadjustment (text_view));
2167     }
2168 }
2169
2170 static void
2171 gtk_text_view_update_layout_width (GtkTextView *text_view)
2172 {
2173   DV(g_print(">Updating layout width ("G_STRLOC")\n"));
2174   
2175   gtk_text_view_ensure_layout (text_view);
2176
2177   gtk_text_layout_set_screen_width (text_view->priv->layout,
2178                                     MAX (1, SCREEN_WIDTH (text_view) - SPACE_FOR_CURSOR));
2179 }
2180
2181 static void
2182 gtk_text_view_update_im_spot_location (GtkTextView *text_view)
2183 {
2184   GdkRectangle area;
2185
2186   if (text_view->priv->layout == NULL)
2187     return;
2188   
2189   gtk_text_view_get_cursor_location (text_view, &area);
2190
2191   area.x -= text_view->priv->xoffset;
2192   area.y -= text_view->priv->yoffset;
2193     
2194   /* Width returned by Pango indicates direction of cursor,
2195    * by it's sign more than the size of cursor.
2196    */
2197   area.width = 0;
2198
2199   gtk_im_context_set_cursor_location (text_view->priv->im_context, &area);
2200 }
2201
2202 static gboolean
2203 do_update_im_spot_location (gpointer text_view)
2204 {
2205   GtkTextViewPrivate *priv;
2206
2207   priv = GTK_TEXT_VIEW (text_view)->priv;
2208   priv->im_spot_idle = 0;
2209
2210   gtk_text_view_update_im_spot_location (text_view);
2211   return FALSE;
2212 }
2213
2214 static void
2215 queue_update_im_spot_location (GtkTextView *text_view)
2216 {
2217   GtkTextViewPrivate *priv;
2218
2219   priv = text_view->priv;
2220
2221   /* Use priority a little higher than GTK_TEXT_VIEW_PRIORITY_VALIDATE,
2222    * so we don't wait until the entire buffer has been validated. */
2223   if (!priv->im_spot_idle)
2224     priv->im_spot_idle = gdk_threads_add_idle_full (GTK_TEXT_VIEW_PRIORITY_VALIDATE - 1,
2225                                                     do_update_im_spot_location,
2226                                                     text_view,
2227                                                     NULL);
2228 }
2229
2230 static void
2231 flush_update_im_spot_location (GtkTextView *text_view)
2232 {
2233   GtkTextViewPrivate *priv;
2234
2235   priv = text_view->priv;
2236
2237   if (priv->im_spot_idle)
2238     {
2239       g_source_remove (priv->im_spot_idle);
2240       priv->im_spot_idle = 0;
2241       gtk_text_view_update_im_spot_location (text_view);
2242     }
2243 }
2244
2245 /**
2246  * gtk_text_view_scroll_to_mark:
2247  * @text_view: a #GtkTextView
2248  * @mark: a #GtkTextMark
2249  * @within_margin: margin as a [0.0,0.5) fraction of screen size
2250  * @use_align: whether to use alignment arguments (if %FALSE, just 
2251  *    get the mark onscreen)
2252  * @xalign: horizontal alignment of mark within visible area
2253  * @yalign: vertical alignment of mark within visible area
2254  *
2255  * Scrolls @text_view so that @mark is on the screen in the position
2256  * indicated by @xalign and @yalign. An alignment of 0.0 indicates
2257  * left or top, 1.0 indicates right or bottom, 0.5 means center. 
2258  * If @use_align is %FALSE, the text scrolls the minimal distance to 
2259  * get the mark onscreen, possibly not scrolling at all. The effective 
2260  * screen for purposes of this function is reduced by a margin of size 
2261  * @within_margin.
2262  **/
2263 void
2264 gtk_text_view_scroll_to_mark (GtkTextView *text_view,
2265                               GtkTextMark *mark,
2266                               gdouble      within_margin,
2267                               gboolean     use_align,
2268                               gdouble      xalign,
2269                               gdouble      yalign)
2270 {  
2271   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2272   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
2273   g_return_if_fail (within_margin >= 0.0 && within_margin < 0.5);
2274   g_return_if_fail (xalign >= 0.0 && xalign <= 1.0);
2275   g_return_if_fail (yalign >= 0.0 && yalign <= 1.0);
2276
2277   /* We need to verify that the buffer contains the mark, otherwise this
2278    * can lead to data structure corruption later on.
2279    */
2280   g_return_if_fail (get_buffer (text_view) == gtk_text_mark_get_buffer (mark));
2281
2282   gtk_text_view_queue_scroll (text_view, mark,
2283                               within_margin,
2284                               use_align,
2285                               xalign,
2286                               yalign);
2287
2288   /* If no validation is pending, we need to go ahead and force an
2289    * immediate scroll.
2290    */
2291   if (text_view->priv->layout &&
2292       gtk_text_layout_is_valid (text_view->priv->layout))
2293     gtk_text_view_flush_scroll (text_view);
2294 }
2295
2296 /**
2297  * gtk_text_view_scroll_mark_onscreen:
2298  * @text_view: a #GtkTextView
2299  * @mark: a mark in the buffer for @text_view
2300  * 
2301  * Scrolls @text_view the minimum distance such that @mark is contained
2302  * within the visible area of the widget.
2303  **/
2304 void
2305 gtk_text_view_scroll_mark_onscreen (GtkTextView *text_view,
2306                                     GtkTextMark *mark)
2307 {
2308   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2309   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
2310
2311   /* We need to verify that the buffer contains the mark, otherwise this
2312    * can lead to data structure corruption later on.
2313    */
2314   g_return_if_fail (get_buffer (text_view) == gtk_text_mark_get_buffer (mark));
2315
2316   gtk_text_view_scroll_to_mark (text_view, mark, 0.0, FALSE, 0.0, 0.0);
2317 }
2318
2319 static gboolean
2320 clamp_iter_onscreen (GtkTextView *text_view, GtkTextIter *iter)
2321 {
2322   GdkRectangle visible_rect;
2323   gtk_text_view_get_visible_rect (text_view, &visible_rect);
2324
2325   return gtk_text_layout_clamp_iter_to_vrange (text_view->priv->layout, iter,
2326                                                visible_rect.y,
2327                                                visible_rect.y + visible_rect.height);
2328 }
2329
2330 /**
2331  * gtk_text_view_move_mark_onscreen:
2332  * @text_view: a #GtkTextView
2333  * @mark: a #GtkTextMark
2334  *
2335  * Moves a mark within the buffer so that it's
2336  * located within the currently-visible text area.
2337  *
2338  * Return value: %TRUE if the mark moved (wasn't already onscreen)
2339  **/
2340 gboolean
2341 gtk_text_view_move_mark_onscreen (GtkTextView *text_view,
2342                                   GtkTextMark *mark)
2343 {
2344   GtkTextIter iter;
2345
2346   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2347   g_return_val_if_fail (mark != NULL, FALSE);
2348
2349   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, mark);
2350
2351   if (clamp_iter_onscreen (text_view, &iter))
2352     {
2353       gtk_text_buffer_move_mark (get_buffer (text_view), mark, &iter);
2354       return TRUE;
2355     }
2356   else
2357     return FALSE;
2358 }
2359
2360 /**
2361  * gtk_text_view_get_visible_rect:
2362  * @text_view: a #GtkTextView
2363  * @visible_rect: rectangle to fill
2364  *
2365  * Fills @visible_rect with the currently-visible
2366  * region of the buffer, in buffer coordinates. Convert to window coordinates
2367  * with gtk_text_view_buffer_to_window_coords().
2368  **/
2369 void
2370 gtk_text_view_get_visible_rect (GtkTextView  *text_view,
2371                                 GdkRectangle *visible_rect)
2372 {
2373   GtkWidget *widget;
2374
2375   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2376
2377   widget = GTK_WIDGET (text_view);
2378
2379   if (visible_rect)
2380     {
2381       visible_rect->x = text_view->priv->xoffset;
2382       visible_rect->y = text_view->priv->yoffset;
2383       visible_rect->width = SCREEN_WIDTH (widget);
2384       visible_rect->height = SCREEN_HEIGHT (widget);
2385
2386       DV(g_print(" visible rect: %d,%d %d x %d\n",
2387                  visible_rect->x,
2388                  visible_rect->y,
2389                  visible_rect->width,
2390                  visible_rect->height));
2391     }
2392 }
2393
2394 /**
2395  * gtk_text_view_set_wrap_mode:
2396  * @text_view: a #GtkTextView
2397  * @wrap_mode: a #GtkWrapMode
2398  *
2399  * Sets the line wrapping for the view.
2400  **/
2401 void
2402 gtk_text_view_set_wrap_mode (GtkTextView *text_view,
2403                              GtkWrapMode  wrap_mode)
2404 {
2405   GtkTextViewPrivate *priv;
2406
2407   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2408
2409   priv = text_view->priv;
2410
2411   if (priv->wrap_mode != wrap_mode)
2412     {
2413       priv->wrap_mode = wrap_mode;
2414
2415       if (priv->layout)
2416         {
2417           priv->layout->default_style->wrap_mode = wrap_mode;
2418           gtk_text_layout_default_style_changed (priv->layout);
2419         }
2420     }
2421
2422   g_object_notify (G_OBJECT (text_view), "wrap-mode");
2423 }
2424
2425 /**
2426  * gtk_text_view_get_wrap_mode:
2427  * @text_view: a #GtkTextView
2428  *
2429  * Gets the line wrapping for the view.
2430  *
2431  * Return value: the line wrap setting
2432  **/
2433 GtkWrapMode
2434 gtk_text_view_get_wrap_mode (GtkTextView *text_view)
2435 {
2436   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_WRAP_NONE);
2437
2438   return text_view->priv->wrap_mode;
2439 }
2440
2441 /**
2442  * gtk_text_view_set_editable:
2443  * @text_view: a #GtkTextView
2444  * @setting: whether it's editable
2445  *
2446  * Sets the default editability of the #GtkTextView. You can override
2447  * this default setting with tags in the buffer, using the "editable"
2448  * attribute of tags.
2449  **/
2450 void
2451 gtk_text_view_set_editable (GtkTextView *text_view,
2452                             gboolean     setting)
2453 {
2454   GtkTextViewPrivate *priv;
2455
2456   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2457
2458   priv = text_view->priv;
2459   setting = setting != FALSE;
2460
2461   if (priv->editable != setting)
2462     {
2463       if (!setting)
2464         {
2465           gtk_text_view_reset_im_context(text_view);
2466           if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
2467             gtk_im_context_focus_out (priv->im_context);
2468         }
2469
2470       priv->editable = setting;
2471
2472       if (setting && gtk_widget_has_focus (GTK_WIDGET (text_view)))
2473         gtk_im_context_focus_in (priv->im_context);
2474
2475       if (priv->layout)
2476         {
2477           gtk_text_layout_set_overwrite_mode (priv->layout,
2478                                               priv->overwrite_mode && priv->editable);
2479           priv->layout->default_style->editable = priv->editable;
2480           gtk_text_layout_default_style_changed (priv->layout);
2481         }
2482
2483       g_object_notify (G_OBJECT (text_view), "editable");
2484     }
2485 }
2486
2487 /**
2488  * gtk_text_view_get_editable:
2489  * @text_view: a #GtkTextView
2490  *
2491  * Returns the default editability of the #GtkTextView. Tags in the
2492  * buffer may override this setting for some ranges of text.
2493  *
2494  * Return value: whether text is editable by default
2495  **/
2496 gboolean
2497 gtk_text_view_get_editable (GtkTextView *text_view)
2498 {
2499   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2500
2501   return text_view->priv->editable;
2502 }
2503
2504 /**
2505  * gtk_text_view_set_pixels_above_lines:
2506  * @text_view: a #GtkTextView
2507  * @pixels_above_lines: pixels above paragraphs
2508  * 
2509  * Sets the default number of blank pixels above paragraphs in @text_view.
2510  * Tags in the buffer for @text_view may override the defaults.
2511  **/
2512 void
2513 gtk_text_view_set_pixels_above_lines (GtkTextView *text_view,
2514                                       gint         pixels_above_lines)
2515 {
2516   GtkTextViewPrivate *priv;
2517
2518   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2519
2520   priv = text_view->priv;
2521
2522   if (priv->pixels_above_lines != pixels_above_lines)
2523     {
2524       priv->pixels_above_lines = pixels_above_lines;
2525
2526       if (priv->layout)
2527         {
2528           priv->layout->default_style->pixels_above_lines = pixels_above_lines;
2529           gtk_text_layout_default_style_changed (priv->layout);
2530         }
2531
2532       g_object_notify (G_OBJECT (text_view), "pixels-above-lines");
2533     }
2534 }
2535
2536 /**
2537  * gtk_text_view_get_pixels_above_lines:
2538  * @text_view: a #GtkTextView
2539  * 
2540  * Gets the default number of pixels to put above paragraphs.
2541  * 
2542  * Return value: default number of pixels above paragraphs
2543  **/
2544 gint
2545 gtk_text_view_get_pixels_above_lines (GtkTextView *text_view)
2546 {
2547   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2548
2549   return text_view->priv->pixels_above_lines;
2550 }
2551
2552 /**
2553  * gtk_text_view_set_pixels_below_lines:
2554  * @text_view: a #GtkTextView
2555  * @pixels_below_lines: pixels below paragraphs 
2556  *
2557  * Sets the default number of pixels of blank space
2558  * to put below paragraphs in @text_view. May be overridden
2559  * by tags applied to @text_view's buffer. 
2560  **/
2561 void
2562 gtk_text_view_set_pixels_below_lines (GtkTextView *text_view,
2563                                       gint         pixels_below_lines)
2564 {
2565   GtkTextViewPrivate *priv;
2566
2567   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2568
2569   priv = text_view->priv;
2570
2571   if (priv->pixels_below_lines != pixels_below_lines)
2572     {
2573       priv->pixels_below_lines = pixels_below_lines;
2574
2575       if (priv->layout)
2576         {
2577           priv->layout->default_style->pixels_below_lines = pixels_below_lines;
2578           gtk_text_layout_default_style_changed (priv->layout);
2579         }
2580
2581       g_object_notify (G_OBJECT (text_view), "pixels-below-lines");
2582     }
2583 }
2584
2585 /**
2586  * gtk_text_view_get_pixels_below_lines:
2587  * @text_view: a #GtkTextView
2588  * 
2589  * Gets the value set by gtk_text_view_set_pixels_below_lines().
2590  * 
2591  * Return value: default number of blank pixels below paragraphs
2592  **/
2593 gint
2594 gtk_text_view_get_pixels_below_lines (GtkTextView *text_view)
2595 {
2596   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2597
2598   return text_view->priv->pixels_below_lines;
2599 }
2600
2601 /**
2602  * gtk_text_view_set_pixels_inside_wrap:
2603  * @text_view: a #GtkTextView
2604  * @pixels_inside_wrap: default number of pixels between wrapped lines
2605  *
2606  * Sets the default number of pixels of blank space to leave between
2607  * display/wrapped lines within a paragraph. May be overridden by
2608  * tags in @text_view's buffer.
2609  **/
2610 void
2611 gtk_text_view_set_pixels_inside_wrap (GtkTextView *text_view,
2612                                       gint         pixels_inside_wrap)
2613 {
2614   GtkTextViewPrivate *priv;
2615
2616   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2617
2618   priv = text_view->priv;
2619
2620   if (priv->pixels_inside_wrap != pixels_inside_wrap)
2621     {
2622       priv->pixels_inside_wrap = pixels_inside_wrap;
2623
2624       if (priv->layout)
2625         {
2626           priv->layout->default_style->pixels_inside_wrap = pixels_inside_wrap;
2627           gtk_text_layout_default_style_changed (priv->layout);
2628         }
2629
2630       g_object_notify (G_OBJECT (text_view), "pixels-inside-wrap");
2631     }
2632 }
2633
2634 /**
2635  * gtk_text_view_get_pixels_inside_wrap:
2636  * @text_view: a #GtkTextView
2637  * 
2638  * Gets the value set by gtk_text_view_set_pixels_inside_wrap().
2639  * 
2640  * Return value: default number of pixels of blank space between wrapped lines
2641  **/
2642 gint
2643 gtk_text_view_get_pixels_inside_wrap (GtkTextView *text_view)
2644 {
2645   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2646
2647   return text_view->priv->pixels_inside_wrap;
2648 }
2649
2650 /**
2651  * gtk_text_view_set_justification:
2652  * @text_view: a #GtkTextView
2653  * @justification: justification
2654  *
2655  * Sets the default justification of text in @text_view.
2656  * Tags in the view's buffer may override the default.
2657  * 
2658  **/
2659 void
2660 gtk_text_view_set_justification (GtkTextView     *text_view,
2661                                  GtkJustification justification)
2662 {
2663   GtkTextViewPrivate *priv;
2664
2665   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2666
2667   priv = text_view->priv;
2668
2669   if (priv->justify != justification)
2670     {
2671       priv->justify = justification;
2672
2673       if (priv->layout)
2674         {
2675           priv->layout->default_style->justification = justification;
2676           gtk_text_layout_default_style_changed (priv->layout);
2677         }
2678
2679       g_object_notify (G_OBJECT (text_view), "justification");
2680     }
2681 }
2682
2683 /**
2684  * gtk_text_view_get_justification:
2685  * @text_view: a #GtkTextView
2686  * 
2687  * Gets the default justification of paragraphs in @text_view.
2688  * Tags in the buffer may override the default.
2689  * 
2690  * Return value: default justification
2691  **/
2692 GtkJustification
2693 gtk_text_view_get_justification (GtkTextView *text_view)
2694 {
2695   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_JUSTIFY_LEFT);
2696
2697   return text_view->priv->justify;
2698 }
2699
2700 /**
2701  * gtk_text_view_set_left_margin:
2702  * @text_view: a #GtkTextView
2703  * @left_margin: left margin in pixels
2704  * 
2705  * Sets the default left margin for text in @text_view.
2706  * Tags in the buffer may override the default.
2707  **/
2708 void
2709 gtk_text_view_set_left_margin (GtkTextView *text_view,
2710                                gint         left_margin)
2711 {
2712   GtkTextViewPrivate *priv;
2713
2714   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2715
2716   priv = text_view->priv;
2717
2718   if (priv->left_margin != left_margin)
2719     {
2720       priv->left_margin = left_margin;
2721
2722       if (priv->layout)
2723         {
2724           priv->layout->default_style->left_margin = left_margin;
2725           gtk_text_layout_default_style_changed (priv->layout);
2726         }
2727
2728       g_object_notify (G_OBJECT (text_view), "left-margin");
2729     }
2730 }
2731
2732 /**
2733  * gtk_text_view_get_left_margin:
2734  * @text_view: a #GtkTextView
2735  * 
2736  * Gets the default left margin size of paragraphs in the @text_view.
2737  * Tags in the buffer may override the default.
2738  * 
2739  * Return value: left margin in pixels
2740  **/
2741 gint
2742 gtk_text_view_get_left_margin (GtkTextView *text_view)
2743 {
2744   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2745
2746   return text_view->priv->left_margin;
2747 }
2748
2749 /**
2750  * gtk_text_view_set_right_margin:
2751  * @text_view: a #GtkTextView
2752  * @right_margin: right margin in pixels
2753  *
2754  * Sets the default right margin for text in the text view.
2755  * Tags in the buffer may override the default.
2756  **/
2757 void
2758 gtk_text_view_set_right_margin (GtkTextView *text_view,
2759                                 gint         right_margin)
2760 {
2761   GtkTextViewPrivate *priv = text_view->priv;
2762
2763   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2764
2765   if (priv->right_margin != right_margin)
2766     {
2767       priv->right_margin = right_margin;
2768
2769       if (priv->layout)
2770         {
2771           priv->layout->default_style->right_margin = right_margin;
2772           gtk_text_layout_default_style_changed (priv->layout);
2773         }
2774
2775       g_object_notify (G_OBJECT (text_view), "right-margin");
2776     }
2777 }
2778
2779 /**
2780  * gtk_text_view_get_right_margin:
2781  * @text_view: a #GtkTextView
2782  * 
2783  * Gets the default right margin for text in @text_view. Tags
2784  * in the buffer may override the default.
2785  * 
2786  * Return value: right margin in pixels
2787  **/
2788 gint
2789 gtk_text_view_get_right_margin (GtkTextView *text_view)
2790 {
2791   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2792
2793   return text_view->priv->right_margin;
2794 }
2795
2796 /**
2797  * gtk_text_view_set_indent:
2798  * @text_view: a #GtkTextView
2799  * @indent: indentation in pixels
2800  *
2801  * Sets the default indentation for paragraphs in @text_view.
2802  * Tags in the buffer may override the default.
2803  **/
2804 void
2805 gtk_text_view_set_indent (GtkTextView *text_view,
2806                           gint         indent)
2807 {
2808   GtkTextViewPrivate *priv;
2809
2810   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2811
2812   priv = text_view->priv;
2813
2814   if (priv->indent != indent)
2815     {
2816       priv->indent = indent;
2817
2818       if (priv->layout)
2819         {
2820           priv->layout->default_style->indent = indent;
2821           gtk_text_layout_default_style_changed (priv->layout);
2822         }
2823
2824       g_object_notify (G_OBJECT (text_view), "indent");
2825     }
2826 }
2827
2828 /**
2829  * gtk_text_view_get_indent:
2830  * @text_view: a #GtkTextView
2831  * 
2832  * Gets the default indentation of paragraphs in @text_view.
2833  * Tags in the view's buffer may override the default.
2834  * The indentation may be negative.
2835  * 
2836  * Return value: number of pixels of indentation
2837  **/
2838 gint
2839 gtk_text_view_get_indent (GtkTextView *text_view)
2840 {
2841   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2842
2843   return text_view->priv->indent;
2844 }
2845
2846 /**
2847  * gtk_text_view_set_tabs:
2848  * @text_view: a #GtkTextView
2849  * @tabs: tabs as a #PangoTabArray
2850  *
2851  * Sets the default tab stops for paragraphs in @text_view.
2852  * Tags in the buffer may override the default.
2853  **/
2854 void
2855 gtk_text_view_set_tabs (GtkTextView   *text_view,
2856                         PangoTabArray *tabs)
2857 {
2858   GtkTextViewPrivate *priv;
2859
2860   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2861
2862   priv = text_view->priv;
2863
2864   if (priv->tabs)
2865     pango_tab_array_free (priv->tabs);
2866
2867   priv->tabs = tabs ? pango_tab_array_copy (tabs) : NULL;
2868
2869   if (priv->layout)
2870     {
2871       /* some unkosher futzing in internal struct details... */
2872       if (priv->layout->default_style->tabs)
2873         pango_tab_array_free (priv->layout->default_style->tabs);
2874
2875       priv->layout->default_style->tabs =
2876         priv->tabs ? pango_tab_array_copy (priv->tabs) : NULL;
2877
2878       gtk_text_layout_default_style_changed (priv->layout);
2879     }
2880
2881   g_object_notify (G_OBJECT (text_view), "tabs");
2882 }
2883
2884 /**
2885  * gtk_text_view_get_tabs:
2886  * @text_view: a #GtkTextView
2887  * 
2888  * Gets the default tabs for @text_view. Tags in the buffer may
2889  * override the defaults. The returned array will be %NULL if
2890  * "standard" (8-space) tabs are used. Free the return value
2891  * with pango_tab_array_free().
2892  * 
2893  * Return value: copy of default tab array, or %NULL if "standard" 
2894  *    tabs are used; must be freed with pango_tab_array_free().
2895  **/
2896 PangoTabArray*
2897 gtk_text_view_get_tabs (GtkTextView *text_view)
2898 {
2899   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
2900
2901   return text_view->priv->tabs ? pango_tab_array_copy (text_view->priv->tabs) : NULL;
2902 }
2903
2904 static void
2905 gtk_text_view_toggle_cursor_visible (GtkTextView *text_view)
2906 {
2907   gtk_text_view_set_cursor_visible (text_view, !text_view->priv->cursor_visible);
2908 }
2909
2910 /**
2911  * gtk_text_view_set_cursor_visible:
2912  * @text_view: a #GtkTextView
2913  * @setting: whether to show the insertion cursor
2914  *
2915  * Toggles whether the insertion point is displayed. A buffer with no editable
2916  * text probably shouldn't have a visible cursor, so you may want to turn
2917  * the cursor off.
2918  **/
2919 void
2920 gtk_text_view_set_cursor_visible (GtkTextView *text_view,
2921                                   gboolean     setting)
2922 {
2923   GtkTextViewPrivate *priv;
2924
2925   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2926
2927   priv = text_view->priv;
2928   setting = (setting != FALSE);
2929
2930   if (priv->cursor_visible != setting)
2931     {
2932       priv->cursor_visible = setting;
2933
2934       if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
2935         {
2936           if (priv->layout)
2937             {
2938               gtk_text_layout_set_cursor_visible (priv->layout, setting);
2939               gtk_text_view_check_cursor_blink (text_view);
2940             }
2941         }
2942
2943       g_object_notify (G_OBJECT (text_view), "cursor-visible");
2944     }
2945 }
2946
2947 /**
2948  * gtk_text_view_get_cursor_visible:
2949  * @text_view: a #GtkTextView
2950  *
2951  * Find out whether the cursor is being displayed.
2952  *
2953  * Return value: whether the insertion mark is visible
2954  **/
2955 gboolean
2956 gtk_text_view_get_cursor_visible (GtkTextView *text_view)
2957 {
2958   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2959
2960   return text_view->priv->cursor_visible;
2961 }
2962
2963
2964 /**
2965  * gtk_text_view_place_cursor_onscreen:
2966  * @text_view: a #GtkTextView
2967  *
2968  * Moves the cursor to the currently visible region of the
2969  * buffer, it it isn't there already.
2970  *
2971  * Return value: %TRUE if the cursor had to be moved.
2972  **/
2973 gboolean
2974 gtk_text_view_place_cursor_onscreen (GtkTextView *text_view)
2975 {
2976   GtkTextIter insert;
2977
2978   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2979
2980   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
2981                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
2982
2983   if (clamp_iter_onscreen (text_view, &insert))
2984     {
2985       gtk_text_buffer_place_cursor (get_buffer (text_view), &insert);
2986       return TRUE;
2987     }
2988   else
2989     return FALSE;
2990 }
2991
2992 static void
2993 gtk_text_view_remove_validate_idles (GtkTextView *text_view)
2994 {
2995   GtkTextViewPrivate *priv = text_view->priv;
2996
2997   if (priv->first_validate_idle != 0)
2998     {
2999       DV (g_print ("Removing first validate idle: %s\n", G_STRLOC));
3000       g_source_remove (priv->first_validate_idle);
3001       priv->first_validate_idle = 0;
3002     }
3003
3004   if (priv->incremental_validate_idle != 0)
3005     {
3006       g_source_remove (priv->incremental_validate_idle);
3007       priv->incremental_validate_idle = 0;
3008     }
3009 }
3010
3011 static void
3012 gtk_text_view_destroy (GtkObject *object)
3013 {
3014   GtkTextView *text_view;
3015   GtkTextViewPrivate *priv;
3016
3017   text_view = GTK_TEXT_VIEW (object);
3018   priv = text_view->priv;
3019
3020   gtk_text_view_remove_validate_idles (text_view);
3021   gtk_text_view_set_buffer (text_view, NULL);
3022   gtk_text_view_destroy_layout (text_view);
3023
3024   if (text_view->priv->scroll_timeout)
3025     {
3026       g_source_remove (text_view->priv->scroll_timeout);
3027       text_view->priv->scroll_timeout = 0;
3028     }
3029
3030   if (priv->im_spot_idle)
3031     {
3032       g_source_remove (priv->im_spot_idle);
3033       priv->im_spot_idle = 0;
3034     }
3035
3036   GTK_OBJECT_CLASS (gtk_text_view_parent_class)->destroy (object);
3037 }
3038
3039 static void
3040 gtk_text_view_finalize (GObject *object)
3041 {
3042   GtkTextView *text_view;
3043   GtkTextViewPrivate *priv;
3044
3045   text_view = GTK_TEXT_VIEW (object);
3046   priv = text_view->priv;
3047
3048   g_assert (priv->buffer == NULL);
3049
3050   gtk_text_view_destroy_layout (text_view);
3051   gtk_text_view_set_buffer (text_view, NULL);
3052   
3053   cancel_pending_scroll (text_view);
3054
3055   if (priv->tabs)
3056     pango_tab_array_free (priv->tabs);
3057   
3058   if (priv->hadjustment)
3059     g_object_unref (priv->hadjustment);
3060   if (priv->vadjustment)
3061     g_object_unref (priv->vadjustment);
3062
3063   text_window_free (priv->text_window);
3064
3065   if (priv->left_window)
3066     text_window_free (priv->left_window);
3067
3068   if (priv->top_window)
3069     text_window_free (priv->top_window);
3070
3071   if (priv->right_window)
3072     text_window_free (priv->right_window);
3073
3074   if (priv->bottom_window)
3075     text_window_free (priv->bottom_window);
3076
3077   g_object_unref (priv->im_context);
3078
3079   g_free (priv->im_module);
3080
3081   G_OBJECT_CLASS (gtk_text_view_parent_class)->finalize (object);
3082 }
3083
3084 static void
3085 gtk_text_view_set_property (GObject         *object,
3086                             guint            prop_id,
3087                             const GValue    *value,
3088                             GParamSpec      *pspec)
3089 {
3090   GtkTextView *text_view;
3091   GtkTextViewPrivate *priv;
3092
3093   text_view = GTK_TEXT_VIEW (object);
3094   priv = text_view->priv;
3095
3096   switch (prop_id)
3097     {
3098     case PROP_PIXELS_ABOVE_LINES:
3099       gtk_text_view_set_pixels_above_lines (text_view, g_value_get_int (value));
3100       break;
3101
3102     case PROP_PIXELS_BELOW_LINES:
3103       gtk_text_view_set_pixels_below_lines (text_view, g_value_get_int (value));
3104       break;
3105
3106     case PROP_PIXELS_INSIDE_WRAP:
3107       gtk_text_view_set_pixels_inside_wrap (text_view, g_value_get_int (value));
3108       break;
3109
3110     case PROP_EDITABLE:
3111       gtk_text_view_set_editable (text_view, g_value_get_boolean (value));
3112       break;
3113
3114     case PROP_WRAP_MODE:
3115       gtk_text_view_set_wrap_mode (text_view, g_value_get_enum (value));
3116       break;
3117       
3118     case PROP_JUSTIFICATION:
3119       gtk_text_view_set_justification (text_view, g_value_get_enum (value));
3120       break;
3121
3122     case PROP_LEFT_MARGIN:
3123       gtk_text_view_set_left_margin (text_view, g_value_get_int (value));
3124       break;
3125
3126     case PROP_RIGHT_MARGIN:
3127       gtk_text_view_set_right_margin (text_view, g_value_get_int (value));
3128       break;
3129
3130     case PROP_INDENT:
3131       gtk_text_view_set_indent (text_view, g_value_get_int (value));
3132       break;
3133
3134     case PROP_TABS:
3135       gtk_text_view_set_tabs (text_view, g_value_get_boxed (value));
3136       break;
3137
3138     case PROP_CURSOR_VISIBLE:
3139       gtk_text_view_set_cursor_visible (text_view, g_value_get_boolean (value));
3140       break;
3141
3142     case PROP_OVERWRITE:
3143       gtk_text_view_set_overwrite (text_view, g_value_get_boolean (value));
3144       break;
3145
3146     case PROP_BUFFER:
3147       gtk_text_view_set_buffer (text_view, GTK_TEXT_BUFFER (g_value_get_object (value)));
3148       break;
3149
3150     case PROP_ACCEPTS_TAB:
3151       gtk_text_view_set_accepts_tab (text_view, g_value_get_boolean (value));
3152       break;
3153       
3154     case PROP_IM_MODULE:
3155       g_free (priv->im_module);
3156       priv->im_module = g_value_dup_string (value);
3157       if (GTK_IS_IM_MULTICONTEXT (priv->im_context))
3158         gtk_im_multicontext_set_context_id (GTK_IM_MULTICONTEXT (priv->im_context), priv->im_module);
3159       break;
3160
3161     default:
3162       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3163       break;
3164     }
3165 }
3166
3167 static void
3168 gtk_text_view_get_property (GObject         *object,
3169                             guint            prop_id,
3170                             GValue          *value,
3171                             GParamSpec      *pspec)
3172 {
3173   GtkTextView *text_view;
3174   GtkTextViewPrivate *priv;
3175
3176   text_view = GTK_TEXT_VIEW (object);
3177   priv = text_view->priv;
3178
3179   switch (prop_id)
3180     {
3181     case PROP_PIXELS_ABOVE_LINES:
3182       g_value_set_int (value, priv->pixels_above_lines);
3183       break;
3184
3185     case PROP_PIXELS_BELOW_LINES:
3186       g_value_set_int (value, priv->pixels_below_lines);
3187       break;
3188
3189     case PROP_PIXELS_INSIDE_WRAP:
3190       g_value_set_int (value, priv->pixels_inside_wrap);
3191       break;
3192
3193     case PROP_EDITABLE:
3194       g_value_set_boolean (value, priv->editable);
3195       break;
3196       
3197     case PROP_WRAP_MODE:
3198       g_value_set_enum (value, priv->wrap_mode);
3199       break;
3200
3201     case PROP_JUSTIFICATION:
3202       g_value_set_enum (value, priv->justify);
3203       break;
3204
3205     case PROP_LEFT_MARGIN:
3206       g_value_set_int (value, priv->left_margin);
3207       break;
3208
3209     case PROP_RIGHT_MARGIN:
3210       g_value_set_int (value, priv->right_margin);
3211       break;
3212
3213     case PROP_INDENT:
3214       g_value_set_int (value, priv->indent);
3215       break;
3216
3217     case PROP_TABS:
3218       g_value_set_boxed (value, priv->tabs);
3219       break;
3220
3221     case PROP_CURSOR_VISIBLE:
3222       g_value_set_boolean (value, priv->cursor_visible);
3223       break;
3224
3225     case PROP_BUFFER:
3226       g_value_set_object (value, get_buffer (text_view));
3227       break;
3228
3229     case PROP_OVERWRITE:
3230       g_value_set_boolean (value, priv->overwrite_mode);
3231       break;
3232
3233     case PROP_ACCEPTS_TAB:
3234       g_value_set_boolean (value, priv->accepts_tab);
3235       break;
3236       
3237     case PROP_IM_MODULE:
3238       g_value_set_string (value, priv->im_module);
3239       break;
3240
3241     default:
3242       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3243       break;
3244     }
3245 }
3246
3247 static void
3248 gtk_text_view_size_request (GtkWidget      *widget,
3249                             GtkRequisition *requisition)
3250 {
3251   GtkTextView *text_view;
3252   GtkTextViewPrivate *priv;
3253   GSList *tmp_list;
3254   gint focus_edge_width;
3255   gint focus_width;
3256   guint border_width;
3257   gboolean interior_focus;
3258
3259   text_view = GTK_TEXT_VIEW (widget);
3260   priv = text_view->priv;
3261
3262   gtk_widget_style_get (widget,
3263                         "interior-focus", &interior_focus,
3264                         "focus-line-width", &focus_width,
3265                         NULL);
3266
3267   if (interior_focus)
3268     focus_edge_width = 0;
3269   else
3270     focus_edge_width = focus_width;
3271
3272   if (priv->layout)
3273     {
3274       priv->text_window->requisition.width = priv->layout->width;
3275       priv->text_window->requisition.height = priv->layout->height;
3276     }
3277   else
3278     {
3279       priv->text_window->requisition.width = 0;
3280       priv->text_window->requisition.height = 0;
3281     }
3282   
3283   requisition->width = priv->text_window->requisition.width + focus_edge_width * 2;
3284   requisition->height = priv->text_window->requisition.height + focus_edge_width * 2;
3285
3286   if (priv->left_window)
3287     requisition->width += priv->left_window->requisition.width;
3288
3289   if (priv->right_window)
3290     requisition->width += priv->right_window->requisition.width;
3291
3292   if (priv->top_window)
3293     requisition->height += priv->top_window->requisition.height;
3294
3295   if (priv->bottom_window)
3296     requisition->height += priv->bottom_window->requisition.height;
3297
3298   border_width = gtk_container_get_border_width (GTK_CONTAINER (text_view));
3299   requisition->width += border_width * 2;
3300   requisition->height += border_width * 2;
3301   
3302   tmp_list = priv->children;
3303   while (tmp_list != NULL)
3304     {
3305       GtkTextViewChild *child = tmp_list->data;
3306
3307       if (child->anchor)
3308         {
3309           GtkRequisition child_req;
3310           GtkRequisition old_req;
3311
3312           gtk_size_request_get_size (GTK_SIZE_REQUEST (child->widget),
3313                                      &old_req, NULL);
3314
3315           gtk_size_request_get_size (GTK_SIZE_REQUEST (child->widget),
3316                                      &child_req, NULL);
3317
3318           /* Invalidate layout lines if required */
3319           if (priv->layout &&
3320               (old_req.width != child_req.width ||
3321                old_req.height != child_req.height))
3322             gtk_text_child_anchor_queue_resize (child->anchor,
3323                                                 priv->layout);
3324         }
3325       else
3326         {
3327           GtkRequisition child_req;
3328
3329           gtk_size_request_get_size (GTK_SIZE_REQUEST (child->widget),
3330                                      &child_req, NULL);
3331         }
3332
3333       tmp_list = g_slist_next (tmp_list);
3334     }
3335
3336   /* Cache the requested size of the text view so we can 
3337    * compare it in the changed_handler() */
3338   priv->cached_size_request = *requisition;
3339 }
3340
3341 static void
3342 gtk_text_view_compute_child_allocation (GtkTextView      *text_view,
3343                                         GtkTextViewChild *vc,
3344                                         GtkAllocation    *allocation)
3345 {
3346   gint buffer_y;
3347   GtkTextIter iter;
3348   GtkRequisition req;
3349   
3350   gtk_text_buffer_get_iter_at_child_anchor (get_buffer (text_view),
3351                                             &iter,
3352                                             vc->anchor);
3353
3354   gtk_text_layout_get_line_yrange (text_view->priv->layout, &iter,
3355                                    &buffer_y, NULL);
3356
3357   buffer_y += vc->from_top_of_line;
3358
3359   allocation->x = vc->from_left_of_buffer - text_view->priv->xoffset;
3360   allocation->y = buffer_y - text_view->priv->yoffset;
3361
3362   gtk_size_request_get_size (GTK_SIZE_REQUEST (vc->widget),
3363                              &req, NULL);
3364   allocation->width = req.width;
3365   allocation->height = req.height;
3366 }
3367
3368 static void
3369 gtk_text_view_update_child_allocation (GtkTextView      *text_view,
3370                                        GtkTextViewChild *vc)
3371 {
3372   GtkAllocation allocation;
3373
3374   gtk_text_view_compute_child_allocation (text_view, vc, &allocation);
3375   
3376   gtk_widget_size_allocate (vc->widget, &allocation);
3377
3378 #if 0
3379   g_print ("allocation for %p allocated to %d,%d yoffset = %d\n",
3380            vc->widget,
3381            vc->widget->allocation.x,
3382            vc->widget->allocation.y,
3383            text_view->priv->yoffset);
3384 #endif
3385 }
3386
3387 static void
3388 gtk_text_view_child_allocated (GtkTextLayout *layout,
3389                                GtkWidget     *child,
3390                                gint           x,
3391                                gint           y,
3392                                gpointer       data)
3393 {
3394   GtkTextViewChild *vc = NULL;
3395   GtkTextView *text_view = data;
3396   
3397   /* x,y is the position of the child from the top of the line, and
3398    * from the left of the buffer. We have to translate that into text
3399    * window coordinates, then size_allocate the child.
3400    */
3401
3402   vc = g_object_get_data (G_OBJECT (child),
3403                           "gtk-text-view-child");
3404
3405   g_assert (vc != NULL);
3406
3407   DV (g_print ("child allocated at %d,%d\n", x, y));
3408   
3409   vc->from_left_of_buffer = x;
3410   vc->from_top_of_line = y;
3411
3412   gtk_text_view_update_child_allocation (text_view, vc);
3413 }
3414
3415 static void
3416 gtk_text_view_allocate_children (GtkTextView *text_view)
3417 {
3418   GSList *tmp_list;
3419
3420   DV(g_print(G_STRLOC"\n"));
3421   
3422   tmp_list = text_view->priv->children;
3423   while (tmp_list != NULL)
3424     {
3425       GtkTextViewChild *child = tmp_list->data;
3426
3427       g_assert (child != NULL);
3428           
3429       if (child->anchor)
3430         {
3431           /* We need to force-validate the regions containing
3432            * children.
3433            */
3434           GtkTextIter child_loc;
3435           gtk_text_buffer_get_iter_at_child_anchor (get_buffer (text_view),
3436                                                     &child_loc,
3437                                                     child->anchor);
3438
3439           /* Since anchored children are only ever allocated from
3440            * gtk_text_layout_get_line_display() we have to make sure
3441            * that the display line caching in the layout doesn't 
3442            * get in the way. Invalidating the layout around the anchor
3443            * achieves this.
3444            */ 
3445           if (GTK_WIDGET_ALLOC_NEEDED (child->widget))
3446             {
3447               GtkTextIter end = child_loc;
3448               gtk_text_iter_forward_char (&end);
3449               gtk_text_layout_invalidate (text_view->priv->layout, &child_loc, &end);
3450             }
3451
3452           gtk_text_layout_validate_yrange (text_view->priv->layout,
3453                                            &child_loc,
3454                                            0, 1);
3455         }
3456       else
3457         {
3458           GtkAllocation allocation;
3459           GtkRequisition child_req;
3460              
3461           allocation.x = child->x;
3462           allocation.y = child->y;
3463
3464           gtk_size_request_get_size (GTK_SIZE_REQUEST (child->widget),
3465                                      &child_req, NULL);
3466
3467           allocation.width = child_req.width;
3468           allocation.height = child_req.height;
3469           
3470           gtk_widget_size_allocate (child->widget, &allocation);          
3471         }
3472
3473       tmp_list = g_slist_next (tmp_list);
3474     }
3475 }
3476
3477 static void
3478 gtk_text_view_size_allocate (GtkWidget *widget,
3479                              GtkAllocation *allocation)
3480 {
3481   GtkAllocation widget_allocation;
3482   GtkTextView *text_view;
3483   GtkTextViewPrivate *priv;
3484   GtkTextIter first_para;
3485   gint y;
3486   gint width, height;
3487   GdkRectangle text_rect;
3488   GdkRectangle left_rect;
3489   GdkRectangle right_rect;
3490   GdkRectangle top_rect;
3491   GdkRectangle bottom_rect;
3492   gint focus_edge_width;
3493   gint focus_width;
3494   guint border_width;
3495   gboolean interior_focus;
3496   gboolean size_changed;
3497   
3498   text_view = GTK_TEXT_VIEW (widget);
3499   priv = text_view->priv;
3500
3501   DV(g_print(G_STRLOC"\n"));
3502
3503   gtk_widget_get_allocation (widget, &widget_allocation);
3504   size_changed =
3505     widget_allocation.width != allocation->width ||
3506     widget_allocation.height != allocation->height;
3507
3508   border_width = gtk_container_get_border_width (GTK_CONTAINER (text_view));
3509
3510   gtk_widget_set_allocation (widget, allocation);
3511
3512   if (gtk_widget_get_realized (widget))
3513     {
3514       gdk_window_move_resize (gtk_widget_get_window (widget),
3515                               allocation->x, allocation->y,
3516                               allocation->width, allocation->height);
3517     }
3518
3519   /* distribute width/height among child windows. Ensure all
3520    * windows get at least a 1x1 allocation.
3521    */
3522
3523   gtk_widget_style_get (widget,
3524                         "interior-focus", &interior_focus,
3525                         "focus-line-width", &focus_width,
3526                         NULL);
3527
3528   if (interior_focus)
3529     focus_edge_width = 0;
3530   else
3531     focus_edge_width = focus_width;
3532   
3533   width = allocation->width - focus_edge_width * 2 - border_width * 2;
3534
3535   if (priv->left_window)
3536     left_rect.width = priv->left_window->requisition.width;
3537   else
3538     left_rect.width = 0;
3539
3540   width -= left_rect.width;
3541
3542   if (priv->right_window)
3543     right_rect.width = priv->right_window->requisition.width;
3544   else
3545     right_rect.width = 0;
3546
3547   width -= right_rect.width;
3548
3549   text_rect.width = MAX (1, width);
3550
3551   top_rect.width = text_rect.width;
3552   bottom_rect.width = text_rect.width;
3553
3554
3555   height = allocation->height - focus_edge_width * 2 - border_width * 2;
3556
3557   if (priv->top_window)
3558     top_rect.height = priv->top_window->requisition.height;
3559   else
3560     top_rect.height = 0;
3561
3562   height -= top_rect.height;
3563
3564   if (priv->bottom_window)
3565     bottom_rect.height = priv->bottom_window->requisition.height;
3566   else
3567     bottom_rect.height = 0;
3568
3569   height -= bottom_rect.height;
3570
3571   text_rect.height = MAX (1, height);
3572
3573   left_rect.height = text_rect.height;
3574   right_rect.height = text_rect.height;
3575
3576   /* Origins */
3577   left_rect.x = focus_edge_width + border_width;
3578   top_rect.y = focus_edge_width + border_width;
3579
3580   text_rect.x = left_rect.x + left_rect.width;
3581   text_rect.y = top_rect.y + top_rect.height;
3582
3583   left_rect.y = text_rect.y;
3584   right_rect.y = text_rect.y;
3585
3586   top_rect.x = text_rect.x;
3587   bottom_rect.x = text_rect.x;
3588
3589   right_rect.x = text_rect.x + text_rect.width;
3590   bottom_rect.y = text_rect.y + text_rect.height;
3591
3592   text_window_size_allocate (priv->text_window,
3593                              &text_rect);
3594
3595   if (priv->left_window)
3596     text_window_size_allocate (priv->left_window,
3597                                &left_rect);
3598
3599   if (priv->right_window)
3600     text_window_size_allocate (priv->right_window,
3601                                &right_rect);
3602
3603   if (priv->top_window)
3604     text_window_size_allocate (priv->top_window,
3605                                &top_rect);
3606
3607   if (priv->bottom_window)
3608     text_window_size_allocate (priv->bottom_window,
3609                                &bottom_rect);
3610
3611   gtk_text_view_update_layout_width (text_view);
3612   
3613   /* Note that this will do some layout validation */
3614   gtk_text_view_allocate_children (text_view);
3615
3616   /* Ensure h/v adj exist */
3617   get_hadjustment (text_view);
3618   get_vadjustment (text_view);
3619
3620   priv->hadjustment->page_size = SCREEN_WIDTH (text_view);
3621   priv->hadjustment->page_increment = SCREEN_WIDTH (text_view) * 0.9;
3622   priv->hadjustment->step_increment = SCREEN_WIDTH (text_view) * 0.1;
3623   priv->hadjustment->lower = 0;
3624   priv->hadjustment->upper = MAX (SCREEN_WIDTH (text_view),
3625                                   priv->width);
3626
3627   if (priv->hadjustment->value > priv->hadjustment->upper - priv->hadjustment->page_size)
3628     gtk_adjustment_set_value (priv->hadjustment, MAX (0, priv->hadjustment->upper - priv->hadjustment->page_size));
3629
3630   gtk_adjustment_changed (priv->hadjustment);
3631
3632   priv->vadjustment->page_size = SCREEN_HEIGHT (text_view);
3633   priv->vadjustment->page_increment = SCREEN_HEIGHT (text_view) * 0.9;
3634   priv->vadjustment->step_increment = SCREEN_HEIGHT (text_view) * 0.1;
3635   priv->vadjustment->lower = 0;
3636   priv->vadjustment->upper = MAX (SCREEN_HEIGHT (text_view),
3637                                   priv->height);
3638
3639   /* Now adjust the value of the adjustment to keep the cursor at the
3640    * same place in the buffer
3641    */
3642   gtk_text_view_get_first_para_iter (text_view, &first_para);
3643   gtk_text_layout_get_line_yrange (priv->layout, &first_para, &y, NULL);
3644
3645   y += priv->first_para_pixels;
3646
3647   if (y > priv->vadjustment->upper - priv->vadjustment->page_size)
3648     y = MAX (0, priv->vadjustment->upper - priv->vadjustment->page_size);
3649
3650   if (y != priv->yoffset)
3651     gtk_adjustment_set_value (priv->vadjustment, y);
3652
3653   gtk_adjustment_changed (priv->vadjustment);
3654
3655   /* The GTK resize loop processes all the pending exposes right
3656    * after doing the resize stuff, so the idle sizer won't have a
3657    * chance to run. So we do the work here. 
3658    */
3659   gtk_text_view_flush_first_validate (text_view);
3660
3661   /* widget->window doesn't get auto-redrawn as the layout is computed, so has to
3662    * be invalidated
3663    */
3664   if (size_changed && gtk_widget_get_realized (widget))
3665     gdk_window_invalidate_rect (gtk_widget_get_window (widget), NULL, FALSE);
3666 }
3667
3668 static void
3669 gtk_text_view_get_first_para_iter (GtkTextView *text_view,
3670                                    GtkTextIter *iter)
3671 {
3672   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), iter,
3673                                     text_view->priv->first_para_mark);
3674 }
3675
3676 static void
3677 gtk_text_view_validate_onscreen (GtkTextView *text_view)
3678 {
3679   GtkWidget *widget;
3680   GtkTextViewPrivate *priv;
3681
3682   widget = GTK_WIDGET (text_view);
3683   priv = text_view->priv;
3684   
3685   DV(g_print(">Validating onscreen ("G_STRLOC")\n"));
3686   
3687   if (SCREEN_HEIGHT (widget) > 0)
3688     {
3689       GtkTextIter first_para;
3690
3691       /* Be sure we've validated the stuff onscreen; if we
3692        * scrolled, these calls won't have any effect, because
3693        * they were called in the recursive validate_onscreen
3694        */
3695       gtk_text_view_get_first_para_iter (text_view, &first_para);
3696
3697       gtk_text_layout_validate_yrange (priv->layout,
3698                                        &first_para,
3699                                        0,
3700                                        priv->first_para_pixels +
3701                                        SCREEN_HEIGHT (widget));
3702     }
3703
3704   priv->onscreen_validated = TRUE;
3705
3706   DV(g_print(">Done validating onscreen, onscreen_validated = TRUE ("G_STRLOC")\n"));
3707   
3708   /* This can have the odd side effect of triggering a scroll, which should
3709    * flip "onscreen_validated" back to FALSE, but should also get us
3710    * back into this function to turn it on again.
3711    */
3712   gtk_text_view_update_adjustments (text_view);
3713
3714   g_assert (priv->onscreen_validated);
3715 }
3716
3717 static void
3718 gtk_text_view_flush_first_validate (GtkTextView *text_view)
3719 {
3720   GtkTextViewPrivate *priv = text_view->priv;
3721
3722   if (priv->first_validate_idle == 0)
3723     return;
3724
3725   /* Do this first, which means that if an "invalidate"
3726    * occurs during any of this process, a new first_validate_callback
3727    * will be installed, and we'll start again.
3728    */
3729   DV (g_print ("removing first validate in %s\n", G_STRLOC));
3730   g_source_remove (priv->first_validate_idle);
3731   priv->first_validate_idle = 0;
3732   
3733   /* be sure we have up-to-date screen size set on the
3734    * layout.
3735    */
3736   gtk_text_view_update_layout_width (text_view);
3737
3738   /* Bail out if we invalidated stuff; scrolling right away will just
3739    * confuse the issue.
3740    */
3741   if (priv->first_validate_idle != 0)
3742     {
3743       DV(g_print(">Width change forced requeue ("G_STRLOC")\n"));
3744     }
3745   else
3746     {
3747       /* scroll to any marks, if that's pending. This can jump us to
3748        * the validation codepath used for scrolling onscreen, if so we
3749        * bail out.  It won't jump if already in that codepath since
3750        * value_changed is not recursive, so also validate if
3751        * necessary.
3752        */
3753       if (!gtk_text_view_flush_scroll (text_view) ||
3754           !priv->onscreen_validated)
3755         gtk_text_view_validate_onscreen (text_view);
3756       
3757       DV(g_print(">Leaving first validate idle ("G_STRLOC")\n"));
3758       
3759       g_assert (priv->onscreen_validated);
3760     }
3761 }
3762
3763 static gboolean
3764 first_validate_callback (gpointer data)
3765 {
3766   GtkTextView *text_view = data;
3767
3768   /* Note that some of this code is duplicated at the end of size_allocate,
3769    * keep in sync with that.
3770    */
3771   
3772   DV(g_print(G_STRLOC"\n"));
3773
3774   gtk_text_view_flush_first_validate (text_view);
3775   
3776   return FALSE;
3777 }
3778
3779 static gboolean
3780 incremental_validate_callback (gpointer data)
3781 {
3782   GtkTextView *text_view = data;
3783   gboolean result = TRUE;
3784
3785   DV(g_print(G_STRLOC"\n"));
3786   
3787   gtk_text_layout_validate (text_view->priv->layout, 2000);
3788
3789   gtk_text_view_update_adjustments (text_view);
3790   
3791   if (gtk_text_layout_is_valid (text_view->priv->layout))
3792     {
3793       text_view->priv->incremental_validate_idle = 0;
3794       result = FALSE;
3795     }
3796
3797   return result;
3798 }
3799
3800 static void
3801 gtk_text_view_invalidate (GtkTextView *text_view)
3802 {
3803   GtkTextViewPrivate *priv = text_view->priv;
3804
3805   DV (g_print (">Invalidate, onscreen_validated = %d now FALSE ("G_STRLOC")\n",
3806                priv->onscreen_validated));
3807
3808   priv->onscreen_validated = FALSE;
3809
3810   /* We'll invalidate when the layout is created */
3811   if (priv->layout == NULL)
3812     return;
3813   
3814   if (!priv->first_validate_idle)
3815     {
3816       priv->first_validate_idle = gdk_threads_add_idle_full (GTK_PRIORITY_RESIZE - 2, first_validate_callback, text_view, NULL);
3817       DV (g_print (G_STRLOC": adding first validate idle %d\n",
3818                    priv->first_validate_idle));
3819     }
3820       
3821   if (!priv->incremental_validate_idle)
3822     {
3823       priv->incremental_validate_idle = gdk_threads_add_idle_full (GTK_TEXT_VIEW_PRIORITY_VALIDATE, incremental_validate_callback, text_view, NULL);
3824       DV (g_print (G_STRLOC": adding incremental validate idle %d\n",
3825                    priv->incremental_validate_idle));
3826     }
3827 }
3828
3829 static void
3830 invalidated_handler (GtkTextLayout *layout,
3831                      gpointer       data)
3832 {
3833   GtkTextView *text_view;
3834
3835   text_view = GTK_TEXT_VIEW (data);
3836
3837   DV (g_print ("Invalidating due to layout invalidate signal\n"));
3838   gtk_text_view_invalidate (text_view);
3839 }
3840
3841 static void
3842 changed_handler (GtkTextLayout     *layout,
3843                  gint               start_y,
3844                  gint               old_height,
3845                  gint               new_height,
3846                  gpointer           data)
3847 {
3848   GtkTextView *text_view;
3849   GtkTextViewPrivate *priv;
3850   GtkWidget *widget;
3851   GdkRectangle visible_rect;
3852   GdkRectangle redraw_rect;
3853   
3854   text_view = GTK_TEXT_VIEW (data);
3855   priv = text_view->priv;
3856   widget = GTK_WIDGET (data);
3857   
3858   DV(g_print(">Lines Validated ("G_STRLOC")\n"));
3859
3860   if (gtk_widget_get_realized (widget))
3861     {      
3862       gtk_text_view_get_visible_rect (text_view, &visible_rect);
3863
3864       redraw_rect.x = visible_rect.x;
3865       redraw_rect.width = visible_rect.width;
3866       redraw_rect.y = start_y;
3867
3868       if (old_height == new_height)
3869         redraw_rect.height = old_height;
3870       else if (start_y + old_height > visible_rect.y)
3871         redraw_rect.height = MAX (0, visible_rect.y + visible_rect.height - start_y);
3872       else
3873         redraw_rect.height = 0;
3874         
3875       if (gdk_rectangle_intersect (&redraw_rect, &visible_rect, &redraw_rect))
3876         {
3877           /* text_window_invalidate_rect() takes buffer coordinates */
3878           text_window_invalidate_rect (priv->text_window,
3879                                        &redraw_rect);
3880
3881           DV(g_print(" invalidated rect: %d,%d %d x %d\n",
3882                      redraw_rect.x,
3883                      redraw_rect.y,
3884                      redraw_rect.width,
3885                      redraw_rect.height));
3886           
3887           if (priv->left_window)
3888             text_window_invalidate_rect (priv->left_window,
3889                                          &redraw_rect);
3890           if (priv->right_window)
3891             text_window_invalidate_rect (priv->right_window,
3892                                          &redraw_rect);
3893           if (priv->top_window)
3894             text_window_invalidate_rect (priv->top_window,
3895                                          &redraw_rect);
3896           if (priv->bottom_window)
3897             text_window_invalidate_rect (priv->bottom_window,
3898                                          &redraw_rect);
3899
3900           queue_update_im_spot_location (text_view);
3901         }
3902     }
3903   
3904   if (old_height != new_height)
3905     {
3906       gboolean yoffset_changed = FALSE;
3907       GSList *tmp_list;
3908       int new_first_para_top;
3909       int old_first_para_top;
3910       GtkTextIter first;
3911       
3912       /* If the bottom of the old area was above the top of the
3913        * screen, we need to scroll to keep the current top of the
3914        * screen in place.  Remember that first_para_pixels is the
3915        * position of the top of the screen in coordinates relative to
3916        * the first paragraph onscreen.
3917        *
3918        * In short we are adding the height delta of the portion of the
3919        * changed region above first_para_mark to priv->yoffset.
3920        */
3921       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &first,
3922                                         priv->first_para_mark);
3923
3924       gtk_text_layout_get_line_yrange (layout, &first, &new_first_para_top, NULL);
3925
3926       old_first_para_top = priv->yoffset - priv->first_para_pixels;
3927
3928       if (new_first_para_top != old_first_para_top)
3929         {
3930           priv->yoffset += new_first_para_top - old_first_para_top;
3931           
3932           get_vadjustment (text_view)->value = priv->yoffset;
3933           yoffset_changed = TRUE;
3934         }
3935
3936       if (yoffset_changed)
3937         {
3938           DV(g_print ("Changing scroll position (%s)\n", G_STRLOC));
3939           gtk_adjustment_value_changed (get_vadjustment (text_view));
3940         }
3941
3942       /* FIXME be smarter about which anchored widgets we update */
3943
3944       tmp_list = priv->children;
3945       while (tmp_list != NULL)
3946         {
3947           GtkTextViewChild *child = tmp_list->data;
3948
3949           if (child->anchor)
3950             gtk_text_view_update_child_allocation (text_view, child);
3951
3952           tmp_list = g_slist_next (tmp_list);
3953         }
3954     }
3955
3956   {
3957     GtkRequisition old_req = priv->cached_size_request;
3958     GtkRequisition new_req;
3959
3960     /* Use this instead of gtk_widget_size_request wrapper
3961      * to avoid the optimization which just returns widget->requisition
3962      * if a resize hasn't been queued.
3963      */
3964     GTK_WIDGET_GET_CLASS (widget)->size_request (widget, &new_req);
3965
3966     if (old_req.width != new_req.width ||
3967         old_req.height != new_req.height)
3968       {
3969         gtk_widget_queue_resize_no_redraw (widget);
3970       }
3971   }
3972 }
3973
3974 static void
3975 gtk_text_view_realize (GtkWidget *widget)
3976 {
3977   GtkAllocation allocation;
3978   GtkTextView *text_view;
3979   GtkTextViewPrivate *priv;
3980   GdkWindow *window;
3981   GdkWindowAttr attributes;
3982   gint attributes_mask;
3983   GSList *tmp_list;
3984   
3985   text_view = GTK_TEXT_VIEW (widget);
3986   priv = text_view->priv;
3987
3988   gtk_widget_set_realized (widget, TRUE);
3989
3990   gtk_widget_get_allocation (widget, &allocation);
3991
3992   attributes.window_type = GDK_WINDOW_CHILD;
3993   attributes.x = allocation.x;
3994   attributes.y = allocation.y;
3995   attributes.width = allocation.width;
3996   attributes.height = allocation.height;
3997   attributes.wclass = GDK_INPUT_OUTPUT;
3998   attributes.visual = gtk_widget_get_visual (widget);
3999   attributes.colormap = gtk_widget_get_colormap (widget);
4000   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK | GDK_EXPOSURE_MASK;
4001
4002   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
4003
4004   window = gdk_window_new (gtk_widget_get_parent_window (widget),
4005                            &attributes, attributes_mask);
4006   gtk_widget_set_window (widget, window);
4007   gdk_window_set_user_data (window, widget);
4008
4009   /* must come before text_window_realize calls */
4010   gtk_widget_style_attach (widget);
4011
4012   gdk_window_set_background (window,
4013                              &gtk_widget_get_style (widget)->bg[gtk_widget_get_state (widget)]);
4014
4015   text_window_realize (priv->text_window, widget);
4016
4017   if (priv->left_window)
4018     text_window_realize (priv->left_window, widget);
4019
4020   if (priv->top_window)
4021     text_window_realize (priv->top_window, widget);
4022
4023   if (priv->right_window)
4024     text_window_realize (priv->right_window, widget);
4025
4026   if (priv->bottom_window)
4027     text_window_realize (priv->bottom_window, widget);
4028
4029   gtk_text_view_ensure_layout (text_view);
4030
4031   if (priv->buffer)
4032     {
4033       GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4034                                                           GDK_SELECTION_PRIMARY);
4035       gtk_text_buffer_add_selection_clipboard (priv->buffer, clipboard);
4036     }
4037
4038   tmp_list = priv->children;
4039   while (tmp_list != NULL)
4040     {
4041       GtkTextViewChild *vc = tmp_list->data;
4042       
4043       text_view_child_set_parent_window (text_view, vc);
4044       
4045       tmp_list = tmp_list->next;
4046     }
4047
4048   /* Ensure updating the spot location. */
4049   gtk_text_view_update_im_spot_location (text_view);
4050 }
4051
4052 static void
4053 gtk_text_view_unrealize (GtkWidget *widget)
4054 {
4055   GtkTextView *text_view;
4056   GtkTextViewPrivate *priv;
4057
4058   text_view = GTK_TEXT_VIEW (widget);
4059   priv = text_view->priv;
4060
4061   if (priv->buffer)
4062     {
4063       GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4064                                                           GDK_SELECTION_PRIMARY);
4065       gtk_text_buffer_remove_selection_clipboard (priv->buffer, clipboard);
4066     }
4067
4068   gtk_text_view_remove_validate_idles (text_view);
4069
4070   if (priv->popup_menu)
4071     {
4072       gtk_widget_destroy (priv->popup_menu);
4073       priv->popup_menu = NULL;
4074     }
4075
4076   text_window_unrealize (priv->text_window);
4077
4078   if (priv->left_window)
4079     text_window_unrealize (priv->left_window);
4080
4081   if (priv->top_window)
4082     text_window_unrealize (priv->top_window);
4083
4084   if (priv->right_window)
4085     text_window_unrealize (priv->right_window);
4086
4087   if (priv->bottom_window)
4088     text_window_unrealize (priv->bottom_window);
4089
4090   gtk_text_view_destroy_layout (text_view);
4091
4092   GTK_WIDGET_CLASS (gtk_text_view_parent_class)->unrealize (widget);
4093 }
4094
4095 static void
4096 gtk_text_view_set_background (GtkTextView *text_view)
4097 {
4098   GtkStyle *style;
4099   GtkStateType state;
4100   GtkWidget *widget;
4101   GtkTextViewPrivate *priv;
4102
4103   widget = GTK_WIDGET (text_view);
4104   priv = text_view->priv;
4105
4106   style = gtk_widget_get_style (widget);
4107   state = gtk_widget_get_state (widget);
4108
4109   gdk_window_set_background (gtk_widget_get_window (widget),
4110                              &style->bg[state]);
4111
4112   gdk_window_set_background (priv->text_window->bin_window,
4113                              &style->base[state]);
4114
4115   if (priv->left_window)
4116     gdk_window_set_background (priv->left_window->bin_window,
4117                                &style->bg[state]);
4118   if (priv->right_window)
4119     gdk_window_set_background (priv->right_window->bin_window,
4120                                &style->bg[state]);
4121
4122   if (priv->top_window)
4123     gdk_window_set_background (priv->top_window->bin_window,
4124                                &style->bg[state]);
4125
4126   if (priv->bottom_window)
4127     gdk_window_set_background (priv->bottom_window->bin_window,
4128                                &style->bg[state]);
4129 }
4130
4131 static void
4132 gtk_text_view_style_set (GtkWidget *widget,
4133                          GtkStyle  *previous_style)
4134 {
4135   GtkTextView *text_view;
4136   GtkTextViewPrivate *priv;
4137   PangoContext *ltr_context, *rtl_context;
4138
4139   text_view = GTK_TEXT_VIEW (widget);
4140   priv = text_view->priv;
4141
4142   if (gtk_widget_get_realized (widget))
4143     {
4144       gtk_text_view_set_background (text_view);
4145     }
4146
4147   if (priv->layout && previous_style)
4148     {
4149       gtk_text_view_set_attributes_from_style (text_view,
4150                                                priv->layout->default_style,
4151                                                gtk_widget_get_style (widget));
4152
4153       ltr_context = gtk_widget_create_pango_context (widget);
4154       pango_context_set_base_dir (ltr_context, PANGO_DIRECTION_LTR);
4155       rtl_context = gtk_widget_create_pango_context (widget);
4156       pango_context_set_base_dir (rtl_context, PANGO_DIRECTION_RTL);
4157
4158       gtk_text_layout_set_contexts (priv->layout, ltr_context, rtl_context);
4159
4160       g_object_unref (ltr_context);
4161       g_object_unref (rtl_context);
4162     }
4163 }
4164
4165 static void
4166 gtk_text_view_direction_changed (GtkWidget        *widget,
4167                                  GtkTextDirection  previous_direction)
4168 {
4169   GtkTextViewPrivate *priv = GTK_TEXT_VIEW (widget)->priv;
4170
4171   if (priv->layout)
4172     {
4173       priv->layout->default_style->direction = gtk_widget_get_direction (widget);
4174
4175       gtk_text_layout_default_style_changed (priv->layout);
4176     }
4177 }
4178
4179 static void
4180 gtk_text_view_state_changed (GtkWidget      *widget,
4181                              GtkStateType    previous_state)
4182 {
4183   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4184   GdkCursor *cursor;
4185
4186   if (gtk_widget_get_realized (widget))
4187     {
4188       gtk_text_view_set_background (text_view);
4189
4190       if (gtk_widget_is_sensitive (widget))
4191         cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget), GDK_XTERM);
4192       else
4193         cursor = NULL;
4194
4195       gdk_window_set_cursor (text_view->priv->text_window->bin_window, cursor);
4196
4197       if (cursor)
4198       gdk_cursor_unref (cursor);
4199
4200       text_view->priv->mouse_cursor_obscured = FALSE;
4201     }
4202
4203   if (!gtk_widget_is_sensitive (widget))
4204     {
4205       /* Clear any selection */
4206       gtk_text_view_unselect (text_view);
4207     }
4208   
4209   gtk_widget_queue_draw (widget);
4210 }
4211
4212 static void
4213 set_invisible_cursor (GdkWindow *window)
4214 {
4215   GdkDisplay *display;
4216   GdkCursor *cursor;
4217
4218   display = gdk_drawable_get_display (window);
4219   cursor = gdk_cursor_new_for_display (display, GDK_BLANK_CURSOR);
4220  
4221   gdk_window_set_cursor (window, cursor);
4222   
4223   gdk_cursor_unref (cursor);
4224 }
4225
4226 static void
4227 gtk_text_view_obscure_mouse_cursor (GtkTextView *text_view)
4228 {
4229   if (text_view->priv->mouse_cursor_obscured)
4230     return;
4231
4232   set_invisible_cursor (text_view->priv->text_window->bin_window);
4233   
4234   text_view->priv->mouse_cursor_obscured = TRUE;
4235 }
4236
4237 static void
4238 gtk_text_view_unobscure_mouse_cursor (GtkTextView *text_view)
4239 {
4240   if (text_view->priv->mouse_cursor_obscured)
4241     {
4242       GdkCursor *cursor;
4243       
4244       cursor = gdk_cursor_new_for_display (gtk_widget_get_display (GTK_WIDGET (text_view)),
4245                                            GDK_XTERM);
4246       gdk_window_set_cursor (text_view->priv->text_window->bin_window, cursor);
4247       gdk_cursor_unref (cursor);
4248       text_view->priv->mouse_cursor_obscured = FALSE;
4249     }
4250 }
4251
4252 static void
4253 gtk_text_view_grab_notify (GtkWidget *widget,
4254                            gboolean   was_grabbed)
4255 {
4256   GtkTextViewPrivate *priv;
4257
4258   priv = GTK_TEXT_VIEW (widget)->priv;
4259
4260   if (priv->grab_device &&
4261       gtk_widget_device_is_shadowed (widget, priv->grab_device))
4262     {
4263       gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget));
4264       gtk_text_view_unobscure_mouse_cursor (GTK_TEXT_VIEW (widget));
4265     }
4266 }
4267
4268
4269 /*
4270  * Events
4271  */
4272
4273 static gboolean
4274 get_event_coordinates (GdkEvent *event, gint *x, gint *y)
4275 {
4276   if (event)
4277     switch (event->type)
4278       {
4279       case GDK_MOTION_NOTIFY:
4280         *x = event->motion.x;
4281         *y = event->motion.y;
4282         return TRUE;
4283         break;
4284
4285       case GDK_BUTTON_PRESS:
4286       case GDK_2BUTTON_PRESS:
4287       case GDK_3BUTTON_PRESS:
4288       case GDK_BUTTON_RELEASE:
4289         *x = event->button.x;
4290         *y = event->button.y;
4291         return TRUE;
4292         break;
4293
4294       case GDK_KEY_PRESS:
4295       case GDK_KEY_RELEASE:
4296       case GDK_ENTER_NOTIFY:
4297       case GDK_LEAVE_NOTIFY:
4298       case GDK_PROPERTY_NOTIFY:
4299       case GDK_SELECTION_CLEAR:
4300       case GDK_SELECTION_REQUEST:
4301       case GDK_SELECTION_NOTIFY:
4302       case GDK_PROXIMITY_IN:
4303       case GDK_PROXIMITY_OUT:
4304       case GDK_DRAG_ENTER:
4305       case GDK_DRAG_LEAVE:
4306       case GDK_DRAG_MOTION:
4307       case GDK_DRAG_STATUS:
4308       case GDK_DROP_START:
4309       case GDK_DROP_FINISHED:
4310       default:
4311         return FALSE;
4312         break;
4313       }
4314
4315   return FALSE;
4316 }
4317
4318 static gint
4319 emit_event_on_tags (GtkWidget   *widget,
4320                     GdkEvent    *event,
4321                     GtkTextIter *iter)
4322 {
4323   GSList *tags;
4324   GSList *tmp;
4325   gboolean retval = FALSE;
4326
4327   tags = gtk_text_iter_get_tags (iter);
4328
4329   tmp = tags;
4330   while (tmp != NULL)
4331     {
4332       GtkTextTag *tag = tmp->data;
4333
4334       if (gtk_text_tag_event (tag, G_OBJECT (widget), event, iter))
4335         {
4336           retval = TRUE;
4337           break;
4338         }
4339
4340       tmp = g_slist_next (tmp);
4341     }
4342
4343   g_slist_free (tags);
4344
4345   return retval;
4346 }
4347
4348 static gint
4349 gtk_text_view_event (GtkWidget *widget, GdkEvent *event)
4350 {
4351   GtkTextView *text_view;
4352   GtkTextViewPrivate *priv;
4353   gint x = 0, y = 0;
4354
4355   text_view = GTK_TEXT_VIEW (widget);
4356   priv = text_view->priv;
4357
4358   if (priv->layout == NULL ||
4359       get_buffer (text_view) == NULL)
4360     return FALSE;
4361
4362   if (event->any.window != priv->text_window->bin_window)
4363     return FALSE;
4364
4365   if (get_event_coordinates (event, &x, &y))
4366     {
4367       GtkTextIter iter;
4368
4369       x += priv->xoffset;
4370       y += priv->yoffset;
4371
4372       /* FIXME this is slow and we do it twice per event.
4373        * My favorite solution is to have GtkTextLayout cache
4374        * the last couple lookups.
4375        */
4376       gtk_text_layout_get_iter_at_pixel (priv->layout,
4377                                          &iter,
4378                                          x, y);
4379
4380       return emit_event_on_tags (widget, event, &iter);
4381     }
4382   else if (event->type == GDK_KEY_PRESS ||
4383            event->type == GDK_KEY_RELEASE)
4384     {
4385       GtkTextIter iter;
4386
4387       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter,
4388                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
4389
4390       return emit_event_on_tags (widget, event, &iter);
4391     }
4392   else
4393     return FALSE;
4394 }
4395
4396 static gint
4397 gtk_text_view_key_press_event (GtkWidget *widget, GdkEventKey *event)
4398 {
4399   GtkTextView *text_view;
4400   GtkTextViewPrivate *priv;
4401   GtkTextMark *insert;
4402   GtkTextIter iter;
4403   gboolean can_insert;
4404   gboolean retval = FALSE;
4405   gboolean obscure = FALSE;
4406
4407   text_view = GTK_TEXT_VIEW (widget);
4408   priv = text_view->priv;
4409   
4410   if (priv->layout == NULL ||
4411       get_buffer (text_view) == NULL)
4412     return FALSE;
4413
4414   /* Make sure input method knows where it is */
4415   flush_update_im_spot_location (text_view);
4416
4417   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4418   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4419   can_insert = gtk_text_iter_can_insert (&iter, priv->editable);
4420   if (gtk_im_context_filter_keypress (priv->im_context, event))
4421     {
4422       priv->need_im_reset = TRUE;
4423       if (!can_insert)
4424         gtk_text_view_reset_im_context (text_view);
4425       obscure = can_insert;
4426       retval = TRUE;
4427     }
4428   /* Binding set */
4429   else if (GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_press_event (widget, event))
4430     {
4431       retval = TRUE;
4432     }
4433   /* use overall editability not can_insert, more predictable for users */
4434   else if (priv->editable &&
4435            (event->keyval == GDK_KEY_Return ||
4436             event->keyval == GDK_KEY_ISO_Enter ||
4437             event->keyval == GDK_KEY_KP_Enter))
4438     {
4439       /* this won't actually insert the newline if the cursor isn't
4440        * editable
4441        */
4442       gtk_text_view_reset_im_context (text_view);
4443       gtk_text_view_commit_text (text_view, "\n");
4444
4445       obscure = TRUE;
4446       retval = TRUE;
4447     }
4448   /* Pass through Tab as literal tab, unless Control is held down */
4449   else if ((event->keyval == GDK_KEY_Tab ||
4450             event->keyval == GDK_KEY_KP_Tab ||
4451             event->keyval == GDK_KEY_ISO_Left_Tab) &&
4452            !(event->state & GDK_CONTROL_MASK))
4453     {
4454       /* If the text widget isn't editable overall, or if the application
4455        * has turned off "accepts_tab", move the focus instead
4456        */
4457       if (priv->accepts_tab && priv->editable)
4458         {
4459           gtk_text_view_reset_im_context (text_view);
4460           gtk_text_view_commit_text (text_view, "\t");
4461           obscure = TRUE;
4462         }
4463       else
4464         g_signal_emit_by_name (text_view, "move-focus",
4465                                (event->state & GDK_SHIFT_MASK) ?
4466                                GTK_DIR_TAB_BACKWARD : GTK_DIR_TAB_FORWARD);
4467
4468       retval = TRUE;
4469     }
4470   else
4471     retval = FALSE;
4472
4473   if (obscure)
4474     gtk_text_view_obscure_mouse_cursor (text_view);
4475   
4476   gtk_text_view_reset_blink_time (text_view);
4477   gtk_text_view_pend_cursor_blink (text_view);
4478
4479   return retval;
4480 }
4481
4482 static gint
4483 gtk_text_view_key_release_event (GtkWidget *widget, GdkEventKey *event)
4484 {
4485   GtkTextView *text_view;
4486   GtkTextViewPrivate *priv;
4487   GtkTextMark *insert;
4488   GtkTextIter iter;
4489
4490   text_view = GTK_TEXT_VIEW (widget);
4491   priv = text_view->priv;
4492
4493   if (priv->layout == NULL || get_buffer (text_view) == NULL)
4494     return FALSE;
4495       
4496   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4497   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4498   if (gtk_text_iter_can_insert (&iter, priv->editable) &&
4499       gtk_im_context_filter_keypress (priv->im_context, event))
4500     {
4501       priv->need_im_reset = TRUE;
4502       return TRUE;
4503     }
4504   else
4505     return GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_release_event (widget, event);
4506 }
4507
4508 static gint
4509 gtk_text_view_button_press_event (GtkWidget *widget, GdkEventButton *event)
4510 {
4511   GtkTextView *text_view;
4512   GtkTextViewPrivate *priv;
4513
4514   text_view = GTK_TEXT_VIEW (widget);
4515   priv = text_view->priv;
4516
4517   gtk_widget_grab_focus (widget);
4518
4519   if (event->window != priv->text_window->bin_window)
4520     {
4521       /* Remove selection if any. */
4522       gtk_text_view_unselect (text_view);
4523       return FALSE;
4524     }
4525
4526   gtk_text_view_reset_blink_time (text_view);
4527
4528 #if 0
4529   /* debug hack */
4530   if (event->button == 3 && (event->state & GDK_CONTROL_MASK) != 0)
4531     _gtk_text_buffer_spew (GTK_TEXT_VIEW (widget)->buffer);
4532   else if (event->button == 3)
4533     gtk_text_layout_spew (GTK_TEXT_VIEW (widget)->layout);
4534 #endif
4535
4536   if (event->type == GDK_BUTTON_PRESS)
4537     {
4538       gtk_text_view_reset_im_context (text_view);
4539
4540       if (event->button == 1)
4541         {
4542           /* If we're in the selection, start a drag copy/move of the
4543            * selection; otherwise, start creating a new selection.
4544            */
4545           GtkTextIter iter;
4546           GtkTextIter start, end;
4547
4548           gtk_text_layout_get_iter_at_pixel (priv->layout,
4549                                              &iter,
4550                                              event->x + priv->xoffset,
4551                                              event->y + priv->yoffset);
4552
4553           if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
4554                                                     &start, &end) &&
4555               gtk_text_iter_in_range (&iter, &start, &end) &&
4556               !(event->state & GDK_SHIFT_MASK))
4557             {
4558               priv->drag_start_x = event->x;
4559               priv->drag_start_y = event->y;
4560               priv->pending_place_cursor_button = event->button;
4561             }
4562           else
4563             {
4564               gtk_text_view_start_selection_drag (text_view, &iter, event);
4565             }
4566
4567           return TRUE;
4568         }
4569       else if (event->button == 2)
4570         {
4571           GtkTextIter iter;
4572
4573           /* We do not want to scroll back to the insert iter when we paste
4574              with the middle button */
4575           priv->scroll_after_paste = FALSE;
4576
4577           gtk_text_layout_get_iter_at_pixel (priv->layout,
4578                                              &iter,
4579                                              event->x + priv->xoffset,
4580                                              event->y + priv->yoffset);
4581
4582           gtk_text_buffer_paste_clipboard (get_buffer (text_view),
4583                                            gtk_widget_get_clipboard (widget, GDK_SELECTION_PRIMARY),
4584                                            &iter,
4585                                            priv->editable);
4586           return TRUE;
4587         }
4588       else if (event->button == 3)
4589         {
4590           gtk_text_view_do_popup (text_view, event);
4591           return TRUE;
4592         }
4593     }
4594   else if ((event->type == GDK_2BUTTON_PRESS ||
4595             event->type == GDK_3BUTTON_PRESS) &&
4596            event->button == 1) 
4597     {
4598       GtkTextIter iter;
4599
4600       gtk_text_view_end_selection_drag (text_view);
4601
4602       gtk_text_layout_get_iter_at_pixel (priv->layout,
4603                                          &iter,
4604                                          event->x + priv->xoffset,
4605                                          event->y + priv->yoffset);
4606       
4607       gtk_text_view_start_selection_drag (text_view, &iter, event);
4608       return TRUE;
4609     }
4610   
4611   return FALSE;
4612 }
4613
4614 static gint
4615 gtk_text_view_button_release_event (GtkWidget *widget, GdkEventButton *event)
4616 {
4617   GtkTextView *text_view;
4618   GtkTextViewPrivate *priv;
4619
4620   text_view = GTK_TEXT_VIEW (widget);
4621   priv = text_view->priv;
4622
4623   if (event->window != priv->text_window->bin_window)
4624     return FALSE;
4625
4626   if (event->button == 1)
4627     {
4628       if (priv->drag_start_x >= 0)
4629         {
4630           priv->drag_start_x = -1;
4631           priv->drag_start_y = -1;
4632         }
4633
4634       if (gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget)))
4635         return TRUE;
4636       else if (priv->pending_place_cursor_button == event->button)
4637         {
4638           GtkTextIter iter;
4639
4640           /* Unselect everything; we clicked inside selection, but
4641            * didn't move by the drag threshold, so just clear selection
4642            * and place cursor.
4643            */
4644           gtk_text_layout_get_iter_at_pixel (priv->layout,
4645                                              &iter,
4646                                              event->x + priv->xoffset,
4647                                              event->y + priv->yoffset);
4648
4649           gtk_text_buffer_place_cursor (get_buffer (text_view), &iter);
4650           gtk_text_view_check_cursor_blink (text_view);
4651           
4652           priv->pending_place_cursor_button = 0;
4653           
4654           return FALSE;
4655         }
4656     }
4657
4658   return FALSE;
4659 }
4660
4661 static void
4662 keymap_direction_changed (GdkKeymap   *keymap,
4663                           GtkTextView *text_view)
4664 {
4665   gtk_text_view_check_keymap_direction (text_view);
4666 }
4667
4668 static gint
4669 gtk_text_view_focus_in_event (GtkWidget *widget, GdkEventFocus *event)
4670 {
4671   GtkTextView *text_view;
4672   GtkTextViewPrivate *priv;
4673
4674   text_view = GTK_TEXT_VIEW (widget);
4675   priv = text_view->priv;
4676
4677   gtk_widget_queue_draw (widget);
4678
4679   DV(g_print (G_STRLOC": focus_in_event\n"));
4680
4681   gtk_text_view_reset_blink_time (text_view);
4682
4683   if (priv->cursor_visible && priv->layout)
4684     {
4685       gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
4686       gtk_text_view_check_cursor_blink (text_view);
4687     }
4688
4689   g_signal_connect (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
4690                     "direction-changed",
4691                     G_CALLBACK (keymap_direction_changed), text_view);
4692   gtk_text_view_check_keymap_direction (text_view);
4693
4694   if (priv->editable)
4695     {
4696       priv->need_im_reset = TRUE;
4697       gtk_im_context_focus_in (priv->im_context);
4698     }
4699
4700   return FALSE;
4701 }
4702
4703 static gint
4704 gtk_text_view_focus_out_event (GtkWidget *widget, GdkEventFocus *event)
4705 {
4706   GtkTextView *text_view;
4707   GtkTextViewPrivate *priv;
4708
4709   text_view = GTK_TEXT_VIEW (widget);
4710   priv = text_view->priv;
4711
4712   gtk_text_view_end_selection_drag (text_view);
4713
4714   gtk_widget_queue_draw (widget);
4715
4716   DV(g_print (G_STRLOC": focus_out_event\n"));
4717   
4718   if (priv->cursor_visible && priv->layout)
4719     {
4720       gtk_text_view_check_cursor_blink (text_view);
4721       gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
4722     }
4723
4724   g_signal_handlers_disconnect_by_func (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
4725                                         keymap_direction_changed,
4726                                         text_view);
4727
4728   if (priv->editable)
4729     {
4730       priv->need_im_reset = TRUE;
4731       gtk_im_context_focus_out (priv->im_context);
4732     }
4733
4734   return FALSE;
4735 }
4736
4737 static gint
4738 gtk_text_view_motion_event (GtkWidget *widget, GdkEventMotion *event)
4739 {
4740   GtkTextView *text_view;
4741   GtkTextViewPrivate *priv;
4742
4743   text_view = GTK_TEXT_VIEW (widget);
4744   priv = text_view->priv;
4745
4746   gtk_text_view_unobscure_mouse_cursor (text_view);
4747
4748   if (event->window == priv->text_window->bin_window &&
4749       priv->drag_start_x >= 0)
4750     {
4751       gint x = event->x;
4752       gint y = event->y;
4753
4754       gdk_event_request_motions (event);
4755
4756       if (gtk_drag_check_threshold (widget,
4757                                     priv->drag_start_x, 
4758                                     priv->drag_start_y,
4759                                     x, y))
4760         {
4761           GtkTextIter iter;
4762           gint buffer_x, buffer_y;
4763
4764           gtk_text_view_window_to_buffer_coords (text_view,
4765                                                  GTK_TEXT_WINDOW_TEXT,
4766                                                  priv->drag_start_x,
4767                                                  priv->drag_start_y,
4768                                                  &buffer_x,
4769                                                  &buffer_y);
4770
4771           gtk_text_layout_get_iter_at_pixel (priv->layout,
4772                                              &iter,
4773                                              buffer_x, buffer_y);
4774
4775           gtk_text_view_start_selection_dnd (text_view, &iter, event);
4776           return TRUE;
4777         }
4778     }
4779
4780   return FALSE;
4781 }
4782
4783 static void
4784 gtk_text_view_paint (GtkWidget      *widget,
4785                      GdkRectangle   *area,
4786                      GdkEventExpose *event)
4787 {
4788   GtkTextView *text_view;
4789   GtkTextViewPrivate *priv;
4790   GList *child_exposes;
4791   GList *tmp_list;
4792   cairo_t *cr;
4793   
4794   text_view = GTK_TEXT_VIEW (widget);
4795   priv = text_view->priv;
4796
4797   g_return_if_fail (priv->layout != NULL);
4798   g_return_if_fail (priv->xoffset >= 0);
4799   g_return_if_fail (priv->yoffset >= 0);
4800
4801   while (priv->first_validate_idle != 0)
4802     {
4803       DV (g_print (G_STRLOC": first_validate_idle: %d\n",
4804                    priv->first_validate_idle));
4805       gtk_text_view_flush_first_validate (text_view);
4806     }
4807
4808   if (!priv->onscreen_validated)
4809     {
4810       g_warning (G_STRLOC ": somehow some text lines were modified or scrolling occurred since the last validation of lines on the screen - may be a text widget bug.");
4811       g_assert_not_reached ();
4812     }
4813   
4814 #if 0
4815   printf ("painting %d,%d  %d x %d\n",
4816           area->x, area->y,
4817           area->width, area->height);
4818 #endif
4819
4820   child_exposes = NULL;
4821
4822   cr = gdk_cairo_create (priv->text_window->bin_window);
4823
4824   gdk_cairo_region (cr, event->region);
4825   cairo_clip (cr);
4826
4827   cairo_translate (cr, -priv->xoffset, -priv->yoffset);
4828
4829   gtk_text_layout_draw (priv->layout,
4830                         widget,
4831                         cr,
4832                         &child_exposes);
4833
4834   cairo_destroy (cr);
4835
4836   tmp_list = child_exposes;
4837   while (tmp_list != NULL)
4838     {
4839       GtkWidget *child = tmp_list->data;
4840   
4841       gtk_container_propagate_expose (GTK_CONTAINER (text_view),
4842                                       child,
4843                                       event);
4844
4845       g_object_unref (child);
4846       
4847       tmp_list = tmp_list->next;
4848     }
4849
4850   g_list_free (child_exposes);
4851 }
4852
4853 static gint
4854 gtk_text_view_expose_event (GtkWidget *widget, GdkEventExpose *event)
4855 {
4856   GSList *tmp_list;
4857   
4858   if (event->window == gtk_text_view_get_window (GTK_TEXT_VIEW (widget),
4859                                                  GTK_TEXT_WINDOW_TEXT))
4860     {
4861       DV(g_print (">Exposed ("G_STRLOC")\n"));
4862       gtk_text_view_paint (widget, &event->area, event);
4863     }
4864
4865   if (event->window == gtk_widget_get_window (widget))
4866     gtk_text_view_draw_focus (widget);
4867
4868   /* Propagate exposes to all unanchored children. 
4869    * Anchored children are handled in gtk_text_view_paint(). 
4870    */
4871   tmp_list = GTK_TEXT_VIEW (widget)->priv->children;
4872   while (tmp_list != NULL)
4873     {
4874       GtkTextViewChild *vc = tmp_list->data;
4875
4876       /* propagate_expose checks that event->window matches
4877        * child->window
4878        */
4879       if (!vc->anchor)
4880         gtk_container_propagate_expose (GTK_CONTAINER (widget),
4881                                         vc->widget,
4882                                         event);
4883       
4884       tmp_list = tmp_list->next;
4885     }
4886   
4887   return FALSE;
4888 }
4889
4890 static void
4891 gtk_text_view_draw_focus (GtkWidget *widget)
4892 {
4893   GtkAllocation allocation;
4894   GdkWindow *window;
4895   gboolean interior_focus;
4896
4897   /* We clear the focus if we are in interior focus mode. */
4898   gtk_widget_style_get (widget,
4899                         "interior-focus", &interior_focus,
4900                         NULL);
4901   
4902   if (gtk_widget_is_drawable (widget))
4903     {
4904       window = gtk_widget_get_window (widget);
4905
4906       if (gtk_widget_has_focus (widget) && !interior_focus)
4907         {
4908           gtk_widget_get_allocation (widget, &allocation);
4909           gtk_paint_focus (gtk_widget_get_style (widget),
4910                            window,
4911                            gtk_widget_get_state (widget),
4912                            NULL, widget, "textview",
4913                            0, 0,
4914                            allocation.width, allocation.height);
4915         }
4916       else
4917         {
4918           gdk_window_clear (window);
4919         }
4920     }
4921 }
4922
4923 static gboolean
4924 gtk_text_view_focus (GtkWidget        *widget,
4925                      GtkDirectionType  direction)
4926 {
4927   GtkContainer *container;
4928   gboolean result;
4929   
4930   container = GTK_CONTAINER (widget);  
4931
4932   if (!gtk_widget_is_focus (widget) &&
4933       gtk_container_get_focus_child (container) == NULL)
4934     {
4935       gtk_widget_grab_focus (widget);
4936       return TRUE;
4937     }
4938   else
4939     {
4940       /*
4941        * Unset CAN_FOCUS flag so that gtk_container_focus() allows
4942        * children to get the focus
4943        */
4944       gtk_widget_set_can_focus (widget, FALSE);
4945       result = GTK_WIDGET_CLASS (gtk_text_view_parent_class)->focus (widget, direction);
4946       gtk_widget_set_can_focus (widget, TRUE);
4947
4948       return result;
4949     }
4950 }
4951
4952 static void
4953 gtk_text_view_move_focus (GtkWidget        *widget,
4954                           GtkDirectionType  direction_type)
4955 {
4956   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4957
4958   if (GTK_TEXT_VIEW_GET_CLASS (text_view)->move_focus)
4959     GTK_TEXT_VIEW_GET_CLASS (text_view)->move_focus (text_view,
4960                                                      direction_type);
4961 }
4962
4963 /*
4964  * Container
4965  */
4966
4967 static void
4968 gtk_text_view_add (GtkContainer *container,
4969                    GtkWidget    *child)
4970 {
4971   /* This is pretty random. */
4972   gtk_text_view_add_child_in_window (GTK_TEXT_VIEW (container),
4973                                      child,
4974                                      GTK_TEXT_WINDOW_WIDGET,
4975                                      0, 0);
4976 }
4977
4978 static void
4979 gtk_text_view_remove (GtkContainer *container,
4980                       GtkWidget    *child)
4981 {
4982   GtkTextView *text_view;
4983   GtkTextViewPrivate *priv;
4984   GtkTextViewChild *vc;
4985   GSList *iter;
4986
4987   text_view = GTK_TEXT_VIEW (container);
4988   priv = text_view->priv;
4989
4990   vc = NULL;
4991   iter = priv->children;
4992
4993   while (iter != NULL)
4994     {
4995       vc = iter->data;
4996
4997       if (vc->widget == child)
4998         break;
4999
5000       iter = g_slist_next (iter);
5001     }
5002
5003   g_assert (iter != NULL); /* be sure we had the child in the list */
5004
5005   priv->children = g_slist_remove (priv->children, vc);
5006
5007   gtk_widget_unparent (vc->widget);
5008
5009   text_view_child_free (vc);
5010 }
5011
5012 static void
5013 gtk_text_view_forall (GtkContainer *container,
5014                       gboolean      include_internals,
5015                       GtkCallback   callback,
5016                       gpointer      callback_data)
5017 {
5018   GSList *iter;
5019   GtkTextView *text_view;
5020   GSList *copy;
5021
5022   g_return_if_fail (GTK_IS_TEXT_VIEW (container));
5023   g_return_if_fail (callback != NULL);
5024
5025   text_view = GTK_TEXT_VIEW (container);
5026
5027   copy = g_slist_copy (text_view->priv->children);
5028   iter = copy;
5029
5030   while (iter != NULL)
5031     {
5032       GtkTextViewChild *vc = iter->data;
5033
5034       (* callback) (vc->widget, callback_data);
5035
5036       iter = g_slist_next (iter);
5037     }
5038
5039   g_slist_free (copy);
5040 }
5041
5042 #define CURSOR_ON_MULTIPLIER 2
5043 #define CURSOR_OFF_MULTIPLIER 1
5044 #define CURSOR_PEND_MULTIPLIER 3
5045 #define CURSOR_DIVIDER 3
5046
5047 static gboolean
5048 cursor_blinks (GtkTextView *text_view)
5049 {
5050   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5051   gboolean blink;
5052
5053 #ifdef DEBUG_VALIDATION_AND_SCROLLING
5054   return FALSE;
5055 #endif
5056   if (gtk_get_debug_flags () & GTK_DEBUG_UPDATES)
5057     return FALSE;
5058
5059   g_object_get (settings, "gtk-cursor-blink", &blink, NULL);
5060
5061   if (!blink)
5062     return FALSE;
5063
5064   if (text_view->priv->editable)
5065     {
5066       GtkTextMark *insert;
5067       GtkTextIter iter;
5068       
5069       insert = gtk_text_buffer_get_insert (get_buffer (text_view));
5070       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
5071       
5072       if (gtk_text_iter_editable (&iter, text_view->priv->editable))
5073         return blink;
5074     }
5075
5076   return FALSE;
5077 }
5078
5079 static gint
5080 get_cursor_time (GtkTextView *text_view)
5081 {
5082   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5083   gint time;
5084
5085   g_object_get (settings, "gtk-cursor-blink-time", &time, NULL);
5086
5087   return time;
5088 }
5089
5090 static gint
5091 get_cursor_blink_timeout (GtkTextView *text_view)
5092 {
5093   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5094   gint time;
5095
5096   g_object_get (settings, "gtk-cursor-blink-timeout", &time, NULL);
5097
5098   return time;
5099 }
5100
5101
5102 /*
5103  * Blink!
5104  */
5105
5106 static gint
5107 blink_cb (gpointer data)
5108 {
5109   GtkTextView *text_view;
5110   GtkTextViewPrivate *priv;
5111   gboolean visible;
5112   gint blink_timeout;
5113
5114   text_view = GTK_TEXT_VIEW (data);
5115   priv = text_view->priv;
5116
5117   if (!gtk_widget_has_focus (GTK_WIDGET (text_view)))
5118     {
5119       g_warning ("GtkTextView - did not receive focus-out-event. If you\n"
5120                  "connect a handler to this signal, it must return\n"
5121                  "FALSE so the text view gets the event as well");
5122
5123       gtk_text_view_check_cursor_blink (text_view);
5124
5125       return FALSE;
5126     }
5127
5128   g_assert (priv->layout);
5129   g_assert (priv->cursor_visible);
5130
5131   visible = gtk_text_layout_get_cursor_visible (priv->layout);
5132
5133   blink_timeout = get_cursor_blink_timeout (text_view);
5134   if (priv->blink_time > 1000 * blink_timeout &&
5135       blink_timeout < G_MAXINT/1000) 
5136     {
5137       /* we've blinked enough without the user doing anything, stop blinking */
5138       visible = 0;
5139       priv->blink_timeout = 0;
5140     } 
5141   else if (visible)
5142     priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER / CURSOR_DIVIDER,
5143                                                    blink_cb,
5144                                                    text_view);
5145   else 
5146     {
5147       priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_ON_MULTIPLIER / CURSOR_DIVIDER,
5148                                                      blink_cb,
5149                                                      text_view);
5150       priv->blink_time += get_cursor_time (text_view);
5151     }
5152
5153   /* Block changed_handler while changing the layout's cursor visibility
5154    * because it would expose the whole paragraph. Instead, we expose
5155    * the cursor's area(s) manually below.
5156    */
5157   g_signal_handlers_block_by_func (priv->layout,
5158                                    changed_handler,
5159                                    text_view);
5160   gtk_text_layout_set_cursor_visible (priv->layout, !visible);
5161   g_signal_handlers_unblock_by_func (priv->layout,
5162                                      changed_handler,
5163                                      text_view);
5164
5165   text_window_invalidate_cursors (priv->text_window);
5166
5167   /* Remove ourselves */
5168   return FALSE;
5169 }
5170
5171
5172 static void
5173 gtk_text_view_stop_cursor_blink (GtkTextView *text_view)
5174 {
5175   if (text_view->priv->blink_timeout)
5176     { 
5177       g_source_remove (text_view->priv->blink_timeout);
5178       text_view->priv->blink_timeout = 0;
5179     }
5180 }
5181
5182 static void
5183 gtk_text_view_check_cursor_blink (GtkTextView *text_view)
5184 {
5185   GtkTextViewPrivate *priv = text_view->priv;
5186
5187   if (priv->layout != NULL &&
5188       priv->cursor_visible &&
5189       gtk_widget_has_focus (GTK_WIDGET (text_view)))
5190     {
5191       if (cursor_blinks (text_view))
5192         {
5193           if (priv->blink_timeout == 0)
5194             {
5195               gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5196               
5197               priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER / CURSOR_DIVIDER,
5198                                                              blink_cb,
5199                                                              text_view);
5200             }
5201         }
5202       else
5203         {
5204           gtk_text_view_stop_cursor_blink (text_view);
5205           gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5206         }
5207     }
5208   else
5209     {
5210       gtk_text_view_stop_cursor_blink (text_view);
5211       gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
5212     }
5213 }
5214
5215 static void
5216 gtk_text_view_pend_cursor_blink (GtkTextView *text_view)
5217 {
5218   GtkTextViewPrivate *priv = text_view->priv;
5219
5220   if (priv->layout != NULL &&
5221       priv->cursor_visible &&
5222       gtk_widget_has_focus (GTK_WIDGET (text_view)) &&
5223       cursor_blinks (text_view))
5224     {
5225       gtk_text_view_stop_cursor_blink (text_view);
5226       gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5227       
5228       priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_PEND_MULTIPLIER / CURSOR_DIVIDER,
5229                                                      blink_cb,
5230                                                      text_view);
5231     }
5232 }
5233
5234 static void
5235 gtk_text_view_reset_blink_time (GtkTextView *text_view)
5236 {
5237   GtkTextViewPrivate *priv = text_view->priv;
5238
5239   priv->blink_time = 0;
5240 }
5241
5242
5243 /*
5244  * Key binding handlers
5245  */
5246
5247 static gboolean
5248 gtk_text_view_move_iter_by_lines (GtkTextView *text_view,
5249                                   GtkTextIter *newplace,
5250                                   gint         count)
5251 {
5252   gboolean ret = TRUE;
5253
5254   while (count < 0)
5255     {
5256       ret = gtk_text_layout_move_iter_to_previous_line (text_view->priv->layout, newplace);
5257       count++;
5258     }
5259
5260   while (count > 0)
5261     {
5262       ret = gtk_text_layout_move_iter_to_next_line (text_view->priv->layout, newplace);
5263       count--;
5264     }
5265
5266   return ret;
5267 }
5268
5269 static void
5270 move_cursor (GtkTextView       *text_view,
5271              const GtkTextIter *new_location,
5272              gboolean           extend_selection)
5273 {
5274   if (extend_selection)
5275     gtk_text_buffer_move_mark_by_name (get_buffer (text_view),
5276                                        "insert",
5277                                        new_location);
5278   else
5279       gtk_text_buffer_place_cursor (get_buffer (text_view),
5280                                     new_location);
5281   gtk_text_view_check_cursor_blink (text_view);
5282 }
5283
5284 static void
5285 gtk_text_view_move_cursor_internal (GtkTextView     *text_view,
5286                                     GtkMovementStep  step,
5287                                     gint             count,
5288                                     gboolean         extend_selection)
5289 {
5290   GtkTextViewPrivate *priv;
5291   GtkTextIter insert;
5292   GtkTextIter newplace;
5293   gboolean cancel_selection = FALSE;
5294   gint cursor_x_pos = 0;
5295   GtkDirectionType leave_direction = -1;
5296
5297   priv = text_view->priv;
5298
5299   if (!priv->cursor_visible) 
5300     {
5301       GtkScrollStep scroll_step;
5302
5303       switch (step) 
5304         {
5305         case GTK_MOVEMENT_VISUAL_POSITIONS:
5306           leave_direction = count > 0 ? GTK_DIR_RIGHT : GTK_DIR_LEFT;
5307           /* fall through */
5308         case GTK_MOVEMENT_LOGICAL_POSITIONS:
5309         case GTK_MOVEMENT_WORDS:
5310           scroll_step = GTK_SCROLL_HORIZONTAL_STEPS;
5311           break;
5312         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5313           scroll_step = GTK_SCROLL_HORIZONTAL_ENDS;
5314           break;          
5315         case GTK_MOVEMENT_DISPLAY_LINES:
5316           leave_direction = count > 0 ? GTK_DIR_DOWN : GTK_DIR_UP;
5317           /* fall through */
5318         case GTK_MOVEMENT_PARAGRAPHS:
5319         case GTK_MOVEMENT_PARAGRAPH_ENDS:
5320           scroll_step = GTK_SCROLL_STEPS;
5321           break;
5322         case GTK_MOVEMENT_PAGES:
5323           scroll_step = GTK_SCROLL_PAGES;
5324           break;
5325         case GTK_MOVEMENT_HORIZONTAL_PAGES:
5326           scroll_step = GTK_SCROLL_HORIZONTAL_PAGES;
5327           break;
5328         case GTK_MOVEMENT_BUFFER_ENDS:
5329           scroll_step = GTK_SCROLL_ENDS;
5330           break;
5331         default:
5332           scroll_step = GTK_SCROLL_PAGES;
5333           break;
5334         }
5335
5336       if (!gtk_text_view_move_viewport (text_view, scroll_step, count))
5337         {
5338           if (leave_direction != -1 &&
5339               !gtk_widget_keynav_failed (GTK_WIDGET (text_view),
5340                                          leave_direction))
5341             {
5342               g_signal_emit_by_name (text_view, "move-focus", leave_direction);
5343             }
5344         }
5345
5346       return;
5347     }
5348
5349   gtk_text_view_reset_im_context (text_view);
5350
5351   if (step == GTK_MOVEMENT_PAGES)
5352     {
5353       if (!gtk_text_view_scroll_pages (text_view, count, extend_selection))
5354         gtk_widget_error_bell (GTK_WIDGET (text_view));
5355
5356       gtk_text_view_check_cursor_blink (text_view);
5357       gtk_text_view_pend_cursor_blink (text_view);
5358       return;
5359     }
5360   else if (step == GTK_MOVEMENT_HORIZONTAL_PAGES)
5361     {
5362       if (!gtk_text_view_scroll_hpages (text_view, count, extend_selection))
5363         gtk_widget_error_bell (GTK_WIDGET (text_view));
5364
5365       gtk_text_view_check_cursor_blink (text_view);
5366       gtk_text_view_pend_cursor_blink (text_view);
5367       return;
5368     }
5369
5370   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5371                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5372
5373   if (! extend_selection)
5374     {
5375       GtkTextIter sel_bound;
5376
5377       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &sel_bound,
5378                                         gtk_text_buffer_get_selection_bound (get_buffer (text_view)));
5379
5380       /* if we move forward, assume the cursor is at the end of the selection;
5381        * if we move backward, assume the cursor is at the start
5382        */
5383       if (count > 0)
5384         gtk_text_iter_order (&sel_bound, &insert);
5385       else
5386         gtk_text_iter_order (&insert, &sel_bound);
5387
5388       /* if we actually have a selection, just move *to* the beginning/end
5389        * of the selection and not *from* there on LOGICAL_POSITIONS
5390        * and VISUAL_POSITIONS movement
5391        */
5392       if (! gtk_text_iter_equal (&sel_bound, &insert))
5393         cancel_selection = TRUE;
5394     }
5395
5396   newplace = insert;
5397
5398   if (step == GTK_MOVEMENT_DISPLAY_LINES)
5399     gtk_text_view_get_virtual_cursor_pos (text_view, &insert, &cursor_x_pos, NULL);
5400
5401   switch (step)
5402     {
5403     case GTK_MOVEMENT_LOGICAL_POSITIONS:
5404       if (! cancel_selection)
5405         gtk_text_iter_forward_visible_cursor_positions (&newplace, count);
5406       break;
5407
5408     case GTK_MOVEMENT_VISUAL_POSITIONS:
5409       if (! cancel_selection)
5410         gtk_text_layout_move_iter_visually (priv->layout,
5411                                             &newplace, count);
5412       break;
5413
5414     case GTK_MOVEMENT_WORDS:
5415       if (count < 0)
5416         gtk_text_iter_backward_visible_word_starts (&newplace, -count);
5417       else if (count > 0) 
5418         {
5419           if (!gtk_text_iter_forward_visible_word_ends (&newplace, count))
5420             gtk_text_iter_forward_to_line_end (&newplace);
5421         }
5422       break;
5423
5424     case GTK_MOVEMENT_DISPLAY_LINES:
5425       if (count < 0)
5426         {
5427           leave_direction = GTK_DIR_UP;
5428
5429           if (gtk_text_view_move_iter_by_lines (text_view, &newplace, count))
5430             gtk_text_layout_move_iter_to_x (priv->layout, &newplace, cursor_x_pos);
5431           else
5432             gtk_text_iter_set_line_offset (&newplace, 0);
5433         }
5434       if (count > 0)
5435         {
5436           leave_direction = GTK_DIR_DOWN;
5437
5438           if (gtk_text_view_move_iter_by_lines (text_view, &newplace, count))
5439             gtk_text_layout_move_iter_to_x (priv->layout, &newplace, cursor_x_pos);
5440           else
5441             gtk_text_iter_forward_to_line_end (&newplace);
5442         }
5443       break;
5444
5445     case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5446       if (count > 1)
5447         gtk_text_view_move_iter_by_lines (text_view, &newplace, --count);
5448       else if (count < -1)
5449         gtk_text_view_move_iter_by_lines (text_view, &newplace, ++count);
5450
5451       if (count != 0)
5452         gtk_text_layout_move_iter_to_line_end (priv->layout, &newplace, count);
5453       break;
5454
5455     case GTK_MOVEMENT_PARAGRAPHS:
5456       if (count > 0)
5457         {
5458           if (!gtk_text_iter_ends_line (&newplace))
5459             {
5460               gtk_text_iter_forward_to_line_end (&newplace);
5461               --count;
5462             }
5463           gtk_text_iter_forward_visible_lines (&newplace, count);
5464           gtk_text_iter_forward_to_line_end (&newplace);
5465         }
5466       else if (count < 0)
5467         {
5468           if (gtk_text_iter_get_line_offset (&newplace) > 0)
5469             gtk_text_iter_set_line_offset (&newplace, 0);
5470           gtk_text_iter_forward_visible_lines (&newplace, count);
5471           gtk_text_iter_set_line_offset (&newplace, 0);
5472         }
5473       break;
5474
5475     case GTK_MOVEMENT_PARAGRAPH_ENDS:
5476       if (count > 0)
5477         {
5478           if (!gtk_text_iter_ends_line (&newplace))
5479             gtk_text_iter_forward_to_line_end (&newplace);
5480         }
5481       else if (count < 0)
5482         {
5483           gtk_text_iter_set_line_offset (&newplace, 0);
5484         }
5485       break;
5486
5487     case GTK_MOVEMENT_BUFFER_ENDS:
5488       if (count > 0)
5489         gtk_text_buffer_get_end_iter (get_buffer (text_view), &newplace);
5490       else if (count < 0)
5491         gtk_text_buffer_get_iter_at_offset (get_buffer (text_view), &newplace, 0);
5492      break;
5493       
5494     default:
5495       break;
5496     }
5497
5498   /* call move_cursor() even if the cursor hasn't moved, since it 
5499      cancels the selection
5500   */
5501   move_cursor (text_view, &newplace, extend_selection);
5502
5503   if (!gtk_text_iter_equal (&insert, &newplace))
5504     {
5505       DV(g_print (G_STRLOC": scrolling onscreen\n"));
5506       gtk_text_view_scroll_mark_onscreen (text_view,
5507                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
5508
5509       if (step == GTK_MOVEMENT_DISPLAY_LINES)
5510         gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, -1);
5511     }
5512   else if (leave_direction != -1)
5513     {
5514       if (!gtk_widget_keynav_failed (GTK_WIDGET (text_view),
5515                                      leave_direction))
5516         {
5517           g_signal_emit_by_name (text_view, "move-focus", leave_direction);
5518         }
5519     }
5520   else if (! cancel_selection)
5521     {
5522       gtk_widget_error_bell (GTK_WIDGET (text_view));
5523     }
5524
5525   gtk_text_view_check_cursor_blink (text_view);
5526   gtk_text_view_pend_cursor_blink (text_view);
5527 }
5528
5529 static void
5530 gtk_text_view_move_cursor (GtkTextView     *text_view,
5531                            GtkMovementStep  step,
5532                            gint             count,
5533                            gboolean         extend_selection)
5534 {
5535   gtk_text_view_move_cursor_internal (text_view, step, count, extend_selection);
5536 }
5537
5538 static gboolean
5539 gtk_text_view_move_viewport (GtkTextView     *text_view,
5540                              GtkScrollStep    step,
5541                              gint             count)
5542 {
5543   GtkAdjustment *adjustment;
5544   gdouble increment;
5545   
5546   switch (step) 
5547     {
5548     case GTK_SCROLL_STEPS:
5549     case GTK_SCROLL_PAGES:
5550     case GTK_SCROLL_ENDS:
5551       adjustment = get_vadjustment (text_view);
5552       break;
5553     case GTK_SCROLL_HORIZONTAL_STEPS:
5554     case GTK_SCROLL_HORIZONTAL_PAGES:
5555     case GTK_SCROLL_HORIZONTAL_ENDS:
5556       adjustment = get_hadjustment (text_view);
5557       break;
5558     default:
5559       adjustment = get_vadjustment (text_view);
5560       break;
5561     }
5562
5563   switch (step) 
5564     {
5565     case GTK_SCROLL_STEPS:
5566     case GTK_SCROLL_HORIZONTAL_STEPS:
5567       increment = adjustment->step_increment;
5568       break;
5569     case GTK_SCROLL_PAGES:
5570     case GTK_SCROLL_HORIZONTAL_PAGES:
5571       increment = adjustment->page_increment;
5572       break;
5573     case GTK_SCROLL_ENDS:
5574     case GTK_SCROLL_HORIZONTAL_ENDS:
5575       increment = adjustment->upper - adjustment->lower;
5576       break;
5577     default:
5578       increment = 0.0;
5579       break;
5580     }
5581
5582   return set_adjustment_clamped (adjustment, adjustment->value + count * increment);
5583 }
5584
5585 static void
5586 gtk_text_view_set_anchor (GtkTextView *text_view)
5587 {
5588   GtkTextIter insert;
5589
5590   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5591                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5592
5593   gtk_text_buffer_create_mark (get_buffer (text_view), "anchor", &insert, TRUE);
5594 }
5595
5596 static gboolean
5597 gtk_text_view_scroll_pages (GtkTextView *text_view,
5598                             gint         count,
5599                             gboolean     extend_selection)
5600 {
5601   GtkTextViewPrivate *priv;
5602   GtkAdjustment *adj;
5603   gint cursor_x_pos, cursor_y_pos;
5604   GtkTextMark *insert_mark;
5605   GtkTextIter old_insert;
5606   GtkTextIter new_insert;
5607   GtkTextIter anchor;
5608   gdouble newval;
5609   gdouble oldval;
5610   gint y0, y1;
5611
5612   priv = text_view->priv;
5613
5614   g_return_val_if_fail (priv->vadjustment != NULL, FALSE);
5615   
5616   adj = priv->vadjustment;
5617
5618   insert_mark = gtk_text_buffer_get_insert (get_buffer (text_view));
5619
5620   /* Make sure we start from the current cursor position, even
5621    * if it was offscreen, but don't queue more scrolls if we're
5622    * already behind.
5623    */
5624   if (priv->pending_scroll)
5625     cancel_pending_scroll (text_view);
5626   else
5627     gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5628
5629   /* Validate the region that will be brought into view by the cursor motion
5630    */
5631   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5632                                     &old_insert, insert_mark);
5633
5634   if (count < 0)
5635     {
5636       gtk_text_view_get_first_para_iter (text_view, &anchor);
5637       y0 = adj->page_size;
5638       y1 = adj->page_size + count * adj->page_increment;
5639     }
5640   else
5641     {
5642       gtk_text_view_get_first_para_iter (text_view, &anchor);
5643       y0 = count * adj->page_increment + adj->page_size;
5644       y1 = 0;
5645     }
5646
5647   gtk_text_layout_validate_yrange (priv->layout, &anchor, y0, y1);
5648   /* FIXME do we need to update the adjustment ranges here? */
5649
5650   new_insert = old_insert;
5651
5652   if (count < 0 && adj->value <= (adj->lower + 1e-12))
5653     {
5654       /* already at top, just be sure we are at offset 0 */
5655       gtk_text_buffer_get_start_iter (get_buffer (text_view), &new_insert);
5656       move_cursor (text_view, &new_insert, extend_selection);
5657     }
5658   else if (count > 0 && adj->value >= (adj->upper - adj->page_size - 1e-12))
5659     {
5660       /* already at bottom, just be sure we are at the end */
5661       gtk_text_buffer_get_end_iter (get_buffer (text_view), &new_insert);
5662       move_cursor (text_view, &new_insert, extend_selection);
5663     }
5664   else
5665     {
5666       gtk_text_view_get_virtual_cursor_pos (text_view, NULL, &cursor_x_pos, &cursor_y_pos);
5667
5668       oldval = adj->value;
5669       newval = adj->value;
5670
5671       newval += count * adj->page_increment;
5672
5673       set_adjustment_clamped (adj, newval);
5674       cursor_y_pos += adj->value - oldval;
5675
5676       gtk_text_layout_get_iter_at_pixel (priv->layout, &new_insert, cursor_x_pos, cursor_y_pos);
5677       clamp_iter_onscreen (text_view, &new_insert);
5678       move_cursor (text_view, &new_insert, extend_selection);
5679
5680       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
5681     }
5682   
5683   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
5684    * only guarantees 1 pixel onscreen.
5685    */
5686   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5687   gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5688
5689   return !gtk_text_iter_equal (&old_insert, &new_insert);
5690 }
5691
5692 static gboolean
5693 gtk_text_view_scroll_hpages (GtkTextView *text_view,
5694                              gint         count,
5695                              gboolean     extend_selection)
5696 {
5697   GtkTextViewPrivate *priv;
5698   GtkAdjustment *adj;
5699   gint cursor_x_pos, cursor_y_pos;
5700   GtkTextMark *insert_mark;
5701   GtkTextIter old_insert;
5702   GtkTextIter new_insert;
5703   gdouble newval;
5704   gdouble oldval;
5705   gint y, height;
5706
5707   priv = text_view->priv;
5708
5709   g_return_val_if_fail (priv->hadjustment != NULL, FALSE);
5710
5711   adj = priv->hadjustment;
5712
5713   insert_mark = gtk_text_buffer_get_insert (get_buffer (text_view));
5714
5715   /* Make sure we start from the current cursor position, even
5716    * if it was offscreen, but don't queue more scrolls if we're
5717    * already behind.
5718    */
5719   if (priv->pending_scroll)
5720     cancel_pending_scroll (text_view);
5721   else
5722     gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5723
5724   /* Validate the line that we're moving within.
5725    */
5726   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5727                                     &old_insert, insert_mark);
5728
5729   gtk_text_layout_get_line_yrange (priv->layout, &old_insert, &y, &height);
5730   gtk_text_layout_validate_yrange (priv->layout, &old_insert, y, y + height);
5731   /* FIXME do we need to update the adjustment ranges here? */
5732
5733   new_insert = old_insert;
5734
5735   if (count < 0 && adj->value <= (adj->lower + 1e-12))
5736     {
5737       /* already at far left, just be sure we are at offset 0 */
5738       gtk_text_iter_set_line_offset (&new_insert, 0);
5739       move_cursor (text_view, &new_insert, extend_selection);
5740     }
5741   else if (count > 0 && adj->value >= (adj->upper - adj->page_size - 1e-12))
5742     {
5743       /* already at far right, just be sure we are at the end */
5744       if (!gtk_text_iter_ends_line (&new_insert))
5745           gtk_text_iter_forward_to_line_end (&new_insert);
5746       move_cursor (text_view, &new_insert, extend_selection);
5747     }
5748   else
5749     {
5750       gtk_text_view_get_virtual_cursor_pos (text_view, NULL, &cursor_x_pos, &cursor_y_pos);
5751
5752       oldval = adj->value;
5753       newval = adj->value;
5754
5755       newval += count * adj->page_increment;
5756
5757       set_adjustment_clamped (adj, newval);
5758       cursor_x_pos += adj->value - oldval;
5759
5760       gtk_text_layout_get_iter_at_pixel (priv->layout, &new_insert, cursor_x_pos, cursor_y_pos);
5761       clamp_iter_onscreen (text_view, &new_insert);
5762       move_cursor (text_view, &new_insert, extend_selection);
5763
5764       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
5765     }
5766
5767   /*  FIXME for lines shorter than the overall widget width, this results in a
5768    *  "bounce" effect as we scroll to the right of the widget, then scroll
5769    *  back to get the end of the line onscreen.
5770    *      http://bugzilla.gnome.org/show_bug.cgi?id=68963
5771    */
5772   
5773   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
5774    * only guarantees 1 pixel onscreen.
5775    */
5776   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5777   gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5778
5779   return !gtk_text_iter_equal (&old_insert, &new_insert);
5780 }
5781
5782 static gboolean
5783 whitespace (gunichar ch, gpointer user_data)
5784 {
5785   return (ch == ' ' || ch == '\t');
5786 }
5787
5788 static gboolean
5789 not_whitespace (gunichar ch, gpointer user_data)
5790 {
5791   return !whitespace (ch, user_data);
5792 }
5793
5794 static gboolean
5795 find_whitepace_region (const GtkTextIter *center,
5796                        GtkTextIter *start, GtkTextIter *end)
5797 {
5798   *start = *center;
5799   *end = *center;
5800
5801   if (gtk_text_iter_backward_find_char (start, not_whitespace, NULL, NULL))
5802     gtk_text_iter_forward_char (start); /* we want the first whitespace... */
5803   if (whitespace (gtk_text_iter_get_char (end), NULL))
5804     gtk_text_iter_forward_find_char (end, not_whitespace, NULL, NULL);
5805
5806   return !gtk_text_iter_equal (start, end);
5807 }
5808
5809 static void
5810 gtk_text_view_insert_at_cursor (GtkTextView *text_view,
5811                                 const gchar *str)
5812 {
5813   if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
5814                                                      text_view->priv->editable))
5815     {
5816       gtk_widget_error_bell (GTK_WIDGET (text_view));
5817     }
5818 }
5819
5820 static void
5821 gtk_text_view_delete_from_cursor (GtkTextView   *text_view,
5822                                   GtkDeleteType  type,
5823                                   gint           count)
5824 {
5825   GtkTextViewPrivate *priv;
5826   GtkTextIter insert;
5827   GtkTextIter start;
5828   GtkTextIter end;
5829   gboolean leave_one = FALSE;
5830
5831   priv = text_view->priv;
5832
5833   gtk_text_view_reset_im_context (text_view);
5834
5835   if (type == GTK_DELETE_CHARS)
5836     {
5837       /* Char delete deletes the selection, if one exists */
5838       if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
5839                                             priv->editable))
5840         return;
5841     }
5842
5843   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5844                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5845
5846   start = insert;
5847   end = insert;
5848
5849   switch (type)
5850     {
5851     case GTK_DELETE_CHARS:
5852       gtk_text_iter_forward_cursor_positions (&end, count);
5853       break;
5854
5855     case GTK_DELETE_WORD_ENDS:
5856       if (count > 0)
5857         gtk_text_iter_forward_word_ends (&end, count);
5858       else if (count < 0)
5859         gtk_text_iter_backward_word_starts (&start, 0 - count);
5860       break;
5861
5862     case GTK_DELETE_WORDS:
5863       break;
5864
5865     case GTK_DELETE_DISPLAY_LINE_ENDS:
5866       break;
5867
5868     case GTK_DELETE_DISPLAY_LINES:
5869       break;
5870
5871     case GTK_DELETE_PARAGRAPH_ENDS:
5872       if (count > 0)
5873         {
5874           /* If we're already at a newline, we need to
5875            * simply delete that newline, instead of
5876            * moving to the next one.
5877            */
5878           if (gtk_text_iter_ends_line (&end))
5879             {
5880               gtk_text_iter_forward_line (&end);
5881               --count;
5882             }
5883
5884           while (count > 0)
5885             {
5886               if (!gtk_text_iter_forward_to_line_end (&end))
5887                 break;
5888
5889               --count;
5890             }
5891         }
5892       else if (count < 0)
5893         {
5894           if (gtk_text_iter_starts_line (&start))
5895             {
5896               gtk_text_iter_backward_line (&start);
5897               if (!gtk_text_iter_ends_line (&end))
5898                 gtk_text_iter_forward_to_line_end (&start);
5899             }
5900           else
5901             {
5902               gtk_text_iter_set_line_offset (&start, 0);
5903             }
5904           ++count;
5905
5906           gtk_text_iter_backward_lines (&start, -count);
5907         }
5908       break;
5909
5910     case GTK_DELETE_PARAGRAPHS:
5911       if (count > 0)
5912         {
5913           gtk_text_iter_set_line_offset (&start, 0);
5914           gtk_text_iter_forward_to_line_end (&end);
5915
5916           /* Do the lines beyond the first. */
5917           while (count > 1)
5918             {
5919               gtk_text_iter_forward_to_line_end (&end);
5920
5921               --count;
5922             }
5923         }
5924
5925       /* FIXME negative count? */
5926
5927       break;
5928
5929     case GTK_DELETE_WHITESPACE:
5930       {
5931         find_whitepace_region (&insert, &start, &end);
5932       }
5933       break;
5934
5935     default:
5936       break;
5937     }
5938
5939   if (!gtk_text_iter_equal (&start, &end))
5940     {
5941       gtk_text_buffer_begin_user_action (get_buffer (text_view));
5942
5943       if (gtk_text_buffer_delete_interactive (get_buffer (text_view), &start, &end,
5944                                               priv->editable))
5945         {
5946           if (leave_one)
5947             gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view),
5948                                                           " ", 1,
5949                                                           priv->editable);
5950         }
5951       else
5952         {
5953           gtk_widget_error_bell (GTK_WIDGET (text_view));
5954         }
5955
5956       gtk_text_buffer_end_user_action (get_buffer (text_view));
5957       gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
5958
5959       DV(g_print (G_STRLOC": scrolling onscreen\n"));
5960       gtk_text_view_scroll_mark_onscreen (text_view,
5961                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
5962     }
5963   else
5964     {
5965       gtk_widget_error_bell (GTK_WIDGET (text_view));
5966     }
5967 }
5968
5969 static void
5970 gtk_text_view_backspace (GtkTextView *text_view)
5971 {
5972   GtkTextViewPrivate *priv;
5973   GtkTextIter insert;
5974
5975   priv = text_view->priv;
5976
5977   gtk_text_view_reset_im_context (text_view);
5978
5979   /* Backspace deletes the selection, if one exists */
5980   if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
5981                                         priv->editable))
5982     return;
5983
5984   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5985                                     &insert,
5986                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5987
5988   if (gtk_text_buffer_backspace (get_buffer (text_view), &insert,
5989                                  TRUE, priv->editable))
5990     {
5991       gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
5992       DV(g_print (G_STRLOC": scrolling onscreen\n"));
5993       gtk_text_view_scroll_mark_onscreen (text_view,
5994                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
5995     }
5996   else
5997     {
5998       gtk_widget_error_bell (GTK_WIDGET (text_view));
5999     }
6000 }
6001
6002 static void
6003 gtk_text_view_cut_clipboard (GtkTextView *text_view)
6004 {
6005   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6006                                                       GDK_SELECTION_CLIPBOARD);
6007   
6008   gtk_text_buffer_cut_clipboard (get_buffer (text_view),
6009                                  clipboard,
6010                                  text_view->priv->editable);
6011   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6012   gtk_text_view_scroll_mark_onscreen (text_view,
6013                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
6014 }
6015
6016 static void
6017 gtk_text_view_copy_clipboard (GtkTextView *text_view)
6018 {
6019   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6020                                                       GDK_SELECTION_CLIPBOARD);
6021   
6022   gtk_text_buffer_copy_clipboard (get_buffer (text_view),
6023                                   clipboard);
6024
6025   /* on copy do not scroll, we are already onscreen */
6026 }
6027
6028 static void
6029 gtk_text_view_paste_clipboard (GtkTextView *text_view)
6030 {
6031   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6032                                                       GDK_SELECTION_CLIPBOARD);
6033   
6034   gtk_text_buffer_paste_clipboard (get_buffer (text_view),
6035                                    clipboard,
6036                                    NULL,
6037                                    text_view->priv->editable);
6038 }
6039
6040 static void
6041 gtk_text_view_paste_done_handler (GtkTextBuffer *buffer,
6042                                   GtkClipboard  *clipboard,
6043                                   gpointer       data)
6044 {
6045   GtkTextView *text_view = data;
6046   GtkTextViewPrivate *priv;
6047
6048   priv = text_view->priv;
6049
6050   if (priv->scroll_after_paste)
6051     {
6052       DV(g_print (G_STRLOC": scrolling onscreen\n"));
6053       gtk_text_view_scroll_mark_onscreen (text_view, gtk_text_buffer_get_insert (buffer));
6054     }
6055
6056   priv->scroll_after_paste = TRUE;
6057 }
6058
6059 static void
6060 gtk_text_view_toggle_overwrite (GtkTextView *text_view)
6061 {
6062   GtkTextViewPrivate *priv = text_view->priv;
6063
6064   if (priv->text_window)
6065     text_window_invalidate_cursors (priv->text_window);
6066
6067   priv->overwrite_mode = !priv->overwrite_mode;
6068
6069   if (priv->layout)
6070     gtk_text_layout_set_overwrite_mode (priv->layout,
6071                                         priv->overwrite_mode && priv->editable);
6072
6073   if (priv->text_window)
6074     text_window_invalidate_cursors (priv->text_window);
6075
6076   gtk_text_view_pend_cursor_blink (text_view);
6077
6078   g_object_notify (G_OBJECT (text_view), "overwrite");
6079 }
6080
6081 /**
6082  * gtk_text_view_get_overwrite:
6083  * @text_view: a #GtkTextView
6084  *
6085  * Returns whether the #GtkTextView is in overwrite mode or not.
6086  *
6087  * Return value: whether @text_view is in overwrite mode or not.
6088  * 
6089  * Since: 2.4
6090  **/
6091 gboolean
6092 gtk_text_view_get_overwrite (GtkTextView *text_view)
6093 {
6094   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
6095
6096   return text_view->priv->overwrite_mode;
6097 }
6098
6099 /**
6100  * gtk_text_view_set_overwrite:
6101  * @text_view: a #GtkTextView
6102  * @overwrite: %TRUE to turn on overwrite mode, %FALSE to turn it off
6103  *
6104  * Changes the #GtkTextView overwrite mode.
6105  *
6106  * Since: 2.4
6107  **/
6108 void
6109 gtk_text_view_set_overwrite (GtkTextView *text_view,
6110                              gboolean     overwrite)
6111 {
6112   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
6113   overwrite = overwrite != FALSE;
6114
6115   if (text_view->priv->overwrite_mode != overwrite)
6116     gtk_text_view_toggle_overwrite (text_view);
6117 }
6118
6119 /**
6120  * gtk_text_view_set_accepts_tab:
6121  * @text_view: A #GtkTextView
6122  * @accepts_tab: %TRUE if pressing the Tab key should insert a tab 
6123  *    character, %FALSE, if pressing the Tab key should move the 
6124  *    keyboard focus.
6125  * 
6126  * Sets the behavior of the text widget when the Tab key is pressed. 
6127  * If @accepts_tab is %TRUE, a tab character is inserted. If @accepts_tab 
6128  * is %FALSE the keyboard focus is moved to the next widget in the focus 
6129  * chain.
6130  * 
6131  * Since: 2.4
6132  **/
6133 void
6134 gtk_text_view_set_accepts_tab (GtkTextView *text_view,
6135                                gboolean     accepts_tab)
6136 {
6137   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
6138
6139   accepts_tab = accepts_tab != FALSE;
6140
6141   if (text_view->priv->accepts_tab != accepts_tab)
6142     {
6143       text_view->priv->accepts_tab = accepts_tab;
6144
6145       g_object_notify (G_OBJECT (text_view), "accepts-tab");
6146     }
6147 }
6148
6149 /**
6150  * gtk_text_view_get_accepts_tab:
6151  * @text_view: A #GtkTextView
6152  * 
6153  * Returns whether pressing the Tab key inserts a tab characters.
6154  * gtk_text_view_set_accepts_tab().
6155  * 
6156  * Return value: %TRUE if pressing the Tab key inserts a tab character, 
6157  *   %FALSE if pressing the Tab key moves the keyboard focus.
6158  * 
6159  * Since: 2.4
6160  **/
6161 gboolean
6162 gtk_text_view_get_accepts_tab (GtkTextView *text_view)
6163 {
6164   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
6165
6166   return text_view->priv->accepts_tab;
6167 }
6168
6169 static void
6170 gtk_text_view_compat_move_focus (GtkTextView     *text_view,
6171                                  GtkDirectionType direction_type)
6172 {
6173   GSignalInvocationHint *hint = g_signal_get_invocation_hint (text_view);
6174
6175   /*  as of GTK+ 2.12, the "move-focus" signal has been moved to GtkWidget,
6176    *  the evil code below makes sure that both emitting the signal and
6177    *  calling the virtual function directly continue to work as expetcted
6178    */
6179
6180   if (hint->signal_id == g_signal_lookup ("move-focus", GTK_TYPE_WIDGET))
6181     {
6182       /*  if this is a signal emission, chain up  */
6183
6184       gboolean retval;
6185
6186       g_signal_chain_from_overridden_handler (text_view,
6187                                               direction_type, &retval);
6188     }
6189   else
6190     {
6191       /*  otherwise emit the signal, since somebody called the virtual
6192        *  function directly
6193        */
6194
6195       g_signal_emit_by_name (text_view, "move-focus", direction_type);
6196     }
6197 }
6198
6199 /*
6200  * Selections
6201  */
6202
6203 static void
6204 gtk_text_view_unselect (GtkTextView *text_view)
6205 {
6206   GtkTextIter insert;
6207
6208   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
6209                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
6210
6211   gtk_text_buffer_move_mark (get_buffer (text_view),
6212                              gtk_text_buffer_get_selection_bound (get_buffer (text_view)),
6213                              &insert);
6214 }
6215
6216 static void
6217 get_iter_at_pointer (GtkTextView *text_view,
6218                      GdkDevice   *device,
6219                      GtkTextIter *iter,
6220                      gint        *x,
6221                      gint        *y)
6222 {
6223   GtkTextViewPrivate *priv;
6224   gint xcoord, ycoord;
6225   GdkModifierType state;
6226
6227   priv = text_view->priv;
6228
6229   gdk_window_get_device_position (priv->text_window->bin_window,
6230                                   device, &xcoord, &ycoord, &state);
6231
6232   gtk_text_layout_get_iter_at_pixel (priv->layout,
6233                                      iter,
6234                                      xcoord + priv->xoffset,
6235                                      ycoord + priv->yoffset);
6236   if (x)
6237     *x = xcoord;
6238
6239   if (y)
6240     *y = ycoord;
6241 }
6242
6243 static void
6244 move_mark_to_pointer_and_scroll (GtkTextView *text_view,
6245                                  const gchar *mark_name,
6246                                  GdkDevice   *device)
6247 {
6248   GtkTextIter newplace;
6249   GtkTextMark *mark;
6250
6251   get_iter_at_pointer (text_view, device, &newplace, NULL, NULL);
6252   
6253   mark = gtk_text_buffer_get_mark (get_buffer (text_view), mark_name);
6254   
6255   /* This may invalidate the layout */
6256   DV(g_print (G_STRLOC": move mark\n"));
6257   
6258   gtk_text_buffer_move_mark (get_buffer (text_view),
6259                              mark,
6260                              &newplace);
6261   
6262   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6263   gtk_text_view_scroll_mark_onscreen (text_view, mark);
6264
6265   DV (g_print ("first validate idle leaving %s is %d\n",
6266                G_STRLOC, text_view->priv->first_validate_idle));
6267 }
6268
6269 static gboolean
6270 selection_scan_timeout (gpointer data)
6271 {
6272   GtkTextView *text_view;
6273
6274   text_view = GTK_TEXT_VIEW (data);
6275
6276   gtk_text_view_scroll_mark_onscreen (text_view, 
6277                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
6278
6279   return TRUE; /* remain installed. */
6280 }
6281
6282 #define UPPER_OFFSET_ANCHOR 0.8
6283 #define LOWER_OFFSET_ANCHOR 0.2
6284
6285 static gboolean
6286 check_scroll (gdouble offset, GtkAdjustment *adj)
6287 {
6288   if ((offset > UPPER_OFFSET_ANCHOR &&
6289        adj->value + adj->page_size < adj->upper) ||
6290       (offset < LOWER_OFFSET_ANCHOR &&
6291        adj->value > adj->lower))
6292     return TRUE;
6293
6294   return FALSE;
6295 }
6296
6297 static gint
6298 drag_scan_timeout (gpointer data)
6299 {
6300   GtkTextView *text_view;
6301   GtkTextViewPrivate *priv;
6302   GtkTextIter newplace;
6303   gint x, y, width, height;
6304   gdouble pointer_xoffset, pointer_yoffset;
6305
6306   text_view = GTK_TEXT_VIEW (data);
6307   priv = text_view->priv;
6308
6309   get_iter_at_pointer (text_view, priv->dnd_device, &newplace, &x, &y);
6310   gdk_drawable_get_size (priv->text_window->bin_window, &width, &height);
6311
6312   gtk_text_buffer_move_mark (get_buffer (text_view),
6313                              priv->dnd_mark,
6314                              &newplace);
6315
6316   pointer_xoffset = (gdouble) x / width;
6317   pointer_yoffset = (gdouble) y / height;
6318
6319   if (check_scroll (pointer_xoffset, priv->hadjustment) ||
6320       check_scroll (pointer_yoffset, priv->vadjustment))
6321     {
6322       /* do not make offsets surpass lower nor upper anchors, this makes
6323        * scrolling speed relative to the distance of the pointer to the
6324        * anchors when it moves beyond them.
6325        */
6326       pointer_xoffset = CLAMP (pointer_xoffset, LOWER_OFFSET_ANCHOR, UPPER_OFFSET_ANCHOR);
6327       pointer_yoffset = CLAMP (pointer_yoffset, LOWER_OFFSET_ANCHOR, UPPER_OFFSET_ANCHOR);
6328
6329       gtk_text_view_scroll_to_mark (text_view,
6330                                     priv->dnd_mark,
6331                                     0., TRUE, pointer_xoffset, pointer_yoffset);
6332     }
6333
6334   return TRUE;
6335 }
6336
6337 typedef enum 
6338 {
6339   SELECT_CHARACTERS,
6340   SELECT_WORDS,
6341   SELECT_LINES
6342 } SelectionGranularity;
6343
6344 /*
6345  * Move @start and @end to the boundaries of the selection unit (indicated by 
6346  * @granularity) which contained @start initially.
6347  * If the selction unit is SELECT_WORDS and @start is not contained in a word
6348  * the selection is extended to all the white spaces between the end of the 
6349  * word preceding @start and the start of the one following.
6350  */
6351 static void
6352 extend_selection (GtkTextView *text_view, 
6353                   SelectionGranularity granularity, 
6354                   GtkTextIter *start, 
6355                   GtkTextIter *end)
6356 {
6357   *end = *start;
6358
6359   if (granularity == SELECT_WORDS) 
6360     {
6361       if (gtk_text_iter_inside_word (start))
6362         {
6363           if (!gtk_text_iter_starts_word (start))
6364             gtk_text_iter_backward_visible_word_start (start);
6365           
6366           if (!gtk_text_iter_ends_word (end))
6367             {
6368               if (!gtk_text_iter_forward_visible_word_end (end))
6369                 gtk_text_iter_forward_to_end (end);
6370             }
6371         }
6372       else
6373         {
6374           GtkTextIter tmp;
6375
6376           tmp = *start;
6377           if (gtk_text_iter_backward_visible_word_start (&tmp))
6378             gtk_text_iter_forward_visible_word_end (&tmp);
6379
6380           if (gtk_text_iter_get_line (&tmp) == gtk_text_iter_get_line (start))
6381             *start = tmp;
6382           else
6383             gtk_text_iter_set_line_offset (start, 0);
6384
6385           tmp = *end;
6386           if (!gtk_text_iter_forward_visible_word_end (&tmp))
6387             gtk_text_iter_forward_to_end (&tmp);
6388
6389           if (gtk_text_iter_ends_word (&tmp))
6390             gtk_text_iter_backward_visible_word_start (&tmp);
6391
6392           if (gtk_text_iter_get_line (&tmp) == gtk_text_iter_get_line (end))
6393             *end = tmp;
6394           else
6395             gtk_text_iter_forward_to_line_end (end);
6396         }
6397     }
6398   else if (granularity == SELECT_LINES) 
6399     {
6400       if (gtk_text_view_starts_display_line (text_view, start))
6401         {
6402           /* If on a display line boundary, we assume the user
6403            * clicked off the end of a line and we therefore select
6404            * the line before the boundary.
6405            */
6406           gtk_text_view_backward_display_line_start (text_view, start);
6407         }
6408       else
6409         {
6410           /* start isn't on the start of a line, so we move it to the
6411            * start, and move end to the end unless it's already there.
6412            */
6413           gtk_text_view_backward_display_line_start (text_view, start);
6414           
6415           if (!gtk_text_view_starts_display_line (text_view, end))
6416             gtk_text_view_forward_display_line_end (text_view, end);
6417         }
6418     }
6419 }
6420  
6421
6422 typedef struct
6423 {
6424   SelectionGranularity granularity;
6425   GtkTextMark *orig_start;
6426   GtkTextMark *orig_end;
6427 } SelectionData;
6428
6429 static void
6430 selection_data_free (SelectionData *data)
6431 {
6432   if (data->orig_start != NULL)
6433     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (data->orig_start),
6434                                  data->orig_start);
6435   if (data->orig_end != NULL)
6436     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (data->orig_end),
6437                                  data->orig_end);
6438   g_free (data);
6439 }
6440
6441 static gint
6442 selection_motion_event_handler (GtkTextView    *text_view, 
6443                                 GdkEventMotion *event, 
6444                                 SelectionData  *data)
6445 {
6446   GtkTextViewPrivate *priv;
6447
6448   priv = text_view->priv;
6449   gdk_event_request_motions (event);
6450
6451   if (priv->grab_device != event->device)
6452     return FALSE;
6453
6454   if (data->granularity == SELECT_CHARACTERS) 
6455     {
6456       move_mark_to_pointer_and_scroll (text_view, "insert", event->device);
6457     }
6458   else 
6459     {
6460       GtkTextIter cursor, start, end;
6461       GtkTextIter orig_start, orig_end;
6462       GtkTextBuffer *buffer;
6463       
6464       buffer = get_buffer (text_view);
6465
6466       gtk_text_buffer_get_iter_at_mark (buffer, &orig_start, data->orig_start);
6467       gtk_text_buffer_get_iter_at_mark (buffer, &orig_end, data->orig_end);
6468
6469       get_iter_at_pointer (text_view, event->device, &cursor, NULL, NULL);
6470       
6471       start = cursor;
6472       extend_selection (text_view, data->granularity, &start, &end);
6473
6474       /* either the selection extends to the front, or end (or not) */
6475       if (gtk_text_iter_compare (&cursor, &orig_start) < 0)
6476         gtk_text_buffer_select_range (buffer, &start, &orig_end);
6477       else
6478         gtk_text_buffer_select_range (buffer, &end, &orig_start);
6479
6480       gtk_text_view_scroll_mark_onscreen (text_view, 
6481                                           gtk_text_buffer_get_insert (buffer));
6482     }
6483
6484   /* If we had to scroll offscreen, insert a timeout to do so
6485    * again. Note that in the timeout, even if the mouse doesn't
6486    * move, due to this scroll xoffset/yoffset will have changed
6487    * and we'll need to scroll again.
6488    */
6489   if (text_view->priv->scroll_timeout != 0) /* reset on every motion event */
6490     g_source_remove (text_view->priv->scroll_timeout);
6491   
6492   text_view->priv->scroll_timeout =
6493     gdk_threads_add_timeout (50, selection_scan_timeout, text_view);
6494
6495   return TRUE;
6496 }
6497
6498 static void
6499 gtk_text_view_start_selection_drag (GtkTextView       *text_view,
6500                                     const GtkTextIter *iter,
6501                                     GdkEventButton    *button)
6502 {
6503   GtkTextViewPrivate *priv;
6504   GtkTextIter cursor, ins, bound;
6505   GtkTextIter orig_start, orig_end;
6506   GtkTextBuffer *buffer;
6507   SelectionData *data;
6508
6509   if (text_view->priv->selection_drag_handler != 0)
6510     return;
6511
6512   priv = text_view->priv;
6513   data = g_new0 (SelectionData, 1);
6514
6515   if (button->type == GDK_2BUTTON_PRESS)
6516     data->granularity = SELECT_WORDS;
6517   else if (button->type == GDK_3BUTTON_PRESS)
6518     data->granularity = SELECT_LINES;
6519   else 
6520     data->granularity = SELECT_CHARACTERS;
6521
6522   priv->grab_device = button->device;
6523   gtk_device_grab_add (GTK_WIDGET (text_view),
6524                        priv->grab_device,
6525                        TRUE);
6526
6527   buffer = get_buffer (text_view);
6528   
6529   cursor = *iter;
6530   ins = cursor;
6531   
6532   extend_selection (text_view, data->granularity, &ins, &bound);
6533   orig_start = ins;
6534   orig_end = bound;
6535
6536   if (button->state & GDK_SHIFT_MASK)
6537     {
6538       /* Extend selection */
6539       GtkTextIter old_ins, old_bound;
6540       GtkTextIter old_start, old_end;
6541
6542       gtk_text_buffer_get_iter_at_mark (buffer, &old_ins, gtk_text_buffer_get_insert (buffer));
6543       gtk_text_buffer_get_iter_at_mark (buffer, &old_bound, gtk_text_buffer_get_selection_bound (buffer));
6544       old_start = old_ins;
6545       old_end = old_bound;
6546       gtk_text_iter_order (&old_start, &old_end);
6547       
6548       /* move the front cursor, if the mouse is in front of the selection. Should the
6549        * cursor however be inside the selection (this happens on tripple click) then we
6550        * move the side which was last moved (current insert mark) */
6551       if (gtk_text_iter_compare (&cursor, &old_start) <= 0 ||
6552           (gtk_text_iter_compare (&cursor, &old_end) < 0 && 
6553            gtk_text_iter_compare (&old_ins, &old_bound) <= 0))
6554         {
6555           bound = old_end;
6556           orig_start = old_end;
6557           orig_end = old_end;
6558         }
6559       else
6560         {
6561           ins = bound;
6562           bound = old_start;
6563           orig_end = bound;
6564           orig_start = bound;
6565         }
6566     }
6567
6568   gtk_text_buffer_select_range (buffer, &ins, &bound);
6569
6570   gtk_text_iter_order (&orig_start, &orig_end);
6571   data->orig_start = gtk_text_buffer_create_mark (buffer, NULL,
6572                                                   &orig_start, TRUE);
6573   data->orig_end = gtk_text_buffer_create_mark (buffer, NULL,
6574                                                 &orig_end, TRUE);
6575   gtk_text_view_check_cursor_blink (text_view);
6576
6577   text_view->priv->selection_drag_handler = g_signal_connect_data (text_view,
6578                                                                    "motion-notify-event",
6579                                                                    G_CALLBACK (selection_motion_event_handler),
6580                                                                    data,
6581                                                                    (GClosureNotify) selection_data_free, 0);
6582 }
6583
6584 /* returns whether we were really dragging */
6585 static gboolean
6586 gtk_text_view_end_selection_drag (GtkTextView *text_view)
6587 {
6588   GtkTextViewPrivate *priv;
6589
6590   priv = text_view->priv;
6591
6592   if (!priv->grab_device)
6593     return FALSE;
6594
6595   if (priv->selection_drag_handler == 0)
6596     return FALSE;
6597
6598   g_signal_handler_disconnect (text_view, priv->selection_drag_handler);
6599   priv->selection_drag_handler = 0;
6600
6601   if (priv->scroll_timeout != 0)
6602     {
6603       g_source_remove (priv->scroll_timeout);
6604       priv->scroll_timeout = 0;
6605     }
6606
6607   gtk_device_grab_remove (GTK_WIDGET (text_view),
6608                           priv->grab_device);
6609   priv->grab_device = NULL;
6610
6611   return TRUE;
6612 }
6613
6614 /*
6615  * Layout utils
6616  */
6617
6618 static void
6619 gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
6620                                          GtkTextAttributes  *values,
6621                                          GtkStyle           *style)
6622 {
6623   values->appearance.bg_color = style->base[GTK_STATE_NORMAL];
6624   values->appearance.fg_color = style->text[GTK_STATE_NORMAL];
6625
6626   if (values->font)
6627     pango_font_description_free (values->font);
6628
6629   values->font = pango_font_description_copy (style->font_desc);
6630 }
6631
6632 static void
6633 gtk_text_view_check_keymap_direction (GtkTextView *text_view)
6634 {
6635   GtkTextViewPrivate *priv = text_view->priv;
6636
6637   if (priv->layout)
6638     {
6639       GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
6640       GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (text_view)));
6641       GtkTextDirection new_cursor_dir;
6642       GtkTextDirection new_keyboard_dir;
6643       gboolean split_cursor;
6644
6645       g_object_get (settings,
6646                     "gtk-split-cursor", &split_cursor,
6647                     NULL);
6648       
6649       if (gdk_keymap_get_direction (keymap) == PANGO_DIRECTION_RTL)
6650         new_keyboard_dir = GTK_TEXT_DIR_RTL;
6651       else
6652         new_keyboard_dir  = GTK_TEXT_DIR_LTR;
6653   
6654       if (split_cursor)
6655         new_cursor_dir = GTK_TEXT_DIR_NONE;
6656       else
6657         new_cursor_dir = new_keyboard_dir;
6658       
6659       gtk_text_layout_set_cursor_direction (priv->layout, new_cursor_dir);
6660       gtk_text_layout_set_keyboard_direction (priv->layout, new_keyboard_dir);
6661     }
6662 }
6663
6664 static void
6665 gtk_text_view_ensure_layout (GtkTextView *text_view)
6666 {
6667   GtkWidget *widget;
6668   GtkTextViewPrivate *priv;
6669
6670   widget = GTK_WIDGET (text_view);
6671   priv = text_view->priv;
6672
6673   if (priv->layout == NULL)
6674     {
6675       GtkTextAttributes *style;
6676       PangoContext *ltr_context, *rtl_context;
6677       GSList *tmp_list;
6678
6679       DV(g_print(G_STRLOC"\n"));
6680       
6681       priv->layout = gtk_text_layout_new ();
6682
6683       g_signal_connect (priv->layout,
6684                         "invalidated",
6685                         G_CALLBACK (invalidated_handler),
6686                         text_view);
6687
6688       g_signal_connect (priv->layout,
6689                         "changed",
6690                         G_CALLBACK (changed_handler),
6691                         text_view);
6692
6693       g_signal_connect (priv->layout,
6694                         "allocate-child",
6695                         G_CALLBACK (gtk_text_view_child_allocated),
6696                         text_view);
6697       
6698       if (get_buffer (text_view))
6699         gtk_text_layout_set_buffer (priv->layout, get_buffer (text_view));
6700
6701       if ((gtk_widget_has_focus (widget) && priv->cursor_visible))
6702         gtk_text_view_pend_cursor_blink (text_view);
6703       else
6704         gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
6705
6706       gtk_text_layout_set_overwrite_mode (priv->layout,
6707                                           priv->overwrite_mode && priv->editable);
6708
6709       ltr_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
6710       pango_context_set_base_dir (ltr_context, PANGO_DIRECTION_LTR);
6711       rtl_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
6712       pango_context_set_base_dir (rtl_context, PANGO_DIRECTION_RTL);
6713
6714       gtk_text_layout_set_contexts (priv->layout, ltr_context, rtl_context);
6715
6716       g_object_unref (ltr_context);
6717       g_object_unref (rtl_context);
6718
6719       gtk_text_view_check_keymap_direction (text_view);
6720
6721       style = gtk_text_attributes_new ();
6722
6723       gtk_widget_ensure_style (widget);
6724       gtk_text_view_set_attributes_from_style (text_view,
6725                                                style,
6726                                                gtk_widget_get_style (widget));
6727
6728       style->pixels_above_lines = priv->pixels_above_lines;
6729       style->pixels_below_lines = priv->pixels_below_lines;
6730       style->pixels_inside_wrap = priv->pixels_inside_wrap;
6731       style->left_margin = priv->left_margin;
6732       style->right_margin = priv->right_margin;
6733       style->indent = priv->indent;
6734       style->tabs = priv->tabs ? pango_tab_array_copy (priv->tabs) : NULL;
6735
6736       style->wrap_mode = priv->wrap_mode;
6737       style->justification = priv->justify;
6738       style->direction = gtk_widget_get_direction (GTK_WIDGET (text_view));
6739
6740       gtk_text_layout_set_default_style (priv->layout, style);
6741
6742       gtk_text_attributes_unref (style);
6743
6744       /* Set layout for all anchored children */
6745
6746       tmp_list = priv->children;
6747       while (tmp_list != NULL)
6748         {
6749           GtkTextViewChild *vc = tmp_list->data;
6750
6751           if (vc->anchor)
6752             {
6753               gtk_text_anchored_child_set_layout (vc->widget,
6754                                                   priv->layout);
6755               /* vc may now be invalid! */
6756             }
6757
6758           tmp_list = g_slist_next (tmp_list);
6759         }
6760
6761       gtk_text_view_invalidate (text_view);
6762     }
6763 }
6764
6765 /**
6766  * gtk_text_view_get_default_attributes:
6767  * @text_view: a #GtkTextView
6768  * 
6769  * Obtains a copy of the default text attributes. These are the
6770  * attributes used for text unless a tag overrides them.
6771  * You'd typically pass the default attributes in to
6772  * gtk_text_iter_get_attributes() in order to get the
6773  * attributes in effect at a given text position.
6774  *
6775  * The return value is a copy owned by the caller of this function,
6776  * and should be freed.
6777  * 
6778  * Return value: a new #GtkTextAttributes
6779  **/
6780 GtkTextAttributes*
6781 gtk_text_view_get_default_attributes (GtkTextView *text_view)
6782 {
6783   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
6784   
6785   gtk_text_view_ensure_layout (text_view);
6786
6787   return gtk_text_attributes_copy (text_view->priv->layout->default_style);
6788 }
6789
6790 static void
6791 gtk_text_view_destroy_layout (GtkTextView *text_view)
6792 {
6793   GtkTextViewPrivate *priv = text_view->priv;
6794
6795   if (priv->layout)
6796     {
6797       GSList *tmp_list;
6798
6799       gtk_text_view_remove_validate_idles (text_view);
6800
6801       g_signal_handlers_disconnect_by_func (priv->layout,
6802                                             invalidated_handler,
6803                                             text_view);
6804       g_signal_handlers_disconnect_by_func (priv->layout,
6805                                             changed_handler,
6806                                             text_view);
6807
6808       /* Remove layout from all anchored children */
6809       tmp_list = priv->children;
6810       while (tmp_list != NULL)
6811         {
6812           GtkTextViewChild *vc = tmp_list->data;
6813
6814           if (vc->anchor)
6815             {
6816               gtk_text_anchored_child_set_layout (vc->widget, NULL);
6817               /* vc may now be invalid! */
6818             }
6819
6820           tmp_list = g_slist_next (tmp_list);
6821         }
6822
6823       gtk_text_view_stop_cursor_blink (text_view);
6824       gtk_text_view_end_selection_drag (text_view);
6825
6826       g_object_unref (priv->layout);
6827       priv->layout = NULL;
6828     }
6829 }
6830
6831 /**
6832  * gtk_text_view_reset_im_context:
6833  * @text_view: a #GtkTextView
6834  *
6835  * Reset the input method context of the text view if needed.
6836  *
6837  * This can be necessary in the case where modifying the buffer
6838  * would confuse on-going input method behavior.
6839  *
6840  * Since: 2.22
6841  */
6842 void
6843 gtk_text_view_reset_im_context (GtkTextView *text_view)
6844 {
6845   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
6846
6847   if (text_view->priv->need_im_reset)
6848     {
6849       text_view->priv->need_im_reset = FALSE;
6850       gtk_im_context_reset (text_view->priv->im_context);
6851     }
6852 }
6853
6854 /**
6855  * gtk_text_view_im_context_filter_keypress:
6856  * @text_view: a #GtkTextView
6857  * @event: the key event
6858  *
6859  * Allow the #GtkTextView input method to internally handle key press
6860  * and release events. If this function returns %TRUE, then no further
6861  * processing should be done for this key event. See
6862  * gtk_im_context_filter_keypress().
6863  *
6864  * Note that you are expected to call this function from your handler
6865  * when overriding key event handling. This is needed in the case when
6866  * you need to insert your own key handling between the input method
6867  * and the default key event handling of the #GtkTextView.
6868  *
6869  * |[
6870  * static gboolean
6871  * gtk_foo_bar_key_press_event (GtkWidget   *widget,
6872  *                              GdkEventKey *event)
6873  * {
6874  *   if ((key->keyval == GDK_Return || key->keyval == GDK_KP_Enter))
6875  *     {
6876  *       if (gtk_text_view_im_context_filter_keypress (GTK_TEXT_VIEW (view), event))
6877  *         return TRUE;
6878  *     }
6879  *
6880  *     /&ast; Do some stuff &ast;/
6881  *
6882  *   return GTK_WIDGET_CLASS (gtk_foo_bar_parent_class)->key_press_event (widget, event);
6883  * }
6884  * ]|
6885  *
6886  * Return value: %TRUE if the input method handled the key event.
6887  *
6888  * Since: 2.22
6889  */
6890 gboolean
6891 gtk_text_view_im_context_filter_keypress (GtkTextView  *text_view,
6892                                           GdkEventKey  *event)
6893 {
6894   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
6895
6896   return gtk_im_context_filter_keypress (text_view->priv->im_context, event);
6897 }
6898
6899 /*
6900  * DND feature
6901  */
6902
6903 static void
6904 drag_begin_cb (GtkWidget      *widget,
6905                GdkDragContext *context,
6906                gpointer        data)
6907 {
6908   GtkTextView     *text_view = GTK_TEXT_VIEW (widget);
6909   GtkTextBuffer   *buffer = gtk_text_view_get_buffer (text_view);
6910   GtkTextIter      start;
6911   GtkTextIter      end;
6912   cairo_surface_t *surface = NULL;
6913
6914   g_signal_handlers_disconnect_by_func (widget, drag_begin_cb, NULL);
6915
6916   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
6917     surface = _gtk_text_util_create_rich_drag_icon (widget, buffer, &start, &end);
6918
6919   if (surface)
6920     {
6921       gtk_drag_set_icon_surface (context, surface);
6922       cairo_surface_destroy (surface);
6923     }
6924   else
6925     {
6926       gtk_drag_set_icon_default (context);
6927     }
6928 }
6929
6930 static void
6931 gtk_text_view_start_selection_dnd (GtkTextView       *text_view,
6932                                    const GtkTextIter *iter,
6933                                    GdkEventMotion    *event)
6934 {
6935   GtkTargetList *target_list;
6936
6937   text_view->priv->drag_start_x = -1;
6938   text_view->priv->drag_start_y = -1;
6939   text_view->priv->pending_place_cursor_button = 0;
6940
6941   target_list = gtk_text_buffer_get_copy_target_list (get_buffer (text_view));
6942
6943   g_signal_connect (text_view, "drag-begin",
6944                     G_CALLBACK (drag_begin_cb), NULL);
6945   gtk_drag_begin (GTK_WIDGET (text_view), target_list,
6946                   GDK_ACTION_COPY | GDK_ACTION_MOVE,
6947                   1, (GdkEvent*)event);
6948 }
6949
6950 static void
6951 gtk_text_view_drag_begin (GtkWidget        *widget,
6952                           GdkDragContext   *context)
6953 {
6954   /* do nothing */
6955 }
6956
6957 static void
6958 gtk_text_view_drag_end (GtkWidget        *widget,
6959                         GdkDragContext   *context)
6960 {
6961 }
6962
6963 static void
6964 gtk_text_view_drag_data_get (GtkWidget        *widget,
6965                              GdkDragContext   *context,
6966                              GtkSelectionData *selection_data,
6967                              guint             info,
6968                              guint             time)
6969 {
6970   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
6971   GtkTextBuffer *buffer = gtk_text_view_get_buffer (text_view);
6972
6973   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
6974     {
6975       gtk_selection_data_set (selection_data,
6976                               gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"),
6977                               8, /* bytes */
6978                               (void*)&buffer,
6979                               sizeof (buffer));
6980     }
6981   else if (info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
6982     {
6983       GtkTextIter start;
6984       GtkTextIter end;
6985       guint8 *str = NULL;
6986       gsize len;
6987
6988       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
6989         {
6990           /* Extract the selected text */
6991           str = gtk_text_buffer_serialize (buffer, buffer,
6992                                            selection_data->target,
6993                                            &start, &end,
6994                                            &len);
6995         }
6996
6997       if (str)
6998         {
6999           gtk_selection_data_set (selection_data,
7000                                   selection_data->target,
7001                                   8, /* bytes */
7002                                   (guchar *) str, len);
7003           g_free (str);
7004         }
7005     }
7006   else
7007     {
7008       GtkTextIter start;
7009       GtkTextIter end;
7010       gchar *str = NULL;
7011
7012       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
7013         {
7014           /* Extract the selected text */
7015           str = gtk_text_iter_get_visible_text (&start, &end);
7016         }
7017
7018       if (str)
7019         {
7020           gtk_selection_data_set_text (selection_data, str, -1);
7021           g_free (str);
7022         }
7023     }
7024 }
7025
7026 static void
7027 gtk_text_view_drag_data_delete (GtkWidget        *widget,
7028                                 GdkDragContext   *context)
7029 {
7030   gtk_text_buffer_delete_selection (GTK_TEXT_VIEW (widget)->priv->buffer,
7031                                     TRUE, GTK_TEXT_VIEW (widget)->priv->editable);
7032 }
7033
7034 static void
7035 gtk_text_view_drag_leave (GtkWidget        *widget,
7036                           GdkDragContext   *context,
7037                           guint             time)
7038 {
7039   GtkTextView *text_view;
7040   GtkTextViewPrivate *priv;
7041
7042   text_view = GTK_TEXT_VIEW (widget);
7043   priv = text_view->priv;
7044
7045   gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7046
7047   if (priv->dnd_device)
7048     priv->dnd_device = NULL;
7049
7050   if (priv->scroll_timeout != 0)
7051     g_source_remove (priv->scroll_timeout);
7052
7053   priv->scroll_timeout = 0;
7054 }
7055
7056 static gboolean
7057 gtk_text_view_drag_motion (GtkWidget        *widget,
7058                            GdkDragContext   *context,
7059                            gint              x,
7060                            gint              y,
7061                            guint             time)
7062 {
7063   GtkTextIter newplace;
7064   GtkTextView *text_view;
7065   GtkTextViewPrivate *priv;
7066   GtkTextIter start;
7067   GtkTextIter end;
7068   GdkRectangle target_rect;
7069   gint bx, by;
7070   GdkAtom target;
7071   GdkDragAction suggested_action = 0;
7072   
7073   text_view = GTK_TEXT_VIEW (widget);
7074   priv = text_view->priv;
7075
7076   target_rect = priv->text_window->allocation;
7077   
7078   if (x < target_rect.x ||
7079       y < target_rect.y ||
7080       x > (target_rect.x + target_rect.width) ||
7081       y > (target_rect.y + target_rect.height))
7082     return FALSE; /* outside the text window, allow parent widgets to handle event */
7083
7084   gtk_text_view_window_to_buffer_coords (text_view,
7085                                          GTK_TEXT_WINDOW_WIDGET,
7086                                          x, y,
7087                                          &bx, &by);
7088
7089   gtk_text_layout_get_iter_at_pixel (priv->layout,
7090                                      &newplace,
7091                                      bx, by);  
7092
7093   target = gtk_drag_dest_find_target (widget, context,
7094                                       gtk_drag_dest_get_target_list (widget));
7095
7096   if (target == GDK_NONE)
7097     {
7098       /* can't accept any of the offered targets */
7099     }                                 
7100   else if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
7101                                                  &start, &end) &&
7102            gtk_text_iter_compare (&newplace, &start) >= 0 &&
7103            gtk_text_iter_compare (&newplace, &end) <= 0)
7104     {
7105       /* We're inside the selection. */
7106     }
7107   else
7108     {      
7109       if (gtk_text_iter_can_insert (&newplace, priv->editable))
7110         {
7111           GtkWidget *source_widget;
7112           
7113           suggested_action = context->suggested_action;
7114           
7115           source_widget = gtk_drag_get_source_widget (context);
7116           
7117           if (source_widget == widget)
7118             {
7119               /* Default to MOVE, unless the user has
7120                * pressed ctrl or alt to affect available actions
7121                */
7122               if ((context->actions & GDK_ACTION_MOVE) != 0)
7123                 suggested_action = GDK_ACTION_MOVE;
7124             }
7125         }
7126       else
7127         {
7128           /* Can't drop here. */
7129         }
7130     }
7131
7132   if (suggested_action != 0)
7133     {
7134       gtk_text_mark_set_visible (priv->dnd_mark,
7135                                  priv->cursor_visible);
7136       
7137       gdk_drag_status (context, suggested_action, time);
7138     }
7139   else
7140     {
7141       gdk_drag_status (context, 0, time);
7142       gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7143     }
7144
7145   priv->dnd_device = gdk_drag_context_get_device (context);
7146
7147   if (!priv->scroll_timeout)
7148     priv->scroll_timeout =
7149       gdk_threads_add_timeout (100, drag_scan_timeout, text_view);
7150
7151   /* TRUE return means don't propagate the drag motion to parent
7152    * widgets that may also be drop sites.
7153    */
7154   return TRUE;
7155 }
7156
7157 static gboolean
7158 gtk_text_view_drag_drop (GtkWidget        *widget,
7159                          GdkDragContext   *context,
7160                          gint              x,
7161                          gint              y,
7162                          guint             time)
7163 {
7164   GtkTextView *text_view;
7165   GtkTextViewPrivate *priv;
7166   GtkTextIter drop_point;
7167   GdkAtom target = GDK_NONE;
7168
7169   text_view = GTK_TEXT_VIEW (widget);
7170   priv = text_view->priv;
7171
7172   if (priv->scroll_timeout != 0)
7173     g_source_remove (priv->scroll_timeout);
7174
7175   priv->scroll_timeout = 0;
7176
7177   gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7178
7179   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
7180                                     &drop_point,
7181                                     priv->dnd_mark);
7182
7183   if (gtk_text_iter_can_insert (&drop_point, priv->editable))
7184     target = gtk_drag_dest_find_target (widget, context, NULL);
7185
7186   if (target != GDK_NONE)
7187     gtk_drag_get_data (widget, context, target, time);
7188   else
7189     gtk_drag_finish (context, FALSE, FALSE, time);
7190
7191   return TRUE;
7192 }
7193
7194 static void
7195 insert_text_data (GtkTextView      *text_view,
7196                   GtkTextIter      *drop_point,
7197                   GtkSelectionData *selection_data)
7198 {
7199   guchar *str;
7200
7201   str = gtk_selection_data_get_text (selection_data);
7202
7203   if (str)
7204     {
7205       if (!gtk_text_buffer_insert_interactive (get_buffer (text_view),
7206                                                drop_point, (gchar *) str, -1,
7207                                                text_view->priv->editable))
7208         {
7209           gtk_widget_error_bell (GTK_WIDGET (text_view));
7210         }
7211
7212       g_free (str);
7213     }
7214 }
7215
7216 static void
7217 gtk_text_view_drag_data_received (GtkWidget        *widget,
7218                                   GdkDragContext   *context,
7219                                   gint              x,
7220                                   gint              y,
7221                                   GtkSelectionData *selection_data,
7222                                   guint             info,
7223                                   guint             time)
7224 {
7225   GtkTextIter drop_point;
7226   GtkTextView *text_view;
7227   GtkTextViewPrivate *priv;
7228   gboolean success = FALSE;
7229   GtkTextBuffer *buffer = NULL;
7230
7231   text_view = GTK_TEXT_VIEW (widget);
7232   priv = text_view->priv;
7233
7234   if (!priv->dnd_mark)
7235     goto done;
7236
7237   buffer = get_buffer (text_view);
7238
7239   gtk_text_buffer_get_iter_at_mark (buffer,
7240                                     &drop_point,
7241                                     priv->dnd_mark);
7242   
7243   if (!gtk_text_iter_can_insert (&drop_point, priv->editable))
7244     goto done;
7245
7246   success = TRUE;
7247
7248   gtk_text_buffer_begin_user_action (buffer);
7249
7250   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
7251     {
7252       GtkTextBuffer *src_buffer = NULL;
7253       GtkTextIter start, end;
7254       gboolean copy_tags = TRUE;
7255
7256       if (selection_data->length != sizeof (src_buffer))
7257         return;
7258
7259       memcpy (&src_buffer, selection_data->data, sizeof (src_buffer));
7260
7261       if (src_buffer == NULL)
7262         return;
7263
7264       g_return_if_fail (GTK_IS_TEXT_BUFFER (src_buffer));
7265
7266       if (gtk_text_buffer_get_tag_table (src_buffer) !=
7267           gtk_text_buffer_get_tag_table (buffer))
7268         {
7269           /*  try to find a suitable rich text target instead  */
7270           GdkAtom *atoms;
7271           gint     n_atoms;
7272           GList   *list;
7273           GdkAtom  target = GDK_NONE;
7274
7275           copy_tags = FALSE;
7276
7277           atoms = gtk_text_buffer_get_deserialize_formats (buffer, &n_atoms);
7278
7279           for (list = context->targets; list; list = g_list_next (list))
7280             {
7281               gint i;
7282
7283               for (i = 0; i < n_atoms; i++)
7284                 if (GUINT_TO_POINTER (atoms[i]) == list->data)
7285                   {
7286                     target = atoms[i];
7287                     break;
7288                   }
7289             }
7290
7291           g_free (atoms);
7292
7293           if (target != GDK_NONE)
7294             {
7295               gtk_drag_get_data (widget, context, target, time);
7296               gtk_text_buffer_end_user_action (buffer);
7297               return;
7298             }
7299         }
7300
7301       if (gtk_text_buffer_get_selection_bounds (src_buffer,
7302                                                 &start,
7303                                                 &end))
7304         {
7305           if (copy_tags)
7306             gtk_text_buffer_insert_range_interactive (buffer,
7307                                                       &drop_point,
7308                                                       &start,
7309                                                       &end,
7310                                                       priv->editable);
7311           else
7312             {
7313               gchar *str;
7314
7315               str = gtk_text_iter_get_visible_text (&start, &end);
7316               gtk_text_buffer_insert_interactive (buffer,
7317                                                   &drop_point, str, -1,
7318                                                   priv->editable);
7319               g_free (str);
7320             }
7321         }
7322     }
7323   else if (selection_data->length > 0 &&
7324            info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
7325     {
7326       gboolean retval;
7327       GError *error = NULL;
7328
7329       retval = gtk_text_buffer_deserialize (buffer, buffer,
7330                                             selection_data->target,
7331                                             &drop_point,
7332                                             (guint8 *) selection_data->data,
7333                                             selection_data->length,
7334                                             &error);
7335
7336       if (!retval)
7337         {
7338           g_warning ("error pasting: %s\n", error->message);
7339           g_clear_error (&error);
7340         }
7341     }
7342   else
7343     insert_text_data (text_view, &drop_point, selection_data);
7344
7345  done:
7346   gtk_drag_finish (context, success,
7347                    success && context->action == GDK_ACTION_MOVE,
7348                    time);
7349
7350   if (success)
7351     {
7352       gtk_text_buffer_get_iter_at_mark (buffer,
7353                                         &drop_point,
7354                                         priv->dnd_mark);
7355       gtk_text_buffer_place_cursor (buffer, &drop_point);
7356
7357       gtk_text_buffer_end_user_action (buffer);
7358     }
7359 }
7360
7361 /**
7362  * gtk_text_view_get_hadjustment:
7363  * @text_view: a #GtkTextView
7364  *
7365  * Gets the horizontal-scrolling #GtkAdjustment.
7366  *
7367  * Returns: (transfer none): pointer to the horizontal #GtkAdjustment
7368  *
7369  * Since: 2.22
7370  **/
7371 GtkAdjustment*
7372 gtk_text_view_get_hadjustment (GtkTextView *text_view)
7373 {
7374   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
7375
7376   return get_hadjustment (text_view);
7377 }
7378
7379 /**
7380  * gtk_text_view_get_vadjustment:
7381  * @text_view: a #GtkTextView
7382  *
7383  * Gets the vertical-scrolling #GtkAdjustment.
7384  *
7385  * Returns: (transfer none): pointer to the vertical #GtkAdjustment
7386  *
7387  * Since: 2.22
7388  **/
7389 GtkAdjustment*
7390 gtk_text_view_get_vadjustment (GtkTextView *text_view)
7391 {
7392   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
7393
7394   return get_vadjustment (text_view);
7395 }
7396
7397 static GtkAdjustment*
7398 get_hadjustment (GtkTextView *text_view)
7399 {
7400   if (text_view->priv->hadjustment == NULL)
7401     gtk_text_view_set_scroll_adjustments (text_view,
7402                                           NULL, /* forces creation */
7403                                           text_view->priv->vadjustment);
7404
7405   return text_view->priv->hadjustment;
7406 }
7407
7408 static GtkAdjustment*
7409 get_vadjustment (GtkTextView *text_view)
7410 {
7411   if (text_view->priv->vadjustment == NULL)
7412     gtk_text_view_set_scroll_adjustments (text_view,
7413                                           text_view->priv->hadjustment,
7414                                           NULL); /* forces creation */
7415   return text_view->priv->vadjustment;
7416 }
7417
7418
7419 static void
7420 gtk_text_view_set_scroll_adjustments (GtkTextView   *text_view,
7421                                       GtkAdjustment *hadj,
7422                                       GtkAdjustment *vadj)
7423 {
7424   GtkTextViewPrivate *priv = text_view->priv;
7425   gboolean need_adjust = FALSE;
7426
7427   if (hadj)
7428     g_return_if_fail (GTK_IS_ADJUSTMENT (hadj));
7429   else
7430     hadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
7431   if (vadj)
7432     g_return_if_fail (GTK_IS_ADJUSTMENT (vadj));
7433   else
7434     vadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
7435
7436   if (priv->hadjustment && (priv->hadjustment != hadj))
7437     {
7438       g_signal_handlers_disconnect_by_func (priv->hadjustment,
7439                                             gtk_text_view_value_changed,
7440                                             text_view);
7441       g_object_unref (priv->hadjustment);
7442     }
7443
7444   if (priv->vadjustment && (priv->vadjustment != vadj))
7445     {
7446       g_signal_handlers_disconnect_by_func (priv->vadjustment,
7447                                             gtk_text_view_value_changed,
7448                                             text_view);
7449       g_object_unref (priv->vadjustment);
7450     }
7451
7452   if (priv->hadjustment != hadj)
7453     {
7454       priv->hadjustment = hadj;
7455       g_object_ref_sink (priv->hadjustment);
7456       
7457       g_signal_connect (priv->hadjustment, "value-changed",
7458                         G_CALLBACK (gtk_text_view_value_changed),
7459                         text_view);
7460       need_adjust = TRUE;
7461     }
7462
7463   if (priv->vadjustment != vadj)
7464     {
7465       priv->vadjustment = vadj;
7466       g_object_ref_sink (priv->vadjustment);
7467       
7468       g_signal_connect (priv->vadjustment, "value-changed",
7469                         G_CALLBACK (gtk_text_view_value_changed),
7470                         text_view);
7471       need_adjust = TRUE;
7472     }
7473
7474   if (need_adjust)
7475     gtk_text_view_value_changed (NULL, text_view);
7476 }
7477
7478 /* FIXME this adjust_allocation is a big cut-and-paste from
7479  * GtkCList, needs to be some "official" way to do this
7480  * factored out.
7481  */
7482 typedef struct
7483 {
7484   GdkWindow *window;
7485   int dx;
7486   int dy;
7487 } ScrollData;
7488
7489 /* The window to which widget->window is relative */
7490 #define ALLOCATION_WINDOW(widget)               \
7491    (!gtk_widget_get_has_window (widget) ?                   \
7492     gtk_widget_get_window (widget) :                        \
7493     gdk_window_get_parent (gtk_widget_get_window (widget)))
7494
7495 static void
7496 adjust_allocation_recurse (GtkWidget *widget,
7497                            gpointer   data)
7498 {
7499   GtkAllocation allocation;
7500   ScrollData *scroll_data = data;
7501
7502   /* Need to really size allocate instead of just poking
7503    * into widget->allocation if the widget is not realized.
7504    * FIXME someone figure out why this was.
7505    */
7506   if (!gtk_widget_get_realized (widget))
7507     {
7508       if (gtk_widget_get_visible (widget))
7509         {
7510           GdkRectangle tmp_rectangle;
7511
7512           tmp_rectangle = allocation;
7513           tmp_rectangle.x += scroll_data->dx;
7514           tmp_rectangle.y += scroll_data->dy;
7515           
7516           gtk_widget_size_allocate (widget, &tmp_rectangle);
7517         }
7518     }
7519   else
7520     {
7521       if (ALLOCATION_WINDOW (widget) == scroll_data->window)
7522         {
7523           allocation.x += scroll_data->dx;
7524           allocation.y += scroll_data->dy;
7525           gtk_widget_set_allocation (widget, &allocation);
7526
7527           if (GTK_IS_CONTAINER (widget))
7528             gtk_container_forall (GTK_CONTAINER (widget),
7529                                   adjust_allocation_recurse,
7530                                   data);
7531         }
7532     }
7533 }
7534
7535 static void
7536 adjust_allocation (GtkWidget *widget,
7537                    int        dx,
7538                    int        dy)
7539 {
7540   ScrollData scroll_data;
7541
7542   if (gtk_widget_get_realized (widget))
7543     scroll_data.window = ALLOCATION_WINDOW (widget);
7544   else
7545     scroll_data.window = NULL;
7546     
7547   scroll_data.dx = dx;
7548   scroll_data.dy = dy;
7549   
7550   adjust_allocation_recurse (widget, &scroll_data);
7551 }
7552             
7553 static void
7554 gtk_text_view_value_changed (GtkAdjustment *adj,
7555                              GtkTextView   *text_view)
7556 {
7557   GtkTextViewPrivate *priv;
7558   GtkTextIter iter;
7559   gint line_top;
7560   gint dx = 0;
7561   gint dy = 0;
7562
7563   priv = text_view->priv;
7564
7565   /* Note that we oddly call this function with adj == NULL
7566    * sometimes
7567    */
7568   
7569   priv->onscreen_validated = FALSE;
7570
7571   DV(g_print(">Scroll offset changed %s/%g, onscreen_validated = FALSE ("G_STRLOC")\n",
7572              adj == priv->hadjustment ? "hadj" : adj == priv->vadjustment ? "vadj" : "none",
7573              adj ? adj->value : 0.0));
7574   
7575   if (adj == priv->hadjustment)
7576     {
7577       dx = priv->xoffset - (gint)adj->value;
7578       priv->xoffset = adj->value;
7579
7580       /* If the change is due to a size change we need 
7581        * to invalidate the entire text window because there might be
7582        * right-aligned or centered text 
7583        */
7584       if (priv->width_changed)
7585         {
7586           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
7587             gdk_window_invalidate_rect (priv->text_window->bin_window, NULL, FALSE);
7588           
7589           priv->width_changed = FALSE;
7590         }
7591     }
7592   else if (adj == priv->vadjustment)
7593     {
7594       dy = priv->yoffset - (gint)adj->value;
7595       priv->yoffset = adj->value;
7596
7597       if (priv->layout)
7598         {
7599           gtk_text_layout_get_line_at_y (priv->layout, &iter, adj->value, &line_top);
7600
7601           gtk_text_buffer_move_mark (get_buffer (text_view), priv->first_para_mark, &iter);
7602
7603           priv->first_para_pixels = adj->value - line_top;
7604         }
7605     }
7606   
7607   if (dx != 0 || dy != 0)
7608     {
7609       GSList *tmp_list;
7610
7611       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
7612         {
7613           if (dy != 0)
7614             {
7615               if (priv->left_window)
7616                 text_window_scroll (priv->left_window, 0, dy);
7617               if (priv->right_window)
7618                 text_window_scroll (priv->right_window, 0, dy);
7619             }
7620       
7621           if (dx != 0)
7622             {
7623               if (priv->top_window)
7624                 text_window_scroll (priv->top_window, dx, 0);
7625               if (priv->bottom_window)
7626                 text_window_scroll (priv->bottom_window, dx, 0);
7627             }
7628       
7629           /* It looks nicer to scroll the main area last, because
7630            * it takes a while, and making the side areas update
7631            * afterward emphasizes the slowness of scrolling the
7632            * main area.
7633            */
7634           text_window_scroll (priv->text_window, dx, dy);
7635         }
7636       
7637       /* Children are now "moved" in the text window, poke
7638        * into widget->allocation for each child
7639        */
7640       tmp_list = priv->children;
7641       while (tmp_list != NULL)
7642         {
7643           GtkTextViewChild *child = tmp_list->data;
7644           
7645           if (child->anchor)
7646             adjust_allocation (child->widget, dx, dy);
7647           
7648           tmp_list = g_slist_next (tmp_list);
7649         }
7650     }
7651
7652   /* This could result in invalidation, which would install the
7653    * first_validate_idle, which would validate onscreen;
7654    * but we're going to go ahead and validate here, so
7655    * first_validate_idle shouldn't have anything to do.
7656    */
7657   gtk_text_view_update_layout_width (text_view);
7658   
7659   /* We also update the IM spot location here, since the IM context
7660    * might do something that leads to validation.
7661    */
7662   gtk_text_view_update_im_spot_location (text_view);
7663
7664   /* note that validation of onscreen could invoke this function
7665    * recursively, by scrolling to maintain first_para, or in response
7666    * to updating the layout width, however there is no problem with
7667    * that, or shouldn't be.
7668    */
7669   gtk_text_view_validate_onscreen (text_view);
7670   
7671   /* process exposes */
7672   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
7673     {
7674       DV (g_print ("Processing updates (%s)\n", G_STRLOC));
7675       
7676       if (priv->left_window)
7677         gdk_window_process_updates (priv->left_window->bin_window, TRUE);
7678
7679       if (priv->right_window)
7680         gdk_window_process_updates (priv->right_window->bin_window, TRUE);
7681
7682       if (priv->top_window)
7683         gdk_window_process_updates (priv->top_window->bin_window, TRUE);
7684       
7685       if (priv->bottom_window)
7686         gdk_window_process_updates (priv->bottom_window->bin_window, TRUE);
7687   
7688       gdk_window_process_updates (priv->text_window->bin_window, TRUE);
7689     }
7690
7691   /* If this got installed, get rid of it, it's just a waste of time. */
7692   if (priv->first_validate_idle != 0)
7693     {
7694       g_source_remove (priv->first_validate_idle);
7695       priv->first_validate_idle = 0;
7696     }
7697
7698   /* Finally we update the IM cursor location again, to ensure any
7699    * changes made by the validation are pushed through.
7700    */
7701   gtk_text_view_update_im_spot_location (text_view);
7702   
7703   DV(g_print(">End scroll offset changed handler ("G_STRLOC")\n"));
7704 }
7705
7706 static void
7707 gtk_text_view_commit_handler (GtkIMContext  *context,
7708                               const gchar   *str,
7709                               GtkTextView   *text_view)
7710 {
7711   gtk_text_view_commit_text (text_view, str);
7712 }
7713
7714 static void
7715 gtk_text_view_commit_text (GtkTextView   *text_view,
7716                            const gchar   *str)
7717 {
7718   GtkTextViewPrivate *priv;
7719   gboolean had_selection;
7720
7721   priv = text_view->priv;
7722
7723   gtk_text_buffer_begin_user_action (get_buffer (text_view));
7724
7725   had_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
7726                                                         NULL, NULL);
7727   
7728   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
7729                                     priv->editable);
7730
7731   if (!strcmp (str, "\n"))
7732     {
7733       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), "\n", 1,
7734                                                          priv->editable))
7735         {
7736           gtk_widget_error_bell (GTK_WIDGET (text_view));
7737         }
7738     }
7739   else
7740     {
7741       if (!had_selection && priv->overwrite_mode)
7742         {
7743           GtkTextIter insert;
7744
7745           gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
7746                                             &insert,
7747                                             gtk_text_buffer_get_insert (get_buffer (text_view)));
7748           if (!gtk_text_iter_ends_line (&insert))
7749             gtk_text_view_delete_from_cursor (text_view, GTK_DELETE_CHARS, 1);
7750         }
7751
7752       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
7753                                                          priv->editable))
7754         {
7755           gtk_widget_error_bell (GTK_WIDGET (text_view));
7756         }
7757     }
7758
7759   gtk_text_buffer_end_user_action (get_buffer (text_view));
7760
7761   gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
7762   DV(g_print (G_STRLOC": scrolling onscreen\n"));
7763   gtk_text_view_scroll_mark_onscreen (text_view,
7764                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
7765 }
7766
7767 static void
7768 gtk_text_view_preedit_changed_handler (GtkIMContext *context,
7769                                        GtkTextView  *text_view)
7770 {
7771   GtkTextViewPrivate *priv;
7772   gchar *str;
7773   PangoAttrList *attrs;
7774   gint cursor_pos;
7775   GtkTextIter iter;
7776
7777   priv = text_view->priv;
7778
7779   gtk_text_buffer_get_iter_at_mark (priv->buffer, &iter,
7780                                     gtk_text_buffer_get_insert (priv->buffer));
7781
7782   /* Keypress events are passed to input method even if cursor position is
7783    * not editable; so beep here if it's multi-key input sequence, input
7784    * method will be reset in key-press-event handler.
7785    */
7786   gtk_im_context_get_preedit_string (context, &str, &attrs, &cursor_pos);
7787
7788   if (str && str[0] && !gtk_text_iter_can_insert (&iter, priv->editable))
7789     {
7790       gtk_widget_error_bell (GTK_WIDGET (text_view));
7791       goto out;
7792     }
7793
7794   g_signal_emit (text_view, signals[PREEDIT_CHANGED], 0, str);
7795
7796   if (priv->layout)
7797     gtk_text_layout_set_preedit_string (priv->layout, str, attrs, cursor_pos);
7798   if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
7799     gtk_text_view_scroll_mark_onscreen (text_view,
7800                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
7801
7802 out:
7803   pango_attr_list_unref (attrs);
7804   g_free (str);
7805 }
7806
7807 static gboolean
7808 gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
7809                                             GtkTextView   *text_view)
7810 {
7811   GtkTextIter start;
7812   GtkTextIter end;
7813   gint pos;
7814   gchar *text;
7815
7816   gtk_text_buffer_get_iter_at_mark (text_view->priv->buffer, &start,
7817                                     gtk_text_buffer_get_insert (text_view->priv->buffer));
7818   end = start;
7819
7820   pos = gtk_text_iter_get_line_index (&start);
7821   gtk_text_iter_set_line_offset (&start, 0);
7822   gtk_text_iter_forward_to_line_end (&end);
7823
7824   text = gtk_text_iter_get_slice (&start, &end);
7825   gtk_im_context_set_surrounding (context, text, -1, pos);
7826   g_free (text);
7827
7828   return TRUE;
7829 }
7830
7831 static gboolean
7832 gtk_text_view_delete_surrounding_handler (GtkIMContext  *context,
7833                                           gint           offset,
7834                                           gint           n_chars,
7835                                           GtkTextView   *text_view)
7836 {
7837   GtkTextViewPrivate *priv;
7838   GtkTextIter start;
7839   GtkTextIter end;
7840
7841   priv = text_view->priv;
7842
7843   gtk_text_buffer_get_iter_at_mark (priv->buffer, &start,
7844                                     gtk_text_buffer_get_insert (priv->buffer));
7845   end = start;
7846
7847   gtk_text_iter_forward_chars (&start, offset);
7848   gtk_text_iter_forward_chars (&end, offset + n_chars);
7849
7850   gtk_text_buffer_delete_interactive (priv->buffer, &start, &end,
7851                                       priv->editable);
7852
7853   return TRUE;
7854 }
7855
7856 static void
7857 gtk_text_view_mark_set_handler (GtkTextBuffer     *buffer,
7858                                 const GtkTextIter *location,
7859                                 GtkTextMark       *mark,
7860                                 gpointer           data)
7861 {
7862   GtkTextView *text_view = GTK_TEXT_VIEW (data);
7863   gboolean need_reset = FALSE;
7864
7865   if (mark == gtk_text_buffer_get_insert (buffer))
7866     {
7867       text_view->priv->virtual_cursor_x = -1;
7868       text_view->priv->virtual_cursor_y = -1;
7869       gtk_text_view_update_im_spot_location (text_view);
7870       need_reset = TRUE;
7871     }
7872   else if (mark == gtk_text_buffer_get_selection_bound (buffer))
7873     {
7874       need_reset = TRUE;
7875     }
7876
7877   if (need_reset)
7878     gtk_text_view_reset_im_context (text_view);
7879 }
7880
7881 static void
7882 gtk_text_view_target_list_notify (GtkTextBuffer    *buffer,
7883                                   const GParamSpec *pspec,
7884                                   gpointer          data)
7885 {
7886   GtkWidget     *widget = GTK_WIDGET (data);
7887   GtkTargetList *view_list;
7888   GtkTargetList *buffer_list;
7889   GList         *list;
7890
7891   view_list = gtk_drag_dest_get_target_list (widget);
7892   buffer_list = gtk_text_buffer_get_paste_target_list (buffer);
7893
7894   if (view_list)
7895     gtk_target_list_ref (view_list);
7896   else
7897     view_list = gtk_target_list_new (NULL, 0);
7898
7899   list = view_list->list;
7900   while (list)
7901     {
7902       GtkTargetPair *pair = list->data;
7903
7904       list = g_list_next (list); /* get next element before removing */
7905
7906       if (pair->info >= GTK_TEXT_BUFFER_TARGET_INFO_TEXT &&
7907           pair->info <= GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
7908         {
7909           gtk_target_list_remove (view_list, pair->target);
7910         }
7911     }
7912
7913   for (list = buffer_list->list; list; list = g_list_next (list))
7914     {
7915       GtkTargetPair *pair = list->data;
7916
7917       gtk_target_list_add (view_list, pair->target, pair->flags, pair->info);
7918     }
7919
7920   gtk_drag_dest_set_target_list (widget, view_list);
7921   gtk_target_list_unref (view_list);
7922 }
7923
7924 static void
7925 gtk_text_view_get_cursor_location  (GtkTextView   *text_view,
7926                                     GdkRectangle  *pos)
7927 {
7928   GtkTextIter insert;
7929   
7930   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
7931                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
7932
7933   gtk_text_layout_get_cursor_locations (text_view->priv->layout, &insert, pos, NULL);
7934 }
7935
7936 static void
7937 gtk_text_view_get_virtual_cursor_pos (GtkTextView *text_view,
7938                                       GtkTextIter *cursor,
7939                                       gint        *x,
7940                                       gint        *y)
7941 {
7942   GtkTextViewPrivate *priv;
7943   GtkTextIter insert;
7944   GdkRectangle pos;
7945
7946   priv = text_view->priv;
7947
7948   if (cursor)
7949     insert = *cursor;
7950   else
7951     gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
7952                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
7953
7954   if ((x && priv->virtual_cursor_x == -1) ||
7955       (y && priv->virtual_cursor_y == -1))
7956     gtk_text_layout_get_cursor_locations (priv->layout, &insert, &pos, NULL);
7957
7958   if (x)
7959     {
7960       if (priv->virtual_cursor_x != -1)
7961         *x = priv->virtual_cursor_x;
7962       else
7963         *x = pos.x;
7964     }
7965
7966   if (y)
7967     {
7968       if (priv->virtual_cursor_x != -1)
7969         *y = priv->virtual_cursor_y;
7970       else
7971         *y = pos.y + pos.height / 2;
7972     }
7973 }
7974
7975 static void
7976 gtk_text_view_set_virtual_cursor_pos (GtkTextView *text_view,
7977                                       gint         x,
7978                                       gint         y)
7979 {
7980   GdkRectangle pos;
7981
7982   if (!text_view->priv->layout)
7983     return;
7984
7985   if (x == -1 || y == -1)
7986     gtk_text_view_get_cursor_location (text_view, &pos);
7987
7988   text_view->priv->virtual_cursor_x = (x == -1) ? pos.x : x;
7989   text_view->priv->virtual_cursor_y = (y == -1) ? pos.y + pos.height / 2 : y;
7990 }
7991
7992 /* Quick hack of a popup menu
7993  */
7994 static void
7995 activate_cb (GtkWidget   *menuitem,
7996              GtkTextView *text_view)
7997 {
7998   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
7999   g_signal_emit_by_name (text_view, signal);
8000 }
8001
8002 static void
8003 append_action_signal (GtkTextView  *text_view,
8004                       GtkWidget    *menu,
8005                       const gchar  *stock_id,
8006                       const gchar  *signal,
8007                       gboolean      sensitive)
8008 {
8009   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
8010
8011   g_object_set_data (G_OBJECT (menuitem), I_("gtk-signal"), (char *)signal);
8012   g_signal_connect (menuitem, "activate",
8013                     G_CALLBACK (activate_cb), text_view);
8014
8015   gtk_widget_set_sensitive (menuitem, sensitive);
8016   
8017   gtk_widget_show (menuitem);
8018   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
8019 }
8020
8021 static void
8022 gtk_text_view_select_all (GtkWidget *widget,
8023                           gboolean select)
8024 {
8025   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
8026   GtkTextBuffer *buffer;
8027   GtkTextIter start_iter, end_iter, insert;
8028
8029   buffer = text_view->priv->buffer;
8030   if (select) 
8031     {
8032       gtk_text_buffer_get_bounds (buffer, &start_iter, &end_iter);
8033       gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
8034     }
8035   else 
8036     {
8037       gtk_text_buffer_get_iter_at_mark (buffer, &insert,
8038                                         gtk_text_buffer_get_insert (buffer));
8039       gtk_text_buffer_move_mark_by_name (buffer, "selection_bound", &insert);
8040     }
8041 }
8042
8043 static void
8044 select_all_cb (GtkWidget   *menuitem,
8045                GtkTextView *text_view)
8046 {
8047   gtk_text_view_select_all (GTK_WIDGET (text_view), TRUE);
8048 }
8049
8050 static void
8051 delete_cb (GtkTextView *text_view)
8052 {
8053   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
8054                                     text_view->priv->editable);
8055 }
8056
8057 static void
8058 popup_menu_detach (GtkWidget *attach_widget,
8059                    GtkMenu   *menu)
8060 {
8061   GTK_TEXT_VIEW (attach_widget)->priv->popup_menu = NULL;
8062 }
8063
8064 static void
8065 popup_position_func (GtkMenu   *menu,
8066                      gint      *x,
8067                      gint      *y,
8068                      gboolean  *push_in,
8069                      gpointer   user_data)
8070 {
8071   GtkAllocation allocation;
8072   GtkTextView *text_view;
8073   GtkWidget *widget;
8074   GdkRectangle cursor_rect;
8075   GdkRectangle onscreen_rect;
8076   gint root_x, root_y;
8077   GtkTextIter iter;
8078   GtkRequisition req;      
8079   GdkScreen *screen;
8080   gint monitor_num;
8081   GdkRectangle monitor;
8082       
8083   text_view = GTK_TEXT_VIEW (user_data);
8084   widget = GTK_WIDGET (text_view);
8085   
8086   g_return_if_fail (gtk_widget_get_realized (widget));
8087   
8088   screen = gtk_widget_get_screen (widget);
8089
8090   gdk_window_get_origin (gtk_widget_get_window (widget),
8091                          &root_x, &root_y);
8092
8093   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8094                                     &iter,
8095                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
8096
8097   gtk_text_view_get_iter_location (text_view,
8098                                    &iter,
8099                                    &cursor_rect);
8100
8101   gtk_text_view_get_visible_rect (text_view, &onscreen_rect);
8102
8103   gtk_size_request_get_size (GTK_SIZE_REQUEST (text_view->priv->popup_menu),
8104                              &req, NULL);
8105
8106   gtk_widget_get_allocation (widget, &allocation);
8107
8108   /* can't use rectangle_intersect since cursor rect can have 0 width */
8109   if (cursor_rect.x >= onscreen_rect.x &&
8110       cursor_rect.x < onscreen_rect.x + onscreen_rect.width &&
8111       cursor_rect.y >= onscreen_rect.y &&
8112       cursor_rect.y < onscreen_rect.y + onscreen_rect.height)
8113     {    
8114       gtk_text_view_buffer_to_window_coords (text_view,
8115                                              GTK_TEXT_WINDOW_WIDGET,
8116                                              cursor_rect.x, cursor_rect.y,
8117                                              &cursor_rect.x, &cursor_rect.y);
8118
8119       *x = root_x + cursor_rect.x + cursor_rect.width;
8120       *y = root_y + cursor_rect.y + cursor_rect.height;
8121     }
8122   else
8123     {
8124       /* Just center the menu, since cursor is offscreen. */
8125       *x = root_x + (allocation.width / 2 - req.width / 2);
8126       *y = root_y + (allocation.height / 2 - req.height / 2);
8127     }
8128
8129   /* Ensure sanity */
8130   *x = CLAMP (*x, root_x, (root_x + allocation.width));
8131   *y = CLAMP (*y, root_y, (root_y + allocation.height));
8132
8133   monitor_num = gdk_screen_get_monitor_at_point (screen, *x, *y);
8134   gtk_menu_set_monitor (menu, monitor_num);
8135   gdk_screen_get_monitor_geometry (screen, monitor_num, &monitor);
8136
8137   *x = CLAMP (*x, monitor.x, monitor.x + MAX (0, monitor.width - req.width));
8138   *y = CLAMP (*y, monitor.y, monitor.y + MAX (0, monitor.height - req.height));
8139
8140   *push_in = FALSE;
8141 }
8142
8143 typedef struct
8144 {
8145   GtkTextView *text_view;
8146   gint button;
8147   guint time;
8148 } PopupInfo;
8149
8150 static gboolean
8151 range_contains_editable_text (const GtkTextIter *start,
8152                               const GtkTextIter *end,
8153                               gboolean default_editability)
8154 {
8155   GtkTextIter iter = *start;
8156
8157   while (gtk_text_iter_compare (&iter, end) < 0)
8158     {
8159       if (gtk_text_iter_editable (&iter, default_editability))
8160         return TRUE;
8161       
8162       gtk_text_iter_forward_to_tag_toggle (&iter, NULL);
8163     }
8164
8165   return FALSE;
8166 }                             
8167
8168 static void
8169 unichar_chosen_func (const char *text,
8170                      gpointer    data)
8171 {
8172   GtkTextView *text_view = GTK_TEXT_VIEW (data);
8173
8174   gtk_text_view_commit_text (text_view, text);
8175 }
8176
8177 static void
8178 popup_targets_received (GtkClipboard     *clipboard,
8179                         GtkSelectionData *data,
8180                         gpointer          user_data)
8181 {
8182   PopupInfo *info = user_data;
8183   GtkTextView *text_view;
8184   GtkTextViewPrivate *priv;
8185
8186   text_view = info->text_view;
8187   priv = text_view->priv;
8188
8189   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
8190     {
8191       /* We implicitely rely here on the fact that if we are pasting ourself, we'll
8192        * have text targets as well as the private GTK_TEXT_BUFFER_CONTENTS target.
8193        */
8194       gboolean clipboard_contains_text;
8195       GtkWidget *menuitem;
8196       GtkWidget *submenu;
8197       gboolean have_selection;
8198       gboolean can_insert;
8199       GtkTextIter iter;
8200       GtkTextIter sel_start, sel_end;
8201       gboolean show_input_method_menu;
8202       gboolean show_unicode_menu;
8203       
8204       clipboard_contains_text = gtk_selection_data_targets_include_text (data);
8205
8206       if (priv->popup_menu)
8207         gtk_widget_destroy (priv->popup_menu);
8208
8209       priv->popup_menu = gtk_menu_new ();
8210       
8211       gtk_menu_attach_to_widget (GTK_MENU (priv->popup_menu),
8212                                  GTK_WIDGET (text_view),
8213                                  popup_menu_detach);
8214       
8215       have_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
8216                                                              &sel_start, &sel_end);
8217       
8218       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8219                                         &iter,
8220                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
8221       
8222       can_insert = gtk_text_iter_can_insert (&iter, priv->editable);
8223       
8224       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_CUT, "cut-clipboard",
8225                             have_selection &&
8226                             range_contains_editable_text (&sel_start, &sel_end,
8227                                                           priv->editable));
8228       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_COPY, "copy-clipboard",
8229                             have_selection);
8230       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_PASTE, "paste-clipboard",
8231                             can_insert && clipboard_contains_text);
8232       
8233       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
8234       gtk_widget_set_sensitive (menuitem, 
8235                                 have_selection &&
8236                                 range_contains_editable_text (&sel_start, &sel_end,
8237                                                               priv->editable));
8238       g_signal_connect_swapped (menuitem, "activate",
8239                                 G_CALLBACK (delete_cb), text_view);
8240       gtk_widget_show (menuitem);
8241       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8242
8243       menuitem = gtk_separator_menu_item_new ();
8244       gtk_widget_show (menuitem);
8245       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8246
8247       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_SELECT_ALL, NULL);
8248       g_signal_connect (menuitem, "activate",
8249                         G_CALLBACK (select_all_cb), text_view);
8250       gtk_widget_show (menuitem);
8251       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8252
8253       g_object_get (gtk_widget_get_settings (GTK_WIDGET (text_view)),
8254                     "gtk-show-input-method-menu", &show_input_method_menu,
8255                     "gtk-show-unicode-menu", &show_unicode_menu,
8256                     NULL);
8257       
8258       if (show_input_method_menu || show_unicode_menu)
8259         {
8260           menuitem = gtk_separator_menu_item_new ();
8261           gtk_widget_show (menuitem);
8262           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8263         }
8264
8265       if (show_input_method_menu)
8266         {
8267           menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
8268           gtk_widget_show (menuitem);
8269           gtk_widget_set_sensitive (menuitem, can_insert);
8270
8271           submenu = gtk_menu_new ();
8272           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
8273           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8274           
8275           gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (priv->im_context),
8276                                                 GTK_MENU_SHELL (submenu));
8277         }
8278
8279       if (show_unicode_menu)
8280         {
8281           menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode Control Character"));
8282           gtk_widget_show (menuitem);
8283           gtk_widget_set_sensitive (menuitem, can_insert);
8284       
8285           submenu = gtk_menu_new ();
8286           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
8287           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8288           
8289           _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
8290                                                         unichar_chosen_func,
8291                                                         text_view);
8292         }
8293           
8294       g_signal_emit (text_view,
8295                      signals[POPULATE_POPUP],
8296                      0,
8297                      priv->popup_menu);
8298       
8299       if (info->button)
8300         gtk_menu_popup (GTK_MENU (priv->popup_menu), NULL, NULL,
8301                         NULL, NULL,
8302                         info->button, info->time);
8303       else
8304         {
8305           gtk_menu_popup (GTK_MENU (priv->popup_menu), NULL, NULL,
8306                           popup_position_func, text_view,
8307                           0, gtk_get_current_event_time ());
8308           gtk_menu_shell_select_first (GTK_MENU_SHELL (priv->popup_menu), FALSE);
8309         }
8310     }
8311
8312   g_object_unref (text_view);
8313   g_free (info);
8314 }
8315
8316 static void
8317 gtk_text_view_do_popup (GtkTextView    *text_view,
8318                         GdkEventButton *event)
8319 {
8320   PopupInfo *info = g_new (PopupInfo, 1);
8321
8322   /* In order to know what entries we should make sensitive, we
8323    * ask for the current targets of the clipboard, and when
8324    * we get them, then we actually pop up the menu.
8325    */
8326   info->text_view = g_object_ref (text_view);
8327   
8328   if (event)
8329     {
8330       info->button = event->button;
8331       info->time = event->time;
8332     }
8333   else
8334     {
8335       info->button = 0;
8336       info->time = gtk_get_current_event_time ();
8337     }
8338
8339   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (text_view),
8340                                                             GDK_SELECTION_CLIPBOARD),
8341                                   gdk_atom_intern_static_string ("TARGETS"),
8342                                   popup_targets_received,
8343                                   info);
8344 }
8345
8346 static gboolean
8347 gtk_text_view_popup_menu (GtkWidget *widget)
8348 {
8349   gtk_text_view_do_popup (GTK_TEXT_VIEW (widget), NULL);  
8350   return TRUE;
8351 }
8352
8353 /* Child GdkWindows */
8354
8355
8356 static GtkTextWindow*
8357 text_window_new (GtkTextWindowType  type,
8358                  GtkWidget         *widget,
8359                  gint               width_request,
8360                  gint               height_request)
8361 {
8362   GtkTextWindow *win;
8363
8364   win = g_new (GtkTextWindow, 1);
8365
8366   win->type = type;
8367   win->widget = widget;
8368   win->window = NULL;
8369   win->bin_window = NULL;
8370   win->requisition.width = width_request;
8371   win->requisition.height = height_request;
8372   win->allocation.width = width_request;
8373   win->allocation.height = height_request;
8374   win->allocation.x = 0;
8375   win->allocation.y = 0;
8376
8377   return win;
8378 }
8379
8380 static void
8381 text_window_free (GtkTextWindow *win)
8382 {
8383   if (win->window)
8384     text_window_unrealize (win);
8385
8386   g_free (win);
8387 }
8388
8389 static void
8390 text_window_realize (GtkTextWindow *win,
8391                      GtkWidget     *widget)
8392 {
8393   GdkWindow *window;
8394   GdkWindowAttr attributes;
8395   gint attributes_mask;
8396   GdkCursor *cursor;
8397
8398   attributes.window_type = GDK_WINDOW_CHILD;
8399   attributes.x = win->allocation.x;
8400   attributes.y = win->allocation.y;
8401   attributes.width = win->allocation.width;
8402   attributes.height = win->allocation.height;
8403   attributes.wclass = GDK_INPUT_OUTPUT;
8404   attributes.visual = gtk_widget_get_visual (win->widget);
8405   attributes.colormap = gtk_widget_get_colormap (win->widget);
8406   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK;
8407
8408   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
8409
8410   window = gtk_widget_get_window (widget);
8411
8412   win->window = gdk_window_new (window,
8413                                 &attributes, attributes_mask);
8414
8415   gdk_window_show (win->window);
8416   gdk_window_set_user_data (win->window, win->widget);
8417   gdk_window_lower (win->window);
8418
8419   attributes.x = 0;
8420   attributes.y = 0;
8421   attributes.width = win->allocation.width;
8422   attributes.height = win->allocation.height;
8423   attributes.event_mask = (GDK_EXPOSURE_MASK            |
8424                            GDK_SCROLL_MASK              |
8425                            GDK_KEY_PRESS_MASK           |
8426                            GDK_BUTTON_PRESS_MASK        |
8427                            GDK_BUTTON_RELEASE_MASK      |
8428                            GDK_POINTER_MOTION_MASK      |
8429                            GDK_POINTER_MOTION_HINT_MASK |
8430                            gtk_widget_get_events (win->widget));
8431
8432   win->bin_window = gdk_window_new (win->window,
8433                                     &attributes,
8434                                     attributes_mask);
8435
8436   gdk_window_show (win->bin_window);
8437   gdk_window_set_user_data (win->bin_window, win->widget);
8438
8439   if (win->type == GTK_TEXT_WINDOW_TEXT)
8440     {
8441       if (gtk_widget_is_sensitive (widget))
8442         {
8443           /* I-beam cursor */
8444           cursor = gdk_cursor_new_for_display (gdk_drawable_get_display (window),
8445                                                GDK_XTERM);
8446           gdk_window_set_cursor (win->bin_window, cursor);
8447           gdk_cursor_unref (cursor);
8448         } 
8449
8450       gtk_im_context_set_client_window (GTK_TEXT_VIEW (widget)->priv->im_context,
8451                                         win->window);
8452
8453
8454       gdk_window_set_background (win->bin_window,
8455                                  &gtk_widget_get_style (widget)->base[gtk_widget_get_state (widget)]);
8456     }
8457   else
8458     {
8459       gdk_window_set_background (win->bin_window,
8460                                  &gtk_widget_get_style (widget)->bg[gtk_widget_get_state (widget)]);
8461     }
8462
8463   g_object_set_qdata (G_OBJECT (win->window),
8464                       g_quark_from_static_string ("gtk-text-view-text-window"),
8465                       win);
8466
8467   g_object_set_qdata (G_OBJECT (win->bin_window),
8468                       g_quark_from_static_string ("gtk-text-view-text-window"),
8469                       win);
8470 }
8471
8472 static void
8473 text_window_unrealize (GtkTextWindow *win)
8474 {
8475   if (win->type == GTK_TEXT_WINDOW_TEXT)
8476     {
8477       gtk_im_context_set_client_window (GTK_TEXT_VIEW (win->widget)->priv->im_context,
8478                                         NULL);
8479     }
8480
8481   gdk_window_set_user_data (win->window, NULL);
8482   gdk_window_set_user_data (win->bin_window, NULL);
8483   gdk_window_destroy (win->bin_window);
8484   gdk_window_destroy (win->window);
8485   win->window = NULL;
8486   win->bin_window = NULL;
8487 }
8488
8489 static void
8490 text_window_size_allocate (GtkTextWindow *win,
8491                            GdkRectangle  *rect)
8492 {
8493   win->allocation = *rect;
8494
8495   if (win->window)
8496     {
8497       gdk_window_move_resize (win->window,
8498                               rect->x, rect->y,
8499                               rect->width, rect->height);
8500
8501       gdk_window_resize (win->bin_window,
8502                          rect->width, rect->height);
8503     }
8504 }
8505
8506 static void
8507 text_window_scroll        (GtkTextWindow *win,
8508                            gint           dx,
8509                            gint           dy)
8510 {
8511   if (dx != 0 || dy != 0)
8512     {
8513       gdk_window_scroll (win->bin_window, dx, dy);
8514     }
8515 }
8516
8517 static void
8518 text_window_invalidate_rect (GtkTextWindow *win,
8519                              GdkRectangle  *rect)
8520 {
8521   GdkRectangle window_rect;
8522
8523   gtk_text_view_buffer_to_window_coords (GTK_TEXT_VIEW (win->widget),
8524                                          win->type,
8525                                          rect->x,
8526                                          rect->y,
8527                                          &window_rect.x,
8528                                          &window_rect.y);
8529
8530   window_rect.width = rect->width;
8531   window_rect.height = rect->height;
8532   
8533   /* Adjust the rect as appropriate */
8534   
8535   switch (win->type)
8536     {
8537     case GTK_TEXT_WINDOW_TEXT:
8538       break;
8539
8540     case GTK_TEXT_WINDOW_LEFT:
8541     case GTK_TEXT_WINDOW_RIGHT:
8542       window_rect.x = 0;
8543       window_rect.width = win->allocation.width;
8544       break;
8545
8546     case GTK_TEXT_WINDOW_TOP:
8547     case GTK_TEXT_WINDOW_BOTTOM:
8548       window_rect.y = 0;
8549       window_rect.height = win->allocation.height;
8550       break;
8551
8552     default:
8553       g_warning ("%s: bug!", G_STRFUNC);
8554       return;
8555       break;
8556     }
8557           
8558   gdk_window_invalidate_rect (win->bin_window, &window_rect, FALSE);
8559
8560 #if 0
8561   {
8562     cairo_t *cr = gdk_cairo_create (win->bin_window);
8563     gdk_cairo_rectangle (cr, &window_rect);
8564     cairo_set_source_rgb  (cr, 1.0, 0.0, 0.0);  /* red */
8565     cairo_fill (cr);
8566     cairo_destroy (cr);
8567   }
8568 #endif
8569 }
8570
8571 static void
8572 text_window_invalidate_cursors (GtkTextWindow *win)
8573 {
8574   GtkTextView *text_view;
8575   GtkTextViewPrivate *priv;
8576   GtkTextIter  iter;
8577   GdkRectangle strong;
8578   GdkRectangle weak;
8579   gboolean     draw_arrow;
8580   gfloat       cursor_aspect_ratio;
8581   gint         stem_width;
8582   gint         arrow_width;
8583
8584   text_view = GTK_TEXT_VIEW (win->widget);
8585   priv = text_view->priv;
8586
8587   gtk_text_buffer_get_iter_at_mark (priv->buffer, &iter,
8588                                     gtk_text_buffer_get_insert (priv->buffer));
8589
8590   if (_gtk_text_layout_get_block_cursor (priv->layout, &strong))
8591     {
8592       text_window_invalidate_rect (win, &strong);
8593       return;
8594     }
8595
8596   gtk_text_layout_get_cursor_locations (priv->layout, &iter,
8597                                         &strong, &weak);
8598
8599   /* cursor width calculation as in gtkstyle.c:draw_insertion_cursor(),
8600    * ignoring the text direction be exposing both sides of the cursor
8601    */
8602
8603   draw_arrow = (strong.x != weak.x || strong.y != weak.y);
8604
8605   gtk_widget_style_get (win->widget,
8606                         "cursor-aspect-ratio", &cursor_aspect_ratio,
8607                         NULL);
8608   
8609   stem_width = strong.height * cursor_aspect_ratio + 1;
8610   arrow_width = stem_width + 1;
8611
8612   strong.width = stem_width;
8613
8614   /* round up to the next even number */
8615   if (stem_width & 1)
8616     stem_width++;
8617
8618   strong.x     -= stem_width / 2;
8619   strong.width += stem_width;
8620
8621   if (draw_arrow)
8622     {
8623       strong.x     -= arrow_width;
8624       strong.width += arrow_width * 2;
8625     }
8626
8627   text_window_invalidate_rect (win, &strong);
8628
8629   if (draw_arrow) /* == have weak */
8630     {
8631       stem_width = weak.height * cursor_aspect_ratio + 1;
8632       arrow_width = stem_width + 1;
8633
8634       weak.width = stem_width;
8635
8636       /* round up to the next even number */
8637       if (stem_width & 1)
8638         stem_width++;
8639
8640       weak.x     -= stem_width / 2;
8641       weak.width += stem_width;
8642
8643       weak.x     -= arrow_width;
8644       weak.width += arrow_width * 2;
8645
8646       text_window_invalidate_rect (win, &weak);
8647     }
8648 }
8649
8650 static gint
8651 text_window_get_width (GtkTextWindow *win)
8652 {
8653   return win->allocation.width;
8654 }
8655
8656 static gint
8657 text_window_get_height (GtkTextWindow *win)
8658 {
8659   return win->allocation.height;
8660 }
8661
8662 /* Windows */
8663
8664
8665 /**
8666  * gtk_text_view_get_window:
8667  * @text_view: a #GtkTextView
8668  * @win: window to get
8669  *
8670  * Retrieves the #GdkWindow corresponding to an area of the text view;
8671  * possible windows include the overall widget window, child windows
8672  * on the left, right, top, bottom, and the window that displays the
8673  * text buffer. Windows are %NULL and nonexistent if their width or
8674  * height is 0, and are nonexistent before the widget has been
8675  * realized.
8676  *
8677  * Return value: (transfer none): a #GdkWindow, or %NULL
8678  **/
8679 GdkWindow*
8680 gtk_text_view_get_window (GtkTextView *text_view,
8681                           GtkTextWindowType win)
8682 {
8683   GtkTextViewPrivate *priv = text_view->priv;
8684
8685   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
8686
8687   switch (win)
8688     {
8689     case GTK_TEXT_WINDOW_WIDGET:
8690       return gtk_widget_get_window (GTK_WIDGET (text_view));
8691       break;
8692
8693     case GTK_TEXT_WINDOW_TEXT:
8694       return priv->text_window->bin_window;
8695       break;
8696
8697     case GTK_TEXT_WINDOW_LEFT:
8698       if (priv->left_window)
8699         return priv->left_window->bin_window;
8700       else
8701         return NULL;
8702       break;
8703
8704     case GTK_TEXT_WINDOW_RIGHT:
8705       if (priv->right_window)
8706         return priv->right_window->bin_window;
8707       else
8708         return NULL;
8709       break;
8710
8711     case GTK_TEXT_WINDOW_TOP:
8712       if (priv->top_window)
8713         return priv->top_window->bin_window;
8714       else
8715         return NULL;
8716       break;
8717
8718     case GTK_TEXT_WINDOW_BOTTOM:
8719       if (priv->bottom_window)
8720         return priv->bottom_window->bin_window;
8721       else
8722         return NULL;
8723       break;
8724
8725     case GTK_TEXT_WINDOW_PRIVATE:
8726       g_warning ("%s: You can't get GTK_TEXT_WINDOW_PRIVATE, it has \"PRIVATE\" in the name because it is private.", G_STRFUNC);
8727       return NULL;
8728       break;
8729     }
8730
8731   g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
8732   return NULL;
8733 }
8734
8735 /**
8736  * gtk_text_view_get_window_type:
8737  * @text_view: a #GtkTextView
8738  * @window: a window type
8739  *
8740  * Usually used to find out which window an event corresponds to.
8741  * If you connect to an event signal on @text_view, this function
8742  * should be called on <literal>event-&gt;window</literal> to
8743  * see which window it was.
8744  *
8745  * Return value: the window type.
8746  **/
8747 GtkTextWindowType
8748 gtk_text_view_get_window_type (GtkTextView *text_view,
8749                                GdkWindow   *window)
8750 {
8751   GtkTextWindow *win;
8752
8753   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
8754   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
8755
8756   if (window == gtk_widget_get_window (GTK_WIDGET (text_view)))
8757     return GTK_TEXT_WINDOW_WIDGET;
8758
8759   win = g_object_get_qdata (G_OBJECT (window),
8760                             g_quark_try_string ("gtk-text-view-text-window"));
8761
8762   if (win)
8763     return win->type;
8764   else
8765     {
8766       return GTK_TEXT_WINDOW_PRIVATE;
8767     }
8768 }
8769
8770 static void
8771 buffer_to_widget (GtkTextView      *text_view,
8772                   gint              buffer_x,
8773                   gint              buffer_y,
8774                   gint             *window_x,
8775                   gint             *window_y)
8776 {
8777   GtkTextViewPrivate *priv = text_view->priv;
8778
8779   if (window_x)
8780     {
8781       *window_x = buffer_x - priv->xoffset;
8782       *window_x += priv->text_window->allocation.x;
8783     }
8784
8785   if (window_y)
8786     {
8787       *window_y = buffer_y - priv->yoffset;
8788       *window_y += priv->text_window->allocation.y;
8789     }
8790 }
8791
8792 static void
8793 widget_to_text_window (GtkTextWindow *win,
8794                        gint           widget_x,
8795                        gint           widget_y,
8796                        gint          *window_x,
8797                        gint          *window_y)
8798 {
8799   if (window_x)
8800     *window_x = widget_x - win->allocation.x;
8801
8802   if (window_y)
8803     *window_y = widget_y - win->allocation.y;
8804 }
8805
8806 static void
8807 buffer_to_text_window (GtkTextView   *text_view,
8808                        GtkTextWindow *win,
8809                        gint           buffer_x,
8810                        gint           buffer_y,
8811                        gint          *window_x,
8812                        gint          *window_y)
8813 {
8814   if (win == NULL)
8815     {
8816       g_warning ("Attempt to convert text buffer coordinates to coordinates "
8817                  "for a nonexistent or private child window of GtkTextView");
8818       return;
8819     }
8820
8821   buffer_to_widget (text_view,
8822                     buffer_x, buffer_y,
8823                     window_x, window_y);
8824
8825   widget_to_text_window (win,
8826                          window_x ? *window_x : 0,
8827                          window_y ? *window_y : 0,
8828                          window_x,
8829                          window_y);
8830 }
8831
8832 /**
8833  * gtk_text_view_buffer_to_window_coords:
8834  * @text_view: a #GtkTextView
8835  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
8836  * @buffer_x: buffer x coordinate
8837  * @buffer_y: buffer y coordinate
8838  * @window_x: (out) (allow-none): window x coordinate return location or %NULL
8839  * @window_y: (out) (allow-none): window y coordinate return location or %NULL
8840  *
8841  * Converts coordinate (@buffer_x, @buffer_y) to coordinates for the window
8842  * @win, and stores the result in (@window_x, @window_y). 
8843  *
8844  * Note that you can't convert coordinates for a nonexisting window (see 
8845  * gtk_text_view_set_border_window_size()).
8846  **/
8847 void
8848 gtk_text_view_buffer_to_window_coords (GtkTextView      *text_view,
8849                                        GtkTextWindowType win,
8850                                        gint              buffer_x,
8851                                        gint              buffer_y,
8852                                        gint             *window_x,
8853                                        gint             *window_y)
8854 {
8855   GtkTextViewPrivate *priv = text_view->priv;
8856
8857   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
8858
8859   switch (win)
8860     {
8861     case GTK_TEXT_WINDOW_WIDGET:
8862       buffer_to_widget (text_view,
8863                         buffer_x, buffer_y,
8864                         window_x, window_y);
8865       break;
8866
8867     case GTK_TEXT_WINDOW_TEXT:
8868       if (window_x)
8869         *window_x = buffer_x - priv->xoffset;
8870       if (window_y)
8871         *window_y = buffer_y - priv->yoffset;
8872       break;
8873
8874     case GTK_TEXT_WINDOW_LEFT:
8875       buffer_to_text_window (text_view,
8876                              priv->left_window,
8877                              buffer_x, buffer_y,
8878                              window_x, window_y);
8879       break;
8880
8881     case GTK_TEXT_WINDOW_RIGHT:
8882       buffer_to_text_window (text_view,
8883                              priv->right_window,
8884                              buffer_x, buffer_y,
8885                              window_x, window_y);
8886       break;
8887
8888     case GTK_TEXT_WINDOW_TOP:
8889       buffer_to_text_window (text_view,
8890                              priv->top_window,
8891                              buffer_x, buffer_y,
8892                              window_x, window_y);
8893       break;
8894
8895     case GTK_TEXT_WINDOW_BOTTOM:
8896       buffer_to_text_window (text_view,
8897                              priv->bottom_window,
8898                              buffer_x, buffer_y,
8899                              window_x, window_y);
8900       break;
8901
8902     case GTK_TEXT_WINDOW_PRIVATE:
8903       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
8904       break;
8905
8906     default:
8907       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
8908       break;
8909     }
8910 }
8911
8912 static void
8913 widget_to_buffer (GtkTextView *text_view,
8914                   gint         widget_x,
8915                   gint         widget_y,
8916                   gint        *buffer_x,
8917                   gint        *buffer_y)
8918 {
8919   GtkTextViewPrivate *priv = text_view->priv;
8920
8921   if (buffer_x)
8922     {
8923       *buffer_x = widget_x + priv->xoffset;
8924       *buffer_x -= priv->text_window->allocation.x;
8925     }
8926
8927   if (buffer_y)
8928     {
8929       *buffer_y = widget_y + priv->yoffset;
8930       *buffer_y -= priv->text_window->allocation.y;
8931     }
8932 }
8933
8934 static void
8935 text_window_to_widget (GtkTextWindow *win,
8936                        gint           window_x,
8937                        gint           window_y,
8938                        gint          *widget_x,
8939                        gint          *widget_y)
8940 {
8941   if (widget_x)
8942     *widget_x = window_x + win->allocation.x;
8943
8944   if (widget_y)
8945     *widget_y = window_y + win->allocation.y;
8946 }
8947
8948 static void
8949 text_window_to_buffer (GtkTextView   *text_view,
8950                        GtkTextWindow *win,
8951                        gint           window_x,
8952                        gint           window_y,
8953                        gint          *buffer_x,
8954                        gint          *buffer_y)
8955 {
8956   if (win == NULL)
8957     {
8958       g_warning ("Attempt to convert GtkTextView buffer coordinates into "
8959                  "coordinates for a nonexistent child window.");
8960       return;
8961     }
8962
8963   text_window_to_widget (win,
8964                          window_x,
8965                          window_y,
8966                          buffer_x,
8967                          buffer_y);
8968
8969   widget_to_buffer (text_view,
8970                     buffer_x ? *buffer_x : 0,
8971                     buffer_y ? *buffer_y : 0,
8972                     buffer_x,
8973                     buffer_y);
8974 }
8975
8976 /**
8977  * gtk_text_view_window_to_buffer_coords:
8978  * @text_view: a #GtkTextView
8979  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
8980  * @window_x: window x coordinate
8981  * @window_y: window y coordinate
8982  * @buffer_x: (out) (allow-none): buffer x coordinate return location or %NULL
8983  * @buffer_y: (out) (allow-none): buffer y coordinate return location or %NULL
8984  *
8985  * Converts coordinates on the window identified by @win to buffer
8986  * coordinates, storing the result in (@buffer_x,@buffer_y).
8987  *
8988  * Note that you can't convert coordinates for a nonexisting window (see 
8989  * gtk_text_view_set_border_window_size()).
8990  **/
8991 void
8992 gtk_text_view_window_to_buffer_coords (GtkTextView      *text_view,
8993                                        GtkTextWindowType win,
8994                                        gint              window_x,
8995                                        gint              window_y,
8996                                        gint             *buffer_x,
8997                                        gint             *buffer_y)
8998 {
8999   GtkTextViewPrivate *priv = text_view->priv;
9000
9001   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9002
9003   switch (win)
9004     {
9005     case GTK_TEXT_WINDOW_WIDGET:
9006       widget_to_buffer (text_view,
9007                         window_x, window_y,
9008                         buffer_x, buffer_y);
9009       break;
9010
9011     case GTK_TEXT_WINDOW_TEXT:
9012       if (buffer_x)
9013         *buffer_x = window_x + priv->xoffset;
9014       if (buffer_y)
9015         *buffer_y = window_y + priv->yoffset;
9016       break;
9017
9018     case GTK_TEXT_WINDOW_LEFT:
9019       text_window_to_buffer (text_view,
9020                              priv->left_window,
9021                              window_x, window_y,
9022                              buffer_x, buffer_y);
9023       break;
9024
9025     case GTK_TEXT_WINDOW_RIGHT:
9026       text_window_to_buffer (text_view,
9027                              priv->right_window,
9028                              window_x, window_y,
9029                              buffer_x, buffer_y);
9030       break;
9031
9032     case GTK_TEXT_WINDOW_TOP:
9033       text_window_to_buffer (text_view,
9034                              priv->top_window,
9035                              window_x, window_y,
9036                              buffer_x, buffer_y);
9037       break;
9038
9039     case GTK_TEXT_WINDOW_BOTTOM:
9040       text_window_to_buffer (text_view,
9041                              priv->bottom_window,
9042                              window_x, window_y,
9043                              buffer_x, buffer_y);
9044       break;
9045
9046     case GTK_TEXT_WINDOW_PRIVATE:
9047       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
9048       break;
9049
9050     default:
9051       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
9052       break;
9053     }
9054 }
9055
9056 static void
9057 set_window_width (GtkTextView      *text_view,
9058                   gint              width,
9059                   GtkTextWindowType type,
9060                   GtkTextWindow   **winp)
9061 {
9062   if (width == 0)
9063     {
9064       if (*winp)
9065         {
9066           text_window_free (*winp);
9067           *winp = NULL;
9068           gtk_widget_queue_resize (GTK_WIDGET (text_view));
9069         }
9070     }
9071   else
9072     {
9073       if (*winp == NULL)
9074         {
9075           *winp = text_window_new (type,
9076                                    GTK_WIDGET (text_view),
9077                                    width, 0);
9078           /* if the widget is already realized we need to realize the child manually */
9079           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9080             text_window_realize (*winp, GTK_WIDGET (text_view));
9081         }
9082       else
9083         {
9084           if ((*winp)->requisition.width == width)
9085             return;
9086
9087           (*winp)->requisition.width = width;
9088         }
9089
9090       gtk_widget_queue_resize (GTK_WIDGET (text_view));
9091     }
9092 }
9093
9094
9095 static void
9096 set_window_height (GtkTextView      *text_view,
9097                    gint              height,
9098                    GtkTextWindowType type,
9099                    GtkTextWindow   **winp)
9100 {
9101   if (height == 0)
9102     {
9103       if (*winp)
9104         {
9105           text_window_free (*winp);
9106           *winp = NULL;
9107           gtk_widget_queue_resize (GTK_WIDGET (text_view));
9108         }
9109     }
9110   else
9111     {
9112       if (*winp == NULL)
9113         {
9114           *winp = text_window_new (type,
9115                                    GTK_WIDGET (text_view),
9116                                    0, height);
9117
9118           /* if the widget is already realized we need to realize the child manually */
9119           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9120             text_window_realize (*winp, GTK_WIDGET (text_view));
9121         }
9122       else
9123         {
9124           if ((*winp)->requisition.height == height)
9125             return;
9126
9127           (*winp)->requisition.height = height;
9128         }
9129
9130       gtk_widget_queue_resize (GTK_WIDGET (text_view));
9131     }
9132 }
9133
9134 /**
9135  * gtk_text_view_set_border_window_size:
9136  * @text_view: a #GtkTextView
9137  * @type: window to affect
9138  * @size: width or height of the window
9139  *
9140  * Sets the width of %GTK_TEXT_WINDOW_LEFT or %GTK_TEXT_WINDOW_RIGHT,
9141  * or the height of %GTK_TEXT_WINDOW_TOP or %GTK_TEXT_WINDOW_BOTTOM.
9142  * Automatically destroys the corresponding window if the size is set
9143  * to 0, and creates the window if the size is set to non-zero.  This
9144  * function can only be used for the "border windows," it doesn't work
9145  * with #GTK_TEXT_WINDOW_WIDGET, #GTK_TEXT_WINDOW_TEXT, or
9146  * #GTK_TEXT_WINDOW_PRIVATE.
9147  **/
9148 void
9149 gtk_text_view_set_border_window_size (GtkTextView      *text_view,
9150                                       GtkTextWindowType type,
9151                                       gint              size)
9152 {
9153   GtkTextViewPrivate *priv = text_view->priv;
9154
9155   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9156   g_return_if_fail (size >= 0);
9157
9158   switch (type)
9159     {
9160     case GTK_TEXT_WINDOW_LEFT:
9161       set_window_width (text_view, size, GTK_TEXT_WINDOW_LEFT,
9162                         &priv->left_window);
9163       break;
9164
9165     case GTK_TEXT_WINDOW_RIGHT:
9166       set_window_width (text_view, size, GTK_TEXT_WINDOW_RIGHT,
9167                         &priv->right_window);
9168       break;
9169
9170     case GTK_TEXT_WINDOW_TOP:
9171       set_window_height (text_view, size, GTK_TEXT_WINDOW_TOP,
9172                          &priv->top_window);
9173       break;
9174
9175     case GTK_TEXT_WINDOW_BOTTOM:
9176       set_window_height (text_view, size, GTK_TEXT_WINDOW_BOTTOM,
9177                          &priv->bottom_window);
9178       break;
9179
9180     default:
9181       g_warning ("Can only set size of left/right/top/bottom border windows with gtk_text_view_set_border_window_size()");
9182       break;
9183     }
9184 }
9185
9186 /**
9187  * gtk_text_view_get_border_window_size:
9188  * @text_view: a #GtkTextView
9189  * @type: window to return size from
9190  *
9191  * Gets the width of the specified border window. See
9192  * gtk_text_view_set_border_window_size().
9193  *
9194  * Return value: width of window
9195  **/
9196 gint
9197 gtk_text_view_get_border_window_size (GtkTextView       *text_view,
9198                                       GtkTextWindowType  type)
9199 {
9200   GtkTextViewPrivate *priv = text_view->priv;
9201
9202   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
9203   
9204   switch (type)
9205     {
9206     case GTK_TEXT_WINDOW_LEFT:
9207       if (priv->left_window)
9208         return priv->left_window->requisition.width;
9209       break;
9210       
9211     case GTK_TEXT_WINDOW_RIGHT:
9212       if (priv->right_window)
9213         return priv->right_window->requisition.width;
9214       break;
9215       
9216     case GTK_TEXT_WINDOW_TOP:
9217       if (priv->top_window)
9218         return priv->top_window->requisition.height;
9219       break;
9220
9221     case GTK_TEXT_WINDOW_BOTTOM:
9222       if (priv->bottom_window)
9223         return priv->bottom_window->requisition.height;
9224       break;
9225       
9226     default:
9227       g_warning ("Can only get size of left/right/top/bottom border windows with gtk_text_view_get_border_window_size()");
9228       break;
9229     }
9230
9231   return 0;
9232 }
9233
9234 /*
9235  * Child widgets
9236  */
9237
9238 static GtkTextViewChild*
9239 text_view_child_new_anchored (GtkWidget          *child,
9240                               GtkTextChildAnchor *anchor,
9241                               GtkTextLayout      *layout)
9242 {
9243   GtkTextViewChild *vc;
9244
9245   vc = g_new (GtkTextViewChild, 1);
9246
9247   vc->type = GTK_TEXT_WINDOW_PRIVATE;
9248   vc->widget = child;
9249   vc->anchor = anchor;
9250
9251   vc->from_top_of_line = 0;
9252   vc->from_left_of_buffer = 0;
9253   
9254   g_object_ref (vc->widget);
9255   g_object_ref (vc->anchor);
9256
9257   g_object_set_data (G_OBJECT (child),
9258                      I_("gtk-text-view-child"),
9259                      vc);
9260
9261   gtk_text_child_anchor_register_child (anchor, child, layout);
9262   
9263   return vc;
9264 }
9265
9266 static GtkTextViewChild*
9267 text_view_child_new_window (GtkWidget          *child,
9268                             GtkTextWindowType   type,
9269                             gint                x,
9270                             gint                y)
9271 {
9272   GtkTextViewChild *vc;
9273
9274   vc = g_new (GtkTextViewChild, 1);
9275
9276   vc->widget = child;
9277   vc->anchor = NULL;
9278
9279   vc->from_top_of_line = 0;
9280   vc->from_left_of_buffer = 0;
9281  
9282   g_object_ref (vc->widget);
9283
9284   vc->type = type;
9285   vc->x = x;
9286   vc->y = y;
9287
9288   g_object_set_data (G_OBJECT (child),
9289                      I_("gtk-text-view-child"),
9290                      vc);
9291   
9292   return vc;
9293 }
9294
9295 static void
9296 text_view_child_free (GtkTextViewChild *child)
9297 {
9298   g_object_set_data (G_OBJECT (child->widget),
9299                      I_("gtk-text-view-child"), NULL);
9300
9301   if (child->anchor)
9302     {
9303       gtk_text_child_anchor_unregister_child (child->anchor,
9304                                               child->widget);
9305       g_object_unref (child->anchor);
9306     }
9307
9308   g_object_unref (child->widget);
9309
9310   g_free (child);
9311 }
9312
9313 static void
9314 text_view_child_set_parent_window (GtkTextView      *text_view,
9315                                    GtkTextViewChild *vc)
9316 {
9317   if (vc->anchor)
9318     gtk_widget_set_parent_window (vc->widget,
9319                                   text_view->priv->text_window->bin_window);
9320   else
9321     {
9322       GdkWindow *window;
9323       window = gtk_text_view_get_window (text_view,
9324                                          vc->type);
9325       gtk_widget_set_parent_window (vc->widget, window);
9326     }
9327 }
9328
9329 static void
9330 add_child (GtkTextView      *text_view,
9331            GtkTextViewChild *vc)
9332 {
9333   text_view->priv->children = g_slist_prepend (text_view->priv->children,
9334                                                vc);
9335
9336   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9337     text_view_child_set_parent_window (text_view, vc);
9338   
9339   gtk_widget_set_parent (vc->widget, GTK_WIDGET (text_view));
9340 }
9341
9342 /**
9343  * gtk_text_view_add_child_at_anchor:
9344  * @text_view: a #GtkTextView
9345  * @child: a #GtkWidget
9346  * @anchor: a #GtkTextChildAnchor in the #GtkTextBuffer for @text_view
9347  * 
9348  * Adds a child widget in the text buffer, at the given @anchor.
9349  **/
9350 void
9351 gtk_text_view_add_child_at_anchor (GtkTextView          *text_view,
9352                                    GtkWidget            *child,
9353                                    GtkTextChildAnchor   *anchor)
9354 {
9355   GtkTextViewChild *vc;
9356
9357   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9358   g_return_if_fail (GTK_IS_WIDGET (child));
9359   g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
9360   g_return_if_fail (gtk_widget_get_parent (child) == NULL);
9361
9362   gtk_text_view_ensure_layout (text_view);
9363
9364   vc = text_view_child_new_anchored (child, anchor,
9365                                      text_view->priv->layout);
9366
9367   add_child (text_view, vc);
9368
9369   g_assert (vc->widget == child);
9370   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9371 }
9372
9373 /**
9374  * gtk_text_view_add_child_in_window:
9375  * @text_view: a #GtkTextView
9376  * @child: a #GtkWidget
9377  * @which_window: which window the child should appear in
9378  * @xpos: X position of child in window coordinates
9379  * @ypos: Y position of child in window coordinates
9380  *
9381  * Adds a child at fixed coordinates in one of the text widget's
9382  * windows. The window must have nonzero size (see
9383  * gtk_text_view_set_border_window_size()). Note that the child
9384  * coordinates are given relative to the #GdkWindow in question, and
9385  * that these coordinates have no sane relationship to scrolling. When
9386  * placing a child in #GTK_TEXT_WINDOW_WIDGET, scrolling is
9387  * irrelevant, the child floats above all scrollable areas. But when
9388  * placing a child in one of the scrollable windows (border windows or
9389  * text window), you'll need to compute the child's correct position
9390  * in buffer coordinates any time scrolling occurs or buffer changes
9391  * occur, and then call gtk_text_view_move_child() to update the
9392  * child's position. Unfortunately there's no good way to detect that
9393  * scrolling has occurred, using the current API; a possible hack
9394  * would be to update all child positions when the scroll adjustments
9395  * change or the text buffer changes. See bug 64518 on
9396  * bugzilla.gnome.org for status of fixing this issue.
9397  **/
9398 void
9399 gtk_text_view_add_child_in_window (GtkTextView       *text_view,
9400                                    GtkWidget         *child,
9401                                    GtkTextWindowType  which_window,
9402                                    gint               xpos,
9403                                    gint               ypos)
9404 {
9405   GtkTextViewChild *vc;
9406
9407   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9408   g_return_if_fail (GTK_IS_WIDGET (child));
9409   g_return_if_fail (gtk_widget_get_parent (child) == NULL);
9410
9411   vc = text_view_child_new_window (child, which_window,
9412                                    xpos, ypos);
9413
9414   add_child (text_view, vc);
9415
9416   g_assert (vc->widget == child);
9417   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9418 }
9419
9420 /**
9421  * gtk_text_view_move_child:
9422  * @text_view: a #GtkTextView
9423  * @child: child widget already added to the text view
9424  * @xpos: new X position in window coordinates
9425  * @ypos: new Y position in window coordinates
9426  *
9427  * Updates the position of a child, as for gtk_text_view_add_child_in_window().
9428  **/
9429 void
9430 gtk_text_view_move_child (GtkTextView *text_view,
9431                           GtkWidget   *child,
9432                           gint         xpos,
9433                           gint         ypos)
9434 {
9435   GtkTextViewChild *vc;
9436
9437   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9438   g_return_if_fail (GTK_IS_WIDGET (child));
9439   g_return_if_fail (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9440
9441   vc = g_object_get_data (G_OBJECT (child),
9442                           "gtk-text-view-child");
9443
9444   g_assert (vc != NULL);
9445
9446   if (vc->x == xpos &&
9447       vc->y == ypos)
9448     return;
9449   
9450   vc->x = xpos;
9451   vc->y = ypos;
9452
9453   if (gtk_widget_get_visible (child) &&
9454       gtk_widget_get_visible (GTK_WIDGET (text_view)))
9455     gtk_widget_queue_resize (child);
9456 }
9457
9458
9459 /* Iterator operations */
9460
9461 /**
9462  * gtk_text_view_forward_display_line:
9463  * @text_view: a #GtkTextView
9464  * @iter: a #GtkTextIter
9465  * 
9466  * Moves the given @iter forward by one display (wrapped) line.
9467  * A display line is different from a paragraph. Paragraphs are
9468  * separated by newlines or other paragraph separator characters.
9469  * Display lines are created by line-wrapping a paragraph. If
9470  * wrapping is turned off, display lines and paragraphs will be the
9471  * same. Display lines are divided differently for each view, since
9472  * they depend on the view's width; paragraphs are the same in all
9473  * views, since they depend on the contents of the #GtkTextBuffer.
9474  * 
9475  * Return value: %TRUE if @iter was moved and is not on the end iterator
9476  **/
9477 gboolean
9478 gtk_text_view_forward_display_line (GtkTextView *text_view,
9479                                     GtkTextIter *iter)
9480 {
9481   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9482   g_return_val_if_fail (iter != NULL, FALSE);
9483
9484   gtk_text_view_ensure_layout (text_view);
9485
9486   return gtk_text_layout_move_iter_to_next_line (text_view->priv->layout, iter);
9487 }
9488
9489 /**
9490  * gtk_text_view_backward_display_line:
9491  * @text_view: a #GtkTextView
9492  * @iter: a #GtkTextIter
9493  * 
9494  * Moves the given @iter backward by one display (wrapped) line.
9495  * A display line is different from a paragraph. Paragraphs are
9496  * separated by newlines or other paragraph separator characters.
9497  * Display lines are created by line-wrapping a paragraph. If
9498  * wrapping is turned off, display lines and paragraphs will be the
9499  * same. Display lines are divided differently for each view, since
9500  * they depend on the view's width; paragraphs are the same in all
9501  * views, since they depend on the contents of the #GtkTextBuffer.
9502  * 
9503  * Return value: %TRUE if @iter was moved and is not on the end iterator
9504  **/
9505 gboolean
9506 gtk_text_view_backward_display_line (GtkTextView *text_view,
9507                                      GtkTextIter *iter)
9508 {
9509   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9510   g_return_val_if_fail (iter != NULL, FALSE);
9511
9512   gtk_text_view_ensure_layout (text_view);
9513
9514   return gtk_text_layout_move_iter_to_previous_line (text_view->priv->layout, iter);
9515 }
9516
9517 /**
9518  * gtk_text_view_forward_display_line_end:
9519  * @text_view: a #GtkTextView
9520  * @iter: a #GtkTextIter
9521  * 
9522  * Moves the given @iter forward to the next display line end.
9523  * A display line is different from a paragraph. Paragraphs are
9524  * separated by newlines or other paragraph separator characters.
9525  * Display lines are created by line-wrapping a paragraph. If
9526  * wrapping is turned off, display lines and paragraphs will be the
9527  * same. Display lines are divided differently for each view, since
9528  * they depend on the view's width; paragraphs are the same in all
9529  * views, since they depend on the contents of the #GtkTextBuffer.
9530  * 
9531  * Return value: %TRUE if @iter was moved and is not on the end iterator
9532  **/
9533 gboolean
9534 gtk_text_view_forward_display_line_end (GtkTextView *text_view,
9535                                         GtkTextIter *iter)
9536 {
9537   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9538   g_return_val_if_fail (iter != NULL, FALSE);
9539
9540   gtk_text_view_ensure_layout (text_view);
9541
9542   return gtk_text_layout_move_iter_to_line_end (text_view->priv->layout, iter, 1);
9543 }
9544
9545 /**
9546  * gtk_text_view_backward_display_line_start:
9547  * @text_view: a #GtkTextView
9548  * @iter: a #GtkTextIter
9549  * 
9550  * Moves the given @iter backward to the next display line start.
9551  * A display line is different from a paragraph. Paragraphs are
9552  * separated by newlines or other paragraph separator characters.
9553  * Display lines are created by line-wrapping a paragraph. If
9554  * wrapping is turned off, display lines and paragraphs will be the
9555  * same. Display lines are divided differently for each view, since
9556  * they depend on the view's width; paragraphs are the same in all
9557  * views, since they depend on the contents of the #GtkTextBuffer.
9558  * 
9559  * Return value: %TRUE if @iter was moved and is not on the end iterator
9560  **/
9561 gboolean
9562 gtk_text_view_backward_display_line_start (GtkTextView *text_view,
9563                                            GtkTextIter *iter)
9564 {
9565   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9566   g_return_val_if_fail (iter != NULL, FALSE);
9567
9568   gtk_text_view_ensure_layout (text_view);
9569
9570   return gtk_text_layout_move_iter_to_line_end (text_view->priv->layout, iter, -1);
9571 }
9572
9573 /**
9574  * gtk_text_view_starts_display_line:
9575  * @text_view: a #GtkTextView
9576  * @iter: a #GtkTextIter
9577  * 
9578  * Determines whether @iter is at the start of a display line.
9579  * See gtk_text_view_forward_display_line() for an explanation of
9580  * display lines vs. paragraphs.
9581  * 
9582  * Return value: %TRUE if @iter begins a wrapped line
9583  **/
9584 gboolean
9585 gtk_text_view_starts_display_line (GtkTextView       *text_view,
9586                                    const GtkTextIter *iter)
9587 {
9588   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9589   g_return_val_if_fail (iter != NULL, FALSE);
9590
9591   gtk_text_view_ensure_layout (text_view);
9592
9593   return gtk_text_layout_iter_starts_line (text_view->priv->layout, iter);
9594 }
9595
9596 /**
9597  * gtk_text_view_move_visually:
9598  * @text_view: a #GtkTextView
9599  * @iter: a #GtkTextIter
9600  * @count: number of characters to move (negative moves left, 
9601  *    positive moves right)
9602  *
9603  * Move the iterator a given number of characters visually, treating
9604  * it as the strong cursor position. If @count is positive, then the
9605  * new strong cursor position will be @count positions to the right of
9606  * the old cursor position. If @count is negative then the new strong
9607  * cursor position will be @count positions to the left of the old
9608  * cursor position.
9609  *
9610  * In the presence of bi-directional text, the correspondence
9611  * between logical and visual order will depend on the direction
9612  * of the current run, and there may be jumps when the cursor
9613  * is moved off of the end of a run.
9614  * 
9615  * Return value: %TRUE if @iter moved and is not on the end iterator
9616  **/
9617 gboolean
9618 gtk_text_view_move_visually (GtkTextView *text_view,
9619                              GtkTextIter *iter,
9620                              gint         count)
9621 {
9622   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9623   g_return_val_if_fail (iter != NULL, FALSE);
9624
9625   gtk_text_view_ensure_layout (text_view);
9626
9627   return gtk_text_layout_move_iter_visually (text_view->priv->layout, iter, count);
9628 }