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