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