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